Calling a Microsoft AI agent from code takes about ten lines in either Python or .NET once your Microsoft Foundry project is ready. This guide shows two ways to do it with complete, runnable code, and explains each line so you can adapt it to your own projects.
What does "calling a Microsoft AI agent" mean?
An AI agent is an LLM with instructions that can also call tools (your functions, web search, MCP servers) and keep conversation history. Microsoft gives you two parts that work together:
- Microsoft Foundry (formerly Azure AI Foundry) hosts your models and, optionally, saved agents.
- Microsoft Agent Framework is the open-source SDK for Python and .NET that builds and runs agents. It reached version 1.0 for both languages in April 2026, per the Agent Framework announcement.
This post covers both common ways to call an agent:
| Approach 1: Agent Framework | Approach 2: Saved Foundry agent | |
|---|---|---|
| Where the agent is defined | In your code, per run (an "ephemeral" agent) | Saved and versioned in your Foundry project |
| How you call it | agent.run(...) / agent.RunAsync(...) | Responses API with a conversation |
| Python package | agent-framework-foundry | azure-ai-projects 2.x |
| .NET package | Microsoft.Agents.AI.Foundry | Azure.AI.Projects + Azure.AI.Projects.Agents |
| Best for | Custom tools, workflows, full control in code | Agents managed in the portal and shared by many apps |
A note on older SDKs. The previous Azure AI Agent Service ("classic") agents are deprecated and scheduled to retire on March 31, 2027 (see the classic quickstart notice). Use the packages in this guide, not Azure.AI.Agents.Persistent or azure-ai-projects 1.x, for new work.
Prerequisites and setup
You need these before running any code below (from the Foundry Responses API quickstart):
- An Azure subscription and a Microsoft Foundry project with a deployed model.
- The Azure CLI, signed in with
az login. - Python 3.10 or later, or the .NET 8 SDK or later.
- Permission to create and use agents in the project. Older classic documentation names the Azure AI User role at project scope; confirm the current role for your tenant in the Foundry portal's access settings.
Find your project endpoint in the Foundry portal; it looks like this:
https://<resource-name>.services.ai.azure.com/api/projects/<project-name>Set the environment variables. The samples below read them, so no endpoint or secret is ever hard-coded:
# Linux / macOS
export FOUNDRY_PROJECT_ENDPOINT="https://<resource-name>.services.ai.azure.com/api/projects/<project-name>"
export FOUNDRY_MODEL="<your deployed model name>"# Windows PowerShell
$env:FOUNDRY_PROJECT_ENDPOINT = "https://<resource-name>.services.ai.azure.com/api/projects/<project-name>"
$env:FOUNDRY_MODEL = "<your deployed model name>"FOUNDRY_MODEL is the deployment name you chose in Foundry, not necessarily the base model name.
Install packages.
# Python (Approach 1)
pip install agent-framework-foundry aiohttp azure-identity
# Python (Approach 2)
pip install "azure-ai-projects>=2.3.0" azure-identity# .NET (Approach 1)
dotnet new console -n AgentDemo
cd AgentDemo
dotnet add package Microsoft.Agents.AI.Foundry --prerelease
dotnet add package Azure.AI.Projects --prerelease
dotnet add package Azure.Identity
# .NET (Approach 2)
dotnet add package Azure.AI.Projects
dotnet add package Azure.AI.Projects.Agents
dotnet add package Azure.AI.Extensions.OpenAI
dotnet add package Azure.IdentityTwo things that trip people up: the Agent Framework Foundry package for .NET is still prerelease (hence --prerelease), and azure-ai-projects 2.x is not compatible with 1.x, so do not mix examples from older tutorials.
Approach 1 in Python: Microsoft Agent Framework
Here the agent is defined in your code and runs in your process. Each call goes to your Foundry project for model inference and tool orchestration. Create a file named hello_agent.py:
import asyncio
import os
from agent_framework import Agent
from agent_framework.foundry import FoundryChatClient
from azure.identity import AzureCliCredential
async def main() -> None:
agent = Agent(
client=FoundryChatClient(
project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
model=os.environ["FOUNDRY_MODEL"],
credential=AzureCliCredential(),
),
instructions="You are a helpful assistant.",
)
result = await agent.run("What is the capital of France?")
print(f"Agent: {result}")
if __name__ == "__main__":
asyncio.run(main())Run it after az login:
python hello_agent.pyHow it works, line by line
FoundryChatClientconnects to your Foundry project using the endpoint and the model deployment name from the environment.AzureCliCredentialuses youraz loginsession, so there is no API key in the code.Agent(...)combines that client withinstructions, the system prompt that shapes every answer.agent.run(...)is asynchronous, so it is awaited insideasyncio.run. The result prints as the agent's text answer.
Agent Framework does not read .env files by itself. If you keep settings in a .env file, install python-dotenv and call load_dotenv() at the top of your script, as the Agent Framework quickstart notes.
Approach 1 in .NET: Microsoft Agent Framework
Create the console project and packages from the setup section, then replace Program.cs with this code:
using Azure.AI.Projects;
using Azure.Identity;
using Microsoft.Agents.AI;
string endpoint = Environment.GetEnvironmentVariable("FOUNDRY_PROJECT_ENDPOINT")
?? throw new InvalidOperationException("FOUNDRY_PROJECT_ENDPOINT is not set.");
string deploymentName = Environment.GetEnvironmentVariable("FOUNDRY_MODEL")
?? throw new InvalidOperationException("FOUNDRY_MODEL is not set.");
AIAgent agent =
new AIProjectClient(new Uri(endpoint), new DefaultAzureCredential())
.AsAIAgent(
model: deploymentName,
instructions: "You are a helpful assistant.",
name: "Assistant");
Console.WriteLine($"Agent: {await agent.RunAsync("What is the capital of France?")}");Run it after az login:
dotnet runHow it works, line by line
- The two environment variables are read once, and the app fails fast with a clear message if either is missing.
AIProjectClientconnects to your Foundry project.DefaultAzureCredentialfinds your Azure CLI login on a developer machine, or a managed identity when deployed.AsAIAgent(...)is an extension method fromMicrosoft.Agents.AI.Foundry. It turns the project client into anAIAgentwith your model, instructions and name.RunAsync(...)sends the question and returns the agent's answer; string interpolation prints its text.
The same code works in a worker service, a console tool or an ASP.NET Core app, because AIAgent is a normal object you can register in dependency injection.
Approach 2 in Python: call a saved Foundry agent
With this approach the agent lives in your Foundry project with a name and versions, and your app only calls it. You can create it in the Foundry portal, or from code as below. The calls follow the Foundry get-started quickstart, with the endpoint, agent name and model moved into environment variables.
Step 1: create the agent once (create_agent.py). Running it again creates a new version of the same agent.
import os
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import PromptAgentDefinition
from azure.identity import DefaultAzureCredential
project = AIProjectClient(
endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
credential=DefaultAzureCredential(),
)
agent = project.agents.create_version(
agent_name=os.environ["FOUNDRY_AGENT_NAME"],
definition=PromptAgentDefinition(
model=os.environ["FOUNDRY_MODEL"],
instructions="You are a helpful assistant that answers general questions",
),
)
print(f"Agent created (id: {agent.id}, name: {agent.name}, version: {agent.version})")Step 2: chat with it (chat_with_agent.py). The Foundry quickstart creates the agent and chats in one file; this version assumes the agent already exists (created above or in the portal), so it skips creation.
import os
from azure.ai.projects import AIProjectClient
from azure.identity import DefaultAzureCredential
project = AIProjectClient(
endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
credential=DefaultAzureCredential(),
)
# An OpenAI client already bound to your agent
openai = project.get_openai_client(agent_name=os.environ["FOUNDRY_AGENT_NAME"])
# A conversation stores the history for multi-turn chat
conversation = openai.conversations.create()
response = openai.responses.create(
conversation=conversation.id,
input="What is the size of France in square miles?",
)
print(response.output_text)
# Follow-up: the agent remembers the previous turn
response = openai.responses.create(
conversation=conversation.id,
input="And what is the capital city?",
)
print(response.output_text)Add the new variable to your environment first: FOUNDRY_AGENT_NAME=MyAgent. Then run python create_agent.py once and python chat_with_agent.py whenever you want to talk to it.
What to notice
get_openai_client(agent_name=...)returns a client that is already bound to your agent, soresponses.createneeds no agent argument.conversations.create()gives you a conversation ID. Reusing it is what makes the follow-up question work. Store this ID in your database per user to continue chats later.DefaultAzureCredentialworks on your laptop throughaz login, and in Azure through a managed identity.
Approach 2 in .NET: call a saved Foundry agent
These examples follow the C# tab of the Foundry get-started quickstart (packages Azure.AI.Projects, Azure.AI.Projects.Agents, Azure.AI.Extensions.OpenAI), with values moved into environment variables. Set FOUNDRY_AGENT_NAME (for example MyAgent) next to the earlier two variables.
Step 1: create the agent once. Run this as its own small console project, or keep it in a setup tool.
using Azure.AI.Extensions.OpenAI;
using Azure.AI.Projects;
using Azure.AI.Projects.Agents;
using Azure.Identity;
string endpoint = Environment.GetEnvironmentVariable("FOUNDRY_PROJECT_ENDPOINT")
?? throw new InvalidOperationException("FOUNDRY_PROJECT_ENDPOINT is not set.");
string agentName = Environment.GetEnvironmentVariable("FOUNDRY_AGENT_NAME")
?? throw new InvalidOperationException("FOUNDRY_AGENT_NAME is not set.");
string model = Environment.GetEnvironmentVariable("FOUNDRY_MODEL")
?? throw new InvalidOperationException("FOUNDRY_MODEL is not set.");
AIProjectClient projectClient = new(
endpoint: new Uri(endpoint),
tokenProvider: new DefaultAzureCredential());
ProjectsAgentDefinition agentDefinition = new DeclarativeAgentDefinition(model)
{
Instructions = "You are a helpful assistant that answers general questions",
};
ProjectsAgentVersion agent = projectClient.AgentAdministrationClient.CreateAgentVersion(
agentName,
options: new(agentDefinition));
Console.WriteLine($"Agent created (id: {agent.Id}, name: {agent.Name}, version: {agent.Version})");Step 2: chat with it. As in Python, the quickstart creates and chats in one file. This version assumes the agent already exists and skips creation.
using Azure.AI.Extensions.OpenAI;
using Azure.AI.Projects;
using Azure.Identity;
using OpenAI.Responses;
#pragma warning disable OPENAI001
string endpoint = Environment.GetEnvironmentVariable("FOUNDRY_PROJECT_ENDPOINT")
?? throw new InvalidOperationException("FOUNDRY_PROJECT_ENDPOINT is not set.");
string agentName = Environment.GetEnvironmentVariable("FOUNDRY_AGENT_NAME")
?? throw new InvalidOperationException("FOUNDRY_AGENT_NAME is not set.");
AIProjectClient projectClient = new(
endpoint: new Uri(endpoint),
tokenProvider: new DefaultAzureCredential());
// A conversation stores the history for multi-turn chat
ProjectConversation conversation = projectClient.ProjectOpenAIClient
.GetProjectConversationsClient()
.CreateProjectConversation();
ProjectResponsesClient responsesClient = projectClient.ProjectOpenAIClient
.GetProjectResponsesClientForAgent(
defaultAgent: agentName,
defaultConversationId: conversation.Id);
ResponseResult response = responsesClient.CreateResponse("What is the size of France in square miles?");
Console.WriteLine(response.GetOutputText());
// Follow-up: the agent remembers the previous turn
response = responsesClient.CreateResponse("And what is the capital city?");
Console.WriteLine(response.GetOutputText());What to notice
GetProjectResponsesClientForAgent(defaultAgent, defaultConversationId)binds the client to your saved agent and your conversation, so everyCreateResponsecall continues the same chat.#pragma warning disable OPENAI001silences the experimental-API warning the quickstart also uses.- Keep
conversation.Idper user if you want to resume the conversation in a later request.
Level up: streaming, memory and tools
The examples below extend Approach 1. Each snippet reuses the agent object created in the earlier sections.
Stream the answer as it is generated
Streaming shows text token by token, which feels much faster in chat UIs.
# Python
print("Agent: ", end="", flush=True)
async for chunk in agent.run("Tell me a fun fact.", stream=True):
if chunk.text:
print(chunk.text, end="", flush=True)
print()// .NET
Console.Write("Agent: ");
await foreach (AgentResponseUpdate update in agent.RunStreamingAsync("Tell me a fun fact."))
{
Console.Write(update);
}
Console.WriteLine();Remember the conversation with a session
By default each call is independent. Create a session and pass it to every call to keep history (see the session guide).
# Python
session = agent.create_session()
first = await agent.run("My name is Alice and I love hiking.", session=session)
second = await agent.run("What do you remember about me?", session=session)
print(second)// .NET
AgentSession session = await agent.CreateSessionAsync();
Console.WriteLine(await agent.RunAsync("My name is Alice and I love hiking.", session));
Console.WriteLine(await agent.RunAsync("What do you remember about me?", session));Sessions can be serialized and restored later (session.to_dict() and AgentSession.from_dict(...) in Python, SerializeSession and DeserializeSessionAsync in .NET), which lets you store a user's chat in your database.
Give the agent your own function as a tool
Tools are how an agent does real work: query a database, call your API, send an email. The agent decides when to call the function and writes the answer from its result. This sample uses a fake weather function, taken from the Foundry quickstart.
# Python: weather_agent.py
import asyncio
import os
from random import randint
from typing import Annotated
from agent_framework import Agent, tool
from agent_framework.foundry import FoundryChatClient
from azure.identity import AzureCliCredential
from pydantic import Field
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
) -> str:
"""Get the weather for a given location."""
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() -> None:
agent = Agent(
client=FoundryChatClient(
project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
model=os.environ["FOUNDRY_MODEL"],
credential=AzureCliCredential(),
),
instructions="You are a helpful weather agent.",
tools=get_weather,
)
result = await agent.run("What's the weather like in Seattle?")
print(f"Agent: {result}")
if __name__ == "__main__":
asyncio.run(main())// .NET: Program.cs
using System.ComponentModel;
using Azure.AI.Projects;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
[Description("Get the weather for a given location.")]
static string GetWeather(
[Description("The location to get the weather for.")] string location)
{
string[] conditions = ["sunny", "cloudy", "rainy", "stormy"];
Random rng = Random.Shared;
return $"The weather in {location} is {conditions[rng.Next(conditions.Length)]} with a high of {rng.Next(10, 31)}°C.";
}
AITool weatherTool = AIFunctionFactory.Create(GetWeather);
string endpoint = Environment.GetEnvironmentVariable("FOUNDRY_PROJECT_ENDPOINT")
?? throw new InvalidOperationException("FOUNDRY_PROJECT_ENDPOINT is not set.");
string deploymentName = Environment.GetEnvironmentVariable("FOUNDRY_MODEL")
?? throw new InvalidOperationException("FOUNDRY_MODEL is not set.");
AIAgent agent =
new AIProjectClient(new Uri(endpoint), new DefaultAzureCredential())
.AsAIAgent(
model: deploymentName,
instructions: "You are a helpful weather agent.",
name: "WeatherAssistant",
tools: [weatherTool]);
Console.WriteLine($"Agent: {await agent.RunAsync("What's the weather like in Seattle?")}");The description text on the function and its parameters is what the model reads to decide when and how to call it, so write it clearly. The Python approval_mode="never_require" setting means the tool runs without asking a human first; for tools that change data, keep human approval on.
Agent Framework also supports built-in tools such as web search (FoundryChatClient.get_web_search_tool() in Python, new HostedWebSearchTool() in .NET), which you can combine with your own functions in the same tools list.
Production tips: security and a web API wrapper
Security and reliability checklist
- No secrets in code. The samples use token credentials, so there is no API key. Keep endpoints in environment variables, app settings or Key Vault.
- Use a specific credential in production. Microsoft warns that
DefaultAzureCredentialis convenient for development but can add latency and probe unintended credential sources in production. PreferManagedIdentityCredential, and give that managed identity access to your Foundry project. - Create the agent once. Build the
AgentorAIAgentat startup and reuse it, not on every request. - Validate input. Limit message length, reject empty messages and never let user text decide which tools run without checks.
- Keep human approval on risky tools that change data or spend money.
- Handle failures. Catch exceptions around the agent call, log the details on the server, and return a generic message to the client.
- Add tracing. Connecting Application Insights to your project does not trace your app automatically; configure Agent Framework observability in the app.
Expose the agent as a web API in Python (FastAPI):
import logging
import os
from agent_framework import Agent
from agent_framework.foundry import FoundryChatClient
from azure.identity import AzureCliCredential, ManagedIdentityCredential
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
logger = logging.getLogger("agent-api")
def build_credential():
# Managed identity in Azure, Azure CLI login on a developer machine
if os.environ.get("APP_ENV") == "production":
return ManagedIdentityCredential()
return AzureCliCredential()
agent = Agent(
client=FoundryChatClient(
project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
model=os.environ["FOUNDRY_MODEL"],
credential=build_credential(),
),
instructions="You are a helpful assistant.",
)
app = FastAPI()
class ChatRequest(BaseModel):
message: str = Field(min_length=1, max_length=2000)
class ChatResponse(BaseModel):
answer: str
@app.post("/chat", response_model=ChatResponse)
async def chat(request: ChatRequest) -> ChatResponse:
try:
result = await agent.run(request.message)
except Exception as exc:
logger.exception("Agent call failed")
raise HTTPException(status_code=502, detail="The AI agent is unavailable.") from exc
return ChatResponse(answer=str(result))Install fastapi and uvicorn, then run uvicorn main:app --reload.
Expose the agent as a web API in .NET (ASP.NET Core Minimal API). Create the project with dotnet new web and add the same three packages as Approach 1:
using Azure.AI.Projects;
using Azure.Core;
using Azure.Identity;
using Microsoft.Agents.AI;
var builder = WebApplication.CreateBuilder(args);
string endpoint = builder.Configuration["FOUNDRY_PROJECT_ENDPOINT"]
?? throw new InvalidOperationException("FOUNDRY_PROJECT_ENDPOINT is not set.");
string model = builder.Configuration["FOUNDRY_MODEL"]
?? throw new InvalidOperationException("FOUNDRY_MODEL is not set.");
// Managed identity in Azure, Azure CLI login on a developer machine
TokenCredential credential = builder.Environment.IsProduction()
? new ManagedIdentityCredential()
: new AzureCliCredential();
builder.Services.AddSingleton<AIAgent>(_ =>
new AIProjectClient(new Uri(endpoint), credential)
.AsAIAgent(
model: model,
instructions: "You are a helpful assistant.",
name: "Assistant"));
var app = builder.Build();
app.MapPost("/chat", async (ChatRequest request, AIAgent agent, ILogger<Program> logger) =>
{
if (string.IsNullOrWhiteSpace(request.Message) || request.Message.Length > 2000)
{
return Results.BadRequest(new { error = "Message is required and must be at most 2000 characters." });
}
try
{
var result = await agent.RunAsync(request.Message);
return Results.Ok(new ChatResponse(result.ToString()));
}
catch (Exception ex)
{
logger.LogError(ex, "Agent call failed");
return Results.Problem("The AI agent is unavailable.", statusCode: StatusCodes.Status502BadGateway);
}
});
app.Run();
public record ChatRequest(string Message);
public record ChatResponse(string Answer);The Agent Framework team also documents exposing a Foundry-connected agent through ASP.NET Core and AG-UI endpoints (public preview) in its Agent Framework blog if you need a chat UI protocol.
Troubleshooting common errors
These are the usual causes; check them in this order.
| Symptom | Likely cause | Fix |
|---|---|---|
| 401 or 403 from the project | Not signed in, or your user or managed identity lacks access to the project | Run az login, then confirm the role assignment on the Foundry project |
| 404, "model not found" or "agent not found" | Wrong endpoint, deployment name or agent name | Compare FOUNDRY_PROJECT_ENDPOINT, FOUNDRY_MODEL and FOUNDRY_AGENT_NAME with the portal; the model value is the deployment name |
| "Environment variable is not set" | The variable was set in another terminal, or Python did not load your .env file | Restart the terminal or IDE; in Python call load_dotenv() |
NuGet cannot find Microsoft.Agents.AI.Foundry | The package is prerelease | Add --prerelease to dotnet add package |
Import errors or missing classes such as PromptAgentDefinition | Mixed azure-ai-projects 1.x and 2.x code | Use a clean virtual environment with azure-ai-projects>=2.3.0 |
| Compiler warning OPENAI001 | The OpenAI Responses types are marked experimental | Add #pragma warning disable OPENAI001, as the quickstart does |
| Slow first call in production | DefaultAzureCredential tries several credential sources | Use ManagedIdentityCredential in Azure |
| Empty answer text | The model returned only tool calls or a blocked response | Check the response object and your agent instructions; the quickstart raises an error when the text is empty |
Summary
- For custom logic and tools in your code, use Microsoft Agent Framework:
AgentandFoundryChatClientin Python,AIProjectClient.AsAIAgent(...)in .NET. - For agents managed in Foundry and shared across apps, create a versioned prompt agent and call it through a conversation:
get_openai_client(agent_name=...)in Python,GetProjectResponsesClientForAgent(...)in .NET. - Use environment variables and token credentials, keep one agent instance per app, and use a managed identity in production.
Microsoft is releasing Agent Framework and Foundry SDK updates frequently, and some packages here are prerelease, so pin package versions and re-check the docs before upgrading.