Skip to content

Add output_format to AssistantAgent for structured output #6071

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

Merged
merged 9 commits into from
Apr 1, 2025

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 77.22%. Comparing base (9915b65) to head (8715ce6).
Report is 1 commits behind head on main.

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   77.19%   77.22%   +0.03%     
==========================================
  Files         197      197              
  Lines       13728    13745      +17     
==========================================
+ Hits        10597    10615      +18     
+ Misses       3131     3130       -1     
Flag Coverage Δ
unittests 77.22% <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
…/_assistant_agent.py

Co-authored-by: Victor Dibia <victordibia@microsoft.com>
@ekzhu ekzhu enabled auto-merge (squash) April 1, 2025 20:05
@ekzhu ekzhu merged commit 86237c9 into main Apr 1, 2025
54 checks passed
@ekzhu ekzhu deleted the ekzhu-assistant-agent-output-format branch April 1, 2025 20:11
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