支持结构化输出的智能体¶
当您运行智能体或多智能体框架时,可能需要它以特定格式输出结果。本笔记本将通过一个简单示例,展示如何为FunctionAgent实现这一功能!🦙🚀
首先安装所需的依赖项
In [ ]:
Copied!
! pip install llama-index
! pip install llama-index
In [ ]:
Copied!
from getpass import getpass
import os
os.environ["OPENAI_API_KEY"] = getpass()
from getpass import getpass
import os
os.environ["OPENAI_API_KEY"] = getpass()
现在我们来定义结构化输出格式
In [ ]:
Copied!
from pydantic import BaseModel, Field
class MathResult(BaseModel):
operation: str = Field(description="The operation that has been performed")
result: int = Field(description="Result of the operation")
from pydantic import BaseModel, Field
class MathResult(BaseModel):
operation: str = Field(description="The operation that has been performed")
result: int = Field(description="Result of the operation")
以及一个非常简单的计算器代理
In [ ]:
Copied!
from llama_index.llms.openai import OpenAI
from llama_index.core.agent.workflow import FunctionAgent
llm = OpenAI(model="gpt-4.1")
def add(x: int, y: int):
"""Add two numbers"""
return x + y
def multiply(x: int, y: int):
"""Multiply two numbers"""
return x * y
agent = FunctionAgent(
llm=llm,
output_cls=MathResult,
tools=[add, multiply],
system_prompt="You are a calculator agent that can add or multiply two numbers by calling tools",
name="calculator",
)
from llama_index.llms.openai import OpenAI
from llama_index.core.agent.workflow import FunctionAgent
llm = OpenAI(model="gpt-4.1")
def add(x: int, y: int):
"""Add two numbers"""
return x + y
def multiply(x: int, y: int):
"""Multiply two numbers"""
return x * y
agent = FunctionAgent(
llm=llm,
output_cls=MathResult,
tools=[add, multiply],
system_prompt="You are a calculator agent that can add or multiply two numbers by calling tools",
name="calculator",
)
现在让我们运行代理程序
In [ ]:
Copied!
response = await agent.run("What is the result of 10 multiplied by 4?")
response = await agent.run("What is the result of 10 multiplied by 4?")
最后,我们可以得到结构化输出
In [ ]:
Copied!
# print the structured output as a plain dictionary
print(response.structured_response)
# print the structured output as a Pydantic model
print(response.get_pydantic_model(MathResult))
# print the structured output as a plain dictionary
print(response.structured_response)
# print the structured output as a Pydantic model
print(response.get_pydantic_model(MathResult))