ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

Clawhub 仓库中的 Axiom AI SDK 评估 API 完全参考:Eval、Scorer、Flag Schema 与 onlineEval 实战指南

Clawhub 仓库中的 Axiom AI SDK 评估 API 完全参考:Eval、Scorer、Flag Schema 与 onlineEval 实战指南 后端前端AI 技能AI 插件搜索引擎【免费下载链接】clawhubSkill Plugin Registry for OpenClaw项目地址https://gitcode.com/gh_mirrors/mo/clawhub点击查看免费下载本指南以 clawhub 仓库.agents/skills/writing-evals技能包中的 api-reference.md 为骨架完整梳理 Axiom AI SDK 评估体系的全部类型签名、导入路径、聚合器与 CLI 选项并结合仓库内的 SKILL.md、scorer-patterns.md、flag-schema-guide.md 及 templates 模板文件做纵深展开。读完你将能够独立编写类型安全的离线评估*.eval.ts、设计可被 CLI 覆写的 flag schema、为生产环境接入onlineEval在线打分并正确配置axiom.config.ts与运行 CLI 命令。1. 评估体系概览与导入路径Axiom AI SDK 的评估体系分为离线评估Eval与在线评估onlineEval两条主线加上Scorer打分器、Aggregation多次试验聚合与Flag Schema运行时配置变量三个支撑子系统。所有 API 均按模块从axiom包导入下表为仓库 api-reference.md 给出的完整导入路径ImportExportsaxiom/aicreateAppScope,initAxiomAI,withSpan,wrapAISDKModel,wrapTool,axiomAIMiddleware,RedactionPolicyaxiom/ai/evalsEval,EvalTask,EvalParamsaxiom/ai/scorersScoreraxiom/ai/evals/onlineonlineEvalaxiom/ai/scorers/aggregationsMean,Median,PassAtK,PassHatK,AtLeastOneTrialPasses,AllTrialsPassaxiom/ai/configdefineConfigaxiom/ai/feedbackcreateFeedbackClient实战提示SKILL.md 强调动手前务必先查看已安装 SDK 自带的文档目录node_modules/axiom/dist/docs/以该版本的真实签名为准——它才是权威来源SKILL.md。2. Eval()离线评估的入口函数2.1 完整签名function EvalTInput, TExpected, TOutput( name: string, params: EvalParamsTInput, TExpected, TOutput { capability: string; step?: string; }, ): void;每个.eval.ts文件调用一次Eval声明某个能力capability的某个步骤step应当达到什么标准。name与capability/step必须是非空字符串它们会被用于遥测 span 命名并直接显示在 Axiom 控制台中api-reference.md。2.2 EvalParams六个核心字段type EvalParamsTInput, TExpected, TOutput { data: | readonly CollectionRecordTInput, TExpected[] | Promisereadonly CollectionRecordTInput, TExpected[] | (() readonly CollectionRecordTInput, TExpected[] | Promisereadonly CollectionRecordTInput, TExpected[]); capability: string; step?: string; task: EvalTaskTInput, TExpected, TOutput; scorers: ReadonlyArrayScorerLikeTInput, TExpected, TOutput; metadata?: Recordstring, unknown; timeout?: number; configFlags?: string[]; trials?: number; // default: 1 };各字段职责data测试集合Collection。可以是静态数组、Promise 或返回数组/异步数组的函数三种形态详见第 8 节动态数据加载。capability/step能力与步骤名。SKILL.md 的术语表中Capability指用 LLM 完成特定任务的生成式 AI 系统范围从单轮模型交互到工作流、单 Agent、多 Agent 系统SKILL.md。task真正执行被测函数的回调接收{ input, expected }返回TOutput、PromiseTOutput或AsyncIterableTOutput流式任务见第 7 节。scorers打分器数组至少 2 个正确性 质量详见第 3、4 节。metadata附加到本次评估的任意键值元数据。timeout单次任务超时毫秒。SKILL.md 的常见坑表格指出默认全局超时 60s长任务需显式设置timeout: 120_000覆盖全局timeoutMsSKILL.md。configFlags通过pickFlags(...)声明本评估允许访问的 flag 路径用于检测越界访问与追踪 flag 影响范围。trials每个用例的试验次数默认 1。结合聚合器可得到跨试验的统计得分。2.3 CollectionRecord 与 EvalTasktype CollectionRecordTInput, TExpected { input: TInput; expected: TExpected; metadata?: Recordstring, unknown; };expected即Ground Truth——经专家核验的正确输出metadata通常按约定写入{ purpose: ... }用于分类happy path / adversarial / boundary / negative。type EvalTaskTInput, TExpected, TOutput (args: { input: TInput; expected: TExpected; }) TOutput | PromiseTOutput | AsyncIterableTOutput;编写守则SKILL.md 明确要求导入真实函数不要创建桩import the actual function — do not create a stub且.eval.ts文件应与源文件同目录放置SKILL.md。最小模板见 minimal.eval.ts。3. Scorer打分器的类型体系3.1 定义签名function ScorerTArgs extends Recordstring, any( name: string, fn: (args: TArgs) number | boolean | Score | Promisenumber | boolean | Score, options?: ScorerOptions, ): Scorer;Scorer 本质是带名字的断言函数。SKILL.md 的五条哲学中第二条即是Scorers are assertions — 每个 scorer 只检查输出的一个属性SKILL.md。3.2 Score、ScorerOptions 与执行期类型type Score { score: number | boolean | null; metadata?: Recordstring, any; }; type ScorerOptions { aggregation?: Aggregation; }; // Eval 实际接受的形式ScorerLike type ScorerLikeTInput, TExpected, TOutput ( args: { input?: TInput; expected?: TExpected; output: TOutput; trialIndex?: number; }, ) Score | PromiseScore; // 执行后附带名称等信息的 ScoreWithName type ScoreWithName Score { name: string; trials?: number[]; aggregation?: string; threshold?: number; };返回类型三选一scorer-patterns.mdbooleantrue 通过计 1.0false 失败计 0.0number原始得分通常 0.0–1.0也允许任意数值{ score, metadata }得分 调试信息。结构化校验失败时返回{ score: false, metadata: { field: intent, expected, actual } }可让失败可排查scorer-patterns.md。3.3 打分器分层策略SKILL.md 要求每个评估至少 2 个打分器建议分层SKILL.md正确性打分器必选——输出是否匹配期望精确匹配、集合匹配、字段匹配等质量打分器推荐——输出是否规范置信度阈值、输出长度、格式合法性、字段完整性无参考打分器面向用户文本时追加——输出是否连贯、相关、无毒LLM-as-judge 或 autoevals。不同输出类型对应的最低打分器组合SKILL.md输出类型最低打分器分类标签正确性精确匹配 置信度阈值自由文本正确性包含/Levenshtein 连贯性LLM-as-judge结构化对象字段匹配 字段完整性工具调用工具名存在性 参数校验检索结果集合匹配 相关性LLM-as-judge仓库 scorer-patterns.md 提供了 10 种可复制模式精确匹配含大小写归一化、带聚合的精确匹配、包含/子串匹配、集合匹配严格/子集/召回率、结构化输出校验、工具调用校验含工具顺序、格式校验JSON/长度/正则、多打分器组合、异步 LLM-as-judge、autoevals 库接入。4. Aggregations跨试验的分数聚合当trials 1时每个用例产生多个分数聚合器将其归约为一个最终分数type AggregationT extends string string { type: T; threshold?: number; aggregate: (scores: number[]) number; };4.1 四种内置聚合器const Mean (): Aggregationmean // 所有试验分数的平均值空数组返回 0 const Median (): Aggregationmedian // 排序后取中位数空数组返回 0 const PassAtK (opts?: { threshold?: number }): Aggregationpassk // 只要有一个试验分数 threshold默认 1即返回 1否则 0 // 别名AtLeastOneTrialPasses const PassHatK (opts?: { threshold?: number }): Aggregationpass^k // 所有试验分数都 threshold默认 1才返回 1否则 0 // 别名AllTrialsPass4.2 在 Scorer 中挂接聚合器import { Scorer } from axiom/ai/scorers; import { Mean, PassHatK, PassAtK } from axiom/ai/scorers/aggregations; // 多试验取平均 const ExactMatchMean Scorer( exact-match-mean, ({ output, expected }: { output: string; expected: string }) { return output expected ? 1 : 0; }, { aggregation: Mean() }, ); // 所有试验都通过才算通过 const ExactMatchAllPass Scorer(exact-match-all, scorerFn, { aggregation: PassHatK() }); // 任一试验通过即可 const ExactMatchAnyPass Scorer(exact-match-any, scorerFn, { aggregation: PassAtK() });5. createAppScope 与 Flag Schema运行时可调参5.1 工厂函数与 AppScope 接口function createAppScopeFlagSchema extends ZodObjectany, FactSchema extends ZodObjectany | undefined( config: { flagSchema: FlagSchema; factSchema?: FactSchema }, ): AppScopeFlagSchema, FactSchema; interface AppScopeFS, SC { flag: (path: string) any; // 点号路径访问如 flag(myCapability.model) fact: (name: string, value: any) void; overrideFlags: (partial: Recordstring, any) void; withFlags: T(overrides: Recordstring, any, fn: () T) T; pickFlags: (...paths: string[]) string[]; getAllDefaultFlags: () Recordstring, any; }Flag是无需改代码即可切换模型、温度、策略的配置变量SKILL.md。典型用法是导出{ flag, pickFlags }// src/app-scope.ts模板见 app-scope.ts import { createAppScope } from axiom/ai; import z from zod; export const flagSchema z.object({ myCapability: z.object({ model: z.enum([gpt-4o-mini-2024-07-18, gpt-5-mini-2025-08-07, gpt-5-nano-2025-08-07]).default(gpt-5-nano-2025-08-07), temperature: z.number().min(0).max(2).default(0.7), }), }); export const { flag, pickFlags } createAppScope({ flagSchema });5.2 Flag 优先级从高到低CLI 覆写--flag.pathvalue——最高评估上下文覆写overrideFlags()Schema 默认值.default()值配合使用withFlags(overrides, fn)做临时覆写回调内生效overrideFlags(partial)做本次运行全局覆写flag-schema-guide.md。5.3 三条硬性校验规则规则合法写法非法写法运行时抛错所有叶子字段必须有.default()z.string().default(gpt-4o-mini)z.string()→[AxiomAI] All flag fields must have defaults. Missing defaults for: model, temperature禁止z.union()/z.discriminatedUnion()z.enum([a,b]).default(a)z.union([z.string(), z.number()])→[AxiomAI] Union types are not supported in flag schemas禁止z.record()静态键的z.object({...})z.record(z.string(), z.string())→[AxiomAI] ZodRecord is not supported in flag schemas常见模式包括模型选择z.enum、温度z.number().min(0).max(2)、maxTokens、策略开关strategy: z.enum([simple,chain-of-thought,react])、布尔开关z.boolean().default(false)、数值阈值confidenceThreshold: z.number().min(0).max(1).default(0.8)详见 flag-schema-guide.md。5.4 pickFlags 与 task 中的读取import { flag, pickFlags } from /app-scope; import { openai } from ai-sdk/openai; import { generateText } from ai; async function categorizeMessage(messages: Array{ role: string; content: string }) { const model flag(supportAgent.categorizeMessage.model); const result await generateText({ model: openai(model), messages, system: Categorize the message as: support, spam, complaint, wrong_company, unknown, }); return result.text; } Eval(categorize-messages, { capability: support-agent, configFlags: pickFlags(supportAgent.categorizeMessage), // 声明访问范围可传多路径 data: [{ input: My app is broken, expected: support }], task: async ({ input }) categorizeMessage([{ role: user, content: input }]), scorers: [ExactMatch], });此外还可用factSchema记录非 flag 元数据如fact(userAction, clicked_button)facts 会挂到 span 上供分析但不能通过 CLI 覆写flag-schema-guide.md。6. defineConfig评估运行配置function defineConfig(config: AxiomConfig): AxiomConfig; interface AxiomConfig { eval?: { url?: string; edgeUrl?: string; token?: string; dataset?: string; orgId?: string; flagSchema?: ZodObjectany | null; instrumentation?: (options: { url: string; edgeUrl: string; token: string; dataset: string; orgId?: string; }) { provider?: TracerProvider } | Promise{ provider?: TracerProvider }; timeoutMs?: number; // 默认: 60000 include?: string[]; // 默认: [**/*.eval.{ts,js,mts,mjs,cts,cjs}] exclude?: string[]; // 默认: [**/node_modules/**, **/dist/**, **/build/**] }; [key: $${string}]: PartialAxiomConfig[eval]; // 环境覆写键 }要点文件发现默认 glob**/*.eval.{ts,js,...}会在全项目发现评估文件exclude默认排除node_modules、dist、build。SKILL.md 提醒评估文件必须以此扩展名结尾否则不会被发现SKILL.md。flagSchema 接线把flagSchema传入defineConfig后CLI 会在运行前对--flag.*参数做 schema 校验flag-schema-guide.md。instrumentation用于接入 token 用量追踪默认模板中注释了setupInstrumentation见 axiom.config.ts。$前缀键允许为不同环境提供部分配置覆写。标准配置示例仓库 axiom.config.ts 模板 README 认证段import { defineConfig } from axiom/ai/config; import { flagSchema } from ./src/app-scope; export default defineConfig({ eval: { url: process.env.AXIOM_URL, token: process.env.AXIOM_TOKEN, dataset: process.env.AXIOM_DATASET, flagSchema, include: [**/*.eval.{ts,js}], exclude: [**/node_modules/**, **/dist/**, **/build/**], timeoutMs: 60_000, // instrumentation: (env) setupInstrumentation(env), // 启用 token 统计 }, });认证环境变量离线与在线评估通用README.mdexport AXIOM_URLhttps://api.axiom.co export AXIOM_TOKENxaat-your-token export AXIOM_DATASETyour-dataset7. onlineEval生产流量在线打分7.1 签名与三类 scorer 条目function onlineEvalTInput, TOutput( meta: { capability: string; step?: string; link?: SpanContext; }, options: { input?: TInput; output: TOutput; scorers: readonly OnlineEvalScorerEntry[]; }, ): PromisePartialRecordstring, ScorerResult; type OnlineEvalScorerEntry | Scorer // 裸 scorer总是运行 | { scorer: Scorer; sampling?: ScorerSampling } // 带按 scorer 采样率 | { name: string; score: Score; metadata?: Recordstring, unknown; error?: string }; // 预计算结果 type ScorerSampling | number // 0.0–1.0 采样率 | ((args: { input?: TInput; output: TOutput }) boolean | Promiseboolean); // 条件采样函数7.2 与离线评估的关键差异维度离线Eval在线onlineEval数据带 ground truth 的精选集合实时生产流量打分器参考型expected 无参考型仅无参考型receiveinput/output无expected时机部署前CI / 本地部署后生产目的防止回归监控质量对比表见 SKILL.md7.3 使用示例与安全语义import { onlineEval } from axiom/ai/evals/online; import { Scorer } from axiom/ai/scorers; void onlineEval(my-eval-name, { // fire-and-forget短生命周期进程用 void capability: qa, step: answer, input: userMessage, // 可选传给 scorer output: response.text, scorers: [formatScorer], // 可带采样率{ scorer: formatScorer, sampling: 0.1 } });评估名必须只含[A-Za-z0-9\-_]在线评估绝不会向应用代码抛异常——scorer 失败会被记为 OTel 事件挂在评估 span 上trace 链接withSpan内自动关联或用link参数延迟关联。7.4 ScorerResulttype ScorerResult { name: string; score: Score; error?: string; };8. 流式任务Streaming TasksEvalTask可返回AsyncIterable用于评估流式 AI 函数如streamText()import { streamText } from ai; Eval(stream-eval, { capability: qa, data: [{ input: What is 22?, expected: 4 }], task: async function* ({ input }) { const result streamText({ model: openai(gpt-4o-mini), prompt: input }); for await (const chunk of result.textStream) { yield chunk; } }, scorers: [ExactMatch], });流块拼接规则api-reference.md字符串块→ 直接拼接chunks.join()对象块→ 返回最后一个块流式场景通常后块覆盖前块空流→ 返回空字符串9. 动态数据加载Dynamic Data Loadingdata支持三种形态函数只在评估启动时被调用一次——数据每次运行重新加载但不会在用例之间反复拉取api-reference.md// 静态数组 data: [{ input: hello, expected: hello }], // 函数评估启动时调用一次 data: () [{ input: hello, expected: hello }], // 异步函数从 API / 数据库 / CSV 拉取 data: async () { const response await fetch(https://api.example.com/test-cases); return response.json(); }, // 直接 Promise data: Promise.resolve([{ input: hello, expected: hello }]),结合 SKILL.md 的数据设计指南先检查用户已有数据JSON/CSV/seed 数据/生产日志没有则从代码生成——读系统提示提取类别、读输入类型、读校验解析逻辑、取枚举常量作为期望值每个类别至少一例happy path / adversarial / boundary / negative基础评估最少 5–8 例生产覆盖建议 15–20 例SKILL.md。10. 手动 Token 追踪非 Vercel AI SDK 场景自动 token 捕获只对 Vercel AI SDKai包开箱即用使用google/generative-ai、openai、anthropic-ai/sdk等其他 SDK 时需在 task 函数内手动写入 span 属性api-reference.mdimport { trace } from opentelemetry/api; task: async ({ input }) { const span trace.getActiveSpan(); // 示例Google Generative AI const result await model.generateContent(input); if (span result.response.usageMetadata) { span.setAttribute(gen_ai.usage.input_tokens, result.response.usageMetadata.promptTokenCount); span.setAttribute(gen_ai.usage.output_tokens, result.response.usageMetadata.candidatesTokenCount); span.setAttribute(gen_ai.request.model, gemini-2.0-flash); span.setAttribute(gen_ai.response.model, result.response.modelVersion); } return result.response.text(); // 示例OpenAI SDK // const result await openai.chat.completions.create({ ... }); // if (span result.usage) { // span.setAttribute(gen_ai.usage.input_tokens, result.usage.prompt_tokens); // span.setAttribute(gen_ai.usage.output_tokens, result.usage.completion_tokens); // span.setAttribute(gen_ai.request.model, gpt-4o-mini); // span.setAttribute(gen_ai.response.model, result.model); // } // return result.choices[0].message.content; },11. CLI 选项运行、调试与实验对比axiom eval [target] [options] Arguments: target file, directory, glob, or eval name (default: .) Options: -w, --watch 监听文件变化 -t, --token TOKEN Axiom API token -d, --dataset NAME Axiom dataset -u, --url URL Axiom API URL -o, --org-id ID Axiom org ID -b, --baseline ID 与基线对比 --debug 本地模式不发网络请求 --list 只列出用例不运行 --flag.*value 覆写 flag 值配合 flag schema 的完整实战命令SKILL.md# 运行全部评估 npx axiom eval # 运行指定文件 / 按名称正则匹配 npx axiom eval src/my-feature.eval.ts npx axiom eval eval-name # 监听模式 npx axiom eval -w # 本地调试无网络 npx axiom eval --debug # 只列用例不运行 npx axiom eval --list # CLI 覆写 flag换模型、调温度、开布尔开关 npx axiom eval --flag.myCapability.modelgpt-4o-mini npx axiom eval --flag.myCapability.temperature0.5 npx axiom eval --flag.myCapability.beThoroughtrue # 从 JSON 文件加载 flag 覆写 npx axiom eval --flags-configexperiments/config.json # 与基线对比 npx axiom eval -b BASELINE_ID12. 从模板到生产完整落地工作流仓库.agents/skills/writing-evals提供reference/templates/下的 7 份可直接复制的模板README.md模板对应打分模式场景minimal.eval.ts精确匹配最简起点classification.eval.ts精确匹配分类标签 对抗/边界用例retrieval.eval.ts集合匹配RAG / 文档检索内置 prompt injection、distractor 用例structured-output.eval.ts字段级匹配复杂对象校验tool-use.eval.ts工具名存在性Agent 工具调用含不应调用工具用例app-scope.ts—flag schema 样板axiom.config.ts—配置文件样板推荐项目布局评估文件与源码同目录按能力分组axiom.config.ts固定在项目根src/ ├── lib/ │ ├── app-scope.ts │ └── capabilities/ │ └── support-agent/ │ ├── support-agent.ts │ ├── support-agent-e2e-tool-use.eval.ts │ ├── categorize-messages.ts │ └── categorize-messages.eval.ts axiom.config.ts package.json标准八步工作流SKILL.md初始化scripts/eval-init创建app-scope.tsaxiom.config.ts脚手架scripts/eval-scaffold type capability [step]按类型生成评估文件定制替换 TODO 占位符为真实数据与真实函数校验scripts/eval-validate file检查文件结构覆盖度scripts/eval-add-cases file找出测试覆盖缺口本地试跑npx axiom eval --debug上报npx axiom eval将结果发往 Axiom复盘scripts/eval-results deployment查询历史结果。附高频排错速查问题原因解决All flag fields must have defaultsflagSchema 叶子缺.default()给每个叶子补默认值flag-schema-guide.mdUnion types are not supported使用了z.union()用z.enum()表达字符串变体Scorer 类型报错输入/输出类型不匹配显式标注 scorer 参数类型({ output, expected }: { output: T; expected: T })评估未被发现扩展名或 glob 不对检查axiom.config.ts的include文件必须以.eval.ts结尾Failed to load vitestaxiom SDK 未装或损坏重装npm install axiomvitest 已内置基线对比为空基线 ID 错误从 Axiom 控制台或上次运行输出获取 ID评估超时任务超过默认 60s给该评估设置timeout: 120_000覆盖全局timeoutMs排错表见 SKILL.md完整 API 签名以本仓库 api-reference.md 为准动手前也可核对已安装 SDK 的node_modules/axiom/dist/docs/。赞分享后端前端AI 技能AI 插件搜索引擎【免费下载链接】clawhubSkill Plugin Registry for OpenClaw项目地址https://gitcode.com/gh_mirrors/mo/clawhub点击查看免费下载相关推荐用 Axiom AI SDK 搭建 AI 评估套件clawhub 的 writing-evals 实战指南用 Axiom AI SDK 搭建 AI 评估套件clawhub 的 writing evals 实战指南 本文以 clawhub 仓库内置的 writing后端前端AI 技能AI 插件搜索引擎clawhub writing-evals 技能Axiom AI 评测 Scorer 模式实战手册clawhub writing evals 技能Axiom AI 评测 Scorer 模式实战手册 本文基于 clawhub 仓库内 writing eval后端前端AI 技能AI 插件搜索引擎clawhub writing-evals 技能详解用 createAppScope Zod 设计 Axiom AI 评测的 Flag Schemaclawhub writing evals 技能详解用 createAppScope Zod 设计 Axiom AI 评测的 Flag Schema 本文后端前端AI 技能AI 插件搜索引擎上一篇如何快速掌握Promptify零基础也能玩转提示工程的NLP解决方案下一篇RISE项目将Jupyter Notebook演示文稿导出为PDF的完整指南创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表