Connect to Azure AI Foundry
이 콘텐츠는 아직 번역되지 않았습니다.
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. Cloud-provisioned Foundry resources authenticate with a managed identity, which the Aspire OpenAI client integration doesn’t support, so use the OpenAI SDK directly for those resources. The Python, Go, and TypeScript examples also use their OpenAI SDKs directly.
Connection properties
Section titled “Connection properties”Aspire exposes each property as an environment variable named [RESOURCE]_[PROPERTY]. For instance, the Uri property of a resource called chat becomes CHAT_URI.
Foundry account resource
Section titled “Foundry account resource”The Foundry account resource exposes the following connection properties:
| Property Name | Description |
|---|---|
Uri | The base endpoint URI for the Azure AI Foundry account |
AIInferenceUri | The account’s model-inference endpoint (the base URI plus a models suffix) |
Key | The 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/modelsFoundry deployment resource
Section titled “Foundry deployment resource”The Foundry deployment resource inherits all properties from its parent account resource and adds:
| Property Name | Description |
|---|---|
ModelName | The deployment name as configured in Azure AI Foundry |
Format | The model provider format, for instance OpenAI |
Version | The 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/modelsCHAT_MODELNAME=chatCHAT_FORMAT=OpenAICHAT_VERSION=2025-06-01For .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=chatFoundry project resource
Section titled “Foundry project resource”The Foundry project resource exposes:
| Property Name | Description |
|---|---|
Uri | The project-scoped endpoint URI (already includes the project name and api-version query string) |
ConnectionString | The composed Endpoint=... connection string, for .NET apps using ConnectionStrings:{name} |
ApplicationInsightsConnectionString | The 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=...Foundry Toolbox resource
Section titled “Foundry Toolbox resource”A Toolbox exposes one MCP endpoint for its configured tools. See Add a Toolbox for the AppHost walkthrough.
| Property | Description |
|---|---|
Uri | Default MCP endpoint, or the endpoint of a pinned immutable version |
ProjectEndpoint | Parent Foundry project endpoint |
Name | Toolbox name |
ApiVersion | Toolbox data-plane API version |
Version | Pinned immutable version, when configured |
FoundryFeatures | Required Foundry-Features request-header value |
AuthorizationScope | Microsoft 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.
Connect from your app
Section titled “Connect from your app”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 running Foundry Local, the recommended approach is the Aspire OpenAI client integration. It registers an OpenAIClient through dependency injection and can also register an IChatClient via Microsoft.Extensions.AI. Cloud-provisioned Foundry resources use managed identity, which the Aspire OpenAI integration does not support; use the OpenAI SDK directly for those resources.
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:
dotnet add package Aspire.OpenAI#:package Aspire.OpenAI@*<PackageReference Include="Aspire.OpenAI" Version="*" />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:
var builder = WebApplication.CreateBuilder(args);
builder.AddOpenAIClient( "chat", settings => { ArgumentNullException.ThrowIfNull(settings.Endpoint); settings.Endpoint = new Uri(settings.Endpoint, "v1/"); }) .AddChatClient();Install the OpenAI SDK
Section titled “Install the OpenAI SDK”dotnet add package OpenAI#:package OpenAI@*<PackageReference Include="OpenAI" Version="*" />dotnet add package Azure.Identity#:package Azure.Identity@*<PackageReference Include="Azure.Identity" Version="*" />Connect with the OpenAI SDK
Section titled “Connect with the OpenAI SDK”For 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:
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():
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:
public class ExampleService(IChatClient chatClient){ public async Task<string> GetResponseAsync(string prompt) { var response = await chatClient.GetResponseAsync(prompt); return response.Text; }}Legacy: Azure AI Inference SDK
Section titled “Legacy: Azure AI Inference SDK”Install the 📦 Aspire.Azure.AI.Inference NuGet package in the client-consuming project:
dotnet add package Aspire.Azure.AI.Inference#:package Aspire.Azure.AI.Inference@*<PackageReference Include="Aspire.Azure.AI.Inference" Version="*" />In Program.cs, call AddAzureChatCompletionsClient on your IHostApplicationBuilder to register a ChatCompletionsClient:
builder.AddAzureChatCompletionsClient(connectionName: "chat");Resolve the client through dependency injection:
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.
Use the official openai-go SDK, which Microsoft recommends for calling Azure AI Foundry Models, together with the Azure SDK for Go’s azure helper package for token authentication:
go get github.com/openai/openai-go/v3go get github.com/Azure/azure-sdk-for-go/sdk/azidentityThe default AddFoundry(...) resource has local auth disabled, so authenticate with the azidentity package:
package main
import ( "context" "fmt" "os"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity" "github.com/openai/openai-go/v3" "github.com/openai/openai-go/v3/azure" "github.com/openai/openai-go/v3/option")
func main() { // Read the Aspire-injected connection properties endpoint := os.Getenv("CHAT_URI") deployment := os.Getenv("CHAT_MODELNAME")
tokenCredential, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { panic(err) }
client := openai.NewClient( option.WithBaseURL(fmt.Sprintf("%sopenai/v1", endpoint)), azure.WithTokenCredential(tokenCredential), )
resp, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{ Messages: []openai.ChatCompletionMessageParamUnion{ openai.UserMessage("Hello from Aspire!"), }, Model: deployment, }) if err != nil { panic(err) }
fmt.Println(resp.Choices[0].Message.Content)}Legacy: azopenai (Go)
Section titled “Legacy: azopenai (Go)”go get github.com/Azure/azure-sdk-for-go/sdk/ai/azopenaigo get github.com/Azure/azure-sdk-for-go/sdk/azidentitypackage main
import ( "context" "fmt" "os"
"github.com/Azure/azure-sdk-for-go/sdk/ai/azopenai" "github.com/Azure/azure-sdk-for-go/sdk/azidentity")
func main() { // Read the Aspire-injected connection properties endpoint := os.Getenv("CHAT_URI") deployment := os.Getenv("CHAT_MODELNAME")
credential, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { panic(err) }
client, err := azopenai.NewClient(endpoint, credential, nil) if err != nil { panic(err) }
resp, err := client.GetChatCompletions( context.Background(), azopenai.ChatCompletionsOptions{ DeploymentName: &deployment, Messages: []azopenai.ChatRequestMessageClassification{ &azopenai.ChatRequestUserMessage{ Content: azopenai.NewChatRequestUserMessageContent("Hello!"), }, }, }, nil, ) if err != nil { panic(err) }
fmt.Println(*resp.Choices[0].Message.Content)}Install the openai, azure-identity, and azure-ai-projects packages:
pip install openai azure-identity azure-ai-projectsUsing the OpenAI SDK for direct model calls (recommended):
The default AddFoundry(...) resource has local auth disabled, so authenticate with azure-identity:
import osfrom openai import OpenAIfrom azure.identity import DefaultAzureCredential, get_bearer_token_provider
# Read the Aspire-injected connection propertiesendpoint = os.environ["CHAT_URI"]deployment = os.environ["CHAT_MODELNAME"]
token_provider = get_bearer_token_provider( DefaultAzureCredential(), "https://ai.azure.com/.default",)
client = OpenAI( base_url=f"{endpoint}openai/v1/", api_key=token_provider,)
response = client.chat.completions.create( model=deployment, messages=[{"role": "user", "content": "Hello from Aspire!"}],)
print(response.choices[0].message.content)Using azure-ai-projects for Foundry project-scoped access:
import osfrom azure.ai.projects import AIProjectClientfrom azure.identity import DefaultAzureCredential
# Read the Aspire-injected project connection propertiesproject_endpoint = os.environ["MYPROJECT_URI"]
project_client = AIProjectClient( endpoint=project_endpoint, credential=DefaultAzureCredential(),)
client = project_client.get_openai_client()
response = client.chat.completions.create( model=os.environ.get("CHAT_MODELNAME", "gpt-5-mini"), messages=[{"role": "user", "content": "Hello from Aspire!"}],)
print(response.choices[0].message.content)Legacy: Azure AI Inference SDK (Python)
Section titled “Legacy: Azure AI Inference SDK (Python)”Install the azure-ai-inference and azure-identity packages:
pip install azure-ai-inference azure-identityThe default AddFoundry(...) resource has local auth disabled, so this example authenticates with DefaultAzureCredential:
import osfrom azure.ai.inference import ChatCompletionsClientfrom azure.identity import DefaultAzureCredential
# Read the Aspire-injected connection propertiesendpoint = os.environ["CHAT_AIINFERENCEURI"]deployment = os.environ["CHAT_MODELNAME"]
client = ChatCompletionsClient( endpoint=endpoint, credential=DefaultAzureCredential(), credential_scopes=["https://cognitiveservices.azure.com/.default"],)
response = client.complete( model=deployment, messages=[{"role": "user", "content": "Hello from Aspire!"}],)
print(response.choices[0].message.content)Install the official openai, @azure/identity, and @azure/ai-projects packages:
npm install openai @azure/identity @azure/ai-projectsUsing the OpenAI SDK for direct model calls (recommended):
The default AddFoundry(...) resource has local auth disabled, so authenticate with @azure/identity:
import OpenAI from 'openai';import { DefaultAzureCredential, getBearerTokenProvider } from '@azure/identity';
// Read Aspire-injected connection propertiesconst endpoint = process.env.CHAT_URI!;const deployment = process.env.CHAT_MODELNAME ?? 'chat';
const tokenProvider = getBearerTokenProvider( new DefaultAzureCredential(), 'https://ai.azure.com/.default',);
const client = new OpenAI({ baseURL: `${endpoint}openai/v1/`, apiKey: tokenProvider,});
const response = await client.chat.completions.create({ model: deployment, messages: [{ role: 'user', content: 'Hello from Aspire!' }],});
console.log(response.choices[0].message.content);Using @azure/ai-projects for Foundry project-scoped access:
import { AIProjectClient } from '@azure/ai-projects';import { DefaultAzureCredential } from '@azure/identity';
// Read Aspire-injected project connection propertiesconst projectEndpoint = process.env.MYPROJECT_URI!;
const projectClient = new AIProjectClient( projectEndpoint, new DefaultAzureCredential(),);
const client = projectClient.getOpenAIClient();
const response = await client.chat.completions.create({ model: process.env.CHAT_MODELNAME ?? 'gpt-5-mini', messages: [{ role: 'user', content: 'Hello from Aspire!' }],});
console.log(response.choices[0].message.content);Legacy: Azure AI Inference SDK (TypeScript)
Section titled “Legacy: Azure AI Inference SDK (TypeScript)”Install the @azure-rest/ai-inference and @azure/identity packages:
npm install @azure-rest/ai-inference @azure/identityThe default AddFoundry(...) resource has local auth disabled, so this example authenticates with DefaultAzureCredential:
import ModelClient from '@azure-rest/ai-inference';import { DefaultAzureCredential } from '@azure/identity';
// Read Aspire-injected connection propertiesconst endpoint = process.env.CHAT_AIINFERENCEURI!;const deployment = process.env.CHAT_MODELNAME ?? 'chat';
const client = ModelClient(endpoint, new DefaultAzureCredential(), { credentials: { scopes: ['https://cognitiveservices.azure.com/.default'] },});
const response = await client.path('/chat/completions').post({ body: { model: deployment, messages: [{ role: 'user', content: 'Hello from Aspire!' }], },});
if (response.status !== '200') { throw new Error(`Request failed: ${response.status}`);}
console.log(response.body.choices[0].message.content);