tracespan —— 无侵入的 Agent 行为追踪库
记录 Agent 每一次运行的 trace(主表) 与 span(附表),覆盖:
- 运行参数(模型、温度、thread_id、工具实参、token 用量……)
- 耗时(每一步与整次运行)
- 是否失败(异常类型与消息,追踪层不吞业务异常)
- 用户
user_id、agent_id、session_id - 输入输出、标签、元数据
存储层是抽象基类 + 多实现,接入方式是无感补丁,查询层提供面向排错的高层接口。
一、安装与目录
pip install tracespan # 从 PyPI 安装(核心零依赖)
pip install 'tracespan[mysql]' # 可选:MySQL 后端
pip install 'tracespan[postgres]'# 可选:PostgreSQL 后端
# 或从源码安装
cd trace
pip install -e .
trace/
├── tracespan/
│ ├── models.py # Trace / Span / Status / SpanKind / 过滤器
│ ├── serialization.py # 安全 JSON 序列化(截断、降级)
│ ├── context.py # ContextVar 传播 trace/span/身份
│ ├── tracer.py # Tracer、@traced、全局配置
│ ├── query.py # 查询与排错接口
│ ├── store/
│ │ ├── base.py # ★ TraceStore 抽象基类
│ │ ├── sql.py # SQL 通用实现(方言适配)
│ │ ├── file.py # 本地 JSONL
│ │ ├── sqlite.py # SQLite
│ │ ├── mysql.py # MySQL
│ │ └── postgres.py # PostgreSQL
│ └── instrumentation/
│ ├── patch.py # 通用无感补丁
│ ├── callbacks.py # LangChain 回调 -> span(chain/llm/tool)
│ └── langchain.py # LangChain / LangGraph 适配
├── examples/
│ ├── quickstart.py
│ ├── langchain_integration.py
│ ├── langgraph_sqlite.py # LangGraph 接入 + SQLite 落库
│ └── deepagents_sqlite.py # deepagents 接入 + SQLite 落库
└── tests/
二、30 秒上手
import tracespan as at
tracer = at.configure(dir="./traces") # 本地文件;也可 db_path="traces.db"
with at.bind_run(user_id="u-1", agent_id="cs", session_id="s-1"):
with tracer.trace("customer_service", input={"q": "退款"}) as trace:
with tracer.span("intent", kind=at.SpanKind.LLM, params={"model": "gpt-4o"}):
pass
with tracer.span("refund_api", kind=at.SpanKind.TOOL,
params={"args": {"order_id": "A100"}}):
pass
q = at.query(tracer.store)
print(q.summary()) # 总数 / 成功 / 失败 / 失败率 / 平均与 P95 耗时
print(q.format_errors()) # 可读的失败报告(含具体失败 span)
print(q.format_trace(trace.trace_id))
运行示例:
../venv/bin/python examples/quickstart.py
deepagents + SQLite 完整示例
../venv/bin/python examples/deepagents_sqlite.py # 离线假模型,无需 Key
DEEPSEEK_API_KEY=sk-... ../venv/bin/python examples/deepagents_sqlite.py --real
一次 agent.invoke(...) 自动落一条 trace;借助注入的回调处理器,deepagents 内部的
chain → model → llm / tools → tool 也会落成带父子关系与耗时的 span 树:
import tracespan as at
tracer = at.configure(db_path="traces.db") # SQLite
at.instrument_langchain() # invoke 补丁 + 内部回调,业务代码不用改
with at.bind_run(user_id="u-1001", agent_id="demo_deep_agent", session_id="s-7"):
result = agent.invoke({"messages": [HumanMessage(content="查订单 A100")]}, config={...})
print(at.query(tracer.store).format_trace(trace_id))
instrument_langchain(inject_callbacks=False) 可关闭内部回调,只记录最外层 invoke。
三、存储层:基类 + 多实现
所有后端实现同一个 TraceStore 接口,替换后端不需要改任何业务代码:
| 实现 | 说明 | 依赖 |
|---|---|---|
FileTraceStore(dir=...) |
本地 append-only JSONL,零依赖、开箱即用 | 无 |
SQLiteTraceStore(db_path=...) |
本地数据库,线程安全 | 标准库 sqlite3 |
MySQLTraceStore(host=..., user=..., database=...) |
MySQL / MariaDB | pymysql |
PostgresTraceStore(dsn=...) |
PostgreSQL | psycopg |
# 同一套 API,随便切换
store = at.SQLiteTraceStore("traces.db")
store = at.MySQLTraceStore(host="127.0.0.1", user="root", password="...", database="trace")
store = at.PostgresTraceStore(dsn="postgresql://user:pwd@host:5432/trace")
tracer = at.Tracer(store) # 上层完全不变
自定义后端
继承 TraceStore,实现 9 个方法即可(save_trace / save_span / get_trace / get_span / get_spans / query_traces / query_spans / delete_trace / close):
from tracespan.store import TraceStore
class MyStore(TraceStore):
def save_trace(self, trace): ...
...
若是 SQL 数据库,更省事的做法是继承 tracespan.store.sql.SQLTraceStore,
只需提供 _connect()、SCHEMA、PLACEHOLDER 与 CONFLICT_STYLE。
表结构
trace(一次 Agent 运行一行)
| 字段 | 说明 |
|---|---|
trace_id / name / parent_trace_id |
主键 / 名称 / 父链路 |
user_id / agent_id / session_id |
运行身份(需求字段) |
status / is_failed / error |
running / ok / error、失败布尔值、异常信息 |
start_time / end_time / duration_ms |
时间与耗时 |
input_json / output_json / params_json |
输入输出与运行参数(JSON) |
tags_json / metadata_json |
标签与元数据 |
span(一次步骤一行,通过 parent_span_id 组成调用树)
| 字段 | 说明 |
|---|---|
span_id / trace_id / parent_span_id |
主键 / 所属 trace / 父 span |
name / kind |
名称 / agent | chain | llm | tool | retrieval | business | custom |
user_id / agent_id / session_id |
冗余存储,便于直接按身份过滤 span |
status / is_failed / error / duration_ms |
同 trace |
input_json / output_json / params_json |
工具实参、模型参数、token 用量等 |
索引:user_id / agent_id / session_id / status / kind / trace_id / parent_span_id。
四、无感接入(核心)
方式一:框架级一次性打补丁(推荐)
现有代码里 agent.invoke(...) / await agent.ainvoke(...) 一行都不用改:
import tracespan as at
at.configure(db_path="traces.db")
at.instrument_langchain() # 给 Runnable / Pregel / CompiledStateGraph 打补丁
# ... 你的原有代码,照常调用 agent.invoke(...)
需要停用时 at.uninstrument_langchain()。默认不包裹 stream/astream,
避免 LangGraph 内部 invoke 与 stream 互相调用时产生重复 span;如需要可传 patch_stream=True。
方式二:任意框架/任意方法
at.instrument(MyFramework, "run", name="my_agent", kind=at.SpanKind.AGENT,
params=lambda owner, args, kwargs: {"model": kwargs.get("model")})
支持同步、异步、生成器与异步生成器方法,打补丁是幂等的。
方式三:装饰器
@at.traced(kind=at.SpanKind.TOOL, agent_id="search")
def search(query: str):
...
身份透传
with at.bind_run(user_id="u-7", agent_id="cs", session_id="s-9", env="prod"):
agent.invoke(...)
bind_run 绑定的身份与 env="prod" 这类 baggage 会自动进入其下所有 trace/span
的对应字段与 params,异步任务之间互不串线。
五、查询与排错接口
q = at.query(store)
q.traces(user_id="u-1", agent_id="cs", failed_only=True, min_duration_ms=1000)
q.spans(trace_id="...", kind=at.SpanKind.TOOL, failed_only=True)
q.by_user("u-1") / q.by_agent("cs") / q.by_session("s-9")
q.failed_traces() / q.failed_spans() / q.errors()
q.slow_traces(min_duration_ms=1000)
q.summary() # {total, ok, failed, error_rate, avg/p95_duration_ms}
q.tree(trace_id) / q.flat_tree(trace_id)
q.format_errors() # 人类可读的失败清单,含失败 span
q.format_trace(trace_id) # 带耗时与错误的调用树
存储层也提供快捷方法:store.find_errors()、store.trace_tree(trace_id)、store.list_traces()。
六、设计取舍
- 追踪不能影响业务:序列化对未知类型降级为截断字符串;异常落库后原样抛出。
- 运行中可观察:trace/span 在开始时先写一条
running,结束时 upsert 更新, 因此长任务在执行过程中就能被查询到。 - 文本截断:默认单字段 8000 字符,防止大 prompt / 大响应撑爆存储。
- 零强制依赖:核心只用标准库;MySQL/PostgreSQL/LangChain 均为可选依赖。
- 一个实现一种职责:存储、上下文、追踪、接入、查询各自独立,可单独替换。
七、验证
cd trace
../venv/bin/python -m unittest discover -s tests -v # 17 个测试全部通过
../venv/bin/python -m unittest tests.test_langgraph -v # 只跑 LangGraph 用例
../venv/bin/python examples/quickstart.py
../venv/bin/python examples/langchain_integration.py
../venv/bin/python examples/langgraph_sqlite.py
../venv/bin/python examples/deepagents_sqlite.py
examples/langgraph_sqlite.py 用条件路由图演示 classify(llm) → order(tool),
运行后可在 ./tracespan.db 中查看 trace 与 span 树。
tests/test_langgraph.py 覆盖 LangGraph 的同步 invoke、异步 ainvoke、节点异常、
调用树与查询报告,使用离线假模型并真实写入 SQLite。
Metadata
Release files for tracespan 0.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| tracespan-0.2.0.tar.gz | 41.6 kB | Without provenance | Details for tracespan-0.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| tracespan-0.2.0-py3-none-any.whl | Python 3 | none | any | Details for tracespan-0.2.0-py3-none-any.whl |
Total release size: 83.8 kB
Release files / tracespan-0.2.0.tar.gz
| Download URL | tracespan-0.2.0.tar.gz |
|---|---|
| Size | 41.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
688dfa4b202280339452565b224515db0ed517d311ae3a65059c7789486bea13
|
|
BLAKE2b-256 checksum How to use checksums |
6164b7f6c0c5e34c8e96fe0d0ca41780124f3aced326429d730d7a30dd9210ad
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.11.7
|
Release files / tracespan-0.2.0-py3-none-any.whl
| Download URL | tracespan-0.2.0-py3-none-any.whl |
|---|---|
| Size | 42.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
57ccc463af1e6250a5b9057588e39618b3deebabd0315fbe64e91bf70985bd2b
|
|
BLAKE2b-256 checksum How to use checksums |
d98c2fc3003a70f3fbcf155754382dc653e03ad3da6e82258a4d9474a7941055
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.11.7
|
Security for tracespan 0.2.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.