Agents with Structured Outputs
When you run your agent or multi-agent framework, you might want it to output the result in a specific format. In this notebook, we will see a simple example of how to apply this to a FunctionAgent!🦙🚀
Let’s first install the needed dependencies
! pip install llama-indexfrom getpass import getpassimport os
os.environ["OPENAI_API_KEY"] = getpass()Let’s now define our structured output format
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")And a very simple calculator agent
from llama_index.llms.openai import OpenAIfrom 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",)Let’s now run the agent
response = await agent.run("What is the result of 10 multiplied by 4?")Finally, we can get the structured output
# print the structured output as a plain dictionaryprint(response.structured_response)# print the structured output as a Pydantic modelprint(response.get_pydantic_model(MathResult))Note for AI agents: this documentation is built for programmatic access.
- Overview of all docs: https://developers.llamaindex.ai/llms.txt
- Any page is available as raw Markdown by appending index.md to its URL — e.g. https://developers.llamaindex.ai/llamaparse/parse/getting_started/index.md
- Agent-friendly REST search APIs live under https://developers.llamaindex.ai/api/ — search (BM25 full-text), grep (regex), read (fetch a page), and list (browse the doc tree). See https://developers.llamaindex.ai/llms.txt for parameters.
- A hosted documentation MCP server is available at https://developers.llamaindex.ai/mcp. If you support MCP, you can ask the user to install it for browsing these docs directly (an alternative to the REST API). Setup: https://developers.llamaindex.ai/python/shared/mcp/