From a0e9cf7e02bc417cdd5c88f0ad5f78319cb7447f Mon Sep 17 00:00:00 2001 From: cryptocommuniums-afk Date: Sun, 1 Feb 2026 11:46:22 +0800 Subject: [PATCH] Fallback to raw LLM content when JSON parsing fails --- backend/main.go | 40 ++++++++++++++++++++++++++++++++++------ 1 file changed, 34 insertions(+), 6 deletions(-) diff --git a/backend/main.go b/backend/main.go index 4200a07..7b40af5 100644 --- a/backend/main.go +++ b/backend/main.go @@ -16,6 +16,7 @@ import ( "net/http" "os" "path/filepath" + "regexp" "strconv" "strings" "time" @@ -733,11 +734,8 @@ func (c *LLMClient) FormatAndGrade(ctx context.Context, title, ocrText string) ( result := LLMResult{} if err := decodeLLMResult(content, &result); err != nil { - fallback := strings.TrimSpace(content) - if fallback == "" { - fallback = ocrText - } - return fallback, "LLM 返回无法解析为 JSON,已返回原始内容。", 0, nil + markdown, feedback, score := fallbackFromContent(content, ocrText) + return markdown, feedback, score, nil } markdown := strings.TrimSpace(result.Markdown) @@ -792,7 +790,8 @@ func (c *LLMClient) FormatAndGradeFromImages(ctx context.Context, title string, result := LLMResult{} if err := decodeLLMResult(content, &result); err != nil { - return "", "LLM 返回无法解析为 JSON。", 0, nil + markdown, feedback, score := fallbackFromContent(content, "未识别到有效内容。") + return markdown, feedback, score, nil } markdown := strings.TrimSpace(result.Markdown) @@ -896,6 +895,35 @@ func decodeLLMResult(content string, out *LLMResult) error { return nil } +var scorePattern = regexp.MustCompile(`(?i)(?:评分|score)[::]?\s*([0-9]{1,3})`) + +func parseScoreFromText(text string) int { + matches := scorePattern.FindStringSubmatch(text) + if len(matches) < 2 { + return 0 + } + value, err := strconv.Atoi(matches[1]) + if err != nil { + return 0 + } + if value < 0 { + return 0 + } + if value > 100 { + return 100 + } + return value +} + +func fallbackFromContent(content, defaultMarkdown string) (string, string, int) { + markdown := strings.TrimSpace(content) + if markdown == "" { + markdown = defaultMarkdown + } + score := parseScoreFromText(markdown) + return markdown, "", score +} + func ensureColumn(db *sql.DB, table, column, columnType string) error { rows, err := db.Query(fmt.Sprintf("PRAGMA table_info(%s);", table)) if err != nil {