# Connect to Microsoft Foundry

<Image
  src={aiFoundryIcon}
  alt="Microsoft Foundry logo"
  width={100}
  height={100}
  class:list={'float-inline-left icon'}
  data-zoom-off
/>

This page describes how consuming apps connect to a Microsoft 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 [Foundry hosting integration](../foundry-host/).

When you reference a 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.

## 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`.

**Caution:** These property names reflect the resource types' actual `GetConnectionProperties()` implementation. If you see older guidance referencing `Endpoint`, `ApiKey`, `Deployment`, or `Model`, those names are outdated. Use the names below instead.

### Foundry account resource

The Foundry account resource exposes the following connection properties:

| Property Name    | Description |
| ----------------- | ----------- |
| `Uri`             | The base endpoint URI for the 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](../foundry-host/#use-foundry-local-for-development)**; 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
```

**Note:** By default, <ApiReference name="Aspire.Hosting.FoundryExtensions.AddFoundry" /> provisions the Foundry account with `disableLocalAuth: true` and creates the role assignments consuming apps need, so apps authenticate via managed identity. Because Aspire only ever surfaces `Key` for Foundry Local, the examples below default to token-based authentication (`DefaultAzureCredential`) for every scenario except Foundry Local.

### 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 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/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
```

### 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=...
```

**Note:** The project resource never exposes an API key or a separate project-name property through Aspire. Authenticate with `DefaultAzureCredential` and use `Uri` directly as the project endpoint.

### Foundry Toolbox resource

A Toolbox exposes one MCP endpoint for its configured tools. See [Add a Toolbox](../foundry-host/#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

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:

- **Foundry Local:** [Aspire.OpenAI](#connect-with-aspireopenai-foundry-local) registers an `OpenAIClient` that uses Foundry Local's API key.
- **Cloud model deployments:** [Aspire.Azure.AI.Extensions.OpenAI](#connect-to-a-model-deployment) registers an `OpenAIClient` that authenticates with Microsoft Entra ID.
- **Foundry projects:** [Aspire.Azure.AI.Extensions.OpenAI](#connect-to-a-foundry-project) registers a `ProjectOpenAIClient` for models and agents, and [Aspire.Azure.AI.Projects](#manage-a-foundry-project-with-aiprojectclient) registers an `AIProjectClient` for project and agent-management operations.

Each OpenAI-based integration can also register an [`IChatClient`](https://learn.microsoft.com/dotnet/api/microsoft.extensions.ai.ichatclient) via `Microsoft.Extensions.AI`. To use the OpenAI SDK without a client integration, see [Connect with the OpenAI SDK](#connect-with-the-openai-sdk).

### Connect with Aspire.OpenAI (Foundry Local)

Install the [📦 Aspire.OpenAI](https://www.nuget.org/packages/Aspire.OpenAI) NuGet package in the client-consuming project:

<InstallDotNetPackage packageName="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](https://learn.microsoft.com/azure/foundry-local/reference/reference-rest#post-v1chatcompletions). `AddChatClient()` reads the model from the same connection string and registers an `IChatClient`:

```csharp title="Program.cs"
var builder = WebApplication.CreateBuilder(args);

builder.AddOpenAIClient(
        "chat",
        settings =>
        {
            ArgumentNullException.ThrowIfNull(settings.Endpoint);
            settings.Endpoint = new Uri(settings.Endpoint, "v1/");
        })
    .AddChatClient();
```

### Connect to a model deployment

For cloud-provisioned Foundry deployments, install the [📦 Aspire.Azure.AI.Extensions.OpenAI](https://www.nuget.org/packages/Aspire.Azure.AI.Extensions.OpenAI) NuGet package in the client-consuming project:

<InstallDotNetPackage packageName="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:

```csharp title="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](/integrations/cloud/azure/azure-openai/azure-openai-connect/#configuration).

**Tip:** To use the same code for Foundry Local and cloud deployments, call `builder.AddOpenAIClientFromConfiguration("chat").AddChatClient()`. It reads the connection string and uses Foundry Local's API key or Microsoft Entra ID for Azure, without an application-side switch.

### Connect to a Foundry project

To call models or agents through a [Foundry project](../foundry-host/#add-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](https://www.nuget.org/packages/Aspire.Azure.AI.Extensions.OpenAI). It registers a `ProjectOpenAIClient` (also resolvable as `OpenAIClient`). The connection name matches the project resource name:

```csharp title="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`:

```csharp title="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

For project and agent-management operations — such as project connections, deployments, datasets, and agent administration — install the [📦 Aspire.Azure.AI.Projects](https://www.nuget.org/packages/Aspire.Azure.AI.Projects) NuGet package:

<InstallDotNetPackage packageName="Aspire.Azure.AI.Projects" />

Call `AddAzureAIProjectClient` to register an `AIProjectClient`:

```csharp title="Program.cs"
builder.AddAzureAIProjectClient("my-project");
```

```csharp title="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.

### Install the OpenAI SDK

<InstallDotNetPackage packageName="OpenAI" />

<InstallDotNetPackage packageName="Azure.Identity" />

### Connect with the OpenAI SDK

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:

```csharp title="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);
```

**Note:** `BearerTokenPolicy` is marked experimental (`OPENAI001`) in the current OpenAI SDK, hence the `#pragma warning disable`. Aspire only ever exposes a `Key` property for [Foundry Local](../foundry-host/#use-foundry-local-for-development) — a cloud or existing Foundry account never surfaces an API key through Aspire, regardless of its own local-auth setting. For Foundry Local, prefer the [Aspire.OpenAI example](#connect-with-aspireopenai-foundry-local) above, which uses the local `/v1/` route rather than the cloud `/openai/v1/` route. For more authentication examples, see Microsoft's [migration guide](https://learn.microsoft.com/azure/foundry/how-to/model-inference-to-openai-migration?tabs=openai&pivots=programming-language-dotnet).

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`](https://learn.microsoft.com/dotnet/api/microsoft.extensions.ai.ichatclient) from `Microsoft.Extensions.AI` for dependency injection. Install [📦 Microsoft.Extensions.AI.OpenAI](https://www.nuget.org/packages/Microsoft.Extensions.AI.OpenAI), construct the `ChatClient` the same way shown above, then chain `AsIChatClient()` and register it before calling `Build()`:

```csharp title="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:

```csharp title="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

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:

| Before | After |
| ------ | ----- |
| `Aspire.Azure.AI.Inference` or `Aspire.Azure.AI.OpenAI` package | `Aspire.Azure.AI.Extensions.OpenAI` package |
| `AddAzureChatCompletionsClient("chat")` against a deployment | `AddAzureOpenAIClient("chat").AddChatClient()` |
| `AddAzureChatCompletionsClient` or `AddAzureOpenAIClient` against a project | `AddAzureProjectOpenAIClient("my-project")` with the **project** endpoint |
| Resolve `ChatCompletionsClient`, `EmbeddingsClient`, or `AzureOpenAIClient` | Resolve `OpenAIClient`, `ProjectOpenAIClient`, or `IChatClient` |
| Project management through the inference endpoint | `Aspire.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](https://learn.microsoft.com/azure/foundry/how-to/model-inference-to-openai-migration).

Use the official [openai-go](https://github.com/openai/openai-go) SDK, which Microsoft recommends for calling Foundry Models, together with the Azure SDK for Go's `azure` helper package for token authentication:

```bash title="Terminal"
go get github.com/openai/openai-go/v3
go get github.com/Azure/azure-sdk-for-go/sdk/azidentity
```

**Note:** Microsoft has retired the classic `azopenai` client calls (`GetChatCompletions` against the versioned REST API) in favor of `openai-go` against the `openai/v1` route. For details, see Microsoft's [Azure AI Inference SDK to OpenAI SDK migration guide](https://learn.microsoft.com/azure/foundry/how-to/model-inference-to-openai-migration). A [legacy example](#legacy-azopenai-go) using `azopenai` is provided below for apps that haven't migrated yet.

The default `AddFoundry(...)` resource has local auth disabled, so authenticate with the `azidentity` package:

```go title="main.go"
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)
}
```

**Note:** If you're running [Foundry Local](../foundry-host/#use-foundry-local-for-development) — the only scenario where Aspire exposes a `Key` property — read `CHAT_KEY` and use `option.WithAPIKey(apiKey)` (from `github.com/openai/openai-go/v3/option`) in place of `azure.WithTokenCredential(...)`.

### Legacy: azopenai (Go)

**Caution:** Microsoft has retired this pattern — calling the classic, versioned Azure OpenAI REST API through `azopenai.GetChatCompletions` — in favor of `openai-go` against the `openai/v1` route shown above. Use this only for existing apps you haven't migrated yet.

```bash title="Terminal"
go get github.com/Azure/azure-sdk-for-go/sdk/ai/azopenai
go get github.com/Azure/azure-sdk-for-go/sdk/azidentity
```

```go title="main.go (legacy)"
package 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)
}
```

**Note:** If you're running Foundry Local, read `CHAT_KEY` and use `azopenai.NewClientWithKeyCredential(endpoint, azcore.NewKeyCredential(apiKey), nil)` (from `github.com/Azure/azure-sdk-for-go/sdk/azcore`) instead.

Install the [openai](https://pypi.org/project/openai/), [azure-identity](https://pypi.org/project/azure-identity/), and [azure-ai-projects](https://pypi.org/project/azure-ai-projects/) packages:

```bash title="Terminal"
pip install openai azure-identity azure-ai-projects
```

**Note:** Microsoft has retired the `azure-ai-inference` SDK in favor of the `openai` package for calling Foundry Models. For details, see Microsoft's [Azure AI Inference SDK to OpenAI SDK migration guide](https://learn.microsoft.com/azure/foundry/how-to/model-inference-to-openai-migration). A [legacy example](#legacy-azure-ai-inference-sdk-python) using `azure-ai-inference` is provided below for apps that haven't migrated yet.

**Using the OpenAI SDK for direct model calls (recommended):**

The default `AddFoundry(...)` resource has local auth disabled, so authenticate with `azure-identity`:

```python title="app.py"
import os
from openai import OpenAI
from azure.identity import DefaultAzureCredential, get_bearer_token_provider

# Read the Aspire-injected connection properties
endpoint   = 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)
```

**Note:** If you're running [Foundry Local](../foundry-host/#use-foundry-local-for-development) — the only scenario where Aspire exposes a `Key` property — read `CHAT_KEY` and pass it as `api_key` instead of the token provider.

**Using `azure-ai-projects` for Foundry project-scoped access:**

```python title="app.py"
import os
from azure.ai.projects import AIProjectClient
from azure.identity import DefaultAzureCredential

# Read the Aspire-injected project connection properties
project_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)

**Caution:** Microsoft has retired the Azure AI Inference SDK in favor of the OpenAI SDK shown above. Use this only for existing apps you haven't migrated yet.

Install the [azure-ai-inference](https://pypi.org/project/azure-ai-inference/) and [azure-identity](https://pypi.org/project/azure-identity/) packages:

```bash title="Terminal"
pip install azure-ai-inference azure-identity
```

The default `AddFoundry(...)` resource has local auth disabled, so this example authenticates with `DefaultAzureCredential`:

```python title="app.py (legacy)"
import os
from azure.ai.inference import ChatCompletionsClient
from azure.identity import DefaultAzureCredential

# Read the Aspire-injected connection properties
endpoint   = 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)
```

**Note:** If you're running [Foundry Local](../foundry-host/#use-foundry-local-for-development) — the only scenario where Aspire exposes a `Key` property — read `CHAT_KEY` and use `AzureKeyCredential(api_key)` (from `azure.core.credentials`) instead.

Install the official [openai](https://www.npmjs.com/package/openai), [@azure/identity](https://www.npmjs.com/package/@azure/identity), and [@azure/ai-projects](https://www.npmjs.com/package/@azure/ai-projects) packages:

```bash title="Terminal"
npm install openai @azure/identity @azure/ai-projects
```

**Note:** Microsoft has retired the `@azure-rest/ai-inference` SDK in favor of the `openai` package for calling Foundry Models. For details, see Microsoft's [Azure AI Inference SDK to OpenAI SDK migration guide](https://learn.microsoft.com/azure/foundry/how-to/model-inference-to-openai-migration). A [legacy example](#legacy-azure-ai-inference-sdk-typescript) using `@azure-rest/ai-inference` is provided below for apps that haven't migrated yet.

**Using the OpenAI SDK for direct model calls (recommended):**

The default `AddFoundry(...)` resource has local auth disabled, so authenticate with `@azure/identity`:

```typescript title="index.ts"
import OpenAI from 'openai';
import { DefaultAzureCredential, getBearerTokenProvider } from '@azure/identity';

// Read Aspire-injected connection properties
const 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);
```

**Note:** If you're running [Foundry Local](../foundry-host/#use-foundry-local-for-development) — the only scenario where Aspire exposes a `Key` property — read `CHAT_KEY` and pass it as `apiKey` instead of the token provider.

**Using `@azure/ai-projects` for Foundry project-scoped access:**

```typescript title="index.ts"
import { AIProjectClient } from '@azure/ai-projects';
import { DefaultAzureCredential } from '@azure/identity';

// Read Aspire-injected project connection properties
const 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)

**Caution:** Microsoft has retired the Azure AI Inference SDK in favor of the OpenAI SDK shown above. Use this only for existing apps you haven't migrated yet.

Install the [@azure-rest/ai-inference](https://www.npmjs.com/package/@azure-rest/ai-inference) and [@azure/identity](https://www.npmjs.com/package/@azure/identity) packages:

```bash title="Terminal"
npm install @azure-rest/ai-inference @azure/identity
```

The default `AddFoundry(...)` resource has local auth disabled, so this example authenticates with `DefaultAzureCredential`:

```typescript title="index.ts (legacy)"
import ModelClient from '@azure-rest/ai-inference';
import { DefaultAzureCredential } from '@azure/identity';

// Read Aspire-injected connection properties
const 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);
```

**Note:** If you're running [Foundry Local](../foundry-host/#use-foundry-local-for-development) — the only scenario where Aspire exposes a `Key` property — read `CHAT_KEY` and use `AzureKeyCredential(apiKey)` (from `@azure/core-auth`) instead.

**Tip:** Every example above, including the legacy Azure AI Inference SDK examples defaults to Managed Identity (`DefaultAzureCredential`), because that's how `AddFoundry(...)` provisions the resource and Aspire only ever surfaces a `Key` property for Foundry Local. Each example includes a note on swapping in `CHAT_KEY` if you're running Foundry Local. See the "Foundry account resource" and "Foundry project resource" connection properties above for details.

## See also

- [Get started with Microsoft Foundry integrations](/integrations/ai/foundry/foundry-get-started/)
- [Microsoft Foundry hosting integration](/integrations/ai/foundry/foundry-host/)
- [Azure AI Inference SDK to OpenAI SDK migration guide](https://learn.microsoft.com/azure/foundry/how-to/model-inference-to-openai-migration)
- [Azure AI Inference integration (legacy)](/integrations/cloud/azure/azure-ai-inference/azure-ai-inference-get-started/)
- [Microsoft Foundry documentation](https://learn.microsoft.com/azure/ai-foundry/)