85 lines
3.6 KiB
Python
85 lines
3.6 KiB
Python
"""调用大模型 + 解析JSON返回的公共逻辑,供 generate_from_text.py / modify_part.py 共用。"""
|
||
|
||
import json
|
||
import os
|
||
from .images import normalize_images
|
||
|
||
DEFAULT_MODEL = "gpt-5.6-luna"
|
||
MODEL = os.getenv("CADMIND_MODEL", DEFAULT_MODEL)
|
||
|
||
|
||
MAX_IMAGES = 5
|
||
|
||
|
||
def build_user_content(text: str, image_base64: str | list[str] | None = None):
|
||
"""构造用户消息内容。带图片时用多模态content数组,不带图片时就是普通字符串——
|
||
保持向后兼容,所有不传图片的旧调用点完全不受影响。image_base64可以是单张(旧调用
|
||
方式,字符串)也可以是一个列表(最多MAX_IMAGES张)——参考图经常需要正视图/侧视图/
|
||
俯视图分开拍,一张图片塞不下这么多信息,最多允许5张一起给模型看。"""
|
||
images = normalize_images(image_base64)
|
||
if not images:
|
||
return text
|
||
return [
|
||
{"type": "text", "text": text},
|
||
*[
|
||
{"type": "image_url", "image_url": {"url": img["url"]}}
|
||
for img in images
|
||
],
|
||
]
|
||
|
||
|
||
class LLMResponseError(Exception):
|
||
"""模型这次没能给出可解析的JSON——通常是gpt-5.6-luna这类推理模型把
|
||
max_completion_tokens全部耗在了内部推理上,实际可见输出被截断成空。
|
||
跟IR校验失败(IRError)不是一回事:这里连IR都还没生成出来。"""
|
||
|
||
|
||
def extract_json(content: str) -> dict:
|
||
content = content.strip()
|
||
if content.startswith("```"):
|
||
content = content.strip("`")
|
||
if content.startswith("json"):
|
||
content = content[4:]
|
||
return json.loads(content)
|
||
|
||
|
||
def _call_once(client, messages, max_completion_tokens: int) -> dict:
|
||
try:
|
||
resp = client.chat.completions.create(
|
||
model=MODEL,
|
||
messages=messages,
|
||
max_completion_tokens=max_completion_tokens,
|
||
response_format={"type": "json_object"},
|
||
)
|
||
except Exception:
|
||
resp = client.chat.completions.create(
|
||
model=MODEL,
|
||
messages=messages,
|
||
max_completion_tokens=max_completion_tokens,
|
||
)
|
||
choice = resp.choices[0]
|
||
content = choice.message.content or ""
|
||
try:
|
||
return extract_json(content)
|
||
except json.JSONDecodeError as e:
|
||
raise LLMResponseError(
|
||
f"模型没能给出合法JSON(finish_reason={choice.finish_reason}, "
|
||
f"可见输出{len(content)}字符, max_completion_tokens={max_completion_tokens}),"
|
||
f"很可能是内部推理耗尽了token预算,输出被截断。原始解析错误: {e}"
|
||
) from e
|
||
|
||
|
||
def call_json(client, messages, max_completion_tokens: int = 16000) -> dict:
|
||
"""真实踩过的坑:能力库/领域知识越来越大,复杂零件(多个孔+异形镂空+参考图)
|
||
的system prompt本身就有2万token,reasoning模型光是内部推理就可能把
|
||
max_completion_tokens全部吃光,实际可见输出是空字符串——旧版4000的预算
|
||
在这种请求下必现,且旧代码让json.JSONDecodeError原样往外抛,整个三级兜底
|
||
都被跳过,调用方直接崩溃。现在这里做两件事:预算本身调大到16000起步;
|
||
真被截断时(LLMResponseError)自动翻倍预算重试一次,两次都不行才让异常
|
||
往外抛给调用方按已有的重试/降级逻辑处理,而不是让人以为"这个具体零件建模失败了"
|
||
——本质是预算不够,不是模型不会做。"""
|
||
try:
|
||
return _call_once(client, messages, max_completion_tokens)
|
||
except LLMResponseError:
|
||
return _call_once(client, messages, max_completion_tokens * 2)
|