Formerly KrillinAI, VideoTranslation and Dubbing Tool for 120+ Languages. Open-source AI workspace for creators, powered by Codex. Video downloader, video translation, create videos, images, audios, and edits with Agents in one place. For your Social Media like YouTube, TikTok, Instagram, etc.
TypeScript agent-skillscodex-clideskop-appdubbingimage-generationlocalizationskillsttsvideo-editingvideo-generationvideo-transcriptionvideo-translation
fix(subtitle): pick the LLM JSON object that carries the expected field
askalf45348ce860a8
diff --git a/runtime/krillinai/internal/service/audio2subtitle.go b/runtime/krillinai/internal/service/audio2subtitle.goindex 8f9a9f15..306402fa 100644--- a/runtime/krillinai/internal/service/audio2subtitle.go+++ b/runtime/krillinai/internal/service/audio2subtitle.go@@ -1872,7 +1872,7 @@ func (s Service) splitLongSentence(item *TranslatedItem) ([]*TranslatedItem, errTranslatedPart string `json:"translated_part"`} `json:"align"`}- if err := json.Unmarshal([]byte(util.ExtractJSON(response)), &splitResult); err != nil {+ if err := json.Unmarshal([]byte(util.ExtractJSONObject(response, "align")), &splitResult); err != nil {log.GetLogger().Error("splitLongSentence parse split result error", zap.Error(err), zap.Any("response", response))return nil, fmt.Errorf("parse split result error: %w", err)}@@ -1911,7 +1911,7 @@ func (s Service) splitOriginLongSentence(sentence string) ([]string, error) {} `json:"short_sentences"`}- cleanResponse := util.ExtractJSON(response)+ cleanResponse := util.ExtractJSONObject(response, "short_sentences")if err = json.Unmarshal([]byte(cleanResponse), &splitResult); err != nil {log.GetLogger().Error("splitOriginLongSentence parse split result error", zap.Error(err), zap.Any("response", response))continuediff --git a/runtime/krillinai/internal/service/audio2subtitle_test.go b/runtime/krillinai/internal/service/audio2subtitle_test.goindex dd48a93d..9d11689b 100644--- a/runtime/krillinai/internal/service/audio2subtitle_test.go+++ b/runtime/krillinai/internal/service/audio2subtitle_test.go@@ -501,3 +501,70 @@ func TestSplitLongSentenceToleratesConversationalPrefix(t *testing.T) {t.Fatalf("unexpected items: %+v, %+v", items[0], items[1])}}++// TestSplitLongSentenceRejectsDecoyObject 覆盖说明文字里带示例 JSON 的响应:+// 真正的对齐结果前面出现一个合法但无关的对象。按字段挑选候选之前,+// 这个示例会被当成回答解析出来,splitLongSentence 于是返回“成功但为空”的分割结果,+// 既不报错也不重试,长句被静默丢弃。+func TestSplitLongSentenceRejectsDecoyObject(t *testing.T) {+ log.InitLogger()+ completer := &scriptedCompleter{responses: []string{+ "格式示例:{}\n{\n \"align\": [\n { \"origin_part\": \"I want to show you\", \"translated_part\": \"Ich möchte es Ihnen zeigen\" },\n { \"origin_part\": \"how it works\", \"translated_part\": \"wie es funktioniert\" }\n ]\n}",+ }}+ service := Service{ChatCompleter: completer}++ items, err := service.splitLongSentence(&TranslatedItem{+ OriginText: "I want to show you how it works",+ TranslatedText: "Ich möchte es Ihnen zeigen wie es funktioniert",+ })+ if err != nil {+ t.Fatalf("splitLongSentence() error = %v, want nil", err)+ }+ if len(items) != 2 {+ t.Fatalf("items = %+v, want 2 items(示例对象不应被当作回答)", items)+ }+ if items[0].OriginText != "I want to show you" || items[1].TranslatedText != "wie es funktioniert" {+ t.Fatalf("unexpected items: %+v, %+v", items[0], items[1])+ }+}++// TestSplitOriginLongSentenceRejectsDecoyObject 覆盖同一类响应在重试型解析点上的表现:+// 示例对象被解析成功但不含 short_sentences,循环随即 break,+// 三次重试一次都不会发生,函数返回空切片且 err 为 nil。+func TestSplitOriginLongSentenceRejectsDecoyObject(t *testing.T) {+ log.InitLogger()+ completer := &scriptedCompleter{responses: []string{+ "请按如下格式输出:{\"example\": true}\n{\n \"short_sentences\": [\n { \"text\": \"And the reason why they chose the owl is because\" },\n { \"text\": \"the owl is a symbol used in Europe\" }\n ]\n}",+ }}+ service := Service{ChatCompleter: completer}++ sentences, err := service.splitOriginLongSentence("And the reason why they chose the owl is because the owl is a symbol used in Europe")+ if err != nil {+ t.Fatalf("splitOriginLongSentence() error = %v, want nil", err)+ }+ if completer.calls != 1 {+ t.Fatalf("ChatCompletion 调用次数 = %d, want 1(无需重试)", completer.calls)+ }+ want := []string{+ "And the reason why they chose the owl is because",+ "the owl is a symbol used in Europe",+ }+ if fmt.Sprint(sentences) != fmt.Sprint(want) {+ t.Fatalf("sentences = %v, want %v", sentences, want)+ }+}++// TestSplitLongSentenceStillFailsOnGarbage (control) 完全不含目标字段的响应仍然是解析错误。+// 该行为在修复前后一致,用于证明按字段挑选候选没有把坏响应变成“成功但为空”。+func TestSplitLongSentenceStillFailsOnGarbage(t *testing.T) {+ log.InitLogger()+ completer := &scriptedCompleter{responses: []string{"抱歉,我无法完成这个请求"}}+ service := Service{ChatCompleter: completer}++ if _, err := service.splitLongSentence(&TranslatedItem{+ OriginText: "I want to show you how it works",+ TranslatedText: "Ich möchte es Ihnen zeigen wie es funktioniert",+ }); err == nil {+ t.Fatal("splitLongSentence() error = nil, want parse error")+ }+}diff --git a/runtime/krillinai/internal/service/translate.go b/runtime/krillinai/internal/service/translate.goindex 4274feaa..1c56de26 100644--- a/runtime/krillinai/internal/service/translate.go+++ b/runtime/krillinai/internal/service/translate.go@@ -139,7 +139,7 @@ func (t *Translator) splitOriginLongSentence(sentence string) ([]string, error)} `json:"short_sentences"`}- cleanResponse := util.ExtractJSON(response)+ cleanResponse := util.ExtractJSONObject(response, "short_sentences")if err = json.Unmarshal([]byte(cleanResponse), &splitResult); err != nil {log.GetLogger().Error("splitOriginLongSentence parse split result error", zap.Error(err), zap.Any("response", response))continue@@ -724,7 +724,7 @@ Required JSON format (output ONLY this structure):zap.Int("响应长度", len(response)))// 解析JSON响应- cleanResponse := util.ExtractJSON(response)+ cleanResponse := util.ExtractJSONObject(response, "translations")var result struct {Translations []struct {diff --git a/runtime/krillinai/internal/service/translate_test.go b/runtime/krillinai/internal/service/translate_test.goindex 4861f975..04c2a1ab 100644--- a/runtime/krillinai/internal/service/translate_test.go+++ b/runtime/krillinai/internal/service/translate_test.go@@ -73,3 +73,56 @@ func TestBatchTranslateTextsToleratesConversationalPrefix(t *testing.T) {t.Fatalf("translations = %v, want %v", translations, want)}}++// TestTranslatorSplitOriginLongSentenceRejectsDecoyObject 覆盖 Translator 上同形的解析点:+// 说明文字里的示例对象在按字段挑选候选之前会被当成回答,+// 循环 break 后返回空切片且 err 为 nil,整句拆分被静默跳过。+func TestTranslatorSplitOriginLongSentenceRejectsDecoyObject(t *testing.T) {+ log.InitLogger()+ completer := &scriptedCompleter{responses: []string{+ "请按如下格式输出:{}\n{\n \"short_sentences\": [\n { \"text\": \"And the reason why they chose the owl is because\" },\n { \"text\": \"the owl is a symbol used in Europe\" }\n ]\n}",+ }}+ translator := &Translator{chatCompleter: completer}++ sentences, err := translator.splitOriginLongSentence("And the reason why they chose the owl is because the owl is a symbol used in Europe")+ if err != nil {+ t.Fatalf("splitOriginLongSentence() error = %v, want nil", err)+ }+ if completer.calls != 1 {+ t.Fatalf("ChatCompletion 调用次数 = %d, want 1(无需重试)", completer.calls)+ }+ want := []string{+ "And the reason why they chose the owl is because",+ "the owl is a symbol used in Europe",+ }+ if fmt.Sprint(sentences) != fmt.Sprint(want) {+ t.Fatalf("sentences = %v, want %v", sentences, want)+ }+}++// TestBatchTranslateTextsRejectsDecoyObject 覆盖批量翻译的解析点:+// 示例对象被当作回答时 translations 为空,数量校验失败,+// 该请求会白白重试三次并最终丢掉整批译文。+func TestBatchTranslateTextsRejectsDecoyObject(t *testing.T) {+ log.InitLogger()+ completer := &scriptedCompleter{responses: []string{+ "输出格式示例:{}\n```json\n{\n \"translations\": [\n { \"index\": 1, \"text\": \"第一句\" },\n { \"index\": 2, \"text\": \"第二句\" },\n ]\n}\n```",+ }}+ translator := &Translator{chatCompleter: completer}++ translations, err := translator.batchTranslateTexts(+ []string{"first sentence", "second sentence"},+ types.StandardLanguageCode("en"),+ types.StandardLanguageCode("zh_cn"),+ )+ if err != nil {+ t.Fatalf("batchTranslateTexts() error = %v, want nil", err)+ }+ if completer.calls != 1 {+ t.Fatalf("ChatCompletion 调用次数 = %d, want 1(无需重试)", completer.calls)+ }+ want := []string{"第一句", "第二句"}+ if fmt.Sprint(translations) != fmt.Sprint(want) {+ t.Fatalf("translations = %v, want %v", translations, want)+ }+}diff --git a/runtime/krillinai/pkg/util/json.go b/runtime/krillinai/pkg/util/json.goindex 42166c4b..f8791e54 100644--- a/runtime/krillinai/pkg/util/json.go+++ b/runtime/krillinai/pkg/util/json.go@@ -1,22 +1,45 @@package util-import "strings"+import (+ "encoding/json"+ "strings"+)-// ExtractJSON 从大模型返回的文本中提取第一个完整的 JSON 值。+// ExtractJSONObject 从大模型返回的文本中提取顶层带有 requiredKey 字段的 JSON 对象。// 本地模型(如通过 Ollama 运行的 llama3.1)经常在 JSON 前后附带对话式说明,// 或在 } 、] 之前多输出一个逗号,这两种情况都会让 encoding/json 解析失败。-// 该函数先去掉 Markdown 代码块标记,再从第一个 { 或 [ 开始按嵌套深度找到匹配的结束符,-// 丢弃前后多余的文本,并去掉结束符前的尾随逗号。-// 扫描会跳过字符串字面量中的内容,因此正文里的括号、引号和逗号不会被破坏。-// 若文本中不存在 JSON 结构,或结构不完整(缺少结束符),则原样返回去除首尾空白的输入,-// 让调用方拿到真实的解析错误。-func ExtractJSON(response string) string {+// 说明里还可能带上示例或解释用的 JSON(如 {} 或 {"note":"..."}),+// 因此这里按顺序扫描文本中的每个完整 JSON 值,只接受顶层带 requiredKey 的对象,+// 避免把示例当成模型真正的回答,从而解析出一个空结果。+// 若文本中没有这样的对象,则原样返回去除首尾空白的输入,+// 让调用方拿到真实的解析错误并走原有的重试逻辑。+func ExtractJSONObject(response, requiredKey string) string {trimmed := CleanMarkdownCodeBlock(response)- start := strings.IndexAny(trimmed, "{[")+ for offset := 0; offset < len(trimmed); {+ value, end, ok := extractFirstJSONValue(trimmed, offset)+ if !ok {+ break+ }+ if hasTopLevelKey(value, requiredKey) {+ return value+ }+ offset = end+ }++ return trimmed+}++// extractFirstJSONValue 从 from 开始找到第一个 { 或 [,按嵌套深度取到匹配的结束符,+// 返回该 JSON 值、它在 s 中结束后的下一个位置,以及是否找到完整结构。+// 扫描会跳过字符串字面量中的内容,因此正文里的括号、引号和逗号不会被破坏;+// 结束符前的尾随逗号会被去掉。结构不完整(缺少结束符)时不做猜测。+func extractFirstJSONValue(s string, from int) (string, int, bool) {+ start := strings.IndexAny(s[from:], "{[")if start < 0 {- return trimmed+ return "", len(s), false}+ start += fromvar (builder strings.Builder@@ -24,8 +47,8 @@ func ExtractJSON(response string) string {inString boolescaped bool)- for i := start; i < len(trimmed); i++ {- c := trimmed[i]+ for i := start; i < len(s); i++ {+ c := s[i]if inString {builder.WriteByte(c)@@ -53,12 +76,22 @@ func ExtractJSON(response string) string {builder.WriteByte(c)if depth == 0 {- return builder.String()+ return builder.String(), i + 1, true}}- // 结构不完整,不做猜测- return trimmed+ return "", len(s), false+}++// hasTopLevelKey 判断 value 是不是顶层含有 key 字段的 JSON 对象。+// 数组、标量以及解析失败的内容都不算,嵌套在下层的同名字段也不算。+func hasTopLevelKey(value, key string) bool {+ var fields map[string]json.RawMessage+ if err := json.Unmarshal([]byte(value), &fields); err != nil {+ return false+ }+ _, ok := fields[key]+ return ok}// trimTrailingComma 去掉已写入内容末尾的逗号(含其后的空白),用于容忍结束符前的尾随逗号。diff --git a/runtime/krillinai/pkg/util/json_extract_boundary_test.go b/runtime/krillinai/pkg/util/json_extract_boundary_test.goindex 90c42e40..a9c05f14 100644--- a/runtime/krillinai/pkg/util/json_extract_boundary_test.go+++ b/runtime/krillinai/pkg/util/json_extract_boundary_test.go@@ -2,113 +2,194 @@ package utilimport "testing"-// TestExtractJSONScannerBoundaries 覆盖扫描器本身的边界:转义处理、行尾符号、+// TestExtractJSONObjectScannerBoundaries 覆盖扫描器本身的边界:转义处理、行尾符号、// BOM、Unicode 转义与更深的嵌套。这些输入在修复前都会原样带着噪声交给// encoding/json,因此每一条都能区分修复前后的行为。-func TestExtractJSONScannerBoundaries(t *testing.T) {+func TestExtractJSONObjectScannerBoundaries(t *testing.T) {tests := []struct {name stringresponse string+ key stringwant string}{{name: "转义反斜杠结尾的字符串后仍能识别尾随逗号",response: `{"a":"x\\",}`,+ key: "a",want: `{"a":"x\\"}`,},{name: "Windows 换行的尾随逗号",response: "{\r\n\"a\": 1,\r\n}",+ key: "a",want: "{\r\n\"a\": 1}",},{name: "BOM 前缀被丢弃",response: "\ufeff{\"a\":1}",+ key: "a",want: `{"a":1}`,},{name: "字符串内的 Unicode 转义不影响嵌套深度",response: `{"a":"\u007d","b":2,}`,+ key: "a",want: `{"a":"\u007d","b":2}`,},{name: "三层嵌套的连续尾随逗号",response: `{"a":{"b":{"c":[1,],},},}`,+ key: "a",want: `{"a":{"b":{"c":[1]}}}`,},{name: "嵌套数组的尾随逗号",- response: `[[1,],]`,- want: `[[1]]`,+ response: `{"a":[[1,],],}`,+ key: "a",+ want: `{"a":[[1]]}`,},}for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {- if got := ExtractJSON(tt.response); got != tt.want {- t.Errorf("ExtractJSON() = %q, want %q", got, tt.want)+ if got := ExtractJSONObject(tt.response, tt.key); got != tt.want {+ t.Errorf("ExtractJSONObject() = %q, want %q", got, tt.want)}})}}-// TestExtractJSONTakesFirstJSONValue 固定“取第一个 JSON 值”的语义。-// 扫描从第一个 { 或 [ 开始,因此正文里出现在真正 JSON 之前的方括号或-// 示意性对象会被当作目标。这是该实现已知且有意的取舍,在此显式钉住,-// 以免日后被误认为回归。-func TestExtractJSONTakesFirstJSONValue(t *testing.T) {+// TestExtractJSONObjectSkipsDecoyValues 钉住按字段选取候选的语义:+// 正文里出现在真正回答之前的方括号、示意性对象或空对象都不含目标字段,+// 会被跳过,扫描继续往后找,直到命中顶层带该字段的对象。+// 修复前取的是第一个 JSON 值,这些用例都会拿到错误的候选。+func TestExtractJSONObjectSkipsDecoyValues(t *testing.T) {tests := []struct {name stringresponse string+ key stringwant string}{{- name: "正文中的方括号先于真正的 JSON 被选中",+ name: "正文中的方括号被跳过",response: `See [1] below: {"short_sentences":[{"text":"a"}]}`,- want: `[1]`,+ key: "short_sentences",+ want: `{"short_sentences":[{"text":"a"}]}`,},{- name: "示意性对象先于真正的 JSON 被选中",+ name: "示意性对象被跳过",response: `{"note":"见下"} 结果:{"short_sentences":[{"text":"a"}]}`,- want: `{"note":"见下"}`,+ key: "short_sentences",+ want: `{"short_sentences":[{"text":"a"}]}`,+ },+ {+ name: "示例空对象被跳过",+ response: "格式如 {}:\n{\"align\":[{\"origin_part\":\"a\",\"translated_part\":\"b\"}]}",+ key: "align",+ want: `{"align":[{"origin_part":"a","translated_part":"b"}]}`,+ },+ {+ name: "多个诱饵连续出现",+ response: `例如 [] 或 {} 或 {"text":"x"},实际结果:{"translations":[{"index":1,"text":"一"}]}`,+ key: "translations",+ want: `{"translations":[{"index":1,"text":"一"}]}`,+ },+ {+ name: "诱饵中带尾随逗号也能跳过",+ response: `{"note":"见下",} 结果:{"short_sentences":[{"text":"a"},]}`,+ key: "short_sentences",+ want: `{"short_sentences":[{"text":"a"}]}`,+ },+ {+ name: "同名字段嵌套在下层时不算命中",+ response: `{"data":{"align":[{"origin_part":"a"}]}}`,+ key: "align",+ want: `{"data":{"align":[{"origin_part":"a"}]}}`,},}for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {- if got := ExtractJSON(tt.response); got != tt.want {- t.Errorf("ExtractJSON() = %q, want %q", got, tt.want)+ if got := ExtractJSONObject(tt.response, tt.key); got != tt.want {+ t.Errorf("ExtractJSONObject() = %q, want %q", got, tt.want)}})}}-// TestExtractJSONLeavesUnparsableInputAlone (control) 结构损坏时函数不做猜测,-// 修复前后都原样返回去除首尾空白的输入,调用方因此仍能拿到真实的解析错误。-// 与表驱动用例中的 "[}"" 互为反向:这里覆盖相反的括号顺序,以及字符串未闭合+// TestExtractJSONObjectLeavesUnparsableInputAlone (control) 结构损坏或没有合适候选时+// 函数不做猜测,修复前后都原样返回去除首尾空白的输入,调用方因此仍能拿到真实的解析错误。+// 与表驱动用例中的 "[}" 互为反向:这里覆盖相反的括号顺序,以及字符串未闭合// (结尾是孤立反斜杠)这一条不同的代码路径。-func TestExtractJSONLeavesUnparsableInputAlone(t *testing.T) {+func TestExtractJSONObjectLeavesUnparsableInputAlone(t *testing.T) {tests := []struct {name stringresponse string+ key stringwant string}{{name: "结束符顺序相反",response: "{]",+ key: "align",want: "{]",},{name: "字符串未闭合且以孤立反斜杠结尾",response: `{"a":"x\`,+ key: "a",want: `{"a":"x\`,},+ {+ name: "未闭合的诱饵吞掉后文时整体原样返回",+ response: `{ 结果:{"align":[{"origin_part":"a"}]}`,+ key: "align",+ want: `{ 结果:{"align":[{"origin_part":"a"}]}`,+ },+ {+ name: "没有任何候选含目标字段",+ response: `{"note":"x"} {"other":1}`,+ key: "align",+ want: `{"note":"x"} {"other":1}`,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if got := ExtractJSONObject(tt.response, tt.key); got != tt.want {+ t.Errorf("ExtractJSONObject() = %q, want %q", got, tt.want)+ }+ })+ }+}++// TestExtractJSONObjectAcceptsPresentButEmptyField 说明字段存在即视为命中:+// 模型明确回答了一个空列表或 null 时不再继续往后扫描,这与"找不到字段"是两回事。+func TestExtractJSONObjectAcceptsPresentButEmptyField(t *testing.T) {+ tests := []struct {+ name string+ response string+ key string+ want string+ }{+ {+ name: "字段为空数组",+ response: `{"align":[]}`,+ key: "align",+ want: `{"align":[]}`,+ },+ {+ name: "字段为 null",+ response: `{"align":null}`,+ key: "align",+ want: `{"align":null}`,+ },}for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {- if got := ExtractJSON(tt.response); got != tt.want {- t.Errorf("ExtractJSON() = %q, want %q", got, tt.want)+ if got := ExtractJSONObject(tt.response, tt.key); got != tt.want {+ t.Errorf("ExtractJSONObject() = %q, want %q", got, tt.want)}})}diff --git a/runtime/krillinai/pkg/util/json_test.go b/runtime/krillinai/pkg/util/json_test.goindex 9857141d..b18a5e98 100644--- a/runtime/krillinai/pkg/util/json_test.go+++ b/runtime/krillinai/pkg/util/json_test.go@@ -5,155 +5,179 @@ import ("testing")-func TestExtractJSON(t *testing.T) {+func TestExtractJSONObject(t *testing.T) {tests := []struct {name stringresponse string+ key stringwant string}{{name: "对话式前缀",response: "以下是分割后的结果:\n\n\n{\n \"align\": [\n { \"origin_part\": \"I want to show you\" }\n ]\n}\n",+ key: "align",want: "{\n \"align\": [\n { \"origin_part\": \"I want to show you\" }\n ]\n}",},{name: "对话式后缀",response: "{\"short_sentences\":[{\"text\":\"a\"}]}\n\n希望这个结果对你有帮助!",+ key: "short_sentences",want: `{"short_sentences":[{"text":"a"}]}`,},{name: "对象尾随逗号",response: "{\n\"short_sentences\":[{\n\"text\": \"the owl is a symbol\",\n}] \n}",+ key: "short_sentences",want: "{\n\"short_sentences\":[{\n\"text\": \"the owl is a symbol\"}] \n}",},{name: "数组尾随逗号",response: `{"short_sentences":[{"text":"a"},{"text":"b"},]}`,+ key: "short_sentences",want: `{"short_sentences":[{"text":"a"},{"text":"b"}]}`,},{name: "前缀与尾随逗号同时出现",response: "以下是分割后的结果:\n```json\n{\"short_sentences\":[{\"text\":\"a\"},]}\n```",+ key: "short_sentences",want: `{"short_sentences":[{"text":"a"}]}`,},{name: "Markdown 代码块",response: "```json\n{\"align\":[{\"origin_part\":\"a\",\"translated_part\":\"b\"}]}\n```",+ key: "align",want: `{"align":[{"origin_part":"a","translated_part":"b"}]}`,},- {- name: "顶层数组",- response: "Sure! Here you go:\n[{\"text\":\"a\"},]",- want: `[{"text":"a"}]`,- },{name: "已经是合法 JSON 时保持不变",response: `{"short_sentences":[{"text":"a"}]}`,+ key: "short_sentences",want: `{"short_sentences":[{"text":"a"}]}`,},{- name: "JSON 之后的多余内容被丢弃",+ name: "跳过不含目标字段的前置对象",+ response: `{"a":1} {"b":2}`,+ key: "b",+ want: `{"b":2}`,+ },+ {+ name: "目标字段在第一个对象时不再继续扫描",response: `{"a":1} {"b":2}`,+ key: "a",want: `{"a":1}`,},{name: "字符串内的括号不影响匹配",response: `{"text":"a } b ] c"}`,+ key: "text",want: `{"text":"a } b ] c"}`,},{name: "字符串内的逗号不被删除",response: `{"text":"a, "}`,+ key: "text",want: `{"text":"a, "}`,},{name: "转义引号不会提前结束字符串",response: `{"text":"he said \"} \" and left",}`,+ key: "text",want: `{"text":"he said \"} \" and left"}`,},{name: "无 JSON 结构时原样返回",response: " 抱歉,我无法完成这个请求 ",+ key: "short_sentences",want: "抱歉,我无法完成这个请求",},{name: "空字符串",response: "",+ key: "short_sentences",want: "",},{name: "结构不完整时原样返回",response: `{"short_sentences":[{"text":"a"}`,+ key: "short_sentences",want: `{"short_sentences":[{"text":"a"}`,},{- name: "空对象",+ name: "空对象不含目标字段",response: "{}",+ key: "align",want: "{}",},{- name: "空数组",+ name: "顶层数组不是对象",response: "[]",+ key: "align",want: "[]",},{name: "嵌套结构的多处尾随逗号",response: `{"a":{"b":[{"c":1},]},}`,+ key: "a",want: `{"a":{"b":[{"c":1}]}}`,},{name: "连续逗号一并去除",response: `{"a":1,,}`,+ key: "a",want: `{"a":1}`,},{name: "结束符不匹配时不做猜测",response: "[}",+ key: "align",want: "[}",},}for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {- if got := ExtractJSON(tt.response); got != tt.want {- t.Errorf("ExtractJSON() = %q, want %q", got, tt.want)+ if got := ExtractJSONObject(tt.response, tt.key); got != tt.want {+ t.Errorf("ExtractJSONObject() = %q, want %q", got, tt.want)}})}}-// TestExtractJSONOutputIsParsable 保证提取结果确实能被 encoding/json 解析,+// TestExtractJSONObjectOutputIsParsable 保证提取结果确实能被 encoding/json 解析,// 这正是 issue #291 中失败的两类响应。-func TestExtractJSONOutputIsParsable(t *testing.T) {+func TestExtractJSONObjectOutputIsParsable(t *testing.T) {responses := []struct {name stringresponse string+ key string}{{name: "场景一_尾随逗号",response: "{\n\"short_sentences\":[{\n\"text\": \"And the reason why they chose the owl is because\",\n},\n{\n\"text\": \"the owl is a symbol used in Europe...\",\n}] \n}",+ key: "short_sentences",},{name: "场景二_中文对话式前缀",response: "以下是分割后的结果:\n\n\n{\n \"align\": [\n { \"origin_part\": \"I want to show you\", \"translated_part\": \"Ich möchte es Ihnen zeigen\" }\n ]\n}\n",+ key: "align",},}for _, tt := range responses {t.Run(tt.name, func(t *testing.T) {var payload map[string]any- if err := json.Unmarshal([]byte(ExtractJSON(tt.response)), &payload); err != nil {+ if err := json.Unmarshal([]byte(ExtractJSONObject(tt.response, tt.key)), &payload); err != nil {t.Fatalf("解析提取结果失败: %v", err)}- if len(payload) == 0 {- t.Fatal("提取结果为空对象")+ if _, ok := payload[tt.key]; !ok {+ t.Fatalf("提取结果缺少 %q 字段: %v", tt.key, payload)}})}}-// TestCleanMarkdownCodeBlockStillStripsFences 固定 ExtractJSON 所依赖的代码块清理行为。-// (control) 该行为在修复前后一致,用于证明 ExtractJSON 没有改变已有的去围栏逻辑。+// TestCleanMarkdownCodeBlockStillStripsFences 固定 ExtractJSONObject 所依赖的代码块清理行为。+// (control) 该行为在修复前后一致,用于证明本次改动没有影响已有的去围栏逻辑。func TestCleanMarkdownCodeBlockStillStripsFences(t *testing.T) {got := CleanMarkdownCodeBlock("```json\n{\"a\":1}\n```")if got != `{"a":1}` {