Skip to content

Commit 5c14b43

Browse files
add missing samples (#386)
1 parent 7daee33 commit 5c14b43

9 files changed

Lines changed: 360 additions & 0 deletions

File tree

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
FROM python:3.11-slim
2+
3+
WORKDIR /app
4+
5+
COPY . user_agent/
6+
WORKDIR /app/user_agent
7+
8+
RUN if [ -f requirements.txt ]; then \
9+
pip install -r requirements.txt; \
10+
else \
11+
echo "No requirements.txt found"; \
12+
fi
13+
14+
EXPOSE 8088
15+
16+
CMD ["python", "main.py"]
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
name: HuggingFace-Agent
2+
description: Hugging Face agent
3+
metadata:
4+
example:
5+
- role: user
6+
content: |-
7+
What's are the trending models in the OpenLLM Leaderboard?
8+
tags:
9+
- Microsoft Agent Framework
10+
template:
11+
name: HuggingFace-Agent
12+
kind: hosted
13+
environment_variables:
14+
- name: AZURE_OPENAI_ENDPOINT
15+
value: ${AZURE_OPENAI_ENDPOINT}
16+
- name: OPENAI_API_VERSION
17+
value: 2025-03-01-preview
18+
- name: AZURE_OPENAI_CHAT_DEPLOYMENT_NAME
19+
value: "{{chat}}"
20+
- name: AZURE_AI_PROJECT_TOOL_CONNECTION_ID
21+
value: "HuggingFaceMCPServer"
22+
resources:
23+
- kind: model
24+
id: gpt-5
25+
name: chat
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
# Copyright (c) Microsoft. All rights reserved.
2+
"""Example showing how to use an agent factory function with ToolClient.
3+
4+
This sample demonstrates how to pass a factory function to from_agent_framework
5+
that receives a ToolClient and returns an AgentProtocol. This pattern allows
6+
the agent to be created dynamically with access to tools from Azure AI Tool
7+
Client at runtime.
8+
"""
9+
10+
import asyncio
11+
import os
12+
from typing import List
13+
from dotenv import load_dotenv
14+
from agent_framework import AIFunction
15+
from agent_framework.azure import AzureOpenAIChatClient
16+
17+
from azure.ai.agentserver.agentframework import from_agent_framework
18+
from azure.identity.aio import DefaultAzureCredential, get_bearer_token_provider
19+
20+
load_dotenv()
21+
22+
23+
def create_agent_factory():
24+
"""Create a factory function that builds an agent with ToolClient.
25+
26+
This function returns a factory that takes a ToolClient and returns
27+
an AgentProtocol. The agent is created at runtime for every request,
28+
allowing it to access the latest tool configuration dynamically.
29+
"""
30+
31+
async def agent_factory(tools: List[AIFunction]) -> AzureOpenAIChatClient:
32+
"""Factory function that creates an agent using the provided tools.
33+
34+
:param tools: The list of AIFunction tools available to the agent.
35+
:type tools: List[AIFunction]
36+
:return: An Agent Framework ChatAgent instance.
37+
:rtype: ChatAgent
38+
"""
39+
# List all available tools from the ToolClient
40+
print("Fetching tools from Azure AI Tool Client via factory...")
41+
print(f"Found {len(tools)} tools:")
42+
for tool in tools:
43+
print(f" - tool: {tool.name}, description: {tool.description}")
44+
45+
if not tools:
46+
print("\nNo tools found!")
47+
print("Make sure your Azure AI project has tools configured.")
48+
raise ValueError("No tools available to create agent")
49+
50+
azure_credential = DefaultAzureCredential()
51+
token_provider = get_bearer_token_provider(azure_credential, "https://cognitiveservices.azure.com/.default")
52+
# Create the Agent Framework agent with the tools
53+
print("\nCreating Agent Framework agent with tools from factory...")
54+
agent = AzureOpenAIChatClient(ad_token_provider=token_provider).create_agent(
55+
name="ToolClientAgent",
56+
instructions="You are a helpful assistant with access to various tools.",
57+
tools=tools,
58+
)
59+
60+
print("Agent created successfully!")
61+
return agent
62+
63+
return agent_factory
64+
65+
66+
async def quickstart():
67+
"""Build and return an AgentFrameworkCBAgent using an agent factory function."""
68+
69+
# Get configuration from environment
70+
project_endpoint = os.getenv("AZURE_AI_PROJECT_ENDPOINT")
71+
72+
if not project_endpoint:
73+
raise ValueError(
74+
"AZURE_AI_PROJECT_ENDPOINT environment variable is required. "
75+
"Set it to your Azure AI project endpoint, e.g., "
76+
"https://<your-account>.services.ai.azure.com/api/projects/<your-project>"
77+
)
78+
79+
# Create Azure credentials
80+
credential = DefaultAzureCredential()
81+
82+
# Create a factory function that will build the agent at runtime
83+
# The factory will receive a ToolClient when the agent first runs
84+
agent_factory = create_agent_factory()
85+
86+
tool_connection_id = os.getenv("AZURE_AI_PROJECT_TOOL_CONNECTION_ID")
87+
# Pass the factory function to from_agent_framework instead of a compiled agent
88+
# The agent will be created on every agent run with access to ToolClient
89+
print("Creating Agent Framework adapter with factory function...")
90+
adapter = from_agent_framework(
91+
agent_factory,
92+
credentials=credential,
93+
tools=[
94+
{"type": "mcp", "project_connection_id": tool_connection_id}
95+
96+
]
97+
)
98+
99+
print("Adapter created! Agent will be built on every request.")
100+
return adapter
101+
102+
103+
async def main(): # pragma: no cover - sample entrypoint
104+
"""Main function to run the agent."""
105+
adapter = await quickstart()
106+
107+
if adapter:
108+
print("\nStarting agent server...")
109+
print("The agent factory will be called for every request that arrives.")
110+
await adapter.run_async()
111+
112+
113+
if __name__ == "__main__":
114+
asyncio.run(main())
115+
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
azure_ai_agentserver_agentframework==1.0.0b5
2+
agent-framework
3+
pytest==8.4.2
4+
python-dotenv==1.1.1
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
FROM python:3.11-slim
2+
3+
WORKDIR /app
4+
5+
COPY . user_agent/
6+
WORKDIR /app/user_agent
7+
8+
RUN if [ -f requirements.txt ]; then \
9+
pip install -r requirements.txt; \
10+
else \
11+
echo "No requirements.txt found"; \
12+
fi
13+
14+
EXPOSE 8088
15+
16+
CMD ["python", "main.py"]
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
# 📚 Microsoft Learn Agent
2+
3+
> **Your AI-powered documentation companion** - Instantly access the vast knowledge of Microsoft Learn with intelligent search and contextual answers.
4+
5+
<div align="center">
6+
7+
![Agent Framework](https://img.shields.io/badge/Agent_Framework-1.0.0-blue?style=for-the-badge)
8+
![Python](https://img.shields.io/badge/Python-3.8+-green?style=for-the-badge)
9+
![Azure AI](https://img.shields.io/badge/Azure_AI-Powered-orange?style=for-the-badge)
10+
![MCP](https://img.shields.io/badge/MCP-Enabled-purple?style=for-the-badge)
11+
12+
</div>
13+
14+
## 🌟 What Makes This Special?
15+
16+
This intelligent agent leverages the power of **Model Context Protocol (MCP)** and **Microsoft Agent Framework** to provide seamless access to Microsoft Learn documentation. Whether you're a developer learning Azure Functions, exploring .NET, or diving into AI services, this agent delivers precise, up-to-date answers from the official Microsoft documentation.
17+
18+
### ✨ Key Features
19+
20+
- 🔍 **Smart Documentation Search** - Natural language queries across Microsoft Learn
21+
- 🧠 **Context-Aware Responses** - Understands your intent and provides relevant code examples
22+
- 🚀 **Real-Time Access** - Always up-to-date with the latest Microsoft documentation
23+
- 🔧 **Easy Integration** - Drop into any Azure AI project with minimal setup
24+
- 💬 **Interactive Mode** - Ask follow-up questions and get clarifications
25+
26+
## 🚀 Quick Start
27+
28+
### Prerequisites
29+
30+
- Python 3.8 or higher
31+
- Azure subscription with AI Foundry access
32+
- [Azure Developer CLI (azd)](https://learn.microsoft.com/azure/developer/azure-developer-cli/install-azd) installed
33+
34+
### 🎯 Commands
35+
36+
Transform your idea into a working agent in seconds:
37+
38+
```bash
39+
# Initialize your project with the AI Foundry starter
40+
azd init --template Azure-Samples/ai-foundry-starter-basic
41+
42+
# Add the Microsoft Learn Agent to your project
43+
azd ai agent init --manifest https://github.com/coreai-microsoft/foundry-golden-path/blob/main/idea-to-proto/01-build-agent-in-code/agent-catalog-code-samples/msft-docs-agent/agent.yaml
44+
45+
# Deploy the agent in Azure AI Foundry
46+
azd up
47+
```
48+
49+
> **💡 Tip:** The `azd` command automatically handles dependency installation and project setup for you!
50+
51+
## 💬 Example Conversations
52+
53+
### Query Azure Functions
54+
55+
```
56+
You: "How do I create an HTTP-triggered Azure Function in Python?"
57+
58+
Agent: "I'll help you create an HTTP-triggered Azure Function in Python! Here's a complete guide:
59+
60+
## Prerequisites
61+
- Azure Functions Core Tools
62+
- Python 3.8-3.11
63+
- Azure CLI
64+
65+
## Step-by-Step Instructions
66+
1. Create a new function app:
67+
```bash
68+
func init MyFunctionApp --python
69+
cd MyFunctionApp
70+
```
71+
72+
2. Create an HTTP trigger function:
73+
```bash
74+
func new --name HttpExample --template "HTTP trigger"
75+
```
76+
77+
[Provides complete code example and deployment instructions...]"
78+
```
79+
80+
## 📖 Learn More
81+
82+
- 🔗 [Microsoft Agent Framework](https://github.com/microsoft/agent-framework) - Official SDK documentation
83+
- 🔗 [Model Context Protocol](https://modelcontextprotocol.io/) - Learn about MCP
84+
- 🔗 [Azure AI Foundry](https://learn.microsoft.com/azure/ai-studio/) - Platform documentation
85+
- 🔗 [Microsoft Learn](https://learn.microsoft.com/) - Source of documentation
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
name: msft-learn-mcp-agent
2+
description: This Agent can access and search Microsoft Learn documentation using MCP (Model Context Protocol) with tool call approval.
3+
metadata:
4+
tags:
5+
- AI Agent Hosting
6+
- Azure AI AgentServer
7+
- MCP
8+
- Microsoft Agent Framework
9+
- Tool Call Approval
10+
authors:
11+
- jeomhove
12+
template:
13+
name: msft-learn-mcp-agent
14+
kind: hosted
15+
protocols:
16+
- protocol: responses
17+
version: v1
18+
environment_variables:
19+
- name: AZURE_AI_PROJECT_ENDPOINT
20+
value: ${AZURE_AI_PROJECT_ENDPOINT}
21+
- name: AZURE_AI_MODEL_DEPLOYMENT_NAME
22+
value: "{{chat}}"
23+
resources:
24+
- kind: model
25+
id: gpt-4o-mini
26+
name: chat
27+
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import asyncio
2+
import os
3+
from agent_framework import ChatAgent, HostedMCPTool
4+
from agent_framework_azure_ai import AzureAIAgentClient
5+
from azure.ai.agentserver.agentframework import from_agent_framework
6+
from azure.identity.aio import DefaultAzureCredential
7+
8+
async def handle_approvals_with_thread(query: str, agent: "AgentProtocol", thread: "AgentThread"):
9+
"""Here we let the thread deal with the previous responses, and we just rerun with the approval."""
10+
from agent_framework import ChatMessage
11+
12+
result = await agent.run(query, thread=thread, store=True)
13+
while len(result.user_input_requests) > 0:
14+
new_input: list[Any] = []
15+
for user_input_needed in result.user_input_requests:
16+
print(
17+
f"User Input Request for function from {agent.name}: {user_input_needed.function_call.name}"
18+
f" with arguments: {user_input_needed.function_call.arguments}"
19+
)
20+
# user_approval = input("Approve function call? (y/n): ")
21+
new_input.append(
22+
ChatMessage(
23+
role="user",
24+
contents=[user_input_needed.create_response(True)],
25+
)
26+
)
27+
result = await agent.run(new_input, thread=thread, store=True)
28+
return result
29+
30+
31+
def get_agent() -> ChatAgent:
32+
"""Create and return a ChatAgent with Bing Grounding search tool."""
33+
assert "AZURE_AI_PROJECT_ENDPOINT" in os.environ, (
34+
"AZURE_AI_PROJECT_ENDPOINT environment variable must be set."
35+
)
36+
assert "AZURE_AI_MODEL_DEPLOYMENT_NAME" in os.environ, (
37+
"AZURE_AI_MODEL_DEPLOYMENT_NAME environment variable must be set."
38+
)
39+
40+
chat_client = AzureAIAgentClient(
41+
endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
42+
async_credential=DefaultAzureCredential(),
43+
)
44+
45+
# Create ChatAgent with the Bing search tool
46+
agent = chat_client.create_agent(
47+
name="DocsAgent",
48+
instructions="You are a helpful assistant that can help with microsoft documentation questions.",
49+
tools=HostedMCPTool(
50+
name="Microsoft Learn MCP",
51+
url="https://learn.microsoft.com/api/mcp",
52+
),
53+
)
54+
return agent
55+
56+
async def test_agent():
57+
agent = get_agent()
58+
thread = agent.get_new_thread()
59+
response = await handle_approvals_with_thread("How do I create an Azure Function in Python?", agent, thread)
60+
print("Agent response:", response.text)
61+
62+
if __name__ == "__main__":
63+
# asyncio.run(test_agent())
64+
from_agent_framework(get_agent()).run()
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
azure-ai-agentserver-agentframework==1.0.0b3
2+
agent-framework
3+
azure-ai-projects==1.1.0b4
4+
5+
pytest==8.4.2
6+
azure-identity==1.25.0
7+
python-dotenv==1.1.1
8+
azure-monitor-opentelemetry==1.8.1

0 commit comments

Comments
 (0)