feat(generation): score articles with selected relevance model (#48)
This commit is contained in:
@ -5,6 +5,7 @@ import (
|
||||
"crypto/rand"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@ -14,6 +15,7 @@ import (
|
||||
)
|
||||
|
||||
type UserInput struct {
|
||||
RankingModelID *string
|
||||
SummaryContext string
|
||||
SummaryPromptTokenBudget int
|
||||
SummaryModelID *string
|
||||
@ -23,10 +25,12 @@ type UserInput struct {
|
||||
Sources []models.Source
|
||||
}
|
||||
type Candidate struct {
|
||||
ID, SourceID string
|
||||
Article scraper.Article
|
||||
orderDate *time.Time
|
||||
orderFrozen bool
|
||||
RelevanceScore float64
|
||||
relevanceScored bool
|
||||
ID, SourceID string
|
||||
Article scraper.Article
|
||||
orderDate *time.Time
|
||||
orderFrozen bool
|
||||
}
|
||||
type SourceStat struct {
|
||||
Feeds *scraper.FeedCounts `json:"feeds,omitempty"`
|
||||
@ -106,7 +110,14 @@ type SummaryResolver interface {
|
||||
type UseCase interface {
|
||||
Generate(context.Context, string) (Result, error)
|
||||
}
|
||||
type RankingResolver interface {
|
||||
Resolve(context.Context, string, *string) (models.ResolvedSummaryModel, error)
|
||||
}
|
||||
|
||||
type Dependencies struct {
|
||||
Scorer TitleScorer
|
||||
ScorerFactory func(models.ResolvedSummaryModel) (TitleScorer, error)
|
||||
RankingResolver RankingResolver
|
||||
Decider MentionDecider
|
||||
Names MentionNameResolver
|
||||
Repository Repository
|
||||
@ -195,6 +206,27 @@ func (u *useCase) Generate(ctx context.Context, userID string) (Result, error) {
|
||||
if resolved.Summarizer == nil {
|
||||
return finish("failed", "summary_model_unavailable", "")
|
||||
}
|
||||
// Production always installs this resolver. Isolated tests may inject only
|
||||
// the downstream ports, as with the summary provider.
|
||||
scorer := u.Scorer
|
||||
if u.RankingResolver != nil {
|
||||
if input.RankingModelID == nil {
|
||||
return finish("failed", "ranking_model_unavailable", "")
|
||||
}
|
||||
model, resolveErr := u.RankingResolver.Resolve(ctx, userID, input.RankingModelID)
|
||||
if resolveErr != nil {
|
||||
if errors.Is(resolveErr, models.ErrRankingModelIncompatible) {
|
||||
return finish("failed", "ranking_model_incompatible", "")
|
||||
}
|
||||
return finish("failed", "ranking_model_unavailable", "")
|
||||
}
|
||||
if u.ScorerFactory != nil {
|
||||
scorer, err = u.ScorerFactory(model)
|
||||
if err != nil || scorer == nil {
|
||||
return finish("failed", "ranking_model_unavailable", "")
|
||||
}
|
||||
}
|
||||
}
|
||||
if u.Decider == nil {
|
||||
return finish("failed", "laya_unavailable", "")
|
||||
}
|
||||
@ -205,6 +237,13 @@ func (u *useCase) Generate(ctx context.Context, userID string) (Result, error) {
|
||||
candidates := []Candidate{}
|
||||
stats := map[string]int{}
|
||||
partial := false
|
||||
type sourceBatch struct {
|
||||
source models.Source
|
||||
stat SourceStat
|
||||
articles []scraper.Article
|
||||
scores []float64
|
||||
}
|
||||
batches := []sourceBatch{}
|
||||
for _, source := range input.Sources {
|
||||
if !source.Operational() {
|
||||
continue
|
||||
@ -238,11 +277,75 @@ func (u *useCase) Generate(ctx context.Context, userID string) (Result, error) {
|
||||
stat.Status = "failed"
|
||||
stat.FailureCode = "source_unavailable"
|
||||
partial = true
|
||||
} else {
|
||||
articles = recentArticles(articles)
|
||||
articles = nil
|
||||
}
|
||||
batches = append(batches, sourceBatch{source: source, stat: stat, articles: articles})
|
||||
stats[source.ID] = len(out.SourceStats)
|
||||
out.SourceStats = append(out.SourceStats, stat)
|
||||
}
|
||||
if scorer != nil {
|
||||
request := TitleScoreRequest{Watchlist: []ScoringCompany{}, Titles: []ScoringTitle{}}
|
||||
for _, asset := range input.Assets {
|
||||
id := asset.ID
|
||||
if asset.CompanyID != nil {
|
||||
id = *asset.CompanyID
|
||||
}
|
||||
request.Watchlist = append(request.Watchlist, ScoringCompany{ID: id, Name: asset.Name})
|
||||
}
|
||||
for _, batch := range batches {
|
||||
for _, article := range batch.articles {
|
||||
request.Titles = append(request.Titles, ScoringTitle{Index: len(request.Titles), Title: article.Title})
|
||||
}
|
||||
}
|
||||
if len(request.Titles) > 0 {
|
||||
scores, scoreErr := scorer.Score(ctx, request)
|
||||
if scoreErr != nil || ctx.Err() != nil {
|
||||
code := "relevance_scoring_failed"
|
||||
if errors.Is(scoreErr, ErrRelevanceResponseInvalid) {
|
||||
code = "relevance_response_invalid"
|
||||
}
|
||||
return finish("failed", code, "")
|
||||
}
|
||||
valid := len(scores) == len(request.Titles)
|
||||
for _, score := range scores {
|
||||
if math.IsNaN(score) || math.IsInf(score, 0) || score < 0 || score > 100 {
|
||||
valid = false
|
||||
}
|
||||
}
|
||||
if !valid {
|
||||
return finish("failed", "relevance_response_invalid", "")
|
||||
}
|
||||
offset := 0
|
||||
for i := range batches {
|
||||
n := len(batches[i].articles)
|
||||
batches[i].scores = append([]float64(nil), scores[offset:offset+n]...)
|
||||
offset += n
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, batch := range batches {
|
||||
source, stat, articles := batch.source, batch.stat, batch.articles
|
||||
feed := u.Scrapers[*source.SourceKey]
|
||||
if stat.Status != "failed" {
|
||||
if scorer != nil {
|
||||
pool := make([]Candidate, len(articles))
|
||||
for i, article := range articles {
|
||||
pool[i] = Candidate{Article: article, RelevanceScore: batch.scores[i]}
|
||||
}
|
||||
sortByRelevance(pool)
|
||||
batch.scores = make([]float64, len(pool))
|
||||
for i, c := range pool {
|
||||
articles[i] = c.Article
|
||||
batch.scores[i] = c.RelevanceScore
|
||||
}
|
||||
} else {
|
||||
articles = recentArticles(articles)
|
||||
batch.scores = make([]float64, len(articles))
|
||||
}
|
||||
if len(articles) > stat.ArticleLimit {
|
||||
articles = articles[:stat.ArticleLimit]
|
||||
}
|
||||
|
||||
orderDates := make([]*time.Time, len(articles))
|
||||
for i, a := range articles {
|
||||
if a.PublishedAt != nil {
|
||||
@ -309,12 +412,12 @@ func (u *useCase) Generate(ctx context.Context, userID string) (Result, error) {
|
||||
article.Content = ""
|
||||
article.ContentTruncated = false
|
||||
}
|
||||
candidates = append(candidates, Candidate{ID: NewID(), SourceID: source.ID, Article: article, orderDate: orderDates[i], orderFrozen: true})
|
||||
candidates = append(candidates, Candidate{ID: NewID(), SourceID: source.ID, Article: article, orderDate: orderDates[i], orderFrozen: true, RelevanceScore: batch.scores[i], relevanceScored: scorer != nil})
|
||||
}
|
||||
}
|
||||
stats[source.ID] = len(out.SourceStats)
|
||||
out.SourceStats = append(out.SourceStats, stat)
|
||||
out.SourceStats[stats[source.ID]] = stat
|
||||
}
|
||||
|
||||
if len(candidates) == 0 {
|
||||
if input.RankingMode == "title_content" && out.TotalCandidates > 0 {
|
||||
return finish("no_results", "no_complete_content", "")
|
||||
|
||||
Reference in New Issue
Block a user