Metadata-Version: 2.4
Name: ctxflow-otel
Version: 0.2.3
Summary: OpenTelemetry SDK for AI agent context observability: see what your agent retrieved, was given and did.
Keywords: opentelemetry,observability,llm-observability,ai-agents,rag,llm,mcp,llamaindex,tracing,ctxflow
Author: ctxflow
License-Expression: Apache-2.0
License-File: LICENSE
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: OpenTelemetry
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: System :: Monitoring
Classifier: Typing :: Typed
Requires-Dist: ctxflow-semconv>=0.2,<0.3
Requires-Dist: opentelemetry-sdk>=1.40,<2
Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.40,<2
Requires-Dist: opentelemetry-instrumentation>=0.61b0,<1
Requires-Dist: docling>=2.150,<3 ; extra == 'docling'
Requires-Dist: llama-index-core>=0.14.19,<0.15 ; extra == 'llamaindex'
Requires-Dist: openinference-instrumentation-llama-index>=4.7,<5 ; extra == 'llamaindex'
Requires-Dist: mcp>=1.24,<3 ; extra == 'mcp'
Requires-Dist: openinference-instrumentation-mcp>=2,<3 ; extra == 'mcp'
Requires-Dist: unstructured[md]>=0.27,<0.28 ; extra == 'unstructured'
Requires-Dist: unstructured-ingest>=1.12,<1.13 ; extra == 'unstructured'
Requires-Python: >=3.12
Project-URL: Homepage, https://ctxflow.sh
Project-URL: Documentation, https://docs.ctxflow.sh
Project-URL: Changelog, https://docs.ctxflow.sh/reference/changelogs/
Project-URL: Source, https://github.com/ctxflow-sh/ctxflow-edge
Project-URL: Issues, https://github.com/ctxflow-sh/ctxflow-edge/issues
Provides-Extra: docling
Provides-Extra: llamaindex
Provides-Extra: mcp
Provides-Extra: unstructured
Description-Content-Type: text/markdown

# ctxflow-otel

