fixy
This commit is contained in:
1 parent
1e7c7bbfbb
commit
feebf7d3c1
12 files changed
+248
-70
No files matched your search
@@ -130,11 +130,12 @@ const insertCallSQL = `
|
||||
INSERT INTO ai_call_logs (
|
||||
company_id, user_id, job_id, raw_product_id, role, provider_mode, model,
|
||||
system_prompt, user_prompt, response_text, error, finish_reason,
|
||||
prompt_tokens, completion_tokens, total_tokens, duration_ms)
|
||||
prompt_tokens, completion_tokens, total_tokens, duration_ms,
|
||||
cached_prompt_tokens, cost_micros)
|
||||
VALUES (
|
||||
$1, $2, $3, $4, $5, $6, $7,
|
||||
$8, $9, $10, $11, $12,
|
||||
$13, $14, $15, $16)`
|
||||
$13, $14, $15, $16, $17, $18)`
|
||||
|
||||
// Record persists one call, merging any CallContext on ctx. Capture must never
|
||||
// break the request it is observing: every failure is swallowed after one log line.
|
||||
@@ -167,11 +168,19 @@ func (r *Recorder) Record(ctx context.Context, c Call) {
|
||||
|
||||
writeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
|
||||
defer cancel()
|
||||
// Persist the exact model-rate cost at capture time. Historical call rows stay
|
||||
// NULL rather than displaying a fabricated per-call amount.
|
||||
price := r.priceFor(ctx, c.Model)
|
||||
var recordedCost any
|
||||
if price.InputPerMTok > 0 || price.CachedInputPerMTok > 0 || price.OutputPerMTok > 0 {
|
||||
recordedCost = CostMicros(price, c.PromptTokens, c.CachedPromptTokens, c.OutputTokens)
|
||||
}
|
||||
_, err := r.pool.Exec(writeCtx, insertCallSQL,
|
||||
nullUUID(c.CompanyID), nullUUID(c.UserID), nullUUID(c.JobID), nullUUID(c.RawProductID),
|
||||
c.Role, c.ProviderMode, c.Model,
|
||||
clamp(c.System), clamp(c.User), clamp(c.Response), clamp(c.Error), c.FinishReason,
|
||||
c.PromptTokens, c.OutputTokens, c.TotalTokens, int(c.Duration.Milliseconds()),
|
||||
c.CachedPromptTokens, recordedCost,
|
||||
)
|
||||
if err != nil {
|
||||
r.noteFailure(err)
|
||||
|
||||
@@ -74,3 +74,11 @@ func TestClamp_boundsBody(t *testing.T) {
|
||||
t.Fatal("clamped body must say it was truncated")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallCapturePersistsCostAndCachedTokens(t *testing.T) {
|
||||
for _, name := range []string{"cached_prompt_tokens", "cost_micros"} {
|
||||
if !strings.Contains(insertCallSQL, name) {
|
||||
t.Fatalf("missing AI call capture field %s", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -412,3 +412,15 @@ func TestSanitizeFileName(t *testing.T) {
|
||||
t.Fatalf("got %q", sanitizeFileName("a b*.csv"))
|
||||
}
|
||||
}
|
||||
|
||||
// Historical API processing predates origin tagging. Generated fields remain
|
||||
// visible in Processed without silently transitioning review-state records.
|
||||
func TestGeneratedProductFilterIncludesLegacyContent(t *testing.T) {
|
||||
_, where := appendProcessedProductFilters(ProductFilter{Status: "generated"}, nil, nil)
|
||||
joined := strings.Join(where, " ")
|
||||
for _, value := range []string{"p.status = 'completed'", "p.processed_name", "p.processed_description", "p.meta_title", "p.meta_description", "needs_review"} {
|
||||
if !strings.Contains(joined, value) {
|
||||
t.Fatalf("missing %s in generated filter: %s", value, joined)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -700,9 +700,9 @@ const (
|
||||
WHEN COALESCE(p.field_sources->>'category', '') IN ('llm', 'vector') THEN ''
|
||||
ELSE COALESCE(NULLIF(BTRIM(r.mapped_data->>'category'), ''), NULLIF(BTRIM(r.mapped_data->>'category_unique_id'), ''), '')
|
||||
END`
|
||||
processedHasNameSQL = `(` + processedPreferredNameSQL + ` <> '')`
|
||||
processedHasDescriptionSQL = `(` + processedPreferredDescriptionSQL + ` <> '')`
|
||||
processedHasCategorySQL = `(COALESCE(NULLIF(p.category, ''), '') <> '' AND lower(p.category) <> 'none')`
|
||||
processedHasNameSQL = `(` + processedPreferredNameSQL + ` <> '')`
|
||||
processedHasDescriptionSQL = `(` + processedPreferredDescriptionSQL + ` <> '')`
|
||||
processedHasCategorySQL = `(COALESCE(NULLIF(p.category, ''), '') <> '' AND lower(p.category) <> 'none')`
|
||||
// Resolve display name / canonical unique_id when products store unique_id, UUID id, or name.
|
||||
processedCategoryResolveJoin = `
|
||||
LEFT JOIN LATERAL (
|
||||
@@ -1071,6 +1071,20 @@ func appendProcessedProductFilters(f ProductFilter, args []any, where []string)
|
||||
n, n, n, n, n))
|
||||
}
|
||||
if f.Status != "" {
|
||||
// The dashboard's Processed tab must also surface already-generated legacy
|
||||
// API results. Pre-v16 jobs were not tagged with their origin, so we cannot
|
||||
// safely approve them in a migration. Include only rows with actual generated
|
||||
// fields, preserving their original needs_review status and actions.
|
||||
if f.Status == "generated" {
|
||||
where = append(where, `(p.status = 'completed' OR
|
||||
(p.status IN ('needs_review', 'processed') AND (
|
||||
NULLIF(BTRIM(COALESCE(p.processed_name, '')), '') IS NOT NULL OR
|
||||
NULLIF(BTRIM(COALESCE(p.processed_description, '')), '') IS NOT NULL OR
|
||||
NULLIF(BTRIM(COALESCE(p.meta_title, '')), '') IS NOT NULL OR
|
||||
NULLIF(BTRIM(COALESCE(p.meta_description, '')), '') IS NOT NULL
|
||||
)))`)
|
||||
return args, where
|
||||
}
|
||||
// needs_review includes legacy pipeline status "processed" (pre-P0-8).
|
||||
if f.Status == "needs_review" {
|
||||
where = append(where, "p.status IN ('needs_review', 'processed')")
|
||||
|
||||
@@ -116,13 +116,16 @@ func (s *Server) handleAdminListAICalls(w http.ResponseWriter, r *http.Request)
|
||||
var companyID, companyName, userID, userEmail, jobID, rawProductID string
|
||||
var role, providerMode, model, callErr, finishReason string
|
||||
var promptTokens, completionTokens, totalTokens, durationMS int
|
||||
var cachedTokens *int
|
||||
var costMicros *int64
|
||||
var createdAt time.Time
|
||||
var sysLen, userLen, respLen int
|
||||
var userPreview, respPreview string
|
||||
if err := rows.Scan(&id, &companyID, &companyName, &userID, &userEmail,
|
||||
&jobID, &rawProductID, &role, &providerMode, &model, &callErr, &finishReason,
|
||||
&promptTokens, &completionTokens, &totalTokens, &durationMS, &createdAt,
|
||||
&sysLen, &userLen, &respLen, &userPreview, &respPreview); err != nil {
|
||||
&sysLen, &userLen, &respLen, &userPreview, &respPreview,
|
||||
&cachedTokens, &costMicros); err != nil {
|
||||
Error(w, http.StatusInternalServerError, "scan ai calls failed")
|
||||
return
|
||||
}
|
||||
@@ -132,29 +135,31 @@ func (s *Server) handleAdminListAICalls(w http.ResponseWriter, r *http.Request)
|
||||
outcome = "failed"
|
||||
}
|
||||
items = append(items, map[string]any{
|
||||
"id": id,
|
||||
"company_id": companyID,
|
||||
"company_name": companyName,
|
||||
"user_id": userID,
|
||||
"user_email": userEmail,
|
||||
"job_id": jobID,
|
||||
"raw_product_id": rawProductID,
|
||||
"role": role,
|
||||
"provider_mode": providerMode,
|
||||
"model": model,
|
||||
"outcome": outcome,
|
||||
"error": callErr,
|
||||
"finish_reason": finishReason,
|
||||
"prompt_tokens": promptTokens,
|
||||
"completion_tokens": completionTokens,
|
||||
"total_tokens": totalTokens,
|
||||
"duration_ms": durationMS,
|
||||
"created_at": createdAt,
|
||||
"system_length": sysLen,
|
||||
"user_length": userLen,
|
||||
"response_length": respLen,
|
||||
"user_preview": userPreview,
|
||||
"response_preview": respPreview,
|
||||
"id": id,
|
||||
"company_id": companyID,
|
||||
"company_name": companyName,
|
||||
"user_id": userID,
|
||||
"user_email": userEmail,
|
||||
"job_id": jobID,
|
||||
"raw_product_id": rawProductID,
|
||||
"role": role,
|
||||
"provider_mode": providerMode,
|
||||
"model": model,
|
||||
"outcome": outcome,
|
||||
"error": callErr,
|
||||
"finish_reason": finishReason,
|
||||
"prompt_tokens": promptTokens,
|
||||
"completion_tokens": completionTokens,
|
||||
"total_tokens": totalTokens,
|
||||
"cached_prompt_tokens": cachedTokens,
|
||||
"cost_micros": costMicros,
|
||||
"duration_ms": durationMS,
|
||||
"created_at": createdAt,
|
||||
"system_length": sysLen,
|
||||
"user_length": userLen,
|
||||
"response_length": respLen,
|
||||
"user_preview": userPreview,
|
||||
"response_preview": respPreview,
|
||||
})
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
@@ -187,7 +192,8 @@ func adminAICallsListSQL(where string, limitArg int) string {
|
||||
l.prompt_tokens, l.completion_tokens, l.total_tokens, l.duration_ms, l.created_at,
|
||||
length(l.system_prompt), length(l.user_prompt), length(l.response_text),
|
||||
left(l.user_prompt, ` + preview + `),
|
||||
left(l.response_text, ` + preview + `)
|
||||
left(l.response_text, ` + preview + `),
|
||||
l.cached_prompt_tokens, l.cost_micros
|
||||
FROM ai_call_logs l
|
||||
LEFT JOIN companies c ON c.id = l.company_id
|
||||
LEFT JOIN users u ON u.id = l.user_id
|
||||
@@ -212,6 +218,8 @@ func (s *Server) handleAdminGetAICall(w http.ResponseWriter, r *http.Request) {
|
||||
var role, providerMode, model, callErr, finishReason string
|
||||
var systemPrompt, userPrompt, responseText string
|
||||
var promptTokens, completionTokens, totalTokens, durationMS int
|
||||
var cachedTokens *int
|
||||
var costMicros *int64
|
||||
var createdAt time.Time
|
||||
err = s.Pool.QueryRow(ctx, `
|
||||
SELECT COALESCE(l.company_id::text, ''), COALESCE(c.name, ''),
|
||||
@@ -219,7 +227,8 @@ func (s *Server) handleAdminGetAICall(w http.ResponseWriter, r *http.Request) {
|
||||
COALESCE(l.job_id::text, ''), COALESCE(l.raw_product_id::text, ''),
|
||||
l.role, l.provider_mode, l.model, l.error, l.finish_reason,
|
||||
l.system_prompt, l.user_prompt, l.response_text,
|
||||
l.prompt_tokens, l.completion_tokens, l.total_tokens, l.duration_ms, l.created_at
|
||||
l.prompt_tokens, l.completion_tokens, l.total_tokens, l.duration_ms, l.created_at,
|
||||
l.cached_prompt_tokens, l.cost_micros
|
||||
FROM ai_call_logs l
|
||||
LEFT JOIN companies c ON c.id = l.company_id
|
||||
LEFT JOIN users u ON u.id = l.user_id
|
||||
@@ -227,7 +236,8 @@ func (s *Server) handleAdminGetAICall(w http.ResponseWriter, r *http.Request) {
|
||||
Scan(&companyID, &companyName, &userID, &userEmail, &jobID, &rawProductID,
|
||||
&role, &providerMode, &model, &callErr, &finishReason,
|
||||
&systemPrompt, &userPrompt, &responseText,
|
||||
&promptTokens, &completionTokens, &totalTokens, &durationMS, &createdAt)
|
||||
&promptTokens, &completionTokens, &totalTokens, &durationMS, &createdAt,
|
||||
&cachedTokens, &costMicros)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
// Expired rows are the common case here, so say so rather than a bare 404.
|
||||
Error(w, http.StatusNotFound, "call not found (captured calls are kept for "+
|
||||
@@ -244,27 +254,29 @@ func (s *Server) handleAdminGetAICall(w http.ResponseWriter, r *http.Request) {
|
||||
outcome = "failed"
|
||||
}
|
||||
JSON(w, http.StatusOK, map[string]any{
|
||||
"id": id,
|
||||
"company_id": companyID,
|
||||
"company_name": companyName,
|
||||
"user_id": userID,
|
||||
"user_email": userEmail,
|
||||
"job_id": jobID,
|
||||
"raw_product_id": rawProductID,
|
||||
"role": role,
|
||||
"provider_mode": providerMode,
|
||||
"model": model,
|
||||
"outcome": outcome,
|
||||
"error": callErr,
|
||||
"finish_reason": finishReason,
|
||||
"system_prompt": systemPrompt,
|
||||
"user_prompt": userPrompt,
|
||||
"response_text": responseText,
|
||||
"prompt_tokens": promptTokens,
|
||||
"completion_tokens": completionTokens,
|
||||
"total_tokens": totalTokens,
|
||||
"duration_ms": durationMS,
|
||||
"created_at": createdAt,
|
||||
"retention_days": aiaudit.RetentionDays,
|
||||
"id": id,
|
||||
"company_id": companyID,
|
||||
"company_name": companyName,
|
||||
"user_id": userID,
|
||||
"user_email": userEmail,
|
||||
"job_id": jobID,
|
||||
"raw_product_id": rawProductID,
|
||||
"role": role,
|
||||
"provider_mode": providerMode,
|
||||
"model": model,
|
||||
"outcome": outcome,
|
||||
"error": callErr,
|
||||
"finish_reason": finishReason,
|
||||
"system_prompt": systemPrompt,
|
||||
"user_prompt": userPrompt,
|
||||
"response_text": responseText,
|
||||
"prompt_tokens": promptTokens,
|
||||
"completion_tokens": completionTokens,
|
||||
"total_tokens": totalTokens,
|
||||
"cached_prompt_tokens": cachedTokens,
|
||||
"cost_micros": costMicros,
|
||||
"duration_ms": durationMS,
|
||||
"created_at": createdAt,
|
||||
"retention_days": aiaudit.RetentionDays,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
-- +goose Up
|
||||
-- Exact per-call cost/cached tokens for the short-lived AI call inspector.
|
||||
-- Nullable because historical rows did not capture per-call costs.
|
||||
ALTER TABLE ai_call_logs ADD COLUMN IF NOT EXISTS cached_prompt_tokens INTEGER;
|
||||
ALTER TABLE ai_call_logs ADD COLUMN IF NOT EXISTS cost_micros BIGINT;
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE ai_call_logs DROP COLUMN IF EXISTS cost_micros;
|
||||
ALTER TABLE ai_call_logs DROP COLUMN IF EXISTS cached_prompt_tokens;
|
||||
Reference in new issue
Block a user