초기 커밋 — 협상 AI 에이전트 정본: 엔진·데모 콘솔·측정 인프라·증빙
- server/: FastAPI 협상 엔진 (5라운드, Q-Table/UCB, 페르소나 계측, :53117) - frontend/: 데모 콘솔 (React+Tailwind → nginx, /api 프록시) - eval/·testdata/: 지표 8종 측정 하네스 + 재현 가능 테스트셋 - results/: 측정 증빙 (지표별 result+provenance, raw 원본 동결+SHA256) ① 86.0 · ② 76.0 · ③ 5.99% · ⑥ p95 3.61ms · ⑦ 611만/년 · ⑧ 91/100 · ⑨ 99.71 · ⑩ 97.99 - docker-compose.yml + run.sh: backend+frontend 일괄 기동 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0112XUWF4bc3gGrEt8vsYCzy
This commit is contained in:
commit
dfb9ad6e66
268 files changed
+164241
No files matched your search
@@ -0,0 +1,47 @@
|
||||
"""N-profiling — LLM 기반 스크립트 톤 변환 (on/off 가능).
|
||||
|
||||
off이거나 API 키가 없으면 프로파일러가 생성되지 않으며,
|
||||
협상 엔진은 원문 스크립트를 그대로 사용한다.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Profiler:
|
||||
"""modifier + verifier 묶음. rewrite()가 검증 실패 시 None을 반환한다."""
|
||||
|
||||
def __init__(self, api_key: str, model: str):
|
||||
# openai 의존성은 profiling 활성 시에만 로드
|
||||
from services.profiling.modifier import ScriptModifier
|
||||
from services.profiling.verifier import ScriptVerifier
|
||||
|
||||
self.modifier = ScriptModifier(api_key=api_key, model=model)
|
||||
self.verifier = ScriptVerifier()
|
||||
|
||||
def rewrite(self, script: str, context: dict = None) -> Optional[str]:
|
||||
modified = self.modifier.modify_script(script, context)
|
||||
if modified is None:
|
||||
return None
|
||||
if not self.verifier.verify_script(script, modified):
|
||||
return None
|
||||
return modified
|
||||
|
||||
|
||||
def build_profiler(api_key: str, model: str, enabled: bool) -> Optional[Profiler]:
|
||||
"""설정에 따라 Profiler를 생성한다. 비활성/키 없음이면 None."""
|
||||
if not enabled:
|
||||
logger.info("[profiling] 비활성 (config)")
|
||||
return None
|
||||
if not api_key:
|
||||
logger.warning("[profiling] OPENAI_API_KEY 없음 — 프로파일링 비활성으로 기동")
|
||||
return None
|
||||
try:
|
||||
profiler = Profiler(api_key=api_key, model=model)
|
||||
logger.info(f"[profiling] 활성 (model={model})")
|
||||
return profiler
|
||||
except Exception as e:
|
||||
logger.warning(f"[profiling] 초기화 실패 — 비활성으로 기동: {e}")
|
||||
return None
|
||||
@@ -0,0 +1,61 @@
|
||||
"""ScriptModifier — LLM으로 협상 스크립트의 톤을 상황·상대 성향에 맞게 재작성한다.
|
||||
|
||||
평문 입출력. {변수} 플레이스홀더는 보존해야 하며, 검증은 verifier가 담당한다.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from openai import OpenAI
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_SYSTEM_PROMPT = """You are an expert Negotiation Script Editor.
|
||||
Rewrite the provided Korean negotiation script to match the requested tone/context.
|
||||
|
||||
Rules:
|
||||
1. **Preserve Variables**: Do NOT change, remove, or add any {placeholder} variables. \
|
||||
Only use variables that exist in the input.
|
||||
2. **Preserve Meaning**: Keep every factual statement and number intact. \
|
||||
Only adjust tone, phrasing, and flow.
|
||||
3. **Language**: The output MUST be in Korean (Hangul).
|
||||
4. **Plain Text Only**: Output ONLY the rewritten script text. \
|
||||
No markdown, no code fences, no explanations.
|
||||
5. Keep the line structure similar to the input (one thought per line)."""
|
||||
|
||||
_USER_TEMPLATE = """Original Script:
|
||||
{script}
|
||||
|
||||
Context/Instructions:
|
||||
{context}
|
||||
|
||||
Rewritten script:"""
|
||||
|
||||
|
||||
class ScriptModifier:
|
||||
def __init__(self, api_key: str, model: str = "gpt-4o"):
|
||||
self.client = OpenAI(api_key=api_key)
|
||||
self.model = model
|
||||
|
||||
def modify_script(self, script: str, context: dict = None) -> Optional[str]:
|
||||
"""스크립트 톤 재작성. 실패 시 None을 반환한다 (호출측에서 원문 유지)."""
|
||||
if not script or not script.strip():
|
||||
return None
|
||||
try:
|
||||
response = self.client.chat.completions.create(
|
||||
model=self.model,
|
||||
temperature=0,
|
||||
messages=[
|
||||
{"role": "system", "content": _SYSTEM_PROMPT},
|
||||
{"role": "user", "content": _USER_TEMPLATE.format(
|
||||
script=script, context=str(context or {}))},
|
||||
],
|
||||
)
|
||||
text = (response.choices[0].message.content or "").strip()
|
||||
# 혹시 모를 코드펜스 제거
|
||||
if text.startswith("```"):
|
||||
text = text.strip("`").strip()
|
||||
return text or None
|
||||
except Exception as e:
|
||||
logger.error(f"[ScriptModifier] LLM 호출 실패: {e}")
|
||||
return None
|
||||
@@ -0,0 +1,31 @@
|
||||
"""ScriptVerifier — LLM이 재작성한 스크립트의 데이터 무결성 검증."""
|
||||
|
||||
import logging
|
||||
|
||||
from common.textutil import extract_placeholders
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ScriptVerifier:
|
||||
"""재작성된 스크립트가 원문의 {변수}를 그대로 보존했는지 검증한다."""
|
||||
|
||||
def verify_script(self, original: str, modified: str) -> bool:
|
||||
if not isinstance(modified, str) or not modified.strip():
|
||||
logger.warning("[ScriptVerifier] 검증 실패: 결과가 비어있음")
|
||||
return False
|
||||
|
||||
original_params = extract_placeholders(original)
|
||||
modified_params = extract_placeholders(modified)
|
||||
|
||||
missing = original_params - modified_params
|
||||
if missing:
|
||||
logger.warning(f"[ScriptVerifier] 검증 실패: 누락된 변수 {missing}")
|
||||
return False
|
||||
|
||||
added = modified_params - original_params
|
||||
if added:
|
||||
logger.warning(f"[ScriptVerifier] 검증 실패: 추가된 미지 변수 {added}")
|
||||
return False
|
||||
|
||||
return True
|
||||
Reference in new issue
Block a user