전문성 페르소나 적용
This commit is contained in:
1 parent
9a5a120892
commit
706ef84b97
9 files changed
+75
-25
No files matched your search
+19
-2
@@ -3,7 +3,8 @@
|
||||
OpenAI 호환 /chat/completions를 쓰는 프로바이더면 base_url만 바꿔 그대로 쓴다.
|
||||
출력은 항상 한국어로 받는다. 사용자 메시지는 데이터로만 다루도록 감싸고, 응답의 프롬프트 유출을 검사한다.
|
||||
"""
|
||||
from typing import TypeVar
|
||||
import re
|
||||
from typing import Any, TypeVar
|
||||
|
||||
from openai import AsyncOpenAI
|
||||
from pydantic import BaseModel
|
||||
@@ -15,6 +16,22 @@ 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):
|
||||
@@ -47,7 +64,7 @@ class StructuredLLM:
|
||||
raise RuntimeError(f"{self.model} 거절: {msg.refusal}")
|
||||
if msg.parsed is None:
|
||||
raise RuntimeError(f"{self.model} 파싱 실패: {msg.content!r}")
|
||||
return msg.parsed
|
||||
return schema.model_validate(_strip_json_tail(msg.parsed.model_dump()))
|
||||
|
||||
|
||||
def create_llm() -> StructuredLLM:
|
||||
|
||||
Reference in new issue
Block a user