ARTICLE DETAIL

资讯详情

深耕网站视觉设计与运营推广的一线实战洞察。

VoltAgent 提示词工程实战:VoltOps Prompts 拉取、标签版本、模板变量与两级缓存

VoltAgent 提示词工程实战:VoltOps Prompts 拉取、标签版本、模板变量与两级缓存 人工智能AI AgentAgent 框架后端多智能体RAG工具调用Agent 记忆【免费下载链接】voltagentAI Agent Engineering Platform built on an Open Source TypeScript AI Agent Framework项目地址https://gitcode.com/gh_mirrors/vo/voltagent点击查看免费下载本文将 VoltAgent 官方文档website/prompt-engineering-docs/usage.md中的提示词使用指南扩展为一份面向落地的技术手册覆盖 API Key 配置、VoltOpsClient初始化、本地 Prompt 拉取CLI Pull、环境标签Labels、模板变量Template Variables、两级缓存策略、Chat Prompt、错误处理与调试等完整链路并结合packages/core与packages/cli的源码实现解释本地优先回退、缓存键生成、TTL 过期与逐请求覆盖等底层机制。一、整体接入流程将 VoltOps 提示词集成到 VoltAgent Agent 中需要完成三步在 VoltAgent 控制台注册项目进入 Settings → Projects复制项目的 public keypk_前缀与 secret keysk_前缀将密钥写入环境变量在代码中初始化VoltOpsClient并通过 Agent 的instructions动态回调获取提示词。VOLTAGENT_PUBLIC_KEYpk_your_public_key_here VOLTAGENT_SECRET_KEYsk_your_secret_key_hereimport { VoltOpsClient } from voltagent/core; const voltOpsClient new VoltOpsClient({ publicKey: process.env.VOLTAGENT_PUBLIC_KEY, secretKey: process.env.VOLTAGENT_SECRET_KEY, });从源码结构看VoltOpsClient的构造器会先校验密钥形态publicKey必须以pk_开头、secretKey必须以sk_开头且均非空见 client.ts。只有校验通过且prompts选项不为false时才会实例化VoltOpsPromptManagerImpl提示词管理器否则client.prompts保持为undefined后续任何getPrompt调用都会抛出 Prompt management is not enabled in VoltOpsClient 错误。这意味着密钥配置错误时故障会出现在第一次取词调用上而不是构造时——调试时应先检查密钥前缀与取值。客户端还有两个值得注意的默认值见 client.tsbaseUrl默认为https://api.voltagent.dev可通过baseUrl选项覆盖promptCache默认配置为{ enabled: true, ttl: 300, maxSize: 100 }用户传入的部分配置会与默认值合并浅合并逐项保留默认值。二、基础用法在动态 instructions 中取词VoltAgent 的 Agentinstructions支持动态回调形式回调参数中的prompts是一个PromptHelper其getPrompt接收PromptReference见 types.ts。最简用法import { openai } from ai-sdk/openai; import { Agent, VoltAgent, VoltOpsClient } from voltagent/core; const voltOpsClient new VoltOpsClient({ publicKey: process.env.VOLTAGENT_PUBLIC_KEY, secretKey: process.env.VOLTAGENT_SECRET_KEY, }); const agent new Agent({ name: SupportAgent, model: openai(gpt-4o-mini), instructions: async ({ prompts }) { return await prompts.getPrompt({ promptName: customer-support-prompt, }); }, }); new VoltAgent({ agents: { agent }, voltOpsClient: voltOpsClient, });将voltOpsClient传给VoltAgent是推荐做法它让框架为所有 Agent 统一提供promptshelper。客户端挂载方式的两个等价选项Agent 级 VoltOpsClient不想依赖顶层VoltAgent配置时也可以把 client 直接挂在单个 Agent 上const agent new Agent({ name: SupportAgent, model: openai(gpt-4o-mini), instructions: async ({ prompts }) { return await prompts.getPrompt({ promptName: customer-support-prompt, }); }, voltOpsClient: voltOpsClient, });直接调用 VoltOpsClient在非 Agent 场景脚本、CLI 工具中可绕过promptshelper 直接访问const content await voltOpsClient.prompts.getPrompt({ promptName: customer-support-prompt, }); console.log(Prompt content:, content);注意从源码看createPromptHelperclient.ts内部同样是转调this.prompts.getPrompt(reference)因此三条路径最终都汇聚到同一个VoltOpsPromptManagerImpl.getPrompt实现缓存与模板处理行为完全一致。三、本地 PromptsCLI 拉取与本地优先回退对于离线开发或高频迭代场景可以把 VoltOps 上的提示词拉取为本地 Markdown 文件Agent 运行时优先读本地文件、命中失败再回退到线上 VoltOps。拉取命令# 1. 拉取到默认目录 .voltagent/prompts pnpm volt prompts pull # 2. 拉取到自定义目录 pnpm volt prompts pull --out ./.promptsCLI 输出成功信息时会提示同步设置运行时变量见 prompts.ts# 3. 让运行时指向同一目录 export VOLTAGENT_PROMPTS_PATH./.prompts第 4 步Agent 侧代码无需任何改动instructions: async ({ prompts }) { return await prompts.getPrompt({ promptName: customer-support-prompt }); };拉取指定版本或标签要在本地保留多个版本可以按版本号或标签定向拉取文件会存储为.voltagent/prompts/promptName/version.mdpnpm volt prompts pull --names support-agent --prompt-version 4 pnpm volt prompts pull --names support-agent --label production对应的 CLI 参数定义见 prompts.ts选项说明-o, --out path输出目录默认.voltagent/prompts-n, --names names...指定要拉取的提示词名支持逗号分隔或重复传入-l, --label label按标签拉取需配合--names--prompt-version version按版本号拉取需配合--names--clean拉取前先删除已有提示词文件运行时按版本或标签请求instructions: async ({ prompts }) { return await prompts.getPrompt({ promptName: support-agent, version: 4, }); };instructions: async ({ prompts }) { return await prompts.getPrompt({ promptName: support-agent, label: production, }); };本地优先、线上回退的解析机制官方文档声明 If a local prompt is found, it is used first. If not, VoltOps is used as the fallback。这个行为可以从本地提示词加载器中得到印证见 local-prompts.ts目录解析优先级resolveLocalPromptsPath显式传入的basePath 环境变量VOLTAGENT_PROMPTS_PATH兼容旧变量VOLTAGENT_PROMPTS_DIR 默认目录.voltagent/prompts目录不存在时返回null即视为本地不可用直接走线上候选文件name.md单文件与name/version.md目录下所有.md文件都会被收集且做了路径穿越防护文件名以..逃逸基目录会直接抛错版本选择selectPromptFile指定version时精确匹配 frontmatter 或文件名中的版本号指定label时匹配 frontmatter 的labels数组label latest未命中时会回退到全部候选两者都不传时优先选带latest标签的最高版本否则选最高版本文件Frontmatter 结构本地文件使用 gray-matter 解析 YAML frontmatter支持name、version、labels、tags、typetext/chat等字段type: chat的正文必须是一个 JSON 消息数组与线上返回的 chat 结构一致失败语义本地文件存在但找不到匹配的版本/标签时抛出带LOCAL_PROMPT_NOT_FOUND错误码的LocalPromptNotFoundError上层凭此错误类型区分本地无此词、需要回退线上与真正的加载失败。本地路径下模板变量同样生效——applyTemplateToPrompt会调用与线上一致的简单模板引擎对text或每条 chat 消息内容做变量替换。四、环境标签Labels标签用于把不同环境的流量指向不同版本的提示词是最常见的多环境发布手段const agent new Agent({ name: ProductionAgent, model: openai(gpt-4o-mini), instructions: async ({ prompts }) { const label process.env.NODE_ENV production ? production : development; return await prompts.getPrompt({ promptName: customer-support-prompt, label: label, }); }, });内置标签Label用途production线上生产流量staging生产前测试development开发中testingQA 环境latest最新版本此外可以使用自定义标签如beta、canary、region-eu实现金丝雀或区域化发布。从本地解析逻辑看local-prompts.ts标签匹配基于 frontmatter 中labels数组的精确成员判断latest享有特殊地位——即使没有文件显式标注latest标签也会自动回退到所有候选中的最高版本这解释了为什么拉了多个版本文件但不带任何标签时请求latest依然能取到词。五、模板变量与 Agent Contextvariables参数用于把动态值替换进提示词模板const agent new Agent({ name: DynamicAgent, model: openai(gpt-4o-mini), instructions: async ({ prompts, context }) { return await prompts.getPrompt({ promptName: customer-support-prompt, label: production, variables: { companyName: VoltAgent Corp, userName: context.get(userName) || Guest, tier: context.get(subscriptionTier) || free, }, }); }, });context是DynamicValueOptions中的Mapstring | symbol, unknown见 types.ts通过agent.generateText的context选项注入const userContext new Map(); userContext.set(userName, Alice); userContext.set(subscriptionTier, premium); const response await agent.generateText(I need help, { context: userContext, });从实现看模板处理由VoltOpsPromptManagerImpl.processPromptContent完成prompt-manager.tstext类型处理整段文本chat类型逐条处理消息内容但仅对字符串内容做替换、复杂 part 数组原样透传模板引擎处理失败时会静默返回原文并记录 error 日志不会中断 Agent 运行。另外要注意模板替换发生在缓存读取之后——缓存存储的是未渲染的原始模板variables每次请求都会重新代入因此同一模板配合不同变量不会互相污染缓存。变量清洗防止提示注入用户可控的变量值在代入模板前应做清洗instructions: async ({ prompts, context }) { const sanitizedUserName context.get(userName)?.replace(/[]/g, )?.substring(0, 50) || Guest; return await prompts.getPrompt({ promptName: personalized-greeting, variables: { userName: sanitizedUserName }, }); };示例采用剥离 HTML 尖括号 截断长度的组合实际项目中应结合白名单、转义与业务边界如最大长度、允许字符集一并处理。六、缓存全局配置、逐请求覆盖与策略建议VoltOps 提供两级缓存以降低 API 调用次数。缓存管理器VoltOpsPromptManagerImplprompt-manager.ts基于内存Map实现核心机制如下缓存键getCacheKey生成${promptName}:${version}未指定版本时以latest参与键——因此同名提示词的不同版本互不干扰TTL 过期条目记录fetchedAt与毫秒化 TTL读取时超期即删除该条目并重新拉取容量上限写入前若cache.size maxSize会按插入顺序逐出最早的条目evictOldestEntry逐请求覆盖getPrompt内部先合成有效缓存配置——enabled与ttl取请求参数优先、否则用全局值而maxSize始终是全局值见 prompt-manager.ts。全局缓存配置const voltOpsClient new VoltOpsClient({ publicKey: process.env.VOLTAGENT_PUBLIC_KEY, secretKey: process.env.VOLTAGENT_SECRET_KEY, prompts: true, promptCache: { enabled: true, ttl: 300, // 秒缓存有效期 maxSize: 100, // 最大缓存条目数 }, });以上三个值恰好与源码默认值一致enabled: true、ttl: 300秒、maxSize: 100即不传promptCache时也享有同等缓存行为。逐 Prompt 缓存覆盖// 本次取词禁用缓存 return await prompts.getPrompt({ promptName: customer-support-prompt, promptCache: { enabled: false }, }); // 稳定提示词使用更长 TTL return await prompts.getPrompt({ promptName: system-instructions, promptCache: { ttl: 3600, enabled: true }, });PromptReference.promptCache类型中maxSize虽被保留用于签名一致性但按源码注释它不适用于逐请求场景types.ts容量只在客户端级别生效。清空缓存与缓存统计voltOpsClient.prompts.clearCache();此外管理器还提供getCacheStats()返回{ size, entries }当前缓存条目数与键列表可用于健康检查或调试面板展示见 prompt-manager.ts。缓存策略建议提示词类型TTL理由高频问候语60s访问频繁可接受小幅度更新延迟系统指令3600s极少变更长缓存收益明显个性化提示词禁用内容动态始终拉取最新// 高频提示词短 TTL await prompts.getPrompt({ promptName: chat-greeting, promptCache: { ttl: 60, enabled: true }, }); // 稳定提示词长 TTL await prompts.getPrompt({ promptName: system-instructions, promptCache: { ttl: 3600, enabled: true }, }); // 动态提示词不走缓存 await prompts.getPrompt({ promptName: personalized-prompt, promptCache: { enabled: false }, variables: { userId: dynamicUserId }, });启动时预加载关键提示词可在应用启动阶段并发预取把网络延迟移出首请求路径const criticalPrompts [welcome-message, error-handler, main-agent]; await Promise.all(criticalPrompts.map((name) prompts.getPrompt({ promptName: name })));preload在实现层同样存在VoltOpsPromptManagerImpl.preload即对多个引用做Promise.all(getPrompt)预取结果会写入缓存供后续请求直接命中。七、Chat Prompt多消息结构化提示词Chat 提示词定义带角色结构的多消息对话适用于需要固定开场白或 few-shot 示例的场景const agent new Agent({ name: ChatAgent, model: openai(gpt-4o-mini), instructions: async ({ prompts }) { return await prompts.getPrompt({ promptName: chat-support-prompt, variables: { agentRole: customer support specialist, companyName: VoltAgent Corp, }, }); }, });其返回结构与 text 提示词不同convertApiResponseToPromptContent按response.type区分见 prompt-manager.ts{ type: chat, messages: [ { role: system, content: You are a customer support specialist. }, { role: user, content: Hello, I need help. }, { role: assistant, content: Hello! How can I assist you today? } ] }所有返回内容都附带metadataname、version、labels、tags、source线上来源为online、本地为local-file可用于运行时日志与灰度审计。本地 chat 文件的正文即消息数组的 JSON 文本解析逻辑与线上结构对齐local-prompts.ts。八、错误处理与调试网络失败与提示词缺失的兜底instructions: async ({ prompts }) { try { return await prompts.getPrompt({ promptName: primary-prompt, timeout: 5000, }); } catch (error) { console.error(Prompt fetch failed:, error); return You are a helpful assistant.; // Fallback } };常见错误对照提示词未找到Prompt weather-prompt not found先在控制台核实提示词名是否存在并始终保留兜底 instructionsinstructions: async ({ prompts }) { try { return await prompts.getPrompt({ promptName: weather-prompt }); } catch (error) { console.error(Prompt fetch failed:, error); return Fallback instructions; } };缺少变量Variable userName not found in template为所有模板变量提供默认值return await prompts.getPrompt({ promptName: greeting-prompt, variables: { userName: context.get(userName) || Guest, currentTime: new Date().toISOString(), }, });认证失败Authentication failed验证环境变量是否按pk_/sk_前缀正确配置console.log(Public Key:, process.env.VOLTAGENT_PUBLIC_KEY?.substring(0, 8) ...); console.log(Secret Key:, process.env.VOLTAGENT_SECRET_KEY ? Set : Missing);结合前述构造器校验逻辑可知前缀不合法时 prompt 管理器根本不会被初始化报错会表现为 Prompt management is not enabled因此前缀检查是第一排查点。缓存过期更新后仍在用旧版本三种处理手段按侵入性递增——// 方案 1主动清空缓存 voltOpsClient.prompts.clearCache(); // 方案 2本次取词临时禁用缓存 return await prompts.getPrompt({ promptName: urgent-prompt, promptCache: { enabled: false }, }); // 方案 3等待 TTL 自然过期独立调试取词脱离 Agent 单独验证取词链路能快速区分网络/认证问题与Agent 配置问题const voltOpsClient new VoltOpsClient({ publicKey: process.env.VOLTAGENT_PUBLIC_KEY, secretKey: process.env.VOLTAGENT_SECRET_KEY, }); try { const prompt await voltOpsClient.prompts.getPrompt({ promptName: test-prompt, }); console.log(Success:, prompt); } catch (error) { console.error(Failed:, error); }九、完整示例将标签、变量、缓存与错误兜底组合起来的生产级写法import { openai } from ai-sdk/openai; import { Agent, VoltAgent, VoltOpsClient } from voltagent/core; const voltOpsClient new VoltOpsClient({ publicKey: process.env.VOLTAGENT_PUBLIC_KEY, secretKey: process.env.VOLTAGENT_SECRET_KEY, prompts: true, promptCache: { enabled: true, ttl: 300, }, }); const supportAgent new Agent({ name: SupportAgent, model: openai(gpt-4o-mini), instructions: async ({ prompts, context }) { const environment process.env.NODE_ENV production ? production : development; try { return await prompts.getPrompt({ promptName: customer-support-agent, label: environment, variables: { companyName: VoltAgent Corp, userName: context.get(userName) || Guest, tier: context.get(subscriptionTier) || free, supportHours: 9 AM - 6 PM EST, }, }); } catch (error) { console.error(Failed to fetch prompt:, error); return You are a helpful customer support agent. Assist users with their questions.; } }, }); new VoltAgent({ agents: { supportAgent }, voltOpsClient: voltOpsClient, });十、API 参考速查getPrompt 选项PromptReference选项类型必填说明promptNamestring是要获取的提示词名称versionnumber否指定版本号优先级高于 labellabelstring否环境标签production、staging 等variablesobject否模板变量键值对promptCacheobject否逐请求缓存覆盖enabled/ttltimeoutnumber否请求超时毫秒PromptCache 选项选项类型默认值说明enabledbooleantrue启用/禁用缓存ttlnumber300缓存有效期秒maxSizenumber100最大缓存条目数仅全局生效相关仓库资源资源路径官方使用指南website/prompt-engineering-docs/usage.mdVoltOpsClient 实现packages/core/src/voltops/client.ts提示词管理器缓存/模板packages/core/src/voltops/prompt-manager.ts本地提示词加载器packages/core/src/voltops/local-prompts.ts类型定义PromptReference 等packages/core/src/voltops/types.tsCLI prompts 命令packages/cli/src/commands/prompts.ts提示词创建指南website/prompt-engineering-docs/creating-prompts.md提示词导入导出website/prompt-engineering-docs/import-export.md小结VoltAgent 的提示词体系围绕线上 VoltOps 本地 Markdown 双源设计prompts.getPrompt在动态 instructions 回调中统一取词本地文件优先、线上回退标签与版本号支持多环境灰度发布模板变量与 context 打通实现个性化渲染且与缓存解耦内存缓存支持全局 TTL/maxSize 配置与逐请求覆盖并可通过clearCache与getCacheStats运维。配套的pnpm volt prompts pull让离线开发与快速迭代成为可能。遵循本文的缓存策略表与错误兜底模板可以把提示词管理从写死在代码里升级为可版本化、可灰度、可观测的工程能力。赞分享人工智能AI AgentAgent 框架后端多智能体RAG工具调用Agent 记忆【免费下载链接】voltagentAI Agent Engineering Platform built on an Open Source TypeScript AI Agent Framework项目地址https://gitcode.com/gh_mirrors/vo/voltagent点击查看免费下载相关推荐VoltAgent 动态提示词Dynamic Prompts实战用 VoltOps 提示词管理与模板变量打造可运营的 AgentVoltAgent 动态提示词Dynamic Prompts实战用 VoltOps 提示词管理与模板变量打造可运营的 Agent 导读 动态提示词Dyn人工智能AI AgentAgent 框架后端多智能体RAG工具调用Agent 记忆Agent 工作流AI 评测MCP 服务MCP Clients语音VoltAgent Prompt 创建与版本管理实战VoltOps 提示词工程完整指南VoltAgent Prompt 创建与版本管理实战VoltOps 提示词工程完整指南 本篇指南围绕 VoltAgentVoltOps平台的提示词Pro人工智能AI AgentAgent 框架后端多智能体RAG工具调用Agent 记忆Agent 工作流AI 评测MCP 服务MCP Clients语音VoltAgent VoltOps 提示词分析用量总览、版本指标与 Trace 溯源机制VoltAgent VoltOps 提示词分析用量总览、版本指标与 Trace 溯源机制 在 VoltAgent 的 VoltOps 提示词管理平台中 An人工智能AI AgentAgent 框架后端多智能体RAG工具调用Agent 记忆Agent 工作流AI 评测MCP 服务MCP Clients语音上一篇如何快速掌握机器学习模型融合Stacking与Blending终极指南下一篇5大决策框架彻底解决云平台选型难题从成本优化到架构设计的终极指南创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表