mirror of
https://github.com/microsoft/agent-framework.git
synced 2026-06-16 21:04:09 +08:00
8b191de936
* .NET: Add Microsoft Fabric sample #3674 (#4230) Co-authored-by: Chris <66376200+crickman@users.noreply.github.com> * Python: Phase 2: Embedding clients for Ollama, Bedrock, and Azure AI Inference (#4207) * Phase 2: Embedding clients for Ollama, Bedrock, and Azure AI Inference Add embedding client implementations to existing provider packages: - OllamaEmbeddingClient: Text embeddings via Ollama's embed API - BedrockEmbeddingClient: Text embeddings via Amazon Titan on Bedrock - AzureAIInferenceEmbeddingClient: Text and image embeddings via Azure AI Inference, supporting Content | str input with separate model IDs for text (AZURE_AI_INFERENCE_EMBEDDING_MODEL_ID) and image (AZURE_AI_INFERENCE_IMAGE_EMBEDDING_MODEL_ID) endpoints Additional changes: - Rename EmbeddingCoT -> EmbeddingT, EmbeddingOptionsCoT -> EmbeddingOptionsT - Add otel_provider_name passthrough to all embedding clients - Register integration pytest marker in all packages - Add lazy-loading namespace exports for Ollama and Bedrock embeddings - Add image embedding sample using Cohere-embed-v3-english - Add azure-ai-inference dependency to azure-ai package Part of #1188 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Fix mypy duplicate name and ruff lint issues - Rename second 'vector' variable to 'img_vector' in image embedding loop - Combine nested with statements in tests - Remove unused result assignments in tests Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * updates from feedback * Fix CI failures in embedding usage handling - Fix Azure AI embedding mypy issues by normalizing vectors to list[float], safely accumulating optional usage token fields, and filtering None entries before constructing GeneratedEmbeddings - Avoid Bandit false positive by initializing usage details as an empty dict - Update OpenAI embedding tests to assert canonical usage keys (input_token_count/total_token_count) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * [Purview] Mark responses as responses and fix epoch bug for python long overflow (#4225) * .NET: Support InvokeMcpTool for declarative workflows (#4204) * Initial implementation of InvokeMcpTool in declarative workflow * Cleaned up sample implementation * Updated sample comments. * Added missing executor routing attribute * Fix PR comments. * Updated based on PR comments. * Updated based on PR comments. * Removed unnecessary using statement. * Update Python package versions to rc2 (#4258) - Bump core and azure-ai to 1.0.0rc2 - Bump preview packages to 1.0.0b260225 - Update dependencies to >=1.0.0rc2 - Add CHANGELOG entries for changes since rc1 - Update uv.lock Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * .NET: Fixing issue where OpenTelemetry span is never exported in .NET in-process workflow execution (#4196) * 1. Add reproduction test for issue #4155: workflow.run Activity never stopped in streaming OffThread path The WorkflowRunActivity_IsStopped_Streaming_OffThread test demonstrates that the workflow.run OpenTelemetry Activity created in StreamingRunEventStream.RunLoopAsync is started but never stopped when using the OffThread/Default streaming execution. The background run loop keeps running after event consumption completes, so the using Activity? declaration never disposes until explicit StopAsync() is called. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> 2. Fix workflow.run Activity never stopped in streaming OffThread execution (#4155) The workflow.run OpenTelemetry Activity in StreamingRunEventStream.RunLoopAsync was scoped to the method lifetime via 'using'. Since the run loop only exits on cancellation, the Activity was never stopped/exported until explicit disposal. Fix: Remove 'using' and explicitly dispose the Activity when the workflow reaches Idle status (all supersteps complete). A safety-net disposal in the finally block handles cancellation and error paths. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Add root-level workflow.session activity spanning run loop lifetime\n\nImplements two-level telemetry hierarchy per PR feedback from lokitoth:\n- workflow.session: spans the entire run loop / stream lifetime\n- workflow_invoke: per input-to-halt cycle, nested within the session\n\nThis ensures the session activity stays open across multiple turns,\nwhile individual run activities are created and disposed per cycle.\n\nAlso fixes linkedSource CancellationTokenSource disposal leak in\nStreamingRunEventStream (added using declaration)." * Address Copilot review: fix Activity/CTS disposal, rename activity, add error tag\n\n1. LockstepRunEventStream: Remove 'using' from Activity in async iterator\n and manually dispose in finally block (fixes #4155 pattern). Also dispose\n linkedSource CTS in finally to prevent leak.\n2. Tags.cs: Add ErrorMessage (\"error.message\") tag for runtime errors,\n distinct from BuildErrorMessage (\"build.error.message\").\n3. ActivityNames: Rename WorkflowRun from \"workflow_invoke\" to \"workflow.run\"\n for cross-language consistency.\n4. WorkflowTelemetryContext: Fix XML doc to say \"outer/parent span\" instead\n of \"root-level span\".\n5. ObservabilityTests: Assert WorkflowSession absence when DisableWorkflowRun\n is true.\n6. WorkflowRunActivityStopTests: Fix streaming test race by disposing\n StreamingRun before asserting activities are stopped.\n7. StreamingRunEventStream/LockstepRunEventStream: Use Tags.ErrorMessage\n instead of Tags.BuildErrorMessage for runtime error events." * Review fixes: revert workflow_invoke rename, use 'using' for linkedSource, move SessionStarted earlier\n\n- Revert ActivityNames.WorkflowRun back to \"workflow_invoke\" (OTEL semantic convention contract)\n- Use 'using' declaration for linkedSource CTS in LockstepRunEventStream (no timing sensitivity)\n- Move SessionStarted event before WaitForInputAsync in StreamingRunEventStream to match Lockstep behavior" * Improve naming and comments in WorkflowRunActivityStopTests" * Prevent session Activity.Current leak in lockstep mode, add nesting test Save and restore Activity.Current in LockstepRunEventStream.Start() so the session activity doesn't leak into caller code via AsyncLocal. Re-establish Activity.Current = sessionActivity before creating the run activity in TakeEventStreamAsync to preserve parent-child nesting. Add test verifying app activities after RunAsync are not parented under the session, and that the workflow_invoke activity nests under the session." * Fix stale XML doc: WorkflowRun -> WorkflowInvoke in ObservabilityTests --------- Co-authored-by: alliscode <bentho@microsoft.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Python / .NET Samples - Restructure and Improve Samples (Feature Branc… (#4092) * Python: .NET Samples - Restructure and Improve Samples (Feature Branch) (#4091) * Moved by agent (#4094) * Fix readme links * .NET Samples - Create `04-hosting` learning path step (#4098) * Agent move * Agent reorderd * Remove A2A section from README Removed A2A section from the Getting Started README. * Agent fixed links * Fix broken sample links in durable-agents README (#4101) * Initial plan * Fix broken internal links in documentation Co-authored-by: crickman <66376200+crickman@users.noreply.github.com> * Revert template link changes; keep only durable-agents README fix Co-authored-by: crickman <66376200+crickman@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: crickman <66376200+crickman@users.noreply.github.com> * .NET Samples - Create `03-workflows` learning path step (#4102) * Fix solution project path * Python: Fix broken markdown links to repo resources (outside /docs) (#4105) * Initial plan * Fix broken markdown links to repo resources Co-authored-by: crickman <66376200+crickman@users.noreply.github.com> * Update README to rename .NET Workflows Samples section --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: crickman <66376200+crickman@users.noreply.github.com> * .NET Samples - Create `02-agents` learning path step (#4107) * .NET: Fix broken relative link in GroupChatToolApproval README (#4108) * Initial plan * Fix broken link in GroupChatToolApproval README Co-authored-by: crickman <66376200+crickman@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: crickman <66376200+crickman@users.noreply.github.com> * Update labeler configuration for workflow samples * .NET - Reorder Agents samples to start from Step01 instead of Step04 (#4110) * Fix solution * Resolve new sample paths * Move new AgentSkills and AgentWithMemory_Step04 samples * Fix link * Fix readme path * fix: update stale dotnet/samples/Durable path reference in AGENTS.md Co-authored-by: crickman <66376200+crickman@users.noreply.github.com> * Moved new sample * Update solution * Resolve merge (new sample) * Sync to new sample - FoundryAgents_Step21_BingCustomSearch * Updated README * .NET Samples - Configuration Naming Update (#4149) * .NET: Restore AzureFunctions index parity with ConsoleApps under DurableAgents samples (#4221) * Clean-up `05_host_your_agent` * Config setting consistency * Refine samples * AGENTS.md * Move new samples * Re-order samples * Move new project and fixup solution * Fixup model config * Fix up new UT project --------- Co-authored-by: Copilot <198982749+Copilot@users.noreply.github.com> * Python: Fix Bedrock embedding test stub missing meta attribute (#4287) * Fix Bedrock embedding test stub missing meta attribute * Increase test coverage so gate passes * Python: (ag-ui): fix approval payloads being re-processed on subsequent conversation turns (#4232) * Fix ag-ui tool call issue * Safe json fix * Python: Update workflow orchestration samples to use AzureOpenAIResponsesClient (#4285) * Update workflow orchestration samples to use AzureOpenAIResponsesClient * Fix broken link * Move scripts to scripts folder --------- Co-authored-by: Roger Barreto <19890735+rogerbarreto@users.noreply.github.com> Co-authored-by: Chris <66376200+crickman@users.noreply.github.com> Co-authored-by: Eduard van Valkenburg <eavanvalkenburg@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Rishabh Chawla <rishabhchawla1995@gmail.com> Co-authored-by: Peter Ibekwe <109177538+peibekwe@users.noreply.github.com> Co-authored-by: Dmytro Struk <13853051+dmytrostruk@users.noreply.github.com> Co-authored-by: Ben Thomas <ben.thomas@microsoft.com> Co-authored-by: alliscode <bentho@microsoft.com> Co-authored-by: Copilot <198982749+Copilot@users.noreply.github.com> Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com>
307 lines
14 KiB
Python
307 lines
14 KiB
Python
# Copyright (c) Microsoft. All rights reserved.
|
|
|
|
import asyncio
|
|
import os
|
|
from typing import Annotated, cast
|
|
|
|
from agent_framework import (
|
|
Agent,
|
|
AgentResponse,
|
|
Message,
|
|
WorkflowEvent,
|
|
WorkflowRunState,
|
|
tool,
|
|
)
|
|
from agent_framework.azure import AzureOpenAIResponsesClient
|
|
from agent_framework.orchestrations import HandoffAgentUserRequest, HandoffBuilder
|
|
from azure.identity import AzureCliCredential
|
|
from dotenv import load_dotenv
|
|
|
|
# Load environment variables from .env file
|
|
load_dotenv()
|
|
|
|
"""Sample: Simple handoff workflow.
|
|
|
|
A handoff workflow defines a pattern that assembles agents in a mesh topology, allowing
|
|
them to transfer control to each other based on the conversation context.
|
|
|
|
Prerequisites:
|
|
- AZURE_AI_PROJECT_ENDPOINT must be your Azure AI Foundry Agent Service (V2) project endpoint.
|
|
- Azure OpenAI configured for AzureOpenAIResponsesClient with required environment variables.
|
|
- Authentication via azure-identity. Use AzureCliCredential and run `az login` before executing the sample.
|
|
|
|
Key Concepts:
|
|
- Auto-registered handoff tools: HandoffBuilder automatically creates handoff tools
|
|
for each participant, allowing the coordinator to transfer control to specialists
|
|
- Termination condition: Controls when the workflow stops requesting user input
|
|
- Request/response cycle: Workflow requests input, user responds, cycle continues
|
|
"""
|
|
|
|
|
|
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
|
|
# See:
|
|
# samples/02-agents/tools/function_tool_with_approval.py
|
|
# samples/02-agents/tools/function_tool_with_approval_and_sessions.py.
|
|
@tool(approval_mode="never_require")
|
|
def process_refund(order_number: Annotated[str, "Order number to process refund for"]) -> str:
|
|
"""Simulated function to process a refund for a given order number."""
|
|
return f"Refund processed successfully for order {order_number}."
|
|
|
|
|
|
@tool(approval_mode="never_require")
|
|
def check_order_status(order_number: Annotated[str, "Order number to check status for"]) -> str:
|
|
"""Simulated function to check the status of a given order number."""
|
|
return f"Order {order_number} is currently being processed and will ship in 2 business days."
|
|
|
|
|
|
@tool(approval_mode="never_require")
|
|
def process_return(order_number: Annotated[str, "Order number to process return for"]) -> str:
|
|
"""Simulated function to process a return for a given order number."""
|
|
return f"Return initiated successfully for order {order_number}. You will receive return instructions via email."
|
|
|
|
|
|
def create_agents(client: AzureOpenAIResponsesClient) -> tuple[Agent, Agent, Agent, Agent]:
|
|
"""Create and configure the triage and specialist agents.
|
|
|
|
Args:
|
|
client: The AzureOpenAIResponsesClient to use for creating agents.
|
|
|
|
Returns:
|
|
Tuple of (triage_agent, refund_agent, order_agent, return_agent)
|
|
"""
|
|
# Triage agent: Acts as the frontline dispatcher
|
|
triage_agent = client.as_agent(
|
|
instructions=(
|
|
"You are frontline support triage. Route customer issues to the appropriate specialist agents "
|
|
"based on the problem described."
|
|
),
|
|
name="triage_agent",
|
|
)
|
|
|
|
# Refund specialist: Handles refund requests
|
|
refund_agent = client.as_agent(
|
|
instructions="You process refund requests.",
|
|
name="refund_agent",
|
|
# In a real application, an agent can have multiple tools; here we keep it simple
|
|
tools=[process_refund],
|
|
)
|
|
|
|
# Order/shipping specialist: Resolves delivery issues
|
|
order_agent = client.as_agent(
|
|
instructions="You handle order and shipping inquiries.",
|
|
name="order_agent",
|
|
# In a real application, an agent can have multiple tools; here we keep it simple
|
|
tools=[check_order_status],
|
|
)
|
|
|
|
# Return specialist: Handles return requests
|
|
return_agent = client.as_agent(
|
|
instructions="You manage product return requests.",
|
|
name="return_agent",
|
|
# In a real application, an agent can have multiple tools; here we keep it simple
|
|
tools=[process_return],
|
|
)
|
|
|
|
return triage_agent, refund_agent, order_agent, return_agent
|
|
|
|
|
|
def _handle_events(events: list[WorkflowEvent]) -> list[WorkflowEvent[HandoffAgentUserRequest]]:
|
|
"""Process workflow events and extract any pending user input requests.
|
|
|
|
This function inspects each event type and:
|
|
- Prints workflow status changes (IDLE, IDLE_WITH_PENDING_REQUESTS, etc.)
|
|
- Displays final conversation snapshots when workflow completes
|
|
- Prints user input request prompts
|
|
- Collects all request_info events for response handling
|
|
|
|
Args:
|
|
events: List of WorkflowEvent to process
|
|
|
|
Returns:
|
|
List of WorkflowEvent[HandoffAgentUserRequest] representing pending user input requests
|
|
"""
|
|
requests: list[WorkflowEvent[HandoffAgentUserRequest]] = []
|
|
|
|
for event in events:
|
|
if event.type == "handoff_sent":
|
|
# handoff_sent event: Indicates a handoff has been initiated
|
|
print(f"\n[Handoff from {event.data.source} to {event.data.target} initiated.]")
|
|
elif event.type == "status" and event.state in {
|
|
WorkflowRunState.IDLE,
|
|
WorkflowRunState.IDLE_WITH_PENDING_REQUESTS,
|
|
}:
|
|
# Status event: Indicates workflow state changes
|
|
print(f"\n[Workflow Status] {event.state}")
|
|
elif event.type == "output":
|
|
# Output event: Contains contents generated by the workflow
|
|
data = event.data
|
|
if isinstance(data, AgentResponse):
|
|
for message in data.messages:
|
|
if not message.text:
|
|
# Skip messages without text (e.g., tool calls)
|
|
continue
|
|
speaker = message.author_name or message.role
|
|
print(f"- {speaker}: {message.text}")
|
|
elif event.type == "output":
|
|
# The output of the handoff workflow is a collection of chat messages from all participants
|
|
conversation = cast(list[Message], event.data)
|
|
if isinstance(conversation, list):
|
|
print("\n=== Final Conversation Snapshot ===")
|
|
for message in conversation:
|
|
speaker = message.author_name or message.role
|
|
print(f"- {speaker}: {message.text or [content.type for content in message.contents]}")
|
|
print("===================================")
|
|
elif event.type == "request_info" and isinstance(event.data, HandoffAgentUserRequest):
|
|
_print_handoff_agent_user_request(event.data.agent_response)
|
|
requests.append(cast(WorkflowEvent[HandoffAgentUserRequest], event))
|
|
|
|
return requests
|
|
|
|
|
|
def _print_handoff_agent_user_request(response: AgentResponse) -> None:
|
|
"""Display the agent's response messages when requesting user input.
|
|
|
|
This will happen when an agent generates a response that doesn't trigger
|
|
a handoff, i.e., the agent is asking the user for more information.
|
|
|
|
Args:
|
|
response: The AgentResponse from the agent requesting user input
|
|
"""
|
|
if not response.messages:
|
|
raise RuntimeError("Cannot print agent responses: response has no messages.")
|
|
|
|
print("\n[Agent is requesting your input...]")
|
|
|
|
# Print agent responses
|
|
for message in response.messages:
|
|
if not message.text:
|
|
# Skip messages without text (e.g., tool calls)
|
|
continue
|
|
speaker = message.author_name or message.role
|
|
print(f"- {speaker}: {message.text}")
|
|
|
|
|
|
async def main() -> None:
|
|
"""Main entry point for the handoff workflow demo.
|
|
|
|
This function demonstrates:
|
|
1. Creating triage and specialist agents
|
|
2. Building a handoff workflow with custom termination condition
|
|
3. Running the workflow with scripted user responses
|
|
4. Processing events and handling user input requests
|
|
|
|
The workflow uses scripted responses instead of interactive input to make
|
|
the demo reproducible and testable. In a production application, you would
|
|
replace the scripted_responses with actual user input collection.
|
|
"""
|
|
# Initialize the Azure OpenAI Responses client
|
|
client = AzureOpenAIResponsesClient(
|
|
project_endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
|
|
deployment_name=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
|
|
credential=AzureCliCredential(),
|
|
)
|
|
|
|
# Create all agents: triage + specialists
|
|
triage, refund, order, support = create_agents(client)
|
|
|
|
# Build the handoff workflow
|
|
# - participants: All agents that can participate in the workflow
|
|
# - with_start_agent: The triage agent is designated as the start agent, which means
|
|
# it receives all user input first and orchestrates handoffs to specialists
|
|
# - termination_condition: Custom logic to stop the request/response loop.
|
|
# Without this, the default behavior continues requesting user input until max_turns
|
|
# is reached. Here we use a custom condition that checks if the conversation has ended
|
|
# naturally (when one of the agents says something like "you're welcome").
|
|
workflow = (
|
|
HandoffBuilder(
|
|
name="customer_support_handoff",
|
|
participants=[triage, refund, order, support],
|
|
# Custom termination: Check if one of the agents has provided a closing message.
|
|
# This looks for the last message containing "welcome", which indicates the
|
|
# conversation has concluded naturally.
|
|
termination_condition=lambda conversation: (
|
|
len(conversation) > 0 and "welcome" in conversation[-1].text.lower()
|
|
),
|
|
)
|
|
.with_start_agent(triage)
|
|
.build()
|
|
)
|
|
|
|
# Scripted user responses for reproducible demo
|
|
# In a console application, replace this with:
|
|
# user_input = input("Your response: ")
|
|
# or integrate with a UI/chat interface
|
|
scripted_responses = [
|
|
"My order 1234 arrived damaged and the packaging was destroyed. I'd like to return it.",
|
|
"Please also process a refund for order 1234.",
|
|
"Thanks for resolving this.",
|
|
]
|
|
|
|
# Start the workflow with the initial user message
|
|
# run(..., stream=True) returns an async iterator of WorkflowEvent
|
|
print("[Starting workflow with initial user message...]\n")
|
|
initial_message = "Hello, I need assistance with my recent purchase."
|
|
print(f"- User: {initial_message}")
|
|
workflow_result = workflow.run(initial_message, stream=True)
|
|
pending_requests = _handle_events([event async for event in workflow_result])
|
|
|
|
# Process the request/response cycle
|
|
# The workflow will continue requesting input until:
|
|
# 1. The termination condition is met, OR
|
|
# 2. We run out of scripted responses
|
|
while pending_requests:
|
|
if not scripted_responses:
|
|
# No more scripted responses; terminate the workflow
|
|
responses = {req.request_id: HandoffAgentUserRequest.terminate() for req in pending_requests}
|
|
else:
|
|
# Get the next scripted response
|
|
user_response = scripted_responses.pop(0)
|
|
print(f"\n- User: {user_response}")
|
|
|
|
# Send response(s) to all pending requests
|
|
# In this demo, there's typically one request per cycle, but the API supports multiple
|
|
responses = {
|
|
req.request_id: HandoffAgentUserRequest.create_response(user_response) for req in pending_requests
|
|
}
|
|
|
|
# Send responses and get new events
|
|
# We use run(responses=...) to get events from the workflow, allowing us to
|
|
# display agent responses and handle new requests as they arrive
|
|
events = await workflow.run(responses=responses)
|
|
pending_requests = _handle_events(events)
|
|
|
|
"""
|
|
Sample Output:
|
|
|
|
[Starting workflow with initial user message...]
|
|
|
|
- User: Hello, I need assistance with my recent purchase.
|
|
- triage_agent: Could you please provide more details about the issue you're experiencing with your recent purchase? This will help me route you to the appropriate specialist.
|
|
|
|
[Workflow Status] IDLE_WITH_PENDING_REQUESTS
|
|
|
|
- User: My order 1234 arrived damaged and the packaging was destroyed. I'd like to return it.
|
|
- triage_agent: I've directed your request to our return agent, who will assist you with returning the damaged order. Thank you for your patience!
|
|
- return_agent: The return for your order 1234 has been successfully initiated. You will receive return instructions via email shortly. If you have any other questions or need further assistance, feel free to ask!
|
|
|
|
[Workflow Status] IDLE_WITH_PENDING_REQUESTS
|
|
|
|
- User: Thanks for resolving this.
|
|
|
|
=== Final Conversation Snapshot ===
|
|
- user: Hello, I need assistance with my recent purchase.
|
|
- triage_agent: Could you please provide more details about the issue you're experiencing with your recent purchase? This will help me route you to the appropriate specialist.
|
|
- user: My order 1234 arrived damaged and the packaging was destroyed. I'd like to return it.
|
|
- triage_agent: I've directed your request to our return agent, who will assist you with returning the damaged order. Thank you for your patience!
|
|
- return_agent: The return for your order 1234 has been successfully initiated. You will receive return instructions via email shortly. If you have any other questions or need further assistance, feel free to ask!
|
|
- user: Thanks for resolving this.
|
|
- triage_agent: You're welcome! If you have any more questions or need assistance in the future, feel free to reach out. Have a great day!
|
|
===================================
|
|
|
|
[Workflow Status] IDLE
|
|
""" # noqa: E501
|
|
|
|
|
|
if __name__ == "__main__":
|
|
asyncio.run(main())
|