Aspirerelease/17.0
Watch Aspire live streams文档试用 Aspire

Connect to Azure AI Foundry

此内容尚不支持你的语言。

Azure AI Foundry logo

This page describes how consuming apps connect to an Azure AI Foundry resource that’s already modeled in your AppHost. For the AppHost API surface — adding a Foundry account, model deployments, Foundry projects, hosted agents, and more — see Azure AI Foundry hosting integration.

When you reference an Azure AI Foundry deployment resource from your AppHost, Aspire injects the connection information into the consuming app as environment variables. In C# apps running Foundry Local, use the Aspire OpenAI client integration for dependency injection and telemetry. For cloud-provisioned Foundry resources, which authenticate with Microsoft Entra ID, use the Aspire.Azure.AI.Extensions.OpenAI client integration for model deployments and Foundry projects, or Aspire.Azure.AI.Projects for project and agent-management operations. The Python, Go, and TypeScript examples use their SDKs directly.

Aspire exposes each property as an environment variable named [RESOURCE]_[PROPERTY]. For instance, the Uri property of a resource called chat becomes CHAT_URI.

The Foundry account resource exposes the following connection properties:

Property NameDescription
UriThe base endpoint URI for the Azure AI Foundry account
AIInferenceUriThe account’s model-inference endpoint (the base URI plus a models suffix)
KeyThe API key only present when running Foundry Local; cloud-provisioned and existing Foundry accounts never expose a key through Aspire, regardless of the resource’s own local-auth setting

Example environment variables (cloud, resource named chat):

CHAT_URI=https://my-foundry.services.ai.azure.com/
CHAT_AIINFERENCEURI=https://my-foundry.services.ai.azure.com/models

The Foundry deployment resource inherits all properties from its parent account resource and adds:

Property NameDescription
ModelNameThe deployment name as configured in Azure AI Foundry
FormatThe model provider format, for instance OpenAI
VersionThe model version, for instance 2025-06-01

Example environment variables (cloud, deployment resource named chat):

CHAT_URI=https://my-foundry.services.ai.azure.com/
CHAT_AIINFERENCEURI=https://my-foundry.services.ai.azure.com/models
CHAT_MODELNAME=chat
CHAT_FORMAT=OpenAI
CHAT_VERSION=2025-06-01

For .NET apps that consume the composed ConnectionStrings:{name} value (for example, via AddAzureOpenAIClient(connectionName: "chat")) instead of the individual properties above, the format is:

Endpoint=https://my-foundry.services.ai.azure.com/;EndpointAIInference=https://my-foundry.services.ai.azure.com/models;Deployment=chat

The Foundry project resource exposes:

Property NameDescription
UriThe project-scoped endpoint URI (already includes the project name and api-version query string)
ConnectionStringThe composed Endpoint=... connection string, for .NET apps using ConnectionStrings:{name}
ApplicationInsightsConnectionStringThe project’s Application Insights connection string, if configured

Example environment variables (project resource named myProject):

MYPROJECT_URI=https://my-foundry.services.ai.azure.com/api/projects/my-project?api-version=...

A Toolbox exposes one MCP endpoint for its configured tools. See Add a Toolbox for the AppHost walkthrough.

PropertyDescription
UriDefault MCP endpoint, or the endpoint of a pinned immutable version
ProjectEndpointParent Foundry project endpoint
NameToolbox name
ApiVersionToolbox data-plane API version
VersionPinned immutable version, when configured
FoundryFeaturesRequired Foundry-Features request-header value
AuthorizationScopeMicrosoft Entra scope for Toolbox requests

For a resource named field-tools, read FIELD_TOOLS_URI, FIELD_TOOLS_FOUNDRYFEATURES, and FIELD_TOOLS_AUTHORIZATIONSCOPE. Acquire an Entra token for the supplied scope, include the Foundry-Features header, and perform the MCP initialize and tools/list handshake against Uri. The composed connection string contains Uri=https://.../toolboxes/field-tools/mcp.

Tool approval policies returned during discovery aren’t enforced by the Toolbox service. Your client must inspect them and obtain approval before calling a tool.

Pick the language your consuming app is written in. Each example assumes your AppHost adds a Foundry deployment resource named chat and references it from the consuming app.

For C# apps, use an Aspire client integration that matches the resource you reference:

Each OpenAI-based integration can also register an IChatClient via Microsoft.Extensions.AI. To use the OpenAI SDK without a client integration, see Connect with the OpenAI SDK.

