data(train 520·holdout 120), server(발화 생성 서버), eval(grounding_eval), run_eval.py·run_test.sh. logs/ 는 실행 때마다 생기는 기록이라 README.md 만 올리고 나머지는 .gitignore 로 뺀다. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
61 lines
2.3 KiB
Python
61 lines
2.3 KiB
Python
"""OpenAI 호환 Chat Completions 호출 — OpenAI API, vLLM 등은 base_url 만 바꿔 쓴다."""
|
|
|
|
import logging
|
|
import os
|
|
from dataclasses import dataclass
|
|
from typing import List, Optional
|
|
|
|
from openai import OpenAI, OpenAIError
|
|
|
|
from config.config_models import ProfileConfig
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
NO_KEY = "EMPTY" # 키가 필요 없는 로컬 서버용 자리값 (openai SDK 는 빈 키를 허용하지 않음)
|
|
|
|
|
|
class LLMError(RuntimeError):
|
|
pass
|
|
|
|
|
|
@dataclass
|
|
class LLMResult:
|
|
content: str
|
|
finish_reason: Optional[str]
|
|
model: str
|
|
prompt_tokens: int = 0
|
|
completion_tokens: int = 0
|
|
system_fingerprint: Optional[str] = None # OpenAI 서버 구성 식별자 — 같은 seed 에서 결과가 달라질 때 설명 근거
|
|
|
|
|
|
class LLMClient:
|
|
def __init__(self, profile: ProfileConfig):
|
|
self.profile = profile
|
|
api_key = os.getenv(profile.api_key_env, "") if profile.api_key_env else ""
|
|
if profile.api_key_env and not api_key:
|
|
logger.warning(f"[LLMClient] 환경변수 {profile.api_key_env} 가 비어 있습니다 — 호출 시 인증 오류가 날 수 있습니다")
|
|
self.client = OpenAI(base_url=profile.base_url, api_key=api_key or NO_KEY,
|
|
timeout=profile.timeout, max_retries=0)
|
|
|
|
def chat(self, messages: List[dict], temperature: float, top_p: float,
|
|
seed: Optional[int], max_tokens: Optional[int]) -> LLMResult:
|
|
kwargs = {"model": self.profile.model, "messages": messages, "temperature": temperature, "top_p": top_p}
|
|
if seed is not None:
|
|
kwargs["seed"] = seed
|
|
if max_tokens is not None:
|
|
kwargs["max_tokens"] = max_tokens
|
|
try:
|
|
response = self.client.chat.completions.create(**kwargs)
|
|
except OpenAIError as e:
|
|
raise LLMError(f"{self.profile.model} 호출 실패: {e}") from e
|
|
choice = response.choices[0]
|
|
usage = response.usage
|
|
return LLMResult(
|
|
content=choice.message.content or "",
|
|
finish_reason=choice.finish_reason,
|
|
model=response.model or self.profile.model,
|
|
prompt_tokens=usage.prompt_tokens if usage else 0,
|
|
completion_tokens=usage.completion_tokens if usage else 0,
|
|
system_fingerprint=getattr(response, "system_fingerprint", None),
|
|
)
|