### Install Agent Framework (Python) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-types/azure-openai-responses-agent Installs the Agent Framework package for Python projects using pip. Use the '--pre' flag to ensure you get the latest prerelease version. ```bash pip install agent-framework --pre ``` -------------------------------- ### Custom Exporter Setup in Python Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-observability Demonstrates how to set up custom exporters for observability by passing a custom tracer provider and meter provider to the `setup_observability` function. This example uses an OTLPSpanExporter with specific configurations. ```python from agent_framework.observability import setup_observability from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter from opentelemetry.sdk.resources import Compression # Assuming Compression is imported from here custom_span_exporter = OTLPSpanExporter(endpoint="http://localhost:4317", timeout=5, compression=Compression.Gzip) setup_observability(exporters=[custom_span_exporter]) ``` -------------------------------- ### Install Agent Framework NuGet Packages (C#) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-types/azure-openai-responses-agent Installs the required Azure OpenAI and Microsoft Agents AI packages for .NET projects. Ensure you are using the prerelease versions for compatibility. ```powershell dotnet add package Azure.AI.OpenAI --prerelease dotnet add package Azure.Identity dotnet add package Microsoft.Agents.AI.OpenAI --prerelease ``` -------------------------------- ### Create and Run Agent using Azure AI Helpers (Python) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-types/azure-ai-foundry-agent Creates an agent using AzureAIAgentClient and environment variables, then runs a prompt against it. This example shows basic agent creation and interaction in Python. ```python import asyncio from agent_framework.azure import AzureAIAgentClient from azure.identity.aio import AzureCliCredential async def main(): async with ( AzureCliCredential() as credential, AzureAIAgentClient(async_credential=credential).create_agent( name="HelperAgent", instructions="You are a helpful assistant." ) as agent, ): result = await agent.run("Hello!") print(result.text) asyncio.run(main()) ``` -------------------------------- ### Install Agent Framework (Python) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-types/azure-openai-chat-completion-agent Installs the agent-framework package using pip for Python projects. ```APIDOC ## Installation (Python) ### Description Add the Agent Framework package to your project. ### Method pip install ### Endpoint N/A ### Parameters None ### Request Example ```bash pip install agent-framework --pre ``` ### Response N/A ``` -------------------------------- ### Install Azure AI Agent Framework Package (Bash) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-types/chat-client-agent Installs the agent-framework-azure-ai Python package, which provides specific client implementations for Azure AI services. This is required when integrating with Azure AI. ```bash # For Azure AI pip install agent-framework-azure-ai --pre ``` -------------------------------- ### Create and Manage Persistent Azure AI Agents in Python Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-types/azure-ai-foundry-agent Provides a Python example for creating, using, and then cleaning up a persistent Azure AI agent. It leverages environment variables for endpoint and model deployment names and requires Azure CLI authentication. ```python import asyncio import os from agent_framework import ChatAgent from agent_framework.azure import AzureAIAgentClient from azure.ai.projects.aio import AIProjectClient from azure.identity.aio import AzureCliCredential async def main(): async with ( AzureCliCredential() as credential, AIProjectClient( endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=credential ) as project_client, ): # Create a persistent agent created_agent = await project_client.agents.create_agent( model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"], name="PersistentAgent", instructions="You are a helpful assistant." ) try: # Use the agent async with ChatAgent( chat_client=AzureAIAgentClient( project_client=project_client, agent_id=created_agent.id ), instructions="You are a helpful assistant." ) as agent: result = await agent.run("Hello!") print(result.text) finally: # Clean up the agent await project_client.agents.delete_agent(created_agent.id) asyncio.run(main()) ``` -------------------------------- ### Programmatic Observability Setup in Python Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-observability Sets up observability programmatically using the `setup_observability` function. This implicitly enables tracing and can override environment variable settings. It requires the `agent_framework` library. ```python from agent_framework.observability import setup_observability setup_observability( enable_sensitive_data=True, otlp_endpoint="http://localhost:4317", applicationinsights_connection_string="InstrumentationKey=your_instrumentation_key", vs_code_extension_port=4317 ) ``` -------------------------------- ### Install Agent Framework Python Package (Bash) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-types/chat-client-agent Installs the core agent-framework Python package using pip. This is the foundational package for building agents in Python. ```bash pip install agent-framework --pre ``` -------------------------------- ### Create and Invoke a Persistent Agent (C#) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-types/azure-ai-foundry-agent Demonstrates creating a new persistent agent with specified model, name, and instructions, then retrieving it as an AIAgent. Finally, it invokes the agent to get a response to a prompt. ```csharp // Create a persistent agent var agentMetadata = await persistentAgentsClient.Administration.CreateAgentAsync( model: "gpt-4o-mini", name: "Joker", instructions: "You are good at telling jokes."); // Retrieve the agent that was just created as an AIAgent using its ID AIAgent agent1 = await persistentAgentsClient.GetAIAgentAsync(agentMetadata.Value.Id); // Invoke the agent and output the text result. Console.WriteLine(await agent1.RunAsync("Tell me a joke about a pirate.")); ``` -------------------------------- ### Install Agent Framework Packages (PowerShell) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-types/azure-openai-chat-completion-agent Installs the necessary NuGet packages for using Azure OpenAI with the Agent Framework in a C# project. ```APIDOC ## Install Agent Framework Packages ### Description Add the required NuGet packages to your project to enable Azure OpenAI integration. ### Method dotnet add package ### Endpoint N/A ### Parameters None ### Request Example ```powershell dotnet add package Azure.AI.OpenAI --prerelease dotnet add package Azure.Identity dotnet add package Microsoft.Agents.AI.OpenAI --prerelease ``` ### Response N/A ``` -------------------------------- ### Using Provided Function Tools (Python) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-tools Shows how an agent automatically utilizes the function tools provided during its construction to answer user queries. The example demonstrates a query that would trigger the get_weather function. ```Python result = await agent.run("What's the weather like in Amsterdam?") print(result.text) # The agent will call get_weather() function ``` -------------------------------- ### Install Azure Monitor Exporter in Bash Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-observability Installs the `azure-monitor-opentelemetry-exporter` package, which is required for integrating Azure AI Foundry projects with Application Insights for tracing. ```bash pip install azure-monitor-opentelemetry-exporter>=1.0.0b41 --pre ``` -------------------------------- ### Azure AI Foundry Observability Setup in Python Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-observability Configures observability for Azure AI Foundry projects by retrieving the Application Insights connection string programmatically and passing it to `setup_observability`. This requires the `azure-ai-projects` and `azure-identity` packages, and assumes the `azure-monitor-opentelemetry-exporter` is installed. ```python from agent_framework.azure import AzureAIAgentClient from agent_framework.observability import setup_observability from azure.ai.projects.aio import AIProjectClient from azure.identity import AzureCliCredential from azure.core.exceptions import ResourceNotFoundError async def main(): async with AIProjectClient(credential=AzureCliCredential(), project_endpoint="https://.foundry.azure.com") as project_client: try: conn_string = await project_client.telemetry.get_application_insights_connection_string() setup_observability(applicationinsights_connection_string=conn_string, enable_sensitive_data=True) except ResourceNotFoundError: print("No Application Insights connection string found for the Azure AI Project.") ``` -------------------------------- ### Install Agent Framework Core (Python) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-types/custom-agent Installs the agent-framework-core Python package using pip. This command is used to add the necessary libraries to a Python project for building and interacting with agents. ```bash pip install agent-framework-core --pre ``` -------------------------------- ### Execute Agent and Get Response (C#) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/model-context-protocol/using-mcp-with-foundry-agents Demonstrates how to invoke an agent with a question and retrieve its response using the Agent Framework in C#. It requires an initialized agent object and run options. ```csharp AgentThread thread = agent.GetNewThread(); var response = await agent.RunAsync( "Please summarize the Azure AI Agent documentation related to MCP Tool calling?", thread, runOptions); Console.WriteLine(response); ``` -------------------------------- ### Agent Middleware Logging Example in Python Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-middleware A simple function-based agent middleware example in Python that logs execution timing before and after the agent run. It utilizes `AgentRunContext` and a `next` callable to proceed through the middleware chain. ```python async def logging_agent_middleware( context: AgentRunContext, next: Callable[[AgentRunContext], Awaitable[None]], ) -> None: """Agent middleware that logs execution timing.""" # Pre-processing: Log before agent execution print("[Agent] Starting execution") # Continue to next middleware or agent execution await next(context) # Post-processing: Log after agent execution print("[Agent] Execution completed") ``` -------------------------------- ### Example Trace Output in JSON Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-observability Demonstrates the structure of trace data generated for an agent invocation. This includes trace and span identifiers, timing information, agent metadata, model details, and token usage. ```json { "name": "invoke_agent Joker", "context": { "trace_id": "0xf2258b51421fe9cf4c0bd428c87b1ae4", "span_id": "0x2cad6fc139dcf01d", "trace_state": "[]" }, "kind": "SpanKind.CLIENT", "parent_id": null, "start_time": "2025-09-25T11:00:48.663688Z", "end_time": "2025-09-25T11:00:57.271389Z", "status": { "status_code": "UNSET" }, "attributes": { "gen_ai.operation.name": "invoke_agent", "gen_ai.system": "openai", "gen_ai.agent.id": "Joker", "gen_ai.agent.name": "Joker", "gen_ai.request.instructions": "You are good at telling jokes.", "gen_ai.response.id": "chatcmpl-CH6fgKwMRGDtGNO3H88gA3AG2o7c5", "gen_ai.usage.input_tokens": 26, "gen_ai.usage.output_tokens": 29 } } ``` -------------------------------- ### Add Microsoft Agents AI NuGet Packages (PowerShell) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-types/chat-client-agent Installs the necessary Microsoft.Agents.AI NuGet package for agent development. This is a prerequisite for building agents using the framework. ```powershell dotnet add package Microsoft.Agents.AI --prerelease ``` -------------------------------- ### Add OllamaSharp NuGet Package (PowerShell) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-types/chat-client-agent Installs the OllamaSharp NuGet package, which provides an `IChatClient` implementation for interacting with the Ollama service. This package is specific to using Ollama for agent backends. ```powershell dotnet add package OllamaSharp ``` -------------------------------- ### Custom Function Tools with Python Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-types/openai-responses-agent Illustrates how to equip an agent with custom Python functions as tools. This example defines a `get_weather` function and shows how the agent can utilize it to respond to user queries. ```Python from typing import Annotated from pydantic import Field def get_weather( location: Annotated[str, Field(description="The location to get weather for")] ) -> str: """Get the weather for a given location.""" # Your weather API implementation here return f"The weather in {location} is sunny with 25°C." async def tools_example(): agent = OpenAIResponsesClient().create_agent( instructions="You are a helpful weather assistant.", tools=get_weather, ) result = await agent.run("What's the weather like in Tokyo?") print(result.text) ``` -------------------------------- ### Set up MCP Client C# Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/model-context-protocol/using-mcp-tools Establishes a connection to an MCP server using the McpClientFactory. This involves specifying a name for the server, the command to run it (e.g., 'npx'), and any necessary arguments. ```csharp await using var mcpClient = await McpClientFactory.CreateAsync(new StdioClientTransport(new() { Name = "MCPServer", Command = "npx", Arguments = ["-y", "--verbose", "@modelcontextprotocol/server-github"], })); ``` -------------------------------- ### Get Azure Credentials (Python) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-types/azure-openai-responses-agent Obtains Azure credentials using `AzureCliCredential`. This method requires the Azure CLI to be installed and the user to be logged in via `az login`. ```python from azure.identity import AzureCliCredential credential = AzureCliCredential() ``` -------------------------------- ### Connect to HTTP/SSE MCP Servers using MCPStreamableHTTPTool Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/model-context-protocol/using-mcp-tools This example shows how to connect to MCP servers accessible via HTTP with Server-Sent Events using `MCPStreamableHTTPTool`. It demonstrates integrating with an agent that can query external documentation services. Ensure the provided URL and authentication headers are correct for your specific MCP server. ```Python import asyncio from agent_framework import ChatAgent, MCPStreamableHTTPTool from agent_framework.azure import AzureAIAgentClient from azure.identity.aio import AzureCliCredential async def http_mcp_example(): """Example using an HTTP-based MCP server.""" async with ( AzureCliCredential() as credential, MCPStreamableHTTPTool( name="Microsoft Learn MCP", url="https://learn.microsoft.com/api/mcp", headers={"Authorization": "Bearer your-token"}, ) as mcp_server, ChatAgent( chat_client=AzureAIAgentClient(async_credential=credential), name="DocsAgent", instructions="You help with Microsoft documentation questions.", ) as agent, ): result = await agent.run( "How to create an Azure storage account using az cli?", tools=mcp_server ) print(result) if __name__ == "__main__": asyncio.run(http_mcp_example()) ``` -------------------------------- ### Install Agent Framework Azure AI Package (Pip) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-types/azure-ai-foundry-agent Installs the agent-framework-azure-ai Python package using pip. This package is needed to utilize the Azure AI Foundry Agents service in Python applications. ```bash pip install agent-framework-azure-ai --pre ``` -------------------------------- ### Install Agent Framework Azure AI Packages (PowerShell) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-types/azure-ai-foundry-agent Installs the necessary NuGet packages for Azure.Identity and Microsoft.Agents.AI.Persistent for C# projects. These packages are required to interact with the Azure AI Foundry Agents service. ```powershell dotnet add package Azure.Identity dotnet add package Microsoft.Agents.AI.AI.Persistent --prerelease ``` -------------------------------- ### Agent Run with Specific Tools Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-tools This code snippet demonstrates how to execute an agent with specific tools available for a given run. It shows how to pass a list of tools to the agent.run() method. The example assumes 'agent', 'get_weather', and 'get_time' are pre-defined objects. ```python result = await agent.run( "What's the weather and time in New York?", tools=[get_weather] # Additional tool for this run ) ``` -------------------------------- ### Get Azure OpenAI Responses Client (C#) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-types/azure-openai-responses-agent Retrieves a specific Responses client from the AzureOpenAIClient, targeting a particular deployment name like 'gpt-4o-mini'. This client is used to create agents for generating responses. ```csharp #pragma warning disable OPENAI001 // Type is for evaluation purposes only and is subject to change or removal in future updates. var responseClient = client.GetOpenAIResponseClient("gpt-4o-mini"); #pragma warning restore OPENAI001 ``` -------------------------------- ### Create Agent with Multiple Search Tools Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-rag This Python example illustrates how to create an agent capable of utilizing multiple search tools, each designed for a different knowledge domain (e.g., products and policies). It involves creating separate search functions, converting them to tools, and then passing them as a list to the agent's constructor. ```python # Create search functions for different knowledge bases product_search = product_collection.create_search_function( function_name="search_products", description="Search for product information and specifications.", search_type="semantic_hybrid", string_mapper=lambda x: f"{x.record.name}: {x.record.description}", ).as_agent_framework_tool() policy_search = policy_collection.create_search_function( function_name="search_policies", description="Search for company policies and procedures.", search_type="keyword_hybrid", string_mapper=lambda x: f"Policy: {x.record.title}\n{x.record.content}", ).as_agent_framework_tool() # Create an agent with multiple search tools agent = chat_client.create_agent( instructions="You are a support agent. Use the appropriate search tool to find information before answering. Cite your sources.", tools=[product_search, policy_search] ) ``` -------------------------------- ### Image Generation with Responses API in Python Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-types/openai-responses-agent Demonstrates how to generate images using the Responses API. The example shows setting up an agent with image generation capabilities and processing the response to get the generated image URI. ```Python from agent_framework import DataContent, UriContent async def image_generation_example(): agent = OpenAIResponsesClient().create_agent( instructions="You are a helpful AI that can generate images.", tools=[{ "type": "image_generation", "size": "1024x1024", "quality": "low", }], ) result = await agent.run("Generate an image of a sunset over the ocean.") # Check for generated images in the response for content in result.contents: if isinstance(content, (DataContent, UriContent)): print(f"Image generated: {content.uri}") ``` -------------------------------- ### Configure Anthropic Agent with Hosted Tools (Python) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-types/anthropic-agent This example shows how to initialize an Anthropic agent with hosted tools, specifically Microsoft Learn MCP and a general web search tool. It demonstrates the agent's ability to process queries using these integrated tools. Dependencies include the 'agent_framework' library and 'AnthropicClient'. ```python from agent_framework import HostedMCPTool, HostedWebSearchTool async def hosted_tools_example(): agent = AnthropicClient().create_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(), ], max_tokens=20000, ) result = await agent.run("Can you compare Python decorators with C# attributes?") print(result.text) ``` -------------------------------- ### Add Function Tools to Azure AI Agent in Python Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-types/azure-ai-foundry-agent Illustrates how to add custom function tools to an Azure AI Foundry agent using Python. The example defines a `get_weather` function and passes it as a tool during agent creation. Requires Azure CLI authentication. ```python import asyncio from typing import Annotated from agent_framework.azure import AzureAIAgentClient from azure.identity.aio import AzureCliCredential from pydantic import Field def get_weather( location: Annotated[str, Field(description="The location to get the weather for.")], ) -> str: """Get the weather for a given location.""" return f"The weather in {location} is sunny with a high of 25°C." async def main(): async with ( AzureCliCredential() as credential, AzureAIAgentClient(async_credential=credential).create_agent( name="WeatherAgent", instructions="You are a helpful weather assistant.", tools=get_weather ) as agent, ): result = await agent.run("What's the weather like in Seattle?") print(result.text) asyncio.run(main()) ``` -------------------------------- ### Create Ollama Chat Client Agent (C#) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-types/chat-client-agent Demonstrates how to create an agent using an `OllamaApiClient` which implements the `IChatClient` interface. This involves initializing the client with the Ollama service endpoint and model, then creating a `ChatClientAgent` with specific instructions and a name. ```csharp using System; using Microsoft.Agents.AI; using OllamaSharp; OllamaApiClient chatClient = new(new Uri("http://localhost:11434"), "phi3"); AIAgent agent = new ChatClientAgent( chatClient, instructions: "You are good at telling jokes.", name: "Joker"); // Invoke the agent and output the text result. Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate.")); ``` -------------------------------- ### Create Agent using Chat Client Convenience Method Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-types/index This example shows an alternative way to create an agent using a convenience method directly on the chat client. It simplifies the agent creation process by chaining the client initialization with the agent creation. ```Python from agent_framework.azure import AzureAIAgentClient from azure.identity.aio import DefaultAzureCredential async with DefaultAzureCredential() as credential: agent = AzureAIAgentClient(async_credential=credential).create_agent( instructions="You are a helpful assistant" ) ``` -------------------------------- ### Python Function Middleware Logging Example Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-middleware Implements function middleware to log the start and end of function execution. It utilizes the FunctionInvocationContext to access function details and modifies the result or terminates processing if needed. The 'next' callable is essential for continuing the middleware chain or executing the actual function. ```python async def logging_function_middleware( context: FunctionInvocationContext, next: Callable[[FunctionInvocationContext], Awaitable[None]], ) -> None: """Function middleware that logs function execution.""" # Pre-processing: Log before function execution print(f"[Function] Calling {context.function.name}") # Continue to next middleware or function execution await next(context) # Post-processing: Log after function execution print(f"[Function] {context.function.name} completed") ``` -------------------------------- ### Python: Stream agent responses in real-time Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-types/azure-ai-foundry-agent This Python code snippet demonstrates how to use the Azure AI Agent Framework to get responses from an agent as they are generated. It utilizes `AzureAIAgentClient` and the `run_stream` method to process response chunks in real-time. Dependencies include `asyncio`, `agent_framework.azure`, and `azure.identity.aio`. ```python import asyncio from agent_framework.azure import AzureAIAgentClient from azure.identity.aio import AzureCliCredential async def main(): async with ( AzureCliCredential() as credential, AzureAIAgentClient(async_credential=credential).create_agent( name="StreamingAgent", instructions="You are a helpful assistant." ) as agent, ): print("Agent: ", end="", flush=True) async for chunk in agent.run_stream("Tell me a short story"): if chunk.text: print(chunk.text, end="", flush=True) print() asyncio.run(main()) ``` -------------------------------- ### Connect to Local MCP Servers using MCPStdioTool Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/model-context-protocol/using-mcp-tools This snippet demonstrates how to connect to a local MCP server running as a process using standard input/output. It utilizes `MCPStdioTool` to establish the connection and integrates it with a `ChatAgent` for performing calculations. Ensure the MCP server command (e.g., `uvx mcp-server-calculator`) is correctly specified. ```Python import asyncio from agent_framework import ChatAgent, MCPStdioTool from agent_framework.openai import OpenAIChatClient async def local_mcp_example(): """Example using a local MCP server via stdio.""" async with ( MCPStdioTool( name="calculator", command="uvx", args=["mcp-server-calculator"] ) as mcp_server, ChatAgent( chat_client=OpenAIChatClient(), name="MathAgent", instructions="You are a helpful math assistant that can solve calculations.", ) as agent, ): result = await agent.run( "What is 15 * 23 + 45?", tools=mcp_server ) print(result) if __name__ == "__main__": asyncio.run(local_mcp_example()) ``` -------------------------------- ### Multi-Tool MCP Configuration with Azure AI Foundry (Python) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/model-context-protocol/using-mcp-with-foundry-agents Demonstrates how to configure an Azure AI Foundry agent to use multiple hosted MCP tools. This example shows setting different approval modes for different tools, such as auto-approving documentation searches and requiring approval for GitHub operations. ```python async def multi_tool_mcp_example(): """Example using multiple hosted MCP tools.""" async with ( AzureCliCredential() as credential, AzureAIAgentClient(async_credential=credential) as chat_client, ): await chat_client.setup_azure_ai_observability() # Create agent with multiple MCP tools agent = chat_client.create_agent( name="MultiToolAgent", instructions="You can search documentation and access GitHub repositories.", tools=[ HostedMCPTool( name="Microsoft Learn MCP", url="https://learn.microsoft.com/api/mcp", approval_mode="never_require", # Auto-approve documentation searches ), HostedMCPTool( name="GitHub MCP", url="https://api.github.com/mcp", approval_mode="always_require", # Require approval for GitHub operations headers={"Authorization": "Bearer github-token"}, ), ], ) result = await agent.run( "Find Azure documentation and also check the latest commits in microsoft/semantic-kernel" ) print(result) if __name__ == "__main__": asyncio.run(multi_tool_mcp_example()) ``` -------------------------------- ### Install Agent Framework Anthropic Package Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-types/anthropic-agent Installs the necessary package for integrating Anthropic models with the Agent Framework. This is a prerequisite for using Anthropic agents. ```bash pip install agent-framework-anthropic --pre ``` -------------------------------- ### Create OpenAI Client and Response Client in C# Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-types/openai-responses-agent Demonstrates how to initialize an OpenAI client using your API key and then obtain a specific OpenAI Response client for a chosen model (e.g., 'gpt-4o-mini'). This is the initial step for creating an OpenAI Responses agent. ```csharp using System; using Microsoft.Agents.AI; using OpenAI; OpenAIClient client = new OpenAIClient(""); #pragma warning disable OPENAI001 // Type is for evaluation purposes only and is subject to change or removal in future updates. var responseClient = client.GetOpenAIResponseClient("gpt-4o-mini"); #pragma warning restore OPENAI001 ``` -------------------------------- ### Basic MCP Integration with Azure AI Foundry Agent (Python) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/model-context-protocol/using-mcp-with-foundry-agents Creates a basic Azure AI Foundry agent that utilizes hosted MCP tools. This example demonstrates initializing the client, setting up observability, creating an agent with a single MCP tool, and running a query. ```python import asyncio from agent_framework import HostedMCPTool from agent_framework.azure import AzureAIAgentClient from azure.identity.aio import AzureCliCredential async def basic_foundry_mcp_example(): """Basic example of Azure AI Foundry agent with hosted MCP tools.""" async with ( AzureCliCredential() as credential, AzureAIAgentClient(async_credential=credential) as chat_client, ): # Enable Azure AI observability (optional but recommended) await chat_client.setup_azure_ai_observability() # Create agent with hosted MCP tool agent = chat_client.create_agent( name="MicrosoftLearnAgent", instructions="You answer questions by searching Microsoft Learn content only.", tools=HostedMCPTool( name="Microsoft Learn MCP", url="https://learn.microsoft.com/api/mcp", ), ) # Simple query without approval workflow result = await agent.run( "Please summarize the Azure AI Agent documentation related to MCP tool calling?" ) print(result) if __name__ == "__main__": asyncio.run(basic_foundry_mcp_example()) ``` -------------------------------- ### Using Hosted File Search Tool (Python) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-tools Shows how to use the `HostedFileSearchTool` for searching within specified vector stores. It requires providing `vector_store_id` and can be configured with `max_results` to limit the number of returned documents. ```Python from agent_framework import HostedFileSearchTool, HostedVectorStoreContent agent = ChatAgent( chat_client=AzureAIAgentClient(async_credential=credential), instructions="You are a document search assistant", tools=[ HostedFileSearchTool( inputs=[ HostedVectorStoreContent(vector_store_id="vs_123") ], max_results=10 ) ] ) result = await agent.run("Find information about quarterly reports") ``` -------------------------------- ### Install A2A Agent Package (Python) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-types/a2a-agent Installs the A2A agent package for Python projects using pip. The --pre flag indicates that pre-release versions are allowed. ```bash pip install agent-framework-a2a --pre ``` -------------------------------- ### Install A2A Agent NuGet Package (C#) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-types/a2a-agent Installs the necessary A2A agent NuGet package for C# projects. This package provides the core components for interacting with A2A agents. ```powershell dotnet add package Microsoft.Agents.AI.A2A --prerelease ``` -------------------------------- ### Install OpenAI NuGet Package (C#) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-types/openai-chat-completion-agent Installs the necessary Microsoft.Agents.AI.OpenAI NuGet package for C# projects. This package enables the use of OpenAI services within the Microsoft Agent Framework. ```powershell dotnet add package Microsoft.Agents.AI.OpenAI --prerelease ``` -------------------------------- ### Using Hosted MCP Tool (Python) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-tools Demonstrates the integration of the `HostedMCPTool` for accessing Microsoft Learn content. This tool allows agents to query documentation via the Microsoft Learn API, requiring agent credentials and a valid API URL. ```Python from agent_framework import HostedMCPTool agent = ChatAgent( chat_client=AzureAIAgentClient(async_credential=credential), instructions="You are a documentation assistant", tools=[ HostedMCPTool( name="Microsoft Learn MCP", url="https://learn.microsoft.com/api/mcp" ) ] ) result = await agent.run("How do I create an Azure storage account?") ``` -------------------------------- ### Using Hosted Web Search Tool (Python) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-tools Shows how to integrate the `HostedWebSearchTool` into a ChatAgent. This tool enables the agent to perform web searches, optionally with user location context, to gather information for its responses. ```Python from agent_framework import HostedWebSearchTool agent = ChatAgent( chat_client=OpenAIChatClient(), instructions="You are a helpful assistant with web search capabilities", tools=[ HostedWebSearchTool( additional_properties={ "user_location": { "city": "Seattle", "country": "US" } } ) ] ) result = await agent.run("What are the latest news about AI?") ``` -------------------------------- ### Mermaid Diagram Example Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/workflows/visualization Example of a workflow represented in Mermaid diagram format. This format visually depicts the flow between different executors, including fan-out and fan-in patterns, with specific styling for different node types. ```mermaid flowchart TD dispatcher["dispatcher (Start)"]; researcher["researcher"]; marketer["marketer"]; legal["legal"]; aggregator["aggregator"]; fan_in__aggregator__e3a4ff58((fan-in)) legal --> fan_in__aggregator__e3a4ff58; marketer --> fan_in__aggregator__e3a4ff58; researcher --> fan_in__aggregator__e3a4ff58; fan_in__aggregator__e3a4ff58 --> aggregator; dispatcher --> researcher; dispatcher --> marketer; dispatcher --> legal; ``` -------------------------------- ### Agent Execution: Streaming and Non-Streaming Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/running-agents Demonstrates how to execute agents using both streaming and non-streaming methods in C# and Python. ```APIDOC ## Agent Execution: Streaming and Non-Streaming This section details how to run agents and receive their outputs. ### C# Examples **Non-streaming:** ```csharp Console.WriteLine(await agent.RunAsync("What is the weather like in Amsterdam?")); ``` **Streaming:** ```csharp await foreach (var update in agent.RunStreamingAsync("What is the weather like in Amsterdam?")) { Console.Write(update); } ``` ### Python Examples **Non-streaming:** ```python result = await agent.run("What is the weather like in Amsterdam?") print(result.text) ``` **Streaming:** ```python async for update in agent.run_stream("What is the weather like in Amsterdam?"): if update.text: print(update.text, end="", flush=True) ``` ``` -------------------------------- ### Custom Agent Run Middleware Example (C#) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-middleware Provides an example implementation of Agent Run middleware in C#. This middleware intercepts agent run requests, logs message counts before and after the agent processes them, and returns the modified response. ```csharp async Task CustomAgentRunMiddleware( IEnumerable messages, AgentThread? thread, AgentRunOptions? options, AIAgent innerAgent, CancellationToken cancellationToken) { Console.WriteLine(messages.Count()); var response = await innerAgent.RunAsync(messages, thread, options, cancellationToken).ConfigureAwait(false); Console.WriteLine(response.Messages.Count); return response; } ``` -------------------------------- ### Register IChatClient Middleware via Factory (C#) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-middleware Illustrates registering IChatClient middleware using a factory method when constructing an agent via SDK client helper methods. This provides a concise way to apply middleware during agent creation. ```csharp var agent = new AzureOpenAIClient(new Uri(endpoint), new AzureCliCredential()) .GetChatClient(deploymentName) .CreateAIAgent("You are a helpful assistant.", clientFactory: (chatClient) => chatClient .AsBuilder() .Use(getResponseFunc: CustomChatClientMiddleware, getStreamingResponseFunc: null) .Build()); ``` -------------------------------- ### Stream Responses from Assistant (Python) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-types/openai-assistants-agent This example illustrates how to receive responses from an assistant as they are generated, providing a better user experience. It uses the `run_stream` method of the agent, iterating over the chunks of text as they become available and printing them in real-time. ```python from agent_framework import OpenAIAssistantsClient async def streaming_example(): async with OpenAIAssistantsClient().create_agent( instructions="You are a helpful assistant.", ) as agent: print("Assistant: ", end="", flush=True) async for chunk in agent.run_stream("Tell me a story about AI."): if chunk.text: print(chunk.text, end="", flush=True) print() # New line after streaming is complete ``` -------------------------------- ### Get Chat Completion Client (C#) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-types/azure-openai-chat-completion-agent Retrieves a chat client from the AzureOpenAIClient for a specific deployment name. ```APIDOC ## Get Chat Completion Client ### Description Azure OpenAI supports multiple services that all provide model calling capabilities. We need to pick the ChatCompletion service to create a ChatCompletion based agent. ### Method C# ### Endpoint N/A ### Parameters None ### Request Example ```csharp var chatCompletionClient = client.GetChatClient("gpt-4o-mini"); ``` ### Response N/A ``` -------------------------------- ### TextSearchProviderOptions Configuration Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-rag This example demonstrates how to configure TextSearchProviderOptions in C# to run searches before each model invocation and maintain a limited conversation history. ```APIDOC ## TextSearchProvider Options The `TextSearchProvider` can be customized via the `TextSearchProviderOptions` class. This example shows setting options to run search before every model invocation and to keep a short rolling window of conversation context. ### Method Configuration ### Parameters #### Request Body - **SearchTime** (`TextSearchProviderOptions.TextSearchBehavior`) - Required - Indicates when the search should be executed. Options: `BeforeAIInvoke`, `OnDemand`. - **RecentMessageMemoryLimit** (`int`) - Optional - The number of recent conversation messages to keep in memory for search input. Default: `0` (disabled). - **FunctionToolName** (`string`) - Optional - The name of the search tool when in on-demand mode. Default: "Search". - **FunctionToolDescription** (`string`) - Optional - The description of the search tool when in on-demand mode. Default: "Allows searching for additional information to help answer the user question.". - **ContextPrompt** (`string`) - Optional - The prompt prefixed to results in `BeforeAIInvoke` mode. Default: "## Additional Context\nConsider the following information from source documents when responding to the user:". - **CitationsPrompt** (`string`) - Optional - The prompt appended after results to request citations in `BeforeAIInvoke` mode. Default: "Include citations to the source document with document name and link if document name and link is available.". - **ContextFormatter** (`Func, string>`) - Optional - A delegate to format search results in `BeforeAIInvoke` mode. Overrides `ContextPrompt` and `CitationsPrompt`. Default: `null`. - **RecentMessageRolesIncluded** (`List`) - Optional - The list of `ChatRole` types to filter recent messages by. Default: `ChatRole.User`. ### Request Example ```csharp TextSearchProviderOptions textSearchOptions = new() { SearchTime = TextSearchProviderOptions.TextSearchBehavior.BeforeAIInvoke, RecentMessageMemoryLimit = 6, }; ``` ### Response #### Success Response (200) Configuration object is set. #### Response Example (Configuration is applied, no direct response body for setting options) ``` -------------------------------- ### Connect to WebSocket MCP Servers using MCPWebsocketTool Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/model-context-protocol/using-mcp-tools This code snippet illustrates connecting to MCP servers over WebSocket connections using `MCPWebsocketTool`. It sets up an agent designed to provide real-time data insights by interacting with a WebSocket-based MCP server. Verify that the WebSocket URL is correct and accessible. ```Python import asyncio from agent_framework import ChatAgent, MCPWebsocketTool from agent_framework.openai import OpenAIChatClient async def websocket_mcp_example(): """Example using a WebSocket-based MCP server.""" async with ( MCPWebsocketTool( name="realtime-data", url="wss://api.example.com/mcp", ) as mcp_server, ChatAgent( chat_client=OpenAIChatClient(), name="DataAgent", instructions="You provide real-time data insights.", ) as agent, ): result = await agent.run( "What is the current market status?", tools=mcp_server ) print(result) if __name__ == "__main__": asyncio.run(websocket_mcp_example()) ``` -------------------------------- ### IChatClient Middleware in C# Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-middleware Example of chat client middleware to inspect and modify requests and responses for the inference service. It interacts with `IChatClient.GetResponseAsync`. Requires `Microsoft.Extensions.AI` and `System.Threading`. ```csharp async Task CustomChatClientMiddleware( IEnumerable messages, ChatOptions? options, IChatClient innerChatClient, CancellationToken cancellationToken) { Console.WriteLine(messages.Count()); var response = await innerChatClient.GetResponseAsync(messages, options, cancellationToken); Console.WriteLine(response.Messages.Count); return response; } ``` -------------------------------- ### Configuration: Environment Variables (Bash) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-types/azure-openai-chat-completion-agent Sets up essential environment variables for configuring Azure OpenAI ChatCompletion agents. ```APIDOC ## Configuration: Environment Variables ### Description Before using Azure OpenAI ChatCompletion agents, you need to set up these environment variables. ### Method Bash ### Endpoint N/A ### Parameters None ### Request Example ```bash export AZURE_OPENAI_ENDPOINT="https://.openai.azure.com" export AZURE_OPENAI_CHAT_DEPLOYMENT_NAME="gpt-4o-mini" # Optionally, you can also set: export AZURE_OPENAI_API_VERSION="2024-10-21" # Default API version export AZURE_OPENAI_API_KEY="" # If not using Azure CLI authentication ``` ### Response N/A ``` -------------------------------- ### Implement Basic Context Provider for Agent Memory in Python Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-memory Shows how to create a basic context provider by inheriting from `ContextProvider`. This example, `UserPreferencesMemory`, injects user preferences as instructions before each agent invocation and can extract preferences after an invocation. It allows for dynamic memory patterns. ```python from agent_framework import ContextProvider, Context, ChatMessage from collections.abc import MutableSequence from typing import Any class UserPreferencesMemory(ContextProvider): def __init__(self): self.preferences = {} async def invoking(self, messages: ChatMessage | MutableSequence[ChatMessage], **kwargs: Any) -> Context: """Provide user preferences before each invocation.""" if self.preferences: preferences_text = ", ".join([f"{k}: {v}" for k, v in self.preferences.items()]) instructions = f"User preferences: {preferences_text}" return Context(instructions=instructions) return Context() async def invoked( self, request_messages: ChatMessage | Sequence[ChatMessage], response_messages: ChatMessage | Sequence[ChatMessage] | None = None, invoke_exception: Exception | None = None, **kwargs: Any, ) -> None: """Extract and store user preferences from the conversation.""" # Implement preference extraction logic pass ``` -------------------------------- ### Create Azure AI Agent (Python) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-types/chat-client-agent Creates an agent using the Azure AI Agent Client. This example demonstrates asynchronous credential handling with `AzureCliCredential` for authentication. ```python from agent_framework import ChatAgent from agent_framework.azure import AzureAIAgentClient from azure.identity.aio import AzureCliCredential # Create agent using Azure AI async with AzureCliCredential() as credential: agent = ChatAgent( chat_client=AzureAIAgentClient(async_credential=credential), instructions="You are a helpful assistant.", name="Azure AI Assistant" ) ``` -------------------------------- ### Get OpenAI Assistants Client (C#) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-types/openai-assistants-agent Retrieves an Assistants client from the initialized OpenAI client. This specific client is used for operations related to OpenAI Assistants. ```csharp #pragma warning disable OPENAI001 // Type is for evaluation purposes only and is subject to change or removal in future updates. var assistantClient = client.GetAssistantClient(); #pragma warning restore OPENAI001 ``` -------------------------------- ### Streaming with Run-Level Tools (Python) Source: https://learn.microsoft.com/en-us/agent-framework/user-guide/agents/agent-tools Demonstrates how to use function tools with streaming agent responses. The `run_stream()` method allows for processing responses incrementally while utilizing specified tools for the query. ```Python async for update in agent.run_stream( "Tell me about the weather", tools=[get_weather] ): if update.text: print(update.text, end="", flush=True) ```