chore: import upstream snapshot with attribution
CodeQL / Analyze (csharp) (push) Waiting to run
CodeQL / Analyze (python) (push) Waiting to run
dotnet-build-and-test / dotnet-test-functions (push) Has been cancelled
dotnet-build-and-test / paths-filter (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Debug, windows-latest, net9.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Release, ubuntu-latest, net10.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Release, ubuntu-latest, net8.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Release, windows-latest, net472) (push) Has been cancelled
dotnet-build-and-test / dotnet-test (Release, integration, true, ubuntu-latest, net10.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-test (Release, integration, true, windows-latest, net472) (push) Has been cancelled
dotnet-build-and-test / dotnet-foundry-hosted-it (push) Has been cancelled
dotnet-build-and-test / dotnet-build-and-test-check (push) Has been cancelled
dotnet-build-and-test / Integration Test Report (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 13:39:25 +08:00
commit db620d33df
5151 changed files with 925932 additions and 0 deletions
@@ -0,0 +1,249 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
import os
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from uuid import uuid4
from agent_framework import (
Agent,
AgentExecutorRequest,
AgentExecutorResponse,
Message,
WorkflowBuilder,
WorkflowContext,
executor,
)
from agent_framework.foundry import FoundryChatClient
from agent_framework.openai import OpenAIChatOptions
from azure.identity import AzureCliCredential
from dotenv import load_dotenv
from pydantic import BaseModel
from typing_extensions import Never
# Load environment variables from .env file
load_dotenv()
"""
Sample: Workflow state with agents and conditional routing.
Store an email once by id, classify it with a detector agent, then either draft a reply with an assistant
agent or finish with a spam notice. Stream events as the workflow runs.
Purpose:
Show how to:
- Use workflow state to decouple large payloads from messages and pass around lightweight references.
- Enforce structured agent outputs with Pydantic models via response_format for robust parsing.
- Route using conditional edges based on a typed intermediate DetectionResult.
- Compose agent backed executors with function style executors and yield the final output when the workflow completes.
Prerequisites:
- FOUNDRY_PROJECT_ENDPOINT must be your Azure AI Foundry Agent Service (V2) project endpoint.
- FOUNDRY_MODEL must be set to your Azure OpenAI model deployment name.
- Authentication via azure-identity. Use AzureCliCredential and run az login before executing the sample.
- Familiarity with WorkflowBuilder, executors, conditional edges, and streaming runs.
"""
EMAIL_STATE_PREFIX = "email:"
CURRENT_EMAIL_ID_KEY = "current_email_id"
class DetectionResultAgent(BaseModel):
"""Structured output returned by the spam detection agent."""
is_spam: bool
reason: str
class EmailResponse(BaseModel):
"""Structured output returned by the email assistant agent."""
response: str
@dataclass
class DetectionResult:
"""Internal detection result enriched with the state email_id for later lookups."""
is_spam: bool
reason: str
email_id: str
@dataclass
class Email:
"""In memory record stored in state to avoid re-sending large bodies on edges."""
email_id: str
email_content: str
def get_condition(expected_result: bool):
"""Create a condition predicate for DetectionResult.is_spam.
Contract:
- If the message is not a DetectionResult, allow it to pass to avoid accidental dead ends.
- Otherwise, return True only when is_spam matches expected_result.
"""
def condition(message: Any) -> bool:
if not isinstance(message, DetectionResult):
return True
return message.is_spam == expected_result
return condition
@executor(id="store_email")
async def store_email(email_text: str, ctx: WorkflowContext[AgentExecutorRequest]) -> None:
"""Persist the raw email content in state and trigger spam detection.
Responsibilities:
- Generate a unique email_id (UUID) for downstream retrieval.
- Store the Email object under a namespaced key and set the current id pointer.
- Emit an AgentExecutorRequest asking the detector to respond.
"""
new_email = Email(email_id=str(uuid4()), email_content=email_text)
ctx.set_state(f"{EMAIL_STATE_PREFIX}{new_email.email_id}", new_email)
ctx.set_state(CURRENT_EMAIL_ID_KEY, new_email.email_id)
await ctx.send_message(
AgentExecutorRequest(messages=[Message("user", contents=[new_email.email_content])], should_respond=True)
)
@executor(id="to_detection_result")
async def to_detection_result(response: AgentExecutorResponse, ctx: WorkflowContext[DetectionResult]) -> None:
"""Parse spam detection JSON into a structured model and enrich with email_id.
Steps:
1) Validate the agent's JSON output into DetectionResultAgent.
2) Retrieve the current email_id from workflow state.
3) Send a typed DetectionResult for conditional routing.
"""
parsed = DetectionResultAgent.model_validate_json(response.agent_response.text)
email_id: str = ctx.get_state(CURRENT_EMAIL_ID_KEY)
await ctx.send_message(DetectionResult(is_spam=parsed.is_spam, reason=parsed.reason, email_id=email_id))
@executor(id="submit_to_email_assistant")
async def submit_to_email_assistant(detection: DetectionResult, ctx: WorkflowContext[AgentExecutorRequest]) -> None:
"""Forward non spam email content to the drafting agent.
Guard:
- This path should only receive non spam. Raise if misrouted.
"""
if detection.is_spam:
raise RuntimeError("This executor should only handle non-spam messages.")
# Load the original content by id from workflow state and forward it to the assistant.
email: Email = ctx.get_state(f"{EMAIL_STATE_PREFIX}{detection.email_id}")
await ctx.send_message(
AgentExecutorRequest(messages=[Message("user", contents=[email.email_content])], should_respond=True)
)
@executor(id="finalize_and_send")
async def finalize_and_send(response: AgentExecutorResponse, ctx: WorkflowContext[Never, str]) -> None:
"""Validate the drafted reply and yield the final output."""
parsed = EmailResponse.model_validate_json(response.agent_response.text)
await ctx.yield_output(f"Email sent: {parsed.response}")
@executor(id="handle_spam")
async def handle_spam(detection: DetectionResult, ctx: WorkflowContext[Never, str]) -> None:
"""Yield output describing why the email was marked as spam."""
if detection.is_spam:
await ctx.yield_output(f"Email marked as spam: {detection.reason}")
else:
raise RuntimeError("This executor should only handle spam messages.")
def create_spam_detection_agent() -> Agent:
"""Creates a spam detection agent."""
return Agent(
client=FoundryChatClient(
project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
model=os.environ["FOUNDRY_MODEL"],
credential=AzureCliCredential(),
),
instructions=(
"You are a spam detection assistant that identifies spam emails. "
"Always return JSON with fields is_spam (bool) and reason (string)."
),
default_options=OpenAIChatOptions[Any](response_format=DetectionResultAgent),
# response_format enforces structured JSON from each agent.
name="spam_detection_agent",
)
def create_email_assistant_agent() -> Agent:
"""Creates an email assistant agent."""
return Agent(
client=FoundryChatClient(
project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
model=os.environ["FOUNDRY_MODEL"],
credential=AzureCliCredential(),
),
instructions=(
"You are an email assistant that helps users draft responses to emails with professionalism. "
"Return JSON with a single field 'response' containing the drafted reply."
),
# response_format enforces structured JSON from each agent.
default_options=OpenAIChatOptions[Any](response_format=EmailResponse),
name="email_assistant_agent",
)
async def main() -> None:
"""Build and run the workflow state with agents and conditional routing workflow."""
# Build the workflow graph with conditional edges.
# Flow:
# store_email -> spam_detection_agent -> to_detection_result -> branch:
# False -> submit_to_email_assistant -> email_assistant_agent -> finalize_and_send
# True -> handle_spam
spam_detection_agent = create_spam_detection_agent()
email_assistant_agent = create_email_assistant_agent()
workflow = (
WorkflowBuilder(start_executor=store_email)
.add_edge(store_email, spam_detection_agent)
.add_edge(spam_detection_agent, to_detection_result)
.add_edge(to_detection_result, submit_to_email_assistant, condition=get_condition(False))
.add_edge(to_detection_result, handle_spam, condition=get_condition(True))
.add_edge(submit_to_email_assistant, email_assistant_agent)
.add_edge(email_assistant_agent, finalize_and_send)
.build()
)
# Read an email from resources/spam.txt if available; otherwise use a default sample.
current_file = Path(__file__)
resources_path = current_file.parent.parent / "resources" / "spam.txt"
if resources_path.exists():
email = resources_path.read_text(encoding="utf-8")
else:
print("Unable to find resource file, using default text.")
email = "You are a WINNER! Click here for a free lottery offer!!!"
# Run and print the final result. Streaming surfaces intermediate execution events as well.
events = await workflow.run(email)
outputs = events.get_outputs()
if outputs:
print(f"Final result: {outputs[0]}")
"""
Sample Output:
Final result: Email marked as spam: This email exhibits several common spam and scam characteristics:
unrealistic claims of large cash winnings, urgent time pressure, requests for sensitive personal and financial
information, and a demand for a processing fee. The sender impersonates a generic lottery commission, and the
message contains a suspicious link. All these are typical of phishing and lottery scam emails.
"""
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,170 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
import json
import os
from typing import Annotated, Any, cast
from agent_framework import Agent, Message, tool
from agent_framework.foundry import FoundryChatClient
from agent_framework.orchestrations import SequentialBuilder
from azure.identity import AzureCliCredential
from dotenv import load_dotenv
from pydantic import Field
# Load environment variables from .env file
load_dotenv()
"""
Sample: Global Workflow kwargs
This sample demonstrates how to pass the same kwargs to every agent in a
workflow using global targeting. When keys in function_invocation_kwargs do NOT
match any executor ID (agent name), the framework treats them as global and
delivers them to all agents.
Compare with workflow_kwargs_per_agent.py which targets kwargs to specific agents.
Key Concepts:
- Global function_invocation_kwargs are delivered to every agent in the workflow
- Useful when all agents share the same credentials, config, or context
- @tool functions receive kwargs via the **kwargs parameter
Prerequisites:
- FOUNDRY_PROJECT_ENDPOINT must be your Azure AI Foundry Agent Service (V2) project endpoint.
- Environment variables configured
"""
# 1. Define a tool for the research agent — queries a company's internal
# database using credentials passed via global kwargs.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/02-agents/tools/function_tool_with_approval.py
# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py.
@tool(approval_mode="never_require")
def query_company_database(
query: Annotated[
str, Field(description="The database query to run, e.g. 'Q3 revenue' or 'headcount by department'")
],
**kwargs: Any,
) -> str:
"""Query the company's internal database for business metrics and data."""
db_config = kwargs.get("db_config", {})
connection_string = db_config.get("connection_string", "")
database = db_config.get("database", "")
if not connection_string or not database:
return f"ERROR: missing db_config — cannot run query '{query}'"
print(f"\n [query_company_database] Connecting to {database} at {connection_string[:30]}...")
# Simulated company data that the LLM would not know on its own
return (
f"Query results from {database}:\n"
f"- Contoso Q3 2025 revenue: $47.2M (up 12% YoY)\n"
f"- Top product line: CloudSync Pro ($18.6M)\n"
f"- Engineering headcount: 342 (up from 298 in Q2)\n"
f"- Customer churn rate: 4.1% (down from 5.3% in Q2)\n"
f"- Net new enterprise customers: 28"
)
# 2. Define a tool for the writer agent — retrieves the formatting style
# from user preferences passed via global kwargs.
@tool(approval_mode="never_require")
def get_formatting_instructions(
section_title: Annotated[str, Field(description="The title of the section or report to format")],
**kwargs: Any,
) -> str:
"""Get the formatting instructions based on user preferences."""
user_prefs = kwargs.get("user_preferences", {})
output_format = user_prefs.get("format", "plain")
language = user_prefs.get("language", "en")
print(f"\n [get_formatting_instructions] Format: {output_format}, Language: {language}")
return (
f"Formatting rules for '{section_title}':\n"
f"- Output format: {output_format}\n"
f"- Language/locale: {language}\n"
f"- Include a footer: 'Generated in {output_format} for locale {language}'"
)
async def main() -> None:
print("=" * 70)
print("Global Workflow kwargs Demo")
print("=" * 70)
# 3. Create a shared chat client.
client = FoundryChatClient(
project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
model=os.environ["FOUNDRY_MODEL"],
credential=AzureCliCredential(),
)
# 4. Create two agents with different tools and responsibilities.
researcher = Agent(
client=client,
name="researcher",
instructions=(
"You are a data analyst. Call query_company_database exactly once "
"with the user's request as the query. Return the raw results."
),
tools=[query_company_database],
)
writer = Agent(
client=client,
name="writer",
instructions=(
"You are a report writer. Call get_formatting_instructions exactly once, "
"then rewrite the data you receive into a polished report following those rules."
),
tools=[get_formatting_instructions],
)
# 5. Build a sequential workflow: researcher -> writer.
workflow = SequentialBuilder(participants=[researcher, writer]).build()
# 6. Define global kwargs — every agent receives all of these.
# Because the keys ("db_config", "user_preferences") do NOT match any
# executor ID ("researcher", "writer"), the framework treats them as
# global and delivers the full dict to every agent.
global_fi_kwargs = {
"db_config": {
"connection_string": "Server=contoso-sql.database.windows.net;Database=metrics",
"database": "contoso_metrics_prod",
},
"user_preferences": {
"format": "markdown",
"language": "en-US",
},
}
print("\nGlobal function_invocation_kwargs (sent to all agents):")
print(json.dumps(global_fi_kwargs, indent=2))
print("\n" + "-" * 70)
print("Workflow Execution:")
print("-" * 70)
# 7. Run the workflow — every agent receives the same global kwargs.
async for event in workflow.run(
"Pull Contoso's Q3 2025 performance data and write an executive summary.",
function_invocation_kwargs=global_fi_kwargs,
stream=True,
):
if event.type == "output":
output_data = cast(list[Message], event.data)
if isinstance(output_data, list):
for item in output_data:
if isinstance(item, Message) and item.text:
print(f"\n[{item.author_name}]: {item.text}")
print("\n" + "=" * 70)
print("Sample Complete")
print("=" * 70)
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,222 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
import json
import os
from typing import Annotated, Any, cast
from agent_framework import Agent, Message, tool
from agent_framework.foundry import FoundryChatClient
from agent_framework.orchestrations import SequentialBuilder
from azure.identity import AzureCliCredential
from dotenv import load_dotenv
from pydantic import Field
# Load environment variables from .env file
load_dotenv()
"""
Sample: Per-Agent Workflow kwargs
This sample demonstrates how to pass different kwargs to different agents in a
workflow using per-agent targeting. When keys in function_invocation_kwargs (or
client_kwargs) match executor IDs (agent names by default), each agent
receives only its own slice of the kwargs.
Key Concepts:
- Per-agent function_invocation_kwargs target specific agents by executor ID
- Agents only receive the kwargs assigned to them (not other agents' kwargs)
- Useful when different agents need different credentials, configs, or context
Prerequisites:
- FOUNDRY_PROJECT_ENDPOINT must be your Azure AI Foundry Agent Service (V2) project endpoint.
- Environment variables configured
"""
# 1. Define a tool for the research agent — queries a company's internal
# database using credentials passed via per-agent kwargs.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/02-agents/tools/function_tool_with_approval.py
# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py.
@tool(approval_mode="never_require")
def query_company_database(
query: Annotated[
str, Field(description="The database query to run, e.g. 'Q3 revenue' or 'headcount by department'")
],
**kwargs: Any,
) -> str:
"""Query the company's internal database for business metrics and data."""
db_config = kwargs.get("db_config", {})
connection_string = db_config.get("connection_string", "")
database = db_config.get("database", "")
if not connection_string or not database:
return f"ERROR: missing db_config — cannot run query '{query}'"
print(f"\n [query_company_database] Connecting to {database} at {connection_string[:30]}...")
# Simulated company data that the LLM would not know on its own
return (
f"Query results from {database}:\n"
f"- Contoso Q3 2025 revenue: $47.2M (up 12% YoY)\n"
f"- Top product line: CloudSync Pro ($18.6M)\n"
f"- Engineering headcount: 342 (up from 298 in Q2)\n"
f"- Customer churn rate: 4.1% (down from 5.3% in Q2)\n"
f"- Net new enterprise customers: 28"
)
# 2. Define a tool for the writer agent — retrieves the formatting style
# from user preferences passed via per-agent kwargs.
@tool(approval_mode="never_require")
def get_formatting_instructions(
section_title: Annotated[str, Field(description="The title of the section or report to format")],
**kwargs: Any,
) -> str:
"""Get the formatting instructions based on user preferences."""
user_prefs = kwargs.get("user_preferences", {})
output_format = user_prefs.get("format", "plain")
language = user_prefs.get("language", "en")
print(f"\n [get_formatting_instructions] Format: {output_format}, Language: {language}")
return (
f"Formatting rules for '{section_title}':\n"
f"- Output format: {output_format}\n"
f"- Language/locale: {language}\n"
f"- Include a footer: 'Generated in {output_format} for locale {language}'"
)
async def main() -> None:
print("=" * 70)
print("Per-Agent Workflow kwargs Demo")
print("=" * 70)
# 3. Create a shared chat client.
client = FoundryChatClient(
project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
model=os.environ["FOUNDRY_MODEL"],
credential=AzureCliCredential(),
)
# 4. Create two agents with different tools and responsibilities.
researcher = Agent(
client=client,
name="researcher",
instructions=(
"You are a data analyst. Call query_company_database exactly once "
"with the user's request as the query. Return the raw results."
),
tools=[query_company_database],
)
writer = Agent(
client=client,
name="writer",
instructions=(
"You are a report writer. Call get_formatting_instructions exactly once, "
"then rewrite the data you receive into a polished report following those rules."
),
tools=[get_formatting_instructions],
)
# 5. Build a sequential workflow: researcher -> writer.
workflow = SequentialBuilder(participants=[researcher, writer]).build()
# 6. Define per-agent kwargs — each agent gets only its own config.
# The keys ("researcher", "writer") match the agent names, which are
# used as executor IDs by default.
per_agent_fi_kwargs = {
"researcher": {
"db_config": {
"connection_string": "Server=contoso-sql.database.windows.net;Database=metrics",
"database": "contoso_metrics_prod",
},
},
"writer": {
"user_preferences": {
"format": "markdown",
"language": "en-US",
},
},
}
print("\nPer-agent function_invocation_kwargs:")
print(json.dumps(per_agent_fi_kwargs, indent=2))
print("\n" + "-" * 70)
print("Workflow Execution:")
print("-" * 70)
# 7. Run the workflow — each agent receives only its targeted kwargs.
async for event in workflow.run(
"Pull Contoso's Q3 2025 performance data and write an executive summary.",
function_invocation_kwargs=per_agent_fi_kwargs,
stream=True,
):
if event.type == "output":
output_data = cast(list[Message], event.data)
if isinstance(output_data, list):
for item in output_data:
if isinstance(item, Message) and item.text:
print(f"\n[{item.author_name}]: {item.text}")
print("\n" + "=" * 70)
print("Sample Complete")
print("=" * 70)
if __name__ == "__main__":
asyncio.run(main())
"""
Sample output:
Per-agent function_invocation_kwargs:
{
"researcher": {
"db_config": {
"connection_string": "Server=contoso-sql.database.windows.net;Database=metrics",
"database": "contoso_metrics_prod"
}
},
"writer": {
"user_preferences": {
"format": "markdown",
"language": "en-US"
}
}
}
----------------------------------------------------------------------
Workflow Execution:
----------------------------------------------------------------------
[query_company_database] Connecting to contoso_metrics_prod at Server=contoso-sql.database.wi...
[researcher]: Here is Contoso's Q3 2025 data:
- Revenue: $47.2M (up 12% YoY)
- Top product: CloudSync Pro ($18.6M)
- Engineering headcount: 342
- Churn rate: 4.1%
- Net new enterprise customers: 28
[get_formatting_instructions] Format: markdown, Language: en-US
[writer]: # Contoso Q3 2025 Executive Summary
| Metric | Value |
|---|---|
| Revenue | $47.2M (+12% YoY) |
| Top Product | CloudSync Pro ($18.6M) |
| Engineering Headcount | 342 |
| Customer Churn | 4.1% |
| New Enterprise Customers | 28 |
Generated in markdown for locale en-US
======================================================================
Sample Complete
======================================================================
"""