LangChain 助手
- 作者仓库星标 0
- 作者更新于 实时读取
- 作者仓库 skills-registry
- 领域
- 写作
- 兼容 Agent
-
- Claude Code
- Cursor
- Cline
- Codex
- Windsurf
- Gemini CLI
- +20
- 信任分
- 88 / 100 · 社区维护
- 作者 / 版本 / 许可
- @tomevault-io · 未声明 license
- Token 消耗评级
- 低消耗
- 接入复杂程度
- 需简单配置
- 是否需要外部 API Key
- 需要 · Vendor-specific
- 兼容的系统
- 未声明(默认跨平台)
- 底层运行要求
- Python
- 文件与系统权限
-
- 只读
- 允许写入 / 修改
- Shell 执行
- 读取环境变量
- 网络行为
- 允许外网请求
- 安装命令数
- 26 条
档案由构建时根据 SKILL.md 与安装命令自动衍生,可能与作者实际意图存在差异。
需要注意: 未限定 allowed-tools,默认拥有全部工具权限。
---
name: langchain-agents-langsmith-evals
description: Use when authoring eval datasets, writing evaluators, running evals against a LangChain / LangGr…
category: 写作
runtime: Python
---
# langchain-agents-langsmith-evals 输出预览
## PART A: 任务判断
- 适用问题:文章、文案、发言稿、润色或结构化表达。
- 输入要求:目标材料、限制条件、期望输出和验收方式。
- 证据边界:围绕“Dataset shape / Evaluators / Runner”读取原文规则,不把推断写成作者承诺。
## PART B: 执行结果
- **01** 任务判断:确认你的需求是否属于文章、文案、发言稿、润色或结构化表达,并标出输入、限制和预期结果。
- **02** 执行计划:优先按“Dataset shape / Evaluators / Runner”拆成步骤,说明每一步会读取什么、修改什么、产出什么。
- **03** 交付结果:给出可复制的命令、文件改动、检查清单或内容草稿,并说明如何继续迭代。
- **04** 风险边界:结合 读取文件、写入/修改文件、执行终端命令、读取环境变量、会按任务需要访问外部网络、需要准备 Vendor-specific API Key 给出执行前确认项。
## Running Rules
- 读取文件、写入/修改文件、执行终端命令、读取环境变量;会按任务需要访问外部网络;需要准备 Vendor-specific API Key。
- 先小样例验证,再放大到真实任务。
- 交付时同时给结果、检查口径和下一步迭代建议。 原文没有稳定的斜杠命令要求。安装验证后通常全局生效,直接在对话里点名这个 Skill 并描述任务即可。
告诉 Agent 目标文件或材料、期望结果、不可改范围、是否允许联网或执行命令。本 Skill 的权限画像是:读取文件、写入/修改文件、执行终端命令、读取环境变量。
先用一个小任务确认它会围绕“Dataset shape / Evaluators / Runner”工作;涉及文件或命令时,先看 diff、日志、预览或测试结果。
检查最终产物是否包含明确结果、必要证据和下一步动作;如果输出泛泛而谈,就补充输入、边界和验收标准后重跑。
---
name: langchain-agents-langsmith-evals
description: Use when authoring eval datasets, writing evaluators, running evals against a LangChain / LangGr…
category: 写作
source: tomevault-io/skills-registry
---
# langchain-agents-langsmith-evals
## 什么时候使用
- 用于组织测试、定位失败并形成修复闭环 适合处理文章、文案、润色、翻译、总结和结构化表达,核心价值是把输入、判断、执行、验证和交付边界固定下来,避免 Agent 泛泛回答。 把任务拆成可执行、可检查、可继续迭代的步骤;使用前要准备 Ven…
- 面向文章、文案、发言稿、润色或结构化表达,优先处理能明确输入、步骤和验收标准的工作。
## 需要提供什么
- 目标材料、目录范围、期望结果和不可改动内容。
- 是否允许联网、执行命令、读写文件或调用外部服务。
## 执行规则
- 围绕「Dataset shape / Evaluators / Runner」组织步骤,不把推断写成作者事实。
- 读取文件、写入/修改文件、执行终端命令、读取环境变量;会按任务需要访问外部网络;需要准备 Vendor-specific API Key。
- 先跑小样例,确认结果可检查后再扩大任务范围。
## 输出要求
- 给出最终产物、关键证据、验证方式和下一步动作。
- 信息不足时标记 unknown,不编造命令、平台或依赖。 作者原文负责流程事实;仓库文件负责来源和命令;流狐只补充适用场景、限制和质量判断。
skill "langchain-agents-langsmith-evals" {
输入层 -> 用户目标 + 目标文件 + 禁止范围 + 验收标准
上下文层 -> Dataset shape / Evaluators / Runner
规则层 -> SKILL.md 触发条件 / 执行顺序 / 输出格式
运行层 -> Python | 读取文件、写入/修改文件、执行终端命令、读取环境变量 | 会按任务需要访问外部网络
安全层 -> 需要准备 Vendor-specific API Key + 小任务验证 + diff / 日志复核
输出层 -> 可复制结果 + 检查清单 + 下一步迭代
} Evals + Testing
Use the langsmith Python SDK directly. There is no CLI wrapper — write a small evals/run.py and run it with python evals/run.py. For per-test-function CI checks, use pytest with the langsmith pytest plugin.
LANGSMITH_API_KEY must be set. LANGSMITH_PROJECT controls which project the trace lands in.
Dataset shape
evals/datasets/smoke.jsonl — one JSON object per line:
{"input": {"messages": [{"role": "user", "content": "Say hello in one word."}]}, "reference": "Hi"}
{"input": {"messages": [{"role": "user", "content": "What is 2+2?"}]}, "reference": "4"}
reference is optional and only used by evaluators that compare against a known answer (correctness LLM-as-judge, exact-match, etc.).
Evaluators
evals/evaluators.py:
"""LangSmith evaluators. Each takes (run, example) and returns a result dict."""
from typing import Any
def correctness_llm_judge(run: Any, example: Any) -> dict[str, Any]:
"""LLM-as-judge against `example.outputs['reference']`."""
# ... call an LLM with run.outputs and example.outputs['reference']
return {"key": "correctness", "score": 0.9, "comment": "close enough"}
def trajectory(run: Any, example: Any) -> dict[str, Any]:
"""Did the expected tool calls fire?"""
expected = example.outputs.get("expected_tools", [])
actual = [c["name"] for c in run.outputs.get("tool_calls", [])]
score = 1.0 if set(expected).issubset(actual) else 0.0
return {"key": "trajectory", "score": score}
EVALUATORS = [correctness_llm_judge, trajectory]
Runner
evals/run.py:
"""Run LangSmith evals. Usage: python evals/run.py [--smoke]"""
import argparse, json, os
from datetime import UTC, datetime
from pathlib import Path
import langsmith
from agent.agent import agent
from evals.evaluators import EVALUATORS
ROOT = Path(__file__).resolve().parent
DATASETS = ROOT / "datasets"
RESULTS = ROOT / "results"
def _load(name: str) -> list[dict]:
path = DATASETS / f"{name}.jsonl"
return [json.loads(l) for l in path.read_text("utf-8").splitlines() if l.strip()]
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--smoke", action="store_true")
args = ap.parse_args()
if not os.getenv("LANGSMITH_API_KEY"):
print("ERROR: LANGSMITH_API_KEY is not set.")
return 2
datasets = ["smoke"] if args.smoke else [p.stem for p in DATASETS.glob("*.jsonl")]
RESULTS.mkdir(exist_ok=True)
results: dict[str, list[dict]] = {}
for ds in datasets:
examples = _load(ds)
out = langsmith.evaluate(
lambda inp: agent.invoke(inp),
data=examples,
evaluators=EVALUATORS,
experiment_prefix=f"{ds}-",
)
results[ds] = list(out)
out_path = RESULTS / f"{datetime.now(UTC).strftime('%Y%m%dT%H%M%SZ')}.json"
out_path.write_text(json.dumps(results, default=str, indent=2), encoding="utf-8")
print(f"Wrote {out_path}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
Run with: python evals/run.py (full) or python evals/run.py --smoke (smoke only).
Suggested smoke pattern (for deploy gating)
Keep evals/datasets/smoke.jsonl small (3–5 rows) and fast (<60 s total). Run python evals/run.py --smoke before any deploy. If smoke fails, fix the agent or the smoke dataset — never bypass. This pattern is recommended but not enforced; the deploy skill expects you to do it manually.
Comparing two runs
The langsmith UI is the best place to compare experiments side-by-side. For a quick CLI diff between two evals/results/*.json files, write a 30-line script that loads both and prints metric deltas — there's no built-in CLI for this.
Testing strategies
The langsmith package ships a pytest plugin. Three layers of testing for a production agent:
1. Unit tests (no API calls)
Use LLMToolEmulator middleware to short-circuit tool execution, and a fake / mocked model:
# tests/test_agent_unit.py
from langchain.agents import create_agent
from langchain.agents.middleware import LLMToolEmulator
def test_agent_handles_empty_input():
agent = create_agent(
model="claude-haiku-4-5", # fastest available; or use a stub
tools=[my_tool],
middleware=[LLMToolEmulator()], # tools return LLM-emulated outputs
)
result = agent.invoke({"messages": [{"role": "user", "content": "hi"}]})
assert "messages" in result
For full hermetic unit tests with no LLM calls at all, mock init_chat_model or pass a FakeChatModel (from langchain_core.language_models.fake import FakeChatModel).
2. Integration tests (real LLM, hermetic tools)
Real model, real middleware, but tools mocked / point at sandboxes:
# tests/test_agent_integration.py
import pytest
from agent.agent import agent
@pytest.mark.integration
def test_smoke_basic():
result = agent.invoke({"messages": [{"role": "user", "content": "Say hi."}]})
msg = result["messages"][-1]
assert "hi" in str(msg.content).lower()
Run with pytest -m integration. Skip in CI without API keys; run locally or in a separately-credentialed CI step.
3. Trajectory + dataset tests via langsmith pytest plugin
# tests/test_agent_trajectories.py
import pytest
from langsmith import testing as t
@t.expect(score_min=0.8, evaluator="correctness")
@pytest.mark.parametrize("example", [
{"messages": [{"role": "user", "content": "What is 2+2?"}], "reference": "4"},
{"messages": [{"role": "user", "content": "Capital of France?"}], "reference": "Paris"},
])
def test_basic_qa(example):
from agent.agent import agent
return agent.invoke({"messages": example["messages"]})
The plugin uploads each test result to LangSmith, runs the named evaluator(s), and fails the test if the score falls below the threshold. This is the recommended way to gate PRs on agent quality.
Eval-as-monitor (production)
In production, the same evaluators that grade your dev runs can run continuously against live traces:
- Set up an evaluator function in LangSmith UI.
- Configure it to run on incoming traces (sampled or all).
- Wire an alert when score drops below threshold.
This catches model drift, prompt rot, and gradual quality degradation that smoke evals don't see.
Common eval gotchas
- LLM-as-judge evaluators are themselves non-deterministic. Run each example 3+ times and average, OR use a low-temperature judge model.
- Don't mix metric directions.
correctnesshigher = better;latencyhigher = worse. Make this explicit in evaluator names so dashboards read correctly. - Smoke datasets that are too large (>10 rows) become a deploy bottleneck. Keep them tight; rely on the full eval suite running async post-deploy for breadth.
langsmith.evaluate(...)runs invocations in parallel by default. If your agent has rate-limited tools, setmax_concurrency=1or accept that retries will fire.
Source: cwijayasundara/agent_cli_langchain — distributed by TomeVault.
先判断是否适合
作者设计意图
作者的方法与取舍
边界和复核