
Agent-Skills-for-Context-Engineering 技能索引指南LLM-as-a-Judge 评估技能体系全解析【免费下载链接】Agent-Skills-for-Context-EngineeringA comprehensive collection of Agent Skills for context engineering, multi-agent architectures, and production agent systems. Use when building, optimizing, or debugging agent systems that require effective context management.项目地址: https://gitcode.com/GitHub_Trending/ag/Agent-Skills-for-Context-Engineering本文以examples/llm-as-judge-skills/skills/index.md技能索引为骨架深入解析 LLM-as-a-Judge 项目中的三大基础技能模块——LLM EvaluatorLLM 评判评估、Context Fundamentals上下文工程基础、Tool DesignAgent 工具设计。你将掌握如何将评估方法论、上下文管理与工具设计原则落地为可执行的 TypeScript 代码并理解技能MD 知识文档→ 提示词Prompt 模板→ 工具TypeScript 实现→ AgentEvaluatorAgent的完整演进链路。一、技能索引在项目中的定位在examples/llm-as-judge-skills这个示例实现中skills/目录承担着知识基座的角色。索引文档开宗明义地定义Skills 是基础性知识模块foundational knowledge modules用于指导 Agent、工具与提示词的设计与实现见 skills/index.md。整个示例遵循一条清晰的流水线这与索引中的定义一一对应SkillsMD 知识文档→ Prompts提示词模板→ ToolsTypeScript 工具实现→ EvaluatorAgent评估 AgentSkillsskills/llm-evaluator/、skills/context-fundamentals/、skills/tool-design/三个知识文档回答评估该怎么做Promptsprompts/evaluation/下的评分与对比提示词模板Toolssrc/tools/evaluation/下的directScore、pairwiseCompare、generateRubric三个可执行工具Agentsrc/agents/evaluator.ts中的EvaluatorAgent类将上述能力统一封装。二、Skill 1LLM Evaluator —— LLM-as-a-Judge 评估方法论2.1 基线选择评估器要对标谁LLM Evaluator 技能文档llm-evaluator.md开篇给出两个基准参照系基线目标说明Human Annotators人工标注LLM 与人类的相关性尽量接近人类与人类之间的相关性LLM 评估器比人工标注快几个数量级且成本更低Finetuned Classifiers微调分类器达到与微调分类器相近的 Recall 与 Precision难度更高的基线因为微调分类器针对特定任务做了优化这一方法论在实现中的体现是工具层不依赖单一的拍脑袋打分而是通过证据evidence、理由justification与多准则加权来逼近人工标注质量。测试用例should use chain-of-thought in scoring见 tests/skills.test.ts专门断言justification.length 20即强制要求评分附带足够长的理由文本这正是以证据驱动评分、逼近人类判断的工程化落地。2.2 三种评分方法的选择矩阵技能文档用一张表总结了三种评分方法的适用场景与可靠性这是索引中直接评分用于客观评估、成对比较用于主观偏好这一核心结论的理论源头方法适用场景可靠性特征Direct Scoring直接评分客观任务事实性、毒性、指令遵循更适合二分类判断Pairwise Comparison成对比较主观评估语气、说服力、连贯性对偏好类任务更可靠Reference-Based基于参照对照黄金标准答案需要 ground truth 参照在源码中这一选择矩阵被直接编码进工具描述。例如 direct-score.ts 的 tool 描述写明Use for objective evaluations like accuracy, completeness, clarity而 pairwise-compare.ts 则写明Use for subjective evaluations like tone, persuasiveness, style. More reliable than direct scoring for preferences。工具描述本身就是技能知识向模型传递的桥梁——模型依据描述决定何时调用哪个工具。2.3 评估指标分类指标与相关指标技能文档将指标分为两类分类指标二分类任务首选Recall、Precision、F1 Score、Cohens κKappa——强调可解释性相关指标Likert 量表任务Spearmans ρrho、Kendalls τtau——度量排序一致性。这与索引中Prefer classification metrics for interpretability的 Key Takeaway 一致。实践中当你用directScore的 1-5 分制做二分类如合格/不合格时应优先报告 Precision/Recall/F1当分数本身是排序意义时才使用 ρ 或 τ。2.4 已知偏差与缓解策略技能文档明确列出三大已知偏差Position Bias位置偏差成对比较时偏向特定位置通常是第一个位置的回复Verbosity Bias冗长偏差偏好更长、更啰嗦的回复即使质量不高Self-Enhancement Bias自我增强偏差评估器偏好由自己生成的答案。对应的缓解策略包括交换位置取平均、评估时对长度做归一化、使用 Panel of LLMsPoLL多评判员机制、加入 dont overthink 指令、使用 CoT n-shot 提示。源码级验证位置偏差的缓解被完整实现于executePairwiseCompare。当swapPositions: true时默认开启见 pairwise-compare.ts 的 schema 默认值函数会执行两轮评估第一轮A 在前、B 在后第二轮B 在前、A 在后再把第二轮的胜者映射回原始坐标pass2.winner A ? B : ...若两轮胜者不一致判定为TIE并给出 0.5 的低置信度pairwise-compare.ts。同时评估提示词中显式写入 Do NOT prefer responses because they are longer冗长偏差与 Do NOT prefer responses based on position位置偏差两条指令pairwise-compare.ts。测试should mitigate position bias with swap与should identify clear winner for quality difference分别验证了相似回复返回 TIE与质量差异明显时胜者稳定两个行为。2.5 实现模式EvaluatorConfig 接口技能文档给出评估器的核心配置接口这是将方法论翻译成类型系统的最小骨架interface EvaluatorConfig { scoringApproach: direct | pairwise | reference-based; criteria: EvaluationCriteria[]; metrics: MetricType[]; useCoT: boolean; nShot: number; } interface EvaluationCriteria { name: string; description: string; rubric: RubricLevel[]; } interface RubricLevel { score: number; description: string; }在仓库中这一配置思想被细化并分散到各工具 schema 中criteria对应DirectScoreInputSchema中的criteria数组含name/description/weight权重限制 0-1、默认 1见 direct-score.tsuseCoT对应 system prompt 中强制要求Find specific evidence → Justify your score的四步流程rubric对应scale: 1-3 | 1-5 | 1-10的枚举与可选的levelDescriptions记录direct-score.ts。2.6 参考研究脉络技能文档末尾列出其方法论参考的关键论文/项目Constitutional AIAnthropic、G-Eval基于 GPT-4 的 NLG 评估、SelfCheckGPT零资源幻觉检测、Prometheus细粒度评估能力、MT-Bench 与 Chatbot Arena。这些为评估器如何设计提供了学术界与工业界的双重视角。三、Skill 2Context Fundamentals —— 上下文工程基础3.1 核心原则一上下文窗口管理Context Fundamentals 技能文档context-fundamentals.md的第一条原则是上下文窗口是有限的每个 token 都算数。三条核心策略Summarize对历史对话轮次做摘要压缩Retrieval仅注入与当前任务相关的检索上下文Compression对长文档实施上下文压缩。在评估场景中的具体体现是DirectScoreInputSchema提供了可选的context字段z.string().optional()见 direct-score.ts调用方可以精确控制注入评估模型的上下文量避免无关信息稀释评分判断。3.2 核心原则二信息层级结构技能文档建议按优先级组织上下文以引导模型注意力1. System Instructions最高优先级 ├── 角色定义 ├── 任务约束 └── 输出格式要求 2. Relevant Context动态 ├── 检索文档 ├── 用户特定数据 └── 近期对话历史 3. User Input当前请求 ├── 查询或指令 └── 内联上下文这一结构在评估工具的用户提示词中得到了忠实复刻。以executeDirectScore的 userPrompt 为例direct-score.ts其顺序正是## Original Prompt任务约束→## Context动态上下文可选→## Response to Evaluate被评估对象→## Criteria评估准则最后才是Respond with valid JSON matching this structure输出格式要求。这种约束在前、数据在后、格式收尾的编排直接降低了模型误解指令的概率。3.3 核心原则三上下文相关性过滤技能文档提出三种相关性维度Temporal Relevance时间相关性新信息通常比旧数据更有价值Semantic Relevance语义相关性用 embedding 找出相关内容Task Relevance任务相关性只包含当前任务所需信息。3.4 三种上下文类型类型示例特征Static静态系统提示词、角色定义、工具描述、格式规范全生命周期稳定Dynamic动态RAG 检索文档、对话历史、用户偏好、会话状态随会话变化Ephemeral瞬时当前工具输出、中间推理步骤、草稿本内容用完即弃EvaluatorAgent.chat()方法就是静态上下文的典型用例——其 system prompt 固定为You are an expert evaluator of AI-generated content...而用户的任意评估诉求则作为动态输入传入evaluator.ts。3.5 最佳实践五条技能文档给出五条可操作的最佳实践Explicit Over Implicit明确陈述需求不依赖模型推断Structured Formatting使用一致的定界符与分节Redundancy Removal避免上下文各节重复信息Source Attribution标注上下文来源以便溯源Freshness Signals指示信息最后更新时间。3.6 两种上下文编排模式RAG 集成模式检索注入 严格约束[System Instructions] You are a helpful assistant. Use the provided context to answer questions. Only use information from the context. If unsure, say so. [Retrieved Context] document sourcedoc1.pdf date2024-01-15 Content here... /document [User Query] {user_input}多轮对话模式摘要 近期轮次 当前请求[System Instructions] ... [Conversation History] Summary of earlier turns: {summary} Recent exchanges: User: {recent_user_1} Assistant: {recent_assistant_1} ... [Current Turn] User: {current_input}3.7 上下文质量指标技能文档定义四类可量化指标用于判断上下文工程是否有效Context Utilization Rate上下文利用率响应中实际用到多少提供的上下文Context Relevance Score上下文相关分上下文与响应的语义相似度Context Compression Ratio压缩率原始大小与压缩后大小之比Information Retention信息保留度摘要后仍保留的关键事实比例。实战验证测试should utilize provided context in evaluationtests/skills.test.ts展示了上下文的实际影响力——当注入用户是医疗专业人士使用技术术语是恰当的这一上下文后含 SSRIs、MAOIs、serotonin syndrome 等技术术语的医学回复获得更高评分。这说明评估时的上下文注入会显著改变评分结果上下文工程能力直接决定评估质量。四、Skill 3Tool Design —— Agent 工具设计最佳实践4.1 单一职责原则Tool Design 技能文档tool-design.md强调每个工具只做好一件事复杂操作由多个工具组合而成// Bad: 一个工具包揽一切 const analyzeAndSummarizeAndSend { ... } // Good: 职责分离 const analyzeDocument { ... } const summarizeContent { ... } const sendEmail { ... }本示例中的三个评估工具正是这一原则的范本directScore只负责单回复评分、pairwiseCompare只负责双回复对比、generateRubric只负责生成评分标准三者通过EvaluatorAgent.evaluateWithGeneratedRubric()组合成完整工作流先生成 rubric再基于 rubric 打分见 evaluator.ts。4.2 清晰的输入 Schema工具输入必须使用显式、带校验、带约束的 schemaconst searchTool tool({ description: Search for documents by semantic similarity, parameters: z.object({ query: z.string().describe(Natural language search query), limit: z.number().min(1).max(100).default(10) .describe(Maximum number of results to return), filters: z.object({ dateAfter: z.string().optional() .describe(ISO date string, only return docs after this date), source: z.enum([internal, external, all]).default(all) }).optional() }), execute: async (input) { ... } });仓库中的PairwiseCompareInputSchema完美展示了这一模式criteria要求至少一个元素z.array(z.string()).min(1)、allowTie与swapPositions均有默认值true、每个字段都有describe()帮助模型理解pairwise-compare.ts。这些.describe()文本就是技能知识注入模型的关键通道。4.3 可预测的输出结构工具应返回一致的、类型化的输出保证模型能可靠解析。技能文档给出统一泛型契约interface ToolResultT { success: boolean; data?: T; error?: { code: string; message: string; retryable: boolean; }; metadata: { executionTimeMs: number; source?: string; }; }实现中DirectScoreOutputSchema、PairwiseCompareOutputSchema、GenerateRubricOutputSchema均遵循类似契约统一的success: boolean字段 metadata含evaluationTimeMs/model结构化元数据。例如DirectScoreOutputSchema用 Zod 严格定义 scores 数组中每个元素的字段类型criterion/score/maxScore/justification/evidence/improvement见 direct-score.ts确保模型拿到的永远是形状确定的 JSON。4.4 优雅的错误处理技能文档的硬性要求工具绝不抛出未捕获异常始终返回结构化错误execute: async (input) { try { const result await performAction(input); return { success: true, data: result }; } catch (error) { return { success: false, error: { code: error.code ?? UNKNOWN_ERROR, message: error.message, retryable: isRetryable(error) } }; } }三个评估工具的execute函数全部遵循此模式try/catch包裹generateText调用失败时返回success: false与空结果集而非抛异常。例如executeDirectScore的 catch 分支返回scores: []、overallScore: 0并在summary.assessment中携带错误信息direct-score.ts。4.5 工具分类与审批技能文档按风险将工具分为三类类别示例审批要求Read-Only只读数据库查询、API 读取、文件读取、搜索无需审批安全State-Modifying改状态数据库写入、文件修改、API POST/PUT/DELETE可能需要审批考虑needsApprovalDangerous危险文件删除、支付处理、生产部署、发送外部通信必须审批 审计日志评估工具属于典型的只读类别——它们只调用模型、返回评估结果不改变任何系统状态因此无需审批即可安全执行。4.6 AI SDK 6 工具特性技能文档详细介绍了 AI SDK 6 的四项新特性这些是构建生产级工具的关键能力① 工具执行审批Approval——静态或基于输入动态判定// 静态审批始终需要人工确认 const deleteTool tool({ description: Delete a file from the system, parameters: z.object({ path: z.string() }), needsApproval: true, // Requires human approval execute: async ({ path }) { ... } }); // 动态审批根据输入内容决定 const commandTool tool({ description: Execute a shell command, parameters: z.object({ command: z.string() }), needsApproval: ({ command }) { return command.includes(rm) || command.includes(delete); }, execute: async ({ command }) { ... } });② 严格模式Strict Mode——保证 schema 完全合规const strictTool tool({ description: ..., parameters: schema, strict: true, // Enable strict mode execute: async (input) { ... } });③ 输入示例Input Examples——帮助模型理解期望的输入格式const complexTool tool({ description: Create a calendar event, parameters: eventSchema, inputExamples: [ { title: Team Standup, date: 2024-01-15, time: 09:00, duration: 30, attendees: [aliceexample.com, bobexample.com] } ], execute: async (input) { ... } });④ toModelOutput——控制返回给模型的内容如截断长文件内容const readFileTool tool({ description: Read file contents, parameters: z.object({ path: z.string() }), execute: async ({ path }) { const content await fs.readFile(path, utf-8); return { path, content, size: content.length }; }, toModelOutput: (result) { // Only send truncated content to model return { path: result.path, content: result.content.slice(0, 5000), truncated: result.content.length 5000 }; } });4.7 七条最佳实践Descriptive Names工具名应清晰表明功能Comprehensive Descriptions工具描述中包含使用示例Reasonable Defaults为可选参数提供合理默认值如swapPositions默认trueIdempotency工具设计为可安全重执行Timeout Handling外部操作实现超时Rate Limiting防止工具失控执行Logging记录所有工具调用用于调试与审计。五、技能应用矩阵技能如何映射到实际构件索引文档的核心内容之一是一张技能应用矩阵它明确了每个技能影响哪些层面Agents/Tools/PromptsSkillAgentsToolsPromptsLLM EvaluatorEvaluatordirectScore, pairwiseCompareevaluation/*Context FundamentalsAllAll (context params)All (context handling)Tool DesignAll (tool selection)Allorchestrator-prompt结合仓库结构可以验证这张矩阵的落地情况LLM Evaluator → Evaluator Agent → 三个评估工具 →prompts/evaluation/下的提示词模板工具的 system prompt 内嵌评估方法论证据提取、理由陈述、忽略长度与位置prompts/evaluation/direct-scoring-prompt.md与pairwise-comparison-prompt.md则保存独立的提示词版本Context Fundamentals → 所有 Agent 与工具三个工具的输入 schema 都提供context可选参数接受外部注入的上下文测试专门验证了上下文对评分的影响Tool Design → 工具选择 → orchestrator-prompt统一的 Zod schema、结构化输出与错误处理贯穿所有工具prompts/agent-system/orchestrator-prompt.md指导编排层如何选择与组合工具。六、新增技能的标准流程索引文档给出在仓库中新增技能的完整步骤创建技能目录skills/skill-name/创建主文件skills/skill-name/skill-name.md主文件必须包含Overview and purpose概述与目的Core principles核心原则Practical patterns实用模式Implementation examples实现示例References参考资料更新本索引skills/index.md这一流程保证了技能文档的结构一致性使每个技能都具备可迁移的原则 可执行的示例 权威来源后续可被 Agent 或人工直接检索与复用。七、技能开发指南高质量技能的评判标准索引文档最后给出技能开发的行为准则Focus on principles that transfer across implementations聚焦可跨实现迁移的原则避免绑定单一框架Include concrete examples and patterns包含具体示例与模式本示例中每个原则都配有 TypeScript 代码Reference authoritative sources引用权威来源如 LLM Evaluator 技能引用了 G-Eval、MT-Bench 等研究Keep content actionable, not just theoretical内容可执行而非纯理论Update as understanding evolves随认知演进持续更新。八、从技能到生产代码EvaluatorAgent 集成示例索引中三个技能最终汇聚于EvaluatorAgent。该类的构造支持model默认取config.openai.model与temperature默认 0.3配置evaluator.ts并通过四个公开方法对外提供能力score(input)委托executeDirectScore做单回复多准则评分compare(input)委托executePairwiseCompare做双回复对比含位置交换消偏generateRubric(input)委托executeGenerateRubric生成评分标准evaluateWithGeneratedRubric(response, prompt, criteria)组合式完整流程——先并行生成各准则的 rubric再基于生成的levelDescriptions执行评分chat(userMessage)无固定结构的自由评估对话。配置方面src/config/index.ts从环境变量读取OPENAI_API_KEY与OPENAI_MODEL默认gpt-4ovalidateConfig()在缺失 API Key 时抛错提醒config/index.ts。一个最小可用示例import { EvaluatorAgent } from ./src/agents/evaluator; const agent new EvaluatorAgent(); // 单回复评分Direct Scoring 技能 const scoreResult await agent.score({ response: Your AI-generated response, prompt: The original prompt, criteria: [ { name: Accuracy, description: Factual correctness, weight: 1 } ] }); console.log(Score: ${scoreResult.overallScore}/5); // 双回复对比Pairwise Comparison 技能 位置偏差缓解 const compareResult await agent.compare({ responseA: First response, responseB: Second response, prompt: The prompt, criteria: [quality, completeness], allowTie: true, swapPositions: true }); console.log(Winner: ${compareResult.winner} (confidence: ${compareResult.confidence}));更多可运行示例见examples/llm-as-judge-skills/examples/目录basic-evaluation.ts、pairwise-comparison.ts、generate-rubric.ts、full-evaluation-workflow.ts测试套件见tests/evaluation.test.ts9 个工具级测试与tests/skills.test.ts10 个技能级测试。结语skills/index.md虽然只是一个索引文件但它勾勒出 LLM-as-a-Judge 示例完整的能力地图LLM Evaluator 决定评什么、怎么评方法论Context Fundamentals 决定喂什么上下文信息工程Tool Design 决定工具怎么建执行质量。三者共同支撑起EvaluatorAgent的生产级评估能力。如果你正在构建自己的评估系统可以按索引的步骤新增技能、按三条技能线的原则设计工具与提示词再以EvaluatorAgent为模板组装成端到端的评估流水线。【免费下载链接】Agent-Skills-for-Context-EngineeringA comprehensive collection of Agent Skills for context engineering, multi-agent architectures, and production agent systems. Use when building, optimizing, or debugging agent systems that require effective context management.项目地址: https://gitcode.com/GitHub_Trending/ag/Agent-Skills-for-Context-Engineering创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考