[feat] agent: Req_Chat 슬림화 — 협상 컨텍스트를 DB 조회로 전환 + CRUD 계층 도입
- Req_Chat 을 session_id/user_input/client_step 3필드로 축소 — rq_type·목표가·앵커·품목가·
매출액·유통코드·파트너 유형·수용률 필드 전부 제거
- NegotiationContextLoader 신설: 세션 시작 시 공유 DB 1회 조회로 컨텍스트 확정
· rq_type = sessions.qt_type ({1,3}→재협상 / {2,4}→재견적)
· anchor = sessions.anchoring_price(박제) — NULL 이면 무할인 폴백 anchor=target (v1.2 정책 승계)
· 매출액 = suppliers.total_revenue(KTC 미러), 유통코드 = quotations.supplier_type 매핑
· 파트너 유형 = 상품별 distinct supplier 수 → PartnerType enum(0=NONE/1=SINGLE/2=MULTIPLE)
- 가격 수용률은 세션 내 동적 계산: max(0, (첫 제시가−현재가)/첫 제시가)
- DB 쿼리를 backend crud 패턴으로 분리: INegoContextCRUD(ABC)+NegoContextCRUD,
IChatSessionRepository 인터페이스 추가 (테스트 더블 주입 가능)
- 와일드카드 1% 수락 시 합의가=offer_1pct 반영 + Res_Chat.settled_price 신설 —
backend 요약/입찰가가 이를 최우선 사용 (19,800원 수락이 20,000원으로 기록되던 버그 수정)
- backend: agent 전송 바디 3필드로 축소, 앵커/파트너 조회 메서드 제거,
test_anchoring_chat 을 새 구조로 재작업(박제 소비/폴백 검증은 agent 테스트로 이관)
- 데모 페이지(/demo·negotiation_demo.html) 제거 — 컨텍스트 주입 경로 폐지로 무의미
- 테스트: agent 83/83, backend 57/57 (컨텍스트 로더 실데이터 왕복 4종 + CRUD 더블 검증 포함)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1ac42ddc9c
commit
ed175c5b65
18 files changed
+641
-267
No files matched your search
@@ -14,16 +14,25 @@ from config.server_configs import agent_config
|
||||
from negotiation.chat.service.chat_engine import ChatEngine, ChatSession, StepView
|
||||
from negotiation.chat.service.indicator import compute_indicator
|
||||
from negotiation.chat.service.chat_session_repository import ChatSessionRepository
|
||||
from negotiation.chat.service.negotiation_context_loader import NegotiationContextLoader
|
||||
from negotiation.chat.service.script_repository import ScriptRepository
|
||||
from negotiation.policies.base import EpisodeState, PolicyContext, Transition
|
||||
from negotiation.policy.model_store import QTablePolicyStore
|
||||
from negotiation.qtable.domain.model.snapshot import NegotiationOutcome, NegotiationSnapshot
|
||||
from negotiation.qtable.domain.model.snapshot import NegotiationOutcome, NegotiationSnapshot, PartnerType
|
||||
from negotiation.qtable.domain.service.reward_calculator import RewardCalculator
|
||||
from negotiation.qtable.domain.service.state_calculator import state_index
|
||||
from negotiation.qtable.infra.repository.learning_repository import LearningRepository
|
||||
from router.v1.chat.protocol import Req_Chat, Res_Chat, Res_ChatSession
|
||||
from tenancy.registry import TenantEngine
|
||||
|
||||
# 직접 호출(데모/테스트) 폴백 기본 컨텍스트 — 운영 경로는 NegotiationContextLoader 가
|
||||
# DB(negotiation.sessions·partner.items·partner.suppliers·quotation.quotations)에서 조회한다.
|
||||
_DEFAULT_RQ_TYPE = "재협상"
|
||||
_DEFAULT_TARGET_PRICE = 10000 # KT 목표 매입가
|
||||
_DEFAULT_ANCHOR_PRICE = 9900 # 앵커링가(목표가보다 낮음). 제시가 ≤ anchor → 우선협상
|
||||
_DEFAULT_REVENUE_AMOUNT = 20_000_000 # 매출액(원) — suppliers.total_revenue 미기재 시 폴백
|
||||
_DEFAULT_DISTRIBUTION_CODE = "A" # 유통 코드 — quotations.supplier_type 미지정 시 폴백
|
||||
|
||||
|
||||
class ChatService:
|
||||
async def chat(self, engine: TenantEngine, req: Req_Chat) -> Res_Chat:
|
||||
@@ -33,7 +42,11 @@ class ChatService:
|
||||
|
||||
# 1) 세션 확보 / 시작 (DB 영속 — 재시작/멀티워커 안전, P8-A)
|
||||
session = await sess_repo.get(req.session_id) if req.session_id else None
|
||||
chat_engine = ChatEngine(repo, rq_type=(session.rq_type if session else req.rq_type))
|
||||
# 새 세션 컨텍스트: 요청 페이로드 대신 DB(negotiation.sessions 등)에서 1회 조회.
|
||||
# 행이 없으면(데모/테스트 직접 호출) 기본값 폴백.
|
||||
db_ctx = None if session else await NegotiationContextLoader().load(req.session_id)
|
||||
rq_type = session.rq_type if session else (db_ctx.rq_type if db_ctx else _DEFAULT_RQ_TYPE)
|
||||
chat_engine = ChatEngine(repo, rq_type=rq_type)
|
||||
|
||||
# ① step desync 감지: backend 가 본 직전 봇 step(client_step)이 agent 세션 step 과 다르면 경고.
|
||||
# agent 가 자기 step 을 정답으로 보고 진행하고(응답의 step/client_step 으로 backend 가 따라옴),
|
||||
@@ -54,14 +67,22 @@ class ChatService:
|
||||
# 새 uuid 발급 없이 그대로 세션 키로 쓴다. 없으면(직접 호출/데모) 생성.
|
||||
session = ChatSession(
|
||||
session_id=req.session_id or str(uuid.uuid4()), tenant_id=engine.tenant_id, company_id=engine.company_id,
|
||||
rq_type=req.rq_type, action_space_size=engine.action_space_size,
|
||||
rq_type=rq_type, action_space_size=engine.action_space_size,
|
||||
context={
|
||||
"revenue_amount": req.revenue_amount, "distribution_code": req.distribution_code,
|
||||
"partner_count": req.partner_count, "acceptance_ratio": req.acceptance_ratio,
|
||||
# 앵커링값은 갑(KT/iMK)이 직접 입력한 값을 사용 (UI 기본값 = target*(1-rate)).
|
||||
"anchor_price": req.anchor_price, "target_price": req.target_price, "round": 0,
|
||||
# 매출액 = suppliers.total_revenue, 유통코드 = quotations.supplier_type 매핑 (loader).
|
||||
# 미기재/미지정이면 기본값 폴백.
|
||||
"revenue_amount": db_ctx.revenue_amount if db_ctx and db_ctx.revenue_amount > 0 else _DEFAULT_REVENUE_AMOUNT,
|
||||
"distribution_code": db_ctx.distribution_code if db_ctx and db_ctx.distribution_code else _DEFAULT_DISTRIBUTION_CODE,
|
||||
# 파트너 유형(PartnerType 값 0/1/2) — 상품별 협력사 수 DB 조회로 세션 시작 시 1회 확정.
|
||||
# snapshot.partner_count 로 그대로 사용(값 호환).
|
||||
# 가격 수용률은 컨텍스트에 두지 않는다 — _snapshot 이 라운드별 제시가로 동적 계산.
|
||||
"partner_count": int(db_ctx.partner_type) if db_ctx else int(PartnerType.SINGLE),
|
||||
# 목표가/앵커링가: sessions 행(생성 시 박제된 anchoring_price) → 박제 ‰ → 1% 폴백 (loader).
|
||||
"anchor_price": db_ctx.anchor_price if db_ctx else _DEFAULT_ANCHOR_PRICE,
|
||||
"target_price": db_ctx.target_price if db_ctx else _DEFAULT_TARGET_PRICE,
|
||||
"round": 0,
|
||||
# 기존 공급가(품목 기준가) — 가격협상_확인 인하율 산출용.
|
||||
"item_price": req.item_price,
|
||||
"item_price": db_ctx.item_price if db_ctx else 0,
|
||||
},
|
||||
)
|
||||
view = chat_engine.start(session)
|
||||
@@ -78,6 +99,10 @@ class ChatService:
|
||||
res.chat_end = view.chat_end
|
||||
res.outcome = view.outcome
|
||||
res.desynced = desynced
|
||||
# 합의가: 성공 확정 이후 턴(협상완료 요약 → 협상종료)에 내려준다. 와일드카드 수락처럼
|
||||
# 유저가 직접 입력하지 않은 가격으로 타결될 수 있어 backend 요약/입찰가는 이 값을 최우선으로 쓴다.
|
||||
if session.context.get("final_outcome") == "success" and session.context.get("input_price"):
|
||||
res.settled_price = int(session.context["input_price"])
|
||||
|
||||
# 3) 학습 결합 (가격협상 카드선택 → 카드 스크립트·협상지표 / 종료 보상)
|
||||
if view.error is None and engine.action_space_size > 0:
|
||||
@@ -112,11 +137,24 @@ class ChatService:
|
||||
return res
|
||||
|
||||
# ---- 학습 ----------------------------------------------------------
|
||||
@staticmethod
|
||||
def _acceptance_ratio(context: dict) -> float:
|
||||
"""가격 수용률 동적 계산 — 협력사 첫 제시가 대비 현재 제시가의 양보율 (설계서 공식).
|
||||
|
||||
acceptance = max(0, (첫 제시가 − 현재 제시가) / 첫 제시가).
|
||||
첫 제시 라운드(양보 없음)·첫 제시가 미기록(과거 세션 호환)이면 0(low 버킷).
|
||||
"""
|
||||
first = context.get("first_offer_price") or 0
|
||||
current = context.get("input_price") or 0
|
||||
if first <= 0 or current <= 0:
|
||||
return 0.0
|
||||
return max(0.0, (first - current) / first)
|
||||
|
||||
def _snapshot(self, session: ChatSession, outcome: NegotiationOutcome) -> NegotiationSnapshot:
|
||||
c = session.context
|
||||
return NegotiationSnapshot(
|
||||
revenue_amount=c["revenue_amount"], distribution_code=c["distribution_code"],
|
||||
partner_count=c["partner_count"], acceptance_ratio=c["acceptance_ratio"],
|
||||
partner_count=c["partner_count"], acceptance_ratio=self._acceptance_ratio(c),
|
||||
input_price=c.get("input_price", c["anchor_price"]), anchor_price=c["anchor_price"],
|
||||
target_price=c["target_price"], round_number=c.get("round", 0), outcome=outcome,
|
||||
)
|
||||
|
||||
Reference in new issue
Block a user