feat(inference): chat_structured 接入 jsonschema 真校验(T1 架构审查整改)
- pyproject.toml 新增 jsonschema>=4.23 依赖 - engine.py: json.loads 后 jsonschema.validate,校验失败按解析失败重试(带错误信息) - 新增 3 用例:违规重试成功/耗尽 parse_error 含详情/合法一次通过 - 全量 163 passed / 100.00% 覆盖(936 stmts/238 br),fail_under=99 达标
This commit is contained in:
@@ -4,6 +4,8 @@ import json
|
||||
import time
|
||||
from typing import Any, Callable
|
||||
|
||||
import jsonschema
|
||||
|
||||
from .client import LLMClient
|
||||
from .exceptions import LLMError
|
||||
from .prompt_registry import PromptRegistry
|
||||
@@ -158,6 +160,9 @@ class InferenceEngine:
|
||||
)
|
||||
last_raw = text
|
||||
data = json.loads(text)
|
||||
if schema:
|
||||
# 真 schema 校验:不合 schema 时按解析失败重试(T1)
|
||||
jsonschema.validate(instance=data, schema=schema)
|
||||
return StructuredResult(
|
||||
data=data, raw_text=text, parse_attempts=attempts,
|
||||
model=self._model_names(None)[0],
|
||||
@@ -172,6 +177,11 @@ class InferenceEngine:
|
||||
last_error_code = "LLM_PARSE_ERROR"
|
||||
# 带错误信息重试
|
||||
base_rendered = base_rendered + f"\n\n上次解析失败:{exc}。请重新输出合法 JSON。"
|
||||
except jsonschema.ValidationError as exc:
|
||||
last_error = f"校验失败: {exc.message}"
|
||||
last_error_code = "LLM_PARSE_ERROR"
|
||||
# 带校验错误信息重试
|
||||
base_rendered = base_rendered + f"\n\n上次校验失败:{exc.message}。请重新输出符合 JSON Schema 的 JSON。"
|
||||
except LLMError as exc:
|
||||
return StructuredResult(
|
||||
data={}, raw_text="", parse_attempts=attempts,
|
||||
|
||||
Reference in New Issue
Block a user