Browse Source

fix(menu): 菜单 JSON 截断导致后续食谱全部走兜底

根因:max_tokens=3000 不足以容纳 3 餐 × D(N)+1 道菜的中文 JSON,
LLM 输出在晚餐中途截断;旧提取逻辑用贪婪正则匹配到半截 JSON,
Java normalizeMenu 解析失败 → 整份菜单降级为规则兜底(营养餐/营养汤)。
实测:首个生成正常,后续 regenerate/多成员均截断。

- max_tokens 3000 → 8000
- JSON 提取改为花括号配平 + 逐级补齐截断片段;仍无法解析时返回空菜单让 Java 兜底
Xiaogang Liao 43 minutes ago
parent
commit
bce8daac47
1 changed files with 70 additions and 2 deletions
  1. 70 2
      cfc-langgraph/app/api/meal.py

+ 70 - 2
cfc-langgraph/app/api/meal.py

@@ -269,7 +269,9 @@ async def generate_menu(req: MenuGenerateRequest):
             api_key=settings.llm_api_key,
             base_url=settings.llm_base_url,
             temperature=0.7,
-            max_tokens=3000,
+            # 一日三餐 D(N)+1 道菜,每道含食材/做法/营养,中文 JSON 很长;
+            # 3000 token 会截断在晚餐中途,导致 Java 侧归一化失败→整份兜底。
+            max_tokens=8000,
         )
 
         response = llm.invoke([
@@ -278,8 +280,74 @@ async def generate_menu(req: MenuGenerateRequest):
         ])
 
         text = response.content.strip()
+
+        def _balanced_json(t):
+            """从 t 中截取第一个花括号配平的完整 JSON;找不到返回 None。"""
+            start = t.find('{')
+            if start < 0:
+                return None
+            depth = 0
+            in_string = False
+            escape = False
+            for i in range(start, len(t)):
+                ch = t[i]
+                if in_string:
+                    if escape:
+                        escape = False
+                    elif ch == '\\':
+                        escape = True
+                    elif ch == '"':
+                        in_string = False
+                    continue
+                if ch == '"':
+                    in_string = True
+                elif ch == '{':
+                    depth += 1
+                elif ch == '}':
+                    depth -= 1
+                    if depth == 0:
+                        return t[start:i + 1]
+            return None
+
+        def _valid_json_str(t):
+            try:
+                json.loads(t)
+                return True
+            except Exception:
+                return False
+
+        menu_json = None
+        # 优先:模型包裹在 ```json ... ``` 或前后有说明文字时,贪婪取首尾大括号
         match = re.search(r'\{[\s\S]*\}', text)
-        menu_json = match.group() if match else '{"meals": []}'
+        if match and _valid_json_str(match.group()):
+            menu_json = match.group()
+        if menu_json is None:
+            # 兜底:按花括号配平截取(处理尾部截断但未闭合的片段)
+            candidate = _balanced_json(text)
+            if candidate and _valid_json_str(candidate):
+                menu_json = candidate
+        if menu_json is None:
+            # 最后兜底:若模型返回截断 JSON,尝试截到最后一个完整 dish 对象后补齐括号
+            candidate = _balanced_json(text)
+            if candidate:
+                # 去掉末尾不完整的 dish/ingredients 片段,逐级补齐 ] }
+                fixed = candidate.rstrip()
+                # 逐步回退到最近的 '}' 并补齐剩余括号
+                while fixed and not _valid_json_str(fixed):
+                    cuts = max(fixed.rfind('}'), fixed.rfind(']'))
+                    if cuts <= 0:
+                        break
+                    fixed = fixed[:cuts + 1]
+                    # 补齐缺失的闭合括号
+                    opens = fixed.count('{') - fixed.count('}')
+                    fixed = fixed + '}' * max(0, opens)
+                if _valid_json_str(fixed):
+                    menu_json = fixed
+                    logger.warning("菜单 JSON 被截断,已修复后返回: trace_id=%s", trace_id)
+        if menu_json is None:
+            logger.warning("菜单 JSON 无法解析,返回空菜单让 Java 走兜底: trace_id=%s, text_head=%s",
+                           trace_id, text[:120])
+            menu_json = '{"meals": []}'
 
         return MenuGenerateResponse(menu_json=menu_json, trace_id=trace_id)
     except Exception as e: