openai/openai-dotnet
Publicmirrored from https://github.com/openai/openai-dotnetAvailable
examples/aspnet-core/README.md
125lines · modecode
| 1 | # OpenAI ASP.NET Core Example |
| 2 | |
| 3 | This example demonstrates how to use the OpenAI .NET client library with ASP.NET Core's dependency injection container, registering a `ChatClient` as a singleton for optimal performance and resource usage. |
| 4 | |
| 5 | ## Features |
| 6 | |
| 7 | - **Singleton Registration**: ChatClient registered as singleton in DI container |
| 8 | - **Thread-Safe**: Demonstrates concurrent usage for chat completion endpoints |
| 9 | - **Configurable Model**: Model selection via configuration (appsettings.json) |
| 10 | - **Modern ASP.NET Core**: Uses minimal APIs with async/await patterns |
| 11 | |
| 12 | ## Prerequisites |
| 13 | |
| 14 | - .NET 8.0 or later |
| 15 | - OpenAI API key |
| 16 | |
| 17 | ## Setup |
| 18 | |
| 19 | 1. **Set your OpenAI API key** using one of these methods: |
| 20 | |
| 21 | **Environment Variable (Recommended):** |
| 22 | |
| 23 | ```powershell |
| 24 | $env:OPENAI_API_KEY = "your-api-key-here" |
| 25 | ``` |
| 26 | |
| 27 | **Configuration (appsettings.json):** |
| 28 | |
| 29 | ```json |
| 30 | { |
| 31 | "OpenAI": { |
| 32 | "Model": "gpt-4o-mini", |
| 33 | "ApiKey": "your-api-key-here" |
| 34 | } |
| 35 | } |
| 36 | ``` |
| 37 | |
| 38 | 2. **Install dependencies:** |
| 39 | |
| 40 | ```powershell |
| 41 | dotnet restore |
| 42 | ``` |
| 43 | |
| 44 | 3. **Run the application:** |
| 45 | |
| 46 | ```powershell |
| 47 | dotnet run |
| 48 | ``` |
| 49 | |
| 50 | ## API Endpoints |
| 51 | |
| 52 | ### Chat Completion |
| 53 | |
| 54 | - **POST** `/chat/complete` |
| 55 | - **Request Body:** |
| 56 | |
| 57 | ```json |
| 58 | { |
| 59 | "message": "Hello, how are you?" |
| 60 | } |
| 61 | ``` |
| 62 | |
| 63 | - **Response:** |
| 64 | |
| 65 | ```json |
| 66 | { |
| 67 | "response": "I'm doing well, thank you for asking! How can I help you today?" |
| 68 | } |
| 69 | ``` |
| 70 | |
| 71 | ## Testing with PowerShell |
| 72 | |
| 73 | **Chat Completion:** |
| 74 | |
| 75 | ```powershell |
| 76 | Invoke-RestMethod -Uri "https://localhost:5000/chat/complete" ` |
| 77 | -Method POST ` |
| 78 | -ContentType "application/json" ` |
| 79 | -Body '{"message": "What is the capital of France?"}' |
| 80 | ``` |
| 81 | |
| 82 | ## Key Implementation Details |
| 83 | |
| 84 | ### Singleton Registration |
| 85 | |
| 86 | ```csharp |
| 87 | builder.Services.AddSingleton<ChatClient>(serviceProvider => new ChatClient( |
| 88 | builder.Configuration["OpenAI:Model"], |
| 89 | new ApiKeyCredential(builder.Configuration["OpenAI:ApiKey"] |
| 90 | ?? Environment.GetEnvironmentVariable("OPENAI_API_KEY") |
| 91 | ?? throw new InvalidOperationException("OpenAI API key not found"))) |
| 92 | ); |
| 93 | ``` |
| 94 | |
| 95 | ### Dependency Injection Usage |
| 96 | |
| 97 | ```csharp |
| 98 | app.MapPost("/chat/complete", async (ChatRequest request, ChatClient client) => |
| 99 | { |
| 100 | var completion = await client.CompleteChatAsync(request.Message); |
| 101 | |
| 102 | return new ChatResponse(completion.Value.Content[0].Text); |
| 103 | }); |
| 104 | ``` |
| 105 | |
| 106 | ## Why Singleton? |
| 107 | |
| 108 | - **Thread-Safe**: `ChatClient` is thread-safe and can handle concurrent requests |
| 109 | - **Resource Efficient**: Reuses HTTP connections and avoids creating multiple instances |
| 110 | - **Performance**: Reduces object allocation overhead |
| 111 | - **Stateless**: Clients don't maintain per-request state |
| 112 | |
| 113 | ## Swagger UI |
| 114 | |
| 115 | When running in development mode, you can access the Swagger UI at: |
| 116 | |
| 117 | - `https://localhost:7071/swagger` |
| 118 | |
| 119 | This provides an interactive interface to test the API endpoints. |
| 120 | |
| 121 | ## Additional Resources |
| 122 | |
| 123 | - [Tutorial: Create a minimal API with ASP.NET Core](https://learn.microsoft.com/aspnet/core/tutorials/min-web-api) |
| 124 | - [.NET dependency injection](https://learn.microsoft.com/dotnet/core/extensions/dependency-injection) |
| 125 | - [Logging in C# and .NET](https://learn.microsoft.com/dotnet/core/extensions/logging) |