ctxflow-otel 0.2.2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ctxflow_otel-0.2.2/CHANGELOG.md +56 -0
- ctxflow_otel-0.2.2/LICENSE +202 -0
- ctxflow_otel-0.2.2/PKG-INFO +174 -0
- ctxflow_otel-0.2.2/README.md +135 -0
- ctxflow_otel-0.2.2/pyproject.toml +81 -0
- ctxflow_otel-0.2.2/pyproject.toml.orig +79 -0
- ctxflow_otel-0.2.2/src/ctxflow_otel/__init__.py +113 -0
- ctxflow_otel-0.2.2/src/ctxflow_otel/__main__.py +5 -0
- ctxflow_otel-0.2.2/src/ctxflow_otel/check.py +538 -0
- ctxflow_otel-0.2.2/src/ctxflow_otel/cli.py +51 -0
- ctxflow_otel-0.2.2/src/ctxflow_otel/config.py +50 -0
- ctxflow_otel-0.2.2/src/ctxflow_otel/conversation.py +85 -0
- ctxflow_otel-0.2.2/src/ctxflow_otel/distro.py +175 -0
- ctxflow_otel-0.2.2/src/ctxflow_otel/export.py +82 -0
- ctxflow_otel-0.2.2/src/ctxflow_otel/identity.py +76 -0
- ctxflow_otel-0.2.2/src/ctxflow_otel/ingest/__init__.py +286 -0
- ctxflow_otel-0.2.2/src/ctxflow_otel/ingest/common.py +307 -0
- ctxflow_otel-0.2.2/src/ctxflow_otel/ingest/docling.py +308 -0
- ctxflow_otel-0.2.2/src/ctxflow_otel/ingest/llamaindex.py +1137 -0
- ctxflow_otel-0.2.2/src/ctxflow_otel/ingest/unstructured.py +537 -0
- ctxflow_otel-0.2.2/src/ctxflow_otel/ingest/unstructured_pipeline.py +269 -0
- ctxflow_otel-0.2.2/src/ctxflow_otel/instrumentors.py +94 -0
- ctxflow_otel-0.2.2/src/ctxflow_otel/llamaindex.py +150 -0
- ctxflow_otel-0.2.2/src/ctxflow_otel/mcp.py +280 -0
- ctxflow_otel-0.2.2/src/ctxflow_otel/py.typed +0 -0
- ctxflow_otel-0.2.2/src/ctxflow_otel/retrieval.py +83 -0
- ctxflow_otel-0.2.2/src/ctxflow_otel/text.py +56 -0
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to `ctxflow-otel`. Format: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Versioning: [SemVer](https://semver.org/).
|
|
4
|
+
|
|
5
|
+
## [Unreleased]
|
|
6
|
+
|
|
7
|
+
## [0.2.2] - 2026-11-29
|
|
8
|
+
|
|
9
|
+
### Fixed
|
|
10
|
+
|
|
11
|
+
- **LlamaIndex with Gemini: no more `AttributeError: 'list' object has no attribute 'get'` from the OpenInference handler.** `openinference-instrumentation-llama-index` (4.7.11, the latest) reads `usage_metadata.prompt_tokens_details` as an OpenAI mapping, but `llama-index-llms-google-genai` puts a list of per-modality counts there. Every `LLMChatEndEvent` logged an error and the counts after that line (reasoning tokens, cache read, thought tokens in the completion count) were lost. `instrument_llamaindex()` now wraps the handler's `_get_token_counts_impl` so a list or tuple of details reads as absent; OpenAI and Anthropic shapes are unchanged.
|
|
12
|
+
- **Direct vector store writes are reported as index writes.** An app that builds its own nodes and writes them with `vector_store.add` / `async_add` (no `NodeParser` call) showed "Index writes: silent". The LlamaIndex ingestion extra now wraps `add` and `async_add` of every `BasePydanticVectorStore` subclass (also those imported after `init()`) and emits one `ingest.upsert` span per source, with chunk ids, text hashes and the `ctxflow.source_*` keys the nodes already carry (the ambient `source_version()` counts). A key a node does not have is left out, never computed from the batch: the core completes it from the `ingest.chunk` span. A write does not add a span when the run's own `ingest.upsert` is open (`IngestionPipeline.run` with a `vector_store`; not under `arun`, a cache hit or `num_workers > 1`, where the write is reported) or when it is nested in a reported write (`async_add` calling `add`, also through `run_in_executor`). An `IngestionPipeline` without a `vector_store` no longer emits an `ingest.upsert`: it writes nothing.
|
|
13
|
+
|
|
14
|
+
### Added
|
|
15
|
+
|
|
16
|
+
- `ctxflow-otel check` warns when the API key is for a Development or Staging environment (`environment.kind` of `GET /v1/whoami`), and says to create a key in the project's Production environment for production data. A Production or custom environment, or a core that does not send `kind`, gives no warning; the exit code does not change.
|
|
17
|
+
|
|
18
|
+
### Removed
|
|
19
|
+
|
|
20
|
+
- **Context usage judgement.** ctxflow no longer judges whether the answer used a retrieved chunk (the lexical overlap score was unreliable with paraphrase, summaries and other languages). The core states that a chunk was delivered to the model (retrieved in the turn). `ctxflow_otel.usage` (`UsageProcessor`, the scorer, the `ctxflow.usage` span) and `ctxflow_otel.distro.usage_processors` are gone; `init()`, `attach()` and `ctxflow-instrument` no longer install a usage processor.
|
|
21
|
+
- `CTXFLOW_USAGE`, `CTXFLOW_USAGE_THRESHOLD` and `CTXFLOW_USAGE_RETRIEVAL_TOOLS`, and the `usage`, `usage_threshold` and `usage_retrieval_tools` fields of `Config`. If one of the variables is set, the SDK logs one warning that it has no effect since 0.2.2 and goes on. `ctxflow-otel check` no longer prints `config: usage on|off`.
|
|
22
|
+
|
|
23
|
+
### Compatibility
|
|
24
|
+
|
|
25
|
+
- Apps that still run an older SDK keep emitting `ctxflow.usage` spans; the core accepts and ignores them.
|
|
26
|
+
|
|
27
|
+
## [0.2.1] - 2026-11-29
|
|
28
|
+
|
|
29
|
+
### Changed
|
|
30
|
+
|
|
31
|
+
- **Usage: the answer of a LlamaIndex workflow root.** A root `output.value` that is the `StopEvent(...)` repr written by the OpenInference LlamaIndex instrumentor (scope `openinference.instrumentation.llama_index`, kind CHAIN) is no longer taken as the answer: the last model span's output is used, as with a JSON root. Other roots, CHAIN ones included, keep their plain-text answer. Same rule in the Python SDK and the collector's usage processor.
|
|
32
|
+
|
|
33
|
+
### Added
|
|
34
|
+
|
|
35
|
+
- **LlamaIndex agent, LLM and tool spans.** The `[llamaindex]` extra now installs `openinference-instrumentation-llama-index`, and `ctxflow-instrument` (not `init()`, so a `LlamaIndexInstrumentor().instrument(config=...)` of your own after `init()` is the one in effect) activates it when `llama-index-core` is installed (`ctxflow_otel.llamaindex.instrument_llamaindex()`); the extra now requires `llama-index-core>=0.14.19`. Under `ctxflow-instrument` your own `instrument(config=...)` call has no effect (it already runs): hide text with `OPENINFERENCE_HIDE_*`, or disable `llama_index` with `OTEL_PYTHON_DISABLED_INSTRUMENTATIONS` and call it yourself, with `skip_dep_check` and a `TraceConfig` that always hides embedding text and vectors. Before, OpenTelemetry skipped the stock entry point (it declares `llama-index-multi-modal-llms-openai`, which a normal app does not install) and no LlamaIndex span left the process. Opt out with `OTEL_PYTHON_DISABLED_INSTRUMENTATIONS=llama_index`; hide more with `OPENINFERENCE_HIDE_*`.
|
|
36
|
+
- **A WARNING when a known AI instrumentor is installed but skipped** (OpenInference LlamaIndex, MCP, OpenAI, Anthropic, LangChain): it names the instrumentor and the fix. It runs after `ctxflow-instrument` loads the instrumentors and honours `OTEL_PYTHON_DISABLED_INSTRUMENTATIONS`.
|
|
37
|
+
- `ctxflow-otel check` shows which project and environment the API key targets and when data last arrived there (`GET /v1/whoami` of the core). An older core (404) gives a warning, never a failure.
|
|
38
|
+
- mcp 2.x: the server span of `tools/call` (the `execute_tool` span) carries `gen_ai.tool.call.arguments` and `gen_ai.tool.call.result`, so the tool input and result reach ctxflow. A second server middleware, just inside the MCP span middleware, records them. mcp 1.x is unchanged.
|
|
39
|
+
- The resource carries `ctxflow.semconv.version` (the version of `ctxflow-semconv`, the contract the SDK writes) next to `telemetry.distro.*`, with the same precedence: it wins over `OTEL_RESOURCE_ATTRIBUTES` and is set only when the SDK creates the provider.
|
|
40
|
+
|
|
41
|
+
## [0.2.0] - 2026-11-26
|
|
42
|
+
|
|
43
|
+
First release. Requires Python 3.12+ and `ctxflow-semconv>=0.2,<0.3`.
|
|
44
|
+
|
|
45
|
+
### Added
|
|
46
|
+
|
|
47
|
+
- **Three integration levels** with one code path (`CtxflowConfigurator`): `ctxflow-instrument python app.py` (OpenTelemetry distro and configurator, no code), `init()` (one line) and `attach(provider)` (processors only, for a provider you own). Identity from baggage on every span (`IdentityProcessor`) and the `conversation()` helper. The `[mcp]` extra (`mcp>=1.24,<3`, `openinference-instrumentation-mcp>=2,<3`) propagates trace context and baggage in MCP `params._meta` with the MCP Python SDK 1.x and 2.x, exactly once. mcp 2.x propagates natively and creates its own client and server spans: `instrument_mcp()` detects it (`ctxflow_otel.mcp.native_propagation()`), does not apply the openinference instrumentation, and adds a server middleware that attaches the incoming baggage to the handler, so spans in tool handlers carry the conversation identity. With mcp 1.x nothing changes. `ctxflow-instrument` does the same through its configurator, and the distro skips the openinference entry point `mcp` when the SDK is 2.x. With mcp 1.x, `instrument_mcp()` logs a warning and returns False if `openinference-instrumentation-mcp` reports a dependency conflict.
|
|
48
|
+
- **No custody (ADR-016).** Prompts, answers, chunk text, tool results and exceptions leave as the app wrote them; chunk ids leave as the vector store holds them and content hashes are plain sha256 (no key, no `k:<key id>:` values). If your data must not leave your network, run ctxflow self-hosted. `CTXFLOW_CUSTODY` and `CTXFLOW_HMAC_KEY` are ignored, with one warning per process. The exporter is `ctxflow_otel.export.ItemIdentityExporter`: it adds the read-side item identity to retrieval spans and passes everything else as it is.
|
|
49
|
+
- **Usage analytics in the SDK (ADR-013, signal S7):** `UsageProcessor` scores each turn when its local root span ends (`lexical-overlap-v1`, threshold 0.2, `CTXFLOW_USAGE_THRESHOLD`) from the answer and the retrieved items' text, and emits a `ctxflow.usage` span with ids and scores only. Items come from retriever spans (OpenInference, OTel GenAI) and from the result of a marked retrieval tool call (`ctxflow.retrieval.tool` or `CTXFLOW_USAGE_RETRIEVAL_TOOLS`, a JSON list of `{id, text}`). It runs off the app thread, is fork-safe, and is installed unless `CTXFLOW_USAGE=off`. Public pure modules `ctxflow_otel.usage.score`, `.extract` and `.evaluate`, pinned by the conformance vectors of `ctxflow-semconv`.
|
|
50
|
+
- **Read-side item identity:** a retrieval span gets `ctxflow.retrieval.item_ids`, `item_hashes` and `item_verifiable`, measured before any reranker or compressor. The text hash (`ctxflow_otel.text`) normalizes with Unicode NFC, one space per whitespace run and trim.
|
|
51
|
+
- **Ingestion extras** `[llamaindex]`, `[docling]` and `[unstructured]`: `ingest.*` spans, C1 chunk metadata (`source_id`, `source_version`, `source_hash` of the original bytes, `chunker_version`, `id_mode`), `ctxflow.chunks.ids` and `ctxflow.chunks.text_hashes` (the same hash as the read side), and deterministic chunk ids with `CTXFLOW_DETERMINISTIC_IDS=on` (a random document id is made content-addressed by the sha256 of its text). Helpers `ctxflow_otel.source_hash(data)` and `ctxflow_otel.content_hash(text)` (plain sha256).
|
|
52
|
+
- **`ctxflow-otel check`** (also `python -m ctxflow_otel check`): checks one host's setup, one line per check, exit code 1 if any failed: the `CTXFLOW_*` config; the OTLP traces endpoint (with its headers and TLS files) is the core and accepts the key, or another endpoint (your collector) accepts an empty OTLP request; with `CTXFLOW_CORE_ENDPOINT` and `CTXFLOW_API_KEY`, the core accepts the collector's key. Redirects are never followed, each probe has a 10 s deadline and sends a `ctxflow-otel/<version>` user agent.
|
|
53
|
+
|
|
54
|
+
### Notes
|
|
55
|
+
|
|
56
|
+
- Pre-release builds had a separate edge worker (`ctxflow-edge-worker`: usage service, observers, signed adapters, `check`). It is retired (ADR-013) and not part of any release: usage is scored by this SDK and by the collector, and `check` is the command above.
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ctxflow-otel
|
|
3
|
+
Version: 0.2.2
|
|
4
|
+
Summary: ctxflow OpenTelemetry distribution for Python.
|
|
5
|
+
Keywords: opentelemetry,llm,mcp,ctxflow
|
|
6
|
+
Author: ctxflow
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Classifier: Development Status :: 4 - Beta
|
|
10
|
+
Classifier: Framework :: OpenTelemetry
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Topic :: System :: Monitoring
|
|
18
|
+
Classifier: Typing :: Typed
|
|
19
|
+
Requires-Dist: ctxflow-semconv>=0.2,<0.3
|
|
20
|
+
Requires-Dist: opentelemetry-sdk>=1.40,<2
|
|
21
|
+
Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.40,<2
|
|
22
|
+
Requires-Dist: opentelemetry-instrumentation>=0.61b0,<1
|
|
23
|
+
Requires-Dist: docling>=2.150,<3 ; extra == 'docling'
|
|
24
|
+
Requires-Dist: llama-index-core>=0.14.19,<0.15 ; extra == 'llamaindex'
|
|
25
|
+
Requires-Dist: openinference-instrumentation-llama-index>=4.7,<5 ; extra == 'llamaindex'
|
|
26
|
+
Requires-Dist: mcp>=1.24,<3 ; extra == 'mcp'
|
|
27
|
+
Requires-Dist: openinference-instrumentation-mcp>=2,<3 ; extra == 'mcp'
|
|
28
|
+
Requires-Dist: unstructured[md]>=0.27,<0.28 ; extra == 'unstructured'
|
|
29
|
+
Requires-Dist: unstructured-ingest>=1.12,<1.13 ; extra == 'unstructured'
|
|
30
|
+
Requires-Python: >=3.12
|
|
31
|
+
Project-URL: Homepage, https://ctxflow.sh
|
|
32
|
+
Project-URL: Documentation, https://docs.ctxflow.sh
|
|
33
|
+
Project-URL: Changelog, https://docs.ctxflow.sh/reference/changelogs/
|
|
34
|
+
Provides-Extra: docling
|
|
35
|
+
Provides-Extra: llamaindex
|
|
36
|
+
Provides-Extra: mcp
|
|
37
|
+
Provides-Extra: unstructured
|
|
38
|
+
Description-Content-Type: text/markdown
|
|
39
|
+
|
|
40
|
+
# ctxflow-otel
|
|
41
|
+
|
|
42
|
+
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.
|
|
43
|
+
|
|
44
|
+
## Quickstart
|
|
45
|
+
|
|
46
|
+
Requires Python 3.12 or later.
|
|
47
|
+
|
|
48
|
+
```sh
|
|
49
|
+
pip install ctxflow-otel # or ctxflow-otel[mcp] to propagate identity through MCP (mcp 1.x and 2.x)
|
|
50
|
+
export OTEL_SERVICE_NAME=my-agent
|
|
51
|
+
export OTEL_EXPORTER_OTLP_ENDPOINT=http://collector:4318 # a ctxflow collector, or ctxflow-core's OTLP endpoint
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
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):
|
|
55
|
+
|
|
56
|
+
```sh
|
|
57
|
+
ctxflow-otel check # or: python -m ctxflow_otel check; exit code 1 if a check failed
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
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:
|
|
61
|
+
|
|
62
|
+
```text
|
|
63
|
+
ok: identity: key targets project "Support Bot", environment "Development", last event 3 min ago
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
`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:
|
|
67
|
+
|
|
68
|
+
```text
|
|
69
|
+
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.
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
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.
|
|
73
|
+
|
|
74
|
+
Three integration levels:
|
|
75
|
+
|
|
76
|
+
```sh
|
|
77
|
+
# 0 lines of code
|
|
78
|
+
ctxflow-instrument python app.py
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
# 1 line: configures the SDK in process
|
|
83
|
+
import ctxflow_otel
|
|
84
|
+
|
|
85
|
+
ctxflow_otel.init() # idempotent; returns the TracerProvider
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
# Processors only: you own the TracerProvider
|
|
90
|
+
ctxflow_otel.attach(provider)
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Identity: `with ctxflow_otel.conversation("conv-42", user_id="u1", turn=3): ...` puts it on every span started inside.
|
|
94
|
+
|
|
95
|
+
`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.
|
|
96
|
+
|
|
97
|
+
## LlamaIndex agent, LLM and tool spans
|
|
98
|
+
|
|
99
|
+
`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.
|
|
100
|
+
|
|
101
|
+
- 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 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.
|
|
102
|
+
- 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.
|
|
103
|
+
- Opt out with `OTEL_PYTHON_DISABLED_INSTRUMENTATIONS=llama_index`.
|
|
104
|
+
- `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.
|
|
105
|
+
|
|
106
|
+
## Skipped instrumentors
|
|
107
|
+
|
|
108
|
+
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.
|
|
109
|
+
|
|
110
|
+
## MCP
|
|
111
|
+
|
|
112
|
+
`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()`.
|
|
113
|
+
|
|
114
|
+
- **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 (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 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).
|
|
115
|
+
- **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...).
|
|
116
|
+
- 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).
|
|
117
|
+
|
|
118
|
+
## Ingestion (LlamaIndex)
|
|
119
|
+
|
|
120
|
+
`pip install "ctxflow-otel[llamaindex]"` (llama-index-core 0.14.x). Chunks get the ctxflow source identity and `ingest.*` spans, with no manual spans.
|
|
121
|
+
|
|
122
|
+
- **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.
|
|
123
|
+
- **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`.
|
|
124
|
+
- **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.
|
|
125
|
+
|
|
126
|
+
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.
|
|
127
|
+
|
|
128
|
+
- `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.
|
|
129
|
+
- `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.
|
|
130
|
+
- `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.
|
|
131
|
+
|
|
132
|
+
Limits:
|
|
133
|
+
- 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.
|
|
134
|
+
- 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.
|
|
135
|
+
- 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.
|
|
136
|
+
- `ingest.embed` is emitted only inside a run, a pipeline embed stage or an index insert/build.
|
|
137
|
+
- `ingest.parse` is a root span: `load_documents` runs before the pipeline. No `ingest.delete` span (LlamaIndex has no hook).
|
|
138
|
+
- Only llama-index-core 0.14.x is tested.
|
|
139
|
+
|
|
140
|
+
## Ingestion (Unstructured)
|
|
141
|
+
|
|
142
|
+
`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.
|
|
143
|
+
|
|
144
|
+
- `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.
|
|
145
|
+
- `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).
|
|
146
|
+
- 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.
|
|
147
|
+
- `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.
|
|
148
|
+
- 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.
|
|
149
|
+
- 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.
|
|
150
|
+
- 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`.
|
|
151
|
+
- Chunker version: `unstructured-<by_title|basic>-<10 hex>` of the effective options (library defaults resolved), the same for the direct call and the pipeline.
|
|
152
|
+
|
|
153
|
+
Limits:
|
|
154
|
+
- 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.
|
|
155
|
+
- Run the pipeline with `num_processes=1`: with more, the steps run in forked workers and their spans are lost.
|
|
156
|
+
- 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`.
|
|
157
|
+
- Not covered: the Unstructured API (`partition_by_api`, `chunk_by_api`) and `ingest.delete` (the pipeline does not propagate deletions).
|
|
158
|
+
- ctxflow does not change the library's own usage telemetry: set `DO_NOT_TRACK` / `SCARF_NO_ANALYTICS` yourself.
|
|
159
|
+
- 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).
|
|
160
|
+
|
|
161
|
+
## Ingestion (Docling)
|
|
162
|
+
|
|
163
|
+
`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`.
|
|
164
|
+
|
|
165
|
+
- 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.
|
|
166
|
+
- 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.
|
|
167
|
+
|
|
168
|
+
Limits:
|
|
169
|
+
- 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.
|
|
170
|
+
- 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.
|
|
171
|
+
- `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.
|
|
172
|
+
- 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).
|
|
173
|
+
|
|
174
|
+
Apache-2.0. Documentation: https://docs.ctxflow.sh. Release notes: `CHANGELOG.md` in the source distribution.
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
# ctxflow-otel
|
|
2
|
+
|
|
3
|
+
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.
|
|
4
|
+
|
|
5
|
+
## Quickstart
|
|
6
|
+
|
|
7
|
+
Requires Python 3.12 or later.
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
pip install ctxflow-otel # or ctxflow-otel[mcp] to propagate identity through MCP (mcp 1.x and 2.x)
|
|
11
|
+
export OTEL_SERVICE_NAME=my-agent
|
|
12
|
+
export OTEL_EXPORTER_OTLP_ENDPOINT=http://collector:4318 # a ctxflow collector, or ctxflow-core's OTLP endpoint
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
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):
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
ctxflow-otel check # or: python -m ctxflow_otel check; exit code 1 if a check failed
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
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:
|
|
22
|
+
|
|
23
|
+
```text
|
|
24
|
+
ok: identity: key targets project "Support Bot", environment "Development", last event 3 min ago
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
`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:
|
|
28
|
+
|
|
29
|
+
```text
|
|
30
|
+
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.
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
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.
|
|
34
|
+
|
|
35
|
+
Three integration levels:
|
|
36
|
+
|
|
37
|
+
```sh
|
|
38
|
+
# 0 lines of code
|
|
39
|
+
ctxflow-instrument python app.py
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
# 1 line: configures the SDK in process
|
|
44
|
+
import ctxflow_otel
|
|
45
|
+
|
|
46
|
+
ctxflow_otel.init() # idempotent; returns the TracerProvider
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
# Processors only: you own the TracerProvider
|
|
51
|
+
ctxflow_otel.attach(provider)
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Identity: `with ctxflow_otel.conversation("conv-42", user_id="u1", turn=3): ...` puts it on every span started inside.
|
|
55
|
+
|
|
56
|
+
`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.
|
|
57
|
+
|
|
58
|
+
## LlamaIndex agent, LLM and tool spans
|
|
59
|
+
|
|
60
|
+
`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.
|
|
61
|
+
|
|
62
|
+
- 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 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.
|
|
63
|
+
- 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.
|
|
64
|
+
- Opt out with `OTEL_PYTHON_DISABLED_INSTRUMENTATIONS=llama_index`.
|
|
65
|
+
- `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.
|
|
66
|
+
|
|
67
|
+
## Skipped instrumentors
|
|
68
|
+
|
|
69
|
+
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.
|
|
70
|
+
|
|
71
|
+
## MCP
|
|
72
|
+
|
|
73
|
+
`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()`.
|
|
74
|
+
|
|
75
|
+
- **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 (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 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).
|
|
76
|
+
- **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...).
|
|
77
|
+
- 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).
|
|
78
|
+
|
|
79
|
+
## Ingestion (LlamaIndex)
|
|
80
|
+
|
|
81
|
+
`pip install "ctxflow-otel[llamaindex]"` (llama-index-core 0.14.x). Chunks get the ctxflow source identity and `ingest.*` spans, with no manual spans.
|
|
82
|
+
|
|
83
|
+
- **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.
|
|
84
|
+
- **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`.
|
|
85
|
+
- **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.
|
|
86
|
+
|
|
87
|
+
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.
|
|
88
|
+
|
|
89
|
+
- `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.
|
|
90
|
+
- `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.
|
|
91
|
+
- `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.
|
|
92
|
+
|
|
93
|
+
Limits:
|
|
94
|
+
- 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.
|
|
95
|
+
- 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.
|
|
96
|
+
- 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.
|
|
97
|
+
- `ingest.embed` is emitted only inside a run, a pipeline embed stage or an index insert/build.
|
|
98
|
+
- `ingest.parse` is a root span: `load_documents` runs before the pipeline. No `ingest.delete` span (LlamaIndex has no hook).
|
|
99
|
+
- Only llama-index-core 0.14.x is tested.
|
|
100
|
+
|
|
101
|
+
## Ingestion (Unstructured)
|
|
102
|
+
|
|
103
|
+
`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.
|
|
104
|
+
|
|
105
|
+
- `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.
|
|
106
|
+
- `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).
|
|
107
|
+
- 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.
|
|
108
|
+
- `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.
|
|
109
|
+
- 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.
|
|
110
|
+
- 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.
|
|
111
|
+
- 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`.
|
|
112
|
+
- Chunker version: `unstructured-<by_title|basic>-<10 hex>` of the effective options (library defaults resolved), the same for the direct call and the pipeline.
|
|
113
|
+
|
|
114
|
+
Limits:
|
|
115
|
+
- 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.
|
|
116
|
+
- Run the pipeline with `num_processes=1`: with more, the steps run in forked workers and their spans are lost.
|
|
117
|
+
- 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`.
|
|
118
|
+
- Not covered: the Unstructured API (`partition_by_api`, `chunk_by_api`) and `ingest.delete` (the pipeline does not propagate deletions).
|
|
119
|
+
- ctxflow does not change the library's own usage telemetry: set `DO_NOT_TRACK` / `SCARF_NO_ANALYTICS` yourself.
|
|
120
|
+
- 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).
|
|
121
|
+
|
|
122
|
+
## Ingestion (Docling)
|
|
123
|
+
|
|
124
|
+
`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`.
|
|
125
|
+
|
|
126
|
+
- 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.
|
|
127
|
+
- 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.
|
|
128
|
+
|
|
129
|
+
Limits:
|
|
130
|
+
- 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.
|
|
131
|
+
- 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.
|
|
132
|
+
- `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.
|
|
133
|
+
- 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).
|
|
134
|
+
|
|
135
|
+
Apache-2.0. Documentation: https://docs.ctxflow.sh. Release notes: `CHANGELOG.md` in the source distribution.
|