mirror of
https://github.com/microsoft/agent-framework.git
synced 2026-06-16 21:04:09 +08:00
Python: Add Durabletask samples and minor fixes (#3157)
* Add samples and minor fixes * Add redis sample and wait-for-completion * Add wait-for-completion support * ADd missing docs
This commit is contained in:
committed by
GitHub
Unverified
parent
1e36ba33c4
commit
3df916064c
@@ -1,6 +1,6 @@
|
||||
# Single Agent Sample
|
||||
# Single Agent
|
||||
|
||||
This sample demonstrates how to use the durable agents extension to create a worker-client setup that hosts a single AI agent and provides interactive conversation via the Durable Task Scheduler.
|
||||
This sample demonstrates how to create a worker-client setup that hosts a single AI agent and provides interactive conversation via the Durable Task Scheduler.
|
||||
|
||||
## Key Concepts Demonstrated
|
||||
|
||||
@@ -15,18 +15,24 @@ See the [README.md](../README.md) file in the parent directory for more informat
|
||||
|
||||
## Running the Sample
|
||||
|
||||
With the environment setup, you can run the sample using separate worker and client processes:
|
||||
With the environment setup, you can run the sample using the combined approach or separate worker and client processes:
|
||||
|
||||
**Start the worker:**
|
||||
**Option 1: Combined (Recommended for Testing)**
|
||||
|
||||
```bash
|
||||
cd samples/getting_started/durabletask/01_single_agent
|
||||
python sample.py
|
||||
```
|
||||
|
||||
**Option 2: Separate Processes**
|
||||
|
||||
Start the worker in one terminal:
|
||||
|
||||
```bash
|
||||
python worker.py
|
||||
```
|
||||
|
||||
The worker will register the Joker agent and listen for requests.
|
||||
|
||||
**In a new terminal, run the client:**
|
||||
In a new terminal, run the client:
|
||||
|
||||
```bash
|
||||
python client.py
|
||||
@@ -58,9 +64,10 @@ Because light attracts bugs!
|
||||
You can view the state of the agent in the Durable Task Scheduler dashboard:
|
||||
|
||||
1. Open your browser and navigate to `http://localhost:8082`
|
||||
2. In the dashboard, you can view the state of the Joker agent, including its conversation history and current state
|
||||
|
||||
The agent maintains conversation state across multiple interactions, and you can inspect this state in the dashboard to understand how the durable agents extension manages conversation context.
|
||||
2. In the dashboard, you can view:
|
||||
- The state of the Joker agent entity (dafx-Joker)
|
||||
- Conversation history and current state
|
||||
- How the durable agents extension manages conversation context
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -23,69 +23,96 @@ logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
"""Main entry point for the client application."""
|
||||
logger.info("Starting Durable Task Agent Client...")
|
||||
def get_client(
|
||||
taskhub: str | None = None,
|
||||
endpoint: str | None = None,
|
||||
log_handler: logging.Handler | None = None
|
||||
) -> DurableAIAgentClient:
|
||||
"""Create a configured DurableAIAgentClient.
|
||||
|
||||
# Get environment variables for taskhub and endpoint with defaults
|
||||
taskhub_name = os.getenv("TASKHUB", "default")
|
||||
endpoint = os.getenv("ENDPOINT", "http://localhost:8080")
|
||||
|
||||
logger.info(f"Using taskhub: {taskhub_name}")
|
||||
logger.info(f"Using endpoint: {endpoint}")
|
||||
logger.info("")
|
||||
|
||||
# Set credential to None for emulator, or DefaultAzureCredential for Azure
|
||||
credential = None if endpoint == "http://localhost:8080" else DefaultAzureCredential()
|
||||
Args:
|
||||
taskhub: Task hub name (defaults to TASKHUB env var or "default")
|
||||
endpoint: Scheduler endpoint (defaults to ENDPOINT env var or "http://localhost:8080")
|
||||
log_handler: Optional logging handler for client logging
|
||||
|
||||
Returns:
|
||||
Configured DurableAIAgentClient instance
|
||||
"""
|
||||
taskhub_name = taskhub or os.getenv("TASKHUB", "default")
|
||||
endpoint_url = endpoint or os.getenv("ENDPOINT", "http://localhost:8080")
|
||||
|
||||
# Create a client using Azure Managed Durable Task
|
||||
client = DurableTaskSchedulerClient(
|
||||
host_address=endpoint,
|
||||
secure_channel=endpoint != "http://localhost:8080",
|
||||
logger.debug(f"Using taskhub: {taskhub_name}")
|
||||
logger.debug(f"Using endpoint: {endpoint_url}")
|
||||
|
||||
credential = None if endpoint_url == "http://localhost:8080" else DefaultAzureCredential()
|
||||
|
||||
dts_client = DurableTaskSchedulerClient(
|
||||
host_address=endpoint_url,
|
||||
secure_channel=endpoint_url != "http://localhost:8080",
|
||||
taskhub=taskhub_name,
|
||||
token_credential=credential
|
||||
token_credential=credential,
|
||||
log_handler=log_handler
|
||||
)
|
||||
|
||||
# Wrap it with the agent client
|
||||
agent_client = DurableAIAgentClient(client)
|
||||
return DurableAIAgentClient(dts_client)
|
||||
|
||||
|
||||
def run_client(agent_client: DurableAIAgentClient) -> None:
|
||||
"""Run client interactions with the Joker agent.
|
||||
|
||||
Args:
|
||||
agent_client: The DurableAIAgentClient instance
|
||||
"""
|
||||
# Get a reference to the Joker agent
|
||||
logger.info("Getting reference to Joker agent...")
|
||||
logger.debug("Getting reference to Joker agent...")
|
||||
joker = agent_client.get_agent("Joker")
|
||||
|
||||
# Create a new thread for the conversation
|
||||
thread = joker.get_new_thread()
|
||||
logger.debug(f"Thread ID: {thread.session_id}")
|
||||
logger.info("Start chatting with the Joker agent! (Type 'exit' to quit)")
|
||||
|
||||
logger.info(f"Created conversation thread: {thread.session_id}")
|
||||
logger.info("")
|
||||
# Interactive conversation loop
|
||||
while True:
|
||||
# Get user input
|
||||
try:
|
||||
user_message = input("You: ").strip()
|
||||
except (EOFError, KeyboardInterrupt):
|
||||
logger.info("\nExiting...")
|
||||
break
|
||||
|
||||
# Check for exit command
|
||||
if user_message.lower() == "exit":
|
||||
logger.info("Goodbye!")
|
||||
break
|
||||
|
||||
# Skip empty messages
|
||||
if not user_message:
|
||||
continue
|
||||
|
||||
# Send message to agent and get response
|
||||
try:
|
||||
response = joker.run(user_message, thread=thread)
|
||||
logger.info(f"Joker: {response.text} \n")
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting response: {e}")
|
||||
|
||||
logger.info("Conversation completed.")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
"""Main entry point for the client application."""
|
||||
logger.debug("Starting Durable Task Agent Client...")
|
||||
|
||||
# Create client using helper function
|
||||
agent_client = get_client()
|
||||
|
||||
try:
|
||||
# First message
|
||||
message1 = "Tell me a short joke about cloud computing."
|
||||
logger.info(f"User: {message1}")
|
||||
logger.info("")
|
||||
|
||||
# Run the agent - this blocks until the response is ready
|
||||
response1 = joker.run(message1, thread=thread)
|
||||
logger.info(f"Agent: {response1.text}")
|
||||
logger.info("")
|
||||
|
||||
# Second message - continuing the conversation
|
||||
message2 = "Now tell me one about Python programming."
|
||||
logger.info(f"User: {message2}")
|
||||
logger.info("")
|
||||
|
||||
response2 = joker.run(message2, thread=thread)
|
||||
logger.info(f"Agent: {response2.text}")
|
||||
logger.info("")
|
||||
|
||||
logger.info(f"Conversation completed successfully!")
|
||||
logger.info(f"Thread ID: {thread.session_id}")
|
||||
|
||||
run_client(agent_client)
|
||||
except Exception as e:
|
||||
logger.exception(f"Error during agent interaction: {e}")
|
||||
finally:
|
||||
logger.info("Client shutting down")
|
||||
logger.debug("Client shutting down")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -14,122 +14,42 @@ To run this sample:
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
|
||||
from agent_framework.azure import AzureOpenAIChatClient
|
||||
from agent_framework_durabletask import DurableAIAgentClient, DurableAIAgentWorker
|
||||
from azure.identity import AzureCliCredential, DefaultAzureCredential
|
||||
from dotenv import load_dotenv
|
||||
from durabletask.azuremanaged.client import DurableTaskSchedulerClient
|
||||
from durabletask.azuremanaged.worker import DurableTaskSchedulerWorker
|
||||
|
||||
# Configure logging
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
# Import helper functions from worker and client modules
|
||||
from client import get_client, run_client
|
||||
from worker import get_worker, setup_worker
|
||||
|
||||
# Configure logging (must be after imports to override their basicConfig)
|
||||
logging.basicConfig(level=logging.INFO, force=True)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def create_joker_agent():
|
||||
"""Create the Joker agent using Azure OpenAI.
|
||||
|
||||
Returns:
|
||||
AgentProtocol: The configured Joker agent
|
||||
"""
|
||||
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
|
||||
name="Joker",
|
||||
instructions="You are good at telling jokes.",
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
"""Main entry point - runs both worker and client in single process."""
|
||||
logger.info("Starting Durable Task Agent Sample (Combined Worker + Client)...")
|
||||
|
||||
# Get environment variables for taskhub and endpoint with defaults
|
||||
taskhub_name = os.getenv("TASKHUB", "default")
|
||||
endpoint = os.getenv("ENDPOINT", "http://localhost:8080")
|
||||
logger.debug("Starting Durable Task Agent Sample (Combined Worker + Client)...")
|
||||
|
||||
logger.info(f"Using taskhub: {taskhub_name}")
|
||||
logger.info(f"Using endpoint: {endpoint}")
|
||||
logger.info("")
|
||||
|
||||
# Set credential to None for emulator, or DefaultAzureCredential for Azure
|
||||
credential = None if endpoint == "http://localhost:8080" else DefaultAzureCredential()
|
||||
secure_channel = endpoint != "http://localhost:8080"
|
||||
silent_handler = logging.NullHandler()
|
||||
|
||||
# Create and start the worker using a context manager
|
||||
with DurableTaskSchedulerWorker(
|
||||
host_address=endpoint,
|
||||
secure_channel=secure_channel,
|
||||
taskhub=taskhub_name,
|
||||
token_credential=credential
|
||||
) as worker:
|
||||
|
||||
# Wrap with the agent worker
|
||||
agent_worker = DurableAIAgentWorker(worker)
|
||||
|
||||
# Create and register the Joker agent
|
||||
logger.info("Creating and registering Joker agent...")
|
||||
joker_agent = create_joker_agent()
|
||||
agent_worker.add_agent(joker_agent)
|
||||
|
||||
logger.info(f"✓ Registered agent: {joker_agent.name}")
|
||||
logger.info(f" Entity name: dafx-{joker_agent.name}")
|
||||
logger.info("")
|
||||
# Create and start the worker using helper function and context manager
|
||||
with get_worker(log_handler=silent_handler) as dts_worker:
|
||||
# Register agents using helper function
|
||||
setup_worker(dts_worker)
|
||||
|
||||
# Start the worker
|
||||
worker.start()
|
||||
logger.info("Worker started and listening for requests...")
|
||||
logger.info("")
|
||||
dts_worker.start()
|
||||
logger.debug("Worker started and listening for requests...")
|
||||
|
||||
# Create the client
|
||||
client = DurableTaskSchedulerClient(
|
||||
host_address=endpoint,
|
||||
secure_channel=secure_channel,
|
||||
taskhub=taskhub_name,
|
||||
token_credential=credential
|
||||
)
|
||||
|
||||
# Wrap it with the agent client
|
||||
agent_client = DurableAIAgentClient(client)
|
||||
|
||||
# Get a reference to the Joker agent
|
||||
logger.info("Getting reference to Joker agent...")
|
||||
joker = agent_client.get_agent("Joker")
|
||||
|
||||
# Create a new thread for the conversation
|
||||
thread = joker.get_new_thread()
|
||||
|
||||
logger.info(f"Created conversation thread: {thread.session_id}")
|
||||
logger.info("")
|
||||
# Create the client using helper function
|
||||
agent_client = get_client(log_handler=silent_handler)
|
||||
|
||||
try:
|
||||
# First message
|
||||
message1 = "Tell me a short joke about cloud computing."
|
||||
logger.info(f"User: {message1}")
|
||||
logger.info("")
|
||||
|
||||
# Run the agent - this blocks until the response is ready
|
||||
response1 = joker.run(message1, thread=thread)
|
||||
logger.info(f"Agent: {response1.text}; {response1}")
|
||||
logger.info("")
|
||||
|
||||
# Second message - continuing the conversation
|
||||
message2 = "Now tell me one about Python programming."
|
||||
logger.info(f"User: {message2}")
|
||||
logger.info("")
|
||||
|
||||
response2 = joker.run(message2, thread=thread)
|
||||
logger.info(f"Agent: {response2.text}; {response2}")
|
||||
logger.info("")
|
||||
|
||||
logger.info(f"Conversation completed successfully!")
|
||||
logger.info(f"Thread ID: {thread.session_id}")
|
||||
|
||||
# Run client interactions using helper function
|
||||
run_client(agent_client)
|
||||
except Exception as e:
|
||||
logger.exception(f"Error during agent interaction: {e}")
|
||||
|
||||
logger.info("")
|
||||
logger.info("Sample completed. Worker shutting down...")
|
||||
logger.debug("Sample completed. Worker shutting down...")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -19,7 +19,7 @@ from azure.identity import AzureCliCredential, DefaultAzureCredential
|
||||
from durabletask.azuremanaged.worker import DurableTaskSchedulerWorker
|
||||
|
||||
# Configure logging
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logging.basicConfig(level=logging.WARNING)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -35,39 +35,71 @@ def create_joker_agent():
|
||||
)
|
||||
|
||||
|
||||
async def main():
|
||||
"""Main entry point for the worker process."""
|
||||
logger.info("Starting Durable Task Agent Worker...")
|
||||
def get_worker(
|
||||
taskhub: str | None = None,
|
||||
endpoint: str | None = None,
|
||||
log_handler: logging.Handler | None = None
|
||||
) -> DurableTaskSchedulerWorker:
|
||||
"""Create a configured DurableTaskSchedulerWorker.
|
||||
|
||||
# Get environment variables for taskhub and endpoint with defaults
|
||||
taskhub_name = os.getenv("TASKHUB", "default")
|
||||
endpoint = os.getenv("ENDPOINT", "http://localhost:8080")
|
||||
|
||||
logger.info(f"Using taskhub: {taskhub_name}")
|
||||
logger.info(f"Using endpoint: {endpoint}")
|
||||
|
||||
# Set credential to None for emulator, or DefaultAzureCredential for Azure
|
||||
credential = None if endpoint == "http://localhost:8080" else DefaultAzureCredential()
|
||||
Args:
|
||||
taskhub: Task hub name (defaults to TASKHUB env var or "default")
|
||||
endpoint: Scheduler endpoint (defaults to ENDPOINT env var or "http://localhost:8080")
|
||||
log_handler: Optional logging handler for worker logging
|
||||
|
||||
Returns:
|
||||
Configured DurableTaskSchedulerWorker instance
|
||||
"""
|
||||
taskhub_name = taskhub or os.getenv("TASKHUB", "default")
|
||||
endpoint_url = endpoint or os.getenv("ENDPOINT", "http://localhost:8080")
|
||||
|
||||
# Create a worker using Azure Managed Durable Task
|
||||
worker = DurableTaskSchedulerWorker(
|
||||
host_address=endpoint,
|
||||
secure_channel=endpoint != "http://localhost:8080",
|
||||
logger.debug(f"Using taskhub: {taskhub_name}")
|
||||
logger.debug(f"Using endpoint: {endpoint_url}")
|
||||
|
||||
credential = None if endpoint_url == "http://localhost:8080" else DefaultAzureCredential()
|
||||
|
||||
return DurableTaskSchedulerWorker(
|
||||
host_address=endpoint_url,
|
||||
secure_channel=endpoint_url != "http://localhost:8080",
|
||||
taskhub=taskhub_name,
|
||||
token_credential=credential
|
||||
token_credential=credential,
|
||||
log_handler=log_handler
|
||||
)
|
||||
|
||||
|
||||
def setup_worker(worker: DurableTaskSchedulerWorker) -> DurableAIAgentWorker:
|
||||
"""Set up the worker with agents registered.
|
||||
|
||||
Args:
|
||||
worker: The DurableTaskSchedulerWorker instance
|
||||
|
||||
Returns:
|
||||
DurableAIAgentWorker with agents registered
|
||||
"""
|
||||
# Wrap it with the agent worker
|
||||
agent_worker = DurableAIAgentWorker(worker)
|
||||
|
||||
# Create and register the Joker agent
|
||||
logger.info("Creating and registering Joker agent...")
|
||||
logger.debug("Creating and registering Joker agent...")
|
||||
joker_agent = create_joker_agent()
|
||||
agent_worker.add_agent(joker_agent)
|
||||
|
||||
logger.info(f"✓ Registered agent: {joker_agent.name}")
|
||||
logger.info(f" Entity name: dafx-{joker_agent.name}")
|
||||
logger.info("")
|
||||
logger.debug(f"✓ Registered agent: {joker_agent.name}")
|
||||
logger.debug(f" Entity name: dafx-{joker_agent.name}")
|
||||
|
||||
return agent_worker
|
||||
|
||||
|
||||
async def main():
|
||||
"""Main entry point for the worker process."""
|
||||
logger.debug("Starting Durable Task Agent Worker...")
|
||||
|
||||
# Create a worker using the helper function
|
||||
worker = get_worker()
|
||||
|
||||
# Setup worker with agents
|
||||
setup_worker(worker)
|
||||
|
||||
logger.info("Worker is ready and listening for requests...")
|
||||
logger.info("Press Ctrl+C to stop.")
|
||||
logger.info("")
|
||||
@@ -80,9 +112,9 @@ async def main():
|
||||
while True:
|
||||
await asyncio.sleep(1)
|
||||
except KeyboardInterrupt:
|
||||
logger.info("Worker shutdown initiated")
|
||||
logger.debug("Worker shutdown initiated")
|
||||
|
||||
logger.info("Worker stopped")
|
||||
logger.debug("Worker stopped")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
# Multi-Agent
|
||||
|
||||
This sample demonstrates how to host multiple AI agents with different tools in a single worker-client setup using the Durable Task Scheduler.
|
||||
|
||||
## Key Concepts Demonstrated
|
||||
|
||||
- Hosting multiple agents (WeatherAgent and MathAgent) in a single worker process.
|
||||
- Each agent with its own specialized tools and instructions.
|
||||
- Interacting with different agents using separate conversation threads.
|
||||
- Worker-client architecture for multi-agent systems.
|
||||
|
||||
## Environment Setup
|
||||
|
||||
See the [README.md](../README.md) file in the parent directory for more information on how to configure the environment, including how to install and run common sample dependencies.
|
||||
|
||||
## Running the Sample
|
||||
|
||||
With the environment setup, you can run the sample using the combined approach or separate worker and client processes:
|
||||
|
||||
**Option 1: Combined (Recommended for Testing)**
|
||||
|
||||
```bash
|
||||
cd samples/getting_started/durabletask/02_multi_agent
|
||||
python sample.py
|
||||
```
|
||||
|
||||
**Option 2: Separate Processes**
|
||||
|
||||
Start the worker in one terminal:
|
||||
|
||||
```bash
|
||||
python worker.py
|
||||
```
|
||||
|
||||
In a new terminal, run the client:
|
||||
|
||||
```bash
|
||||
python client.py
|
||||
```
|
||||
|
||||
The client will interact with both agents:
|
||||
|
||||
```
|
||||
Starting Durable Task Multi-Agent Client...
|
||||
Using taskhub: default
|
||||
Using endpoint: http://localhost:8080
|
||||
|
||||
================================================================================
|
||||
Testing WeatherAgent
|
||||
================================================================================
|
||||
|
||||
Created weather conversation thread: <guid>
|
||||
User: What is the weather in Seattle?
|
||||
|
||||
🔧 [TOOL CALLED] get_weather(location=Seattle)
|
||||
✓ [TOOL RESULT] {'location': 'Seattle', 'temperature': 72, 'conditions': 'Sunny', 'humidity': 45}
|
||||
|
||||
WeatherAgent: The current weather in Seattle is sunny with a temperature of 72°F and 45% humidity.
|
||||
|
||||
================================================================================
|
||||
Testing MathAgent
|
||||
================================================================================
|
||||
|
||||
Created math conversation thread: <guid>
|
||||
User: Calculate a 20% tip on a $50 bill
|
||||
|
||||
🔧 [TOOL CALLED] calculate_tip(bill_amount=50.0, tip_percentage=20.0)
|
||||
✓ [TOOL RESULT] {'bill_amount': 50.0, 'tip_percentage': 20.0, 'tip_amount': 10.0, 'total': 60.0}
|
||||
|
||||
MathAgent: For a $50 bill with a 20% tip, the tip amount is $10.00 and the total is $60.00.
|
||||
```
|
||||
|
||||
## Viewing Agent State
|
||||
|
||||
You can view the state of both agents in the Durable Task Scheduler dashboard:
|
||||
|
||||
1. Open your browser and navigate to `http://localhost:8082`
|
||||
2. In the dashboard, you can view:
|
||||
- The state of both WeatherAgent and MathAgent entities (dafx-WeatherAgent, dafx-MathAgent)
|
||||
- Each agent's conversation state across multiple interactions
|
||||
@@ -0,0 +1,116 @@
|
||||
"""Client application for interacting with multiple hosted agents.
|
||||
|
||||
This client connects to the Durable Task Scheduler and interacts with two different
|
||||
agents (WeatherAgent and MathAgent), demonstrating how to work with multiple agents
|
||||
each with their own specialized capabilities and tools.
|
||||
|
||||
Prerequisites:
|
||||
- The worker must be running with both agents registered
|
||||
- Set AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_CHAT_DEPLOYMENT_NAME
|
||||
(plus AZURE_OPENAI_API_KEY or Azure CLI authentication)
|
||||
- Durable Task Scheduler must be running
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
|
||||
from agent_framework_durabletask import DurableAIAgentClient
|
||||
from azure.identity import DefaultAzureCredential
|
||||
from durabletask.azuremanaged.client import DurableTaskSchedulerClient
|
||||
|
||||
# Configure logging
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def get_client(
|
||||
taskhub: str | None = None,
|
||||
endpoint: str | None = None,
|
||||
log_handler: logging.Handler | None = None
|
||||
) -> DurableAIAgentClient:
|
||||
"""Create a configured DurableAIAgentClient.
|
||||
|
||||
Args:
|
||||
taskhub: Task hub name (defaults to TASKHUB env var or "default")
|
||||
endpoint: Scheduler endpoint (defaults to ENDPOINT env var or "http://localhost:8080")
|
||||
log_handler: Optional logging handler for client logging
|
||||
|
||||
Returns:
|
||||
Configured DurableAIAgentClient instance
|
||||
"""
|
||||
taskhub_name = taskhub or os.getenv("TASKHUB", "default")
|
||||
endpoint_url = endpoint or os.getenv("ENDPOINT", "http://localhost:8080")
|
||||
|
||||
logger.debug(f"Using taskhub: {taskhub_name}")
|
||||
logger.debug(f"Using endpoint: {endpoint_url}")
|
||||
|
||||
credential = None if endpoint_url == "http://localhost:8080" else DefaultAzureCredential()
|
||||
|
||||
dts_client = DurableTaskSchedulerClient(
|
||||
host_address=endpoint_url,
|
||||
secure_channel=endpoint_url != "http://localhost:8080",
|
||||
taskhub=taskhub_name,
|
||||
token_credential=credential,
|
||||
log_handler=log_handler
|
||||
)
|
||||
|
||||
return DurableAIAgentClient(dts_client)
|
||||
|
||||
|
||||
def run_client(agent_client: DurableAIAgentClient) -> None:
|
||||
"""Run client interactions with both WeatherAgent and MathAgent.
|
||||
|
||||
Args:
|
||||
agent_client: The DurableAIAgentClient instance
|
||||
"""
|
||||
logger.debug("Testing WeatherAgent")
|
||||
|
||||
# Get reference to WeatherAgent
|
||||
weather_agent = agent_client.get_agent("WeatherAgent")
|
||||
weather_thread = weather_agent.get_new_thread()
|
||||
|
||||
logger.debug(f"Created weather conversation thread: {weather_thread.session_id}")
|
||||
|
||||
# Test WeatherAgent
|
||||
weather_message = "What is the weather in Seattle?"
|
||||
logger.info(f"User: {weather_message}")
|
||||
|
||||
weather_response = weather_agent.run(weather_message, thread=weather_thread)
|
||||
logger.info(f"WeatherAgent: {weather_response.text} \n")
|
||||
|
||||
logger.debug("Testing MathAgent")
|
||||
|
||||
# Get reference to MathAgent
|
||||
math_agent = agent_client.get_agent("MathAgent")
|
||||
math_thread = math_agent.get_new_thread()
|
||||
|
||||
logger.debug(f"Created math conversation thread: {math_thread.session_id}")
|
||||
|
||||
# Test MathAgent
|
||||
math_message = "Calculate a 20% tip on a $50 bill"
|
||||
logger.info(f"User: {math_message}")
|
||||
|
||||
math_response = math_agent.run(math_message, thread=math_thread)
|
||||
logger.info(f"MathAgent: {math_response.text} \n")
|
||||
|
||||
logger.debug("Both agents completed successfully!")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
"""Main entry point for the client application."""
|
||||
logger.debug("Starting Durable Task Multi-Agent Client...")
|
||||
|
||||
# Create client using helper function
|
||||
agent_client = get_client()
|
||||
|
||||
try:
|
||||
run_client(agent_client)
|
||||
except Exception as e:
|
||||
logger.exception(f"Error during agent interaction: {e}")
|
||||
finally:
|
||||
logger.debug("Client shutting down")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,6 @@
|
||||
# Agent Framework packages (installing from local package until a package is published)
|
||||
-e ../../../../
|
||||
-e ../../../../packages/durabletask
|
||||
|
||||
# Azure authentication
|
||||
azure-identity
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Multi-Agent Sample - Durable Task Integration (Combined Worker + Client)
|
||||
|
||||
This sample demonstrates running both the worker and client in a single process
|
||||
for multiple agents with different tools. The worker registers two agents
|
||||
(WeatherAgent and MathAgent), each with their own specialized capabilities.
|
||||
|
||||
Prerequisites:
|
||||
- Set AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_CHAT_DEPLOYMENT_NAME
|
||||
(plus AZURE_OPENAI_API_KEY or Azure CLI authentication)
|
||||
- Durable Task Scheduler must be running (e.g., using Docker)
|
||||
|
||||
To run this sample:
|
||||
python sample.py
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Import helper functions from worker and client modules
|
||||
from client import get_client, run_client
|
||||
from worker import get_worker, setup_worker
|
||||
|
||||
# Configure logging
|
||||
logging.basicConfig(level=logging.INFO, force=True)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def main():
|
||||
"""Main entry point - runs both worker and client in single process."""
|
||||
logger.debug("Starting Durable Task Multi-Agent Sample (Combined Worker + Client)...")
|
||||
|
||||
silent_handler = logging.NullHandler()
|
||||
# Create and start the worker using helper function and context manager
|
||||
with get_worker(log_handler=silent_handler) as dts_worker:
|
||||
# Register agents using helper function
|
||||
setup_worker(dts_worker)
|
||||
|
||||
# Start the worker
|
||||
dts_worker.start()
|
||||
logger.debug("Worker started and listening for requests...")
|
||||
|
||||
# Create the client using helper function
|
||||
agent_client = get_client(log_handler=silent_handler)
|
||||
|
||||
try:
|
||||
# Run client interactions using helper function
|
||||
run_client(agent_client)
|
||||
except Exception as e:
|
||||
logger.exception(f"Error during agent interaction: {e}")
|
||||
|
||||
logger.debug("Sample completed. Worker shutting down...")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
load_dotenv()
|
||||
main()
|
||||
@@ -0,0 +1,172 @@
|
||||
"""Worker process for hosting multiple agents with different tools using Durable Task.
|
||||
|
||||
This worker registers two agents - a weather assistant and a math assistant - each
|
||||
with their own specialized tools. This demonstrates how to host multiple agents
|
||||
with different capabilities in a single worker process.
|
||||
|
||||
Prerequisites:
|
||||
- Set AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_CHAT_DEPLOYMENT_NAME
|
||||
(plus AZURE_OPENAI_API_KEY or Azure CLI authentication)
|
||||
- Start a Durable Task Scheduler (e.g., using Docker)
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
from typing import Any
|
||||
|
||||
from agent_framework.azure import AzureOpenAIChatClient
|
||||
from agent_framework_durabletask import DurableAIAgentWorker
|
||||
from azure.identity import AzureCliCredential, DefaultAzureCredential
|
||||
from durabletask.azuremanaged.worker import DurableTaskSchedulerWorker
|
||||
|
||||
# Configure logging
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Agent names
|
||||
WEATHER_AGENT_NAME = "WeatherAgent"
|
||||
MATH_AGENT_NAME = "MathAgent"
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
def create_weather_agent():
|
||||
"""Create the Weather agent using Azure OpenAI.
|
||||
|
||||
Returns:
|
||||
AgentProtocol: The configured Weather agent with weather tool
|
||||
"""
|
||||
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
|
||||
name=WEATHER_AGENT_NAME,
|
||||
instructions="You are a helpful weather assistant. Provide current weather information.",
|
||||
tools=[get_weather],
|
||||
)
|
||||
|
||||
|
||||
def create_math_agent():
|
||||
"""Create the Math agent using Azure OpenAI.
|
||||
|
||||
Returns:
|
||||
AgentProtocol: The configured Math agent with calculation tools
|
||||
"""
|
||||
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
|
||||
name=MATH_AGENT_NAME,
|
||||
instructions="You are a helpful math assistant. Help users with calculations like tip calculations.",
|
||||
tools=[calculate_tip],
|
||||
)
|
||||
|
||||
|
||||
def get_worker(
|
||||
taskhub: str | None = None,
|
||||
endpoint: str | None = None,
|
||||
log_handler: logging.Handler | None = None
|
||||
) -> DurableTaskSchedulerWorker:
|
||||
"""Create a configured DurableTaskSchedulerWorker.
|
||||
|
||||
Args:
|
||||
taskhub: Task hub name (defaults to TASKHUB env var or "default")
|
||||
endpoint: Scheduler endpoint (defaults to ENDPOINT env var or "http://localhost:8080")
|
||||
log_handler: Optional logging handler for worker logging
|
||||
|
||||
Returns:
|
||||
Configured DurableTaskSchedulerWorker instance
|
||||
"""
|
||||
taskhub_name = taskhub or os.getenv("TASKHUB", "default")
|
||||
endpoint_url = endpoint or os.getenv("ENDPOINT", "http://localhost:8080")
|
||||
|
||||
logger.debug(f"Using taskhub: {taskhub_name}")
|
||||
logger.debug(f"Using endpoint: {endpoint_url}")
|
||||
|
||||
credential = None if endpoint_url == "http://localhost:8080" else DefaultAzureCredential()
|
||||
|
||||
return DurableTaskSchedulerWorker(
|
||||
host_address=endpoint_url,
|
||||
secure_channel=endpoint_url != "http://localhost:8080",
|
||||
taskhub=taskhub_name,
|
||||
token_credential=credential,
|
||||
log_handler=log_handler
|
||||
)
|
||||
|
||||
|
||||
def setup_worker(worker: DurableTaskSchedulerWorker) -> DurableAIAgentWorker:
|
||||
"""Set up the worker with multiple agents registered.
|
||||
|
||||
Args:
|
||||
worker: The DurableTaskSchedulerWorker instance
|
||||
|
||||
Returns:
|
||||
DurableAIAgentWorker with agents registered
|
||||
"""
|
||||
# Wrap it with the agent worker
|
||||
agent_worker = DurableAIAgentWorker(worker)
|
||||
|
||||
# Create and register both agents
|
||||
logger.debug("Creating and registering agents...")
|
||||
weather_agent = create_weather_agent()
|
||||
math_agent = create_math_agent()
|
||||
|
||||
agent_worker.add_agent(weather_agent)
|
||||
agent_worker.add_agent(math_agent)
|
||||
|
||||
logger.debug(f"✓ Registered agents: {weather_agent.name}, {math_agent.name}")
|
||||
|
||||
return agent_worker
|
||||
|
||||
|
||||
async def main():
|
||||
"""Main entry point for the worker process."""
|
||||
logger.debug("Starting Durable Task Multi-Agent Worker...")
|
||||
|
||||
# Create a worker using the helper function
|
||||
worker = get_worker()
|
||||
|
||||
# Setup worker with agents
|
||||
setup_worker(worker)
|
||||
|
||||
logger.info("Worker is ready and listening for requests...")
|
||||
logger.info("Press Ctrl+C to stop. \n")
|
||||
|
||||
try:
|
||||
# Start the worker (this blocks until stopped)
|
||||
worker.start()
|
||||
|
||||
# Keep the worker running
|
||||
while True:
|
||||
await asyncio.sleep(1)
|
||||
except KeyboardInterrupt:
|
||||
logger.debug("Worker shutdown initiated")
|
||||
|
||||
logger.info("Worker stopped")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,150 @@
|
||||
# Single Agent with Reliable Streaming
|
||||
|
||||
This sample demonstrates how to use Redis Streams with agent response callbacks to enable reliable, resumable streaming for durable agents. Streaming responses are persisted to Redis, allowing clients to disconnect and reconnect without losing messages.
|
||||
|
||||
## Key Concepts Demonstrated
|
||||
|
||||
- Using `AgentResponseCallbackProtocol` to capture streaming agent responses.
|
||||
- Persisting streaming chunks to Redis Streams for reliable delivery.
|
||||
- Non-blocking agent execution with `wait_for_response=False` (fire-and-forget mode).
|
||||
- Cursor-based resumption for disconnected clients.
|
||||
- Decoupling agent execution from response streaming.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
In addition to the common setup in the parent [README.md](../README.md), this sample requires Redis:
|
||||
|
||||
```bash
|
||||
docker run -d --name redis -p 6379:6379 redis:latest
|
||||
```
|
||||
|
||||
## Environment Setup
|
||||
|
||||
See the [README.md](../README.md) file in the parent directory for more information on how to configure the environment, including how to install and run common sample dependencies.
|
||||
|
||||
Additional environment variables for this sample:
|
||||
|
||||
```bash
|
||||
# Optional: Redis Configuration
|
||||
REDIS_CONNECTION_STRING=redis://localhost:6379
|
||||
REDIS_STREAM_TTL_MINUTES=10
|
||||
```
|
||||
|
||||
## Running the Sample
|
||||
|
||||
With the environment setup, you can run the sample using the combined approach or separate worker and client processes:
|
||||
|
||||
**Option 1: Combined (Recommended for Testing)**
|
||||
|
||||
```bash
|
||||
cd samples/getting_started/durabletask/03_single_agent_streaming
|
||||
python sample.py
|
||||
```
|
||||
|
||||
**Option 2: Separate Processes**
|
||||
|
||||
Start the worker in one terminal:
|
||||
|
||||
```bash
|
||||
python worker.py
|
||||
```
|
||||
|
||||
In a new terminal, run the client:
|
||||
|
||||
```bash
|
||||
python client.py
|
||||
```
|
||||
|
||||
The client will send a travel planning request to the TravelPlanner agent and stream the response from Redis in real-time:
|
||||
|
||||
```
|
||||
================================================================================
|
||||
TravelPlanner Agent - Redis Streaming Demo
|
||||
================================================================================
|
||||
|
||||
You: Plan a 3-day trip to Tokyo with emphasis on culture and food
|
||||
|
||||
TravelPlanner (streaming from Redis):
|
||||
--------------------------------------------------------------------------------
|
||||
# Your Amazing 3-Day Tokyo Adventure! 🗾
|
||||
|
||||
Let me create the perfect cultural and culinary journey through Tokyo...
|
||||
|
||||
## Day 1: Traditional Tokyo & First Impressions
|
||||
...
|
||||
(continues streaming)
|
||||
...
|
||||
|
||||
✓ Response complete!
|
||||
```
|
||||
|
||||
|
||||
## How It Works
|
||||
|
||||
### Redis Streaming Callback
|
||||
|
||||
The `RedisStreamCallback` class implements `AgentResponseCallbackProtocol` to capture streaming updates and persist them to Redis:
|
||||
|
||||
```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)
|
||||
```
|
||||
|
||||
### Worker Registration
|
||||
|
||||
The worker registers the agent with the Redis streaming callback:
|
||||
|
||||
```python
|
||||
redis_callback = RedisStreamCallback()
|
||||
agent_worker = DurableAIAgentWorker(worker, callback=redis_callback)
|
||||
agent_worker.add_agent(create_travel_agent())
|
||||
```
|
||||
|
||||
### Client Streaming
|
||||
|
||||
The client uses fire-and-forget mode to start the agent and streams from Redis:
|
||||
|
||||
```python
|
||||
# Start agent run with wait_for_response=False for non-blocking execution
|
||||
travel_planner.run(user_message, thread=thread, wait_for_response=False)
|
||||
|
||||
# Stream response from Redis while the agent is processing
|
||||
async with await get_stream_handler() as stream_handler:
|
||||
async for chunk in stream_handler.read_stream(thread_id):
|
||||
if chunk.text:
|
||||
print(chunk.text, end="", flush=True)
|
||||
elif chunk.is_done:
|
||||
break
|
||||
```
|
||||
|
||||
**Fire-and-Forget Mode**: The `wait_for_response=False` parameter enables non-blocking execution. The `run()` method signals the agent and returns immediately, allowing the client to stream from Redis without blocking.
|
||||
|
||||
### Cursor-Based Resumption
|
||||
|
||||
Clients can resume streaming from any point after disconnection:
|
||||
|
||||
```python
|
||||
cursor = "1734649123456-0" # Entry ID from previous stream
|
||||
async with await get_stream_handler() as stream_handler:
|
||||
async for chunk in stream_handler.read_stream(thread_id, cursor=cursor):
|
||||
# Process chunk
|
||||
```
|
||||
|
||||
## Viewing Agent State
|
||||
|
||||
You can view the state of the TravelPlanner agent in the Durable Task Scheduler dashboard:
|
||||
|
||||
1. Open your browser and navigate to `http://localhost:8082`
|
||||
2. In the dashboard, you can view:
|
||||
- The state of the TravelPlanner agent entity (dafx-TravelPlanner)
|
||||
- Conversation history and current state
|
||||
- How the durable agents extension manages conversation context with streaming
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
"""Client application for interacting with the TravelPlanner agent and streaming from Redis.
|
||||
|
||||
This client demonstrates:
|
||||
1. Sending a travel planning request to the durable agent
|
||||
2. Streaming the response from Redis in real-time
|
||||
3. Handling reconnection and cursor-based resumption
|
||||
|
||||
Prerequisites:
|
||||
- The worker must be running with the TravelPlanner agent registered
|
||||
- Set AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_CHAT_DEPLOYMENT_NAME
|
||||
- Redis must be running
|
||||
- Durable Task Scheduler must be running
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
from datetime import timedelta
|
||||
|
||||
import redis.asyncio as aioredis
|
||||
from agent_framework_durabletask import DurableAIAgentClient
|
||||
from azure.identity import DefaultAzureCredential
|
||||
from durabletask.azuremanaged.client import DurableTaskSchedulerClient
|
||||
|
||||
from redis_stream_response_handler import RedisStreamResponseHandler
|
||||
|
||||
# Configure logging
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
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 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( # type: ignore[reportUnknownMemberType]
|
||||
REDIS_CONNECTION_STRING,
|
||||
encoding="utf-8",
|
||||
decode_responses=False,
|
||||
)
|
||||
|
||||
return RedisStreamResponseHandler(
|
||||
redis_client=redis_client,
|
||||
stream_ttl=timedelta(minutes=REDIS_STREAM_TTL_MINUTES),
|
||||
)
|
||||
|
||||
|
||||
def get_client(
|
||||
taskhub: str | None = None,
|
||||
endpoint: str | None = None,
|
||||
log_handler: logging.Handler | None = None
|
||||
) -> DurableAIAgentClient:
|
||||
"""Create a configured DurableAIAgentClient.
|
||||
|
||||
Args:
|
||||
taskhub: Task hub name (defaults to TASKHUB env var or "default")
|
||||
endpoint: Scheduler endpoint (defaults to ENDPOINT env var or "http://localhost:8080")
|
||||
log_handler: Optional log handler for client logging
|
||||
|
||||
Returns:
|
||||
Configured DurableAIAgentClient instance
|
||||
"""
|
||||
taskhub_name = taskhub or os.getenv("TASKHUB", "default")
|
||||
endpoint_url = endpoint or os.getenv("ENDPOINT", "http://localhost:8080")
|
||||
|
||||
logger.debug(f"Using taskhub: {taskhub_name}")
|
||||
logger.debug(f"Using endpoint: {endpoint_url}")
|
||||
|
||||
credential = None if endpoint_url == "http://localhost:8080" else DefaultAzureCredential()
|
||||
|
||||
dts_client = DurableTaskSchedulerClient(
|
||||
host_address=endpoint_url,
|
||||
secure_channel=endpoint_url != "http://localhost:8080",
|
||||
taskhub=taskhub_name,
|
||||
token_credential=credential,
|
||||
log_handler=log_handler
|
||||
)
|
||||
|
||||
return DurableAIAgentClient(dts_client)
|
||||
|
||||
|
||||
async def stream_from_redis(thread_id: str, cursor: str | None = None) -> None:
|
||||
"""Stream agent responses from Redis.
|
||||
|
||||
Args:
|
||||
thread_id: The conversation/thread ID to stream from
|
||||
cursor: Optional cursor to resume from. If None, starts from beginning.
|
||||
"""
|
||||
stream_key = f"agent-stream:{thread_id}"
|
||||
logger.info(f"Streaming response from Redis (thread: {thread_id[:8]}...)")
|
||||
logger.debug(f"To manually check Redis, run: redis-cli XLEN {stream_key}")
|
||||
if cursor:
|
||||
logger.info(f"Resuming from cursor: {cursor}")
|
||||
|
||||
async with await get_stream_handler() as stream_handler:
|
||||
logger.info(f"Stream handler created, starting to read...")
|
||||
try:
|
||||
chunk_count = 0
|
||||
async for chunk in stream_handler.read_stream(thread_id, cursor):
|
||||
chunk_count += 1
|
||||
logger.debug(f"Received chunk #{chunk_count}: error={chunk.error}, is_done={chunk.is_done}, text_len={len(chunk.text) if chunk.text else 0}")
|
||||
|
||||
if chunk.error:
|
||||
logger.error(f"Stream error: {chunk.error}")
|
||||
break
|
||||
|
||||
if chunk.is_done:
|
||||
print("\n✓ Response complete!", flush=True)
|
||||
logger.info(f"Stream completed after {chunk_count} chunks")
|
||||
break
|
||||
|
||||
if chunk.text:
|
||||
# Print directly to console with flush for immediate display
|
||||
print(chunk.text, end='', flush=True)
|
||||
|
||||
if chunk_count == 0:
|
||||
logger.warning("No chunks received from Redis stream!")
|
||||
logger.warning(f"Check Redis manually: redis-cli XLEN {stream_key}")
|
||||
logger.warning(f"View stream contents: redis-cli XREAD STREAMS {stream_key} 0")
|
||||
|
||||
except Exception as ex:
|
||||
logger.error(f"Error reading from Redis: {ex}", exc_info=True)
|
||||
|
||||
|
||||
def run_client(agent_client: DurableAIAgentClient) -> None:
|
||||
"""Run client interactions with the TravelPlanner agent.
|
||||
|
||||
Args:
|
||||
agent_client: The DurableAIAgentClient instance
|
||||
"""
|
||||
# Get a reference to the TravelPlanner agent
|
||||
logger.debug("Getting reference to TravelPlanner agent...")
|
||||
travel_planner = agent_client.get_agent("TravelPlanner")
|
||||
|
||||
# Create a new thread for the conversation
|
||||
thread = travel_planner.get_new_thread()
|
||||
if not thread.session_id:
|
||||
logger.error("Failed to create a new thread with session ID!")
|
||||
return
|
||||
|
||||
key = thread.session_id.key
|
||||
logger.info(f"Thread ID: {key}")
|
||||
|
||||
# Get user input
|
||||
print("\nEnter your travel planning request:")
|
||||
user_message = input("> ").strip()
|
||||
|
||||
if not user_message:
|
||||
logger.warning("No input provided. Using default message.")
|
||||
user_message = "Plan a 3-day trip to Tokyo with emphasis on culture and food"
|
||||
|
||||
logger.info(f"\nYou: {user_message}\n")
|
||||
logger.info("TravelPlanner (streaming from Redis):")
|
||||
logger.info("-" * 80)
|
||||
|
||||
# Start the agent run with wait_for_response=False for non-blocking execution
|
||||
# This signals the agent to start processing without waiting for completion
|
||||
# The agent will execute in the background and write chunks to Redis
|
||||
travel_planner.run(user_message, thread=thread, wait_for_response=False)
|
||||
|
||||
# Stream the response from Redis
|
||||
# This demonstrates that the client can stream from Redis while
|
||||
# the agent is still processing (or after it completes)
|
||||
asyncio.run(stream_from_redis(str(key)))
|
||||
|
||||
logger.info("\nDemo completed!")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from dotenv import load_dotenv
|
||||
load_dotenv()
|
||||
|
||||
# Create the client
|
||||
client = get_client()
|
||||
|
||||
# Run the demo
|
||||
run_client(client)
|
||||
+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: type[BaseException] | None, exc_val: BaseException | None, exc_tb: object) -> None:
|
||||
"""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,9 @@
|
||||
# Agent Framework packages (installing from local package until a package is published)
|
||||
-e ../../../../
|
||||
-e ../../../../packages/durabletask
|
||||
|
||||
# Azure authentication
|
||||
azure-identity
|
||||
|
||||
# Redis client
|
||||
redis
|
||||
@@ -0,0 +1,62 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
"""Single Agent Streaming Sample - Durable Task Integration (Combined Worker + Client)
|
||||
|
||||
This sample demonstrates running both the worker and client in a single process
|
||||
with reliable Redis-based streaming for agent responses.
|
||||
|
||||
The worker is started first to register the TravelPlanner agent with Redis streaming
|
||||
callback, then client operations are performed against the running worker.
|
||||
|
||||
Prerequisites:
|
||||
- Set AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_CHAT_DEPLOYMENT_NAME
|
||||
(plus AZURE_OPENAI_API_KEY or Azure CLI authentication)
|
||||
- Durable Task Scheduler must be running (e.g., using Docker)
|
||||
- Redis must be running (e.g., docker run -d --name redis -p 6379:6379 redis:latest)
|
||||
|
||||
To run this sample:
|
||||
python sample.py
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Import helper functions from worker and client modules
|
||||
from client import get_client, run_client
|
||||
from worker import get_worker, setup_worker
|
||||
|
||||
# Configure logging (must be after imports to override their basicConfig)
|
||||
logging.basicConfig(level=logging.INFO, force=True)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def main():
|
||||
"""Main entry point - runs both worker and client in single process."""
|
||||
logger.debug("Starting Durable Task Agent Sample with Redis Streaming...")
|
||||
|
||||
silent_handler = logging.NullHandler()
|
||||
|
||||
# Create and start the worker using helper function and context manager
|
||||
with get_worker(log_handler=silent_handler) as dts_worker:
|
||||
# Register agents and callbacks using helper function
|
||||
setup_worker(dts_worker)
|
||||
|
||||
# Start the worker
|
||||
dts_worker.start()
|
||||
logger.debug("Worker started and listening for requests...")
|
||||
|
||||
# Create the client using helper function
|
||||
agent_client = get_client(log_handler=silent_handler)
|
||||
|
||||
try:
|
||||
# Run client interactions using helper function
|
||||
run_client(agent_client)
|
||||
except Exception as e:
|
||||
logger.exception(f"Error during agent interaction: {e}")
|
||||
|
||||
logger.debug("Sample completed. Worker shutting down...")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
load_dotenv()
|
||||
main()
|
||||
@@ -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!"
|
||||
@@ -0,0 +1,251 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
"""Worker process for hosting a TravelPlanner agent with reliable Redis streaming.
|
||||
|
||||
This worker registers the TravelPlanner agent with the Durable Task Scheduler
|
||||
and uses RedisStreamCallback to persist streaming responses to Redis for reliable delivery.
|
||||
|
||||
Prerequisites:
|
||||
- Set AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_CHAT_DEPLOYMENT_NAME
|
||||
(plus AZURE_OPENAI_API_KEY or Azure CLI authentication)
|
||||
- Start a Durable Task Scheduler (e.g., using Docker)
|
||||
- Start Redis (e.g., docker run -d --name redis -p 6379:6379 redis:latest)
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
from datetime import timedelta
|
||||
|
||||
import redis.asyncio as aioredis
|
||||
from agent_framework import AgentRunResponseUpdate
|
||||
from agent_framework.azure import AzureOpenAIChatClient
|
||||
from agent_framework_durabletask import AgentCallbackContext, AgentResponseCallbackProtocol, DurableAIAgentWorker
|
||||
from azure.identity import AzureCliCredential, DefaultAzureCredential
|
||||
from durabletask.azuremanaged.worker import DurableTaskSchedulerWorker
|
||||
|
||||
from redis_stream_response_handler import RedisStreamResponseHandler
|
||||
from tools import get_local_events, get_weather_forecast
|
||||
|
||||
# Configure logging
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
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 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( # type: ignore[reportUnknownMemberType]
|
||||
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._sequence_numbers: dict[str, int] = {} # Track sequence per thread
|
||||
|
||||
async def on_streaming_response_update(
|
||||
self,
|
||||
update: AgentRunResponseUpdate,
|
||||
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:
|
||||
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
|
||||
|
||||
logger.debug(
|
||||
"[%s][%s] Wrote chunk to Redis: seq=%d, text=%s",
|
||||
context.agent_name,
|
||||
thread_id[:8],
|
||||
sequence,
|
||||
text,
|
||||
)
|
||||
except Exception as ex:
|
||||
logger.error(f"Error writing to Redis stream: {ex}", exc_info=True)
|
||||
|
||||
async def on_agent_response(self, response: object, 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)
|
||||
|
||||
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:
|
||||
logger.error(f"Error writing end-of-stream marker: {ex}", exc_info=True)
|
||||
|
||||
|
||||
def create_travel_agent():
|
||||
"""Create the TravelPlanner agent using Azure OpenAI.
|
||||
|
||||
Returns:
|
||||
AgentProtocol: The configured TravelPlanner agent with travel planning tools.
|
||||
"""
|
||||
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_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],
|
||||
)
|
||||
|
||||
|
||||
def get_worker(
|
||||
taskhub: str | None = None,
|
||||
endpoint: str | None = None,
|
||||
log_handler: logging.Handler | None = None
|
||||
) -> DurableTaskSchedulerWorker:
|
||||
"""Create a configured DurableTaskSchedulerWorker.
|
||||
|
||||
Args:
|
||||
taskhub: Task hub name (defaults to TASKHUB env var or "default")
|
||||
endpoint: Scheduler endpoint (defaults to ENDPOINT env var or "http://localhost:8080")
|
||||
log_handler: Optional log handler for worker logging
|
||||
|
||||
Returns:
|
||||
Configured DurableTaskSchedulerWorker instance
|
||||
"""
|
||||
taskhub_name = taskhub or os.getenv("TASKHUB", "default")
|
||||
endpoint_url = endpoint or os.getenv("ENDPOINT", "http://localhost:8080")
|
||||
|
||||
logger.debug(f"Using taskhub: {taskhub_name}")
|
||||
logger.debug(f"Using endpoint: {endpoint_url}")
|
||||
|
||||
credential = None if endpoint_url == "http://localhost:8080" else DefaultAzureCredential()
|
||||
|
||||
return DurableTaskSchedulerWorker(
|
||||
host_address=endpoint_url,
|
||||
secure_channel=endpoint_url != "http://localhost:8080",
|
||||
taskhub=taskhub_name,
|
||||
token_credential=credential,
|
||||
log_handler=log_handler
|
||||
)
|
||||
|
||||
|
||||
def setup_worker(worker: DurableTaskSchedulerWorker) -> DurableAIAgentWorker:
|
||||
"""Set up the worker with the TravelPlanner agent and Redis streaming callback.
|
||||
|
||||
Args:
|
||||
worker: The DurableTaskSchedulerWorker instance
|
||||
|
||||
Returns:
|
||||
DurableAIAgentWorker with agent and callback registered
|
||||
"""
|
||||
# Create the Redis streaming callback
|
||||
redis_callback = RedisStreamCallback()
|
||||
|
||||
# Wrap it with the agent worker
|
||||
agent_worker = DurableAIAgentWorker(worker, callback=redis_callback)
|
||||
|
||||
# Create and register the TravelPlanner agent
|
||||
logger.debug("Creating and registering TravelPlanner agent...")
|
||||
travel_agent = create_travel_agent()
|
||||
agent_worker.add_agent(travel_agent)
|
||||
|
||||
logger.debug(f"✓ Registered agent: {travel_agent.name}")
|
||||
|
||||
return agent_worker
|
||||
|
||||
|
||||
async def main():
|
||||
"""Main entry point for the worker process."""
|
||||
logger.debug("Starting Durable Task Agent Worker with Redis Streaming...")
|
||||
|
||||
# Create a worker using the helper function
|
||||
worker = get_worker()
|
||||
|
||||
# Setup worker with agent and callback
|
||||
setup_worker(worker)
|
||||
|
||||
# Start the worker
|
||||
logger.debug("Worker started and listening for requests...")
|
||||
worker.start()
|
||||
|
||||
try:
|
||||
# Keep the worker running
|
||||
while True:
|
||||
await asyncio.sleep(1)
|
||||
except KeyboardInterrupt:
|
||||
logger.debug("Worker shutting down...")
|
||||
finally:
|
||||
worker.stop()
|
||||
logger.debug("Worker stopped")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
+8
-12
@@ -1,4 +1,4 @@
|
||||
# Single Agent Orchestration Chaining Sample
|
||||
# Single Agent Orchestration Chaining
|
||||
|
||||
This sample demonstrates how to chain multiple invocations of the same agent using a durable orchestration while preserving conversation state between runs.
|
||||
|
||||
@@ -15,32 +15,30 @@ See the [README.md](../README.md) file in the parent directory for more informat
|
||||
|
||||
## Running the Sample
|
||||
|
||||
With the environment setup, you can run the sample using one of two approaches:
|
||||
With the environment setup, you can run the sample using the combined approach or separate worker and client processes:
|
||||
|
||||
### Option 1: Combined Worker + Client (Quick Start)
|
||||
**Option 1: Combined (Recommended for Testing)**
|
||||
|
||||
```bash
|
||||
cd samples/getting_started/durabletask/04_single_agent_orchestration_chaining
|
||||
python sample.py
|
||||
```
|
||||
|
||||
This runs both worker and client in a single process.
|
||||
**Option 2: Separate Processes**
|
||||
|
||||
### Option 2: Separate Worker and Client
|
||||
|
||||
**Start the worker in one terminal:**
|
||||
Start the worker in one terminal:
|
||||
|
||||
```bash
|
||||
python worker.py
|
||||
```
|
||||
|
||||
**In a new terminal, run the client:**
|
||||
In a new terminal, run the client:
|
||||
|
||||
```bash
|
||||
python client.py
|
||||
```
|
||||
|
||||
The orchestration will execute the writer agent twice sequentially, and you'll see output like:
|
||||
The orchestration will execute the writer agent twice sequentially:
|
||||
|
||||
```
|
||||
[Orchestration] Starting single agent chaining...
|
||||
@@ -62,11 +60,9 @@ Each small step forward brings you closer to mastery and growth.
|
||||
You can view the state of the orchestration in the Durable Task Scheduler dashboard:
|
||||
|
||||
1. Open your browser and navigate to `http://localhost:8082`
|
||||
2. In the dashboard, you can view the orchestration instance, including:
|
||||
2. In the dashboard, you can view:
|
||||
- The sequential execution of both agent runs
|
||||
- The conversation thread shared between runs
|
||||
- Input and output at each step
|
||||
- Overall orchestration state and history
|
||||
|
||||
The orchestration maintains the conversation context across both agent invocations, demonstrating how durable orchestrations can coordinate multi-step agent workflows.
|
||||
|
||||
|
||||
+77
-64
@@ -24,80 +24,93 @@ logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
"""Main entry point for the client application."""
|
||||
logger.info("Starting Durable Task Single Agent Chaining Orchestration Client...")
|
||||
def get_client(
|
||||
taskhub: str | None = None,
|
||||
endpoint: str | None = None,
|
||||
log_handler: logging.Handler | None = None
|
||||
) -> DurableTaskSchedulerClient:
|
||||
"""Create a configured DurableTaskSchedulerClient.
|
||||
|
||||
# Get environment variables for taskhub and endpoint with defaults
|
||||
taskhub_name = os.getenv("TASKHUB", "default")
|
||||
endpoint = os.getenv("ENDPOINT", "http://localhost:8080")
|
||||
|
||||
logger.info(f"Using taskhub: {taskhub_name}")
|
||||
logger.info(f"Using endpoint: {endpoint}")
|
||||
logger.info("")
|
||||
|
||||
# Set credential to None for emulator, or DefaultAzureCredential for Azure
|
||||
credential = None if endpoint == "http://localhost:8080" else DefaultAzureCredential()
|
||||
Args:
|
||||
taskhub: Task hub name (defaults to TASKHUB env var or "default")
|
||||
endpoint: Scheduler endpoint (defaults to ENDPOINT env var or "http://localhost:8080")
|
||||
log_handler: Optional logging handler for client logging
|
||||
|
||||
Returns:
|
||||
Configured DurableTaskSchedulerClient instance
|
||||
"""
|
||||
taskhub_name = taskhub or os.getenv("TASKHUB", "default")
|
||||
endpoint_url = endpoint or os.getenv("ENDPOINT", "http://localhost:8080")
|
||||
|
||||
# Create a client using Azure Managed Durable Task
|
||||
client = DurableTaskSchedulerClient(
|
||||
host_address=endpoint,
|
||||
secure_channel=endpoint != "http://localhost:8080",
|
||||
logger.debug(f"Using taskhub: {taskhub_name}")
|
||||
logger.debug(f"Using endpoint: {endpoint_url}")
|
||||
|
||||
credential = None if endpoint_url == "http://localhost:8080" else DefaultAzureCredential()
|
||||
|
||||
return DurableTaskSchedulerClient(
|
||||
host_address=endpoint_url,
|
||||
secure_channel=endpoint_url != "http://localhost:8080",
|
||||
taskhub=taskhub_name,
|
||||
token_credential=credential
|
||||
token_credential=credential,
|
||||
log_handler=log_handler
|
||||
)
|
||||
|
||||
|
||||
def run_client(client: DurableTaskSchedulerClient) -> None:
|
||||
"""Run client to start and monitor the orchestration.
|
||||
|
||||
Args:
|
||||
client: The DurableTaskSchedulerClient instance
|
||||
"""
|
||||
logger.debug("Starting single agent chaining orchestration...")
|
||||
|
||||
# Start the orchestration
|
||||
instance_id = client.schedule_new_orchestration( # type: ignore
|
||||
orchestrator="single_agent_chaining_orchestration",
|
||||
input="",
|
||||
)
|
||||
|
||||
logger.info("Starting single agent chaining orchestration...")
|
||||
logger.info("")
|
||||
logger.info(f"Orchestration started with instance ID: {instance_id}")
|
||||
logger.debug("Waiting for orchestration to complete...")
|
||||
|
||||
# Retrieve the final state
|
||||
metadata = client.wait_for_orchestration_completion(
|
||||
instance_id=instance_id,
|
||||
timeout=300
|
||||
)
|
||||
|
||||
if metadata and metadata.runtime_status.name == "COMPLETED":
|
||||
result = metadata.serialized_output
|
||||
|
||||
logger.debug("Orchestration completed successfully!")
|
||||
|
||||
# Parse and display the result
|
||||
if result:
|
||||
final_text = json.loads(result)
|
||||
logger.info("Final refined sentence: %s \n", final_text)
|
||||
|
||||
elif metadata:
|
||||
logger.error(f"Orchestration ended with status: {metadata.runtime_status.name}")
|
||||
if metadata.serialized_output:
|
||||
logger.error(f"Output: {metadata.serialized_output}")
|
||||
else:
|
||||
logger.error("Orchestration did not complete within the timeout period")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
"""Main entry point for the client application."""
|
||||
logger.debug("Starting Durable Task Single Agent Chaining Orchestration Client...")
|
||||
|
||||
# Create client using helper function
|
||||
client = get_client()
|
||||
|
||||
try:
|
||||
# Start the orchestration
|
||||
instance_id = client.schedule_new_orchestration(
|
||||
orchestrator="single_agent_chaining_orchestration",
|
||||
input="",
|
||||
)
|
||||
|
||||
logger.info(f"Orchestration started with instance ID: {instance_id}")
|
||||
logger.info("Waiting for orchestration to complete...")
|
||||
logger.info("")
|
||||
|
||||
# Retrieve the final state
|
||||
metadata = client.wait_for_orchestration_completion(
|
||||
instance_id=instance_id,
|
||||
timeout=300
|
||||
)
|
||||
|
||||
if metadata and metadata.runtime_status.name == "COMPLETED":
|
||||
result = metadata.serialized_output
|
||||
|
||||
logger.info("=" * 80)
|
||||
logger.info("Orchestration completed successfully!")
|
||||
logger.info("=" * 80)
|
||||
logger.info("")
|
||||
logger.info("Results:")
|
||||
logger.info("")
|
||||
|
||||
# Parse and display the result
|
||||
if result:
|
||||
final_text = json.loads(result)
|
||||
logger.info("Final refined sentence:")
|
||||
logger.info(f" {final_text}")
|
||||
logger.info("")
|
||||
|
||||
logger.info("=" * 80)
|
||||
|
||||
elif metadata:
|
||||
logger.error(f"Orchestration ended with status: {metadata.runtime_status.name}")
|
||||
if metadata.serialized_output:
|
||||
logger.error(f"Output: {metadata.serialized_output}")
|
||||
else:
|
||||
logger.error("Orchestration did not complete within the timeout period")
|
||||
|
||||
run_client(client)
|
||||
except Exception as e:
|
||||
logger.exception(f"Error during orchestration: {e}")
|
||||
finally:
|
||||
logger.info("")
|
||||
logger.info("Client shutting down")
|
||||
logger.debug("")
|
||||
logger.debug("Client shutting down")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
+25
-210
@@ -19,235 +19,50 @@ To run this sample:
|
||||
python sample.py
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from collections.abc import Generator
|
||||
from typing import Any
|
||||
|
||||
from agent_framework import AgentRunResponse
|
||||
from agent_framework.azure import AzureOpenAIChatClient
|
||||
from agent_framework_durabletask import DurableAIAgentOrchestrationContext, DurableAIAgentWorker
|
||||
from azure.identity import AzureCliCredential, DefaultAzureCredential
|
||||
from dotenv import load_dotenv
|
||||
from durabletask.task import OrchestrationContext, Task
|
||||
from durabletask.azuremanaged.client import DurableTaskSchedulerClient
|
||||
from durabletask.azuremanaged.worker import DurableTaskSchedulerWorker
|
||||
|
||||
# Import helper functions from worker and client modules
|
||||
from client import get_client, run_client
|
||||
from worker import get_worker, setup_worker
|
||||
|
||||
# Configure logging
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logging.basicConfig(level=logging.INFO, force=True)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Agent name
|
||||
WRITER_AGENT_NAME = "WriterAgent"
|
||||
|
||||
|
||||
def create_writer_agent():
|
||||
"""Create the Writer agent using Azure OpenAI.
|
||||
|
||||
This agent refines short pieces of text, enhancing initial sentences
|
||||
and polishing improved versions further.
|
||||
|
||||
Returns:
|
||||
AgentProtocol: The configured Writer agent
|
||||
"""
|
||||
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()).create_agent(
|
||||
name=WRITER_AGENT_NAME,
|
||||
instructions=instructions,
|
||||
)
|
||||
|
||||
|
||||
def single_agent_chaining_orchestration(
|
||||
context: OrchestrationContext, _: str
|
||||
) -> Generator[Task[Any], Any, str]:
|
||||
"""Orchestration that runs the writer agent twice on the same thread.
|
||||
|
||||
This demonstrates chaining behavior where the output of the first agent run
|
||||
becomes part of the input for the second run, all while maintaining the
|
||||
conversation context through a shared thread.
|
||||
|
||||
Args:
|
||||
context: The orchestration context
|
||||
_: Input parameter (unused)
|
||||
|
||||
Returns:
|
||||
str: The final refined text from the second agent run
|
||||
"""
|
||||
logger.info("[Orchestration] Starting single agent chaining...")
|
||||
|
||||
# Wrap the orchestration context to access agents
|
||||
agent_context = DurableAIAgentOrchestrationContext(context)
|
||||
|
||||
# Get the writer agent using the agent context
|
||||
writer = agent_context.get_agent(WRITER_AGENT_NAME)
|
||||
|
||||
# Create a new thread for the conversation - this will be shared across both runs
|
||||
writer_thread = writer.get_new_thread()
|
||||
|
||||
logger.info(f"[Orchestration] Created thread: {writer_thread.session_id}")
|
||||
|
||||
# First run: Generate an initial inspirational sentence
|
||||
logger.info("[Orchestration] First agent run: Generating initial sentence...")
|
||||
initial_response: AgentRunResponse = yield writer.run(
|
||||
messages="Write a concise inspirational sentence about learning.",
|
||||
thread=writer_thread,
|
||||
)
|
||||
logger.info(f"[Orchestration] Initial response: {initial_response.text}")
|
||||
|
||||
# Second run: Refine the initial response on the same thread
|
||||
improved_prompt = (
|
||||
f"Improve this further while keeping it under 25 words: "
|
||||
f"{initial_response.text}"
|
||||
)
|
||||
|
||||
logger.info("[Orchestration] Second agent run: Refining the sentence...")
|
||||
refined_response: AgentRunResponse = yield writer.run(
|
||||
messages=improved_prompt,
|
||||
thread=writer_thread,
|
||||
)
|
||||
|
||||
logger.info(f"[Orchestration] Refined response: {refined_response.text}")
|
||||
|
||||
logger.info("[Orchestration] Chaining complete")
|
||||
return refined_response.text
|
||||
|
||||
|
||||
async def run_client(
|
||||
endpoint: str, taskhub_name: str, credential: DefaultAzureCredential | None
|
||||
):
|
||||
"""Run the client to start and monitor the orchestration.
|
||||
|
||||
Args:
|
||||
endpoint: The durable task scheduler endpoint
|
||||
taskhub_name: The task hub name
|
||||
credential: The credential for authentication
|
||||
"""
|
||||
logger.info("")
|
||||
logger.info("=" * 80)
|
||||
logger.info("CLIENT: Starting orchestration...")
|
||||
logger.info("=" * 80)
|
||||
logger.info("")
|
||||
|
||||
# Create a client
|
||||
client = DurableTaskSchedulerClient(
|
||||
host_address=endpoint,
|
||||
secure_channel=endpoint != "http://localhost:8080",
|
||||
taskhub=taskhub_name,
|
||||
token_credential=credential
|
||||
)
|
||||
|
||||
try:
|
||||
# Start the orchestration
|
||||
instance_id = client.schedule_new_orchestration(
|
||||
single_agent_chaining_orchestration
|
||||
)
|
||||
|
||||
logger.info(f"Orchestration started with instance ID: {instance_id}")
|
||||
logger.info("Waiting for orchestration to complete...")
|
||||
logger.info("")
|
||||
|
||||
# Retrieve the final state
|
||||
metadata = client.wait_for_orchestration_completion(
|
||||
instance_id=instance_id,
|
||||
timeout=300
|
||||
)
|
||||
|
||||
if metadata and metadata.runtime_status.name == "COMPLETED":
|
||||
result = metadata.serialized_output
|
||||
|
||||
logger.info("")
|
||||
logger.info("=" * 80)
|
||||
logger.info("ORCHESTRATION COMPLETED SUCCESSFULLY!")
|
||||
logger.info("=" * 80)
|
||||
logger.info("")
|
||||
|
||||
# Parse and display the result
|
||||
if result:
|
||||
final_text = json.loads(result)
|
||||
logger.info("Final refined sentence:")
|
||||
logger.info(f" {final_text}")
|
||||
else:
|
||||
logger.warning("No output returned from orchestration")
|
||||
|
||||
elif metadata:
|
||||
logger.error(f"Orchestration did not complete successfully: {metadata.runtime_status.name}")
|
||||
if metadata.serialized_output:
|
||||
logger.error(f"Output: {metadata.serialized_output}")
|
||||
else:
|
||||
logger.error("Could not retrieve orchestration metadata")
|
||||
|
||||
except Exception as e:
|
||||
logger.exception(f"Error during orchestration: {e}")
|
||||
|
||||
logger.info("")
|
||||
logger.info("Client shutting down")
|
||||
|
||||
|
||||
def main():
|
||||
"""Main entry point - runs both worker and client in single process."""
|
||||
logger.info("Starting Single Agent Orchestration Chaining Sample...")
|
||||
logger.info("")
|
||||
logger.debug("Starting Single Agent Orchestration Chaining Sample...")
|
||||
|
||||
# Load environment variables
|
||||
load_dotenv()
|
||||
|
||||
# Get environment variables for taskhub and endpoint with defaults
|
||||
taskhub_name = os.getenv("TASKHUB", "default")
|
||||
endpoint = os.getenv("ENDPOINT", "http://localhost:8080")
|
||||
|
||||
logger.info(f"Using taskhub: {taskhub_name}")
|
||||
logger.info(f"Using endpoint: {endpoint}")
|
||||
logger.info("")
|
||||
|
||||
# Set credential to None for emulator, or DefaultAzureCredential for Azure
|
||||
credential = None if endpoint == "http://localhost:8080" else DefaultAzureCredential()
|
||||
secure_channel = endpoint != "http://localhost:8080"
|
||||
|
||||
# Create and start the worker using a context manager
|
||||
with DurableTaskSchedulerWorker(
|
||||
host_address=endpoint,
|
||||
secure_channel=secure_channel,
|
||||
taskhub=taskhub_name,
|
||||
token_credential=credential
|
||||
) as worker:
|
||||
|
||||
# Wrap with the agent worker
|
||||
agent_worker = DurableAIAgentWorker(worker)
|
||||
|
||||
# Create and register the Writer agent
|
||||
logger.info("Creating and registering Writer agent...")
|
||||
writer_agent = create_writer_agent()
|
||||
agent_worker.add_agent(writer_agent)
|
||||
|
||||
logger.info(f"✓ Registered agent: {writer_agent.name}")
|
||||
logger.info(f" Entity name: dafx-{writer_agent.name}")
|
||||
|
||||
# Register the orchestration function
|
||||
logger.info("Registering orchestration function...")
|
||||
worker.add_orchestrator(single_agent_chaining_orchestration)
|
||||
logger.info("✓ Registered orchestration: single_agent_chaining_orchestration")
|
||||
logger.info("")
|
||||
silent_handler = logging.NullHandler()
|
||||
# Create and start the worker using helper function and context manager
|
||||
with get_worker(log_handler=silent_handler) as dts_worker:
|
||||
# Register agents and orchestrations using helper function
|
||||
setup_worker(dts_worker)
|
||||
|
||||
# Start the worker
|
||||
worker.start()
|
||||
logger.info("Worker started and listening for requests...")
|
||||
logger.info("")
|
||||
dts_worker.start()
|
||||
logger.debug("Worker started and listening for requests...")
|
||||
|
||||
# Create the client using helper function
|
||||
client = get_client(log_handler=silent_handler)
|
||||
|
||||
logger.debug("CLIENT: Starting orchestration...")
|
||||
|
||||
# Run the client in the same process
|
||||
try:
|
||||
asyncio.run(run_client(endpoint, taskhub_name, credential))
|
||||
run_client(client)
|
||||
except KeyboardInterrupt:
|
||||
logger.info("Sample interrupted by user")
|
||||
logger.debug("Sample interrupted by user")
|
||||
except Exception as e:
|
||||
logger.exception(f"Error during orchestration: {e}")
|
||||
finally:
|
||||
logger.info("Worker stopping...")
|
||||
logger.debug("Worker stopping...")
|
||||
|
||||
logger.info("Sample completed")
|
||||
logger.debug("")
|
||||
logger.debug("Sample completed")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
+80
-40
@@ -14,7 +14,6 @@ import asyncio
|
||||
from collections.abc import Generator
|
||||
import logging
|
||||
import os
|
||||
from typing import Any
|
||||
|
||||
from agent_framework import AgentRunResponse
|
||||
from agent_framework.azure import AzureOpenAIChatClient
|
||||
@@ -51,9 +50,18 @@ def create_writer_agent():
|
||||
)
|
||||
|
||||
|
||||
def get_orchestration():
|
||||
"""Get the orchestration function for this sample.
|
||||
|
||||
Returns:
|
||||
The orchestration function to register with the worker
|
||||
"""
|
||||
return single_agent_chaining_orchestration
|
||||
|
||||
|
||||
def single_agent_chaining_orchestration(
|
||||
context: OrchestrationContext, _: str
|
||||
) -> Generator[Task[Any], Any, str]:
|
||||
) -> Generator[Task[AgentRunResponse], AgentRunResponse, str]:
|
||||
"""Orchestration that runs the writer agent twice on the same thread.
|
||||
|
||||
This demonstrates chaining behavior where the output of the first agent run
|
||||
@@ -64,10 +72,13 @@ def single_agent_chaining_orchestration(
|
||||
context: The orchestration context
|
||||
_: Input parameter (unused)
|
||||
|
||||
Yields:
|
||||
Task[AgentRunResponse]: Tasks that resolve to AgentRunResponse
|
||||
|
||||
Returns:
|
||||
str: The final refined text from the second agent run
|
||||
"""
|
||||
logger.info("[Orchestration] Starting single agent chaining...")
|
||||
logger.debug("[Orchestration] Starting single agent chaining...")
|
||||
|
||||
# Wrap the orchestration context to access agents
|
||||
agent_context = DurableAIAgentOrchestrationContext(context)
|
||||
@@ -78,12 +89,13 @@ def single_agent_chaining_orchestration(
|
||||
# Create a new thread for the conversation - this will be shared across both runs
|
||||
writer_thread = writer.get_new_thread()
|
||||
|
||||
logger.info(f"[Orchestration] Created thread: {writer_thread.session_id}")
|
||||
logger.debug(f"[Orchestration] Created thread: {writer_thread.session_id}")
|
||||
|
||||
prompt = "Write a concise inspirational sentence about learning."
|
||||
# First run: Generate an initial inspirational sentence
|
||||
logger.info("[Orchestration] First agent run: Generating initial sentence...")
|
||||
initial_response: AgentRunResponse = yield writer.run(
|
||||
messages="Write a concise inspirational sentence about learning.",
|
||||
logger.info("[Orchestration] First agent run: Generating initial sentence about: %s", prompt)
|
||||
initial_response = yield writer.run(
|
||||
messages=prompt,
|
||||
thread=writer_thread,
|
||||
)
|
||||
logger.info(f"[Orchestration] Initial response: {initial_response.text}")
|
||||
@@ -94,61 +106,89 @@ def single_agent_chaining_orchestration(
|
||||
f"{initial_response.text}"
|
||||
)
|
||||
|
||||
logger.info("[Orchestration] Second agent run: Refining the sentence...")
|
||||
refined_response: AgentRunResponse = yield writer.run(
|
||||
logger.info("[Orchestration] Second agent run: Refining the sentence: %s", improved_prompt)
|
||||
refined_response = yield writer.run(
|
||||
messages=improved_prompt,
|
||||
thread=writer_thread,
|
||||
)
|
||||
|
||||
logger.info(f"[Orchestration] Refined response: {refined_response.text}")
|
||||
|
||||
logger.info("[Orchestration] Chaining complete")
|
||||
logger.debug("[Orchestration] Chaining complete")
|
||||
return refined_response.text
|
||||
|
||||
|
||||
async def main():
|
||||
"""Main entry point for the worker process."""
|
||||
logger.info("Starting Durable Task Single Agent Chaining Worker with Orchestration...")
|
||||
def get_worker(
|
||||
taskhub: str | None = None,
|
||||
endpoint: str | None = None,
|
||||
log_handler: logging.Handler | None = None
|
||||
) -> DurableTaskSchedulerWorker:
|
||||
"""Create a configured DurableTaskSchedulerWorker.
|
||||
|
||||
# Get environment variables for taskhub and endpoint with defaults
|
||||
taskhub_name = os.getenv("TASKHUB", "default")
|
||||
endpoint = os.getenv("ENDPOINT", "http://localhost:8080")
|
||||
|
||||
logger.info(f"Using taskhub: {taskhub_name}")
|
||||
logger.info(f"Using endpoint: {endpoint}")
|
||||
|
||||
# Set credential to None for emulator, or DefaultAzureCredential for Azure
|
||||
credential = None if endpoint == "http://localhost:8080" else DefaultAzureCredential()
|
||||
Args:
|
||||
taskhub: Task hub name (defaults to TASKHUB env var or "default")
|
||||
endpoint: Scheduler endpoint (defaults to ENDPOINT env var or "http://localhost:8080")
|
||||
log_handler: Optional logging handler for worker logging
|
||||
|
||||
Returns:
|
||||
Configured DurableTaskSchedulerWorker instance
|
||||
"""
|
||||
taskhub_name = taskhub or os.getenv("TASKHUB", "default")
|
||||
endpoint_url = endpoint or os.getenv("ENDPOINT", "http://localhost:8080")
|
||||
|
||||
# Create a worker using Azure Managed Durable Task
|
||||
worker = DurableTaskSchedulerWorker(
|
||||
host_address=endpoint,
|
||||
secure_channel=endpoint != "http://localhost:8080",
|
||||
logger.debug(f"Using taskhub: {taskhub_name}")
|
||||
logger.debug(f"Using endpoint: {endpoint_url}")
|
||||
|
||||
credential = None if endpoint_url == "http://localhost:8080" else DefaultAzureCredential()
|
||||
|
||||
return DurableTaskSchedulerWorker(
|
||||
host_address=endpoint_url,
|
||||
secure_channel=endpoint_url != "http://localhost:8080",
|
||||
taskhub=taskhub_name,
|
||||
token_credential=credential
|
||||
token_credential=credential,
|
||||
log_handler=log_handler
|
||||
)
|
||||
|
||||
|
||||
def setup_worker(worker: DurableTaskSchedulerWorker) -> DurableAIAgentWorker:
|
||||
"""Set up the worker with agents and orchestrations registered.
|
||||
|
||||
Args:
|
||||
worker: The DurableTaskSchedulerWorker instance
|
||||
|
||||
Returns:
|
||||
DurableAIAgentWorker with agents and orchestrations registered
|
||||
"""
|
||||
# Wrap it with the agent worker
|
||||
agent_worker = DurableAIAgentWorker(worker)
|
||||
|
||||
# Create and register the Writer agent
|
||||
logger.info("Creating and registering Writer agent...")
|
||||
logger.debug("Creating and registering Writer agent...")
|
||||
writer_agent = create_writer_agent()
|
||||
agent_worker.add_agent(writer_agent)
|
||||
|
||||
logger.info(f"✓ Registered agent: {writer_agent.name}")
|
||||
logger.info(f" Entity name: dafx-{writer_agent.name}")
|
||||
logger.info("")
|
||||
logger.debug(f"✓ Registered agent: {writer_agent.name}")
|
||||
|
||||
# Register the orchestration function
|
||||
logger.info("Registering orchestration function...")
|
||||
worker.add_orchestrator(single_agent_chaining_orchestration)
|
||||
logger.info(f"✓ Registered orchestration: {single_agent_chaining_orchestration.__name__}")
|
||||
logger.info("")
|
||||
logger.debug("Registering orchestration function...")
|
||||
worker.add_orchestrator(single_agent_chaining_orchestration) # type: ignore
|
||||
logger.debug(f"✓ Registered orchestration: {single_agent_chaining_orchestration.__name__}")
|
||||
|
||||
logger.info("Worker is ready and listening for requests...")
|
||||
logger.info("Press Ctrl+C to stop.")
|
||||
logger.info("")
|
||||
return agent_worker
|
||||
|
||||
|
||||
async def main():
|
||||
"""Main entry point for the worker process."""
|
||||
logger.debug("Starting Durable Task Single Agent Chaining Worker with Orchestration...")
|
||||
|
||||
# Create a worker using the helper function
|
||||
worker = get_worker()
|
||||
|
||||
# Setup worker with agents and orchestrations
|
||||
setup_worker(worker)
|
||||
|
||||
logger.debug("Worker is ready and listening for requests...")
|
||||
logger.debug("Press Ctrl+C to stop.")
|
||||
|
||||
try:
|
||||
# Start the worker (this blocks until stopped)
|
||||
@@ -158,9 +198,9 @@ async def main():
|
||||
while True:
|
||||
await asyncio.sleep(1)
|
||||
except KeyboardInterrupt:
|
||||
logger.info("Worker shutdown initiated")
|
||||
logger.debug("Worker shutdown initiated")
|
||||
|
||||
logger.info("Worker stopped")
|
||||
logger.debug("Worker stopped")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
+10
-14
@@ -1,4 +1,4 @@
|
||||
# Multi-Agent Orchestration with Concurrency Sample
|
||||
# Multi-Agent Orchestration with Concurrency
|
||||
|
||||
This sample demonstrates how to host multiple agents and run them concurrently using a durable orchestration, aggregating their responses into a single result.
|
||||
|
||||
@@ -15,38 +15,37 @@ See the [README.md](../README.md) file in the parent directory for more informat
|
||||
|
||||
## Running the Sample
|
||||
|
||||
With the environment setup, you can run the sample using one of two approaches:
|
||||
With the environment setup, you can run the sample using the combined approach or separate worker and client processes:
|
||||
|
||||
### Option 1: Combined Worker + Client (Quick Start)
|
||||
**Option 1: Combined (Recommended for Testing)**
|
||||
|
||||
```bash
|
||||
cd samples/getting_started/durabletask/05_multi_agent_orchestration_concurrency
|
||||
python sample.py
|
||||
```
|
||||
|
||||
This runs both worker and client in a single process.
|
||||
**Option 2: Separate Processes**
|
||||
|
||||
### Option 2: Separate Worker and Client
|
||||
|
||||
**Start the worker in one terminal:**
|
||||
Start the worker in one terminal:
|
||||
|
||||
```bash
|
||||
python worker.py
|
||||
```
|
||||
|
||||
**In a new terminal, run the client:**
|
||||
In a new terminal, run the client:
|
||||
|
||||
```bash
|
||||
python client.py
|
||||
```
|
||||
|
||||
The orchestration will execute both agents concurrently, and you'll see output like:
|
||||
The orchestration will execute both agents concurrently:
|
||||
|
||||
```
|
||||
Prompt: What is temperature?
|
||||
|
||||
Starting multi-agent concurrent orchestration...
|
||||
Orchestration started with instance ID: abc123...
|
||||
⚡ Running PhysicistAgent and ChemistAgent in parallel...
|
||||
Orchestration status: COMPLETED
|
||||
|
||||
Results:
|
||||
@@ -63,13 +62,10 @@ Chemist's response:
|
||||
You can view the state of the orchestration in the Durable Task Scheduler dashboard:
|
||||
|
||||
1. Open your browser and navigate to `http://localhost:8082`
|
||||
2. In the dashboard, you can view the orchestration instance, including:
|
||||
- The concurrent execution of both agents (Physicist and Chemist)
|
||||
2. In the dashboard, you can view:
|
||||
- The concurrent execution of both agents (PhysicistAgent and ChemistAgent)
|
||||
- Separate conversation threads for each agent
|
||||
- Parallel task execution and completion timing
|
||||
- Aggregated results from both agents
|
||||
- Overall orchestration state and history
|
||||
|
||||
The orchestration demonstrates how multiple agents can be executed in parallel, with results collected and aggregated once all agents complete.
|
||||
|
||||
|
||||
|
||||
+73
-73
@@ -24,90 +24,90 @@ logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
"""Main entry point for the client application."""
|
||||
logger.info("Starting Durable Task Multi-Agent Orchestration Client...")
|
||||
def get_client(
|
||||
taskhub: str | None = None,
|
||||
endpoint: str | None = None,
|
||||
log_handler: logging.Handler | None = None
|
||||
) -> DurableTaskSchedulerClient:
|
||||
"""Create a configured DurableTaskSchedulerClient.
|
||||
|
||||
# Get environment variables for taskhub and endpoint with defaults
|
||||
taskhub_name = os.getenv("TASKHUB", "default")
|
||||
endpoint = os.getenv("ENDPOINT", "http://localhost:8080")
|
||||
|
||||
logger.info(f"Using taskhub: {taskhub_name}")
|
||||
logger.info(f"Using endpoint: {endpoint}")
|
||||
logger.info("")
|
||||
|
||||
# Set credential to None for emulator, or DefaultAzureCredential for Azure
|
||||
credential = None if endpoint == "http://localhost:8080" else DefaultAzureCredential()
|
||||
Args:
|
||||
taskhub: Task hub name (defaults to TASKHUB env var or "default")
|
||||
endpoint: Scheduler endpoint (defaults to ENDPOINT env var or "http://localhost:8080")
|
||||
log_handler: Optional logging handler for client logging
|
||||
|
||||
Returns:
|
||||
Configured DurableTaskSchedulerClient instance
|
||||
"""
|
||||
taskhub_name = taskhub or os.getenv("TASKHUB", "default")
|
||||
endpoint_url = endpoint or os.getenv("ENDPOINT", "http://localhost:8080")
|
||||
|
||||
# Create a client using Azure Managed Durable Task
|
||||
client = DurableTaskSchedulerClient(
|
||||
host_address=endpoint,
|
||||
secure_channel=endpoint != "http://localhost:8080",
|
||||
logger.debug(f"Using taskhub: {taskhub_name}")
|
||||
logger.debug(f"Using endpoint: {endpoint_url}")
|
||||
|
||||
credential = None if endpoint_url == "http://localhost:8080" else DefaultAzureCredential()
|
||||
|
||||
return DurableTaskSchedulerClient(
|
||||
host_address=endpoint_url,
|
||||
secure_channel=endpoint_url != "http://localhost:8080",
|
||||
taskhub=taskhub_name,
|
||||
token_credential=credential
|
||||
token_credential=credential,
|
||||
log_handler=log_handler
|
||||
)
|
||||
|
||||
|
||||
def run_client(client: DurableTaskSchedulerClient, prompt: str = "What is temperature?") -> None:
|
||||
"""Run client to start and monitor the orchestration.
|
||||
|
||||
Args:
|
||||
client: The DurableTaskSchedulerClient instance
|
||||
prompt: The prompt to send to both agents
|
||||
"""
|
||||
# Start the orchestration with the prompt as input
|
||||
instance_id = client.schedule_new_orchestration( # type: ignore
|
||||
orchestrator="multi_agent_concurrent_orchestration",
|
||||
input=prompt,
|
||||
)
|
||||
|
||||
# Define the prompt to send to both agents
|
||||
prompt = "What is temperature?"
|
||||
logger.info(f"Orchestration started with instance ID: {instance_id}")
|
||||
logger.debug("Waiting for orchestration to complete...")
|
||||
|
||||
logger.info(f"Prompt: {prompt}")
|
||||
logger.info("")
|
||||
logger.info("Starting multi-agent concurrent orchestration...")
|
||||
# Retrieve the final state
|
||||
metadata = client.wait_for_orchestration_completion(
|
||||
instance_id=instance_id,
|
||||
)
|
||||
|
||||
if metadata and metadata.runtime_status.name == "COMPLETED":
|
||||
result = metadata.serialized_output
|
||||
|
||||
logger.debug("Orchestration completed successfully!")
|
||||
|
||||
# Parse and display the result
|
||||
if result:
|
||||
result_json = json.loads(result) if isinstance(result, str) else result
|
||||
logger.info("Orchestration Results:\n%s", json.dumps(result_json, indent=2))
|
||||
|
||||
elif metadata:
|
||||
logger.error(f"Orchestration ended with status: {metadata.runtime_status.name}")
|
||||
if metadata.serialized_output:
|
||||
logger.error(f"Output: {metadata.serialized_output}")
|
||||
else:
|
||||
logger.error("Orchestration did not complete within the timeout period")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
"""Main entry point for the client application."""
|
||||
logger.debug("Starting Durable Task Multi-Agent Orchestration Client...")
|
||||
|
||||
# Create client using helper function
|
||||
client = get_client()
|
||||
|
||||
try:
|
||||
# Start the orchestration with the prompt as input
|
||||
instance_id = client.schedule_new_orchestration(
|
||||
orchestrator="multi_agent_concurrent_orchestration",
|
||||
input=prompt,
|
||||
)
|
||||
|
||||
logger.info(f"Orchestration started with instance ID: {instance_id}")
|
||||
logger.info("Waiting for orchestration to complete...")
|
||||
logger.info("")
|
||||
|
||||
# Retrieve the final state
|
||||
metadata = client.wait_for_orchestration_completion(
|
||||
instance_id=instance_id,
|
||||
)
|
||||
|
||||
if metadata and metadata.runtime_status.name == "COMPLETED":
|
||||
result = metadata.serialized_output
|
||||
|
||||
logger.info("=" * 80)
|
||||
logger.info("Orchestration completed successfully!")
|
||||
logger.info("=" * 80)
|
||||
logger.info("")
|
||||
logger.info(f"Prompt: {prompt}")
|
||||
logger.info("")
|
||||
logger.info("Results:")
|
||||
logger.info("")
|
||||
|
||||
# Parse and display the result
|
||||
if result:
|
||||
result_dict = json.loads(result)
|
||||
|
||||
logger.info("Physicist's response:")
|
||||
logger.info(f" {result_dict.get('physicist', 'N/A')}")
|
||||
logger.info("")
|
||||
|
||||
logger.info("Chemist's response:")
|
||||
logger.info(f" {result_dict.get('chemist', 'N/A')}")
|
||||
logger.info("")
|
||||
|
||||
logger.info("=" * 80)
|
||||
|
||||
elif metadata:
|
||||
logger.error(f"Orchestration ended with status: {metadata.runtime_status.name}")
|
||||
if metadata.serialized_output:
|
||||
logger.error(f"Output: {metadata.serialized_output}")
|
||||
else:
|
||||
logger.error("Orchestration did not complete within the timeout period")
|
||||
|
||||
run_client(client)
|
||||
except Exception as e:
|
||||
logger.exception(f"Error during orchestration: {e}")
|
||||
finally:
|
||||
logger.info("")
|
||||
logger.info("Client shutting down")
|
||||
logger.debug("Client shutting down")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
+20
-222
@@ -16,249 +16,47 @@ To run this sample:
|
||||
python sample.py
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from collections.abc import Generator
|
||||
from typing import Any
|
||||
|
||||
from agent_framework import AgentRunResponse
|
||||
from agent_framework.azure import AzureOpenAIChatClient
|
||||
from agent_framework_durabletask import DurableAIAgentOrchestrationContext, DurableAIAgentWorker
|
||||
from azure.identity import AzureCliCredential, DefaultAzureCredential
|
||||
from dotenv import load_dotenv
|
||||
from durabletask.task import OrchestrationContext, when_all, Task
|
||||
from durabletask.azuremanaged.client import DurableTaskSchedulerClient
|
||||
from durabletask.azuremanaged.worker import DurableTaskSchedulerWorker
|
||||
|
||||
# Import helper functions from worker and client modules
|
||||
from client import get_client, run_client
|
||||
from worker import get_worker, setup_worker
|
||||
|
||||
# Configure logging
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logging.basicConfig(level=logging.INFO, force=True)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Agent names
|
||||
PHYSICIST_AGENT_NAME = "PhysicistAgent"
|
||||
CHEMIST_AGENT_NAME = "ChemistAgent"
|
||||
|
||||
|
||||
def create_physicist_agent():
|
||||
"""Create the Physicist agent using Azure OpenAI.
|
||||
|
||||
Returns:
|
||||
AgentProtocol: The configured Physicist agent
|
||||
"""
|
||||
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
|
||||
name=PHYSICIST_AGENT_NAME,
|
||||
instructions="You are an expert in physics. You answer questions from a physics perspective.",
|
||||
)
|
||||
|
||||
|
||||
def create_chemist_agent():
|
||||
"""Create the Chemist agent using Azure OpenAI.
|
||||
|
||||
Returns:
|
||||
AgentProtocol: The configured Chemist agent
|
||||
"""
|
||||
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
|
||||
name=CHEMIST_AGENT_NAME,
|
||||
instructions="You are an expert in chemistry. You answer questions from a chemistry perspective.",
|
||||
)
|
||||
|
||||
|
||||
def multi_agent_concurrent_orchestration(context: OrchestrationContext, prompt: str) -> Generator[Task[Any], Any, dict[str, str]]:
|
||||
"""Orchestration that runs both agents in parallel and aggregates results.
|
||||
|
||||
Uses DurableAIAgentOrchestrationContext to wrap the orchestration context and
|
||||
access agents via the OrchestrationAgentExecutor.
|
||||
|
||||
Args:
|
||||
context: The orchestration context
|
||||
|
||||
Returns:
|
||||
dict: Dictionary with 'physicist' and 'chemist' response texts
|
||||
"""
|
||||
logger.info(f"[Orchestration] Starting concurrent execution for prompt: {prompt}")
|
||||
|
||||
# Wrap the orchestration context to access agents
|
||||
agent_context = DurableAIAgentOrchestrationContext(context)
|
||||
|
||||
# Get agents using the agent context (returns DurableAIAgent proxies)
|
||||
physicist = agent_context.get_agent(PHYSICIST_AGENT_NAME)
|
||||
chemist = agent_context.get_agent(CHEMIST_AGENT_NAME)
|
||||
|
||||
# Create separate threads for each agent
|
||||
physicist_thread = physicist.get_new_thread()
|
||||
chemist_thread = chemist.get_new_thread()
|
||||
|
||||
logger.info(f"[Orchestration] Created threads - Physicist: {physicist_thread.session_id}, Chemist: {chemist_thread.session_id}")
|
||||
|
||||
# Create tasks from agent.run() calls - these return DurableAgentTask instances
|
||||
physicist_task = physicist.run(messages=str(prompt), thread=physicist_thread)
|
||||
chemist_task = chemist.run(messages=str(prompt), thread=chemist_thread)
|
||||
|
||||
logger.info("[Orchestration] Created agent tasks, executing concurrently...")
|
||||
|
||||
# Execute both tasks concurrently using task.when_all
|
||||
# The DurableAgentTask instances wrap the underlying entity calls
|
||||
task_results = yield when_all([physicist_task, chemist_task])
|
||||
|
||||
logger.info("[Orchestration] Both agents completed")
|
||||
|
||||
# Extract results from the tasks - DurableAgentTask yields AgentRunResponse
|
||||
physicist_result: AgentRunResponse = task_results[0]
|
||||
chemist_result: AgentRunResponse = task_results[1]
|
||||
|
||||
result = {
|
||||
"physicist": physicist_result.text,
|
||||
"chemist": chemist_result.text,
|
||||
}
|
||||
|
||||
logger.info(f"[Orchestration] Aggregated results ready")
|
||||
return result
|
||||
|
||||
|
||||
async def run_client(endpoint: str, taskhub_name: str, credential: DefaultAzureCredential | None, prompt: str):
|
||||
"""Run the client to start and monitor the orchestration.
|
||||
|
||||
Args:
|
||||
endpoint: The durable task scheduler endpoint
|
||||
taskhub_name: The task hub name
|
||||
credential: The credential for authentication
|
||||
prompt: The prompt to send to both agents
|
||||
"""
|
||||
logger.info("")
|
||||
logger.info("=" * 80)
|
||||
logger.info("CLIENT: Starting orchestration...")
|
||||
logger.info("=" * 80)
|
||||
|
||||
# Create a client
|
||||
client = DurableTaskSchedulerClient(
|
||||
host_address=endpoint,
|
||||
secure_channel=endpoint != "http://localhost:8080",
|
||||
taskhub=taskhub_name,
|
||||
token_credential=credential
|
||||
)
|
||||
|
||||
logger.info(f"Prompt: {prompt}")
|
||||
logger.info("")
|
||||
|
||||
try:
|
||||
# Start the orchestration with the prompt as input
|
||||
instance_id = client.schedule_new_orchestration(
|
||||
multi_agent_concurrent_orchestration,
|
||||
input=prompt,
|
||||
)
|
||||
|
||||
logger.info(f"Orchestration started with instance ID: {instance_id}")
|
||||
logger.info("Waiting for orchestration to complete...")
|
||||
logger.info("")
|
||||
|
||||
# Retrieve the final state
|
||||
metadata = client.wait_for_orchestration_completion(
|
||||
instance_id=instance_id
|
||||
)
|
||||
|
||||
if metadata and metadata.runtime_status.name == "COMPLETED":
|
||||
result = metadata.serialized_output
|
||||
|
||||
logger.info("")
|
||||
logger.info("=" * 80)
|
||||
logger.info("ORCHESTRATION COMPLETED SUCCESSFULLY!")
|
||||
logger.info("=" * 80)
|
||||
logger.info("")
|
||||
logger.info(f"Prompt: {prompt}")
|
||||
logger.info("")
|
||||
logger.info("Results:")
|
||||
logger.info("")
|
||||
|
||||
# Parse and display the result
|
||||
if result:
|
||||
result_dict = json.loads(result)
|
||||
|
||||
logger.info("Physicist's response:")
|
||||
logger.info(f" {result_dict.get('physicist', 'N/A')}")
|
||||
logger.info("")
|
||||
|
||||
logger.info("Chemist's response:")
|
||||
logger.info(f" {result_dict.get('chemist', 'N/A')}")
|
||||
logger.info("")
|
||||
|
||||
logger.info("=" * 80)
|
||||
|
||||
elif metadata:
|
||||
logger.error(f"Orchestration ended with status: {metadata.runtime_status.name}")
|
||||
if metadata.serialized_output:
|
||||
logger.error(f"Output: {metadata.serialized_output}")
|
||||
else:
|
||||
logger.error("Orchestration did not complete within the timeout period")
|
||||
|
||||
except Exception as e:
|
||||
logger.exception(f"Error during orchestration: {e}")
|
||||
|
||||
|
||||
def main():
|
||||
"""Main entry point - runs both worker and client in single process."""
|
||||
logger.info("Starting Durable Task Multi-Agent Orchestration Sample (Combined Worker + Client)...")
|
||||
logger.debug("Starting Durable Task Multi-Agent Orchestration Sample (Combined Worker + Client)...")
|
||||
|
||||
# Get environment variables for taskhub and endpoint with defaults
|
||||
taskhub_name = os.getenv("TASKHUB", "default")
|
||||
endpoint = os.getenv("ENDPOINT", "http://localhost:8080")
|
||||
|
||||
logger.info(f"Using taskhub: {taskhub_name}")
|
||||
logger.info(f"Using endpoint: {endpoint}")
|
||||
logger.info("")
|
||||
|
||||
# Set credential to None for emulator, or DefaultAzureCredential for Azure
|
||||
credential = None if endpoint == "http://localhost:8080" else DefaultAzureCredential()
|
||||
secure_channel = endpoint != "http://localhost:8080"
|
||||
|
||||
# Create and start the worker using a context manager
|
||||
with DurableTaskSchedulerWorker(
|
||||
host_address=endpoint,
|
||||
secure_channel=secure_channel,
|
||||
taskhub=taskhub_name,
|
||||
token_credential=credential
|
||||
) as worker:
|
||||
|
||||
# Wrap with the agent worker
|
||||
agent_worker = DurableAIAgentWorker(worker)
|
||||
|
||||
# Create and register both agents
|
||||
logger.info("Creating and registering agents...")
|
||||
physicist_agent = create_physicist_agent()
|
||||
chemist_agent = create_chemist_agent()
|
||||
|
||||
agent_worker.add_agent(physicist_agent)
|
||||
agent_worker.add_agent(chemist_agent)
|
||||
|
||||
logger.info(f"✓ Registered agent: {physicist_agent.name}")
|
||||
logger.info(f" Entity name: dafx-{physicist_agent.name}")
|
||||
logger.info(f"✓ Registered agent: {chemist_agent.name}")
|
||||
logger.info(f" Entity name: dafx-{chemist_agent.name}")
|
||||
logger.info("")
|
||||
|
||||
# Register the orchestration function
|
||||
logger.info("Registering orchestration function...")
|
||||
worker.add_orchestrator(multi_agent_concurrent_orchestration)
|
||||
logger.info(f"✓ Registered orchestration: {multi_agent_concurrent_orchestration.__name__}")
|
||||
logger.info("")
|
||||
silent_handler = logging.NullHandler()
|
||||
# Create and start the worker using helper function and context manager
|
||||
with get_worker(log_handler=silent_handler) as dts_worker:
|
||||
# Register agents and orchestrations using helper function
|
||||
setup_worker(dts_worker)
|
||||
|
||||
# Start the worker
|
||||
worker.start()
|
||||
logger.info("Worker started and listening for requests...")
|
||||
dts_worker.start()
|
||||
logger.debug("Worker started and listening for requests...")
|
||||
|
||||
# Create the client using helper function
|
||||
client = get_client(log_handler=silent_handler)
|
||||
|
||||
# Define the prompt
|
||||
prompt = "What is temperature?"
|
||||
|
||||
logger.debug("CLIENT: Starting orchestration...")
|
||||
|
||||
try:
|
||||
# Run the client to start the orchestration
|
||||
asyncio.run(run_client(endpoint, taskhub_name, credential, prompt))
|
||||
|
||||
run_client(client, prompt)
|
||||
except Exception as e:
|
||||
logger.exception(f"Error during sample execution: {e}")
|
||||
|
||||
logger.info("")
|
||||
logger.info("Sample completed. Worker shutting down...")
|
||||
logger.debug("Sample completed. Worker shutting down...")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
+63
-36
@@ -64,6 +64,7 @@ def multi_agent_concurrent_orchestration(context: OrchestrationContext, prompt:
|
||||
|
||||
Args:
|
||||
context: The orchestration context
|
||||
prompt: The prompt to send to both agents
|
||||
|
||||
Returns:
|
||||
dict: Dictionary with 'physicist' and 'chemist' response texts
|
||||
@@ -82,19 +83,19 @@ def multi_agent_concurrent_orchestration(context: OrchestrationContext, prompt:
|
||||
physicist_thread = physicist.get_new_thread()
|
||||
chemist_thread = chemist.get_new_thread()
|
||||
|
||||
logger.info(f"[Orchestration] Created threads - Physicist: {physicist_thread.session_id}, Chemist: {chemist_thread.session_id}")
|
||||
logger.debug(f"[Orchestration] Created threads - Physicist: {physicist_thread.session_id}, Chemist: {chemist_thread.session_id}")
|
||||
|
||||
# Create tasks from agent.run() calls - these return DurableAgentTask instances
|
||||
physicist_task = physicist.run(messages=str(prompt), thread=physicist_thread)
|
||||
chemist_task = chemist.run(messages=str(prompt), thread=chemist_thread)
|
||||
|
||||
logger.info("[Orchestration] Created agent tasks, executing concurrently...")
|
||||
logger.debug("[Orchestration] Created agent tasks, executing concurrently...")
|
||||
|
||||
# Execute both tasks concurrently using when_all
|
||||
# The DurableAgentTask instances wrap the underlying entity calls
|
||||
task_results = yield when_all([physicist_task, chemist_task])
|
||||
|
||||
logger.info("[Orchestration] Both agents completed")
|
||||
logger.debug("[Orchestration] Both agents completed")
|
||||
|
||||
# Extract results from the tasks - DurableAgentTask yields AgentRunResponse
|
||||
physicist_result: AgentRunResponse = task_results[0]
|
||||
@@ -105,58 +106,84 @@ def multi_agent_concurrent_orchestration(context: OrchestrationContext, prompt:
|
||||
"chemist": chemist_result.text,
|
||||
}
|
||||
|
||||
logger.info(f"[Orchestration] Aggregated results ready")
|
||||
logger.debug(f"[Orchestration] Aggregated results ready")
|
||||
return result
|
||||
|
||||
|
||||
async def main():
|
||||
"""Main entry point for the worker process."""
|
||||
logger.info("Starting Durable Task Multi-Agent Worker with Orchestration...")
|
||||
def get_worker(
|
||||
taskhub: str | None = None,
|
||||
endpoint: str | None = None,
|
||||
log_handler: logging.Handler | None = None
|
||||
) -> DurableTaskSchedulerWorker:
|
||||
"""Create a configured DurableTaskSchedulerWorker.
|
||||
|
||||
# Get environment variables for taskhub and endpoint with defaults
|
||||
taskhub_name = os.getenv("TASKHUB", "default")
|
||||
endpoint = os.getenv("ENDPOINT", "http://localhost:8080")
|
||||
|
||||
logger.info(f"Using taskhub: {taskhub_name}")
|
||||
logger.info(f"Using endpoint: {endpoint}")
|
||||
|
||||
# Set credential to None for emulator, or DefaultAzureCredential for Azure
|
||||
credential = None if endpoint == "http://localhost:8080" else DefaultAzureCredential()
|
||||
Args:
|
||||
taskhub: Task hub name (defaults to TASKHUB env var or "default")
|
||||
endpoint: Scheduler endpoint (defaults to ENDPOINT env var or "http://localhost:8080")
|
||||
log_handler: Optional logging handler for worker logging
|
||||
|
||||
Returns:
|
||||
Configured DurableTaskSchedulerWorker instance
|
||||
"""
|
||||
taskhub_name = taskhub or os.getenv("TASKHUB", "default")
|
||||
endpoint_url = endpoint or os.getenv("ENDPOINT", "http://localhost:8080")
|
||||
|
||||
# Create a worker using Azure Managed Durable Task
|
||||
worker = DurableTaskSchedulerWorker(
|
||||
host_address=endpoint,
|
||||
secure_channel=endpoint != "http://localhost:8080",
|
||||
logger.debug(f"Using taskhub: {taskhub_name}")
|
||||
logger.debug(f"Using endpoint: {endpoint_url}")
|
||||
|
||||
credential = None if endpoint_url == "http://localhost:8080" else DefaultAzureCredential()
|
||||
|
||||
return DurableTaskSchedulerWorker(
|
||||
host_address=endpoint_url,
|
||||
secure_channel=endpoint_url != "http://localhost:8080",
|
||||
taskhub=taskhub_name,
|
||||
token_credential=credential
|
||||
token_credential=credential,
|
||||
log_handler=log_handler
|
||||
)
|
||||
|
||||
|
||||
def setup_worker(worker: DurableTaskSchedulerWorker) -> DurableAIAgentWorker:
|
||||
"""Set up the worker with agents and orchestrations registered.
|
||||
|
||||
Args:
|
||||
worker: The DurableTaskSchedulerWorker instance
|
||||
|
||||
Returns:
|
||||
DurableAIAgentWorker with agents and orchestrations registered
|
||||
"""
|
||||
# Wrap it with the agent worker
|
||||
agent_worker = DurableAIAgentWorker(worker)
|
||||
|
||||
# Create and register both agents
|
||||
logger.info("Creating and registering agents...")
|
||||
logger.debug("Creating and registering agents...")
|
||||
physicist_agent = create_physicist_agent()
|
||||
chemist_agent = create_chemist_agent()
|
||||
|
||||
agent_worker.add_agent(physicist_agent)
|
||||
agent_worker.add_agent(chemist_agent)
|
||||
|
||||
logger.info(f"✓ Registered agent: {physicist_agent.name}")
|
||||
logger.info(f" Entity name: dafx-{physicist_agent.name}")
|
||||
logger.info(f"✓ Registered agent: {chemist_agent.name}")
|
||||
logger.info(f" Entity name: dafx-{chemist_agent.name}")
|
||||
logger.info("")
|
||||
logger.debug(f"✓ Registered agents: {physicist_agent.name}, {chemist_agent.name}")
|
||||
|
||||
# Register the orchestration function
|
||||
logger.info("Registering orchestration function...")
|
||||
worker.add_orchestrator(multi_agent_concurrent_orchestration)
|
||||
logger.info(f"✓ Registered orchestration: {multi_agent_concurrent_orchestration.__name__}")
|
||||
logger.info("")
|
||||
logger.debug("Registering orchestration function...")
|
||||
worker.add_orchestrator(multi_agent_concurrent_orchestration) # type: ignore
|
||||
logger.debug(f"✓ Registered orchestration: {multi_agent_concurrent_orchestration.__name__}")
|
||||
|
||||
logger.info("Worker is ready and listening for requests...")
|
||||
logger.info("Press Ctrl+C to stop.")
|
||||
logger.info("")
|
||||
return agent_worker
|
||||
|
||||
|
||||
async def main():
|
||||
"""Main entry point for the worker process."""
|
||||
logger.debug("Starting Durable Task Multi-Agent Worker with Orchestration...")
|
||||
|
||||
# Create a worker using the helper function
|
||||
worker = get_worker()
|
||||
|
||||
# Setup worker with agents and orchestrations
|
||||
setup_worker(worker)
|
||||
|
||||
logger.debug("Worker is ready and listening for requests...")
|
||||
logger.debug("Press Ctrl+C to stop.")
|
||||
|
||||
try:
|
||||
# Start the worker (this blocks until stopped)
|
||||
@@ -166,9 +193,9 @@ async def main():
|
||||
while True:
|
||||
await asyncio.sleep(1)
|
||||
except KeyboardInterrupt:
|
||||
logger.info("Worker shutdown initiated")
|
||||
logger.debug("Worker shutdown initiated")
|
||||
|
||||
logger.info("Worker stopped")
|
||||
logger.debug("Worker stopped")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
# Multi-Agent Orchestration with Conditionals
|
||||
|
||||
This sample demonstrates conditional orchestration logic with two agents that analyze incoming emails and route execution based on spam detection results.
|
||||
|
||||
## Key Concepts Demonstrated
|
||||
|
||||
- Multi-agent orchestration with two specialized agents (SpamDetectionAgent and EmailAssistantAgent).
|
||||
- Conditional branching with different execution paths based on spam detection results.
|
||||
- Structured outputs using Pydantic models with `response_format` for type-safe agent responses.
|
||||
- Activity functions for side effects (spam handling and email sending).
|
||||
- Decision-based routing where orchestration logic branches on agent output.
|
||||
|
||||
## Environment Setup
|
||||
|
||||
See the [README.md](../README.md) file in the parent directory for more information on how to configure the environment, including how to install and run common sample dependencies.
|
||||
|
||||
## Running the Sample
|
||||
|
||||
With the environment setup, you can run the sample using the combined approach or separate worker and client processes:
|
||||
|
||||
**Option 1: Combined (Recommended for Testing)**
|
||||
|
||||
```bash
|
||||
cd samples/getting_started/durabletask/06_multi_agent_orchestration_conditionals
|
||||
python sample.py
|
||||
```
|
||||
|
||||
**Option 2: Separate Processes**
|
||||
|
||||
Start the worker in one terminal:
|
||||
|
||||
```bash
|
||||
python worker.py
|
||||
```
|
||||
|
||||
In a new terminal, run the client:
|
||||
|
||||
```bash
|
||||
python client.py
|
||||
```
|
||||
|
||||
The sample runs two test cases:
|
||||
|
||||
**Test 1: Legitimate Email**
|
||||
```
|
||||
Email ID: email-001
|
||||
Email Content: Hello! I wanted to reach out about our upcoming project meeting...
|
||||
|
||||
🔍 SpamDetectionAgent: Analyzing email...
|
||||
✓ Not spam - routing to EmailAssistantAgent
|
||||
|
||||
📧 EmailAssistantAgent: Drafting response...
|
||||
✓ Email sent: [Professional response drafted by EmailAssistantAgent]
|
||||
```
|
||||
|
||||
**Test 2: Spam Email**
|
||||
```
|
||||
Email ID: email-002
|
||||
Email Content: URGENT! You've won $1,000,000! Click here now...
|
||||
|
||||
🔍 SpamDetectionAgent: Analyzing email...
|
||||
⚠️ Spam detected: [Reason from SpamDetectionAgent]
|
||||
✓ Email marked as spam and handled
|
||||
```
|
||||
|
||||
## How It Works
|
||||
|
||||
1. **Input Validation**: Orchestration validates email payload using Pydantic models.
|
||||
2. **Spam Detection**: SpamDetectionAgent analyzes email content.
|
||||
3. **Conditional Routing**:
|
||||
- If spam: Calls `handle_spam_email` activity
|
||||
- If legitimate: Runs EmailAssistantAgent and calls `send_email` activity
|
||||
4. **Result**: Returns confirmation message from the appropriate activity.
|
||||
|
||||
## Viewing Agent State
|
||||
|
||||
You can view the state of both agents and orchestration in the Durable Task Scheduler dashboard:
|
||||
|
||||
1. Open your browser and navigate to `http://localhost:8082`
|
||||
2. In the dashboard, you can view:
|
||||
- Orchestration instance status and history
|
||||
- SpamDetectionAgent and EmailAssistantAgent entity states
|
||||
- Activity execution logs
|
||||
- Decision branch paths taken
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
"""Client application for starting a spam detection orchestration.
|
||||
|
||||
This client connects to the Durable Task Scheduler and starts an orchestration
|
||||
that uses conditional logic to either handle spam emails or draft professional responses.
|
||||
|
||||
Prerequisites:
|
||||
- The worker must be running with both agents, orchestration, and activities registered
|
||||
- Set AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_CHAT_DEPLOYMENT_NAME
|
||||
(plus AZURE_OPENAI_API_KEY or Azure CLI authentication)
|
||||
- Durable Task Scheduler must be running
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
|
||||
from azure.identity import DefaultAzureCredential
|
||||
from durabletask.azuremanaged.client import DurableTaskSchedulerClient
|
||||
|
||||
# Configure logging
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def get_client(
|
||||
taskhub: str | None = None,
|
||||
endpoint: str | None = None,
|
||||
log_handler: logging.Handler | None = None
|
||||
) -> DurableTaskSchedulerClient:
|
||||
"""Create a configured DurableTaskSchedulerClient.
|
||||
|
||||
Args:
|
||||
taskhub: Task hub name (defaults to TASKHUB env var or "default")
|
||||
endpoint: Scheduler endpoint (defaults to ENDPOINT env var or "http://localhost:8080")
|
||||
log_handler: Optional logging handler for client logging
|
||||
|
||||
Returns:
|
||||
Configured DurableTaskSchedulerClient instance
|
||||
"""
|
||||
taskhub_name = taskhub or os.getenv("TASKHUB", "default")
|
||||
endpoint_url = endpoint or os.getenv("ENDPOINT", "http://localhost:8080")
|
||||
|
||||
logger.debug(f"Using taskhub: {taskhub_name}")
|
||||
logger.debug(f"Using endpoint: {endpoint_url}")
|
||||
|
||||
credential = None if endpoint_url == "http://localhost:8080" else DefaultAzureCredential()
|
||||
|
||||
return DurableTaskSchedulerClient(
|
||||
host_address=endpoint_url,
|
||||
secure_channel=endpoint_url != "http://localhost:8080",
|
||||
taskhub=taskhub_name,
|
||||
token_credential=credential,
|
||||
log_handler=log_handler
|
||||
)
|
||||
|
||||
|
||||
def run_client(
|
||||
client: DurableTaskSchedulerClient,
|
||||
email_id: str = "email-001",
|
||||
email_content: str = "Hello! I wanted to reach out about our upcoming project meeting."
|
||||
) -> None:
|
||||
"""Run client to start and monitor the spam detection orchestration.
|
||||
|
||||
Args:
|
||||
client: The DurableTaskSchedulerClient instance
|
||||
email_id: The email ID
|
||||
email_content: The email content to analyze
|
||||
"""
|
||||
payload = {
|
||||
"email_id": email_id,
|
||||
"email_content": email_content,
|
||||
}
|
||||
|
||||
logger.debug("Starting spam detection orchestration...")
|
||||
|
||||
# Start the orchestration with the email payload
|
||||
instance_id = client.schedule_new_orchestration( # type: ignore
|
||||
orchestrator="spam_detection_orchestration",
|
||||
input=payload,
|
||||
)
|
||||
|
||||
logger.debug(f"Orchestration started with instance ID: {instance_id}")
|
||||
logger.debug("Waiting for orchestration to complete...")
|
||||
|
||||
# Retrieve the final state
|
||||
metadata = client.wait_for_orchestration_completion(
|
||||
instance_id=instance_id,
|
||||
timeout=300
|
||||
)
|
||||
|
||||
if metadata and metadata.runtime_status.name == "COMPLETED":
|
||||
result = metadata.serialized_output
|
||||
|
||||
logger.debug("Orchestration completed successfully!")
|
||||
|
||||
# Parse and display the result
|
||||
if result:
|
||||
# Remove quotes if present
|
||||
if result.startswith('"') and result.endswith('"'):
|
||||
result = result[1:-1]
|
||||
logger.info(f"Result: {result}")
|
||||
|
||||
elif metadata:
|
||||
logger.error(f"Orchestration ended with status: {metadata.runtime_status.name}")
|
||||
if metadata.serialized_output:
|
||||
logger.error(f"Output: {metadata.serialized_output}")
|
||||
else:
|
||||
logger.error("Orchestration did not complete within the timeout period")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
"""Main entry point for the client application."""
|
||||
logger.debug("Starting Durable Task Spam Detection Orchestration Client...")
|
||||
|
||||
# Create client using helper function
|
||||
client = get_client()
|
||||
|
||||
try:
|
||||
# Test with a legitimate email
|
||||
logger.info("TEST 1: Legitimate Email")
|
||||
|
||||
run_client(
|
||||
client,
|
||||
email_id="email-001",
|
||||
email_content="Hello! I wanted to reach out about our upcoming project meeting scheduled for next week."
|
||||
)
|
||||
|
||||
# Test with a spam email
|
||||
logger.info("TEST 2: Spam Email")
|
||||
|
||||
run_client(
|
||||
client,
|
||||
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!"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.exception(f"Error during orchestration: {e}")
|
||||
finally:
|
||||
logger.debug("")
|
||||
logger.debug("Client shutting down")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
# Agent Framework packages (installing from local package until a package is published)
|
||||
-e ../../../../
|
||||
-e ../../../../packages/durabletask
|
||||
|
||||
# Azure authentication
|
||||
azure-identity
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
"""Multi-Agent Orchestration with Conditionals Sample - Durable Task Integration
|
||||
|
||||
This sample demonstrates conditional orchestration logic with two agents:
|
||||
- SpamDetectionAgent: Analyzes emails for spam content
|
||||
- EmailAssistantAgent: Drafts professional responses to legitimate emails
|
||||
|
||||
The orchestration branches based on spam detection results, calling different
|
||||
activity functions to handle spam or send legitimate email responses.
|
||||
|
||||
Prerequisites:
|
||||
- Set AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_CHAT_DEPLOYMENT_NAME
|
||||
(plus AZURE_OPENAI_API_KEY or Azure CLI authentication)
|
||||
- Durable Task Scheduler must be running (e.g., using Docker)
|
||||
|
||||
To run this sample:
|
||||
python sample.py
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Import helper functions from worker and client modules
|
||||
from client import get_client, run_client
|
||||
from worker import get_worker, setup_worker
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
force=True
|
||||
)
|
||||
logger = logging.getLogger()
|
||||
|
||||
|
||||
def main():
|
||||
"""Main entry point - runs both worker and client in single process."""
|
||||
logger.debug("Starting Durable Task Spam Detection Orchestration Sample (Combined Worker + Client)...")
|
||||
|
||||
silent_handler = logging.NullHandler()
|
||||
# Create and start the worker using helper function and context manager
|
||||
with get_worker(log_handler=silent_handler) as dts_worker:
|
||||
# Register agents, orchestrations, and activities using helper function
|
||||
setup_worker(dts_worker)
|
||||
|
||||
# Start the worker
|
||||
dts_worker.start()
|
||||
logger.debug("Worker started and listening for requests...")
|
||||
|
||||
# Create the client using helper function
|
||||
client = get_client(log_handler=silent_handler)
|
||||
logger.debug("CLIENT: Starting orchestration tests...")
|
||||
|
||||
try:
|
||||
# Test 1: Legitimate email
|
||||
# logger.info("TEST 1: Legitimate Email")
|
||||
|
||||
run_client(
|
||||
client,
|
||||
email_id="email-001",
|
||||
email_content="Hello! I wanted to reach out about our upcoming project meeting scheduled for next week."
|
||||
)
|
||||
|
||||
# Test 2: Spam email
|
||||
logger.info("TEST 2: Spam Email")
|
||||
|
||||
run_client(
|
||||
client,
|
||||
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!"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.exception(f"Error during sample execution: {e}")
|
||||
|
||||
logger.debug("Sample completed. Worker shutting down...")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
load_dotenv()
|
||||
main()
|
||||
+302
@@ -0,0 +1,302 @@
|
||||
"""Worker process for hosting spam detection and email assistant agents with conditional orchestration.
|
||||
|
||||
This worker registers two domain-specific agents (spam detector and email assistant) and an
|
||||
orchestration function that routes execution based on spam detection results. Activity functions
|
||||
handle side effects (spam handling and email sending).
|
||||
|
||||
Prerequisites:
|
||||
- Set AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_CHAT_DEPLOYMENT_NAME
|
||||
(plus AZURE_OPENAI_API_KEY or Azure CLI authentication)
|
||||
- Start a Durable Task Scheduler (e.g., using Docker)
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Generator
|
||||
import logging
|
||||
import os
|
||||
from typing import Any, cast
|
||||
|
||||
from agent_framework import AgentRunResponse
|
||||
from agent_framework.azure import AzureOpenAIChatClient
|
||||
from agent_framework_durabletask import DurableAIAgentOrchestrationContext, DurableAIAgentWorker
|
||||
from azure.identity import AzureCliCredential, DefaultAzureCredential
|
||||
from durabletask.task import ActivityContext, OrchestrationContext, Task
|
||||
from durabletask.azuremanaged.worker import DurableTaskSchedulerWorker
|
||||
from pydantic import BaseModel, ValidationError
|
||||
|
||||
# Configure logging
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Agent names
|
||||
SPAM_AGENT_NAME = "SpamDetectionAgent"
|
||||
EMAIL_AGENT_NAME = "EmailAssistantAgent"
|
||||
|
||||
|
||||
class SpamDetectionResult(BaseModel):
|
||||
"""Result from spam detection agent."""
|
||||
is_spam: bool
|
||||
reason: str
|
||||
|
||||
|
||||
class EmailResponse(BaseModel):
|
||||
"""Result from email assistant agent."""
|
||||
response: str
|
||||
|
||||
|
||||
class EmailPayload(BaseModel):
|
||||
"""Input payload for the orchestration."""
|
||||
email_id: str
|
||||
email_content: str
|
||||
|
||||
|
||||
def create_spam_agent():
|
||||
"""Create the Spam Detection agent using Azure OpenAI.
|
||||
|
||||
Returns:
|
||||
AgentProtocol: The configured Spam Detection agent
|
||||
"""
|
||||
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
|
||||
name=SPAM_AGENT_NAME,
|
||||
instructions="You are a spam detection assistant that identifies spam emails.",
|
||||
)
|
||||
|
||||
|
||||
def create_email_agent():
|
||||
"""Create the Email Assistant agent using Azure OpenAI.
|
||||
|
||||
Returns:
|
||||
AgentProtocol: The configured Email Assistant agent
|
||||
"""
|
||||
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
|
||||
name=EMAIL_AGENT_NAME,
|
||||
instructions="You are an email assistant that helps users draft responses to emails with professionalism.",
|
||||
)
|
||||
|
||||
|
||||
def handle_spam_email(context: ActivityContext, reason: str) -> str:
|
||||
"""Activity function to handle spam emails.
|
||||
|
||||
Args:
|
||||
context: The activity context
|
||||
reason: The reason why the email was marked as spam
|
||||
|
||||
Returns:
|
||||
str: Confirmation message
|
||||
"""
|
||||
logger.debug(f"[Activity] Handling spam email: {reason}")
|
||||
return f"Email marked as spam: {reason}"
|
||||
|
||||
|
||||
def send_email(context: ActivityContext, message: str) -> str:
|
||||
"""Activity function to send emails.
|
||||
|
||||
Args:
|
||||
context: The activity context
|
||||
message: The email message to send
|
||||
|
||||
Returns:
|
||||
str: Confirmation message
|
||||
"""
|
||||
logger.debug(f"[Activity] Sending email: {message[:50]}...")
|
||||
return f"Email sent: {message}"
|
||||
|
||||
|
||||
def spam_detection_orchestration(context: OrchestrationContext, payload_raw: Any) -> Generator[Task[Any], Any, str]:
|
||||
"""Orchestration that detects spam and conditionally drafts email responses.
|
||||
|
||||
This orchestration:
|
||||
1. Validates the input payload
|
||||
2. Runs the spam detection agent
|
||||
3. If spam: calls handle_spam_email activity
|
||||
4. If legitimate: runs email assistant agent and calls send_email activity
|
||||
|
||||
Args:
|
||||
context: The orchestration context
|
||||
payload_raw: The input payload dictionary
|
||||
|
||||
Returns:
|
||||
str: Result message from activity functions
|
||||
"""
|
||||
logger.debug("[Orchestration] Starting spam detection orchestration")
|
||||
|
||||
# Validate input
|
||||
if not isinstance(payload_raw, dict):
|
||||
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
|
||||
|
||||
logger.debug(f"[Orchestration] Processing email ID: {payload.email_id}")
|
||||
|
||||
# Wrap the orchestration context to access agents
|
||||
agent_context = DurableAIAgentOrchestrationContext(context)
|
||||
|
||||
# Get spam detection agent
|
||||
spam_agent = agent_context.get_agent(SPAM_AGENT_NAME)
|
||||
|
||||
# Run spam detection
|
||||
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}"
|
||||
)
|
||||
|
||||
logger.info("[Orchestration] Running spam detection agent: %s", spam_prompt)
|
||||
spam_result_task = spam_agent.run(
|
||||
messages=spam_prompt,
|
||||
response_format=SpamDetectionResult,
|
||||
)
|
||||
|
||||
spam_result_raw: AgentRunResponse = yield spam_result_task
|
||||
spam_result = cast(SpamDetectionResult, spam_result_raw.value)
|
||||
|
||||
logger.info("[Orchestration] Spam detection result: is_spam=%s", spam_result.is_spam)
|
||||
|
||||
# Branch based on spam detection result
|
||||
if spam_result.is_spam:
|
||||
logger.debug("[Orchestration] Email is spam, handling...")
|
||||
result_task: Task[str] = context.call_activity("handle_spam_email", input=spam_result.reason)
|
||||
result: str = yield result_task
|
||||
return result
|
||||
|
||||
# Email is legitimate - draft a response
|
||||
logger.debug("[Orchestration] Email is legitimate, drafting response...")
|
||||
|
||||
email_agent = agent_context.get_agent(EMAIL_AGENT_NAME)
|
||||
|
||||
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}"
|
||||
)
|
||||
|
||||
logger.info("[Orchestration] Running email assistant agent: %s", email_prompt)
|
||||
email_result_task = email_agent.run(
|
||||
messages=email_prompt,
|
||||
response_format=EmailResponse,
|
||||
)
|
||||
|
||||
email_result_raw: AgentRunResponse = yield email_result_task
|
||||
email_result = cast(EmailResponse, email_result_raw.value)
|
||||
|
||||
logger.debug("[Orchestration] Email response drafted, sending...")
|
||||
result_task: Task[str] = context.call_activity("send_email", input=email_result.response)
|
||||
result: str = yield result_task
|
||||
|
||||
logger.info("Sent Email: %s", result)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def get_worker(
|
||||
taskhub: str | None = None,
|
||||
endpoint: str | None = None,
|
||||
log_handler: logging.Handler | None = None
|
||||
) -> DurableTaskSchedulerWorker:
|
||||
"""Create a configured DurableTaskSchedulerWorker.
|
||||
|
||||
Args:
|
||||
taskhub: Task hub name (defaults to TASKHUB env var or "default")
|
||||
endpoint: Scheduler endpoint (defaults to ENDPOINT env var or "http://localhost:8080")
|
||||
log_handler: Optional logging handler for worker logging
|
||||
|
||||
Returns:
|
||||
Configured DurableTaskSchedulerWorker instance
|
||||
"""
|
||||
"""Create a configured DurableTaskSchedulerWorker.
|
||||
|
||||
Args:
|
||||
taskhub: Task hub name (defaults to TASKHUB env var or "default")
|
||||
endpoint: Scheduler endpoint (defaults to ENDPOINT env var or "http://localhost:8080")
|
||||
log_handler: Optional logging handler
|
||||
|
||||
Returns:
|
||||
Configured DurableTaskSchedulerWorker instance
|
||||
"""
|
||||
taskhub_name = taskhub or os.getenv("TASKHUB", "default")
|
||||
endpoint_url = endpoint or os.getenv("ENDPOINT", "http://localhost:8080")
|
||||
|
||||
logger.debug(f"Using taskhub: {taskhub_name}")
|
||||
logger.debug(f"Using endpoint: {endpoint_url}")
|
||||
|
||||
credential = None if endpoint_url == "http://localhost:8080" else DefaultAzureCredential()
|
||||
|
||||
return DurableTaskSchedulerWorker(
|
||||
host_address=endpoint_url,
|
||||
secure_channel=endpoint_url != "http://localhost:8080",
|
||||
taskhub=taskhub_name,
|
||||
token_credential=credential,
|
||||
log_handler=log_handler
|
||||
)
|
||||
|
||||
|
||||
def setup_worker(worker: DurableTaskSchedulerWorker) -> DurableAIAgentWorker:
|
||||
"""Set up the worker with agents, orchestrations, and activities registered.
|
||||
|
||||
Args:
|
||||
worker: The DurableTaskSchedulerWorker instance
|
||||
|
||||
Returns:
|
||||
DurableAIAgentWorker with agents, orchestrations, and activities registered
|
||||
"""
|
||||
# Wrap it with the agent worker
|
||||
agent_worker = DurableAIAgentWorker(worker)
|
||||
|
||||
# Create and register both agents
|
||||
logger.debug("Creating and registering agents...")
|
||||
spam_agent = create_spam_agent()
|
||||
email_agent = create_email_agent()
|
||||
|
||||
agent_worker.add_agent(spam_agent)
|
||||
agent_worker.add_agent(email_agent)
|
||||
|
||||
logger.debug(f"✓ Registered agents: {spam_agent.name}, {email_agent.name}")
|
||||
|
||||
# Register activity functions
|
||||
logger.debug("Registering activity functions...")
|
||||
worker.add_activity(handle_spam_email) # type: ignore[arg-type]
|
||||
worker.add_activity(send_email) # type: ignore[arg-type]
|
||||
logger.debug(f"✓ Registered activity: handle_spam_email")
|
||||
logger.debug(f"✓ Registered activity: send_email")
|
||||
|
||||
# Register the orchestration function
|
||||
logger.debug("Registering orchestration function...")
|
||||
worker.add_orchestrator(spam_detection_orchestration) # type: ignore[arg-type]
|
||||
logger.debug(f"✓ Registered orchestration: {spam_detection_orchestration.__name__}")
|
||||
|
||||
return agent_worker
|
||||
|
||||
|
||||
async def main():
|
||||
"""Main entry point for the worker process."""
|
||||
logger.debug("Starting Durable Task Spam Detection Worker with Orchestration...")
|
||||
|
||||
# Create a worker using the helper function
|
||||
worker = get_worker()
|
||||
|
||||
# Setup worker with agents, orchestrations, and activities
|
||||
setup_worker(worker)
|
||||
|
||||
logger.debug("Worker is ready and listening for requests...")
|
||||
logger.debug("Press Ctrl+C to stop.")
|
||||
|
||||
try:
|
||||
# Start the worker (this blocks until stopped)
|
||||
worker.start()
|
||||
|
||||
# Keep the worker running
|
||||
while True:
|
||||
await asyncio.sleep(1)
|
||||
except KeyboardInterrupt:
|
||||
logger.debug("Worker shutdown initiated")
|
||||
|
||||
logger.debug("Worker stopped")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
# Single-Agent Orchestration with Human-in-the-Loop (HITL)
|
||||
|
||||
This sample demonstrates the human-in-the-loop pattern where a WriterAgent generates content and waits for human approval before publishing. The orchestration handles external events, timeouts, and iterative refinement based on feedback.
|
||||
|
||||
## Key Concepts Demonstrated
|
||||
|
||||
- Human-in-the-loop workflow with orchestration pausing for external approval/rejection events.
|
||||
- External event handling using `wait_for_external_event()` to receive human input.
|
||||
- Timeout management with `when_any()` to race between approval event and timeout.
|
||||
- Iterative refinement where agent regenerates content based on reviewer feedback.
|
||||
- Structured outputs using Pydantic models with `response_format` for type-safe agent responses.
|
||||
- Activity functions for notifications and publishing as separate side effects.
|
||||
- Long-running orchestrations maintaining state across multiple interactions.
|
||||
|
||||
## Environment Setup
|
||||
|
||||
See the [README.md](../README.md) file in the parent directory for more information on how to configure the environment, including how to install and run common sample dependencies.
|
||||
|
||||
## Running the Sample
|
||||
|
||||
With the environment setup, you can run the sample using the combined approach or separate worker and client processes:
|
||||
|
||||
**Option 1: Combined (Recommended for Testing)**
|
||||
|
||||
```bash
|
||||
cd samples/getting_started/durabletask/07_single_agent_orchestration_hitl
|
||||
python sample.py
|
||||
```
|
||||
|
||||
**Option 2: Separate Processes**
|
||||
|
||||
Start the worker in one terminal:
|
||||
|
||||
```bash
|
||||
python worker.py
|
||||
```
|
||||
|
||||
In a new terminal, run the client:
|
||||
|
||||
```bash
|
||||
python client.py
|
||||
```
|
||||
|
||||
The sample runs two test scenarios:
|
||||
|
||||
**Test 1: Immediate Approval**
|
||||
```
|
||||
Topic: The benefits of cloud computing
|
||||
[WriterAgent generates content]
|
||||
[Notification sent: Please review the content]
|
||||
[Client sends approval]
|
||||
✓ Content published successfully
|
||||
```
|
||||
|
||||
**Test 2: Rejection with Feedback, Then Approval**
|
||||
```
|
||||
Topic: The future of artificial intelligence
|
||||
[WriterAgent generates initial content]
|
||||
[Notification sent: Please review the content]
|
||||
[Client sends rejection with feedback: "Make it more technical..."]
|
||||
[WriterAgent regenerates content with feedback]
|
||||
[Notification sent: Please review the revised content]
|
||||
[Client sends approval]
|
||||
✓ Revised content published successfully
|
||||
```
|
||||
|
||||
## How It Works
|
||||
|
||||
1. **Initial Generation**: WriterAgent creates content based on the topic.
|
||||
2. **Review Loop** (up to max_review_attempts):
|
||||
- Activity notifies user for approval
|
||||
- Orchestration waits for approval event OR timeout
|
||||
- **If approved**: Publishes content and returns
|
||||
- **If rejected**: Incorporates feedback and regenerates
|
||||
- **If timeout**: Raises TimeoutError
|
||||
3. **Completion**: Returns published content or error.
|
||||
|
||||
## Viewing Agent State
|
||||
|
||||
You can view the state of the WriterAgent and orchestration in the Durable Task Scheduler dashboard:
|
||||
|
||||
1. Open your browser and navigate to `http://localhost:8082`
|
||||
2. In the dashboard, you can view:
|
||||
- Orchestration instance status and pending events
|
||||
- WriterAgent entity state and conversation threads
|
||||
- Activity execution logs
|
||||
- External event history
|
||||
+308
@@ -0,0 +1,308 @@
|
||||
"""Client application for starting a human-in-the-loop content generation orchestration.
|
||||
|
||||
This client connects to the Durable Task Scheduler and demonstrates the HITL pattern
|
||||
by starting an orchestration, sending approval/rejection events, and monitoring progress.
|
||||
|
||||
Prerequisites:
|
||||
- The worker must be running with the agent, orchestration, and activities registered
|
||||
- Set AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_CHAT_DEPLOYMENT_NAME
|
||||
(plus AZURE_OPENAI_API_KEY or Azure CLI authentication)
|
||||
- Durable Task Scheduler must be running
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
|
||||
from azure.identity import DefaultAzureCredential
|
||||
from durabletask.azuremanaged.client import DurableTaskSchedulerClient
|
||||
from durabletask.client import OrchestrationState
|
||||
|
||||
# Configure logging
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Constants
|
||||
HUMAN_APPROVAL_EVENT = "HumanApproval"
|
||||
|
||||
|
||||
def get_client(
|
||||
taskhub: str | None = None,
|
||||
endpoint: str | None = None,
|
||||
log_handler: logging.Handler | None = None
|
||||
) -> DurableTaskSchedulerClient:
|
||||
"""Create a configured DurableTaskSchedulerClient.
|
||||
|
||||
Args:
|
||||
taskhub: Task hub name (defaults to TASKHUB env var or "default")
|
||||
endpoint: Scheduler endpoint (defaults to ENDPOINT env var or "http://localhost:8080")
|
||||
log_handler: Optional logging handler for client logging
|
||||
|
||||
Returns:
|
||||
Configured DurableTaskSchedulerClient instance
|
||||
"""
|
||||
taskhub_name = taskhub or os.getenv("TASKHUB", "default")
|
||||
endpoint_url = endpoint or os.getenv("ENDPOINT", "http://localhost:8080")
|
||||
|
||||
logger.debug(f"Using taskhub: {taskhub_name}")
|
||||
logger.debug(f"Using endpoint: {endpoint_url}")
|
||||
|
||||
credential = None if endpoint_url == "http://localhost:8080" else DefaultAzureCredential()
|
||||
|
||||
return DurableTaskSchedulerClient(
|
||||
host_address=endpoint_url,
|
||||
secure_channel=endpoint_url != "http://localhost:8080",
|
||||
taskhub=taskhub_name,
|
||||
token_credential=credential,
|
||||
log_handler=log_handler
|
||||
)
|
||||
|
||||
|
||||
def _log_completion_result(
|
||||
metadata: OrchestrationState | None,
|
||||
) -> None:
|
||||
"""Log the orchestration completion result.
|
||||
|
||||
Args:
|
||||
metadata: The orchestration metadata
|
||||
"""
|
||||
if metadata and metadata.runtime_status.name == "COMPLETED":
|
||||
result = metadata.serialized_output
|
||||
|
||||
logger.debug(f"Orchestration completed successfully!")
|
||||
|
||||
if result:
|
||||
try:
|
||||
result_dict = json.loads(result)
|
||||
logger.info("Final Result: %s", json.dumps(result_dict, indent=2))
|
||||
except json.JSONDecodeError:
|
||||
logger.debug(f"Result: {result}")
|
||||
|
||||
elif metadata:
|
||||
logger.error(f"Orchestration ended with status: {metadata.runtime_status.name}")
|
||||
if metadata.serialized_output:
|
||||
logger.error(f"Output: {metadata.serialized_output}")
|
||||
else:
|
||||
logger.error("Orchestration did not complete within the timeout period")
|
||||
|
||||
|
||||
def _wait_and_log_completion(
|
||||
client: DurableTaskSchedulerClient,
|
||||
instance_id: str,
|
||||
timeout: int = 60
|
||||
) -> None:
|
||||
"""Wait for orchestration completion and log the result.
|
||||
|
||||
Args:
|
||||
client: The DurableTaskSchedulerClient instance
|
||||
instance_id: The orchestration instance ID
|
||||
timeout: Maximum time to wait for completion in seconds
|
||||
"""
|
||||
logger.debug("Waiting for orchestration to complete...")
|
||||
metadata = client.wait_for_orchestration_completion(
|
||||
instance_id=instance_id,
|
||||
timeout=timeout
|
||||
)
|
||||
|
||||
_log_completion_result(metadata)
|
||||
|
||||
|
||||
def send_approval(
|
||||
client: DurableTaskSchedulerClient,
|
||||
instance_id: str,
|
||||
approved: bool,
|
||||
feedback: str = ""
|
||||
) -> None:
|
||||
"""Send approval or rejection event to the orchestration.
|
||||
|
||||
Args:
|
||||
client: The DurableTaskSchedulerClient instance
|
||||
instance_id: The orchestration instance ID
|
||||
approved: Whether to approve or reject
|
||||
feedback: Optional feedback message (used when rejected)
|
||||
"""
|
||||
approval_data = {
|
||||
"approved": approved,
|
||||
"feedback": feedback
|
||||
}
|
||||
|
||||
logger.debug(f"Sending {'APPROVAL' if approved else 'REJECTION'} to instance {instance_id}")
|
||||
if feedback:
|
||||
logger.debug(f"Feedback: {feedback}")
|
||||
|
||||
# Raise the external event
|
||||
client.raise_orchestration_event(
|
||||
instance_id=instance_id,
|
||||
event_name=HUMAN_APPROVAL_EVENT,
|
||||
data=approval_data
|
||||
)
|
||||
|
||||
logger.debug("Event sent successfully")
|
||||
|
||||
|
||||
def wait_for_notification(
|
||||
client: DurableTaskSchedulerClient,
|
||||
instance_id: str,
|
||||
timeout_seconds: int = 10
|
||||
) -> bool:
|
||||
"""Wait for the orchestration to reach a notification point.
|
||||
|
||||
Polls the orchestration status until it appears to be waiting for approval.
|
||||
|
||||
Args:
|
||||
client: The DurableTaskSchedulerClient instance
|
||||
instance_id: The orchestration instance ID
|
||||
timeout_seconds: Maximum time to wait
|
||||
|
||||
Returns:
|
||||
True if notification detected, False if timeout
|
||||
"""
|
||||
logger.debug("Waiting for orchestration to reach notification point...")
|
||||
|
||||
start_time = time.time()
|
||||
while time.time() - start_time < timeout_seconds:
|
||||
try:
|
||||
metadata = client.get_orchestration_state(
|
||||
instance_id=instance_id,
|
||||
)
|
||||
|
||||
if metadata:
|
||||
# Check if we're waiting for approval by examining custom status
|
||||
if metadata.serialized_custom_status:
|
||||
try:
|
||||
custom_status = json.loads(metadata.serialized_custom_status)
|
||||
# Handle both string and dict custom status
|
||||
status_str = custom_status if isinstance(custom_status, str) else str(custom_status)
|
||||
if status_str.lower().startswith("requesting human feedback"):
|
||||
logger.debug("Orchestration is requesting human feedback")
|
||||
return True
|
||||
except (json.JSONDecodeError, AttributeError):
|
||||
# If it's not JSON, treat as plain string
|
||||
if metadata.serialized_custom_status.lower().startswith("requesting human feedback"):
|
||||
logger.debug("Orchestration is requesting human feedback")
|
||||
return True
|
||||
|
||||
# Check for terminal states
|
||||
if metadata.runtime_status.name == "COMPLETED":
|
||||
logger.debug("Orchestration already completed")
|
||||
return False
|
||||
elif metadata.runtime_status.name == "FAILED":
|
||||
logger.error("Orchestration failed")
|
||||
return False
|
||||
except Exception as e:
|
||||
logger.debug(f"Status check: {e}")
|
||||
|
||||
time.sleep(1)
|
||||
|
||||
logger.warning("Timeout waiting for notification")
|
||||
return False
|
||||
|
||||
|
||||
def run_interactive_client(client: DurableTaskSchedulerClient) -> None:
|
||||
"""Run an interactive client that prompts for user input and handles approval workflow.
|
||||
|
||||
Args:
|
||||
client: The DurableTaskSchedulerClient instance
|
||||
"""
|
||||
# Get user inputs
|
||||
logger.debug("Content Generation - Human-in-the-Loop")
|
||||
|
||||
topic = input("Enter the topic for content generation: ").strip()
|
||||
if not topic:
|
||||
topic = "The benefits of cloud computing"
|
||||
logger.info(f"Using default topic: {topic}")
|
||||
|
||||
max_attempts_str = input("Enter max review attempts (default: 3): ").strip()
|
||||
max_review_attempts = int(max_attempts_str) if max_attempts_str else 3
|
||||
|
||||
timeout_hours_str = input("Enter approval timeout in hours (default: 5): ").strip()
|
||||
timeout_hours = float(timeout_hours_str) if timeout_hours_str else 5.0
|
||||
approval_timeout_seconds = int(timeout_hours * 3600)
|
||||
|
||||
payload = {
|
||||
"topic": topic,
|
||||
"max_review_attempts": max_review_attempts,
|
||||
"approval_timeout_seconds": approval_timeout_seconds
|
||||
}
|
||||
|
||||
logger.debug(f"Configuration: Topic={topic}, Max attempts={max_review_attempts}, Timeout={timeout_hours}h")
|
||||
|
||||
# Start the orchestration
|
||||
logger.debug("Starting content generation orchestration...")
|
||||
instance_id = client.schedule_new_orchestration( # type: ignore
|
||||
orchestrator="content_generation_hitl_orchestration",
|
||||
input=payload,
|
||||
)
|
||||
|
||||
logger.info(f"Orchestration started with instance ID: {instance_id}")
|
||||
|
||||
# Review loop
|
||||
attempt = 1
|
||||
while attempt <= max_review_attempts:
|
||||
logger.info(f"Review Attempt {attempt}/{max_review_attempts}")
|
||||
|
||||
# Wait for orchestration to reach notification point
|
||||
logger.debug("Waiting for content generation...")
|
||||
if not wait_for_notification(client, instance_id, timeout_seconds=120):
|
||||
logger.error("Failed to receive notification. Orchestration may have completed or failed.")
|
||||
break
|
||||
|
||||
logger.info("Content is ready for review! Please review the content in the worker logs.")
|
||||
|
||||
# Get user decision
|
||||
while True:
|
||||
decision = input("Do you approve this content? (yes/no): ").strip().lower()
|
||||
if decision in ['yes', 'y', 'no', 'n']:
|
||||
break
|
||||
logger.info("Please enter 'yes' or 'no'")
|
||||
|
||||
approved = decision in ['yes', 'y']
|
||||
|
||||
if approved:
|
||||
logger.debug("Sending approval...")
|
||||
send_approval(client, instance_id, approved=True)
|
||||
logger.info("Approval sent. Waiting for orchestration to complete...")
|
||||
_wait_and_log_completion(client, instance_id, timeout=60)
|
||||
break
|
||||
else:
|
||||
feedback = input("Enter feedback for improvement: ").strip()
|
||||
if not feedback:
|
||||
feedback = "Please revise the content."
|
||||
|
||||
logger.debug("Sending rejection with feedback...")
|
||||
send_approval(client, instance_id, approved=False, feedback=feedback)
|
||||
logger.info("Rejection sent. Content will be regenerated...")
|
||||
|
||||
attempt += 1
|
||||
|
||||
if attempt > max_review_attempts:
|
||||
logger.info(f"Maximum review attempts ({max_review_attempts}) reached.")
|
||||
_wait_and_log_completion(client, instance_id, timeout=30)
|
||||
break
|
||||
|
||||
# Small pause before next iteration
|
||||
time.sleep(2)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
"""Main entry point for the client application."""
|
||||
logger.debug("Starting Durable Task HITL Content Generation Client")
|
||||
|
||||
# Create client using helper function
|
||||
client = get_client()
|
||||
|
||||
try:
|
||||
run_interactive_client(client)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
logger.info("Interrupted by user")
|
||||
except Exception as e:
|
||||
logger.exception(f"Error during orchestration: {e}")
|
||||
finally:
|
||||
logger.debug("Client shutting down")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
# Agent Framework packages (installing from local package until a package is published)
|
||||
-e ../../../../
|
||||
-e ../../../../packages/durabletask
|
||||
|
||||
# Azure authentication
|
||||
azure-identity
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
"""Human-in-the-Loop Orchestration Sample - Durable Task Integration
|
||||
|
||||
This sample demonstrates the HITL pattern with a WriterAgent that generates content
|
||||
and waits for human approval. The orchestration handles:
|
||||
- External event waiting (approval/rejection)
|
||||
- Timeout handling
|
||||
- Iterative refinement based on feedback
|
||||
- Activity functions for notifications and publishing
|
||||
|
||||
Prerequisites:
|
||||
- Set AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_CHAT_DEPLOYMENT_NAME
|
||||
(plus AZURE_OPENAI_API_KEY or Azure CLI authentication)
|
||||
- Durable Task Scheduler must be running (e.g., using Docker)
|
||||
|
||||
To run this sample:
|
||||
python sample.py
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Import helper functions from worker and client modules
|
||||
from client import get_client, run_interactive_client
|
||||
from worker import get_worker, setup_worker
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
force=True
|
||||
)
|
||||
logger = logging.getLogger()
|
||||
|
||||
|
||||
def main():
|
||||
"""Main entry point - runs both worker and client in single process."""
|
||||
logger.debug("Starting Durable Task HITL Content Generation Sample (Combined Worker + Client)...")
|
||||
|
||||
silent_handler = logging.NullHandler()
|
||||
# Create and start the worker using helper function and context manager
|
||||
with get_worker(log_handler=silent_handler) as dts_worker:
|
||||
# Register agent, orchestration, and activities using helper function
|
||||
setup_worker(dts_worker)
|
||||
|
||||
# Start the worker
|
||||
dts_worker.start()
|
||||
logger.debug("Worker started and listening for requests...")
|
||||
|
||||
# Create the client using helper function
|
||||
client = get_client(log_handler=silent_handler)
|
||||
|
||||
try:
|
||||
logger.debug("CLIENT: Starting orchestration tests...")
|
||||
|
||||
run_interactive_client(client)
|
||||
|
||||
except Exception as e:
|
||||
logger.exception(f"Error during sample execution: {e}")
|
||||
|
||||
logger.debug("Sample completed. Worker shutting down...")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
load_dotenv()
|
||||
main()
|
||||
+364
@@ -0,0 +1,364 @@
|
||||
"""Worker process for hosting a writer agent with human-in-the-loop orchestration.
|
||||
|
||||
This worker registers a WriterAgent and an orchestration function that implements
|
||||
a human-in-the-loop review workflow. The orchestration pauses for external events
|
||||
(human approval/rejection) with timeout handling, and iterates based on feedback.
|
||||
|
||||
Prerequisites:
|
||||
- Set AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_CHAT_DEPLOYMENT_NAME
|
||||
(plus AZURE_OPENAI_API_KEY or Azure CLI authentication)
|
||||
- Start a Durable Task Scheduler (e.g., using Docker)
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Generator
|
||||
from datetime import timedelta
|
||||
import logging
|
||||
import os
|
||||
from typing import Any, cast
|
||||
|
||||
from agent_framework import AgentRunResponse
|
||||
from agent_framework.azure import AzureOpenAIChatClient
|
||||
from agent_framework_durabletask import DurableAIAgentOrchestrationContext, DurableAIAgentWorker
|
||||
from azure.identity import AzureCliCredential, DefaultAzureCredential
|
||||
from durabletask.task import ActivityContext, OrchestrationContext, Task, when_any # type: ignore
|
||||
from durabletask.azuremanaged.worker import DurableTaskSchedulerWorker
|
||||
from pydantic import BaseModel, ValidationError
|
||||
|
||||
# Configure logging
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Constants
|
||||
WRITER_AGENT_NAME = "WriterAgent"
|
||||
HUMAN_APPROVAL_EVENT = "HumanApproval"
|
||||
|
||||
|
||||
class ContentGenerationInput(BaseModel):
|
||||
"""Input for content generation orchestration."""
|
||||
topic: str
|
||||
max_review_attempts: int = 3
|
||||
approval_timeout_seconds: float = 300 # 5 minutes for demo (72 hours in production)
|
||||
|
||||
|
||||
class GeneratedContent(BaseModel):
|
||||
"""Structured output from writer agent."""
|
||||
title: str
|
||||
content: str
|
||||
|
||||
|
||||
class HumanApproval(BaseModel):
|
||||
"""Human approval decision."""
|
||||
approved: bool
|
||||
feedback: str = ""
|
||||
|
||||
|
||||
def create_writer_agent():
|
||||
"""Create the Writer agent using Azure OpenAI.
|
||||
|
||||
Returns:
|
||||
AgentProtocol: The configured Writer agent
|
||||
"""
|
||||
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."
|
||||
"Limit response to 300 words or less."
|
||||
)
|
||||
|
||||
return AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
|
||||
name=WRITER_AGENT_NAME,
|
||||
instructions=instructions,
|
||||
)
|
||||
|
||||
|
||||
def notify_user_for_approval(context: ActivityContext, content: dict[str, str]) -> None:
|
||||
"""Activity function to notify user for approval.
|
||||
|
||||
Args:
|
||||
context: The activity context
|
||||
content: The generated content dictionary
|
||||
"""
|
||||
model = GeneratedContent.model_validate(content)
|
||||
logger.info("NOTIFICATION: Please review the following content for approval:")
|
||||
logger.info(f"Title: {model.title or '(untitled)'}")
|
||||
logger.info(f"Content: {model.content}")
|
||||
logger.info("Use the client to send approval or rejection.")
|
||||
|
||||
def publish_content(context: ActivityContext, content: dict[str, str]) -> None:
|
||||
"""Activity function to publish approved content.
|
||||
|
||||
Args:
|
||||
context: The activity context
|
||||
content: The generated content dictionary
|
||||
"""
|
||||
model = GeneratedContent.model_validate(content)
|
||||
logger.info("PUBLISHING: Content has been published successfully:")
|
||||
logger.info(f"Title: {model.title or '(untitled)'}")
|
||||
logger.info(f"Content: {model.content}")
|
||||
|
||||
|
||||
def content_generation_hitl_orchestration(
|
||||
context: OrchestrationContext,
|
||||
payload_raw: Any
|
||||
) -> Generator[Task[Any], Any, dict[str, str]]:
|
||||
"""Human-in-the-loop orchestration for content generation with approval workflow.
|
||||
|
||||
This orchestration:
|
||||
1. Generates initial content using WriterAgent
|
||||
2. Loops up to max_review_attempts times:
|
||||
a. Notifies user for approval
|
||||
b. Waits for approval event or timeout
|
||||
c. If approved: publishes and returns
|
||||
d. If rejected: incorporates feedback and regenerates
|
||||
e. If timeout: raises TimeoutError
|
||||
3. Raises RuntimeError if max attempts exhausted
|
||||
|
||||
Args:
|
||||
context: The orchestration context
|
||||
payload_raw: The input payload
|
||||
|
||||
Returns:
|
||||
dict: Result with published content
|
||||
|
||||
Raises:
|
||||
ValueError: If input is invalid or agent returns no content
|
||||
TimeoutError: If human approval times out
|
||||
RuntimeError: If max review attempts exhausted
|
||||
"""
|
||||
logger.debug("[Orchestration] Starting HITL content generation orchestration")
|
||||
|
||||
# Validate input
|
||||
if not isinstance(payload_raw, dict):
|
||||
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
|
||||
|
||||
logger.debug(f"[Orchestration] Topic: {payload.topic}")
|
||||
logger.debug(f"[Orchestration] Max attempts: {payload.max_review_attempts}")
|
||||
logger.debug(f"[Orchestration] Approval timeout: {payload.approval_timeout_seconds}s")
|
||||
|
||||
# Wrap the orchestration context to access agents
|
||||
agent_context = DurableAIAgentOrchestrationContext(context)
|
||||
|
||||
# Get the writer agent
|
||||
writer = agent_context.get_agent(WRITER_AGENT_NAME)
|
||||
writer_thread = writer.get_new_thread()
|
||||
|
||||
logger.info(f"ThreadID: {writer_thread.session_id}")
|
||||
|
||||
# Generate initial content
|
||||
logger.info("[Orchestration] Generating initial content...")
|
||||
|
||||
initial_response: AgentRunResponse = yield writer.run(
|
||||
messages=f"Write a short article about '{payload.topic}'.",
|
||||
thread=writer_thread,
|
||||
response_format=GeneratedContent,
|
||||
)
|
||||
content = cast(GeneratedContent, initial_response.value)
|
||||
|
||||
if not isinstance(content, GeneratedContent):
|
||||
raise ValueError("Agent returned no content after extraction.")
|
||||
|
||||
logger.debug(f"[Orchestration] Initial content generated: {content.title}")
|
||||
|
||||
# Review loop
|
||||
attempt = 0
|
||||
while attempt < payload.max_review_attempts:
|
||||
attempt += 1
|
||||
logger.debug(f"[Orchestration] Review iteration #{attempt}/{payload.max_review_attempts}")
|
||||
|
||||
context.set_custom_status(f"Requesting human feedback (Attempt {attempt}, timeout {payload.approval_timeout_seconds}s)")
|
||||
|
||||
# Notify user for approval
|
||||
yield context.call_activity(
|
||||
"notify_user_for_approval",
|
||||
input=content.model_dump()
|
||||
)
|
||||
|
||||
logger.debug("[Orchestration] Waiting for human approval or timeout...")
|
||||
|
||||
# Wait for approval event or timeout
|
||||
approval_task: Task[Any] = context.wait_for_external_event(HUMAN_APPROVAL_EVENT) # type: ignore
|
||||
timeout_task: Task[Any] = context.create_timer( # type: ignore
|
||||
context.current_utc_datetime + timedelta(seconds=payload.approval_timeout_seconds)
|
||||
)
|
||||
|
||||
# Race between approval and timeout
|
||||
winner_task = yield when_any([approval_task, timeout_task]) # type: ignore
|
||||
|
||||
if winner_task == approval_task:
|
||||
# Approval received before timeout
|
||||
logger.debug("[Orchestration] Received human approval event")
|
||||
|
||||
context.set_custom_status("Content reviewed by human reviewer.")
|
||||
|
||||
# Parse approval
|
||||
approval_data: Any = approval_task.get_result() # type: ignore
|
||||
logger.debug(f"[Orchestration] Approval data: {approval_data}")
|
||||
|
||||
# Handle different formats of approval_data
|
||||
if isinstance(approval_data, dict):
|
||||
approval = HumanApproval.model_validate(approval_data)
|
||||
elif isinstance(approval_data, str):
|
||||
# Try to parse as boolean-like string
|
||||
lower_data = approval_data.lower().strip()
|
||||
if lower_data in {"true", "yes", "approved", "y", "1"}:
|
||||
approval = HumanApproval(approved=True, feedback="")
|
||||
elif lower_data in {"false", "no", "rejected", "n", "0"}:
|
||||
approval = HumanApproval(approved=False, feedback="")
|
||||
else:
|
||||
approval = HumanApproval(approved=False, feedback=approval_data)
|
||||
else:
|
||||
approval = HumanApproval(approved=False, feedback=str(approval_data)) # type: ignore
|
||||
|
||||
if approval.approved:
|
||||
# Content approved - publish and return
|
||||
logger.debug("[Orchestration] Content approved! Publishing...")
|
||||
context.set_custom_status("Content approved by human reviewer. Publishing...")
|
||||
publish_task: Task[Any] = context.call_activity(
|
||||
"publish_content",
|
||||
input=content.model_dump()
|
||||
)
|
||||
yield publish_task
|
||||
|
||||
logger.debug("[Orchestration] Content published successfully")
|
||||
return {"content": content.content, "title": content.title}
|
||||
|
||||
# Content rejected - incorporate feedback and regenerate
|
||||
logger.debug(f"[Orchestration] Content rejected. Feedback: {approval.feedback}")
|
||||
context.set_custom_status(f"Content rejected by human reviewer. Regenerating...")
|
||||
|
||||
rewrite_prompt = (
|
||||
"The content was rejected by a human reviewer. Please rewrite the article incorporating their feedback.\n\n"
|
||||
f"Human Feedback: {approval.feedback or 'No specific feedback provided.'}"
|
||||
)
|
||||
|
||||
logger.debug("[Orchestration] Regenerating content with feedback...")
|
||||
|
||||
logger.warning(f"Regenerating with ThreadID: {writer_thread.session_id}")
|
||||
|
||||
rewrite_response: AgentRunResponse = yield writer.run(
|
||||
messages=rewrite_prompt,
|
||||
thread=writer_thread,
|
||||
response_format=GeneratedContent,
|
||||
)
|
||||
rewritten_content = cast(GeneratedContent, rewrite_response.value)
|
||||
|
||||
if not isinstance(rewritten_content, GeneratedContent):
|
||||
raise ValueError("Agent returned no content after rewrite.")
|
||||
|
||||
content = rewritten_content
|
||||
logger.debug(f"[Orchestration] Content regenerated: {content.title}")
|
||||
|
||||
else:
|
||||
# Timeout occurred
|
||||
logger.error(f"[Orchestration] Approval timeout after {payload.approval_timeout_seconds}s")
|
||||
|
||||
raise TimeoutError(
|
||||
f"Human approval timed out after {payload.approval_timeout_seconds} second(s)."
|
||||
)
|
||||
|
||||
# Max attempts exhausted
|
||||
raise RuntimeError(
|
||||
f"Content could not be approved after {payload.max_review_attempts} iteration(s)."
|
||||
)
|
||||
|
||||
|
||||
def get_worker(
|
||||
taskhub: str | None = None,
|
||||
endpoint: str | None = None,
|
||||
log_handler: logging.Handler | None = None
|
||||
) -> DurableTaskSchedulerWorker:
|
||||
"""Create a configured DurableTaskSchedulerWorker.
|
||||
|
||||
Args:
|
||||
taskhub: Task hub name (defaults to TASKHUB env var or "default")
|
||||
endpoint: Scheduler endpoint (defaults to ENDPOINT env var or "http://localhost:8080")
|
||||
log_handler: Optional logging handler for worker logging
|
||||
|
||||
Returns:
|
||||
Configured DurableTaskSchedulerWorker instance
|
||||
"""
|
||||
taskhub_name = taskhub or os.getenv("TASKHUB", "default")
|
||||
endpoint_url = endpoint or os.getenv("ENDPOINT", "http://localhost:8080")
|
||||
|
||||
logger.debug(f"Using taskhub: {taskhub_name}")
|
||||
logger.debug(f"Using endpoint: {endpoint_url}")
|
||||
|
||||
credential = None if endpoint_url == "http://localhost:8080" else DefaultAzureCredential()
|
||||
|
||||
return DurableTaskSchedulerWorker(
|
||||
host_address=endpoint_url,
|
||||
secure_channel=endpoint_url != "http://localhost:8080",
|
||||
taskhub=taskhub_name,
|
||||
token_credential=credential,
|
||||
log_handler=log_handler
|
||||
)
|
||||
|
||||
|
||||
def setup_worker(worker: DurableTaskSchedulerWorker) -> DurableAIAgentWorker:
|
||||
"""Set up the worker with agents, orchestrations, and activities registered.
|
||||
|
||||
Args:
|
||||
worker: The DurableTaskSchedulerWorker instance
|
||||
|
||||
Returns:
|
||||
DurableAIAgentWorker with agents, orchestrations, and activities registered
|
||||
"""
|
||||
# Wrap it with the agent worker
|
||||
agent_worker = DurableAIAgentWorker(worker)
|
||||
|
||||
# Create and register the writer agent
|
||||
logger.debug("Creating and registering Writer agent...")
|
||||
writer_agent = create_writer_agent()
|
||||
agent_worker.add_agent(writer_agent)
|
||||
|
||||
logger.debug(f"✓ Registered agent: {writer_agent.name}")
|
||||
|
||||
# Register activity functions
|
||||
logger.debug("Registering activity functions...")
|
||||
worker.add_activity(notify_user_for_approval) # type: ignore
|
||||
worker.add_activity(publish_content) # type: ignore
|
||||
logger.debug(f"✓ Registered activity: notify_user_for_approval")
|
||||
logger.debug(f"✓ Registered activity: publish_content")
|
||||
|
||||
# Register the orchestration function
|
||||
logger.debug("Registering orchestration function...")
|
||||
worker.add_orchestrator(content_generation_hitl_orchestration) # type: ignore
|
||||
logger.debug(f"✓ Registered orchestration: {content_generation_hitl_orchestration.__name__}")
|
||||
|
||||
return agent_worker
|
||||
|
||||
|
||||
async def main():
|
||||
"""Main entry point for the worker process."""
|
||||
logger.debug("Starting Durable Task HITL Content Generation Worker...")
|
||||
|
||||
# Create a worker using the helper function
|
||||
worker = get_worker()
|
||||
|
||||
# Setup worker with agents, orchestrations, and activities
|
||||
setup_worker(worker)
|
||||
|
||||
logger.debug("Worker is ready and listening for requests...")
|
||||
logger.debug("Press Ctrl+C to stop.")
|
||||
|
||||
try:
|
||||
# Start the worker (this blocks until stopped)
|
||||
worker.start()
|
||||
|
||||
# Keep the worker running
|
||||
while True:
|
||||
await asyncio.sleep(1)
|
||||
except KeyboardInterrupt:
|
||||
logger.debug("Worker shutdown initiated")
|
||||
|
||||
logger.debug("Worker stopped")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -2,9 +2,17 @@
|
||||
|
||||
This directory contains samples for durable agent hosting using the Durable Task Scheduler. These samples demonstrate the worker-client architecture pattern, enabling distributed agent execution with persistent conversation state.
|
||||
|
||||
- **[01_single_agent](01_single_agent/)**: A sample that demonstrates how to host a single conversational agent using the Durable Task Scheduler and interact with it via a client.
|
||||
- **[04_single_agent_orchestration_chaining](04_single_agent_orchestration_chaining/)**: A sample that demonstrates how to chain multiple invocations of the same agent using a durable orchestration.
|
||||
- **[05_multi_agent_orchestration_concurrency](05_multi_agent_orchestration_concurrency/)**: A sample that demonstrates how to host multiple agents and run them concurrently using a durable orchestration.
|
||||
## Sample Catalog
|
||||
|
||||
### Basic Patterns
|
||||
- **[01_single_agent](01_single_agent/)**: Host a single conversational agent and interact with it via a client. Demonstrates basic worker-client architecture and agent state management.
|
||||
- **[02_multi_agent](02_multi_agent/)**: Host multiple domain-specific agents (physicist and chemist) and route requests to the appropriate agent based on the question topic.
|
||||
|
||||
### Orchestration Patterns
|
||||
- **[04_single_agent_orchestration_chaining](04_single_agent_orchestration_chaining/)**: Chain multiple invocations of the same agent using durable orchestration, preserving conversation context across sequential runs.
|
||||
- **[05_multi_agent_orchestration_concurrency](05_multi_agent_orchestration_concurrency/)**: Run multiple agents concurrently within an orchestration, aggregating their responses in parallel.
|
||||
- **[06_multi_agent_orchestration_conditionals](06_multi_agent_orchestration_conditionals/)**: Implement conditional branching in orchestrations with spam detection and email assistant agents. Demonstrates structured outputs with Pydantic models and activity functions for side effects.
|
||||
- **[07_single_agent_orchestration_hitl](07_single_agent_orchestration_hitl/)**: Human-in-the-loop pattern with external event handling, timeouts, and iterative refinement based on human feedback. Shows long-running workflows with external interactions.
|
||||
|
||||
## Running the Samples
|
||||
|
||||
@@ -78,20 +86,35 @@ The DTS dashboard will be available at `http://localhost:8082`.
|
||||
|
||||
Each sample reads configuration from environment variables. You'll need to set the following environment variables:
|
||||
|
||||
Bash (Linux/macOS/WSL):
|
||||
|
||||
```bash
|
||||
export AZURE_OPENAI_ENDPOINT="https://your-resource.openai.azure.com/"
|
||||
export AZURE_OPENAI_CHAT_DEPLOYMENT_NAME="your-deployment-name"
|
||||
```
|
||||
|
||||
PowerShell:
|
||||
|
||||
```powershell
|
||||
$env:AZURE_OPENAI_ENDPOINT="https://your-resource.openai.azure.com/"
|
||||
$env:AZURE_OPENAI_CHAT_DEPLOYMENT_NAME="your-deployment-name"
|
||||
```
|
||||
|
||||
### Installing Dependencies
|
||||
|
||||
Navigate to the sample directory and install dependencies:
|
||||
Navigate to the sample directory and install dependencies. For example:
|
||||
|
||||
```bash
|
||||
cd samples/getting_started/durabletask/01_single_agent
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
If you're using `uv` for package management:
|
||||
|
||||
```bash
|
||||
uv pip install -r requirements.txt
|
||||
```
|
||||
|
||||
### Running the Samples
|
||||
|
||||
Each sample follows a worker-client architecture. Most samples provide separate `worker.py` and `client.py` files, though some include a combined `sample.py` for convenience.
|
||||
|
||||
Reference in New Issue
Block a user