ctxflow OpenTelemetry distribution for Python: identity from baggage and the read-side item identity on top of the OpenTelemetry SDK. The text leaves: prompts, answers, chunk text, tool results and exceptions reach ctxflow as the app wrote them, with chunk ids as stored and plain sha256 hashes (see [What is sent](https://docs.ctxflow.sh/data-and-privacy/what-is-sent/); if your data must not leave your network, run ctxflow self-hosted). The extras activate the instrumentations they need (`[mcp]`, `[llamaindex]`); any other one (OpenInference, Traceloop...) you install yourself.

## Quickstart

Requires Python 3.12 or later.

```sh
pip install ctxflow-otel         # or ctxflow-otel[mcp] to propagate identity through MCP (mcp 1.x and 2.x)
export OTEL_SERVICE_NAME=my-agent
export OTEL_EXPORTER_OTLP_ENDPOINT=http://collector:4318   # a ctxflow collector, or the ctxflow OTLP endpoint
```

Check a host's setup (config, exporter endpoint and API key; with `CTXFLOW_CORE_ENDPOINT` and `CTXFLOW_API_KEY`, the core as the collector reaches it):

```sh
ctxflow-otel check          # or: python -m ctxflow_otel check; exit code 1 if a check failed
```

When the core accepts the key, `check` also asks it which project and environment the key belongs to and when data last arrived there (`GET /v1/whoami`, which ingests nothing), so you can see that the key is the one you meant (Development or Production) and that your data reaches it:

```text
ok: identity: key targets project "Support Bot", environment "Development", last event 3 min ago
```

`no events yet` means nothing was ingested for that environment. When the key is for a Development or Staging environment (the core says it in `environment.kind`), `check` adds a warning, because that data shows only in that environment, not in Production:

```text
warn: identity: key targets environment "Development" (development), not production: data sent with this key shows only there. For production data, create a key in the project's Production environment.
```

A custom environment, a Production key and a core that does not send `kind` (older) give no warning. A core without that endpoint gives a `warn:` line and the other checks are unchanged; the line never makes `check` fail.

Three integration levels:

```sh
# 0 lines of code
ctxflow-instrument python app.py
```

```python
# 1 line: configures the SDK in process
import ctxflow_otel

ctxflow_otel.init()  # idempotent; returns the TracerProvider
```

```python
# Processors only: you own the TracerProvider
ctxflow_otel.attach(provider)
```

Identity: `with ctxflow_otel.conversation("conv-42", user_id="u1", turn=3): ...` puts it on every span started inside.

`CTXFLOW_CUSTODY` and `CTXFLOW_HMAC_KEY` of pre-release builds are ignored, with one warning at startup (ctxflow keeps no custody of the text). Hashes in the ingestion sections below are plain sha256.

## LlamaIndex agent, LLM and tool spans

`pip install "ctxflow-otel[llamaindex]"` also installs `openinference-instrumentation-llama-index`. `ctxflow-instrument` activates it when `llama-index-core` is installed, so a `FunctionAgent` (or any LlamaIndex app) exports its agent/workflow, LLM, tool and retriever spans with no manual code. ctxflow activates it itself, with `skip_dep_check`: the stock OpenInference entry point is skipped by OpenTelemetry in a normal app (it declares `llama-index-multi-modal-llms-openai` as a dependency), and ctxflow does not load it.

- Text leaves as the app wrote it, retrieved documents and their metadata included. Embeddings are always hidden (`hide_embeddings_text`, `hide_embeddings_vectors`: the embedding span would repeat the query and carry the full vector). To hide more, set the `OPENINFERENCE_HIDE_*` variables (for example `OPENINFERENCE_HIDE_INPUTS=true`). The embedding spans' `input.value` (the text being embedded) is only hidden by `OPENINFERENCE_HIDE_INPUTS`, which hides prompts too.
- The retriever spans are kept: they feed the read-side item identity. With them, a manual `retrieval` span around a LlamaIndex retriever is not needed. If you keep one inside an agent tool, the two spans are siblings and the core counts two retrievals with the same items until it merges them; outside an agent (a plain retriever call under your own span) the retriever span is a child of yours and counts once.
- Opt out with `OTEL_PYTHON_DISABLED_INSTRUMENTATIONS=llama_index`.
- `init()` and `attach(provider)` do not activate it, so a `LlamaIndexInstrumentor().instrument(config=TraceConfig(...))` of your own (after `init()`) is the one in effect. Under `ctxflow-instrument` such a call has no effect (the instrumentor already runs; OpenTelemetry only logs that it is already instrumented): use the `OPENINFERENCE_HIDE_*` variables, or set `OTEL_PYTHON_DISABLED_INSTRUMENTATIONS=llama_index` and make your own call.

## Skipped instrumentors

OpenTelemetry skips an instrumentor whose declared dependencies do not match the installed libraries, and says so only in a low-level log line. With `ctxflow-instrument`, ctxflow logs a WARNING for each known AI instrumentor (OpenInference: LlamaIndex, MCP, OpenAI, Anthropic, LangChain) that is installed, whose library is installed too, and that did not run. The message names the instrumentor and the way out: fix the dependency, or set `OTEL_PYTHON_DISABLED_INSTRUMENTATIONS=<name>` to silence it.

## MCP

`pip install "ctxflow-otel[mcp]"` (mcp 1.24+ and 2.x). `init()` or `ctxflow-instrument` makes MCP carry the trace context and the baggage (identity) in `params._meta`, so a tool span on the server has the conversation of the client. Call `ctxflow_otel.mcp.instrument_mcp()` yourself with `attach()`.

- **mcp 2.x** creates its own spans (scope `mcp-python-sdk`): `MCP send tools/call <tool>` (client) and `tools/call <tool>` (server, `gen_ai.operation.name=execute_tool`). The SDK adds a middleware to every server connection that attaches the incoming baggage to the handler, and records the tool call on the server span: `gen_ai.tool.call.arguments` (the arguments as compact JSON) and `gen_ai.tool.call.result` (the text blocks of the result joined by a newline, or the JSON of the result if it has other blocks). The text leaves as it is; ctxflow stores it or not according to the project's text setting. It is recorded where the tool runs: the server span is the tool call ctxflow reads, and the client span (`MCP send`) is not a tool call and carries no text. Binary results (image, audio, blob) become a placeholder such as `[image image/png 3000004 bytes]`, an interim `input_required` result records no result, and each attribute is cut at 64 KiB (the core's limit). A server that does not run the SDK sends no tool text, whatever the client does, and the server needs mcp's span middleware in `server.middleware` (the default).
- **mcp 1.x** has no spans of its own. `openinference-instrumentation-mcp` propagates the context. The tool text comes from the instrumentation of the framework that calls the tool (OpenInference, Traceloop...).
- Stdio servers: `ctxflow_otel.mcp.child_env()` gives the child process its `OTEL_*` and `CTXFLOW_*` variables (it forwards secrets too: only for servers you trust).

## Ingestion (LlamaIndex)

`pip install "ctxflow-otel[llamaindex]"` (llama-index-core 0.14.x). Chunks get the ctxflow source identity and `ingest.*` spans, with no manual spans.

- **Level 0 (no code):** `init()` or `ctxflow-instrument` registers one dispatcher span handler when `llama_index.core` is imported (apps that never ingest never load it). It stamps every `NodeParser` output in `IngestionPipeline.run`, `run_transformations`, `VectorStoreIndex.from_documents` (with or without `transformations=`), `index.insert`, chained and hierarchical parsers, custom `NodeParser` subclasses and parsers built before `init()`. `pipeline.transformations` is never changed.
- **Direct vector store writes (level 0, no code):** if your app builds its own nodes and calls `vector_store.add(nodes)` / `async_add` (any `BasePydanticVectorStore`, also one imported after `init()`), each write emits one `ingest.upsert` span per source: ids and text hashes of the nodes that have an embedding, plus the `ctxflow.source_id`, `source_version`, `source_hash` (and `chunker_version`, `id_mode`, `embed_model`) the nodes already carry in their metadata. `source_id` falls back to `file_path` (relative to `CTXFLOW_SOURCE_ROOT`) or `ref_doc_id`, and the version to `source_version()` / `CTXFLOW_SOURCE_VERSION`; a version or hash the nodes do not have is left out (the core completes it from the `ingest.chunk` span, never from the batch). No span is added when the run's own `ingest.upsert` is open (`IngestionPipeline.run` with a `vector_store`; `arun`, a cache hit and `num_workers > 1` have none open, so the write is reported) or for a write nested in a reported one (`async_add` calling `add`). Set the C1 keys on your nodes yourself: nothing stamps nodes you do not get from a `NodeParser`.
- **Level 1 (one line):** `from ctxflow_otel.ingest.llamaindex import ctxflow_transformations`, then `IngestionPipeline(transformations=ctxflow_transformations([...]))`. It adds a picklable stage after each parser, so it also covers `arun` and `num_workers > 1`. Its settings are part of the pipeline cache key. If both levels are on, nothing is stamped twice.

Each chunk carries `ctxflow.source_id`, `source_version`, `source_hash`, `chunker_version` and `id_mode` in its metadata, hidden from embedding models and LLMs (`excluded_*_metadata_keys` of the chunk; your Documents are not changed). Spans: `ingest.run`, `ingest.parse` (`load_documents`), `ingest.chunk`, `ingest.embed`, `ingest.upsert`; they hold ids, hashes and lengths, never text.

- `source_id`: `ctxflow.source_id` metadata, else `file_path` relative to `CTXFLOW_SOURCE_ROOT`, else the document id (warning if it is random and ids are deterministic). Never an absolute path. `load_documents(root)` sets it (and `source_hash`, the sha256 of the file) for you.
- `source_version`: `ctxflow.source_version` metadata, else `with source_version("v2"):`, else `CTXFLOW_SOURCE_VERSION`, else the label `h:<12 hex>` of the content hash with a one-time warning. That fallback is not a corpus version label. Set the version explicitly.
- `CTXFLOW_DETERMINISTIC_IDS=on`: chunk ids are `uuid5(source_id | source_version | chunker_version | ordinal)`. With a stable document id (`load_documents`, or your own `id_`) the ordinal is `<doc_id>:<i>`, the chunk position inside that document, so inserting page by page, `num_workers > 1` and re-ingesting after one page changed never collide. With a random document id the ordinal is `h:<16 hex>` of the sha256 of the document text plus the page occurrence and position, so the ids follow the content. Chained parsers join their chunker versions with `/`; the chunker version also holds the parameters that change the chunks (chunk size and overlap, `chunk_sizes`, window and buffer sizes, breakpoint threshold, embedding model name). Every relationship is rewritten, so none dangles.

Limits:
- Level 0 does not cover `arun` (the run and embed spans appear, but no C1 and no ids), `num_workers > 1`, or `parser.get_nodes_from_documents(docs)` called directly (call `parser(docs)` instead). Use level 1 for `arun` and workers.
- Any `IngestionCache`, including the default in-memory one of each pipeline, keeps the chunks and the version of its first run at level 0. Use level 1 if the version changes while a cache lives.
- If both levels are on, the first one to stamp sets the id mode (a stage never turns deterministic ids back into default ones; it does upgrade default chunks to deterministic). A stage with an explicit version re-stamps chunks of another version, such as a cached output.
- `ingest.embed` is emitted only inside a run, a pipeline embed stage or an index insert/build.
- `ingest.parse` is a root span: `load_documents` runs before the pipeline. No `ingest.delete` span (LlamaIndex has no hook).
- Only llama-index-core 0.14.x is tested.

## Ingestion (Unstructured)

`pip install "ctxflow-otel[unstructured]"` (unstructured 0.27.x with `md`, unstructured-ingest 1.12.x). `init()` or `ctxflow-instrument` wraps the library when it is imported (`init()` imports nothing itself). Call `init()` before `from unstructured... import partition` or the old function stays, and before you create a `Pipeline`: `Pipeline.__init__` calls `set_tracer_provider`, so a Pipeline built first sends its spans to the library's provider, without ctxflow's processors. The library's own step spans (`partition`, `chunk`, `upload`...) reach your exporter too. Tested with md, txt and html.

- `partition` / `partition_*` -> `ingest.parse` (sha256 of the original file, source id, version, text length). `chunk_by_title`, `chunk_elements` and `partition(chunking_strategy=...)` -> `ingest.chunk`, one span per chunk call and source.
- `unstructured-ingest`: `Pipeline.run` -> `ingest.run`; chunk step -> `ingest.chunk`; embed step -> `ingest.embed` (with `ctxflow.embed_model`); destination write -> `ingest.upsert` (sync, async and batch uploaders). The source id is the connector's `rel_path` (extension kept).
- C1 is in each chunk's `ElementMetadata` as the ad-hoc keys `ctxflow.source_id`, `source_version`, `source_hash`, `chunker_version`, `id_mode`. They survive `elements_to_json`, `elements_from_dicts` and the pipeline's ndjson/json files. A stager that flattens elements into rows (SQL, vector stores) keeps them as top-level `ctxflow.*` fields when the destination accepts extra fields; a destination with a fixed table schema drops those it has no column for.
- `source_id`: from the parse step, else `file_directory/filename` relative to `CTXFLOW_SOURCE_ROOT`, else the bare file name (set `CTXFLOW_SOURCE_ROOT`). `source_version`: `with source_version("v2"):` / `CTXFLOW_SOURCE_VERSION`, else the connector's `data_source.version`, else `h:<12 hex>` of the file hash.
- Ids: with `CTXFLOW_DETERMINISTIC_IDS=on`, `chunk_id = uuid5(source_id | source_version | chunker_version | <base>:<i>)`. `i` is the position among the chunks of one chunk call and source. `base` is `h:<16 hex>` of the sha256 of the first input element id when it is content-derived (partition ids hash filename, text, page and position), else `h:<16 hex>` of the sha256 of the input texts. A source chunked in several calls gets distinct ids, and the same inputs give the same ids. The ids are applied again after the library's own re-hash. Off: the library's ids stay and `id_mode=default` is recorded.
  - Why: `chunk_by_title` returns random ids, and the library's re-hash uses only the bare file name, text and position, so `a/x.md` and `b/x.md` with the same text collide.
  - In the pipeline, the destination's primary key is the library's own (a uuid5 of the element id), not the C2 id. The C2 id lives in `element_id` (and in the spans). Join on `element_id`.
  - Chunker version: `unstructured-<by_title|basic>-<10 hex>` of the effective options (library defaults resolved), the same for the direct call and the pipeline.

Limits:
- A chunk call over several documents is split per source (each chunked alone), so its output differs from the library's even with ids off.
- Run the pipeline with `num_processes=1`: with more, the steps run in forked workers and their spans are lost.
- Chunk strategies the pipeline does not run locally (`by_page`, `by_similarity`, API chunking) get no C1 and keep the library's ids; `ingest.upsert` then has no `id_mode`.
- Not covered: the Unstructured API (`partition_by_api`, `chunk_by_api`) and `ingest.delete` (the pipeline does not propagate deletions).
- ctxflow does not change the library's own usage telemetry: set `DO_NOT_TRACK` / `SCARF_NO_ANALYTICS` yourself.
- Elements built by hand have no filename: source id is the label `h:<12 hex>` of the hash of their text (it changes with the content: give a filename).

## Ingestion (Docling)

`pip install "ctxflow-otel[docling]"` (docling 2.150+, tested on 2.151.1). `init()` or `ctxflow-instrument` wraps, when Docling is imported, the public `DocumentConverter.convert_all` (`convert` calls it) and, if `llama-index-readers-docling` is installed, `DoclingReader.lazy_load_data`.

- Each converted file gets an `ingest.parse` span: `ctxflow.source_id` (path relative to `CTXFLOW_SOURCE_ROOT`, extension kept; outside the root the label `h:<12 hex>` of the file hash with a one-time warning), `ctxflow.source_hash` (sha256 of the ORIGINAL file bytes, not of the converted text) and `ctxflow.parse.chars` (length of the Markdown export; size only). A failed conversion marks the span as an error.
- With `DoclingReader` (markdown or JSON export) each Document gets `ctxflow.source_id` and `ctxflow.source_hash` in its metadata (hidden from embeddings and LLMs; your `extra_info` wins) and, if its id is random and the source id is a root-relative path, that path as its id. The LlamaIndex extra then stamps the chunks of `DoclingNodeParser` with the hash of the original file and, with `CTXFLOW_DETERMINISTIC_IDS=on`, stable ids. The chunker version is `llamaindex-docling-<chunker kind>-<hash>` (hash of `max_tokens`, tokenizer model, `merge_peers`... of the Docling chunker), joined with `/` to other parsers in a chain.

Limits:
- Without LlamaIndex nothing stamps the chunks of `HybridChunker` or other Docling chunkers: only `ingest.parse` is emitted. `ctxflow_otel.ingest.docling.source_metadata(path)` returns the C1 keys for your own chunks.
- Sources that are URLs get the span without `source_id`/`source_hash`. `convert_string` and the pairing of results with sources inside ZIP archives are not covered.
- `ctxflow.parse.chars` counts the characters of the text items (not tables cells or the exact export length). ZIP archive members, and every result after the first one that does not match its source, get no identity.
- Local verification: Docling is in the uv group `docling` (`uv sync --all-packages --group docling`); the default `uv sync` and CI do not install it (it pulls torch).

Apache-2.0. Documentation: https://docs.ctxflow.sh. Release notes: `CHANGELOG.md` in the source distribution.
