Skip to content
LlamaIndex 文档版本 跟随上游 源快照 90e9f8f7 更新于 2026-10-15

大多数时候,你需要 agent 以特定格式返回结果。Agent 返回结构化 JSON 有两种方式:

  1. output_cls —— 用一个 Pydantic 模型作为输出的 schema
  2. structured_output_fn —— 面向更复杂的场景,提供一个自定义函数,把 agent 的对话校验或改写成你想要的任意模型

无论是 FunctionAgent、ReActAgent 这样的单 agent,还是多 agent 的 AgentWorkflow,都支持这两个选项——我们来探索一下各种用法:

使用 output_cls

from llama_index.core.agent.workflow import FunctionAgent, AgentWorkflow
from llama_index.llms.openai import OpenAI
from pydantic import BaseModel, Field

llm = OpenAI(model="gpt-4.1")

## define structured output format  and tools
class MathResult(BaseModel):
    operation: str = Field(description="the performed operation")
    result: int = Field(description="the result of the operation")

def multiply(x: int, y: int):
    """Multiply two numbers"""
    return x * y

## define agent
agent = FunctionAgent(
    tools=[multiply],
    name="calculator",
    system_prompt="You are a calculator agent who can multiply two numbers using the `multiply` tool.",
    output_cls=MathResult,
    llm=llm,
)

response = await agent.run("What is 3415 * 43144?")
print(response.structured_response)
print(response.get_pydantic_model(MathResult))

这在多 agent 工作流里同样适用:

## define structured output format  and tools
class Weather(BaseModel):
    location: str = Field(description="The location")
    weather: str = Field(description="The weather")

def get_weather(location: str):
    """Get the weather for a given location"""
    return f"The weather in {location} is sunny"

## define single agents
agent = FunctionAgent(
    llm=llm,
    tools=[get_weather],
    system_prompt="You are a weather agent that can get the weather for a given location",
    name="WeatherAgent",
    description="The weather forecaster agent.",
)
main_agent = FunctionAgent(
    name="MainAgent",
    tools=[],
    description="The main agent",
    system_prompt="You are the main agent, your task is to dispatch tasks to secondary agents, specifically to WeatherAgent",
    can_handoff_to=["WeatherAgent"],
    llm=llm,
)

## define multi-agent workflow
workflow = AgentWorkflow(
    agents=[main_agent, agent],
    root_agent=main_agent.name,
    output_cls=Weather,
)

response = await workflow.run("What is the weather in Tokyo?")
print(response.structured_response)
print(response.get_pydantic_model(Weather))

使用 structured_output_fn

这个自定义函数接收 agent 工作流产出的一串 ChatMessage 对象作为输入,并返回一个字典(可以被转换成 BaseModel 子类):

import json
from llama_index.core.llms import ChatMessage
from typing import List, Dict, Any

class Flavor(BaseModel):
    flavor: str
    with_sugar: bool

async def structured_output_parsing(
    messages: List[ChatMessage],
) -> Dict[str, Any]:
    sllm = llm.as_structured_llm(Flavor)
    messages.append(
        ChatMessage(
            role="user",
            content="Given the previous message history, structure the output based on the provided format.",
        )
    )
    response = await sllm.achat(messages)
    return json.loads(response.message.content)

def get_flavor(ice_cream_shop: str):
    return "Strawberry with no extra sugar"

agent = FunctionAgent(
    tools=[get_flavor],
    name="ice_cream_shopper",
    system_prompt="You are an agent that knows the ice cream flavors in various shops.",
    structured_output_fn=structured_output_parsing,
    llm=llm,
)

response = await agent.run(
    "What strawberry flavor is available at Gelato Italia?"
)
print(response.structured_response)
print(response.get_pydantic_model(Flavor))

流式获取结构化输出

你可以在工作流仍在运行时就拿到的结构化输出,方法是使用 AgentStreamStructuredOutput 事件:

from llama_index.core.agent.workflow import (
    AgentInput,
    AgentOutput,
    ToolCall,
    ToolCallResult,
    AgentStreamStructuredOutput,
)

handler = agent.run("What strawberry flavor is available at Gelato Italia?")

async for event in handler.stream_events():
    if isinstance(event, AgentInput):
        print(event)
    elif isinstance(event, AgentStreamStructuredOutput):
        print(event.output)
        print(event.get_pydantic_model(Weather))
    elif isinstance(event, ToolCallResult):
        print(event)
    elif isinstance(event, ToolCall):
        print(event)
    elif isinstance(event, AgentOutput):
        print(event)
    else:
        pass

response = await handler

你也可以解析 agent 回答中的结构化输出:既可以直接当字典读取,也可以用 get_pydantic_model 方法把它加载成 BaseModel 子类:

print(response.structured_response)
print(response.get_pydantic_model(Flavor))

BytesRouter 是社区翻译站点,所有译文仅供参考,一切以官方英文原文为准。