| | | 1 | | using System.Text.Json; |
| | | 2 | | using Microsoft.Extensions.Logging; |
| | | 3 | | using Spectre.Console.Cli; |
| | | 4 | | using Spectre.Console; |
| | | 5 | | using OpenAiIntegration; |
| | | 6 | | using ContextProviders.Kicktipp; |
| | | 7 | | using EHonda.KicktippAi.Core; |
| | | 8 | | using Orchestrator.Commands.Shared; |
| | | 9 | | using Orchestrator.Infrastructure; |
| | | 10 | | using Orchestrator.Infrastructure.Factories; |
| | | 11 | | using Orchestrator.Infrastructure.Langfuse; |
| | | 12 | | |
| | | 13 | | namespace Orchestrator.Commands.Operations.RandomMatch; |
| | | 14 | | |
| | | 15 | | public class RandomMatchCommand : AsyncCommand<RandomMatchSettings> |
| | | 16 | | { |
| | | 17 | | private readonly IAnsiConsole _console; |
| | | 18 | | private readonly IFirebaseServiceFactory _firebaseServiceFactory; |
| | | 19 | | private readonly IKicktippClientFactory _kicktippClientFactory; |
| | | 20 | | private readonly IOpenAiServiceFactory _openAiServiceFactory; |
| | | 21 | | private readonly IContextProviderFactory _contextProviderFactory; |
| | | 22 | | private readonly ILogger<RandomMatchCommand> _logger; |
| | | 23 | | private readonly ILangfusePublicApiClient? _langfuseClient; |
| | | 24 | | |
| | 1 | 25 | | public RandomMatchCommand( |
| | 1 | 26 | | IAnsiConsole console, |
| | 1 | 27 | | IFirebaseServiceFactory firebaseServiceFactory, |
| | 1 | 28 | | IKicktippClientFactory kicktippClientFactory, |
| | 1 | 29 | | IOpenAiServiceFactory openAiServiceFactory, |
| | 1 | 30 | | IContextProviderFactory contextProviderFactory, |
| | 1 | 31 | | ILogger<RandomMatchCommand> logger, |
| | 1 | 32 | | ILangfusePublicApiClient? langfuseClient = null) |
| | | 33 | | { |
| | 1 | 34 | | _console = console; |
| | 1 | 35 | | _firebaseServiceFactory = firebaseServiceFactory; |
| | 1 | 36 | | _kicktippClientFactory = kicktippClientFactory; |
| | 1 | 37 | | _openAiServiceFactory = openAiServiceFactory; |
| | 1 | 38 | | _contextProviderFactory = contextProviderFactory; |
| | 1 | 39 | | _logger = logger; |
| | 1 | 40 | | _langfuseClient = langfuseClient; |
| | 1 | 41 | | } |
| | | 42 | | |
| | | 43 | | protected override async Task<int> ExecuteAsync(CommandContext context, RandomMatchSettings settings, CancellationTo |
| | | 44 | | { |
| | | 45 | | try |
| | | 46 | | { |
| | 1 | 47 | | var initialModel = string.IsNullOrWhiteSpace(settings.Model) ? "(competition default)" : settings.Model; |
| | 1 | 48 | | _console.MarkupLine($"[green]Random match command initialized with model:[/] [yellow]{initialModel}[/]"); |
| | | 49 | | |
| | 1 | 50 | | if (settings.WithJustification) |
| | | 51 | | { |
| | 1 | 52 | | _console.MarkupLine("[green]Justification output enabled - model reasoning will be captured[/]"); |
| | | 53 | | } |
| | | 54 | | |
| | 1 | 55 | | await ExecuteRandomMatchWorkflow(settings); |
| | | 56 | | |
| | 1 | 57 | | return 0; |
| | | 58 | | } |
| | 1 | 59 | | catch (Exception ex) |
| | | 60 | | { |
| | 1 | 61 | | _logger.LogError(ex, "Error executing random-match command"); |
| | 1 | 62 | | _console.MarkupLine($"[red]Error:[/] {ex.Message}"); |
| | 1 | 63 | | return 1; |
| | | 64 | | } |
| | 1 | 65 | | } |
| | | 66 | | |
| | | 67 | | private async Task ExecuteRandomMatchWorkflow(RandomMatchSettings settings) |
| | | 68 | | { |
| | | 69 | | // Start root OTel activity for Langfuse trace |
| | 1 | 70 | | using var activity = Telemetry.Source.StartActivity("random-match"); |
| | | 71 | | |
| | | 72 | | // RandomMatch is always a development trace |
| | 1 | 73 | | LangfuseActivityPropagation.SetEnvironment(activity, "development"); |
| | | 74 | | |
| | 1 | 75 | | var communityContext = settings.CommunityContext ?? settings.Community; |
| | 1 | 76 | | var competition = CompetitionResolver.ResolveCompetition(settings.Competition, settings.Community, communityCont |
| | 1 | 77 | | var modelConfig = PredictionServiceCommandSupport.CreateModelConfig(settings.Model, settings.ReasoningEffort); |
| | 1 | 78 | | var model = modelConfig.Model; |
| | 1 | 79 | | var repositoryCompetition = CompetitionResolver.ToRepositoryCompetitionArgument(competition); |
| | | 80 | | |
| | 1 | 81 | | if (settings.WithJustification && PredictionServiceCommandSupport.UsesLangfusePromptSource( |
| | 1 | 82 | | competition, |
| | 1 | 83 | | settings.Community, |
| | 1 | 84 | | communityContext, |
| | 1 | 85 | | settings.PromptSource, |
| | 1 | 86 | | bonusPrompt: false)) |
| | | 87 | | { |
| | 0 | 88 | | throw new NotSupportedException( |
| | 0 | 89 | | "WM 2026 hosted match prompts with justification are not supported yet. Use local prompts or omit --with |
| | | 90 | | } |
| | | 91 | | |
| | | 92 | | // Create services using factories |
| | 1 | 93 | | var kicktippClient = _kicktippClientFactory.CreateClient(); |
| | 1 | 94 | | var predictionService = PredictionServiceCommandSupport.CreatePredictionService( |
| | 1 | 95 | | _openAiServiceFactory, |
| | 1 | 96 | | _langfuseClient, |
| | 1 | 97 | | _console, |
| | 1 | 98 | | model, |
| | 1 | 99 | | competition, |
| | 1 | 100 | | settings.Community, |
| | 1 | 101 | | communityContext, |
| | 1 | 102 | | settings.PromptSource, |
| | 1 | 103 | | settings.LangfusePromptName, |
| | 1 | 104 | | settings.LangfusePromptLabel, |
| | 1 | 105 | | settings.LangfusePromptVersion, |
| | 1 | 106 | | modelConfig.ReasoningEffort, |
| | 1 | 107 | | maxOutputTokenCount: null, |
| | 1 | 108 | | bonusPrompt: false); |
| | | 109 | | |
| | | 110 | | // Create context provider using factory (community is used as context) |
| | 1 | 111 | | var contextProvider = _contextProviderFactory.CreateKicktippContextProvider( |
| | 1 | 112 | | kicktippClient, settings.Community, communityContext, repositoryCompetition); |
| | | 113 | | |
| | 1 | 114 | | var tokenUsageTracker = _openAiServiceFactory.GetTokenUsageTracker(); |
| | | 115 | | |
| | 1 | 116 | | _console.MarkupLine($"[dim]Match prompt:[/] [blue]{predictionService.GetMatchPromptPath(settings.WithJustificati |
| | | 117 | | |
| | | 118 | | // Create context repository for hybrid context lookup |
| | 1 | 119 | | var contextRepository = _firebaseServiceFactory.CreateContextRepository(repositoryCompetition); |
| | | 120 | | |
| | | 121 | | // Reset token usage tracker for this workflow |
| | 1 | 122 | | tokenUsageTracker.Reset(); |
| | | 123 | | |
| | 1 | 124 | | _console.MarkupLine($"[blue]Using community:[/] [yellow]{settings.Community}[/]"); |
| | 1 | 125 | | _console.MarkupLine($"[blue]Using community context:[/] [yellow]{communityContext}[/]"); |
| | 1 | 126 | | _console.MarkupLine($"[blue]Using competition:[/] [yellow]{competition}[/]"); |
| | 1 | 127 | | _console.MarkupLine("[blue]Getting current matchday matches...[/]"); |
| | | 128 | | |
| | | 129 | | // Step 1: Get current matchday matches |
| | 1 | 130 | | var matchesWithHistory = await kicktippClient.GetMatchesWithHistoryAsync(settings.Community); |
| | | 131 | | |
| | 1 | 132 | | if (!matchesWithHistory.Any()) |
| | | 133 | | { |
| | 1 | 134 | | _console.MarkupLine("[yellow]No matches found for current matchday[/]"); |
| | 1 | 135 | | return; |
| | | 136 | | } |
| | | 137 | | |
| | | 138 | | // Step 2: Pick a random match |
| | 1 | 139 | | var randomIndex = Random.Shared.Next(matchesWithHistory.Count); |
| | 1 | 140 | | var selectedMatchWithHistory = matchesWithHistory[randomIndex]; |
| | 1 | 141 | | var match = selectedMatchWithHistory.Match; |
| | | 142 | | |
| | 1 | 143 | | _console.MarkupLine($"[green]Found {matchesWithHistory.Count} matches for current matchday[/]"); |
| | 1 | 144 | | _console.MarkupLine($"[cyan]Randomly selected match {randomIndex + 1}/{matchesWithHistory.Count}:[/] [yellow]{ma |
| | | 145 | | |
| | | 146 | | // Set Langfuse trace-level attributes |
| | 1 | 147 | | var matchday = match.Matchday; |
| | 1 | 148 | | var sessionId = $"random-match-{matchday}-{settings.Community}"; |
| | 1 | 149 | | var traceTags = new[] { settings.Community, model, competition, "random-match" }; |
| | 1 | 150 | | LangfuseActivityPropagation.SetSessionId(activity, sessionId); |
| | 1 | 151 | | LangfuseActivityPropagation.SetTraceTags(activity, traceTags); |
| | 1 | 152 | | LangfuseActivityPropagation.SetTraceMetadata(activity, "community", settings.Community); |
| | 1 | 153 | | LangfuseActivityPropagation.SetTraceMetadata(activity, "communityContext", communityContext); |
| | 1 | 154 | | LangfuseActivityPropagation.SetTraceMetadata(activity, "competition", competition); |
| | 1 | 155 | | LangfuseActivityPropagation.SetTraceMetadata(activity, "matchday", matchday.ToString()); |
| | 1 | 156 | | LangfuseActivityPropagation.SetTraceMetadata(activity, "model", model); |
| | 1 | 157 | | LangfuseActivityPropagation.SetTraceMetadata(activity, "homeTeams", PredictionTelemetryMetadata.BuildDelimitedFi |
| | 1 | 158 | | LangfuseActivityPropagation.SetTraceMetadata(activity, "awayTeams", PredictionTelemetryMetadata.BuildDelimitedFi |
| | 1 | 159 | | LangfuseActivityPropagation.SetTraceMetadata(activity, "teams", PredictionTelemetryMetadata.BuildDelimitedFilter |
| | 1 | 160 | | LangfuseActivityPropagation.SetTraceMetadata(activity, "selectedMatch", $"{match.HomeTeam} vs {match.AwayTeam}", |
| | | 161 | | |
| | | 162 | | // Set trace input |
| | 1 | 163 | | var traceInput = new |
| | 1 | 164 | | { |
| | 1 | 165 | | community = settings.Community, |
| | 1 | 166 | | matchday, |
| | 1 | 167 | | model, |
| | 1 | 168 | | competition, |
| | 1 | 169 | | match = $"{match.HomeTeam} vs {match.AwayTeam}" |
| | 1 | 170 | | }; |
| | 1 | 171 | | activity?.SetTag("langfuse.trace.input", JsonSerializer.Serialize(traceInput)); |
| | | 172 | | |
| | 1 | 173 | | _console.MarkupLine($"[dim]Matchday: {matchday}[/]"); |
| | | 174 | | |
| | 1 | 175 | | if (match.IsCancelled) |
| | | 176 | | { |
| | 1 | 177 | | _console.MarkupLine($"[yellow] ⚠ {match.HomeTeam} vs {match.AwayTeam} is cancelled (Abgesagt). " + |
| | 1 | 178 | | $"Processing with inherited time - prediction may need re-evaluation when rescheduled.[/]"); |
| | | 179 | | } |
| | | 180 | | |
| | | 181 | | // Step 3: Generate prediction |
| | 1 | 182 | | _console.MarkupLine($"[yellow] → Generating prediction...[/]"); |
| | | 183 | | |
| | | 184 | | // Get context using hybrid approach (database first, fallback to on-demand) |
| | 1 | 185 | | var contextDocuments = await GetHybridContextAsync( |
| | 1 | 186 | | contextRepository, |
| | 1 | 187 | | contextProvider, |
| | 1 | 188 | | match.HomeTeam, |
| | 1 | 189 | | match.AwayTeam, |
| | 1 | 190 | | communityContext, |
| | 1 | 191 | | competition); |
| | | 192 | | |
| | 1 | 193 | | _console.MarkupLine($"[dim] Using {contextDocuments.Count} context documents[/]"); |
| | | 194 | | |
| | | 195 | | // Predict the match |
| | 1 | 196 | | var telemetryMetadata = new PredictionTelemetryMetadata( |
| | 1 | 197 | | HomeTeam: match.HomeTeam, |
| | 1 | 198 | | AwayTeam: match.AwayTeam, |
| | 1 | 199 | | RepredictionIndex: 0); |
| | | 200 | | |
| | 1 | 201 | | var prediction = await predictionService.PredictMatchAsync(match, contextDocuments, settings.WithJustification, |
| | | 202 | | |
| | 1 | 203 | | if (prediction != null) |
| | | 204 | | { |
| | 1 | 205 | | _console.MarkupLine($"[green] ✓ Prediction:[/] {prediction.HomeGoals}:{prediction.AwayGoals}"); |
| | 1 | 206 | | WriteJustificationIfNeeded(prediction, settings.WithJustification); |
| | | 207 | | |
| | | 208 | | // Set trace output |
| | 1 | 209 | | var traceOutput = new |
| | 1 | 210 | | { |
| | 1 | 211 | | match = $"{match.HomeTeam} vs {match.AwayTeam}", |
| | 1 | 212 | | prediction = $"{prediction.HomeGoals}:{prediction.AwayGoals}" |
| | 1 | 213 | | }; |
| | 1 | 214 | | activity?.SetTag("langfuse.trace.output", JsonSerializer.Serialize(traceOutput)); |
| | | 215 | | } |
| | | 216 | | else |
| | | 217 | | { |
| | 1 | 218 | | _console.MarkupLine($"[red] ✗ Failed to generate prediction[/]"); |
| | 1 | 219 | | activity?.SetTag("langfuse.trace.output", JsonSerializer.Serialize(new { error = "Failed to generate predict |
| | | 220 | | } |
| | | 221 | | |
| | | 222 | | // Display token usage summary |
| | 1 | 223 | | var summary = tokenUsageTracker.GetCompactSummary(); |
| | 1 | 224 | | _console.MarkupLine($"[dim]Token usage (uncached/cached/reasoning/output/$cost): {summary}[/]"); |
| | 1 | 225 | | } |
| | | 226 | | |
| | | 227 | | /// <summary> |
| | | 228 | | /// Retrieves all available context documents from the database for the given community context. |
| | | 229 | | /// </summary> |
| | | 230 | | private async Task<Dictionary<string, DocumentContext>> GetMatchContextDocumentsAsync( |
| | | 231 | | IContextRepository contextRepository, |
| | | 232 | | string homeTeam, |
| | | 233 | | string awayTeam, |
| | | 234 | | string communityContext, |
| | | 235 | | string competition) |
| | | 236 | | { |
| | 1 | 237 | | var contextDocuments = new Dictionary<string, DocumentContext>(); |
| | 1 | 238 | | var selection = MatchContextDocumentCatalog.ForMatch(homeTeam, awayTeam, communityContext, competition); |
| | | 239 | | |
| | 1 | 240 | | _console.MarkupLine($"[dim] Looking for {selection.RequiredDocumentNames.Count} specific context documents in |
| | | 241 | | |
| | | 242 | | try |
| | | 243 | | { |
| | 1 | 244 | | foreach (var documentName in selection.RequiredDocumentNames) |
| | | 245 | | { |
| | 1 | 246 | | var contextDoc = await contextRepository.GetLatestContextDocumentAsync(documentName, communityContext); |
| | 1 | 247 | | if (contextDoc != null) |
| | | 248 | | { |
| | 1 | 249 | | contextDocuments[documentName] = new DocumentContext(contextDoc.DocumentName, contextDoc.Content); |
| | 1 | 250 | | _console.MarkupLine($"[dim] ✓ Retrieved {documentName} (version {contextDoc.Version})[/]"); |
| | | 251 | | } |
| | | 252 | | else |
| | | 253 | | { |
| | 1 | 254 | | _console.MarkupLine($"[dim] ✗ Missing {documentName}[/]"); |
| | | 255 | | } |
| | 1 | 256 | | } |
| | | 257 | | |
| | 1 | 258 | | foreach (var documentName in selection.OptionalDocumentNames) |
| | | 259 | | { |
| | | 260 | | try |
| | | 261 | | { |
| | 1 | 262 | | var contextDoc = await contextRepository.GetLatestContextDocumentAsync(documentName, communityContex |
| | 1 | 263 | | if (contextDoc != null) |
| | | 264 | | { |
| | 1 | 265 | | contextDocuments[documentName] = new DocumentContext(contextDoc.DocumentName, contextDoc.Content |
| | 1 | 266 | | _console.MarkupLine($"[dim] ✓ Retrieved optional {documentName} (version {contextDoc.Versio |
| | | 267 | | } |
| | | 268 | | else |
| | | 269 | | { |
| | 1 | 270 | | _console.MarkupLine($"[dim] · Missing optional {documentName}[/]"); |
| | | 271 | | } |
| | 1 | 272 | | } |
| | 1 | 273 | | catch (Exception optEx) |
| | | 274 | | { |
| | 1 | 275 | | _console.MarkupLine($"[dim] · Failed optional {documentName}: {optEx.Message}[/]"); |
| | 1 | 276 | | } |
| | 1 | 277 | | } |
| | 1 | 278 | | } |
| | 1 | 279 | | catch (Exception ex) |
| | | 280 | | { |
| | 1 | 281 | | _console.MarkupLine($"[red] Warning: Failed to retrieve context from database: {ex.Message}[/]"); |
| | 1 | 282 | | } |
| | | 283 | | |
| | 1 | 284 | | return contextDocuments; |
| | 1 | 285 | | } |
| | | 286 | | |
| | | 287 | | /// <summary> |
| | | 288 | | /// Gets context documents using database first, falling back to on-demand context provider if needed. |
| | | 289 | | /// </summary> |
| | | 290 | | private async Task<List<DocumentContext>> GetHybridContextAsync( |
| | | 291 | | IContextRepository contextRepository, |
| | | 292 | | IKicktippContextProvider contextProvider, |
| | | 293 | | string homeTeam, |
| | | 294 | | string awayTeam, |
| | | 295 | | string communityContext, |
| | | 296 | | string competition) |
| | | 297 | | { |
| | 1 | 298 | | var contextDocuments = new List<DocumentContext>(); |
| | 1 | 299 | | var databaseContexts = await GetMatchContextDocumentsAsync( |
| | 1 | 300 | | contextRepository, |
| | 1 | 301 | | homeTeam, |
| | 1 | 302 | | awayTeam, |
| | 1 | 303 | | communityContext, |
| | 1 | 304 | | competition); |
| | | 305 | | |
| | 1 | 306 | | var requiredDocuments = MatchContextDocumentCatalog |
| | 1 | 307 | | .ForMatch(homeTeam, awayTeam, communityContext, competition) |
| | 1 | 308 | | .RequiredDocumentNames; |
| | | 309 | | |
| | 1 | 310 | | int requiredPresent = requiredDocuments.Count(d => databaseContexts.ContainsKey(d)); |
| | 1 | 311 | | int requiredTotal = requiredDocuments.Count; |
| | | 312 | | |
| | 1 | 313 | | if (requiredPresent == requiredTotal) |
| | | 314 | | { |
| | 1 | 315 | | _console.MarkupLine($"[green] Using {databaseContexts.Count} context documents from database (all require |
| | 1 | 316 | | contextDocuments.AddRange(databaseContexts.Values); |
| | | 317 | | } |
| | | 318 | | else |
| | | 319 | | { |
| | 1 | 320 | | _console.MarkupLine($"[yellow] Warning: Only found {requiredPresent}/{requiredTotal} required context doc |
| | | 321 | | |
| | 1 | 322 | | contextDocuments.AddRange(databaseContexts.Values); |
| | | 323 | | |
| | 1 | 324 | | var existingNames = new HashSet<string>(contextDocuments.Select(c => c.Name), StringComparer.OrdinalIgnoreCa |
| | 1 | 325 | | await foreach (var context in contextProvider.GetMatchContextAsync(homeTeam, awayTeam)) |
| | | 326 | | { |
| | 1 | 327 | | if (existingNames.Add(context.Name)) |
| | | 328 | | { |
| | 1 | 329 | | contextDocuments.Add(context); |
| | | 330 | | } |
| | | 331 | | } |
| | | 332 | | |
| | 1 | 333 | | _console.MarkupLine($"[yellow] Using {contextDocuments.Count} merged context documents (database + on-dem |
| | 1 | 334 | | } |
| | | 335 | | |
| | 1 | 336 | | if (CompetitionResolver.IsWorldCupCompetition(competition)) |
| | | 337 | | { |
| | 0 | 338 | | EnsureWorldCupRequiredContextPresent(contextDocuments, requiredDocuments); |
| | | 339 | | } |
| | | 340 | | |
| | 1 | 341 | | return contextDocuments; |
| | 1 | 342 | | } |
| | | 343 | | |
| | | 344 | | private static void EnsureWorldCupRequiredContextPresent( |
| | | 345 | | IReadOnlyList<DocumentContext> contextDocuments, |
| | | 346 | | IReadOnlyList<string> requiredDocuments) |
| | | 347 | | { |
| | 0 | 348 | | var presentDocumentNames = new HashSet<string>( |
| | 0 | 349 | | contextDocuments.Select(document => document.Name), |
| | 0 | 350 | | StringComparer.OrdinalIgnoreCase); |
| | 0 | 351 | | var missingDocumentNames = requiredDocuments |
| | 0 | 352 | | .Where(documentName => !presentDocumentNames.Contains(documentName)) |
| | 0 | 353 | | .ToList(); |
| | | 354 | | |
| | 0 | 355 | | if (missingDocumentNames.Count == 0) |
| | | 356 | | { |
| | 0 | 357 | | return; |
| | | 358 | | } |
| | | 359 | | |
| | 0 | 360 | | throw new InvalidOperationException( |
| | 0 | 361 | | "Missing required WM26 context documents after database and on-demand fallback: " + |
| | 0 | 362 | | $"{string.Join(", ", missingDocumentNames)}. Seed FIFA rankings with collect-context fifa and lineups with c |
| | | 363 | | } |
| | | 364 | | |
| | | 365 | | private void WriteJustificationIfNeeded(Prediction? prediction, bool includeJustification, bool fromDatabase = false |
| | | 366 | | { |
| | 1 | 367 | | if (!includeJustification || prediction == null) |
| | | 368 | | { |
| | 1 | 369 | | return; |
| | | 370 | | } |
| | | 371 | | |
| | 1 | 372 | | var sourceLabel = fromDatabase ? "stored prediction" : "model response"; |
| | | 373 | | |
| | 1 | 374 | | var justificationWriter = new JustificationConsoleWriter(_console); |
| | 1 | 375 | | justificationWriter.WriteJustification( |
| | 1 | 376 | | prediction.Justification, |
| | 1 | 377 | | "[dim] ↳ Justification:[/]", |
| | 1 | 378 | | " ", |
| | 1 | 379 | | $"[yellow] ↳ No justification available for this {sourceLabel}[/]"); |
| | 1 | 380 | | } |
| | | 381 | | } |