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 (ADR-016: no custody; 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.
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 ctxflow-core's 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):
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:
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:
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:
# 0 lines of code
ctxflow-instrument python app.py
# 1 line: configures the SDK in process
import ctxflow_otel
ctxflow_otel.init() # idempotent; returns the TracerProvider
# 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 (ADR-016). 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 (ADR-016), 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 theOPENINFERENCE_HIDE_*variables (for exampleOPENINFERENCE_HIDE_INPUTS=true). The embedding spans'input.value(the text being embedded) is only hidden byOPENINFERENCE_HIDE_INPUTS, which hides prompts too. - The retriever spans are kept: they feed the read-side item identity. With them, a manual
retrievalspan 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()andattach(provider)do not activate it, so aLlamaIndexInstrumentor().instrument(config=TraceConfig(...))of your own (afterinit()) is the one in effect. Underctxflow-instrumentsuch a call has no effect (the instrumentor already runs; OpenTelemetry only logs that it is already instrumented): use theOPENINFERENCE_HIDE_*variables, or setOTEL_PYTHON_DISABLED_INSTRUMENTATIONS=llama_indexand 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) andtools/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) andgen_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 (ADR-016); 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 interiminput_requiredresult 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 inserver.middleware(the default). - mcp 1.x has no spans of its own.
openinference-instrumentation-mcppropagates 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 itsOTEL_*andCTXFLOW_*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()orctxflow-instrumentregisters one dispatcher span handler whenllama_index.coreis imported (apps that never ingest never load it). It stamps everyNodeParseroutput inIngestionPipeline.run,run_transformations,VectorStoreIndex.from_documents(with or withouttransformations=),index.insert, chained and hierarchical parsers, customNodeParsersubclasses and parsers built beforeinit().pipeline.transformationsis 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(anyBasePydanticVectorStore, also one imported afterinit()), each write emits oneingest.upsertspan per source: ids and text hashes of the nodes that have an embedding, plus thectxflow.source_id,source_version,source_hash(andchunker_version,id_mode,embed_model) the nodes already carry in their metadata.source_idfalls back tofile_path(relative toCTXFLOW_SOURCE_ROOT) orref_doc_id, and the version tosource_version()/CTXFLOW_SOURCE_VERSION; a version or hash the nodes do not have is left out (the core completes it from theingest.chunkspan, never from the batch). No span is added when the run's owningest.upsertis open (IngestionPipeline.runwith avector_store;arun, a cache hit andnum_workers > 1have none open, so the write is reported) or for a write nested in a reported one (async_addcallingadd). Set the C1 keys on your nodes yourself: nothing stamps nodes you do not get from aNodeParser. - Level 1 (one line):
from ctxflow_otel.ingest.llamaindex import ctxflow_transformations, thenIngestionPipeline(transformations=ctxflow_transformations([...])). It adds a picklable stage after each parser, so it also coversarunandnum_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_idmetadata, elsefile_pathrelative toCTXFLOW_SOURCE_ROOT, else the document id (warning if it is random and ids are deterministic). Never an absolute path.load_documents(root)sets it (andsource_hash, the sha256 of the file) for you.source_version:ctxflow.source_versionmetadata, elsewith source_version("v2"):, elseCTXFLOW_SOURCE_VERSION, else the labelh:<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 areuuid5(source_id | source_version | chunker_version | ordinal). With a stable document id (load_documents, or your ownid_) the ordinal is<doc_id>:<i>, the chunk position inside that document, so inserting page by page,num_workers > 1and re-ingesting after one page changed never collide. With a random document id the ordinal ish:<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, orparser.get_nodes_from_documents(docs)called directly (callparser(docs)instead). Use level 1 forarunand 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.embedis emitted only inside a run, a pipeline embed stage or an index insert/build.ingest.parseis a root span:load_documentsruns before the pipeline. Noingest.deletespan (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_elementsandpartition(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(withctxflow.embed_model); destination write ->ingest.upsert(sync, async and batch uploaders). The source id is the connector'srel_path(extension kept).- C1 is in each chunk's
ElementMetadataas the ad-hoc keysctxflow.source_id,source_version,source_hash,chunker_version,id_mode. They surviveelements_to_json,elements_from_dictsand the pipeline's ndjson/json files. A stager that flattens elements into rows (SQL, vector stores) keeps them as top-levelctxflow.*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, elsefile_directory/filenamerelative toCTXFLOW_SOURCE_ROOT, else the bare file name (setCTXFLOW_SOURCE_ROOT).source_version:with source_version("v2"):/CTXFLOW_SOURCE_VERSION, else the connector'sdata_source.version, elseh:<12 hex>of the file hash.- Ids: with
CTXFLOW_DETERMINISTIC_IDS=on,chunk_id = uuid5(source_id | source_version | chunker_version | <base>:<i>).iis the position among the chunks of one chunk call and source.baseish:<16 hex>of the sha256 of the first input element id when it is content-derived (partition ids hash filename, text, page and position), elseh:<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 andid_mode=defaultis recorded.- Why:
chunk_by_titlereturns random ids, and the library's re-hash uses only the bare file name, text and position, soa/x.mdandb/x.mdwith 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 onelement_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.
- Why:
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.upsertthen has noid_mode. - Not covered: the Unstructured API (
partition_by_api,chunk_by_api) andingest.delete(the pipeline does not propagate deletions). - ctxflow does not change the library's own usage telemetry: set
DO_NOT_TRACK/SCARF_NO_ANALYTICSyourself. - 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.parsespan:ctxflow.source_id(path relative toCTXFLOW_SOURCE_ROOT, extension kept; outside the root the labelh:<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) andctxflow.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 getsctxflow.source_idandctxflow.source_hashin its metadata (hidden from embeddings and LLMs; yourextra_infowins) 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 ofDoclingNodeParserwith the hash of the original file and, withCTXFLOW_DETERMINISTIC_IDS=on, stable ids. The chunker version isllamaindex-docling-<chunker kind>-<hash>(hash ofmax_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
HybridChunkeror other Docling chunkers: onlyingest.parseis 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_stringand the pairing of results with sources inside ZIP archives are not covered. ctxflow.parse.charscounts 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 defaultuv syncand CI do not install it (it pulls torch).
Apache-2.0. Documentation: https://docs.ctxflow.sh. Release notes: CHANGELOG.md in the source distribution.
Metadata
Release files for ctxflow-otel 0.2.2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| ctxflow_otel-0.2.2.tar.gz | 78.6 kB | With provenance | Details for ctxflow_otel-0.2.2.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| ctxflow_otel-0.2.2-py3-none-any.whl | Python 3 | none | any | Details for ctxflow_otel-0.2.2-py3-none-any.whl |
Total release size: 159.8 kB
Release files / ctxflow_otel-0.2.2.tar.gz
| Download URL | ctxflow_otel-0.2.2.tar.gz |
|---|---|
| Size | 78.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
2a8b963f6cffb849ae2e355b0271496163d5d4520afbfac3d7005ae0130a0509
|
|
BLAKE2b-256 checksum How to use checksums |
bd4d87cf90b288528193591429b177a81e85d1e1886304900b9cf7a9c629467b
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.
Transparency logRelease files / ctxflow_otel-0.2.2-py3-none-any.whl
| Download URL | ctxflow_otel-0.2.2-py3-none-any.whl |
|---|---|
| Size | 81.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
6eb8ece81610ad51df7784f7dc33610011823f4710aa67cf7d7eedab34030b3d
|
|
BLAKE2b-256 checksum How to use checksums |
0bb03fb5c7f9258f3464b457dbeb91717f1fb31545a4496077af6f3569a60f55
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.
Transparency logSecurity for ctxflow-otel 0.2.2
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for ctxflow_otel-0.2.2.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.