chore(repo): initialize Tradarr repository
Add the existing application baseline and repository documentation/ignore rules. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
79
backend/internal/ai/anthropic.go
Normal file
79
backend/internal/ai/anthropic.go
Normal file
@ -0,0 +1,79 @@
|
||||
package ai
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type anthropicProvider struct {
|
||||
apiKey string
|
||||
model string
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
func newAnthropic(apiKey, model string) *anthropicProvider {
|
||||
if model == "" {
|
||||
model = "claude-sonnet-4-6"
|
||||
}
|
||||
return &anthropicProvider{
|
||||
apiKey: apiKey,
|
||||
model: model,
|
||||
client: &http.Client{},
|
||||
}
|
||||
}
|
||||
|
||||
func (p *anthropicProvider) Name() string { return "anthropic" }
|
||||
|
||||
func (p *anthropicProvider) Summarize(ctx context.Context, prompt string, _ GenOptions) (string, error) {
|
||||
body := map[string]interface{}{
|
||||
"model": p.model,
|
||||
"max_tokens": 4096,
|
||||
"messages": []map[string]string{
|
||||
{"role": "user", "content": prompt},
|
||||
},
|
||||
}
|
||||
b, _ := json.Marshal(body)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://api.anthropic.com/v1/messages", bytes.NewReader(b))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("x-api-key", p.apiKey)
|
||||
req.Header.Set("anthropic-version", "2023-06-01")
|
||||
|
||||
resp, err := p.client.Do(req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
raw, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("anthropic API error %d: %s", resp.StatusCode, raw)
|
||||
}
|
||||
|
||||
var result struct {
|
||||
Content []struct {
|
||||
Text string `json:"text"`
|
||||
} `json:"content"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &result); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(result.Content) == 0 {
|
||||
return "", nil
|
||||
}
|
||||
return result.Content[0].Text, nil
|
||||
}
|
||||
|
||||
func (p *anthropicProvider) ListModels(_ context.Context) ([]string, error) {
|
||||
return []string{
|
||||
"claude-opus-4-7",
|
||||
"claude-sonnet-4-6",
|
||||
"claude-haiku-4-5-20251001",
|
||||
}, nil
|
||||
}
|
||||
52
backend/internal/ai/claudecode.go
Normal file
52
backend/internal/ai/claudecode.go
Normal file
@ -0,0 +1,52 @@
|
||||
package ai
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type claudeCodeProvider struct {
|
||||
model string
|
||||
}
|
||||
|
||||
func newClaudeCode(model string) *claudeCodeProvider {
|
||||
if model == "" {
|
||||
model = "claude-sonnet-4-6"
|
||||
}
|
||||
return &claudeCodeProvider{model: model}
|
||||
}
|
||||
|
||||
func (p *claudeCodeProvider) Name() string { return "claudecode" }
|
||||
|
||||
func (p *claudeCodeProvider) Summarize(ctx context.Context, prompt string, _ GenOptions) (string, error) {
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd := exec.CommandContext(ctx, "claude", "-p", prompt, "--model", p.model)
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
|
||||
err := cmd.Run()
|
||||
fmt.Printf("[claudecode] stdout len=%d stderr=%q err=%v\n", stdout.Len(), stderr.String(), err)
|
||||
|
||||
if err != nil {
|
||||
msg := strings.TrimSpace(stderr.String())
|
||||
if msg == "" {
|
||||
msg = strings.TrimSpace(stdout.String())
|
||||
}
|
||||
if msg == "" {
|
||||
msg = err.Error()
|
||||
}
|
||||
return "", fmt.Errorf("claude cli: %s", msg)
|
||||
}
|
||||
return strings.TrimSpace(stdout.String()), nil
|
||||
}
|
||||
|
||||
func (p *claudeCodeProvider) ListModels(_ context.Context) ([]string, error) {
|
||||
return []string{
|
||||
"claude-opus-4-7",
|
||||
"claude-sonnet-4-6",
|
||||
"claude-haiku-4-5-20251001",
|
||||
}, nil
|
||||
}
|
||||
116
backend/internal/ai/gemini.go
Normal file
116
backend/internal/ai/gemini.go
Normal file
@ -0,0 +1,116 @@
|
||||
package ai
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type geminiProvider struct {
|
||||
apiKey string
|
||||
model string
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
func newGemini(apiKey, model string) *geminiProvider {
|
||||
if model == "" {
|
||||
model = "gemini-2.0-flash"
|
||||
}
|
||||
return &geminiProvider{
|
||||
apiKey: apiKey,
|
||||
model: model,
|
||||
client: &http.Client{},
|
||||
}
|
||||
}
|
||||
|
||||
func (p *geminiProvider) Name() string { return "gemini" }
|
||||
|
||||
func (p *geminiProvider) Summarize(ctx context.Context, prompt string, _ GenOptions) (string, error) {
|
||||
url := fmt.Sprintf(
|
||||
"https://generativelanguage.googleapis.com/v1beta/models/%s:generateContent?key=%s",
|
||||
p.model, p.apiKey,
|
||||
)
|
||||
body := map[string]interface{}{
|
||||
"contents": []map[string]interface{}{
|
||||
{"parts": []map[string]string{{"text": prompt}}},
|
||||
},
|
||||
}
|
||||
b, _ := json.Marshal(body)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(b))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := p.client.Do(req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
raw, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("gemini API error %d: %s", resp.StatusCode, raw)
|
||||
}
|
||||
|
||||
var result struct {
|
||||
Candidates []struct {
|
||||
Content struct {
|
||||
Parts []struct {
|
||||
Text string `json:"text"`
|
||||
} `json:"parts"`
|
||||
} `json:"content"`
|
||||
} `json:"candidates"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &result); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(result.Candidates) == 0 || len(result.Candidates[0].Content.Parts) == 0 {
|
||||
return "", nil
|
||||
}
|
||||
return result.Candidates[0].Content.Parts[0].Text, nil
|
||||
}
|
||||
|
||||
func (p *geminiProvider) ListModels(ctx context.Context) ([]string, error) {
|
||||
url := fmt.Sprintf("https://generativelanguage.googleapis.com/v1beta/models?key=%s", p.apiKey)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := p.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("gemini list models error %d: %s", resp.StatusCode, raw)
|
||||
}
|
||||
var result struct {
|
||||
Models []struct {
|
||||
Name string `json:"name"`
|
||||
SupportedMethods []string `json:"supportedGenerationMethods"`
|
||||
} `json:"models"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &result); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var names []string
|
||||
for _, m := range result.Models {
|
||||
for _, method := range m.SupportedMethods {
|
||||
if method == "generateContent" {
|
||||
// name is "models/gemini-xxx", strip prefix
|
||||
id := m.Name
|
||||
if len(id) > 7 {
|
||||
id = id[7:] // strip "models/"
|
||||
}
|
||||
names = append(names, id)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
168
backend/internal/ai/ollama.go
Normal file
168
backend/internal/ai/ollama.go
Normal file
@ -0,0 +1,168 @@
|
||||
package ai
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// OllamaModelInfo holds detailed info about an installed Ollama model.
|
||||
type OllamaModelInfo struct {
|
||||
Name string `json:"name"`
|
||||
Size int64 `json:"size"`
|
||||
ModifiedAt string `json:"modified_at"`
|
||||
Details struct {
|
||||
ParameterSize string `json:"parameter_size"`
|
||||
QuantizationLevel string `json:"quantization_level"`
|
||||
Family string `json:"family"`
|
||||
} `json:"details"`
|
||||
}
|
||||
|
||||
// OllamaProvider implements Provider for Ollama and also exposes model management operations.
|
||||
type OllamaProvider struct {
|
||||
endpoint string
|
||||
model string
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
func newOllama(endpoint, model string) *OllamaProvider {
|
||||
if endpoint == "" {
|
||||
endpoint = "http://ollama:11434"
|
||||
}
|
||||
if model == "" {
|
||||
model = "llama3"
|
||||
}
|
||||
return &OllamaProvider{
|
||||
endpoint: endpoint,
|
||||
model: model,
|
||||
client: &http.Client{},
|
||||
}
|
||||
}
|
||||
|
||||
// NewOllamaManager creates an OllamaProvider for model management (pull/delete/list).
|
||||
func NewOllamaManager(endpoint string) *OllamaProvider {
|
||||
return newOllama(endpoint, "")
|
||||
}
|
||||
|
||||
|
||||
func (p *OllamaProvider) Name() string { return "ollama" }
|
||||
|
||||
func (p *OllamaProvider) Summarize(ctx context.Context, prompt string, opts GenOptions) (string, error) {
|
||||
numCtx := 32768
|
||||
if opts.NumCtx > 0 {
|
||||
numCtx = opts.NumCtx
|
||||
}
|
||||
body := map[string]interface{}{
|
||||
"model": p.model,
|
||||
"prompt": prompt,
|
||||
"stream": false,
|
||||
"think": opts.Think,
|
||||
"options": map[string]interface{}{
|
||||
"num_ctx": numCtx,
|
||||
},
|
||||
}
|
||||
b, _ := json.Marshal(body)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, p.endpoint+"/api/generate", bytes.NewReader(b))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := p.client.Do(req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
raw, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("ollama API error %d: %s", resp.StatusCode, raw)
|
||||
}
|
||||
|
||||
var result struct {
|
||||
Response string `json:"response"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &result); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return result.Response, nil
|
||||
}
|
||||
|
||||
func (p *OllamaProvider) ListModels(ctx context.Context) ([]string, error) {
|
||||
infos, err := p.ListModelsDetailed(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
names := make([]string, len(infos))
|
||||
for i, m := range infos {
|
||||
names[i] = m.Name
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
|
||||
func (p *OllamaProvider) ListModelsDetailed(ctx context.Context) ([]OllamaModelInfo, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, p.endpoint+"/api/tags", nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := p.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
raw, _ := io.ReadAll(resp.Body)
|
||||
var result struct {
|
||||
Models []OllamaModelInfo `json:"models"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &result); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return result.Models, nil
|
||||
}
|
||||
|
||||
// PullModel pulls (downloads) a model from Ollama Hub. Blocks until complete.
|
||||
func (p *OllamaProvider) PullModel(ctx context.Context, name string) error {
|
||||
body, _ := json.Marshal(map[string]interface{}{"name": name, "stream": false})
|
||||
// Use a long-timeout client since model downloads can take many minutes
|
||||
client := &http.Client{Timeout: 60 * time.Minute}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, p.endpoint+"/api/pull", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("ollama pull error %d: %s", resp.StatusCode, raw)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteModel removes a model from local storage.
|
||||
func (p *OllamaProvider) DeleteModel(ctx context.Context, name string) error {
|
||||
body, _ := json.Marshal(map[string]string{"name": name})
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodDelete, p.endpoint+"/api/delete", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := p.client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
|
||||
raw, _ := io.ReadAll(resp.Body)
|
||||
return fmt.Errorf("ollama delete error %d: %s", resp.StatusCode, raw)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
52
backend/internal/ai/openai.go
Normal file
52
backend/internal/ai/openai.go
Normal file
@ -0,0 +1,52 @@
|
||||
package ai
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
openai "github.com/sashabaranov/go-openai"
|
||||
)
|
||||
|
||||
type openAIProvider struct {
|
||||
client *openai.Client
|
||||
model string
|
||||
}
|
||||
|
||||
func newOpenAI(apiKey, model string) *openAIProvider {
|
||||
if model == "" {
|
||||
model = openai.GPT4oMini
|
||||
}
|
||||
return &openAIProvider{
|
||||
client: openai.NewClient(apiKey),
|
||||
model: model,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *openAIProvider) Name() string { return "openai" }
|
||||
|
||||
func (p *openAIProvider) Summarize(ctx context.Context, prompt string, _ GenOptions) (string, error) {
|
||||
resp, err := p.client.CreateChatCompletion(ctx, openai.ChatCompletionRequest{
|
||||
Model: p.model,
|
||||
Messages: []openai.ChatCompletionMessage{
|
||||
{Role: openai.ChatMessageRoleUser, Content: prompt},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(resp.Choices) == 0 {
|
||||
return "", nil
|
||||
}
|
||||
return resp.Choices[0].Message.Content, nil
|
||||
}
|
||||
|
||||
func (p *openAIProvider) ListModels(ctx context.Context) ([]string, error) {
|
||||
resp, err := p.client.ListModels(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var models []string
|
||||
for _, m := range resp.Models {
|
||||
models = append(models, m.ID)
|
||||
}
|
||||
return models, nil
|
||||
}
|
||||
384
backend/internal/ai/pipeline.go
Normal file
384
backend/internal/ai/pipeline.go
Normal file
@ -0,0 +1,384 @@
|
||||
package ai
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/tradarr/backend/internal/crypto"
|
||||
"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 {
|
||||
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
|
||||
}
|
||||
|
||||
func (p *Pipeline) GenerateForUser(ctx context.Context, userID string) (*models.Summary, error) {
|
||||
p.generating.Store(true)
|
||||
defer p.generating.Store(false)
|
||||
|
||||
provider, providerCfg, err := p.buildProviderForRole("summary")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
assets, err := p.repo.GetUserAssets(userID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get user assets: %w", err)
|
||||
}
|
||||
symbols := make([]string, len(assets))
|
||||
for i, a := range assets {
|
||||
symbols[i] = a.Symbol
|
||||
}
|
||||
|
||||
hoursStr, _ := p.repo.GetSetting("articles_lookback_hours")
|
||||
hours, _ := strconv.Atoi(hoursStr)
|
||||
if hours == 0 {
|
||||
hours = 24
|
||||
}
|
||||
|
||||
articles, err := p.repo.GetRecentArticles(hours)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get articles: %w", err)
|
||||
}
|
||||
if len(articles) == 0 {
|
||||
return nil, fmt.Errorf("no recent articles found")
|
||||
}
|
||||
|
||||
maxStr, _ := p.repo.GetSetting("summary_max_articles")
|
||||
maxArticles, _ := strconv.Atoi(maxStr)
|
||||
if maxArticles == 0 {
|
||||
maxArticles = 50
|
||||
}
|
||||
|
||||
// Passe 1 : filtrage par pertinence — seulement si nettement plus d'articles que le max
|
||||
if len(articles) > maxArticles*2 {
|
||||
filterProvider, _, filterErr := p.buildProviderForRole("filter")
|
||||
if filterErr != nil {
|
||||
filterProvider = provider // fallback to summary provider
|
||||
}
|
||||
fmt.Printf("[pipeline] Passe 1 — filtrage : %d articles → sélection des %d plus pertinents…\n", len(articles), maxArticles)
|
||||
t1 := time.Now()
|
||||
articles = p.filterByRelevance(ctx, filterProvider, symbols, articles, maxArticles)
|
||||
fmt.Printf("[pipeline] Passe 1 — terminée en %s : %d articles retenus\n", time.Since(t1).Round(time.Second), len(articles))
|
||||
} else if len(articles) > maxArticles {
|
||||
articles = articles[:maxArticles]
|
||||
fmt.Printf("[pipeline] troncature directe à %d articles (pas assez d'excédent pour justifier un appel IA)\n", maxArticles)
|
||||
}
|
||||
|
||||
systemPrompt, _ := p.repo.GetSetting("ai_system_prompt")
|
||||
if systemPrompt == "" {
|
||||
systemPrompt = DefaultSystemPrompt
|
||||
}
|
||||
|
||||
tz, _ := p.repo.GetSetting("timezone")
|
||||
|
||||
// Passe 2 : résumé complet
|
||||
fmt.Printf("[pipeline] Passe 2 — résumé : génération sur %d articles…\n", len(articles))
|
||||
t2 := time.Now()
|
||||
prompt := buildPrompt(systemPrompt, symbols, articles, tz)
|
||||
// Passe 2 : think activé pour une meilleure qualité d'analyse
|
||||
summary, err := provider.Summarize(ctx, prompt, GenOptions{Think: true, NumCtx: 32768})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("AI summarize: %w", err)
|
||||
}
|
||||
fmt.Printf("[pipeline] Passe 2 — terminée en %s\n", time.Since(t2).Round(time.Second))
|
||||
|
||||
return p.repo.CreateSummary(userID, summary, &providerCfg.ID)
|
||||
}
|
||||
|
||||
// filterByRelevance splits articles into batches and asks the AI to select relevant
|
||||
// ones from each batch. Results are pooled then truncated to max.
|
||||
func (p *Pipeline) filterByRelevance(ctx context.Context, provider Provider, symbols []string, articles []models.Article, max int) []models.Article {
|
||||
batchSizeStr, _ := p.repo.GetSetting("filter_batch_size")
|
||||
batchSize, _ := strconv.Atoi(batchSizeStr)
|
||||
if batchSize <= 0 {
|
||||
batchSize = 20
|
||||
}
|
||||
|
||||
var selected []models.Article
|
||||
numBatches := (len(articles) + batchSize - 1) / batchSize
|
||||
|
||||
for b := 0; b < numBatches; b++ {
|
||||
start := b * batchSize
|
||||
end := start + batchSize
|
||||
if end > len(articles) {
|
||||
end = len(articles)
|
||||
}
|
||||
batch := articles[start:end]
|
||||
|
||||
fmt.Printf("[pipeline] Passe 1 — batch %d/%d (%d articles)…\n", b+1, numBatches, len(batch))
|
||||
t := time.Now()
|
||||
chosen := p.filterBatch(ctx, provider, symbols, batch)
|
||||
fmt.Printf("[pipeline] Passe 1 — batch %d/%d terminé en %s : %d retenus\n", b+1, numBatches, time.Since(t).Round(time.Second), len(chosen))
|
||||
|
||||
selected = append(selected, chosen...)
|
||||
|
||||
// Stop early if we have plenty of candidates
|
||||
if len(selected) >= max*2 {
|
||||
fmt.Printf("[pipeline] Passe 1 — suffisamment de candidats (%d), arrêt anticipé\n", len(selected))
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if len(selected) <= max {
|
||||
return selected
|
||||
}
|
||||
return selected[:max]
|
||||
}
|
||||
|
||||
// filterBatch asks the AI to return all relevant articles from a single batch.
|
||||
func (p *Pipeline) filterBatch(ctx context.Context, provider Provider, symbols []string, batch []models.Article) []models.Article {
|
||||
prompt := buildFilterBatchPrompt(symbols, batch)
|
||||
response, err := provider.Summarize(ctx, prompt, GenOptions{Think: false, NumCtx: 4096})
|
||||
if err != nil {
|
||||
fmt.Printf("[pipeline] filterBatch — échec (%v), conservation du batch entier\n", err)
|
||||
return batch
|
||||
}
|
||||
|
||||
indices := parseIndexArray(response, len(batch))
|
||||
if len(indices) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
filtered := make([]models.Article, 0, len(indices))
|
||||
for _, i := range indices {
|
||||
filtered = append(filtered, batch[i])
|
||||
}
|
||||
return filtered
|
||||
}
|
||||
|
||||
func buildFilterBatchPrompt(symbols []string, batch []models.Article) string {
|
||||
var sb strings.Builder
|
||||
sb.WriteString("Tu es un assistant de trading financier.\n")
|
||||
sb.WriteString(fmt.Sprintf("Parmi les %d articles ci-dessous, sélectionne TOUS ceux pertinents pour un trader actif.\n", len(batch)))
|
||||
|
||||
if len(symbols) > 0 {
|
||||
sb.WriteString("Actifs prioritaires : ")
|
||||
sb.WriteString(strings.Join(symbols, ", "))
|
||||
sb.WriteString("\n")
|
||||
}
|
||||
|
||||
sb.WriteString("\nRéponds UNIQUEMENT avec un tableau JSON des indices retenus (base 0), exemple : [0, 2, 5]\n")
|
||||
sb.WriteString("Si aucun article n'est pertinent, réponds : []\n")
|
||||
sb.WriteString("N'ajoute aucun texte avant ou après le tableau JSON.\n\n")
|
||||
sb.WriteString("Articles :\n")
|
||||
|
||||
for i, a := range batch {
|
||||
sb.WriteString(fmt.Sprintf("[%d] %s (%s)\n", i, a.Title, a.SourceName))
|
||||
}
|
||||
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
var jsonArrayRe = regexp.MustCompile(`\[[\d\s,]+\]`)
|
||||
|
||||
func parseIndexArray(response string, maxIndex int) []int {
|
||||
match := jsonArrayRe.FindString(response)
|
||||
if match == "" {
|
||||
return nil
|
||||
}
|
||||
match = strings.Trim(match, "[]")
|
||||
parts := strings.Split(match, ",")
|
||||
|
||||
seen := make(map[int]bool)
|
||||
var indices []int
|
||||
for _, p := range parts {
|
||||
n, err := strconv.Atoi(strings.TrimSpace(p))
|
||||
if err != nil || n < 0 || n >= maxIndex || seen[n] {
|
||||
continue
|
||||
}
|
||||
seen[n] = true
|
||||
indices = append(indices, n)
|
||||
}
|
||||
return indices
|
||||
}
|
||||
|
||||
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(reportID, excerpt, question string, mgr *ReportManager) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
|
||||
mgr.Register(reportID, cancel)
|
||||
|
||||
go func() {
|
||||
defer cancel()
|
||||
defer mgr.Remove(reportID)
|
||||
|
||||
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)
|
||||
mgr.Register(messageID, cancel)
|
||||
|
||||
go func() {
|
||||
defer cancel()
|
||||
defer mgr.Remove(messageID)
|
||||
|
||||
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()
|
||||
}
|
||||
35
backend/internal/ai/provider.go
Normal file
35
backend/internal/ai/provider.go
Normal file
@ -0,0 +1,35 @@
|
||||
package ai
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// GenOptions permet de contrôler le comportement de génération par appel.
|
||||
type GenOptions struct {
|
||||
Think bool // active le mode raisonnement (Qwen3 /think)
|
||||
NumCtx int // taille du contexte KV (0 = valeur par défaut du provider)
|
||||
}
|
||||
|
||||
type Provider interface {
|
||||
Name() string
|
||||
Summarize(ctx context.Context, prompt string, opts GenOptions) (string, error)
|
||||
ListModels(ctx context.Context) ([]string, error)
|
||||
}
|
||||
|
||||
func NewProvider(name, apiKey, model, endpoint string) (Provider, error) {
|
||||
switch name {
|
||||
case "openai":
|
||||
return newOpenAI(apiKey, model), nil
|
||||
case "anthropic":
|
||||
return newAnthropic(apiKey, model), nil
|
||||
case "gemini":
|
||||
return newGemini(apiKey, model), nil
|
||||
case "ollama":
|
||||
return newOllama(endpoint, model), nil
|
||||
case "claudecode":
|
||||
return newClaudeCode(model), nil
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown provider: %s", name)
|
||||
}
|
||||
}
|
||||
37
backend/internal/ai/report_manager.go
Normal file
37
backend/internal/ai/report_manager.go
Normal file
@ -0,0 +1,37 @@
|
||||
package ai
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// ReportManager tracks in-flight report goroutines so they can be cancelled.
|
||||
type ReportManager struct {
|
||||
mu sync.Mutex
|
||||
cancels map[string]context.CancelFunc
|
||||
}
|
||||
|
||||
func NewReportManager() *ReportManager {
|
||||
return &ReportManager{cancels: make(map[string]context.CancelFunc)}
|
||||
}
|
||||
|
||||
func (m *ReportManager) Register(id string, cancel context.CancelFunc) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.cancels[id] = cancel
|
||||
}
|
||||
|
||||
func (m *ReportManager) Cancel(id string) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if cancel, ok := m.cancels[id]; ok {
|
||||
cancel()
|
||||
delete(m.cancels, id)
|
||||
}
|
||||
}
|
||||
|
||||
func (m *ReportManager) Remove(id string) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
delete(m.cancels, id)
|
||||
}
|
||||
Reference in New Issue
Block a user