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,94 @@
# Function Tools Workflow
This sample demonstrates an agent with function tools responding to user queries about a restaurant menu.
## Overview
The workflow showcases:
- **Function Tools**: Agent equipped with tools to query menu data
- **Real Foundry-backed agent**: Uses `FoundryChatClient` to create an agent with tools
- **Agent Registration**: Shows how to register agents with the `WorkflowFactory`
## Tools
The MenuAgent has access to these function tools:
| Tool | Description |
|------|-------------|
| `get_menu()` | Returns all menu items with category, name, and price |
| `get_specials()` | Returns today's special items |
| `get_item_price(name)` | Returns the price of a specific item |
## Menu Data
```
Soups:
- Clam Chowder - $4.95 (Special)
- Tomato Soup - $4.95
Salads:
- Cobb Salad - $9.99
- House Salad - $4.95
Drinks:
- Chai Tea - $2.95 (Special)
- Soda - $1.95
```
## Prerequisites
- Microsoft Foundry configured with required environment variables
- Authentication via azure-identity (run `az login` before executing)
## Usage
```bash
python main.py
```
## Example Output
```
Loaded workflow: function-tools-workflow
============================================================
Restaurant Menu Assistant
============================================================
[Bot]: Welcome to the Restaurant Menu Assistant!
[Bot]: Today's soup special is the Clam Chowder for $4.95!
============================================================
Session Complete
============================================================
```
## How It Works
1. Create a Foundry chat client
2. Create an agent with instructions and function tools
3. Register the agent with the workflow factory
4. Load the workflow YAML and run it with `run()` and `stream=True`
```python
# Create the agent with tools
client = FoundryChatClient(
project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
model=os.environ["FOUNDRY_MODEL"],
credential=AzureCliCredential(),
)
menu_agent = client.as_agent(
name="MenuAgent",
instructions="You are a helpful restaurant menu assistant...",
tools=[get_menu, get_specials, get_item_price],
)
# Register with the workflow factory
factory = WorkflowFactory(execution_mode="graph")
factory.register_agent("MenuAgent", menu_agent)
# Load and run the workflow
workflow = factory.create_workflow_from_yaml_path(workflow_path)
async for event in workflow.run(inputs={"userInput": "What is the soup of the day?"}, stream=True):
...
```
@@ -0,0 +1,132 @@
# Copyright (c) Microsoft. All rights reserved.
"""
Demonstrate a workflow that responds to user input using an agent with
function tools assigned. Exits the loop when the user enters "exit".
"""
import asyncio
import os
from dataclasses import dataclass
from pathlib import Path
from typing import Annotated, Any
from agent_framework import Agent, FileCheckpointStorage, tool
from agent_framework.foundry import FoundryChatClient
from agent_framework_declarative import ExternalInputRequest, ExternalInputResponse, WorkflowFactory
from azure.identity import AzureCliCredential
from dotenv import load_dotenv
from pydantic import Field
# Load environment variables from .env file
load_dotenv()
TEMP_DIR = Path(__file__).with_suffix("").parent / "tmp" / "checkpoints"
TEMP_DIR.mkdir(parents=True, exist_ok=True)
@dataclass
class MenuItem:
category: str
name: str
price: float
is_special: bool = False
MENU_ITEMS = [
MenuItem(category="Soup", name="Clam Chowder", price=4.95, is_special=True),
MenuItem(category="Soup", name="Tomato Soup", price=4.95, is_special=False),
MenuItem(category="Salad", name="Cobb Salad", price=9.99, is_special=False),
MenuItem(category="Salad", name="House Salad", price=4.95, is_special=False),
MenuItem(category="Drink", name="Chai Tea", price=2.95, is_special=True),
MenuItem(category="Drink", name="Soda", price=1.95, is_special=False),
]
# 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 get_menu() -> list[dict[str, Any]]:
"""Get all menu items."""
return [{"category": i.category, "name": i.name, "price": i.price} for i in MENU_ITEMS]
@tool(approval_mode="never_require")
def get_specials() -> list[dict[str, Any]]:
"""Get today's specials."""
return [{"category": i.category, "name": i.name, "price": i.price} for i in MENU_ITEMS if i.is_special]
@tool(approval_mode="never_require")
def get_item_price(name: Annotated[str, Field(description="Menu item name")]) -> str:
"""Get price of a menu item."""
for item in MENU_ITEMS:
if item.name.lower() == name.lower():
return f"${item.price:.2f}"
return f"Item '{name}' not found."
async def main():
# Create agent with tools
client = FoundryChatClient(
project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
model=os.environ["FOUNDRY_MODEL"],
credential=AzureCliCredential(),
)
menu_agent = Agent(
client=client,
name="MenuAgent",
instructions="Answer questions about menu items, specials, and prices.",
tools=[get_menu, get_specials, get_item_price],
)
# Clean up any existing checkpoints
for file in TEMP_DIR.glob("*"):
file.unlink()
factory = WorkflowFactory(checkpoint_storage=FileCheckpointStorage(TEMP_DIR))
factory.register_agent("MenuAgent", menu_agent)
workflow = factory.create_workflow_from_yaml_path(Path(__file__).parent / "workflow.yaml")
# Get initial input
print("Restaurant Menu Assistant (type 'exit' to quit)\n")
user_input = input("You: ").strip() # noqa: ASYNC250
if not user_input:
return
# Run workflow with external loop handling
pending_request_id: str | None = None
first_response = True
while True:
if pending_request_id:
response = ExternalInputResponse(user_input=user_input)
stream = workflow.run(stream=True, responses={pending_request_id: response})
else:
stream = workflow.run({"userInput": user_input}, stream=True)
pending_request_id = None
first_response = True
async for event in stream:
if event.type == "output" and isinstance(event.data, str):
if first_response:
print("MenuAgent: ", end="")
first_response = False
print(event.data, end="", flush=True)
elif event.type == "request_info" and isinstance(event.data, ExternalInputRequest):
pending_request_id = event.request_id
print()
if not pending_request_id:
break
user_input = input("\nYou: ").strip()
if not user_input:
continue
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,22 @@
# Function Tools Workflow - .NET-style
#
# This workflow demonstrates an agent with function tools in a loop
# responding to user input, using the same minimal structure as .NET.
#
# Example input:
# What is the soup of the day?
#
kind: Workflow
trigger:
kind: OnConversationStart
id: workflow_demo
actions:
- kind: InvokeAzureAgent
id: invoke_menu_agent
agent:
name: MenuAgent
input:
externalLoop:
when: =Upper(System.LastMessage.Text) <> "EXIT"