Revalidate admin roles from the database and serialize report generation registration with owner-scoped deletion. Refs #9 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
262 lines
8.4 KiB
Go
262 lines
8.4 KiB
Go
package ai
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"strconv"
|
|
"strings"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"github.com/tradarr/backend/internal/crypto"
|
|
"github.com/tradarr/backend/internal/generation"
|
|
"github.com/tradarr/backend/internal/models"
|
|
)
|
|
|
|
const DefaultSystemPrompt = `Tu es un assistant spécialisé en trading financier. Analyse l'ensemble des actualités suivantes, toutes sources confondues, et crée un résumé global structuré en français, orienté trading.
|
|
|
|
Structure ton résumé ainsi :
|
|
1. **Vue macro** : tendances globales du marché (économie, géopolitique, secteurs)
|
|
2. **Actifs surveillés** : pour chaque actif de la watchlist mentionné dans les news :
|
|
- Sentiment (haussier/baissier/neutre)
|
|
- Faits clés et catalyseurs
|
|
- Risques et opportunités
|
|
3. **Autres mouvements notables** : actifs hors watchlist à surveiller
|
|
4. **Synthèse** : points d'attention prioritaires pour la journée`
|
|
|
|
type Pipeline struct {
|
|
generationUseCase generation.UseCase
|
|
repo *models.Repository
|
|
enc *crypto.Encryptor
|
|
generating atomic.Bool
|
|
}
|
|
|
|
func NewPipeline(repo *models.Repository, enc *crypto.Encryptor) *Pipeline {
|
|
return &Pipeline{repo: repo, enc: enc}
|
|
}
|
|
|
|
func (p *Pipeline) IsGenerating() bool {
|
|
return p.generating.Load()
|
|
}
|
|
|
|
func (p *Pipeline) BuildProvider(name, apiKey, endpoint string) (Provider, error) {
|
|
return NewProvider(name, apiKey, "", endpoint)
|
|
}
|
|
|
|
// buildProviderForRole resolves and builds the AI provider for a given task role.
|
|
func (p *Pipeline) buildProviderForRole(role string) (Provider, *models.AIProvider, error) {
|
|
cfg, model, err := p.repo.GetRoleProvider(role)
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("get provider for role %s: %w", role, err)
|
|
}
|
|
if cfg == nil {
|
|
return nil, nil, fmt.Errorf("no AI provider configured for role %s", role)
|
|
}
|
|
apiKey := ""
|
|
if cfg.APIKeyEncrypted != "" {
|
|
apiKey, err = p.enc.Decrypt(cfg.APIKeyEncrypted)
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("decrypt API key for role %s: %w", role, err)
|
|
}
|
|
}
|
|
provider, err := NewProvider(cfg.Name, apiKey, model, cfg.Endpoint)
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("build provider for role %s: %w", role, err)
|
|
}
|
|
return provider, cfg, nil
|
|
}
|
|
|
|
// Legacy entry point delegates to the same transient use case as HTTP/scheduler.
|
|
func (p *Pipeline) GenerateForUser(ctx context.Context, userID string) (*models.Summary, error) {
|
|
if p.generationUseCase == nil {
|
|
return nil, fmt.Errorf("generation use case unavailable")
|
|
}
|
|
p.generating.Store(true)
|
|
defer p.generating.Store(false)
|
|
result, err := p.generationUseCase.Generate(ctx, userID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if result.Outcome.Status == "failed" {
|
|
return nil, fmt.Errorf("generation failed: %s", result.Outcome.FailureCode)
|
|
}
|
|
return result.Summary, nil
|
|
}
|
|
|
|
// Compatibility seam; callers needing failure diagnostics use RankArticles.
|
|
func (p *Pipeline) filterByRelevance(ctx context.Context, provider Provider, symbols []string, articles []models.Article, max int) []models.Article {
|
|
size, _ := p.repo.GetSetting("filter_batch_size")
|
|
batchSize, _ := strconv.Atoi(size)
|
|
selected, err := RankArticles(ctx, provider, symbols, articles, batchSize, "title_content")
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
return selected
|
|
}
|
|
|
|
func parseIndexArray(response string, maxIndex int) []int {
|
|
var values []int
|
|
if json.Unmarshal([]byte(response), &values) != nil || values == nil {
|
|
return nil
|
|
}
|
|
seen := map[int]bool{}
|
|
for _, v := range values {
|
|
if v < 0 || v >= maxIndex || seen[v] {
|
|
return nil
|
|
}
|
|
seen[v] = true
|
|
}
|
|
return values
|
|
}
|
|
|
|
func (p *Pipeline) GenerateForAll(ctx context.Context) error {
|
|
users, err := p.repo.ListUsers()
|
|
if err != nil {
|
|
return fmt.Errorf("GenerateForAll: list users: %w", err)
|
|
}
|
|
fmt.Printf("[pipeline] GenerateForAll: %d user(s) to process\n", len(users))
|
|
for _, user := range users {
|
|
if _, err := p.GenerateForUser(ctx, user.ID); err != nil {
|
|
fmt.Printf("summary for user %s: %v\n", user.Email, err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// GenerateReportAsync crée le rapport en DB (status=generating) et lance la génération en arrière-plan.
|
|
func (p *Pipeline) GenerateReportAsync(ownerID, reportID, excerpt, question string, mgr *ReportManager) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
|
|
if err := mgr.RegisterForReport(ownerID, reportID, reportID, cancel, func() (bool, error) { report, err := p.repo.GetReport(reportID, ownerID); return report != nil, err }); err != nil {
|
|
return
|
|
}
|
|
|
|
go func() {
|
|
defer cancel()
|
|
defer mgr.Remove(ownerID, reportID)
|
|
|
|
if ctx.Err() != nil {
|
|
return
|
|
}
|
|
answer, err := p.callProviderForReport(ctx, excerpt, question)
|
|
if err != nil {
|
|
if ctx.Err() != nil {
|
|
// annulé volontairement — le rapport est supprimé par le handler
|
|
return
|
|
}
|
|
_ = p.repo.UpdateReport(reportID, "error", "", err.Error())
|
|
return
|
|
}
|
|
_ = p.repo.UpdateReport(reportID, "done", answer, "")
|
|
}()
|
|
}
|
|
|
|
func (p *Pipeline) callProviderForReport(ctx context.Context, excerpt, question string) (string, error) {
|
|
provider, _, err := p.buildProviderForRole("report")
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
prompt := fmt.Sprintf(
|
|
"Tu es un assistant financier expert. L'utilisateur a sélectionné les extraits suivants d'un résumé de marché :\n\n%s\n\nQuestion de l'utilisateur : %s\n\nRéponds en français, de façon précise et orientée trading.",
|
|
excerpt, question,
|
|
)
|
|
|
|
return provider.Summarize(ctx, prompt, GenOptions{Think: true, NumCtx: 16384})
|
|
}
|
|
|
|
// GenerateReportMessageAsync génère une réponse de conversation en arrière-plan.
|
|
// history contient tous les messages précédents (user + assistant), dans l'ordre.
|
|
func (p *Pipeline) GenerateReportMessageAsync(messageID string, report *models.Report, history []models.ReportMessage, mgr *ReportManager) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
|
|
if err := mgr.RegisterForReport(report.UserID, report.ID, messageID, cancel, func() (bool, error) {
|
|
current, err := p.repo.GetReport(report.ID, report.UserID)
|
|
return current != nil, err
|
|
}); err != nil {
|
|
return
|
|
}
|
|
|
|
go func() {
|
|
defer cancel()
|
|
defer mgr.Remove(report.UserID, messageID)
|
|
|
|
if ctx.Err() != nil {
|
|
return
|
|
}
|
|
answer, err := p.callProviderForConversation(ctx, report, history)
|
|
if err != nil {
|
|
if ctx.Err() != nil {
|
|
return
|
|
}
|
|
_ = p.repo.UpdateReportMessage(messageID, "error", err.Error())
|
|
return
|
|
}
|
|
_ = p.repo.UpdateReportMessage(messageID, "done", answer)
|
|
}()
|
|
}
|
|
|
|
func (p *Pipeline) callProviderForConversation(ctx context.Context, report *models.Report, history []models.ReportMessage) (string, error) {
|
|
provider, _, err := p.buildProviderForRole("report")
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
var sb strings.Builder
|
|
sb.WriteString("Tu es un assistant financier expert engagé dans une conversation avec un trader.\n\n")
|
|
sb.WriteString("## Contexte initial\n")
|
|
sb.WriteString("Extraits sélectionnés :\n")
|
|
sb.WriteString(report.ContextExcerpt)
|
|
sb.WriteString("\n\nQuestion initiale : ")
|
|
sb.WriteString(report.Question)
|
|
sb.WriteString("\nRéponse initiale : ")
|
|
sb.WriteString(report.Answer)
|
|
sb.WriteString("\n\n## Suite de la conversation\n")
|
|
|
|
for _, msg := range history {
|
|
if msg.Role == "user" {
|
|
sb.WriteString("Trader : ")
|
|
} else {
|
|
sb.WriteString("Assistant : ")
|
|
}
|
|
sb.WriteString(msg.Content)
|
|
sb.WriteString("\n")
|
|
}
|
|
|
|
sb.WriteString("\nRéponds en français, de façon précise et orientée trading.")
|
|
|
|
return provider.Summarize(ctx, sb.String(), GenOptions{Think: true, NumCtx: 16384})
|
|
}
|
|
|
|
func buildPrompt(systemPrompt string, symbols []string, articles []models.Article, tz string) string {
|
|
var sb strings.Builder
|
|
sb.WriteString(systemPrompt)
|
|
sb.WriteString("\n\n")
|
|
if len(symbols) > 0 {
|
|
sb.WriteString("Le trader surveille particulièrement ces actifs (sois attentif à toute mention) : ")
|
|
sb.WriteString(strings.Join(symbols, ", "))
|
|
sb.WriteString(".\n\n")
|
|
}
|
|
loc, err := time.LoadLocation(tz)
|
|
if err != nil || tz == "" {
|
|
loc = time.UTC
|
|
}
|
|
sb.WriteString(fmt.Sprintf("Date d'analyse : %s\n\n", time.Now().In(loc).Format("02/01/2006 15:04")))
|
|
sb.WriteString("## Actualités\n\n")
|
|
|
|
for i, a := range articles {
|
|
sb.WriteString(fmt.Sprintf("### [%d] %s\n", i+1, a.Title))
|
|
sb.WriteString(fmt.Sprintf("Source : %s\n", a.SourceName))
|
|
if a.PublishedAt.Valid {
|
|
sb.WriteString(fmt.Sprintf("Date : %s\n", a.PublishedAt.Time.Format("02/01/2006 15:04")))
|
|
}
|
|
content := a.Content
|
|
if len(content) > 1000 {
|
|
content = content[:1000] + "..."
|
|
}
|
|
sb.WriteString(content)
|
|
sb.WriteString("\n\n")
|
|
}
|
|
|
|
return sb.String()
|
|
}
|