137 lines
4.2 KiB
Go
137 lines
4.2 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
|
|
mentionNames generation.MentionNameResolver
|
|
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)
|
|
}
|
|
|
|
// 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
|
|
}
|
|
|
|
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()
|
|
}
|