Files
민헌andClaude Opus 5.5 13ab9dee84 chore: 2차년도 성능평가 측정 구성 초기 업로드
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>
2026-10-21 14:05:48 +09:00

114 lines
5.1 KiB
Python

"""문항별 모델 응답 생성 (OpenAI 호환 Chat Completions API).
베이스라인과 개발 모델을 같은 조건(같은 문항·같은 대화 히스토리·같은 디코딩 설정)으로 실행한다.
OpenAI API, vLLM·TGI 등 OpenAI 호환 서버 모두 base_url 만 바꿔 쓴다.
API 키는 환경 변수(기본 OPENAI_API_KEY)에서 읽는다. 로컬 서버처럼 키가 필요 없으면 비워 둔다.
출력은 JSONL 이고 한 줄에 문항 하나: sample_id, dialogue_id, turn, system, model, candidate, finish_reason, usage, params.
이미 출력 파일에 있는 sample_id 는 건너뛴다 (중단 후 이어서 실행).
"""
import json
import os
import time
import urllib.error
import urllib.request
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Callable, Optional
from grounding_eval.data import EvalItem, read_jsonl
RETRY_STATUS = frozenset({408, 409, 429, 500, 502, 503, 504})
@dataclass(frozen=True)
class GenerationConfig:
base_url: str
model: str
temperature: float = 0.0
top_p: float = 1.0
seed: int = 0
max_tokens: int = 512
timeout: float = 120.0
retries: int = 4
class GenerationError(RuntimeError):
pass
def load_api_key(env_name: Optional[str]) -> Optional[str]:
if not env_name:
return None
key = os.environ.get(env_name)
if not key:
raise GenerationError(f"환경 변수 {env_name} 에 API 키가 없습니다")
return key
def chat_completion(config: GenerationConfig, messages: list, api_key: Optional[str],
sleep: Callable[[float], None] = time.sleep) -> dict:
body = json.dumps({"model": config.model, "messages": messages, "temperature": config.temperature,
"top_p": config.top_p, "seed": config.seed, "max_tokens": config.max_tokens}).encode("utf-8")
headers = {"Content-Type": "application/json"}
if api_key:
headers["Authorization"] = f"Bearer {api_key}"
url = config.base_url.rstrip("/") + "/chat/completions"
last_error = None
for attempt in range(config.retries + 1):
request = urllib.request.Request(url, data=body, headers=headers, method="POST")
try:
with urllib.request.urlopen(request, timeout=config.timeout) as response:
return json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as e:
detail = e.read().decode("utf-8", errors="replace")[:300]
last_error = GenerationError(f"HTTP {e.code}: {detail}")
if e.code not in RETRY_STATUS:
raise last_error from e
except (urllib.error.URLError, TimeoutError, ConnectionError) as e:
last_error = GenerationError(f"연결 실패: {e}")
if attempt < config.retries:
sleep(min(2 ** attempt, 30))
raise last_error
def generate_one(item: EvalItem, config: GenerationConfig, system: str, api_key: Optional[str],
sleep: Callable[[float], None] = time.sleep) -> dict:
response = chat_completion(config, item.messages, api_key, sleep=sleep)
try:
choice = response["choices"][0]
candidate = choice["message"]["content"] or ""
except (KeyError, IndexError, TypeError) as e:
raise GenerationError(f"{item.sample_id}: 응답 형식이 올바르지 않습니다: {str(response)[:300]}") from e
params = asdict(config)
params.pop("base_url")
return {"sample_id": item.sample_id, "dialogue_id": item.dialogue_id, "turn": item.turn, "system": system,
"model": response.get("model", config.model), "candidate": candidate,
"finish_reason": choice.get("finish_reason"), "usage": response.get("usage"), "params": params}
def generate_all(items: list[EvalItem], config: GenerationConfig, system: str, out_path,
api_key: Optional[str] = None, workers: int = 1,
sleep: Callable[[float], None] = time.sleep,
log: Callable[[str], None] = print) -> dict:
"""문항 전체를 생성해 out_path 에 이어 쓴다. {"done", "skipped", "failed": [sample_id, ...]} 를 돌려준다."""
out_path = Path(out_path)
done_ids = {r["sample_id"] for r in read_jsonl(out_path)} if out_path.exists() else set()
todo = [i for i in items if i.sample_id not in done_ids]
failed = []
with out_path.open("a", encoding="utf-8") as f, ThreadPoolExecutor(max_workers=max(1, workers)) as pool:
futures = {pool.submit(generate_one, item, config, system, api_key, sleep): item for item in todo}
for n, future in enumerate(as_completed(futures), start=1):
item = futures[future]
try:
row = future.result()
except GenerationError as e:
failed.append(item.sample_id)
log(f"[{n}/{len(todo)}] 실패 {item.sample_id}: {e}")
continue
f.write(json.dumps(row, ensure_ascii=False) + "\n")
f.flush()
log(f"[{n}/{len(todo)}] 생성 {item.sample_id}")
return {"done": len(todo) - len(failed), "skipped": len(items) - len(todo), "failed": sorted(failed)}