openai/openai-dotnet

Public

mirrored from https://github.com/openai/openai-dotnetAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
OpenAI_2.6.0

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

examples/aspnet-core/Program.cs

73lines · modeblame

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