Python: [BREAKING] Types API Review improvements (#3647)

* Replace Role and FinishReason classes with NewType + Literal

- Remove EnumLike metaclass from _types.py
- Replace Role class with NewType('Role', str) + RoleLiteral
- Replace FinishReason class with NewType('FinishReason', str) + FinishReasonLiteral
- Update all usages across codebase to use string literals
- Remove .value access patterns (direct string comparison now works)
- Add backward compatibility for legacy dict serialization format
- Update tests to reflect new string-based types

Addresses #3591, #3615

* Simplify ChatResponse and AgentResponse type hints (#3592)

- Remove overloads from ChatResponse.__init__
- Remove text parameter from ChatResponse.__init__
- Remove | dict[str, Any] from finish_reason and usage_details params
- Remove **kwargs from AgentResponse.__init__
- Both now accept ChatMessage | Sequence[ChatMessage] | None for messages
- Update docstrings and examples to reflect changes
- Fix tests that were using removed kwargs
- Fix Role type hint usage in ag-ui utils

* Remove text parameter from ChatResponseUpdate and AgentResponseUpdate (#3597)

- Remove text parameter from ChatResponseUpdate.__init__
- Remove text parameter from AgentResponseUpdate.__init__
- Remove **kwargs from both update classes
- Simplify contents parameter type to Sequence[Content] | None
- Update all usages to use contents=[Content.from_text(...)] pattern
- Fix imports in test files
- Update docstrings and examples

* Rename from_chat_response_updates to from_updates (#3593)

- ChatResponse.from_chat_response_updates → ChatResponse.from_updates
- ChatResponse.from_chat_response_generator → ChatResponse.from_update_generator
- AgentResponse.from_agent_run_response_updates → AgentResponse.from_updates

* Remove try_parse_value method from ChatResponse and AgentResponse (#3595)

- Remove try_parse_value method from ChatResponse
- Remove try_parse_value method from AgentResponse
- Remove try_parse_value calls from from_updates and from_update_generator methods
- Update samples to use try/except with response.value instead
- Update tests to use response.value pattern
- Users should now use response.value with try/except for safe parsing

* Add agent_id to AgentResponse and clarify author_name documentation (#3596)

- Add agent_id parameter to AgentResponse class
- Document that author_name is on ChatMessage objects, not responses
- Update ChatResponse docstring with author_name note
- Update AgentResponse docstring with author_name note

* Simplify ChatMessage.__init__ signature (#3618)

- Make contents a positional argument accepting Sequence[Content | str]
- Auto-convert strings in contents to TextContent
- Remove overloads, keep text kwarg for backward compatibility with serialization
- Update _parse_content_list to handle string items
- Update all usages across codebase to use new format: ChatMessage("role", ["text"])

* Allow Content as input on run and get_response

- Update prepare_messages and normalize_messages to accept Content
- Update type signatures in _agents.py and _clients.py
- Add tests for Content input handling

* Fix ChatMessage usage across packages and samples

Update all remaining ChatMessage(role=..., text=...) to use new
ChatMessage('role', ['text']) signature.

* Fix Role string usage and response format parsing

- Fix redis provider: remove .value access on string literals
- Fix durabletask ensure_response_format: set _response_format before accessing .value

* Fix ollama .value and ai_model_id issues, handle None in content list

- Fix ollama _chat_client: remove .value on string literals
- Fix ollama _chat_client: rename ai_model_id to model_id
- Fix _parse_content_list: skip None values gracefully

* Fix A2AAgent type signature to include Content

* Fix Role/FinishReason NewType dict annotations and improve test coverage to 95%

* Fix mypy errors for Role/FinishReason NewType usage

* Fix Role.TOOL and Role.ASSISTANT usage in _orchestrator_helpers.py

* Fix Role NewType usage in durabletask _models.py
This commit is contained in:
Eduard van Valkenburg
2026-02-04 11:13:23 +01:00
committed by GitHub
Unverified
parent ef798629e5
commit 838a7fd61d
341 changed files with 3766 additions and 3228 deletions
@@ -8,7 +8,6 @@ from agent_framework import (
WorkflowContext,
executor,
handler,
tool,
)
from typing_extensions import Never
@@ -13,7 +13,6 @@ from agent_framework import (
WorkflowRunState,
WorkflowStatusEvent,
handler,
tool,
)
from agent_framework._workflows._events import WorkflowOutputEvent
from agent_framework.azure import AzureOpenAIChatClient
@@ -123,7 +122,7 @@ async def main():
# Run the workflow with the user's initial message and stream events as they occur.
# This surfaces executor events, workflow outputs, run-state changes, and errors.
async for event in workflow.run_stream(
ChatMessage(role="user", text="Create a slogan for a new electric SUV that is affordable and fun to drive.")
ChatMessage("user", ["Create a slogan for a new electric SUV that is affordable and fun to drive."])
):
if isinstance(event, WorkflowStatusEvent):
prefix = f"State ({event.origin.value}): "
@@ -11,7 +11,6 @@ from agent_framework import (
WorkflowOutputEvent,
executor,
handler,
tool,
)
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential
@@ -9,12 +9,10 @@ from agent_framework import (
AgentResponse,
AgentRunUpdateEvent,
ChatMessage,
Role,
WorkflowBuilder,
WorkflowContext,
WorkflowOutputEvent,
executor,
tool,
)
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential
@@ -72,7 +70,7 @@ async def enrich_with_references(
) -> None:
"""Inject a follow-up user instruction that adds an external note for the next agent."""
conversation = list(draft.full_conversation or draft.agent_response.messages)
original_prompt = next((message.text for message in conversation if message.role == Role.USER), "")
original_prompt = next((message.text for message in conversation if message.role == "user"), "")
external_note = _lookup_external_note(original_prompt) or (
"No additional references were found. Please refine the previous assistant response for clarity."
)
@@ -82,7 +80,7 @@ async def enrich_with_references(
f"{external_note}\n\n"
"Please update the prior assistant answer so it weaves this note into the guidance."
)
conversation.append(ChatMessage(role=Role.USER, text=follow_up))
conversation.append(ChatMessage("user", [follow_up]))
await ctx.send_message(AgentExecutorRequest(messages=conversation))
@@ -16,7 +16,6 @@ from agent_framework import (
FunctionCallContent,
FunctionResultContent,
RequestInfoEvent,
Role,
WorkflowBuilder,
WorkflowContext,
WorkflowOutputEvent,
@@ -50,9 +49,9 @@ Prerequisites:
- Authentication via azure-identity. Run `az login` before executing.
"""
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def fetch_product_brief(
product_name: Annotated[str, Field(description="Product name to look up.")],
) -> str:
@@ -68,8 +67,8 @@ def fetch_product_brief(
}
return briefs.get(product_name.lower(), f"No stored brief for '{product_name}'.")
@tool(approval_mode="never_require")
@tool(approval_mode="never_require")
def get_brand_voice_profile(
voice_name: Annotated[str, Field(description="Brand or campaign voice to emulate.")],
) -> str:
@@ -149,7 +148,7 @@ class Coordinator(Executor):
await ctx.send_message(
AgentExecutorRequest(
messages=original_request.conversation
+ [ChatMessage(Role.USER, text="The draft is approved as-is.")],
+ [ChatMessage("user", text="The draft is approved as-is.")],
should_respond=True,
),
target_id=self.final_editor_id,
@@ -164,7 +163,7 @@ class Coordinator(Executor):
"Rewrite the draft from the previous assistant message into a polished final version. "
"Keep the response under 120 words and reflect any requested tone adjustments."
)
conversation.append(ChatMessage(Role.USER, text=instruction))
conversation.append(ChatMessage("user", text=instruction))
await ctx.send_message(
AgentExecutorRequest(messages=conversation, should_respond=True), target_id=self.writer_id
)
@@ -9,7 +9,6 @@ from agent_framework import (
WorkflowBuilder,
WorkflowContext,
handler,
tool,
)
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential
@@ -121,7 +120,7 @@ async def main():
# Run the workflow with the user's initial message.
# For foundational clarity, use run (non streaming) and print the workflow output.
events = await workflow.run(
ChatMessage(role="user", text="Create a slogan for a new electric SUV that is affordable and fun to drive.")
ChatMessage("user", ["Create a slogan for a new electric SUV that is affordable and fun to drive."])
)
# The terminal node yields output; print its contents.
outputs = events.get_outputs()
@@ -11,7 +11,6 @@ from agent_framework import (
FunctionResultContent,
HandoffAgentUserRequest,
HandoffBuilder,
Role,
WorkflowAgent,
tool,
)
@@ -118,7 +117,7 @@ def handle_response_and_requests(response: AgentResponse) -> dict[str, HandoffAg
pending_requests: dict[str, HandoffAgentUserRequest] = {}
for message in response.messages:
if message.text:
print(f"- {message.author_name or message.role.value}: {message.text}")
print(f"- {message.author_name or message.role}: {message.text}")
for content in message.contents:
if isinstance(content, FunctionCallContent):
if isinstance(content.arguments, dict):
@@ -200,7 +199,7 @@ async def main() -> None:
for request in pending_requests.values():
for message in request.agent_response.messages:
if message.text:
print(f"- {message.author_name or message.role.value}: {message.text}")
print(f"- {message.author_name or message.role}: {message.text}")
if not scripted_responses:
# No more scripted responses; terminate the workflow
@@ -217,7 +216,7 @@ async def main() -> None:
function_results = [
FunctionResultContent(call_id=req_id, result=response) for req_id, response in responses.items()
]
response = await agent.run(ChatMessage(role=Role.TOOL, contents=function_results))
response = await agent.run(ChatMessage("tool", function_results))
pending_requests = handle_response_and_requests(response)
@@ -6,7 +6,6 @@ from agent_framework import (
ChatAgent,
HostedCodeInterpreterTool,
MagenticBuilder,
tool,
)
from agent_framework.openai import OpenAIChatClient, OpenAIResponsesClient
@@ -11,7 +11,6 @@ from agent_framework import (
WorkflowBuilder,
WorkflowContext,
handler,
tool,
)
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential
@@ -2,7 +2,7 @@
import asyncio
from agent_framework import Role, SequentialBuilder
from agent_framework import SequentialBuilder
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential
@@ -52,7 +52,7 @@ async def main() -> None:
for i, msg in enumerate(agent_response.messages, start=1):
role_value = getattr(msg.role, "value", msg.role)
normalized_role = str(role_value).lower() if role_value is not None else "assistant"
name = msg.author_name or ("assistant" if normalized_role == Role.ASSISTANT.value else "user")
name = msg.author_name or ("assistant" if normalized_role == "assistant".value else "user")
print(f"{'-' * 60}\n{i:02d} [{name}]\n{msg.text}")
"""
@@ -20,13 +20,11 @@ from agent_framework import ( # noqa: E402
Executor,
FunctionCallContent,
FunctionResultContent,
Role,
WorkflowAgent,
WorkflowBuilder,
WorkflowContext,
handler,
response_handler,
tool,
)
from getting_started.workflows.agents.workflow_as_agent_reflection_pattern import ( # noqa: E402
ReviewRequest,
@@ -168,7 +166,7 @@ async def main() -> None:
result=human_response,
)
# Send the human review result back to the agent.
response = await agent.run(ChatMessage(role=Role.TOOL, contents=[human_review_function_result]))
response = await agent.run(ChatMessage("tool", [human_review_function_result]))
print(f"📤 Agent Response: {response.messages[-1].text}")
print("=" * 50)
@@ -11,11 +11,9 @@ from agent_framework import (
ChatMessage,
Content,
Executor,
Role,
WorkflowBuilder,
WorkflowContext,
handler,
tool,
)
from agent_framework.openai import OpenAIChatClient
from pydantic import BaseModel
@@ -81,7 +79,7 @@ class Reviewer(Executor):
# Construct review instructions and context.
messages = [
ChatMessage(
role=Role.SYSTEM,
role="system",
text=(
"You are a reviewer for an AI agent. Provide feedback on the "
"exchange between a user and the agent. Indicate approval only if:\n"
@@ -98,7 +96,7 @@ class Reviewer(Executor):
messages.extend(request.agent_messages)
# Add explicit review instruction.
messages.append(ChatMessage(role=Role.USER, text="Please review the agent's responses."))
messages.append(ChatMessage("user", ["Please review the agent's responses."]))
print("Reviewer: Sending review request to LLM...")
response = await self._chat_client.get_response(messages=messages, options={"response_format": _Response})
@@ -127,7 +125,7 @@ class Worker(Executor):
print("Worker: Received user messages, generating response...")
# Initialize chat with system prompt.
messages = [ChatMessage(role=Role.SYSTEM, text="You are a helpful assistant.")]
messages = [ChatMessage("system", ["You are a helpful assistant."])]
messages.extend(user_messages)
print("Worker: Calling LLM to generate response...")
@@ -162,7 +160,7 @@ class Worker(Executor):
# Emit approved result to external consumer via AgentRunUpdateEvent.
await ctx.add_event(
AgentRunUpdateEvent(self.id, data=AgentResponseUpdate(contents=contents, role=Role.ASSISTANT))
AgentRunUpdateEvent(self.id, data=AgentResponseUpdate(contents=contents, role="assistant"))
)
return
@@ -170,9 +168,9 @@ class Worker(Executor):
print("Worker: Regenerating response with feedback...")
# Incorporate review feedback.
messages.append(ChatMessage(role=Role.SYSTEM, text=review.feedback))
messages.append(ChatMessage("system", [review.feedback]))
messages.append(
ChatMessage(role=Role.SYSTEM, text="Please incorporate the feedback and regenerate the response.")
ChatMessage("system", ["Please incorporate the feedback and regenerate the response."])
)
messages.extend(request.user_messages)
@@ -78,7 +78,7 @@ async def main() -> None:
response1 = await agent.run(query1, thread=thread)
if response1.messages:
for msg in response1.messages:
speaker = msg.author_name or msg.role.value
speaker = msg.author_name or msg.role
print(f"[{speaker}]: {msg.text}")
# Second turn: Reference the previous topic
@@ -88,7 +88,7 @@ async def main() -> None:
response2 = await agent.run(query2, thread=thread)
if response2.messages:
for msg in response2.messages:
speaker = msg.author_name or msg.role.value
speaker = msg.author_name or msg.role
print(f"[{speaker}]: {msg.text}")
# Third turn: Ask a follow-up question
@@ -98,7 +98,7 @@ async def main() -> None:
response3 = await agent.run(query3, thread=thread)
if response3.messages:
for msg in response3.messages:
speaker = msg.author_name or msg.role.value
speaker = msg.author_name or msg.role
print(f"[{speaker}]: {msg.text}")
# Show the accumulated conversation history
@@ -108,7 +108,7 @@ async def main() -> None:
if thread.message_store:
history = await thread.message_store.list_messages()
for i, msg in enumerate(history, start=1):
role = msg.role.value if hasattr(msg.role, "value") else str(msg.role)
role = msg.role if hasattr(msg.role, "value") else str(msg.role)
speaker = msg.author_name or role
text_preview = msg.text[:80] + "..." if len(msg.text) > 80 else msg.text
print(f"{i:02d}. [{speaker}]: {text_preview}")
@@ -16,7 +16,6 @@ from agent_framework import (
Executor,
FileCheckpointStorage,
RequestInfoEvent,
Role,
Workflow,
WorkflowBuilder,
WorkflowCheckpoint,
@@ -26,7 +25,6 @@ from agent_framework import (
get_checkpoint_summary,
handler,
response_handler,
tool,
)
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential
@@ -94,7 +92,7 @@ class BriefPreparer(Executor):
# Hand the prompt to the writer agent. We always route through the
# workflow context so the runtime can capture messages for checkpointing.
await ctx.send_message(
AgentExecutorRequest(messages=[ChatMessage(Role.USER, text=prompt)], should_respond=True),
AgentExecutorRequest(messages=[ChatMessage("user", text=prompt)], should_respond=True),
target_id=self._agent_id,
)
@@ -156,7 +154,7 @@ class ReviewGateway(Executor):
f"Human guidance: {reply}"
)
await ctx.send_message(
AgentExecutorRequest(messages=[ChatMessage(Role.USER, text=prompt)], should_respond=True),
AgentExecutorRequest(messages=[ChatMessage("user", text=prompt)], should_respond=True),
target_id=self._writer_id,
)
@@ -37,7 +37,6 @@ from agent_framework import (
WorkflowContext,
WorkflowOutputEvent,
handler,
tool,
)
@@ -106,7 +106,7 @@ def create_workflow(checkpoint_storage: FileCheckpointStorage) -> tuple[Workflow
.with_checkpointing(checkpoint_storage)
.with_termination_condition(
# Terminate after 5 user messages for this demo
lambda conv: sum(1 for msg in conv if msg.role.value == "user") >= 5
lambda conv: sum(1 for msg in conv if msg.role == "user") >= 5
)
.build()
)
@@ -285,7 +285,7 @@ async def resume_with_responses(
# Now safe to cast event.data to list[ChatMessage]
conversation = cast(list[ChatMessage], event.data)
for msg in conversation[-3:]: # Show last 3 messages
author = msg.author_name or msg.role.value
author = msg.author_name or msg.role
text = msg.text[:100] + "..." if len(msg.text) > 100 else msg.text
print(f" {author}: {text}")
@@ -24,7 +24,6 @@ from agent_framework import (
WorkflowStatusEvent,
handler,
response_handler,
tool,
)
CHECKPOINT_DIR = Path(__file__).with_suffix("").parent / "tmp" / "sub_workflow_checkpoints"
@@ -31,7 +31,6 @@ from agent_framework import (
ChatMessageStore,
InMemoryCheckpointStorage,
SequentialBuilder,
tool,
)
from agent_framework.openai import OpenAIChatClient
@@ -70,7 +69,7 @@ async def basic_checkpointing() -> None:
response = await agent.run(query, checkpoint_storage=checkpoint_storage)
for msg in response.messages:
speaker = msg.author_name or msg.role.value
speaker = msg.author_name or msg.role
print(f"[{speaker}]: {msg.text}")
# Show checkpoints that were created
@@ -10,10 +10,9 @@ from agent_framework import (
WorkflowContext,
WorkflowExecutor,
handler,
tool,
)
from typing_extensions import Never
"""
Sample: Sub-Workflows (Basics)
@@ -16,7 +16,6 @@ from agent_framework import (
WorkflowExecutor,
handler,
response_handler,
tool,
)
from typing_extensions import Never
@@ -14,7 +14,6 @@ from agent_framework import (
WorkflowOutputEvent,
handler,
response_handler,
tool,
)
from typing_extensions import Never
@@ -9,12 +9,10 @@ from agent_framework import ( # Core chat primitives used to build requests
AgentExecutorResponse,
ChatAgent, # Output from an AgentExecutor
ChatMessage,
Role,
WorkflowBuilder, # Fluent builder for wiring executors and edges
WorkflowContext, # Per-run context and event bus
executor, # Decorator to declare a Python function as a workflow executor
tool,
)
)
from agent_framework.azure import AzureOpenAIChatClient # Thin client wrapper for Azure OpenAI chat models
from azure.identity import AzureCliCredential # Uses your az CLI login for credentials
from pydantic import BaseModel # Structured outputs for safer parsing
@@ -125,7 +123,7 @@ async def to_email_assistant_request(
"""
# Bridge executor. Converts a structured DetectionResult into a ChatMessage and forwards it as a new request.
detection = DetectionResult.model_validate_json(response.agent_response.text)
user_msg = ChatMessage(Role.USER, text=detection.email_content)
user_msg = ChatMessage("user", text=detection.email_content)
await ctx.send_message(AgentExecutorRequest(messages=[user_msg], should_respond=True))
@@ -189,7 +187,7 @@ async def main() -> None:
# Execute the workflow. Since the start is an AgentExecutor, pass an AgentExecutorRequest.
# The workflow completes when it becomes idle (no more work to do).
request = AgentExecutorRequest(messages=[ChatMessage(Role.USER, text=email)], should_respond=True)
request = AgentExecutorRequest(messages=[ChatMessage("user", text=email)], should_respond=True)
events = await workflow.run(request)
outputs = events.get_outputs()
if outputs:
@@ -13,13 +13,11 @@ from agent_framework import (
AgentExecutorResponse,
ChatAgent,
ChatMessage,
Role,
WorkflowBuilder,
WorkflowContext,
WorkflowEvent,
WorkflowOutputEvent,
executor,
tool,
)
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential
@@ -93,7 +91,7 @@ async def store_email(email_text: str, ctx: WorkflowContext[AgentExecutorRequest
await ctx.set_shared_state(CURRENT_EMAIL_ID_KEY, new_email.email_id)
await ctx.send_message(
AgentExecutorRequest(messages=[ChatMessage(Role.USER, text=new_email.email_content)], should_respond=True)
AgentExecutorRequest(messages=[ChatMessage("user", text=new_email.email_content)], should_respond=True)
)
@@ -120,7 +118,7 @@ async def submit_to_email_assistant(analysis: AnalysisResult, ctx: WorkflowConte
email: Email = await ctx.get_shared_state(f"{EMAIL_STATE_PREFIX}{analysis.email_id}")
await ctx.send_message(
AgentExecutorRequest(messages=[ChatMessage(Role.USER, text=email.email_content)], should_respond=True)
AgentExecutorRequest(messages=[ChatMessage("user", text=email.email_content)], should_respond=True)
)
@@ -135,7 +133,7 @@ async def summarize_email(analysis: AnalysisResult, ctx: WorkflowContext[AgentEx
# Only called for long NotSpam emails by selection_func
email: Email = await ctx.get_shared_state(f"{EMAIL_STATE_PREFIX}{analysis.email_id}")
await ctx.send_message(
AgentExecutorRequest(messages=[ChatMessage(Role.USER, text=email.email_content)], should_respond=True)
AgentExecutorRequest(messages=[ChatMessage("user", text=email.email_content)], should_respond=True)
)
@@ -9,7 +9,6 @@ from agent_framework import (
WorkflowContext,
WorkflowOutputEvent,
handler,
tool,
)
from typing_extensions import Never
@@ -10,11 +10,9 @@ from agent_framework import (
ChatMessage,
Executor,
ExecutorCompletedEvent,
Role,
WorkflowBuilder,
WorkflowContext,
handler,
tool,
)
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential
@@ -97,7 +95,7 @@ class SubmitToJudgeAgent(Executor):
f"Target: {self._target}\nGuess: {guess}\nResponse:"
)
await ctx.send_message(
AgentExecutorRequest(messages=[ChatMessage(Role.USER, text=prompt)], should_respond=True),
AgentExecutorRequest(messages=[ChatMessage("user", text=prompt)], should_respond=True),
target_id=self._judge_agent_id,
)
@@ -13,12 +13,10 @@ from agent_framework import ( # Core chat primitives used to form LLM requests
ChatAgent, # Case entry for a switch-case edge group
ChatMessage,
Default, # Default branch when no cases match
Role,
WorkflowBuilder, # Fluent builder for assembling the graph
WorkflowContext, # Per-run context and event bus
executor, # Decorator to turn a function into a workflow executor
tool,
)
)
from agent_framework.azure import AzureOpenAIChatClient # Thin client for Azure OpenAI chat models
from azure.identity import AzureCliCredential # Uses your az CLI login for credentials
from pydantic import BaseModel # Structured outputs with validation
@@ -100,7 +98,7 @@ async def store_email(email_text: str, ctx: WorkflowContext[AgentExecutorRequest
# Kick off the detector by forwarding the email as a user message to the spam_detection_agent.
await ctx.send_message(
AgentExecutorRequest(messages=[ChatMessage(Role.USER, text=new_email.email_content)], should_respond=True)
AgentExecutorRequest(messages=[ChatMessage("user", text=new_email.email_content)], should_respond=True)
)
@@ -121,7 +119,7 @@ async def submit_to_email_assistant(detection: DetectionResult, ctx: WorkflowCon
# Load the original content from shared state using the id carried in DetectionResult.
email: Email = await ctx.get_shared_state(f"{EMAIL_STATE_PREFIX}{detection.email_id}")
await ctx.send_message(
AgentExecutorRequest(messages=[ChatMessage(Role.USER, text=email.email_content)], should_respond=True)
AgentExecutorRequest(messages=[ChatMessage("user", text=email.email_content)], should_respond=True)
)
@@ -3,9 +3,9 @@
"""Ticketing plugin for CustomerSupport workflow."""
import uuid
from collections.abc import Callable
from dataclasses import dataclass
from enum import Enum
from collections.abc import Callable
# ANSI color codes
MAGENTA = "\033[35m"
@@ -10,8 +10,7 @@ from dataclasses import dataclass
from pathlib import Path
from typing import Annotated, Any
from agent_framework import FileCheckpointStorage, RequestInfoEvent, WorkflowOutputEvent
from agent_framework import tool
from agent_framework import FileCheckpointStorage, RequestInfoEvent, WorkflowOutputEvent, tool
from agent_framework.azure import AzureOpenAIChatClient
from agent_framework_declarative import ExternalInputRequest, ExternalInputResponse, WorkflowFactory
from azure.identity import AzureCliCredential
@@ -38,17 +37,20 @@ MENU_ITEMS = [
MenuItem(category="Drink", name="Soda", price=1.95, is_special=False),
]
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_menu() -> list[dict[str, Any]]:
"""Get all menu items."""
return [{"category": i.category, "name": i.name, "price": i.price} for i in MENU_ITEMS]
@tool(approval_mode="never_require")
def get_specials() -> list[dict[str, Any]]:
"""Get today's specials."""
return [{"category": i.category, "name": i.name, "price": i.price} for i in MENU_ITEMS if i.is_special]
@tool(approval_mode="never_require")
def get_item_price(name: Annotated[str, Field(description="Menu item name")]) -> str:
"""Get price of a menu item."""
@@ -13,9 +13,9 @@ from agent_framework import (
Executor,
WorkflowBuilder,
WorkflowContext,
tool,
executor,
handler,
tool,
)
from agent_framework.openai import OpenAIChatClient
@@ -29,11 +29,9 @@ from agent_framework import (
ChatMessage,
ConcurrentBuilder,
RequestInfoEvent,
Role,
WorkflowOutputEvent,
WorkflowRunState,
WorkflowStatusEvent,
tool,
)
from agent_framework._workflows._agent_executor import AgentExecutorResponse
from agent_framework.azure import AzureOpenAIChatClient
@@ -72,7 +70,7 @@ async def aggregate_with_synthesis(results: list[AgentExecutorResponse]) -> Any:
# Check for human feedback in the conversation (will be last user message if present)
if r.full_conversation:
for msg in reversed(r.full_conversation):
if msg.role == Role.USER and msg.text and "perspectives" not in msg.text.lower():
if msg.role == "user" and msg.text and "perspectives" not in msg.text.lower():
human_guidance = msg.text
break
except Exception:
@@ -82,14 +80,14 @@ async def aggregate_with_synthesis(results: list[AgentExecutorResponse]) -> Any:
guidance_text = f"\n\nHuman guidance: {human_guidance}" if human_guidance else ""
system_msg = ChatMessage(
Role.SYSTEM,
"system",
text=(
"You are a synthesis expert. Consolidate the following analyst perspectives "
"into one cohesive, balanced summary (3-4 sentences). If human guidance is provided, "
"prioritize aspects as directed."
),
)
user_msg = ChatMessage(Role.USER, text="\n\n".join(expert_sections) + guidance_text)
user_msg = ChatMessage("user", text="\n\n".join(expert_sections) + guidance_text)
response = await _chat_client.get_response([system_msg, user_msg])
return response.messages[-1].text if response.messages else ""
@@ -174,7 +172,7 @@ async def main() -> None:
else event.data.full_conversation
)
for msg in recent:
name = msg.author_name or msg.role.value
name = msg.author_name or msg.role
text = (msg.text or "")[:150]
print(f" [{name}]: {text}...")
print("-" * 40)
@@ -35,7 +35,6 @@ from agent_framework import (
WorkflowOutputEvent,
WorkflowRunState,
WorkflowStatusEvent,
tool,
)
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential
@@ -164,7 +163,7 @@ async def main() -> None:
if event.data:
messages: list[ChatMessage] = event.data
for msg in messages:
role = msg.role.value.capitalize()
role = msg.role.capitalize()
name = msg.author_name or "unknown"
text = (msg.text or "")[:200]
print(f"[{role}][{name}]: {text}...")
@@ -10,7 +10,6 @@ from agent_framework import (
ChatMessage, # Chat message structure
Executor, # Base class for workflow executors
RequestInfoEvent, # Event emitted when human input is requested
Role, # Enum of chat roles (user, assistant, system)
WorkflowBuilder, # Fluent builder for assembling the graph
WorkflowContext, # Per run context and event bus
WorkflowOutputEvent, # Event emitted when workflow yields output
@@ -18,8 +17,7 @@ from agent_framework import (
WorkflowStatusEvent, # Event emitted on run state changes
handler,
response_handler, # Decorator to expose an Executor method as a step
tool,
)
)
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential
from pydantic import BaseModel
@@ -88,7 +86,7 @@ class TurnManager(Executor):
- Input is a simple starter token (ignored here).
- Output is an AgentExecutorRequest that triggers the agent to produce a guess.
"""
user = ChatMessage(Role.USER, text="Start by making your first guess.")
user = ChatMessage("user", text="Start by making your first guess.")
await ctx.send_message(AgentExecutorRequest(messages=[user], should_respond=True))
@handler
@@ -138,7 +136,7 @@ class TurnManager(Executor):
# Provide feedback to the agent to try again.
# We keep the agent's output strictly JSON to ensure stable parsing on the next turn.
user_msg = ChatMessage(
Role.USER,
"user",
text=(f'Feedback: {reply}. Return ONLY a JSON object matching the schema {{"guess": <int 1..10>}}.'),
)
await ctx.send_message(AgentExecutorRequest(messages=[user_msg], should_respond=True))
@@ -32,7 +32,6 @@ from agent_framework import (
WorkflowOutputEvent,
WorkflowRunState,
WorkflowStatusEvent,
tool,
)
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential
@@ -109,7 +108,7 @@ async def main() -> None:
else event.data.full_conversation
)
for msg in recent:
name = msg.author_name or msg.role.value
name = msg.author_name or msg.role
text = (msg.text or "")[:150]
print(f" [{name}]: {text}...")
print("-" * 40)
@@ -132,7 +131,7 @@ async def main() -> None:
if event.data:
messages: list[ChatMessage] = event.data[-3:]
for msg in messages:
role = msg.role.value if msg.role else "unknown"
role = msg.role if msg.role else "unknown"
print(f"[{role}]: {msg.text}")
workflow_complete = True
@@ -11,7 +11,6 @@ from agent_framework import (
WorkflowContext,
WorkflowOutputEvent,
handler,
tool,
)
from typing_extensions import Never
@@ -12,7 +12,6 @@ from agent_framework import (
Executor,
WorkflowContext,
handler,
tool,
)
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential
@@ -3,7 +3,7 @@
import asyncio
from typing import Any
from agent_framework import ChatMessage, ConcurrentBuilder, Role
from agent_framework import ChatMessage, ConcurrentBuilder
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential
@@ -66,13 +66,13 @@ async def main() -> None:
# Ask the model to synthesize a concise summary of the experts' outputs
system_msg = ChatMessage(
Role.SYSTEM,
"system",
text=(
"You are a helpful assistant that consolidates multiple domain expert outputs "
"into one cohesive, concise summary with clear takeaways. Keep it under 200 words."
),
)
user_msg = ChatMessage(Role.USER, text="\n\n".join(expert_sections))
user_msg = ChatMessage("user", text="\n\n".join(expert_sections))
response = await chat_client.get_response([system_msg, user_msg])
# Return the model's final assistant text as the completion result
@@ -8,11 +8,9 @@ from agent_framework import (
ChatMessage,
ConcurrentBuilder,
Executor,
Role,
Workflow,
WorkflowContext,
handler,
tool,
)
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential
@@ -98,13 +96,13 @@ class SummarizationExecutor(Executor):
# Ask the model to synthesize a concise summary of the experts' outputs
system_msg = ChatMessage(
Role.SYSTEM,
"system",
text=(
"You are a helpful assistant that consolidates multiple domain expert outputs "
"into one cohesive, concise summary with clear takeaways. Keep it under 200 words."
),
)
user_msg = ChatMessage(Role.USER, text="\n\n".join(expert_sections))
user_msg = ChatMessage("user", text="\n\n".join(expert_sections))
response = await self.chat_client.get_response([system_msg, user_msg])
@@ -7,9 +7,7 @@ from agent_framework import (
ChatAgent,
ChatMessage,
GroupChatBuilder,
Role,
WorkflowOutputEvent,
tool,
)
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential
@@ -73,7 +71,7 @@ async def main() -> None:
.participants([researcher, writer])
# Set a hard termination condition: stop after 4 assistant messages
# The agent orchestrator will intelligently decide when to end before this limit but just in case
.with_termination_condition(lambda messages: sum(1 for msg in messages if msg.role == Role.ASSISTANT) >= 4)
.with_termination_condition(lambda messages: sum(1 for msg in messages if msg.role == "assistant") >= 4)
.build()
)
@@ -9,9 +9,7 @@ from agent_framework import (
ChatAgent,
ChatMessage,
GroupChatBuilder,
Role,
WorkflowOutputEvent,
tool,
)
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential
@@ -214,7 +212,7 @@ Share your perspective authentically. Feel free to:
GroupChatBuilder()
.with_orchestrator(agent=moderator)
.participants([farmer, developer, teacher, activist, spiritual_leader, artist, immigrant, doctor])
.with_termination_condition(lambda messages: sum(1 for msg in messages if msg.role == Role.ASSISTANT) >= 10)
.with_termination_condition(lambda messages: sum(1 for msg in messages if msg.role == "assistant") >= 10)
.build()
)
@@ -9,7 +9,6 @@ from agent_framework import (
GroupChatBuilder,
GroupChatState,
WorkflowOutputEvent,
tool,
)
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential
@@ -14,7 +14,6 @@ from agent_framework import (
WorkflowEvent,
WorkflowOutputEvent,
resolve_agent_id,
tool,
)
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential
@@ -95,7 +94,7 @@ def _display_event(event: WorkflowEvent) -> None:
conversation = cast(list[ChatMessage], event.data)
print("\n=== Final Conversation (Autonomous with Iteration) ===")
for message in conversation:
speaker = message.author_name or message.role.value
speaker = message.author_name or message.role
text_preview = message.text[:200] + "..." if len(message.text) > 200 else message.text
print(f"- {speaker}: {text_preview}")
print(f"\nTotal messages: {len(conversation)}")
@@ -131,7 +130,7 @@ async def main() -> None:
)
.with_termination_condition(
# Terminate after coordinator provides 5 assistant responses
lambda conv: sum(1 for msg in conv if msg.author_name == "coordinator" and msg.role.value == "assistant")
lambda conv: sum(1 for msg in conv if msg.author_name == "coordinator" and msg.role == "assistant")
>= 5
)
.build()
@@ -131,7 +131,7 @@ def _handle_events(events: list[WorkflowEvent]) -> list[RequestInfoEvent]:
if not message.text:
# Skip messages without text (e.g., tool calls)
continue
speaker = message.author_name or message.role.value
speaker = message.author_name or message.role
print(f"- {speaker}: {message.text}")
# HandoffSentEvent: Indicates a handoff has been initiated
@@ -151,7 +151,7 @@ def _handle_events(events: list[WorkflowEvent]) -> list[RequestInfoEvent]:
if isinstance(conversation, list):
print("\n=== Final Conversation Snapshot ===")
for message in conversation:
speaker = message.author_name or message.role.value
speaker = message.author_name or message.role
print(f"- {speaker}: {message.text or [content.type for content in message.contents]}")
print("===================================")
@@ -183,7 +183,7 @@ def _print_handoff_agent_user_request(response: AgentResponse) -> None:
if not message.text:
# Skip messages without text (e.g., tool calls)
continue
speaker = message.author_name or message.role.value
speaker = message.author_name or message.role
print(f"- {speaker}: {message.text}")
@@ -126,7 +126,7 @@ def _handle_events(events: list[WorkflowEvent]) -> list[RequestInfoEvent]:
if not message.text:
# Skip messages without text (e.g., tool calls)
continue
speaker = message.author_name or message.role.value
speaker = message.author_name or message.role
print(f"- {speaker}: {message.text}")
# HandoffSentEvent: Indicates a handoff has been initiated
@@ -146,7 +146,7 @@ def _handle_events(events: list[WorkflowEvent]) -> list[RequestInfoEvent]:
if isinstance(conversation, list):
print("\n=== Final Conversation Snapshot ===")
for message in conversation:
speaker = message.author_name or message.role.value
speaker = message.author_name or message.role
print(f"- {speaker}: {message.text or [content.type for content in message.contents]}")
print("===================================")
@@ -178,7 +178,7 @@ def _print_handoff_agent_user_request(response: AgentResponse) -> None:
if not message.text:
# Skip messages without text (e.g., tool calls)
continue
speaker = message.author_name or message.role.value
speaker = message.author_name or message.role
print(f"- {speaker}: {message.text}")
@@ -41,7 +41,6 @@ from agent_framework import (
WorkflowEvent,
WorkflowRunState,
WorkflowStatusEvent,
tool,
)
from azure.identity.aio import AzureCliCredential
@@ -157,7 +156,7 @@ async def main() -> None:
HandoffBuilder()
.participants([triage, code_specialist])
.with_start_agent(triage)
.with_termination_condition(lambda conv: sum(1 for msg in conv if msg.role.value == "user") >= 2)
.with_termination_condition(lambda conv: sum(1 for msg in conv if msg.role == "user") >= 2)
.build()
)
@@ -15,7 +15,6 @@ from agent_framework import (
MagenticOrchestratorEvent,
MagenticProgressLedger,
WorkflowOutputEvent,
tool,
)
from agent_framework.openai import OpenAIChatClient, OpenAIResponsesClient
@@ -16,7 +16,6 @@ from agent_framework import (
WorkflowOutputEvent,
WorkflowRunState,
WorkflowStatusEvent,
tool,
)
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity._credentials import AzureCliCredential
@@ -12,7 +12,6 @@ from agent_framework import (
MagenticPlanReviewRequest,
RequestInfoEvent,
WorkflowOutputEvent,
tool,
)
from agent_framework.openai import OpenAIChatClient
@@ -3,7 +3,7 @@
import asyncio
from typing import cast
from agent_framework import ChatMessage, Role, SequentialBuilder, WorkflowOutputEvent
from agent_framework import ChatMessage, SequentialBuilder, WorkflowOutputEvent
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential
@@ -53,7 +53,7 @@ async def main() -> None:
if outputs:
print("===== Final Conversation =====")
for i, msg in enumerate(outputs[-1], start=1):
name = msg.author_name or ("assistant" if msg.role == Role.ASSISTANT else "user")
name = msg.author_name or ("assistant" if msg.role == "assistant" else "user")
print(f"{'-' * 60}\n{i:02d} [{name}]\n{msg.text}")
"""
@@ -7,11 +7,9 @@ from agent_framework import (
AgentExecutorResponse,
ChatMessage,
Executor,
Role,
SequentialBuilder,
WorkflowContext,
handler,
tool,
)
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential
@@ -48,12 +46,12 @@ class Summarizer(Executor):
the output must be `list[ChatMessage]`.
"""
if not agent_response.full_conversation:
await ctx.send_message([ChatMessage(role=Role.ASSISTANT, text="No conversation to summarize.")])
await ctx.send_message([ChatMessage("assistant", ["No conversation to summarize."])])
return
users = sum(1 for m in agent_response.full_conversation if m.role == Role.USER)
assistants = sum(1 for m in agent_response.full_conversation if m.role == Role.ASSISTANT)
summary = ChatMessage(role=Role.ASSISTANT, text=f"Summary -> users:{users} assistants:{assistants}")
users = sum(1 for m in agent_response.full_conversation if m.role == "user")
assistants = sum(1 for m in agent_response.full_conversation if m.role == "assistant")
summary = ChatMessage("assistant", [f"Summary -> users:{users} assistants:{assistants}"])
final_conversation = list(agent_response.full_conversation) + [summary]
await ctx.send_message(final_conversation)
@@ -78,7 +76,7 @@ async def main() -> None:
print("===== Final Conversation =====")
messages: list[ChatMessage] | Any = outputs[0]
for i, msg in enumerate(messages, start=1):
name = msg.author_name or ("assistant" if msg.role == Role.ASSISTANT else "user")
name = msg.author_name or ("assistant" if msg.role == "assistant" else "user")
print(f"{'-' * 60}\n{i:02d} [{name}]\n{msg.text}")
"""
@@ -6,12 +6,10 @@ from agent_framework import (
ChatAgent,
ChatMessage,
Executor,
Role,
SequentialBuilder,
Workflow,
WorkflowContext,
handler,
tool,
)
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential
@@ -64,7 +62,7 @@ async def run_workflow(workflow: Workflow, query: str) -> None:
if outputs:
messages: list[ChatMessage] = outputs[0]
for message in messages:
name = message.author_name or ("assistant" if message.role == Role.ASSISTANT else "user")
name = message.author_name or ("assistant" if message.role == "assistant" else "user")
print(f"{name}: {message.text}")
else:
raise RuntimeError("No outputs received from the workflow.")
@@ -11,13 +11,11 @@ from agent_framework import ( # Core chat primitives to build LLM requests
Executor, # Base class for custom Python executors
ExecutorCompletedEvent,
ExecutorInvokedEvent,
Role, # Enum of chat roles (user, assistant, system)
WorkflowBuilder, # Fluent builder for wiring the workflow graph
WorkflowContext, # Per run context and event bus
WorkflowOutputEvent, # Event emitted when workflow yields output
handler, # Decorator to mark an Executor method as invokable
tool,
)
)
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential # Uses your az CLI login for credentials
from typing_extensions import Never
@@ -47,7 +45,7 @@ class DispatchToExperts(Executor):
@handler
async def dispatch(self, prompt: str, ctx: WorkflowContext[AgentExecutorRequest]) -> None:
# Wrap the incoming prompt as a user message for each expert and request a response.
initial_message = ChatMessage(Role.USER, text=prompt)
initial_message = ChatMessage("user", text=prompt)
await ctx.send_message(AgentExecutorRequest(messages=[initial_message], should_respond=True))
@@ -14,8 +14,7 @@ from agent_framework import (
WorkflowOutputEvent, # Event emitted when workflow yields output
WorkflowViz, # Utility to visualize a workflow graph
handler, # Decorator to expose an Executor method as a step
tool,
)
)
from typing_extensions import Never
"""
@@ -11,11 +11,9 @@ from agent_framework import (
AgentExecutorResponse,
ChatAgent,
ChatMessage,
Role,
WorkflowBuilder,
WorkflowContext,
executor,
tool,
)
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential
@@ -105,7 +103,7 @@ async def store_email(email_text: str, ctx: WorkflowContext[AgentExecutorRequest
await ctx.set_shared_state(CURRENT_EMAIL_ID_KEY, new_email.email_id)
await ctx.send_message(
AgentExecutorRequest(messages=[ChatMessage(Role.USER, text=new_email.email_content)], should_respond=True)
AgentExecutorRequest(messages=[ChatMessage("user", text=new_email.email_content)], should_respond=True)
)
@@ -136,7 +134,7 @@ async def submit_to_email_assistant(detection: DetectionResult, ctx: WorkflowCon
# Load the original content by id from shared state and forward it to the assistant.
email: Email = await ctx.get_shared_state(f"{EMAIL_STATE_PREFIX}{detection.email_id}")
await ctx.send_message(
AgentExecutorRequest(messages=[ChatMessage(Role.USER, text=email.email_content)], should_respond=True)
AgentExecutorRequest(messages=[ChatMessage("user", text=email.email_content)], should_respond=True)
)
@@ -97,7 +97,7 @@ def _print_output(event: WorkflowOutputEvent) -> None:
print("Workflow completed. Aggregated results from both agents:")
for msg in messages:
if msg.text:
print(f"- {msg.author_name or msg.role.value}: {msg.text}")
print(f"- {msg.author_name or msg.role}: {msg.text}")
async def main() -> None:
@@ -116,7 +116,7 @@ async def main() -> None:
print("\n" + "-" * 60)
print("Workflow completed. Final conversation:")
for msg in output:
role = msg.role.value if hasattr(msg.role, "value") else msg.role
role = msg.role if hasattr(msg.role, "value") else msg.role
text = msg.text[:200] + "..." if len(msg.text) > 200 else msg.text
print(f" [{role}]: {text}")
else:
@@ -9,12 +9,10 @@ from agent_framework import (
ChatAgent,
ChatMessage,
Executor,
Role,
WorkflowBuilder,
WorkflowContext,
WorkflowViz,
handler,
tool,
)
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential
@@ -41,7 +39,7 @@ class DispatchToExperts(Executor):
@handler
async def dispatch(self, prompt: str, ctx: WorkflowContext[AgentExecutorRequest]) -> None:
# Wrap the incoming prompt as a user message for each expert and request a response.
initial_message = ChatMessage(Role.USER, text=prompt)
initial_message = ChatMessage("user", text=prompt)
await ctx.send_message(AgentExecutorRequest(messages=[initial_message], should_respond=True))