chore: import upstream snapshot with attribution
CodeQL / Analyze (csharp) (push) Has been cancelled
CodeQL / Analyze (python) (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 13:21:23 +08:00
commit b957a53def
5423 changed files with 863745 additions and 0 deletions
@@ -0,0 +1,6 @@
AZURE_AI_AGENT_PROJECT_CONNECTION_STRING = "<example-connection-string>"
AZURE_AI_AGENT_MODEL_DEPLOYMENT_NAME = "<example-model-deployment-name>"
AZURE_AI_AGENT_ENDPOINT = "<example-endpoint>"
AZURE_AI_AGENT_SUBSCRIPTION_ID = "<example-subscription-id>"
AZURE_AI_AGENT_RESOURCE_GROUP_NAME = "<example-resource-group-name>"
AZURE_AI_AGENT_PROJECT_NAME = "<example-project-name>"
@@ -0,0 +1,124 @@
## Azure AI Agents
The following getting started samples show how to use Azure AI Agents with Semantic Kernel.
To set up the required resources, follow the "Quickstart: Create a new agent" guide [here](https://learn.microsoft.com/en-us/azure/ai-services/agents/quickstart?pivots=programming-language-python-azure).
You will need to install the optional Semantic Kernel `azure` dependencies if you haven't already via:
```bash
pip install semantic-kernel
```
Before running an Azure AI Agent, modify your .env file to include:
```bash
AZURE_AI_AGENT_ENDPOINT = "<example-endpoint-string>"
AZURE_AI_AGENT_MODEL_DEPLOYMENT_NAME = "<example-deployment-name>"
AZURE_AI_AGENT_API_VERSION = "<example-api-version>"
```
The endpoint can be found listed as part of the Azure Foundry [portal](https://ai.azure.com) in the format of: `https://<resource>.services.ai.azure.com/api/projects/<project-name>`.
The .env should be placed in the root directory.
## Configuring the AI Project Client
Ensure that your Azure AI Agent resources are configured with at least a Basic or Standard SKU.
To begin, create the project client as follows:
```python
async with (
AzureCliCredential() as creds,
AzureAIAgent.create_client(credential=creds) as client,
):
# Your operational code here
```
Before running the example, make sure to run `az login` command in shell using Azure CLI to authenticate and get access to Azure services.
### Required Imports
The required imports for the `Azure AI Agent` include async libraries:
```python
from azure.identity.aio import AzureCliCredential
```
### Initializing the Agent
You can pass in an endpoint, along with an optional api-version, to create the client:
```python
ai_agent_settings = AzureAIAgentSettings()
async with (
AzureCliCredential() as creds,
AzureAIAgent.create_client(
credential=creds,
endpoint=ai_agent_settings.endpoint,
api_version=ai_agent_settings.api_version,
) as client,
):
# operational logic
```
### Creating an Agent Definition
Once the client is initialized, you can define the agent:
```python
# Create agent definition
agent_definition = await client.agents.create_agent(
model=ai_agent_settings.model_deployment_name,
name=AGENT_NAME,
instructions=AGENT_INSTRUCTIONS,
)
```
Then, instantiate the `AzureAIAgent` with the `client` and `agent_definition`:
```python
# Create the AzureAI Agent
agent = AzureAIAgent(
client=client,
definition=agent_definition,
)
```
Now, you can create a thread, add chat messages to the agent, and invoke it with given inputs and optional parameters.
### Reusing an Agent Definition
In certain scenarios, you may prefer to reuse an existing agent definition rather than creating a new one. This can be done by calling `await client.agents.get_agent(...)` instead of `await client.agents.create_agent(...)`.
For a practical example, refer to the [`step7_azure_ai_agent_retrieval`](./step7_azure_ai_agent_retrieval.py) sample.
## Requests and Rate Limits
### Managing API Request Frequency
Your default request limits may be low, affecting how often you can poll the status of a run. You have two options:
1. Adjust the `polling_options` of the `AzureAIAgent`
By default, the polling interval is 250 ms. You can slow it down to 1 second (or another preferred value) to reduce the number of API calls:
```python
# Required imports
from datetime import timedelta
from semantic_kernel.agents.run_polling_options import RunPollingOptions
# Configure the polling options as part of the `AzureAIAgent`
agent = AzureAIAgent(
client=client,
definition=agent_definition,
polling_options=RunPollingOptions(run_polling_interval=timedelta(seconds=1)),
)
```
2. Increase Rate Limits in Azure AI Foundry
You can also adjust your deployment's Rate Limit (Tokens per minute), which impacts the Rate Limit (Requests per minute). This can be configured in Azure AI Foundry under your project's deployment settings for the "Connected Azure OpenAI Service Resource."
@@ -0,0 +1,77 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
from azure.identity.aio import AzureCliCredential
from semantic_kernel.agents import AzureAIAgent, AzureAIAgentSettings, AzureAIAgentThread
"""
The following sample demonstrates how to create an Azure AI agent that answers
user questions. This sample demonstrates the basic steps to create an agent
and simulate a conversation with the agent.
The interaction with the agent is via the `get_response` method, which sends a
user input to the agent and receives a response from the agent. The conversation
history is maintained by the agent service, i.e. the responses are automatically
associated with the thread. Therefore, client code does not need to maintain the
conversation history.
"""
# Simulate a conversation with the agent
USER_INPUTS = [
"Hello, I am John Doe.",
"What is your name?",
"What is my name?",
]
async def main() -> None:
async with (
AzureCliCredential() as creds,
AzureAIAgent.create_client(credential=creds) as client,
):
# 1. Create an agent on the Azure AI agent service
agent_definition = await client.agents.create_agent(
model=AzureAIAgentSettings().model_deployment_name,
name="Assistant",
instructions="Answer the user's questions.",
)
# 2. Create a Semantic Kernel agent for the Azure AI agent
agent = AzureAIAgent(
client=client,
definition=agent_definition,
)
# 3. Create a thread for the agent
# If no thread is provided, a new thread will be
# created and returned with the initial response
thread: AzureAIAgentThread = None
try:
for user_input in USER_INPUTS:
print(f"# User: {user_input}")
# 4. Invoke the agent with the specified message for response
response = await agent.get_response(messages=user_input, thread=thread)
print(f"# {response.name}: {response}")
thread = response.thread
finally:
# 6. Cleanup: Delete the thread and agent
await thread.delete() if thread else None
await client.agents.delete_agent(agent.id)
"""
Sample Output:
# User: Hello, I am John Doe.
# Assistant: Hello, John! How can I assist you today?
# User: What is your name?
# Assistant: I'm here as your assistant, so you can just call me Assistant. How can I help you today?
# User: What is my name?
# Assistant: Your name is John Doe. How can I assist you today, John?
"""
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,94 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
from typing import Annotated
from azure.identity.aio import AzureCliCredential
from semantic_kernel.agents import AzureAIAgent, AzureAIAgentSettings
from semantic_kernel.functions import kernel_function
"""
The following sample demonstrates how to create an Azure AI agent that answers
questions about a sample menu using a Semantic Kernel Plugin.
"""
# Define a sample plugin for the sample
class MenuPlugin:
"""A sample Menu Plugin used for the concept sample."""
@kernel_function(description="Provides a list of specials from the menu.")
def get_specials(self) -> Annotated[str, "Returns the specials from the menu."]:
return """
Special Soup: Clam Chowder
Special Salad: Cobb Salad
Special Drink: Chai Tea
"""
@kernel_function(description="Provides the price of the requested menu item.")
def get_item_price(
self, menu_item: Annotated[str, "The name of the menu item."]
) -> Annotated[str, "Returns the price of the menu item."]:
return "$9.99"
# Simulate a conversation with the agent
USER_INPUTS = [
"Hello",
"What is the special soup?",
"How much does that cost?",
"Thank you",
]
async def main() -> None:
async with (
AzureCliCredential() as creds,
AzureAIAgent.create_client(credential=creds) as client,
):
# 1. Create an agent on the Azure AI agent service
agent_definition = await client.agents.create_agent(
model=AzureAIAgentSettings().model_deployment_name,
name="Host",
instructions="Answer questions about the menu.",
)
# 2. Create a Semantic Kernel agent for the Azure AI agent
agent = AzureAIAgent(
client=client,
definition=agent_definition,
plugins=[MenuPlugin()], # Add the plugin to the agent
)
# 3. Create a thread for the agent
# If no thread is provided, a new thread will be
# created and returned with the initial response
thread = None
try:
for user_input in USER_INPUTS:
print(f"# User: {user_input}")
# 4. Invoke the agent for the specified thread for response
async for response in agent.invoke(
messages=user_input,
thread=thread,
):
print(f"# {response.name}: {response}")
thread = response.thread
finally:
# 5. Cleanup: Delete the thread and agent
await thread.delete() if thread else None
await client.agents.delete_agent(agent.id)
"""
Sample Output:
# User: Hello
# Agent: Hello! How can I assist you today?
# User: What is the special soup?
# ...
"""
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,119 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
from azure.identity.aio import AzureCliCredential
from semantic_kernel.agents import AgentGroupChat, AzureAIAgent, AzureAIAgentSettings
from semantic_kernel.agents.strategies import TerminationStrategy
from semantic_kernel.contents import AuthorRole
"""
The following sample demonstrates how to create an OpenAI assistant using either
Azure OpenAI or OpenAI, a chat completion agent and have them participate in a
group chat to work towards the user's requirement.
Note: This sample use the `AgentGroupChat` feature of Semantic Kernel, which is
no longer maintained. For a replacement, consider using the `GroupChatOrchestration`.
Read more about the `GroupChatOrchestration` here:
https://learn.microsoft.com/semantic-kernel/frameworks/agent/agent-orchestration/group-chat?pivots=programming-language-python
Here is a migration guide from `AgentGroupChat` to `GroupChatOrchestration`:
https://learn.microsoft.com/semantic-kernel/support/migration/group-chat-orchestration-migration-guide?pivots=programming-language-python
"""
class ApprovalTerminationStrategy(TerminationStrategy):
"""A strategy for determining when an agent should terminate."""
async def should_agent_terminate(self, agent, history):
"""Check if the agent should terminate."""
return "approved" in history[-1].content.lower()
REVIEWER_NAME = "ArtDirector"
REVIEWER_INSTRUCTIONS = """
You are an art director who has opinions about copywriting born of a love for David Ogilvy.
The goal is to determine if the given copy is acceptable to print.
If so, state that it is approved. Do not use the word "approve" unless you are giving approval.
If not, provide insight on how to refine suggested copy without example.
"""
COPYWRITER_NAME = "CopyWriter"
COPYWRITER_INSTRUCTIONS = """
You are a copywriter with ten years of experience and are known for brevity and a dry humor.
The goal is to refine and decide on the single best copy as an expert in the field.
Only provide a single proposal per response.
You're laser focused on the goal at hand.
Don't waste time with chit chat.
Consider suggestions when refining an idea.
"""
TASK = "a slogan for a new line of electric cars."
async def main():
ai_agent_settings = AzureAIAgentSettings()
async with (
AzureCliCredential() as creds,
AzureAIAgent.create_client(credential=creds) as client,
):
# 1. Create the reviewer agent on the Azure AI agent service
reviewer_agent_definition = await client.agents.create_agent(
model=ai_agent_settings.model_deployment_name,
name=REVIEWER_NAME,
instructions=REVIEWER_INSTRUCTIONS,
)
# 2. Create a Semantic Kernel agent for the reviewer Azure AI agent
agent_reviewer = AzureAIAgent(
client=client,
definition=reviewer_agent_definition,
)
# 3. Create the copy writer agent on the Azure AI agent service
copy_writer_agent_definition = await client.agents.create_agent(
model=ai_agent_settings.model_deployment_name,
name=COPYWRITER_NAME,
instructions=COPYWRITER_INSTRUCTIONS,
)
# 4. Create a Semantic Kernel agent for the copy writer Azure AI agent
agent_writer = AzureAIAgent(
client=client,
definition=copy_writer_agent_definition,
)
# 5. Place the agents in a group chat with a custom termination strategy
chat = AgentGroupChat(
agents=[agent_writer, agent_reviewer],
termination_strategy=ApprovalTerminationStrategy(agents=[agent_reviewer], maximum_iterations=10),
)
try:
# 6. Add the task as a message to the group chat
await chat.add_chat_message(message=TASK)
print(f"# {AuthorRole.USER}: '{TASK}'")
# 7. Invoke the chat
async for content in chat.invoke():
print(f"# {content.role} - {content.name or '*'}: '{content.content}'")
finally:
# 8. Cleanup: Delete the agents
await chat.reset()
await client.agents.delete_agent(agent_reviewer.id)
await client.agents.delete_agent(agent_writer.id)
"""
Sample Output:
# AuthorRole.USER: 'a slogan for a new line of electric cars.'
# AuthorRole.ASSISTANT - CopyWriter: '"Charge Ahead: Drive the Future."'
# AuthorRole.ASSISTANT - ArtDirector: 'This slogan has a nice ring to it and captures the ...'
# AuthorRole.ASSISTANT - CopyWriter: '"Plug In. Drive Green."'
...
"""
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,133 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
import os
from azure.ai.agents.models import CodeInterpreterTool, FilePurpose
from azure.identity.aio import AzureCliCredential
from semantic_kernel.agents import AzureAIAgent, AzureAIAgentSettings, AzureAIAgentThread
from semantic_kernel.contents import AuthorRole
"""
The following sample demonstrates how to create a simple, Azure AI agent that
uses the code interpreter tool to answer a coding question.
"""
TASK = "What's the total sum of all sales for all segments using Python?"
async def main() -> None:
async with (
AzureCliCredential() as creds,
AzureAIAgent.create_client(credential=creds) as client,
):
# 1. Create an agent with a code interpreter on the Azure AI agent service
csv_file_path = os.path.join(
os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "resources", "sales.csv"
)
# 2. Upload the CSV file to the Azure AI agent service
file = await client.agents.files.upload_and_poll(file_path=csv_file_path, purpose=FilePurpose.AGENTS)
# 3. Create a code interpreter tool referencing the uploaded file
code_interpreter = CodeInterpreterTool(file_ids=[file.id])
agent_definition = await client.agents.create_agent(
model=AzureAIAgentSettings().model_deployment_name,
tools=code_interpreter.definitions,
tool_resources=code_interpreter.resources,
)
# 4. Create a Semantic Kernel agent for the Azure AI agent
agent = AzureAIAgent(
client=client,
definition=agent_definition,
)
# 5. Create a thread for the agent
# If no thread is provided, a new thread will be
# created and returned with the initial response
thread: AzureAIAgentThread | None = None
try:
print(f"# User: '{TASK}'")
# 6. Invoke the agent for the specified thread for response
async for response in agent.invoke(messages=TASK, thread=thread):
if response.role != AuthorRole.TOOL:
print(f"# Agent: {response}")
thread = response.thread
finally:
# 7. Cleanup: Delete the thread, agent, and file
await thread.delete() if thread else None
await client.agents.delete_agent(agent.id)
await client.agents.files.delete(file.id)
"""
Sample Output:
# User: 'Give me the code to calculate the total sales for all segments.'
# AuthorRole.ASSISTANT: Let me first load the uploaded file to understand its contents before providing
tailored code.
```python
import pandas as pd
# Load the uploaded file
file_path = '/mnt/data/assistant-GBaUAF6AKds3sfdfSpxJZG'
data = pd.read_excel(file_path) # Attempting to load as an Excel file initially
# Display the first few rows and understand its structure
data.head(), data.info()
```
# AuthorRole.ASSISTANT: The file format couldn't be automatically determined. Let me attempt to load it as a
CSV or other type.
```python
# Attempt to load the file as a CSV
data = pd.read_csv(file_path)
# Display the first few rows of the dataset and its information
data.head(), data.info()
```
# AuthorRole.ASSISTANT: <class 'pandas.core.frame.DataFrame'>
RangeIndex: 700 entries, 0 to 699
Data columns (total 14 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Segment 700 non-null object
1 Country 700 non-null object
2 Product 700 non-null object
3 Units Sold 700 non-null float64
4 Sale Price 700 non-null float64
5 Gross Sales 700 non-null float64
6 Discounts 700 non-null float64
7 Sales 700 non-null float64
8 COGS 700 non-null float64
9 Profit 700 non-null float64
10 Date 700 non-null object
11 Month Number 700 non-null int64
12 Month Name 700 non-null object
13 Year 700 non-null int64
dtypes: float64(7), int64(2), object(5)
memory usage: 76.7+ KB
The dataset has been successfully loaded and contains information regarding sales, profits, and related metrics
for various segments. To calculate the total sales across all segments, we can use the "Sales" column.
Here's the code to calculate the total sales:
```python
# Calculate the total sales for all segments
total_sales = data['Sales'].sum()
total_sales
```
# AuthorRole.ASSISTANT: The total sales for all segments amount to approximately **118,726,350.29**. Let me
know if you need additional analysis or code for manipulating this data!
"""
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,84 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
import os
from azure.ai.agents.models import FileInfo, FileSearchTool, VectorStore
from azure.identity.aio import AzureCliCredential
from semantic_kernel.agents import AzureAIAgent, AzureAIAgentSettings, AzureAIAgentThread
from semantic_kernel.contents import AuthorRole
"""
The following sample demonstrates how to create a simple, Azure AI agent that
uses a file search tool to answer user questions.
"""
# Simulate a conversation with the agent
USER_INPUTS = [
"Who is the youngest employee?",
"Who works in sales?",
"I have a customer request, who can help me?",
]
async def main() -> None:
async with (
AzureCliCredential() as creds,
AzureAIAgent.create_client(credential=creds) as client,
):
# 1. Read and upload the file to the Azure AI agent service
pdf_file_path = os.path.join(
os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "resources", "employees.pdf"
)
file: FileInfo = await client.agents.files.upload_and_poll(file_path=pdf_file_path, purpose="assistants")
vector_store: VectorStore = await client.agents.vector_stores.create_and_poll(
file_ids=[file.id], name="my_vectorstore"
)
# 2. Create file search tool with uploaded resources
file_search = FileSearchTool(vector_store_ids=[vector_store.id])
# 3. Create an agent on the Azure AI agent service with the file search tool
agent_definition = await client.agents.create_agent(
model=AzureAIAgentSettings().model_deployment_name,
tools=file_search.definitions,
tool_resources=file_search.resources,
)
# 4. Create a Semantic Kernel agent for the Azure AI agent
agent = AzureAIAgent(
client=client,
definition=agent_definition,
)
# 5. Create a thread for the agent
# If no thread is provided, a new thread will be
# created and returned with the initial response
thread: AzureAIAgentThread = None
try:
for user_input in USER_INPUTS:
print(f"# User: '{user_input}'")
# 6. Invoke the agent for the specified thread for response
async for response in agent.invoke(messages=user_input, thread=thread):
if response.role != AuthorRole.TOOL:
print(f"# Agent: {response}")
thread = response.thread
finally:
# 7. Cleanup: Delete the thread and agent and other resources
await thread.delete() if thread else None
await client.agents.vector_stores.delete(vector_store.id)
await client.agents.files.delete(file.id)
await client.agents.delete_agent(agent.id)
"""
Sample Output:
# User: 'Who is the youngest employee?'
# Agent: The youngest employee is Teodor Britton, who is an accountant and was born on January 9, 1997...
# User: 'Who works in sales?'
"""
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,119 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
import json
import os
from azure.ai.agents.models import OpenApiAnonymousAuthDetails, OpenApiTool
from azure.identity.aio import AzureCliCredential
from semantic_kernel.agents import AzureAIAgent, AzureAIAgentSettings, AzureAIAgentThread
from semantic_kernel.contents import ChatMessageContent, FunctionCallContent, FunctionResultContent
"""
The following sample demonstrates how to create a simple, Azure AI agent that
uses OpenAPI tools to answer user questions.
"""
# Simulate a conversation with the agent
USER_INPUTS = [
"What is the name and population of the country that uses currency with abbreviation THB",
"What is the current weather in the capital city of the country?",
]
async def handle_streaming_intermediate_steps(message: ChatMessageContent) -> None:
for item in message.items or []:
if isinstance(item, FunctionResultContent):
print(f"Function Result:> {item.result} for function: {item.name}")
elif isinstance(item, FunctionCallContent):
print(f"Function Call:> {item.name} with arguments: {item.arguments}")
else:
print(f"{item}")
async def main() -> None:
async with (
AzureCliCredential() as creds,
AzureAIAgent.create_client(credential=creds) as client,
):
# 1. Read in the OpenAPI spec files
openapi_spec_file_path = os.path.join(
os.path.dirname(os.path.dirname(os.path.realpath(__file__))),
"resources",
)
with open(os.path.join(openapi_spec_file_path, "weather.json")) as weather_file:
weather_openapi_spec = json.loads(weather_file.read())
with open(os.path.join(openapi_spec_file_path, "countries.json")) as countries_file:
countries_openapi_spec = json.loads(countries_file.read())
# 2. Create OpenAPI tools
# Note that connection or managed identity auth setup requires additional setup in Azure
auth = OpenApiAnonymousAuthDetails()
openapi_weather = OpenApiTool(
name="get_weather",
spec=weather_openapi_spec,
description="Retrieve weather information for a location",
auth=auth,
)
openapi_countries = OpenApiTool(
name="get_country",
spec=countries_openapi_spec,
description="Retrieve country information",
auth=auth,
)
# 3. Create an agent on the Azure AI agent service with the OpenAPI tools
agent_definition = await client.agents.create_agent(
model=AzureAIAgentSettings().model_deployment_name,
tools=openapi_weather.definitions + openapi_countries.definitions,
)
# 4. Create a Semantic Kernel agent for the Azure AI agent
agent = AzureAIAgent(
client=client,
definition=agent_definition,
)
# 5. Create a thread for the agent
# If no thread is provided, a new thread will be
# created and returned with the initial response
thread: AzureAIAgentThread = None
try:
for user_input in USER_INPUTS:
print(f"# User: '{user_input}'")
# 7. Invoke the agent for the specified thread for response
async for response in agent.invoke(messages=user_input, thread=thread):
print(f"# Agent: {response}")
thread = response.thread
finally:
# 8. Cleanup: Delete the thread and agent
await client.agents.threads.delete(thread.id) if thread else None
await client.agents.delete_agent(agent.id)
"""
Sample Output:
# User: 'What is the name and population of the country that uses currency with abbreviation THB'
# Agent: It seems I encountered an issue while trying to retrieve data about the country that uses the ...
As of the latest estimates, the population of Thailand is approximately 69 million people. If you ...
# User: 'What is the current weather in the capital city of the country?'
# Agent: The current weather in Bangkok, Thailand, the capital city, is as follows:
- **Temperature**: 24°C (76°F)
- **Feels Like**: 26°C (79°F)
- **Weather Description**: Light rain
- **Humidity**: 69%
- **Cloud Cover**: 75%
- **Pressure**: 1017 hPa
- **Wind Speed**: 8 km/h (5 mph) from the east-northeast (ENE)
- **Visibility**: 10 km (approximately 6 miles)
This weather information reflects the current conditions as of the latest observation. If you need ...
"""
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,84 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
from azure.identity.aio import AzureCliCredential
from semantic_kernel.agents import AzureAIAgent, AzureAIAgentThread
from semantic_kernel.contents import ChatMessageContent, FunctionCallContent, FunctionResultContent
"""
The following sample demonstrates how to use an already existing
Azure AI Agent within Semantic Kernel. This sample requires that you
have an existing agent created either previously in code or via the
Azure Portal (or CLI).
"""
# Simulate a conversation with the agent
USER_INPUTS = [
"Using the provided doc, tell me about the evolution of RAG.",
]
async def handle_streaming_intermediate_steps(message: ChatMessageContent) -> None:
for item in message.items or []:
if isinstance(item, FunctionResultContent):
print(f"Function Result:> {item.result} for function: {item.name}")
elif isinstance(item, FunctionCallContent):
print(f"Function Call:> {item.name} with arguments: {item.arguments}")
else:
print(f"{item}")
async def main() -> None:
async with (
AzureCliCredential() as creds,
AzureAIAgent.create_client(credential=creds) as client,
):
# 1. Retrieve the agent definition based on the `agent_id`
# Replace the "your-agent-id" with the actual agent ID
# you want to use.
agent_definition = await client.agents.get_agent(
agent_id="<your-agent-id>",
)
# 2. Create a Semantic Kernel agent for the Azure AI agent
agent = AzureAIAgent(
client=client,
definition=agent_definition,
)
# 3. Create a thread for the agent
# If no thread is provided, a new thread will be
# created and returned with the initial response
thread: AzureAIAgentThread = None
try:
for user_input in USER_INPUTS:
print(f"# User: '{user_input}'")
# 4. Invoke the agent for the specified thread for response
async for response in agent.invoke_stream(
messages=user_input,
thread=thread,
on_intermediate_message=handle_streaming_intermediate_steps,
):
# Print the agent's response
print(f"{response}", end="", flush=True)
# Update the thread for subsequent messages
thread = response.thread
finally:
# 5. Cleanup: Delete the thread and agent
await thread.delete() if thread else None
# Do not clean up the agent so it can be used again
"""
Sample Output:
# User: 'Why is the sky blue?'
# Agent: The sky appears blue because molecules in the Earth's atmosphere scatter sunlight,
and blue light is scattered more than other colors due to its shorter wavelength.
"""
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,110 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
from typing import Annotated
from azure.identity.aio import AzureCliCredential
from semantic_kernel.agents import AgentRegistry, AzureAIAgent, AzureAIAgentSettings
from semantic_kernel.functions import kernel_function
from semantic_kernel.kernel import Kernel
"""
The following sample demonstrates how to create an Azure AI agent that answers
questions about a sample menu using a Semantic Kernel Plugin. The agent is created
using a yaml declarative spec.
"""
# Define a sample plugin for the sample
class MenuPlugin:
"""A sample Menu Plugin used for the concept sample."""
@kernel_function(description="Provides a list of specials from the menu.")
def get_specials(self) -> Annotated[str, "Returns the specials from the menu."]:
return """
Special Soup: Clam Chowder
Special Salad: Cobb Salad
Special Drink: Chai Tea
"""
@kernel_function(description="Provides the price of the requested menu item.")
def get_item_price(
self, menu_item: Annotated[str, "The name of the menu item."]
) -> Annotated[str, "Returns the price of the menu item."]:
return "$9.99"
# Simulate a conversation with the agent
USER_INPUTS = [
"Hello",
"What is the special soup?",
"How much does that cost?",
"Thank you",
]
# Define the YAML string for the sample
SPEC = """
type: foundry_agent
name: Host
instructions: Respond politely to the user's questions.
model:
id: ${AzureAI:ChatModelId}
tools:
- id: MenuPlugin.get_specials
type: function
- id: MenuPlugin.get_item_price
type: function
"""
async def main() -> None:
settings = AzureAIAgentSettings()
async with (
AzureCliCredential() as creds,
AzureAIAgent.create_client(credential=creds) as client,
):
# 1. Create a Kernel instance
# For declarative agents, the kernel is required to resolve the plugin(s)
kernel = Kernel()
kernel.add_plugin(MenuPlugin())
# 2. Create a Semantic Kernel agent for the Azure AI agent
agent: AzureAIAgent = await AgentRegistry.create_from_yaml(
SPEC,
kernel=kernel,
settings=settings,
client=client,
)
# 3. Create a thread for the agent
# If no thread is provided, a new thread will be
# created and returned with the initial response
thread = None
try:
for user_input in USER_INPUTS:
print(f"# User: {user_input}")
# 4. Invoke the agent for the specified thread for response
async for response in agent.invoke(
messages=user_input,
thread=thread,
):
print(f"# {response.name}: {response}")
thread = response.thread
finally:
# 5. Cleanup: Delete the thread and agent
await thread.delete() if thread else None
await client.agents.delete_agent(agent.id)
"""
Sample Output:
# User: Hello
# Agent: Hello! How can I assist you today?
# User: What is the special soup?
# ...
"""
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,119 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
from azure.ai.agents.models import McpTool
from azure.identity.aio import AzureCliCredential
from semantic_kernel.agents import AzureAIAgent, AzureAIAgentSettings, AzureAIAgentThread
from semantic_kernel.contents import ChatMessageContent, FunctionCallContent, FunctionResultContent
"""
The following sample demonstrates how to create a simple, Azure AI agent that
uses the mcp tool to connect to an mcp server.
"""
TASK = "Please summarize the Azure REST API specifications Readme"
async def handle_intermediate_messages(message: ChatMessageContent) -> None:
for item in message.items or []:
if isinstance(item, FunctionResultContent):
print(f"Function Result:> {item.result} for function: {item.name}")
elif isinstance(item, FunctionCallContent):
print(f"Function Call:> {item.name} with arguments: {item.arguments}")
else:
print(f"{item}")
async def main() -> None:
async with (
AzureCliCredential() as creds,
AzureAIAgent.create_client(credential=creds) as client,
):
# 1. Define the MCP tool with the server URL
mcp_tool = McpTool(
server_label="github",
server_url="https://gitmcp.io/Azure/azure-rest-api-specs",
allowed_tools=[], # Specify allowed tools if needed
)
# Optionally you may configure to require approval
# Allowed values are "never" or "always"
mcp_tool.set_approval_mode("never")
# 2. Create an agent with the MCP tool on the Azure AI agent service
agent_definition = await client.agents.create_agent(
model=AzureAIAgentSettings().model_deployment_name,
tools=mcp_tool.definitions,
instructions="You are a helpful agent that can use MCP tools to assist users.",
)
# 3. Create a Semantic Kernel agent for the Azure AI agent
agent = AzureAIAgent(
client=client,
definition=agent_definition,
)
# 4. Create a thread for the agent
# If no thread is provided, a new thread will be
# created and returned with the initial response
thread: AzureAIAgentThread | None = None
try:
print(f"# User: '{TASK}'")
# 5. Invoke the agent for the specified thread for response
async for response in agent.invoke(
messages=TASK, thread=thread, on_intermediate_message=handle_intermediate_messages
):
print(f"# Agent: {response}")
thread = response.thread
finally:
# 6. Cleanup: Delete the thread, agent, and file
await thread.delete() if thread else None
await client.agents.delete_agent(agent.id)
"""
Sample Output:
# User: 'Please summarize the Azure REST API specifications Readme'
Function Call:> fetch_azure_rest_api_docs with arguments: {}
The Azure REST API specifications Readme provides comprehensive documentation and guidelines for designing,
authoring, validating, and evolving Azure REST APIs. It covers key areas including:
1. Breaking changes and versioning: Guidelines to manage API changes that break backward compatibility, when to
increment API versions, and how to maintain smooth API evolution.
2. OpenAPI/Swagger specifications: How to author REST APIs using OpenAPI specification 2.0 (Swagger), including
structure, conventions, validation tools, and extensions used by AutoRest for generating client SDKs.
3. TypeSpec language: Introduction to TypeSpec, a powerful language for describing and generating REST API
specifications and client SDKs with extensibility to other API styles.
4. Directory structure and uniform versioning: Organizing service specifications by teams, resource provider
namespaces, and following uniform versioning to keep API versions consistent across documentation and SDKs.
5. Validation and tooling: Tools and processes like OAV, AutoRest, RESTler, and CI checks used to validate API
specs, generate SDKs, detect breaking changes, lint specifications, and test service contract accuracy.
6. Authoring best practices: Manual and automated guidelines for quality API spec authoring, including writing
effective descriptions, resource modeling, naming conventions, and examples.
7. Code generation configurations: How to configure readme files to generate SDKs for various languages
including .NET, Java, Python, Go, Typescript, and Azure CLI using AutoRest.
8. API Scenarios and testing: Defining API scenario test files for end-to-end REST API workflows, including
variables, ARM template integration, and usage of test-proxy for recording traffic.
9. SDK automation and release requests: Workflows for SDK generation validation, suppressing breaking change
warnings, and requesting official Azure SDK releases.
Overall, the Readme acts as a central hub providing references, guidelines, examples, and tools for maintaining
high-quality Azure REST API specifications and seamless SDK generation across multiple languages and
platforms. It ensures consistent API design, versioning, validation, and developer experience in the Azure
ecosystem.
"""
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,143 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
from datetime import timedelta
from azure.ai.agents.models import DeepResearchTool
from azure.identity.aio import AzureCliCredential
from semantic_kernel.agents import AzureAIAgent, AzureAIAgentSettings, AzureAIAgentThread, RunPollingOptions
from semantic_kernel.contents import AnnotationContent, ChatMessageContent, FunctionCallContent, FunctionResultContent
"""
The following sample demonstrates how to create an AzureAIAgent along
with the Deep Research Tool. Please visit the following documentation for more info
on what is required to run the sample: https://aka.ms/agents-deep-research. Please pay
attention to the purple `Note` boxes in the Azure docs.
Note that when you use your Bing Connection ID, it needs to be the connection ID from the project, not the resource.
It has the following format:
'/subscriptions/<sub_id>/resourceGroups/<rg_name>/providers/<provider_name>/accounts/<account_name>/projects/<project_name>/connections/<connection_name>'
"""
TASK = (
"Research the current state of studies on orca intelligence and orca language, "
"including what is currently known about orcas' cognitive capabilities and communication systems."
)
async def handle_intermediate_messages(message: ChatMessageContent) -> None:
for item in message.items or []:
if isinstance(item, FunctionResultContent):
print(f"Function Result:> {item.result} for function: {item.name}")
elif isinstance(item, FunctionCallContent):
print(f"Function Call:> {item.name} with arguments: {item.arguments}")
else:
print(f"{item}")
print()
async def main() -> None:
async with (
AzureCliCredential() as creds,
AzureAIAgent.create_client(credential=creds) as client,
):
azure_ai_agent_settings = AzureAIAgentSettings()
# 1. Define the Deep Research tool
deep_research_tool = DeepResearchTool(
bing_grounding_connection_id=azure_ai_agent_settings.bing_connection_id,
deep_research_model=azure_ai_agent_settings.deep_research_model,
)
# 2. Create an agent with the tool on the Azure AI agent service
agent_definition = await client.agents.create_agent(
model="gpt-4o",
tools=deep_research_tool.definitions,
instructions="You are a helpful Agent that assists in researching scientific topics.",
)
# 3. Create a Semantic Kernel agent for the Azure AI agent
agent = AzureAIAgent(client=client, definition=agent_definition, name="DeepResearchAgent")
# 4. Create a thread for the agent
# If no thread is provided, a new thread will be
# created and returned with the initial response
thread: AzureAIAgentThread | None = None
try:
print(f"# User: '{TASK}'")
# 5. Invoke the agent for the specified thread for response
async for response in agent.invoke(
messages=TASK,
thread=thread,
on_intermediate_message=handle_intermediate_messages,
polling_options=RunPollingOptions(run_polling_timeout=timedelta(minutes=10)),
):
# Note that the underlying Deep Research Tool uses the o3 reasoning model.
# When using the non-streaming invoke, it is normal for there to be
# several minutes of processing before agent response(s) appear.
# For a fast response, consider using the streaming invoke method.
# A sample exists in the `concepts/agents/azure_ai_agent` directory.
print(f"# {response.name}: {response}")
for item in response.items or []:
if isinstance(item, AnnotationContent):
label = item.title or item.url or (item.quote or "Annotation")
print(f"\n[Annotation] {label} -> {item.url}")
thread = response.thread
finally:
# 6. Cleanup: Delete the thread, agent, and file
await thread.delete() if thread else None
await client.agents.delete_agent(agent.id)
"""
Sample Output:
# User: 'Research the current state of studies on orca intelligence and orca language, including what is
currently known about orcas' cognitive capabilities and communication systems.'
Function Call:> deep_research with arguments: {'input': '{"prompt": "Research the current state of studies on
orca intelligence and orca language. Include up-to-date findings on both their cognitive capabilities and
communication systems. Structure the findings as a detailed report with well-formatted headers that break down
topics such as orcas\' cognitive skills (e.g., problem-solving, memory, and social intelligence), their
language or communication methods (e.g., vocalizations, dialects, and symbolic communication), and comparisons
to other highly intelligent species. Include sources, prioritize recent peer-reviewed studies and reputable
marine biology publications, and ensure the report is well-cited and clear."}'}
# DeepResearchAgent: Got it! I'll gather recent studies and findings on orca intelligence and their
# communication systems, focusing on cognitive abilities and the mechanisms of their language.
# I'll update you with a comprehensive overview soon.
Title: Current Research on Orca Intelligence and Language
Starting deep research...
# DeepResearchAgent: cot_summary: **Examining orca intelligence**
The task involves looking into orca cognitive abilities, communication methods, and comparisons with
other intelligent species. It includes recent peer-reviewed studies and credible sources. 【1†Bing Search】
[Annotation] Bing Search: '2024 orca intelligence cognitive study research' -> https://www.bing.com/search?q=2024%20orca%20intelligence%20cognitive%20study%20research
# DeepResearchAgent: cot_summary: **Investigating orca intelligence**
I'm curious about headlines discussing orcas' cognitive abilities and behaviors, especially their tool use,
recent attacks, and comparisons with dolphins. 【1†Bing Search】
[Annotation] Bing Search: 'orca cognition recent peer-reviewed studies orca communication recent study' -> https://www.bing.com/search?q=orca%20cognition%20recent%20peer-reviewed%20studies%20orca%20communication%20recent%20study
# DeepResearchAgent: cot_summary: **Researching social dynamics**
I'm gathering info on killer whale social dynamics from what appears to be a 2024 article on ResearchGate.
# DeepResearchAgent: cot_summary: **Assessing publication type**
I'm exploring if the ResearchGate link points to a preprint, student paper, or journal article.
Progress is steady as I look into its initiation and source.
# DeepResearchAgent: cot_summary: **Investigating PDF issues**
...
"""
if __name__ == "__main__":
asyncio.run(main())