openai/openai-dotnet
Publicmirrored from https://github.com/openai/openai-dotnetAvailable
examples/aspnet-core/Program.cs
73lines · modecode
| 1 | using System.ClientModel; |
| 2 | using OpenAI.Chat; |
| 3 | |
| 4 | var builder = WebApplication.CreateBuilder(args); |
| 5 | |
| 6 | // Add services to the container. |
| 7 | builder.Services.AddEndpointsApiExplorer(); |
| 8 | builder.Services.AddSwaggerGen(); |
| 9 | |
| 10 | builder.Services.AddSingleton<ChatClient>(serviceProvider => new ChatClient(builder.Configuration["OpenAI:Model"], |
| 11 | new ApiKeyCredential(builder.Configuration["OpenAI:ApiKey"] |
| 12 | ?? Environment.GetEnvironmentVariable("OPENAI_API_KEY") |
| 13 | ?? throw new InvalidOperationException("OpenAI API key not found"))) |
| 14 | ); |
| 15 | builder.Services.AddScoped<ChatHttpHandler>(); |
| 16 | |
| 17 | |
| 18 | var app = builder.Build(); |
| 19 | |
| 20 | // Configure the HTTP request pipeline. |
| 21 | if (app.Environment.IsDevelopment()) |
| 22 | { |
| 23 | app.UseSwagger(); |
| 24 | app.UseSwaggerUI(); |
| 25 | } |
| 26 | |
| 27 | app.UseHttpsRedirection(); |
| 28 | |
| 29 | var chatHandler = app.Services.GetRequiredService<ChatHttpHandler>(); |
| 30 | |
| 31 | app.MapPost("/chat/complete", chatHandler.HandleChatRequest); |
| 32 | |
| 33 | app.Run(); |
| 34 | |
| 35 | public class ChatHttpHandler |
| 36 | { |
| 37 | private readonly ChatClient _client; |
| 38 | private readonly ILogger<ChatHttpHandler> _logger; |
| 39 | |
| 40 | // Chat completion endpoint using injected ChatClient client |
| 41 | public ChatHttpHandler(ChatClient client, ILogger<ChatHttpHandler> logger) |
| 42 | { |
| 43 | _client = client; |
| 44 | _logger = logger; |
| 45 | } |
| 46 | |
| 47 | public async Task<ChatResponse> HandleChatRequest(ChatRequest request) |
| 48 | { |
| 49 | _logger.LogInformation("Handling chat request: {Message}", request.Message); |
| 50 | var completion = await _client.CompleteChatAsync(request.Message); |
| 51 | return new ChatResponse(completion.Value.Content[0].Text); |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | public class ChatRequest |
| 56 | { |
| 57 | public string Message { get; set; } |
| 58 | |
| 59 | public ChatRequest(string message) |
| 60 | { |
| 61 | Message = message; |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | public class ChatResponse |
| 66 | { |
| 67 | public string Response { get; set; } |
| 68 | |
| 69 | public ChatResponse(string response) |
| 70 | { |
| 71 | Response = response; |
| 72 | } |
| 73 | } |