You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Output Parser接入LangChain Agent并强制输出Zod结构化格式?

如何让LangChain Agent输出指定Zod结构化格式

要让LangChain的Agent输出符合Zod定义的结构化格式,需要将Zod输出解析器与Agent的提示词和执行流程结合,具体操作如下:

关键步骤

  • 导入ZodOutputParser,用于将LLM输出解析为Zod定义的结构
  • 生成解析器的格式指令,嵌入到系统提示词中,明确要求LLM最终输出符合指定结构的内容
  • 在Agent执行完成后,用解析器处理返回的结果

修改后的完整代码

import { TavilySearchResults } from "@langchain/community/tools/tavily_search";
import { ChatOpenAI } from "@langchain/openai";
import { ChatPromptTemplate, MessagesPlaceholder } from "@langchain/core/prompts";
import { z } from "zod";
import { createOpenAIToolsAgent, AgentExecutor } from "langchain/agents";
import { ZodOutputParser } from "@langchain/core/output_parsers"; // 新增导入

const model = new ChatOpenAI({ model: "gpt-4o", temperature: 0.7 });
const format = z.object({
    original: z.string().describe("The original phrase"),
    translated: z.string().describe("The translated phrase"),
});

// 创建Zod输出解析器实例
const parser = new ZodOutputParser(format);

const searchTool = new TavilySearchResults({ maxResults: 1 });
const tools = [searchTool];

// 修改提示词,加入解析器的格式指令,明确要求输出结构
const promptTemplate = ChatPromptTemplate.fromMessages([
    ["system", `Translate the user's message into {language}. 
    You must output your final result in the following JSON format:
    ${parser.getFormatInstructions()}
    Do not include any other text outside of this JSON structure.`],
    ["user", "{input}"],
    new MessagesPlaceholder("chat_history"),
    new MessagesPlaceholder("agent_scratchpad"),
]);

const agent = await createOpenAIToolsAgent({
    llm: model,
    tools,
    prompt: promptTemplate,
});

const agentExecutor = new AgentExecutor({
    agent,
    tools,
    verbose: false,
});

// 执行Agent并解析结果
const response = await agentExecutor.invoke({
    input: "Hello from the other side.",
    language: "italian",
    agent_scratchpad: [],
    chat_history: [],
});

// 用Zod解析器处理Agent的输出
const parsedResult = await parser.parse(response.output);
console.log(parsedResult);

关键说明

  1. 格式指令嵌入:通过parser.getFormatInstructions()生成LLM可识别的格式要求,确保Agent完成工具调用后返回符合Zod结构的JSON
  2. 结果解析:Agent执行后返回的response.output是原始文本,需要用parser.parse()将其转换为符合Zod定义的结构化对象,同时自动完成类型校验
  3. 工具兼容性:如果你的场景不需要搜索工具,可以直接移除TavilySearchResults相关代码,不影响结构化输出的逻辑

内容的提问来源于stack exchange,提问作者timthekoder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 05:42:34