LangChain 监控
- 作者仓库星标 0
- 作者更新于 实时读取
- 作者仓库 skills-registry
- 领域
- AI 智能
- 兼容 Agent
-
- Claude Code
- Cursor
- Cline
- Codex
- Windsurf
- Gemini CLI
- +20
- 信任分
- 88 / 100 · 社区维护
- 作者 / 版本 / 许可
- @tomevault-io · 未声明 license
- Token 消耗评级
- 中等消耗
- 接入复杂程度
- 需手动接入
- 是否需要外部 API Key
- 需要 · OpenAI
- 兼容的系统
- Docker
- 底层运行要求
- Python · Docker
- 文件与系统权限
-
- 只读
- 允许写入 / 修改
- 读取环境变量
- 网络行为
- 允许外网请求
- 安装命令数
- 26 条
档案由构建时根据 SKILL.md 与安装命令自动衍生,可能与作者实际意图存在差异。
需要注意: 未限定 allowed-tools,默认拥有全部工具权限。
---
name: langchain-agents-observability
description: Use when debugging an agent's behaviour, reading LangSmith traces, setting up tracing in product…
category: AI 智能
runtime: Python / Docker
---
# langchain-agents-observability 输出预览
## PART A: 任务判断
- 适用问题:提示词、Agent 工作流、模型评估或自动化推理。
- 输入要求:目标材料、限制条件、期望输出和验收方式。
- 证据边界:围绕“Required environment variables / Where traces live / What middleware looks like in traces”读取原文规则,不把推断写成作者承诺。
## PART B: 执行结果
- **01** 任务判断:确认你的需求是否属于提示词、Agent 工作流、模型评估或自动化推理,并标出输入、限制和预期结果。
- **02** 执行计划:优先按“Required environment variables / Where traces live / What middleware looks like in traces”拆成步骤,说明每一步会读取什么、修改什么、产出什么。
- **03** 交付结果:给出可复制的命令、文件改动、检查清单或内容草稿,并说明如何继续迭代。
- **04** 风险边界:结合 读取文件、写入/修改文件、读取环境变量、会按任务需要访问外部网络、需要准备 OpenAI API Key 给出执行前确认项。
## Running Rules
- 读取文件、写入/修改文件、读取环境变量;会按任务需要访问外部网络;需要准备 OpenAI API Key。
- 先小样例验证,再放大到真实任务。
- 交付时同时给结果、检查口径和下一步迭代建议。 原文没有稳定的斜杠命令要求。安装验证后通常全局生效,直接在对话里点名这个 Skill 并描述任务即可。
告诉 Agent 目标文件或材料、期望结果、不可改范围、是否允许联网或执行命令。本 Skill 的权限画像是:读取文件、写入/修改文件、读取环境变量。
先用一个小任务确认它会围绕“Required environment variables / Where traces live / What middleware looks like in traces”工作;涉及文件或命令时,先看 diff、日志、预览或测试结果。
检查最终产物是否包含明确结果、必要证据和下一步动作;如果输出泛泛而谈,就补充输入、边界和验收标准后重跑。
---
name: langchain-agents-observability
description: Use when debugging an agent's behaviour, reading LangSmith traces, setting up tracing in product…
category: AI 智能
source: tomevault-io/skills-registry
---
# langchain-agents-observability
## 什么时候使用
- 把 AI / Agent方向的常用动作沉淀成 Agent 可调用的技能 适合处理AI Agent、提示词、模型评估与自动化推理,核心价值是把输入、判断、执行、验证和交付边界固定下来,避免 Agent 泛泛回答。 把任务拆成可执行、可检查…
- 面向提示词、Agent 工作流、模型评估或自动化推理,优先处理能明确输入、步骤和验收标准的工作。
## 需要提供什么
- 目标材料、目录范围、期望结果和不可改动内容。
- 是否允许联网、执行命令、读写文件或调用外部服务。
## 执行规则
- 围绕「Required environment variables / Where traces live / What middleware looks like in traces」组织步骤,不把推断写成作者事实。
- 读取文件、写入/修改文件、读取环境变量;会按任务需要访问外部网络;需要准备 OpenAI API Key。
- 先跑小样例,确认结果可检查后再扩大任务范围。
## 输出要求
- 给出最终产物、关键证据、验证方式和下一步动作。
- 信息不足时标记 unknown,不编造命令、平台或依赖。 作者原文负责流程事实;仓库文件负责来源和命令;流狐只补充适用场景、限制和质量判断。
skill "langchain-agents-observability" {
输入层 -> 用户目标 + 目标文件 + 禁止范围 + 验收标准
上下文层 -> Required environment variables / Where traces live / What middleware looks like in traces
规则层 -> SKILL.md 触发条件 / 执行顺序 / 输出格式
运行层 -> Python / Docker | 读取文件、写入/修改文件、读取环境变量 | 会按任务需要访问外部网络
安全层 -> 需要准备 OpenAI API Key + 小任务验证 + diff / 日志复核
输出层 -> 可复制结果 + 检查清单 + 下一步迭代
} Observability
LangChain ecosystem projects trace through LangSmith by default. Tracing turns on automatically when LANGSMITH_TRACING=true is set — no code changes required. Every agent.invoke(...) becomes one trace; tool calls, sub-agent delegations, and middleware hooks are nested spans.
For production, you'll often want OTEL on top of (or instead of) LangSmith.
Required environment variables
LANGSMITH_API_KEY=ls_... # required
LANGSMITH_TRACING=true # enables capture
LANGSMITH_PROJECT=my-agent # bucket name in the LangSmith UI
If LANGSMITH_TRACING is unset or false, the agent runs but no traces are captured. The agent does not fail — silent observability gap. Always set it explicitly.
Where traces live
LangSmith UI → the project named in LANGSMITH_PROJECT. Filter by experiment, time range, or status. Each trace is a tree:
- Top-level:
agent.invoke(...). - Children: middleware
wrap_*calls, model calls, tool calls, sub-agenttaskinvocations. - Leaves: token streams, tool inputs/outputs, errors with stack traces.
What middleware looks like in traces
Each middleware that wraps a model or tool call appears as its own span. Useful for diagnosing "why did this take so long" — you can see exactly which retry or fallback fired.
Manual span instrumentation
from langsmith import traceable
@traceable
def my_helper(x: int) -> int:
return x * 2
@traceable works on any callable; it shows up as its own span under the parent trace. Use it for application-specific operations not auto-captured (DB queries, external API calls outside of LangChain tools).
OpenTelemetry integration
LangSmith can emit OTLP traces alongside its native ones, so existing observability backends (Jaeger, Tempo, Honeycomb, Datadog) get the data:
export OTEL_EXPORTER_OTLP_ENDPOINT="https://api.honeycomb.io"
export OTEL_EXPORTER_OTLP_HEADERS="x-honeycomb-team=$HONEYCOMB_API_KEY"
export LANGSMITH_OTEL_ENABLED=true
When LANGSMITH_OTEL_ENABLED=true, traces are dual-emitted: to LangSmith AND to your OTLP collector. Spans use OpenTelemetry semantic conventions for AI / LLM workflows.
Distributed tracing across services
If your agent calls another service (e.g. a separate retriever microservice), propagate the trace context so spans link up:
from opentelemetry import propagate, trace
# When making an outbound call:
headers = {}
propagate.inject(headers) # adds traceparent header
requests.post("https://retriever.internal/", headers=headers, json={...})
The downstream service should call propagate.extract(request.headers) and create a span as a child.
Cloud Run-specific tracing
Cloud Run automatically adds X-Cloud-Trace-Context to incoming requests. To correlate Cloud Run access logs with LangSmith spans, log the trace ID at the start of each request handler:
import os, structlog
log = structlog.get_logger()
@app.post("/invoke")
def invoke(req, request: Request):
trace_header = request.headers.get("X-Cloud-Trace-Context", "")
cloud_trace_id = trace_header.split("/")[0]
log.bind(cloud_trace_id=cloud_trace_id, thread_id=req.thread_id).info("invoke")
...
Common failure-mode diagnostics
| Symptom | Likely cause | First thing to check |
|---|---|---|
agent import fails |
Missing dep, wrong path, syntax error | python -c "from agent.agent import agent" from project root |
| Smoke evals fail with auth error | Wrong / missing provider key | python -c "import os; print(bool(os.getenv('OPENAI_API_KEY')))" |
| Smoke evals fail with rate-limit | Provider rate limit during eval | Drop dataset to 1 row; add ModelRetryMiddleware; retry |
langgraph dev hangs on start |
langgraph.json graph path wrong |
cat langgraph.json — verify ./agent/agent.py:agent exists |
langgraph dev reload stops |
Latest edit broke import | Check terminal for the exception |
| Docker container crashes on boot | .env not passed at run time |
docker logs <container> |
| Cloud Run service doesn't start | Listening on 127.0.0.1 instead of 0.0.0.0:$PORT | gcloud run services logs read SERVICE |
| Trace shows the LLM but no tool calls | Tool not registered with the model | bind_tools(TOOLS) (LangGraph) or tools=... arg to create_agent |
| Trace shows tool calls but they fail | Tool raised an exception | Click the failing span — exception + traceback are captured |
| Conversation memory lost between turns | No checkpointer or thread_id mismatch | compile(checkpointer=...) AND config={"configurable": {"thread_id": ...}} on every invoke |
| Token cost suddenly spikes | No SummarizationMiddleware; long context |
Add it; trigger at ~8000 tokens, keep last 20 messages |
| Random 30-60s pauses in production | Provider rate-limit handled by retry middleware | Check trace — ModelRetryMiddleware span shows the backoff sleeps |
HITL interrupt() never resumes |
No checkpointer at compile time | HumanInTheLoopMiddleware requires a checkpointer |
| Costs much higher than expected | Retries multiplying. No ModelCallLimitMiddleware |
Add it; cap at e.g. run_limit=50 |
Quick local verification (no LangSmith needed)
python -c "
from agent.agent import agent
result = agent.invoke({'messages': [{'role': 'user', 'content': 'hello'}]})
print(result)
"
If this fails, the agent is broken regardless of tracing. Fix it first.
Production alerting
LangSmith UI supports alerts on:
- p95 latency exceeding a threshold.
- Error rate exceeding a threshold (% of runs that throw).
- Specific evaluator scores dropping below a threshold (eval-as-monitor pattern).
Configure these per project in the LangSmith UI. For escalation to PagerDuty / Slack, use LangSmith's webhook integrations or pipe traces through OTEL into your existing alert stack.
Trace sampling for high-volume services
LangSmith captures every trace by default. For very high traffic (>100 RPS sustained), sampling is supported via the LANGSMITH_SAMPLING_RATE env var (e.g. 0.1 = 10%). Trace integrity is preserved for sampled traces (full tree), so this is safe — you just see fewer of them.
Trace URLs in code
When LANGSMITH_TRACING=true, the SDK prints a trace URL to stderr after each agent.invoke(...). Capture it in production logs for debugging:
import sys, contextlib, io
buf = io.StringIO()
with contextlib.redirect_stderr(buf):
result = agent.invoke({"messages": [...]})
trace_url = next((line for line in buf.getvalue().splitlines() if "smith.langchain.com" in line), "")
log.info("agent_invoked", trace_url=trace_url)
Source: cwijayasundara/agent_cli_langchain — distributed by TomeVault.
先判断是否适合
作者设计意图
作者的方法与取舍
边界和复核