Get started with the OpenAI integration
Dette indhold er ikke tilgængeligt i dit sprog endnu.
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.OpenAIcomponent to obtain anOpenAIClientand (optionally) anIChatClient.
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.
Set up hosting integration
Section titled “Set up hosting integration”To begin, install the Aspire OpenAI hosting integration in your Aspire AppHost project:
aspire add openaiAspire CLI er interaktiv; vælg det passende søgeresultat når du bliver spurgt:
Select an integration to add:
> openai (Aspire.Hosting.OpenAI)> Other results listed as selectable options...#:package Aspire.Hosting.OpenAI@*<PackageReference Include="Aspire.Hosting.OpenAI" Version="*" />Next, in the AppHost project, create instances of OpenAI resources and pass them to the consuming client projects:
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.
Configure authentication
Section titled “Configure authentication”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:
dotnet user-secrets set Parameters:openai-openai-apikey sk-your-api-keySet up client integration
Section titled “Set up client integration”To get started with the Aspire OpenAI client integration, install the package:
dotnet add package Aspire.OpenAI#:package Aspire.OpenAI@*<PackageReference Include="Aspire.OpenAI" Version="*" />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...}