using System.ClientModel; using System.Diagnostics; using System.Text.Json.Nodes; using Microsoft.AspNetCore.Mvc.ModelBinding; using OpenAI.Models; using OpenAI.RealtimeConversation; var builder = WebApplication.CreateBuilder(args); // Add services to the container. // Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi builder.Services.AddOpenApi(); var app = builder.Build(); app.UseDefaultFiles(); app.MapStaticAssets(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.MapOpenApi(); } app.UseHttpsRedirection(); HttpClient client = new(); string? apiKey = app.Configuration.GetValue("API:OpenAI"); client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); app.MapGet("/ephemeral_token", async () => { if (apiKey == null) throw new Exception("API key not set"); #pragma warning disable OPENAI002 var options = new { model = "gpt-4o-realtime-preview", modalities = new []{"audio", "text"},//ConversationContentModalities.Audio | ConversationContentModalities.Text, voice = "ballad",//ConversationVoice.Ballad, // TODO: Vernünfigte Werte suchen //turn_detection = new { //}//ConversationTurnDetectionOptions.CreateServerVoiceActivityTurnDetectionOptions(0.5f, TimeSpan.FromMilliseconds(300), TimeSpan.FromMilliseconds(500), true) }; #pragma warning restore OPENAI002 try { JsonContent content = JsonContent.Create(options); HttpResponseMessage response = await client.PostAsync("https://api.openai.com/v1/realtime/sessions", content); Console.WriteLine($"Failed to create session: {response.RequestMessage.Content.ReadAsStringAsync().Result}"); if (response.IsSuccessStatusCode) { var v = await response.Content.ReadFromJsonAsync(); string? ephemeralToken = v?["client_secret"]?["value"]?.GetValue(); double? expiresAt = v?["client_secret"]?["expires_at"]?.GetValue(); return new { ephemeralToken, expiresAt, }; } else { Console.WriteLine($"Failed to create session: {response}"); } } catch (Exception e) { Console.WriteLine(e); throw; } return null; }).WithName("GetEphemeralToken"); app.MapFallbackToFile("/index.html"); app.Run();