75 lines
2.6 KiB
Python
75 lines
2.6 KiB
Python
"""structured output 공용 래퍼.
|
|
|
|
OpenAI 호환 /chat/completions를 쓰는 프로바이더면 base_url만 바꿔 그대로 쓴다.
|
|
출력은 항상 한국어로 받는다. 사용자 메시지는 데이터로만 다루도록 감싸고, 응답의 프롬프트 유출을 검사한다.
|
|
"""
|
|
import re
|
|
from typing import Any, TypeVar
|
|
|
|
from openai import AsyncOpenAI
|
|
from pydantic import BaseModel
|
|
|
|
from settings import settings
|
|
from utils.prompt_guard import GUARD_RULE, check_leak, wrap_data
|
|
|
|
T = TypeVar("T", bound=BaseModel)
|
|
|
|
KOREAN_OUTPUT_RULE = "모든 출력은 한국어로 쓴다."
|
|
|
|
_JSON_CLOSING_TAIL = re.compile(r'\s*"\s*}+\s*$')
|
|
|
|
|
|
def _strip_json_tail(value: Any) -> Any:
|
|
"""문자열 값 끝에 섞여 나오는 JSON 닫는 기호("} 또는 짝 없는 ")를 지운다."""
|
|
if isinstance(value, dict):
|
|
return {key: _strip_json_tail(item) for key, item in value.items()}
|
|
if isinstance(value, list):
|
|
return [_strip_json_tail(item) for item in value]
|
|
if not isinstance(value, str):
|
|
return value
|
|
text = _JSON_CLOSING_TAIL.sub("", value).rstrip()
|
|
if text.endswith('"') and text.count('"') % 2 == 1:
|
|
text = text[:-1].rstrip()
|
|
return text
|
|
|
|
|
|
class StructuredLLM:
|
|
def __init__(self, model: str, api_key: str, base_url: str | None = None):
|
|
self.model = model
|
|
self._client = AsyncOpenAI(api_key=api_key, base_url=base_url)
|
|
|
|
async def ask(
|
|
self,
|
|
schema: type[T],
|
|
prompt: str,
|
|
*,
|
|
system: str | None = None,
|
|
temperature: float = 0.0,
|
|
) -> T:
|
|
system_content = "\n\n".join(rule for rule in (system, KOREAN_OUTPUT_RULE, GUARD_RULE) if rule)
|
|
messages = [
|
|
{"role": "system", "content": system_content},
|
|
{"role": "user", "content": wrap_data(prompt)},
|
|
]
|
|
|
|
msg = (await self._client.chat.completions.parse(
|
|
model=self.model,
|
|
messages=messages,
|
|
response_format=schema,
|
|
temperature=temperature,
|
|
)).choices[0].message
|
|
|
|
check_leak(msg.content)
|
|
if msg.refusal:
|
|
raise RuntimeError(f"{self.model} 거절: {msg.refusal}")
|
|
if msg.parsed is None:
|
|
raise RuntimeError(f"{self.model} 파싱 실패: {msg.content!r}")
|
|
return schema.model_validate(_strip_json_tail(msg.parsed.model_dump()))
|
|
|
|
|
|
def create_llm() -> StructuredLLM:
|
|
"""LLM_PROVIDER 설정에 맞는 StructuredLLM을 만든다."""
|
|
if settings.llm_provider == "vllm":
|
|
return StructuredLLM(settings.vllm_model, settings.vllm_api_key, settings.vllm_base_url)
|
|
return StructuredLLM(settings.llm_model, settings.chatgpt_api_key)
|