This commit is contained in:
Simon Lübeß
2025-05-20 16:58:17 +02:00
parent e2764bd984
commit aeb0b87351
8 changed files with 584 additions and 75 deletions

View File

@ -1,3 +1,10 @@
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.
@ -17,30 +24,63 @@ if (app.Environment.IsDevelopment())
app.UseHttpsRedirection();
var summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
HttpClient client = new();
string? apiKey = app.Configuration.GetValue<string>("API:OpenAI");
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
app.MapGet("/weatherforecast", () =>
app.MapGet("/ephemeral_token", async () =>
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)]
))
.ToArray();
return forecast;
})
.WithName("GetWeatherForecast");
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<JsonObject>();
string? ephemeralToken = v?["client_secret"]?["value"]?.GetValue<string>();
double? expiresAt = v?["client_secret"]?["expires_at"]?.GetValue<double>();
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();
internal record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}