mirror of
https://github.com/microsoft/agent-framework.git
synced 2026-06-16 21:04:09 +08:00
b05fc9e849
* Initial plan * Add load_dotenv() to 303 Python samples for environment variable loading Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com> * Update SAMPLE_GUIDELINES.md to document load_dotenv() requirement Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com> * Update samples README.md to document .env file usage Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com> * Run ruff format on all changed sample files Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com> * Clarify load_dotenv() usage in README - local dev vs production Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com> * Remove deprecated getting_started folder as requested Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com> * Document env_file_path parameter for per-client configuration Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com> * Merge main branch to resolve conflicts Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com> * Fix run_evaluation.py file that was empty in merge commit Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com> * Remove dotnet changes from merge - out of scope for this PR Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com> * Remove package and test changes from merge - only sample changes needed Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com> * Remove test_func_utils.py - only sample changes needed Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com> * Revert sample files not in original changeset - keep only load_dotenv additions Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com> * Move load_dotenv() outside snippet tag in 06_host_your_agent.py Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com> * Fix comment placement - move load_dotenv before code comments Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com> * Fix load_dotenv() placement across all samples - after docstring, before code comments Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com> * Merge latest main branch with load_dotenv changes Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com> * Remove non-sample changes from merge - keep only load_dotenv additions Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com> * Revert non-load_dotenv sample changes from merge Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com> * Fix run_evaluation.py - use main's improved version (file already had load_dotenv) Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com> * Manual update * Manual update 2 * Fix Role usage and load_dotenv placement per PR review feedback Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> * Fix Role usage - use string literals not enum attributes Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> * Fix SAMPLE_GUIDELINES.md example - load_dotenv before docstring per guidance Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> * Move load_dotenv() before docstrings in all samples per SAMPLE_GUIDELINES ordering Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> * Address PR review: rename files, fix placement, add session usage, remove note Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> * Update Redis README to reference renamed file redis_history_provider.py Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com> Co-authored-by: Tao Chen <taochen@microsoft.com> Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> Co-authored-by: Eduard van Valkenburg <eavanvalkenburg@users.noreply.github.com>
146 lines
5.5 KiB
Python
146 lines
5.5 KiB
Python
# Copyright (c) Microsoft. All rights reserved.
|
|
|
|
"""
|
|
Sample: Request Info with SequentialBuilder
|
|
|
|
This sample demonstrates using the `.with_request_info()` method to pause a
|
|
SequentialBuilder workflow AFTER each agent runs, allowing external input
|
|
(e.g., human feedback) for review and optional iteration.
|
|
|
|
Purpose:
|
|
Show how to use the request info API that pauses after every agent response,
|
|
using the standard request_info pattern for consistency.
|
|
|
|
Demonstrate:
|
|
- Configuring request info with `.with_request_info()`
|
|
- Handling request_info events with AgentInputRequest data
|
|
- Injecting responses back into the workflow via run(responses=..., stream=True)
|
|
|
|
Prerequisites:
|
|
- AZURE_AI_PROJECT_ENDPOINT must be your Azure AI Foundry Agent Service (V2) project endpoint.
|
|
- Azure OpenAI configured for AzureOpenAIResponsesClient with required environment variables
|
|
- Authentication via azure-identity (run az login before executing)
|
|
"""
|
|
|
|
import asyncio
|
|
import os
|
|
from collections.abc import AsyncIterable
|
|
from typing import cast
|
|
|
|
from agent_framework import (
|
|
AgentExecutorResponse,
|
|
Message,
|
|
WorkflowEvent,
|
|
)
|
|
from agent_framework.azure import AzureOpenAIResponsesClient
|
|
from agent_framework.orchestrations import AgentRequestInfoResponse, SequentialBuilder
|
|
from azure.identity import AzureCliCredential
|
|
from dotenv import load_dotenv
|
|
|
|
# Load environment variables from .env file
|
|
load_dotenv()
|
|
|
|
|
|
async def process_event_stream(stream: AsyncIterable[WorkflowEvent]) -> dict[str, AgentRequestInfoResponse] | None:
|
|
"""Process events from the workflow stream to capture human feedback requests."""
|
|
requests: dict[str, AgentExecutorResponse] = {}
|
|
async for event in stream:
|
|
if event.type == "request_info" and isinstance(event.data, AgentExecutorResponse):
|
|
requests[event.request_id] = event.data
|
|
|
|
elif event.type == "output":
|
|
# The output of the sequential workflow is a list of ChatMessages
|
|
print("\n" + "=" * 60)
|
|
print("WORKFLOW COMPLETE")
|
|
print("=" * 60)
|
|
print("Final output:")
|
|
outputs = cast(list[Message], event.data)
|
|
for message in outputs:
|
|
print(f"[{message.author_name or message.role}]: {message.text}")
|
|
|
|
responses: dict[str, AgentRequestInfoResponse] = {}
|
|
if requests:
|
|
for request_id, request in requests.items():
|
|
# Display agent response and conversation context for review
|
|
print("\n" + "-" * 40)
|
|
print("REQUEST INFO: INPUT REQUESTED")
|
|
print(
|
|
f"Agent {request.executor_id} just responded with: '{request.agent_response.text}'. "
|
|
"Please provide your feedback."
|
|
)
|
|
print("-" * 40)
|
|
if request.full_conversation:
|
|
print("Conversation context:")
|
|
recent = (
|
|
request.full_conversation[-2:] if len(request.full_conversation) > 2 else request.full_conversation
|
|
)
|
|
for msg in recent:
|
|
name = msg.author_name or msg.role
|
|
text = (msg.text or "")[:150]
|
|
print(f" [{name}]: {text}...")
|
|
print("-" * 40)
|
|
|
|
# Get feedback on the agent's response (approve or request iteration)
|
|
user_input = input("Your guidance (or 'skip' to approve): ") # noqa: ASYNC250
|
|
if user_input.lower() == "skip":
|
|
user_input = AgentRequestInfoResponse.approve()
|
|
else:
|
|
user_input = AgentRequestInfoResponse.from_strings([user_input])
|
|
|
|
responses[request_id] = user_input
|
|
|
|
return responses if responses else None
|
|
|
|
|
|
async def main() -> None:
|
|
client = AzureOpenAIResponsesClient(
|
|
project_endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
|
|
deployment_name=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
|
|
credential=AzureCliCredential(),
|
|
)
|
|
|
|
# Create agents for a sequential document review workflow
|
|
drafter = client.as_agent(
|
|
name="drafter",
|
|
instructions=("You are a document drafter. When given a topic, create a brief draft (2-3 sentences)."),
|
|
)
|
|
|
|
editor = client.as_agent(
|
|
name="editor",
|
|
instructions=(
|
|
"You are an editor. Review the draft and make improvements. "
|
|
"Incorporate any human feedback that was provided."
|
|
),
|
|
)
|
|
|
|
finalizer = client.as_agent(
|
|
name="finalizer",
|
|
instructions=(
|
|
"You are a finalizer. Take the edited content and create a polished final version. "
|
|
"Incorporate any additional feedback provided."
|
|
),
|
|
)
|
|
|
|
# Build workflow with request info enabled (pauses after each agent responds)
|
|
workflow = (
|
|
SequentialBuilder(participants=[drafter, editor, finalizer])
|
|
# Only enable request info for the editor agent
|
|
.with_request_info(agents=["editor"])
|
|
.build()
|
|
)
|
|
|
|
# Initiate the first run of the workflow.
|
|
# Runs are not isolated; state is preserved across multiple calls to run.
|
|
stream = workflow.run("Write a brief introduction to artificial intelligence.", stream=True)
|
|
|
|
pending_responses = await process_event_stream(stream)
|
|
while pending_responses is not None:
|
|
# Run the workflow until there is no more human feedback to provide,
|
|
# in which case this workflow completes.
|
|
stream = workflow.run(stream=True, responses=pending_responses)
|
|
pending_responses = await process_event_stream(stream)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
asyncio.run(main())
|