### Start Dojo Frontend Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/integrations/ag-ui/testing-with-dojo.md Install frontend dependencies and start the Dojo development server. The frontend will be available at http://localhost:3000. ```bash cd apps/dojo pnpm install pnpm dev ``` -------------------------------- ### Start Backend Server Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/integrations/ag-ui/testing-with-dojo.md Run the backend server with example agents using uv. The server typically starts on http://localhost:8888. ```bash cd integrations/microsoft-agent-framework/python/examples uv run dev ``` -------------------------------- ### Local MCP Server Example (Python) Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/agents/tools/local-mcp-tools.md Example demonstrating the use of a local MCP server via standard input/output with `MCPStdioTool`. This requires installing `mcp --pre` for MCP support. The agent is configured with a math assistant persona and uses the calculator tool. ```python import asyncio from agent_framework import Agent, 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, Agent( 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()) ``` -------------------------------- ### AG-UI Server Setup with Python Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/integrations/ag-ui/getting-started.md Installs necessary packages and sets up a FastAPI server for AG-UI. Ensure environment variables for Azure OpenAI are configured. ```bash pip install agent-framework-ag-ui --pre ``` ```bash uv pip install agent-framework-ag-ui --prerelease=allow ``` ```python import os from agent_framework import Agent from agent_framework.openai import OpenAIChatCompletionClient from agent_framework_ag_ui import add_agent_framework_fastapi_endpoint from azure.identity import AzureCliCredential from fastapi import FastAPI # Read required configuration endpoint = os.environ.get("AZURE_OPENAI_ENDPOINT") deployment_name = os.environ.get("AZURE_OPENAI_CHAT_COMPLETION_MODEL") if not endpoint: raise ValueError("AZURE_OPENAI_ENDPOINT environment variable is required") if not deployment_name: raise ValueError("AZURE_OPENAI_CHAT_COMPLETION_MODEL environment variable is required") chat_client = OpenAIChatCompletionClient( model=deployment_name, azure_endpoint=endpoint, api_version=os.getenv("AZURE_OPENAI_API_VERSION"), credential=AzureCliCredential(), ) # Create the AI agent agent = Agent( name="AGUIAssistant", instructions="You are a helpful assistant.", client=chat_client, ) # Create FastAPI app app = FastAPI(title="AG-UI Server") ``` -------------------------------- ### Setup Agent Framework Observability Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/migration-guide/from-autogen/index.md Demonstrates zero-code and manual setup for Agent Framework observability using OpenTelemetry. Environment variables can enable zero-code setup. ```python from agent_framework import Agent from agent_framework.observability import setup_observability from agent_framework.openai import OpenAIChatClient # Zero-code setup via environment variables # Set ENABLE_OTEL=true # Set OTLP_ENDPOINT=http://localhost:4317 # Or manual setup setup_observability( otlp_endpoint="http://localhost:4317" ) # Create client for the example client = OpenAIChatClient(model="gpt-5") async def observability_example(): # Observability is automatically applied to all agents and workflows agent = Agent(name="assistant", client=client) result = await agent.run("Hello") # Automatically traced ``` -------------------------------- ### Navigate to Python Examples Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/integrations/ag-ui/testing-with-dojo.md Change directory to the Python examples within the AG-UI repository. ```bash cd integrations/microsoft-agent-framework/python/examples ``` -------------------------------- ### Chat Middleware Example Setup Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/agents/middleware/chat-middleware.md This code sets up the necessary imports for demonstrating chat middleware functionality. It includes types for context, messages, responses, and middleware control, along with tools for AI interaction and authentication. ```python # Copyright (c) Microsoft. All rights reserved. import asyncio from collections.abc import Awaitable, Callable from random import randint from typing import Annotated from agent_framework import ( ChatContext, ChatMiddleware, ChatResponse, Message, MiddlewareTermination, chat_middleware, tool, ) from agent_framework import Agent from agent_framework.foundry import FoundryChatClient from azure.identity.aio import AzureCliCredential from pydantic import Field """ Chat MiddlewareTypes Example This sample demonstrates how to use chat middleware to observe and override inputs sent to AI models. Chat middleware intercepts chat requests before they reach the underlying AI service, allowing you to: 1. Observe and log input messages 2. Modify input messages before sending to AI 3. Override the entire response The example covers: - Class-based chat middleware inheriting from ChatMiddleware - Function-based chat middleware with @chat_middleware decorator - MiddlewareTypes registration at agent level (applies to all runs) - MiddlewareTypes registration at run level (applies to specific run only) """ ``` -------------------------------- ### Initialize Project with Durable Agents Quickstart Template (Bash) Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/integrations/azure-functions.md Use this Bash command to create a new project directory and navigate into it for the quickstart template. ```bash mkdir MyDurableAgent cd MyDurableAgent ``` -------------------------------- ### Initialize Project with Durable Agents Quickstart Template (.NET) Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/integrations/azure-functions.md Initialize your project using the durable agents quickstart template for .NET. ```console azd init --template durable-agents-quickstart-dotnet ``` -------------------------------- ### Initialize Project with Durable Agents Quickstart Template (PowerShell) Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/integrations/azure-functions.md Use this PowerShell command to create a new project directory and navigate into it for the quickstart template. ```powershell New-Item -ItemType Directory -Path MyDurableAgent Set-Location MyDurableAgent ``` -------------------------------- ### Initialize Project with Durable Agents Quickstart Template (Python) Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/integrations/azure-functions.md Initialize your project using the durable agents quickstart template for Python. ```console azd init --template durable-agents-quickstart-python ``` -------------------------------- ### Create a GitHub Copilot Agent with Tools and Instructions Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/agents/providers/github-copilot.md Configure an agent with custom instructions and function tools to guide its behavior and capabilities. The example shows how to define a weather tool. ```csharp using GitHub.Copilot.SDK; using Microsoft.Agents.AI; using Microsoft.Extensions.AI; AIFunction weatherTool = AIFunctionFactory.Create((string location) => { return $"The weather in {location} is sunny with a high of 25C."; }, "GetWeather", "Get the weather for a given location."); await using CopilotClient copilotClient = new(); await copilotClient.StartAsync(); AIAgent agent = copilotClient.AsAIAgent( tools: [weatherTool], instructions: "You are a helpful weather agent."); Console.WriteLine(await agent.RunAsync("What's the weather like in Seattle?")); ``` -------------------------------- ### Install DevUI Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/devui/index.md Install DevUI from PyPI using pip. Use the --pre flag for pre-release versions. ```bash pip install agent-framework-devui --pre ``` -------------------------------- ### Complete Human-in-the-Loop Example Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/support/upgrade/requests-and-responses-upgrade-guide-python.md Provides a full example of checkpoint resume with pending human approval, demonstrating the new request-response handling mechanism. ```python from agent_framework import ( Executor, FileCheckpointStorage, WorkflowBuilder, handler, response_handler, ) ``` -------------------------------- ### Example Agent Output with Frontend Tools Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/integrations/ag-ui/frontend-tools.md This example demonstrates the expected streaming output when an AI agent utilizes frontend tools, showing the tool call and its result. ```text User (:q or quit to exit): Where am I located? [Client Tool Call - Name: GetUserLocation] [Client Tool Result: Amsterdam, Netherlands (52.37°N, 4.90°E)] You are currently in Amsterdam, Netherlands, at coordinates 52.37°N, 4.90°E. ``` -------------------------------- ### Complete Example: Workflow Agent with Streaming Output Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/workflows/as-agents.md Demonstrates setting up a chat client, creating specialized agents, building a sequential workflow, and running it with streaming output. This example shows how to track and display output from different agents in the workflow. ```python import asyncio import os from agent_framework.foundry import FoundryChatClient from agent_framework.orchestrations import SequentialBuilder from azure.identity import AzureCliCredential async def main(): # Set up the chat client client = FoundryChatClient( project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"], model=os.environ["FOUNDRY_MODEL"], credential=AzureCliCredential(), ) # Create specialized agents researcher = client.as_agent( name="Researcher", instructions="Research the given topic and provide key facts.", ) writer = client.as_agent( name="Writer", instructions="Write engaging content based on the research provided.", ) reviewer = client.as_agent( name="Reviewer", instructions="Review the content and provide a final polished version.", ) # Build a sequential workflow workflow = SequentialBuilder(participants=[researcher, writer, reviewer]).build() # Convert to a workflow agent workflow_agent = workflow.as_agent(name="Content Creation Pipeline") # Run the workflow print("Starting workflow...") print("=" * 60) current_author = None async for update in workflow_agent.run( "Write about quantum computing", stream=True, ): # Show when different agents are responding if update.author_name and update.author_name != current_author: if current_author: print("\n" + "-" * 40) print(f"\n[{update.author_name}]:") current_author = update.author_name if update.text: print(update.text, end="", flush=True) print("\n" + "=" * 60) print("Workflow completed!") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Install .NET Agent Framework Packages Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/workflows/edges.md Install the necessary NuGet packages for building agent workflows in a .NET project. ```bash dotnet add package Azure.AI.Projects --prerelease dotnet add package Azure.Identity dotnet add package Microsoft.Agents.AI.Workflows --prerelease dotnet add package Microsoft.Agents.AI.Foundry --prerelease ``` -------------------------------- ### Install Foundry Local Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/agents/providers/foundry-local.md Install the agent-framework-foundry-local package using pip. Use the --pre flag for pre-release versions. ```bash pip install agent-framework-foundry-local --pre ``` -------------------------------- ### Install Copilot Studio Agent Framework Package (Python) Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/agents/providers/copilot-studio.md Install the agent-framework-copilotstudio package using pip for Python support. Use the --pre flag for prerelease versions. ```bash pip install agent-framework-copilotstudio --pre ``` -------------------------------- ### Install OpenAI Hosting Dependencies (.NET CLI) Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/integrations/openai-endpoints.md Install the necessary NuGet packages for hosting agents via OpenAI ChatCompletions/Responses protocols and connecting to Azure OpenAI services. ```bash # Hosting.A2A.AspNetCore for OpenAI ChatCompletions/Responses protocol(s) integration dotnet add package Microsoft.Agents.AI.Hosting.OpenAI --prerelease # Libraries to connect to Azure OpenAI dotnet add package Azure.AI.OpenAI --prerelease dotnet add package Azure.Identity dotnet add package Microsoft.Extensions.AI dotnet add package Microsoft.Extensions.AI.OpenAI --prerelease # Swagger to test app dotnet add package Microsoft.AspNetCore.OpenApi dotnet add package Swashbuckle.AspNetCore ``` -------------------------------- ### Create and Start a Basic GitHub Copilot Agent Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/agents/providers/github-copilot.md Instantiate a CopilotClient, start it, and then create an AI agent using the AsAIAgent extension method. This agent can then be used to run prompts. ```csharp using GitHub.Copilot.SDK; using Microsoft.Agents.AI; await using CopilotClient copilotClient = new(); await copilotClient.StartAsync(); AIAgent agent = copilotClient.AsAIAgent(); Console.WriteLine(await agent.RunAsync("What is Microsoft Agent Framework?")); ``` -------------------------------- ### Install AG-UI Server Packages (C#) Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/integrations/ag-ui/getting-started.md Installs the necessary NuGet packages for creating an AG-UI server using ASP.NET Core. Ensure you are using .NET 8.0 or later. ```bash dotnet add package Microsoft.Agents.AI.Hosting.AGUI.AspNetCore --prerelease dotnet add package Azure.AI.Projects --prerelease dotnet add package Azure.Identity dotnet add package Microsoft.Agents.AI.Foundry --prerelease ``` -------------------------------- ### Start Server and Client Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/integrations/ag-ui/getting-started.md Ensure the server is running in one terminal before starting the client in another. This is a common troubleshooting step for connection issues. ```bash # Terminal 1 python server.py # Terminal 2 (after server starts) python client.py ``` -------------------------------- ### Python Example: Basic Anthropic Agent Creation Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/agents/providers/anthropic.md Create a basic Anthropic agent with a name and instructions. This example shows the simplest way to instantiate an agent and run a query. ```python async def basic_example(): # Create an agent using Anthropic agent = AnthropicClient().as_agent( name="HelpfulAssistant", instructions="You are a helpful assistant.", ) result = await agent.run("Hello, how can you help me?") print(result.text) ``` -------------------------------- ### Install GitHub Copilot Agent Package (Python) Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/agents/providers/github-copilot.md Install the Microsoft Agent Framework GitHub Copilot package using pip. Use the `--pre` flag for pre-release versions. ```bash pip install agent-framework-github-copilot --pre ``` -------------------------------- ### GitHub MCP Example with PAT Authentication Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/agents/tools/hosted-mcp-tools.md This example demonstrates connecting to GitHub's MCP server using a Personal Access Token (PAT) for authentication. Ensure GITHUB_PAT and FOUNDRY_PROJECT_ENDPOINT environment variables are set. ```python import asyncio import os from agent_framework import Agent from agent_framework.foundry import FoundryChatClient from azure.identity import AzureCliCredential from dotenv import load_dotenv async def github_mcp_example() -> None: """Example of using GitHub MCP server with PAT authentication.""" # 1. Load environment variables from .env file if present load_dotenv() # 2. Get configuration from environment github_pat = os.getenv("GITHUB_PAT") if not github_pat: raise ValueError( "GITHUB_PAT environment variable must be set. Create a token at https://github.com/settings/tokens" ) # 3. Create authentication headers with GitHub PAT auth_headers = { "Authorization": f"Bearer {github_pat}", } # 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 client = FoundryChatClient(credential=AzureCliCredential()) github_mcp_tool = client.get_mcp_tool( name="GitHub", url="https://api.githubcopilot.com/mcp/", headers=auth_headers, approval_mode="never_require", ) # 5. Create agent with the GitHub MCP tool async with Agent( client=client, name="GitHubAgent", instructions=( "You are a helpful assistant that can help users interact with GitHub. " "You can search for repositories, read file contents, check issues, and more. " "Always be clear about what operations you're performing." ), tools=github_mcp_tool, ) as agent: # Example 1: Get authenticated user information query1 = "What is my GitHub username and tell me about my account?" print(f"\nUser: {query1}") result1 = await agent.run(query1) print(f"Agent: {result1.text}") # Example 2: List my repositories query2 = "List all the repositories I own on GitHub" print(f"\nUser: {query2}") result2 = await agent.run(query2) print(f"Agent: {result2.text}") if __name__ == "__main__": asyncio.run(github_mcp_example()) ``` -------------------------------- ### File Search Tool Example (Python) Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/agents/tools/file-search.md This Python example demonstrates using the file search tool with the OpenAI Responses Client for direct document-based question answering. It includes helper functions to create and delete vector stores. ```python # Copyright (c) Microsoft. All rights reserved. import asyncio from agent_framework import Agent, Content from agent_framework.openai import OpenAIChatClient """ OpenAI Responses Client with File Search Example This sample demonstrates using get_file_search_tool() with OpenAI Responses Client for direct document-based question answering and information retrieval. """ # Helper functions async def create_vector_store(client: OpenAIChatClient) -> tuple[str, Content]: """Create a vector store with sample documents.""" file = await client.client.files.create( file=("todays_weather.txt", b"The weather today is sunny with a high of 75F."), purpose="user_data" ) vector_store = await client.client.vector_stores.create( name="knowledge_base", expires_after={"anchor": "last_active_at", "days": 1}, ) result = await client.client.vector_stores.files.create_and_poll(vector_store_id=vector_store.id, file_id=file.id) if result.last_error is not None: raise Exception(f"Vector store file processing failed with status: {result.last_error.message}") return file.id, Content.from_hosted_vector_store(vector_store_id=vector_store.id) async def delete_vector_store(client: OpenAIChatClient, 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) async def main() -> None: client = OpenAIChatClient() message = "What is the weather today? Do a file search to find the answer." stream = False print(f"User: {message}") 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=[client.get_file_search_tool(vector_store_ids=[vector_store_id])], ) if stream: print("Assistant: ", end="") async for chunk in agent.run(message, stream=True): if chunk.text: print(chunk.text, end="") print("") else: response = await agent.run(message) print(f"Assistant: {response}") await delete_vector_store(client, file_id, vector_store_id) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Start Orchestration with Bash Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/integrations/azure-functions.md Initiate an orchestration using the built-in Durable Functions HTTP API. This example starts the 'agent_orchestration_workflow' with a specific input. ```bash curl -X POST http://localhost:7071/runtime/webhooks/durabletask/orchestrators/agent_orchestration_workflow \ -H "Content-Type: application/json" \ -d '"\"What are three popular programming languages?\""' ``` -------------------------------- ### Start Orchestration with PowerShell Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/integrations/azure-functions.md Initiate an orchestration using the built-in Durable Functions HTTP API with PowerShell. This example starts the 'agent_orchestration_workflow' with a specific input. ```powershell $body = '"What are three popular programming languages?"' Invoke-RestMethod -Method Post -Uri "http://localhost:7071/runtime/webhooks/durabletask/orchestrators/agent_orchestration_workflow" ` -ContentType "application/json" ` -Body $body ``` -------------------------------- ### Set Up Environment Variables for Samples Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/devui/samples.md Copy and edit the example environment file for a specific sample. This is necessary to configure credentials and other settings required by the samples. ```bash # Copy and edit the example file cp weather_agent_azure/.env.example weather_agent_azure/.env # Edit .env with your credentials ``` -------------------------------- ### Start a New Conversation with Durable Agent (PowerShell) Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/integrations/azure-functions.md Initiate a new conversation with your durable agent using PowerShell. This example demonstrates sending an HTTP POST request and retrieving the response content and headers, including the `x-ms-thread-id`. ```powershell $response = Invoke-WebRequest -Uri "http://localhost:7071/api/agents/MyDurableAgent/run" ` -Method POST ` -Headers @{"Content-Type"="text/plain"} ` -Body "What are three popular programming languages?" $response.Headers $response.Content ``` -------------------------------- ### Start a New Conversation with Durable Agent (Bash) Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/integrations/azure-functions.md Initiate a new conversation with your durable agent by sending an HTTP POST request. This example uses Bash and cURL. The response includes a `x-ms-thread-id` header, which is crucial for continuing the conversation. ```bash curl -i -X POST http://localhost:7071/api/agents/MyDurableAgent/run \ -H "Content-Type: text/plain" \ -d "What are three popular programming languages?" ``` -------------------------------- ### Initialize Hosted Tools with Responses Client Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/agents/providers/openai.md Demonstrates how to initialize hosted tools like code interpreter, web search, and file search using the Responses client. Use this when you need to provide agents with access to specific functionalities. ```python async def hosted_tools_example(): client = OpenAIChatClient() # Each tool is created via a client method code_interpreter = client.get_code_interpreter_tool() web_search = client.get_web_search_tool() file_search = client.get_file_search_tool(vector_store_ids=["vs_abc123"]) mcp_tool = client.get_mcp_tool( name="GitHub", url="https://api.githubcopilot.com/mcp/", approval_mode="never_require", ) agent = client.as_agent( name="PowerAgent", instructions="You have access to code execution, web search, files, and GitHub.", tools=[code_interpreter, web_search, file_search, mcp_tool], ) result = await agent.run("Search the web for Python best practices, then write a summary.") print(result) ``` -------------------------------- ### Before: Agent Initialization and Run with Keyword Arguments Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/support/upgrade/typed-options-guide-python.md Shows the previous approach to configuring an Agent and running it, where options were passed as keyword arguments to the constructor and run methods. ```python from agent_framework import Agent from agent_framework.openai import OpenAIChatClient client = OpenAIChatClient() # Default options as keyword arguments on constructor agent = Agent( client=client, name="assistant", model="gpt-4", temperature=0.7, ) # Run also took keyword arguments response = await agent.run( "Hello!", max_tokens=1000, ) ``` -------------------------------- ### Agent Framework Middleware Setup Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/migration-guide/from-autogen/index.md Define and apply middleware functions to an Agent Framework Agent for cross-cutting concerns like logging and security. The `logging_middleware` logs agent start and completion, while `security_middleware` blocks calls containing sensitive data. ```python from agent_framework import Agent, AgentContext, FunctionInvocationContext from typing import Callable, Awaitable # Assume we have client from previous examples async def logging_middleware( context: AgentContext, call_next: Callable[[AgentContext], Awaitable[None]] ) -> None: print(f"Agent {context.agent.name} starting") await call_next() print(f"Agent {context.agent.name} completed") async def security_middleware( context: FunctionInvocationContext, call_next: Callable[[FunctionInvocationContext], Awaitable[None]] ) -> None: if "password" in str(context.arguments): print("Blocking function call with sensitive data") return # Don't call call_next() await call_next() agent = Agent( name="secure_agent", client=client, middleware=[logging_middleware, security_middleware] ) ``` -------------------------------- ### Organizing Related Tools in a Python Class Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/integrations/ag-ui/backend-tool-rendering.md Group related tools within a class to improve organization and manage shared state, such as API keys. This example shows how to define a `WeatherTools` class with methods for getting current weather and forecasts. ```python from agent_framework import tool from typing import Annotated, Any, Dict from pydantic import Field class WeatherTools: """Collection of weather-related tools.""" def __init__(self, api_key: str): self.api_key = api_key @tool def get_current_weather( self, location: Annotated[str, Field(description="The city.")], ) -> str: """Get current weather for a location.""" # Use self.api_key to call API return f"Current weather in {location}: Sunny, 22°C" @tool def get_forecast( self, location: Annotated[str, Field(description="The city.")], days: Annotated[int, Field(description="Number of days")] = 3, ) -> dict[str, Any]: """Get weather forecast for a location.""" # Use self.api_key to call API return {"location": location, "forecast": [...]} # Create tools instance weather_tools = WeatherTools(api_key="your-api-key") # Create agent with class-based tools # agent = Agent( # name="WeatherAgent", # instructions="You are a weather assistant.", # client=OpenAIChatCompletionClient(...), # tools=[ # weather_tools.get_current_weather, # weather_tools.get_forecast, # ], # ) ``` -------------------------------- ### Install agent-framework-core with explicit providers Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/support/upgrade/python-2026-significant-changes.md After the changes, install agent-framework-core and then explicitly install the provider packages you need, such as agent-framework-openai or agent-framework-foundry. ```bash pip install agent-framework-core pip install agent-framework-openai ``` ```bash pip install agent-framework-core pip install agent-framework-foundry ``` -------------------------------- ### Install AG-UI Integration Package Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/integrations/ag-ui/index.md Install the AG-UI integration package using pip. This command installs both the core agent framework and the AG-UI integration components. ```bash pip install agent-framework-ag-ui --pre ``` -------------------------------- ### Initialize Agent with Context Providers (Python) Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/agents/agent-pipeline.md Shows how to initialize an Agent with a unified list of context providers, including history and AI context providers. This approach consolidates context management within a single list. ```python from agent_framework import Agent, InMemoryHistoryProvider agent = Agent( client=my_client, context_providers=[ InMemoryHistoryProvider(), MyMemoryProvider(), MyRagProvider(), ], ) ``` -------------------------------- ### Install Python Requirements Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/integrations/azure-functions.md Install the required Python packages from the requirements.txt file. ```console python -m pip install -r requirements.txt ``` -------------------------------- ### Complete Observability Example Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/agents/observability.md This sample demonstrates how to configure OpenTelemetry providers and observe an agent's execution, including tool calls and agent responses. It simulates a weather agent interacting with a user. ```python # Copyright (c) Microsoft. All rights reserved. import asyncio from random import randint from typing import Annotated from agent_framework import Agent, tool from agent_framework.observability import configure_otel_providers, get_tracer from agent_framework.openai import OpenAIChatClient from opentelemetry.trace import SpanKind from opentelemetry.trace.span import format_trace_id from pydantic import Field """ This sample shows how you can observe an agent in Agent Framework by using the same observability setup function. """ # NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. @tool(approval_mode="never_require") async def get_weather( location: Annotated[str, Field(description="The location to get the weather for.")], ) -> str: """Get the weather for a given location.""" await asyncio.sleep(randint(0, 10) / 10.0) # Simulate a network call conditions = ["sunny", "cloudy", "rainy", "stormy"] return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}°C." async def main(): # calling `configure_otel_providers` will *enable* tracing and create the necessary tracing, logging # and metrics providers based on environment variables. # See the .env.example file for the available configuration options. configure_otel_providers() questions = ["What's the weather in Amsterdam?", "and in Paris, and which is better?", "Why is the sky blue?"] with get_tracer().start_as_current_span("Scenario: Agent Chat", kind=SpanKind.CLIENT) as current_span: print(f"Trace ID: {format_trace_id(current_span.get_span_context().trace_id)}") agent = Agent( client=OpenAIChatClient(), tools=get_weather, name="WeatherAgent", instructions="You are a weather assistant.", id="weather-agent", ) thread = agent.create_session() for question in questions: print(f"\nUser: {question}") print(f"{agent.name}: ", end="") async for update in agent.run( question, session=thread, stream=True, ): if update.text: print(update.text, end="") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Install A2A and Foundry Dependencies (.NET CLI) Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/integrations/a2a.md Install the necessary NuGet packages for A2A protocol integration, Microsoft Foundry connection, and Swagger for testing. Use the .NET CLI for installation. ```bash # Hosting.A2A.AspNetCore for A2A protocol integration dotnet add package Microsoft.Agents.AI.Hosting.A2A.AspNetCore --prerelease # Libraries to connect to Microsoft Foundry dotnet add package Azure.AI.Projects --prerelease dotnet add package Azure.Identity dotnet add package Microsoft.Agents.AI.Foundry --prerelease # Swagger to test app dotnet add package Microsoft.AspNetCore.OpenApi dotnet add package Swashbuckle.AspNetCore ``` -------------------------------- ### Run Python Agent with Tools Source: https://context7.com/microsoftdocs/semantic-kernel-docs/llms.txt Instantiate an agent with tools and run a query. This example demonstrates how to integrate defined tools into an agent's capabilities. ```python import asyncio from semantic_kernel.connectors.ai.foundry import FoundryChatClient from azure.identity import AzureCliCredential async def main(): agent = FoundryChatClient(credential=AzureCliCredential()).as_agent( instructions="You are a helpful assistant.", tools=[get_weather, deploy_service], ) result = await agent.run("What is the weather like in Amsterdam?") print(result.text) asyncio.run(main()) ``` -------------------------------- ### Install Python Dependencies Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/integrations/ag-ui/testing-with-dojo.md Install the required Python dependencies using uv for dependency management. ```bash uv sync ``` -------------------------------- ### Set Up MCP Client in C# Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/agents/tools/local-mcp-tools.md Create an MCP client to connect to a specified MCP server. Configure the server name, executable command, and arguments for the server process. ```csharp await using var mcpClient = await McpClientFactory.CreateAsync(new StdioClientTransport(new() { Name = "MCPServer", Command = "npx", Arguments = ["-y", "--verbose", "@modelcontextprotocol/server-github"] })); ``` -------------------------------- ### Agent Creation and Run Options Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/support/upgrade/typed-options-guide-python.md Demonstrates the shift from keyword arguments for model and tools to using a default_options dictionary for agent creation and an options dictionary for agent runs. Note that 'tools' remains a keyword argument for both. ```python # Before agent = Agent( client=client, name="assistant", tools=[my_function], instructions="You are helpful.", model="gpt-4", ) # After - tools and instructions stay as keyword args on creation agent = Agent( client=client, name="assistant", tools=[my_function], # Still a keyword argument! instructions="You are helpful.", # Still a keyword argument! default_options={"model": "gpt-4"}, ) # For run(), only tools is available as keyword argument response = await agent.run( "Hello!", tools=[another_function], # Can override tools options={"max_tokens": 100}, ) ``` -------------------------------- ### Install Foundry Python Packages Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/agents/providers/microsoft-foundry.md Install the necessary packages for Foundry integration and Azure identity. ```bash pip install agent-framework-foundry pip install azure-identity ``` -------------------------------- ### Install Neo4j Integration Package Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/integrations/neo4j-graphrag.md Install the Neo4j integration package for the Agent Framework using pip. ```bash pip install agent-framework-neo4j ``` -------------------------------- ### Launch DevUI with Programmatic Registration Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/devui/index.md Launch DevUI with agents registered in-memory. This example shows how to create an agent with a tool and then serve it using DevUI. ```python from agent_framework import Agent from agent_framework.openai import OpenAIChatClient from agent_framework.devui import serve def get_weather(location: str) -> str: """Get weather for a location.""" return f"Weather in {location}: 72F and sunny" # Create your agent agent = Agent( name="WeatherAgent", client=OpenAIChatClient(), tools=[get_weather] ) # Launch DevUI serve(entities=[agent], auto_open=True) # Opens browser to http://localhost:8080 ``` -------------------------------- ### Install Azure Monitor OpenTelemetry Package Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/agents/observability.md Install the necessary package for integrating with Azure Monitor for OpenTelemetry. ```bash pip install azure-monitor-opentelemetry ``` -------------------------------- ### Create and Run Agent with KernelFunction Tool Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/migration-guide/from-semantic-kernel/index.md Demonstrates how to create a KernelFunction, convert it to an Agent Framework tool, and use it with an agent. Ensure the necessary client and function decorators are imported. ```python from semantic_kernel.functions import kernel_function from agent_framework.openai import OpenAIChatClient # Create a plugin class with kernel functions @kernel_function(name="get_weather", description="Get the weather for a location") def get_weather(self, location: str) -> str: return f"The weather in {location} is sunny." # Get the KernelFunction and convert it to an Agent Framework tool agent_tool = get_weather.as_agent_framework_tool() # Use the tool with an Agent Framework agent agent = OpenAIChatClient(model="gpt-4o").as_agent(tools=agent_tool) response = await agent.run("What's the weather in Seattle?") print(response.text) ``` -------------------------------- ### Create Agent with Web Search Tool (C#) Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/agents/tools/web-search.md Demonstrates creating an agent with the Web Search tool using C#. Ensure the necessary NuGet package is installed. For production, use specific credentials instead of `DefaultAzureCredential`. ```csharp using System; using Azure.AI.Projects; using Azure.Identity; using Microsoft.Agents.AI; using Microsoft.Extensions.AI; // Requires: dotnet add package Microsoft.Agents.AI.Foundry --prerelease var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set."); var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini"; // Create an agent with the web search (Bing grounding) tool AIAgent agent = new AIProjectClient(new Uri(endpoint), new DefaultAzureCredential()) .AsAIAgent( model: deploymentName, instructions: "You are a helpful assistant that can search the web for current information.", tools: [new WebSearchToolDefinition()]); Console.WriteLine(await agent.RunAsync("What is the current weather in Seattle?")); ``` -------------------------------- ### Install Neo4j GraphRAG Package Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/integrations/neo4j-graphrag.md Install the Neo4j GraphRAG provider package for Agent Framework using the .NET CLI. ```bash dotnet add package Neo4j.AgentFramework.GraphRAG ``` -------------------------------- ### Example: Class-based Middleware in Agent Initialization Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/agents/middleware/defining-middleware.md Demonstrates initializing an Agent with custom middleware. The `middleware` list accepts instances of `SecurityAgentMiddleware` and `LoggingFunctionMiddleware`. ```python async def main() -> None: """Example demonstrating class-based middleware.""" print("=== Class-based MiddlewareTypes Example ===") # For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred # authentication option. async with ( AzureCliCredential() as credential, Agent( client=FoundryChatClient(credential=credential), name="WeatherAgent", instructions="You are a helpful weather assistant.", tools=get_weather, middleware=[SecurityAgentMiddleware(), LoggingFunctionMiddleware()], ) as agent, ): # Test with normal query print("\n--- Normal Query ---") query = "What's the weather like in Seattle?" print(f"User: {query}") result = await agent.run(query) print(f"Agent: {result.text}\n") # Test with security-related query print("--- Security Test ---") query = "What's the password for the weather service?" print(f"User: {query}") result = await agent.run(query) print(f"Agent: {result.text}\n") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Create and Run a Basic Agent (C#) Source: https://context7.com/microsoftdocs/semantic-kernel-docs/llms.txt Instantiate an AI agent using a provider-specific client and run it for non-streaming or streaming responses. Ensure environment variables for endpoint and deployment name are set. ```csharp // C# – Microsoft Foundry (Azure OpenAI) using System; using Azure.AI.Projects; using Azure.Identity; using Microsoft.Agents.AI; var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? throw new InvalidOperationException("Set AZURE_OPENAI_ENDPOINT"); var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini"; AIAgent agent = new AIProjectClient(new Uri(endpoint), new DefaultAzureCredential()) .AsAIAgent( model: deploymentName, instructions: "You are a friendly assistant. Keep your answers brief.", name: "HelloAgent"); // Non-streaming Console.WriteLine(await agent.RunAsync("What is the largest city in France?")); // Output: Paris is the largest city in France. // Streaming await foreach (var update in agent.RunStreamingAsync("Tell me a one-sentence fun fact.")) { Console.Write(update); } ``` -------------------------------- ### Start Azure Functions Runtime Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/integrations/azure-functions.md Navigate to your project directory and start the Azure Functions runtime to host your durable agent. ```console func start ``` -------------------------------- ### Set Up Azure OpenAI Client (C#) Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/workflows/orchestrations/concurrent.md Initializes the Azure OpenAI client for chat completions. Ensure AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_DEPLOYMENT_NAME environment variables are set. Consider production-ready credentials over DefaultAzureCredential. ```csharp using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Azure.AI.Projects; using Azure.Identity; using Microsoft.Agents.AI.Workflows; using Microsoft.Extensions.AI; using Microsoft.Agents.AI; // 1) Set up the Azure OpenAI client var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set."); var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini"; var client = new AIProjectClient(new Uri(endpoint), new DefaultAzureCredential()) .GetProjectOpenAIClient() .GetProjectResponsesClient() .AsIChatClient(deploymentName); ``` -------------------------------- ### Demonstrate Pre-Termination Middleware Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/agents/middleware/termination.md This example shows how to integrate `PreTerminationMiddleware` into an agent. It tests both a normal query and a query containing a blocked word to demonstrate the termination behavior. ```python import asyncio from semantic_kernel.agents.agent import Agent from semantic_kernel.connectors.ai.foundry import FoundryChatClient from semantic_kernel.connectors.ai.foundry.foundry_chat_credential import AzureCliCredential # Assume get_weather, PreTerminationMiddleware are defined elsewhere async def pre_termination_middleware() -> None: """Demonstrate pre-termination middleware that blocks requests with certain words.""" print("\n--- Example 1: Pre-termination MiddlewareTypes ---") async with ( AzureCliCredential() as credential, Agent( client=FoundryChatClient(credential=credential), name="WeatherAgent", instructions="You are a helpful weather assistant.", tools=get_weather, middleware=[PreTerminationMiddleware(blocked_words=["bad", "inappropriate"])], ) as agent, ): # Test with normal query print("\n1. Normal query:") query = "What's the weather like in Seattle?" print(f"User: {query}") result = await agent.run(query) print(f"Agent: {result.text}") # Test with blocked word print("\n2. Query with blocked word:") query = "What's the bad weather in New York?" print(f"User: {query}") result = await agent.run(query) print(f"Agent: {result.text}") # To run this example: # asyncio.run(pre_termination_middleware()) ``` -------------------------------- ### Install Python OpenAI Provider Package Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/agents/providers/openai.md Install the agent-framework-openai package for Python to enable direct OpenAI and Azure OpenAI usage. ```bash pip install agent-framework-openai ``` -------------------------------- ### Debug Logging Example in Workflows Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/workflows/declarative.md An example of using SendActivity for debug logging within a workflow to track variable states during execution. ```yaml # Debug logging example - kind: SendActivity id: debug_log activity: text: =Concat("[DEBUG] Current state: counter=", Local.counter, ", status=", Local.status) ``` -------------------------------- ### Create Agent with Web Search Tool (Python) Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/agents/tools/web-search.md Shows how to create an agent with the Web Search tool using Python. This example configures the tool with location context for more relevant search results. ```python # Copyright (c) Microsoft. All rights reserved. import asyncio from agent_framework import Agent from agent_framework.openai import OpenAIChatClient """ OpenAI Responses Client with Web Search Example 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: client = OpenAIChatClient() # Create web search tool with location context web_search_tool = client.get_web_search_tool( user_location={"city": "Seattle", "region": "US"}, ) agent = Agent( client=client, instructions="You are a helpful assistant that can search the web for current information.", tools=[web_search_tool], ) message = "What is the current weather? Do not ask for my current location." stream = False print(f"User: {message}") if stream: print("Assistant: ", end="") async for chunk in agent.run(message, stream=True): if chunk.text: print(chunk.text, end="") print("") else: response = await agent.run(message) print(f"Assistant: {response}") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Demonstrate Pre-Termination Middleware Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/agents/middleware/termination.md This example shows how to use `PreTerminationMiddleware` with an agent. It tests both a normal query and a query containing a blocked word to demonstrate the termination behavior. ```python import asyncio from semantic_kernel.agents import Agent from semantic_kernel.connectors.ai.foundry import FoundryChatClient from azure.identity import AzureCliCredential async def pre_termination_middleware() -> None: """Demonstrate pre-termination middleware that blocks requests with certain words.""" print("\n--- Example 1: Pre-termination MiddlewareTypes ---") async with ( AzureCliCredential() as credential, Agent( client=FoundryChatClient(credential=credential), name="WeatherAgent", instructions="You are a helpful weather assistant.", tools=get_weather, middleware=[PreTerminationMiddleware(blocked_words=["bad", "inappropriate"])], ) as agent, ): # Test with normal query print("\n1. Normal query:") query = "What's the weather like in Seattle?" print(f"User: {query}") result = await agent.run(query) print(f"Agent: {result.text}") # Test with blocked word print("\n2. Query with blocked word:") query = "What's the bad weather in New York?" print(f"User: {query}") result = await agent.run(query) print(f"Agent: {result.text}") # To run this example: # asyncio.run(pre_termination_middleware()) ``` -------------------------------- ### Install Agent Framework Core Package (Python) Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/agents/providers/custom.md Install the necessary Python package for the Agent Framework core functionality using pip. ```bash pip install agent-framework-core ``` -------------------------------- ### Example Output with Tool Calls Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/integrations/ag-ui/backend-tool-rendering.md Illustrates the expected console output when an agent successfully calls backend tools, including function calls, their parameters, results, and the final agent response. ```text User (:q or quit to exit): What's the weather like in Amsterdam? [Run Started - Thread: thread_abc123, Run: run_xyz789] [Function Call - Name: SearchRestaurants] Parameter: Location = Amsterdam Parameter: Cuisine = any [Function Result - CallId: call_def456] Result: {"Location":"Amsterdam","Cuisine":"any","Results":[...]} The weather in Amsterdam is sunny with a temperature of 22°C. Here are some great restaurants in the area: The Golden Fork (Italian, 4.5 stars)... [Run Finished - Thread: thread_abc123] ``` -------------------------------- ### Install Agent Framework (OpenAI Compatible) Source: https://github.com/microsoftdocs/semantic-kernel-docs/blob/main/agent-framework/agents/providers/ollama.md Installs the base Agent Framework package. Use this when connecting to Ollama via its OpenAI-compatible endpoint. ```bash pip install agent-framework ```