agentforge-langfuse 0.2.3__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.
- agentforge_langfuse-0.2.3/.gitignore +49 -0
- agentforge_langfuse-0.2.3/LICENSE +202 -0
- agentforge_langfuse-0.2.3/PKG-INFO +75 -0
- agentforge_langfuse-0.2.3/README.md +50 -0
- agentforge_langfuse-0.2.3/pyproject.toml +61 -0
- agentforge_langfuse-0.2.3/src/agentforge_langfuse/__init__.py +8 -0
- agentforge_langfuse-0.2.3/src/agentforge_langfuse/_inmem_runner.py +78 -0
- agentforge_langfuse-0.2.3/src/agentforge_langfuse/_runner.py +120 -0
- agentforge_langfuse-0.2.3/src/agentforge_langfuse/hook.py +199 -0
- agentforge_langfuse-0.2.3/src/agentforge_langfuse/py.typed +0 -0
- agentforge_langfuse-0.2.3/tests/integration/test_langfuse_live.py +53 -0
- agentforge_langfuse-0.2.3/tests/unit/test_langfuse_hook.py +156 -0
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# Python
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*$py.class
|
|
5
|
+
*.so
|
|
6
|
+
|
|
7
|
+
# Distribution / packaging
|
|
8
|
+
.Python
|
|
9
|
+
build/
|
|
10
|
+
dist/
|
|
11
|
+
*.egg-info/
|
|
12
|
+
*.egg
|
|
13
|
+
wheels/
|
|
14
|
+
sdist/
|
|
15
|
+
share/python-wheels/
|
|
16
|
+
|
|
17
|
+
# uv
|
|
18
|
+
.venv/
|
|
19
|
+
uv-cache/
|
|
20
|
+
|
|
21
|
+
# Testing
|
|
22
|
+
.pytest_cache/
|
|
23
|
+
.coverage
|
|
24
|
+
.coverage.*
|
|
25
|
+
htmlcov/
|
|
26
|
+
coverage.xml
|
|
27
|
+
.tox/
|
|
28
|
+
.mypy_cache/
|
|
29
|
+
.ruff_cache/
|
|
30
|
+
.hypothesis/
|
|
31
|
+
|
|
32
|
+
# Environment
|
|
33
|
+
.env
|
|
34
|
+
.envrc
|
|
35
|
+
|
|
36
|
+
# Editors
|
|
37
|
+
.vscode/
|
|
38
|
+
.idea/
|
|
39
|
+
*.swp
|
|
40
|
+
*.swo
|
|
41
|
+
*~
|
|
42
|
+
|
|
43
|
+
# OS
|
|
44
|
+
.DS_Store
|
|
45
|
+
Thumbs.db
|
|
46
|
+
|
|
47
|
+
# Project-local
|
|
48
|
+
*.local
|
|
49
|
+
.agentforge-state/.session-cache
|
|
@@ -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,75 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: agentforge-langfuse
|
|
3
|
+
Version: 0.2.3
|
|
4
|
+
Summary: Langfuse trace dashboard hook for AgentForge
|
|
5
|
+
Project-URL: Homepage, https://github.com/Scaffoldic/agentforge-py
|
|
6
|
+
Project-URL: Repository, https://github.com/Scaffoldic/agentforge-py
|
|
7
|
+
Project-URL: Changelog, https://github.com/Scaffoldic/agentforge-py/blob/main/CHANGELOG.md
|
|
8
|
+
Project-URL: Issues, https://github.com/Scaffoldic/agentforge-py/issues
|
|
9
|
+
Author: The AgentForge Authors
|
|
10
|
+
License-Expression: Apache-2.0
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: agent,ai,langfuse,llm,observability
|
|
13
|
+
Classifier: Development Status :: 2 - Pre-Alpha
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Topic :: System :: Monitoring
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Python: >=3.13
|
|
21
|
+
Requires-Dist: agentforge-core~=0.2.3
|
|
22
|
+
Provides-Extra: langfuse
|
|
23
|
+
Requires-Dist: langfuse>=2.0; extra == 'langfuse'
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# agentforge-langfuse
|
|
27
|
+
|
|
28
|
+
Langfuse trace dashboard hook for the AgentForge framework.
|
|
29
|
+
|
|
30
|
+
Implements the `StepHook` + `FinishHook` contracts and
|
|
31
|
+
registers as `agentforge.hooks:langfuse`.
|
|
32
|
+
|
|
33
|
+
## Installation
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install agentforge-langfuse[langfuse]
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
The `[langfuse]` extra pulls in the `langfuse>=2.0` SDK.
|
|
40
|
+
Without it, the production factory raises `ModuleError` with
|
|
41
|
+
pip remediation.
|
|
42
|
+
|
|
43
|
+
## Usage
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
from agentforge import Agent
|
|
47
|
+
from agentforge_langfuse import LangfuseHook
|
|
48
|
+
|
|
49
|
+
hook = LangfuseHook.from_config(
|
|
50
|
+
public_key="pk-lf-...",
|
|
51
|
+
secret_key="sk-lf-...",
|
|
52
|
+
host="https://cloud.langfuse.com",
|
|
53
|
+
trace_name_prefix="agentforge.pr-reviewer",
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
agent = Agent(
|
|
57
|
+
model="bedrock:...",
|
|
58
|
+
on_step=hook,
|
|
59
|
+
on_finish=hook,
|
|
60
|
+
)
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Trace shape
|
|
64
|
+
|
|
65
|
+
- One **trace** per run, opened on the first step (keyed by
|
|
66
|
+
`run_id`).
|
|
67
|
+
- One **span** per step (`name = "step:<kind>"`).
|
|
68
|
+
- A **nested span** per `tool_call` (`name = "tool:<name>"`).
|
|
69
|
+
- Two **scores** on finish: `cost_usd` and `duration_ms`.
|
|
70
|
+
- The trace is `flush()`-ed at finish so it lands in the
|
|
71
|
+
dashboard without waiting for the SDK's batch interval.
|
|
72
|
+
|
|
73
|
+
## License
|
|
74
|
+
|
|
75
|
+
Apache-2.0.
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# agentforge-langfuse
|
|
2
|
+
|
|
3
|
+
Langfuse trace dashboard hook for the AgentForge framework.
|
|
4
|
+
|
|
5
|
+
Implements the `StepHook` + `FinishHook` contracts and
|
|
6
|
+
registers as `agentforge.hooks:langfuse`.
|
|
7
|
+
|
|
8
|
+
## Installation
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
pip install agentforge-langfuse[langfuse]
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
The `[langfuse]` extra pulls in the `langfuse>=2.0` SDK.
|
|
15
|
+
Without it, the production factory raises `ModuleError` with
|
|
16
|
+
pip remediation.
|
|
17
|
+
|
|
18
|
+
## Usage
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
from agentforge import Agent
|
|
22
|
+
from agentforge_langfuse import LangfuseHook
|
|
23
|
+
|
|
24
|
+
hook = LangfuseHook.from_config(
|
|
25
|
+
public_key="pk-lf-...",
|
|
26
|
+
secret_key="sk-lf-...",
|
|
27
|
+
host="https://cloud.langfuse.com",
|
|
28
|
+
trace_name_prefix="agentforge.pr-reviewer",
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
agent = Agent(
|
|
32
|
+
model="bedrock:...",
|
|
33
|
+
on_step=hook,
|
|
34
|
+
on_finish=hook,
|
|
35
|
+
)
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Trace shape
|
|
39
|
+
|
|
40
|
+
- One **trace** per run, opened on the first step (keyed by
|
|
41
|
+
`run_id`).
|
|
42
|
+
- One **span** per step (`name = "step:<kind>"`).
|
|
43
|
+
- A **nested span** per `tool_call` (`name = "tool:<name>"`).
|
|
44
|
+
- Two **scores** on finish: `cost_usd` and `duration_ms`.
|
|
45
|
+
- The trace is `flush()`-ed at finish so it lands in the
|
|
46
|
+
dashboard without waiting for the SDK's batch interval.
|
|
47
|
+
|
|
48
|
+
## License
|
|
49
|
+
|
|
50
|
+
Apache-2.0.
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# agentforge-langfuse — Langfuse LLM trace dashboard for AgentForge.
|
|
2
|
+
#
|
|
3
|
+
# Tier-3 module per ADR-0003. Installs as `agentforge.hooks:langfuse`
|
|
4
|
+
# and emits one trace per agent run, one span per step, and a score
|
|
5
|
+
# per run. The production runner wraps `langfuse.Langfuse` under
|
|
6
|
+
# `# pragma: no cover`; unit tests inject a fake runner.
|
|
7
|
+
|
|
8
|
+
[project]
|
|
9
|
+
name = "agentforge-langfuse"
|
|
10
|
+
version = "0.2.3"
|
|
11
|
+
description = "Langfuse trace dashboard hook for AgentForge"
|
|
12
|
+
readme = "README.md"
|
|
13
|
+
requires-python = ">=3.13"
|
|
14
|
+
license = "Apache-2.0"
|
|
15
|
+
license-files = ["LICENSE"]
|
|
16
|
+
authors = [
|
|
17
|
+
{name = "The AgentForge Authors"},
|
|
18
|
+
]
|
|
19
|
+
keywords = ["ai", "agent", "observability", "langfuse", "llm"]
|
|
20
|
+
classifiers = [
|
|
21
|
+
"Development Status :: 2 - Pre-Alpha",
|
|
22
|
+
"Intended Audience :: Developers",
|
|
23
|
+
"License :: OSI Approved :: Apache Software License",
|
|
24
|
+
"Programming Language :: Python :: 3",
|
|
25
|
+
"Programming Language :: Python :: 3.13",
|
|
26
|
+
"Topic :: System :: Monitoring",
|
|
27
|
+
"Typing :: Typed",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
dependencies = [
|
|
31
|
+
"agentforge-core ~= 0.2.3",
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
[project.optional-dependencies]
|
|
35
|
+
# Required to use the production runner. Bare install works fine for
|
|
36
|
+
# tests that inject `FakeLangfuseRunner`.
|
|
37
|
+
langfuse = ["langfuse>=2.0"]
|
|
38
|
+
|
|
39
|
+
[project.urls]
|
|
40
|
+
Homepage = "https://github.com/Scaffoldic/agentforge-py"
|
|
41
|
+
Repository = "https://github.com/Scaffoldic/agentforge-py"
|
|
42
|
+
Changelog = "https://github.com/Scaffoldic/agentforge-py/blob/main/CHANGELOG.md"
|
|
43
|
+
Issues = "https://github.com/Scaffoldic/agentforge-py/issues"
|
|
44
|
+
|
|
45
|
+
[project.entry-points."agentforge.hooks"]
|
|
46
|
+
langfuse = "agentforge_langfuse:LangfuseHook"
|
|
47
|
+
|
|
48
|
+
[build-system]
|
|
49
|
+
requires = ["hatchling>=1.27"]
|
|
50
|
+
build-backend = "hatchling.build"
|
|
51
|
+
|
|
52
|
+
[tool.hatch.build.targets.wheel]
|
|
53
|
+
packages = ["src/agentforge_langfuse"]
|
|
54
|
+
|
|
55
|
+
[tool.hatch.build.targets.sdist]
|
|
56
|
+
include = [
|
|
57
|
+
"src/agentforge_langfuse",
|
|
58
|
+
"tests",
|
|
59
|
+
"README.md",
|
|
60
|
+
"LICENSE",
|
|
61
|
+
]
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""`agentforge-langfuse` — Langfuse trace dashboard for AgentForge."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from agentforge_langfuse._runner import LangfuseRunner
|
|
6
|
+
from agentforge_langfuse.hook import LangfuseHook
|
|
7
|
+
|
|
8
|
+
__all__ = ["LangfuseHook", "LangfuseRunner"]
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""In-memory `LangfuseRunner` for unit tests + downstream integration.
|
|
2
|
+
|
|
3
|
+
Records calls as tagged tuples on the instance, keyed by
|
|
4
|
+
``run_id`` so tests can assert against the full trace shape.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class _TraceRecord:
|
|
15
|
+
name: str
|
|
16
|
+
run_id: str
|
|
17
|
+
metadata: dict[str, Any] = field(default_factory=dict)
|
|
18
|
+
spans: list[dict[str, Any]] = field(default_factory=list)
|
|
19
|
+
scores: list[dict[str, Any]] = field(default_factory=list)
|
|
20
|
+
flushed: bool = False
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class FakeLangfuseRunner:
|
|
24
|
+
"""In-memory recorder of every Langfuse call."""
|
|
25
|
+
|
|
26
|
+
def __init__(self) -> None:
|
|
27
|
+
self.traces: dict[str, _TraceRecord] = {}
|
|
28
|
+
self.closed = False
|
|
29
|
+
|
|
30
|
+
def open_trace(
|
|
31
|
+
self,
|
|
32
|
+
*,
|
|
33
|
+
name: str,
|
|
34
|
+
run_id: str,
|
|
35
|
+
metadata: dict[str, Any] | None = None,
|
|
36
|
+
) -> str:
|
|
37
|
+
self.traces[run_id] = _TraceRecord(
|
|
38
|
+
name=name,
|
|
39
|
+
run_id=run_id,
|
|
40
|
+
metadata=dict(metadata or {}),
|
|
41
|
+
)
|
|
42
|
+
return run_id
|
|
43
|
+
|
|
44
|
+
def add_span(
|
|
45
|
+
self,
|
|
46
|
+
*,
|
|
47
|
+
trace_id: str,
|
|
48
|
+
name: str,
|
|
49
|
+
metadata: dict[str, Any] | None = None,
|
|
50
|
+
) -> None:
|
|
51
|
+
rec = self.traces.get(trace_id)
|
|
52
|
+
if rec is None:
|
|
53
|
+
return
|
|
54
|
+
rec.spans.append({"name": name, "metadata": dict(metadata or {})})
|
|
55
|
+
|
|
56
|
+
def add_score(
|
|
57
|
+
self,
|
|
58
|
+
*,
|
|
59
|
+
trace_id: str,
|
|
60
|
+
name: str,
|
|
61
|
+
value: float,
|
|
62
|
+
comment: str | None = None,
|
|
63
|
+
) -> None:
|
|
64
|
+
rec = self.traces.get(trace_id)
|
|
65
|
+
if rec is None:
|
|
66
|
+
return
|
|
67
|
+
rec.scores.append({"name": name, "value": float(value), "comment": comment})
|
|
68
|
+
|
|
69
|
+
def flush(self, *, trace_id: str) -> None:
|
|
70
|
+
rec = self.traces.get(trace_id)
|
|
71
|
+
if rec is not None:
|
|
72
|
+
rec.flushed = True
|
|
73
|
+
|
|
74
|
+
def close(self) -> None:
|
|
75
|
+
self.closed = True
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
__all__ = ["FakeLangfuseRunner"]
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""Langfuse runner Protocol + production SDK wrapper.
|
|
2
|
+
|
|
3
|
+
The Protocol abstracts the calls `LangfuseHook` makes so unit
|
|
4
|
+
tests don't need the SDK in the dev venv. Production
|
|
5
|
+
`_LangfuseClientRunner` wraps a `langfuse.Langfuse` client
|
|
6
|
+
under `# pragma: no cover`.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import Any, Protocol
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class LangfuseRunner(Protocol):
|
|
15
|
+
"""Lifecycle Protocol for Langfuse trace + span emissions."""
|
|
16
|
+
|
|
17
|
+
def open_trace(
|
|
18
|
+
self,
|
|
19
|
+
*,
|
|
20
|
+
name: str,
|
|
21
|
+
run_id: str,
|
|
22
|
+
metadata: dict[str, Any] | None = None,
|
|
23
|
+
) -> str: # pragma: no cover
|
|
24
|
+
"""Open a trace and return the trace_id used by subsequent calls."""
|
|
25
|
+
...
|
|
26
|
+
|
|
27
|
+
def add_span(
|
|
28
|
+
self,
|
|
29
|
+
*,
|
|
30
|
+
trace_id: str,
|
|
31
|
+
name: str,
|
|
32
|
+
metadata: dict[str, Any] | None = None,
|
|
33
|
+
) -> None: # pragma: no cover
|
|
34
|
+
"""Add a span under the named trace."""
|
|
35
|
+
...
|
|
36
|
+
|
|
37
|
+
def add_score(
|
|
38
|
+
self,
|
|
39
|
+
*,
|
|
40
|
+
trace_id: str,
|
|
41
|
+
name: str,
|
|
42
|
+
value: float,
|
|
43
|
+
comment: str | None = None,
|
|
44
|
+
) -> None: # pragma: no cover
|
|
45
|
+
"""Score the trace on a named dimension (cost, duration, ...)."""
|
|
46
|
+
...
|
|
47
|
+
|
|
48
|
+
def flush(self, *, trace_id: str) -> None: # pragma: no cover
|
|
49
|
+
"""Force the SDK's batch buffer to drain for ``trace_id``."""
|
|
50
|
+
...
|
|
51
|
+
|
|
52
|
+
def close(self) -> None: # pragma: no cover
|
|
53
|
+
"""Release the underlying SDK client."""
|
|
54
|
+
...
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class _LangfuseClientRunner: # pragma: no cover — exercised only with `-m live`.
|
|
58
|
+
"""Production runner wrapping ``langfuse.Langfuse``."""
|
|
59
|
+
|
|
60
|
+
def __init__(self, client: Any) -> None:
|
|
61
|
+
self._client = client
|
|
62
|
+
# Langfuse SDK creates trace handles lazily; we cache the
|
|
63
|
+
# objects keyed by our caller-side trace_id (== run_id) so
|
|
64
|
+
# subsequent add_span / add_score calls can target them.
|
|
65
|
+
self._traces: dict[str, Any] = {}
|
|
66
|
+
|
|
67
|
+
def open_trace(
|
|
68
|
+
self,
|
|
69
|
+
*,
|
|
70
|
+
name: str,
|
|
71
|
+
run_id: str,
|
|
72
|
+
metadata: dict[str, Any] | None = None,
|
|
73
|
+
) -> str:
|
|
74
|
+
trace = self._client.trace(
|
|
75
|
+
name=name,
|
|
76
|
+
id=run_id,
|
|
77
|
+
metadata=dict(metadata or {}),
|
|
78
|
+
)
|
|
79
|
+
self._traces[run_id] = trace
|
|
80
|
+
return run_id
|
|
81
|
+
|
|
82
|
+
def add_span(
|
|
83
|
+
self,
|
|
84
|
+
*,
|
|
85
|
+
trace_id: str,
|
|
86
|
+
name: str,
|
|
87
|
+
metadata: dict[str, Any] | None = None,
|
|
88
|
+
) -> None:
|
|
89
|
+
trace = self._traces.get(trace_id)
|
|
90
|
+
if trace is None:
|
|
91
|
+
return
|
|
92
|
+
trace.span(name=name, metadata=dict(metadata or {}))
|
|
93
|
+
|
|
94
|
+
def add_score(
|
|
95
|
+
self,
|
|
96
|
+
*,
|
|
97
|
+
trace_id: str,
|
|
98
|
+
name: str,
|
|
99
|
+
value: float,
|
|
100
|
+
comment: str | None = None,
|
|
101
|
+
) -> None:
|
|
102
|
+
trace = self._traces.get(trace_id)
|
|
103
|
+
if trace is None:
|
|
104
|
+
return
|
|
105
|
+
trace.score(name=name, value=value, comment=comment)
|
|
106
|
+
|
|
107
|
+
def flush(self, *, trace_id: str) -> None:
|
|
108
|
+
flush = getattr(self._client, "flush", None)
|
|
109
|
+
if callable(flush):
|
|
110
|
+
flush()
|
|
111
|
+
# Drop the local handle once flushed.
|
|
112
|
+
self._traces.pop(trace_id, None)
|
|
113
|
+
|
|
114
|
+
def close(self) -> None:
|
|
115
|
+
shutdown = getattr(self._client, "shutdown", None)
|
|
116
|
+
if callable(shutdown):
|
|
117
|
+
shutdown()
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
__all__ = ["LangfuseRunner"]
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""`LangfuseHook` — Langfuse trace dashboard emitter.
|
|
2
|
+
|
|
3
|
+
Implements the `StepHook + FinishHook` callable contract via
|
|
4
|
+
`__call__(payload)` dispatch (mirrors `OpenTelemetryHook`).
|
|
5
|
+
|
|
6
|
+
Trace shape:
|
|
7
|
+
|
|
8
|
+
- One trace per run, opened on the first step seen, keyed by
|
|
9
|
+
``run_id``. ``Step`` doesn't carry the run_id directly, so
|
|
10
|
+
the hook reads it from `agentforge_core.runtime.current_run`
|
|
11
|
+
(set by `Agent.run`'s `RunContext`).
|
|
12
|
+
- One span per step, named ``"step:<kind>"``, carrying the
|
|
13
|
+
step's iteration, duration, and cost as metadata.
|
|
14
|
+
- A nested span per ``step.tool_call``, named
|
|
15
|
+
``"tool:<name>"`` with the redacted argument shape.
|
|
16
|
+
- Two scores at finish: ``"cost_usd"`` and ``"duration_ms"``.
|
|
17
|
+
- A `flush` call at finish so the trace lands in the
|
|
18
|
+
dashboard without waiting for the SDK's batch interval.
|
|
19
|
+
|
|
20
|
+
Construction is two paths:
|
|
21
|
+
|
|
22
|
+
- ``LangfuseHook(runner=<LangfuseRunner>, ...)`` — direct
|
|
23
|
+
injection.
|
|
24
|
+
- ``LangfuseHook.from_config(public_key=..., secret_key=...,
|
|
25
|
+
host=...)`` — builds the production runner by lazy-importing
|
|
26
|
+
``langfuse``.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
from typing import TYPE_CHECKING, Any
|
|
32
|
+
|
|
33
|
+
from agentforge_core.production.exceptions import ModuleError
|
|
34
|
+
from agentforge_core.production.run_context import current_run
|
|
35
|
+
from agentforge_core.values.state import RunResult, Step
|
|
36
|
+
|
|
37
|
+
if TYPE_CHECKING:
|
|
38
|
+
from agentforge_langfuse._runner import LangfuseRunner
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
_DEFAULT_REDACT = ("api_key", "password", "secret", "token", "authorization")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class LangfuseHook:
|
|
45
|
+
"""Langfuse-backed observability hook."""
|
|
46
|
+
|
|
47
|
+
def __init__(
|
|
48
|
+
self,
|
|
49
|
+
*,
|
|
50
|
+
runner: LangfuseRunner,
|
|
51
|
+
trace_name_prefix: str = "agentforge",
|
|
52
|
+
redact_fields: tuple[str, ...] | None = None,
|
|
53
|
+
) -> None:
|
|
54
|
+
if not trace_name_prefix:
|
|
55
|
+
msg = "trace_name_prefix is required"
|
|
56
|
+
raise ValueError(msg)
|
|
57
|
+
self._runner = runner
|
|
58
|
+
self._trace_name_prefix = trace_name_prefix.rstrip(".")
|
|
59
|
+
self._redact_fields = tuple(
|
|
60
|
+
f.lower() for f in (redact_fields if redact_fields is not None else _DEFAULT_REDACT)
|
|
61
|
+
)
|
|
62
|
+
# Track which run_ids we've already opened a trace for.
|
|
63
|
+
self._opened: set[str] = set()
|
|
64
|
+
|
|
65
|
+
@classmethod
|
|
66
|
+
def from_config(
|
|
67
|
+
cls,
|
|
68
|
+
*,
|
|
69
|
+
public_key: str,
|
|
70
|
+
secret_key: str,
|
|
71
|
+
host: str | None = None,
|
|
72
|
+
trace_name_prefix: str = "agentforge",
|
|
73
|
+
redact_fields: tuple[str, ...] | None = None,
|
|
74
|
+
) -> LangfuseHook: # pragma: no cover — exercised only with `-m live`.
|
|
75
|
+
"""Build a `LangfuseHook` backed by a real `langfuse.Langfuse` client."""
|
|
76
|
+
runner = _build_langfuse_runner(
|
|
77
|
+
public_key=public_key,
|
|
78
|
+
secret_key=secret_key,
|
|
79
|
+
host=host,
|
|
80
|
+
)
|
|
81
|
+
return cls(
|
|
82
|
+
runner=runner,
|
|
83
|
+
trace_name_prefix=trace_name_prefix,
|
|
84
|
+
redact_fields=redact_fields,
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
@property
|
|
88
|
+
def redact_fields(self) -> tuple[str, ...]:
|
|
89
|
+
return self._redact_fields
|
|
90
|
+
|
|
91
|
+
def __call__(self, payload: Step | RunResult) -> None:
|
|
92
|
+
"""Hook entry point — dispatches on payload type."""
|
|
93
|
+
if isinstance(payload, Step):
|
|
94
|
+
self._on_step(payload)
|
|
95
|
+
else:
|
|
96
|
+
self._on_finish(payload)
|
|
97
|
+
|
|
98
|
+
def _on_step(self, step: Step) -> None:
|
|
99
|
+
run_id = self._current_run_id()
|
|
100
|
+
if run_id is None:
|
|
101
|
+
return # No run context bound — caller fired the hook outside Agent.run.
|
|
102
|
+
if run_id not in self._opened:
|
|
103
|
+
self._runner.open_trace(
|
|
104
|
+
name=f"{self._trace_name_prefix}.run",
|
|
105
|
+
run_id=run_id,
|
|
106
|
+
metadata={"agentforge.run_id": run_id},
|
|
107
|
+
)
|
|
108
|
+
self._opened.add(run_id)
|
|
109
|
+
self._runner.add_span(
|
|
110
|
+
trace_id=run_id,
|
|
111
|
+
name=f"step:{step.kind}",
|
|
112
|
+
metadata={
|
|
113
|
+
"iteration": step.iteration,
|
|
114
|
+
"duration_ms": step.duration_ms,
|
|
115
|
+
"cost_usd": step.cost_usd,
|
|
116
|
+
"tokens_in": step.tokens_in,
|
|
117
|
+
"tokens_out": step.tokens_out,
|
|
118
|
+
},
|
|
119
|
+
)
|
|
120
|
+
if step.tool_call is not None:
|
|
121
|
+
self._runner.add_span(
|
|
122
|
+
trace_id=run_id,
|
|
123
|
+
name=f"tool:{step.tool_call.name}",
|
|
124
|
+
metadata={"args": self._redact(dict(step.tool_call.arguments))},
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
def _on_finish(self, result: RunResult) -> None:
|
|
128
|
+
run_id = result.run_id
|
|
129
|
+
if run_id not in self._opened:
|
|
130
|
+
# Hook never saw a step (zero-step run); open the trace
|
|
131
|
+
# synthetically so the score has a home.
|
|
132
|
+
self._runner.open_trace(
|
|
133
|
+
name=f"{self._trace_name_prefix}.run",
|
|
134
|
+
run_id=run_id,
|
|
135
|
+
metadata={"agentforge.run_id": run_id, "synthetic": True},
|
|
136
|
+
)
|
|
137
|
+
self._opened.add(run_id)
|
|
138
|
+
self._runner.add_score(
|
|
139
|
+
trace_id=run_id,
|
|
140
|
+
name="cost_usd",
|
|
141
|
+
value=float(result.cost_usd),
|
|
142
|
+
comment=f"finish_reason={result.finish_reason}",
|
|
143
|
+
)
|
|
144
|
+
self._runner.add_score(
|
|
145
|
+
trace_id=run_id,
|
|
146
|
+
name="duration_ms",
|
|
147
|
+
value=float(result.duration_ms),
|
|
148
|
+
)
|
|
149
|
+
self._runner.flush(trace_id=run_id)
|
|
150
|
+
self._opened.discard(run_id)
|
|
151
|
+
|
|
152
|
+
def close(self) -> None:
|
|
153
|
+
"""Release the underlying runner."""
|
|
154
|
+
self._runner.close()
|
|
155
|
+
|
|
156
|
+
@staticmethod
|
|
157
|
+
def _current_run_id() -> str | None:
|
|
158
|
+
try:
|
|
159
|
+
ctx = current_run()
|
|
160
|
+
except RuntimeError:
|
|
161
|
+
return None
|
|
162
|
+
return ctx.run_id
|
|
163
|
+
|
|
164
|
+
def _redact(self, args: dict[str, Any]) -> dict[str, Any]:
|
|
165
|
+
out: dict[str, Any] = {}
|
|
166
|
+
for key, value in args.items():
|
|
167
|
+
if any(token in key.lower() for token in self._redact_fields):
|
|
168
|
+
out[key] = "<redacted>"
|
|
169
|
+
else:
|
|
170
|
+
out[key] = value
|
|
171
|
+
return out
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _build_langfuse_runner( # pragma: no cover — exercised only with `-m live`.
|
|
175
|
+
*,
|
|
176
|
+
public_key: str,
|
|
177
|
+
secret_key: str,
|
|
178
|
+
host: str | None,
|
|
179
|
+
) -> LangfuseRunner:
|
|
180
|
+
"""Lazy-import `langfuse` and build a production runner."""
|
|
181
|
+
try:
|
|
182
|
+
from langfuse import Langfuse # noqa: PLC0415
|
|
183
|
+
except ImportError as exc: # pragma: no cover — exercised only when SDK is missing
|
|
184
|
+
msg = (
|
|
185
|
+
"langfuse is not installed. Install via "
|
|
186
|
+
"`pip install agentforge-langfuse[langfuse]` to use the production runner."
|
|
187
|
+
)
|
|
188
|
+
raise ModuleError(msg) from exc
|
|
189
|
+
|
|
190
|
+
from agentforge_langfuse._runner import _LangfuseClientRunner # noqa: PLC0415
|
|
191
|
+
|
|
192
|
+
kwargs: dict[str, Any] = {"public_key": public_key, "secret_key": secret_key}
|
|
193
|
+
if host is not None:
|
|
194
|
+
kwargs["host"] = host
|
|
195
|
+
client = Langfuse(**kwargs)
|
|
196
|
+
return _LangfuseClientRunner(client)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
__all__ = ["LangfuseHook"]
|
|
File without changes
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Live `LangfuseHook` integration test (feat-009 v0.2 follow-up).
|
|
2
|
+
|
|
3
|
+
Gated by `@pytest.mark.live` and `LANGFUSE_PUBLIC_KEY` +
|
|
4
|
+
`LANGFUSE_SECRET_KEY` env vars. Run with:
|
|
5
|
+
|
|
6
|
+
LANGFUSE_PUBLIC_KEY=pk-lf-... LANGFUSE_SECRET_KEY=sk-lf-... \\
|
|
7
|
+
LANGFUSE_HOST=https://cloud.langfuse.com \\
|
|
8
|
+
uv run pytest -m live packages/agentforge-langfuse/
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import os
|
|
14
|
+
|
|
15
|
+
import pytest
|
|
16
|
+
from agentforge_core.production.run_context import bind_run, new_run, reset_run
|
|
17
|
+
from agentforge_core.values.state import RunResult, Step
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@pytest.mark.live
|
|
21
|
+
def test_langfuse_live_emits_trace() -> None:
|
|
22
|
+
public_key = os.environ.get("LANGFUSE_PUBLIC_KEY")
|
|
23
|
+
secret_key = os.environ.get("LANGFUSE_SECRET_KEY")
|
|
24
|
+
if not public_key or not secret_key:
|
|
25
|
+
pytest.skip("LANGFUSE_PUBLIC_KEY / LANGFUSE_SECRET_KEY not set")
|
|
26
|
+
host = os.environ.get("LANGFUSE_HOST")
|
|
27
|
+
|
|
28
|
+
from agentforge_langfuse import LangfuseHook # noqa: PLC0415
|
|
29
|
+
|
|
30
|
+
hook = LangfuseHook.from_config(
|
|
31
|
+
public_key=public_key,
|
|
32
|
+
secret_key=secret_key,
|
|
33
|
+
host=host,
|
|
34
|
+
trace_name_prefix="agentforge.live",
|
|
35
|
+
)
|
|
36
|
+
ctx = new_run(task="live")
|
|
37
|
+
token = bind_run(ctx)
|
|
38
|
+
try:
|
|
39
|
+
hook(Step(iteration=0, kind="think", content="live", duration_ms=5))
|
|
40
|
+
hook(
|
|
41
|
+
RunResult(
|
|
42
|
+
output="ok",
|
|
43
|
+
cost_usd=0.001,
|
|
44
|
+
tokens_in=1,
|
|
45
|
+
tokens_out=1,
|
|
46
|
+
run_id=ctx.run_id,
|
|
47
|
+
duration_ms=10,
|
|
48
|
+
finish_reason="completed",
|
|
49
|
+
)
|
|
50
|
+
)
|
|
51
|
+
finally:
|
|
52
|
+
reset_run(token)
|
|
53
|
+
hook.close()
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""Unit tests for `LangfuseHook` (feat-009 v0.2 follow-up)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterator
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
from agentforge_core.production.run_context import bind_run, new_run, reset_run
|
|
9
|
+
from agentforge_core.values.messages import ToolCall
|
|
10
|
+
from agentforge_core.values.state import RunResult, Step
|
|
11
|
+
from agentforge_langfuse import LangfuseHook
|
|
12
|
+
from agentforge_langfuse._inmem_runner import FakeLangfuseRunner
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@pytest.fixture
|
|
16
|
+
def bound_run_id() -> Iterator[str]:
|
|
17
|
+
"""Bind a RunContext so `current_run()` resolves inside the hook."""
|
|
18
|
+
ctx = new_run(task="t")
|
|
19
|
+
token = bind_run(ctx)
|
|
20
|
+
try:
|
|
21
|
+
yield ctx.run_id
|
|
22
|
+
finally:
|
|
23
|
+
reset_run(token)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def test_first_step_opens_trace_and_adds_span(bound_run_id: str) -> None:
|
|
27
|
+
runner = FakeLangfuseRunner()
|
|
28
|
+
hook = LangfuseHook(runner=runner, trace_name_prefix="af.test")
|
|
29
|
+
|
|
30
|
+
hook(Step(iteration=0, kind="think", content="hello", duration_ms=10))
|
|
31
|
+
|
|
32
|
+
rec = runner.traces[bound_run_id]
|
|
33
|
+
assert rec.name == "af.test.run"
|
|
34
|
+
assert rec.metadata["agentforge.run_id"] == bound_run_id
|
|
35
|
+
assert len(rec.spans) == 1
|
|
36
|
+
assert rec.spans[0]["name"] == "step:think"
|
|
37
|
+
assert rec.spans[0]["metadata"]["iteration"] == 0
|
|
38
|
+
assert rec.spans[0]["metadata"]["duration_ms"] == 10
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def test_subsequent_step_reuses_trace(bound_run_id: str) -> None:
|
|
42
|
+
runner = FakeLangfuseRunner()
|
|
43
|
+
hook = LangfuseHook(runner=runner)
|
|
44
|
+
hook(Step(iteration=0, kind="think", content="a"))
|
|
45
|
+
hook(Step(iteration=1, kind="act", content="b"))
|
|
46
|
+
|
|
47
|
+
rec = runner.traces[bound_run_id]
|
|
48
|
+
assert [s["name"] for s in rec.spans] == ["step:think", "step:act"]
|
|
49
|
+
assert len(runner.traces) == 1
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def test_step_with_tool_call_nests_span_and_redacts(bound_run_id: str) -> None:
|
|
53
|
+
runner = FakeLangfuseRunner()
|
|
54
|
+
hook = LangfuseHook(runner=runner)
|
|
55
|
+
step = Step(
|
|
56
|
+
iteration=0,
|
|
57
|
+
kind="act",
|
|
58
|
+
content="x",
|
|
59
|
+
tool_call=ToolCall(
|
|
60
|
+
id="t-1",
|
|
61
|
+
name="web_search",
|
|
62
|
+
arguments={"query": "hi", "api_key": "shh"},
|
|
63
|
+
),
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
hook(step)
|
|
67
|
+
|
|
68
|
+
rec = runner.traces[bound_run_id]
|
|
69
|
+
tool_span = next(s for s in rec.spans if s["name"] == "tool:web_search")
|
|
70
|
+
assert tool_span["metadata"]["args"]["api_key"] == "<redacted>"
|
|
71
|
+
assert tool_span["metadata"]["args"]["query"] == "hi"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def test_finish_adds_scores_and_flushes(bound_run_id: str) -> None:
|
|
75
|
+
runner = FakeLangfuseRunner()
|
|
76
|
+
hook = LangfuseHook(runner=runner)
|
|
77
|
+
hook(Step(iteration=0, kind="think", content="x"))
|
|
78
|
+
hook(
|
|
79
|
+
RunResult(
|
|
80
|
+
output="ok",
|
|
81
|
+
cost_usd=0.42,
|
|
82
|
+
tokens_in=5,
|
|
83
|
+
tokens_out=7,
|
|
84
|
+
run_id=bound_run_id,
|
|
85
|
+
duration_ms=123,
|
|
86
|
+
finish_reason="completed",
|
|
87
|
+
)
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
rec = runner.traces[bound_run_id]
|
|
91
|
+
scores = {s["name"]: s for s in rec.scores}
|
|
92
|
+
assert scores["cost_usd"]["value"] == 0.42
|
|
93
|
+
assert "finish_reason=completed" in (scores["cost_usd"]["comment"] or "")
|
|
94
|
+
assert scores["duration_ms"]["value"] == 123.0
|
|
95
|
+
assert rec.flushed is True
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def test_finish_without_prior_step_opens_synthetic_trace() -> None:
|
|
99
|
+
runner = FakeLangfuseRunner()
|
|
100
|
+
hook = LangfuseHook(runner=runner)
|
|
101
|
+
|
|
102
|
+
hook(
|
|
103
|
+
RunResult(
|
|
104
|
+
output="ok",
|
|
105
|
+
cost_usd=0.0,
|
|
106
|
+
tokens_in=0,
|
|
107
|
+
tokens_out=0,
|
|
108
|
+
run_id="r-zero-step",
|
|
109
|
+
duration_ms=5,
|
|
110
|
+
finish_reason="completed",
|
|
111
|
+
)
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
rec = runner.traces["r-zero-step"]
|
|
115
|
+
assert rec.metadata["synthetic"] is True
|
|
116
|
+
assert any(s["name"] == "cost_usd" for s in rec.scores)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def test_step_outside_run_context_is_a_noop() -> None:
|
|
120
|
+
"""If a caller fires the hook outside `Agent.run`, the hook
|
|
121
|
+
silently drops the step instead of crashing."""
|
|
122
|
+
runner = FakeLangfuseRunner()
|
|
123
|
+
hook = LangfuseHook(runner=runner)
|
|
124
|
+
hook(Step(iteration=0, kind="think", content="x"))
|
|
125
|
+
assert runner.traces == {}
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def test_empty_prefix_rejected() -> None:
|
|
129
|
+
with pytest.raises(ValueError, match="trace_name_prefix is required"):
|
|
130
|
+
LangfuseHook(runner=FakeLangfuseRunner(), trace_name_prefix="")
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def test_close_propagates_to_runner() -> None:
|
|
134
|
+
runner = FakeLangfuseRunner()
|
|
135
|
+
hook = LangfuseHook(runner=runner)
|
|
136
|
+
hook.close()
|
|
137
|
+
assert runner.closed
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def test_fake_runner_silently_drops_unknown_trace_ids() -> None:
|
|
141
|
+
"""Defensive: if a caller mis-routes a span/score to an unknown
|
|
142
|
+
trace_id, the fake drops it silently (matches the production
|
|
143
|
+
SDK's behavior of failing soft on unknown handles)."""
|
|
144
|
+
runner = FakeLangfuseRunner()
|
|
145
|
+
runner.add_span(trace_id="never-opened", name="x")
|
|
146
|
+
runner.add_score(trace_id="never-opened", name="cost_usd", value=1.0)
|
|
147
|
+
runner.flush(trace_id="never-opened")
|
|
148
|
+
assert runner.traces == {}
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def test_redact_fields_override_propagates() -> None:
|
|
152
|
+
hook = LangfuseHook(
|
|
153
|
+
runner=FakeLangfuseRunner(),
|
|
154
|
+
redact_fields=("ssn", "card_number"),
|
|
155
|
+
)
|
|
156
|
+
assert hook.redact_fields == ("ssn", "card_number")
|