Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add output_format to AssistantAgent for structured output #6071

Open
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

ekzhu
Copy link
Collaborator

@ekzhu ekzhu commented Mar 22, 2025

Resolves #5934

This PR adds ability for AssistantAgent to generate a StructuredMessage[T] where T is the content type in base model.

How to use?

from typing import Literal

from pydantic import BaseModel

from autogen_agentchat.agents import AssistantAgent
from autogen_ext.models.openai import OpenAIChatCompletionClient
from autogen_agentchat.ui import Console

# The response format for the agent as a Pydantic base model.
class AgentResponse(BaseModel):
    thoughts: str
    response: Literal["happy", "sad", "neutral"]


# Create an agent that uses the OpenAI GPT-4o model which supports structured output.
model_client = OpenAIChatCompletionClient(model="gpt-4o")
agent = AssistantAgent(
    "assistant",
    model_client=model_client,
    system_message="Categorize the input as happy, sad, or neutral following the JSON format.",
    # Setting the output format to AgentResponse to force the agent to produce a JSON string as response.
    output_content_type=AgentResponse,
)

result = await Console(agent.run_stream(task="I am happy."))

# Check the last message in the result, validate its type, and print the thoughts and response.
assert isinstance(result.messages[-1], StructuredMessage)
assert isinstance(result.messages[-1].content, AgentResponse)
print("Thought: ", result.messages[-1].content.thoughts)
print("Response: ", result.messages[-1].content.response)
await model_client.close()
---------- user ----------
I am happy.
---------- assistant ----------
{
  "thoughts": "The user explicitly states they are happy.",
  "response": "happy"
}
Thought:  The user explicitly states they are happy.
Response:  happy

Copy link

codecov bot commented Mar 22, 2025

Codecov Report

Attention: Patch coverage is 92.00000% with 2 lines in your changes missing coverage. Please review.

Project coverage is 76.99%. Comparing base (7487687) to head (ddbdd47).

Files with missing lines Patch % Lines
...t/src/autogen_agentchat/agents/_assistant_agent.py 92.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #6071      +/-   ##
==========================================
+ Coverage   76.96%   76.99%   +0.03%     
==========================================
  Files         192      192              
  Lines       13438    13455      +17     
==========================================
+ Hits        10342    10360      +18     
+ Misses       3096     3095       -1     
Flag Coverage Δ
unittests 76.99% <92.00%> (+0.03%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@ekzhu ekzhu requested a review from victordibia March 23, 2025 03:01
@ekzhu ekzhu marked this pull request as draft March 24, 2025 10:13
@ekzhu ekzhu marked this pull request as ready for review March 28, 2025 01:25

* If the model returns no tool call, then the response is immediately returned as a :class:`~autogen_agentchat.messages.TextMessage` in :attr:`~autogen_agentchat.base.Response.chat_message`.
If the `output_content_type` is set, the agent will respond with a :class:`~autogen_agentchat.messages.StructuredMessage`
instead of a :class:`~autogen_agentchat.messages.TextMessage` in the final response by default.
Copy link

@a-holm a-holm Mar 30, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps consider adding a note to the docstring mentioning that using output_content_type currently prevents the agent state from being saved/loaded via the declarative configuration mechanism (due to the check in _to_config). This would help manage user expectations.

Otherwise a very well-documented and clean PR that has tests and everything.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add output_content_type parameters to AssistantAgent
3 participants