Connect with Aspire.OpenAI (Foundry Local)

Section titled “Connect with Aspire.OpenAI (Foundry Local)”

Install the 📦 Aspire.OpenAI NuGet package in the client-consuming project:

.NET CLI — Add Aspire.OpenAI package
dotnet add package Aspire.OpenAI

Aspire injects the Foundry Local deployment’s connection string as ConnectionStrings:chat, with the format Endpoint=<uri>;Key=unused;Model=<id>. The unused key is a placeholder because Foundry Local doesn’t require authentication.

AddOpenAIClient("chat") parses the endpoint and key before invoking the settings callback. The callback only changes the endpoint to Foundry Local’s /v1/ route, documented in the Foundry Local REST API reference. AddChatClient() reads the model from the same connection string and registers an IChatClient:

Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.AddOpenAIClient(
"chat",
settings =>
{
ArgumentNullException.ThrowIfNull(settings.Endpoint);
settings.Endpoint = new Uri(settings.Endpoint, "v1/");
})
.AddChatClient();

For cloud-provisioned Foundry deployments, install the 📦 Aspire.Azure.AI.Extensions.OpenAI NuGet package in the client-consuming project:

.NET CLI — Add Aspire.Azure.AI.Extensions.OpenAI package
dotnet add package Aspire.Azure.AI.Extensions.OpenAI

The deployment’s connection string includes the account endpoint and the Deployment name. Call AddAzureOpenAIClient to register an OpenAIClient for the account’s /openai/v1/ route, then AddChatClient() to register an IChatClient for that deployment:

Program.cs
builder.AddAzureOpenAIClient("chat")
.AddChatClient();

The client authenticates with Microsoft Entra ID: Aspire uses a development credential locally and managed identity when deployed to Azure. Resolve OpenAI.OpenAIClient or IChatClient through dependency injection. Use AddEmbeddingGenerator() for embedding deployments, and AddKeyedAzureOpenAIClient for keyed registrations. For configuration and telemetry options, see Connect to Azure OpenAI.

To call models or agents through a Foundry project, reference both the Foundry resource and the project from the consuming app in your AppHost. The project reference supplies the project endpoint; the Foundry resource reference configures the app’s identity and access. Then call AddAzureProjectOpenAIClient from 📦 Aspire.Azure.AI.Extensions.OpenAI. It registers a ProjectOpenAIClient (also resolvable as OpenAIClient). The connection name matches the project resource name:

Program.cs
var clientBuilder = builder.AddAzureProjectOpenAIClient("my-project");
clientBuilder.AddChatClient("chat");
clientBuilder.AddEmbeddingGenerator("embeddings");

Model names refer to deployments available to the project. To call a prompt agent, resolve ProjectOpenAIClient:

AgentService.cs
using Azure.AI.Extensions.OpenAI;
public class AgentService(ProjectOpenAIClient client)
{
public async Task AskAsync(string prompt)
{
var responses = client.GetProjectResponsesClientForAgent(new AgentReference("my-agent"));
var response = await responses.CreateResponseAsync(prompt);
// Use response...
}
}

Hosted agents use GetProjectResponsesClientForAgentEndpoint("my-agent") instead. The Responses APIs may require suppressing the OPENAI001 experimental-API warning.

Project clients authenticate with Microsoft Entra ID only; connection strings with a Key are rejected. Settings are read from the Aspire:Azure:AI:Extensions:OpenAI configuration section. Use AddKeyedAzureProjectOpenAIClient for keyed registrations.

Manage a Foundry project with AIProjectClient

Section titled “Manage a Foundry project with AIProjectClient”

For project and agent-management operations — such as project connections, deployments, datasets, and agent administration — install the 📦 Aspire.Azure.AI.Projects NuGet package:

.NET CLI — Add Aspire.Azure.AI.Projects package
dotnet add package Aspire.Azure.AI.Projects

Call AddAzureAIProjectClient to register an AIProjectClient:

Program.cs
builder.AddAzureAIProjectClient("my-project");
ProjectService.cs
using Azure.AI.Projects;
public class ProjectService(AIProjectClient projectClient)
{
// Use projectClient...
}

Use AddKeyedAzureAIProjectClient for keyed registrations. Settings are read from the Aspire:Azure:AI:Projects configuration section; set DisableTracing to true to turn off the Azure.AI.Projects.* traces. Like the project OpenAI client, it uses Microsoft Entra ID and rejects API keys. Neither project integration registers a health check.

