openai/openai-dotnet

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
joseharriaga/stable-api-listing

Branches

Tags

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

Clone

HTTPS

Download ZIP

examples/aspnet-core/Program.cs

73lines · modecode

1using 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"],
11 new 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{
23 app.UseSwagger();
24 app.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{
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
55public class ChatRequest
56{
57 public string Message { get; set; }
58
59 public ChatRequest(string message)
60 {
61 Message = message;
62 }
63}
64
65public class ChatResponse
66{
67 public string Response { get; set; }
68
69 public ChatResponse(string response)
70 {
71 Response = response;
72 }
73}