Перейти к содержимому

Get started with the OpenAI integration

Это содержимое пока не доступно на вашем языке.

OpenAI logo

OpenAI provides access to chat/completions, embeddings, image, and audio models via a REST API. The OpenAI integration lets you:

  • Model an OpenAI account (endpoint + API key) once in the AppHost.
  • Add one or more model resources that compose their connection strings from the parent.
  • Reference those model resources from projects to get strongly-named connection strings.
  • Consume those connection strings with the Aspire.OpenAI component to obtain an OpenAIClient and (optionally) an IChatClient.

In this introduction, you’ll see how to install and use the Aspire OpenAI integrations in a simple configuration. If you already have this knowledge, see OpenAI hosting integration for full reference details.

To begin, install the Aspire OpenAI hosting integration in your Aspire AppHost project:

Aspire CLI — Добавить пакет Aspire.Hosting.OpenAI
aspire add openai

Aspire CLI интерактивен; выберите подходящий результат поиска при запросе:

Aspire CLI — Пример вывода
Select an integration to add:
> openai (Aspire.Hosting.OpenAI)
> Other results listed as selectable options...

Next, in the AppHost project, create instances of OpenAI resources and pass them to the consuming client projects:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var openai = builder.AddOpenAI("openai");
var chat = openai.AddModel("chat", "gpt-4o-mini");
var embeddings = openai.AddModel("embeddings", "text-embedding-3-small");
builder.AddProject<Projects.ExampleProject>()
.WithReference(chat);
builder.Build().Run();

The preceding code adds an OpenAI parent resource and two model resources. Referencing chat passes a connection string named chat to the project. Multiple models can share the single API key and endpoint via the parent resource.

The integration creates a secret parameter named openai-openai-apikey that automatically falls back to the OPENAI_API_KEY environment variable. Provide the key via user-secrets:

Terminal window
dotnet user-secrets set Parameters:openai-openai-apikey sk-your-api-key

To get started with the Aspire OpenAI client integration, install the package:

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

In the Program.cs file of your client-consuming project, use AddOpenAIClient to register an OpenAIClient for dependency injection:

builder.AddOpenAIClient(connectionName: "chat");

After adding the OpenAIClient, you can retrieve the client instance using dependency injection:

public class ExampleService(OpenAIClient client)
{
// Use client...
}