| | | 1 | | using Azure; |
| | | 2 | | using Azure.AI.OpenAI; |
| | | 3 | | using Chronicis.Api.Data; |
| | | 4 | | using Chronicis.Shared.DTOs; |
| | | 5 | | using Chronicis.Shared.Enums; |
| | | 6 | | using Microsoft.EntityFrameworkCore; |
| | | 7 | | using OpenAI.Chat; |
| | | 8 | | |
| | | 9 | | namespace Chronicis.Api.Services; |
| | | 10 | | |
| | | 11 | | /// <summary> |
| | | 12 | | /// Azure OpenAI implementation of AI summary generation service. |
| | | 13 | | /// Supports articles, campaigns, and arcs with customizable templates. |
| | | 14 | | /// </summary> |
| | | 15 | | public class SummaryService : ISummaryService |
| | | 16 | | { |
| | | 17 | | private readonly ChronicisDbContext _context; |
| | | 18 | | private readonly IConfiguration _configuration; |
| | | 19 | | private readonly ILogger<SummaryService> _logger; |
| | | 20 | | private readonly AzureOpenAIClient _openAIClient; |
| | | 21 | | private readonly ChatClient _chatClient; |
| | | 22 | | |
| | 0 | 23 | | private const decimal InputTokenCostPer1K = 0.00040m; |
| | 0 | 24 | | private const decimal OutputTokenCostPer1K = 0.00176m; |
| | | 25 | | private const int CharsPerToken = 4; |
| | | 26 | | |
| | | 27 | | // Well-known template IDs (from seed data) |
| | 0 | 28 | | private static readonly Guid DefaultTemplateId = Guid.Parse("00000000-0000-0000-0000-000000000001"); |
| | 0 | 29 | | private static readonly Guid CampaignRecapTemplateId = Guid.Parse("00000000-0000-0000-0000-000000000006"); |
| | | 30 | | |
| | 0 | 31 | | public SummaryService( |
| | 0 | 32 | | ChronicisDbContext context, |
| | 0 | 33 | | IConfiguration configuration, |
| | 0 | 34 | | ILogger<SummaryService> logger) |
| | | 35 | | { |
| | 0 | 36 | | _context = context; |
| | 0 | 37 | | _configuration = configuration; |
| | 0 | 38 | | _logger = logger; |
| | | 39 | | |
| | 0 | 40 | | var endpoint = _configuration["AzureOpenAI:Endpoint"]; |
| | 0 | 41 | | var apiKey = _configuration["AzureOpenAI:ApiKey"]; |
| | 0 | 42 | | var deploymentName = _configuration["AzureOpenAI:DeploymentName"]; |
| | | 43 | | |
| | 0 | 44 | | if (string.IsNullOrEmpty(endpoint)) |
| | 0 | 45 | | throw new InvalidOperationException("AzureOpenAI:Endpoint not configured"); |
| | 0 | 46 | | if (string.IsNullOrEmpty(apiKey)) |
| | 0 | 47 | | throw new InvalidOperationException("AzureOpenAI:ApiKey not configured"); |
| | 0 | 48 | | if (string.IsNullOrEmpty(deploymentName)) |
| | 0 | 49 | | throw new InvalidOperationException("AzureOpenAI:DeploymentName not configured"); |
| | | 50 | | |
| | 0 | 51 | | _openAIClient = new AzureOpenAIClient(new Uri(endpoint), new AzureKeyCredential(apiKey)); |
| | 0 | 52 | | _chatClient = _openAIClient.GetChatClient(deploymentName); |
| | 0 | 53 | | } |
| | | 54 | | |
| | | 55 | | #region Templates |
| | | 56 | | |
| | | 57 | | public async Task<List<SummaryTemplateDto>> GetTemplatesAsync() |
| | | 58 | | { |
| | 0 | 59 | | return await _context.SummaryTemplates |
| | 0 | 60 | | .AsNoTracking() |
| | 0 | 61 | | .Where(t => t.IsSystem) // For now, only system templates |
| | 0 | 62 | | .OrderBy(t => t.Name) |
| | 0 | 63 | | .Select(t => new SummaryTemplateDto |
| | 0 | 64 | | { |
| | 0 | 65 | | Id = t.Id, |
| | 0 | 66 | | Name = t.Name, |
| | 0 | 67 | | Description = t.Description, |
| | 0 | 68 | | IsSystem = t.IsSystem |
| | 0 | 69 | | }) |
| | 0 | 70 | | .ToListAsync(); |
| | 0 | 71 | | } |
| | | 72 | | |
| | | 73 | | #endregion |
| | | 74 | | |
| | | 75 | | #region Article Summary |
| | | 76 | | |
| | | 77 | | public async Task<SummaryEstimateDto> EstimateArticleSummaryAsync(Guid articleId) |
| | | 78 | | { |
| | 0 | 79 | | var article = await _context.Articles |
| | 0 | 80 | | .AsNoTracking() |
| | 0 | 81 | | .Include(a => a.SummaryTemplate) |
| | 0 | 82 | | .FirstOrDefaultAsync(a => a.Id == articleId) |
| | 0 | 83 | | ?? throw new InvalidOperationException($"Article {articleId} not found"); |
| | | 84 | | |
| | 0 | 85 | | var (primary, backlinks) = await GetArticleSourcesAsync(articleId); |
| | 0 | 86 | | var promptTemplate = await GetEffectivePromptAsync( |
| | 0 | 87 | | article.SummaryTemplateId, |
| | 0 | 88 | | article.SummaryCustomPrompt, |
| | 0 | 89 | | DefaultTemplateId); |
| | | 90 | | |
| | 0 | 91 | | var sourceContent = FormatArticleSources(primary, backlinks); |
| | 0 | 92 | | var fullPrompt = BuildPrompt(promptTemplate, article.Title, sourceContent, ""); |
| | | 93 | | |
| | 0 | 94 | | int estimatedInputTokens = fullPrompt.Length / CharsPerToken; |
| | 0 | 95 | | int estimatedOutputTokens = int.Parse(_configuration["AzureOpenAI:MaxOutputTokens"] ?? "1500"); |
| | | 96 | | |
| | 0 | 97 | | decimal estimatedCost = |
| | 0 | 98 | | (estimatedInputTokens / 1000m * InputTokenCostPer1K) + |
| | 0 | 99 | | (estimatedOutputTokens / 1000m * OutputTokenCostPer1K); |
| | | 100 | | |
| | | 101 | | // Count sources: 1 for primary (if exists) + backlink count |
| | 0 | 102 | | var sourceCount = (primary != null ? 1 : 0) + backlinks.Count; |
| | | 103 | | |
| | 0 | 104 | | return new SummaryEstimateDto |
| | 0 | 105 | | { |
| | 0 | 106 | | EntityId = articleId, |
| | 0 | 107 | | EntityType = "Article", |
| | 0 | 108 | | EntityName = article.Title, |
| | 0 | 109 | | SourceCount = sourceCount, |
| | 0 | 110 | | EstimatedInputTokens = estimatedInputTokens, |
| | 0 | 111 | | EstimatedOutputTokens = estimatedOutputTokens, |
| | 0 | 112 | | EstimatedCostUSD = Math.Round(estimatedCost, 4), |
| | 0 | 113 | | HasExistingSummary = !string.IsNullOrEmpty(article.AISummary), |
| | 0 | 114 | | ExistingSummaryDate = article.AISummaryGeneratedAt, |
| | 0 | 115 | | TemplateId = article.SummaryTemplateId, |
| | 0 | 116 | | TemplateName = article.SummaryTemplate?.Name, |
| | 0 | 117 | | CustomPrompt = article.SummaryCustomPrompt, |
| | 0 | 118 | | IncludeWebSources = article.SummaryIncludeWebSources |
| | 0 | 119 | | }; |
| | 0 | 120 | | } |
| | | 121 | | |
| | | 122 | | public async Task<SummaryGenerationDto> GenerateArticleSummaryAsync(Guid articleId, GenerateSummaryRequestDto? reque |
| | | 123 | | { |
| | | 124 | | try |
| | | 125 | | { |
| | 0 | 126 | | var article = await _context.Articles |
| | 0 | 127 | | .Include(a => a.SummaryTemplate) |
| | 0 | 128 | | .FirstOrDefaultAsync(a => a.Id == articleId); |
| | | 129 | | |
| | 0 | 130 | | if (article == null) |
| | | 131 | | { |
| | 0 | 132 | | return new SummaryGenerationDto |
| | 0 | 133 | | { |
| | 0 | 134 | | Success = false, |
| | 0 | 135 | | ErrorMessage = $"Article {articleId} not found" |
| | 0 | 136 | | }; |
| | | 137 | | } |
| | | 138 | | |
| | 0 | 139 | | var (primary, backlinks) = await GetArticleSourcesAsync(articleId); |
| | | 140 | | |
| | | 141 | | // Need at least the article's own content OR backlinks |
| | 0 | 142 | | if (primary == null && backlinks.Count == 0) |
| | | 143 | | { |
| | 0 | 144 | | return new SummaryGenerationDto |
| | 0 | 145 | | { |
| | 0 | 146 | | Success = false, |
| | 0 | 147 | | ErrorMessage = "No content available. Add content to this article or create links from other article |
| | 0 | 148 | | }; |
| | | 149 | | } |
| | | 150 | | |
| | | 151 | | // Determine effective configuration |
| | 0 | 152 | | var templateId = request?.TemplateId ?? article.SummaryTemplateId; |
| | 0 | 153 | | var customPrompt = request?.CustomPrompt ?? article.SummaryCustomPrompt; |
| | 0 | 154 | | var includeWeb = request?.IncludeWebSources ?? article.SummaryIncludeWebSources; |
| | | 155 | | |
| | | 156 | | // Save configuration if requested |
| | 0 | 157 | | if (request?.SaveConfiguration == true) |
| | | 158 | | { |
| | 0 | 159 | | article.SummaryTemplateId = request.TemplateId; |
| | 0 | 160 | | article.SummaryCustomPrompt = request.CustomPrompt; |
| | 0 | 161 | | article.SummaryIncludeWebSources = request.IncludeWebSources; |
| | | 162 | | } |
| | | 163 | | |
| | 0 | 164 | | var promptTemplate = await GetEffectivePromptAsync(templateId, customPrompt, DefaultTemplateId); |
| | 0 | 165 | | var sourceContent = FormatArticleSources(primary, backlinks); |
| | | 166 | | |
| | | 167 | | // Build sources list for response |
| | 0 | 168 | | var allSources = new List<SourceContent>(); |
| | 0 | 169 | | if (primary != null) |
| | 0 | 170 | | allSources.Add(primary); |
| | 0 | 171 | | allSources.AddRange(backlinks); |
| | | 172 | | |
| | | 173 | | // TODO: Implement web search when includeWeb is true |
| | 0 | 174 | | var webContent = ""; |
| | | 175 | | |
| | 0 | 176 | | var result = await GenerateSummaryInternalAsync( |
| | 0 | 177 | | article.Title, |
| | 0 | 178 | | promptTemplate, |
| | 0 | 179 | | sourceContent, |
| | 0 | 180 | | webContent, |
| | 0 | 181 | | allSources, |
| | 0 | 182 | | request?.MaxOutputTokens ?? 1500); |
| | | 183 | | |
| | 0 | 184 | | if (result.Success) |
| | | 185 | | { |
| | 0 | 186 | | article.AISummary = result.Summary; |
| | 0 | 187 | | article.AISummaryGeneratedAt = DateTime.UtcNow; |
| | 0 | 188 | | await _context.SaveChangesAsync(); |
| | 0 | 189 | | result.GeneratedDate = article.AISummaryGeneratedAt.Value; |
| | | 190 | | } |
| | | 191 | | |
| | 0 | 192 | | return result; |
| | | 193 | | } |
| | 0 | 194 | | catch (Exception ex) |
| | | 195 | | { |
| | 0 | 196 | | _logger.LogError(ex, "Error generating AI summary for article {ArticleId}", articleId); |
| | 0 | 197 | | return new SummaryGenerationDto |
| | 0 | 198 | | { |
| | 0 | 199 | | Success = false, |
| | 0 | 200 | | ErrorMessage = $"Error generating summary: {ex.Message}" |
| | 0 | 201 | | }; |
| | | 202 | | } |
| | 0 | 203 | | } |
| | | 204 | | |
| | | 205 | | public async Task<ArticleSummaryDto?> GetArticleSummaryAsync(Guid articleId) |
| | | 206 | | { |
| | 0 | 207 | | var article = await _context.Articles |
| | 0 | 208 | | .AsNoTracking() |
| | 0 | 209 | | .Include(a => a.SummaryTemplate) |
| | 0 | 210 | | .FirstOrDefaultAsync(a => a.Id == articleId); |
| | | 211 | | |
| | 0 | 212 | | if (article == null) |
| | 0 | 213 | | return null; |
| | | 214 | | |
| | 0 | 215 | | return new ArticleSummaryDto |
| | 0 | 216 | | { |
| | 0 | 217 | | ArticleId = articleId, |
| | 0 | 218 | | Summary = article.AISummary, |
| | 0 | 219 | | GeneratedAt = article.AISummaryGeneratedAt, |
| | 0 | 220 | | TemplateId = article.SummaryTemplateId, |
| | 0 | 221 | | TemplateName = article.SummaryTemplate?.Name, |
| | 0 | 222 | | CustomPrompt = article.SummaryCustomPrompt, |
| | 0 | 223 | | IncludeWebSources = article.SummaryIncludeWebSources |
| | 0 | 224 | | }; |
| | 0 | 225 | | } |
| | | 226 | | |
| | | 227 | | public async Task<SummaryPreviewDto?> GetArticleSummaryPreviewAsync(Guid articleId) |
| | | 228 | | { |
| | 0 | 229 | | var article = await _context.Articles |
| | 0 | 230 | | .AsNoTracking() |
| | 0 | 231 | | .Include(a => a.SummaryTemplate) |
| | 0 | 232 | | .Where(a => a.Id == articleId) |
| | 0 | 233 | | .Select(a => new SummaryPreviewDto |
| | 0 | 234 | | { |
| | 0 | 235 | | Title = a.Title, |
| | 0 | 236 | | Summary = a.AISummary, |
| | 0 | 237 | | TemplateName = a.SummaryTemplate != null ? a.SummaryTemplate.Name : null |
| | 0 | 238 | | }) |
| | 0 | 239 | | .FirstOrDefaultAsync(); |
| | | 240 | | |
| | 0 | 241 | | return article; |
| | 0 | 242 | | } |
| | | 243 | | |
| | | 244 | | public async Task<bool> ClearArticleSummaryAsync(Guid articleId) |
| | | 245 | | { |
| | 0 | 246 | | var article = await _context.Articles.FirstOrDefaultAsync(a => a.Id == articleId); |
| | 0 | 247 | | if (article == null) |
| | 0 | 248 | | return false; |
| | | 249 | | |
| | 0 | 250 | | article.AISummary = null; |
| | 0 | 251 | | article.AISummaryGeneratedAt = null; |
| | 0 | 252 | | await _context.SaveChangesAsync(); |
| | 0 | 253 | | return true; |
| | 0 | 254 | | } |
| | | 255 | | |
| | | 256 | | private async Task<(SourceContent? Primary, List<SourceContent> Backlinks)> GetArticleSourcesAsync(Guid articleId) |
| | | 257 | | { |
| | | 258 | | // Get the article's own content as the primary/canonical source |
| | 0 | 259 | | var article = await _context.Articles |
| | 0 | 260 | | .AsNoTracking() |
| | 0 | 261 | | .FirstOrDefaultAsync(a => a.Id == articleId); |
| | | 262 | | |
| | 0 | 263 | | SourceContent? primarySource = null; |
| | 0 | 264 | | if (article != null && !string.IsNullOrEmpty(article.Body)) |
| | | 265 | | { |
| | 0 | 266 | | primarySource = new SourceContent |
| | 0 | 267 | | { |
| | 0 | 268 | | Type = "Primary", |
| | 0 | 269 | | Title = article.Title, |
| | 0 | 270 | | Content = article.Body, |
| | 0 | 271 | | ArticleId = article.Id |
| | 0 | 272 | | }; |
| | | 273 | | } |
| | | 274 | | |
| | | 275 | | // Get all articles that link TO this article (backlinks) |
| | 0 | 276 | | var backlinks = await _context.ArticleLinks |
| | 0 | 277 | | .AsNoTracking() |
| | 0 | 278 | | .Where(al => al.TargetArticleId == articleId) |
| | 0 | 279 | | .Select(al => al.SourceArticle) |
| | 0 | 280 | | .Distinct() |
| | 0 | 281 | | .Where(a => !string.IsNullOrEmpty(a.Body) && a.Visibility == ArticleVisibility.Public) |
| | 0 | 282 | | .Select(a => new SourceContent |
| | 0 | 283 | | { |
| | 0 | 284 | | Type = "Backlink", |
| | 0 | 285 | | Title = a.Title, |
| | 0 | 286 | | Content = a.Body!, |
| | 0 | 287 | | ArticleId = a.Id |
| | 0 | 288 | | }) |
| | 0 | 289 | | .ToListAsync(); |
| | | 290 | | |
| | 0 | 291 | | return (primarySource, backlinks); |
| | 0 | 292 | | } |
| | | 293 | | |
| | | 294 | | #endregion |
| | | 295 | | |
| | | 296 | | #region Campaign Summary |
| | | 297 | | |
| | | 298 | | public async Task<SummaryEstimateDto> EstimateCampaignSummaryAsync(Guid campaignId) |
| | | 299 | | { |
| | 0 | 300 | | var campaign = await _context.Campaigns |
| | 0 | 301 | | .AsNoTracking() |
| | 0 | 302 | | .Include(c => c.SummaryTemplate) |
| | 0 | 303 | | .FirstOrDefaultAsync(c => c.Id == campaignId) |
| | 0 | 304 | | ?? throw new InvalidOperationException($"Campaign {campaignId} not found"); |
| | | 305 | | |
| | 0 | 306 | | var sources = await GetCampaignSourcesAsync(campaignId); |
| | 0 | 307 | | var promptTemplate = await GetEffectivePromptAsync( |
| | 0 | 308 | | campaign.SummaryTemplateId, |
| | 0 | 309 | | campaign.SummaryCustomPrompt, |
| | 0 | 310 | | CampaignRecapTemplateId); |
| | | 311 | | |
| | 0 | 312 | | var sourceContent = FormatSources(sources); |
| | 0 | 313 | | var fullPrompt = BuildPrompt(promptTemplate, campaign.Name, sourceContent, ""); |
| | | 314 | | |
| | 0 | 315 | | int estimatedInputTokens = fullPrompt.Length / CharsPerToken; |
| | 0 | 316 | | int estimatedOutputTokens = int.Parse(_configuration["AzureOpenAI:MaxOutputTokens"] ?? "1500"); |
| | | 317 | | |
| | 0 | 318 | | decimal estimatedCost = |
| | 0 | 319 | | (estimatedInputTokens / 1000m * InputTokenCostPer1K) + |
| | 0 | 320 | | (estimatedOutputTokens / 1000m * OutputTokenCostPer1K); |
| | | 321 | | |
| | 0 | 322 | | return new SummaryEstimateDto |
| | 0 | 323 | | { |
| | 0 | 324 | | EntityId = campaignId, |
| | 0 | 325 | | EntityType = "Campaign", |
| | 0 | 326 | | EntityName = campaign.Name, |
| | 0 | 327 | | SourceCount = sources.Count, |
| | 0 | 328 | | EstimatedInputTokens = estimatedInputTokens, |
| | 0 | 329 | | EstimatedOutputTokens = estimatedOutputTokens, |
| | 0 | 330 | | EstimatedCostUSD = Math.Round(estimatedCost, 4), |
| | 0 | 331 | | HasExistingSummary = !string.IsNullOrEmpty(campaign.AISummary), |
| | 0 | 332 | | ExistingSummaryDate = campaign.AISummaryGeneratedAt, |
| | 0 | 333 | | TemplateId = campaign.SummaryTemplateId, |
| | 0 | 334 | | TemplateName = campaign.SummaryTemplate?.Name, |
| | 0 | 335 | | CustomPrompt = campaign.SummaryCustomPrompt, |
| | 0 | 336 | | IncludeWebSources = campaign.SummaryIncludeWebSources |
| | 0 | 337 | | }; |
| | 0 | 338 | | } |
| | | 339 | | |
| | | 340 | | public async Task<SummaryGenerationDto> GenerateCampaignSummaryAsync(Guid campaignId, GenerateSummaryRequestDto? req |
| | | 341 | | { |
| | | 342 | | try |
| | | 343 | | { |
| | 0 | 344 | | var campaign = await _context.Campaigns |
| | 0 | 345 | | .Include(c => c.SummaryTemplate) |
| | 0 | 346 | | .FirstOrDefaultAsync(c => c.Id == campaignId); |
| | | 347 | | |
| | 0 | 348 | | if (campaign == null) |
| | | 349 | | { |
| | 0 | 350 | | return new SummaryGenerationDto |
| | 0 | 351 | | { |
| | 0 | 352 | | Success = false, |
| | 0 | 353 | | ErrorMessage = $"Campaign {campaignId} not found" |
| | 0 | 354 | | }; |
| | | 355 | | } |
| | | 356 | | |
| | 0 | 357 | | var sources = await GetCampaignSourcesAsync(campaignId); |
| | | 358 | | |
| | 0 | 359 | | if (sources.Count == 0) |
| | | 360 | | { |
| | 0 | 361 | | return new SummaryGenerationDto |
| | 0 | 362 | | { |
| | 0 | 363 | | Success = false, |
| | 0 | 364 | | ErrorMessage = "No public session notes found in this campaign." |
| | 0 | 365 | | }; |
| | | 366 | | } |
| | | 367 | | |
| | 0 | 368 | | var templateId = request?.TemplateId ?? campaign.SummaryTemplateId; |
| | 0 | 369 | | var customPrompt = request?.CustomPrompt ?? campaign.SummaryCustomPrompt; |
| | 0 | 370 | | var includeWeb = request?.IncludeWebSources ?? campaign.SummaryIncludeWebSources; |
| | | 371 | | |
| | 0 | 372 | | if (request?.SaveConfiguration == true) |
| | | 373 | | { |
| | 0 | 374 | | campaign.SummaryTemplateId = request.TemplateId; |
| | 0 | 375 | | campaign.SummaryCustomPrompt = request.CustomPrompt; |
| | 0 | 376 | | campaign.SummaryIncludeWebSources = request.IncludeWebSources; |
| | | 377 | | } |
| | | 378 | | |
| | 0 | 379 | | var promptTemplate = await GetEffectivePromptAsync(templateId, customPrompt, CampaignRecapTemplateId); |
| | 0 | 380 | | var sourceContent = FormatSources(sources); |
| | 0 | 381 | | var webContent = ""; |
| | | 382 | | |
| | 0 | 383 | | var result = await GenerateSummaryInternalAsync( |
| | 0 | 384 | | campaign.Name, |
| | 0 | 385 | | promptTemplate, |
| | 0 | 386 | | sourceContent, |
| | 0 | 387 | | webContent, |
| | 0 | 388 | | sources, |
| | 0 | 389 | | request?.MaxOutputTokens ?? 1500); |
| | | 390 | | |
| | 0 | 391 | | if (result.Success) |
| | | 392 | | { |
| | 0 | 393 | | campaign.AISummary = result.Summary; |
| | 0 | 394 | | campaign.AISummaryGeneratedAt = DateTime.UtcNow; |
| | 0 | 395 | | await _context.SaveChangesAsync(); |
| | 0 | 396 | | result.GeneratedDate = campaign.AISummaryGeneratedAt.Value; |
| | | 397 | | } |
| | | 398 | | |
| | 0 | 399 | | return result; |
| | | 400 | | } |
| | 0 | 401 | | catch (Exception ex) |
| | | 402 | | { |
| | 0 | 403 | | _logger.LogError(ex, "Error generating AI summary for campaign {CampaignId}", campaignId); |
| | 0 | 404 | | return new SummaryGenerationDto |
| | 0 | 405 | | { |
| | 0 | 406 | | Success = false, |
| | 0 | 407 | | ErrorMessage = $"Error generating summary: {ex.Message}" |
| | 0 | 408 | | }; |
| | | 409 | | } |
| | 0 | 410 | | } |
| | | 411 | | |
| | | 412 | | public async Task<EntitySummaryDto?> GetCampaignSummaryAsync(Guid campaignId) |
| | | 413 | | { |
| | 0 | 414 | | var campaign = await _context.Campaigns |
| | 0 | 415 | | .AsNoTracking() |
| | 0 | 416 | | .Include(c => c.SummaryTemplate) |
| | 0 | 417 | | .FirstOrDefaultAsync(c => c.Id == campaignId); |
| | | 418 | | |
| | 0 | 419 | | if (campaign == null) |
| | 0 | 420 | | return null; |
| | | 421 | | |
| | 0 | 422 | | return new EntitySummaryDto |
| | 0 | 423 | | { |
| | 0 | 424 | | EntityId = campaignId, |
| | 0 | 425 | | EntityType = "Campaign", |
| | 0 | 426 | | Summary = campaign.AISummary, |
| | 0 | 427 | | GeneratedAt = campaign.AISummaryGeneratedAt, |
| | 0 | 428 | | TemplateId = campaign.SummaryTemplateId, |
| | 0 | 429 | | TemplateName = campaign.SummaryTemplate?.Name, |
| | 0 | 430 | | CustomPrompt = campaign.SummaryCustomPrompt, |
| | 0 | 431 | | IncludeWebSources = campaign.SummaryIncludeWebSources |
| | 0 | 432 | | }; |
| | 0 | 433 | | } |
| | | 434 | | |
| | | 435 | | public async Task<bool> ClearCampaignSummaryAsync(Guid campaignId) |
| | | 436 | | { |
| | 0 | 437 | | var campaign = await _context.Campaigns.FirstOrDefaultAsync(c => c.Id == campaignId); |
| | 0 | 438 | | if (campaign == null) |
| | 0 | 439 | | return false; |
| | | 440 | | |
| | 0 | 441 | | campaign.AISummary = null; |
| | 0 | 442 | | campaign.AISummaryGeneratedAt = null; |
| | 0 | 443 | | await _context.SaveChangesAsync(); |
| | 0 | 444 | | return true; |
| | 0 | 445 | | } |
| | | 446 | | |
| | | 447 | | private async Task<List<SourceContent>> GetCampaignSourcesAsync(Guid campaignId) |
| | | 448 | | { |
| | | 449 | | // Get all public session articles in this campaign |
| | 0 | 450 | | var sessions = await _context.Articles |
| | 0 | 451 | | .AsNoTracking() |
| | 0 | 452 | | .Where(a => a.CampaignId == campaignId |
| | 0 | 453 | | && a.Type == ArticleType.Session |
| | 0 | 454 | | && a.Visibility == ArticleVisibility.Public |
| | 0 | 455 | | && !string.IsNullOrEmpty(a.Body)) |
| | 0 | 456 | | .OrderBy(a => a.SessionDate ?? a.CreatedAt) |
| | 0 | 457 | | .Select(a => new SourceContent |
| | 0 | 458 | | { |
| | 0 | 459 | | Type = "Session", |
| | 0 | 460 | | Title = a.Title, |
| | 0 | 461 | | Content = a.Body!, |
| | 0 | 462 | | ArticleId = a.Id |
| | 0 | 463 | | }) |
| | 0 | 464 | | .ToListAsync(); |
| | | 465 | | |
| | 0 | 466 | | return sessions; |
| | 0 | 467 | | } |
| | | 468 | | |
| | | 469 | | #endregion |
| | | 470 | | |
| | | 471 | | #region Arc Summary |
| | | 472 | | |
| | | 473 | | public async Task<SummaryEstimateDto> EstimateArcSummaryAsync(Guid arcId) |
| | | 474 | | { |
| | 0 | 475 | | var arc = await _context.Arcs |
| | 0 | 476 | | .AsNoTracking() |
| | 0 | 477 | | .Include(a => a.SummaryTemplate) |
| | 0 | 478 | | .FirstOrDefaultAsync(a => a.Id == arcId) |
| | 0 | 479 | | ?? throw new InvalidOperationException($"Arc {arcId} not found"); |
| | | 480 | | |
| | 0 | 481 | | var sources = await GetArcSourcesAsync(arcId); |
| | 0 | 482 | | var promptTemplate = await GetEffectivePromptAsync( |
| | 0 | 483 | | arc.SummaryTemplateId, |
| | 0 | 484 | | arc.SummaryCustomPrompt, |
| | 0 | 485 | | CampaignRecapTemplateId); |
| | | 486 | | |
| | 0 | 487 | | var sourceContent = FormatSources(sources); |
| | 0 | 488 | | var fullPrompt = BuildPrompt(promptTemplate, arc.Name, sourceContent, ""); |
| | | 489 | | |
| | 0 | 490 | | int estimatedInputTokens = fullPrompt.Length / CharsPerToken; |
| | 0 | 491 | | int estimatedOutputTokens = int.Parse(_configuration["AzureOpenAI:MaxOutputTokens"] ?? "1500"); |
| | | 492 | | |
| | 0 | 493 | | decimal estimatedCost = |
| | 0 | 494 | | (estimatedInputTokens / 1000m * InputTokenCostPer1K) + |
| | 0 | 495 | | (estimatedOutputTokens / 1000m * OutputTokenCostPer1K); |
| | | 496 | | |
| | 0 | 497 | | return new SummaryEstimateDto |
| | 0 | 498 | | { |
| | 0 | 499 | | EntityId = arcId, |
| | 0 | 500 | | EntityType = "Arc", |
| | 0 | 501 | | EntityName = arc.Name, |
| | 0 | 502 | | SourceCount = sources.Count, |
| | 0 | 503 | | EstimatedInputTokens = estimatedInputTokens, |
| | 0 | 504 | | EstimatedOutputTokens = estimatedOutputTokens, |
| | 0 | 505 | | EstimatedCostUSD = Math.Round(estimatedCost, 4), |
| | 0 | 506 | | HasExistingSummary = !string.IsNullOrEmpty(arc.AISummary), |
| | 0 | 507 | | ExistingSummaryDate = arc.AISummaryGeneratedAt, |
| | 0 | 508 | | TemplateId = arc.SummaryTemplateId, |
| | 0 | 509 | | TemplateName = arc.SummaryTemplate?.Name, |
| | 0 | 510 | | CustomPrompt = arc.SummaryCustomPrompt, |
| | 0 | 511 | | IncludeWebSources = arc.SummaryIncludeWebSources |
| | 0 | 512 | | }; |
| | 0 | 513 | | } |
| | | 514 | | |
| | | 515 | | public async Task<SummaryGenerationDto> GenerateArcSummaryAsync(Guid arcId, GenerateSummaryRequestDto? request = nul |
| | | 516 | | { |
| | | 517 | | try |
| | | 518 | | { |
| | 0 | 519 | | var arc = await _context.Arcs |
| | 0 | 520 | | .Include(a => a.SummaryTemplate) |
| | 0 | 521 | | .FirstOrDefaultAsync(a => a.Id == arcId); |
| | | 522 | | |
| | 0 | 523 | | if (arc == null) |
| | | 524 | | { |
| | 0 | 525 | | return new SummaryGenerationDto |
| | 0 | 526 | | { |
| | 0 | 527 | | Success = false, |
| | 0 | 528 | | ErrorMessage = $"Arc {arcId} not found" |
| | 0 | 529 | | }; |
| | | 530 | | } |
| | | 531 | | |
| | 0 | 532 | | var sources = await GetArcSourcesAsync(arcId); |
| | | 533 | | |
| | 0 | 534 | | if (sources.Count == 0) |
| | | 535 | | { |
| | 0 | 536 | | return new SummaryGenerationDto |
| | 0 | 537 | | { |
| | 0 | 538 | | Success = false, |
| | 0 | 539 | | ErrorMessage = "No public session notes found in this arc." |
| | 0 | 540 | | }; |
| | | 541 | | } |
| | | 542 | | |
| | 0 | 543 | | var templateId = request?.TemplateId ?? arc.SummaryTemplateId; |
| | 0 | 544 | | var customPrompt = request?.CustomPrompt ?? arc.SummaryCustomPrompt; |
| | 0 | 545 | | var includeWeb = request?.IncludeWebSources ?? arc.SummaryIncludeWebSources; |
| | | 546 | | |
| | 0 | 547 | | if (request?.SaveConfiguration == true) |
| | | 548 | | { |
| | 0 | 549 | | arc.SummaryTemplateId = request.TemplateId; |
| | 0 | 550 | | arc.SummaryCustomPrompt = request.CustomPrompt; |
| | 0 | 551 | | arc.SummaryIncludeWebSources = request.IncludeWebSources; |
| | | 552 | | } |
| | | 553 | | |
| | 0 | 554 | | var promptTemplate = await GetEffectivePromptAsync(templateId, customPrompt, CampaignRecapTemplateId); |
| | 0 | 555 | | var sourceContent = FormatSources(sources); |
| | 0 | 556 | | var webContent = ""; |
| | | 557 | | |
| | 0 | 558 | | var result = await GenerateSummaryInternalAsync( |
| | 0 | 559 | | arc.Name, |
| | 0 | 560 | | promptTemplate, |
| | 0 | 561 | | sourceContent, |
| | 0 | 562 | | webContent, |
| | 0 | 563 | | sources, |
| | 0 | 564 | | request?.MaxOutputTokens ?? 1500); |
| | | 565 | | |
| | 0 | 566 | | if (result.Success) |
| | | 567 | | { |
| | 0 | 568 | | arc.AISummary = result.Summary; |
| | 0 | 569 | | arc.AISummaryGeneratedAt = DateTime.UtcNow; |
| | 0 | 570 | | await _context.SaveChangesAsync(); |
| | 0 | 571 | | result.GeneratedDate = arc.AISummaryGeneratedAt.Value; |
| | | 572 | | } |
| | | 573 | | |
| | 0 | 574 | | return result; |
| | | 575 | | } |
| | 0 | 576 | | catch (Exception ex) |
| | | 577 | | { |
| | 0 | 578 | | _logger.LogError(ex, "Error generating AI summary for arc {ArcId}", arcId); |
| | 0 | 579 | | return new SummaryGenerationDto |
| | 0 | 580 | | { |
| | 0 | 581 | | Success = false, |
| | 0 | 582 | | ErrorMessage = $"Error generating summary: {ex.Message}" |
| | 0 | 583 | | }; |
| | | 584 | | } |
| | 0 | 585 | | } |
| | | 586 | | |
| | | 587 | | public async Task<EntitySummaryDto?> GetArcSummaryAsync(Guid arcId) |
| | | 588 | | { |
| | 0 | 589 | | var arc = await _context.Arcs |
| | 0 | 590 | | .AsNoTracking() |
| | 0 | 591 | | .Include(a => a.SummaryTemplate) |
| | 0 | 592 | | .FirstOrDefaultAsync(a => a.Id == arcId); |
| | | 593 | | |
| | 0 | 594 | | if (arc == null) |
| | 0 | 595 | | return null; |
| | | 596 | | |
| | 0 | 597 | | return new EntitySummaryDto |
| | 0 | 598 | | { |
| | 0 | 599 | | EntityId = arcId, |
| | 0 | 600 | | EntityType = "Arc", |
| | 0 | 601 | | Summary = arc.AISummary, |
| | 0 | 602 | | GeneratedAt = arc.AISummaryGeneratedAt, |
| | 0 | 603 | | TemplateId = arc.SummaryTemplateId, |
| | 0 | 604 | | TemplateName = arc.SummaryTemplate?.Name, |
| | 0 | 605 | | CustomPrompt = arc.SummaryCustomPrompt, |
| | 0 | 606 | | IncludeWebSources = arc.SummaryIncludeWebSources |
| | 0 | 607 | | }; |
| | 0 | 608 | | } |
| | | 609 | | |
| | | 610 | | public async Task<bool> ClearArcSummaryAsync(Guid arcId) |
| | | 611 | | { |
| | 0 | 612 | | var arc = await _context.Arcs.FirstOrDefaultAsync(a => a.Id == arcId); |
| | 0 | 613 | | if (arc == null) |
| | 0 | 614 | | return false; |
| | | 615 | | |
| | 0 | 616 | | arc.AISummary = null; |
| | 0 | 617 | | arc.AISummaryGeneratedAt = null; |
| | 0 | 618 | | await _context.SaveChangesAsync(); |
| | 0 | 619 | | return true; |
| | 0 | 620 | | } |
| | | 621 | | |
| | | 622 | | private async Task<List<SourceContent>> GetArcSourcesAsync(Guid arcId) |
| | | 623 | | { |
| | | 624 | | // Get all public session articles in this arc |
| | 0 | 625 | | var sessions = await _context.Articles |
| | 0 | 626 | | .AsNoTracking() |
| | 0 | 627 | | .Where(a => a.ArcId == arcId |
| | 0 | 628 | | && a.Type == ArticleType.Session |
| | 0 | 629 | | && a.Visibility == ArticleVisibility.Public |
| | 0 | 630 | | && !string.IsNullOrEmpty(a.Body)) |
| | 0 | 631 | | .OrderBy(a => a.SessionDate ?? a.CreatedAt) |
| | 0 | 632 | | .Select(a => new SourceContent |
| | 0 | 633 | | { |
| | 0 | 634 | | Type = "Session", |
| | 0 | 635 | | Title = a.Title, |
| | 0 | 636 | | Content = a.Body!, |
| | 0 | 637 | | ArticleId = a.Id |
| | 0 | 638 | | }) |
| | 0 | 639 | | .ToListAsync(); |
| | | 640 | | |
| | 0 | 641 | | return sessions; |
| | 0 | 642 | | } |
| | | 643 | | |
| | | 644 | | #endregion |
| | | 645 | | |
| | | 646 | | #region Internal Helpers |
| | | 647 | | |
| | | 648 | | private async Task<string> GetEffectivePromptAsync(Guid? templateId, string? customPrompt, Guid defaultTemplateId) |
| | | 649 | | { |
| | | 650 | | // Custom prompt is used as additional instructions, not a full replacement |
| | 0 | 651 | | if (!string.IsNullOrWhiteSpace(customPrompt)) |
| | | 652 | | { |
| | | 653 | | // Wrap custom prompt with source content structure |
| | 0 | 654 | | return $@"You are analyzing tabletop RPG campaign notes about: {{EntityName}} |
| | 0 | 655 | | |
| | 0 | 656 | | Here are the source materials. The CANONICAL CONTENT is from the article itself and should be treated as authoritative f |
| | 0 | 657 | | |
| | 0 | 658 | | {{SourceContent}} |
| | 0 | 659 | | |
| | 0 | 660 | | {{WebContent}} |
| | 0 | 661 | | |
| | 0 | 662 | | Custom instructions from the user: |
| | 0 | 663 | | {customPrompt} |
| | 0 | 664 | | |
| | 0 | 665 | | Based on the source materials above and following the custom instructions, provide a comprehensive summary. Treat the ca |
| | | 666 | | } |
| | | 667 | | |
| | | 668 | | // Use specified template or default |
| | 0 | 669 | | var effectiveTemplateId = templateId ?? defaultTemplateId; |
| | | 670 | | |
| | 0 | 671 | | var template = await _context.SummaryTemplates |
| | 0 | 672 | | .AsNoTracking() |
| | 0 | 673 | | .FirstOrDefaultAsync(t => t.Id == effectiveTemplateId); |
| | | 674 | | |
| | 0 | 675 | | if (template != null) |
| | | 676 | | { |
| | 0 | 677 | | return template.PromptTemplate; |
| | | 678 | | } |
| | | 679 | | |
| | | 680 | | // Fallback to default template |
| | 0 | 681 | | template = await _context.SummaryTemplates |
| | 0 | 682 | | .AsNoTracking() |
| | 0 | 683 | | .FirstOrDefaultAsync(t => t.Id == defaultTemplateId); |
| | | 684 | | |
| | 0 | 685 | | return template?.PromptTemplate ?? throw new InvalidOperationException("Default template not found"); |
| | 0 | 686 | | } |
| | | 687 | | |
| | | 688 | | private static string BuildPrompt(string template, string entityName, string sourceContent, string webContent) |
| | | 689 | | { |
| | 0 | 690 | | return template |
| | 0 | 691 | | .Replace("{EntityName}", entityName) |
| | 0 | 692 | | .Replace("{SourceContent}", sourceContent) |
| | 0 | 693 | | .Replace("{WebContent}", string.IsNullOrEmpty(webContent) ? "" : $"\n\nAdditional context from external sour |
| | | 694 | | } |
| | | 695 | | |
| | | 696 | | private static string FormatSources(List<SourceContent> sources) |
| | | 697 | | { |
| | 0 | 698 | | return string.Join("\n\n", sources.Select(s => |
| | 0 | 699 | | $"--- From: {s.Title} ({s.Type}) ---\n{s.Content}\n---")); |
| | | 700 | | } |
| | | 701 | | |
| | | 702 | | private static string FormatArticleSources(SourceContent? primary, List<SourceContent> backlinks) |
| | | 703 | | { |
| | 0 | 704 | | var parts = new List<string>(); |
| | | 705 | | |
| | 0 | 706 | | if (primary != null) |
| | | 707 | | { |
| | 0 | 708 | | parts.Add($"=== CANONICAL CONTENT (from the article itself) ===\n{primary.Content}\n==="); |
| | | 709 | | } |
| | | 710 | | |
| | 0 | 711 | | if (backlinks.Any()) |
| | | 712 | | { |
| | 0 | 713 | | parts.Add("=== REFERENCES FROM OTHER ARTICLES ==="); |
| | 0 | 714 | | foreach (var backlink in backlinks) |
| | | 715 | | { |
| | 0 | 716 | | parts.Add($"--- From: {backlink.Title} ---\n{backlink.Content}\n---"); |
| | | 717 | | } |
| | | 718 | | } |
| | | 719 | | |
| | 0 | 720 | | return string.Join("\n\n", parts); |
| | | 721 | | } |
| | | 722 | | |
| | | 723 | | |
| | | 724 | | private async Task<SummaryGenerationDto> GenerateSummaryInternalAsync( |
| | | 725 | | string entityName, |
| | | 726 | | string promptTemplate, |
| | | 727 | | string sourceContent, |
| | | 728 | | string webContent, |
| | | 729 | | List<SourceContent> sources, |
| | | 730 | | int maxOutputTokens) |
| | | 731 | | { |
| | 0 | 732 | | var prompt = BuildPrompt(promptTemplate, entityName, sourceContent, webContent); |
| | | 733 | | |
| | 0 | 734 | | var maxInputTokens = int.Parse(_configuration["AzureOpenAI:MaxInputTokens"] ?? "8000"); |
| | 0 | 735 | | if (prompt.Length / CharsPerToken > maxInputTokens) |
| | | 736 | | { |
| | 0 | 737 | | _logger.LogWarning("Prompt exceeds max input tokens, truncating content"); |
| | 0 | 738 | | var maxContentLength = maxInputTokens * CharsPerToken - (promptTemplate.Length + entityName.Length + 200); |
| | 0 | 739 | | var truncatedSourceContent = sourceContent.Substring(0, Math.Min(sourceContent.Length, maxContentLength)); |
| | 0 | 740 | | prompt = BuildPrompt(promptTemplate, entityName, truncatedSourceContent, webContent); |
| | | 741 | | } |
| | | 742 | | |
| | 0 | 743 | | var messages = new List<ChatMessage> |
| | 0 | 744 | | { |
| | 0 | 745 | | new SystemChatMessage("You are a helpful assistant that summarizes tabletop RPG campaign notes."), |
| | 0 | 746 | | new UserChatMessage(prompt) |
| | 0 | 747 | | }; |
| | | 748 | | |
| | 0 | 749 | | var chatOptions = new ChatCompletionOptions |
| | 0 | 750 | | { |
| | 0 | 751 | | MaxOutputTokenCount = maxOutputTokens, |
| | 0 | 752 | | Temperature = 0.7f |
| | 0 | 753 | | }; |
| | | 754 | | |
| | 0 | 755 | | var completion = await _chatClient.CompleteChatAsync(messages, chatOptions); |
| | | 756 | | |
| | 0 | 757 | | var summary = completion.Value.Content[0].Text; |
| | 0 | 758 | | var inputTokens = completion.Value.Usage.InputTokenCount; |
| | 0 | 759 | | var outputTokens = completion.Value.Usage.OutputTokenCount; |
| | | 760 | | |
| | 0 | 761 | | var actualCost = |
| | 0 | 762 | | (inputTokens / 1000m * InputTokenCostPer1K) + |
| | 0 | 763 | | (outputTokens / 1000m * OutputTokenCostPer1K); |
| | | 764 | | |
| | 0 | 765 | | return new SummaryGenerationDto |
| | 0 | 766 | | { |
| | 0 | 767 | | Success = true, |
| | 0 | 768 | | Summary = summary, |
| | 0 | 769 | | TokensUsed = completion.Value.Usage.TotalTokenCount, |
| | 0 | 770 | | ActualCostUSD = Math.Round(actualCost, 4), |
| | 0 | 771 | | Sources = sources.Select(s => new SummarySourceDto |
| | 0 | 772 | | { |
| | 0 | 773 | | Type = s.Type, |
| | 0 | 774 | | Title = s.Title, |
| | 0 | 775 | | ArticleId = s.ArticleId |
| | 0 | 776 | | }).ToList() |
| | 0 | 777 | | }; |
| | 0 | 778 | | } |
| | | 779 | | |
| | | 780 | | #endregion |
| | | 781 | | } |
| | | 782 | | |
| | | 783 | | /// <summary> |
| | | 784 | | /// Internal class for holding source content during processing |
| | | 785 | | /// </summary> |
| | | 786 | | internal class SourceContent |
| | | 787 | | { |
| | | 788 | | public string Type { get; set; } = string.Empty; |
| | | 789 | | public string Title { get; set; } = string.Empty; |
| | | 790 | | public string Content { get; set; } = string.Empty; |
| | | 791 | | public Guid? ArticleId { get; set; } |
| | | 792 | | } |