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

# Context segments and retrieval metadata

> Mark which parts of a prompt came from retrieval, memory, a tool or the user so Zespan can tell where a failure started. Metadata only: offsets, hashes, ids and enums. TypeScript and Python.

When an answer goes wrong, the first question is which layer failed: the instructions, retrieval, memory, a tool, or the model. Zespan can only answer that when it knows what went into the prompt. **Context segments** tell it: you mark a piece of text as `rag`, `memory`, `tool`, `user`, `system` or `example`, and Zespan records where that text sat in the prompt, never the text itself.

> [!NOTE]
>
> Available for: **TypeScript** and **Python**. Same fields and behavior in both.

## What leaves your process

For every segment found in a model call, the SDK sends only:

| Field | Meaning |
| - | - |
| `source` | `rag`, `memory`, `tool`, `user`, `system` or `example` |
| `msg_index` | Position of the message in the request you sent (absent for a system prompt) |
| `start`, `end` | Offsets of the segment inside that message, in characters |
| `sha256_16` | First 16 hex characters of a hash of the segment text (only for text of at least 40 characters) |
| `doc_id`, `store`, `score` | The document id, the store name and the retrieval score you passed |
| `chars`, `located`, `auto`, `scoped` | Length, whether the text was found in the call, whether an integration tagged it, whether it was registered inside a scope |

The text is located inside your process, against the request you send, **before** redaction or capture settings are applied. These fields are content-free, so they are kept even with `storePrompts: false`. The segment text itself is stored only where prompt capture already stores it.

## Mark a segment

```typescript TypeScript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import { zespan } from "@zespan/sdk";

const docs = await store.search(query, 5);
const context = docs
  .map((d) => zespan.context.segment(d.text, { source: "rag", docId: d.id, store: "kb", score: d.score }))
  .join("\n\n");

await client.chat.completions.create({
  model: MODEL,
  messages: [
    { role: "system", content: "Answer from the context only." },
    { role: "user", content: `Context:\n${context}\n\nQuestion: ${query}` },
  ],
});
```

```python Python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
import zespan

docs = store.search(query, 5)
context = "\n\n".join(
    zespan.context.segment(d.text, "rag", doc_id=d.id, store="kb", score=d.score) for d in docs
)

client.chat.completions.create(
    model=MODEL,
    messages=[
        {"role": "system", "content": "Answer from the context only."},
        {"role": "user", "content": f"Context:\n{context}\n\nQuestion: {query}"},
    ],
)
```

`segment()` returns the text you passed (the same value), so it drops into existing code. `segments()` marks several texts at once. Nothing here throws into your code: a bad argument leaves the text unmarked.

A segment is attached to a model call only when its exact text appears in that call's messages. Segments you mark but never use are not reported, so a stray mark never produces a false finding.

> [!WARNING]
>
> Marked segments wait in a pool per trace. Calls running at the same time in one trace, or in a process with no trace context, share that pool: when two of them mark the **same text** with different document ids, Zespan cannot tell whose document a call used. Give each request its own trace (`withZespanTrace` / `with_zespan_trace`) to keep them apart. Each trace holds at most 64 pending segments; a segment beyond that is not attached (it is never reported as missing).

## Report segments that never reached the prompt

Wrap a request in a scope when you want to know about documents that were retrieved but dropped before the prompt was built (for example by a token budget):

```typescript TypeScript theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
await zespan.context.withSegmentScope(async () => {
  const docs = await store.search(query, 20);
  const marked = docs.map((d) => zespan.context.segment(d.text, { source: "rag", docId: d.id }));
  return generate(query, fitToBudget(marked)); // some are dropped here
});
```

```python Python theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
with zespan.context.segment_scope():
    docs = store.search(query, 20)
    marked = [zespan.context.segment(d.text, "rag", doc_id=d.id) for d in docs]
    answer = generate(query, fit_to_budget(marked))  # some are dropped here
```

When the scope ends, segments registered inside it that a model call made inside the scope looked for and did not find are reported as `located: false` with `scoped: true`. This is the only way a segment is ever reported as not found. A scope in which no model call ran (for example because your code failed first), or in which only one of our framework integrations made the call (they link their own segments by run id), reports nothing: nothing is known about those segments.

## Threads and workers

Segments follow your trace context. They do not cross a thread that does not carry the context:

* **Python:** `asyncio.to_thread` copies the context. For `loop.run_in_executor` and `ThreadPoolExecutor.submit`, wrap the function: `pool.submit(zespan.context.bind(work))`.
* **TypeScript:** a worker thread has its own memory. Call `zespan.context.exportSegments()` in the main thread and `zespan.context.importSegments(handoff)` in the worker.

## Automatic tagging in our integrations

Our LangChain, LlamaIndex, Google ADK, Haystack and Semantic Kernel integrations tag retrieved documents, tool results and recalled memory for you, linked through the framework's own run ids, so two requests running at once never hand each other segments. These tags carry `auto: true` and metadata only.

Turn auto-tagging off with `contextAutoTag: false` (TypeScript), `context_auto_tag=False` (Python), or the environment variable `ZESPAN_CONTEXT_AUTOTAG=off`. The setting is read on every call.

## Retrieval metadata

Retriever spans from the Pinecone, Chroma, Qdrant and Weaviate auto-patch, the LangChain, LlamaIndex, Haystack and vectra integrations, `recordRetrieval` / `record_retrieval`, and OpenInference retrieval spans sent over OTLP carry content-free retrieval metadata:

| Key | Meaning |
| - | - |
| `zespan.retrieval.returned`, `empty` | How many documents came back, and whether the result was empty. A retriever that reported nothing is not counted as empty. |
| `zespan.retrieval.store`, `index`, `namespace`, `top_k` | Where the search ran and the requested result count |
| `zespan.retrieval.query_hash`, `filter_hash` | Hashes of the query and the filter (text of at least 40 characters) |
| `zespan.retrieval.doc_ids`, `doc_hashes`, `doc_scores` | Up to 50 document ids (redacted like tool arguments), content hashes and scores |

Reranker spans (Cohere `rerank`, LangChain compression and rerank retrievers, and in Python LlamaIndex postprocessors and Haystack rankers) carry `zespan.rerank.in_ids`, `out_ids`, `out_scores` and `top_n`.

All of these survive `storePrompts: false`. Retrieved documents are stored as objects with a document id; a document without one gets a stable generated id.

## Next steps

> [card] [Manual spans](https://docs.zespan.com/sdk/manual-spans.md)
>
> Record retrieval and custom steps yourself.

> [card] [Prompt management](https://docs.zespan.com/sdk/prompt-management.md#link-model-calls-to-the-prompt-version)
>
> Link model calls to the prompt version they used.

> [card] [Span kinds](https://docs.zespan.com/reference/span-kinds.md)
>
> Retriever and reranker spans in the trace tree.

> [card] [PII redaction](https://docs.zespan.com/sdk/pii-redaction.md)
>
> What is redacted before data leaves your process.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.