Agent 서버 구축: 멀티테넌트 협상 PoC (UCB Q-Table 학습 + /chat + 14 API + 학습검증 하네스), config 단일화(local.toml) + 빌드 경량화
This commit is contained in:
1 parent
212725e5f9
commit
951d6eab84
140 files changed
+6689
-214
No files matched your search
@@ -0,0 +1,12 @@
|
||||
"""profiling 패키지 (구 N-profiling).
|
||||
|
||||
Chat_server 의 `N-profiling` 은 패키지명에 하이픈(`-`)이 들어가 정상 import 가 불가능했고,
|
||||
`chat_engine.py` 에서 `importlib.util.spec_from_file_location` + `sys.modules` 수동 등록으로
|
||||
동적 로드하는 해킹(`_load_dynamic_module`)으로 우회했다.
|
||||
|
||||
여기서는 `profiling` 으로 개명하여 정식 패키지 import 로 전환한다.
|
||||
before: ScriptModifier = _load_dynamic_module("script_modifier", "ScriptModifier")
|
||||
after : from negotiation.profiling.script_modifier import ScriptModifier
|
||||
|
||||
LLM 자격증명은 P7 에서 TenantConfig.llm 주입으로 전환한다(현재는 env 폴백).
|
||||
"""
|
||||
@@ -0,0 +1,34 @@
|
||||
"""LLM 자격증명 — OpenAIConfig(toml)에서 주입.
|
||||
|
||||
프로젝트 컨벤션대로 toml 로 관리한다. P7 에서 TenantConfig.llm 로 테넌트별 오버라이드를 얹을 수 있다.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
|
||||
@dataclass
|
||||
class LlmCredentials:
|
||||
"""LLM 접속 정보. provider 로 openai/azure 분기."""
|
||||
|
||||
provider: str = "openai" # "openai" | "azure"
|
||||
api_key: Optional[str] = None
|
||||
model: Optional[str] = None # openai 모델명 / azure 배포 이름
|
||||
base_url: Optional[str] = None
|
||||
azure_endpoint: Optional[str] = None
|
||||
api_version: Optional[str] = None
|
||||
|
||||
@classmethod
|
||||
def from_config(cls) -> "LlmCredentials":
|
||||
"""server_configs.openai_config 에서 생성 (전역 기본값)."""
|
||||
from config.server_configs import openai_config as c
|
||||
return cls(
|
||||
provider=c.provider, api_key=c.api_key or None, model=c.model or None,
|
||||
base_url=c.base_url or None, azure_endpoint=c.azure_endpoint or None,
|
||||
api_version=c.api_version or None,
|
||||
)
|
||||
|
||||
def is_configured(self) -> bool:
|
||||
if self.provider == "azure":
|
||||
return bool(self.api_key and self.azure_endpoint and self.model)
|
||||
return bool(self.api_key and self.model)
|
||||
Whitespace-only changes.
@@ -0,0 +1,34 @@
|
||||
"""LangGraph 기반 대화 그래프 (구 N-profiling/domain/graph.py 이식).
|
||||
|
||||
원본 import 버그 수정: `n_profiling.llm`(존재하지 않음) → `negotiation.profiling.infra.llm_adapter`.
|
||||
chat_engine 은 이 모듈을 사용하지 않으며(script_modifier/verifier 만 사용), langgraph 는 선택 의존성이다.
|
||||
직접 import 할 때만 langgraph 가 필요하다.
|
||||
"""
|
||||
|
||||
from typing import List, TypedDict
|
||||
|
||||
from langchain_core.messages import BaseMessage
|
||||
from langgraph.graph import StateGraph
|
||||
from langgraph.checkpoint.sqlite import SqliteSaver
|
||||
|
||||
from negotiation.profiling.infra.llm_adapter import get_llm
|
||||
|
||||
|
||||
class AgentState(TypedDict):
|
||||
"""대화 상태. messages: 대화 히스토리."""
|
||||
|
||||
messages: List[BaseMessage]
|
||||
|
||||
|
||||
def call_model(state: AgentState):
|
||||
response = get_llm().invoke(state["messages"])
|
||||
return {"messages": [response]}
|
||||
|
||||
|
||||
# 대화 상태를 메모리에 임시 저장하는 체크포인터.
|
||||
memory = SqliteSaver.from_conn_string(":memory:")
|
||||
|
||||
graph = StateGraph(AgentState)
|
||||
graph.add_node("llm", call_model)
|
||||
graph.set_entry_point("llm")
|
||||
graph.set_finish_point("llm")
|
||||
Whitespace-only changes.
@@ -0,0 +1,51 @@
|
||||
"""LLM 어댑터 — openai SDK 직접 호출 (langchain 미사용).
|
||||
|
||||
provider 로 OpenAI / Azure OpenAI 분기. 무거운 import 는 호출 시점에 한다.
|
||||
chat_complete: messages → 응답 텍스트. json_mode 면 JSON 객체 강제(response_format).
|
||||
"""
|
||||
|
||||
import json
|
||||
from typing import List, Optional
|
||||
|
||||
from negotiation.profiling.config import LlmCredentials
|
||||
|
||||
|
||||
def _client(creds: LlmCredentials):
|
||||
if creds.provider == "azure":
|
||||
from openai import AzureOpenAI
|
||||
return AzureOpenAI(api_key=creds.api_key, azure_endpoint=creds.azure_endpoint,
|
||||
api_version=creds.api_version or "2024-06-01")
|
||||
from openai import OpenAI
|
||||
kwargs = {"api_key": creds.api_key}
|
||||
if creds.base_url:
|
||||
kwargs["base_url"] = creds.base_url
|
||||
return OpenAI(**kwargs)
|
||||
|
||||
|
||||
def chat_complete(messages: List[dict], creds: Optional[LlmCredentials] = None,
|
||||
json_mode: bool = False, temperature: float = 0.7, max_tokens: int = 1024) -> str:
|
||||
"""OpenAI(또는 Azure) chat completion 호출 → 응답 텍스트.
|
||||
|
||||
Args:
|
||||
messages: [{"role": "system"|"user"|"assistant", "content": "..."}]
|
||||
creds: 자격증명(없으면 OpenAIConfig 전역값).
|
||||
json_mode: True 면 JSON 객체 응답 강제.
|
||||
"""
|
||||
if creds is None:
|
||||
creds = LlmCredentials.from_config()
|
||||
if not creds.is_configured():
|
||||
raise RuntimeError("LLM 미설정 (OpenAIConfig.api_key/model 확인)")
|
||||
|
||||
client = _client(creds)
|
||||
kwargs = {"model": creds.model, "messages": messages,
|
||||
"temperature": temperature, "max_tokens": max_tokens}
|
||||
if json_mode:
|
||||
kwargs["response_format"] = {"type": "json_object"}
|
||||
resp = client.chat.completions.create(**kwargs)
|
||||
return resp.choices[0].message.content or ""
|
||||
|
||||
|
||||
def chat_json(messages: List[dict], creds: Optional[LlmCredentials] = None, **kw) -> dict:
|
||||
"""JSON 응답을 파싱해 dict 로 반환."""
|
||||
text = chat_complete(messages, creds=creds, json_mode=True, **kw)
|
||||
return json.loads(text)
|
||||
@@ -0,0 +1,52 @@
|
||||
"""ScriptModifier — LLM 으로 협상 스크립트 어조/내용을 다듬되 구조·치환자·스타일 보존.
|
||||
|
||||
openai SDK 직접 호출(langchain 미사용). 프롬프트 문구는 우리 자체 작성(CLEANROOM.md).
|
||||
LLM 미설정/실패 시 원본을 그대로 반환(안전 폴백).
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from negotiation.profiling.config import LlmCredentials
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_SYSTEM = """역할: 협상 스크립트 문장 다듬기 도우미.
|
||||
입력은 JSON 블록 리스트다. 각 블록의 text 만 다듬고 그 외 모든 것은 그대로 둔다.
|
||||
규칙:
|
||||
- 출력은 입력과 동일 구조의 유효한 JSON 이어야 한다. {"script": [...]} 형태로 반환한다.
|
||||
- {price} 같은 치환자는 추가/삭제/변경하지 않는다. 입력에 있던 것만 유지한다.
|
||||
- color/bold 등 스타일 키와 children 배열 구조는 변경하지 않는다.
|
||||
- text 값만 요청된 어조/맥락에 맞게 자연스럽게 다시 쓴다(한국어).
|
||||
- 새로운 키를 추가하지 않는다."""
|
||||
|
||||
|
||||
class ScriptModifier:
|
||||
def __init__(self, creds: Optional[LlmCredentials] = None):
|
||||
self._creds = creds
|
||||
|
||||
def is_available(self) -> bool:
|
||||
creds = self._creds or LlmCredentials.from_config()
|
||||
return creds.is_configured()
|
||||
|
||||
def modify_script(self, original_script: list, context: dict = None) -> list:
|
||||
"""context(예: {'tone': 'polite'})에 맞춰 스크립트 텍스트 수정. 실패 시 원본 반환."""
|
||||
if not original_script or not isinstance(original_script, list):
|
||||
return original_script
|
||||
try:
|
||||
from negotiation.profiling.infra.llm_adapter import chat_json
|
||||
|
||||
messages = [
|
||||
{"role": "system", "content": _SYSTEM},
|
||||
{"role": "user", "content":
|
||||
"원본 스크립트:\n" + json.dumps(original_script, ensure_ascii=False) +
|
||||
"\n\n맥락/지시:\n" + json.dumps(context or {}, ensure_ascii=False) +
|
||||
"\n\n위 규칙대로 다듬어 {\"script\": [...]} 로 출력."},
|
||||
]
|
||||
result = chat_json(messages, creds=self._creds)
|
||||
modified = result.get("script", result) if isinstance(result, dict) else result
|
||||
return modified if isinstance(modified, list) else original_script
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to modify script via LLM: {e}")
|
||||
return original_script
|
||||
@@ -0,0 +1,47 @@
|
||||
import re
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ScriptVerifier:
|
||||
"""수정된 스크립트가 원본의 필수 구조/데이터(파라미터 placeholder)를 유지하는지 검증.
|
||||
|
||||
구 N-profiling/script_verifier.py 이식 (로직 동일, 외부 의존성 없음).
|
||||
"""
|
||||
|
||||
def verify_script(self, original_script: list, modified_script: list) -> bool:
|
||||
if not isinstance(modified_script, list):
|
||||
logger.warning("Verification Failed: Modified script is not a list.")
|
||||
return False
|
||||
|
||||
original_params = self._extract_params(original_script)
|
||||
modified_params = self._extract_params(modified_script)
|
||||
|
||||
# 원본의 모든 파라미터가 수정본에 존재해야 한다(데이터 주입 보장).
|
||||
missing_params = original_params - modified_params
|
||||
if missing_params:
|
||||
logger.warning(f"Verification Failed: Missing parameters {missing_params}")
|
||||
return False
|
||||
|
||||
# 환각으로 추가된 파라미터(원본에 없던 변수) 금지.
|
||||
added_params = modified_params - original_params
|
||||
if added_params:
|
||||
logger.warning(f"Verification Failed: Added unknown parameters {added_params}")
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
def _extract_params(self, script: list) -> set:
|
||||
"""스크립트 구조에서 {param_name} 형태 파라미터를 추출한다."""
|
||||
params = set()
|
||||
for block in script:
|
||||
if not isinstance(block, dict):
|
||||
continue
|
||||
children = block.get("children", [])
|
||||
for child in children:
|
||||
text = child.get("text", "")
|
||||
matches = re.findall(r"\{([^}]+)\}", text)
|
||||
for match in matches:
|
||||
params.add(match)
|
||||
return params
|
||||
Reference in new issue
Block a user