Skip to main content

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、全局配置
│   ├── writer.py            # ★ 异步写入队列(后台线程、有界队列、失败只记日志)
│   ├── logging_utils.py     # setup_logging():让写入失败在线上可见
│   ├── 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

tracer.flush()              # 默认异步入库;脚本里查库前 flush 一次(线上服务不需要)

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={...})

tracer.flush()                                # 等异步入库排空(应用里不必显式调用)
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()。


六、异步写入与线上安全

默认就是异步入库:业务线程只把记录塞进内存队列(put_nowait,不阻塞), 由后台守护线程 tracespan-writer 批量落库。追踪层任何一环出问题都不会冒泡到业务。

tracer = at.configure(db_path="traces.db")          # async_write=True(默认)
tracer = at.configure(db_path="traces.db", async_write=False)   # 同步,测试/脚本用

失败隔离的四道闸门:

场景 行为
落库抛异常(DB 挂了、表不存在、磁盘满) 记 ERROR 日志 + errors 计数,不抛给业务,进程继续跑
存储长时间不可用 失败日志限流:前 5 条带完整堆栈,之后每 30 秒汇总一条,不会刷爆日志
队列满(存储跟不上) 丢弃新记录 + dropped 计数,告警限流 30 秒一条,不阻塞、不刷屏
业务代码抛异常 照常落库为 error,然后把原异常原样抛出,顺序与语义不变
进程退出 atexit 自动 flush(2 秒预算),尽力排空,退出阶段不再抛错

几个关键细节:

  • 入队即快照。同一条 trace/span 在运行中还会被继续修改(mark_ok 写 output、补 params), 入队时复制一份,后台线程永远读不到"正在被改"的对象,也不会撞上容器并发修改。
  • 不阻塞启动线程。队列上限 queue_size=10000,后台按 batch_size=200 批量取出, 空闲 flush_interval=0.2s 轮询一次,对业务延迟的影响可以忽略。
  • 可观测。tracer.producer_stats() 直接给出队列指标,方便打进 Prometheus 之类的监控。
tracer.producer_stats()
# {'submitted': 1024, 'written': 1020, 'pending': 4, 'dropped': 0, 'errors': 0, 'queue_size': 10000}

tracer.flush()          # 等队列排空(脚本/测试查库前用)
tracer.close()          # 停机:停线程 + 排空 + 关 store,幂等

dropped / errors 一直上涨,说明存储性能跟不上或配置有误——这两个计数就是线上告警抓手。

日志默认落在 tracespan / tracespan.writer 命名空间,库不会去动宿主项目的 logging 配置。 如果宿主没配 handler,ERROR 会走 logging.lastResort 打到 stderr;想统一格式就显式打开:

at.setup_logging("INFO")     # 只挂载 tracespan 命名空间,不影响其它 logger

调优参数(configure(...) 或 Tracer(...) 都可传):

参数 默认 说明
async_write True 总开关,False 回到同步写
queue_size 10000 队列上限,按峰值写入量给
batch_size 200 单批最多处理条数
flush_interval 0.2 后台空闲轮询间隔(秒)
error_log_burst 5 前 N 条落库失败打全量堆栈,之后 30 秒一条汇总
owns_store True configure(store=...) 时为 False,避免误关外部连接

重复调用 configure() 是安全的:旧的全局 Tracer 会被关闭(后台线程退出,不漏线程), 但不会关闭你自己传进去的 store。

实测效果(examples/async_vs_sync.py,存储每次写入故意延迟 5ms,1200 次落库):

[同步] 业务耗时    8318.6ms  落库 1200 次
[异步] 业务耗时      44.9ms  落库 1200 次  (flush=ok)
=> 业务线程快了 185.4×,省下约 8274ms

[坏存储] 业务照常完成 100 次调用,未抛任何异常
[坏存储] 落库失败 1200 次;ERROR 日志只打出 5 条(前 5 条带堆栈,之后限流)

七、设计取舍

  • 追踪不能影响业务:写入默认异步 + 队列有界 + 失败只记日志;序列化对未知类型降级为截断字符串; 业务异常落库后原样抛出。
  • 运行中可观察:trace/span 在开始时先写一条 running,结束时 upsert 更新, 因此长任务在执行过程中就能被查询到。
  • 文本截断:默认单字段 8000 字符,防止大 prompt / 大响应撑爆存储。
  • 零强制依赖:核心只用标准库;MySQL/PostgreSQL/LangChain 均为可选依赖。
  • 一个实现一种职责:存储、上下文、追踪、接入、查询各自独立,可单独替换。

八、验证

cd trace
../venv/bin/python -m unittest discover -s tests -v     # 27 个测试全部通过
../venv/bin/python -m unittest tests.test_langgraph -v  # 只跑 LangGraph 用例
../venv/bin/python -m unittest tests.test_async_writer -v  # 只跑异步写入用例
../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
../venv/bin/python examples/async_vs_sync.py            # 同步/异步耗时对比 + 失败隔离

examples/langgraph_sqlite.py 用条件路由图演示 classify(llm) → order(tool), 运行后可在 ./tracespan.db 中查看 trace 与 span 树。

tests/test_langgraph.py 覆盖 LangGraph 的同步 invoke、异步 ainvoke、节点异常、 调用树与查询报告,使用离线假模型并真实写入 SQLite。

tests/test_async_writer.py 覆盖异步写入的关键保证:入队不阻塞、flush 后可见、 落库失败只记日志不抛出、失败日志限流、队列满丢弃、入队快照、重复 configure 不漏线程。

Metadata

Release files for tracespan 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for tracespan 0.3.0
File Size Uploaded Provenance Actions
tracespan-0.3.0.tar.gz 52.4 kB Without provenance Details for tracespan-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for tracespan 0.3.0
File Interpreter ABI Platform Actions
tracespan-0.3.0-py3-none-any.whl Python 3 none any Details for tracespan-0.3.0-py3-none-any.whl

Total release size: 102.6 kB

Release files / tracespan-0.3.0.tar.gz

Download URL tracespan-0.3.0.tar.gz
Size 52.4 kB
Tags Source
SHA-256 checksum
How to use checksums
313aba3e71db6151fd7b559a609b8e595273d42c0f7873b9bfe5cf39bc5f0955
BLAKE2b-256 checksum
How to use checksums
6cd8f5dc6aa48e6bed09e71bea2c5c5fa475f23c340cad48f46b69eea295436c
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.3.0-py3-none-any.whl

Download URL tracespan-0.3.0-py3-none-any.whl
Size 50.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
fb19e68f26b153ca5d94e69baf9f13d1ad199d69206bc65917cb133361534bf4
BLAKE2b-256 checksum
How to use checksums
3f97bdcc23183a9142a03ee7f4b977648190eb6ec9b691a0d14fcce95f6ae13c
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.3.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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page