mirror of
https://github.com/microsoft/agent-framework.git
synced 2026-06-16 21:04:09 +08:00
Move Python durable samples to durable directory
- Moved getting_started/durabletask to durable/console_apps - Moved getting_started/azure_functions to durable/azure_functions - Updated all paths in README files - Created durable/README.md with overview - Updated main samples README.md with new structure Co-authored-by: larohra <41490930+larohra@users.noreply.github.com>
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
# Single Agent Sample (Python)
|
||||
|
||||
This sample demonstrates how to use the Durable Extension for Agent Framework to create a simple Azure Functions app that hosts a single AI agent and provides direct HTTP API access for interactive conversations.
|
||||
|
||||
## Key Concepts Demonstrated
|
||||
|
||||
- Defining a simple agent with the Microsoft Agent Framework and wiring it into
|
||||
an Azure Functions app via the Durable Extension for Agent Framework.
|
||||
- Calling the agent through generated HTTP endpoints (`/api/agents/Joker/run`).
|
||||
- Managing conversation state with thread identifiers, so multiple clients can
|
||||
interact with the agent concurrently without sharing context.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Follow the common setup steps in `../README.md` to install tooling, configure Azure OpenAI credentials, and install the Python dependencies for this sample.
|
||||
|
||||
## Running the Sample
|
||||
|
||||
Send a prompt to the Joker agent:
|
||||
|
||||
Bash (Linux/macOS/WSL):
|
||||
|
||||
```bash
|
||||
curl -i -X POST http://localhost:7071/api/agents/Joker/run \
|
||||
-d "Tell me a short joke about cloud computing."
|
||||
```
|
||||
|
||||
PowerShell:
|
||||
|
||||
```powershell
|
||||
Invoke-RestMethod -Method Post -Uri http://localhost:7071/api/agents/Joker/run `
|
||||
-Body "Tell me a short joke about cloud computing."
|
||||
```
|
||||
|
||||
The agent responds with a JSON payload that includes the generated joke.
|
||||
|
||||
> [!TIP]
|
||||
> To return immediately with an HTTP 202 response instead of waiting for the agent output, set the `x-ms-wait-for-response` header or include `"wait_for_response": false` in the request body. The default behavior waits for the response.
|
||||
|
||||
## Expected Output
|
||||
|
||||
The default plain-text response looks like the following:
|
||||
|
||||
```http
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: text/plain; charset=utf-8
|
||||
x-ms-thread-id: 4f205157170244bfbd80209df383757e
|
||||
|
||||
```
|
||||
|
||||
When you specify the `x-ms-wait-for-response` header or include `"wait_for_response": false` in the request body, the Functions host responds with an HTTP 202 and queues the request to run in the background. A typical response body looks like the following:
|
||||
|
||||
```json
|
||||
{
|
||||
"status": "accepted",
|
||||
"response": "Agent request accepted",
|
||||
"message": "Tell me a short joke about cloud computing.",
|
||||
"thread_id": "<guid>",
|
||||
"correlation_id": "<guid>"
|
||||
}
|
||||
```
|
||||
"correlation_id": "<guid>"
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,22 @@
|
||||
### Joker Agent Sample Interactions
|
||||
@baseUrl = http://localhost:7071
|
||||
@agentName = Joker
|
||||
@agentRoute = {{baseUrl}}/api/agents/{{agentName}}
|
||||
@healthRoute = {{baseUrl}}/api/health
|
||||
|
||||
### Health Check
|
||||
GET {{healthRoute}}
|
||||
|
||||
### Ask for a joke (JSON payload)
|
||||
POST {{agentRoute}}/run
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"message": "Add a security element to it.",
|
||||
"thread_id": "thread-001"
|
||||
}
|
||||
|
||||
### Ask for a joke (plain text payload)
|
||||
POST {{agentRoute}}/run
|
||||
|
||||
Give me a programming joke about race conditions.
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Host a single Azure OpenAI-powered agent inside Azure Functions.
|
||||
|
||||
Components used in this sample:
|
||||
- AzureOpenAIChatClient to call the Azure OpenAI chat deployment.
|
||||
- AgentFunctionApp to expose HTTP endpoints via the Durable Functions extension.
|
||||
|
||||
Prerequisites: set `AZURE_OPENAI_ENDPOINT` and `AZURE_OPENAI_CHAT_DEPLOYMENT_NAME` (plus `AZURE_OPENAI_API_KEY` or Azure CLI authentication) before starting the Functions host."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from agent_framework.azure import AgentFunctionApp, AzureOpenAIChatClient
|
||||
from azure.identity import AzureCliCredential
|
||||
|
||||
|
||||
# 1. Instantiate the agent with the chosen deployment and instructions.
|
||||
def _create_agent() -> Any:
|
||||
"""Create the Joker agent."""
|
||||
|
||||
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
|
||||
name="Joker",
|
||||
instructions="You are good at telling jokes.",
|
||||
)
|
||||
|
||||
|
||||
# 2. Register the agent with AgentFunctionApp so Azure Functions exposes the required triggers.
|
||||
app = AgentFunctionApp(agents=[_create_agent()], enable_health_check=True, max_poll_retries=50)
|
||||
|
||||
"""
|
||||
Expected output when invoking `POST /api/agents/Joker/run` with plain-text input:
|
||||
|
||||
HTTP/1.1 202 Accepted
|
||||
{
|
||||
"status": "accepted",
|
||||
"response": "Agent request accepted",
|
||||
"message": "Tell me a short joke about cloud computing.",
|
||||
"conversation_id": "<guid>",
|
||||
"correlation_id": "<guid>"
|
||||
}
|
||||
"""
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"version": "2.0",
|
||||
"extensionBundle": {
|
||||
"id": "Microsoft.Azure.Functions.ExtensionBundle",
|
||||
"version": "[4.*, 5.0.0)"
|
||||
},
|
||||
"extensions": {
|
||||
"durableTask": {
|
||||
"hubName": "%TASKHUB_NAME%"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"IsEncrypted": false,
|
||||
"Values": {
|
||||
"FUNCTIONS_WORKER_RUNTIME": "python",
|
||||
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
|
||||
"DURABLE_TASK_SCHEDULER_CONNECTION_STRING": "Endpoint=http://localhost:8080;TaskHub=default;Authentication=None",
|
||||
"TASKHUB_NAME": "default",
|
||||
"AZURE_OPENAI_ENDPOINT": "<AZURE_OPENAI_ENDPOINT>",
|
||||
"AZURE_OPENAI_CHAT_DEPLOYMENT_NAME": "<AZURE_OPENAI_CHAT_DEPLOYMENT_NAME>",
|
||||
"AZURE_OPENAI_API_KEY": "<AZURE_OPENAI_API_KEY>"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
# Agent Framework packages
|
||||
# To use the deployed version, uncomment the line below and comment out the local installation lines
|
||||
# agent-framework-azurefunctions
|
||||
|
||||
# Local installation (for development and testing)
|
||||
# Each package must be listed explicitly because pip doesn't resolve uv workspace sources.
|
||||
# Without explicit entries, pip would fetch transitive dependencies from PyPI instead of local source.
|
||||
-e ../../../../packages/core # Core framework - base dependency for all packages
|
||||
-e ../../../../packages/durabletask # Durable Task support - dependency of azurefunctions
|
||||
-e ../../../../packages/azurefunctions # Azure Functions integration - the main package for this sample
|
||||
|
||||
# Azure authentication
|
||||
azure-identity
|
||||
@@ -0,0 +1,104 @@
|
||||
# Multi-Agent Sample
|
||||
|
||||
This sample demonstrates how to use the Durable Extension for Agent Framework to create an Azure Functions app that hosts multiple AI agents and provides direct HTTP API access for interactive conversations with each agent.
|
||||
|
||||
## Key Concepts Demonstrated
|
||||
|
||||
- Using the Microsoft Agent Framework to define multiple AI agents with unique names and instructions.
|
||||
- Registering multiple agents with the Function app and running them using HTTP.
|
||||
- Conversation management (via thread IDs) for isolated interactions per agent.
|
||||
- Two different methods for registering agents: list-based initialization and incremental addition.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Complete the common environment preparation steps described in `../README.md`, including installing Azure Functions Core Tools, starting Azurite, configuring Azure OpenAI settings, and installing this sample's requirements.
|
||||
|
||||
## Running the Sample
|
||||
|
||||
With the environment setup and function app running, you can test the sample by sending HTTP requests to the different agent endpoints.
|
||||
|
||||
You can use the `demo.http` file to send messages to the agents, or a command line tool like `curl` as shown below:
|
||||
|
||||
> **Note:** Each endpoint waits for the agent response by default. To receive an immediate HTTP 202 instead, set the `x-ms-wait-for-response` header or include `"wait_for_response": false` in the request body.
|
||||
|
||||
### Test the Weather Agent
|
||||
|
||||
Bash (Linux/macOS/WSL):
|
||||
Weather agent request:
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:7071/api/agents/WeatherAgent/run \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"message": "What is the weather in Seattle?"}'
|
||||
```
|
||||
|
||||
Expected HTTP 202 payload:
|
||||
|
||||
```json
|
||||
{
|
||||
"status": "accepted",
|
||||
"response": "Agent request accepted",
|
||||
"message": "What is the weather in Seattle?",
|
||||
"thread_id": "<guid>",
|
||||
"correlation_id": "<guid>"
|
||||
}
|
||||
```
|
||||
|
||||
Math agent request:
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:7071/api/agents/MathAgent/run \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"message": "Calculate a 20% tip on a $50 bill"}'
|
||||
```
|
||||
|
||||
Expected HTTP 202 payload:
|
||||
|
||||
```json
|
||||
{
|
||||
"status": "accepted",
|
||||
"response": "Agent request accepted",
|
||||
"message": "Calculate a 20% tip on a $50 bill",
|
||||
"thread_id": "<guid>",
|
||||
"correlation_id": "<guid>"
|
||||
}
|
||||
```
|
||||
|
||||
Health check (optional):
|
||||
|
||||
```bash
|
||||
curl http://localhost:7071/api/health
|
||||
```
|
||||
|
||||
Expected response:
|
||||
|
||||
```json
|
||||
{
|
||||
"status": "healthy",
|
||||
"agents": [
|
||||
{"name": "WeatherAgent", "type": "ChatAgent"},
|
||||
{"name": "MathAgent", "type": "ChatAgent"}
|
||||
],
|
||||
"agent_count": 2
|
||||
}
|
||||
```
|
||||
|
||||
## Code Structure
|
||||
|
||||
The sample demonstrates two ways to register multiple agents:
|
||||
|
||||
### Option 1: Pass list of agents during initialization
|
||||
```python
|
||||
app = AgentFunctionApp(agents=[weather_agent, math_agent])
|
||||
```
|
||||
|
||||
### Option 2: Add agents incrementally (commented in sample)
|
||||
```python
|
||||
app = AgentFunctionApp()
|
||||
app.add_agent(weather_agent)
|
||||
app.add_agent(math_agent)
|
||||
```
|
||||
|
||||
Each agent automatically gets:
|
||||
- `POST /api/agents/{agent_name}/run` - Send messages to the agent
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
### DAFx Multi-Agent Function App - HTTP Samples
|
||||
### Use with the VS Code REST Client extension or any HTTP client
|
||||
###
|
||||
### API Structure:
|
||||
### - POST /api/agents/{agentName}/run -> Send a message to an agent
|
||||
### - GET /api/health -> Health check and agent metadata
|
||||
|
||||
### Variables
|
||||
@baseUrl = http://localhost:7071
|
||||
@weatherAgentName = WeatherAgent
|
||||
@mathAgentName = MathAgent
|
||||
@weatherAgentRoute = {{baseUrl}}/api/agents/{{weatherAgentName}}
|
||||
@mathAgentRoute = {{baseUrl}}/api/agents/{{mathAgentName}}
|
||||
@healthRoute = {{baseUrl}}/api/health
|
||||
|
||||
### Health Check
|
||||
# Confirms the Azure Functions app is running and both agents are registered
|
||||
# Expected response:
|
||||
# {
|
||||
# "status": "healthy",
|
||||
# "agents": [
|
||||
# {"name": "WeatherAgent", "type": "AzureOpenAIAssistantsAgent"},
|
||||
# {"name": "MathAgent", "type": "AzureOpenAIAssistantsAgent"}
|
||||
# ],
|
||||
# "agent_count": 2
|
||||
# }
|
||||
GET {{healthRoute}}
|
||||
|
||||
###
|
||||
|
||||
### Weather Agent - Current Conditions
|
||||
# Tests the Weather agent's tool-assisted response path
|
||||
# Expected response: { "response": "The weather in Seattle...", "status": "success" }
|
||||
POST {{weatherAgentRoute}}/run
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"message": "What is the weather in Seattle?",
|
||||
"thread_id": "weather-user-001"
|
||||
}
|
||||
|
||||
###
|
||||
|
||||
|
||||
### Math Agent - Tip Calculation
|
||||
# Exercises the Math agent with a calculation request
|
||||
# Expected response: { "response": "A 20% tip on a $50 bill is $10...", "status": "success" }
|
||||
POST {{mathAgentRoute}}/run
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"message": "Calculate a 20% tip on a $50 bill",
|
||||
"thread_id": "math-user-001"
|
||||
}
|
||||
|
||||
###
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
"""Host multiple Azure OpenAI agents inside a single Azure Functions app.
|
||||
|
||||
Components used in this sample:
|
||||
- AzureOpenAIChatClient to create agents bound to a shared Azure OpenAI deployment.
|
||||
- AgentFunctionApp to register multiple agents and expose dedicated HTTP endpoints.
|
||||
- Custom tool functions to demonstrate tool invocation from different agents.
|
||||
|
||||
Prerequisites: set `AZURE_OPENAI_ENDPOINT` and `AZURE_OPENAI_CHAT_DEPLOYMENT_NAME`, plus either
|
||||
`AZURE_OPENAI_API_KEY` or authenticate with Azure CLI before starting the Functions host."""
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from agent_framework.azure import AgentFunctionApp, AzureOpenAIChatClient
|
||||
from azure.identity import AzureCliCredential
|
||||
from agent_framework import tool
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 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_weather(location: str) -> dict[str, Any]:
|
||||
"""Get current weather for a location."""
|
||||
|
||||
logger.info(f"🔧 [TOOL CALLED] get_weather(location={location})")
|
||||
result = {
|
||||
"location": location,
|
||||
"temperature": 72,
|
||||
"conditions": "Sunny",
|
||||
"humidity": 45,
|
||||
}
|
||||
logger.info(f"✓ [TOOL RESULT] {result}")
|
||||
return result
|
||||
|
||||
@tool(approval_mode="never_require")
|
||||
def calculate_tip(bill_amount: float, tip_percentage: float = 15.0) -> dict[str, Any]:
|
||||
"""Calculate tip amount and total bill."""
|
||||
|
||||
logger.info(
|
||||
f"🔧 [TOOL CALLED] calculate_tip(bill_amount={bill_amount}, tip_percentage={tip_percentage})"
|
||||
)
|
||||
tip = bill_amount * (tip_percentage / 100)
|
||||
total = bill_amount + tip
|
||||
result = {
|
||||
"bill_amount": bill_amount,
|
||||
"tip_percentage": tip_percentage,
|
||||
"tip_amount": round(tip, 2),
|
||||
"total": round(total, 2),
|
||||
}
|
||||
logger.info(f"✓ [TOOL RESULT] {result}")
|
||||
return result
|
||||
|
||||
|
||||
# 1. Create multiple agents, each with its own instruction set and tools.
|
||||
chat_client = AzureOpenAIChatClient(credential=AzureCliCredential())
|
||||
|
||||
weather_agent = chat_client.as_agent(
|
||||
name="WeatherAgent",
|
||||
instructions="You are a helpful weather assistant. Provide current weather information.",
|
||||
tools=[get_weather],
|
||||
)
|
||||
|
||||
math_agent = chat_client.as_agent(
|
||||
name="MathAgent",
|
||||
instructions="You are a helpful math assistant. Help users with calculations like tip calculations.",
|
||||
tools=[calculate_tip],
|
||||
)
|
||||
|
||||
|
||||
# 2. Register both agents with AgentFunctionApp to expose their HTTP routes and health check.
|
||||
app = AgentFunctionApp(agents=[weather_agent, math_agent], enable_health_check=True, max_poll_retries=50)
|
||||
|
||||
# Option 2: Add agents after initialization (commented out as we're using Option 1)
|
||||
# app = AgentFunctionApp(enable_health_check=True)
|
||||
# app.add_agent(weather_agent)
|
||||
# app.add_agent(math_agent)
|
||||
|
||||
"""
|
||||
Expected output when invoking `POST /api/agents/WeatherAgent/run`:
|
||||
|
||||
HTTP/1.1 202 Accepted
|
||||
{
|
||||
"status": "accepted",
|
||||
"response": "Agent request accepted",
|
||||
"message": "What is the weather in Seattle?",
|
||||
"conversation_id": "<guid>",
|
||||
"correlation_id": "<guid>"
|
||||
}
|
||||
|
||||
Expected output when invoking `POST /api/agents/MathAgent/run`:
|
||||
|
||||
HTTP/1.1 202 Accepted
|
||||
{
|
||||
"status": "accepted",
|
||||
"response": "Agent request accepted",
|
||||
"message": "Calculate a 20% tip on a $50 bill",
|
||||
"conversation_id": "<guid>",
|
||||
"correlation_id": "<guid>"
|
||||
}
|
||||
"""
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"version": "2.0",
|
||||
"logging": {
|
||||
"applicationInsights": {
|
||||
"samplingSettings": {
|
||||
"isEnabled": true,
|
||||
"maxTelemetryItemsPerSecond": 20
|
||||
}
|
||||
}
|
||||
},
|
||||
"extensionBundle": {
|
||||
"id": "Microsoft.Azure.Functions.ExtensionBundle",
|
||||
"version": "[4.*, 5.0.0)"
|
||||
},
|
||||
"extensions": {
|
||||
"durableTask": {
|
||||
"hubName": "%TASKHUB_NAME%"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"IsEncrypted": false,
|
||||
"Values": {
|
||||
"FUNCTIONS_WORKER_RUNTIME": "python",
|
||||
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
|
||||
"DURABLE_TASK_SCHEDULER_CONNECTION_STRING": "Endpoint=http://localhost:8080;TaskHub=default;Authentication=None",
|
||||
"TASKHUB_NAME": "default",
|
||||
"AZURE_OPENAI_ENDPOINT": "<AZURE_OPENAI_ENDPOINT>",
|
||||
"AZURE_OPENAI_CHAT_DEPLOYMENT_NAME": "<AZURE_OPENAI_CHAT_DEPLOYMENT_NAME>",
|
||||
"AZURE_OPENAI_API_KEY": "<AZURE_OPENAI_API_KEY>"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
# Agent Framework packages
|
||||
# To use the deployed version, uncomment the line below and comment out the local installation lines
|
||||
# agent-framework-azurefunctions
|
||||
|
||||
# Local installation (for development and testing)
|
||||
# Each package must be listed explicitly because pip doesn't resolve uv workspace sources.
|
||||
# Without explicit entries, pip would fetch transitive dependencies from PyPI instead of local source.
|
||||
-e ../../../../packages/core # Core framework - base dependency for all packages
|
||||
-e ../../../../packages/durabletask # Durable Task support - dependency of azurefunctions
|
||||
-e ../../../../packages/azurefunctions # Azure Functions integration - the main package for this sample
|
||||
|
||||
# Azure authentication
|
||||
azure-identity
|
||||
@@ -0,0 +1,132 @@
|
||||
# Agent Response Callbacks with Redis Streaming
|
||||
|
||||
This sample demonstrates how to use Redis Streams with agent response callbacks to enable reliable, resumable streaming for durable agents. Clients can disconnect and reconnect without losing messages by using cursor-based pagination.
|
||||
|
||||
## Key Concepts Demonstrated
|
||||
|
||||
- Using `AgentResponseCallbackProtocol` to capture streaming agent responses
|
||||
- Persisting streaming chunks to Redis Streams for reliable delivery
|
||||
- Building a custom HTTP endpoint to read from Redis with Server-Sent Events (SSE) format
|
||||
- Supporting cursor-based resumption for disconnected clients
|
||||
- Managing Redis client lifecycle with async context managers
|
||||
|
||||
## Prerequisites
|
||||
|
||||
In addition to the common setup steps in `../README.md`, this sample requires Redis:
|
||||
|
||||
```bash
|
||||
# Start Redis
|
||||
docker run -d --name redis -p 6379:6379 redis:latest
|
||||
```
|
||||
|
||||
Update `local.settings.json` with your Redis connection string:
|
||||
|
||||
```json
|
||||
{
|
||||
"Values": {
|
||||
"REDIS_CONNECTION_STRING": "redis://localhost:6379"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Running the Sample
|
||||
|
||||
### Start the agent run
|
||||
|
||||
The agent executes in the background via durable orchestration. The `RedisStreamCallback` persists streaming chunks to Redis:
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:7071/api/agents/TravelPlanner/run \
|
||||
-H "Content-Type: text/plain" \
|
||||
-d "Plan a 3-day trip to Tokyo"
|
||||
```
|
||||
|
||||
Response (202 Accepted):
|
||||
```json
|
||||
{
|
||||
"status": "accepted",
|
||||
"response": "Agent request accepted",
|
||||
"conversation_id": "abc-123-def-456",
|
||||
"correlation_id": "xyz-789"
|
||||
}
|
||||
```
|
||||
|
||||
### Stream the response from Redis
|
||||
|
||||
Use the custom `/api/agent/stream/{conversation_id}` endpoint to read persisted chunks:
|
||||
|
||||
```bash
|
||||
curl http://localhost:7071/api/agent/stream/abc-123-def-456 \
|
||||
-H "Accept: text/event-stream"
|
||||
```
|
||||
|
||||
Response (SSE format):
|
||||
```
|
||||
id: 1734649123456-0
|
||||
event: message
|
||||
data: Here's a wonderful 3-day Tokyo itinerary...
|
||||
|
||||
id: 1734649123789-0
|
||||
event: message
|
||||
data: Day 1: Arrival and Shibuya...
|
||||
|
||||
id: 1734649124012-0
|
||||
event: done
|
||||
data: [DONE]
|
||||
```
|
||||
|
||||
### Resume from a cursor
|
||||
|
||||
Use a cursor ID from an SSE event to skip already-processed messages:
|
||||
|
||||
```bash
|
||||
curl "http://localhost:7071/api/agent/stream/abc-123-def-456?cursor=1734649123456-0" \
|
||||
-H "Accept: text/event-stream"
|
||||
```
|
||||
|
||||
## How It Works
|
||||
|
||||
### 1. Redis Callback
|
||||
|
||||
The `RedisStreamCallback` class implements `AgentResponseCallbackProtocol` to capture streaming updates:
|
||||
|
||||
```python
|
||||
class RedisStreamCallback(AgentResponseCallbackProtocol):
|
||||
async def on_streaming_response_update(self, update, context):
|
||||
# Write chunk to Redis Stream
|
||||
async with await get_stream_handler() as handler:
|
||||
await handler.write_chunk(thread_id, update.text, sequence)
|
||||
|
||||
async def on_agent_response(self, response, context):
|
||||
# Write end-of-stream marker
|
||||
async with await get_stream_handler() as handler:
|
||||
await handler.write_completion(thread_id, sequence)
|
||||
```
|
||||
|
||||
### 2. Custom Streaming Endpoint
|
||||
|
||||
The `/api/agent/stream/{conversation_id}` endpoint reads from Redis:
|
||||
|
||||
```python
|
||||
@app.route(route="agent/stream/{conversation_id}", methods=["GET"])
|
||||
async def stream(req):
|
||||
conversation_id = req.route_params.get("conversation_id")
|
||||
cursor = req.params.get("cursor") # Optional
|
||||
|
||||
async with await get_stream_handler() as handler:
|
||||
async for chunk in handler.read_stream(conversation_id, cursor):
|
||||
# Format and return chunks
|
||||
```
|
||||
|
||||
### 3. Redis Streams
|
||||
|
||||
Messages are stored in Redis Streams with automatic TTL (default: 10 minutes):
|
||||
|
||||
```
|
||||
Stream Key: agent-stream:{conversation_id}
|
||||
Entry: {
|
||||
"text": "chunk content",
|
||||
"sequence": "0",
|
||||
"timestamp": "1734649123456"
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,55 @@
|
||||
### Reliable Streaming with Redis - Demo HTTP Requests
|
||||
### Use with the VS Code REST Client extension or any HTTP client
|
||||
###
|
||||
### Workflow:
|
||||
### 1. POST /api/agents/{agentName}/run -> Start durable agent (returns conversation_id)
|
||||
### 2. GET /api/agent/stream/{id} -> Read chunks from Redis (SSE or plain text)
|
||||
### 3. Add ?cursor={id} to resume from a specific point
|
||||
###
|
||||
### Prerequisites:
|
||||
### - Redis: docker run -d --name redis -p 6379:6379 redis:latest
|
||||
### - Start function app: func start
|
||||
|
||||
### Variables
|
||||
@baseUrl = http://localhost:7071
|
||||
@agentName = TravelPlanner
|
||||
|
||||
### Health Check
|
||||
GET {{baseUrl}}/api/health
|
||||
|
||||
###
|
||||
|
||||
### Start Agent Run
|
||||
# Starts the agent in the background via durable orchestration.
|
||||
# The RedisStreamCallback persists streaming chunks to Redis.
|
||||
# @name trip
|
||||
POST {{baseUrl}}/api/agents/{{agentName}}/run
|
||||
Content-Type: text/plain
|
||||
|
||||
Plan a 3-day trip to Tokyo
|
||||
|
||||
###
|
||||
|
||||
### Stream from Redis (SSE format)
|
||||
# Reads persisted chunks from Redis using cursor-based pagination.
|
||||
# The conversation_id is automatically captured from the previous request.
|
||||
@conversationId = {{trip.response.body.$.conversation_id}}
|
||||
GET {{baseUrl}}/api/agent/stream/{{conversationId}}
|
||||
Accept: text/event-stream
|
||||
|
||||
###
|
||||
|
||||
### Stream from Redis (plain text)
|
||||
# Same as above, but returns plain text instead of SSE format
|
||||
GET {{baseUrl}}/api/agent/stream/{{conversationId}}
|
||||
Accept: text/plain
|
||||
|
||||
###
|
||||
|
||||
### Resume from cursor
|
||||
# Use a cursor ID from an SSE event to skip already-processed messages
|
||||
# Replace {cursor_id} with an actual entry ID from the SSE stream
|
||||
GET {{baseUrl}}/api/agent/stream/{{conversationId}}?cursor={cursor_id}
|
||||
Accept: text/event-stream
|
||||
|
||||
###
|
||||
@@ -0,0 +1,319 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
"""Reliable streaming for durable agents using Redis Streams.
|
||||
|
||||
This sample demonstrates how to implement reliable streaming for durable agents using Redis Streams.
|
||||
|
||||
Components used in this sample:
|
||||
- AzureOpenAIChatClient to create the travel planner agent with tools.
|
||||
- AgentFunctionApp with a Redis-based callback for persistent streaming.
|
||||
- Custom HTTP endpoint to resume streaming from any point using cursor-based pagination.
|
||||
|
||||
Prerequisites:
|
||||
- Set AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_CHAT_DEPLOYMENT_NAME
|
||||
- Redis running (docker run -d --name redis -p 6379:6379 redis:latest)
|
||||
- DTS and Azurite running (see parent README)
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
from datetime import timedelta
|
||||
|
||||
import azure.functions as func
|
||||
import redis.asyncio as aioredis
|
||||
from agent_framework import AgentResponseUpdate
|
||||
from agent_framework.azure import (
|
||||
AgentCallbackContext,
|
||||
AgentFunctionApp,
|
||||
AgentResponseCallbackProtocol,
|
||||
AzureOpenAIChatClient,
|
||||
)
|
||||
from azure.identity import AzureCliCredential
|
||||
from redis_stream_response_handler import RedisStreamResponseHandler, StreamChunk
|
||||
from tools import get_local_events, get_weather_forecast
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Configuration
|
||||
REDIS_CONNECTION_STRING = os.environ.get("REDIS_CONNECTION_STRING", "redis://localhost:6379")
|
||||
REDIS_STREAM_TTL_MINUTES = int(os.environ.get("REDIS_STREAM_TTL_MINUTES", "10"))
|
||||
|
||||
|
||||
async def get_stream_handler() -> RedisStreamResponseHandler:
|
||||
"""Create a new Redis stream handler for each request.
|
||||
|
||||
This avoids event loop conflicts in Azure Functions by creating
|
||||
a fresh Redis client in the current event loop context.
|
||||
"""
|
||||
# Create a new Redis client in the current event loop
|
||||
redis_client = aioredis.from_url(
|
||||
REDIS_CONNECTION_STRING,
|
||||
encoding="utf-8",
|
||||
decode_responses=False,
|
||||
)
|
||||
|
||||
return RedisStreamResponseHandler(
|
||||
redis_client=redis_client,
|
||||
stream_ttl=timedelta(minutes=REDIS_STREAM_TTL_MINUTES),
|
||||
)
|
||||
|
||||
|
||||
class RedisStreamCallback(AgentResponseCallbackProtocol):
|
||||
"""Callback that writes streaming updates to Redis Streams for reliable delivery.
|
||||
|
||||
This enables clients to disconnect and reconnect without losing messages.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._logger = logging.getLogger("durableagent.samples.redis_streaming")
|
||||
self._sequence_numbers = {} # Track sequence per thread
|
||||
|
||||
async def on_streaming_response_update(
|
||||
self,
|
||||
update: AgentResponseUpdate,
|
||||
context: AgentCallbackContext,
|
||||
) -> None:
|
||||
"""Write streaming update to Redis Stream.
|
||||
|
||||
Args:
|
||||
update: The streaming response update chunk.
|
||||
context: The callback context with thread_id, agent_name, etc.
|
||||
"""
|
||||
thread_id = context.thread_id
|
||||
if not thread_id:
|
||||
self._logger.warning("No thread_id available for streaming update")
|
||||
return
|
||||
|
||||
if not update.text:
|
||||
return
|
||||
|
||||
text = update.text
|
||||
|
||||
# Get or initialize sequence number for this thread
|
||||
if thread_id not in self._sequence_numbers:
|
||||
self._sequence_numbers[thread_id] = 0
|
||||
|
||||
sequence = self._sequence_numbers[thread_id]
|
||||
|
||||
try:
|
||||
# Use context manager to ensure Redis client is properly closed
|
||||
async with await get_stream_handler() as stream_handler:
|
||||
# Write chunk to Redis Stream using public API
|
||||
await stream_handler.write_chunk(thread_id, text, sequence)
|
||||
|
||||
self._sequence_numbers[thread_id] += 1
|
||||
|
||||
self._logger.info(
|
||||
"[%s][%s] Wrote chunk to Redis: seq=%d, text=%s",
|
||||
context.agent_name,
|
||||
thread_id[:8],
|
||||
sequence,
|
||||
text,
|
||||
)
|
||||
except Exception as ex:
|
||||
self._logger.error(f"Error writing to Redis stream: {ex}", exc_info=True)
|
||||
|
||||
async def on_agent_response(self, response, context: AgentCallbackContext) -> None:
|
||||
"""Write end-of-stream marker when agent completes.
|
||||
|
||||
Args:
|
||||
response: The final agent response.
|
||||
context: The callback context.
|
||||
"""
|
||||
thread_id = context.thread_id
|
||||
if not thread_id:
|
||||
return
|
||||
|
||||
sequence = self._sequence_numbers.get(thread_id, 0)
|
||||
|
||||
try:
|
||||
# Use context manager to ensure Redis client is properly closed
|
||||
async with await get_stream_handler() as stream_handler:
|
||||
# Write end-of-stream marker using public API
|
||||
await stream_handler.write_completion(thread_id, sequence)
|
||||
|
||||
self._logger.info(
|
||||
"[%s][%s] Agent completed, wrote end-of-stream marker",
|
||||
context.agent_name,
|
||||
thread_id[:8],
|
||||
)
|
||||
|
||||
# Clean up sequence tracker
|
||||
self._sequence_numbers.pop(thread_id, None)
|
||||
except Exception as ex:
|
||||
self._logger.error(f"Error writing end-of-stream marker: {ex}", exc_info=True)
|
||||
|
||||
|
||||
# Create the Redis streaming callback
|
||||
redis_callback = RedisStreamCallback()
|
||||
|
||||
|
||||
# Create the travel planner agent
|
||||
def create_travel_agent():
|
||||
"""Create the TravelPlanner agent with tools."""
|
||||
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
|
||||
name="TravelPlanner",
|
||||
instructions="""You are an expert travel planner who creates detailed, personalized travel itineraries.
|
||||
When asked to plan a trip, you should:
|
||||
1. Create a comprehensive day-by-day itinerary
|
||||
2. Include specific recommendations for activities, restaurants, and attractions
|
||||
3. Provide practical tips for each destination
|
||||
4. Consider weather and local events when making recommendations
|
||||
5. Include estimated times and logistics between activities
|
||||
|
||||
Always use the available tools to get current weather forecasts and local events
|
||||
for the destination to make your recommendations more relevant and timely.
|
||||
|
||||
Format your response with clear headings for each day and include emoji icons
|
||||
to make the itinerary easy to scan and visually appealing.""",
|
||||
tools=[get_weather_forecast, get_local_events],
|
||||
)
|
||||
|
||||
|
||||
# Create AgentFunctionApp with the Redis callback
|
||||
app = AgentFunctionApp(
|
||||
agents=[create_travel_agent()],
|
||||
enable_health_check=True,
|
||||
default_callback=redis_callback,
|
||||
max_poll_retries=100, # Increase for longer-running agents
|
||||
)
|
||||
|
||||
|
||||
# Custom streaming endpoint for reading from Redis
|
||||
# Use the standard /api/agents/TravelPlanner/run endpoint to start agent runs
|
||||
|
||||
|
||||
@app.function_name("stream")
|
||||
@app.route(route="agent/stream/{conversation_id}", methods=["GET"])
|
||||
async def stream(req: func.HttpRequest) -> func.HttpResponse:
|
||||
"""Resume streaming from a specific cursor position for an existing session.
|
||||
|
||||
This endpoint reads all currently available chunks from Redis for the given
|
||||
conversation ID, starting from the specified cursor (or beginning if no cursor).
|
||||
|
||||
Use this endpoint to resume a stream after disconnection. Pass the conversation ID
|
||||
and optionally a cursor (Redis entry ID) to continue from where you left off.
|
||||
|
||||
Query Parameters:
|
||||
cursor (optional): Redis stream entry ID to resume from. If not provided, starts from beginning.
|
||||
|
||||
Response Headers:
|
||||
Content-Type: text/event-stream or text/plain based on Accept header
|
||||
x-conversation-id: The conversation/thread ID
|
||||
|
||||
SSE Event Fields (when Accept: text/event-stream):
|
||||
id: Redis stream entry ID (use as cursor for resumption)
|
||||
event: "message" for content, "done" for completion, "error" for errors
|
||||
data: The text content or status message
|
||||
"""
|
||||
try:
|
||||
conversation_id = req.route_params.get("conversation_id")
|
||||
if not conversation_id:
|
||||
return func.HttpResponse(
|
||||
"Conversation ID is required.",
|
||||
status_code=400,
|
||||
)
|
||||
|
||||
# Get optional cursor from query string
|
||||
cursor = req.params.get("cursor")
|
||||
|
||||
logger.info(
|
||||
f"Resuming stream for conversation {conversation_id} from cursor: {cursor or '(beginning)'}"
|
||||
)
|
||||
|
||||
# Check Accept header to determine response format
|
||||
accept_header = req.headers.get("Accept", "")
|
||||
use_sse_format = "text/plain" not in accept_header.lower()
|
||||
|
||||
# Stream chunks from Redis
|
||||
return await _stream_to_client(conversation_id, cursor, use_sse_format)
|
||||
|
||||
except Exception as ex:
|
||||
logger.error(f"Error in stream endpoint: {ex}", exc_info=True)
|
||||
return func.HttpResponse(
|
||||
f"Internal server error: {str(ex)}",
|
||||
status_code=500,
|
||||
)
|
||||
|
||||
|
||||
async def _stream_to_client(
|
||||
conversation_id: str,
|
||||
cursor: str | None,
|
||||
use_sse_format: bool,
|
||||
) -> func.HttpResponse:
|
||||
"""Stream chunks from Redis to the HTTP response.
|
||||
|
||||
Args:
|
||||
conversation_id: The conversation ID to stream from.
|
||||
cursor: Optional cursor to resume from. If None, streams from the beginning.
|
||||
use_sse_format: True to use SSE format, false for plain text.
|
||||
|
||||
Returns:
|
||||
HTTP response with all currently available chunks.
|
||||
"""
|
||||
chunks = []
|
||||
|
||||
# Use context manager to ensure Redis client is properly closed
|
||||
async with await get_stream_handler() as stream_handler:
|
||||
try:
|
||||
async for chunk in stream_handler.read_stream(conversation_id, cursor):
|
||||
if chunk.error:
|
||||
logger.warning(f"Stream error for {conversation_id}: {chunk.error}")
|
||||
chunks.append(_format_error(chunk.error, use_sse_format))
|
||||
break
|
||||
|
||||
if chunk.is_done:
|
||||
chunks.append(_format_end_of_stream(chunk.entry_id, use_sse_format))
|
||||
break
|
||||
|
||||
if chunk.text:
|
||||
chunks.append(_format_chunk(chunk, use_sse_format))
|
||||
|
||||
except Exception as ex:
|
||||
logger.error(f"Error reading from Redis: {ex}", exc_info=True)
|
||||
chunks.append(_format_error(str(ex), use_sse_format))
|
||||
|
||||
# Return all chunks
|
||||
response_body = "".join(chunks)
|
||||
|
||||
return func.HttpResponse(
|
||||
body=response_body,
|
||||
mimetype="text/event-stream" if use_sse_format else "text/plain; charset=utf-8",
|
||||
headers={
|
||||
"Cache-Control": "no-cache",
|
||||
"Connection": "keep-alive",
|
||||
"x-conversation-id": conversation_id,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _format_chunk(chunk: StreamChunk, use_sse_format: bool) -> str:
|
||||
"""Format a text chunk."""
|
||||
if use_sse_format:
|
||||
return _format_sse_event("message", chunk.text, chunk.entry_id)
|
||||
return chunk.text
|
||||
|
||||
|
||||
def _format_end_of_stream(entry_id: str, use_sse_format: bool) -> str:
|
||||
"""Format end-of-stream marker."""
|
||||
if use_sse_format:
|
||||
return _format_sse_event("done", "[DONE]", entry_id)
|
||||
return "\n"
|
||||
|
||||
|
||||
def _format_error(error: str, use_sse_format: bool) -> str:
|
||||
"""Format error message."""
|
||||
if use_sse_format:
|
||||
return _format_sse_event("error", error, None)
|
||||
return f"\n[Error: {error}]\n"
|
||||
|
||||
|
||||
def _format_sse_event(event_type: str, data: str, event_id: str | None = None) -> str:
|
||||
"""Format a Server-Sent Event."""
|
||||
lines = []
|
||||
if event_id:
|
||||
lines.append(f"id: {event_id}")
|
||||
lines.append(f"event: {event_type}")
|
||||
lines.append(f"data: {data}")
|
||||
lines.append("")
|
||||
return "\n".join(lines) + "\n"
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"version": "2.0",
|
||||
"logging": {
|
||||
"applicationInsights": {
|
||||
"samplingSettings": {
|
||||
"isEnabled": true,
|
||||
"maxTelemetryItemsPerSecond": 20
|
||||
}
|
||||
}
|
||||
},
|
||||
"extensionBundle": {
|
||||
"id": "Microsoft.Azure.Functions.ExtensionBundle",
|
||||
"version": "[4.*, 5.0.0)"
|
||||
},
|
||||
"extensions": {
|
||||
"durableTask": {
|
||||
"hubName": "%TASKHUB_NAME%"
|
||||
}
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"IsEncrypted": false,
|
||||
"Values": {
|
||||
"FUNCTIONS_WORKER_RUNTIME": "python",
|
||||
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
|
||||
"DURABLE_TASK_SCHEDULER_CONNECTION_STRING": "Endpoint=http://localhost:8080;TaskHub=default;Authentication=None",
|
||||
"TASKHUB_NAME": "default",
|
||||
"AZURE_OPENAI_ENDPOINT": "<AZURE_OPENAI_ENDPOINT>",
|
||||
"AZURE_OPENAI_CHAT_DEPLOYMENT_NAME": "<AZURE_OPENAI_CHAT_DEPLOYMENT_NAME>",
|
||||
"AZURE_OPENAI_API_KEY": "<AZURE_OPENAI_API_KEY>",
|
||||
"REDIS_CONNECTION_STRING": "redis://localhost:6379",
|
||||
"REDIS_STREAM_TTL_MINUTES": "10"
|
||||
}
|
||||
}
|
||||
+200
@@ -0,0 +1,200 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
"""Redis-based streaming response handler for durable agents.
|
||||
|
||||
This module provides reliable, resumable streaming of agent responses using Redis Streams
|
||||
as a message broker. It enables clients to disconnect and reconnect without losing messages.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from datetime import timedelta
|
||||
from collections.abc import AsyncIterator
|
||||
|
||||
import redis.asyncio as aioredis
|
||||
|
||||
|
||||
@dataclass
|
||||
class StreamChunk:
|
||||
"""Represents a chunk of streamed data from Redis.
|
||||
|
||||
Attributes:
|
||||
entry_id: The Redis stream entry ID (used as cursor for resumption).
|
||||
text: The text content of the chunk, if any.
|
||||
is_done: Whether this is the final chunk in the stream.
|
||||
error: Error message if an error occurred, otherwise None.
|
||||
"""
|
||||
entry_id: str
|
||||
text: str | None = None
|
||||
is_done: bool = False
|
||||
error: str | None = None
|
||||
|
||||
|
||||
class RedisStreamResponseHandler:
|
||||
"""Handles agent responses by persisting them to Redis Streams.
|
||||
|
||||
This handler writes agent response updates to Redis Streams, enabling reliable,
|
||||
resumable streaming delivery to clients. Clients can disconnect and reconnect
|
||||
at any point using cursor-based pagination.
|
||||
|
||||
Attributes:
|
||||
MAX_EMPTY_READS: Maximum number of empty reads before timing out.
|
||||
POLL_INTERVAL_MS: Interval in milliseconds between polling attempts.
|
||||
"""
|
||||
|
||||
MAX_EMPTY_READS = 300
|
||||
POLL_INTERVAL_MS = 1000
|
||||
|
||||
def __init__(self, redis_client: aioredis.Redis, stream_ttl: timedelta):
|
||||
"""Initialize the Redis stream response handler.
|
||||
|
||||
Args:
|
||||
redis_client: The async Redis client instance.
|
||||
stream_ttl: Time-to-live for stream entries in Redis.
|
||||
"""
|
||||
self._redis = redis_client
|
||||
self._stream_ttl = stream_ttl
|
||||
|
||||
async def __aenter__(self):
|
||||
"""Enter async context manager."""
|
||||
return self
|
||||
|
||||
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
||||
"""Exit async context manager and close Redis connection."""
|
||||
await self._redis.aclose()
|
||||
|
||||
async def write_chunk(
|
||||
self,
|
||||
conversation_id: str,
|
||||
text: str,
|
||||
sequence: int,
|
||||
) -> None:
|
||||
"""Write a single text chunk to the Redis Stream.
|
||||
|
||||
Args:
|
||||
conversation_id: The conversation ID for this agent run.
|
||||
text: The text content to write.
|
||||
sequence: The sequence number for ordering.
|
||||
"""
|
||||
stream_key = self._get_stream_key(conversation_id)
|
||||
await self._redis.xadd(
|
||||
stream_key,
|
||||
{
|
||||
"text": text,
|
||||
"sequence": str(sequence),
|
||||
"timestamp": str(int(time.time() * 1000)),
|
||||
}
|
||||
)
|
||||
await self._redis.expire(stream_key, self._stream_ttl)
|
||||
|
||||
async def write_completion(
|
||||
self,
|
||||
conversation_id: str,
|
||||
sequence: int,
|
||||
) -> None:
|
||||
"""Write an end-of-stream marker to the Redis Stream.
|
||||
|
||||
Args:
|
||||
conversation_id: The conversation ID for this agent run.
|
||||
sequence: The final sequence number.
|
||||
"""
|
||||
stream_key = self._get_stream_key(conversation_id)
|
||||
await self._redis.xadd(
|
||||
stream_key,
|
||||
{
|
||||
"text": "",
|
||||
"sequence": str(sequence),
|
||||
"timestamp": str(int(time.time() * 1000)),
|
||||
"done": "true",
|
||||
}
|
||||
)
|
||||
await self._redis.expire(stream_key, self._stream_ttl)
|
||||
|
||||
async def read_stream(
|
||||
self,
|
||||
conversation_id: str,
|
||||
cursor: str | None = None,
|
||||
) -> AsyncIterator[StreamChunk]:
|
||||
"""Read entries from a Redis Stream with cursor-based pagination.
|
||||
|
||||
This method polls the Redis Stream for new entries, yielding chunks as they
|
||||
become available. Clients can resume from any point using the entry_id from
|
||||
a previous chunk.
|
||||
|
||||
Args:
|
||||
conversation_id: The conversation ID to read from.
|
||||
cursor: Optional cursor to resume from. If None, starts from beginning.
|
||||
|
||||
Yields:
|
||||
StreamChunk instances containing text content or status markers.
|
||||
"""
|
||||
stream_key = self._get_stream_key(conversation_id)
|
||||
start_id = cursor if cursor else "0-0"
|
||||
|
||||
empty_read_count = 0
|
||||
has_seen_data = False
|
||||
|
||||
while True:
|
||||
try:
|
||||
# Read up to 100 entries from the stream
|
||||
entries = await self._redis.xread(
|
||||
{stream_key: start_id},
|
||||
count=100,
|
||||
block=None,
|
||||
)
|
||||
|
||||
if not entries:
|
||||
# No entries found
|
||||
if not has_seen_data:
|
||||
empty_read_count += 1
|
||||
if empty_read_count >= self.MAX_EMPTY_READS:
|
||||
timeout_seconds = self.MAX_EMPTY_READS * self.POLL_INTERVAL_MS / 1000
|
||||
yield StreamChunk(
|
||||
entry_id=start_id,
|
||||
error=f"Stream not found or timed out after {timeout_seconds} seconds"
|
||||
)
|
||||
return
|
||||
|
||||
# Wait before polling again
|
||||
await asyncio.sleep(self.POLL_INTERVAL_MS / 1000)
|
||||
continue
|
||||
|
||||
has_seen_data = True
|
||||
|
||||
# Process entries from the stream
|
||||
for stream_name, stream_entries in entries:
|
||||
for entry_id, entry_data in stream_entries:
|
||||
start_id = entry_id.decode() if isinstance(entry_id, bytes) else entry_id
|
||||
|
||||
# Decode entry data
|
||||
text = entry_data.get(b"text", b"").decode() if b"text" in entry_data else None
|
||||
done = entry_data.get(b"done", b"").decode() if b"done" in entry_data else None
|
||||
error = entry_data.get(b"error", b"").decode() if b"error" in entry_data else None
|
||||
|
||||
if error:
|
||||
yield StreamChunk(entry_id=start_id, error=error)
|
||||
return
|
||||
|
||||
if done == "true":
|
||||
yield StreamChunk(entry_id=start_id, is_done=True)
|
||||
return
|
||||
|
||||
if text:
|
||||
yield StreamChunk(entry_id=start_id, text=text)
|
||||
|
||||
except Exception as ex:
|
||||
yield StreamChunk(entry_id=start_id, error=str(ex))
|
||||
return
|
||||
|
||||
@staticmethod
|
||||
def _get_stream_key(conversation_id: str) -> str:
|
||||
"""Generate the Redis key for a conversation's stream.
|
||||
|
||||
Args:
|
||||
conversation_id: The conversation ID.
|
||||
|
||||
Returns:
|
||||
The Redis stream key.
|
||||
"""
|
||||
return f"agent-stream:{conversation_id}"
|
||||
@@ -0,0 +1,16 @@
|
||||
# Agent Framework packages
|
||||
# To use the deployed version, uncomment the line below and comment out the local installation lines
|
||||
# agent-framework-azurefunctions
|
||||
|
||||
# Local installation (for development and testing)
|
||||
# Each package must be listed explicitly because pip doesn't resolve uv workspace sources.
|
||||
# Without explicit entries, pip would fetch transitive dependencies from PyPI instead of local source.
|
||||
-e ../../../../packages/core # Core framework - base dependency for all packages
|
||||
-e ../../../../packages/durabletask # Durable Task support - dependency of azurefunctions
|
||||
-e ../../../../packages/azurefunctions # Azure Functions integration - the main package for this sample
|
||||
|
||||
# Azure authentication
|
||||
azure-identity
|
||||
|
||||
# Redis client
|
||||
redis
|
||||
@@ -0,0 +1,165 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
"""Mock travel tools for demonstration purposes.
|
||||
|
||||
In a real application, these would call actual weather and events APIs.
|
||||
"""
|
||||
|
||||
from typing import Annotated
|
||||
|
||||
|
||||
def get_weather_forecast(
|
||||
destination: Annotated[str, "The destination city or location"],
|
||||
date: Annotated[str, 'The date for the forecast (e.g., "2025-01-15" or "next Monday")'],
|
||||
) -> str:
|
||||
"""Get the weather forecast for a destination on a specific date.
|
||||
|
||||
Use this to provide weather-aware recommendations in the itinerary.
|
||||
|
||||
Args:
|
||||
destination: The destination city or location.
|
||||
date: The date for the forecast.
|
||||
|
||||
Returns:
|
||||
A weather forecast summary.
|
||||
"""
|
||||
# Mock weather data based on destination for realistic responses
|
||||
weather_by_region = {
|
||||
"Tokyo": ("Partly cloudy with a chance of light rain", 58, 45),
|
||||
"Paris": ("Overcast with occasional drizzle", 52, 41),
|
||||
"New York": ("Clear and cold", 42, 28),
|
||||
"London": ("Foggy morning, clearing in afternoon", 48, 38),
|
||||
"Sydney": ("Sunny and warm", 82, 68),
|
||||
"Rome": ("Sunny with light breeze", 62, 48),
|
||||
"Barcelona": ("Partly sunny", 59, 47),
|
||||
"Amsterdam": ("Cloudy with light rain", 46, 38),
|
||||
"Dubai": ("Sunny and hot", 85, 72),
|
||||
"Singapore": ("Tropical thunderstorms in afternoon", 88, 77),
|
||||
"Bangkok": ("Hot and humid, afternoon showers", 91, 78),
|
||||
"Los Angeles": ("Sunny and pleasant", 72, 55),
|
||||
"San Francisco": ("Morning fog, afternoon sun", 62, 52),
|
||||
"Seattle": ("Rainy with breaks", 48, 40),
|
||||
"Miami": ("Warm and sunny", 78, 65),
|
||||
"Honolulu": ("Tropical paradise weather", 82, 72),
|
||||
}
|
||||
|
||||
# Find a matching destination or use a default
|
||||
forecast = ("Partly cloudy", 65, 50)
|
||||
for city, weather in weather_by_region.items():
|
||||
if city.lower() in destination.lower():
|
||||
forecast = weather
|
||||
break
|
||||
|
||||
condition, high_f, low_f = forecast
|
||||
high_c = (high_f - 32) * 5 // 9
|
||||
low_c = (low_f - 32) * 5 // 9
|
||||
|
||||
recommendation = _get_weather_recommendation(condition)
|
||||
|
||||
return f"""Weather forecast for {destination} on {date}:
|
||||
Conditions: {condition}
|
||||
High: {high_f}°F ({high_c}°C)
|
||||
Low: {low_f}°F ({low_c}°C)
|
||||
|
||||
Recommendation: {recommendation}"""
|
||||
|
||||
|
||||
def get_local_events(
|
||||
destination: Annotated[str, "The destination city or location"],
|
||||
date: Annotated[str, 'The date to search for events (e.g., "2025-01-15" or "next week")'],
|
||||
) -> str:
|
||||
"""Get local events and activities happening at a destination around a specific date.
|
||||
|
||||
Use this to suggest timely activities and experiences.
|
||||
|
||||
Args:
|
||||
destination: The destination city or location.
|
||||
date: The date to search for events.
|
||||
|
||||
Returns:
|
||||
A list of local events and activities.
|
||||
"""
|
||||
# Mock events data based on destination
|
||||
events_by_city = {
|
||||
"Tokyo": [
|
||||
"🎭 Kabuki Theater Performance at Kabukiza Theatre - Traditional Japanese drama",
|
||||
"🌸 Winter Illuminations at Yoyogi Park - Spectacular light displays",
|
||||
"🍜 Ramen Festival at Tokyo Station - Sample ramen from across Japan",
|
||||
"🎮 Gaming Expo at Tokyo Big Sight - Latest video games and technology",
|
||||
],
|
||||
"Paris": [
|
||||
"🎨 Impressionist Exhibition at Musée d'Orsay - Extended evening hours",
|
||||
"🍷 Wine Tasting Tour in Le Marais - Local sommelier guided",
|
||||
"🎵 Jazz Night at Le Caveau de la Huchette - Historic jazz club",
|
||||
"🥐 French Pastry Workshop - Learn from master pâtissiers",
|
||||
],
|
||||
"New York": [
|
||||
"🎭 Broadway Show: Hamilton - Limited engagement performances",
|
||||
"🏀 Knicks vs Lakers at Madison Square Garden",
|
||||
"🎨 Modern Art Exhibit at MoMA - New installations",
|
||||
"🍕 Pizza Walking Tour of Brooklyn - Artisan pizzerias",
|
||||
],
|
||||
"London": [
|
||||
"👑 Royal Collection Exhibition at Buckingham Palace",
|
||||
"🎭 West End Musical: The Phantom of the Opera",
|
||||
"🍺 Craft Beer Festival at Brick Lane",
|
||||
"🎪 Winter Wonderland at Hyde Park - Rides and markets",
|
||||
],
|
||||
"Sydney": [
|
||||
"🏄 Pro Surfing Competition at Bondi Beach",
|
||||
"🎵 Opera at Sydney Opera House - La Bohème",
|
||||
"🦘 Wildlife Night Safari at Taronga Zoo",
|
||||
"🍽️ Harbor Dinner Cruise with fireworks",
|
||||
],
|
||||
"Rome": [
|
||||
"🏛️ After-Hours Vatican Tour - Skip the crowds",
|
||||
"🍝 Pasta Making Class in Trastevere",
|
||||
"🎵 Classical Concert at Borghese Gallery",
|
||||
"🍷 Wine Tasting in Roman Cellars",
|
||||
],
|
||||
}
|
||||
|
||||
# Find events for the destination or use generic events
|
||||
events = [
|
||||
"🎭 Local theater performance",
|
||||
"🍽️ Food and wine festival",
|
||||
"🎨 Art gallery opening",
|
||||
"🎵 Live music at local venues",
|
||||
]
|
||||
|
||||
for city, city_events in events_by_city.items():
|
||||
if city.lower() in destination.lower():
|
||||
events = city_events
|
||||
break
|
||||
|
||||
event_list = "\n• ".join(events)
|
||||
return f"""Local events in {destination} around {date}:
|
||||
|
||||
• {event_list}
|
||||
|
||||
💡 Tip: Book popular events in advance as they may sell out quickly!"""
|
||||
|
||||
|
||||
def _get_weather_recommendation(condition: str) -> str:
|
||||
"""Get a recommendation based on weather conditions.
|
||||
|
||||
Args:
|
||||
condition: The weather condition description.
|
||||
|
||||
Returns:
|
||||
A recommendation string.
|
||||
"""
|
||||
condition_lower = condition.lower()
|
||||
|
||||
if "rain" in condition_lower or "drizzle" in condition_lower:
|
||||
return "Bring an umbrella and waterproof jacket. Consider indoor activities for backup."
|
||||
elif "fog" in condition_lower:
|
||||
return "Morning visibility may be limited. Plan outdoor sightseeing for afternoon."
|
||||
elif "cold" in condition_lower:
|
||||
return "Layer up with warm clothing. Hot drinks and cozy cafés recommended."
|
||||
elif "hot" in condition_lower or "warm" in condition_lower:
|
||||
return "Stay hydrated and use sunscreen. Plan strenuous activities for cooler morning hours."
|
||||
elif "thunder" in condition_lower or "storm" in condition_lower:
|
||||
return "Keep an eye on weather updates. Have indoor alternatives ready."
|
||||
else:
|
||||
return "Pleasant conditions expected. Great day for outdoor exploration!"
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
# Single Agent Orchestration Sample (Python)
|
||||
|
||||
This sample shows how to chain two invocations of the same agent inside a Durable Functions orchestration while
|
||||
preserving the conversation state between runs.
|
||||
|
||||
## Key Concepts
|
||||
- Deterministic orchestrations that make sequential agent calls on a shared thread
|
||||
- Reusing an agent thread to carry conversation history across invocations
|
||||
- HTTP endpoints for starting the orchestration and polling for status/output
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Start with the shared setup instructions in `../README.md` to create a virtual environment, install dependencies, and configure Azure OpenAI and storage settings.
|
||||
|
||||
## Running the Sample
|
||||
Start the orchestration:
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:7071/api/singleagent/run
|
||||
```
|
||||
|
||||
Poll the returned `statusQueryGetUri` until completion:
|
||||
|
||||
```bash
|
||||
curl http://localhost:7071/api/singleagent/status/<instanceId>
|
||||
```
|
||||
|
||||
> **Note:** The underlying agent run endpoint now waits for responses by default. If you invoke it directly and prefer an immediate HTTP 202, set the `x-ms-wait-for-response` header or include `"wait_for_response": false` in the payload.
|
||||
|
||||
The orchestration first requests an inspirational sentence from the agent, then refines the initial response while
|
||||
keeping it under 25 words—mirroring the behaviour of the corresponding .NET sample.
|
||||
|
||||
## Expected Output
|
||||
|
||||
Sample response when starting the orchestration:
|
||||
|
||||
```json
|
||||
{
|
||||
"message": "Single-agent orchestration started.",
|
||||
"instanceId": "ebb5c1df123e4d6fb8e7d703ffd0d0b0",
|
||||
"statusQueryGetUri": "http://localhost:7071/api/singleagent/status/ebb5c1df123e4d6fb8e7d703ffd0d0b0"
|
||||
}
|
||||
```
|
||||
|
||||
Sample completed status payload:
|
||||
|
||||
```json
|
||||
{
|
||||
"instanceId": "ebb5c1df123e4d6fb8e7d703ffd0d0b0",
|
||||
"runtimeStatus": "Completed",
|
||||
"output": "Learning is a journey where curiosity turns effort into mastery."
|
||||
}
|
||||
```
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
### Start the single-agent orchestration
|
||||
POST http://localhost:7071/api/singleagent/run
|
||||
|
||||
|
||||
### Check the status of the orchestration
|
||||
|
||||
@instanceId =<Replace with the instance ID from the response above>
|
||||
|
||||
GET http://localhost:7071/api/singleagent/status/{{instanceId}}
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
"""Chain two runs of a single agent inside a Durable Functions orchestration.
|
||||
|
||||
Components used in this sample:
|
||||
- AzureOpenAIChatClient to construct the writer agent hosted by Agent Framework.
|
||||
- AgentFunctionApp to surface HTTP and orchestration triggers via the Azure Functions extension.
|
||||
- Durable Functions orchestration to run sequential agent invocations on the same conversation thread.
|
||||
|
||||
Prerequisites: configure `AZURE_OPENAI_ENDPOINT`, `AZURE_OPENAI_CHAT_DEPLOYMENT_NAME`, and either
|
||||
`AZURE_OPENAI_API_KEY` or authenticate with Azure CLI before starting the Functions host."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from collections.abc import Generator
|
||||
from typing import Any
|
||||
|
||||
import azure.functions as func
|
||||
from agent_framework.azure import AgentFunctionApp, AzureOpenAIChatClient
|
||||
from azure.durable_functions import DurableOrchestrationClient, DurableOrchestrationContext
|
||||
from azure.identity import AzureCliCredential
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 1. Define the agent name used across the orchestration.
|
||||
WRITER_AGENT_NAME = "WriterAgent"
|
||||
|
||||
|
||||
# 2. Create the writer agent that will be invoked twice within the orchestration.
|
||||
def _create_writer_agent() -> Any:
|
||||
"""Create the writer agent with the same persona as the C# sample."""
|
||||
|
||||
instructions = (
|
||||
"You refine short pieces of text. When given an initial sentence you enhance it;\n"
|
||||
"when given an improved sentence you polish it further."
|
||||
)
|
||||
|
||||
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
|
||||
name=WRITER_AGENT_NAME,
|
||||
instructions=instructions,
|
||||
)
|
||||
|
||||
|
||||
# 3. Register the agent with AgentFunctionApp so HTTP and orchestration triggers are exposed.
|
||||
app = AgentFunctionApp(agents=[_create_writer_agent()], enable_health_check=True)
|
||||
|
||||
|
||||
# 4. Orchestration that runs the agent sequentially on a shared thread for chaining behaviour.
|
||||
@app.orchestration_trigger(context_name="context")
|
||||
def single_agent_orchestration(context: DurableOrchestrationContext) -> Generator[Any, Any, str]:
|
||||
"""Run the writer agent twice on the same thread to mirror chaining behaviour."""
|
||||
|
||||
writer = app.get_agent(context, WRITER_AGENT_NAME)
|
||||
writer_thread = writer.get_new_thread()
|
||||
|
||||
initial = yield writer.run(
|
||||
messages="Write a concise inspirational sentence about learning.",
|
||||
thread=writer_thread,
|
||||
)
|
||||
|
||||
improved_prompt = (
|
||||
"Improve this further while keeping it under 25 words: "
|
||||
f"{initial.text}"
|
||||
)
|
||||
|
||||
refined = yield writer.run(
|
||||
messages=improved_prompt,
|
||||
thread=writer_thread,
|
||||
)
|
||||
|
||||
return refined.text
|
||||
|
||||
|
||||
# 5. HTTP endpoint to kick off the orchestration and return the status query URI.
|
||||
@app.route(route="singleagent/run", methods=["POST"])
|
||||
@app.durable_client_input(client_name="client")
|
||||
async def start_single_agent_orchestration(
|
||||
req: func.HttpRequest,
|
||||
client: DurableOrchestrationClient,
|
||||
) -> func.HttpResponse:
|
||||
"""Start the orchestration and return status metadata."""
|
||||
|
||||
instance_id = await client.start_new(
|
||||
orchestration_function_name="single_agent_orchestration",
|
||||
)
|
||||
|
||||
logger.info("[HTTP] Started orchestration with instance_id: %s", instance_id)
|
||||
|
||||
status_url = _build_status_url(req.url, instance_id, route="singleagent")
|
||||
|
||||
payload = {
|
||||
"message": "Single-agent orchestration started.",
|
||||
"instanceId": instance_id,
|
||||
"statusQueryGetUri": status_url,
|
||||
}
|
||||
|
||||
return func.HttpResponse(
|
||||
body=json.dumps(payload),
|
||||
status_code=202,
|
||||
mimetype="application/json",
|
||||
)
|
||||
|
||||
|
||||
# 6. HTTP endpoint to fetch orchestration status using the original instance ID.
|
||||
@app.route(route="singleagent/status/{instanceId}", methods=["GET"])
|
||||
@app.durable_client_input(client_name="client")
|
||||
async def get_orchestration_status(
|
||||
req: func.HttpRequest,
|
||||
client: DurableOrchestrationClient,
|
||||
) -> func.HttpResponse:
|
||||
"""Return orchestration runtime status."""
|
||||
|
||||
instance_id = req.route_params.get("instanceId")
|
||||
if not instance_id:
|
||||
return func.HttpResponse(
|
||||
body=json.dumps({"error": "Missing instanceId"}),
|
||||
status_code=400,
|
||||
mimetype="application/json",
|
||||
)
|
||||
|
||||
status = await client.get_status(instance_id)
|
||||
|
||||
response_data: dict[str, Any] = {
|
||||
"instanceId": status.instance_id,
|
||||
"runtimeStatus": status.runtime_status.name if status.runtime_status else None,
|
||||
}
|
||||
|
||||
if status.input_ is not None:
|
||||
response_data["input"] = status.input_
|
||||
|
||||
if status.output is not None:
|
||||
response_data["output"] = status.output
|
||||
|
||||
return func.HttpResponse(
|
||||
body=json.dumps(response_data),
|
||||
status_code=200,
|
||||
mimetype="application/json",
|
||||
)
|
||||
|
||||
|
||||
# 7. Helper to construct durable status URLs similar to the .NET sample implementation.
|
||||
def _build_status_url(request_url: str, instance_id: str, *, route: str) -> str:
|
||||
"""Construct the status query URI similar to DurableHttpApiExtensions in C#."""
|
||||
|
||||
# Split once on /api/ to preserve host and scheme in local emulator and Azure.
|
||||
base_url, _, _ = request_url.partition("/api/")
|
||||
if not base_url:
|
||||
base_url = request_url.rstrip("/")
|
||||
return f"{base_url}/api/{route}/status/{instance_id}"
|
||||
|
||||
|
||||
"""
|
||||
Expected output when calling `POST /api/singleagent/run` and following the returned status URL:
|
||||
|
||||
HTTP/1.1 202 Accepted
|
||||
{
|
||||
"message": "Single-agent orchestration started.",
|
||||
"instanceId": "<guid>",
|
||||
"statusQueryGetUri": "http://localhost:7071/api/singleagent/status/<guid>"
|
||||
}
|
||||
|
||||
Subsequent `GET /api/singleagent/status/<guid>` after completion returns:
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
{
|
||||
"instanceId": "<guid>",
|
||||
"runtimeStatus": "Completed",
|
||||
"output": "Learning is a journey where curiosity turns effort into mastery."
|
||||
}
|
||||
"""
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"version": "2.0",
|
||||
"extensionBundle": {
|
||||
"id": "Microsoft.Azure.Functions.ExtensionBundle",
|
||||
"version": "[4.*, 5.0.0)"
|
||||
},
|
||||
"extensions": {
|
||||
"durableTask": {
|
||||
"hubName": "%TASKHUB_NAME%"
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"IsEncrypted": false,
|
||||
"Values": {
|
||||
"FUNCTIONS_WORKER_RUNTIME": "python",
|
||||
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
|
||||
"DURABLE_TASK_SCHEDULER_CONNECTION_STRING": "Endpoint=http://localhost:8080;TaskHub=default;Authentication=None",
|
||||
"TASKHUB_NAME": "default",
|
||||
"AZURE_OPENAI_ENDPOINT": "<AZURE_OPENAI_ENDPOINT>",
|
||||
"AZURE_OPENAI_CHAT_DEPLOYMENT_NAME": "<AZURE_OPENAI_CHAT_DEPLOYMENT_NAME>",
|
||||
"AZURE_OPENAI_API_KEY": "<AZURE_OPENAI_API_KEY>"
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
# Agent Framework packages
|
||||
# To use the deployed version, uncomment the line below and comment out the local installation lines
|
||||
# agent-framework-azurefunctions
|
||||
|
||||
# Local installation (for development and testing)
|
||||
# Each package must be listed explicitly because pip doesn't resolve uv workspace sources.
|
||||
# Without explicit entries, pip would fetch transitive dependencies from PyPI instead of local source.
|
||||
-e ../../../../packages/core # Core framework - base dependency for all packages
|
||||
-e ../../../../packages/durabletask # Durable Task support - dependency of azurefunctions
|
||||
-e ../../../../packages/azurefunctions # Azure Functions integration - the main package for this sample
|
||||
|
||||
# Azure authentication
|
||||
azure-identity
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
# Multi-Agent Orchestration (Concurrency) – Python
|
||||
|
||||
This sample starts a Durable Functions orchestration that runs two agents in parallel and merges their responses.
|
||||
|
||||
## Highlights
|
||||
- Two agents (`PhysicistAgent` and `ChemistAgent`) share a single Azure OpenAI deployment configuration.
|
||||
- The orchestration uses `context.task_all(...)` to safely run both agents concurrently.
|
||||
- HTTP routes (`/api/multiagent/run` and `/api/multiagent/status/{instanceId}`) mirror the .NET sample for parity.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Use the shared setup instructions in `../README.md` to prepare the environment, install dependencies, and configure Azure OpenAI and storage settings before running this sample.
|
||||
|
||||
## Running the Sample
|
||||
Start the orchestration:
|
||||
|
||||
```bash
|
||||
curl -X POST \
|
||||
-H "Content-Type: text/plain" \
|
||||
--data "What is temperature?" \
|
||||
http://localhost:7071/api/multiagent/run
|
||||
```
|
||||
|
||||
Poll the returned `statusQueryGetUri` until completion:
|
||||
|
||||
```bash
|
||||
curl http://localhost:7071/api/multiagent/status/<instanceId>
|
||||
```
|
||||
|
||||
> **Note:** The agent run endpoints wait for responses by default. If you call them directly and need an immediate HTTP 202, set the `x-ms-wait-for-response` header or include `"wait_for_response": false` in the request payload.
|
||||
|
||||
The orchestration launches both agents simultaneously so their domain-specific answers can be combined for the caller.
|
||||
|
||||
## Expected Output
|
||||
|
||||
Example response when starting the orchestration:
|
||||
|
||||
```json
|
||||
{
|
||||
"message": "Multi-agent concurrent orchestration started.",
|
||||
"prompt": "What is temperature?",
|
||||
"instanceId": "94d56266f0a04e5a8f9f3a1f77a4c597",
|
||||
"statusQueryGetUri": "http://localhost:7071/api/multiagent/status/94d56266f0a04e5a8f9f3a1f77a4c597"
|
||||
}
|
||||
```
|
||||
|
||||
Example completed status payload:
|
||||
|
||||
```json
|
||||
{
|
||||
"instanceId": "94d56266f0a04e5a8f9f3a1f77a4c597",
|
||||
"runtimeStatus": "Completed",
|
||||
"output": {
|
||||
"physicist": "Temperature measures the average kinetic energy of particles in a system.",
|
||||
"chemist": "Temperature reflects how molecular motion influences reaction rates and equilibria."
|
||||
}
|
||||
}
|
||||
```
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
### Start the multi-agent concurrent orchestration
|
||||
POST http://localhost:7071/api/multiagent/run
|
||||
Content-Type: text/plain
|
||||
|
||||
What is temperature?
|
||||
|
||||
### Check the status of the orchestration
|
||||
|
||||
@instanceId =<Enter the instance ID from the response above>
|
||||
|
||||
GET http://localhost:7071/api/multiagent/status/{{instanceId}}
|
||||
+192
@@ -0,0 +1,192 @@
|
||||
"""Fan out concurrent runs across two agents inside a Durable Functions orchestration.
|
||||
|
||||
Components used in this sample:
|
||||
- AzureOpenAIChatClient to create domain-specific agents hosted by Agent Framework.
|
||||
- AgentFunctionApp to expose orchestration and HTTP triggers.
|
||||
- Durable Functions orchestration that executes agent calls in parallel and aggregates results.
|
||||
|
||||
Prerequisites: configure `AZURE_OPENAI_ENDPOINT`, `AZURE_OPENAI_CHAT_DEPLOYMENT_NAME`, and either
|
||||
`AZURE_OPENAI_API_KEY` or authenticate with Azure CLI before starting the Functions host."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from collections.abc import Generator
|
||||
from typing import Any, cast
|
||||
|
||||
import azure.functions as func
|
||||
from agent_framework import AgentResponse
|
||||
from agent_framework.azure import AgentFunctionApp, AzureOpenAIChatClient
|
||||
from azure.durable_functions import DurableOrchestrationClient, DurableOrchestrationContext
|
||||
from azure.identity import AzureCliCredential
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 1. Define agent names shared across the orchestration.
|
||||
PHYSICIST_AGENT_NAME = "PhysicistAgent"
|
||||
CHEMIST_AGENT_NAME = "ChemistAgent"
|
||||
|
||||
|
||||
# 2. Instantiate both agents that the orchestration will run concurrently.
|
||||
def _create_agents() -> list[Any]:
|
||||
chat_client = AzureOpenAIChatClient(credential=AzureCliCredential())
|
||||
|
||||
physicist = chat_client.as_agent(
|
||||
name=PHYSICIST_AGENT_NAME,
|
||||
instructions="You are an expert in physics. You answer questions from a physics perspective.",
|
||||
)
|
||||
|
||||
chemist = chat_client.as_agent(
|
||||
name=CHEMIST_AGENT_NAME,
|
||||
instructions="You are an expert in chemistry. You answer questions from a chemistry perspective.",
|
||||
)
|
||||
|
||||
return [physicist, chemist]
|
||||
|
||||
|
||||
# 3. Register both agents with AgentFunctionApp and selectively enable HTTP endpoints.
|
||||
agents = _create_agents()
|
||||
app = AgentFunctionApp(enable_health_check=True, enable_http_endpoints=False)
|
||||
app.add_agent(agents[0], enable_http_endpoint=True)
|
||||
app.add_agent(agents[1])
|
||||
|
||||
|
||||
# 4. Durable Functions orchestration that runs both agents in parallel.
|
||||
@app.orchestration_trigger(context_name="context")
|
||||
def multi_agent_concurrent_orchestration(context: DurableOrchestrationContext) -> Generator[Any, Any, dict[str, str]]:
|
||||
"""Fan out to two domain-specific agents and aggregate their responses."""
|
||||
|
||||
prompt = context.get_input()
|
||||
if not prompt or not str(prompt).strip():
|
||||
raise ValueError("Prompt is required")
|
||||
|
||||
physicist = app.get_agent(context, PHYSICIST_AGENT_NAME)
|
||||
chemist = app.get_agent(context, CHEMIST_AGENT_NAME)
|
||||
|
||||
physicist_thread = physicist.get_new_thread()
|
||||
chemist_thread = chemist.get_new_thread()
|
||||
|
||||
# Create tasks from agent.run() calls
|
||||
physicist_task = physicist.run(messages=str(prompt), thread=physicist_thread)
|
||||
chemist_task = chemist.run(messages=str(prompt), thread=chemist_thread)
|
||||
|
||||
# Execute both tasks concurrently using task_all
|
||||
task_results = yield context.task_all([physicist_task, chemist_task])
|
||||
|
||||
physicist_result = cast(AgentResponse, task_results[0])
|
||||
chemist_result = cast(AgentResponse, task_results[1])
|
||||
|
||||
return {
|
||||
"physicist": physicist_result.text,
|
||||
"chemist": chemist_result.text,
|
||||
}
|
||||
|
||||
|
||||
# 5. HTTP endpoint to accept prompts and start the concurrent orchestration.
|
||||
@app.route(route="multiagent/run", methods=["POST"])
|
||||
@app.durable_client_input(client_name="client")
|
||||
async def start_multi_agent_concurrent_orchestration(
|
||||
req: func.HttpRequest,
|
||||
client: DurableOrchestrationClient,
|
||||
) -> func.HttpResponse:
|
||||
"""Kick off the orchestration with a plain text prompt."""
|
||||
|
||||
body_bytes = req.get_body() or b""
|
||||
prompt = body_bytes.decode("utf-8", errors="replace").strip()
|
||||
if not prompt:
|
||||
return func.HttpResponse(
|
||||
body=json.dumps({"error": "Prompt is required"}),
|
||||
status_code=400,
|
||||
mimetype="application/json",
|
||||
)
|
||||
|
||||
instance_id = await client.start_new(
|
||||
orchestration_function_name="multi_agent_concurrent_orchestration",
|
||||
client_input=prompt,
|
||||
)
|
||||
|
||||
logger.info("[HTTP] Started orchestration with instance_id: %s", instance_id)
|
||||
|
||||
status_url = _build_status_url(req.url, instance_id, route="multiagent")
|
||||
|
||||
payload = {
|
||||
"message": "Multi-agent concurrent orchestration started.",
|
||||
"prompt": prompt,
|
||||
"instanceId": instance_id,
|
||||
"statusQueryGetUri": status_url,
|
||||
}
|
||||
|
||||
return func.HttpResponse(
|
||||
body=json.dumps(payload),
|
||||
status_code=202,
|
||||
mimetype="application/json",
|
||||
)
|
||||
|
||||
|
||||
# 6. HTTP endpoint to retrieve orchestration status and aggregated outputs.
|
||||
@app.route(route="multiagent/status/{instanceId}", methods=["GET"])
|
||||
@app.durable_client_input(client_name="client")
|
||||
async def get_orchestration_status(
|
||||
req: func.HttpRequest,
|
||||
client: DurableOrchestrationClient,
|
||||
) -> func.HttpResponse:
|
||||
instance_id = req.route_params.get("instanceId")
|
||||
if not instance_id:
|
||||
return func.HttpResponse(
|
||||
body=json.dumps({"error": "Missing instanceId"}),
|
||||
status_code=400,
|
||||
mimetype="application/json",
|
||||
)
|
||||
|
||||
status = await client.get_status(instance_id)
|
||||
|
||||
response_data: dict[str, Any] = {
|
||||
"instanceId": status.instance_id,
|
||||
"runtimeStatus": status.runtime_status.name if status.runtime_status else None,
|
||||
"createdTime": status.created_time.isoformat() if status.created_time else None,
|
||||
"lastUpdatedTime": status.last_updated_time.isoformat() if status.last_updated_time else None,
|
||||
}
|
||||
|
||||
if status.input_ is not None:
|
||||
response_data["input"] = status.input_
|
||||
|
||||
if status.output is not None:
|
||||
response_data["output"] = status.output
|
||||
|
||||
return func.HttpResponse(
|
||||
body=json.dumps(response_data),
|
||||
status_code=200,
|
||||
mimetype="application/json",
|
||||
)
|
||||
|
||||
|
||||
# 7. Helper to construct durable status URLs.
|
||||
def _build_status_url(request_url: str, instance_id: str, *, route: str) -> str:
|
||||
base_url, _, _ = request_url.partition("/api/")
|
||||
if not base_url:
|
||||
base_url = request_url.rstrip("/")
|
||||
return f"{base_url}/api/{route}/status/{instance_id}"
|
||||
|
||||
|
||||
"""
|
||||
Expected output when calling `POST /api/multiagent/run` with a plain-text prompt:
|
||||
|
||||
HTTP/1.1 202 Accepted
|
||||
{
|
||||
"message": "Multi-agent concurrent orchestration started.",
|
||||
"prompt": "What is temperature?",
|
||||
"instanceId": "<guid>",
|
||||
"statusQueryGetUri": "http://localhost:7071/api/multiagent/status/<guid>"
|
||||
}
|
||||
|
||||
Polling `GET /api/multiagent/status/<guid>` after completion returns:
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
{
|
||||
"instanceId": "<guid>",
|
||||
"runtimeStatus": "Completed",
|
||||
"output": {
|
||||
"physicist": "Temperature measures the average kinetic energy of particles in a system.",
|
||||
"chemist": "Temperature reflects how molecular motion influences reaction rates and equilibria."
|
||||
}
|
||||
}
|
||||
"""
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"version": "2.0",
|
||||
"extensionBundle": {
|
||||
"id": "Microsoft.Azure.Functions.ExtensionBundle",
|
||||
"version": "[4.*, 5.0.0)"
|
||||
},
|
||||
"extensions": {
|
||||
"durableTask": {
|
||||
"hubName": "%TASKHUB_NAME%"
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"IsEncrypted": false,
|
||||
"Values": {
|
||||
"FUNCTIONS_WORKER_RUNTIME": "python",
|
||||
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
|
||||
"DURABLE_TASK_SCHEDULER_CONNECTION_STRING": "Endpoint=http://localhost:8080;TaskHub=default;Authentication=None",
|
||||
"TASKHUB_NAME": "default",
|
||||
"AZURE_OPENAI_ENDPOINT": "<AZURE_OPENAI_ENDPOINT>",
|
||||
"AZURE_OPENAI_CHAT_DEPLOYMENT_NAME": "<AZURE_OPENAI_CHAT_DEPLOYMENT_NAME>",
|
||||
"AZURE_OPENAI_API_KEY": "<AZURE_OPENAI_API_KEY>"
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
# Agent Framework packages
|
||||
# To use the deployed version, uncomment the line below and comment out the local installation lines
|
||||
# agent-framework-azurefunctions
|
||||
|
||||
# Local installation (for development and testing)
|
||||
# Each package must be listed explicitly because pip doesn't resolve uv workspace sources.
|
||||
# Without explicit entries, pip would fetch transitive dependencies from PyPI instead of local source.
|
||||
-e ../../../../packages/core # Core framework - base dependency for all packages
|
||||
-e ../../../../packages/durabletask # Durable Task support - dependency of azurefunctions
|
||||
-e ../../../../packages/azurefunctions # Azure Functions integration - the main package for this sample
|
||||
|
||||
# Azure authentication
|
||||
azure-identity
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
# Multi-Agent Orchestration (Conditionals) – Python
|
||||
|
||||
This sample evaluates incoming emails with a spam detector agent and,
|
||||
when appropriate, drafts a response using an email assistant agent.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Set up the shared prerequisites outlined in `../README.md`, including the virtual environment, dependency installation, and Azure OpenAI and storage configuration.
|
||||
|
||||
## Scenario Overview
|
||||
- Two Azure OpenAI agents share a single deployment: one flags spam, the other drafts replies.
|
||||
- Structured responses (`is_spam` and `reason`, or `response`) determine which orchestration branch runs.
|
||||
- Activity functions handle the side effects of spam handling and email sending.
|
||||
|
||||
## Running the Sample
|
||||
Submit an email payload:
|
||||
|
||||
```bash
|
||||
curl -X POST "http://localhost:7071/api/spamdetection/run" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"email_id": "email-001", "email_content": "URGENT! You'\''ve won $1,000,000! Click here now to claim your prize! Limited time offer! Don'\''t miss out!"}'
|
||||
```
|
||||
|
||||
Poll the returned `statusQueryGetUri` or call the status route directly:
|
||||
|
||||
```bash
|
||||
curl http://localhost:7071/api/spamdetection/status/<instanceId>
|
||||
```
|
||||
|
||||
> **Note:** The spam detection run endpoint waits for responses by default. To opt into an immediate HTTP 202, set the `x-ms-wait-for-response` header or include `"wait_for_response": false` in the POST body.
|
||||
|
||||
## Expected Responses
|
||||
- Spam payloads return `Email marked as spam: <reason>` by invoking the `handle_spam_email` activity.
|
||||
- Legitimate emails return `Email sent: <draft>` after the email assistant agent produces a structured reply.
|
||||
- The status endpoint mirrors Durable Functions metadata, including runtime status and the agent output.
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
### Test spam detection with a legitimate email
|
||||
POST http://localhost:7071/api/spamdetection/run
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"email_id": "email-001",
|
||||
"email_content": "Hi John, I hope you're doing well. I wanted to follow up on our meeting yesterday about the quarterly report. Could you please send me the updated figures by Friday? Thanks!"
|
||||
}
|
||||
|
||||
|
||||
### Test spam detection with a spam email
|
||||
POST http://localhost:7071/api/spamdetection/run
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"email_id": "email-002",
|
||||
"email_content": "URGENT! You've won $1,000,000! Click here now to claim your prize! Limited time offer! Don't miss out!"
|
||||
}
|
||||
|
||||
|
||||
### Check the status of the orchestration
|
||||
@instanceId =<Replace with the instance ID from the response above>
|
||||
|
||||
GET http://localhost:7071/api/spamdetection/status/{{instanceId}}
|
||||
+253
@@ -0,0 +1,253 @@
|
||||
"""Route email requests through conditional orchestration with two agents.
|
||||
|
||||
Components used in this sample:
|
||||
- AzureOpenAIChatClient agents for spam detection and email drafting.
|
||||
- AgentFunctionApp with Durable orchestration, activity, and HTTP triggers.
|
||||
- Pydantic models that validate payloads and agent JSON responses.
|
||||
|
||||
Prerequisites: set `AZURE_OPENAI_ENDPOINT`, `AZURE_OPENAI_CHAT_DEPLOYMENT_NAME`,
|
||||
and either `AZURE_OPENAI_API_KEY` or sign in with Azure CLI before running the
|
||||
Functions host."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from collections.abc import Generator, Mapping
|
||||
from typing import Any
|
||||
|
||||
import azure.functions as func
|
||||
from agent_framework.azure import AgentFunctionApp, AzureOpenAIChatClient
|
||||
from azure.durable_functions import DurableOrchestrationClient, DurableOrchestrationContext
|
||||
from azure.identity import AzureCliCredential
|
||||
from pydantic import BaseModel, ValidationError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 1. Define agent names shared across the orchestration.
|
||||
SPAM_AGENT_NAME = "SpamDetectionAgent"
|
||||
EMAIL_AGENT_NAME = "EmailAssistantAgent"
|
||||
|
||||
|
||||
class SpamDetectionResult(BaseModel):
|
||||
is_spam: bool
|
||||
reason: str
|
||||
|
||||
|
||||
class EmailResponse(BaseModel):
|
||||
response: str
|
||||
|
||||
|
||||
class EmailPayload(BaseModel):
|
||||
email_id: str
|
||||
email_content: str
|
||||
|
||||
|
||||
# 2. Instantiate both agents so they can be registered with AgentFunctionApp.
|
||||
def _create_agents() -> list[Any]:
|
||||
chat_client = AzureOpenAIChatClient(credential=AzureCliCredential())
|
||||
|
||||
spam_agent = chat_client.as_agent(
|
||||
name=SPAM_AGENT_NAME,
|
||||
instructions="You are a spam detection assistant that identifies spam emails.",
|
||||
)
|
||||
|
||||
email_agent = chat_client.as_agent(
|
||||
name=EMAIL_AGENT_NAME,
|
||||
instructions="You are an email assistant that helps users draft responses to emails with professionalism.",
|
||||
)
|
||||
|
||||
return [spam_agent, email_agent]
|
||||
|
||||
|
||||
app = AgentFunctionApp(agents=_create_agents(), enable_health_check=True)
|
||||
|
||||
|
||||
# 3. Activities handle the side effects for spam and legitimate emails.
|
||||
@app.activity_trigger(input_name="reason")
|
||||
def handle_spam_email(reason: str) -> str:
|
||||
return f"Email marked as spam: {reason}"
|
||||
|
||||
|
||||
@app.activity_trigger(input_name="message")
|
||||
def send_email(message: str) -> str:
|
||||
return f"Email sent: {message}"
|
||||
|
||||
|
||||
# 4. Orchestration validates input, runs agents, and branches on spam results.
|
||||
@app.orchestration_trigger(context_name="context")
|
||||
def spam_detection_orchestration(context: DurableOrchestrationContext) -> Generator[Any, Any, str]:
|
||||
payload_raw = context.get_input()
|
||||
if not isinstance(payload_raw, Mapping):
|
||||
raise ValueError("Email data is required")
|
||||
|
||||
try:
|
||||
payload = EmailPayload.model_validate(payload_raw)
|
||||
except ValidationError as exc:
|
||||
raise ValueError(f"Invalid email payload: {exc}") from exc
|
||||
|
||||
spam_agent = app.get_agent(context, SPAM_AGENT_NAME)
|
||||
email_agent = app.get_agent(context, EMAIL_AGENT_NAME)
|
||||
|
||||
spam_thread = spam_agent.get_new_thread()
|
||||
|
||||
spam_prompt = (
|
||||
"Analyze this email for spam content and return a JSON response with 'is_spam' (boolean) "
|
||||
"and 'reason' (string) fields:\n"
|
||||
f"Email ID: {payload.email_id}\n"
|
||||
f"Content: {payload.email_content}"
|
||||
)
|
||||
|
||||
spam_result_raw = yield spam_agent.run(
|
||||
messages=spam_prompt,
|
||||
thread=spam_thread,
|
||||
options={"response_format": SpamDetectionResult},
|
||||
)
|
||||
|
||||
spam_result = spam_result_raw.try_parse_value(SpamDetectionResult)
|
||||
if spam_result is None:
|
||||
raise ValueError("Failed to parse spam detection result")
|
||||
|
||||
if spam_result.is_spam:
|
||||
result = yield context.call_activity("handle_spam_email", spam_result.reason) # type: ignore[misc]
|
||||
return result
|
||||
|
||||
email_thread = email_agent.get_new_thread()
|
||||
|
||||
email_prompt = (
|
||||
"Draft a professional response to this email. Return a JSON response with a 'response' field "
|
||||
"containing the reply:\n\n"
|
||||
f"Email ID: {payload.email_id}\n"
|
||||
f"Content: {payload.email_content}"
|
||||
)
|
||||
|
||||
email_result_raw = yield email_agent.run(
|
||||
messages=email_prompt,
|
||||
thread=email_thread,
|
||||
options={"response_format": EmailResponse},
|
||||
)
|
||||
|
||||
email_result = email_result_raw.try_parse_value(EmailResponse)
|
||||
if email_result is None:
|
||||
raise ValueError("Failed to parse email response")
|
||||
|
||||
result = yield context.call_activity("send_email", email_result.response) # type: ignore[misc]
|
||||
return result
|
||||
|
||||
|
||||
# 5. HTTP starter endpoint launches the orchestration for each email payload.
|
||||
@app.route(route="spamdetection/run", methods=["POST"])
|
||||
@app.durable_client_input(client_name="client")
|
||||
async def start_spam_detection_orchestration(
|
||||
req: func.HttpRequest,
|
||||
client: DurableOrchestrationClient,
|
||||
) -> func.HttpResponse:
|
||||
try:
|
||||
body = req.get_json()
|
||||
except ValueError:
|
||||
body = None
|
||||
|
||||
if not isinstance(body, Mapping):
|
||||
return func.HttpResponse(
|
||||
body=json.dumps({"error": "Email data is required"}),
|
||||
status_code=400,
|
||||
mimetype="application/json",
|
||||
)
|
||||
|
||||
try:
|
||||
payload = EmailPayload.model_validate(body)
|
||||
except ValidationError as exc:
|
||||
return func.HttpResponse(
|
||||
body=json.dumps({"error": f"Invalid email payload: {exc}"}),
|
||||
status_code=400,
|
||||
mimetype="application/json",
|
||||
)
|
||||
|
||||
instance_id = await client.start_new(
|
||||
orchestration_function_name="spam_detection_orchestration",
|
||||
client_input=payload.model_dump(),
|
||||
)
|
||||
|
||||
logger.info("[HTTP] Started spam detection orchestration with instance_id: %s", instance_id)
|
||||
|
||||
status_url = _build_status_url(req.url, instance_id, route="spamdetection")
|
||||
|
||||
payload_json = {
|
||||
"message": "Spam detection orchestration started.",
|
||||
"emailId": payload.email_id,
|
||||
"instanceId": instance_id,
|
||||
"statusQueryGetUri": status_url,
|
||||
}
|
||||
|
||||
return func.HttpResponse(
|
||||
body=json.dumps(payload_json),
|
||||
status_code=202,
|
||||
mimetype="application/json",
|
||||
)
|
||||
|
||||
|
||||
# 6. Status endpoint mirrors Durable Functions default payload with agent data.
|
||||
@app.route(route="spamdetection/status/{instanceId}", methods=["GET"])
|
||||
@app.durable_client_input(client_name="client")
|
||||
async def get_orchestration_status(
|
||||
req: func.HttpRequest,
|
||||
client: DurableOrchestrationClient,
|
||||
) -> func.HttpResponse:
|
||||
instance_id = req.route_params.get("instanceId")
|
||||
if not instance_id:
|
||||
return func.HttpResponse(
|
||||
body=json.dumps({"error": "Missing instanceId"}),
|
||||
status_code=400,
|
||||
mimetype="application/json",
|
||||
)
|
||||
|
||||
status = await client.get_status(instance_id)
|
||||
|
||||
response_data: dict[str, Any] = {
|
||||
"instanceId": status.instance_id,
|
||||
"runtimeStatus": status.runtime_status.name if status.runtime_status else None,
|
||||
"createdTime": status.created_time.isoformat() if status.created_time else None,
|
||||
"lastUpdatedTime": status.last_updated_time.isoformat() if status.last_updated_time else None,
|
||||
}
|
||||
|
||||
if status.input_ is not None:
|
||||
response_data["input"] = status.input_
|
||||
|
||||
if status.output is not None:
|
||||
response_data["output"] = status.output
|
||||
|
||||
return func.HttpResponse(
|
||||
body=json.dumps(response_data),
|
||||
status_code=200,
|
||||
mimetype="application/json",
|
||||
)
|
||||
|
||||
|
||||
# 7. Helper utilities keep URL construction and structured parsing deterministic.
|
||||
def _build_status_url(request_url: str, instance_id: str, *, route: str) -> str:
|
||||
base_url, _, _ = request_url.partition("/api/")
|
||||
if not base_url:
|
||||
base_url = request_url.rstrip("/")
|
||||
return f"{base_url}/api/{route}/status/{instance_id}"
|
||||
|
||||
|
||||
"""
|
||||
Expected response from `POST /api/spamdetection/run`:
|
||||
|
||||
HTTP/1.1 202 Accepted
|
||||
{
|
||||
"message": "Spam detection orchestration started.",
|
||||
"emailId": "123",
|
||||
"instanceId": "<durable-instance-id>",
|
||||
"statusQueryGetUri": "http://localhost:7071/runtime/webhooks/durabletask/instances/<durable-instance-id>"
|
||||
}
|
||||
|
||||
Expected response from `GET /api/spamdetection/status/{instanceId}` once complete:
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
{
|
||||
"instanceId": "<durable-instance-id>",
|
||||
"runtimeStatus": "Completed",
|
||||
"createdTime": "2024-01-01T00:00:00+00:00",
|
||||
"lastUpdatedTime": "2024-01-01T00:00:10+00:00",
|
||||
"output": "Email sent: Thank you for reaching out..."
|
||||
}
|
||||
"""
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"version": "2.0",
|
||||
"extensionBundle": {
|
||||
"id": "Microsoft.Azure.Functions.ExtensionBundle",
|
||||
"version": "[4.*, 5.0.0)"
|
||||
},
|
||||
"extensions": {
|
||||
"durableTask": {
|
||||
"hubName": "%TASKHUB_NAME%"
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"IsEncrypted": false,
|
||||
"Values": {
|
||||
"FUNCTIONS_WORKER_RUNTIME": "python",
|
||||
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
|
||||
"DURABLE_TASK_SCHEDULER_CONNECTION_STRING": "Endpoint=http://localhost:8080;TaskHub=default;Authentication=None",
|
||||
"TASKHUB_NAME": "default",
|
||||
"AZURE_OPENAI_ENDPOINT": "<AZURE_OPENAI_ENDPOINT>",
|
||||
"AZURE_OPENAI_CHAT_DEPLOYMENT_NAME": "<AZURE_OPENAI_CHAT_DEPLOYMENT_NAME>",
|
||||
"AZURE_OPENAI_API_KEY": "<AZURE_OPENAI_API_KEY>"
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
# Agent Framework packages
|
||||
# To use the deployed version, uncomment the line below and comment out the local installation lines
|
||||
# agent-framework-azurefunctions
|
||||
|
||||
# Local installation (for development and testing)
|
||||
# Each package must be listed explicitly because pip doesn't resolve uv workspace sources.
|
||||
# Without explicit entries, pip would fetch transitive dependencies from PyPI instead of local source.
|
||||
-e ../../../../packages/core # Core framework - base dependency for all packages
|
||||
-e ../../../../packages/durabletask # Durable Task support - dependency of azurefunctions
|
||||
-e ../../../../packages/azurefunctions # Azure Functions integration - the main package for this sample
|
||||
|
||||
# Azure authentication
|
||||
azure-identity
|
||||
@@ -0,0 +1,48 @@
|
||||
# Single-Agent Orchestration (HITL) – Python
|
||||
|
||||
This sample demonstrates the human-in-the-loop (HITL) scenario.
|
||||
A single writer agent iterates on content until a human reviewer approves the
|
||||
output or a maximum number of attempts is reached.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Complete the common setup instructions in `../README.md` to prepare the virtual environment, install dependencies, and configure Azure OpenAI and storage settings.
|
||||
|
||||
## What It Shows
|
||||
- Identical environment variable usage (`AZURE_OPENAI_ENDPOINT`,
|
||||
`AZURE_OPENAI_DEPLOYMENT`) and HTTP surface area (`/api/hitl/...`).
|
||||
- Durable orchestrations that pause for external events while maintaining
|
||||
deterministic state (`context.wait_for_external_event` + timed cancellation).
|
||||
- Activity functions that encapsulate the out-of-band operations such as notifying
|
||||
a reviewer and publishing content.
|
||||
|
||||
## Running the Sample
|
||||
Start the HITL orchestration:
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:7071/api/hitl/run \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"topic": "Write a friendly release note"}'
|
||||
```
|
||||
|
||||
Poll the returned `statusQueryGetUri` or call the status route directly:
|
||||
|
||||
```bash
|
||||
curl http://localhost:7071/api/hitl/status/<instanceId>
|
||||
```
|
||||
|
||||
Approve or reject the draft:
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:7071/api/hitl/approve/<instanceId> \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"approved": true, "feedback": "Looks good"}'
|
||||
```
|
||||
|
||||
> **Note:** Calls to the underlying agent run endpoint wait for responses by default. If you need an immediate HTTP 202 response, set the `x-ms-wait-for-response` header or include `"wait_for_response": false` in the request body.
|
||||
|
||||
## Expected Responses
|
||||
- `POST /api/hitl/run` returns a 202 Accepted payload with the Durable Functions instance ID.
|
||||
- `POST /api/hitl/approve/{instanceId}` echoes the decision that the orchestration receives.
|
||||
- `GET /api/hitl/status/{instanceId}` reports `runtimeStatus`, custom status messages, and the final content when approved.
|
||||
The orchestration sets custom status messages, retries on rejection with reviewer feedback, and raises a timeout if human approval does not arrive.
|
||||
@@ -0,0 +1,45 @@
|
||||
### Start the HITL content generation orchestration with default timeout (72 hours)
|
||||
POST http://localhost:7071/api/hitl/run
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"topic": "The Future of Artificial Intelligence",
|
||||
"max_review_attempts": 3
|
||||
}
|
||||
|
||||
|
||||
### Start the HITL content generation orchestration with a short timeout (~4 seconds)
|
||||
POST http://localhost:7071/api/hitl/run
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"topic": "The Future of Artificial Intelligence",
|
||||
"max_review_attempts": 3,
|
||||
"approval_timeout_hours": 0.001
|
||||
}
|
||||
|
||||
|
||||
### Replace INSTANCE_ID_GOES_HERE below with the value returned from the POST call
|
||||
@instanceId=<INSTANCE_ID_GOES_HERE>
|
||||
|
||||
### Check the status of the orchestration
|
||||
GET http://localhost:7071/api/hitl/status/{{instanceId}}
|
||||
|
||||
### Send human approval
|
||||
POST http://localhost:7071/api/hitl/approve/{{instanceId}}
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"approved": true,
|
||||
"feedback": "Great article! The content is well-structured and informative."
|
||||
}
|
||||
|
||||
### Send human rejection with feedback
|
||||
POST http://localhost:7071/api/hitl/approve/{{instanceId}}
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"approved": false,
|
||||
"feedback": "The article needs more technical depth and better examples."
|
||||
}
|
||||
|
||||
+397
@@ -0,0 +1,397 @@
|
||||
"""Iterate on generated content with a human-in-the-loop Durable orchestration.
|
||||
|
||||
Components used in this sample:
|
||||
- AzureOpenAIChatClient for a single writer agent that emits structured JSON.
|
||||
- AgentFunctionApp with Durable orchestration, HTTP triggers, and activity triggers.
|
||||
- External events that pause the workflow until a human decision arrives or times out.
|
||||
|
||||
Prerequisites: configure `AZURE_OPENAI_ENDPOINT`, `AZURE_OPENAI_CHAT_DEPLOYMENT_NAME`, and
|
||||
either `AZURE_OPENAI_API_KEY` or sign in with Azure CLI before running `func start`."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from collections.abc import Generator, Mapping
|
||||
from datetime import timedelta
|
||||
from typing import Any
|
||||
|
||||
import azure.functions as func
|
||||
from agent_framework.azure import AgentFunctionApp, AzureOpenAIChatClient
|
||||
from azure.durable_functions import DurableOrchestrationClient, DurableOrchestrationContext
|
||||
from azure.identity import AzureCliCredential
|
||||
from pydantic import BaseModel, ValidationError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 1. Define orchestration constants used throughout the workflow.
|
||||
WRITER_AGENT_NAME = "WriterAgent"
|
||||
HUMAN_APPROVAL_EVENT = "HumanApproval"
|
||||
|
||||
|
||||
class ContentGenerationInput(BaseModel):
|
||||
topic: str
|
||||
max_review_attempts: int = 3
|
||||
approval_timeout_hours: float = 72
|
||||
|
||||
|
||||
class GeneratedContent(BaseModel):
|
||||
title: str
|
||||
content: str
|
||||
|
||||
|
||||
class HumanApproval(BaseModel):
|
||||
approved: bool
|
||||
feedback: str = ""
|
||||
|
||||
|
||||
# 2. Create the writer agent that produces structured JSON responses.
|
||||
def _create_writer_agent() -> Any:
|
||||
instructions = (
|
||||
"You are a professional content writer who creates high-quality articles on various topics. "
|
||||
"You write engaging, informative, and well-structured content that follows best practices for readability and accuracy. "
|
||||
"Return your response as JSON with 'title' and 'content' fields."
|
||||
)
|
||||
|
||||
return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
|
||||
name=WRITER_AGENT_NAME,
|
||||
instructions=instructions,
|
||||
)
|
||||
|
||||
|
||||
app = AgentFunctionApp(agents=[_create_writer_agent()], enable_health_check=True)
|
||||
|
||||
|
||||
# 3. Activities encapsulate external work for review notifications and publishing.
|
||||
@app.activity_trigger(input_name="content")
|
||||
def notify_user_for_approval(content: dict[str, str]) -> None:
|
||||
model = GeneratedContent.model_validate(content)
|
||||
logger.info("NOTIFICATION: Please review the following content for approval:")
|
||||
logger.info("Title: %s", model.title or "(untitled)")
|
||||
logger.info("Content: %s", model.content)
|
||||
logger.info("Use the approval endpoint to approve or reject this content.")
|
||||
|
||||
|
||||
@app.activity_trigger(input_name="content")
|
||||
def publish_content(content: dict[str, str]) -> None:
|
||||
model = GeneratedContent.model_validate(content)
|
||||
logger.info("PUBLISHING: Content has been published successfully:")
|
||||
logger.info("Title: %s", model.title or "(untitled)")
|
||||
logger.info("Content: %s", model.content)
|
||||
|
||||
|
||||
# 4. Orchestration loops until the human approves, times out, or attempts are exhausted.
|
||||
@app.orchestration_trigger(context_name="context")
|
||||
def content_generation_hitl_orchestration(context: DurableOrchestrationContext) -> Generator[Any, Any, dict[str, str]]:
|
||||
payload_raw = context.get_input()
|
||||
if not isinstance(payload_raw, Mapping):
|
||||
raise ValueError("Content generation input is required")
|
||||
|
||||
try:
|
||||
payload = ContentGenerationInput.model_validate(payload_raw)
|
||||
except ValidationError as exc:
|
||||
raise ValueError(f"Invalid content generation input: {exc}") from exc
|
||||
|
||||
writer = app.get_agent(context, WRITER_AGENT_NAME)
|
||||
writer_thread = writer.get_new_thread()
|
||||
|
||||
context.set_custom_status(f"Starting content generation for topic: {payload.topic}")
|
||||
|
||||
initial_raw = yield writer.run(
|
||||
messages=f"Write a short article about '{payload.topic}'.",
|
||||
thread=writer_thread,
|
||||
options={"response_format": GeneratedContent},
|
||||
)
|
||||
|
||||
content = initial_raw.value
|
||||
|
||||
if content is None:
|
||||
raise ValueError("Agent returned no content after extraction.")
|
||||
|
||||
attempt = 0
|
||||
while attempt < payload.max_review_attempts:
|
||||
attempt += 1
|
||||
context.set_custom_status(
|
||||
f"Requesting human feedback. Iteration #{attempt}. Timeout: {payload.approval_timeout_hours} hour(s)."
|
||||
)
|
||||
|
||||
yield context.call_activity("notify_user_for_approval", content.model_dump()) # type: ignore[misc]
|
||||
|
||||
approval_task = context.wait_for_external_event(HUMAN_APPROVAL_EVENT)
|
||||
timeout_task = context.create_timer(
|
||||
context.current_utc_datetime + timedelta(hours=payload.approval_timeout_hours)
|
||||
)
|
||||
|
||||
winner = yield context.task_any([approval_task, timeout_task])
|
||||
|
||||
if winner == approval_task:
|
||||
timeout_task.cancel() # type: ignore[attr-defined]
|
||||
approval_payload = _parse_human_approval(approval_task.result)
|
||||
|
||||
if approval_payload.approved:
|
||||
context.set_custom_status("Content approved by human reviewer. Publishing content...")
|
||||
yield context.call_activity("publish_content", content.model_dump()) # type: ignore[misc]
|
||||
context.set_custom_status(
|
||||
f"Content published successfully at {context.current_utc_datetime:%Y-%m-%dT%H:%M:%S}"
|
||||
)
|
||||
return {"content": content.content}
|
||||
|
||||
context.set_custom_status(
|
||||
"Content rejected by human reviewer. Incorporating feedback and regenerating..."
|
||||
)
|
||||
|
||||
# Check if we've exhausted attempts
|
||||
if attempt >= payload.max_review_attempts:
|
||||
break
|
||||
|
||||
rewrite_prompt = (
|
||||
"The content was rejected by a human reviewer. Please rewrite the article incorporating their feedback.\n\n"
|
||||
f"Human Feedback: {approval_payload.feedback or 'No feedback provided.'}"
|
||||
)
|
||||
rewritten_raw = yield writer.run(
|
||||
messages=rewrite_prompt,
|
||||
thread=writer_thread,
|
||||
options={"response_format": GeneratedContent},
|
||||
)
|
||||
|
||||
content = rewritten_raw.try_parse_value(GeneratedContent)
|
||||
if content is None:
|
||||
raise ValueError("Agent returned no content after rewrite.")
|
||||
else:
|
||||
context.set_custom_status(
|
||||
f"Human approval timed out after {payload.approval_timeout_hours} hour(s). Treating as rejection."
|
||||
)
|
||||
raise TimeoutError(
|
||||
f"Human approval timed out after {payload.approval_timeout_hours} hour(s)."
|
||||
)
|
||||
|
||||
# If we exit the loop without returning, max attempts were exhausted
|
||||
context.set_custom_status("Max review attempts exhausted.")
|
||||
raise RuntimeError(
|
||||
f"Content could not be approved after {payload.max_review_attempts} iteration(s)."
|
||||
)
|
||||
|
||||
|
||||
# 5. HTTP endpoint that starts the human-in-the-loop orchestration.
|
||||
@app.route(route="hitl/run", methods=["POST"])
|
||||
@app.durable_client_input(client_name="client")
|
||||
async def start_content_generation(
|
||||
req: func.HttpRequest,
|
||||
client: DurableOrchestrationClient,
|
||||
) -> func.HttpResponse:
|
||||
try:
|
||||
body = req.get_json()
|
||||
except ValueError:
|
||||
body = None
|
||||
|
||||
if not isinstance(body, Mapping):
|
||||
return func.HttpResponse(
|
||||
body=json.dumps({"error": "Request body must be valid JSON."}),
|
||||
status_code=400,
|
||||
mimetype="application/json",
|
||||
)
|
||||
|
||||
try:
|
||||
payload = ContentGenerationInput.model_validate(body)
|
||||
except ValidationError as exc:
|
||||
return func.HttpResponse(
|
||||
body=json.dumps({"error": f"Invalid content generation input: {exc}"}),
|
||||
status_code=400,
|
||||
mimetype="application/json",
|
||||
)
|
||||
|
||||
instance_id = await client.start_new(
|
||||
orchestration_function_name="content_generation_hitl_orchestration",
|
||||
client_input=payload.model_dump(),
|
||||
)
|
||||
|
||||
status_url = _build_status_url(req.url, instance_id, route="hitl")
|
||||
|
||||
payload_json = {
|
||||
"message": "HITL content generation orchestration started.",
|
||||
"topic": payload.topic,
|
||||
"instanceId": instance_id,
|
||||
"statusQueryGetUri": status_url,
|
||||
}
|
||||
|
||||
return func.HttpResponse(
|
||||
body=json.dumps(payload_json),
|
||||
status_code=202,
|
||||
mimetype="application/json",
|
||||
)
|
||||
|
||||
|
||||
# 6. Endpoint that delivers human approval or rejection back into the orchestration.
|
||||
@app.route(route="hitl/approve/{instanceId}", methods=["POST"])
|
||||
@app.durable_client_input(client_name="client")
|
||||
async def send_human_approval(
|
||||
req: func.HttpRequest,
|
||||
client: DurableOrchestrationClient,
|
||||
) -> func.HttpResponse:
|
||||
instance_id = req.route_params.get("instanceId")
|
||||
if not instance_id:
|
||||
return func.HttpResponse(
|
||||
body=json.dumps({"error": "Missing instanceId in route."}),
|
||||
status_code=400,
|
||||
mimetype="application/json",
|
||||
)
|
||||
|
||||
try:
|
||||
body = req.get_json()
|
||||
except ValueError:
|
||||
body = None
|
||||
|
||||
if not isinstance(body, Mapping):
|
||||
return func.HttpResponse(
|
||||
body=json.dumps({"error": "Approval response is required"}),
|
||||
status_code=400,
|
||||
mimetype="application/json",
|
||||
)
|
||||
|
||||
try:
|
||||
approval = HumanApproval.model_validate(body)
|
||||
except ValidationError as exc:
|
||||
return func.HttpResponse(
|
||||
body=json.dumps({"error": f"Invalid approval payload: {exc}"}),
|
||||
status_code=400,
|
||||
mimetype="application/json",
|
||||
)
|
||||
|
||||
await client.raise_event(instance_id, HUMAN_APPROVAL_EVENT, approval.model_dump())
|
||||
|
||||
payload_json = {
|
||||
"message": "Human approval sent to orchestration.",
|
||||
"instanceId": instance_id,
|
||||
"approved": approval.approved,
|
||||
}
|
||||
|
||||
return func.HttpResponse(
|
||||
body=json.dumps(payload_json),
|
||||
status_code=200,
|
||||
mimetype="application/json",
|
||||
)
|
||||
|
||||
|
||||
# 7. Endpoint that mirrors Durable Functions status plus custom workflow messaging.
|
||||
@app.route(route="hitl/status/{instanceId}", methods=["GET"])
|
||||
@app.durable_client_input(client_name="client")
|
||||
async def get_orchestration_status(
|
||||
req: func.HttpRequest,
|
||||
client: DurableOrchestrationClient,
|
||||
) -> func.HttpResponse:
|
||||
instance_id = req.route_params.get("instanceId")
|
||||
if not instance_id:
|
||||
return func.HttpResponse(
|
||||
body=json.dumps({"error": "Missing instanceId"}),
|
||||
status_code=400,
|
||||
mimetype="application/json",
|
||||
)
|
||||
|
||||
status = await client.get_status(
|
||||
instance_id,
|
||||
show_history=False,
|
||||
show_history_output=False,
|
||||
show_input=True,
|
||||
)
|
||||
|
||||
# Check if status is None or if the instance doesn't exist (runtime_status is None)
|
||||
if getattr(status, "runtime_status", None) is None:
|
||||
return func.HttpResponse(
|
||||
body=json.dumps({"error": "Instance not found."}),
|
||||
status_code=404,
|
||||
mimetype="application/json",
|
||||
)
|
||||
|
||||
response_data: dict[str, Any] = {
|
||||
"instanceId": getattr(status, "instance_id", None),
|
||||
"runtimeStatus": getattr(status.runtime_status, "name", None)
|
||||
if getattr(status, "runtime_status", None)
|
||||
else None,
|
||||
"workflowStatus": getattr(status, "custom_status", None),
|
||||
}
|
||||
|
||||
if getattr(status, "input_", None) is not None:
|
||||
response_data["input"] = status.input_
|
||||
|
||||
if getattr(status, "output", None) is not None:
|
||||
response_data["output"] = status.output
|
||||
|
||||
failure_details = getattr(status, "failure_details", None)
|
||||
if failure_details is not None:
|
||||
response_data["failureDetails"] = failure_details
|
||||
|
||||
return func.HttpResponse(
|
||||
body=json.dumps(response_data),
|
||||
status_code=200,
|
||||
mimetype="application/json",
|
||||
)
|
||||
|
||||
|
||||
# 8. Helper utilities keep parsing logic deterministic.
|
||||
def _build_status_url(request_url: str, instance_id: str, *, route: str) -> str:
|
||||
base_url, _, _ = request_url.partition("/api/")
|
||||
if not base_url:
|
||||
base_url = request_url.rstrip("/")
|
||||
return f"{base_url}/api/{route}/status/{instance_id}"
|
||||
|
||||
|
||||
def _parse_human_approval(raw: Any) -> HumanApproval:
|
||||
if isinstance(raw, Mapping):
|
||||
return HumanApproval.model_validate(raw)
|
||||
|
||||
if isinstance(raw, str):
|
||||
stripped = raw.strip()
|
||||
if not stripped:
|
||||
return HumanApproval(approved=False, feedback="")
|
||||
try:
|
||||
parsed = json.loads(stripped)
|
||||
if isinstance(parsed, Mapping):
|
||||
return HumanApproval.model_validate(parsed)
|
||||
except json.JSONDecodeError:
|
||||
logger.debug(
|
||||
"[HITL] Approval payload is not valid JSON; using string heuristics.",
|
||||
exc_info=True,
|
||||
)
|
||||
|
||||
affirmative = {"true", "yes", "approved", "y", "1"}
|
||||
negative = {"false", "no", "rejected", "n", "0"}
|
||||
lower = stripped.lower()
|
||||
if lower in affirmative:
|
||||
return HumanApproval(approved=True, feedback="")
|
||||
if lower in negative:
|
||||
return HumanApproval(approved=False, feedback="")
|
||||
return HumanApproval(approved=False, feedback=stripped)
|
||||
|
||||
raise ValueError("Approval payload must be a JSON object or string.")
|
||||
|
||||
|
||||
"""
|
||||
Expected response from `POST /api/hitl/run`:
|
||||
|
||||
HTTP/1.1 202 Accepted
|
||||
{
|
||||
"message": "HITL content generation orchestration started.",
|
||||
"topic": "Contoso launch",
|
||||
"instanceId": "<durable-instance-id>",
|
||||
"statusQueryGetUri": "http://localhost:7071/api/hitl/status/<durable-instance-id>"
|
||||
}
|
||||
|
||||
Expected response after approving via `POST /api/hitl/approve/{instanceId}`:
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
{
|
||||
"message": "Human approval sent to orchestration.",
|
||||
"instanceId": "<durable-instance-id>",
|
||||
"approved": true
|
||||
}
|
||||
|
||||
Expected response from `GET /api/hitl/status/{instanceId}` once published:
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
{
|
||||
"instanceId": "<durable-instance-id>",
|
||||
"runtimeStatus": "Completed",
|
||||
"workflowStatus": "Content published successfully at 2024-01-01T12:00:00",
|
||||
"output": {
|
||||
"content": "Thank you for joining the Contoso product launch..."
|
||||
}
|
||||
}
|
||||
"""
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"version": "2.0",
|
||||
"extensionBundle": {
|
||||
"id": "Microsoft.Azure.Functions.ExtensionBundle",
|
||||
"version": "[4.*, 5.0.0)"
|
||||
},
|
||||
"extensions": {
|
||||
"durableTask": {
|
||||
"hubName": "%TASKHUB_NAME%"
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"IsEncrypted": false,
|
||||
"Values": {
|
||||
"FUNCTIONS_WORKER_RUNTIME": "python",
|
||||
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
|
||||
"DURABLE_TASK_SCHEDULER_CONNECTION_STRING": "Endpoint=http://localhost:8080;TaskHub=default;Authentication=None",
|
||||
"TASKHUB_NAME": "default",
|
||||
"AZURE_OPENAI_ENDPOINT": "<AZURE_OPENAI_ENDPOINT>",
|
||||
"AZURE_OPENAI_CHAT_DEPLOYMENT_NAME": "<AZURE_OPENAI_CHAT_DEPLOYMENT_NAME>",
|
||||
"AZURE_OPENAI_API_KEY": "<AZURE_OPENAI_API_KEY>"
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
# Agent Framework packages
|
||||
# To use the deployed version, uncomment the line below and comment out the local installation lines
|
||||
# agent-framework-azurefunctions
|
||||
|
||||
# Local installation (for development and testing)
|
||||
# Each package must be listed explicitly because pip doesn't resolve uv workspace sources.
|
||||
# Without explicit entries, pip would fetch transitive dependencies from PyPI instead of local source.
|
||||
-e ../../../../packages/core # Core framework - base dependency for all packages
|
||||
-e ../../../../packages/durabletask # Durable Task support - dependency of azurefunctions
|
||||
-e ../../../../packages/azurefunctions # Azure Functions integration - the main package for this sample
|
||||
|
||||
# Azure authentication
|
||||
azure-identity
|
||||
@@ -0,0 +1,187 @@
|
||||
# Agent as MCP Tool Sample
|
||||
|
||||
This sample demonstrates how to configure AI agents to be accessible as both HTTP endpoints and [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) tools, enabling flexible integration patterns for AI agent consumption.
|
||||
|
||||
## Key Concepts Demonstrated
|
||||
|
||||
- **Multi-trigger Agent Configuration**: Configure agents to support HTTP triggers, MCP tool triggers, or both
|
||||
- **Microsoft Agent Framework Integration**: Use the framework to define AI agents with specific roles and capabilities
|
||||
- **Flexible Agent Registration**: Register agents with customizable trigger configurations
|
||||
- **MCP Server Hosting**: Expose agents as MCP tools for consumption by MCP-compatible clients
|
||||
|
||||
## Sample Architecture
|
||||
|
||||
This sample creates three agents with different trigger configurations:
|
||||
|
||||
| Agent | Role | HTTP Trigger | MCP Tool Trigger | Description |
|
||||
|-------|------|--------------|------------------|-------------|
|
||||
| **Joker** | Comedy specialist | ✅ Enabled | ❌ Disabled | Accessible only via HTTP requests |
|
||||
| **StockAdvisor** | Financial data | ❌ Disabled | ✅ Enabled | Accessible only as MCP tool |
|
||||
| **PlantAdvisor** | Indoor plant recommendations | ✅ Enabled | ✅ Enabled | Accessible via both HTTP and MCP |
|
||||
|
||||
## Environment Setup
|
||||
|
||||
See the [README.md](../README.md) file in the parent directory for complete setup instructions, including:
|
||||
|
||||
- Prerequisites installation
|
||||
- Azure OpenAI configuration
|
||||
- Durable Task Scheduler setup
|
||||
- Storage emulator configuration
|
||||
|
||||
## Configuration
|
||||
|
||||
Update your `local.settings.json` with your Azure OpenAI credentials:
|
||||
|
||||
```json
|
||||
{
|
||||
"Values": {
|
||||
"AZURE_OPENAI_ENDPOINT": "https://your-resource.openai.azure.com/",
|
||||
"AZURE_OPENAI_CHAT_DEPLOYMENT_NAME": "your-deployment-name",
|
||||
"AZURE_OPENAI_KEY": "your-api-key-if-not-using-rbac"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Running the Sample
|
||||
|
||||
1. **Start the Function App**:
|
||||
```bash
|
||||
cd python/samples/durable/azure_functions/08_mcp_server
|
||||
func start
|
||||
```
|
||||
|
||||
2. **Note the MCP Server Endpoint**: When the app starts, you'll see the MCP server endpoint in the terminal output. It will look like:
|
||||
```
|
||||
MCP server endpoint: http://localhost:7071/runtime/webhooks/mcp
|
||||
```
|
||||
|
||||
## Testing MCP Tool Integration
|
||||
|
||||
### Using MCP Inspector
|
||||
|
||||
1. Install the [MCP Inspector](https://modelcontextprotocol.io/docs/tools/inspector)
|
||||
2. Connect using the MCP server endpoint from your terminal output
|
||||
3. Select **"Streamable HTTP"** as the transport method
|
||||
4. Test the available MCP tools:
|
||||
- `StockAdvisor` - Available only as MCP tool
|
||||
- `PlantAdvisor` - Available as both HTTP and MCP tool
|
||||
|
||||
### Using Other MCP Clients
|
||||
|
||||
Any MCP-compatible client can connect to the server endpoint and utilize the exposed agent tools. The agents will appear as callable tools within the MCP protocol.
|
||||
|
||||
## Testing HTTP Endpoints
|
||||
|
||||
For agents with HTTP triggers enabled (Joker and PlantAdvisor), you can test them using curl:
|
||||
|
||||
```bash
|
||||
# Test Joker agent (HTTP only)
|
||||
curl -X POST http://localhost:7071/api/agents/Joker/run \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"message": "Tell me a joke"}'
|
||||
|
||||
# Test PlantAdvisor agent (HTTP and MCP)
|
||||
curl -X POST http://localhost:7071/api/agents/PlantAdvisor/run \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"message": "Recommend an indoor plant"}'
|
||||
```
|
||||
|
||||
Note: StockAdvisor does not have HTTP endpoints and is only accessible via MCP tool triggers.
|
||||
|
||||
## Expected Output
|
||||
|
||||
**HTTP Responses** will be returned directly to your HTTP client.
|
||||
|
||||
**MCP Tool Responses** will be visible in:
|
||||
- The terminal where `func start` is running
|
||||
- Your MCP client interface
|
||||
- The DTS dashboard at `http://localhost:8080` (if using Durable Task Scheduler)
|
||||
|
||||
## Health Check
|
||||
|
||||
Check the health endpoint to see which agents have which triggers enabled:
|
||||
|
||||
```bash
|
||||
curl http://localhost:7071/api/health
|
||||
```
|
||||
|
||||
Expected response:
|
||||
|
||||
```json
|
||||
{
|
||||
"status": "healthy",
|
||||
"agents": [
|
||||
{
|
||||
"name": "Joker",
|
||||
"type": "Agent",
|
||||
"http_endpoint_enabled": true,
|
||||
"mcp_tool_enabled": false
|
||||
},
|
||||
{
|
||||
"name": "StockAdvisor",
|
||||
"type": "Agent",
|
||||
"http_endpoint_enabled": false,
|
||||
"mcp_tool_enabled": true
|
||||
},
|
||||
{
|
||||
"name": "PlantAdvisor",
|
||||
"type": "Agent",
|
||||
"http_endpoint_enabled": true,
|
||||
"mcp_tool_enabled": true
|
||||
}
|
||||
],
|
||||
"agent_count": 3
|
||||
}
|
||||
```
|
||||
|
||||
## Code Structure
|
||||
|
||||
The sample shows how to enable MCP tool triggers with flexible agent configuration:
|
||||
|
||||
```python
|
||||
from agent_framework.azure import AgentFunctionApp, AzureOpenAIChatClient
|
||||
|
||||
# Create Azure OpenAI Chat Client
|
||||
chat_client = AzureOpenAIChatClient()
|
||||
|
||||
# Define agents with different roles
|
||||
joker_agent = chat_client.as_agent(
|
||||
name="Joker",
|
||||
instructions="You are good at telling jokes.",
|
||||
)
|
||||
|
||||
stock_agent = chat_client.as_agent(
|
||||
name="StockAdvisor",
|
||||
instructions="Check stock prices.",
|
||||
)
|
||||
|
||||
plant_agent = chat_client.as_agent(
|
||||
name="PlantAdvisor",
|
||||
instructions="Recommend plants.",
|
||||
description="Get plant recommendations.",
|
||||
)
|
||||
|
||||
# Create the AgentFunctionApp
|
||||
app = AgentFunctionApp(enable_health_check=True)
|
||||
|
||||
# Configure agents with different trigger combinations:
|
||||
# HTTP trigger only (default)
|
||||
app.add_agent(joker_agent)
|
||||
|
||||
# MCP tool trigger only (HTTP disabled)
|
||||
app.add_agent(stock_agent, enable_http_endpoint=False, enable_mcp_tool_trigger=True)
|
||||
|
||||
# Both HTTP and MCP tool triggers enabled
|
||||
app.add_agent(plant_agent, enable_http_endpoint=True, enable_mcp_tool_trigger=True)
|
||||
```
|
||||
|
||||
This automatically creates the following endpoints based on agent configuration:
|
||||
- `POST /api/agents/{AgentName}/run` - HTTP endpoint (when `enable_http_endpoint=True`)
|
||||
- MCP tool triggers for agents with `enable_mcp_tool_trigger=True`
|
||||
- `GET /api/health` - Health check endpoint showing agent configurations
|
||||
|
||||
## Learn More
|
||||
|
||||
- [Model Context Protocol Documentation](https://modelcontextprotocol.io/)
|
||||
- [Microsoft Agent Framework Documentation](https://github.com/microsoft/agent-framework)
|
||||
- [Azure Functions Documentation](https://learn.microsoft.com/azure/azure-functions/)
|
||||
@@ -0,0 +1,63 @@
|
||||
"""
|
||||
Example showing how to configure AI agents with different trigger configurations.
|
||||
|
||||
This sample demonstrates how to configure agents to be accessible as both HTTP endpoints
|
||||
and Model Context Protocol (MCP) tools, enabling flexible integration patterns for AI agent
|
||||
consumption.
|
||||
|
||||
Key concepts demonstrated:
|
||||
- Multi-trigger Agent Configuration: Configure agents to support HTTP triggers, MCP tool triggers, or both
|
||||
- Microsoft Agent Framework Integration: Use the framework to define AI agents with specific roles
|
||||
- Flexible Agent Registration: Register agents with customizable trigger configurations
|
||||
|
||||
This sample creates three agents with different trigger configurations:
|
||||
- Joker: HTTP trigger only (default)
|
||||
- StockAdvisor: MCP tool trigger only (HTTP disabled)
|
||||
- PlantAdvisor: Both HTTP and MCP tool triggers enabled
|
||||
|
||||
Required environment variables:
|
||||
- AZURE_OPENAI_ENDPOINT: Your Azure OpenAI endpoint
|
||||
- AZURE_OPENAI_CHAT_DEPLOYMENT_NAME: Your Azure OpenAI deployment name
|
||||
|
||||
Authentication uses AzureCliCredential (Azure Identity).
|
||||
"""
|
||||
|
||||
from agent_framework.azure import AgentFunctionApp, AzureOpenAIChatClient
|
||||
|
||||
# Create Azure OpenAI Chat Client
|
||||
# This uses AzureCliCredential for authentication (requires 'az login')
|
||||
chat_client = AzureOpenAIChatClient()
|
||||
|
||||
# Define three AI agents with different roles
|
||||
# Agent 1: Joker - HTTP trigger only (default)
|
||||
agent1 = chat_client.as_agent(
|
||||
name="Joker",
|
||||
instructions="You are good at telling jokes.",
|
||||
)
|
||||
|
||||
# Agent 2: StockAdvisor - MCP tool trigger only
|
||||
agent2 = chat_client.as_agent(
|
||||
name="StockAdvisor",
|
||||
instructions="Check stock prices.",
|
||||
)
|
||||
|
||||
# Agent 3: PlantAdvisor - Both HTTP and MCP tool triggers
|
||||
agent3 = chat_client.as_agent(
|
||||
name="PlantAdvisor",
|
||||
instructions="Recommend plants.",
|
||||
description="Get plant recommendations.",
|
||||
)
|
||||
|
||||
# Create the AgentFunctionApp with selective trigger configuration
|
||||
app = AgentFunctionApp(
|
||||
enable_health_check=True,
|
||||
)
|
||||
|
||||
# Agent 1: HTTP trigger only (default)
|
||||
app.add_agent(agent1)
|
||||
|
||||
# Agent 2: Disable HTTP trigger, enable MCP tool trigger only
|
||||
app.add_agent(agent2, enable_http_endpoint=False, enable_mcp_tool_trigger=True)
|
||||
|
||||
# Agent 3: Enable both HTTP and MCP tool triggers
|
||||
app.add_agent(agent3, enable_http_endpoint=True, enable_mcp_tool_trigger=True)
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"version": "2.0",
|
||||
"extensionBundle": {
|
||||
"id": "Microsoft.Azure.Functions.ExtensionBundle",
|
||||
"version": "[4.*, 5.0.0)"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"IsEncrypted": false,
|
||||
"Values": {
|
||||
"FUNCTIONS_WORKER_RUNTIME": "python",
|
||||
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
|
||||
"DURABLE_TASK_SCHEDULER_CONNECTION_STRING": "Endpoint=http://localhost:8080;TaskHub=default;Authentication=None",
|
||||
"AZURE_OPENAI_ENDPOINT": "<AZURE_OPENAI_ENDPOINT>",
|
||||
"AZURE_OPENAI_CHAT_DEPLOYMENT_NAME": "<AZURE_OPENAI_CHAT_DEPLOYMENT_NAME>"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
# Agent Framework packages
|
||||
# To use the deployed version, uncomment the line below and comment out the local installation lines
|
||||
# agent-framework-azurefunctions
|
||||
|
||||
# Local installation (for development and testing)
|
||||
# Each package must be listed explicitly because pip doesn't resolve uv workspace sources.
|
||||
# Without explicit entries, pip would fetch transitive dependencies from PyPI instead of local source.
|
||||
-e ../../../../packages/core # Core framework - base dependency for all packages
|
||||
-e ../../../../packages/durabletask # Durable Task support - dependency of azurefunctions
|
||||
-e ../../../../packages/azurefunctions # Azure Functions integration - the main package for this sample
|
||||
|
||||
# Azure authentication
|
||||
azure-identity
|
||||
@@ -0,0 +1,48 @@
|
||||
These are common instructions for setting up your environment for every sample in this directory.
|
||||
These samples illustrate the Durable extensibility for Agent Framework running in Azure Functions.
|
||||
|
||||
All of these samples are set up to run in Azure Functions. Azure Functions has a local development tool called [CoreTools](https://learn.microsoft.com/azure/azure-functions/functions-run-local?tabs=windows%2Cpython%2Cv2&pivots=programming-language-python#install-the-azure-functions-core-tools) which we will set up to run these samples locally.
|
||||
|
||||
## Environment Setup
|
||||
|
||||
### 1. Install dependencies and create appropriate services
|
||||
|
||||
- Install [Azure Functions Core Tools 4.x](https://learn.microsoft.com/azure/azure-functions/functions-run-local?tabs=windows%2Cpython%2Cv2&pivots=programming-language-python#install-the-azure-functions-core-tools)
|
||||
|
||||
- Install [Azurite storage emulator](https://learn.microsoft.com/en-us/azure/storage/common/storage-install-azurite?toc=%2Fazure%2Fstorage%2Fblobs%2Ftoc.json&bc=%2Fazure%2Fstorage%2Fblobs%2Fbreadcrumb%2Ftoc.json&tabs=visual-studio%2Cblob-storage)
|
||||
|
||||
- Create an [Azure OpenAI](https://azure.microsoft.com/en-us/products/ai-foundry/models/openai) resource. Note the Azure OpenAI endpoint, deployment name, and the key (or ensure you can authenticate with `AzureCliCredential`).
|
||||
|
||||
- Install a tool to execute HTTP calls, for example the [REST Client extension](https://marketplace.visualstudio.com/items?itemName=humao.rest-client)
|
||||
|
||||
- [Optionally] Create an [Azure Function Python app](https://learn.microsoft.com/en-us/azure/azure-functions/functions-create-function-app-portal?tabs=core-tools&pivots=flex-consumption-plan) to later deploy your app to Azure if you so desire.
|
||||
|
||||
### 2. Create and activate a virtual environment
|
||||
|
||||
**Windows (PowerShell):**
|
||||
```powershell
|
||||
python -m venv .venv
|
||||
.venv\Scripts\Activate.ps1
|
||||
```
|
||||
|
||||
**Linux/macOS:**
|
||||
```bash
|
||||
python -m venv .venv
|
||||
source .venv/bin/activate
|
||||
```
|
||||
|
||||
### 3. Running the samples
|
||||
|
||||
- [Start the Azurite emulator](https://learn.microsoft.com/en-us/azure/storage/common/storage-install-azurite?tabs=npm%2Cblob-storage#run-azurite)
|
||||
|
||||
- Inside each sample:
|
||||
|
||||
- Install Python dependencies – from the sample directory, run `pip install -r requirements.txt` (or the equivalent in your active virtual environment).
|
||||
|
||||
- Copy `local.settings.json.template` to `local.settings.json`, then update `AZURE_OPENAI_ENDPOINT` and `AZURE_OPENAI_CHAT_DEPLOYMENT_NAME` for Azure OpenAI authentication. The samples use `AzureCliCredential` by default, so ensure you're logged in via `az login`.
|
||||
- Alternatively, you can use API key authentication by setting `AZURE_OPENAI_API_KEY` and updating the code to use `AzureOpenAIChatClient()` without the credential parameter.
|
||||
- Keep `TASKHUB_NAME` set to `default` unless you plan to change the durable task hub name.
|
||||
|
||||
- Run the command `func start` from the root of the sample
|
||||
|
||||
- Follow each sample's README for scenario-specific steps, and use its `demo.http` file (or provided curl examples) to trigger the hosted HTTP endpoints.
|
||||
Reference in New Issue
Block a user