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. Your app reads those environment variables and constructs a client with the OpenAI SDK — Microsoft’s currently recommended way to call Azure AI Foundry Models — the pattern works the same from any language. In C#, you can also use the legacy Aspire Azure AI Inference client integration for automatic dependency injection, health checks, and telemetry via Microsoft.Extensions.AI.

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 AddAzureChatCompletionsClient(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, the recommended approach is the OpenAI SDK, which Microsoft now recommends for connecting to Azure AI Foundry Models. Read the Aspire-injected connection properties from the environment and construct an OpenAI ChatClient pointed at your Foundry endpoint’s OpenAI-compatible route.

.NET CLI — Add OpenAI package
dotnet add package OpenAI

The default AddFoundry(...) resource has local auth disabled, so consuming apps authenticate with Managed Identity. Also install the 📦 Azure.Identity package:

Terminal
dotnet add package Azure.Identity

In Program.cs, read the Aspire-injected connection properties 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;
}
}

Install the 📦 Aspire.Azure.AI.Inference NuGet package in the client-consuming project:

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

In Program.cs, call AddAzureChatCompletionsClient on your IHostApplicationBuilder to register a ChatCompletionsClient:

Program.cs
builder.AddAzureChatCompletionsClient(connectionName: "chat");

Resolve the client through dependency injection:

ExampleService.cs
public class ExampleService(ChatCompletionsClient client)
{
// Use client for chat completions...
}

For keyed clients, configuration options, health checks, and telemetry details for this legacy integration, see Connect to Azure AI Inference.