Python: [BREAKING] Replace Hosted*Tool classes with tool methods (#3634)

* Replace Hosted*Tool classes with client static factory methods

* fixed failing test

* mypy fix

* mypy fix 2

* declarative mypy fix

* addressed comments

* ToolProtocol removal

* fixed test

* agents mypy fix

* fix failing tests

* mypy fix

* addressed comments

* fixed tests

* addressed comments + added factory method overrides for azureai v2 client

* mypy fix

* added kwargs to azureai tool methods

* fixed in test

* _sessions fix

* test fix
This commit is contained in:
Giles Odigwe
2026-02-10 16:04:27 -08:00
committed by GitHub
Unverified
parent d249473a6d
commit 7a88af0aef
133 changed files with 3018 additions and 2650 deletions
@@ -1,20 +1,23 @@
# Copyright (c) Microsoft. All rights reserved.
from agent_framework import HostedMCPTool
from agent_framework.azure import AzureOpenAIChatClient
from azure.ai.agentserver.agentframework import from_agent_framework # pyright: ignore[reportUnknownVariableType]
from azure.identity import DefaultAzureCredential
def main():
# Create MCP tool configuration as dict
mcp_tool = {
"type": "mcp",
"server_label": "Microsoft_Learn_MCP",
"server_url": "https://learn.microsoft.com/api/mcp",
}
# Create an Agent using the Azure OpenAI Chat Client with a MCP Tool that connects to Microsoft Learn MCP
agent = AzureOpenAIChatClient(credential=DefaultAzureCredential()).as_agent(
name="DocsAgent",
instructions="You are a helpful assistant that can help with microsoft documentation questions.",
tools=HostedMCPTool(
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
),
tools=mcp_tool,
)
# Run the agent as a hosted agent
@@ -2,7 +2,6 @@
import asyncio
from agent_framework import HostedMCPTool, HostedWebSearchTool
from agent_framework.anthropic import AnthropicChatOptions, AnthropicClient
"""
@@ -17,16 +16,21 @@ This sample demonstrates using Anthropic with:
async def main() -> None:
"""Example of streaming response (get results as they are generated)."""
agent = AnthropicClient[AnthropicChatOptions]().as_agent(
client = AnthropicClient[AnthropicChatOptions]()
# Create MCP tool configuration using instance method
mcp_tool = client.get_mcp_tool(
name="Microsoft_Learn_MCP",
url="https://learn.microsoft.com/api/mcp",
)
# Create web search tool configuration using instance method
web_search_tool = client.get_web_search_tool()
agent = client.as_agent(
name="DocsAgent",
instructions="You are a helpful agent for both Microsoft docs questions and general questions.",
tools=[
HostedMCPTool(
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
),
HostedWebSearchTool(),
],
tools=[mcp_tool, web_search_tool],
default_options={
# anthropic needs a value for the max_tokens parameter
# we set it to 1024, but you can override like this:
@@ -2,7 +2,6 @@
import asyncio
from agent_framework import HostedMCPTool, HostedWebSearchTool
from agent_framework.anthropic import AnthropicClient
from anthropic import AsyncAnthropicFoundry
@@ -28,16 +27,21 @@ To use the Foundry integration ensure you have the following environment variabl
async def main() -> None:
"""Example of streaming response (get results as they are generated)."""
agent = AnthropicClient(anthropic_client=AsyncAnthropicFoundry()).as_agent(
client = AnthropicClient(anthropic_client=AsyncAnthropicFoundry())
# Create MCP tool configuration using instance method
mcp_tool = client.get_mcp_tool(
name="Microsoft_Learn_MCP",
url="https://learn.microsoft.com/api/mcp",
)
# Create web search tool configuration using instance method
web_search_tool = client.get_web_search_tool()
agent = client.as_agent(
name="DocsAgent",
instructions="You are a helpful agent for both Microsoft docs questions and general questions.",
tools=[
HostedMCPTool(
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
),
HostedWebSearchTool(),
],
tools=[mcp_tool, web_search_tool],
default_options={
# anthropic needs a value for the max_tokens parameter
# we set it to 1024, but you can override like this:
@@ -4,7 +4,7 @@ import asyncio
import logging
from pathlib import Path
from agent_framework import Content, HostedCodeInterpreterTool
from agent_framework import Content
from agent_framework.anthropic import AnthropicChatOptions, AnthropicClient
logger = logging.getLogger(__name__)
@@ -34,7 +34,7 @@ async def main() -> None:
agent = client.as_agent(
name="DocsAgent",
instructions="You are a helpful agent for creating powerpoint presentations.",
tools=HostedCodeInterpreterTool(),
tools=client.get_code_interpreter_tool(),
default_options={
"max_tokens": 20000,
"thinking": {"type": "enabled", "budget_tokens": 10000},
@@ -15,7 +15,7 @@ This folder contains examples demonstrating different ways to create and use age
| [`azure_ai_with_bing_grounding.py`](azure_ai_with_bing_grounding.py) | Shows how to use Bing Grounding search with Azure AI agents to search the web for current information and provide grounded responses with citations. Requires a Bing connection configured in your Azure AI project. |
| [`azure_ai_with_bing_custom_search.py`](azure_ai_with_bing_custom_search.py) | Shows how to use Bing Custom Search with Azure AI agents to search custom search instances and provide responses with relevant results. Requires a Bing Custom Search connection and instance configured in your Azure AI project. |
| [`azure_ai_with_browser_automation.py`](azure_ai_with_browser_automation.py) | Shows how to use Browser Automation with Azure AI agents to perform automated web browsing tasks and provide responses based on web interactions. Requires a Browser Automation connection configured in your Azure AI project. |
| [`azure_ai_with_code_interpreter.py`](azure_ai_with_code_interpreter.py) | Shows how to use the `HostedCodeInterpreterTool` with Azure AI agents to write and execute Python code for mathematical problem solving and data analysis. |
| [`azure_ai_with_code_interpreter.py`](azure_ai_with_code_interpreter.py) | Shows how to use `AzureAIClient.get_code_interpreter_tool()` with Azure AI agents to write and execute Python code for mathematical problem solving and data analysis. |
| [`azure_ai_with_code_interpreter_file_generation.py`](azure_ai_with_code_interpreter_file_generation.py) | Shows how to retrieve file IDs from code interpreter generated files using both streaming and non-streaming approaches. |
| [`azure_ai_with_code_interpreter_file_download.py`](azure_ai_with_code_interpreter_file_download.py) | Shows how to download files generated by code interpreter using the OpenAI containers API. |
| [`azure_ai_with_content_filtering.py`](azure_ai_with_content_filtering.py) | Shows how to enable content filtering (RAI policy) on Azure AI agents using `RaiConfig`. Requires creating an RAI policy in Azure AI Foundry portal first. |
@@ -23,8 +23,8 @@ This folder contains examples demonstrating different ways to create and use age
| [`azure_ai_with_existing_conversation.py`](azure_ai_with_existing_conversation.py) | Demonstrates how to use an existing conversation created on the service side with Azure AI agents. Shows two approaches: specifying conversation ID at the client level and using AgentThread with an existing conversation ID. |
| [`azure_ai_with_application_endpoint.py`](azure_ai_with_application_endpoint.py) | Demonstrates calling the Azure AI application-scoped endpoint. |
| [`azure_ai_with_explicit_settings.py`](azure_ai_with_explicit_settings.py) | Shows how to create an agent with explicitly configured `AzureAIClient` settings, including project endpoint, model deployment, and credentials rather than relying on environment variable defaults. |
| [`azure_ai_with_file_search.py`](azure_ai_with_file_search.py) | Shows how to use the `HostedFileSearchTool` with Azure AI agents to upload files, create vector stores, and enable agents to search through uploaded documents to answer user questions. |
| [`azure_ai_with_hosted_mcp.py`](azure_ai_with_hosted_mcp.py) | Shows how to integrate hosted Model Context Protocol (MCP) tools with Azure AI Agent. |
| [`azure_ai_with_file_search.py`](azure_ai_with_file_search.py) | Shows how to use `AzureAIClient.get_file_search_tool()` with Azure AI agents to upload files, create vector stores, and enable agents to search through uploaded documents to answer user questions. |
| [`azure_ai_with_hosted_mcp.py`](azure_ai_with_hosted_mcp.py) | Shows how to integrate hosted Model Context Protocol (MCP) tools with Azure AI Agent using `AzureAIClient.get_mcp_tool()`. |
| [`azure_ai_with_local_mcp.py`](azure_ai_with_local_mcp.py) | Shows how to integrate local Model Context Protocol (MCP) tools with Azure AI agents. |
| [`azure_ai_with_response_format.py`](azure_ai_with_response_format.py) | Shows how to use structured outputs (response format) with Azure AI agents using Pydantic models to enforce specific response schemas. |
| [`azure_ai_with_runtime_json_schema.py`](azure_ai_with_runtime_json_schema.py) | Shows how to use structured outputs (response format) with Azure AI agents using a JSON schema to enforce specific response schemas. |
@@ -32,12 +32,12 @@ This folder contains examples demonstrating different ways to create and use age
| [`azure_ai_with_search_context_semantic.py`](../../context_providers/azure_ai_search/azure_ai_with_search_context_semantic.py) | Shows how to use AzureAISearchContextProvider with semantic mode. Fast hybrid search with vector + keyword search and semantic ranking for RAG. Best for simple queries where speed is critical. |
| [`azure_ai_with_sharepoint.py`](azure_ai_with_sharepoint.py) | Shows how to use SharePoint grounding with Azure AI agents to search through SharePoint content and answer user questions with proper citations. Requires a SharePoint connection configured in your Azure AI project. |
| [`azure_ai_with_thread.py`](azure_ai_with_thread.py) | Demonstrates thread management with Azure AI agents, including automatic thread creation for stateless conversations and explicit thread management for maintaining conversation context across multiple interactions. |
| [`azure_ai_with_image_generation.py`](azure_ai_with_image_generation.py) | Shows how to use the `ImageGenTool` with Azure AI agents to generate images based on text prompts. |
| [`azure_ai_with_image_generation.py`](azure_ai_with_image_generation.py) | Shows how to use `AzureAIClient.get_image_generation_tool()` with Azure AI agents to generate images based on text prompts. |
| [`azure_ai_with_memory_search.py`](azure_ai_with_memory_search.py) | Shows how to use memory search functionality with Azure AI agents for conversation persistence. Demonstrates creating memory stores and enabling agents to search through conversation history. |
| [`azure_ai_with_microsoft_fabric.py`](azure_ai_with_microsoft_fabric.py) | Shows how to use Microsoft Fabric with Azure AI agents to query Fabric data sources and provide responses based on data analysis. Requires a Microsoft Fabric connection configured in your Azure AI project. |
| [`azure_ai_with_openapi.py`](azure_ai_with_openapi.py) | Shows how to integrate OpenAPI specifications with Azure AI agents using dictionary-based tool configuration. Demonstrates using external REST APIs for dynamic data lookup. |
| [`azure_ai_with_reasoning.py`](azure_ai_with_reasoning.py) | Shows how to enable reasoning for a model that supports it. |
| [`azure_ai_with_web_search.py`](azure_ai_with_web_search.py) | Shows how to use the `HostedWebSearchTool` with Azure AI agents to perform web searches and retrieve up-to-date information from the internet. |
| [`azure_ai_with_web_search.py`](azure_ai_with_web_search.py) | Shows how to use `AzureAIClient.get_web_search_tool()` with Azure AI agents to perform web searches and retrieve up-to-date information from the internet. |
## Environment Variables
@@ -17,7 +17,9 @@ Shows both streaming and non-streaming responses with function tools.
"""
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/getting_started/tools/function_tool_with_approval.py
# and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
@@ -27,7 +27,9 @@ Each method returns a Agent that can be used for conversations.
"""
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/getting_started/tools/function_tool_with_approval.py
# and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
@@ -18,7 +18,9 @@ while subsequent calls with `get_agent()` reuse the latest agent version.
"""
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/getting_started/tools/function_tool_with_approval.py
# and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
@@ -2,8 +2,8 @@
import asyncio
from agent_framework import ChatResponse, HostedCodeInterpreterTool
from agent_framework.azure import AzureAIProjectAgentProvider
from agent_framework import ChatResponse
from agent_framework.azure import AzureAIClient, AzureAIProjectAgentProvider
from azure.identity.aio import AzureCliCredential
from openai.types.responses.response import Response as OpenAIResponse
from openai.types.responses.response_code_interpreter_tool_call import ResponseCodeInterpreterToolCall
@@ -11,22 +11,26 @@ from openai.types.responses.response_code_interpreter_tool_call import ResponseC
"""
Azure AI Agent Code Interpreter Example
This sample demonstrates using HostedCodeInterpreterTool with AzureAIProjectAgentProvider
This sample demonstrates using get_code_interpreter_tool() with AzureAIProjectAgentProvider
for Python code execution and mathematical problem solving.
"""
async def main() -> None:
"""Example showing how to use the HostedCodeInterpreterTool with AzureAIProjectAgentProvider."""
"""Example showing how to use the code interpreter tool with AzureAIProjectAgentProvider."""
async with (
AzureCliCredential() as credential,
AzureAIProjectAgentProvider(credential=credential) as provider,
):
# Create a client to access hosted tool factory methods
client = AzureAIClient(credential=credential)
code_interpreter_tool = client.get_code_interpreter_tool()
agent = await provider.create_agent(
name="MyCodeInterpreterAgent",
instructions="You are a helpful assistant that can write and execute Python code to solve problems.",
tools=HostedCodeInterpreterTool(),
tools=[code_interpreter_tool],
)
query = "Use code to get the factorial of 100?"
@@ -9,9 +9,8 @@ from agent_framework import (
AgentResponseUpdate,
Annotation,
Content,
HostedCodeInterpreterTool,
)
from agent_framework.azure import AzureAIProjectAgentProvider
from agent_framework.azure import AzureAIClient, AzureAIProjectAgentProvider
from azure.identity.aio import AzureCliCredential
"""
@@ -119,17 +118,21 @@ async def download_container_files(file_contents: list[Annotation | Content], ag
async def non_streaming_example() -> None:
"""Example of downloading files from non-streaming response using CitationAnnotation."""
"""Example of downloading files from non-streaming response using Annotation."""
print("=== Non-Streaming Response Example ===")
async with (
AzureCliCredential() as credential,
AzureAIProjectAgentProvider(credential=credential) as provider,
):
# Create a client to access hosted tool factory methods
client = AzureAIClient(credential=credential)
code_interpreter_tool = client.get_code_interpreter_tool()
agent = await provider.create_agent(
name="V2CodeInterpreterFileAgent",
instructions="You are a helpful assistant that can write and execute Python code to create files.",
tools=HostedCodeInterpreterTool(),
tools=[code_interpreter_tool],
)
print(f"User: {QUERY}\n")
@@ -154,8 +157,8 @@ async def non_streaming_example() -> None:
if annotations_found:
print(f"SUCCESS: Found {len(annotations_found)} file annotation(s)")
# Download the container files
downloaded_paths = await download_container_files(annotations_found, agent)
# Download the container files (cast to Sequence for type compatibility)
downloaded_paths = await download_container_files(list(annotations_found), agent)
if downloaded_paths:
print("\nDownloaded files available at:")
@@ -166,17 +169,21 @@ async def non_streaming_example() -> None:
async def streaming_example() -> None:
"""Example of downloading files from streaming response using HostedFileContent."""
"""Example of downloading files from streaming response using Content with type='hosted_file'."""
print("\n=== Streaming Response Example ===")
async with (
AzureCliCredential() as credential,
AzureAIProjectAgentProvider(credential=credential) as provider,
):
# Create a client to access hosted tool factory methods
client = AzureAIClient(credential=credential)
code_interpreter_tool = client.get_code_interpreter_tool()
agent = await provider.create_agent(
name="V2CodeInterpreterFileAgentStreaming",
instructions="You are a helpful assistant that can write and execute Python code to create files.",
tools=HostedCodeInterpreterTool(),
tools=[code_interpreter_tool],
)
print(f"User: {QUERY}\n")
@@ -4,9 +4,8 @@ import asyncio
from agent_framework import (
AgentResponseUpdate,
HostedCodeInterpreterTool,
)
from agent_framework.azure import AzureAIProjectAgentProvider
from agent_framework.azure import AzureAIClient, AzureAIProjectAgentProvider
from azure.identity.aio import AzureCliCredential
"""
@@ -31,10 +30,14 @@ async def non_streaming_example() -> None:
AzureCliCredential() as credential,
AzureAIProjectAgentProvider(credential=credential) as provider,
):
# Create a client to access hosted tool factory methods
client = AzureAIClient(credential=credential)
code_interpreter_tool = client.get_code_interpreter_tool()
agent = await provider.create_agent(
name="V2CodeInterpreterFileAgent",
name="CodeInterpreterFileAgent",
instructions="You are a helpful assistant that can write and execute Python code to create files.",
tools=HostedCodeInterpreterTool(),
tools=[code_interpreter_tool],
)
print(f"User: {QUERY}\n")
@@ -67,10 +70,14 @@ async def streaming_example() -> None:
AzureCliCredential() as credential,
AzureAIProjectAgentProvider(credential=credential) as provider,
):
# Create a client to access hosted tool factory methods
client = AzureAIClient(credential=credential)
code_interpreter_tool = client.get_code_interpreter_tool()
agent = await provider.create_agent(
name="V2CodeInterpreterFileAgentStreaming",
instructions="You are a helpful assistant that can write and execute Python code to create files.",
tools=HostedCodeInterpreterTool(),
tools=[code_interpreter_tool],
)
print(f"User: {QUERY}\n")
@@ -17,7 +17,9 @@ This sample demonstrates usage of AzureAIProjectAgentProvider with existing conv
"""
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/getting_started/tools/function_tool_with_approval.py
# and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
@@ -18,7 +18,9 @@ settings rather than relying on environment variable defaults.
"""
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/getting_started/tools/function_tool_with_approval.py
# and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
@@ -4,8 +4,7 @@ import asyncio
import os
from pathlib import Path
from agent_framework import Content, HostedFileSearchTool
from agent_framework.azure import AzureAIProjectAgentProvider
from agent_framework.azure import AzureAIClient, AzureAIProjectAgentProvider
from azure.ai.agents.aio import AgentsClient
from azure.ai.agents.models import FileInfo, VectorStore
from azure.identity.aio import AzureCliCredential
@@ -45,8 +44,9 @@ async def main() -> None:
vector_store = await agents_client.vector_stores.create_and_poll(file_ids=[file.id], name="my_vectorstore")
print(f"Created vector store, vector store ID: {vector_store.id}")
# 2. Create file search tool with uploaded resources
file_search_tool = HostedFileSearchTool(inputs=[Content.from_hosted_vector_store(vector_store_id=vector_store.id)])
# 2. Create a client to access hosted tool factory methods
client = AzureAIClient(credential=credential)
file_search_tool = client.get_file_search_tool(vector_store_ids=[vector_store.id])
# 3. Create an agent with file search capabilities using the provider
agent = await provider.create_agent(
@@ -55,7 +55,7 @@ async def main() -> None:
"You are a helpful assistant that can search through uploaded employee files "
"to answer questions about employees."
),
tools=file_search_tool,
tools=[file_search_tool],
)
# 4. Simulate conversation with the agent
@@ -3,8 +3,8 @@
import asyncio
from typing import Any
from agent_framework import AgentResponse, AgentThread, HostedMCPTool, Message, SupportsAgentRun
from agent_framework.azure import AzureAIProjectAgentProvider
from agent_framework import AgentResponse, AgentThread, Message, SupportsAgentRun
from agent_framework.azure import AzureAIClient, AzureAIProjectAgentProvider
from azure.identity.aio import AzureCliCredential
"""
@@ -65,14 +65,19 @@ async def run_hosted_mcp_without_approval() -> None:
AzureCliCredential() as credential,
AzureAIProjectAgentProvider(credential=credential) as provider,
):
# Create a client to access hosted tool factory methods
client = AzureAIClient(credential=credential)
# Create MCP tool using instance method
mcp_tool = client.get_mcp_tool(
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
approval_mode="never_require",
)
agent = await provider.create_agent(
name="MyLearnDocsAgent",
instructions="You are a helpful assistant that can help with Microsoft documentation questions.",
tools=HostedMCPTool(
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
approval_mode="never_require",
),
tools=[mcp_tool],
)
query = "How to create an Azure storage account using az cli?"
@@ -91,14 +96,19 @@ async def run_hosted_mcp_with_approval_and_thread() -> None:
AzureCliCredential() as credential,
AzureAIProjectAgentProvider(credential=credential) as provider,
):
# Create a client to access hosted tool factory methods
client = AzureAIClient(credential=credential)
# Create MCP tool using instance method
mcp_tool = client.get_mcp_tool(
name="api-specs",
url="https://gitmcp.io/Azure/azure-rest-api-specs",
approval_mode="always_require",
)
agent = await provider.create_agent(
name="MyApiSpecsAgent",
instructions="You are a helpful agent that can use MCP tools to assist users.",
tools=HostedMCPTool(
name="api-specs",
url="https://gitmcp.io/Azure/azure-rest-api-specs",
approval_mode="always_require",
),
tools=[mcp_tool],
)
thread = agent.get_new_thread()
@@ -5,8 +5,7 @@ import tempfile
from pathlib import Path
from urllib import request as urllib_request
from agent_framework import HostedImageGenerationTool
from agent_framework.azure import AzureAIProjectAgentProvider
from agent_framework.azure import AzureAIClient, AzureAIProjectAgentProvider
from azure.identity.aio import AzureCliCredential
"""
@@ -28,22 +27,21 @@ async def main() -> None:
AzureCliCredential() as credential,
AzureAIProjectAgentProvider(credential=credential) as provider,
):
# Create a client to access hosted tool factory methods
client = AzureAIClient(credential=credential)
# Create image generation tool using instance method
image_gen_tool = client.get_image_generation_tool(
model="gpt-image-1",
size="1024x1024",
output_format="png",
quality="low",
background="opaque",
)
agent = await provider.create_agent(
name="ImageGenAgent",
instructions="Generate images based on user requirements.",
tools=[
HostedImageGenerationTool(
options={
"model_id": "gpt-image-1",
"image_size": "1024x1024",
"media_type": "png",
},
additional_properties={
"quality": "low",
"background": "opaque",
},
)
],
tools=[image_gen_tool],
)
query = "Generate an image of Microsoft logo."
@@ -79,22 +79,22 @@ async def example_with_thread_persistence_in_memory() -> None:
thread = agent.get_new_thread()
# First conversation
query1 = "What's the weather like in Tokyo?"
print(f"User: {query1}")
result1 = await agent.run(query1, thread=thread, options={"store": False})
print(f"Agent: {result1.text}")
first_query = "What's the weather like in Tokyo?"
print(f"User: {first_query}")
first_result = await agent.run(first_query, thread=thread, options={"store": False})
print(f"Agent: {first_result.text}")
# Second conversation using the same thread - maintains context
query2 = "How about London?"
print(f"\nUser: {query2}")
result2 = await agent.run(query2, thread=thread, options={"store": False})
print(f"Agent: {result2.text}")
second_query = "How about London?"
print(f"\nUser: {second_query}")
second_result = await agent.run(second_query, thread=thread, options={"store": False})
print(f"Agent: {second_result.text}")
# Third conversation - agent should remember both previous cities
query3 = "Which of the cities I asked about has better weather?"
print(f"\nUser: {query3}")
result3 = await agent.run(query3, thread=thread, options={"store": False})
print(f"Agent: {result3.text}")
third_query = "Which of the cities I asked about has better weather?"
print(f"\nUser: {third_query}")
third_result = await agent.run(third_query, thread=thread, options={"store": False})
print(f"Agent: {third_result.text}")
print("Note: The agent remembers context from previous messages in the same thread.\n")
@@ -121,10 +121,10 @@ async def example_with_existing_thread_id() -> None:
# Start a conversation and get the thread ID
thread = agent.get_new_thread()
query1 = "What's the weather in Paris?"
print(f"User: {query1}")
result1 = await agent.run(query1, thread=thread)
print(f"Agent: {result1.text}")
first_query = "What's the weather in Paris?"
print(f"User: {first_query}")
first_result = await agent.run(first_query, thread=thread)
print(f"Agent: {first_result.text}")
# The thread ID is set after the first response
existing_thread_id = thread.service_thread_id
@@ -134,19 +134,19 @@ async def example_with_existing_thread_id() -> None:
print("\n--- Continuing with the same thread ID in a new agent instance ---")
# Create a new agent instance from the same provider
agent2 = await provider.create_agent(
second_agent = await provider.create_agent(
name="BasicWeatherAgent",
instructions="You are a helpful weather agent.",
tools=get_weather,
)
# Create a thread with the existing ID
thread = agent2.get_new_thread(service_thread_id=existing_thread_id)
thread = second_agent.get_new_thread(service_thread_id=existing_thread_id)
query2 = "What was the last city I asked about?"
print(f"User: {query2}")
result2 = await agent2.run(query2, thread=thread)
print(f"Agent: {result2.text}")
second_query = "What was the last city I asked about?"
print(f"User: {second_query}")
second_result = await second_agent.run(second_query, thread=thread)
print(f"Agent: {second_result.text}")
print("Note: The agent continues the conversation from the previous thread by using thread ID.\n")
@@ -2,15 +2,14 @@
import asyncio
from agent_framework import HostedWebSearchTool
from agent_framework.azure import AzureAIProjectAgentProvider
from agent_framework.azure import AzureAIClient, AzureAIProjectAgentProvider
from azure.identity.aio import AzureCliCredential
"""
Azure AI Agent With Web Search
This sample demonstrates basic usage of AzureAIProjectAgentProvider to create an agent
that can perform web searches using the HostedWebSearchTool.
that can perform web searches using get_web_search_tool().
Pre-requisites:
- Make sure to set up the AZURE_AI_PROJECT_ENDPOINT and AZURE_AI_MODEL_DEPLOYMENT_NAME
@@ -25,10 +24,15 @@ async def main() -> None:
AzureCliCredential() as credential,
AzureAIProjectAgentProvider(credential=credential) as provider,
):
# Create a client to access hosted tool factory methods
client = AzureAIClient(credential=credential)
# Create web search tool using instance method
web_search_tool = client.get_web_search_tool()
agent = await provider.create_agent(
name="WebsearchAgent",
instructions="You are a helpful assistant that can search the web",
tools=[HostedWebSearchTool()],
tools=[web_search_tool],
)
query = "What's the weather today in Seattle?"
@@ -32,20 +32,20 @@ async with (
|------|-------------|
| [`azure_ai_provider_methods.py`](azure_ai_provider_methods.py) | Comprehensive example demonstrating all `AzureAIAgentsProvider` methods: `create_agent()`, `get_agent()`, `as_agent()`, and managing multiple agents from a single provider. |
| [`azure_ai_basic.py`](azure_ai_basic.py) | The simplest way to create an agent using `AzureAIAgentsProvider`. It automatically handles all configuration using environment variables. Shows both streaming and non-streaming responses. |
| [`azure_ai_with_bing_custom_search.py`](azure_ai_with_bing_custom_search.py) | Shows how to use Bing Custom Search with Azure AI agents to find real-time information from the web using custom search configurations. Demonstrates how to set up and use HostedWebSearchTool with custom search instances. |
| [`azure_ai_with_bing_grounding.py`](azure_ai_with_bing_grounding.py) | Shows how to use Bing Grounding search with Azure AI agents to find real-time information from the web. Demonstrates web search capabilities with proper source citations and comprehensive error handling. |
| [`azure_ai_with_bing_custom_search.py`](azure_ai_with_bing_custom_search.py) | Shows how to use Bing Custom Search with Azure AI agents to find real-time information from the web using custom search configurations. Demonstrates how to use `AzureAIAgentClient.get_web_search_tool()` with custom search instances. |
| [`azure_ai_with_bing_grounding.py`](azure_ai_with_bing_grounding.py) | Shows how to use Bing Grounding search with Azure AI agents to find real-time information from the web. Demonstrates `AzureAIAgentClient.get_web_search_tool()` with proper source citations and comprehensive error handling. |
| [`azure_ai_with_bing_grounding_citations.py`](azure_ai_with_bing_grounding_citations.py) | Demonstrates how to extract and display citations from Bing Grounding search responses. Shows how to collect citation annotations (title, URL, snippet) during streaming responses, enabling users to verify sources and access referenced content. |
| [`azure_ai_with_code_interpreter_file_generation.py`](azure_ai_with_code_interpreter_file_generation.py) | Shows how to retrieve file IDs from code interpreter generated files using both streaming and non-streaming approaches. |
| [`azure_ai_with_code_interpreter.py`](azure_ai_with_code_interpreter.py) | Shows how to use the HostedCodeInterpreterTool with Azure AI agents to write and execute Python code. Includes helper methods for accessing code interpreter data from response chunks. |
| [`azure_ai_with_code_interpreter.py`](azure_ai_with_code_interpreter.py) | Shows how to use `AzureAIAgentClient.get_code_interpreter_tool()` with Azure AI agents to write and execute Python code. Includes helper methods for accessing code interpreter data from response chunks. |
| [`azure_ai_with_existing_agent.py`](azure_ai_with_existing_agent.py) | Shows how to work with an existing SDK Agent object using `provider.as_agent()`. This wraps the agent without making HTTP calls. |
| [`azure_ai_with_existing_thread.py`](azure_ai_with_existing_thread.py) | Shows how to work with a pre-existing thread by providing the thread ID. Demonstrates proper cleanup of manually created threads. |
| [`azure_ai_with_explicit_settings.py`](azure_ai_with_explicit_settings.py) | Shows how to create an agent with explicitly configured provider settings, including project endpoint and model deployment name. |
| [`azure_ai_with_azure_ai_search.py`](azure_ai_with_azure_ai_search.py) | Demonstrates how to use Azure AI Search with Azure AI agents. Shows how to create an agent with search tools using the SDK directly and wrap it with `provider.get_agent()`. |
| [`azure_ai_with_file_search.py`](azure_ai_with_file_search.py) | Demonstrates how to use the HostedFileSearchTool with Azure AI agents to search through uploaded documents. Shows file upload, vector store creation, and querying document content. |
| [`azure_ai_with_file_search.py`](azure_ai_with_file_search.py) | Demonstrates how to use `AzureAIAgentClient.get_file_search_tool()` with Azure AI agents to search through uploaded documents. Shows file upload, vector store creation, and querying document content. |
| [`azure_ai_with_function_tools.py`](azure_ai_with_function_tools.py) | Demonstrates how to use function tools with agents. Shows both agent-level tools (defined when creating the agent) and query-level tools (provided with specific queries). |
| [`azure_ai_with_hosted_mcp.py`](azure_ai_with_hosted_mcp.py) | Shows how to integrate Azure AI agents with hosted Model Context Protocol (MCP) servers for enhanced functionality and tool integration. Demonstrates remote MCP server connections and tool discovery. |
| [`azure_ai_with_hosted_mcp.py`](azure_ai_with_hosted_mcp.py) | Shows how to use `AzureAIAgentClient.get_mcp_tool()` with hosted Model Context Protocol (MCP) servers for enhanced functionality and tool integration. Demonstrates remote MCP server connections and tool discovery. |
| [`azure_ai_with_local_mcp.py`](azure_ai_with_local_mcp.py) | Shows how to integrate Azure AI agents with local Model Context Protocol (MCP) servers for enhanced functionality and tool integration. Demonstrates both agent-level and run-level tool configuration. |
| [`azure_ai_with_multiple_tools.py`](azure_ai_with_multiple_tools.py) | Demonstrates how to use multiple tools together with Azure AI agents, including web search, MCP servers, and function tools. Shows coordinated multi-tool interactions and approval workflows. |
| [`azure_ai_with_multiple_tools.py`](azure_ai_with_multiple_tools.py) | Demonstrates how to use multiple tools together with Azure AI agents, including web search, MCP servers, and function tools using client static methods. Shows coordinated multi-tool interactions and approval workflows. |
| [`azure_ai_with_openapi_tools.py`](azure_ai_with_openapi_tools.py) | Demonstrates how to use OpenAPI tools with Azure AI agents to integrate external REST APIs. Shows OpenAPI specification loading, anonymous authentication, thread context management, and coordinated multi-API conversations. |
| [`azure_ai_with_response_format.py`](azure_ai_with_response_format.py) | Demonstrates how to use structured outputs with Azure AI agents using Pydantic models. |
| [`azure_ai_with_thread.py`](azure_ai_with_thread.py) | Demonstrates thread management with Azure AI agents, including automatic thread creation for stateless conversations and explicit thread management for maintaining conversation context across multiple interactions. |
@@ -2,8 +2,7 @@
import asyncio
from agent_framework import HostedWebSearchTool
from agent_framework.azure import AzureAIAgentsProvider
from agent_framework.azure import AzureAIAgentClient, AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
"""
@@ -30,25 +29,25 @@ To set up Bing Custom Search:
async def main() -> None:
"""Main function demonstrating Azure AI agent with Bing Custom Search."""
# 1. Create Bing Custom Search tool using HostedWebSearchTool
# The connection ID and instance name will be automatically picked up from environment variables
bing_search_tool = HostedWebSearchTool(
name="Bing Custom Search",
description="Search the web for current information using Bing Custom Search",
)
# 2. Use AzureAIAgentsProvider for agent creation and management
# Use AzureAIAgentsProvider for agent creation and management
async with (
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
# Create a client to access hosted tool factory methods
client = AzureAIAgentClient(credential=credential)
# Create Bing Custom Search tool using instance method
# The connection ID and instance name will be automatically picked up from environment variables
# (BING_CUSTOM_CONNECTION_ID and BING_CUSTOM_INSTANCE_NAME)
bing_search_tool = client.get_web_search_tool()
agent = await provider.create_agent(
name="BingSearchAgent",
instructions=(
"You are a helpful agent that can use Bing Custom Search tools to assist users. "
"Use the available Bing Custom Search tools to answer questions and perform tasks."
),
tools=bing_search_tool,
tools=[bing_search_tool],
)
# 3. Demonstrate agent capabilities with bing custom search
@@ -2,8 +2,7 @@
import asyncio
from agent_framework import HostedWebSearchTool
from agent_framework.azure import AzureAIAgentsProvider
from agent_framework.azure import AzureAIAgentClient, AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
"""
@@ -25,18 +24,17 @@ To set up Bing Grounding:
async def main() -> None:
"""Main function demonstrating Azure AI agent with Bing Grounding search."""
# 1. Create Bing Grounding search tool using HostedWebSearchTool
# The connection ID will be automatically picked up from environment variable
bing_search_tool = HostedWebSearchTool(
name="Bing Grounding Search",
description="Search the web for current information using Bing",
)
# 2. Use AzureAIAgentsProvider for agent creation and management
# Use AzureAIAgentsProvider for agent creation and management
async with (
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
# Create a client to access hosted tool factory methods
client = AzureAIAgentClient(credential=credential)
# Create Bing Grounding search tool using instance method
# The connection ID will be automatically picked up from environment variable
bing_search_tool = client.get_web_search_tool()
agent = await provider.create_agent(
name="BingSearchAgent",
instructions=(
@@ -44,7 +42,7 @@ async def main() -> None:
"Use the Bing search tool to find up-to-date information and provide accurate, "
"well-sourced answers. Always cite your sources when possible."
),
tools=bing_search_tool,
tools=[bing_search_tool],
)
# 3. Demonstrate agent capabilities with web search
@@ -2,8 +2,8 @@
import asyncio
from agent_framework import Annotation, HostedWebSearchTool
from agent_framework.azure import AzureAIAgentsProvider
from agent_framework import Annotation
from agent_framework.azure import AzureAIAgentClient, AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
"""
@@ -27,18 +27,17 @@ To set up Bing Grounding:
async def main() -> None:
"""Main function demonstrating Azure AI agent with Bing Grounding search."""
# 1. Create Bing Grounding search tool using HostedWebSearchTool
# The connection ID will be automatically picked up from environment variable
bing_search_tool = HostedWebSearchTool(
name="Bing Grounding Search",
description="Search the web for current information using Bing",
)
# 2. Use AzureAIAgentsProvider for agent creation and management
# Use AzureAIAgentsProvider for agent creation and management
async with (
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
# Create a client to access hosted tool factory methods
client = AzureAIAgentClient(credential=credential)
# Create Bing Grounding search tool using instance method
# The connection ID will be automatically picked up from environment variable
bing_search_tool = client.get_web_search_tool()
agent = await provider.create_agent(
name="BingSearchAgent",
instructions=(
@@ -46,7 +45,7 @@ async def main() -> None:
"Use the Bing search tool to find up-to-date information and provide accurate, "
"well-sourced answers. Always cite your sources when possible."
),
tools=bing_search_tool,
tools=[bing_search_tool],
)
# 3. Demonstrate agent capabilities with web search
@@ -2,8 +2,8 @@
import asyncio
from agent_framework import AgentResponse, ChatResponseUpdate, HostedCodeInterpreterTool
from agent_framework.azure import AzureAIAgentsProvider
from agent_framework import AgentResponse, ChatResponseUpdate
from agent_framework.azure import AzureAIAgentClient, AzureAIAgentsProvider
from azure.ai.agents.models import (
RunStepDeltaCodeInterpreterDetailItemObject,
)
@@ -12,7 +12,7 @@ from azure.identity.aio import AzureCliCredential
"""
Azure AI Agent with Code Interpreter Example
This sample demonstrates using HostedCodeInterpreterTool with Azure AI Agents
This sample demonstrates using get_code_interpreter_tool() with Azure AI Agents
for Python code execution and mathematical problem solving.
"""
@@ -32,7 +32,7 @@ def print_code_interpreter_inputs(response: AgentResponse) -> None:
async def main() -> None:
"""Example showing how to use the HostedCodeInterpreterTool with Azure AI."""
"""Example showing how to use the code interpreter tool with Azure AI."""
print("=== Azure AI Agent with Code Interpreter Example ===")
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
@@ -41,10 +41,14 @@ async def main() -> None:
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
# Create a client to access hosted tool factory methods
client = AzureAIAgentClient(credential=credential)
code_interpreter_tool = client.get_code_interpreter_tool()
agent = await provider.create_agent(
name="CodingAgent",
instructions=("You are a helpful assistant that can write and execute Python code to solve problems."),
tools=HostedCodeInterpreterTool(),
tools=[code_interpreter_tool],
)
query = "Generate the factorial of 100 using python code, show the code and execute it."
print(f"User: {query}")
@@ -3,17 +3,14 @@
import asyncio
import os
from agent_framework import (
HostedCodeInterpreterTool,
)
from agent_framework.azure import AzureAIAgentsProvider
from agent_framework.azure import AzureAIAgentClient, AzureAIAgentsProvider
from azure.ai.agents.aio import AgentsClient
from azure.identity.aio import AzureCliCredential
"""
Azure AI Agent Code Interpreter File Generation Example
This sample demonstrates using HostedCodeInterpreterTool with AzureAIAgentsProvider
This sample demonstrates using get_code_interpreter_tool() with AzureAIAgentsProvider
to generate a text file and then retrieve it.
The test flow:
@@ -32,6 +29,10 @@ async def main() -> None:
AgentsClient(endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential) as agents_client,
AzureAIAgentsProvider(agents_client=agents_client) as provider,
):
# Create a client to access hosted tool factory methods
client = AzureAIAgentClient(credential=credential)
code_interpreter_tool = client.get_code_interpreter_tool()
agent = await provider.create_agent(
name="CodeInterpreterAgent",
instructions=(
@@ -39,7 +40,7 @@ async def main() -> None:
"ALWAYS use the code interpreter tool to execute Python code when asked to create files. "
"Write actual Python code to create files, do not just describe what you would do."
),
tools=[HostedCodeInterpreterTool()],
tools=[code_interpreter_tool],
)
# Be very explicit about wanting code execution and a download link
@@ -19,7 +19,9 @@ by providing thread IDs for thread reuse patterns.
"""
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/getting_started/tools/function_tool_with_approval.py
# and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
@@ -18,7 +18,9 @@ settings rather than relying on environment variable defaults.
"""
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/getting_started/tools/function_tool_with_approval.py
# and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
@@ -4,8 +4,7 @@ import asyncio
import os
from pathlib import Path
from agent_framework import Content, HostedFileSearchTool
from agent_framework.azure import AzureAIAgentsProvider
from agent_framework.azure import AzureAIAgentClient, AzureAIAgentsProvider
from azure.ai.agents.aio import AgentsClient
from azure.ai.agents.models import FileInfo, VectorStore
from azure.identity.aio import AzureCliCredential
@@ -45,8 +44,9 @@ async def main() -> None:
vector_store = await agents_client.vector_stores.create_and_poll(file_ids=[file.id], name="my_vectorstore")
print(f"Created vector store, vector store ID: {vector_store.id}")
# 2. Create file search tool with uploaded resources
file_search_tool = HostedFileSearchTool(inputs=[Content.from_hosted_vector_store(vector_store_id=vector_store.id)])
# 2. Create a client to access hosted tool factory methods
client = AzureAIAgentClient(credential=credential)
file_search_tool = client.get_file_search_tool(vector_store_ids=[vector_store.id])
# 3. Create an agent with file search capabilities
agent = await provider.create_agent(
@@ -55,7 +55,7 @@ async def main() -> None:
"You are a helpful assistant that can search through uploaded employee files "
"to answer questions about employees."
),
tools=file_search_tool,
tools=[file_search_tool],
)
# 4. Simulate conversation with the agent
@@ -18,7 +18,9 @@ showing both agent-level and query-level tool configuration patterns.
"""
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/getting_started/tools/function_tool_with_approval.py
# and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
@@ -3,8 +3,8 @@
import asyncio
from typing import Any
from agent_framework import AgentResponse, AgentThread, HostedMCPTool, SupportsAgentRun
from agent_framework.azure import AzureAIAgentsProvider
from agent_framework import AgentResponse, AgentThread, SupportsAgentRun
from agent_framework.azure import AzureAIAgentClient, AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
"""
@@ -40,17 +40,23 @@ async def handle_approvals_with_thread(query: str, agent: "SupportsAgentRun", th
async def main() -> None:
"""Example showing Hosted MCP tools for a Azure AI Agent."""
async with (
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
# Create a client to access hosted tool factory methods
client = AzureAIAgentClient(credential=credential)
# Create MCP tool using instance method
mcp_tool = client.get_mcp_tool(
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
)
agent = await provider.create_agent(
name="DocsAgent",
instructions="You are a helpful assistant that can help with microsoft documentation questions.",
tools=HostedMCPTool(
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
),
tools=[mcp_tool],
)
thread = agent.get_new_thread()
# First query
@@ -6,12 +6,10 @@ from typing import Any
from agent_framework import (
AgentThread,
HostedMCPTool,
HostedWebSearchTool,
SupportsAgentRun,
tool,
)
from agent_framework.azure import AzureAIAgentsProvider
from agent_framework.azure import AzureAIAgentClient, AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
"""
@@ -35,7 +33,9 @@ To set up Bing Grounding:
"""
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/getting_started/tools/function_tool_with_approval.py
# and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_time() -> str:
"""Get the current UTC time."""
@@ -67,20 +67,27 @@ async def handle_approvals_with_thread(query: str, agent: "SupportsAgentRun", th
async def main() -> None:
"""Example showing Hosted MCP tools for a Azure AI Agent."""
"""Example showing multiple tools for an Azure AI Agent."""
async with (
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
# Create a client to access hosted tool factory methods
client = AzureAIAgentClient(credential=credential)
# Create tools using instance methods
mcp_tool = client.get_mcp_tool(
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
)
web_search_tool = client.get_web_search_tool()
agent = await provider.create_agent(
name="DocsAgent",
instructions="You are a helpful assistant that can help with microsoft documentation questions.",
tools=[
HostedMCPTool(
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
),
HostedWebSearchTool(count=5),
mcp_tool,
web_search_tool,
get_time,
],
)
@@ -17,7 +17,9 @@ automatic thread creation with explicit thread management for persistent context
"""
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/getting_started/tools/function_tool_with_approval.py
# and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
@@ -7,7 +7,7 @@ This folder contains examples demonstrating different ways to create and use age
| File | Description |
|------|-------------|
| [`azure_assistants_basic.py`](azure_assistants_basic.py) | The simplest way to create an agent using `Agent` with `AzureOpenAIAssistantsClient`. Shows both streaming and non-streaming responses with automatic assistant creation and cleanup. |
| [`azure_assistants_with_code_interpreter.py`](azure_assistants_with_code_interpreter.py) | Shows how to use the HostedCodeInterpreterTool with Azure agents to write and execute Python code. Includes helper methods for accessing code interpreter data from response chunks. |
| [`azure_assistants_with_code_interpreter.py`](azure_assistants_with_code_interpreter.py) | Shows how to use `AzureOpenAIAssistantsClient.get_code_interpreter_tool()` with Azure agents to write and execute Python code. Includes helper methods for accessing code interpreter data from response chunks. |
| [`azure_assistants_with_existing_assistant.py`](azure_assistants_with_existing_assistant.py) | Shows how to work with a pre-existing assistant by providing the assistant ID to the Azure Assistants client. Demonstrates proper cleanup of manually created assistants. |
| [`azure_assistants_with_explicit_settings.py`](azure_assistants_with_explicit_settings.py) | Shows how to initialize an agent with a specific assistants client, configuring settings explicitly including endpoint and deployment name. |
| [`azure_assistants_with_function_tools.py`](azure_assistants_with_function_tools.py) | Demonstrates how to use function tools with agents. Shows both agent-level tools (defined when creating the agent) and query-level tools (provided with specific queries). |
@@ -17,12 +17,13 @@ This folder contains examples demonstrating different ways to create and use age
| [`azure_chat_client_with_function_tools.py`](azure_chat_client_with_function_tools.py) | Demonstrates how to use function tools with agents. Shows both agent-level tools (defined when creating the agent) and query-level tools (provided with specific queries). |
| [`azure_chat_client_with_thread.py`](azure_chat_client_with_thread.py) | Demonstrates thread management with Azure agents, including automatic thread creation for stateless conversations and explicit thread management for maintaining conversation context across multiple interactions. |
| [`azure_responses_client_basic.py`](azure_responses_client_basic.py) | The simplest way to create an agent using `Agent` with `AzureOpenAIResponsesClient`. Shows both streaming and non-streaming responses for structured response generation with Azure OpenAI models. |
| [`azure_responses_client_code_interpreter_files.py`](azure_responses_client_code_interpreter_files.py) | Demonstrates using HostedCodeInterpreterTool with file uploads for data analysis. Shows how to create, upload, and analyze CSV files using Python code execution with Azure OpenAI Responses. |
| [`azure_responses_client_code_interpreter_files.py`](azure_responses_client_code_interpreter_files.py) | Demonstrates using `AzureOpenAIResponsesClient.get_code_interpreter_tool()` with file uploads for data analysis. Shows how to create, upload, and analyze CSV files using Python code execution with Azure OpenAI Responses. |
| [`azure_responses_client_image_analysis.py`](azure_responses_client_image_analysis.py) | Shows how to use Azure OpenAI Responses for image analysis and vision tasks. Demonstrates multi-modal messages combining text and image content using remote URLs. |
| [`azure_responses_client_with_code_interpreter.py`](azure_responses_client_with_code_interpreter.py) | Shows how to use the HostedCodeInterpreterTool with Azure agents to write and execute Python code. Includes helper methods for accessing code interpreter data from response chunks. |
| [`azure_responses_client_with_code_interpreter.py`](azure_responses_client_with_code_interpreter.py) | Shows how to use `AzureOpenAIResponsesClient.get_code_interpreter_tool()` with Azure agents to write and execute Python code. Includes helper methods for accessing code interpreter data from response chunks. |
| [`azure_responses_client_with_explicit_settings.py`](azure_responses_client_with_explicit_settings.py) | Shows how to initialize an agent with a specific responses client, configuring settings explicitly including endpoint and deployment name. |
| [`azure_responses_client_with_file_search.py`](azure_responses_client_with_file_search.py) | Demonstrates using HostedFileSearchTool with Azure OpenAI Responses Client for direct document-based question answering and information retrieval from vector stores. |
| [`azure_responses_client_with_file_search.py`](azure_responses_client_with_file_search.py) | Demonstrates using `AzureOpenAIResponsesClient.get_file_search_tool()` with Azure OpenAI Responses Client for direct document-based question answering and information retrieval from vector stores. |
| [`azure_responses_client_with_function_tools.py`](azure_responses_client_with_function_tools.py) | Demonstrates how to use function tools with agents. Shows both agent-level tools (defined when creating the agent) and query-level tools (provided with specific queries). |
| [`azure_responses_client_with_hosted_mcp.py`](azure_responses_client_with_hosted_mcp.py) | Shows how to integrate Azure OpenAI Responses Client with hosted Model Context Protocol (MCP) servers using `AzureOpenAIResponsesClient.get_mcp_tool()` for extended functionality. |
| [`azure_responses_client_with_local_mcp.py`](azure_responses_client_with_local_mcp.py) | Shows how to integrate Azure OpenAI Responses Client with local Model Context Protocol (MCP) servers using MCPStreamableHTTPTool for extended functionality. |
| [`azure_responses_client_with_thread.py`](azure_responses_client_with_thread.py) | Demonstrates thread management with Azure agents, including automatic thread creation for stateless conversations and explicit thread management for maintaining conversation context across multiple interactions. |
@@ -2,9 +2,8 @@
import asyncio
from agent_framework import Agent, AgentResponseUpdate, ChatResponseUpdate, HostedCodeInterpreterTool
from agent_framework import Agent, AgentResponseUpdate, ChatResponseUpdate
from agent_framework.azure import AzureOpenAIAssistantsClient
from azure.identity import AzureCliCredential
from openai.types.beta.threads.runs import (
CodeInterpreterToolCallDelta,
RunStepDelta,
@@ -16,7 +15,7 @@ from openai.types.beta.threads.runs.code_interpreter_tool_call_delta import Code
"""
Azure OpenAI Assistants with Code Interpreter Example
This sample demonstrates using HostedCodeInterpreterTool with Azure OpenAI Assistants
This sample demonstrates using get_code_interpreter_tool() with Azure OpenAI Assistants
for Python code execution and mathematical problem solving.
"""
@@ -41,15 +40,19 @@ def get_code_interpreter_chunk(chunk: AgentResponseUpdate) -> str | None:
async def main() -> None:
"""Example showing how to use the HostedCodeInterpreterTool with Azure OpenAI Assistants."""
"""Example showing how to use the code interpreter tool with Azure OpenAI Assistants."""
print("=== Azure OpenAI Assistants Agent with Code Interpreter Example ===")
# Create code interpreter tool using static method
client = AzureOpenAIAssistantsClient()
code_interpreter_tool = client.get_code_interpreter_tool()
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
# authentication option.
async with Agent(
client=AzureOpenAIAssistantsClient(credential=AzureCliCredential()),
client=client,
instructions="You are a helpful assistant that can write and execute Python code to solve problems.",
tools=HostedCodeInterpreterTool(),
tools=[code_interpreter_tool],
) as agent:
query = "What is current datetime?"
print(f"User: {query}")
@@ -19,7 +19,9 @@ using existing assistant IDs rather than creating new ones.
"""
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/getting_started/tools/function_tool_with_approval.py
# and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
@@ -18,7 +18,9 @@ settings rather than relying on environment variable defaults.
"""
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/getting_started/tools/function_tool_with_approval.py
# and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
@@ -18,7 +18,9 @@ showing both agent-level and query-level tool configuration patterns.
"""
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/getting_started/tools/function_tool_with_approval.py
# and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
@@ -17,7 +17,9 @@ automatic thread creation with explicit thread management for persistent context
"""
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/getting_started/tools/function_tool_with_approval.py
# and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
@@ -17,7 +17,9 @@ interactions, showing both streaming and non-streaming responses.
"""
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/getting_started/tools/function_tool_with_approval.py
# and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
@@ -18,7 +18,9 @@ settings rather than relying on environment variable defaults.
"""
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/getting_started/tools/function_tool_with_approval.py
# and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
@@ -18,7 +18,9 @@ showing both agent-level and query-level tool configuration patterns.
"""
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/getting_started/tools/function_tool_with_approval.py
# and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
@@ -17,7 +17,9 @@ automatic thread creation with explicit thread management for persistent context
"""
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/getting_started/tools/function_tool_with_approval.py
# and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
@@ -17,7 +17,9 @@ response generation, showing both streaming and non-streaming responses.
"""
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/getting_started/tools/function_tool_with_approval.py
# and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
@@ -4,7 +4,7 @@ import asyncio
import os
import tempfile
from agent_framework import Agent, HostedCodeInterpreterTool
from agent_framework import Agent
from agent_framework.azure import AzureOpenAIResponsesClient
from azure.identity import AzureCliCredential
from openai import AsyncAzureOpenAI
@@ -12,7 +12,7 @@ from openai import AsyncAzureOpenAI
"""
Azure OpenAI Responses Client with Code Interpreter and Files Example
This sample demonstrates using HostedCodeInterpreterTool with Azure OpenAI Responses
This sample demonstrates using get_code_interpreter_tool() with Azure OpenAI Responses
for Python code execution and data analysis with uploaded files.
"""
@@ -76,10 +76,15 @@ async def main() -> None:
temp_file_path, file_id = await create_sample_file_and_upload(openai_client)
# Create agent using Azure OpenAI Responses client
client = AzureOpenAIResponsesClient(credential=credential)
# Create code interpreter tool with file access
code_interpreter_tool = client.get_code_interpreter_tool(file_ids=[file_id])
agent = Agent(
client=AzureOpenAIResponsesClient(credential=credential),
client=client,
instructions="You are a helpful assistant that can analyze data files using Python code.",
tools=HostedCodeInterpreterTool(inputs=[{"file_id": file_id}]),
tools=[code_interpreter_tool],
)
# Test the code interpreter with the uploaded file
@@ -27,9 +27,9 @@ async def main():
user_message = Message(
role="user",
contents=[
Content.from_text(text="What do you see in this image?"),
Content.from_text("What do you see in this image?"),
Content.from_uri(
uri="https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg",
uri="https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800",
media_type="image/jpeg",
),
],
@@ -2,7 +2,7 @@
import asyncio
from agent_framework import Agent, ChatResponse, HostedCodeInterpreterTool
from agent_framework import Agent, ChatResponse
from agent_framework.azure import AzureOpenAIResponsesClient
from azure.identity import AzureCliCredential
from openai.types.responses.response import Response as OpenAIResponse
@@ -11,21 +11,26 @@ from openai.types.responses.response_code_interpreter_tool_call import ResponseC
"""
Azure OpenAI Responses Client with Code Interpreter Example
This sample demonstrates using HostedCodeInterpreterTool with Azure OpenAI Responses
This sample demonstrates using get_code_interpreter_tool() with Azure OpenAI Responses
for Python code execution and mathematical problem solving.
"""
async def main() -> None:
"""Example showing how to use the HostedCodeInterpreterTool with Azure OpenAI Responses."""
"""Example showing how to use the code interpreter tool with Azure OpenAI Responses."""
print("=== Azure OpenAI Responses Agent with Code Interpreter Example ===")
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
# authentication option.
client = AzureOpenAIResponsesClient(credential=AzureCliCredential())
# Create code interpreter tool using instance method
code_interpreter_tool = client.get_code_interpreter_tool()
agent = Agent(
client=AzureOpenAIResponsesClient(credential=AzureCliCredential()),
client=client,
instructions="You are a helpful assistant that can write and execute Python code to solve problems.",
tools=HostedCodeInterpreterTool(),
tools=[code_interpreter_tool],
)
query = "Use code to calculate the factorial of 100?"
@@ -18,7 +18,9 @@ settings rather than relying on environment variable defaults.
"""
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/getting_started/tools/function_tool_with_approval.py
# and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
@@ -2,14 +2,14 @@
import asyncio
from agent_framework import Agent, Content, HostedFileSearchTool
from agent_framework import Agent, Content
from agent_framework.azure import AzureOpenAIResponsesClient
from azure.identity import AzureCliCredential
"""
Azure OpenAI Responses Client with File Search Example
This sample demonstrates using HostedFileSearchTool with Azure OpenAI Responses Client
This sample demonstrates using get_file_search_tool() with Azure OpenAI Responses Client
for direct document-based question answering and information retrieval.
Prerequisites:
@@ -51,12 +51,15 @@ async def main() -> None:
# Make sure you're logged in via 'az login' before running this sample
client = AzureOpenAIResponsesClient(credential=AzureCliCredential())
file_id, vector_store = await create_vector_store(client)
file_id, vector_store_id = await create_vector_store(client)
# Create file search tool using instance method
file_search_tool = client.get_file_search_tool(vector_store_ids=[vector_store_id])
agent = Agent(
client=client,
instructions="You are a helpful assistant that can search through files to find information.",
tools=[HostedFileSearchTool(inputs=vector_store)],
tools=[file_search_tool],
)
query = "What is the weather today? Do a file search to find the answer."
@@ -64,7 +67,7 @@ async def main() -> None:
result = await agent.run(query)
print(f"Agent: {result}\n")
await delete_vector_store(client, file_id, vector_store.vector_store_id)
await delete_vector_store(client, file_id, vector_store_id)
if __name__ == "__main__":
@@ -18,7 +18,9 @@ showing both agent-level and query-level tool configuration patterns.
"""
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/getting_started/tools/function_tool_with_approval.py
# and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
@@ -3,7 +3,7 @@
import asyncio
from typing import TYPE_CHECKING, Any
from agent_framework import Agent, HostedMCPTool
from agent_framework import Agent
from agent_framework.azure import AzureOpenAIResponsesClient
from azure.identity import AzureCliCredential
@@ -33,7 +33,10 @@ async def handle_approvals_without_thread(query: str, agent: "SupportsAgentRun")
new_inputs.append(Message(role="assistant", contents=[user_input_needed]))
user_approval = input("Approve function call? (y/n): ")
new_inputs.append(
Message(role="user", contents=[user_input_needed.to_function_approval_response(user_approval.lower() == "y")])
Message(
role="user",
contents=[user_input_needed.to_function_approval_response(user_approval.lower() == "y")],
)
)
result = await agent.run(new_inputs)
@@ -82,7 +85,8 @@ async def handle_approvals_with_thread_streaming(query: str, agent: "SupportsAge
user_approval = input("Approve function call? (y/n): ")
new_input.append(
Message(
role="user", contents=[user_input_needed.to_function_approval_response(user_approval.lower() == "y")]
role="user",
contents=[user_input_needed.to_function_approval_response(user_approval.lower() == "y")],
)
)
new_input_added = True
@@ -94,21 +98,24 @@ async def run_hosted_mcp_without_thread_and_specific_approval() -> None:
"""Example showing Mcp Tools with approvals without using a thread."""
print("=== Mcp with approvals and without thread ===")
credential = AzureCliCredential()
client = AzureOpenAIResponsesClient(credential=credential)
# Create MCP tool with specific approval settings
mcp_tool = client.get_mcp_tool(
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
# we don't require approval for microsoft_docs_search tool calls
# but we do for any other tool
approval_mode={"never_require_approval": ["microsoft_docs_search"]},
)
# Tools are provided when creating the agent
# The agent can use these tools for any query during its lifetime
async with Agent(
client=AzureOpenAIResponsesClient(
credential=credential,
),
client=client,
name="DocsAgent",
instructions="You are a helpful assistant that can help with microsoft documentation questions.",
tools=HostedMCPTool(
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
# we don't require approval for microsoft_docs_search tool calls
# but we do for any other tool
approval_mode={"never_require_approval": ["microsoft_docs_search"]},
),
tools=[mcp_tool],
) as agent:
# First query
query1 = "How to create an Azure storage account using az cli?"
@@ -127,22 +134,25 @@ async def run_hosted_mcp_without_approval() -> None:
"""Example showing Mcp Tools without approvals."""
print("=== Mcp without approvals ===")
credential = AzureCliCredential()
client = AzureOpenAIResponsesClient(credential=credential)
# Create MCP tool without approval requirements
mcp_tool = client.get_mcp_tool(
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
# we don't require approval for any function calls
# this means we will not see the approval messages,
# it is fully handled by the service and a final response is returned.
approval_mode="never_require",
)
# Tools are provided when creating the agent
# The agent can use these tools for any query during its lifetime
async with Agent(
client=AzureOpenAIResponsesClient(
credential=credential,
),
client=client,
name="DocsAgent",
instructions="You are a helpful assistant that can help with microsoft documentation questions.",
tools=HostedMCPTool(
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
# we don't require approval for any function calls
# this means we will not see the approval messages,
# it is fully handled by the service and a final response is returned.
approval_mode="never_require",
),
tools=[mcp_tool],
) as agent:
# First query
query1 = "How to create an Azure storage account using az cli?"
@@ -161,20 +171,23 @@ async def run_hosted_mcp_with_thread() -> None:
"""Example showing Mcp Tools with approvals using a thread."""
print("=== Mcp with approvals and with thread ===")
credential = AzureCliCredential()
client = AzureOpenAIResponsesClient(credential=credential)
# Create MCP tool with always require approval
mcp_tool = client.get_mcp_tool(
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
# we require approval for all function calls
approval_mode="always_require",
)
# Tools are provided when creating the agent
# The agent can use these tools for any query during its lifetime
async with Agent(
client=AzureOpenAIResponsesClient(
credential=credential,
),
client=client,
name="DocsAgent",
instructions="You are a helpful assistant that can help with microsoft documentation questions.",
tools=HostedMCPTool(
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
# we require approval for all function calls
approval_mode="always_require",
),
tools=[mcp_tool],
) as agent:
# First query
thread = agent.get_new_thread()
@@ -194,20 +207,23 @@ async def run_hosted_mcp_with_thread_streaming() -> None:
"""Example showing Mcp Tools with approvals using a thread."""
print("=== Mcp with approvals and with thread ===")
credential = AzureCliCredential()
client = AzureOpenAIResponsesClient(credential=credential)
# Create MCP tool with always require approval
mcp_tool = client.get_mcp_tool(
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
# we require approval for all function calls
approval_mode="always_require",
)
# Tools are provided when creating the agent
# The agent can use these tools for any query during its lifetime
async with Agent(
client=AzureOpenAIResponsesClient(
credential=credential,
),
client=client,
name="DocsAgent",
instructions="You are a helpful assistant that can help with microsoft documentation questions.",
tools=HostedMCPTool(
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
# we require approval for all function calls
approval_mode="always_require",
),
tools=[mcp_tool],
) as agent:
# First query
thread = agent.get_new_thread()
@@ -48,14 +48,14 @@ async def main():
url=MCP_URL,
) as mcp_tool:
# First query — expect the agent to use the MCP tool if it helps
q1 = "How to create an Azure storage account using az cli?"
r1 = await agent.run(q1, tools=mcp_tool)
print("\n=== Answer 1 ===\n", r1.text)
first_query = "How to create an Azure storage account using az cli?"
first_response = await agent.run(first_query, tools=mcp_tool)
print("\n=== Answer 1 ===\n", first_response.text)
# Follow-up query (connection is reused)
q2 = "What is Microsoft Agent Framework?"
r2 = await agent.run(q2, tools=mcp_tool)
print("\n=== Answer 2 ===\n", r2.text)
second_query = "What is Microsoft Agent Framework?"
second_response = await agent.run(second_query, tools=mcp_tool)
print("\n=== Answer 2 ===\n", second_response.text)
if __name__ == "__main__":
@@ -17,7 +17,9 @@ automatic thread creation with explicit thread management for persistent context
"""
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/getting_started/tools/function_tool_with_approval.py
# and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
@@ -1,6 +1,6 @@
# OpenAI Agent Framework Examples
This folder contains examples demonstrating different ways to create and use agents with the OpenAI Assistants client from the `agent_framework.openai` package.
This folder contains examples demonstrating different ways to create and use agents with the OpenAI clients from the `agent_framework.openai` package.
## Examples
@@ -8,10 +8,10 @@ This folder contains examples demonstrating different ways to create and use age
|------|-------------|
| [`openai_assistants_basic.py`](openai_assistants_basic.py) | Basic usage of `OpenAIAssistantProvider` with streaming and non-streaming responses. |
| [`openai_assistants_provider_methods.py`](openai_assistants_provider_methods.py) | Demonstrates all `OpenAIAssistantProvider` methods: `create_agent()`, `get_agent()`, and `as_agent()`. |
| [`openai_assistants_with_code_interpreter.py`](openai_assistants_with_code_interpreter.py) | Using `HostedCodeInterpreterTool` with `OpenAIAssistantProvider` to execute Python code. |
| [`openai_assistants_with_code_interpreter.py`](openai_assistants_with_code_interpreter.py) | Using `OpenAIAssistantsClient.get_code_interpreter_tool()` with `OpenAIAssistantProvider` to execute Python code. |
| [`openai_assistants_with_existing_assistant.py`](openai_assistants_with_existing_assistant.py) | Working with pre-existing assistants using `get_agent()` and `as_agent()` methods. |
| [`openai_assistants_with_explicit_settings.py`](openai_assistants_with_explicit_settings.py) | Configuring `OpenAIAssistantProvider` with explicit settings including API key and model ID. |
| [`openai_assistants_with_file_search.py`](openai_assistants_with_file_search.py) | Using `HostedFileSearchTool` with `OpenAIAssistantProvider` for file search capabilities. |
| [`openai_assistants_with_file_search.py`](openai_assistants_with_file_search.py) | Using `OpenAIAssistantsClient.get_file_search_tool()` with `OpenAIAssistantProvider` for file search capabilities. |
| [`openai_assistants_with_function_tools.py`](openai_assistants_with_function_tools.py) | Function tools with `OpenAIAssistantProvider` at both agent-level and query-level. |
| [`openai_assistants_with_response_format.py`](openai_assistants_with_response_format.py) | Structured outputs with `OpenAIAssistantProvider` using Pydantic models. |
| [`openai_assistants_with_thread.py`](openai_assistants_with_thread.py) | Thread management with `OpenAIAssistantProvider` for conversation context persistence. |
@@ -20,24 +20,25 @@ This folder contains examples demonstrating different ways to create and use age
| [`openai_chat_client_with_function_tools.py`](openai_chat_client_with_function_tools.py) | Demonstrates how to use function tools with agents. Shows both agent-level tools (defined when creating the agent) and query-level tools (provided with specific queries). |
| [`openai_chat_client_with_local_mcp.py`](openai_chat_client_with_local_mcp.py) | Shows how to integrate OpenAI agents with local Model Context Protocol (MCP) servers for enhanced functionality and tool integration. |
| [`openai_chat_client_with_thread.py`](openai_chat_client_with_thread.py) | Demonstrates thread management with OpenAI agents, including automatic thread creation for stateless conversations and explicit thread management for maintaining conversation context across multiple interactions. |
| [`openai_chat_client_with_web_search.py`](openai_chat_client_with_web_search.py) | Shows how to use web search capabilities with OpenAI agents to retrieve and use information from the internet in responses. |
| [`openai_chat_client_with_web_search.py`](openai_chat_client_with_web_search.py) | Shows how to use `OpenAIChatClient.get_web_search_tool()` for web search capabilities with OpenAI agents. |
| [`openai_chat_client_with_runtime_json_schema.py`](openai_chat_client_with_runtime_json_schema.py) | Shows how to supply a runtime JSON Schema via `additional_chat_options` for structured output without defining a Pydantic model. |
| [`openai_responses_client_basic.py`](openai_responses_client_basic.py) | The simplest way to create an agent using `Agent` with `OpenAIResponsesClient`. Shows both streaming and non-streaming responses for structured response generation with OpenAI models. |
| [`openai_responses_client_image_analysis.py`](openai_responses_client_image_analysis.py) | Demonstrates how to use vision capabilities with agents to analyze images. |
| [`openai_responses_client_image_generation.py`](openai_responses_client_image_generation.py) | Demonstrates how to use image generation capabilities with OpenAI agents to create images based on text descriptions. Requires PIL (Pillow) for image display. |
| [`openai_responses_client_image_generation.py`](openai_responses_client_image_generation.py) | Demonstrates how to use `OpenAIResponsesClient.get_image_generation_tool()` to create images based on text descriptions. |
| [`openai_responses_client_reasoning.py`](openai_responses_client_reasoning.py) | Demonstrates how to use reasoning capabilities with OpenAI agents, showing how the agent can provide detailed reasoning for its responses. |
| [`openai_responses_client_streaming_image_generation.py`](openai_responses_client_streaming_image_generation.py) | Demonstrates streaming image generation with partial images for real-time image creation feedback and improved user experience. |
| [`openai_responses_client_with_agent_as_tool.py`](openai_responses_client_with_agent_as_tool.py) | Shows how to use the agent-as-tool pattern with OpenAI Responses Client, where one agent delegates work to specialized sub-agents wrapped as tools using `as_tool()`. Demonstrates hierarchical agent architectures. |
| [`openai_responses_client_with_code_interpreter.py`](openai_responses_client_with_code_interpreter.py) | Shows how to use the HostedCodeInterpreterTool with OpenAI agents to write and execute Python code. Includes helper methods for accessing code interpreter data from response chunks. |
| [`openai_responses_client_with_code_interpreter.py`](openai_responses_client_with_code_interpreter.py) | Shows how to use `OpenAIResponsesClient.get_code_interpreter_tool()` to write and execute Python code. |
| [`openai_responses_client_with_code_interpreter_files.py`](openai_responses_client_with_code_interpreter_files.py) | Shows how to use code interpreter with uploaded files for data analysis. |
| [`openai_responses_client_with_explicit_settings.py`](openai_responses_client_with_explicit_settings.py) | Shows how to initialize an agent with a specific responses client, configuring settings explicitly including API key and model ID. |
| [`openai_responses_client_with_file_search.py`](openai_responses_client_with_file_search.py) | Demonstrates how to use file search capabilities with OpenAI agents, allowing the agent to search through uploaded files to answer questions. |
| [`openai_responses_client_with_file_search.py`](openai_responses_client_with_file_search.py) | Demonstrates how to use `OpenAIResponsesClient.get_file_search_tool()` for searching through uploaded files. |
| [`openai_responses_client_with_function_tools.py`](openai_responses_client_with_function_tools.py) | Demonstrates how to use function tools with agents. Shows both agent-level tools (defined when creating the agent) and run-level tools (provided with specific queries). |
| [`openai_responses_client_with_hosted_mcp.py`](openai_responses_client_with_hosted_mcp.py) | Shows how to integrate OpenAI agents with hosted Model Context Protocol (MCP) servers, including approval workflows and tool management for remote MCP services. |
| [`openai_responses_client_with_hosted_mcp.py`](openai_responses_client_with_hosted_mcp.py) | Shows how to use `OpenAIResponsesClient.get_mcp_tool()` for hosted MCP servers, including approval workflows. |
| [`openai_responses_client_with_local_mcp.py`](openai_responses_client_with_local_mcp.py) | Shows how to integrate OpenAI agents with local Model Context Protocol (MCP) servers for enhanced functionality and tool integration. |
| [`openai_responses_client_with_runtime_json_schema.py`](openai_responses_client_with_runtime_json_schema.py) | Shows how to supply a runtime JSON Schema via `additional_chat_options` for structured output without defining a Pydantic model. |
| [`openai_responses_client_with_structured_output.py`](openai_responses_client_with_structured_output.py) | Demonstrates how to use structured outputs with OpenAI agents to get structured data responses in predefined formats. |
| [`openai_responses_client_with_thread.py`](openai_responses_client_with_thread.py) | Demonstrates thread management with OpenAI agents, including automatic thread creation for stateless conversations and explicit thread management for maintaining conversation context across multiple interactions. |
| [`openai_responses_client_with_web_search.py`](openai_responses_client_with_web_search.py) | Shows how to use web search capabilities with OpenAI agents to retrieve and use information from the internet in responses. |
| [`openai_responses_client_with_web_search.py`](openai_responses_client_with_web_search.py) | Shows how to use `OpenAIResponsesClient.get_web_search_tool()` for web search capabilities. |
## Environment Variables
@@ -18,7 +18,9 @@ assistant lifecycle management, showing both streaming and non-streaming respons
"""
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/getting_started/tools/function_tool_with_approval.py
# and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
@@ -20,7 +20,9 @@ This sample demonstrates the methods available on the OpenAIAssistantProvider cl
"""
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/getting_started/tools/function_tool_with_approval.py
# and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
@@ -3,8 +3,8 @@
import asyncio
import os
from agent_framework import AgentResponseUpdate, ChatResponseUpdate, HostedCodeInterpreterTool
from agent_framework.openai import OpenAIAssistantProvider
from agent_framework import AgentResponseUpdate, ChatResponseUpdate
from agent_framework.openai import OpenAIAssistantProvider, OpenAIAssistantsClient
from openai import AsyncOpenAI
from openai.types.beta.threads.runs import (
CodeInterpreterToolCallDelta,
@@ -17,7 +17,7 @@ from openai.types.beta.threads.runs.code_interpreter_tool_call_delta import Code
"""
OpenAI Assistants with Code Interpreter Example
This sample demonstrates using HostedCodeInterpreterTool with OpenAI Assistants
This sample demonstrates using get_code_interpreter_tool() with OpenAI Assistants
for Python code execution and mathematical problem solving.
"""
@@ -42,17 +42,18 @@ def get_code_interpreter_chunk(chunk: AgentResponseUpdate) -> str | None:
async def main() -> None:
"""Example showing how to use the HostedCodeInterpreterTool with OpenAI Assistants."""
"""Example showing how to use the code interpreter tool with OpenAI Assistants."""
print("=== OpenAI Assistants Provider with Code Interpreter Example ===")
client = AsyncOpenAI()
provider = OpenAIAssistantProvider(client)
chat_client = OpenAIAssistantsClient(client=client)
agent = await provider.create_agent(
name="CodeHelper",
model=os.environ.get("OPENAI_CHAT_MODEL_ID", "gpt-4"),
instructions="You are a helpful assistant that can write and execute Python code to solve problems.",
tools=[HostedCodeInterpreterTool()],
tools=[chat_client.get_code_interpreter_tool()],
)
try:
@@ -18,7 +18,9 @@ settings rather than relying on environment variable defaults.
"""
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/getting_started/tools/function_tool_with_approval.py
# and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
@@ -43,7 +45,9 @@ async def main() -> None:
)
try:
result = await agent.run("What's the weather like in New York?")
query = "What's the weather like in New York?"
print(f"Query: {query}")
result = await agent.run(query)
print(f"Result: {result}\n")
finally:
await client.beta.assistants.delete(agent.id)
@@ -3,14 +3,14 @@
import asyncio
import os
from agent_framework import Content, HostedFileSearchTool
from agent_framework.openai import OpenAIAssistantProvider
from agent_framework import Content
from agent_framework.openai import OpenAIAssistantProvider, OpenAIAssistantsClient
from openai import AsyncOpenAI
"""
OpenAI Assistants with File Search Example
This sample demonstrates using HostedFileSearchTool with OpenAI Assistants
This sample demonstrates using get_file_search_tool() with OpenAI Assistants
for document-based question answering and information retrieval.
"""
@@ -42,29 +42,30 @@ async def main() -> None:
client = AsyncOpenAI()
provider = OpenAIAssistantProvider(client)
chat_client = OpenAIAssistantsClient(client=client)
agent = await provider.create_agent(
name="SearchAssistant",
model=os.environ.get("OPENAI_CHAT_MODEL_ID", "gpt-4"),
instructions="You are a helpful assistant that searches files in a knowledge base.",
tools=[HostedFileSearchTool()],
tools=[chat_client.get_file_search_tool()],
)
try:
query = "What is the weather today? Do a file search to find the answer."
file_id, vector_store = await create_vector_store(client)
file_id, vector_store_content = await create_vector_store(client)
print(f"User: {query}")
print("Agent: ", end="", flush=True)
async for chunk in agent.run(
query,
stream=True,
options={"tool_resources": {"file_search": {"vector_store_ids": [vector_store.vector_store_id]}}},
options={"tool_resources": {"file_search": {"vector_store_ids": [vector_store_content.vector_store_id]}}},
):
if chunk.text:
print(chunk.text, end="", flush=True)
await delete_vector_store(client, file_id, vector_store.vector_store_id)
await delete_vector_store(client, file_id, vector_store_content.vector_store_id)
finally:
await client.beta.assistants.delete(agent.id)
@@ -18,7 +18,9 @@ persistent conversation threads and context preservation across interactions.
"""
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/getting_started/tools/function_tool_with_approval.py
# and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
@@ -15,7 +15,9 @@ interactions, showing both streaming and non-streaming responses.
"""
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/getting_started/tools/function_tool_with_approval.py
# and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, "The location to get the weather for."],
@@ -17,7 +17,9 @@ settings rather than relying on environment variable defaults.
"""
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/getting_started/tools/function_tool_with_approval.py
# and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
@@ -17,7 +17,9 @@ showing both agent-level and query-level tool configuration patterns.
"""
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/getting_started/tools/function_tool_with_approval.py
# and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
@@ -16,7 +16,9 @@ conversation threads and message history preservation across interactions.
"""
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/getting_started/tools/function_tool_with_approval.py
# and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
@@ -2,30 +2,29 @@
import asyncio
from agent_framework import Agent, HostedWebSearchTool
from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient
"""
OpenAI Chat Client with Web Search Example
This sample demonstrates using HostedWebSearchTool with OpenAI Chat Client
This sample demonstrates using get_web_search_tool() with OpenAI Chat Client
for real-time information retrieval and current data access.
"""
async def main() -> None:
# Test that the agent will use the web search tool with location
additional_properties = {
"user_location": {
"country": "US",
"city": "Seattle",
}
}
client = OpenAIChatClient(model_id="gpt-4o-search-preview")
# Create web search tool with location context
web_search_tool = client.get_web_search_tool(
user_location={"city": "Seattle", "country": "US"},
)
agent = Agent(
client=OpenAIChatClient(model_id="gpt-4o-search-preview"),
client=client,
instructions="You are a helpful assistant that can search the web for current information.",
tools=[HostedWebSearchTool(additional_properties=additional_properties)],
tools=[web_search_tool],
)
message = "What is the current weather? Do not ask for my current location."
@@ -66,7 +66,9 @@ async def security_and_override_middleware(
print(type(context.result))
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/getting_started/tools/function_tool_with_approval.py
# and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
@@ -101,7 +103,7 @@ async def streaming_example() -> None:
middleware=[security_and_override_middleware],
),
instructions="You are a helpful weather agent.",
# tools=get_weather,
tools=get_weather,
)
query = "What's the weather like in Portland?"
@@ -28,7 +28,7 @@ async def main():
contents=[
Content.from_text(text="What do you see in this image?"),
Content.from_uri(
uri="https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg",
uri="https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800",
media_type="image/jpeg",
),
],
@@ -2,8 +2,12 @@
import asyncio
import base64
import tempfile
import urllib.request as urllib_request
from pathlib import Path
from agent_framework import HostedImageGenerationTool
import aiofiles # pyright: ignore[reportMissingModuleSource]
from agent_framework import Content
from agent_framework.openai import OpenAIResponsesClient
"""
@@ -16,65 +20,80 @@ and automated visual asset generation.
"""
def show_image_info(data_uri: str) -> None:
"""Display information about the generated image."""
try:
# Extract format and size info from data URI
if data_uri.startswith("data:image/"):
format_info = data_uri.split(";")[0].split("/")[1]
base64_data = data_uri.split(",", 1)[1]
image_bytes = base64.b64decode(base64_data)
size_kb = len(image_bytes) / 1024
async def save_image(output: Content) -> None:
"""Save the generated image to a temporary directory."""
filename = "generated_image.webp"
file_path = Path(tempfile.gettempdir()) / filename
print(" Image successfully generated!")
print(f" Format: {format_info.upper()}")
print(f" Size: {size_kb:.1f} KB")
print(f" Data URI length: {len(data_uri)} characters")
print("")
print(" To save and view the image:")
print(' 1. Install Pillow: "pip install pillow" or "uv add pillow"')
print(" 2. Use the data URI in your code to save/display the image")
print(" 3. Or copy the base64 data to an online base64 image decoder")
data_bytes: bytes | None = None
uri = getattr(output, "uri", None)
if isinstance(uri, str):
if ";base64," in uri:
try:
b64 = uri.split(";base64,", 1)[1]
data_bytes = base64.b64decode(b64)
except Exception:
data_bytes = None
else:
print(f" Image URL generated: {data_uri}")
print(" You can open this URL in a browser to view the image")
try:
data_bytes = await asyncio.to_thread(lambda: urllib_request.urlopen(uri).read())
except Exception:
data_bytes = None
except Exception as e:
print(f" Error processing image data: {e}")
print(" Image generated but couldn't parse details")
if data_bytes is None:
raise RuntimeError("Image output present but could not retrieve bytes.")
async with aiofiles.open(file_path, "wb") as f:
await f.write(data_bytes)
print(f"Image downloaded and saved to: {file_path}")
async def main() -> None:
print("=== OpenAI Responses Image Generation Agent Example ===")
# Create an agent with customized image generation options
agent = OpenAIResponsesClient().as_agent(
client = OpenAIResponsesClient()
agent = client.as_agent(
instructions="You are a helpful AI that can generate images.",
tools=[
HostedImageGenerationTool(
options={
"size": "1024x1024",
"output_format": "webp",
}
client.get_image_generation_tool(
size="1024x1024",
output_format="webp",
)
],
)
query = "Generate a nice beach scenery with blue skies in summer time."
query = "Generate a black furry cat."
print(f"User: {query}")
print("Generating image with parameters: 1024x1024 size, transparent background, low quality, WebP format...")
print("Generating image with parameters: 1024x1024 size, WebP format...")
result = await agent.run(query)
print(f"Agent: {result.text}")
# Show information about the generated image
# Find and save the generated image
image_saved = False
for message in result.messages:
for content in message.contents:
if content.type == "image_generation_tool_result" and content.outputs:
for output in content.outputs:
if output.type in ("data", "uri") and output.uri:
show_image_info(output.uri)
break
if content.type == "image_generation_tool_result_tool_result" and content.outputs:
output = content.outputs
if isinstance(output, Content) and output.uri:
await save_image(output)
image_saved = True
elif isinstance(output, list):
for out in output:
if isinstance(out, Content) and out.uri:
await save_image(out)
image_saved = True
break
if image_saved:
break
if image_saved:
break
if not image_saved:
print("No image data found in the agent response.")
if __name__ == "__main__":
@@ -2,9 +2,10 @@
import asyncio
import base64
import tempfile
from pathlib import Path
import anyio
from agent_framework import HostedImageGenerationTool
from agent_framework.openai import OpenAIResponsesClient
"""OpenAI Responses Client Streaming Image Generation Example
@@ -42,15 +43,14 @@ async def main():
print("=== OpenAI Streaming Image Generation Example ===\n")
# Create agent with streaming image generation enabled
agent = OpenAIResponsesClient().as_agent(
client = OpenAIResponsesClient()
agent = client.as_agent(
instructions="You are a helpful agent that can generate images.",
tools=[
HostedImageGenerationTool(
options={
"size": "1024x1024",
"quality": "high",
"partial_images": 3,
}
client.get_image_generation_tool(
size="1024x1024",
quality="high",
partial_images=3,
)
],
)
@@ -62,9 +62,9 @@ async def main():
# Track partial images
image_count = 0
# Create output directory
output_dir = anyio.Path("generated_images")
await output_dir.mkdir(exist_ok=True)
# Use temp directory for output
output_dir = Path(tempfile.gettempdir()) / "generated_images"
output_dir.mkdir(exist_ok=True)
print(" Streaming response:")
async for update in agent.run(query, stream=True):
@@ -72,7 +72,11 @@ async def main():
# Handle partial images
# The final partial image IS the complete, full-quality image. Each partial
# represents a progressive refinement, with the last one being the finished result.
if content.type == "data" and content.additional_properties.get("is_partial_image"):
if (
content.type == "uri"
and content.additional_properties
and content.additional_properties.get("is_partial_image")
):
print(f" Image {image_count} received")
# Extract file extension from media_type (e.g., "image/png" -> "png")
@@ -89,7 +93,7 @@ async def main():
# Summary
print("\n Summary:")
print(f" Images received: {image_count}")
print(" Output directory: generated_images")
print(f" Output directory: {output_dir}")
print("\n Streaming image generation completed!")
@@ -4,26 +4,27 @@ import asyncio
from agent_framework import (
Agent,
HostedCodeInterpreterTool,
Content,
)
from agent_framework.openai import OpenAIResponsesClient
"""
OpenAI Responses Client with Code Interpreter Example
This sample demonstrates using HostedCodeInterpreterTool with OpenAI Responses Client
This sample demonstrates using get_code_interpreter_tool() with OpenAI Responses Client
for Python code execution and mathematical problem solving.
"""
async def main() -> None:
"""Example showing how to use the HostedCodeInterpreterTool with OpenAI Responses."""
"""Example showing how to use the code interpreter tool with OpenAI Responses."""
print("=== OpenAI Responses Agent with Code Interpreter Example ===")
client = OpenAIResponsesClient()
agent = Agent(
client=OpenAIResponsesClient(),
client=client,
instructions="You are a helpful assistant that can write and execute Python code to solve problems.",
tools=HostedCodeInterpreterTool(),
tools=client.get_code_interpreter_tool(),
)
query = "Use code to get the factorial of 100?"
@@ -34,16 +35,17 @@ async def main() -> None:
for message in result.messages:
code_blocks = [c for c in message.contents if c.type == "code_interpreter_tool_call"]
outputs = [c for c in message.contents if c.type == "code_interpreter_tool_result"]
if code_blocks:
code_inputs = code_blocks[0].inputs or []
for content in code_inputs:
if content.type == "text":
if isinstance(content, Content) and content.type == "text":
print(f"Generated code:\n{content.text}")
break
if outputs:
print("Execution outputs:")
for out in outputs[0].outputs or []:
if out.type == "text":
if isinstance(out, Content) and out.type == "text":
print(out.text)
@@ -4,14 +4,14 @@ import asyncio
import os
import tempfile
from agent_framework import Agent, HostedCodeInterpreterTool
from agent_framework import Agent
from agent_framework.openai import OpenAIResponsesClient
from openai import AsyncOpenAI
"""
OpenAI Responses Client with Code Interpreter and Files Example
This sample demonstrates using HostedCodeInterpreterTool with OpenAI Responses Client
This sample demonstrates using get_code_interpreter_tool() with OpenAI Responses Client
for Python code execution and data analysis with uploaded files.
"""
@@ -66,10 +66,11 @@ async def main() -> None:
temp_file_path, file_id = await create_sample_file_and_upload(openai_client)
# Create agent using OpenAI Responses client
client = OpenAIResponsesClient()
agent = Agent(
client=OpenAIResponsesClient(),
client=client,
instructions="You are a helpful assistant that can analyze data files using Python code.",
tools=HostedCodeInterpreterTool(inputs=[{"file_id": file_id}]),
tools=client.get_code_interpreter_tool(file_ids=[file_id]),
)
# Test the code interpreter with the uploaded file
@@ -17,7 +17,9 @@ settings rather than relying on environment variable defaults.
"""
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/getting_started/tools/function_tool_with_approval.py
# and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
@@ -2,13 +2,13 @@
import asyncio
from agent_framework import Agent, Content, HostedFileSearchTool
from agent_framework import Agent, Content
from agent_framework.openai import OpenAIResponsesClient
"""
OpenAI Responses Client with File Search Example
This sample demonstrates using HostedFileSearchTool with OpenAI Responses Client
This sample demonstrates using get_file_search_tool() with OpenAI Responses Client
for direct document-based question answering and information retrieval.
"""
@@ -33,7 +33,6 @@ async def create_vector_store(client: OpenAIResponsesClient) -> tuple[str, Conte
async def delete_vector_store(client: OpenAIResponsesClient, file_id: str, vector_store_id: str) -> None:
"""Delete the vector store after using it."""
await client.client.vector_stores.delete(vector_store_id=vector_store_id)
await client.client.files.delete(file_id=file_id)
@@ -45,12 +44,12 @@ async def main() -> None:
stream = False
print(f"User: {message}")
file_id, vector_store = await create_vector_store(client)
file_id, vector_store_id = await create_vector_store(client)
agent = Agent(
client=client,
instructions="You are a helpful assistant that can search through files to find information.",
tools=[HostedFileSearchTool(inputs=vector_store)],
tools=[client.get_file_search_tool(vector_store_ids=[vector_store_id])],
)
if stream:
@@ -62,7 +61,7 @@ async def main() -> None:
else:
response = await agent.run(message)
print(f"Assistant: {response}")
await delete_vector_store(client, file_id, vector_store.vector_store_id)
await delete_vector_store(client, file_id, vector_store_id)
if __name__ == "__main__":
@@ -17,7 +17,9 @@ showing both agent-level and query-level tool configuration patterns.
"""
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/getting_started/tools/function_tool_with_approval.py
# and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
@@ -3,7 +3,7 @@
import asyncio
from typing import TYPE_CHECKING, Any
from agent_framework import Agent, HostedMCPTool
from agent_framework import Agent
from agent_framework.openai import OpenAIResponsesClient
"""
@@ -32,7 +32,10 @@ async def handle_approvals_without_thread(query: str, agent: "SupportsAgentRun")
new_inputs.append(Message(role="assistant", contents=[user_input_needed]))
user_approval = input("Approve function call? (y/n): ")
new_inputs.append(
Message(role="user", contents=[user_input_needed.to_function_approval_response(user_approval.lower() == "y")])
Message(
role="user",
contents=[user_input_needed.to_function_approval_response(user_approval.lower() == "y")],
)
)
result = await agent.run(new_inputs)
@@ -81,7 +84,8 @@ async def handle_approvals_with_thread_streaming(query: str, agent: "SupportsAge
user_approval = input("Approve function call? (y/n): ")
new_input.append(
Message(
role="user", contents=[user_input_needed.to_function_approval_response(user_approval.lower() == "y")]
role="user",
contents=[user_input_needed.to_function_approval_response(user_approval.lower() == "y")],
)
)
new_input_added = True
@@ -93,19 +97,21 @@ async def run_hosted_mcp_without_thread_and_specific_approval() -> None:
"""Example showing Mcp Tools with approvals without using a thread."""
print("=== Mcp with approvals and without thread ===")
# Tools are provided when creating the agent
# The agent can use these tools for any query during its lifetime
client = OpenAIResponsesClient()
# Create MCP tool with specific approval mode
mcp_tool = client.get_mcp_tool(
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
# we don't require approval for microsoft_docs_search tool calls
# but we do for any other tool
approval_mode={"never_require_approval": ["microsoft_docs_search"]},
)
async with Agent(
client=OpenAIResponsesClient(),
client=client,
name="DocsAgent",
instructions="You are a helpful assistant that can help with microsoft documentation questions.",
tools=HostedMCPTool(
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
# we don't require approval for microsoft_docs_search tool calls
# but we do for any other tool
approval_mode={"never_require_approval": ["microsoft_docs_search"]},
),
tools=mcp_tool,
) as agent:
# First query
query1 = "How to create an Azure storage account using az cli?"
@@ -124,20 +130,20 @@ async def run_hosted_mcp_without_approval() -> None:
"""Example showing Mcp Tools without approvals."""
print("=== Mcp without approvals ===")
# Tools are provided when creating the agent
# The agent can use these tools for any query during its lifetime
client = OpenAIResponsesClient()
# Create MCP tool that never requires approval
mcp_tool = client.get_mcp_tool(
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
# we don't require approval for any function calls
approval_mode="never_require",
)
async with Agent(
client=OpenAIResponsesClient(),
client=client,
name="DocsAgent",
instructions="You are a helpful assistant that can help with microsoft documentation questions.",
tools=HostedMCPTool(
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
# we don't require approval for any function calls
# this means we will not see the approval messages,
# it is fully handled by the service and a final response is returned.
approval_mode="never_require",
),
tools=mcp_tool,
) as agent:
# First query
query1 = "How to create an Azure storage account using az cli?"
@@ -156,18 +162,20 @@ async def run_hosted_mcp_with_thread() -> None:
"""Example showing Mcp Tools with approvals using a thread."""
print("=== Mcp with approvals and with thread ===")
# Tools are provided when creating the agent
# The agent can use these tools for any query during its lifetime
client = OpenAIResponsesClient()
# Create MCP tool that always requires approval
mcp_tool = client.get_mcp_tool(
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
# we require approval for all function calls
approval_mode="always_require",
)
async with Agent(
client=OpenAIResponsesClient(),
client=client,
name="DocsAgent",
instructions="You are a helpful assistant that can help with microsoft documentation questions.",
tools=HostedMCPTool(
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
# we require approval for all function calls
approval_mode="always_require",
),
tools=mcp_tool,
) as agent:
# First query
thread = agent.get_new_thread()
@@ -187,18 +195,20 @@ async def run_hosted_mcp_with_thread_streaming() -> None:
"""Example showing Mcp Tools with approvals using a thread."""
print("=== Mcp with approvals and with thread ===")
# Tools are provided when creating the agent
# The agent can use these tools for any query during its lifetime
client = OpenAIResponsesClient()
# Create MCP tool that always requires approval
mcp_tool = client.get_mcp_tool(
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
# we require approval for all function calls
approval_mode="always_require",
)
async with Agent(
client=OpenAIResponsesClient(),
client=client,
name="DocsAgent",
instructions="You are a helpful assistant that can help with microsoft documentation questions.",
tools=HostedMCPTool(
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
# we require approval for all function calls
approval_mode="always_require",
),
tools=mcp_tool,
) as agent:
# First query
thread = agent.get_new_thread()
@@ -16,7 +16,9 @@ persistent conversation context and simplified response handling.
"""
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/getting_started/tools/function_tool_with_approval.py and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production;
# see samples/getting_started/tools/function_tool_with_approval.py
# and samples/getting_started/tools/function_tool_with_approval_and_threads.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
@@ -2,30 +2,29 @@
import asyncio
from agent_framework import Agent, HostedWebSearchTool
from agent_framework import Agent
from agent_framework.openai import OpenAIResponsesClient
"""
OpenAI Responses Client with Web Search Example
This sample demonstrates using HostedWebSearchTool with OpenAI Responses Client
This sample demonstrates using get_web_search_tool() with OpenAI Responses Client
for direct real-time information retrieval and current data access.
"""
async def main() -> None:
# Test that the agent will use the web search tool with location
additional_properties = {
"user_location": {
"country": "US",
"city": "Seattle",
}
}
client = OpenAIResponsesClient()
# Create web search tool with location context
web_search_tool = client.get_web_search_tool(
user_location={"city": "Seattle", "country": "US"},
)
agent = Agent(
client=OpenAIResponsesClient(),
client=client,
instructions="You are a helpful assistant that can search the web for current information.",
tools=[HostedWebSearchTool(additional_properties=additional_properties)],
tools=[web_search_tool],
)
message = "What is the current weather? Do not ask for my current location."
@@ -22,7 +22,7 @@ from agent_framework.azure import AzureAIClient
from azure.identity.aio import AzureCliCredential
if TYPE_CHECKING:
from agent_framework import ToolProtocol
from agent_framework import FunctionTool
if sys.version_info >= (3, 12):
from typing import override # type: ignore # pragma: no cover
@@ -94,7 +94,7 @@ class AggregateContextProvider(ContextProvider):
contexts = await asyncio.gather(*[provider.invoking(messages, **kwargs) for provider in self.providers])
instructions: str = ""
return_messages: list[Message] = []
tools: list["ToolProtocol"] = []
tools: list["FunctionTool"] = []
for ctx in contexts:
if ctx.instructions:
instructions += ctx.instructions
@@ -3,7 +3,7 @@
import asyncio
import os
from agent_framework import Agent, HostedMCPTool
from agent_framework import Agent
from agent_framework.openai import OpenAIResponsesClient
from dotenv import load_dotenv
@@ -42,20 +42,20 @@ async def github_mcp_example() -> None:
"Authorization": f"Bearer {github_pat}",
}
# 4. Create MCP tool with authentication
# HostedMCPTool manages the connection to the MCP server and makes its tools available
# 4. Create agent with the GitHub MCP tool using instance method
# The MCP tool manages the connection to the MCP server and makes its tools available
# Set approval_mode="never_require" to allow the MCP tool to execute without approval
github_mcp_tool = HostedMCPTool(
name="GitHub",
description="Tool for interacting with GitHub.",
url="https://api.githubcopilot.com/mcp/",
client = OpenAIResponsesClient()
github_mcp_tool = client.get_mcp_tool(
server_label="GitHub",
server_url="https://api.githubcopilot.com/mcp/",
headers=auth_headers,
approval_mode="never_require",
require_approval="never",
)
# 5. Create agent with the GitHub MCP tool
async with Agent(
client=OpenAIResponsesClient(),
client=client,
name="GitHubAgent",
instructions=(
"You are a helpful assistant that can help users interact with GitHub. "
@@ -83,10 +83,9 @@ async def main() -> None:
HandoffBuilder(
name="autonomous_iteration_handoff",
participants=[coordinator, research_agent, summary_agent],
termination_condition=lambda conv: sum(
1 for msg in conv if msg.author_name == "coordinator" and msg.role == "assistant"
)
>= 5,
termination_condition=lambda conv: (
sum(1 for msg in conv if msg.author_name == "coordinator" and msg.role == "assistant") >= 5
),
)
.with_start_agent(coordinator)
.add_handoff(coordinator, [research_agent, summary_agent])
@@ -33,7 +33,6 @@ from typing import cast
from agent_framework import (
Agent,
AgentResponseUpdate,
HostedCodeInterpreterTool,
Message,
WorkflowEvent,
WorkflowRunState,
@@ -109,13 +108,16 @@ async def create_agents_v1(credential: AzureCliCredential) -> AsyncIterator[tupl
),
)
# Create code interpreter tool using instance method
code_interpreter_tool = client.get_code_interpreter_tool()
code_specialist = client.as_agent(
name="code_specialist",
instructions=(
"You are a Python code specialist. Use the code interpreter to execute Python code "
"and create files when requested. Always save files to /mnt/data/ directory."
),
tools=[HostedCodeInterpreterTool()],
tools=[code_interpreter_tool],
)
yield triage, code_specialist # type: ignore
@@ -139,6 +141,9 @@ async def create_agents_v2(credential: AzureCliCredential) -> AsyncIterator[tupl
instructions="You are a triage agent. Your ONLY job is to route requests to the appropriate specialist.",
)
# Create code interpreter tool using instance method
code_interpreter_tool = code_client.get_code_interpreter_tool()
code_specialist = code_client.as_agent(
name="CodeSpecialist",
instructions=(
@@ -147,7 +152,7 @@ async def create_agents_v2(credential: AzureCliCredential) -> AsyncIterator[tupl
"Always save files to /mnt/data/ directory. "
"Do NOT discuss handoffs or routing - just complete the coding task directly."
),
tools=[HostedCodeInterpreterTool()],
tools=[code_interpreter_tool],
)
yield triage, code_specialist
@@ -8,7 +8,6 @@ from typing import cast
from agent_framework import (
Agent,
AgentResponseUpdate,
HostedCodeInterpreterTool,
Message,
WorkflowEvent,
)
@@ -54,12 +53,16 @@ async def main() -> None:
client=OpenAIChatClient(model_id="gpt-4o-search-preview"),
)
# Create code interpreter tool using instance method
coder_client = OpenAIResponsesClient()
code_interpreter_tool = coder_client.get_code_interpreter_tool()
coder_agent = Agent(
name="CoderAgent",
description="A helpful assistant that writes and executes code to process and analyze data.",
instructions="You solve questions using code. Please provide detailed analysis and computation process.",
client=OpenAIResponsesClient(),
tools=HostedCodeInterpreterTool(),
client=coder_client,
tools=code_interpreter_tool,
)
# Create a manager agent for orchestration
@@ -4,7 +4,6 @@ import asyncio
from agent_framework import (
Agent,
HostedCodeInterpreterTool,
)
from agent_framework.openai import OpenAIChatClient, OpenAIResponsesClient
from agent_framework.orchestrations import MagenticBuilder
@@ -32,12 +31,16 @@ async def main() -> None:
client=OpenAIChatClient(model_id="gpt-4o-search-preview"),
)
# Create code interpreter tool using instance method
coder_client = OpenAIResponsesClient()
code_interpreter_tool = coder_client.get_code_interpreter_tool()
coder_agent = Agent(
name="CoderAgent",
description="A helpful assistant that writes and executes code to process and analyze data.",
instructions="You solve questions using code. Please provide detailed analysis and computation process.",
client=OpenAIResponsesClient(),
tools=HostedCodeInterpreterTool(),
client=coder_client,
tools=code_interpreter_tool,
)
# Create a manager agent for orchestration
@@ -39,18 +39,24 @@ async def run_semantic_kernel() -> None:
async def run_agent_framework() -> None:
from agent_framework.azure import AzureAIAgentClient, HostedCodeInterpreterTool
from agent_framework.azure import AzureAIAgentClient, AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).as_agent(
AzureAIAgentsProvider(credential=credential) as provider,
):
# Create a client to access hosted tool factory methods
client = AzureAIAgentClient(agents_client=provider._agents_client)
code_interpreter_tool = client.get_code_interpreter_tool()
agent = await provider.create_agent(
name="Analyst",
instructions="Use the code interpreter for numeric work.",
tools=[HostedCodeInterpreterTool()],
) as agent,
):
# HostedCodeInterpreterTool mirrors the built-in Azure AI capability.
tools=[code_interpreter_tool],
)
# Code interpreter tool mirrors the built-in Azure AI capability.
reply = await agent.run(
"Use Python to compute 42 ** 2 and explain the result.",
tool_choice="auto",
@@ -37,16 +37,19 @@ async def run_semantic_kernel() -> None:
async def run_agent_framework() -> None:
from agent_framework import HostedCodeInterpreterTool
from agent_framework.openai import OpenAIAssistantsClient
assistants_client = OpenAIAssistantsClient()
# Create code interpreter tool using static method
code_interpreter_tool = OpenAIAssistantsClient.get_code_interpreter_tool()
# AF exposes the same tool configuration via create_agent.
async with assistants_client.as_agent(
name="CodeRunner",
instructions="Use the code interpreter when calculations are required.",
model="gpt-4.1",
tools=[HostedCodeInterpreterTool()],
tools=[code_interpreter_tool],
) as assistant_agent:
response = await assistant_agent.run(
"Use Python to calculate the mean of [41, 42, 45] and explain the steps.",
@@ -19,8 +19,8 @@ from agent_framework import (
Message,
WorkflowEvent,
)
from agent_framework.orchestrations import HandoffBuilder, HandoffUserInputRequest
from agent_framework.azure import AzureOpenAIChatClient
from agent_framework.orchestrations import HandoffBuilder, HandoffUserInputRequest
from azure.identity import AzureCliCredential
from semantic_kernel.agents import Agent, ChatCompletionAgent, HandoffOrchestration, OrchestrationHandoffs
from semantic_kernel.agents.runtime import InProcessRuntime
@@ -15,7 +15,7 @@ import asyncio
from collections.abc import Sequence
from typing import cast
from agent_framework import Agent, HostedCodeInterpreterTool
from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient, OpenAIResponsesClient
from agent_framework.orchestrations import MagenticBuilder
from semantic_kernel.agents import (
@@ -138,12 +138,16 @@ async def run_agent_framework_example(prompt: str) -> str | None:
client=OpenAIChatClient(ai_model_id="gpt-4o-search-preview"),
)
# Create code interpreter tool using instance method
coder_client = OpenAIResponsesClient()
code_interpreter_tool = coder_client.get_code_interpreter_tool()
coder = Agent(
name="CoderAgent",
description="A helpful assistant that writes and executes code to process and analyze data.",
instructions="You solve questions using code. Please provide detailed analysis and computation process.",
client=OpenAIResponsesClient(),
tools=HostedCodeInterpreterTool(),
client=coder_client,
tools=code_interpreter_tool,
)
# Create a manager agent for orchestration
@@ -20,7 +20,7 @@ from typing import TYPE_CHECKING, ClassVar, cast
######################################################################
# region Agent Framework imports
######################################################################
from agent_framework import Executor, WorkflowBuilder, WorkflowContext, handler
from agent_framework import Executor, WorkflowBuilder, WorkflowContext, handler
from pydantic import BaseModel, Field
######################################################################
@@ -26,7 +26,6 @@ from agent_framework import (
WorkflowBuilder,
WorkflowContext,
WorkflowExecutor,
handler,
)
from pydantic import BaseModel, Field