Skip to content

Commit 644c9d6

Browse files
added readme to samples folder
1 parent b885fa5 commit 644c9d6

1 file changed

Lines changed: 261 additions & 0 deletions

File tree

  • python/samples/getting_started/declarative
Lines changed: 261 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,261 @@
1+
# Declarative Agent Samples
2+
3+
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.
4+
5+
## Installation
6+
7+
Install the declarative package via pip:
8+
9+
```bash
10+
pip install agent-framework-declarative --pre
11+
```
12+
13+
## What is Declarative Agent Framework?
14+
15+
The declarative package provides support for building agents based on YAML specifications. This approach offers several benefits:
16+
17+
- **Cross-Platform Compatibility**: Write one YAML definition and create agents in both Python and .NET - the same agent configuration works across both platforms
18+
- **Separation of Concerns**: Define agent behavior in YAML files separate from your implementation code
19+
- **Reusability**: Share and version agent configurations independently across projects and languages
20+
- **Flexibility**: Easily swap between different LLM providers and configurations
21+
- **Maintainability**: Update agent instructions and settings without modifying code
22+
23+
## Samples in This Folder
24+
25+
### 1. **Get Weather Agent** ([`get_weather_agent.py`](./get_weather_agent.py))
26+
27+
Demonstrates how to create an agent with custom function tools using the declarative approach.
28+
29+
- Uses Azure OpenAI Responses client
30+
- Shows how to bind Python functions to the agent using the `bindings` parameter
31+
- Loads agent configuration from `agent-samples/chatclient/GetWeather.yaml`
32+
- Implements a simple weather lookup function tool
33+
34+
**Key concepts**: Function binding, Azure OpenAI integration, tool usage
35+
36+
### 2. **Microsoft Learn Agent** ([`microsoft_learn_agent.py`](./microsoft_learn_agent.py))
37+
38+
Shows how to create an agent that can search and retrieve information from Microsoft Learn documentation using the Model Context Protocol (MCP).
39+
40+
- Uses Azure AI Foundry client with MCP server integration
41+
- Demonstrates async context managers for proper resource cleanup
42+
- Loads agent configuration from `agent-samples/foundry/MicrosoftLearnAgent.yaml`
43+
- Uses Azure CLI credentials for authentication
44+
- Leverages MCP to access Microsoft documentation tools
45+
46+
**Requirements**: `pip install agent-framework-azure-ai --pre`
47+
48+
**Key concepts**: Azure AI Foundry integration, MCP server usage, async patterns, resource management
49+
50+
### 3. **Azure OpenAI Responses Agent** ([`azure_openai_responses_agent.py`](./azure_openai_responses_agent.py))
51+
52+
Illustrates a basic agent using Azure OpenAI with structured responses.
53+
54+
- Uses Azure OpenAI Responses client
55+
- Shows how to pass credentials via `client_kwargs`
56+
- Loads agent configuration from `agent-samples/azure/AzureOpenAIResponses.yaml`
57+
- Demonstrates accessing structured response data
58+
59+
**Key concepts**: Azure OpenAI integration, credential management, structured outputs
60+
61+
### 4. **OpenAI Responses Agent** ([`openai_responses_agent.py`](./openai_responses_agent.py))
62+
63+
Demonstrates the simplest possible agent using OpenAI directly.
64+
65+
- Uses OpenAI API (requires `OPENAI_API_KEY` environment variable)
66+
- Shows minimal configuration needed for basic agent creation
67+
- Loads agent configuration from `agent-samples/openai/OpenAIResponses.yaml`
68+
69+
**Key concepts**: OpenAI integration, minimal setup, environment-based configuration
70+
71+
## Agent Samples Repository
72+
73+
All the YAML configuration files referenced in these samples are located in the [`agent-samples`](../../../../agent-samples/) folder at the repository root. This folder contains declarative agent specifications organized by provider:
74+
75+
- **`agent-samples/azure/`** - Azure OpenAI agent configurations
76+
- **`agent-samples/chatclient/`** - Chat client agent configurations with tools
77+
- **`agent-samples/foundry/`** - Azure AI Foundry agent configurations
78+
- **`agent-samples/openai/`** - OpenAI agent configurations
79+
80+
**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.
81+
82+
These YAML files define:
83+
- Agent instructions and system prompts
84+
- Model selection and parameters
85+
- Tool and function configurations
86+
- Provider-specific settings
87+
- MCP server integrations (where applicable)
88+
89+
## Common Patterns
90+
91+
### Creating an Agent from YAML String
92+
93+
```python
94+
from agent_framework.declarative import AgentFactory
95+
96+
with open("agent.yaml", "r") as f:
97+
yaml_str = f.read()
98+
99+
agent = AgentFactory().create_agent_from_yaml(yaml_str)
100+
# response = await agent.run("Your query here")
101+
```
102+
103+
### Creating an Agent from YAML Path
104+
105+
```python
106+
from pathlib import Path
107+
from agent_framework.declarative import AgentFactory
108+
109+
yaml_path = Path("agent.yaml")
110+
agent = AgentFactory().create_agent_from_yaml_path(yaml_path)
111+
# response = await agent.run("Your query here")
112+
```
113+
114+
### Binding Custom Functions
115+
116+
```python
117+
from pathlib import Path
118+
from agent_framework.declarative import AgentFactory
119+
120+
def my_function(param: str) -> str:
121+
return f"Result: {param}"
122+
123+
agent_factory = AgentFactory(bindings={"my_function": my_function})
124+
agent = agent_factory.create_agent_from_yaml_path(Path("agent_with_tool.yaml"))
125+
```
126+
127+
### Using Credentials
128+
129+
```python
130+
from pathlib import Path
131+
from agent_framework.declarative import AgentFactory
132+
from azure.identity import AzureCliCredential
133+
134+
agent = AgentFactory(
135+
client_kwargs={"credential": AzureCliCredential()}
136+
).create_agent_from_yaml_path(Path("azure_agent.yaml"))
137+
```
138+
139+
### Adding Custom Provider Mappings
140+
141+
```python
142+
from pathlib import Path
143+
from agent_framework.declarative import AgentFactory
144+
# from my_custom_module import MyCustomChatClient
145+
146+
# Register a custom provider mapping
147+
agent_factory = AgentFactory(
148+
additional_mappings={
149+
"MyProvider": {
150+
"package": "my_custom_module",
151+
"name": "MyCustomChatClient",
152+
"model_id_field": "model_id",
153+
}
154+
}
155+
)
156+
157+
# Now you can reference "MyProvider" in your YAML
158+
# Example YAML snippet:
159+
# model:
160+
# provider: MyProvider
161+
# id: my-model-name
162+
163+
agent = agent_factory.create_agent_from_yaml_path(Path("custom_provider.yaml"))
164+
```
165+
166+
This allows you to extend the declarative framework with custom chat client implementations. The mapping requires:
167+
- **package**: The Python package/module to import from
168+
- **name**: The class name of your ChatClientProtocol implementation
169+
- **model_id_field**: The constructor parameter name that accepts the value of the `model.id` field from the YAML
170+
171+
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.
172+
173+
### Using PowerFx Formulas in YAML
174+
175+
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.
176+
177+
#### Environment Variable Lookup
178+
179+
Access environment variables using the `Env.<variable_name>` syntax:
180+
181+
```yaml
182+
model:
183+
connection:
184+
kind: key
185+
apiKey: =Env.OPENAI_API_KEY
186+
endpoint: =Env.BASE_URL & "/v1" # String concatenation with &
187+
188+
options:
189+
temperature: 0.7
190+
maxOutputTokens: =Env.MAX_TOKENS # Will be converted to appropriate type
191+
```
192+
193+
#### Conditional Logic
194+
195+
Use PowerFx operators for conditional configuration. This is particularly useful for adjusting parameters based on which model is being used:
196+
197+
```yaml
198+
model:
199+
id: =Env.MODEL_NAME
200+
options:
201+
# Set max tokens based on model - using conditional logic
202+
maxOutputTokens: =If(Env.MODEL_NAME = "gpt-5", 8000, 4000)
203+
204+
# Adjust temperature for different environments
205+
temperature: =If(Env.ENVIRONMENT = "production", 0.3, 0.7)
206+
207+
# Use logical operators for complex conditions
208+
seed: =If(Env.ENVIRONMENT = "production" And Env.DETERMINISTIC = "true", 42, Blank())
209+
```
210+
211+
#### Supported PowerFx Features
212+
213+
- **String operations**: Concatenation (`&`), comparison (`=`, `<>`), substring testing (`in`, `exactin`)
214+
- **Logical operators**: `And`, `Or`, `Not` (also `&&`, `||`, `!`)
215+
- **Arithmetic**: Basic math operations (`+`, `-`, `*`, `/`)
216+
- **Conditional**: `If(condition, true_value, false_value)`
217+
- **Environment access**: `Env.<VARIABLE_NAME>`
218+
219+
Example with multiple features:
220+
221+
```yaml
222+
instructions: =If(
223+
Env.USE_EXPERT_MODE = "true",
224+
"You are an expert AI assistant with advanced capabilities. " & Env.CUSTOM_INSTRUCTIONS,
225+
"You are a helpful AI assistant."
226+
)
227+
228+
model:
229+
options:
230+
stopSequences: =If("gpt-4" in Env.MODEL_NAME, ["END", "STOP"], ["END"])
231+
```
232+
233+
**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.
234+
235+
## Running the Samples
236+
237+
Each sample can be run independently. Make sure you have the required environment variables set:
238+
239+
- For Azure samples: Ensure you're logged in via Azure CLI (`az login`)
240+
- For OpenAI samples: Set `OPENAI_APIKEY` environment variable
241+
242+
```bash
243+
# Run a specific sample
244+
python get_weather_agent.py
245+
python microsoft_learn_agent.py
246+
python azure_openai_responses_agent.py
247+
python openai_responses_agent.py
248+
```
249+
250+
## Learn More
251+
252+
- [Agent Framework Declarative Package](../../../packages/declarative/) - Main declarative package documentation
253+
- [Agent Samples](../../../../agent-samples/) - Additional declarative agent YAML specifications
254+
- [Agent Framework Core](../../../packages/core/) - Core agent framework documentation
255+
256+
## Next Steps
257+
258+
1. Explore the YAML files in the `agent-samples` folder to understand the configuration format
259+
2. Try modifying the samples to use different models or instructions
260+
3. Create your own declarative agent configurations
261+
4. Build custom function tools and bind them to your agents

0 commit comments

Comments
 (0)