NovelForge icon indicating copy to clipboard operation
NovelForge copied to clipboard

增强 agent_service 对 OneAPI中转模型的结构化输出兼容性

Open wutsusemi opened this issue 10 months ago • 2 comments

通过 OneAPI 调用模型时,经常调用失败,出现LLM 返回了空响应,似乎原因是模型经常将结构化数据直接以纯文本 JSON 形式返回,而不是标准的 OpenAI tool_calls 格式,而当前的 agent_service.py 使用 model.with_structured_output(output_type) 时,如果未检测到 tool_calls 会直接返回 None,导致代码抛出 "LLM 返回了空响应" 错误,即使模型实际上已经生成了有效的 JSON 内容。 建议在 run_llm_agent 方法中增加处理策略,用ai给出的方案是: 优先尝试 method="json_mode",强制模型输出 JSON;若 LangChain 解析失败(返回 None),增加手动解析 response.content 的兜底逻辑。

修改 run_llm_agent 中的 try 块逻辑

...

messages.append(HumanMessage(content=user_prompt))

response = None

1. 优先尝试 json_mode

try: structured_llm = model.with_structured_output(output_type, method="json_mode") response = await structured_llm.ainvoke(messages) except Exception: pass

2. 如果失败,回退到默认模式

if response is None: try: structured_llm_def = model.with_structured_output(output_type) response = await structured_llm_def.ainvoke(messages) except Exception: pass

3. 手动解析原始文本

if response is None: raw_res = await model.ainvoke(messages) if raw_res.content: try: import json, re text = raw_res.content.strip() # 清洗 markdown 标记 if "" in text: match = re.search(r"(?:json)?(.*?)```", text, re.DOTALL) if match: text = match.group(1).strip()

        data = json.loads(text)
        # Pydantic 转换
        if hasattr(output_type, 'model_validate'):
            response = output_type.model_validate(data)
        else:
            response = data
    except Exception:
        pass

if response is None: raise ValueError("LLM 返回了空响应")

...

应用后无错误

wutsusemi avatar Jan 27 '26 11:01 wutsusemi

是指卡片点击AI生成按钮进行生成时容易失败吗?下个版本会优化的,不过不是这种方式

RhythmicWave avatar Jan 27 '26 11:01 RhythmicWave

是的是的,使用中转api时一直空响应,期待一下下个版本

wutsusemi avatar Jan 27 '26 13:01 wutsusemi