Build an Ontology with Graphs and Metadata

An ontology is a shared map from the words people use to the things they mean: which concepts exist, what each one means, how they relate, and where the evidence for each one lives. Agents answer more accurately with that map than without it, because a question like "what was Q3 revenue for enterprise customers" can be resolved to defined terms before anything is searched.

Captain can hold that map next to the documents it describes, and use it at query time. This guide shows one way to model it with features Captain already has:

Ontology elementCaptain feature
A concept and its definitionA short text document per concept, with metadata naming it
Synonyms, owner, certification statusMetadata on the concept document
Which passages talk about a conceptMetadata on documents and chunks, such as concepts: ["revenue"]
Relationships between concepts, and from concepts to evidenceTyped chunk relations
Resolving a question to concepts, then to evidenceFilters, boosts and relation-aware queries

If you already have an ontology, from your own modeling or from a tool that drafts one from schemas and query history such as NVIDIA Auto Ontology, the same model applies: load its terms as concept records and its relationships as relations, then ground them in your documents. Captain then serves both the definitions and the documents to your agents through the same query API and MCP server.

Plan the Collection

Relations connect chunks within one collection, so keep the concept records and the documents they describe in the same collection, and tell them apart with metadata:

FieldOnExampleUsed for
ontology_typeevery documentconcept or sourceSearching only definitions, or only evidence
concept_idconcept recordsrevenueA stable key for the concept
synonymsconcept records["sales", "turnover", "top line"]Matching the words people actually use
statusconcept recordsdraft or certifiedGovernance: answer only from certified definitions
conceptssource documents or chunks["revenue", "customer"]Linking evidence to concepts
primary_conceptsource documents or chunksrevenueA single value you can filter on exactly

Metadata does not need a schema. A key that a document lacks simply never matches it, so you can add fields as the ontology grows. Keep each key's value type the same across the collection: a key can be filtered on with one type only.

Filter on scalar fields such as primary_concept or status. For list fields such as concepts, use a boost with in, which matches when any element matches.

1. Create the Collection

import requests

BASE_URL = "https://api.captain.dev"
HEADERS = {"Authorization": "Bearer YOUR_API_KEY"}
COLLECTION = "finance-ontology"

requests.put(f"{BASE_URL}/v2/collections/{COLLECTION}", headers=HEADERS, json={})

2. Load the Concepts

Index each concept as a short text document. Put the definition in the text, so search can match it, and the structured facts in custom_metadata, so filters and boosts can use them.

concepts = [
    {
        "concept_id": "revenue",
        "label": "Revenue",
        "synonyms": ["sales", "turnover", "top line"],
        "definition": "Revenue is income from invoiced sales, recognized when the invoice is issued. "
                      "It excludes taxes and refunds.",
        "status": "certified",
        "owner": "finance",
    },
    {
        "concept_id": "enterprise_customer",
        "label": "Enterprise customer",
        "synonyms": ["enterprise account", "large account"],
        "definition": "An enterprise customer is an account with an annual contract value above $100,000.",
        "status": "draft",
        "owner": "sales-ops",
    },
]

for c in concepts:
    requests.post(
        f"{BASE_URL}/v2/collections/{COLLECTION}/index/text",
        headers=HEADERS,
        json={
            "filename": f"concept-{c['concept_id']}.md",
            "content": f"# {c['label']}\n\n{c['definition']}\n\nAlso called: {', '.join(c['synonyms'])}.",
            "custom_metadata": {
                "ontology_type": "concept",
                "concept_id": c["concept_id"],
                "synonyms": c["synonyms"],
                "status": c["status"],
                "owner": c["owner"],
            },
        },
    )

Each request returns a job_id. Poll Get Job Status until it finishes before you link the concept with relations.

3. Load and Tag the Source Documents

Index the documents that hold the evidence: policies, reports, contracts, data dictionaries, meeting notes. Tag them with the concepts they cover when you know at upload time. Index File takes custom_metadata for every file in the request and file_metadata for one entry per file:

files = [
    ("files", ("revenue-recognition-policy.pdf", open("revenue-recognition-policy.pdf", "rb"), "application/pdf")),
    ("files", ("q3-board-report.pdf", open("q3-board-report.pdf", "rb"), "application/pdf")),
]
requests.post(
    f"{BASE_URL}/v2/collections/{COLLECTION}/index/file",
    headers=HEADERS,
    files=files,
    data={
        "custom_metadata": '{"ontology_type": "source"}',
        "file_metadata": '[{"primary_concept": "revenue", "concepts": ["revenue"]}, '
                         '{"primary_concept": "revenue", "concepts": ["revenue", "enterprise_customer"]}]',
    },
)

When the concepts are only known after indexing, for example from a review or a classification pipeline, write them in bulk. Update Document Metadata in Batches tags whole documents, and Update Chunk Metadata in Batches tags single passages. Both merge the keys you send and keep the rest, up to 100 items per request:

requests.patch(
    f"{BASE_URL}/v3/collections/{COLLECTION}/chunks/metadata/batch",
    headers=HEADERS,
    json={"items": [
        {"item_id": "1", "chunk_id": "7c2e9a41d5b84f0e9a3c6d18b2f47e05:4",
         "metadata": {"concepts": ["revenue"], "primary_concept": "revenue"}},
        {"item_id": "2", "chunk_id": "7c2e9a41d5b84f0e9a3c6d18b2f47e05:9",
         "metadata": {"concepts": ["enterprise_customer"], "primary_concept": "enterprise_customer"}},
    ]},
)

Use the chunk_id exactly as a query result or Get Chunks returns it. Do not build chunk IDs yourself. If you re-index a document, look its chunk IDs up again before writing more metadata or relations.

