fix(qa_service): fix log placement and add KeyError→LLMParseError handling

This commit is contained in:
wh
2026-04-10 16:11:17 +08:00
parent 4211e587ee
commit 00f092e728

View File

@@ -3,6 +3,7 @@ import base64
from app.clients.llm.base import LLMClient
from app.clients.storage.base import StorageClient
from app.core.config import get_config
from app.core.exceptions import LLMParseError
from app.core.json_utils import extract_json
from app.core.logging import get_logger
from app.models.qa_models import (
@@ -47,10 +48,15 @@ async def gen_text_qa(req: GenTextQARequest, llm: LLMClient) -> TextQAResponse:
messages = [{"role": "user", "content": prompt}]
raw = await llm.chat(model, messages)
items_raw = extract_json(raw)
logger.info("gen_text_qa", extra={"items": len(req.items), "model": model})
items_raw = extract_json(raw)
pairs = [QAPair(question=item["question"], answer=item["answer"]) for item in items_raw]
if not isinstance(items_raw, list):
raise LLMParseError("大模型返回的问答对格式不正确")
try:
pairs = [QAPair(question=item["question"], answer=item["answer"]) for item in items_raw]
except (KeyError, TypeError):
raise LLMParseError("大模型返回的问答对格式不正确")
return TextQAResponse(pairs=pairs)
@@ -91,16 +97,22 @@ async def gen_image_qa(
]
raw = await llm.chat_vision(model, messages)
logger.info("gen_image_qa", extra={"path": item.cropped_image_path, "model": model})
items_raw = extract_json(raw)
for qa in items_raw:
pairs.append(
ImageQAPair(
question=qa["question"],
answer=qa["answer"],
image_path=item.cropped_image_path,
logger.info("gen_image_qa", extra={"path": item.cropped_image_path, "model": model})
if not isinstance(items_raw, list):
raise LLMParseError("大模型返回的问答对格式不正确")
try:
for qa in items_raw:
pairs.append(
ImageQAPair(
question=qa["question"],
answer=qa["answer"],
image_path=item.cropped_image_path,
)
)
)
except (KeyError, TypeError):
raise LLMParseError("大模型返回的问答对格式不正确")
return ImageQAResponse(pairs=pairs)