.NET CLI — Add OpenAI package
dotnet add package OpenAI
.NET CLI — Add Azure.Identity package
dotnet add package Azure.Identity

If you’d rather not use a client integration with cloud-provisioned Foundry resources, read the Aspire-injected connection properties in Program.cs and construct a ChatClient authenticated with DefaultAzureCredential, pointing it at the Foundry endpoint’s openai/v1 route:

Program.cs
using Azure.Identity;
using OpenAI;
using OpenAI.Chat;
using System.ClientModel.Primitives;
#pragma warning disable OPENAI001
var endpoint = Environment.GetEnvironmentVariable("CHAT_URI");
var deployment = Environment.GetEnvironmentVariable("CHAT_MODELNAME");
var tokenPolicy = new BearerTokenPolicy(
new DefaultAzureCredential(),
"https://ai.azure.com/.default");
var client = new ChatClient(
model: deployment,
authenticationPolicy: tokenPolicy,
options: new OpenAIClientOptions
{
Endpoint = new Uri($"{endpoint}openai/v1/")
});
ChatCompletion completion = client.CompleteChat(
new UserChatMessage("Hello from Aspire!"));
Console.WriteLine(completion.Content[0].Text);

If your app has a host builder — for example, an ASP.NET Core or worker service Program.cs using WebApplication.CreateBuilder(args) or Host.CreateApplicationBuilder(args) — you can instead register an IChatClient from Microsoft.Extensions.AI for dependency injection. Install 📦 Microsoft.Extensions.AI.OpenAI, construct the ChatClient the same way shown above, then chain AsIChatClient() and register it before calling Build():

Program.cs
using Azure.Identity;
using Microsoft.Extensions.AI;
using OpenAI;
using OpenAI.Chat;
using System.ClientModel.Primitives;
#pragma warning disable OPENAI001
var builder = Host.CreateApplicationBuilder(args);
var endpoint = Environment.GetEnvironmentVariable("CHAT_URI");
var deployment = Environment.GetEnvironmentVariable("CHAT_MODELNAME");
var tokenPolicy = new BearerTokenPolicy(
new DefaultAzureCredential(),
"https://ai.azure.com/.default");
var client = new ChatClient(
model: deployment,
authenticationPolicy: tokenPolicy,
options: new OpenAIClientOptions
{
Endpoint = new Uri($"{endpoint}openai/v1/")
});
IChatClient chatClient = client.AsIChatClient();
builder.Services.AddSingleton(chatClient);
var host = builder.Build();
host.Run();

Resolve the IChatClient through dependency injection:

ExampleService.cs
public class ExampleService(IChatClient chatClient)
{
public async Task<string> GetResponseAsync(string prompt)
{
var response = await chatClient.GetResponseAsync(prompt);
return response.Text;
}
}

Migrate from Aspire.Azure.AI.Inference or Aspire.Azure.AI.OpenAI

Section titled “Migrate from Aspire.Azure.AI.Inference or Aspire.Azure.AI.OpenAI”

The Aspire.Azure.AI.Inference and Aspire.Azure.AI.OpenAI client integrations are discontinued, and previously published versions remain on NuGet. Microsoft has also retired the Azure AI Inference SDK (Azure.AI.Inference / ChatCompletionsClient) in favor of the OpenAI SDK. To upgrade a Foundry app:

BeforeAfter
Aspire.Azure.AI.Inference or Aspire.Azure.AI.OpenAI packageAspire.Azure.AI.Extensions.OpenAI package
AddAzureChatCompletionsClient("chat") against a deploymentAddAzureOpenAIClient("chat").AddChatClient()
AddAzureChatCompletionsClient or AddAzureOpenAIClient against a projectAddAzureProjectOpenAIClient("my-project") with the project endpoint
Resolve ChatCompletionsClient, EmbeddingsClient, or AzureOpenAIClientResolve OpenAIClient, ProjectOpenAIClient, or IChatClient
Project management through the inference endpointAspire.Azure.AI.Projects and AddAzureAIProjectClient

Azure AI Inference SDK request and response types aren’t interchangeable with OpenAI SDK types, so update calls accordingly. Project clients don’t accept API keys; grant the app’s identity the permissions it needs instead. For SDK-level differences, see Microsoft’s Azure AI Inference SDK to OpenAI SDK migration guide.