| | | 1 | | using System.Globalization; |
| | | 2 | | using System.Text; |
| | | 3 | | using System.Text.Json; |
| | | 4 | | using EHonda.KicktippAi.Core; |
| | | 5 | | using Microsoft.Extensions.Logging; |
| | | 6 | | using NodaTime; |
| | | 7 | | using OpenAiIntegration; |
| | | 8 | | using Orchestrator.Commands.Observability; |
| | | 9 | | using Orchestrator.Infrastructure.Factories; |
| | | 10 | | using Spectre.Console; |
| | | 11 | | using Spectre.Console.Cli; |
| | | 12 | | |
| | | 13 | | namespace Orchestrator.Commands.Observability.ExportExperimentItem; |
| | | 14 | | |
| | | 15 | | public sealed class ExportExperimentItemCommand : AsyncCommand<ExportExperimentItemSettings> |
| | | 16 | | { |
| | 0 | 17 | | private static readonly DateTimeZone BundesligaTimeZone = DateTimeZoneProviders.Tzdb["Europe/Berlin"]; |
| | 0 | 18 | | private static readonly JsonSerializerOptions OutputJsonOptions = new() |
| | 0 | 19 | | { |
| | 0 | 20 | | PropertyNamingPolicy = JsonNamingPolicy.CamelCase, |
| | 0 | 21 | | WriteIndented = true |
| | 0 | 22 | | }; |
| | | 23 | | |
| | | 24 | | private readonly IAnsiConsole _console; |
| | | 25 | | private readonly IFirebaseServiceFactory _firebaseServiceFactory; |
| | | 26 | | private readonly ILogger<ExportExperimentItemCommand> _logger; |
| | | 27 | | |
| | 0 | 28 | | public ExportExperimentItemCommand( |
| | 0 | 29 | | IAnsiConsole console, |
| | 0 | 30 | | IFirebaseServiceFactory firebaseServiceFactory, |
| | 0 | 31 | | ILogger<ExportExperimentItemCommand> logger) |
| | | 32 | | { |
| | 0 | 33 | | _console = console; |
| | 0 | 34 | | _firebaseServiceFactory = firebaseServiceFactory; |
| | 0 | 35 | | _logger = logger; |
| | 0 | 36 | | } |
| | | 37 | | |
| | | 38 | | public override async Task<int> ExecuteAsync(CommandContext context, ExportExperimentItemSettings settings) |
| | | 39 | | { |
| | | 40 | | try |
| | | 41 | | { |
| | 0 | 42 | | _console.MarkupLine($"[green]Exporting experiment item for:[/] [yellow]{Markup.Escape(settings.HomeTeam)}[/] |
| | | 43 | | |
| | 0 | 44 | | var predictionRepository = _firebaseServiceFactory.CreatePredictionRepository(); |
| | 0 | 45 | | var contextRepository = _firebaseServiceFactory.CreateContextRepository(); |
| | 0 | 46 | | var matchOutcomeRepository = _firebaseServiceFactory.CreateMatchOutcomeRepository(); |
| | | 47 | | |
| | 0 | 48 | | var reconstructionService = new MatchPromptReconstructionService( |
| | 0 | 49 | | predictionRepository, |
| | 0 | 50 | | contextRepository, |
| | 0 | 51 | | new InstructionsTemplateProvider(PromptsFileProvider.Create())); |
| | | 52 | | |
| | 0 | 53 | | var evaluationTime = EvaluationTimeParser.ParseOrNull(settings.EvaluationTime); |
| | | 54 | | |
| | 0 | 55 | | var storedMatch = await predictionRepository.GetStoredMatchAsync( |
| | 0 | 56 | | settings.HomeTeam, |
| | 0 | 57 | | settings.AwayTeam, |
| | 0 | 58 | | settings.Matchday!.Value, |
| | 0 | 59 | | evaluationTime is null ? settings.Model : null, |
| | 0 | 60 | | evaluationTime is null ? settings.CommunityContext : null); |
| | | 61 | | |
| | 0 | 62 | | if (storedMatch is null) |
| | | 63 | | { |
| | 0 | 64 | | _console.MarkupLine($"[red]Stored match not found on matchday {settings.Matchday}:[/] {Markup.Escape(set |
| | 0 | 65 | | return 1; |
| | | 66 | | } |
| | | 67 | | |
| | 0 | 68 | | var promptMatch = RehydrateForPromptOutput(storedMatch); |
| | | 69 | | ReconstructedMatchPredictionPrompt? reconstructedPrompt; |
| | 0 | 70 | | if (evaluationTime is null) |
| | | 71 | | { |
| | 0 | 72 | | reconstructedPrompt = await reconstructionService.ReconstructMatchPredictionPromptAsync( |
| | 0 | 73 | | promptMatch, |
| | 0 | 74 | | settings.Model, |
| | 0 | 75 | | settings.CommunityContext, |
| | 0 | 76 | | settings.WithJustification); |
| | | 77 | | } |
| | | 78 | | else |
| | | 79 | | { |
| | 0 | 80 | | var selection = MatchContextDocumentCatalog.ForMatch( |
| | 0 | 81 | | promptMatch.HomeTeam, |
| | 0 | 82 | | promptMatch.AwayTeam, |
| | 0 | 83 | | settings.CommunityContext); |
| | | 84 | | |
| | 0 | 85 | | reconstructedPrompt = await reconstructionService.ReconstructMatchPredictionPromptAtTimestampAsync( |
| | 0 | 86 | | promptMatch, |
| | 0 | 87 | | settings.Model, |
| | 0 | 88 | | settings.CommunityContext, |
| | 0 | 89 | | evaluationTime.Value, |
| | 0 | 90 | | selection.RequiredDocumentNames, |
| | 0 | 91 | | selection.OptionalDocumentNames, |
| | 0 | 92 | | settings.WithJustification); |
| | | 93 | | } |
| | | 94 | | |
| | 0 | 95 | | if (reconstructedPrompt is null) |
| | | 96 | | { |
| | 0 | 97 | | _console.MarkupLine("[red]No stored prediction metadata found for that match/model/community combination |
| | 0 | 98 | | return 1; |
| | | 99 | | } |
| | | 100 | | |
| | 0 | 101 | | var outcomes = await matchOutcomeRepository.GetMatchdayOutcomesAsync( |
| | 0 | 102 | | settings.Matchday.Value, |
| | 0 | 103 | | settings.CommunityContext); |
| | | 104 | | |
| | 0 | 105 | | var outcome = outcomes.FirstOrDefault(candidate => |
| | 0 | 106 | | string.Equals(candidate.HomeTeam, settings.HomeTeam, StringComparison.OrdinalIgnoreCase) && |
| | 0 | 107 | | string.Equals(candidate.AwayTeam, settings.AwayTeam, StringComparison.OrdinalIgnoreCase)); |
| | | 108 | | |
| | 0 | 109 | | if (outcome is null) |
| | | 110 | | { |
| | 0 | 111 | | _console.MarkupLine("[red]No persisted match outcome was found for the selected match.[/]"); |
| | 0 | 112 | | return 1; |
| | | 113 | | } |
| | | 114 | | |
| | 0 | 115 | | if (!outcome.HasOutcome || outcome.HomeGoals is null || outcome.AwayGoals is null) |
| | | 116 | | { |
| | 0 | 117 | | _console.MarkupLine("[red]The selected match does not have a completed persisted outcome yet.[/]"); |
| | 0 | 118 | | return 1; |
| | | 119 | | } |
| | | 120 | | |
| | 0 | 121 | | var export = BuildExport(reconstructedPrompt, outcome); |
| | 0 | 122 | | var outputPath = ResolveOutputPath(settings, export.DatasetItem.Metadata); |
| | 0 | 123 | | Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); |
| | | 124 | | |
| | 0 | 125 | | await File.WriteAllTextAsync( |
| | 0 | 126 | | outputPath, |
| | 0 | 127 | | JsonSerializer.Serialize(export, OutputJsonOptions)); |
| | | 128 | | |
| | 0 | 129 | | _console.MarkupLine($"[green]Wrote experiment item:[/] [yellow]{Markup.Escape(outputPath)}[/]"); |
| | 0 | 130 | | _console.MarkupLine($"[blue]Dataset item id:[/] {Markup.Escape(export.DatasetItem.Id)}"); |
| | 0 | 131 | | _console.MarkupLine($"[blue]{(evaluationTime is null ? "Prediction timestamp" : "Reconstruction timestamp")} |
| | 0 | 132 | | _console.MarkupLine($"[blue]Outcome:[/] {outcome.HomeGoals}:{outcome.AwayGoals} ({outcome.Availability})"); |
| | | 133 | | |
| | 0 | 134 | | return 0; |
| | | 135 | | } |
| | 0 | 136 | | catch (Exception ex) |
| | | 137 | | { |
| | 0 | 138 | | _logger.LogError(ex, "Error exporting experiment item"); |
| | 0 | 139 | | _console.MarkupLine($"[red]Error:[/] {Markup.Escape(ex.Message)}"); |
| | 0 | 140 | | return 1; |
| | | 141 | | } |
| | 0 | 142 | | } |
| | | 143 | | |
| | | 144 | | private static ExportedExperimentItem BuildExport( |
| | | 145 | | ReconstructedMatchPredictionPrompt reconstructedPrompt, |
| | | 146 | | PersistedMatchOutcome outcome) |
| | | 147 | | { |
| | 0 | 148 | | using var matchJsonDocument = JsonDocument.Parse(reconstructedPrompt.MatchJson); |
| | 0 | 149 | | var tippSpielId = outcome.TippSpielId ?? throw new InvalidOperationException( |
| | 0 | 150 | | $"Persisted outcome for {outcome.HomeTeam} vs {outcome.AwayTeam} is missing tippspielId."); |
| | | 151 | | |
| | 0 | 152 | | var metadata = new MatchExperimentMetadata( |
| | 0 | 153 | | reconstructedPrompt.CommunityContext, |
| | 0 | 154 | | outcome.Competition, |
| | 0 | 155 | | reconstructedPrompt.Match.Matchday, |
| | 0 | 156 | | reconstructedPrompt.Match.HomeTeam, |
| | 0 | 157 | | reconstructedPrompt.Match.AwayTeam, |
| | 0 | 158 | | tippSpielId, |
| | 0 | 159 | | reconstructedPrompt.Model, |
| | 0 | 160 | | reconstructedPrompt.IncludeJustification, |
| | 0 | 161 | | reconstructedPrompt.PromptTimestamp, |
| | 0 | 162 | | reconstructedPrompt.PromptTemplatePath, |
| | 0 | 163 | | reconstructedPrompt.ContextDocumentNames, |
| | 0 | 164 | | reconstructedPrompt.ResolvedContextDocuments |
| | 0 | 165 | | .Select(document => new MatchExperimentResolvedContextDocument( |
| | 0 | 166 | | document.DocumentName, |
| | 0 | 167 | | document.Version, |
| | 0 | 168 | | document.CreatedAt)) |
| | 0 | 169 | | .ToList() |
| | 0 | 170 | | .AsReadOnly(), |
| | 0 | 171 | | new MatchExperimentHistoricalPrediction( |
| | 0 | 172 | | outcome.HomeGoals!.Value, |
| | 0 | 173 | | outcome.AwayGoals!.Value)); |
| | | 174 | | |
| | 0 | 175 | | return new ExportedExperimentItem( |
| | 0 | 176 | | new MatchExperimentDatasetItem( |
| | 0 | 177 | | BuildHostedDatasetItemId(outcome.Competition, outcome.CommunityContext, tippSpielId), |
| | 0 | 178 | | matchJsonDocument.RootElement.Clone(), |
| | 0 | 179 | | new MatchExperimentExpectedOutput( |
| | 0 | 180 | | outcome.HomeGoals!.Value, |
| | 0 | 181 | | outcome.AwayGoals!.Value, |
| | 0 | 182 | | outcome.Availability.ToString()), |
| | 0 | 183 | | metadata), |
| | 0 | 184 | | new MatchExperimentRunnerPayload( |
| | 0 | 185 | | reconstructedPrompt.SystemPrompt, |
| | 0 | 186 | | reconstructedPrompt.MatchJson)); |
| | 0 | 187 | | } |
| | | 188 | | |
| | | 189 | | private static Match RehydrateForPromptOutput(Match match) |
| | | 190 | | { |
| | 0 | 191 | | var instant = match.StartsAt.ToInstant(); |
| | 0 | 192 | | var offset = BundesligaTimeZone.GetUtcOffset(instant); |
| | 0 | 193 | | var localizedStartsAt = instant.InZone(DateTimeZone.ForOffset(offset)); |
| | 0 | 194 | | return new Match(match.HomeTeam, match.AwayTeam, localizedStartsAt, match.Matchday, match.IsCancelled); |
| | | 195 | | } |
| | | 196 | | |
| | | 197 | | private static string ResolveOutputPath(ExportExperimentItemSettings settings, MatchExperimentMetadata metadata) |
| | | 198 | | { |
| | 0 | 199 | | if (!string.IsNullOrWhiteSpace(settings.OutputPath)) |
| | | 200 | | { |
| | 0 | 201 | | return Path.GetFullPath(settings.OutputPath); |
| | | 202 | | } |
| | | 203 | | |
| | 0 | 204 | | var fileName = $"{metadata.Matchday:00}-{Slugify(metadata.HomeTeam)}-vs-{Slugify(metadata.AwayTeam)}-{Slugify(me |
| | 0 | 205 | | return Path.GetFullPath(Path.Combine("artifacts", "langfuse-runner-spike", fileName)); |
| | | 206 | | } |
| | | 207 | | |
| | | 208 | | private static string BuildHostedDatasetItemId(string competition, string communityContext, string tippSpielId) |
| | | 209 | | { |
| | 0 | 210 | | return string.Join( |
| | 0 | 211 | | "__", |
| | 0 | 212 | | Slugify(competition), |
| | 0 | 213 | | Slugify(communityContext), |
| | 0 | 214 | | $"ts{Slugify(tippSpielId)}"); |
| | | 215 | | } |
| | | 216 | | |
| | | 217 | | private static string Slugify(string value) |
| | | 218 | | { |
| | 0 | 219 | | var normalized = value.Normalize(NormalizationForm.FormD); |
| | 0 | 220 | | var builder = new StringBuilder(normalized.Length); |
| | | 221 | | |
| | 0 | 222 | | foreach (var character in normalized) |
| | | 223 | | { |
| | 0 | 224 | | if (CharUnicodeInfo.GetUnicodeCategory(character) == UnicodeCategory.NonSpacingMark) |
| | | 225 | | { |
| | | 226 | | continue; |
| | | 227 | | } |
| | | 228 | | |
| | 0 | 229 | | if (char.IsLetterOrDigit(character)) |
| | | 230 | | { |
| | 0 | 231 | | builder.Append(char.ToLowerInvariant(character)); |
| | 0 | 232 | | continue; |
| | | 233 | | } |
| | | 234 | | |
| | 0 | 235 | | if (builder.Length == 0 || builder[^1] == '-') |
| | | 236 | | { |
| | | 237 | | continue; |
| | | 238 | | } |
| | | 239 | | |
| | 0 | 240 | | builder.Append('-'); |
| | | 241 | | } |
| | | 242 | | |
| | 0 | 243 | | return builder.ToString().Trim('-'); |
| | | 244 | | } |
| | | 245 | | } |