4. Add the Relationships

Relations are typed, directed links between two chunks. relation_type is your own label, so you can use the vocabulary of your ontology. Two kinds are useful:

  • Concept to concept: is_a, part_of, measured_by, depends_on, same_as.
  • Concept to evidence: defined_by, calculated_in, mentioned_in, contradicted_by.

Create or Update Chunk Relations in Batches writes up to 100 at a time. A relation's identity is its source chunk, target chunk and type, so sending the same relation again updates its metadata rather than creating a duplicate, which makes reloading an ontology safe.

def first_chunk_id(document_id):
    """The chunk_id of a document's first chunk, as Get Chunks returns it."""
    r = requests.get(f"{BASE_URL}/v3/collections/{COLLECTION}/chunks",
                     headers=HEADERS, params={"document_id": document_id}).json()
    return r["chunks"][0]["chunk_id"]

# document_id values come from each indexing job's file list or from List Documents
REVENUE = first_chunk_id(revenue_document_id)          # the Revenue concept record
ENTERPRISE = first_chunk_id(enterprise_document_id)    # the Enterprise customer concept record
POLICY_PASSAGE = "7c2e9a41d5b84f0e9a3c6d18b2f47e05:4"   # a chunk_id from a query result

requests.put(
    f"{BASE_URL}/v3/collections/{COLLECTION}/relations/batch",
    headers=HEADERS,
    json={"items": [
        {"item_id": "r1", "source_chunk_id": REVENUE, "target_chunk_id": POLICY_PASSAGE,
         "relation_type": "defined_by", "metadata": {"certified_by": "finance", "confidence": 1.0}},
        {"item_id": "r2", "source_chunk_id": ENTERPRISE, "target_chunk_id": REVENUE,
         "relation_type": "measured_by", "metadata": {"source": "sales-ops glossary"}},
    ]},
)

A concept record indexed from a short text is usually a single chunk. Relations are one-way: no reverse relation is created. Query with relation_direction: "both" when you want to follow them either way.

5. Query Through the Ontology

An agent answering "what was Q3 revenue for enterprise customers" can work in three steps. Each step keeps to certified concepts and carries the concepts resolved in the first step forward.

Resolve the words to concepts. Search only the concept records, and only certified ones:

found = requests.post(
    f"{BASE_URL}/v3/collections/{COLLECTION}/query",
    headers=HEADERS,
    json={
        "query": "Q3 revenue for enterprise customers",
        "limit": 5,
        "filter": {"ontology_type": "concept", "status": "certified"},
    },
).json()

concept_ids = sorted({r["custom_metadata"]["concept_id"] for r in found["results"]})
if not concept_ids:
    raise SystemExit("No certified concept matches this question: answer from plain search, or ask the user to rephrase.")

The definitions and synonyms in the concept records are what let "top line" find Revenue. Each result carries the concept's metadata in custom_metadata. With the records above, only revenue comes back: enterprise_customer is still a draft. When nothing certified matches, stop here rather than sending the next two requests: they need at least one concept (a limit of 0 or an empty in list is rejected).

Follow the graph. Ask for the relations and linked chunks of exactly those concepts, keeping the certified check:

grounded = requests.post(
    f"{BASE_URL}/v3/collections/{COLLECTION}/query",
    headers=HEADERS,
    json={
        "query": "definition",
        "limit": len(concept_ids),
        "filter": {"ontology_type": "concept", "status": "certified",
                   "concept_id": {"$in": concept_ids}},
        "include": {"relations": True, "related_chunks": True},
        "relation_types": ["defined_by", "measured_by"],
        "relation_direction": "outgoing",
    },
).json()

Each result then carries relations (the edges) and related_chunks (the linked passages, with their text), so the agent sees the definition and its source in one response.

filter applies to the search results, not to related_chunks. A relation can point at a draft concept or an unreviewed passage. Check each related chunk's metadata, or record the review state on the relation itself (for example "certified_by" in its metadata), before an agent relies on it.

Retrieve the evidence. Search the source documents, favouring the passages tagged with the resolved concepts:

evidence = requests.post(
    f"{BASE_URL}/v3/collections/{COLLECTION}/query",
    headers=HEADERS,
    json={
        "query": "Q3 revenue for enterprise customers",
        "limit": 10,
        "filter": {"ontology_type": "source"},
        "boost": [{"field": "concepts", "in": concept_ids, "weight": 2.0}],
    },
).json()

Use filter when only tagged passages may answer, for example "primary_concept": {"$in": concept_ids}. Use boost when tagged passages should win but untagged ones may still help. Add "reserve": 1 to a boost rule when a tagged passage must appear even if reranking prefers another. See Metadata Boosts for weights and reserve.

To run the concept lookup and the evidence search in one call, send both as entries to Batch Query.

Keep It Governed

  • Certify before you rely on it. Load new or generated concepts as status: "draft", and filter agents to status: "certified". Promote a concept by updating its metadata. Nothing needs re-indexing.
  • Change definitions in place. Edit a concept's metadata with Update Document Metadata. To change its definition text, send the new text to Index Text with the same filename: it updates that same document. Re-create relations that pointed at the old chunk, because chunk boundaries can change when text changes.
  • Remove a relationship with Delete Chunk Relation.
  • Measure the lift. Build a set of real questions with known answers and run it as an Evaluation, with and without the ontology filters and boosts. Keep the version that answers more questions correctly.

Limits

LimitValue
Items per batch request (metadata or relations)1 to 100, at most 1 MiB
Boost rules per query10, with up to 50 values per in
RelationsBetween chunks in the same collection
relation_directionoutgoing (default), incoming, or both
Was this page helpful?