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

# Assemble Context (RAG)

> One-shot context assembly for LLM prompts — memories + timeline + graph

Purpose-built for retrieval-augmented generation (RAG). Given a user query, the endpoint retrieves the most relevant memories, recent events, and graph relationships, then returns a **pre-formatted context string** ready to prepend to your LLM prompt.

This is the easiest way to add memory to your AI chat. One call → formatted context.

## Request

### Headers

<ParamField header="Authorization" type="string" required>
  Bearer token with your API key
</ParamField>

<ParamField header="Content-Type" type="string" required>
  application/json
</ParamField>

### Body

<ParamField body="query" type="string" required>
  The user's query. This drives retrieval.
</ParamField>

<ParamField body="session_id" type="string">
  Chat session ID for hierarchical session context.
</ParamField>

<ParamField body="top_k" type="integer" default="10">
  Number of memories to retrieve. Max 100.
</ParamField>

<ParamField body="max_context_length" type="integer" default="4000">
  Maximum assembled context length in tokens. Older chunks truncated if exceeded.
</ParamField>

<ParamField body="include_graph" type="boolean" default="false">
  Include knowledge-graph relationships.
</ParamField>

<ParamField body="include_timeline" type="boolean" default="true">
  Include recent events from EventStoreDB.
</ParamField>

## Response

<ResponseField name="data.prompt_ready" type="string">
  **The key field** — a pre-formatted context string you can prepend directly to your LLM system message.
</ResponseField>

<ResponseField name="data.context" type="object">
  Structured context with separate `chunks`, `sources`, `graph_context`, and `timeline` sections.
</ResponseField>

<ResponseField name="data.message" type="string">
  Status message (e.g., "Context assembled from 8 memories and 3 recent events").
</ResponseField>

## Complete RAG example

<RequestExample>
  ```bash cURL theme={null}
  curl -X POST https://api.60db.ai/memory/context \
    -H "Authorization: Bearer your-api-key" \
    -H "Content-Type: application/json" \
    -d '{
      "query": "What do you know about my preferences?",
      "top_k": 8,
      "max_context_length": 2000,
      "include_timeline": true
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('https://api.60db.ai/memory/context', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer your-api-key',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      query: "What do you know about my preferences?",
      top_k: 8,
      max_context_length: 2000,
      include_timeline: true,
    }),
  });
  const data = await response.json();
  console.log(data.data.prompt_ready);
  ```

  ```python Python theme={null}
  import requests

  response = requests.post(
      "https://api.60db.ai/memory/context",
      headers={
          "Authorization": "Bearer your-api-key",
          "Content-Type": "application/json",
      },
      json={
          "query": "What do you know about my preferences?",
          "top_k": 8,
          "max_context_length": 2000,
          "include_timeline": True,
      },
  )
  data = response.json()
  print(data["data"]["prompt_ready"])
  ```
</RequestExample>

<ResponseExample>
  ```json Response theme={null}
  {
    "success": true,
    "data": {
      "context": {
        "chunks": [
          {
            "chunk_id": "c_01HV...",
            "source_id": "mem_01HV8K...",
            "text": "User prefers vegetarian food, lactose intolerant",
            "score": 0.92
          }
        ],
        "sources": [
          {
            "source_id": "mem_01HV8K...",
            "title": "Dietary preferences",
            "text": "User prefers vegetarian food, lactose intolerant",
            "score": 0.92
          }
        ]
      },
      "prompt_ready": "## User Memories\n- User prefers vegetarian food, lactose intolerant",
      "message": "Context assembled from 1 memories and 0 recent events"
    }
  }
  ```
</ResponseExample>

## Billing

Flat \*\*$0.0005 per query** — slightly higher than `/memory/search` because context assembly also formats an LLM-ready prompt with recent events and optional graph context. A chat application doing 1,000 turns/day costs about $15/month.

Response headers:

| Header             | Meaning                          |
| ------------------ | -------------------------------- |
| `x-credit-balance` | Wallet balance after this charge |
| `x-credit-charged` | `0.000500`                       |
| `x-billing-tx`     | Audit row UUID                   |

<Note>
  If the memory service is unreachable and the endpoint returns the graceful-degradation empty context (see below), you are **not** charged — the auto-refund guard reverses the deduction.
</Note>

See [Pricing & Billing](/api-reference/memory/pricing) for the full rate card.

## Graceful degradation

If the Memory service is unavailable, `/memory/context` returns `prompt_ready: ""` instead of failing. Your application can continue with no context — the SLM chat will still work, just without memory-grounded responses.

```json No-context response theme={null}
{
  "success": true,
  "data": {
    "context": { "chunks": [], "sources": [] },
    "prompt_ready": "",
    "message": "Memory system not ready — no context assembled"
  }
}
```

**Best practice**: Always check if `prompt_ready` is non-empty before prepending it.
