agentforge-otel 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_otel-0.2.3/.gitignore +49 -0
- agentforge_otel-0.2.3/LICENSE +202 -0
- agentforge_otel-0.2.3/PKG-INFO +90 -0
- agentforge_otel-0.2.3/README.md +64 -0
- agentforge_otel-0.2.3/pyproject.toml +62 -0
- agentforge_otel-0.2.3/src/agentforge_otel/__init__.py +13 -0
- agentforge_otel-0.2.3/src/agentforge_otel/hook.py +235 -0
- agentforge_otel-0.2.3/src/agentforge_otel/py.typed +0 -0
- agentforge_otel-0.2.3/tests/unit/test_hook.py +478 -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,90 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: agentforge-otel
|
|
3
|
+
Version: 0.2.3
|
|
4
|
+
Summary: OpenTelemetry tracing + metrics emitter 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: Documentation, https://github.com/Scaffoldic/agentforge-py
|
|
8
|
+
Project-URL: Changelog, https://github.com/Scaffoldic/agentforge-py/blob/main/CHANGELOG.md
|
|
9
|
+
Project-URL: Issues, https://github.com/Scaffoldic/agentforge-py/issues
|
|
10
|
+
Author: The AgentForge Authors
|
|
11
|
+
License-Expression: Apache-2.0
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Keywords: agent,ai,observability,opentelemetry,tracing
|
|
14
|
+
Classifier: Development Status :: 2 - Pre-Alpha
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Topic :: System :: Monitoring
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.13
|
|
22
|
+
Requires-Dist: agentforge-core~=0.2.3
|
|
23
|
+
Requires-Dist: opentelemetry-exporter-otlp-proto-grpc>=1.27
|
|
24
|
+
Requires-Dist: opentelemetry-sdk>=1.27
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# agentforge-otel
|
|
28
|
+
|
|
29
|
+
OpenTelemetry tracing for AgentForge (feat-009).
|
|
30
|
+
|
|
31
|
+
The OTel **API** ships in `agentforge-core` — the framework emits
|
|
32
|
+
spans unconditionally. Without this package, those calls degrade to
|
|
33
|
+
`NonRecordingSpan` (near-zero cost). Installing `agentforge-otel`
|
|
34
|
+
wires up the **SDK**, an OTLP exporter, and a sampler so the spans
|
|
35
|
+
actually reach a collector.
|
|
36
|
+
|
|
37
|
+
## Quick start
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
from agentforge import Agent
|
|
41
|
+
from agentforge_otel import OpenTelemetryHook
|
|
42
|
+
|
|
43
|
+
otel = OpenTelemetryHook(
|
|
44
|
+
endpoint="http://otel-collector:4317",
|
|
45
|
+
service_name="my-agent",
|
|
46
|
+
sample_rate=1.0,
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
agent = Agent(
|
|
50
|
+
model="bedrock:...",
|
|
51
|
+
tools=[...],
|
|
52
|
+
on_step=otel,
|
|
53
|
+
on_finish=otel,
|
|
54
|
+
)
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Constructing the hook installs the SDK provider once (idempotent). The
|
|
58
|
+
framework's existing span emission then produces a tree per run:
|
|
59
|
+
|
|
60
|
+
span: agent.run
|
|
61
|
+
└── span: strategy.iteration
|
|
62
|
+
├── span: llm.call
|
|
63
|
+
├── span: tool.<name>
|
|
64
|
+
└── span: evaluator.<name>
|
|
65
|
+
|
|
66
|
+
Span attributes carry `agentforge.run_id`, cost, token counts,
|
|
67
|
+
finish reason, and step count — same correlation key the
|
|
68
|
+
`RunIdFilter` puts on every log line.
|
|
69
|
+
|
|
70
|
+
## Multiple backends
|
|
71
|
+
|
|
72
|
+
Run OTel alongside any other observer:
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
agent = Agent(
|
|
76
|
+
model="...",
|
|
77
|
+
on_step=[otel, my_statsd_hook],
|
|
78
|
+
on_finish=[otel, persist_to_db],
|
|
79
|
+
)
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Hooks fire in registration order; one hook's exception doesn't
|
|
83
|
+
affect siblings (the framework logs WARN via
|
|
84
|
+
`agentforge.observability` and keeps going).
|
|
85
|
+
|
|
86
|
+
## Vendor compatibility
|
|
87
|
+
|
|
88
|
+
OTel is the wire format; any collector that ingests OTLP works:
|
|
89
|
+
Datadog, Honeycomb, Jaeger, Grafana Tempo, SigNoz, New Relic. Point
|
|
90
|
+
the `endpoint` at your collector's gRPC port (4317 by default).
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
# agentforge-otel
|
|
2
|
+
|
|
3
|
+
OpenTelemetry tracing for AgentForge (feat-009).
|
|
4
|
+
|
|
5
|
+
The OTel **API** ships in `agentforge-core` — the framework emits
|
|
6
|
+
spans unconditionally. Without this package, those calls degrade to
|
|
7
|
+
`NonRecordingSpan` (near-zero cost). Installing `agentforge-otel`
|
|
8
|
+
wires up the **SDK**, an OTLP exporter, and a sampler so the spans
|
|
9
|
+
actually reach a collector.
|
|
10
|
+
|
|
11
|
+
## Quick start
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
from agentforge import Agent
|
|
15
|
+
from agentforge_otel import OpenTelemetryHook
|
|
16
|
+
|
|
17
|
+
otel = OpenTelemetryHook(
|
|
18
|
+
endpoint="http://otel-collector:4317",
|
|
19
|
+
service_name="my-agent",
|
|
20
|
+
sample_rate=1.0,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
agent = Agent(
|
|
24
|
+
model="bedrock:...",
|
|
25
|
+
tools=[...],
|
|
26
|
+
on_step=otel,
|
|
27
|
+
on_finish=otel,
|
|
28
|
+
)
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Constructing the hook installs the SDK provider once (idempotent). The
|
|
32
|
+
framework's existing span emission then produces a tree per run:
|
|
33
|
+
|
|
34
|
+
span: agent.run
|
|
35
|
+
└── span: strategy.iteration
|
|
36
|
+
├── span: llm.call
|
|
37
|
+
├── span: tool.<name>
|
|
38
|
+
└── span: evaluator.<name>
|
|
39
|
+
|
|
40
|
+
Span attributes carry `agentforge.run_id`, cost, token counts,
|
|
41
|
+
finish reason, and step count — same correlation key the
|
|
42
|
+
`RunIdFilter` puts on every log line.
|
|
43
|
+
|
|
44
|
+
## Multiple backends
|
|
45
|
+
|
|
46
|
+
Run OTel alongside any other observer:
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
agent = Agent(
|
|
50
|
+
model="...",
|
|
51
|
+
on_step=[otel, my_statsd_hook],
|
|
52
|
+
on_finish=[otel, persist_to_db],
|
|
53
|
+
)
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Hooks fire in registration order; one hook's exception doesn't
|
|
57
|
+
affect siblings (the framework logs WARN via
|
|
58
|
+
`agentforge.observability` and keeps going).
|
|
59
|
+
|
|
60
|
+
## Vendor compatibility
|
|
61
|
+
|
|
62
|
+
OTel is the wire format; any collector that ingests OTLP works:
|
|
63
|
+
Datadog, Honeycomb, Jaeger, Grafana Tempo, SigNoz, New Relic. Point
|
|
64
|
+
the `endpoint` at your collector's gRPC port (4317 by default).
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# agentforge-otel — OpenTelemetry tracing + metrics for AgentForge.
|
|
2
|
+
#
|
|
3
|
+
# Tier-3 module per ADR-0003. Installing this package wires up the
|
|
4
|
+
# OTel SDK (provider + OTLP exporter + sampler) so that the framework
|
|
5
|
+
# spans emitted from `agentforge-core/observability/tracing.py`
|
|
6
|
+
# actually reach a collector. Without this package the spans degrade
|
|
7
|
+
# to OTel's NonRecordingSpan (near-zero cost).
|
|
8
|
+
|
|
9
|
+
[project]
|
|
10
|
+
name = "agentforge-otel"
|
|
11
|
+
version = "0.2.3"
|
|
12
|
+
description = "OpenTelemetry tracing + metrics emitter for AgentForge"
|
|
13
|
+
readme = "README.md"
|
|
14
|
+
requires-python = ">=3.13"
|
|
15
|
+
license = "Apache-2.0"
|
|
16
|
+
license-files = ["LICENSE"]
|
|
17
|
+
authors = [
|
|
18
|
+
{name = "The AgentForge Authors"},
|
|
19
|
+
]
|
|
20
|
+
keywords = ["ai", "agent", "observability", "opentelemetry", "tracing"]
|
|
21
|
+
classifiers = [
|
|
22
|
+
"Development Status :: 2 - Pre-Alpha",
|
|
23
|
+
"Intended Audience :: Developers",
|
|
24
|
+
"License :: OSI Approved :: Apache Software License",
|
|
25
|
+
"Programming Language :: Python :: 3",
|
|
26
|
+
"Programming Language :: Python :: 3.13",
|
|
27
|
+
"Topic :: System :: Monitoring",
|
|
28
|
+
"Typing :: Typed",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
dependencies = [
|
|
32
|
+
"agentforge-core ~= 0.2.3",
|
|
33
|
+
"opentelemetry-sdk>=1.27",
|
|
34
|
+
"opentelemetry-exporter-otlp-proto-grpc>=1.27",
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
[project.urls]
|
|
38
|
+
Homepage = "https://github.com/Scaffoldic/agentforge-py"
|
|
39
|
+
Repository = "https://github.com/Scaffoldic/agentforge-py"
|
|
40
|
+
Documentation = "https://github.com/Scaffoldic/agentforge-py"
|
|
41
|
+
Changelog = "https://github.com/Scaffoldic/agentforge-py/blob/main/CHANGELOG.md"
|
|
42
|
+
Issues = "https://github.com/Scaffoldic/agentforge-py/issues"
|
|
43
|
+
|
|
44
|
+
# Entry-point registration — feat-010 will load by name from
|
|
45
|
+
# `modules.observability` in agentforge.yaml.
|
|
46
|
+
[project.entry-points."agentforge.hooks"]
|
|
47
|
+
otel = "agentforge_otel.hook:OpenTelemetryHook"
|
|
48
|
+
|
|
49
|
+
[build-system]
|
|
50
|
+
requires = ["hatchling>=1.27"]
|
|
51
|
+
build-backend = "hatchling.build"
|
|
52
|
+
|
|
53
|
+
[tool.hatch.build.targets.wheel]
|
|
54
|
+
packages = ["src/agentforge_otel"]
|
|
55
|
+
|
|
56
|
+
[tool.hatch.build.targets.sdist]
|
|
57
|
+
include = [
|
|
58
|
+
"src/agentforge_otel",
|
|
59
|
+
"tests",
|
|
60
|
+
"README.md",
|
|
61
|
+
"LICENSE",
|
|
62
|
+
]
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""OpenTelemetry tracing for AgentForge — feat-009.
|
|
2
|
+
|
|
3
|
+
Public surface:
|
|
4
|
+
- `OpenTelemetryHook` — configures the SDK provider + OTLP exporter
|
|
5
|
+
on construction, satisfies both `on_step` and `on_finish` hook
|
|
6
|
+
contracts via `__call__(step_or_result)` dispatch.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from agentforge_otel.hook import OpenTelemetryHook
|
|
12
|
+
|
|
13
|
+
__all__ = ["OpenTelemetryHook"]
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
"""`OpenTelemetryHook` — SDK setup + per-step/per-finish hook impl.
|
|
2
|
+
|
|
3
|
+
Construction installs the OTel SDK tracer provider with an OTLP gRPC
|
|
4
|
+
exporter and a `TraceIdRatioBased` sampler. Idempotent — repeat
|
|
5
|
+
construction reuses the existing provider.
|
|
6
|
+
|
|
7
|
+
The hook itself satisfies both step and finish hook contracts via
|
|
8
|
+
`__call__(payload)`:
|
|
9
|
+
- `Step` -> annotate the current span (run span or whatever's active)
|
|
10
|
+
with per-step attributes.
|
|
11
|
+
- `RunResult` -> the run span has already been closed by `Agent.run`'s
|
|
12
|
+
context manager; the hook just adds a final summary log via the
|
|
13
|
+
`agentforge.observability` logger for callers that want a compact
|
|
14
|
+
per-run line in their logs.
|
|
15
|
+
|
|
16
|
+
For arg redaction: the hook scrubs values whose keys match
|
|
17
|
+
`redact_fields` (case-insensitive substring match) before adding tool
|
|
18
|
+
call args as span attributes.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import logging
|
|
24
|
+
import re
|
|
25
|
+
import threading
|
|
26
|
+
from typing import Any
|
|
27
|
+
|
|
28
|
+
from agentforge_core.values.state import RunResult, Step
|
|
29
|
+
from opentelemetry import trace
|
|
30
|
+
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
|
|
31
|
+
from opentelemetry.sdk.resources import SERVICE_NAME, Resource
|
|
32
|
+
from opentelemetry.sdk.trace import TracerProvider
|
|
33
|
+
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
|
34
|
+
from opentelemetry.sdk.trace.sampling import TraceIdRatioBased
|
|
35
|
+
|
|
36
|
+
_log = logging.getLogger("agentforge.observability")
|
|
37
|
+
|
|
38
|
+
_DEFAULT_REDACT = ("api_key", "password", "secret", "token", "authorization")
|
|
39
|
+
|
|
40
|
+
# Module-level lock so concurrent hook instantiations don't race on
|
|
41
|
+
# the global tracer provider. The "installed" flag lives on a mutable
|
|
42
|
+
# list to avoid a `global` declaration (PLW0603).
|
|
43
|
+
_setup_lock = threading.Lock()
|
|
44
|
+
_provider_installed: list[bool] = [False]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class OpenTelemetryHook:
|
|
48
|
+
"""Configures OTel SDK on construction; satisfies StepHook + FinishHook.
|
|
49
|
+
|
|
50
|
+
Args:
|
|
51
|
+
endpoint: OTLP gRPC endpoint (e.g. `http://otel-collector:4317`).
|
|
52
|
+
Defaults to the OTel SDK's own env-var defaults
|
|
53
|
+
(`OTEL_EXPORTER_OTLP_ENDPOINT`).
|
|
54
|
+
service_name: Resource attribute under `service.name`. Required.
|
|
55
|
+
sample_rate: `TraceIdRatioBased` rate in [0.0, 1.0]. Default 1.0
|
|
56
|
+
(every trace sampled).
|
|
57
|
+
redact_fields: Substring matches for sensitive field names.
|
|
58
|
+
Defaults to common API-key / password / token names; pass
|
|
59
|
+
your own to override.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
def __init__(
|
|
63
|
+
self,
|
|
64
|
+
*,
|
|
65
|
+
endpoint: str | None = None,
|
|
66
|
+
service_name: str = "agentforge",
|
|
67
|
+
sample_rate: float = 1.0,
|
|
68
|
+
redact_fields: tuple[str, ...] | None = None,
|
|
69
|
+
redact_value_patterns: tuple[str, ...] | None = None,
|
|
70
|
+
) -> None:
|
|
71
|
+
if not 0.0 <= sample_rate <= 1.0:
|
|
72
|
+
raise ValueError(f"sample_rate must be in [0, 1]; got {sample_rate}")
|
|
73
|
+
if not service_name:
|
|
74
|
+
raise ValueError("service_name is required")
|
|
75
|
+
|
|
76
|
+
self._service_name = service_name
|
|
77
|
+
self._endpoint = endpoint
|
|
78
|
+
self._sample_rate = sample_rate
|
|
79
|
+
self._redact_fields = tuple(
|
|
80
|
+
f.lower() for f in (redact_fields if redact_fields is not None else _DEFAULT_REDACT)
|
|
81
|
+
)
|
|
82
|
+
# feat-009 v0.3 polish: content-based PII redaction. Patterns
|
|
83
|
+
# are compiled once at construction so per-step redaction
|
|
84
|
+
# stays cheap. Default None — content-based redaction is
|
|
85
|
+
# opt-in.
|
|
86
|
+
self._redact_value_patterns: tuple[re.Pattern[str], ...] = (
|
|
87
|
+
tuple(re.compile(p) for p in redact_value_patterns)
|
|
88
|
+
if redact_value_patterns is not None
|
|
89
|
+
else ()
|
|
90
|
+
)
|
|
91
|
+
_ensure_provider(
|
|
92
|
+
service_name=service_name,
|
|
93
|
+
endpoint=endpoint,
|
|
94
|
+
sample_rate=sample_rate,
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
@property
|
|
98
|
+
def service_name(self) -> str:
|
|
99
|
+
return self._service_name
|
|
100
|
+
|
|
101
|
+
@property
|
|
102
|
+
def redact_fields(self) -> tuple[str, ...]:
|
|
103
|
+
return self._redact_fields
|
|
104
|
+
|
|
105
|
+
@property
|
|
106
|
+
def redact_value_patterns(self) -> tuple[re.Pattern[str], ...]:
|
|
107
|
+
return self._redact_value_patterns
|
|
108
|
+
|
|
109
|
+
def __call__(self, payload: Step | RunResult) -> None:
|
|
110
|
+
"""Hook entry point — dispatches on payload type."""
|
|
111
|
+
if isinstance(payload, Step):
|
|
112
|
+
self._on_step(payload)
|
|
113
|
+
else:
|
|
114
|
+
self._on_finish(payload)
|
|
115
|
+
|
|
116
|
+
# ------------------------------------------------------------------
|
|
117
|
+
# Step handling — annotate the current span.
|
|
118
|
+
# ------------------------------------------------------------------
|
|
119
|
+
|
|
120
|
+
def _on_step(self, step: Step) -> None:
|
|
121
|
+
span = trace.get_current_span()
|
|
122
|
+
# Span is the no-op NonRecordingSpan when nothing is active —
|
|
123
|
+
# safe to call set_attribute on it (it just discards).
|
|
124
|
+
span.add_event(
|
|
125
|
+
"agent.step",
|
|
126
|
+
attributes={
|
|
127
|
+
"agentforge.step.iteration": step.iteration,
|
|
128
|
+
"agentforge.step.kind": step.kind,
|
|
129
|
+
"agentforge.step.cost_usd": step.cost_usd,
|
|
130
|
+
"agentforge.step.tokens_in": step.tokens_in,
|
|
131
|
+
"agentforge.step.tokens_out": step.tokens_out,
|
|
132
|
+
"agentforge.step.duration_ms": step.duration_ms,
|
|
133
|
+
},
|
|
134
|
+
)
|
|
135
|
+
if step.tool_call is not None:
|
|
136
|
+
span.add_event(
|
|
137
|
+
"agent.tool_call",
|
|
138
|
+
attributes={
|
|
139
|
+
"agentforge.tool.name": step.tool_call.name,
|
|
140
|
+
"agentforge.tool.args": self._redact(dict(step.tool_call.arguments)),
|
|
141
|
+
},
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
# ------------------------------------------------------------------
|
|
145
|
+
# Finish handling — the run span already closed; log a summary.
|
|
146
|
+
# ------------------------------------------------------------------
|
|
147
|
+
|
|
148
|
+
def _on_finish(self, result: RunResult) -> None:
|
|
149
|
+
_log.info(
|
|
150
|
+
"run %s finished: %s (cost=$%.4f, tokens_in=%d, tokens_out=%d, steps=%d, %dms)",
|
|
151
|
+
result.run_id,
|
|
152
|
+
result.finish_reason,
|
|
153
|
+
result.cost_usd,
|
|
154
|
+
result.tokens_in,
|
|
155
|
+
result.tokens_out,
|
|
156
|
+
len(result.steps),
|
|
157
|
+
result.duration_ms,
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
# ------------------------------------------------------------------
|
|
161
|
+
# Redaction helper.
|
|
162
|
+
# ------------------------------------------------------------------
|
|
163
|
+
|
|
164
|
+
def _redact(self, args: dict[str, Any]) -> str:
|
|
165
|
+
"""Stringify a dict for span attribution, masking sensitive
|
|
166
|
+
keys *and* values matching configured regex patterns.
|
|
167
|
+
|
|
168
|
+
Two redaction passes:
|
|
169
|
+
1. Key-based: case-insensitive substring match on the field
|
|
170
|
+
name against `redact_fields` (e.g. ``api_key``,
|
|
171
|
+
``password``). The whole value gets masked.
|
|
172
|
+
2. Content-based (feat-009 v0.3 polish): for string values
|
|
173
|
+
that survived the key check, run each pattern in
|
|
174
|
+
`redact_value_patterns` against the stringified value;
|
|
175
|
+
any match masks the whole value.
|
|
176
|
+
|
|
177
|
+
Span attributes accept primitives + lists thereof; we render
|
|
178
|
+
the dict to a compact ``k=v`` form rather than fight the
|
|
179
|
+
schema.
|
|
180
|
+
"""
|
|
181
|
+
parts: list[str] = []
|
|
182
|
+
for key, value in args.items():
|
|
183
|
+
if any(token in key.lower() for token in self._redact_fields):
|
|
184
|
+
parts.append(f"{key}=<redacted>")
|
|
185
|
+
continue
|
|
186
|
+
if self._value_matches_pattern(value):
|
|
187
|
+
parts.append(f"{key}=<redacted>")
|
|
188
|
+
continue
|
|
189
|
+
parts.append(f"{key}={value!r}")
|
|
190
|
+
return ", ".join(parts)
|
|
191
|
+
|
|
192
|
+
def _value_matches_pattern(self, value: Any) -> bool:
|
|
193
|
+
"""True if any configured regex pattern matches the value
|
|
194
|
+
text. Non-string values are stringified first so payloads
|
|
195
|
+
like ``42``, ``True``, or nested dicts are still scanned."""
|
|
196
|
+
if not self._redact_value_patterns:
|
|
197
|
+
return False
|
|
198
|
+
text = value if isinstance(value, str) else str(value)
|
|
199
|
+
return any(p.search(text) for p in self._redact_value_patterns)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _ensure_provider(
|
|
203
|
+
*,
|
|
204
|
+
service_name: str,
|
|
205
|
+
endpoint: str | None,
|
|
206
|
+
sample_rate: float,
|
|
207
|
+
) -> None:
|
|
208
|
+
"""Install the SDK provider + OTLP exporter once per process.
|
|
209
|
+
|
|
210
|
+
Idempotent: subsequent calls (with potentially-different config)
|
|
211
|
+
keep the first-installed provider. Re-installing would silently
|
|
212
|
+
drop spans already in-flight on the previous provider, so we
|
|
213
|
+
don't do that — first wins.
|
|
214
|
+
"""
|
|
215
|
+
with _setup_lock:
|
|
216
|
+
if _provider_installed[0]:
|
|
217
|
+
return
|
|
218
|
+
# If the user has already installed a TracerProvider themselves
|
|
219
|
+
# (rare but possible — they wired OTel manually), respect it.
|
|
220
|
+
existing = trace.get_tracer_provider()
|
|
221
|
+
if isinstance(existing, TracerProvider):
|
|
222
|
+
_provider_installed[0] = True
|
|
223
|
+
return
|
|
224
|
+
resource = Resource.create({SERVICE_NAME: service_name})
|
|
225
|
+
provider = TracerProvider(
|
|
226
|
+
resource=resource,
|
|
227
|
+
sampler=TraceIdRatioBased(sample_rate),
|
|
228
|
+
)
|
|
229
|
+
exporter_kwargs: dict[str, Any] = {}
|
|
230
|
+
if endpoint is not None:
|
|
231
|
+
exporter_kwargs["endpoint"] = endpoint
|
|
232
|
+
exporter = OTLPSpanExporter(**exporter_kwargs)
|
|
233
|
+
provider.add_span_processor(BatchSpanProcessor(exporter))
|
|
234
|
+
trace.set_tracer_provider(provider)
|
|
235
|
+
_provider_installed[0] = True
|
|
File without changes
|
|
@@ -0,0 +1,478 @@
|
|
|
1
|
+
"""Unit tests for `agentforge_otel.hook.OpenTelemetryHook`.
|
|
2
|
+
|
|
3
|
+
Uses OTel's `InMemorySpanExporter` so we can assert on the actual
|
|
4
|
+
spans the framework + hook produce, without sending traffic anywhere.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import logging
|
|
10
|
+
|
|
11
|
+
import agentforge_otel.hook as hook_mod
|
|
12
|
+
import pytest
|
|
13
|
+
from agentforge import Agent
|
|
14
|
+
from agentforge_core.contracts.strategy import ReasoningStrategy
|
|
15
|
+
from agentforge_core.values.messages import ToolCall
|
|
16
|
+
from agentforge_core.values.state import AgentState, RunResult, Step
|
|
17
|
+
from agentforge_otel import OpenTelemetryHook
|
|
18
|
+
from opentelemetry import trace
|
|
19
|
+
from opentelemetry.sdk.resources import Resource
|
|
20
|
+
from opentelemetry.sdk.trace import TracerProvider
|
|
21
|
+
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
|
|
22
|
+
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@pytest.fixture(autouse=True)
|
|
26
|
+
def _reset_provider_state():
|
|
27
|
+
"""Reset the module-level "provider installed" flag + tracer
|
|
28
|
+
provider so each test starts clean. OTel's `set_tracer_provider`
|
|
29
|
+
refuses to swap once set, so we reset the internals.
|
|
30
|
+
"""
|
|
31
|
+
hook_mod._provider_installed[0] = False
|
|
32
|
+
trace._TRACER_PROVIDER_SET_ONCE = trace.Once() # type: ignore[attr-defined]
|
|
33
|
+
trace._TRACER_PROVIDER = None # type: ignore[attr-defined]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _install_inmemory_provider() -> InMemorySpanExporter:
|
|
37
|
+
"""Replace OTel's provider with one that exports to an in-memory
|
|
38
|
+
list. Returns the exporter so tests can inspect emitted spans."""
|
|
39
|
+
exporter = InMemorySpanExporter()
|
|
40
|
+
provider = TracerProvider(resource=Resource.create({"service.name": "test"}))
|
|
41
|
+
provider.add_span_processor(SimpleSpanProcessor(exporter))
|
|
42
|
+
trace.set_tracer_provider(provider)
|
|
43
|
+
hook_mod._provider_installed[0] = True
|
|
44
|
+
return exporter
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
# --- construction ---------------------------------------------------
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def test_invalid_sample_rate_rejected():
|
|
51
|
+
with pytest.raises(ValueError, match="sample_rate"):
|
|
52
|
+
OpenTelemetryHook(service_name="t", sample_rate=1.5)
|
|
53
|
+
with pytest.raises(ValueError, match="sample_rate"):
|
|
54
|
+
OpenTelemetryHook(service_name="t", sample_rate=-0.1)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def test_missing_service_name_rejected():
|
|
58
|
+
with pytest.raises(ValueError, match="service_name"):
|
|
59
|
+
OpenTelemetryHook(service_name="")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def test_construction_idempotent_does_not_replace_provider():
|
|
63
|
+
"""If a provider is already installed, the hook doesn't clobber it."""
|
|
64
|
+
exporter = _install_inmemory_provider()
|
|
65
|
+
existing_provider = trace.get_tracer_provider()
|
|
66
|
+
|
|
67
|
+
OpenTelemetryHook(service_name="agent-1", endpoint="http://nowhere:4317")
|
|
68
|
+
# Provider unchanged — installation respected the existing one.
|
|
69
|
+
assert trace.get_tracer_provider() is existing_provider
|
|
70
|
+
assert exporter is not None # exporter still wired
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
# --- step events ---------------------------------------------------
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def test_step_event_added_to_current_span():
|
|
77
|
+
exporter = _install_inmemory_provider()
|
|
78
|
+
h = OpenTelemetryHook(service_name="test", endpoint="http://localhost:4317")
|
|
79
|
+
|
|
80
|
+
tracer = trace.get_tracer("agentforge")
|
|
81
|
+
with tracer.start_as_current_span("agent.run"):
|
|
82
|
+
h(
|
|
83
|
+
Step(
|
|
84
|
+
iteration=0,
|
|
85
|
+
kind="observe",
|
|
86
|
+
content="hello",
|
|
87
|
+
tokens_in=10,
|
|
88
|
+
tokens_out=20,
|
|
89
|
+
cost_usd=0.001,
|
|
90
|
+
duration_ms=42,
|
|
91
|
+
)
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
finished = exporter.get_finished_spans()
|
|
95
|
+
assert len(finished) == 1
|
|
96
|
+
events = list(finished[0].events)
|
|
97
|
+
step_events = [e for e in events if e.name == "agent.step"]
|
|
98
|
+
assert len(step_events) == 1
|
|
99
|
+
attrs = dict(step_events[0].attributes or {})
|
|
100
|
+
assert attrs["agentforge.step.iteration"] == 0
|
|
101
|
+
assert attrs["agentforge.step.kind"] == "observe"
|
|
102
|
+
assert attrs["agentforge.step.cost_usd"] == pytest.approx(0.001)
|
|
103
|
+
assert attrs["agentforge.step.tokens_in"] == 10
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def test_tool_call_event_added_with_redaction():
|
|
107
|
+
exporter = _install_inmemory_provider()
|
|
108
|
+
h = OpenTelemetryHook(service_name="test", endpoint="http://localhost:4317")
|
|
109
|
+
|
|
110
|
+
tracer = trace.get_tracer("agentforge")
|
|
111
|
+
with tracer.start_as_current_span("agent.run"):
|
|
112
|
+
h(
|
|
113
|
+
Step(
|
|
114
|
+
iteration=0,
|
|
115
|
+
kind="act",
|
|
116
|
+
content="call",
|
|
117
|
+
tool_call=ToolCall(
|
|
118
|
+
id="01TEST",
|
|
119
|
+
name="charge_customer",
|
|
120
|
+
arguments={
|
|
121
|
+
"customer_id": "cust_42",
|
|
122
|
+
"api_key": "sk-secret-xyz",
|
|
123
|
+
"amount_cents": 1000,
|
|
124
|
+
},
|
|
125
|
+
),
|
|
126
|
+
)
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
finished = exporter.get_finished_spans()
|
|
130
|
+
events = [e for e in finished[0].events if e.name == "agent.tool_call"]
|
|
131
|
+
assert len(events) == 1
|
|
132
|
+
attrs = dict(events[0].attributes or {})
|
|
133
|
+
args_str = str(attrs["agentforge.tool.args"])
|
|
134
|
+
assert "customer_id=" in args_str
|
|
135
|
+
assert "amount_cents=" in args_str
|
|
136
|
+
# api_key value redacted; key still visible.
|
|
137
|
+
assert "api_key=<redacted>" in args_str
|
|
138
|
+
assert "sk-secret-xyz" not in args_str
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def test_custom_redact_fields_take_effect():
|
|
142
|
+
exporter = _install_inmemory_provider()
|
|
143
|
+
h = OpenTelemetryHook(
|
|
144
|
+
service_name="test", endpoint="http://localhost:4317", redact_fields=("ssn",)
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
tracer = trace.get_tracer("agentforge")
|
|
148
|
+
with tracer.start_as_current_span("agent.run"):
|
|
149
|
+
h(
|
|
150
|
+
Step(
|
|
151
|
+
iteration=0,
|
|
152
|
+
kind="act",
|
|
153
|
+
content="x",
|
|
154
|
+
tool_call=ToolCall(
|
|
155
|
+
id="01T",
|
|
156
|
+
name="lookup",
|
|
157
|
+
arguments={"ssn": "123-45-6789", "api_key": "still-visible"},
|
|
158
|
+
),
|
|
159
|
+
)
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
finished = exporter.get_finished_spans()
|
|
163
|
+
event = next(e for e in finished[0].events if e.name == "agent.tool_call")
|
|
164
|
+
args_str = str(dict(event.attributes or {})["agentforge.tool.args"])
|
|
165
|
+
assert "ssn=<redacted>" in args_str
|
|
166
|
+
# api_key no longer in the redact list — visible.
|
|
167
|
+
assert "still-visible" in args_str
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
# --- finish handling ----------------------------------------------
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def test_finish_emits_summary_log(caplog):
|
|
174
|
+
caplog.set_level(logging.INFO, logger="agentforge.observability")
|
|
175
|
+
h = OpenTelemetryHook(service_name="test", endpoint="http://localhost:4317")
|
|
176
|
+
|
|
177
|
+
result = RunResult(
|
|
178
|
+
output="done",
|
|
179
|
+
cost_usd=0.05,
|
|
180
|
+
tokens_in=100,
|
|
181
|
+
tokens_out=50,
|
|
182
|
+
run_id="01HXFINISH",
|
|
183
|
+
duration_ms=1234,
|
|
184
|
+
finish_reason="completed",
|
|
185
|
+
)
|
|
186
|
+
h(result)
|
|
187
|
+
|
|
188
|
+
msgs = [r.message for r in caplog.records]
|
|
189
|
+
assert any("01HXFINISH" in m and "completed" in m and "$0.0500" in m for m in msgs)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
# --- public properties --------------------------------------------
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def test_public_properties():
|
|
196
|
+
h = OpenTelemetryHook(
|
|
197
|
+
service_name="my-agent",
|
|
198
|
+
endpoint="http://localhost:4317",
|
|
199
|
+
redact_fields=("custom",),
|
|
200
|
+
)
|
|
201
|
+
assert h.service_name == "my-agent"
|
|
202
|
+
assert h.redact_fields == ("custom",)
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
# --- end-to-end with Agent --------------------------------------
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
@pytest.mark.asyncio
|
|
209
|
+
async def test_end_to_end_root_span_from_agent_run():
|
|
210
|
+
"""Construct an Agent, run it with the OTel hook installed, assert
|
|
211
|
+
the framework's `agent.run` root span landed in the exporter with
|
|
212
|
+
the right attributes."""
|
|
213
|
+
exporter = _install_inmemory_provider()
|
|
214
|
+
|
|
215
|
+
class _OneStep(ReasoningStrategy):
|
|
216
|
+
async def run(self, state: AgentState) -> AgentState:
|
|
217
|
+
state.steps.append(Step(iteration=0, kind="observe", content="hi"))
|
|
218
|
+
return state
|
|
219
|
+
|
|
220
|
+
otel = OpenTelemetryHook(service_name="test", endpoint="http://localhost:4317")
|
|
221
|
+
async with Agent(strategy=_OneStep(), on_step=otel, on_finish=otel) as agent:
|
|
222
|
+
await agent.run("the task")
|
|
223
|
+
|
|
224
|
+
finished = exporter.get_finished_spans()
|
|
225
|
+
run_spans = [s for s in finished if s.name == "agent.run"]
|
|
226
|
+
assert len(run_spans) == 1
|
|
227
|
+
attrs = dict(run_spans[0].attributes or {})
|
|
228
|
+
assert attrs["agentforge.task"] == "the task"
|
|
229
|
+
assert attrs["agentforge.finish_reason"] == "completed"
|
|
230
|
+
assert attrs["agentforge.n_steps"] == 1
|
|
231
|
+
# The step hook annotated the span with an event.
|
|
232
|
+
step_events = [e for e in run_spans[0].events if e.name == "agent.step"]
|
|
233
|
+
assert len(step_events) == 1
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
@pytest.mark.asyncio
|
|
237
|
+
async def test_child_span_tree_via_react_loop():
|
|
238
|
+
"""Drive an Agent with the built-in ReActLoop strategy and a
|
|
239
|
+
scripted FakeLLM that triggers one tool_call. Assert the full
|
|
240
|
+
OTel span tree lands:
|
|
241
|
+
agent.run
|
|
242
|
+
├── strategy.iteration (iter 0)
|
|
243
|
+
│ ├── llm.call
|
|
244
|
+
│ └── tool.<name>
|
|
245
|
+
└── strategy.iteration (iter 1)
|
|
246
|
+
└── llm.call
|
|
247
|
+
"""
|
|
248
|
+
from agentforge._testing import FakeLLMClient # noqa: PLC0415
|
|
249
|
+
from agentforge.strategies.react import ReActLoop # noqa: PLC0415
|
|
250
|
+
from agentforge_core.contracts.tool import Tool # noqa: PLC0415
|
|
251
|
+
from agentforge_core.values.messages import LLMResponse, TokenUsage # noqa: PLC0415
|
|
252
|
+
from pydantic import BaseModel # noqa: PLC0415
|
|
253
|
+
|
|
254
|
+
exporter = _install_inmemory_provider()
|
|
255
|
+
|
|
256
|
+
class _SearchArgs(BaseModel):
|
|
257
|
+
query: str
|
|
258
|
+
|
|
259
|
+
class _SearchTool(Tool):
|
|
260
|
+
name = "search"
|
|
261
|
+
description = "echoes the query"
|
|
262
|
+
input_schema = _SearchArgs
|
|
263
|
+
|
|
264
|
+
async def run(self, query: str) -> str:
|
|
265
|
+
return f"got {query!r}"
|
|
266
|
+
|
|
267
|
+
fake = FakeLLMClient(
|
|
268
|
+
responses=[
|
|
269
|
+
LLMResponse(
|
|
270
|
+
content="I'll search.",
|
|
271
|
+
stop_reason="tool_use",
|
|
272
|
+
tool_calls=(ToolCall(id="t-1", name="search", arguments={"query": "x"}),),
|
|
273
|
+
usage=TokenUsage(input_tokens=5, output_tokens=3),
|
|
274
|
+
cost_usd=0.0,
|
|
275
|
+
model="fake",
|
|
276
|
+
provider="fake",
|
|
277
|
+
),
|
|
278
|
+
LLMResponse(
|
|
279
|
+
content="done",
|
|
280
|
+
stop_reason="end_turn",
|
|
281
|
+
usage=TokenUsage(input_tokens=4, output_tokens=2),
|
|
282
|
+
cost_usd=0.0,
|
|
283
|
+
model="fake",
|
|
284
|
+
provider="fake",
|
|
285
|
+
),
|
|
286
|
+
],
|
|
287
|
+
)
|
|
288
|
+
otel = OpenTelemetryHook(service_name="test", endpoint="http://localhost:4317")
|
|
289
|
+
async with Agent(
|
|
290
|
+
model=fake,
|
|
291
|
+
tools=[_SearchTool()],
|
|
292
|
+
strategy=ReActLoop(),
|
|
293
|
+
on_step=otel,
|
|
294
|
+
on_finish=otel,
|
|
295
|
+
) as agent:
|
|
296
|
+
await agent.run("find x")
|
|
297
|
+
|
|
298
|
+
finished = exporter.get_finished_spans()
|
|
299
|
+
by_name: dict[str, list] = {}
|
|
300
|
+
for s in finished:
|
|
301
|
+
by_name.setdefault(s.name, []).append(s)
|
|
302
|
+
|
|
303
|
+
# Root span
|
|
304
|
+
assert len(by_name["agent.run"]) == 1
|
|
305
|
+
# Two iterations: one with the tool_call, one terminating
|
|
306
|
+
assert len(by_name["strategy.iteration"]) == 2
|
|
307
|
+
# Two LLM calls (one per iteration)
|
|
308
|
+
assert len(by_name["llm.call"]) == 2
|
|
309
|
+
# One tool execution
|
|
310
|
+
assert len(by_name["tool.search"]) == 1
|
|
311
|
+
# llm.call spans carry provider + token attributes
|
|
312
|
+
llm_attrs = dict(by_name["llm.call"][0].attributes or {})
|
|
313
|
+
assert llm_attrs["agentforge.llm.provider"] == "fake"
|
|
314
|
+
assert llm_attrs["agentforge.llm.tokens_in"] == 5
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
@pytest.mark.asyncio
|
|
318
|
+
async def test_child_span_tree_via_tot_strategy():
|
|
319
|
+
"""Drive an Agent with the built-in ``TreeOfThoughts`` strategy
|
|
320
|
+
and assert ``strategy.iteration`` spans land under ``agent.run``
|
|
321
|
+
with ``agentforge.strategy=tot``.
|
|
322
|
+
"""
|
|
323
|
+
from agentforge._testing import FakeLLMClient # noqa: PLC0415
|
|
324
|
+
from agentforge.strategies.tot import TreeOfThoughts # noqa: PLC0415
|
|
325
|
+
from agentforge_core.values.messages import LLMResponse, TokenUsage # noqa: PLC0415
|
|
326
|
+
|
|
327
|
+
exporter = _install_inmemory_provider()
|
|
328
|
+
|
|
329
|
+
def _resp(content: str) -> LLMResponse:
|
|
330
|
+
return LLMResponse(
|
|
331
|
+
content=content,
|
|
332
|
+
stop_reason="end_turn",
|
|
333
|
+
usage=TokenUsage(input_tokens=5, output_tokens=3),
|
|
334
|
+
cost_usd=0.0,
|
|
335
|
+
model="fake",
|
|
336
|
+
provider="fake",
|
|
337
|
+
)
|
|
338
|
+
|
|
339
|
+
fake = FakeLLMClient(
|
|
340
|
+
responses=[
|
|
341
|
+
_resp('{"thoughts": [{"id": "t1", "content": "thought 1"}]}'),
|
|
342
|
+
_resp('{"scores": [{"branch_id": "t1", "score": 0.9, "reasoning": "ok"}]}'),
|
|
343
|
+
_resp("Final answer."),
|
|
344
|
+
]
|
|
345
|
+
)
|
|
346
|
+
otel = OpenTelemetryHook(service_name="test", endpoint="http://localhost:4317")
|
|
347
|
+
async with Agent(
|
|
348
|
+
model=fake,
|
|
349
|
+
tools=[],
|
|
350
|
+
strategy=TreeOfThoughts(branch_factor=1, depth=1, score_threshold=0.5),
|
|
351
|
+
on_step=otel,
|
|
352
|
+
on_finish=otel,
|
|
353
|
+
) as agent:
|
|
354
|
+
await agent.run("solve x")
|
|
355
|
+
|
|
356
|
+
finished = exporter.get_finished_spans()
|
|
357
|
+
by_name: dict[str, list] = {}
|
|
358
|
+
for s in finished:
|
|
359
|
+
by_name.setdefault(s.name, []).append(s)
|
|
360
|
+
|
|
361
|
+
assert len(by_name["agent.run"]) == 1
|
|
362
|
+
assert len(by_name["strategy.iteration"]) == 1
|
|
363
|
+
attrs = dict(by_name["strategy.iteration"][0].attributes or {})
|
|
364
|
+
assert attrs["agentforge.strategy"] == "tot"
|
|
365
|
+
assert attrs["agentforge.iteration"] == 0
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
@pytest.mark.asyncio
|
|
369
|
+
async def test_child_span_tree_via_multi_agent_strategy():
|
|
370
|
+
"""Drive an Agent with the built-in ``MultiAgentSupervisor`` and
|
|
371
|
+
assert ``strategy.iteration`` spans land with
|
|
372
|
+
``agentforge.strategy=multi_agent``.
|
|
373
|
+
"""
|
|
374
|
+
from agentforge._testing import FakeLLMClient # noqa: PLC0415
|
|
375
|
+
from agentforge.strategies._base import get_runtime # noqa: PLC0415
|
|
376
|
+
from agentforge.strategies.multi_agent import MultiAgentSupervisor # noqa: PLC0415
|
|
377
|
+
from agentforge_core.contracts.strategy import ReasoningStrategy # noqa: PLC0415
|
|
378
|
+
from agentforge_core.values.messages import LLMResponse, TokenUsage # noqa: PLC0415
|
|
379
|
+
from agentforge_core.values.state import Step as StepCls # noqa: PLC0415
|
|
380
|
+
|
|
381
|
+
exporter = _install_inmemory_provider()
|
|
382
|
+
|
|
383
|
+
class _Worker(ReasoningStrategy):
|
|
384
|
+
async def run(self, state):
|
|
385
|
+
get_runtime(state).budget.check()
|
|
386
|
+
state.steps.append(StepCls(iteration=1, kind="synthesize", content="ok", cost_usd=0.0))
|
|
387
|
+
return state
|
|
388
|
+
|
|
389
|
+
def _resp(content: str) -> LLMResponse:
|
|
390
|
+
return LLMResponse(
|
|
391
|
+
content=content,
|
|
392
|
+
stop_reason="end_turn",
|
|
393
|
+
usage=TokenUsage(input_tokens=5, output_tokens=3),
|
|
394
|
+
cost_usd=0.0,
|
|
395
|
+
model="fake",
|
|
396
|
+
provider="fake",
|
|
397
|
+
)
|
|
398
|
+
|
|
399
|
+
fake = FakeLLMClient(
|
|
400
|
+
responses=[
|
|
401
|
+
_resp('{"assignments": [{"worker": "a", "task": "subtask 1"}]}'),
|
|
402
|
+
_resp("aggregated answer."),
|
|
403
|
+
]
|
|
404
|
+
)
|
|
405
|
+
otel = OpenTelemetryHook(service_name="test", endpoint="http://localhost:4317")
|
|
406
|
+
async with Agent(
|
|
407
|
+
model=fake,
|
|
408
|
+
tools=[],
|
|
409
|
+
strategy=MultiAgentSupervisor(workers={"a": _Worker()}, max_rounds=1),
|
|
410
|
+
on_step=otel,
|
|
411
|
+
on_finish=otel,
|
|
412
|
+
) as agent:
|
|
413
|
+
await agent.run("big task")
|
|
414
|
+
|
|
415
|
+
finished = exporter.get_finished_spans()
|
|
416
|
+
by_name: dict[str, list] = {}
|
|
417
|
+
for s in finished:
|
|
418
|
+
by_name.setdefault(s.name, []).append(s)
|
|
419
|
+
|
|
420
|
+
assert len(by_name["agent.run"]) == 1
|
|
421
|
+
assert len(by_name["strategy.iteration"]) == 1
|
|
422
|
+
attrs = dict(by_name["strategy.iteration"][0].attributes or {})
|
|
423
|
+
assert attrs["agentforge.strategy"] == "multi_agent"
|
|
424
|
+
assert attrs["agentforge.iteration"] == 0
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
# --- content-based PII redaction (feat-009 v0.3 polish) --------
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def test_redact_value_patterns_masks_matching_values() -> None:
|
|
431
|
+
"""Values matching any regex in `redact_value_patterns` get
|
|
432
|
+
replaced wholesale — even when the key isn't in
|
|
433
|
+
`redact_fields`."""
|
|
434
|
+
h = OpenTelemetryHook(
|
|
435
|
+
service_name="test",
|
|
436
|
+
endpoint="http://localhost:4317",
|
|
437
|
+
redact_value_patterns=(
|
|
438
|
+
r"\b\d{3}-\d{2}-\d{4}\b", # US SSN
|
|
439
|
+
r"\b\d{16}\b", # Credit-card-like 16-digit run
|
|
440
|
+
r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}", # email
|
|
441
|
+
),
|
|
442
|
+
)
|
|
443
|
+
rendered = h._redact(
|
|
444
|
+
{
|
|
445
|
+
"ssn": "123-45-6789",
|
|
446
|
+
"card": "4111111111111111",
|
|
447
|
+
"email": "alice@example.com",
|
|
448
|
+
"innocent": "hello world",
|
|
449
|
+
"count": 7,
|
|
450
|
+
}
|
|
451
|
+
)
|
|
452
|
+
assert "ssn=<redacted>" in rendered
|
|
453
|
+
assert "card=<redacted>" in rendered
|
|
454
|
+
assert "email=<redacted>" in rendered
|
|
455
|
+
# Plain integers + harmless strings pass through.
|
|
456
|
+
assert "innocent='hello world'" in rendered
|
|
457
|
+
assert "count=7" in rendered
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def test_redact_value_patterns_default_none_is_passthrough() -> None:
|
|
461
|
+
"""Without `redact_value_patterns`, behaviour is identical to
|
|
462
|
+
v0.1 (key-only redaction)."""
|
|
463
|
+
h = OpenTelemetryHook(service_name="test", endpoint="http://localhost:4317")
|
|
464
|
+
assert h.redact_value_patterns == ()
|
|
465
|
+
rendered = h._redact({"email": "alice@example.com", "api_key": "shh"})
|
|
466
|
+
assert "email='alice@example.com'" in rendered
|
|
467
|
+
assert "api_key=<redacted>" in rendered
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
def test_redact_key_match_takes_precedence_over_value_match() -> None:
|
|
471
|
+
h = OpenTelemetryHook(
|
|
472
|
+
service_name="test",
|
|
473
|
+
endpoint="http://localhost:4317",
|
|
474
|
+
redact_value_patterns=(r"unused-pattern",),
|
|
475
|
+
)
|
|
476
|
+
rendered = h._redact({"api_key": "abc"})
|
|
477
|
+
# Key matches first; we never even check the value patterns.
|
|
478
|
+
assert "api_key=<redacted>" in rendered
|