audr-adapter-langfuse 0.1.0__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.
@@ -0,0 +1,7 @@
1
+ dist/
2
+ .venv/
3
+ __pycache__/
4
+ .pytest_cache/
5
+ .ruff_cache/
6
+ .mypy_cache/
7
+ .coverage
@@ -0,0 +1,16 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ## [0.1.0] - 2026-11-13
11
+
12
+ ### Added
13
+
14
+ - Initial release: an OpenTelemetry span processor that turns Langfuse generation,
15
+ embedding, tool and retriever observations into AUDR records for an existing
16
+ `audr.Client`.
@@ -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 2026 Chargebee, Inc. and the AUDR contributors
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,16 @@
1
+ Agent Usage Detail Record (AUDR)
2
+ Copyright 2026 Chargebee, Inc. and the AUDR contributors
3
+
4
+ This product includes software developed at Chargebee, Inc.
5
+ (https://www.chargebee.com/).
6
+
7
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
8
+ these files except in compliance with the License. You may obtain a copy of the
9
+ License at
10
+
11
+ http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ Unless required by applicable law or agreed to in writing, software distributed
14
+ under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
15
+ CONDITIONS OF ANY KIND, either express or implied. See the License for the
16
+ specific language governing permissions and limitations under the License.
@@ -0,0 +1,195 @@
1
+ Metadata-Version: 2.5
2
+ Name: audr-adapter-langfuse
3
+ Version: 0.1.0
4
+ Summary: Langfuse adapter for AUDR (experimental)
5
+ Project-URL: Homepage, https://openaudr.dev
6
+ Project-URL: Issues, https://github.com/openaudr/audr/issues
7
+ Project-URL: Source, https://github.com/openaudr/audr/tree/main/adapters/langfuse/python
8
+ Project-URL: Changelog, https://github.com/openaudr/audr/blob/main/adapters/langfuse/python/CHANGELOG.md
9
+ Project-URL: Specification, https://openaudr.dev/spec/v1.1.0/
10
+ Author-email: The AUDR contributors <audr@chargebee.com>
11
+ License-Expression: Apache-2.0
12
+ License-File: LICENSE
13
+ License-File: NOTICE
14
+ Keywords: adapter,audr,langfuse,llm,metering,opentelemetry
15
+ Classifier: Development Status :: 3 - Alpha
16
+ Classifier: Framework :: AsyncIO
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Programming Language :: Python :: 3.14
24
+ Classifier: Typing :: Typed
25
+ Requires-Python: >=3.11
26
+ Requires-Dist: audr<0.3,>=0.2
27
+ Requires-Dist: pydantic<3,>=2.10
28
+ Provides-Extra: runtime
29
+ Requires-Dist: langfuse<6,>=5.2; extra == 'runtime'
30
+ Requires-Dist: opentelemetry-sdk<2,>=1.45; extra == 'runtime'
31
+ Description-Content-Type: text/markdown
32
+
33
+ # audr-adapter-langfuse
34
+
35
+ [![PyPI](https://img.shields.io/pypi/v/audr-adapter-langfuse?include_prereleases)](https://pypi.org/project/audr-adapter-langfuse/)
36
+ [![Python versions](https://img.shields.io/pypi/pyversions/audr-adapter-langfuse)](https://pypi.org/project/audr-adapter-langfuse/)
37
+
38
+ The **AUDR span processor** for [Langfuse](https://langfuse.com) turns every generation,
39
+ embedding, tool and retriever observation recorded through the Langfuse Python SDK into one
40
+ [AUDR](https://openaudr.dev) record for an `audr.Client` your application owns. Because it
41
+ observes the Langfuse layer, one processor meters every integration that reports through
42
+ the SDK: the `langfuse.openai` drop-in, the LangChain `CallbackHandler`,
43
+ `@observe(as_type="generation")` and manual observations. It reads usage, cost,
44
+ identifiers and timings only: never observation input or output, prompts, completions or
45
+ error messages.
46
+
47
+ > **Status: alpha.** The record model follows AUDR specification 1.x; until this package
48
+ > reaches 1.0.0, a minor release may change the public API.
49
+
50
+ ## Setup
51
+
52
+ ```bash
53
+ pip install "audr-adapter-langfuse[runtime]"
54
+ ```
55
+
56
+ Requires Python 3.11 or later and `langfuse` 5.2 or later within 5.x, which the `runtime`
57
+ extra installs. The Langfuse SDK is built on OpenTelemetry; the adapter is an OpenTelemetry
58
+ `SpanProcessor` added to the same `TracerProvider` as Langfuse's own processor. Langfuse and
59
+ OpenTelemetry are imported when `LangfuseAudrProcessor` is first accessed, not when
60
+ `audr_adapter_langfuse` is imported.
61
+
62
+ ## Usage
63
+
64
+ Construct the processor on the running event loop that owns the `Client`, add it to a
65
+ `TracerProvider`, and hand that provider to the Langfuse client:
66
+
67
+ ```python
68
+ import asyncio
69
+
70
+ from audr import Attribution, Client, FileSink
71
+ from audr_adapter_langfuse import LangfuseAudrProcessor, LangfuseConfig
72
+ from langfuse import Langfuse, propagate_attributes
73
+ from opentelemetry.sdk.trace import TracerProvider
74
+
75
+
76
+ async def main() -> None:
77
+ async with Client(FileSink("audr.jsonl")) as client:
78
+ processor = LangfuseAudrProcessor(
79
+ client=client,
80
+ config=LangfuseConfig(
81
+ provider="openai",
82
+ attribution_defaults=Attribution(environment="production"),
83
+ ),
84
+ )
85
+ tracer_provider = TracerProvider()
86
+ tracer_provider.add_span_processor(processor)
87
+ langfuse = Langfuse(tracer_provider=tracer_provider) # keys from LANGFUSE_* variables
88
+ try:
89
+ with propagate_attributes(metadata={"audr_account_id": "acct_42"}):
90
+ with langfuse.start_as_current_observation(
91
+ name="answer", as_type="generation", model="gpt-4o-mini"
92
+ ) as generation:
93
+ generation.update(usage_details={"input": 120, "output": 40})
94
+ finally:
95
+ langfuse.shutdown()
96
+ await processor.drain(timeout=5)
97
+ processor.close()
98
+
99
+
100
+ asyncio.run(main())
101
+ ```
102
+
103
+ Leaving the `async with` block drains the client's queue and closes its sink. A runnable
104
+ version that keeps Langfuse offline is
105
+ [`examples/observe_generation.py`](https://github.com/openaudr/audr/blob/main/adapters/langfuse/python/examples/observe_generation.py).
106
+
107
+ > [!IMPORTANT]
108
+ > The processor meters only spans the provider records. Configure the `TracerProvider` you
109
+ > pass to Langfuse to sample every billed trace: Langfuse's own `sample_rate` does not apply
110
+ > to a provider you supply. A Langfuse client that is disabled, because its keys are missing
111
+ > or `tracing_enabled=False`, creates no spans, and no record is produced. Shut down in this
112
+ > order: `langfuse.shutdown()` (or `langfuse.flush()`), `await processor.drain()`,
113
+ > `processor.close()`, then the client; the
114
+ > [shutdown order](https://github.com/openaudr/audr/blob/main/adapters/langfuse/python/docs/reference.md#shutdown-order)
115
+ > explains each step.
116
+
117
+ ## Attribution
118
+
119
+ Attribution is read for each span from `audr_*` metadata keys, field by field: observation
120
+ metadata wins over that of the observations still open around it, nearest first, which wins
121
+ over trace metadata set with `propagate_attributes()`, which wins over
122
+ `langfuse.environment` (only when it is exactly an AUDR environment), which wins over
123
+ `LangfuseConfig.attribution_defaults`. `labels` merge by key. Langfuse experiment runs
124
+ (`sdk-experiment`) are attributed to `evaluation`. Flat keys keep each value under
125
+ Langfuse's 200-character limit for propagated metadata:
126
+
127
+ ```python
128
+ from langfuse import propagate_attributes
129
+
130
+ with propagate_attributes(
131
+ metadata={
132
+ "audr_environment": "production",
133
+ "audr_account_id": "acct_42",
134
+ "audr_subscription_id": "sub_7",
135
+ "audr_user_id": "u_8f14e45f", # pseudonymous, never an email or a name
136
+ "audr_feature_id": "support-chat", # selects the meter the usage is billed against
137
+ "audr_labels": {"team": "support"},
138
+ }
139
+ ):
140
+ pass # observations created here carry this attribution
141
+ ```
142
+
143
+ - A span with no `environment`, or a `production` span with no `account_id`, is skipped with
144
+ a warning rather than billed to a guess.
145
+ - Langfuse's own `user_id` is **not** copied to `attribution.user_id`: applications often
146
+ put an email there. Set `audr_user_id` to a pseudonymous id instead.
147
+
148
+ ## Records
149
+
150
+ | Langfuse observation type | `resource.operation` | `usage` |
151
+ | --- | --- | --- |
152
+ | `generation` | `generation` | `llm` tokens, `requests: 1` |
153
+ | `embedding` | `embedding` | `llm` tokens, `requests: 1` |
154
+ | `tool` | `tool_execution` | `tool`, `type: invocation`, `call_count: 1` |
155
+ | `retriever` | `retrieval` | `tool`, `type: retrieval`, `call_count: 1` |
156
+
157
+ Other types (`span`, `agent`, `chain`, `event`, `evaluator`, `guardrail`) and spans from
158
+ other OpenTelemetry instrumentation are not metered.
159
+
160
+ - **Identifiers.** `run.run_id` and `run.trace_id` are the OpenTelemetry trace id, and
161
+ `run.span_id` and `run.parent_span_id` the span ids, so every observation in one Langfuse
162
+ trace joins.
163
+ - **Usage.** Cache reads, cache writes and reasoning are counted apart from
164
+ `input_tokens` and `output_tokens`. Langfuse's exclusive buckets are folded back together,
165
+ so audio and modality counts stay in input and output; raw OpenAI usage, as the
166
+ `langfuse.openai` drop-in records it, and raw Anthropic usage are recognised too. The
167
+ [reference](https://github.com/openaudr/audr/blob/main/adapters/langfuse/python/docs/reference.md#tokens)
168
+ lists every key.
169
+ - **Cost.** A generation's or embedding's `cost_details` becomes `cost.total_cost` in USD
170
+ when the application or integration set it on the span. Langfuse's server-side inferred
171
+ cost is never seen, so most records carry no cost.
172
+ - **Provider.** Langfuse records no provider. The adapter takes `gen_ai.provider.name`,
173
+ then `gen_ai.system`, then the LangChain `ls_provider` metadata, then
174
+ `LangfuseConfig.provider`. A generation or embedding with none is skipped with a warning.
175
+ - **Failures.** A span with status `ERROR` or level `ERROR` carries
176
+ `run.error_code = LANGFUSE_OBSERVATION_ERROR`. Failed tool and retriever spans are always
177
+ recorded; a failed generation or embedding is recorded only when it reported usage or a
178
+ positive cost.
179
+
180
+ When one model call is recorded as a model span inside another, as with LangChain's
181
+ `ChatOpenAI` while the `langfuse.openai` drop-in is imported, only the inner span is
182
+ recorded, with the `audr_*` metadata of the spans around it. Running this adapter alongside
183
+ another AUDR adapter that observes the same calls, such as the LiteLLM adapter, records each
184
+ call twice.
185
+
186
+ ## Documentation
187
+
188
+ - [Reference](https://github.com/openaudr/audr/blob/main/adapters/langfuse/python/docs/reference.md): options, span metadata, record fields, shutdown order, diagnostics, operational bounds
189
+ - [Examples](https://github.com/openaudr/audr/tree/main/adapters/langfuse/python/examples): runnable offline, without Langfuse keys
190
+ - [Changelog](https://github.com/openaudr/audr/blob/main/adapters/langfuse/python/CHANGELOG.md)
191
+ - [AUDR specification](https://openaudr.dev), which defines every record field
192
+
193
+ ## License
194
+
195
+ Apache-2.0. Contributions follow [`CONTRIBUTING.md`](https://github.com/openaudr/audr/blob/main/CONTRIBUTING.md).
@@ -0,0 +1,163 @@
1
+ # audr-adapter-langfuse
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/audr-adapter-langfuse?include_prereleases)](https://pypi.org/project/audr-adapter-langfuse/)
4
+ [![Python versions](https://img.shields.io/pypi/pyversions/audr-adapter-langfuse)](https://pypi.org/project/audr-adapter-langfuse/)
5
+
6
+ The **AUDR span processor** for [Langfuse](https://langfuse.com) turns every generation,
7
+ embedding, tool and retriever observation recorded through the Langfuse Python SDK into one
8
+ [AUDR](https://openaudr.dev) record for an `audr.Client` your application owns. Because it
9
+ observes the Langfuse layer, one processor meters every integration that reports through
10
+ the SDK: the `langfuse.openai` drop-in, the LangChain `CallbackHandler`,
11
+ `@observe(as_type="generation")` and manual observations. It reads usage, cost,
12
+ identifiers and timings only: never observation input or output, prompts, completions or
13
+ error messages.
14
+
15
+ > **Status: alpha.** The record model follows AUDR specification 1.x; until this package
16
+ > reaches 1.0.0, a minor release may change the public API.
17
+
18
+ ## Setup
19
+
20
+ ```bash
21
+ pip install "audr-adapter-langfuse[runtime]"
22
+ ```
23
+
24
+ Requires Python 3.11 or later and `langfuse` 5.2 or later within 5.x, which the `runtime`
25
+ extra installs. The Langfuse SDK is built on OpenTelemetry; the adapter is an OpenTelemetry
26
+ `SpanProcessor` added to the same `TracerProvider` as Langfuse's own processor. Langfuse and
27
+ OpenTelemetry are imported when `LangfuseAudrProcessor` is first accessed, not when
28
+ `audr_adapter_langfuse` is imported.
29
+
30
+ ## Usage
31
+
32
+ Construct the processor on the running event loop that owns the `Client`, add it to a
33
+ `TracerProvider`, and hand that provider to the Langfuse client:
34
+
35
+ ```python
36
+ import asyncio
37
+
38
+ from audr import Attribution, Client, FileSink
39
+ from audr_adapter_langfuse import LangfuseAudrProcessor, LangfuseConfig
40
+ from langfuse import Langfuse, propagate_attributes
41
+ from opentelemetry.sdk.trace import TracerProvider
42
+
43
+
44
+ async def main() -> None:
45
+ async with Client(FileSink("audr.jsonl")) as client:
46
+ processor = LangfuseAudrProcessor(
47
+ client=client,
48
+ config=LangfuseConfig(
49
+ provider="openai",
50
+ attribution_defaults=Attribution(environment="production"),
51
+ ),
52
+ )
53
+ tracer_provider = TracerProvider()
54
+ tracer_provider.add_span_processor(processor)
55
+ langfuse = Langfuse(tracer_provider=tracer_provider) # keys from LANGFUSE_* variables
56
+ try:
57
+ with propagate_attributes(metadata={"audr_account_id": "acct_42"}):
58
+ with langfuse.start_as_current_observation(
59
+ name="answer", as_type="generation", model="gpt-4o-mini"
60
+ ) as generation:
61
+ generation.update(usage_details={"input": 120, "output": 40})
62
+ finally:
63
+ langfuse.shutdown()
64
+ await processor.drain(timeout=5)
65
+ processor.close()
66
+
67
+
68
+ asyncio.run(main())
69
+ ```
70
+
71
+ Leaving the `async with` block drains the client's queue and closes its sink. A runnable
72
+ version that keeps Langfuse offline is
73
+ [`examples/observe_generation.py`](https://github.com/openaudr/audr/blob/main/adapters/langfuse/python/examples/observe_generation.py).
74
+
75
+ > [!IMPORTANT]
76
+ > The processor meters only spans the provider records. Configure the `TracerProvider` you
77
+ > pass to Langfuse to sample every billed trace: Langfuse's own `sample_rate` does not apply
78
+ > to a provider you supply. A Langfuse client that is disabled, because its keys are missing
79
+ > or `tracing_enabled=False`, creates no spans, and no record is produced. Shut down in this
80
+ > order: `langfuse.shutdown()` (or `langfuse.flush()`), `await processor.drain()`,
81
+ > `processor.close()`, then the client; the
82
+ > [shutdown order](https://github.com/openaudr/audr/blob/main/adapters/langfuse/python/docs/reference.md#shutdown-order)
83
+ > explains each step.
84
+
85
+ ## Attribution
86
+
87
+ Attribution is read for each span from `audr_*` metadata keys, field by field: observation
88
+ metadata wins over that of the observations still open around it, nearest first, which wins
89
+ over trace metadata set with `propagate_attributes()`, which wins over
90
+ `langfuse.environment` (only when it is exactly an AUDR environment), which wins over
91
+ `LangfuseConfig.attribution_defaults`. `labels` merge by key. Langfuse experiment runs
92
+ (`sdk-experiment`) are attributed to `evaluation`. Flat keys keep each value under
93
+ Langfuse's 200-character limit for propagated metadata:
94
+
95
+ ```python
96
+ from langfuse import propagate_attributes
97
+
98
+ with propagate_attributes(
99
+ metadata={
100
+ "audr_environment": "production",
101
+ "audr_account_id": "acct_42",
102
+ "audr_subscription_id": "sub_7",
103
+ "audr_user_id": "u_8f14e45f", # pseudonymous, never an email or a name
104
+ "audr_feature_id": "support-chat", # selects the meter the usage is billed against
105
+ "audr_labels": {"team": "support"},
106
+ }
107
+ ):
108
+ pass # observations created here carry this attribution
109
+ ```
110
+
111
+ - A span with no `environment`, or a `production` span with no `account_id`, is skipped with
112
+ a warning rather than billed to a guess.
113
+ - Langfuse's own `user_id` is **not** copied to `attribution.user_id`: applications often
114
+ put an email there. Set `audr_user_id` to a pseudonymous id instead.
115
+
116
+ ## Records
117
+
118
+ | Langfuse observation type | `resource.operation` | `usage` |
119
+ | --- | --- | --- |
120
+ | `generation` | `generation` | `llm` tokens, `requests: 1` |
121
+ | `embedding` | `embedding` | `llm` tokens, `requests: 1` |
122
+ | `tool` | `tool_execution` | `tool`, `type: invocation`, `call_count: 1` |
123
+ | `retriever` | `retrieval` | `tool`, `type: retrieval`, `call_count: 1` |
124
+
125
+ Other types (`span`, `agent`, `chain`, `event`, `evaluator`, `guardrail`) and spans from
126
+ other OpenTelemetry instrumentation are not metered.
127
+
128
+ - **Identifiers.** `run.run_id` and `run.trace_id` are the OpenTelemetry trace id, and
129
+ `run.span_id` and `run.parent_span_id` the span ids, so every observation in one Langfuse
130
+ trace joins.
131
+ - **Usage.** Cache reads, cache writes and reasoning are counted apart from
132
+ `input_tokens` and `output_tokens`. Langfuse's exclusive buckets are folded back together,
133
+ so audio and modality counts stay in input and output; raw OpenAI usage, as the
134
+ `langfuse.openai` drop-in records it, and raw Anthropic usage are recognised too. The
135
+ [reference](https://github.com/openaudr/audr/blob/main/adapters/langfuse/python/docs/reference.md#tokens)
136
+ lists every key.
137
+ - **Cost.** A generation's or embedding's `cost_details` becomes `cost.total_cost` in USD
138
+ when the application or integration set it on the span. Langfuse's server-side inferred
139
+ cost is never seen, so most records carry no cost.
140
+ - **Provider.** Langfuse records no provider. The adapter takes `gen_ai.provider.name`,
141
+ then `gen_ai.system`, then the LangChain `ls_provider` metadata, then
142
+ `LangfuseConfig.provider`. A generation or embedding with none is skipped with a warning.
143
+ - **Failures.** A span with status `ERROR` or level `ERROR` carries
144
+ `run.error_code = LANGFUSE_OBSERVATION_ERROR`. Failed tool and retriever spans are always
145
+ recorded; a failed generation or embedding is recorded only when it reported usage or a
146
+ positive cost.
147
+
148
+ When one model call is recorded as a model span inside another, as with LangChain's
149
+ `ChatOpenAI` while the `langfuse.openai` drop-in is imported, only the inner span is
150
+ recorded, with the `audr_*` metadata of the spans around it. Running this adapter alongside
151
+ another AUDR adapter that observes the same calls, such as the LiteLLM adapter, records each
152
+ call twice.
153
+
154
+ ## Documentation
155
+
156
+ - [Reference](https://github.com/openaudr/audr/blob/main/adapters/langfuse/python/docs/reference.md): options, span metadata, record fields, shutdown order, diagnostics, operational bounds
157
+ - [Examples](https://github.com/openaudr/audr/tree/main/adapters/langfuse/python/examples): runnable offline, without Langfuse keys
158
+ - [Changelog](https://github.com/openaudr/audr/blob/main/adapters/langfuse/python/CHANGELOG.md)
159
+ - [AUDR specification](https://openaudr.dev), which defines every record field
160
+
161
+ ## License
162
+
163
+ Apache-2.0. Contributions follow [`CONTRIBUTING.md`](https://github.com/openaudr/audr/blob/main/CONTRIBUTING.md).