> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hydradb.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Context Graphs

> How HydraDB models relationships between chunks using triplets to improve recall quality.

## 1. What it is

A context graph is a structured map of relationships between stored pieces of context in your tenant.

It represents those relationships as **triplets**: `source → relation → target`. Each triplet is a directional connection between two pieces of context, with `source`, `relation`, and `target` returned as structured objects - not plain strings.

Context graphs augment retrieval. They do not replace it.

***

## 2. What it does

When `graph_context: true` is set on a recall call, HydraDB returns relationship data alongside the retrieved chunks - showing how those chunks connect to each other and to your query.

This helps your LLM reason about questions that require connecting information across multiple chunks or sources. Similarity search returns relevant content; the context graph surfaces how that content fits together.

***

## 3. When to use it

Use context graphs when:

* Answers require synthesising information across multiple chunks.
* Relational context matters for correctness - cause and effect, ownership, sequence, dependency.
* You need multi-hop reasoning ("What team owns the service that failed?", "What depends on this API?").

Skip them for direct factual lookups. Graph traversal adds response size and can add latency, so reserve it for queries where relational structure materially improves the answer.

***

## 4. How it works

Context graphs are hybrid: relationships are extracted at ingestion time and traversed at recall time.

**At ingestion**, HydraDB extracts relationships from your data and stores them in the graph. Sources can also declare explicit relationships to other sources via a `relations` payload at ingestion.

**At recall**, when `graph_context: true` is set:

1. HydraDB runs hybrid retrieval to find relevant chunks.
2. It traverses the graph to discover relevant relationships between retrieved context.
3. It returns multi-hop paths from the query (`query_paths`), relationship paths between retrieved chunks (`chunk_relations`), and a chunk-to-path-group mapping (`chunk_id_to_group_ids`).

When no relevant relationships are found, graph fields may be empty.

***

## 5. Key concepts

**Triplets.** The unit of the graph. Each triplet is `source → relation → target`, where `source` and `target` are entity objects and `relation` describes the connection between them.

Example: `billing_policy → governs → failed_payment_handling`

**`query_paths`.** Multi-hop chains of triplets connecting the query to retrieved chunks. Each path carries a relevancy score and the chunk IDs whose traversal produced it.

**`chunk_relations`.** Paths describing how returned chunks relate to one another. Same shape as `query_paths`; the difference is the anchor - query-driven vs chunk-to-chunk.

**`chunk_id_to_group_ids`.** Maps each chunk ID to the path-group identifiers (e.g. `p_0`, `p_1`) it belongs to. Use it to group retrieved chunks by which graph path produced them.

For full field schemas, see the [Full Recall API Reference](/api-reference/endpoint/full-recall).

***

## 6. Minimal working example

<CodeGroup>
  ```bash cURL theme={"dark"}
  curl -X POST 'https://api.hydradb.com/recall/full_recall' \
    -H "Authorization: Bearer $HYDRA_DB_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "tenant_id": "acme_corp",
      "query": "How does the billing system handle failed payments?",
      "mode": "thinking",
      "graph_context": true
    }'
  ```

  ```typescript TypeScript SDK theme={"dark"}
  const result = await client.recall.fullRecall({
    tenant_id: "acme_corp",
    query: "How does the billing system handle failed payments?",
    mode: "thinking",
    graph_context: true,
  });

  if (result.graph_context) {
    for (const path of result.graph_context.query_paths) {
      for (const t of path.triplets) {
        console.log(
          `${t.source.name} - ${t.relation.canonical_predicate} → ${t.target.name}`,
        );
      }
    }
  }
  ```

  ```python Python SDK theme={"dark"}
  result = client.recall.full_recall(
      tenant_id="acme_corp",
      query="How does the billing system handle failed payments?",
      mode="thinking",
      graph_context=True,
  )

  if result.graph_context:
      for path in result.graph_context.query_paths:
          for t in path.triplets:
              print(
                  t.source.name,
                  " - ",
                  t.relation.canonical_predicate,
                  "→",
                  t.target.name,
              )
  ```
</CodeGroup>

A response with graph context looks like:

```json theme={"dark"}
{
  "chunks": [ /* ranked chunks */ ],
  "graph_context": {
    "query_paths": [
      {
        "triplets": [
          {
            "source": { "name": "billing_policy", "type": "POLICY" },
            "relation": { "canonical_predicate": "governs" },
            "target": { "name": "failed_payment_handling", "type": "PROCESS" }
          }
        ],
        "relevancy_score": 0.84,
        "group_id": "p_0",
        "source_chunk_ids": ["chunk_abc", "chunk_def"]
      }
    ],
    "chunk_relations": [],
    "chunk_id_to_group_ids": { "chunk_abc": ["p_0"] }
  }
}
```

When no relevant relationships are found, graph fields may be empty.

***

## 7. Using graph context in your prompt

To include graph relationships in your LLM prompt, use the `buildContextString` / `build_context_string` helper from [How to Use API Results](/essentials/api-results). It handles `query_paths`, `chunk_relations`, and `chunk_id_to_group_ids` automatically.

The helper formats triplets as:

```
[billing_policy] -> governs -> [failed_payment_handling]: policy covering retry logic
  ↳ [failed_payment_handling] -> triggers -> [notification_service]: sends customer alert
```

***

## 8. Common mistakes

**Forgetting `graph_context: true`.** Without the flag, recall still returns chunks, but the graph fields will not be populated.

**Assuming the graph replaces retrieval.** It doesn't. `chunks` is still the primary result; the graph enriches it with relationships. Use both.

**Enabling graph context on every request.** It increases response size and adds traversal cost. Reserve it for queries where relational structure improves the answer.

**Treating triplets as flat strings.** `source`, `relation`, and `target` are objects with their own fields. Read them as structured data.

**Expecting relationships that don't exist.** If the retrieved chunks don't share entities or declared relations, the graph fields will be empty. That's not an error - it's the absence of structure for that query.

***

## Related

* [Recall](/essentials/recall) - how chunks and graph context are retrieved together
* [Memories](/essentials/memories) - user-scoped context for personalization
* [Knowledge](/essentials/knowledge) - document-level context for shared retrieval
* [How to Use API Results](/essentials/api-results) - formatting graph context for LLM prompts
* [Full Recall API Reference](/api-reference/endpoint/full-recall) - full graph response schema
