| | | 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 | | |
| | | 12 | | namespace Orchestrator.Commands.Operations.RandomMatch; |
| | | 13 | | |
| | | 14 | | public class RandomMatchCommand : AsyncCommand<RandomMatchSettings> |
| | | 15 | | { |
| | | 16 | | private readonly IAnsiConsole _console; |
| | | 17 | | private readonly IFirebaseServiceFactory _firebaseServiceFactory; |
| | | 18 | | private readonly IKicktippClientFactory _kicktippClientFactory; |
| | | 19 | | private readonly IOpenAiServiceFactory _openAiServiceFactory; |
| | | 20 | | private readonly IContextProviderFactory _contextProviderFactory; |
| | | 21 | | private readonly ILogger<RandomMatchCommand> _logger; |
| | | 22 | | |
| | 1 | 23 | | public RandomMatchCommand( |
| | 1 | 24 | | IAnsiConsole console, |
| | 1 | 25 | | IFirebaseServiceFactory firebaseServiceFactory, |
| | 1 | 26 | | IKicktippClientFactory kicktippClientFactory, |
| | 1 | 27 | | IOpenAiServiceFactory openAiServiceFactory, |
| | 1 | 28 | | IContextProviderFactory contextProviderFactory, |
| | 1 | 29 | | ILogger<RandomMatchCommand> logger) |
| | | 30 | | { |
| | 1 | 31 | | _console = console; |
| | 1 | 32 | | _firebaseServiceFactory = firebaseServiceFactory; |
| | 1 | 33 | | _kicktippClientFactory = kicktippClientFactory; |
| | 1 | 34 | | _openAiServiceFactory = openAiServiceFactory; |
| | 1 | 35 | | _contextProviderFactory = contextProviderFactory; |
| | 1 | 36 | | _logger = logger; |
| | 1 | 37 | | } |
| | | 38 | | |
| | | 39 | | public override async Task<int> ExecuteAsync(CommandContext context, RandomMatchSettings settings) |
| | | 40 | | { |
| | | 41 | | try |
| | | 42 | | { |
| | 1 | 43 | | _console.MarkupLine($"[green]Random match command initialized with model:[/] [yellow]{settings.Model}[/]"); |
| | | 44 | | |
| | 1 | 45 | | if (settings.WithJustification) |
| | | 46 | | { |
| | 1 | 47 | | _console.MarkupLine("[green]Justification output enabled - model reasoning will be captured[/]"); |
| | | 48 | | } |
| | | 49 | | |
| | 1 | 50 | | await ExecuteRandomMatchWorkflow(settings); |
| | | 51 | | |
| | 1 | 52 | | return 0; |
| | | 53 | | } |
| | 1 | 54 | | catch (Exception ex) |
| | | 55 | | { |
| | 1 | 56 | | _logger.LogError(ex, "Error executing random-match command"); |
| | 1 | 57 | | _console.MarkupLine($"[red]Error:[/] {ex.Message}"); |
| | 1 | 58 | | return 1; |
| | | 59 | | } |
| | 1 | 60 | | } |
| | | 61 | | |
| | | 62 | | private async Task ExecuteRandomMatchWorkflow(RandomMatchSettings settings) |
| | | 63 | | { |
| | | 64 | | // Start root OTel activity for Langfuse trace |
| | 1 | 65 | | using var activity = Telemetry.Source.StartActivity("random-match"); |
| | | 66 | | |
| | | 67 | | // RandomMatch is always a development trace |
| | 1 | 68 | | LangfuseActivityPropagation.SetEnvironment(activity, "development"); |
| | | 69 | | |
| | | 70 | | // Create services using factories |
| | 1 | 71 | | var kicktippClient = _kicktippClientFactory.CreateClient(); |
| | 1 | 72 | | var predictionService = _openAiServiceFactory.CreatePredictionService(settings.Model); |
| | | 73 | | |
| | | 74 | | // Create context provider using factory (community is used as context) |
| | 1 | 75 | | var contextProvider = _contextProviderFactory.CreateKicktippContextProvider( |
| | 1 | 76 | | kicktippClient, settings.Community, settings.Community); |
| | | 77 | | |
| | 1 | 78 | | var tokenUsageTracker = _openAiServiceFactory.GetTokenUsageTracker(); |
| | | 79 | | |
| | 1 | 80 | | _console.MarkupLine($"[dim]Match prompt:[/] [blue]{predictionService.GetMatchPromptPath(settings.WithJustificati |
| | | 81 | | |
| | | 82 | | // Create context repository for hybrid context lookup |
| | 1 | 83 | | var contextRepository = _firebaseServiceFactory.CreateContextRepository(); |
| | | 84 | | |
| | | 85 | | // Reset token usage tracker for this workflow |
| | 1 | 86 | | tokenUsageTracker.Reset(); |
| | | 87 | | |
| | 1 | 88 | | _console.MarkupLine($"[blue]Using community:[/] [yellow]{settings.Community}[/]"); |
| | 1 | 89 | | _console.MarkupLine("[blue]Getting current matchday matches...[/]"); |
| | | 90 | | |
| | | 91 | | // Step 1: Get current matchday matches |
| | 1 | 92 | | var matchesWithHistory = await kicktippClient.GetMatchesWithHistoryAsync(settings.Community); |
| | | 93 | | |
| | 1 | 94 | | if (!matchesWithHistory.Any()) |
| | | 95 | | { |
| | 1 | 96 | | _console.MarkupLine("[yellow]No matches found for current matchday[/]"); |
| | 1 | 97 | | return; |
| | | 98 | | } |
| | | 99 | | |
| | | 100 | | // Step 2: Pick a random match |
| | 1 | 101 | | var randomIndex = Random.Shared.Next(matchesWithHistory.Count); |
| | 1 | 102 | | var selectedMatchWithHistory = matchesWithHistory[randomIndex]; |
| | 1 | 103 | | var match = selectedMatchWithHistory.Match; |
| | | 104 | | |
| | 1 | 105 | | _console.MarkupLine($"[green]Found {matchesWithHistory.Count} matches for current matchday[/]"); |
| | 1 | 106 | | _console.MarkupLine($"[cyan]Randomly selected match {randomIndex + 1}/{matchesWithHistory.Count}:[/] [yellow]{ma |
| | | 107 | | |
| | | 108 | | // Set Langfuse trace-level attributes |
| | 1 | 109 | | var matchday = match.Matchday; |
| | 1 | 110 | | var sessionId = $"random-match-{matchday}-{settings.Community}"; |
| | 1 | 111 | | var traceTags = new[] { settings.Community, settings.Model, "random-match" }; |
| | 1 | 112 | | LangfuseActivityPropagation.SetSessionId(activity, sessionId); |
| | 1 | 113 | | LangfuseActivityPropagation.SetTraceTags(activity, traceTags); |
| | 1 | 114 | | LangfuseActivityPropagation.SetTraceMetadata(activity, "community", settings.Community); |
| | 1 | 115 | | LangfuseActivityPropagation.SetTraceMetadata(activity, "kicktipp-season", KicktippSeasonMetadata.Current); |
| | 1 | 116 | | LangfuseActivityPropagation.SetTraceMetadata(activity, "matchday", matchday.ToString()); |
| | 1 | 117 | | LangfuseActivityPropagation.SetTraceMetadata(activity, "model", settings.Model); |
| | 1 | 118 | | LangfuseActivityPropagation.SetTraceMetadata(activity, "homeTeams", PredictionTelemetryMetadata.BuildDelimitedFi |
| | 1 | 119 | | LangfuseActivityPropagation.SetTraceMetadata(activity, "awayTeams", PredictionTelemetryMetadata.BuildDelimitedFi |
| | 1 | 120 | | LangfuseActivityPropagation.SetTraceMetadata(activity, "teams", PredictionTelemetryMetadata.BuildDelimitedFilter |
| | 1 | 121 | | LangfuseActivityPropagation.SetTraceMetadata(activity, "selectedMatch", $"{match.HomeTeam} vs {match.AwayTeam}", |
| | | 122 | | |
| | | 123 | | // Set trace input |
| | 1 | 124 | | var traceInput = new |
| | 1 | 125 | | { |
| | 1 | 126 | | community = settings.Community, |
| | 1 | 127 | | matchday, |
| | 1 | 128 | | model = settings.Model, |
| | 1 | 129 | | match = $"{match.HomeTeam} vs {match.AwayTeam}" |
| | 1 | 130 | | }; |
| | 1 | 131 | | activity?.SetTag("langfuse.trace.input", JsonSerializer.Serialize(traceInput)); |
| | | 132 | | |
| | 1 | 133 | | _console.MarkupLine($"[dim]Matchday: {matchday}[/]"); |
| | | 134 | | |
| | 1 | 135 | | if (match.IsCancelled) |
| | | 136 | | { |
| | 1 | 137 | | _console.MarkupLine($"[yellow] ⚠ {match.HomeTeam} vs {match.AwayTeam} is cancelled (Abgesagt). " + |
| | 1 | 138 | | $"Processing with inherited time - prediction may need re-evaluation when rescheduled.[/]"); |
| | | 139 | | } |
| | | 140 | | |
| | | 141 | | // Step 3: Generate prediction |
| | 1 | 142 | | _console.MarkupLine($"[yellow] → Generating prediction...[/]"); |
| | | 143 | | |
| | | 144 | | // Get context using hybrid approach (database first, fallback to on-demand) |
| | 1 | 145 | | var contextDocuments = await GetHybridContextAsync( |
| | 1 | 146 | | contextRepository, |
| | 1 | 147 | | contextProvider, |
| | 1 | 148 | | match.HomeTeam, |
| | 1 | 149 | | match.AwayTeam, |
| | 1 | 150 | | settings.Community); |
| | | 151 | | |
| | 1 | 152 | | _console.MarkupLine($"[dim] Using {contextDocuments.Count} context documents[/]"); |
| | | 153 | | |
| | | 154 | | // Predict the match |
| | 1 | 155 | | var telemetryMetadata = new PredictionTelemetryMetadata( |
| | 1 | 156 | | HomeTeam: match.HomeTeam, |
| | 1 | 157 | | AwayTeam: match.AwayTeam, |
| | 1 | 158 | | RepredictionIndex: 0); |
| | | 159 | | |
| | 1 | 160 | | var prediction = await predictionService.PredictMatchAsync(match, contextDocuments, settings.WithJustification, |
| | | 161 | | |
| | 1 | 162 | | if (prediction != null) |
| | | 163 | | { |
| | 1 | 164 | | _console.MarkupLine($"[green] ✓ Prediction:[/] {prediction.HomeGoals}:{prediction.AwayGoals}"); |
| | 1 | 165 | | WriteJustificationIfNeeded(prediction, settings.WithJustification); |
| | | 166 | | |
| | | 167 | | // Set trace output |
| | 1 | 168 | | var traceOutput = new |
| | 1 | 169 | | { |
| | 1 | 170 | | match = $"{match.HomeTeam} vs {match.AwayTeam}", |
| | 1 | 171 | | prediction = $"{prediction.HomeGoals}:{prediction.AwayGoals}" |
| | 1 | 172 | | }; |
| | 1 | 173 | | activity?.SetTag("langfuse.trace.output", JsonSerializer.Serialize(traceOutput)); |
| | | 174 | | } |
| | | 175 | | else |
| | | 176 | | { |
| | 1 | 177 | | _console.MarkupLine($"[red] ✗ Failed to generate prediction[/]"); |
| | 1 | 178 | | activity?.SetTag("langfuse.trace.output", JsonSerializer.Serialize(new { error = "Failed to generate predict |
| | | 179 | | } |
| | | 180 | | |
| | | 181 | | // Display token usage summary |
| | 1 | 182 | | var summary = tokenUsageTracker.GetCompactSummary(); |
| | 1 | 183 | | _console.MarkupLine($"[dim]Token usage (uncached/cached/reasoning/output/$cost): {summary}[/]"); |
| | 1 | 184 | | } |
| | | 185 | | |
| | | 186 | | /// <summary> |
| | | 187 | | /// Retrieves all available context documents from the database for the given community context. |
| | | 188 | | /// </summary> |
| | | 189 | | private async Task<Dictionary<string, DocumentContext>> GetMatchContextDocumentsAsync( |
| | | 190 | | IContextRepository contextRepository, |
| | | 191 | | string homeTeam, |
| | | 192 | | string awayTeam, |
| | | 193 | | string communityContext) |
| | | 194 | | { |
| | 1 | 195 | | var contextDocuments = new Dictionary<string, DocumentContext>(); |
| | 1 | 196 | | var homeAbbreviation = GetTeamAbbreviation(homeTeam); |
| | 1 | 197 | | var awayAbbreviation = GetTeamAbbreviation(awayTeam); |
| | | 198 | | |
| | 1 | 199 | | var requiredDocuments = new[] |
| | 1 | 200 | | { |
| | 1 | 201 | | "bundesliga-standings.csv", |
| | 1 | 202 | | $"community-rules-{communityContext}.md", |
| | 1 | 203 | | $"recent-history-{homeAbbreviation}.csv", |
| | 1 | 204 | | $"recent-history-{awayAbbreviation}.csv", |
| | 1 | 205 | | $"home-history-{homeAbbreviation}.csv", |
| | 1 | 206 | | $"away-history-{awayAbbreviation}.csv", |
| | 1 | 207 | | $"head-to-head-{homeAbbreviation}-vs-{awayAbbreviation}.csv" |
| | 1 | 208 | | }; |
| | | 209 | | |
| | 1 | 210 | | var optionalDocuments = new[] |
| | 1 | 211 | | { |
| | 1 | 212 | | $"{homeAbbreviation}-transfers.csv", |
| | 1 | 213 | | $"{awayAbbreviation}-transfers.csv" |
| | 1 | 214 | | }; |
| | | 215 | | |
| | 1 | 216 | | _console.MarkupLine($"[dim] Looking for {requiredDocuments.Length} specific context documents in database[/]" |
| | | 217 | | |
| | | 218 | | try |
| | | 219 | | { |
| | 1 | 220 | | foreach (var documentName in requiredDocuments) |
| | | 221 | | { |
| | 1 | 222 | | var contextDoc = await contextRepository.GetLatestContextDocumentAsync(documentName, communityContext); |
| | 1 | 223 | | if (contextDoc != null) |
| | | 224 | | { |
| | 1 | 225 | | contextDocuments[documentName] = new DocumentContext(contextDoc.DocumentName, contextDoc.Content); |
| | 1 | 226 | | _console.MarkupLine($"[dim] ✓ Retrieved {documentName} (version {contextDoc.Version})[/]"); |
| | | 227 | | } |
| | | 228 | | else |
| | | 229 | | { |
| | 1 | 230 | | _console.MarkupLine($"[dim] ✗ Missing {documentName}[/]"); |
| | | 231 | | } |
| | 1 | 232 | | } |
| | | 233 | | |
| | 1 | 234 | | foreach (var documentName in optionalDocuments) |
| | | 235 | | { |
| | | 236 | | try |
| | | 237 | | { |
| | 1 | 238 | | var contextDoc = await contextRepository.GetLatestContextDocumentAsync(documentName, communityContex |
| | 1 | 239 | | if (contextDoc != null) |
| | | 240 | | { |
| | 1 | 241 | | contextDocuments[documentName] = new DocumentContext(contextDoc.DocumentName, contextDoc.Content |
| | 1 | 242 | | _console.MarkupLine($"[dim] ✓ Retrieved optional {documentName} (version {contextDoc.Versio |
| | | 243 | | } |
| | | 244 | | else |
| | | 245 | | { |
| | 1 | 246 | | _console.MarkupLine($"[dim] · Missing optional {documentName}[/]"); |
| | | 247 | | } |
| | 1 | 248 | | } |
| | 1 | 249 | | catch (Exception optEx) |
| | | 250 | | { |
| | 1 | 251 | | _console.MarkupLine($"[dim] · Failed optional {documentName}: {optEx.Message}[/]"); |
| | 1 | 252 | | } |
| | 1 | 253 | | } |
| | 1 | 254 | | } |
| | 1 | 255 | | catch (Exception ex) |
| | | 256 | | { |
| | 1 | 257 | | _console.MarkupLine($"[red] Warning: Failed to retrieve context from database: {ex.Message}[/]"); |
| | 1 | 258 | | } |
| | | 259 | | |
| | 1 | 260 | | return contextDocuments; |
| | 1 | 261 | | } |
| | | 262 | | |
| | | 263 | | /// <summary> |
| | | 264 | | /// Gets context documents using database first, falling back to on-demand context provider if needed. |
| | | 265 | | /// </summary> |
| | | 266 | | private async Task<List<DocumentContext>> GetHybridContextAsync( |
| | | 267 | | IContextRepository contextRepository, |
| | | 268 | | IKicktippContextProvider contextProvider, |
| | | 269 | | string homeTeam, |
| | | 270 | | string awayTeam, |
| | | 271 | | string communityContext) |
| | | 272 | | { |
| | 1 | 273 | | var contextDocuments = new List<DocumentContext>(); |
| | 1 | 274 | | var databaseContexts = await GetMatchContextDocumentsAsync( |
| | 1 | 275 | | contextRepository, |
| | 1 | 276 | | homeTeam, |
| | 1 | 277 | | awayTeam, |
| | 1 | 278 | | communityContext); |
| | | 279 | | |
| | 1 | 280 | | var homeAbbreviation = GetTeamAbbreviation(homeTeam); |
| | 1 | 281 | | var awayAbbreviation = GetTeamAbbreviation(awayTeam); |
| | 1 | 282 | | var requiredDocuments = new[] |
| | 1 | 283 | | { |
| | 1 | 284 | | "bundesliga-standings.csv", |
| | 1 | 285 | | $"community-rules-{communityContext}.md", |
| | 1 | 286 | | $"recent-history-{homeAbbreviation}.csv", |
| | 1 | 287 | | $"recent-history-{awayAbbreviation}.csv", |
| | 1 | 288 | | $"home-history-{homeAbbreviation}.csv", |
| | 1 | 289 | | $"away-history-{awayAbbreviation}.csv", |
| | 1 | 290 | | $"head-to-head-{homeAbbreviation}-vs-{awayAbbreviation}.csv" |
| | 1 | 291 | | }; |
| | | 292 | | |
| | 1 | 293 | | int requiredPresent = requiredDocuments.Count(d => databaseContexts.ContainsKey(d)); |
| | 1 | 294 | | int requiredTotal = requiredDocuments.Length; |
| | | 295 | | |
| | 1 | 296 | | if (requiredPresent == requiredTotal) |
| | | 297 | | { |
| | 1 | 298 | | _console.MarkupLine($"[green] Using {databaseContexts.Count} context documents from database (all require |
| | 1 | 299 | | contextDocuments.AddRange(databaseContexts.Values); |
| | | 300 | | } |
| | | 301 | | else |
| | | 302 | | { |
| | 1 | 303 | | _console.MarkupLine($"[yellow] Warning: Only found {requiredPresent}/{requiredTotal} required context doc |
| | | 304 | | |
| | 1 | 305 | | contextDocuments.AddRange(databaseContexts.Values); |
| | | 306 | | |
| | 1 | 307 | | var existingNames = new HashSet<string>(contextDocuments.Select(c => c.Name), StringComparer.OrdinalIgnoreCa |
| | 1 | 308 | | await foreach (var context in contextProvider.GetMatchContextAsync(homeTeam, awayTeam)) |
| | | 309 | | { |
| | 1 | 310 | | if (existingNames.Add(context.Name)) |
| | | 311 | | { |
| | 1 | 312 | | contextDocuments.Add(context); |
| | | 313 | | } |
| | | 314 | | } |
| | | 315 | | |
| | 1 | 316 | | _console.MarkupLine($"[yellow] Using {contextDocuments.Count} merged context documents (database + on-dem |
| | 1 | 317 | | } |
| | | 318 | | |
| | 1 | 319 | | return contextDocuments; |
| | 1 | 320 | | } |
| | | 321 | | |
| | | 322 | | /// <summary> |
| | | 323 | | /// Gets a team abbreviation for file naming. |
| | | 324 | | /// </summary> |
| | | 325 | | private static string GetTeamAbbreviation(string teamName) |
| | | 326 | | { |
| | 1 | 327 | | var abbreviations = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) |
| | 1 | 328 | | { |
| | 1 | 329 | | { "1. FC Heidenheim 1846", "fch" }, |
| | 1 | 330 | | { "1. FC Köln", "fck" }, |
| | 1 | 331 | | { "1. FC Union Berlin", "fcu" }, |
| | 1 | 332 | | { "1899 Hoffenheim", "tsg" }, |
| | 1 | 333 | | { "Bayer 04 Leverkusen", "b04" }, |
| | 1 | 334 | | { "Bor. Mönchengladbach", "bmg" }, |
| | 1 | 335 | | { "Borussia Dortmund", "bvb" }, |
| | 1 | 336 | | { "Eintracht Frankfurt", "sge" }, |
| | 1 | 337 | | { "FC Augsburg", "fca" }, |
| | 1 | 338 | | { "FC Bayern München", "fcb" }, |
| | 1 | 339 | | { "FC St. Pauli", "fcs" }, |
| | 1 | 340 | | { "FSV Mainz 05", "m05" }, |
| | 1 | 341 | | { "Hamburger SV", "hsv" }, |
| | 1 | 342 | | { "RB Leipzig", "rbl" }, |
| | 1 | 343 | | { "SC Freiburg", "scf" }, |
| | 1 | 344 | | { "VfB Stuttgart", "vfb" }, |
| | 1 | 345 | | { "VfL Wolfsburg", "wob" }, |
| | 1 | 346 | | { "Werder Bremen", "svw" } |
| | 1 | 347 | | }; |
| | | 348 | | |
| | 1 | 349 | | if (abbreviations.TryGetValue(teamName, out var abbreviation)) |
| | | 350 | | { |
| | 1 | 351 | | return abbreviation; |
| | | 352 | | } |
| | | 353 | | |
| | 1 | 354 | | var words = teamName.Split(' ', StringSplitOptions.RemoveEmptyEntries); |
| | 1 | 355 | | var abbr = new System.Text.StringBuilder(); |
| | | 356 | | |
| | 1 | 357 | | foreach (var word in words.Take(3)) |
| | | 358 | | { |
| | 1 | 359 | | if (word.Length > 0 && char.IsLetter(word[0])) |
| | | 360 | | { |
| | 1 | 361 | | abbr.Append(char.ToLowerInvariant(word[0])); |
| | | 362 | | } |
| | | 363 | | } |
| | | 364 | | |
| | 1 | 365 | | return abbr.Length > 0 ? abbr.ToString() : "unknown"; |
| | | 366 | | } |
| | | 367 | | |
| | | 368 | | private void WriteJustificationIfNeeded(Prediction? prediction, bool includeJustification, bool fromDatabase = false |
| | | 369 | | { |
| | 1 | 370 | | if (!includeJustification || prediction == null) |
| | | 371 | | { |
| | 1 | 372 | | return; |
| | | 373 | | } |
| | | 374 | | |
| | 1 | 375 | | var sourceLabel = fromDatabase ? "stored prediction" : "model response"; |
| | | 376 | | |
| | 1 | 377 | | var justificationWriter = new JustificationConsoleWriter(_console); |
| | 1 | 378 | | justificationWriter.WriteJustification( |
| | 1 | 379 | | prediction.Justification, |
| | 1 | 380 | | "[dim] ↳ Justification:[/]", |
| | 1 | 381 | | " ", |
| | 1 | 382 | | $"[yellow] ↳ No justification available for this {sourceLabel}[/]"); |
| | 1 | 383 | | } |
| | | 384 | | } |