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,272 @@
# Declarative Agent Samples
This folder contains sample code demonstrating how to use the **Microsoft Agent Framework Declarative** package to create agents from YAML specifications. The declarative approach allows you to define your agents in a structured, configuration-driven way, separating agent behavior from implementation details.
## Installation
Install the declarative package via pip:
```bash
pip install agent-framework-declarative --pre
```
## What is Declarative Agent Framework?
The declarative package provides support for building agents based on YAML specifications. This approach offers several benefits:
- **Cross-Platform Compatibility**: Write one YAML definition and create agents in both Python and .NET - the same agent configuration works across both platforms
- **Separation of Concerns**: Define agent behavior in YAML files separate from your implementation code
- **Reusability**: Share and version agent configurations independently across projects and languages
- **Flexibility**: Easily swap between different LLM providers and configurations
- **Maintainability**: Update agent instructions and settings without modifying code
## Samples in This Folder
### 1. **Get Weather Agent** ([`get_weather_agent.py`](./get_weather_agent.py))
Demonstrates how to create an agent with custom function tools using the declarative approach.
- Uses Azure OpenAI Responses client
- Shows how to bind Python functions to the agent using the `bindings` parameter
- Loads agent configuration from `declarative-agents/agent-samples/chatclient/GetWeather.yaml`
- Implements a simple weather lookup function tool
**Key concepts**: Function binding, Azure OpenAI integration, tool usage
### 2. **Microsoft Learn Agent** ([`microsoft_learn_agent.py`](./microsoft_learn_agent.py))
Shows how to create an agent that can search and retrieve information from Microsoft Learn documentation using the Model Context Protocol (MCP).
- Uses Azure AI Foundry client with MCP server integration
- Demonstrates async context managers for proper resource cleanup
- Loads agent configuration from `declarative-agents/agent-samples/foundry/MicrosoftLearnAgent.yaml`
- Uses Azure CLI credentials for authentication
- Leverages MCP to access Microsoft documentation tools
**Requirements**: `pip install agent-framework-foundry`
**Key concepts**: Azure AI Foundry integration, MCP server usage, async patterns, resource management
### 3. **Inline YAML Agent** ([`inline_yaml.py`](./inline_yaml.py))
Shows how to create an agent using an inline YAML string rather than a file.
- Uses Azure AI Foundry v2 Client with instructions.
**Requirements**: `pip install agent-framework-foundry`
**Key concepts**: Inline YAML definition.
### 4. **Azure OpenAI Responses Agent** ([`azure_openai_responses_agent.py`](./azure_openai_responses_agent.py))
Illustrates a basic agent using Azure OpenAI with structured responses.
- Uses Azure OpenAI Responses client
- Shows how to pass credentials via `client_kwargs`
- Loads agent configuration from `declarative-agents/agent-samples/azure/AzureOpenAIResponses.yaml`
- Demonstrates accessing structured response data
**Key concepts**: Azure OpenAI integration, credential management, structured outputs
### 5. **OpenAI Responses Agent** ([`openai_agent.py`](./openai_agent.py))
Demonstrates the simplest possible agent using OpenAI directly.
- Uses OpenAI API (requires `OPENAI_API_KEY` environment variable)
- Shows minimal configuration needed for basic agent creation
- Loads agent configuration from `declarative-agents/agent-samples/openai/OpenAIResponses.yaml`
**Key concepts**: OpenAI integration, minimal setup, environment-based configuration
## Agent Samples Repository
All the YAML configuration files referenced in these samples are located in the [`declarative-agents/agent-samples`](../../../../declarative-agents/agent-samples/) folder at the repository root. This folder contains declarative agent specifications organized by provider:
- **`declarative-agents/agent-samples/azure/`** - Azure OpenAI agent configurations
- **`declarative-agents/agent-samples/chatclient/`** - Chat client agent configurations with tools
- **`declarative-agents/agent-samples/foundry/`** - Azure AI Foundry agent configurations
- **`declarative-agents/agent-samples/openai/`** - OpenAI agent configurations
**Important**: These YAML files are **platform-agnostic** and work with both Python and .NET implementations of the Agent Framework. You can use the exact same YAML definition to create agents in either language, making it easy to share agent configurations across different technology stacks.
These YAML files define:
- Agent instructions and system prompts
- Model selection and parameters
- Tool and function configurations
- Provider-specific settings
- MCP server integrations (where applicable)
## Common Patterns
### Creating an Agent from YAML String
```python
from agent_framework.declarative import AgentFactory
with open("agent.yaml", "r") as f:
yaml_str = f.read()
agent = AgentFactory().create_agent_from_yaml(yaml_str)
# response = await agent.run("Your query here")
```
### Creating an Agent from YAML Path
```python
from pathlib import Path
from agent_framework.declarative import AgentFactory
yaml_path = Path("agent.yaml")
agent = AgentFactory().create_agent_from_yaml_path(yaml_path)
# response = await agent.run("Your query here")
```
### Binding Custom Functions
```python
from pathlib import Path
from agent_framework.declarative import AgentFactory
def my_function(param: str) -> str:
return f"Result: {param}"
agent_factory = AgentFactory(bindings={"my_function": my_function})
agent = agent_factory.create_agent_from_yaml_path(Path("agent_with_tool.yaml"))
```
### Using Credentials
```python
from pathlib import Path
from agent_framework.declarative import AgentFactory
from azure.identity import AzureCliCredential
agent = AgentFactory(
client_kwargs={"credential": AzureCliCredential()}
).create_agent_from_yaml_path(Path("azure_agent.yaml"))
```
### Adding Custom Provider Mappings
```python
from pathlib import Path
from agent_framework.declarative import AgentFactory
# from my_custom_module import MyCustomChatClient
# Register a custom provider mapping
agent_factory = AgentFactory(
additional_mappings={
"MyProvider": {
"package": "my_custom_module",
"name": "MyCustomChatClient",
"model_field": "model",
}
}
)
# Now you can reference "MyProvider" in your YAML
# Example YAML snippet:
# model:
# provider: MyProvider
# id: my-model-name
agent = agent_factory.create_agent_from_yaml_path(Path("custom_provider.yaml"))
```
This allows you to extend the declarative framework with custom chat client implementations. The mapping requires:
- **package**: The Python package/module to import from
- **name**: The class name of your SupportsChatGetResponse implementation
- **model_field**: The constructor parameter name that accepts the value of the `model.id` field from the YAML
You can reference your custom provider using either `Provider.ApiType` format or just `Provider` in your YAML configuration, as long as it matches the registered mapping.
### Using PowerFx Formulas in YAML
The declarative framework supports PowerFx formulas in YAML values, enabling dynamic configuration based on environment variables and conditional logic. Prefix any value with `=` to evaluate it as a PowerFx expression.
#### Environment Variable Lookup
Access environment variables using the `Env.<variable_name>` syntax:
```yaml
model:
connection:
kind: key
apiKey: =Env.OPENAI_API_KEY
endpoint: =Env.BASE_URL & "/v1" # String concatenation with &
options:
temperature: 0.7
maxOutputTokens: =Env.MAX_TOKENS # Will be converted to appropriate type
```
#### Conditional Logic
Use PowerFx operators for conditional configuration. This is particularly useful for adjusting parameters based on which model is being used:
```yaml
model:
id: =Env.MODEL_NAME
options:
# Set max tokens based on model - using conditional logic
maxOutputTokens: =If(Env.MODEL_NAME = "gpt-5", 8000, 4000)
# Adjust temperature for different environments
temperature: =If(Env.ENVIRONMENT = "production", 0.3, 0.7)
# Use logical operators for complex conditions
seed: =If(Env.ENVIRONMENT = "production" And Env.DETERMINISTIC = "true", 42, Blank())
```
#### Supported PowerFx Features
- **String operations**: Concatenation (`&`), comparison (`=`, `<>`), substring testing (`in`, `exactin`)
- **Logical operators**: `And`, `Or`, `Not` (also `&&`, `||`, `!`)
- **Arithmetic**: Basic math operations (`+`, `-`, `*`, `/`)
- **Conditional**: `If(condition, true_value, false_value)`
- **Environment access**: `Env.<VARIABLE_NAME>`
Example with multiple features:
```yaml
instructions: =If(
Env.USE_EXPERT_MODE = "true",
"You are an expert AI assistant with advanced capabilities. " & Env.CUSTOM_INSTRUCTIONS,
"You are a helpful AI assistant."
)
model:
options:
stopSequences: =If("gpt-4" in Env.MODEL_NAME, ["END", "STOP"], ["END"])
```
**Note**: PowerFx evaluation happens when the YAML is loaded, not at runtime. Use environment variables (via `.env` file or `env_file` parameter) to make configurations flexible across environments.
## Running the Samples
Each sample can be run independently. Make sure you have the required environment variables set:
- For Azure samples: Ensure you're logged in via Azure CLI (`az login`)
- For OpenAI samples: Set `OPENAI_API_KEY` environment variable
```bash
# Run a specific sample
python get_weather_agent.py
python microsoft_learn_agent.py
python inline_yaml.py
python azure_openai_responses_agent.py
python openai_responses_agent.py
```
## Learn More
- [Agent Framework Declarative Package](../../../packages/declarative/) - Main declarative package documentation
- [Agent Samples](../../../../declarative-agents/agent-samples/) - Additional declarative agent YAML specifications
- [Agent Framework Core](../../../packages/core/) - Core agent framework documentation
## Next Steps
1. Explore the YAML files in the `declarative-agents/agent-samples` folder to understand the configuration format
2. Try modifying the samples to use different models or instructions
3. Create your own declarative agent configurations
4. Build custom function tools and bind them to your agents
@@ -0,0 +1,44 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
from pathlib import Path
from agent_framework.declarative import AgentFactory
from azure.identity import AzureCliCredential
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
async def main():
"""Create an agent from a declarative yaml specification and run it."""
# get the path
current_path = Path(__file__).parent
yaml_path = (
current_path.parent.parent.parent.parent
/ "declarative-agents"
/ "agent-samples"
/ "azure"
/ "AzureOpenAIResponses.yaml"
)
# load the yaml from the path
with yaml_path.open("r") as f:
yaml_str = f.read()
# create the agent from the yaml
agent = AgentFactory(client_kwargs={"credential": AzureCliCredential()}).create_agent_from_yaml(yaml_str)
# use the agent
response = await agent.run("Why is the sky blue, answer in Dutch?")
# Use response.value with try/except for safe parsing
try:
parsed = response.value
model_dump_json = getattr(parsed, "model_dump_json", None)
if callable(model_dump_json):
print("Agent response:", model_dump_json(indent=2))
else:
print("Agent response:", response.text)
except Exception:
print("Agent response:", response.text)
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,48 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
from pathlib import Path
from random import randint
from typing import Literal
from agent_framework.declarative import AgentFactory
from agent_framework.foundry import FoundryChatClient
from azure.identity import AzureCliCredential
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
def get_weather(location: str, unit: Literal["celsius", "fahrenheit"] = "celsius") -> str:
"""A simple function tool to get weather information."""
return f"The weather in {location} is {randint(-10, 30) if unit == 'celsius' else randint(30, 100)} degrees {unit}."
async def main():
"""Create an agent from a declarative yaml specification and run it."""
# get the path
current_path = Path(__file__).parent
yaml_path = (
current_path.parent.parent.parent.parent
/ "declarative-agents"
/ "agent-samples"
/ "chatclient"
/ "GetWeather.yaml"
)
# load the yaml from the path
with yaml_path.open("r") as f:
yaml_str = f.read()
# create the AgentFactory with a chat client and bindings
agent_factory = AgentFactory(
client=FoundryChatClient(credential=AzureCliCredential()),
bindings={"get_weather": get_weather},
)
# create the agent from the yaml
agent = agent_factory.create_agent_from_yaml(yaml_str)
# use the agent
response = await agent.run("What's the weather in Amsterdam, in celsius?")
print("Agent response:", response.text)
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,52 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
import os
from agent_framework.declarative import AgentFactory
from azure.identity.aio import AzureCliCredential
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
"""
This sample shows how to create an agent using an inline YAML string rather than a file.
It uses a Azure AI Client so it needs the credential to be passed into the AgentFactory.
Prerequisites:
- `pip install agent-framework-foundry agent-framework-declarative --pre`
- Set the following environment variables in a .env file or your environment:
- FOUNDRY_PROJECT_ENDPOINT
- FOUNDRY_MODEL
"""
async def main():
"""Create an agent from a declarative YAML specification and run it."""
yaml_definition = """kind: Prompt
name: DiagnosticAgent
displayName: Diagnostic Assistant
instructions: Specialized diagnostic and issue detection agent for systems with critical error protocol and automatic handoff capabilities
description: A agent that performs diagnostics on systems and can escalate issues when critical errors are detected.
model:
id: =Env.FOUNDRY_MODEL
"""
# create the agent from the yaml
async with (
AzureCliCredential() as credential,
AgentFactory(
client_kwargs={
"credential": credential,
"project_endpoint": os.environ["FOUNDRY_PROJECT_ENDPOINT"],
},
safe_mode=False,
).create_agent_from_yaml(yaml_definition) as agent,
):
response = await agent.run("What can you do for me?")
print("Agent response:", response.text)
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,161 @@
# Copyright (c) Microsoft. All rights reserved.
"""
MCP Tool via YAML Declaration
This sample demonstrates how to create agents with MCP (Model Context Protocol)
tools using YAML declarations and the declarative AgentFactory.
Key Features Demonstrated:
1. Loading agent definitions from YAML using AgentFactory
2. Configuring MCP tools with different authentication methods:
- API key authentication (OpenAI.Responses provider)
- Azure AI Foundry connection references (Foundry provider)
Authentication Options:
- OpenAI.Responses: Supports inline API key auth via headers
- Foundry: Uses project-backed chat with Foundry connections for secure credential storage
(no secrets passed in API calls - connection name references pre-configured auth)
Prerequisites:
- `pip install agent-framework-openai agent-framework-declarative --pre`
- For OpenAI example: Set OPENAI_API_KEY and GITHUB_PAT environment variables
- For Azure AI example: Set up a Foundry connection in your Azure AI project
"""
import asyncio
from agent_framework.declarative import AgentFactory
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
# Example 1: OpenAI.Responses with API key authentication
# Uses inline API key - suitable for OpenAI provider which supports headers
YAML_OPENAI_WITH_API_KEY = """
kind: Prompt
name: GitHubAgent
displayName: GitHub Assistant
description: An agent that can interact with GitHub using the MCP protocol
instructions: |
You are a helpful assistant that can interact with GitHub.
You can search for repositories, read file contents, and check issues.
Always be clear about what operations you're performing.
model:
id: gpt-4o
provider: OpenAI.Responses # Uses OpenAI's Responses API (requires OPENAI_API_KEY env var)
tools:
- kind: mcp
name: github-mcp
description: GitHub MCP tool for repository operations
url: https://api.githubcopilot.com/mcp/
connection:
kind: key
apiKey: =Env.GITHUB_PAT # PowerFx syntax to read from environment variable
approvalMode: never
allowedTools:
- get_file_contents
- get_me
- search_repositories
- search_code
- list_issues
"""
# Example 2: Azure AI with Foundry connection reference
# No secrets in YAML - references a pre-configured Foundry connection by name
# The connection stores credentials securely in Azure AI Foundry
YAML_AZURE_AI_WITH_FOUNDRY_CONNECTION = """
kind: Prompt
name: GitHubAgent
displayName: GitHub Assistant
description: An agent that can interact with GitHub using the MCP protocol
instructions: |
You are a helpful assistant that can interact with GitHub.
You can search for repositories, read file contents, and check issues.
Always be clear about what operations you're performing.
model:
id: gpt-4o
provider: Foundry
tools:
- kind: mcp
name: github-mcp
description: GitHub MCP tool for repository operations
url: https://api.githubcopilot.com/mcp/
connection:
kind: remote
authenticationMode: oauth
name: github-mcp-oauth-connection # References a Foundry connection
approvalMode: never
allowedTools:
- get_file_contents
- get_me
- search_repositories
- search_code
- list_issues
"""
async def run_openai_example():
"""Run the OpenAI.Responses example with API key auth."""
print("=" * 60)
print("Example 1: OpenAI.Responses with API Key Authentication")
print("=" * 60)
factory = AgentFactory(
safe_mode=False, # Allow PowerFx env var resolution (=Env.VAR_NAME)
)
print("\nCreating agent from YAML definition...")
agent = factory.create_agent_from_yaml(YAML_OPENAI_WITH_API_KEY)
async with agent:
query = "What is my GitHub username?"
print(f"\nUser: {query}")
response = await agent.run(query)
print(f"\nAgent: {response.text}")
async def run_azure_ai_example():
"""Run the Azure AI example with Foundry connection.
Prerequisites:
1. Create a Foundry connection named 'github-mcp-oauth-connection' in your
Azure AI project with OAuth credentials for GitHub
2. Set PROJECT_ENDPOINT environment variable to your Azure AI project endpoint
"""
print("=" * 60)
print("Example 2: Azure AI with Foundry Connection Reference")
print("=" * 60)
from azure.identity import AzureCliCredential
factory = AgentFactory(client_kwargs={"credential": AzureCliCredential()})
print("\nCreating agent from YAML definition...")
# Use async method for provider-based agent creation
agent = await factory.create_agent_from_yaml_async(YAML_AZURE_AI_WITH_FOUNDRY_CONNECTION)
async with agent:
query = "What is my GitHub username?"
print(f"\nUser: {query}")
response = await agent.run(query)
print(f"\nAgent: {response.text}")
async def main():
"""Run the MCP tool examples."""
# Run the OpenAI example
await run_openai_example()
# Run the Azure AI example (uncomment to run)
# Requires: Foundry connection set up and PROJECT_ENDPOINT env var
# await run_azure_ai_example()
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,50 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
from pathlib import Path
from agent_framework.declarative import AgentFactory
from azure.identity.aio import AzureCliCredential
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
"""
This sample demonstrates creating an agent from a declarative YAML file specification.
It uses a MCP server to connect to the Microsoft Learn content and a FoundryChatClient.
The yaml also has some chat options set, such as temperature and topP.
These options do not work with newer OpenAI models, so ensure to use a compatible model such as gpt-4o-mini.
Environment variables:
- FOUNDRY_PROJECT_ENDPOINT: The endpoint URL for the Foundry project.
- FOUNDRY_MODEL: The model ID to use for the agent, make sure it is compatible with the chat options specified in
the yaml, or remove the options.
"""
async def main():
"""Create an agent from a declarative yaml specification and run it."""
# get the path
current_path = Path(__file__).parent
yaml_path = (
current_path.parent.parent.parent.parent
/ "declarative-agents"
/ "agent-samples"
/ "foundry"
/ "MicrosoftLearnAgent.yaml"
)
# create the agent from the yaml
async with (
AzureCliCredential() as credential,
AgentFactory(client_kwargs={"credential": credential}, safe_mode=False).create_agent_from_yaml_path(
yaml_path
) as agent,
):
response = await agent.run("How do I create a storage account with private endpoint using bicep?")
print("Agent response:", response.text)
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,36 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
from pathlib import Path
from agent_framework.declarative import AgentFactory
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
async def main():
"""Create an agent from a declarative yaml specification and run it."""
# get the path
current_path = Path(__file__).parent
yaml_path = (
current_path.parent.parent.parent.parent
/ "declarative-agents"
/ "agent-samples"
/ "openai"
/ "OpenAIResponses.yaml"
)
# create the agent from the yaml
agent = AgentFactory(safe_mode=False).create_agent_from_yaml_path(yaml_path)
# use the agent
response = await agent.run("Why is the sky blue, answer in Dutch?")
# Use response.value with try/except for safe parsing
try:
parsed = response.value
print("Agent response:", parsed)
except Exception:
print("Agent response:", response.text)
if __name__ == "__main__":
asyncio.run(main())