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

如何确保LLM始终返回JSON响应?当前Agent配置存疑

问题解决方案

核心问题根源

你使用的chat-conversational-react-description类型Agent,设计初衷是支持多轮对话式的工具调用与自然语言交互,其内置Prompt会引导AI生成解释性的自然语言内容(比如思考过程、工具调用说明)。你附加在用户提示末尾的结构化输出指令,优先级远低于Agent的原生引导逻辑,因此AI经常忽略你的格式要求。

确保稳定获取结构化响应的方案

1. 更换适配结构化输出的Agent类型

优先使用structured-chat-zero-shot-react-description类型,该Agent原生支持结构化输出场景,内置Prompt会强化格式约束,配合自定义规则能大幅提升输出稳定性:

const executor = await initializeAgentExecutorWithOptions(tools, model, {
  agentType: 'structured-chat-zero-shot-react-description',
  verbose: false,
});

2. 将格式约束嵌入Agent的System Prompt

不要将格式指令附加在用户提示末尾,而是直接修改Agent的System Prompt,把结构化输出要求作为核心规则植入:

const systemPrompt = `你需要严格按照以下结构返回JSON格式的字符串:
type SomeObject = {
  field1: number,
  field2: number,
}
- 仅返回该JSON字符串,不得添加任何额外解释、Markdown语法或自然语言内容。
- 必须保证JSON格式合法。`;

const prompt = ChatPromptTemplate.fromMessages([
  ["system", systemPrompt],
  ["user", "{input}"],
]);

const agent = new StructuredChatAgent({
  llm: model,
  tools: tools,
  prompt: prompt,
});

const executor = AgentExecutor.fromAgentAndTools({
  agent: agent,
  tools: tools,
  verbose: false,
});

3. 使用输出解析器强制格式校验

借助LangChain的JsonOutputParser或StructuredOutputParser,直接定义输出结构并强制校验,AI输出不符合格式时会自动触发重试:

class SomeObject extends BaseModel {
  @Field(description="数字类型的字段1")
  field1: number;

  @Field(description="数字类型的字段2")
  field2: number;
}

const parser = new JsonOutputParser({ pydanticSchema: SomeObject });
const formatInstructions = parser.getFormatInstructions();

const prompt = ChatPromptTemplate.fromMessages([
  ["system", `请严格按照以下格式要求返回:${formatInstructions},不得添加任何额外内容。`],
  ["user", "{input}"],
]);

const chain = prompt.pipe(model).pipe(parser);
const result = await chain.invoke({ input: "你的查询内容" });

4. 简化逻辑:无需Agent时直接调用LLM+解析器

如果你的场景不需要复杂的工具调用流程,完全可以跳过Agent Executor,直接用LLM配合输出解析器,避免Agent原生Prompt的干扰:

// 沿用上面定义的parser和prompt
const chain = prompt.pipe(model).pipe(parser);
const structuredResult = await chain.invoke({ input: "你的查询内容" });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 08:12:24