mirror of
https://github.com/microsoft/agent-framework.git
synced 2026-06-16 21:04:09 +08:00
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:
committed by
GitHub
Unverified
parent
ef798629e5
commit
838a7fd61d
+2
-4
@@ -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))
|
||||
|
||||
|
||||
+4
-5
@@ -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}")
|
||||
|
||||
"""
|
||||
|
||||
+1
-3
@@ -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)
|
||||
|
||||
+6
-8
@@ -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}")
|
||||
|
||||
Reference in New Issue
Block a user