Skip to main content

tracespan —— 无侵入的 Agent 行为追踪库

记录 Agent 每一次运行的 trace(主表) 与 span(附表),覆盖:

  • 运行参数(模型、温度、thread_id、工具实参、token 用量……)
  • 耗时(每一步与整次运行)
  • 是否失败(异常类型与消息,追踪层不吞业务异常)
  • 用户 user_id、agent_id、session_id
  • 输入输出、标签、元数据

存储层是抽象基类 + 多实现,接入方式是无感补丁,查询层提供面向排错的高层接口, 写入默认异步且失败隔离——落库出错只记日志,不影响业务逻辑(极端情况如进程被强杀、 队列打满时可能丢数据,见第六节)。

调用树用 dotted_order 一个字符串编码完整路径(ORDER BY 即可还原,不依赖父节点先落库), 支持按 trace 一致性采样、单 trace span 熔断,以及用 HTTP header 跨服务接续同一条调用链。


一、安装与目录

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  # 无感接入 + MySQL 落库
│   ├── langgraph_sqlite.py       # LangGraph 接入 + SQLite 落库
│   ├── deepagents_sqlite.py      # deepagents 接入 + SQLite 落库
│   └── async_vs_sync.py          # 同步/异步写入耗时对比
└── 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)   # 上层完全不变

MySQL 的 CREATE DATABASE 不在建表语句里,database 必须已存在; 拿不准就先用 CREATE DATABASE IF NOT EXISTS trace 建好,或参考 examples/langchain_integration.py 里的 ensure_database()。 表结构(含索引)由 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 标签与元数据
dotted_order 根节点的路径串,跨服务串联时作为子 trace 的前缀

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 用量等
dotted_order 完整路径串,ORDER BY dotted_order 即可还原整棵调用树

索引:user_id / agent_id / session_id / status / kind / trace_id / parent_span_id / dotted_order。

老库升级:0.3.x 建的库没有 dotted_order 列,新版本打开时会自动 ALTER TABLE 补列并建索引, 不需要手工迁移;补列失败也不会阻断启动,老数据仍可按 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 秒预算),尽力排空,退出阶段不再抛错

说清楚"不丢"的边界:以上保证的是"不影响业务",不等于"数据一定不丢"。 进程被 kill -9、容器被冻结、队列打满丢弃记录这几种情况下 trace 会缺失。 serverless(Lambda / 云函数)尤其要注意:函数返回后实例可能立刻被回收, 请在返回前显式 tracer.flush(),否则 atexit 的 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,避免误关外部连接
sample_rate None 采样率 0~1,按 trace 一致性采样;None/1 表示全量
max_spans_per_trace 10000 单条 trace 的 span 上限,防跑飞的重试循环写爆表

重复调用 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 条带堆栈,之后限流)

七、调用树排序、采样与跨服务追踪

这一节的三项能力参考了 LangSmith 的实现(详见 docs/LANGSMITH.md): 用 dotted_order 一个字符串还原调用树、按 trace 做一致性采样、把上下文塞进 HTTP header 跨服务传递。

7.1 dotted_order:一个字符串就能还原树

每个 span 自动生成 dotted_order,格式是「父路径 + . + 本节点」:

根 span : 20261119T143012123456Z<trace_id>.20261119T143012345678Z<span_id>
子 span : ...父的那一串....20261119T143600001234Z<span_id>
孙 span : ...再往后接一段...

时间戳定长、UTC、微秒精度,因此字符串字典序 == 时间先后顺序。于是:

-- 一句 SQL 就能按「深度优先 + 同级按时间」取出整棵树,不需要 JOIN 或递归 CTE
SELECT * FROM tracespan_span WHERE trace_id = ? ORDER BY dotted_order;
spans = store.get_spans(trace_id)       # 或 store.query_spans(...)
tree = at.build_tree(spans)             # 内部按 dotted_order 排序后组树
at.sort_spans(spans)                    # 只要排序好的扁平列表

span.depth                              # 层级:根 span 为 0,其子为 1

历史数据(没有 dotted_order 的旧记录)会自动退回 start_time 排序, parent_span_id 也一直保留,所以新老数据都能组树,不强制迁移。

7.2 按 trace 一致性采样

tracer = at.configure(db_path="traces.db", sample_rate=0.1)   # 只记录 10%
  • 采样键是 trace_id,用 SHA-256 做确定性哈希,因此同一条 trace 的父子 span 要么全采、要么全丢, 不会出现「有子节点没父节点」的残缺树,也不会因为重启而前后不一致。
  • 被丢掉的 trace 完全不产生写入,但 ContextVar 上下文照常传递,业务代码无感知、嵌套关系照常正确。
  • sample_rate=None 或 1 表示全量;0 表示只观察不记录(压测时很好用)。

7.3 单 trace 熔断

tracer = at.configure(db_path="traces.db", max_spans_per_trace=2000)

失控的重试循环 / 递归 Agent 会在一条 trace 里产生几十万 span,直接打爆存储。 超过上限后:不再写入新 span,但只告警一次,业务照常跑。

# tracespan: trace 3f2a... 的 span 数已达上限 2000,后续 span 不再写入
#            (检查是否有失控的重试/循环;可调大 max_spans_per_trace)

7.4 跨服务:把调用树「背」在 header 里

上游服务:

import requests, tracespan as at

with at.bind_run(user_id="u-1", agent_id="order", session_id="s-1"):
    with at.get_tracer().span("call_risk_service"):
        headers = at.headers_of_current_context()      # {'tracespan-context': '...'}
        requests.post("http://risk/api/check", json=body, headers=headers)

下游服务(换进程、换服务、换语言都能接):

import tracespan as at

ctx = at.TraceContext.from_headers(request.headers)    # 大小写不敏感,坏 header 返回 None
with at.bind_context(ctx):
    with at.get_tracer().span("risk_check"):           # 自动挂到上游那个 span 下面
        ...

下游新建的 trace/span,其 dotted_order 会以上游节点为前缀,两边的数据落到同一个库里就能拼成一棵树。 user_id / agent_id / session_id / baggage / 采样决定 一并传过去,不会因为跨服务就丢身份。


八、设计取舍

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

九、验证

cd trace
../venv/bin/python -m unittest discover -s tests -v     # 45 个测试(MySQL 未配置时 skip 3 个)
../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/langgraph_sqlite.py
../venv/bin/python examples/deepagents_sqlite.py
../venv/bin/python examples/async_vs_sync.py            # 同步/异步耗时对比 + 失败隔离

# MySQL 集成测试与示例:不配环境变量时自动 skip
export TRACESPAN_MYSQL_HOST=127.0.0.1 TRACESPAN_MYSQL_USER=root \
       TRACESPAN_MYSQL_PASSWORD=你的密码 TRACESPAN_MYSQL_DB=tracespan_test
../venv/bin/python -m unittest tests.test_mysql -v
../venv/bin/python examples/langchain_integration.py

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

examples/langchain_integration.py 用 MySQL 做存储,连接信息全部走 TRACESPAN_MYSQL_HOST/PORT/USER/PASSWORD/DB 环境变量(密码不落代码), 库不存在会自动 CREATE DATABASE IF NOT EXISTS,表由 store 初始化时自动创建。

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

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

tests/test_mysql.py 是真实 MySQL 的集成测试(建表、upsert、失败查询、调用树、 级联删除),不配 TRACESPAN_MYSQL_* 环境变量时整组 skip。


延伸阅读

  • docs/LANGSMITH.md:LangSmith 是怎么做 Agent 追踪的—— dotted_order 如何用一个字符串还原调用树、客户端队列/攒批/压缩链路、 按 trace 的一致性采样、跨进程 header 传播,以及与 tracespan 的逐项对照和演进建议。
  • docs/PUBLISHING.md:发布到 PyPI 的完整流程与踩坑记录。

Metadata

Release files for tracespan 0.4.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.4.0
File Size Uploaded Provenance Actions
tracespan-0.4.0.tar.gz 65.9 kB Without provenance Details for tracespan-0.4.0.tar.gz

Built distribution (wheel)

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

Total release size: 124.0 kB

Release files / tracespan-0.4.0.tar.gz

Download URL tracespan-0.4.0.tar.gz
Size 65.9 kB
Tags Source
SHA-256 checksum
How to use checksums
15bdafd4e478735ef2c46d40b082c6926e853e93d58ab254c1d81ccbc4899e8d
BLAKE2b-256 checksum
How to use checksums
42296e86f8b80be52eaf0ac1ea66d5c16d2fac6350b7c5af6d2657f2120eb56c
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.4.0-py3-none-any.whl

Download URL tracespan-0.4.0-py3-none-any.whl
Size 58.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
fc6ae9dfd3030b50706974ee7faf2be8c48b0f6caf20858e1a64acf585bfb5b4
BLAKE2b-256 checksum
How to use checksums
9ac286b04a49d1d5fa86e16e366a5cb8f85468595fed4674c4e84c776ea3e04d
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.4.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