Compare commits

...
Author SHA1 Message Date
JinwooKimandClaude Fable 5 0fab2f9cb2 [chore] agent: 서빙 번들 .prev 백업은 추적 제외
export 도구가 번들 교체 때마다 자동 생성하는 직전본 백업 — 버전 기록은
autonomy_v3x.npz 명명본이 담당하므로 git 에는 중복이다.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 17:04:07 +09:00
JinwooKimandClaude Fable 5 8f4c82a282 Merge feat/switch-model into feat/switch-model-v2 (main 1cce752 기준)
충돌 해결 원칙: main 의 협상 고도화(결정 스택 규칙층·ScriptNaturalizer 표현층·카드 전술·
LPS 최저가 연동)와 switch-model 의 완전 자율 모드(DQN·봉투·ment_generator)를 모두 유지.
- chat_engine: rules(config 규칙층) + autonomy_decider 공존, vars_for 는 main 전술 변수 +
  자율 변수(autonomy_offer/internet_lowest_price/customer_condition) 합집합,
  wild_card_1pct 수락 분기는 main 의 pending_counter_price 일반화로 대체(자율 분기만 유지)
- chat_service: tactics/naturalizer import + ment_generator import 병존,
  _play_closing_tactic(main) + _autonomy_learn(자율 로깅) 메서드 병존
- nego_context_crud: _ITEMS/_SUPPLIERS 컬럼 합집합 (name + internet_lowest_price)
- docker-compose: OPENAI_API_KEY passthrough + DQN_SERVING/AUTONOMY_MODE 플래그 병존
검증: py_compile + 결함 회귀 게이트 78/78 통과

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 17:03:04 +09:00
JinwooKimandClaude Fable 5 94c7a6568d [test] agent: 자율 협상 결함 회귀 게이트 (배포 전 필수)
실전에서 발견된 결함 전부를 자동 재생하는 배포 게이트 — 실패 시 exit 1(배포 금지).
지형 2종(실스케일 423,198 / 소액 10,000) x 협력사 시나리오 3종(완고/목표가위 고정/협조)
+ 엔진 전환·봉투 마스크·멘트 가드 단위검사 = 76+항목.

검사 대상은 서빙 실물(AutonomyPolicy.decide + ChatEngine._autonomy_next + ment 가드).
결정론(스크립트 상대 + greedy 정책)이라 실행마다 동일 결과. DB/LLM/도커 불필요.
v3.4 교훈 반영: 한 지형 통과가 다른 지형을 보증하지 않는다 — 게이트 후 궤적 눈 비교 병행.

실행: APP_ENV=local python -m tools.test_autonomy_defects [번들경로]

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 16:58:08 +09:00
JinwooKimandClaude Fable 5 51b3820cc9 [feat] agent: 완전 자율 협상 모드 (AUTONOMY_MODE) + LLM 멘트
판정 룰(앵커타결/와일드존/3라운드결렬)과 카드 선택을 학습 정책으로 대체:
수락/역제안 금액/압박 화법/결렬 전부 행동 30개(수락1+결렬1+역제안 6단x화법4+압박4)에서 선택.

- autonomy_actions: 행동 공간·특징 인코딩 (학습/서빙 공유)
- autonomy_store: numpy 서빙 + 행동 봉투 7개(수락<=목표가 / 역제안 단조 / 역제시·결렬은
  설득 2회 후 해금 / 마무리국면 압박 금지 / 첫 역제안 앵커 이하 / 최종제안 1회 보장)
- chat_engine: 자율 스텝(역제안/최종제안/압박1~4), 최종제안 금액=목표가, 턴캡 12
- ment_generator: Gemini 멘트 생성 + 가드(숫자 화이트리스트·목표가 비공개·금지어·문장완결,
  실패시 템플릿 폴백, 6초 컷), 인터넷최저가 근거 인용(수집됨+제시가 초과시만), 대화 기억
- chat_service: 자율 행동 experience_logs 로깅(AUT|종류|위치|전략), 대화기억 ctx 관리
- context loader/CRUD: 인터넷최저가·견적기간·협력사 이력 로드 (v3 상태 21차원)
- train_full_autonomy: 시뮬 15k ep — 앵커율 0.8~6% 정합, 협력사 현실화(컷반발·반복짜증·
  양보 상호성), 관측성 마스크(마감 40% 미관측·15% 전부미상 — 서빙 중립값 분포 정합),
  보상 수정(목표가 초과 타결=결렬 취급)
- 서빙 v3.5 (v3.3 목표가 즉시지르기 퇴화, v3.4 소액지형 첫턴 통보 퇴화 — 게이트 반려 이력 보관)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 16:57:38 +09:00
JinwooKimandClaude Fable 5 d4acdd0ac5 [feat] agent: 카드 선택 DQN 서빙 전환 (action-as-feature)
- feature_dqn_policy: ScoreNet(상태+카드특징 → 점수) 학습 정책 (replay+타깃넷)
- feature_builder: 이산화 없는 연속 상태 벡터(9) + 테넌트 성향 벡터(5)
- dqn_store: numpy 전용 서빙(컨테이너 PyTorch 불필요), DQN_SERVING 플래그,
  미지원 테넌트는 Q-table 자동 폴백
- 파이프라인: build_card_embeddings -> train_feature_dqn -> export_dqn_serving(npz)
- retrain_from_logs: 실로그 재학습 + OPE(SNIPS) 게이트, 통과 시에만 번들 교체(.prev 백업)
- probe_serving_dqn / compare_qtable_vs_dqn: 배포 전 행동 점검 도구

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 16:56:24 +09:00
민헌 1cce752b47 Merge branch 'feature/negodata-lps' — negodata↔LPS 인터넷 최저가 연동(수동 트리거 전용) 2026-07-10 16:49:49 +09:00
민헌andClaude Fable 5 5ddf5f6249 refactor(negodata): LPS 자동 요청 배치 제거 — 검색은 수동 트리거 전용
협의 결정(2026-07-10): 크롤 비용이 사용자 행동에만 비례하도록,
갱신 오래된 상품을 자동으로 검색 요청하던 잡(매일 04:00, 상한 500건,
일 ~$2)을 제거한다. 검색 진입점은 상품 화면의 수동 트리거
(POST /v1/item/{id}/lowest-price) 하나만 남는다.

- request_lps_searches 잡·request_stale_searches 서비스·stale_items
  CRUD·배치 상수(REFRESH_HOURS 등) 제거
- 수집 잡(sync_lps_results, 5분)은 유지 — 크롤을 일으키지 않는
  반영 백스톱(모달 조기 종료·폴링 초과분 자동 반영, 비용 0)

검증: 스케줄러 등록 잡 3개(견적마감 2 + LPS 수집 1) 확인, 수집 잡 실행 정상

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 16:47:39 +09:00
민헌andClaude Fable 5 3171311746 feat(negodata/front): PriceUpdateModal 데모 → LPS 실연동
- 가짜 setTimeout 애니메이션 제거 — 상품별 POST lowest-price(큐 접수,
  duplicated 는 결과 대기 합류) 후 GET 5초 폴링(서버가 조회 시 lps_db
  증분 동기화를 겸하므로 폴링이 곧 수집)
- 요청 시각 이후 crawl_end_time 이력만 이번 결과로 인정, 완료/미발견
  로그 구분(emerald/amber), 5분 대기초과분은 주기 동기화 자동반영 안내
- 종료 시 /v1/item/list invalidate → 테이블 인터넷 최저가 컬럼 갱신
- 닫기 = 폴링만 중단(서버 검색은 계속됨을 UI 에 명시)
- orval 재생성: lowest-price 응답 타입화(LowestPriceEntry·lowest_price)

검증: tsc 통과, vite build 통과 (API 흐름 자체는 ③ e2e 로 검증됨)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 16:32:38 +09:00
민헌andClaude Fable 5 28b4a9e797 feat(negodata): lowest-price 스텁 API 실구현 — 즉시 트리거 + 온디맨드 동기화 조회
- POST /v1/item/{id}/lowest-price: 상품 1건 LPS 즉시 검색요청(manual
  우선순위). queued/duplicated/unavailable 상태 반환, 실패는
  ErrorType.LPS_UNAVAILABLE(2000 블록 신설)
- GET /v1/item/{id}/lowest-price: 대표 최저가 + 최근 수집 이력(최신순,
  LowestPriceEntry 타입화). 조회 전 lps_db 증분 동기화 1회 수행 —
  5분 크론을 기다리지 않는 실시간 폴링 UX(멱등·저비용)
- 동시성 방어 2겹: 프로세스 내 asyncio.Lock(크론·온디맨드 직렬화) +
  uq_iilp_item_crawl_time 유니크 인덱스(alters/2026-07-10, init.sql
  멱등 반영·dev DB 적용) — 경합 진 쪽 tx 실패 후 다음 tick 흡수
- LpsSyncService 무인자 생성자(FastAPI Depends 호환)
- compose: negodata-backend 에 LPS_DB_HOST·LPS_BASE_URL env(미설정 시
  연동 비활성으로 조용히 동작)

검증(도커 컨테이너 e2e): 인증→POST queued→LPS 크롤→GET 온디맨드
동기화로 이력 즉시 노출(not_found 정책: 대표값 미변경 확인),
company 스코프 차단(타사 상품 ITEM_NOT_FOUND) 확인

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 16:17:05 +09:00
minaChoi c0e6987c3c [fix] negodata/front: 통계 카테고리별 절감 차트 -> 손해(음수)는 안보이게, 대시보드에서 일반관리자도 회사 통계 보이게 수정 2026-07-10 15:58:13 +09:00
민헌andClaude Fable 5 523661e3d2 feat(negodata): LPS 최저가 동기화 배치 — 요청(API)·수집(lps_db)·반영(items)
설계(2026-07-10 결정): 요청은 LPS API(dedupe·워커알림 보존), 결과는
lps_db.price_history 직접 읽기(읽기전용 엔진). product_code=item_id
로 결과가 자동 매핑된다.

- 잡③ request_lps_searches(매일 04:00 KST): 24h 이상 미수집 상품을
  최대 500건 enqueue(job_type=batch, 100건/콜 청크) — 비용 발생 잡
- 잡④ sync_lps_results(5분): 워터마크(max crawl_end_time) 증분 수집
  → item_internet_lowest_prices append(성공/실패 모두) + 성공분 최신값
  items.internet_lowest_price 박제(+yn). 한 트랜잭션(부분반영 방지)
- 스캔 바닥 3일 — 비uuid·미존재 상품 행이 워터마크를 못 올려도
  재스캔 범위 유한
- ⚠️ 시각은 aware UTC 통일 — naive 를 timestamptz 파라미터로 넘기면
  PG 세션 타임존(KST) 해석으로 9시간 어긋남(중복 수집 실측 버그 수정)
- LowestPriceWebsite 코드 enum(naver=1 coupang=2 …), iilp ORM 모델,
  lps_base_url config(+LPS_BASE_URL env)

검증: 실상품 1건 e2e(요청→크롤 found 15,000원→이력+박제 반영),
멱등성(재실행 빈 카운터), 비uuid 12건 스킵, 대상선정 쿼리 500건 상한

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 15:38:57 +09:00
HyeongBaeYangandClaude Fable 5 b41f7c67f1 [feat] negodata: 카드 에디터 조건 전략 변수 + 미리보기 변수 라벨 치환
① 카드 목록 스크립트 미리보기에서 {변수} 토큰을 한글 라벨 칩으로 렌더
   (renderCardScriptPreview) — 원시 토큰({prev_partner_price} 등) 노출 제거.
② "조건 전략"(customer_condition) 특수 변수 추가:
   - 툴바 '+ 조건 전략' → 본문에 위치 칩 삽입, 본문 아래 별도 Slate 입력창 노출
   - 조건 내용은 변수 노드에 중첩 보관(edit_script 배열 유지·하위호환) + 저장 시
     script 의 해당 위치에 주입 → agent 는 완성된 문구를 그대로 읽음(무변경)
   - 서브 에디터는 조건 전략 버튼 숨김(중첩 방지), 빈 조건 저장 차단

DB·백엔드·agent 변경 없음(edit_script 타입 unknown, 조건 노드 내 중첩).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 15:18:11 +09:00
민헌andClaude Fable 5 9e9de52200 feat(negodata): lps_db 읽기전용 연결 기반 — DBType.LPS + 조건부 엔진 등록
LPS(인터넷 최저가 검색) 연동 1단계. price_history 동기화 배치가 쓸
읽기전용 접속을 기존 확장점(DBType enum + 세션매니저 맵)에 등록한다.

- DBType.LPS=2, LpsDBConfig(read_* 만 — write 엔진 미등록으로 앱 차원
  읽기전용 강제, write 요청 시 KeyError)
- config name 비면 미등록(구버전 toml·LPS 없는 환경에서도 부팅 가능),
  배치는 is_registered() 로 사전 확인
- env override: LPS_DB_HOST/PORT/USER/PASSWORD/NAME (도커용)
- 검증: 엔진 등록·읽기 세션·write 가드 KeyError·lps_db.price_history
  실조회 확인

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 15:11:18 +09:00
HyeongBaeYang 26d9fa3c4b Merge branch 'feat/chat-update' — 협상 고도화(LLM 표현/이해층·카드 전술·변수 카탈로그) 2026-07-10 13:39:19 +09:00
HyeongBaeYangandClaude Fable 5 22500eae4c [chore] compose: agent 에 OPENAI_API_KEY passthrough — LLM 표현/이해층 키 주입
빈 값이면 무시(server_configs env override 가 값 있을 때만 적용)라 무해.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 13:37:50 +09:00
HyeongBaeYangandClaude Fable 5 afacd74382 [feat] negodata: 카드 변수 카탈로그에 전술 변수 6종 추가
agent 전술 재설계로 늘어난 치환 변수를 편집기 툴바·칩에 노출:
제시가(input_price)·협력사 직전가(prev_partner_price)·제안가(counter_price)·
중간가(target_mid_price)·절충가(middle_price)·인하율(discount_rate).
name 은 agent chat_engine.vars_for 치환 키와 일치. 라벨은 렌더 시점 조회라
기존 저장 카드도 마이그레이션 없이 한글 라벨로 표기된다.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 13:37:50 +09:00
HyeongBaeYangandClaude Fable 5 1682481b01 [feat] agent: 협상 고도화 — LLM 표현/이해층 + 카드 전술 실행계층 + ktcommerce 정리
카드 재설계("멘트 카드 → 전술 카드"):
- tactics.py 신설: 카드번호→전술(카운터 산식) 레지스트리, min(counter,target) 클램프
- 카운터 수락=즉시 타결(pending_counter_price 일반화, 구 offer_1pct 흡수)
- 목표가 초과 타결 금지(성공스텝 진입 가드) + "카드 소진=실패" 폐지→종결 국면
- 선택형 와일드카드(WC-*) 발동 + card.wild_cards 멘트 DB 어댑터

LLM 계층:
- Phase 2 표현층 ScriptNaturalizer(카드 멘트 자연화, 마커·치환자·숫자 보존 검증)
- Phase 3 이해층 InputInterpreter(자유발화 NLU→기대입력, 한국어 가격 파서)
- OPENAI_API_KEY env override(server_configs) + 전역 자격증명 게이트

결정 스택(Phase 1):
- 협상 규칙 데이터화(negotiation.wildcard_*_ratio/max_counter_rounds)
- 선택카드 우선순위 prior(UCB 방문수 감쇠, Q-table 오염 없음)

버그픽스:
- 인하율 음수 표기 제거 + 인상/동일/인하 구분(discount_phrase)
- 자연화 강조마커 보존(볼드/색 소실 시 원본 폴백)
- 카드 시드 가격변수(prev_partner_price·target_mid_price·middle_price 등) 치환

정리:
- ktcommerce 테넌트 삭제 + 테스트 21파일 imarketkorea/_base 로 마이그레이션
- 실 LLM 호출 차단 conftest 가드

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 13:37:36 +09:00
민헌 18f6466a8b Merge branch 'feature/lps' — 인터넷 최저가 검색(LPS) 시스템 2026-07-10 13:30:48 +09:00
민헌andClaude Fable 5 d4cee1caf7 feat(lps): API 스케일 파라미터를 .env 로 노출 — PROCESS_COUNT·커넥션 예산
주석 상태였던 PROCESS_COUNT/DB_CONNECTION_BUDGET 를 활성화하되 서버별
값은 .env(LPS_API_PROCESS_COUNT, LPS_DB_CONNECTION_BUDGET)로 조정.
기본 1/40 — API 는 단일 프로세스로도 ~1,100 RPS(실측)라 평시 충분,
부하 대비 시에만 상향. 풀 자동 산정이 예산 초과를 방지.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 12:02:17 +09:00
민헌andClaude Fable 5 a267326bf7 fix(lps): Docker 이미지 무시크릿화 + 배포 견고화 — 리뷰 발견사항 일괄 적용
시크릿 유출 차단(핵심):
- config.local.toml(OpenAI·DECODO·네이버 키)이 COPY . . 로 이미지에
  구워지던 문제 — .dockerignore 제외 + 빌드 시 example(플레이스홀더)
  복사로 대체. 실값은 compose env 주입(리포 루트 .env, 템플릿 .env.example)
- DECODO_PORT_START/END/SESSION_MINUTES env override 추가 — 포트가
  toml(플레이스홀더 0)에만 있으면 자격증명을 넣어도 프록시가 조용히
  꺼지는 구멍 봉합

배포 견고화:
- API Dockerfile 에 HEALTHCHECK(/healthz) 추가
- autoheal 컨테이너 추가 — compose restart 는 unhealthy 를 재시작하지
  않으므로 라벨(autoheal=true) 기반 자동 재시작 담당
- 이미지 python 3.12→3.14 정렬(로컬 개발·테스트 환경과 일치)
- API 이미지 경량화: requirements-api.txt 분리(크롤 의존성 제거, 330MB)

검증: 양 이미지 빌드 성공, 이미지 내 시크릿·.profiles 부재 확인,
무시크릿 API 이미지 스모크(healthz/readyz/HEALTHCHECK healthy) 통과

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 11:53:47 +09:00
민헌andClaude Fable 5 c075dfbcfb fix(lps): .dockerignore 에 .profiles/ 추가 — Chrome 세션 이미지 유출 차단
COPY . . 가 로컬 Chrome 프로필(쿠키·cf_clearance, 149MB)을 API·워커
이미지에 굽고 있었다. 컨테이너는 빈 프로필에서 웜업으로 쿠키를 만들고
volume(/profiles)에 영속하는 설계라 이미지에 있을 이유가 없다.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 11:45:19 +09:00
민헌andClaude Fable 5 4381649658 docs(lps): 워커·브라우저 1:1 근거와 워커 수 상한 산정법 문서화
- 6-2: 브라우저가 아니라 신원(프로필+sticky IP)이 희소 자원인 이유,
  비율이 어긋날 때의 손해(유휴 낭비 vs 락 직렬화), 신원당 처리량 캡
- 6-3: 워커 상한 = min(RAM캡, 포트캡÷3, 실측 정체점) — 하드캡 계산식과
  계단식 실측 시 멈춤 신호 5가지(처리량 정체·blocks_1h·메모리·
  단일코어 포화·p95)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 11:32:12 +09:00
민헌andClaude Fable 5 463416c3a2 fix(lps): 워커 행(hang) 3중 방어 — 잡 데드라인·웜업 타임아웃·정리 루프 격리
부하테스트(N=10) 실측: 쿠팡 브라우저 재기동 경로 행으로 워커 2/3가
12~15분 정지(쿠팡 검색 1콜 880s), heartbeat 가 lease 를 계속 갱신해
reaper 회수 불가 + stuck_running=0 으로 관측 사각. 이에 대한 방어:

- P1 잡 데드라인: runner._process 에 wait_for(기본 300s, env
  LPS_JOB_DEADLINE_SEC) — 초과 시 취소·fail → 백오프 재큐/DEAD
- 웜업 시도당 60s 타임아웃 — 웜업이 어댑터 락을 쥔 채 행하면
  그 워커의 실 검색이 전부 락 대기로 동반 정지(실측 케이스)
- P2 browser reaper: close_if_idle 에 60s 타임아웃 — 한 어댑터
  close 행이 정리 루프 전체를 멈추는 것 방지(실측 케이스)
- P3 stuck_running: lease 만료 OR 실행 10분 초과(run_started_at)
  — 행 상태에서도 지표·알림에 잡히게

테스트 5건 추가(데드라인 DEAD/재큐, stuck 지표, reaper 격리)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 11:27:03 +09:00
민헌andClaude Fable 5 fbd2cec1da test(lps): 부하테스트 상품셋 100종 카탈로그 분리 — 실제 입력 분포 재현
- loadtest/catalog.json 신설(실존 상품 100종): 규격만 54 · 모델포함 26 ·
  이름만 20 · 기준가 포함 7 (price→가격밴드 필터 경로 포함)
- loadtest.py 는 인라인 6종 대신 카탈로그 로드, 실행 시 구성 요약 출력

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 10:50:28 +09:00
민헌andClaude Fable 5 5e485e9b6e feat(lps): 오픈마켓 폴백 기본 비활성(LPS_FALLBACKS 토글) — 협의 결정 B안 적용
2026-07-10 협의: 검색은 네이버+쿠팡만. G마켓·옥션·11번가 폴백은 최종 최저가
기여 0회에 검색당 최대 15s·프록시 비용 ~87%를 차지해 로직에서 제외.
주석처리 대신 env 토글로 코드·테스트는 살려둔다(부패 방지·env 한 줄 재가동).

- worker_main: LPS_FALLBACKS(기본 빈값=OFF)로만 폴백 어댑터 생성, 잘못된 값 경고,
  기동 로그에 폴백 상태 표기. 핸들러는 빈 폴백을 원래 정상 처리라 로직 변경 없음
- run_local_worker.sh: 폴백 여부 대화형 질문 추가(기본 비활성)
- compose: LPS_FALLBACKS 주석 env(재가동용)
- decision-openmarket-crawler.md: 결정(B)·근거·재가동 절차(라이브 스모크 선행) 확정 기록
- README·architecture·operations: 기본 비활성 반영

검증: 전체 테스트 106 passed(폴백 로직 테스트는 fake 주입이라 계속 유효),
워커 실기동 로그 '오픈마켓 폴백: OFF' 확인

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 10:14:39 +09:00
minaChoi 7f1c0be2b3 [feat] negodata: 협력사 채팅 계정(supplier_users) 관리 — 발급·비번 재설정·활성상태
- 백엔드: supplier_users/supplier_user_tokens ORM 매핑, /v1/supplier/{id}/account 4종(조회·발급·재설정·상태), 회사 스코프 게이팅, 재설정·비활성 시 토큰 삭제로 기존 로그인 즉시 무효화
- 비밀번호: 발급=서버 자동생성(1회 반환), 재설정=커스텀 지정 가능(미지정 시 자동생성)
- 프론트: 협력사 상세 SupplierAccountManager 섹션 + 목록 '채팅 계정' 컬럼, orval 재생성(SupplierType 은 enumLabels 로컬 상수로 이동)
- 테스트: test_supplier_account.py 9건, 전체 스위트 green
2026-07-10 10:14:00 +09:00
민헌andClaude Fable 5 89fe2c9805 feat(lps): 실시간 관측 대시보드 추가 — 큐 추이·코어별 CPU·프로세스 그룹 사용률
loadtest/monitor.py (:9700, 단일 파일·외부 인프라 없음) + run_monitor.sh(대화형).
e2e 부하(N=100 loadtest.py) 중 "프로세스가 잘 진행되는지, 코어가 전부 도는지,
병목이 어느 층인지"를 브라우저에서 2초 간격으로 본다:

- 큐 추이: /v1/lps/ops 폴링 — PENDING/RUNNING/DONE/DEAD 라인 + 처리량(개/분) 타일
- 프로세스 그룹 CPU: worker/api/chrome/postgres — 병목 층 판독
  (chrome 은 워커 자손만 집계해 사용자 브라우저와 분리, uvicorn spawn 자식은 부모로 api 귀속)
- 코어별 사용률 막대: 멀티코어 활용 확인
- 현재 스냅샷 표 + 호버 툴팁 + 라인 끝 직접 라벨(dataviz 팔레트 검증 통과, 다크 서피스)
- psutil 의존성 추가(로컬 관측 전용)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 09:50:14 +09:00
민헌andClaude Fable 5 64d5063041 feat(lps): 서버 실행 스크립트에 멀티코어 대화형 선택 추가
일반 실행(1) 선택 시 PROCESS_COUNT 를 물어보고(기본 1, CPU 코어 수 표기),
2 이상이면 DB_CONNECTION_BUDGET 도 물어본다(기본 96 — 전용 PG 벤치값).
워커 스크립트(run_local_worker.sh)의 동시성 질문과 같은 대화형 패턴.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 09:09:55 +09:00
민헌andClaude Fable 5 47c64eaf8b fix(lps): 워커 graceful shutdown — 신호 핸들러·잡 마무리 유예·정리 격리
- SIGINT/SIGTERM 핸들러 등록: cancel 대신 stop 이벤트 set → 새 잡 클레임 중단,
  하던 잡은 마무리 후 자연 종료(트레이스백 없이 exit 0). 신호 재수신 시 강제 종료
- 종료 유예 LPS_SHUTDOWN_GRACE_SEC(기본 60s) 초과 시 강제 취소(잡은 lease 만료 후 재큐)
- 워커/리퍼가 예외로 죽으면 기존처럼 전파하되, finally에서 남은 태스크 취소·완주 대기 후 정리
- 리스너·어댑터 정리를 항목별 try/except로 격리 — 하나 실패해도 나머지 Chrome 정리
- 웜업(bg) 태스크는 종료 신호 즉시 취소해 어댑터 락 해제
- compose lps-worker에 stop_grace_period: 75s (기본 10s면 드레인 전 SIGKILL)
- 운영 가이드에 워커 종료 절차 문서화

검증: SIGTERM/SIGINT 실기동 테스트 — graceful 로그 후 exit 0, 기존 테스트 26개 통과

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 09:03:57 +09:00
민헌andClaude Fable 5 ddb6f6bd2f fix(lps): 워커 로그 노이즈 2건 제거 — 리퍼 네이버 스킵 + 폴백 데드라인 cancel 제거
- browser-reaper가 close_if_idle 없는 어댑터(네이버 httpx)를 건너뛰도록 getattr 가드
  → 30초마다 반복되던 ERROR 로그 제거
- 폴백 데드라인을 wait_for(cancel) → asyncio.wait(버림)으로 변경
  → in-flight page.goto 취소 시 patchright 내부 future가 남기는
    'Future exception was never retrieved' 노이즈 제거, 페이지 어중간 상태 방지
  → 버려진 태스크는 강한 참조 집합(_abandoned_fallbacks)에 보관(GC 중도 파괴 방지),
    종료 시 콜백이 예외 회수 후 집합에서 제거
- 데드라인 테스트에 잔여 태스크 배수(drain) 검증 추가

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 08:50:12 +09:00
민헌andClaude Opus 4.8 08a9c52088 docs(lps): 아키텍처에 API 멀티코어 스케일·커넥션 풀 자동산정(6-1) 추가
process_count 를 늘릴 때 풀 오버서브스크립션→커넥션 고갈 함정과
connection_budget 기반 자동 역산 해법을 문서화.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 08:35:48 +09:00
민헌andClaude Opus 4.8 0e30354ba5 feat(lps): 로컬 워커·부하테스트(GUI) 실행 스크립트 추가 (대화형)
기존 run_local_server.sh 스타일에 맞춘 대화형 .sh 두 개.

- run_local_worker.sh: 동시성(WORKER_CONCURRENCY)·Chrome 프로필(LPS_PROFILE_DIR)
  선택 후 워커 기동. 실행 중 워커 감지 시 교체 여부 확인. venv/config 자동 보장.
- run_loadtest_gui.sh: Locust 웹 UI(:8089) 기동. 워커 실행 중이면 경고(크롤 비용),
  API 미기동 시 PROCESS_COUNT 받아 백그라운드 기동(종료 시 함께 정리). 부하생성기 --processes.
- .gitignore(lps): .profiles/(Chrome 쿠키·cf_clearance 세션) 커밋 방지
- README·operations: 새 스크립트 안내로 갱신

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 08:33:11 +09:00
민헌andClaude Opus 4.8 9c2432c818 feat(lps): process_count 기반 커넥션 풀 자동 산정 — 멀티코어 풀 오버서브스크립션 방지
connection_budget(기본 40)을 두고, 기동 시 process_count 에 맞춰
pool_size/max_overflow 를 역산: (pool+overflow)×2엔진×process_count ≤ budget.
워커를 늘려도 config 가 스스로 예산을 지켜 커넥션 고갈→요청 실패를 예방.

- config_models: MainDBConfig.connection_budget 추가
- server_configs: _autosize_pool(process_count 확정 후 산정) + _apply_pool_env_override
  (우선순위 = 명시 DB_POOL_SIZE > 자동 산정 > toml pool)
- web_main: 기동 로그에 실효 풀/총커넥션/예산 출력
- env: DB_CONNECTION_BUDGET override, docker-compose 에 knob 노출
- tests: test_pool_autosize 10케이스(예산 준수·분할비·비활성·infeasible 바닥)
- docs: operations 2-1 멀티코어/풀 섹션 + loadtest README 자동산정 표

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-09 23:59:05 +09:00
민헌andClaude Fable 5 a63793daf0 test(lps): Locust API 부하 테스트 + 멀티코어 벤치 (풀 병목 발견·증명)
API(enqueue/조회, asyncpg I/O 바운드) 부하 테스트로 멀티코어 활용·한계 측정.

- loadtest/locustfile.py: enqueue(고유코드 write)+조회 가중 부하.
- loadtest/bench_multicore.sh: PROCESS_COUNT 1→N 자동 비교(--processes 로 부하생성기도 멀티프로세스).
- server_configs: PROCESS_COUNT / DB_POOL_SIZE / DB_MAX_OVERFLOW env override(코드·toml 수정 없이 튜닝).
- loadtest/README.md: 발견 문서화.

발견(11코어·1500users): 기본 풀(10/20)로 워커 늘리면 실패 폭증(1w=0 → 4w=10336) —
(pool+overflow)×2엔진×workers=240 > PG max_connections=100 커넥션 고갈(SQLAlchemy pool checkout 실패).
증명: 풀 8/4(96<100)로 PC=4 재실행 → RPS 1336→2705(2배), 실패 0. 코드는 멀티코어 활용 가능,
막는 건 풀 오버서브스크립션. 규칙: (pool+overflow)×2×process_count ≤ max_connections.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 23:45:25 +09:00
민헌andClaude Fable 5 eba78dbbb9 docs(lps): README 최신화 — Dockerfile.worker·문서목록(배포/관측/크롤러논의)
폴더구조에 Dockerfile.worker, 문서 표에 Docker배포·관측·decision-openmarket-crawler 반영.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 23:32:52 +09:00
민헌andClaude Fable 5 97e566f844 docs(lps): 운영 가이드 — 관측(readyz/ops/알림)·라이브 스모크·Docker 배포
P4/P5 반영: /readyz·/v1/lps/ops·워커 하트비트·임계 알림 env, LPS_LIVE 라이브 스모크,
docker compose 배포(헤드풀 Chromium+Xvfb·시크릿 env·프로필 볼륨·HEALTHCHECK).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 23:27:02 +09:00
민헌andClaude Fable 5 eb1ff8fee1 test(lps): P5 브라우저 경로 스모크 — search 오케스트레이션 + 라이브 드리프트 감지
가장 취약·복잡한 경로(회전·재시도·차단감지)의 자동 테스트 공백을 메운다.

- mock 하니스(_MockPage/_MockCtx/_MockProxy)로 search() 를 결정론 테스트(브라우저 없이):
  정상 반환 / 차단→IP회전→복구 / 프록시전송오류→회전→복구 / 비프록시오류→실패(무회전) /
  차단 소진→blocked 실패. 5종.
- 라이브 스모크(각 어댑터 실제 사이트 검색→파싱): 셀렉터·안티봇 드리프트 감지. IP 의존·느려서
  기본 skip, LPS_LIVE=1 로 명시 실행(수동/야간). 네이버 스모크 통과 확인.

전체 96 passed, 5 skipped.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 23:25:42 +09:00
민헌andClaude Fable 5 d6dd47e652 feat(lps): P4 관측·알림·워커 헬스 — readyz/ops + 하트비트/HEALTHCHECK + 임계 알림
프로덕션 운영 가시성. 행/좀비 워커 감지 + 큐/차단 지표 노출 + 임계 알림.

- API: /readyz(DB 도달성=readiness, 실패 503; /healthz=liveness와 구분).
  /v1/lps/ops(플랫 JSON): 큐 카운트 + oldest_pending_sec(큐지연) + dead_1h + stuck_running + blocks_1h.
- crud: JobQueue.ops()/ping(), BotDetectionLog.recent_count().
- worker: run_ops_monitor — 하트비트 파일 주기 갱신(Docker HEALTHCHECK 가 신선도로 행 워커 감지)
  + 임계(DEAD/차단/큐지연/stuck) 초과 시 WARN 로그 + (LPS_ALERT_WEBHOOK 있으면) Slack 호환 웹훅.
- Dockerfile.worker: HEALTHCHECK(하트비트 <120s). 임계·웹훅은 env(LPS_ALERT_*).
- 테스트: readyz/ops 2종.

검증: 컨테이너 healthy 판정, 하트비트 갱신, ops 스냅샷 정상. 91 tests.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 23:21:43 +09:00
민헌andClaude Fable 5 3a8d669970 feat(lps): P2 시크릿 env 주입 + Chrome 프로필 영속 볼륨
프로덕션에서 시크릿을 이미지에 굽지 않고 env 로 주입, 재시작 시 챌린지 쿠키 유지.

- server_configs: 시크릿 env override 추가(house 의 DB override 패턴 확장) —
  OPENAI_API_KEY/MODEL, DECODO_HOST/USERNAME/PASSWORD/COST_PER_GB, NAVER_KEYS="id:sec,...".
  로컬은 env 미설정 → config.local.toml 그대로.
- worker_main: Chrome 프로필 경로를 LPS_PROFILE_DIR(기본 /tmp)로 env 화 → 영속 볼륨 마운트 가능.
- docker-compose: lps-worker 에 lps-profiles 볼륨(/profiles) + 시크릿 env 주입 주석 예시.
- config.example: 프로덕션 env 주입 목록 문서화.

검증: env override 동작(OpenAI/DECODO/Naver), 프로필이 /profiles 볼륨에 Cookies 포함 저장(cf_clearance 유지). 89 tests.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 23:04:37 +09:00
민헌andClaude Fable 5 94d4e54d5e feat(lps): P1 컨테이너화 — 워커 이미지(Chromium+Xvfb) + compose
프로덕션 배포 토대. headless Chrome 은 Akamai/Cloudflare Turnstile 에 탐지됨(실측 실패)
→ 컨테이너에선 Xvfb(가상 디스플레이)로 headful Chromium 을 실행한다.

- Dockerfile.worker: chromium+xvfb+xauth+한글폰트. Xvfb 를 백그라운드로 띄우고 python 을
  exec 승계(로그가 docker logs 로 나옴; xvfb-run 은 stdout 을 삼킴). root=--no-sandbox 필수.
- Dockerfile: API 전용(lean, 브라우저 불필요)임을 명시.
- docker-compose: lps-api(:9600) + lps-worker(shm 1g, DB=host.docker.internal) 서비스 추가.
- browser_base: 브라우저 실행 대상 env 화(LPS_CHROME_EXECUTABLE/CHANNEL). 컨테이너=시스템
  chromium(+no-sandbox/disable-dev-shm-usage), 로컬=실제 Chrome(channel=chrome).

검증(컨테이너): DB연결·프리플라이트·쿠팡(Akamai)·gmarket(Turnstile) 웜업 통과 →
end-to-end 검색 DONE(8몰: 네이버·쿠팡·G마켓·옥션·11번가, 비용 $0.016). docker logs 로 로그 확인.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 22:56:56 +09:00
민헌andClaude Fable 5 e2cd2570e3 docs(lps): 오픈마켓 크롤러 유지 여부 논의 문서
팀 논의용 의사결정 메모 — 크롤러가 비용·복잡성 ~80%인데 ROI 미증명.
현황 데이터(비용 87% DECODO·최저가 이긴 적 0·플래키), 핵심 질문(by_mall 소비처),
옵션 4종(A.TTL캐시 / B.게이트 / C.gmarket드롭 / D.현행), curl_cffi 불가 근거.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 21:51:21 +09:00
민헌andClaude Fable 5 10eb67e8c6 docs(lps): 문서 최신화 — 오픈마켓 폴백·Turnstile·비용계측·동시성·프록시복원력
이번 라운드 변경을 README/아키텍처/운영 가이드에 반영.
- README: 기능표(오픈마켓 폴백·원가계측·다중병렬), 워크플로우 4-1 폴백 단계, 폴더구조
- architecture: 안티봇 대응(쿠팡 Akamai / ESM Cloudflare Turnstile 웜업·동적차단),
  검색 원가 계측(CDP 실측·컴포넌트별 비용), 다중 상품 병렬, 유휴 브라우저 정리
- operations: 로그 항목(프리플라이트·웜업·IP회전·데드라인·유휴정리), 문제해결(407·Turnstile·
  Chrome 정리·느림/비쌈), 배포유의, 원가/몰별 DB 쿼리

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 21:18:12 +09:00
민헌andClaude Fable 5 77a36c43d4 fix(lps): gmarket 웜업 신뢰성 — 나쁜 IP 시 회전 재시도
웜업이 인터랙티브 Turnstile(IP 평판 나쁨)로 실패하면 다른 IP 로 회전해 최대 3회 재시도.
gmarket 커버리지 플래키함 완화(100 IP 풀에서 좋은 IP 를 찾을 확률↑).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 21:06:29 +09:00
민헌andClaude Fable 5 0cd817a61d fix(lps): 대역폭 비용 정확화 — CDP 실제 전송 바이트로 계측
지금까지 last_bytes=page.content()(렌더된 DOM 크기)라 실제 네트워크 전송량이 아니었다
— 리소스 차단 효과가 안 보이고 ESM DOM(~5MB) 과대계상 → DECODO 비용이 부정확했다.

- browser_base: CDP 세션(new_cdp_session) 부착, Network.loadingFinished 의 encodedDataLength
  누적 → last_bytes=실제 전송 바이트. 컨텍스트당 1회 부착, 검색마다 리셋. 미지원 시 DOM 폴백.
- 실측(gmarket): 콜드(차단해제) 3.44MB → 웜(차단활성) 1.07MB(~3x↓) — 동적 차단 효과가 이제 숫자로 보임.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 20:27:11 +09:00
민헌andClaude Fable 5 8a594b667d perf(lps): Step2/3 — Turnstile 웜업·동적 차단 + 유휴 브라우저 정리
G마켓/옥션 Cloudflare Turnstile 을 실제로 통과시키고, 쌓이는 브라우저를 정리한다.

Turnstile 규명(실측): patchright 가 콜드 ~12초에 자동 통과, 통과 후 cf_clearance 쿠키로
이후 요청은 ~5초(웜). 단 **리소스를 조금이라도 차단하면 Turnstile 지문검사에 걸려 실패**
(이미지만 막아도 실패). 하지만 **cf_clearance 확보 후엔 차단해도 재챌린지 없음**.
- 동적 차단: _block_active + _blocking_now() 훅. ESM 은 cf_clearance 있을 때만 차단
  (콜드=허용→Turnstile 통과, 웜=이미지/미디어/폰트 차단→대역폭↓). ready_timeout 25s.
  best-effort Turnstile 체크박스 클릭(인터랙티브/나쁜IP 대비).
- 웜업: 기동 시 gmarket/auction/coupang 를 1회 풀어 쿠키 선점(백그라운드) → 실 작업은 웜.
- 유휴 브라우저 정리: _last_used + close_if_idle + run_browser_reaper(유휴 120s) — 메모리 회수.
  쿠키는 user_data_dir 에 남아 재기동해도 (같은 IP면) 웜 유지.
- 테스트: 유휴 정리 2종.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 20:20:58 +09:00
minaChoi a80dac20ed [fix] postgres-init: init.sql 병합 충돌 해소 — last_accessed_at DEFAULT now()
stash 충돌 마커 제거. company.users·supplier.supplier_users 에 DEFAULT now() 추가(신규 DB)
+ 말미 보정 ALTER(기존 DB). ORM server_default 의존이라 없으면 유저 생성 시 NOT NULL 위반.

Little-Helped: Stupid Claude
2026-07-09 17:04:40 +09:00
minaChoi 1b9ca062f3 [feat] negodata: 협상카드 회사 스코프·공용 읽기전용 + 견적 목표가 산정내역 수정
협상카드
- 목록/조회를 등록자 개인 → 회사(company.users 조인) 단위로 확장: 같은 회사 유저 카드 + 공용(user_id NULL)
- 공용 카드는 기본 제공 자산 → 수정·삭제 불가(OWNER 포함), is_shared=True API 등록 거부
- 개인 카드 변경은 본인∪최고관리자만, 프론트 버튼 disable+툴팁
- 공개범위 셀렉터·엑셀 공개범위 컬럼·CardTable 전체 배지 제거(항상 개인 등록)
- test_card.py 5케이스 재작성

견적 목표가 산정내역
- get_setting_rates: 단일 컬럼 select 결과를 이중 인덱싱해 항상 예외 → 마진율이 늘 0으로 적용되던 버그 수정
- get_target_breakdown: 채택 후보 판정을 '현재 최소값' → '저장 목표가와 값 일치'로 변경(산정 후 상품가 변동에도 초록 체크 유지)
- 견적상세 협상카드 탭 세션ID 컬럼 제거

견적생성 모달
- 목표가 미리보기·마감기한 기본값(+1h)·미래 검증, combobox 팝오버 scrollIntoView, maskPrices 비율(%) 마스킹

Little-Helped: Stupid Claude
2026-07-09 17:04:40 +09:00
민헌andClaude Fable 5 4b8dee8583 perf(lps): Step1 — 폴백 데드라인 + fail-fast로 검색 지연 상한
G마켓 챌린지가 안 풀린 채 25~70초를 먹던 문제에 상한을 씌운다. 폴백은 '있으면 좋은'
보강이라 데드라인으로 잘라도 안전(그 몰만 스킵).

- handler: 각 폴백 크롤에 fallback_deadline_sec(기본 15s) wait_for. 초과 시 스킵.
  _timed_search 예외를 BaseException 로(CancelledError 계측 포함).
- 폴백 어댑터 max_block_retries=0(챌린지 대기 2배 방지), ESM ready_timeout 22→12s, st11 20→15s.
- 테스트: 느린 폴백 데드라인 스킵 1종.

실측(동시성2·4상품): 상품당 p50 84.6s→34.2s(~2.5x), 벽시계 181s→65s(~2.8x),
처리량 1.3→3.7 상품/분, 1000건 $7.12→$5.06(~29%↓, 실패 챌린지 대역폭 절감).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 17:01:09 +09:00
민헌andClaude Fable 5 ba67275cd8 docs(lps): 운영 가이드 — WORKER_CONCURRENCY 병렬 실행 + loadtest.py 안내
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 16:28:51 +09:00
민헌andClaude Fable 5 ad26e6ce6f feat(lps): 다중 상품 병렬 검색(워커별 브라우저 세트) + 부하테스트 스크립트
WORKER_CONCURRENCY 를 늘려도 공유 브라우저 lock 때문에 직렬화되던 문제를 고쳐 진짜 병렬 검색.

- worker_main: _build_worker(i) 로 워커마다 자립 세트(브라우저 어댑터·AI·핸들러) 생성.
  프로필 분리(user_data_dir_w{i}, ProcessSingleton 충돌 회피) + 워커별 다른 프록시 포트
  (proxy.seed_offset 로 100포트를 균등 분할=다른 IP). naver/judge/keyword 도 워커별(공유상태 경합 제거).
  프리플라이트는 대표 프록시로 게이트 1회 확인.
- proxy.seed_offset(k): 워커 시작 포트 분산.
- loadtest.py: N개 상품 제출→폴링→처리량·지연(p50/p95)·AI/DECODO/총비용 집계.
  실측(동시성2, 4상품): 순차합 323s→벽시계 181s(~1.8x), 상품당 $0.0071, 1000건 ~$7.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 16:28:08 +09:00
민헌andClaude Fable 5 bf19d4a8fd perf(lps): 폴백 크롤 병렬화 + 오픈마켓 대역폭 절감
한 검색의 소요·DECODO 비용을 크게 낮춘다(실측: 110s→52s, proxy 8MB→2MB, 총비용 70%↓).

- 폴백 병렬화: _enrich_with_fallback 의 순차 for-loop → gather 동시 크롤. 각 몰 어댑터는
  별 브라우저 인스턴스라 병렬 안전. 소요=합→최댓값. AI usage 계측 동시성 불변식 주석 명시
  (judge.last_usage 세팅~읽기 사이 await 없음 → asyncio 협조 스케줄링상 안전).
- 대역폭: blocked_resource_types 를 어댑터별 설정화. 오픈마켓은 이미지/미디어/폰트만 차단
  (CSS/JS 유지 — 챌린지/렌더 보호). 격리 실험으로 차단 유무가 ESM 챌린지 성패에 무관함 확인
  (실패 원인은 IP평판/headless). st11 라이브 0.11MB 검증.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 16:11:32 +09:00
minaChoi 0d62440ee1 [feat] negodata/front: 온보딩 페이지 추가 + 이용안내 모달 재작성 2026-07-09 16:08:54 +09:00
민헌andClaude Fable 5 a80109cdcf chore(lps): FE 원가 타일 AI/DECODO 비용 분해 + config example cost_per_gb
- 임시 FE: 총 비용 타일에 AI·DECODO 분해, 크롤 트래픽에 프록시 경유 바이트(과금분)
- config.local.toml.example: DecodoConfig.cost_per_gb 안내

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 15:34:57 +09:00
민헌andClaude Fable 5 c955a8f367 feat(lps): 프록시 전송오류 IP회전 + 시작 프리플라이트 + DECODO/컴포넌트별 비용
프록시(DECODO) 포트/IP 사망(407/ERR_TUNNEL/ERR_HTTP_RESPONSE_CODE_FAILURE)이
봇차단과 구분 없이 예외로 튕겨 같은 죽은 포트로 재시도만 하다 DEAD 되던 문제를 고친다.

- browser_base: is_proxy_error(순수함수) + search 루프에서 프록시 전송오류 시 IP 회전 재시도
  (max_proxy_retries=2). 봇감지 회전과 통합. uses_proxy 프로퍼티.
- 쿠팡 어댑터를 BrowserSearchAdapter 로 통합 — 중복 machinery 제거, 회전 로직 한 곳에서 공유
  (detect_block 순수함수는 유지, 테스트 호환).
- proxy.healthcheck(): 시작 프리플라이트 — 살아있는 포트 선점 + egress IP 로그(빠른 실패·가시성).
  worker_main 기동 시 호출.
- 비용: DecodoConfig.cost_per_gb 추가. metrics 에 proxy_bytes(네이버 직접 제외) + 컴포넌트별
  cost{ai_usd, proxy_usd, total_usd}. FE 원가 타일에 AI/DECODO 분해·프록시 바이트.
- 테스트: is_proxy_error 8종 + 비용 분해 1종.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 15:33:37 +09:00
민헌andClaude Fable 5 9c478e80fd chore(lps): 임시 FE — 검색 원가 4타일(소요/AI비용/토큰/크롤 트래픽)
작업 카드에 result.metrics 렌더: 소요시간(+소스별), AI 비용$·호출수, AI 토큰(in/out),
크롤 트래픽(html bytes·fetch수·크롤 몰).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 15:17:42 +09:00
민헌andClaude Fable 5 69f6641c27 feat(lps): 검색 1건 원가 계측 — AI 토큰·비용 + 시간 + 크롤 트래픽
검색이 소모하는 리소스/비용/시간을 잡 단위로 집계해 result.metrics 로 적재(API/FE 노출).
지금까진 타임스탬프만 있고 실제 비용 동인(AI 토큰·대역폭)은 버려지고 있었다.

- services/metrics.SearchMetrics: duration_ms + ai(calls/tokens/est_cost_usd, gpt-4o-mini 단가)
  + crawl(fetches/html_bytes/malls_crawled) + source_ms
- AI 클라이언트: resp.usage 를 last_usage 로 노출(그동안 폐기하던 토큰)
- 어댑터: last_bytes(처리 HTML 바이트) 노출 — naver/coupang/browser_base 공통
- handler: 각 fetch 타이밍+바이트, AI 호출 토큰을 metrics 로 누적 → 결과에 스냅샷
- FE: 작업 카드에 원가 4타일(소요/AI비용/토큰/크롤 트래픽)
- 테스트 2종. ⚠️ html_bytes 는 대역폭 근사(오픈마켓 리소스 미차단분 제외=하한), CDP 정확화는 백로그

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 15:14:35 +09:00
민헌andClaude Fable 5 61b9e6ae82 docs(lps): 오픈마켓 폴백 크롤 반영 — 아키텍처·README
파이프라인 ⑤-1 폴백 단계(네이버 미커버 몰만 크롤), 구성요소 표에 오픈마켓 폴백,
폴더 구조에 esm/st11 추가.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 14:54:00 +09:00
민헌andClaude Fable 5 7e5814b0e5 chore(lps): 임시 FE — 오픈마켓 크롤 소스 표기(색상·크롤 뱃지·몰별 색)
by_mall/top 에 등장하는 gmarket·auction·st11 을 소스 색상 태그(+‘크롤’ 뱃지)로 표기.
몰별 최저가 막대도 소스별 색. 폴백으로 크롤된 몰임을 UI에서 구분.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 14:47:31 +09:00
민헌andClaude Fable 5 f9714c3f06 feat(lps): 오픈마켓 폴백 오케스트레이션 + 몰 dedup
사용자 규칙 '네이버로 그 몰 값 확보 성공→그 값, 실패(몰 없음)→실사이트 크롤' 구현.

- handler: found 라운드 뒤 _enrich_with_fallback — 네이버 매칭이 커버 못 한 타깃 몰만
  (canonical_mall 로 판정) 크롤 어댑터로 검색→같은상품 판정→병합. 크롤 실패는 격리(무시).
  fallback_crawl STAGE 기록.
- summarize_by_mall: 키를 (source,mall)→몰명(canonical)으로 — 네이버노출 vs 직접크롤 같은 몰
  중복을 최저가 1건으로 병합(dedup).
- card_parser: MALL_BY_SOURCE + canonical_mall() 추가.
- worker_main: gmarket/auction/st11 폴백 어댑터 등록(lazy 기동, 리소스차단 OFF).
- 테스트: 커버몰 크롤생략·미커버 크롤·실패격리·몰 dedup 4종.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 14:45:39 +09:00
민헌andClaude Fable 5 e365e5c6e0 feat(lps): G마켓·옥션·11번가 크롤 어댑터 + 브라우저 어댑터 베이스
네이버 폴백용 오픈마켓 크롤러 3종. 4중 복제를 피해 BrowserSearchAdapter 베이스로
브라우저 수명·프록시 회전·차단감지+IP회전 재시도·감지기록을 공유하고, 사이트 차이는
훅(_search_url/_parse/ready_selector/block_markers)으로 분리.

- browser_base: patchright 공통 machinery(쿠팡 machinery 일반화)
- card_parser: 오픈마켓 공용 카드 파서(CardConfig 주입) + util(extract_price/clean_name/shipping)
- esm: G마켓·옥션(eBay 백엔드 공유, site 파라미터 1개로 커버, '잠시만' 챌린지 대기)
- st11: 11번가 PC(공식API 판매자계정 필요라 불가). 지연로딩 → scroll_steps, '.c-card-item' 토큰
- 학습 반영: 오픈마켓은 리소스차단 OFF(렌더/챌린지 깨짐), 스턱 챌린지='잠시만' 잔존 시 차단 간주→IP회전
- 파서 결정론 테스트 7종(실렌더 카드 3개씩 경량 fixture). 라이브 검증: 신선 IP로 3사 모두 파싱 성공

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 14:41:05 +09:00
민헌andClaude Fable 5 3a2c6e43d4 feat(lps): price_history 몰별 최저가 스냅샷(by_mall JSONB)
몰이 열린 집합이라 와이드 컬럼(gmarket_*, st11_* …) 대신 JSONB 한 컬럼으로 담는다
— 몰 추가 시 마이그레이션 0. naver/coupang/final 3선 컬럼은 그래프 하위호환 유지.

- models: price_history.by_mall JSONB 추가
- crud: record/list 에 by_mall 왕복(json.dumps + CAST jsonb)
- handler: _price_snapshot 에 summarize_by_mall 적재, final 은 소스무관 전체 최저로
- protocol/service: history API 응답에 by_mall 노출
- migrations/2026-07-09: 기존 dev DB 동기화용 ALTER(추적 파일)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 14:15:58 +09:00
민헌andClaude Fable 5 2eccf4de50 chore: 로컬 리서치 노트(Temp.md·new.md) gitignore 처리
크롤링 라이브러리/안티스크래핑 조사 노트로 로컬 참고용. 향후 크롤러 작업에
관련되므로 삭제하지 않고 추적만 제외해 git status 를 정리한다.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 14:03:08 +09:00
민헌andClaude Fable 5 7806b35723 chore(lps): 임시 검색 콘솔 FE(lps-temp-fe) — API/그래프/몰별·배송 확인용
API 통신 확인용 단일 파일 프론트(외부 CDN 0, SVG 차트 자체 구현).
검색 요청 → 잡 폴링(파이프라인 퍼널·소스별 건수) → 최저가 히어로/상품표,
최저가 이력 3선 그래프(네이버·쿠팡·최종), 몰별 최저가 막대, 배송 뱃지,
헤더 헬스·큐 상태 실시간. CORS 매칭 위해 :5173 서빙(serve.sh, 대화형).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 13:59:56 +09:00
민헌andClaude Fable 5 8460a5d833 fix(lps): 쿠팡 차단 감지 다종화 — Edge Deny·권한제한·짧은HTML 폴백
기존엔 Akamai JS 챌린지 마커만 감지해, Edge Access Denied(errors.edgesuite.net)와
'사용권한이 제한된' 권한제한 페이지가 blocked=False 로 오판됐다. 그 결과 IP 회전·
bot_detection 기록이 누락되고 같은 IP 로 재시도만 반복하다 DEAD 로 빠졌다.

- 마커 3계열로 확장(Akamai / Edge Deny / 권한제한)
- 짧은 HTML 폴백(_MIN_RESULT_HTML): 0건인데 <10KB 면 미지의 차단으로 간주
  (정상 '검색결과 없음'은 전체 chrome 포함이라 큼)
- 감지를 순수 함수 detect_block(html, product_count) 로 분리 — 단위 테스트 6종

검증: 신라면 '사용권한이 제한된'(3383B) 감지 → IP 회전 → 새 IP 59건 복구.
파서 배송 분류 테스트도 함께 추가(shared fixture).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 13:59:43 +09:00
민헌andClaude Fable 5 61bc719e28 feat(lps): 배송비 유형 분류 — 쿠팡 배송신호 파싱 + 네이버 배송비제외 명시
NormalizedProduct 에 shipping_type(rocket|rocket_merchant|free|paid|None) 추가.
쿠팡 파서: 로켓 뱃지(img src)로 유형, '무료배송'/'배송비 X원' 텍스트로 금액 판별
(상품명 '무료배송' 오탐은 이름 제거 후 매칭). 네이버 lprice 는 배송비 제외
상품가라 배송 필드 None — 카탈로그 '배송비포함 최저가'와 다른 이유를 docs/api.md 에 명시.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 13:59:28 +09:00
민헌andClaude Fable 5 313d882df4 feat(lps): 네이버 몰별 최저가 분해(by_mall) — 오픈마켓 가시화
네이버 오픈API 결과엔 G마켓·옥션·11번가 등이 이미 mallName 으로 들어오는데
최저가 1건만 쓰고 몰 정보를 버리고 있었다. summarize_by_mall() 로 매칭 후보를
(소스, 판매몰)별 최저가로 축약해 result.by_mall(가격 오름차순)에 노출한다.
추가 요청 0건으로 오픈마켓 몰별 최저가를 확보 — 별도 크롤러 불필요.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 13:59:15 +09:00
민헌andClaude Opus 4.8 4863425ca5 refactor(lps): job_type 명칭 정리 — 출처 기반(레거시 negowiz 제거)
레거시 용어(negowiz)와 모호한 이름(new/single)을 출처 기반으로 변경.
우선순위 1~4는 유지, 기본값 single→manual.

- new_product(1) / manual(2, 기본) / partner(3) / batch(4)
- lps_service 우선순위 맵 + protocol 기본값/설명 + docs/api.md 표 + 테스트 갱신
- 전체 54/54

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 11:33:46 +09:00
민헌andClaude Opus 4.8 8bf34ea346 docs(lps): 프로젝트 문서화 — README + docs/(아키텍처·DB·API·운영)
비개발자/기획자/개발자 누구나 이해하도록 일목요연하게 정리. 길이 분산 위해 분할.

- README.md: 3줄 요약 + 워크플로우 다이어그램 + 주요기능 + 빠른시작 + 문서 목차
- docs/architecture.md: 구성요소·처리 파이프라인·재시도/프록시/봇감지/이력 원리
- docs/database.md: 테이블 4종(job/price_history/search_negative/bot_detection) + 코드값
- docs/api.md: 엔드포인트 요청/응답 예시(curl/Postman), 상태·코드 요약
- docs/operations.md: 실행·로그·DB조회·테스트·문제해결·배포유의

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 11:27:39 +09:00
민헌andClaude Opus 4.8 5906acc48a feat(lps): 최저가 이력(price_history) — 트리거 기반 시계열 그래프
같은 상품 반복 검색 시 최저가를 스냅샷으로 적재 → 네이버/쿠팡/최종 3개 선 그래프.
배치 아님(조회된 상품만, 실제 검색 시각에 기록) — 트래픽/리소스 절약.

- price_history 테이블: product_code·triggered_at(X축)·naver/coupang/final 최저가+상세·outcome
- crud/price_history: record() + list_by_product(시각 오름차순)
- handler: AI 매칭 후 소스별 min + 전체 min 스냅샷 기록(_price_snapshot).
  found/not_found 기록, 네거티브 캐시 히트·기술실패는 미기록
- API: GET /v1/lps/products/{product_code}/history → 그래프 데이터(시각 오름차순)
- tests: 스냅샷 계산/기록·조회/핸들러 기록규칙/API → 전체 54/54

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 11:13:28 +09:00
민헌andClaude Opus 4.8 bca8032b79 feat(lps): 봇 감지 시 IP 회전+재시도 + 감지 이력 기록
쿠팡이 봇으로 감지(Akamai 차단 페이지)하면, 같은 IP로 재시도하던 것을
'브라우저 끄고 새 IP로 켜서 재시도'로 전환. 감지 패턴도 축적한다.

- DecodoProxy.rotate(): 시간창 무관 즉시 다음 포트(=새 IP). current_port 노출
- coupang/adapter: 0건+차단마커 감지 시 → 감지기록 → proxy.rotate()+강제재기동 →
  인라인 재시도(max_block_retries=1). IP당 요청수(ip_request_no) 추적, 재기동 시 리셋
- bot_detection 테이블 + crud: source/query/ip_request_no/proxy_port/elapsed_sec/marker/
  headless/html_len 기록 → 'IP당 몇 요청 만에 감지되나' 분석 가능
- worker_main: on_detect=BotDetectionLog.record 주입
- 로그: [coupang][BOT-DETECTED] ip_req#N port=... elapsed=...s marker=...
- tests: proxy rotate 즉시회전 + 감지기록 CRUD → 전체 47/47

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 11:04:07 +09:00
민헌andClaude Opus 4.8 7911ba1745 refactor(lps): 환경설정 TOML 단일화 — .env 제거, 시크릿도 config.local.toml 로 통합
설정이 .env(시크릿)+toml(설정)로 갈려 있던 것을 config.local.toml 하나로 통합.
DB 비번이 이미 toml 에 있어 분리 기준이 임의적이었고, backend(하우스 패턴)도
toml 단일이라 일관성 확보. 환경별로 바뀌는 값(DB_HOST 등)만 env override 유지.

- config_models: NaverConfig(keys 로테이션)·OpenAIConfig·DecodoConfig 추가
- server_configs: 3개 로드, load_dotenv 제거(python-dotenv 의존성도 제거)
- proxy/naver/similarity/keyword/worker_main: os.environ → config 객체 참조
- config.local.toml.example: [NaverConfig]/[OpenAIConfig]/[DecodoConfig] 섹션
- .env/.env.example 삭제, README/주석 갱신 (배포는 toml 마운트 or env override)
- tests: DecodoConfig 기반으로 갱신 → 전체 44/44

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 10:06:00 +09:00
민헌andClaude Opus 4.8 2481c79e3f feat(lps): DECODO 포트기반 sticky + 대역폭 최적화(리소스 차단)
대시보드 실측 반영 — Decodo residential 은 포트 기반 sticky(gate:10001..N,
고정 user/pass, 각 포트=sticky 세션). IP 회전 = 포트 순환.

- proxy.DecodoProxy: 시간창 기반 포트 선택(창 안 동일 IP, 창 지나면 다음 포트=새 IP).
  _UNSET sentinel 로 '미지정(env)' vs '명시적 빈값' 구분(테스트 결정성)
- coupang/adapter: 이미지/미디어/폰트/CSS 차단(block_resources) — per-GB 대역폭 대폭 절감,
  Akamai(JS)·상품파싱엔 무영향. 라이브 검증: 차단 ON 에도 Akamai 통과+파싱 정상
- .env.example: DECODO_HOST/USERNAME/PASSWORD/PORT_START/PORT_END/SESSION_MINUTES
- tests: 포트범위/시간창 안정성/활성조건 5건 → 전체 44/44

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 09:48:54 +09:00
민헌andClaude Opus 4.8 4de85d43ed feat(lps): DECODO residential 프록시 — 쿠팡 sticky 세션 + 주기적 IP 회전
datacenter IP + Akamai 대응. 매 요청 IP 변경은 쿠키-IP 불일치로 재챌린지를
유발하므로, sticky 세션(일정 시간 같은 IP) + 주기적 회전 방식 사용.

- search/proxy.DecodoProxy: username 에 -session-<시간창id>-sessionduration-<분> 부착
  → 창 안에선 같은 IP, 창이 지나면 새 IP. 자격증명은 .env(DECODO_*), 4개 다 있어야 활성
- coupang/adapter: proxy 주입 + 세션창 경과 시 브라우저 재기동(IP 회전). 무프록시면 직접 연결
- worker_main: 쿠팡에만 DecodoProxy 경유(네이버는 공식 API라 미적용)
- .env.example: DECODO_HOST/PORT/USERNAME/PASSWORD/SESSION_MINUTES 슬롯
- tests: 활성조건·sticky username·server형식·세션창 회전 4건 → 전체 43/43

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 09:40:26 +09:00
민헌andClaude Opus 4.8 d54dee4f24 feat(lps): 재시도/못찾음 완결 로직 — 재정제 루프 + not_found + 네거티브 캐시
'못 찾음'을 유한하게 종료. 두 재시도 축을 분리(기술=큐 attempts/백오프,
검색어=refine 라운드). not_found 는 정상 종료(DONE)지 dead-letter 아님.

- ai/keyword: LLM 검색어 생성(정밀/광역) — 원본 0매칭 시에만 지연 호출(비용 절약)
- handler: 한정 재정제 루프(원본→정밀→광역, max_rounds=3) + 명시적 outcome(found/not_found)
  · 0매칭+소스정상 → 다음 라운드, 0매칭+기술실패 → raise(큐 재시도)
  · 라운드 소진 → not_found + 네거티브 캐시 기록
- negative_cache: search_negative 테이블 + TTL(24h) upsert — 같은 상품 재요청 재검색 차단
- worker_main: OPENAI 있으면 judge+keyword_gen ON, neg_cache 상시
- tests: 재정제/not_found/캐시히트/기술실패/캐시CRUD 11건 → 전체 39/39
- 라이브: 없는상품 3라운드→not_found(30s), 재요청 캐시히트(0.00s)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 09:12:47 +09:00
민헌andClaude Opus 4.8 b0a86b9720 feat(lps): AI 유사도 판정 — '같은 상품' 매칭으로 액세서리 오염 해결
파이프라인의 비워둔 슬롯(이상치 뒤·top-N 앞)에 OpenAI 유사도 판정을 결합.
"스탠리 텀블러" 검색 시 빨대마개·커버 등 호환 액세서리가 최저가로 올라오던
문제를 해결한다(기계적 최저가 → 같은 상품 최저가).

- ai/similarity: SimilarityJudge(OpenAI structured output). 액세서리/부품/다른규격 불일치 판별
- pipeline/core: apply_filters + rank_result 로 분리(AI 를 그 사이에 끼움), run_price_pipeline 동작 불변
- handler: judge 주입 시 ai_match STAGE 추가(필터 후 후보만 판정 → 토큰 절약), 미주입 시 생략
- worker_main: OPENAI_API_KEY 있으면 판정 ON
- requirements: openai / tests: fake judge 필터링 검증 → 전체 32/32
- 라이브: '스탠리 퀜처 887ml' → ai_match(60→15) → 실제 텀블러 top-6(액세서리 제거)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 08:44:57 +09:00
민헌andClaude Opus 4.8 9557c1b1af feat(lps): 네이버 어댑터 + 다중 소스 병합 검색
네이버 쇼핑 오픈API 어댑터(크롤링 불필요) + 핸들러를 다중 소스로 확장.
쿠팡(브라우저)+네이버(API)를 동시 검색·병합해 교차 최저가를 뽑는다.

- search/naver/adapter: httpx + 오픈API + 키 로테이션(429/403 순환), .env 키 로드
- search/naver/transform: 순수 변환(태그/엔티티 정리, lprice). 가격비교(catalog) lprice 는
  '여러 판매자 중 최저가'라 최저가 솔루션엔 핵심 → 유지
- handler: asyncio.gather 동시 검색 + 소스별 실패 격리(일부 죽어도 결과) + 전체 실패 시 잡 실패
- worker_main: adapters={coupang, naver}
- tests: 네이버 변환 + 병합/실패격리/전체실패 4건 → 전체 31/31
- 라이브: 쿠팡30+네이버30 병합 top-N 최저가(소스 라벨 포함)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 08:38:15 +09:00
민헌andClaude Opus 4.8 7491bbecd9 chore(lps): .env 에서 Azure OpenAI 제거 — OpenAI 단일 방식
Azure OpenAI 는 사용하지 않기로 하여 슬롯 제거. AI 는 OPENAI_API_KEY 로 통일.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 17:31:16 +09:00
민헌andClaude Opus 4.8 c4b8692f3a chore(lps): 시크릿용 .env 도입 — API 키(NAVER/OpenAI/Azure) 주입 경로
키는 코드/커밋이 아닌 환경변수로 주입한다(감사: 시크릿 하드코딩 금지).
config.local.toml=비-시크릿 설정, .env=시크릿으로 분리.

- .env.example(템플릿, 커밋) + .env(로컬, 미추적)로 키 슬롯 제공
  · NAVER_CLIENT_ID/SECRET(+로테이션 _2..), OPENAI_API_KEY, AZURE_OPENAI_*
- server_configs 가 기동 시 lps/.env 를 load_dotenv 로 환경변수 주입
- requirements: python-dotenv 추가
- README: .env 셋업 단계 안내

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 17:14:34 +09:00
민헌andClaude Opus 4.8 fb72ab625f feat(lps): 코어 파이프라인 — mall 필터·IQR 이상치·top-N 최저가
검색 결과를 실제 최저가로 정제하는 파이프라인을 핸들러에 결합한다.
검색→필터→이상치→정렬→top-N. AI 유사도 판정 슬롯은 비워둠(키 대기).

- pipeline/filters: keep_only_mall·filter_out_malls·filter_by_price_band(요청 현재가 기준 targeted 컷)
- pipeline/outliers: IQR 기반 이상치 제거(z-score 대신 — 분포 가정 없음, stdlib만)
- pipeline/core: STAGE in/out 관측 로깅 + top-N 최저가(레퍼런스 pipeline_log 계승)
- handler: 검색→run_price_pipeline 결합, 요청 price 를 밴드 기준으로 사용
- tests: 정렬/IQR(극단 저·고가 제거)/밴드/mall/빈입력/STAGE/실 fixture 7건 → 전체 27/27
- 라이브 확인: 스탠리 텀블러 40건→top-5 최저가, STAGE 카운트 노출

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 17:06:15 +09:00
민헌andClaude Opus 4.8 abcb58ba05 feat(lps): 워커 루프 + LISTEN/NOTIFY — 큐 소비 파이프라인 가동
큐를 실제로 돌린다: 적재 → 워커 claim → 핸들러 실행 → 결과 저장 → DONE.
API(적재)와 워커(소비)를 분리 프로세스로(코드베이스 공유, 독립 스케일).

- worker/notify: 전용 asyncpg LISTEN 리스너. enqueue 에서 pg_notify → 유휴 워커 즉시 기상(폴링 제거)
- worker/runner: Worker(claim→처리, 처리중 heartbeat 로 lease 갱신, complete/fail) + run_reaper
- worker/handlers: job_type 별 핸들러(주입식). SEARCH=소스 어댑터 검색→정규화 결과
- worker_main: API 분리 워커 진입점(브라우저 무거워 기본 동시성 1)
- job_crud.enqueue: 삽입 시 pg_notify (중복 스킵 시엔 미발생)
- tests: drain→DONE·실패→재시도→dead·reaper 회수 후 재처리·NOTIFY 기상 4건 (전체 20/20)
- 라이브 E2E 확인: 적재→워커가 실제 쿠팡 검색(8건)→DONE

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 16:58:58 +09:00
민헌andClaude Opus 4.8 bebb6a71e6 feat(lps): 검색 API 라우터 — 요청 적재(enqueue) + 상태/큐 통계 조회
커머스 검색요청 계약을 프레임워크(protocol+service+RemoveNoneResponse)로 재구성.
실제 검색은 워커가 큐에서 꺼내 수행하도록 API 는 적재까지만 담당(비동기 분리).

- POST /v1/lps/search: 상품 리스트 → 상품별 SEARCH 잡 적재, product_code 로 활성 중복 방지, job_type→우선순위 매핑
- GET /v1/lps/jobs/{job_id}: 잡 상태/시도/결과 조회
- GET /v1/lps/queue/stats: 상태별 카운트(모니터링)
- protocol/lps_service 추가, job_crud.get() 단건조회, enums LPS_JOB_NOT_FOUND
- tests: 적재/중복/상태/미존재/통계 5건 (ASGI 클라이언트 + 실 lps_db) → 전체 16/16

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 16:49:28 +09:00
민헌andClaude Opus 4.8 da9bd7750c feat(lps): 작업 큐 엔진 — PostgreSQL 원자적 claim + lease + dead-letter
레퍼런스의 DB-큐 반면교사를 전부 뒤집는 큐 엔진을 구축한다.
 - 원자적 claim: FOR UPDATE SKIP LOCKED 서브쿼리 + 같은 UPDATE + RETURNING
   → 워커 다수여도 이중 할당 원천 불가(fetch/claim 미분리)
 - 모든 전이는 조건부 CAS(status/worker_id 가드) + RETURNING
 - 복구는 timeout 추측이 아닌 lease 만료 소유권 기반(reaper 회수)
 - 재시도 지수백오프 + max_attempts + dead-letter 를 큐에 내장(스크립트 난립 제거)
 - dedupe_key 부분 유니크로 활성 중복 차단, counts()로 관측(수동 psql 대체)

- enums: JobStatus(PENDING/RUNNING/DONE/DEAD)·JobType(SEARCH/OUTBOX)
- models: job 테이블(무FK·SMALLINT코드·TIMESTAMPTZ, claim/lease/dedupe 인덱스)
- crud/job_crud: JobQueue(enqueue/claim/complete/fail/renew_lease/reap/counts)
- tests: 동시 8워커 이중할당0·lease회수·재시도→dead·소유권가드 등 8건(실 lps_db)

부수: 포트 9400→9600 (negodata 9400 충돌 회피)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 16:37:32 +09:00
민헌andClaude Opus 4.8 e27b73c018 feat(lps): 쿠팡 검색 어댑터 — Akamai 우회(Patchright) + 정규화 파서
소스 어댑터 패턴으로 크롤링을 시작한다. 쿠팡은 Akamai Bot Manager 의
JS 행동 챌린지라 curl_cffi 단독 불가 → Patchright(스텔스 Playwright) +
실제 Chrome(channel=chrome)으로 챌린지를 통과하고 selectolax 로 파싱한다.

- contract: SearchAdapter(ABC)·NormalizedProduct·AdapterHealth·AdapterError
- coupang: adapter(브라우저 재사용, 챌린지 1회)·parser(순수)·selectors(외부화, webpack 해시 prefix 매칭)
- 공용: rate_limiter(2~8s 랜덤)·proxy(무프록시 off 인터페이스)·util.parse_price
- 가격 파싱: 단위가격 '(1개당 44,400원)'의 앞 '1' 오인 방지 — '원' 앞 숫자 앵커링
- deps: curl_cffi·selectolax·patchright(nodriver 는 py3.14 버그로 대체)
- tests: 파서 회귀(소형 fixture) — 라이브 2회 검색 + 파서 3/3 통과

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 15:59:48 +09:00
HyeongBaeYangandClaude Fable 5 b368a19f79 [feat] agent: 카드번호 기반 Q-table 마이그레이션 + 학습 리셋 스크립트
카탈로그 카드 추가/삭제/재정렬 시 action_id 가 밀려도 학습이 카드를 따라가도록,
Q-table 버전에 카탈로그 스냅샷(카드번호)을 저장하고 카드번호로 리맵한다.

- q_table_versions.action_cards JSONB 신설(카드번호 목록, index=action_id).
  models.py + init.sql(DDL·ALTER) + 로컬 DB ALTER.
- 버전 생성(get_or_create/warm_start/migrate)이 action_cards 저장.
- migrate_active_version_dim: 옛 action_cards ↔ 새 카탈로그를 카드번호로 리맵
  (중간 삽입/삭제 보정, 사라진 카드 버림, 새 카드 fresh). 레거시(스냅샷 없음)는 위치 폴백.
  version_name 은 vid 접미로 유니크.
- model_store.load: card_list 계산 → 차원변경 OR 동일차원 내용변경 시 마이그레이션,
  레거시 버전 action_cards backfill(set_version_action_cards).
- tools/reset_learning.py: learning 스키마만 비우는 리셋(카드·협상 데이터 보존),
  --company/--yes 옵션. 카탈로그 바꾸고 학습 처음부터 할 때 사용.
- 테스트: 중간 카드 삭제 시 카드번호 리맵으로 학습 보존 검증. agent 100/100.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 15:19:55 +09:00
민헌andClaude Opus 4.8 11a7be7154 feat(lps): 인터넷 최저가 검색 솔루션 프레임워크 골격 추가
backend 와 동일한 프레임워크로 lps/ 폴더를 신설한다. 구체적인 도메인
로직(크롤링/오픈API/최저가 산정)은 미정이라 골격만 구성한다.

- FastAPI 부트스트랩(web_main/router) + lifespan·CORS·gzip·로그 미들웨어 + /healthz
- TOML 설정 로더(APP_ENV) + pydantic config + DB env override
- DB 세션 매니저(논리 DB × R/W, service→람다 위임) — 엔진 lazy 라 DB 없이도 부팅
- 공통 응답 규약(gmodel) + ErrorType/DBType/DBWRType
- router→services→crud 계층 컨벤션(services/crud 는 빈 폴더로 자리만)
- 포트 9400(backend 9300·agent 9500 회피), Dockerfile/run_local_server.sh/README
- tests/test_health.py 스모크(healthz, DB 없이 통과)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 15:18:27 +09:00
HyeongBaeYang 7b7f606ace Merge branch 'feat/nego-card-update' 2026-07-08 15:09:31 +09:00
HyeongBaeYangandClaude Fable 5 f4e59a2184 [feat] agent: per-company 카탈로그 — 회사 전용 카드도 action space 포함
카탈로그 스코프를 공용(user_id NULL) 전용에서 "공용 + 그 회사 유저가 만든 카드"로 확장.
공용 먼저(action_id 0..N-1 안정) → 회사 카드 뒤(append) 정렬로 공용 카드 학습을 보호.

- get_nego_catalog(cdb, company_id): company_id 주면 공용 + company.users 소속 카드 함께 조회.
- registry._apply_db_catalog: company_id(UUID)면 회사 카드 포함(데모/비-UUID는 공용만).
- 효과: 견적이 회사 전용 카드를 선택해도 카탈로그에 있어 _selection_mask 가 매핑됨
  (기존 스코프 불일치 갭 — 회사 카드 선택이 무시되던 문제 해소).

한계: 공용 카드 추가 시 회사 카드 action_id 밀림(공용은 안정) — 카드번호 기반 매핑 후속.
agent 99/99.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 15:03:30 +09:00
HyeongBaeYangandClaude Fable 5 18020a9e07 [feat] 카드 카탈로그 DB 정본화 — config 결합 제거 + 학습 보존 자동반영
카드 카탈로그(negodata)가 Q-table action space 를 정의하는 정본이 되고, 카드 변경이
config 수정·학습 손실 없이 agent 에 자동 반영되는 고리를 완성.

- action space 정리: 카탈로그 전체(NGC-001~011, 11장) 고정, 견적별 선택은 축소가 아니라
  available_mask(_selection_mask) 로 처리 — action_id↔카드 대응을 견적마다 일정하게 유지해
  Q-table 학습 일관성 보장. 구 인덱스 방식(selected[action_id]) 폐기.
- ① 카탈로그 DB 정본화: action_mapping.type=db 면 registry 가 card.nego_cards(user_id NULL,
  number 순) 조회로 action_to_card 동적 구성(파일은 폴백). port/adapter(card_catalog_*).
  _base=type:db. → negodata 카드 추가/삭제 시 config 수정 불필요.
- ② 차원 변경 학습 보존 마이그레이션: migrate_active_version_dim — 겹치는 셀 복사
  (append/truncate 안전) + 새 카드 fresh. model_store.load 가 차원 불일치 시 호출.
- ③ reload 엔드포인트: /v1/catalog-refresh(테넌트) · /v1/catalog-refresh-all(전역, 화이트리스트).
- ④ 브랜드: company_profile_repo — 자동 온보딩 고객사(company_id UUID)는
  company.companies.name 으로 {company_name} 채움. 데모 테넌트는 파일 유지.
- 크로스서비스: negodata card_service 가 공용 nego 카드 변경 시 agent_notify 로 전역 리로드 알림
  (best-effort, is_test skip). config 에 agent_base_url.
- 하니스 episodes 400→600(action 11 수렴). 테스트 갱신·추가로 agent 98/98.

알려진 갭(후속): per-company 카탈로그 스코프(회사 카드도 action space 포함), 카탈로그 중간
삭제 시 카드번호 기반 마이그레이션.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 14:56:28 +09:00
민헌andClaude Opus 4.8 235863aea9 fix(list): 견적 유형(qt_type)에 신규협상·신규견적(3·4) 추가
프론트 QtType 이 재협상·재견적(1·2)만 정의해, 신규협상(3)/신규견적(4)
세션은 목록 '구분'이 '-' 로 깨지고 필터로도 걸러지지 않았다.
backend·negodata enum 과 동일하게 4종으로 맞춘다.

- QtType/QT_TYPE_LABEL 에 NEW_NEGO(3)·NEW_QUOTE(4) 추가 → 목록 표시 정상화.
- filterOptions '구분' 에 신규견적·신규협상 노출 → 필터 선택 가능.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 14:15:46 +09:00
민헌andClaude Opus 4.8 5519c6e73b feat(negotiation): 세션 목록 기본 그룹 정렬 + order 지정 시 전체 정렬
목록 진입 시 "지금 할 일"이 먼저 보이도록 기본 정렬을 개선하고,
사용자가 마감일로 직접 훑어볼 수 있는 전체 정렬 모드를 추가한다.

- 기본(order 미지정): 협상생성·협상중을 상단 그룹으로 마감 임박순,
  종료(완료·미참여·거부)는 하단 그룹으로 최근 마감순. 동일 마감은
  session_id 로 tie-break 하여 페이지네이션 안정화.
- order=asc/desc: 그룹 구분 없이 전체를 마감(qt_end_time) 기준으로 정렬.
- router: order 기본값을 "asc" → None(Optional) 로 변경해 "그룹 기본"과
  "명시적 전체 정렬"을 구분.
- frontend: SessionListParams.order 주석을 새 계약에 맞게 갱신(타입 무변경).
- tests: 기본=그룹 / 파라미터=전체 정렬 검증으로 분리(21 passed).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 14:12:56 +09:00
민헌andClaude Opus 4.8 c2760c804f fix(agent): 하드코딩 '재원부족' 와일드카드 제거
_pick_wildcard 가 실제 선택 와일드카드와 매핑되지 않은 채 '와일드카드를
하나라도 골랐으면' 조건만으로 wild_card_budget(재원부족)을 반환해, 선택하지
않은 재원부족 멘트가 노출되는 오작동이 있었다.

- 재원부족 분기 삭제 → 해당 구간은 일반 가격협상으로 폴백. 와일드카드는
  앵커<제시가≤앵커*1.02 구간의 1% 인하(wild_card_1pct)만 발동한다.
- wildcard_used 마킹을 1% 분기 안으로 이동 — 가격협상으로 돌아갈 때도
  마킹하면 이후 라운드의 정당한 1% 카드까지 억제되는 부작용 방지.
- test_p7_chat: 와일드카드 발동 단언을 wild_card_1pct 로 교체.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-07 18:10:45 +09:00
민헌 98df5e2608 Merge remote-tracking branch 'origin/main' into feature/backend-frontend
# Conflicts:
#	postgres-init/init-data/init.sql
2026-07-07 17:26:58 +09:00
HyeongBaeYang a2731d97f5 conflict 수정. 2026-07-07 17:18:54 +09:00
HyeongBaeYang 15f3d10eb6 와일들카드 선택 수정 . 2026-07-07 17:16:19 +09:00
minaChoi d21e7c10b0 [refactor] 공급유형 기준을 상품-협력사 매핑으로 전환 2026-07-07 17:05:07 +09:00
minaChoi 9ac8fe6363 Merge commit '8c700b1e080a29a02375664e856bc6e5b757c7c3' into feature/negodata 2026-07-07 16:19:52 +09:00
minaChoiandClaude Opus 4.8 c62b66e35b [feat] negodata: 소유권 게이팅 + 견적 낙찰 + 작성자명 표시 + 전화입력 + 카드 엑셀
- 소유권 게이팅(common/authz): 변경 액션 본인∪OWNER, 협력사 삭제 OWNER 전용
- 견적 수동 낙찰(award) + 작성자명(creatorName) 표시 + 전화번호 입력 컴포넌트 + 카드 엑셀 업로드
- supplier_type 은 이번 커밋 미변경(다음 커밋에서 코드부터 정리 예정)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 16:18:33 +09:00
minaChoiandClaude Opus 4.8 c32ee300e6 [feat] negodata: 통계 페이지(성과 분석) 추가 — 파생 집계 API + recharts 차트
- 백엔드 GET /v1/statistics/summary: 회사/내견적 스코프, 최근 6개월 파생 집계(저장 X, DDL 0)
- 지표: 총절감/절감률/낙찰률/앵커도달률/마감수/재견적라운드 + 월별추이·마감결과분해·참여율·유형별(협상/견적)·카테고리·카드빈도
- 프론트 recharts+shadcn Chart, 사이드바 통계 nav, /statistics

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 16:18:33 +09:00
369 changed files with 22005 additions and 1230 deletions

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
# docker compose 용 환경변수 템플릿 — 복사해서 사용: cp .env.example .env
# 실제 값(.env)은 커밋하지 않는다(.gitignore). 이미지에는 시크릿이 없으므로(lps 는 example
# config 로 빌드) 아래 값이 없으면 해당 기능이 꺼진 채 뜬다(주석 참고).
# ── LPS DB (미설정 시 postgres/postgres) ──
LPS_DB_USER=postgres
LPS_DB_PASSWORD=postgres
# ── LPS API 스케일 (미설정 시 1 / 40 — 단일 프로세스로도 ~1,100 RPS) ──
LPS_API_PROCESS_COUNT=1 # uvicorn 프로세스 수(=사용 코어 수). 커넥션 풀은 예산에서 자동 역산
LPS_DB_CONNECTION_BUDGET=40 # lps API 커넥션 총예산. 공유 PG=40, 전용 PG(max_conn≈100)=90
# ── LPS 워커 시크릿 ──
OPENAI_API_KEY= # 비면 AI 유사도 판정 OFF
NAVER_KEYS= # "id1:secret1,id2:secret2" — 네이버 쇼핑 오픈API 키(여러 개면 로테이션)
DECODO_HOST= # 예: gate.decodo.com — DECODO 4종이 비면 프록시 미사용(직접 연결)
DECODO_USERNAME=
DECODO_PASSWORD=
DECODO_PORT_START=0 # 예: 10001
DECODO_PORT_END=0 # 예: 10010
DECODO_COST_PER_GB=0 # 요금($/GB) — 검색 원가 계측용(예: 3.0)
+7
View File
@@ -24,3 +24,10 @@ CLAUDE.md
# OS # OS
.DS_Store .DS_Store
# 로컬 리서치 노트(크롤링 라이브러리·안티스크래핑 조사) — 추적 안 함, 로컬 참고용
/Temp.md
/new.md
# 서빙 번들 교체 시 자동 생성되는 직전본 백업 (export 도구가 만듦)
agent/artifacts/*.prev
+8 -8
View File
@@ -1,6 +1,6 @@
# Negosium Agent # Negosium Agent
범용 멀티테넌트 협상 솔루션 PoC. 여러 회사(ktcommerce·imarketkorea 등)가 **각자 데이터로 분기 학습**하는 범용 멀티테넌트 협상 솔루션 PoC. 여러 회사(imarketkorea 등)가 **각자 데이터로 분기 학습**하는
협상 카드 선택 에이전트. Q-Learning(UCB) 기반 `Chat_server`(단일 테넌트)를 참고해 신규 구축한다. 협상 카드 선택 에이전트. Q-Learning(UCB) 기반 `Chat_server`(단일 테넌트)를 참고해 신규 구축한다.
PoC 목표 두 가지: PoC 목표 두 가지:
@@ -99,10 +99,10 @@ APP_ENV=test python -m pytest # 테스트 (config.local.toml 사
**1) 의사결정 루프 데모** — 테넌트별 config 주입·상태분류·보상·DB 격리를 눈으로 확인: **1) 의사결정 루프 데모** — 테넌트별 config 주입·상태분류·보상·DB 격리를 눈으로 확인:
```bash ```bash
APP_ENV=local python -m tools.console_demo --tenant ktcommerce # 기본 3턴 시나리오 APP_ENV=local python -m tools.console_demo --tenant imarketkorea # 기본 3턴 시나리오
APP_ENV=local python -m tools.console_demo --tenant imarketkorea # 다른 테넌트(다른 카드셋·임계값) APP_ENV=local python -m tools.console_demo --tenant imarketkorea # 다른 테넌트(다른 카드셋·임계값)
APP_ENV=local python -m tools.console_demo --tenant ktcommerce --interactive # 직접 입력 APP_ENV=local python -m tools.console_demo --tenant imarketkorea --interactive # 직접 입력
APP_ENV=local python -m tools.console_demo --tenant ktcommerce --no-db # DB 없이 APP_ENV=local python -m tools.console_demo --tenant imarketkorea --no-db # DB 없이
``` ```
> ⚠️ 카드선택은 임시 placeholder 정책(실제 UCB Q-Table 은 H1/P5). 학습은 아직 일어나지 않는다. > ⚠️ 카드선택은 임시 placeholder 정책(실제 UCB Q-Table 은 H1/P5). 학습은 아직 일어나지 않는다.
@@ -113,13 +113,13 @@ curl localhost:9500/healthz # 200
curl localhost:9500/v1/health # {"status":"ok",...} curl localhost:9500/v1/health # {"status":"ok",...}
curl localhost:9500/v1/foo # 400 TENANT_HEADER_MISSING (헤더 없음) curl localhost:9500/v1/foo # 400 TENANT_HEADER_MISSING (헤더 없음)
curl localhost:9500/v1/foo -H 'X-Tenant-ID: nonexistent' # 404 TENANT_NOT_REGISTERED curl localhost:9500/v1/foo -H 'X-Tenant-ID: nonexistent' # 404 TENANT_NOT_REGISTERED
curl localhost:9500/v1/foo -H 'X-Tenant-ID: ktcommerce' # 통과(라우트 미존재라 404 Not Found) curl localhost:9500/v1/foo -H 'X-Tenant-ID: imarketkorea' # 통과(라우트 미존재라 404 Not Found)
``` ```
**2-1) 협상 한 라운드 (HTTP 프리뷰)** — `POST /v1/negotiation/step` (Swagger: http://localhost:9500/docs): **2-1) 협상 한 라운드 (HTTP 프리뷰)** — `POST /v1/negotiation/step` (Swagger: http://localhost:9500/docs):
```bash ```bash
curl -s -X POST localhost:9500/v1/negotiation/step \ curl -s -X POST localhost:9500/v1/negotiation/step \
-H 'X-Tenant-ID: ktcommerce' -H 'Content-Type: application/json' \ -H 'X-Tenant-ID: imarketkorea' -H 'Content-Type: application/json' \
-d '{"revenue_amount":20000000,"distribution_code":"A","partner_count":1, -d '{"revenue_amount":20000000,"distribution_code":"A","partner_count":1,
"acceptance_ratio":0.11,"input_price":990,"anchor_price":800,"target_price":1000, "acceptance_ratio":0.11,"input_price":990,"anchor_price":800,"target_price":1000,
"round_number":3,"outcome":"success"}' "round_number":3,"outcome":"success"}'
@@ -156,7 +156,7 @@ APP_ENV=local python -m tools.show_logs # learning.experience_logs 를 co
**가격협상 턴 UCB 카드선택·학습 + 종료보상 역전파**. 브라우저 채팅 UI. (`tests/test_p7_chat.py` 5/5) **가격협상 턴 UCB 카드선택·학습 + 종료보상 역전파**. 브라우저 채팅 UI. (`tests/test_p7_chat.py` 5/5)
- ✅ **H5 학습검증 하네스 (PoC 본체)**: 카드별 효과가 다른 시뮬 구매자(`eval_harness/`) → 정책 비교. - ✅ **H5 학습검증 하네스 (PoC 본체)**: 카드별 효과가 다른 시뮬 구매자(`eval_harness/`) → 정책 비교.
**학습형(qtable_ucb)이 random/static 대비 평균보상 우위(95%CI 분리)·좋은카드 적중 0.9 vs 0.32** → **학습형(qtable_ucb)이 random/static 대비 평균보상 우위(95%CI 분리)·좋은카드 적중 0.9 vs 0.32** →
"학습하면 성과가 오른다" 정량 입증. `python -m eval_harness.runner --config configs/exp_default.yaml --tenant ktcommerce`. (`tests/test_h5_*` 5/5) "학습하면 성과가 오른다" 정량 입증. `python -m eval_harness.runner --config configs/exp_default.yaml --tenant imarketkorea`. (`tests/test_h5_*` 5/5)
- ✅ **P7 14개 API**: chat / q-table(versions·switch·current) / experience-logs / reset-learning · - ✅ **P7 14개 API**: chat / q-table(versions·switch·current) / experience-logs / reset-learning ·
reset-all(타테넌트 무영향) / invalidate-session / **train**(오프라인 Q-learning) / verification-report / reset-all(타테넌트 무영향) / invalidate-session / **train**(오프라인 Q-learning) / verification-report /
card-update · card-search. 전부 X-Tenant-ID 격리. (`tests/test_p7_apis.py` 5/5) card-update · card-search. 전부 X-Tenant-ID 격리. (`tests/test_p7_apis.py` 5/5)
@@ -177,7 +177,7 @@ APP_ENV=local python -m tools.show_logs # learning.experience_logs 를 co
### PoC 본체 결과 (H5, 위 경제모델 기준 / target=10000·anchor=8000 시나리오) ### PoC 본체 결과 (H5, 위 경제모델 기준 / target=10000·anchor=8000 시나리오)
``` ```
python -m eval_harness.runner --config configs/exp_default.yaml --tenant ktcommerce python -m eval_harness.runner --config configs/exp_default.yaml --tenant imarketkorea
policy success settled/tgt turns mean_rwd ±95%CI good_hit policy success settled/tgt turns mean_rwd ±95%CI good_hit
random 0.988 0.904 2.02 1.1176 0.0206 0.350 random 0.988 0.904 2.02 1.1176 0.0206 0.350
static 1.000 0.923 2.56 0.9995 0.0020 0.000 static 1.000 0.923 2.56 0.9995 0.0020 0.000
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+14
View File
@@ -0,0 +1,14 @@
{
"rows": 25,
"episodes": 4,
"skipped": {
"종료행/카드턴 없음(미완결 세션)": 8
},
"min_episodes": 1,
"deployed": false,
"ope_candidate": 0.9029104414200676,
"ope_candidate_ess": 1.0,
"ope_current": 0.9029104414200676,
"ope_current_ess": 1.0,
"result": "gate_failed"
}
+1
View File
@@ -55,6 +55,7 @@ class QTableVersion(_DBTypeMixin, MAIN_BASE):
discount_factor = Column(Numeric(6, 4), nullable=False, default=0.95) discount_factor = Column(Numeric(6, 4), nullable=False, default=0.95)
epochs = Column(Integer, nullable=False, default=0) epochs = Column(Integer, nullable=False, default=0)
is_active = Column(Boolean, nullable=False, default=False) is_active = Column(Boolean, nullable=False, default=False)
action_cards = Column(JSONB, nullable=True) # 카탈로그 스냅샷: 카드번호 목록(index=action_id). 카드번호 기반 마이그레이션용.
created_at = Column(DateTime(timezone=True), server_default=text("now()")) created_at = Column(DateTime(timezone=True), server_default=text("now()"))
deleted = Column(Boolean, nullable=False, default=False) deleted = Column(Boolean, nullable=False, default=False)
+17
View File
@@ -40,3 +40,20 @@ def _apply_db_env_override(cfg: MainDBConfig):
_apply_db_env_override(main_db_config) _apply_db_env_override(main_db_config)
# LLM 키/설정 env override (DB 와 동일 패턴). 로컬은 config.local.toml [OpenAIConfig] 에 기재,
# Docker/CI/운영은 toml 없이 env 로 주입한다(docker-compose 가 OPENAI_API_KEY passthrough).
# env 미설정 시 no-op → toml 값 그대로.
def _apply_llm_env_override(cfg: OpenAIConfig):
if os.environ.get("OPENAI_API_KEY"):
cfg.api_key = os.environ["OPENAI_API_KEY"]
if os.environ.get("OPENAI_MODEL"):
cfg.model = os.environ["OPENAI_MODEL"]
if os.environ.get("OPENAI_BASE_URL"):
cfg.base_url = os.environ["OPENAI_BASE_URL"]
if os.environ.get("OPENAI_PROVIDER"):
cfg.provider = os.environ["OPENAI_PROVIDER"]
_apply_llm_env_override(openai_config)
+13
View File
@@ -4,10 +4,23 @@ import os
os.environ.setdefault("APP_ENV", "local") os.environ.setdefault("APP_ENV", "local")
import pytest
import pytest_asyncio import pytest_asyncio
from httpx import ASGITransport, AsyncClient from httpx import ASGITransport, AsyncClient
@pytest.fixture(autouse=True)
def _no_real_llm(monkeypatch):
"""실 LLM 호출 차단 — imarketkorea 가 llm.enabled=true 라 로컬에 실키가 있으면
챗 플로우가 자연화/NLU(과금·비결정 응답)를 시도한다. LLM 검증 테스트는
available 을 테스트 안에서 직접 덮어써 이 가드를 우회한다."""
from negotiation.chat.service.input_interpreter import InputInterpreter
from negotiation.chat.service.script_naturalizer import ScriptNaturalizer
monkeypatch.setattr(ScriptNaturalizer, "available", staticmethod(lambda: False))
monkeypatch.setattr(InputInterpreter, "available", staticmethod(lambda: False))
@pytest_asyncio.fixture(scope="session", autouse=True) @pytest_asyncio.fixture(scope="session", autouse=True)
async def _dispose_app_engines(): async def _dispose_app_engines():
"""테스트 세션 종료 시 앱 싱글톤 엔진 정리 ('Event loop is closed' 경고 제거).""" """테스트 세션 종료 시 앱 싱글톤 엔진 정리 ('Event loop is closed' 경고 제거)."""
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,203 @@
# 완전 자율 협상 에이전트 — 처음 대비 변경 정리
> 기준: 협상카드 + 룰 엔진 시절(처음) → 완전 자율 에이전트 v3.2 + LLM 멘트 (2026-07-10 현재)
> 롤백: `docker-compose.yml` 의 `AUTONOMY_MODE=0` 하나로 룰 엔진 즉시 복귀 (재빌드 불필요)
---
## 1. 한눈에 보기 — 무엇이 바뀌었나
| 영역 | 처음 (룰 + 카드) | 지금 (자율 에이전트) |
|---|---|---|
| **협상 판정** | 하드코딩 룰 (앵커 이하 타결 / 와일드카드 존 / 3라운드 결렬) | RL 정책이 매 턴 행동을 직접 선택 |
| **발화 선택** | DB 협상카드(NGC-001~011)를 UCB/Q-table 로 선택 | 카드 없음 — 행동 30개 중 신경망이 선택 |
| **역제안 금액** | 카드에 박힌 고정값 | 앵커~목표가 6단 사다리에서 정책이 선택 |
| **와일드카드** | 사람이 등록한 카드(WC-01~05) 발동 | 최종제안·역제시 타이밍을 정책+봉투가 자율 수행 |
| **멘트** | 고정 템플릿 | Gemini LLM 생성 + 할루시네이션 가드 (실패 시 템플릿 폴백) |
| **입력 상태** | 가격 스냅샷 9차원 | 21차원 (마감·협력사 이력·인터넷최저가·에피소드 기억 추가) |
| **학습** | Q-table 온라인 갱신 | 시뮬레이터 DQN 학습 → 프로브 게이트 → npz 번들 배포 |
---
## 2. 의사결정 — 행동 공간 30개
```
ACCEPT 수락 (협상완료, 제시가 타결)
WALK 결렬 의사 → 최종제안 1회 보장 후 종료
COUNTER 역제안: 금액 위치 6단 {-5%, 0, 25, 50, 75, 100% of (목표가-앵커가)} × 화법 4종
PRESS 압박(설득): 화법 4종
```
행동의 실체는 `Action(kind, counter_q, strategy)` — **(무엇을, 얼마에, 어떤 말투로)** 좌표 3개짜리 데이터다
(`policies/autonomy_actions.py`, DB 아님). 에이전트는 매 턴 30개 중 조합 1개를 고르고,
원화 환산(앵커 + q×스팬)과 문장(LLM)은 선택 이후의 실행 단계.
역제안 사다리 6단 (실스케일 앵커 418,966/목표 423,198 기준):
q=−0.05→418,754 / 0→418,966(앵커) / 0.25→420,024 / 0.5→421,082 / 0.75→422,140 / 1.0→423,198(목표가).
비율(q)이라 견적 스케일과 무관하게 같은 행동 공간이 재사용된다.
화법 4종은 기존 카드 전략 분류를 그대로 승계: **경쟁 압박 / 수용 공감 / 기준 고수 / 협력 파트너**.
톤 선택도 학습 결과 — 라이브에서 초반 경쟁(1)→중반 수용(2)→교착 협력(4)으로 국면별 전환 관측.
설계 출처: 화법 4종·금액 범위(앵커~목표가)는 제품 승계, 수락·결렬 포함은 완전 자율 정의의 필연,
**격자 6단만 설계 재량**(`COUNTER_GRID` 수정+재학습으로 변경 가능). 알려진 한계: 부를 수 있는
금액이 격자 6지점뿐 — 연속 금액 미세조정은 불가(필요 시 격자 확장이 현실적).
- 모델: action-as-feature DQN (ScoreNet MLP — 상태 21 + 행동특징 9 → 점수 1개)
- 서빙: **numpy 전용** (`autonomy_serving.npz`) — 컨테이너에 PyTorch 불필요
- 현재 서빙본: **v3.5** (백업 `autonomy_v35.npz` / 반려본 v3.4 / 이전 v3.2)
## 3. 입력 상태 — 9차원 → 21차원
"완전한 에이전트에는 다 들어가야 한다" 요구로 확장:
| 그룹 | 차원 | 내용 | 출처 |
|---|---|---|---|
| 기본 | 9 | 매출액·유통코드·협력사수·수락률·제시가·앵커가·목표가·라운드 등 | 기존 스냅샷 |
| 테넌트 | 5 | 보상 설정 특징 | reward config |
| **에피소드 기억** | 2 | 직전 역제안 유무·위치 | ctx `autonomy_last` |
| **마감** | 1 | 마감 잔여율 | quotations start/end_time |
| **협력사 이력** | 3 | 과거 협상 횟수·성공률·평균 타결비율 | experience_logs ⨝ sessions |
| **시장가** | 1 | 인터넷 최저가 갭 | items.internet_lowest_price |
- 소스가 없으면 중립값(0.5/0) — 학습 시뮬의 '미상' 표현과 동일
- 상대 **발화 내용 파싱은 보류** (사용자 결정 — 프론트 입력 UI 변경 필요)
## 4. 행동 봉투 — 실전 테스트에서 잡은 결함의 구조적 방지
룰과 다름: **룰은 결과를 정하고, 봉투는 행동만 금지**한다. 나머지(타이밍·속도·금액)는 전부 정책 학습.
| # | 봉투 | 막는 결함 (실제 발생 사례) | 성격 |
|---|---|---|---|
| ① | 목표가 초과 제시가는 **수락 불가** | v3.1 이 보상 구멍을 착취해 목표가+14% 매입 | 안전 (영구) |
| ② | 직전 역제안보다 **낮은 금액 재제시 금지** (단조 양보) | 423,198 → 420,024 제안 철회 사건 | 안전 (영구) |
| ③ | 역제시는 **설득 ≥2회 후 해금** (`AUTONOMY_MIN_PRESS`) | 첫 턴부터 역제시 — 옛 의미론(일반카드=설득, 와일드카드만 역제시) 복원 | 예절 (해제 후보) |
| ④ | 목표가 0.5% 이내 **마무리 국면에선 압박 금지** | 802원 차이에 "재검토 부탁" 반복하던 푼돈 흥정 | 예절 (해제 후보) |
| ⑤ | **첫 역제안은 앵커가 이하만** (q ≤ 0) | 사다리 꼭대기 근처(422,140)에서 개시해 올라갈 계단이 없던 문제 | 예절 (해제 후보) |
| ⑥ | 같은 금액 반복·결렬 의사 → **자율_최종제안 1회 보장, 금액은 목표가** | 확인 없이 결렬 / 직전 금액을 "최종"으로 반복해 승인 여지를 남긴 채 종료하던 문제 | 안전 (영구) |
| ⑦ | **결렬(walk)도 해금 전 금지** — 설득 ≥2회 전에는 설득만 가능 | 설득 0회에 walk 선택 시 최종제안 보장(⑥)과 결합해 "첫 턴 목표가 통보"가 됨 (v3.4 라이브 결함) | 예절 (해제 후보) |
- 구현: 서빙 `policy/autonomy_store.py` 후보 마스크 + 학습 `tools/train_full_autonomy.py` `available_actions` **양쪽 동일**
- 예절 봉투(③④⑤)는 실로그가 쌓이면 `AUTONOMY_MIN_PRESS=0` 등으로 해제 실험 가능
## 5. 멘트 — 템플릿 → LLM + 가드레일
**역할 분리(안전 설계):** 무엇을 말할지(금액/전략/수락/결렬)는 RL 이 결정, LLM 은 **표현만** 담당.
```
설정: agent/config/config.local.toml [OpenAIConfig]
모델: gemini-2.5-flash-lite (OpenAI 호환 base_url)
· 2.5-flash → thinking 지연으로 백엔드 10초 한도 초과 ("협상 응답 지연" 토스트 원인)
· 2.0-flash → 은퇴(404)
시간: LLM_TIMEOUT_S=6 초과 시 템플릿 폴백 (검증 최대 응답 2.9초)
끄기: AUTONOMY_LLM=0
```
**할루시네이션 가드 (하나라도 걸리면 템플릿 폴백, 협상은 계속):**
| 가드 | 내용 |
|---|---|
| 숫자 화이트리스트 | 프롬프트로 준 금액(제시가·제안가·직전제안가·양보폭) 외 숫자 = 즉시 폐기 |
| **목표가 비공개** | 압박 프롬프트에 목표가 미포함 + 화이트리스트에서도 제외 — 노출 사고 재발 방지 |
| 금지어 | 보장/물량/독점/최저가/시장가/%/계약기간/법적 등 승인 안 된 전술·커밋 |
| 문장 완결 | thinking 토큰 소진으로 잘린 문장 폐기 (max_tokens 2048) |
| 제안가 포함 | 역제안·최종제안 멘트에 제안 금액 필수 |
**추가 기능:**
- **인터넷 최저가 인용** (구 NGC-008 자율판): 수집돼 있고 제시가 > 최저가일 때만 근거 인용 허용 — 그 턴에만 '최저가' 금지어 해제, 수치는 화이트리스트 검증
- **대화 기억**: 직전 제안 거절 사실·양보폭을 멘트에 반영("직전 제안에서 5원 상향한…") + 직전 멘트와 같은 문장구조 반복 금지 — "멘트가 다 똑같다" 해결. temperature 0.9
## 6. 학습 시뮬레이터 버전 이력 — 실패 2건 포함
| 버전 | 변경 | 결과 |
|---|---|---|
| v1 | 최초 학습 | 한 방 큰 컷 + 같은 숫자 반복 → "이게 협상이야??" |
| v2 | 에피소드 기억·컷 특징·협력사 반복 짜증/이탈 | 개선되나 지형 불일치 잔존 |
| v3 | 상태 21차원 확장 | — |
| v3.1 | **지형 정합**: 앵커율 0.8~6% 샘플링 (실제 ~1% vs 시뮬 20%) | ⚠️ 보상 구멍 착취 — 목표가+14% 매입 학습 → 봉투 ① 신설 |
| **v3.2** | 컷 반발·반복 짜증·**양보 상호성**(우리가 올리면 상대도 내림)·floor ≤ 첫제시가×0.98 | ✅ **현재 서빙본** (목표가 초과 타결 0/30) |
| v3.3 | 단조·상호성 반영 재학습 | ❌ "무조건 목표가 즉시 지르기"로 퇴화 → **프로브 게이트 반려** (`full_autonomy.pt` 만 보관, 미서빙) |
| v3.4 | 봉투 ①~⑤ 정합 + **보상 수정**(목표가 초과 타결 = 결렬 취급) 재학습 | ❌ **반려** — 초기 게이트(실스케일 단일 지형) 통과 후 라이브에서 퇴화 발견: 소액 지형에서 첫 턴 walk→목표가 통보 / walk 잠금 후엔 압박 12연발·최종제안 생략·화법 단조(전부 전략3). 게이트를 2개 지형으로 확장해 재판정 → v3.2 우위 확인, v3.2 복원 (`autonomy_v34_rejected.npz` 보관) |
| **v3.5** | v3.4 + **관측성 마스크**: 마감 40% 미관측(0.5 고정)·15% 완전 미상 에피소드 — 서빙 중립값 상태를 시뮬 분포에 혼입 (v3.4 퇴화 원인 해소) | ✅ **현재 서빙본** — 게이트 78/78, 사다리 3단 사용, 협조 케이스 목표가 대비 -2,116원 타결. 게이트가 이 과정에서 **철회 실버그** 발견(아래) |
> **교훈 1 — 보상 = 유일한 스펙**: 룰을 제거하면 보상 함수의 구멍이 곧 행동이 된다 (v3.1).
> **교훈 2 — 프로브 게이트**: 재학습은 퇴화할 수 있다. 배포 전 반드시 실스케일 제시가별 행동표(`tools/probe_serving_dqn.py`)로 비교 검증 (v3.3).
> **교훈 3 — 지형 일반화**: 한 지형의 게이트 통과가 다른 지형을 보증하지 않는다 (v3.4 — 실스케일 통과, 소액 퇴화).
> **교훈 4 — 시뮬은 관측까지 닮아야 한다**: 세계뿐 아니라 '무엇을 모르는지'도 서빙과 같아야 한다. 마감·이력 미상(중립값) 상태가 시뮬에 없으면 그 상태가 분포 밖이 된다 (v3.4 원인 → v3.5 해소).
**철회 실버그 (게이트가 발견, 2026-07-10 수정):** 단조 봉투의 기준 `autonomy_last`가 '마지막 행동'이라 counter→**press**→counter 순서에서 설득이 역제안 기억을 덮어써 봉투가 뚫렸다(9,975 제안 후 9,900 재제안). 역제안 기억을 `autonomy_last_counter`로 별도 보존하도록 수정 — 시뮬(역제안만 추적)과도 일치. v3.2는 이 패턴을 쓰지 않아 드러나지 않았을 뿐 프로덕션에 실존하던 구멍.
## 7. 현재 협상 흐름 (검증 완료)
```
협력사 제시
│
▼
설득(압박) ≥2회 ── 인터넷최저가 근거 인용 가능, 목표가 절대 비공개
│
▼
역제안 해금 ── 첫 제안은 앵커가 이하로 개시 (봉투⑤)
│
▼
단조 상향 사다리 ── 후퇴 금지(봉투②), 양보폭·속도는 정책이 결정
│
▼
목표가 0.5% 이내 ── 압박 중단, 클로징만 (봉투④)
│
├─ 제시가 ≤ 목표가 → 수락 → 협상완료
├─ 같은 금액 반복 / 결렬 의사 → 자율_최종제안 1회, 금액=목표가 (봉투⑥)
│ ├─ 예 → 협상완료 └─ 아니오 → 협상실패
└─ 12턴 초과(엔지니어링 캡) → 최종제안(목표가) 1회 거쳐 종료 — 캡도 봉투⑥을 우회하지 않음
```
## 8. 운영 스위치 & 파이프라인
| 스위치 (docker-compose agent env) | 값 | 의미 |
|---|---|---|
| `AUTONOMY_MODE` | 1 | 자율 모드 (0 = 룰 엔진 복귀) |
| `DQN_SERVING` | 1 | 카드 선택 DQN (0 = UCB Q-table) |
| `AUTONOMY_LLM` | 1(기본) | LLM 멘트 (0 = 템플릿만) |
| `AUTONOMY_MIN_PRESS` | 2(기본) | 역제시 해금에 필요한 설득 횟수 |
| `LLM_TIMEOUT_S` | 6(기본) | LLM 시간 상한, 초과 시 템플릿 폴백 |
**학습→배포 파이프라인:**
```
tools/train_full_autonomy (시뮬 15k ep, 룰 베이스라인 비교)
→ tools/export_autonomy_serving (artifacts/autonomy_serving.npz, .prev 자동 백업)
→ tools/probe_serving_dqn (실스케일 행동표 — 눈으로 보는 진단)
→ tools/test_autonomy_defects (결함 회귀 게이트 — 지형 2종×시나리오 3종 + 단위·멘트가드 검사,
자동 합격/불합격. 단, v3.4 사례처럼 게이트 통과 ≠ 품질 보증:
궤적 자체도 눈으로 비교할 것)
→ docker compose build agent (npz 는 이미지에 베이크)
```
**로깅:** 자율 행동도 experience_logs 에 기록 (card_id = `AUT|종류|위치|전략`, 진행 row + 종결 row). 카드 재학습(`retrain_from_logs`)은 AUT 세션 자동 제외.
## 9. 변경 파일 지도
| 파일 | 역할 |
|---|---|
| `negotiation/policy/autonomy_store.py` | **신규** — 자율 정책 numpy 서빙 + 봉투 ①~⑤ 마스크 |
| `negotiation/policies/autonomy_actions.py` | **신규** — 행동 30개·특징 인코딩 (학습/서빙 공유) |
| `negotiation/chat/service/ment_generator.py` | **신규** — LLM 멘트 생성 + 가드레일 |
| `negotiation/chat/service/chat_engine.py` | 자율 스텝(자율_역제안/최종제안/압박_1~4) + `_autonomy_next` 봉투⑥ |
| `services/chat_service.py` | decider 주입·행동 로깅·대화기억 ctx 관리 |
| `negotiation/chat/infra/repository/nego_context_crud.py` | 인터넷최저가·견적기간·협력사이력 조회 |
| `negotiation/chat/service/negotiation_context_loader.py` | 확장 컨텍스트 로드 (company_id) |
| `tools/train_full_autonomy.py` | **신규** — 시뮬레이터(현실화 협력사 모델) + DQN 학습 |
| `tools/export_autonomy_serving.py` / `probe_serving_dqn.py` | **신규** — 번들 내보내기 / 프로브 게이트 |
| `tools/test_autonomy_defects.py` | **신규** — 결함 회귀 게이트: 실전에서 발견된 결함 41항목을 시나리오·단위·멘트가드 검사로 자동 재생 (서빙 실물 코드 구동, DB/LLM 불필요) |
| `config/config.local.toml` | Gemini 접속 정보 (gitignore, 이미지에 베이크) |
| `docker-compose.yml` | `AUTONOMY_MODE` / `DQN_SERVING` 플래그 |
## 10. 남은 일
- [x] 결함 회귀 게이트 구축 — `test_autonomy_defects.py` 41항목, v3.2 전항목 통과 확인 (2026-07-10)
- [x] 보상 수정 — 목표가 초과 타결은 학습 보상에서 결렬 취급 (v3.1 구멍을 유인 수준에서 차단, 봉투 ①과 이중 방어)
- [ ] ⚠️ **Gemini API 키 재발급** — 채팅에 노출된 키, 테스트 종료 후 반드시 교체 (config.local.toml + 이미지 리빌드)
- [x] 봉투 정합 재학습 — v3.4 반려(소액 지형 퇴화) → 원인 규명(관측성 불일치) → **v3.5 관측성 마스크로 해소, 배포 완료** (2026-07-10)
- [x] 철회 실버그 수정 — counter→press→counter 에서 단조 봉투 뚫림 → `autonomy_last_counter` 별도 보존
- [x] 턴캡 최종제안 보장 — 캡 종료도 "끝내기 전 한 번 더"를 거침
- [ ] 상대 발화 LLM 파싱 (보류 중 — 프론트 입력 UI 변경 필요)
- [ ] 실로그 축적 후: 예절 봉투(③④⑤) 해제 실험 → LLM 협력사 셀프플레이 (집컴 GPU 단계)
- [ ] (소소) negodata 프론트 "목표 마진율 1000%" 표시 버그 후보
+30
View File
@@ -0,0 +1,30 @@
ID,??MD,?????,?????,??? ???,????,???,???,????,????,???,???,1???,1? ?? ???,1? ????,????,2???,2? ?? ???,2? ????,????,3???,3? ?? ???,3? ????,????,4???,,,,,
1,,???,,,AT2025042400050,?????,"163,600",??,None (??),"8,180","8,099",,,,,,,,,,,,,,,,,,
2,,???,,,AT2025042200057,????,"350,000",??,Single (??),"35,000","33,600",35000,0,?? ?? ?? ??,o,34900,0.00286533,??? ?? ?? ??,o,33700,0.038575668,??? ?? ?? ??,x,33600,,,,,
3,,???,,,AT2025042300003,TV???,"6,790,000",??,Multiple (??),"48,500","46,560",50000,0,?? ?? ?? ??,x,46560,,?? ??,,,,,,,,,,,
4,,???,,,AT2025042200041,?????,"18,700,000",??,Multiple (??),"1,804,550","1,678,232",2200000,0,?? ?? ?? ??,x,2000000,0.1,?? ?? ?? ??,,1700000,0.294117647,??? ?? ?? ??,,1700000,,,,,
5,,???,,,AT2025041600034,???,"760,320",??,Multiple (??),"73,304","70,372",70000,,?? ??,,,,,,,,,,,,,,,
6,,???,,,AT2025042400010,????? ??,"780,000",??,Multiple (??),"75,642"," 72,617 ",,,,,,,,,,,,,,,,,,
7,,???,,,AT2025042400030,???,"313,000",??,Multiple (??),"31,300","29,735",50000,0,?? ?? ?? ??,,40000,0.25,?? ?? ?? ??,,30500,0.639344262,??? ?? ?? ??,,30500,,,,,
8,,???,,,AT2025042300096,?????,"706,800",??,None (??),"68,162","65,436",115800,0,?? ?? ?? ??,,70000,0.654285714,?? ?? ?? ??,,69000,0.67826087,??? ?? ?? ??,,65400,,,,,
9,,???,,,AT2025042300082,??????,"12,000",??,Multiple (??),"1,200","1,188",,,,,,,,,,,,,,,,,,
2.1,,???,ID 2 ???? ??(??>??),,AT2025042200057,????,"350,000",??,Single (??),"35,000"," 33,250 ",,,,,,,,,,,,,,,,,,
6.1,,???,ID 6 ???? ??(??>??),,AT2025042400010,????? ??,780000,??,Multiple (??),"75,642"," 71,860 ",,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
,,,,1,AT2025042400050,SOOT777,?????,,,,,,,,,,,,,,,,,,,,,,
,,,,2,AT2025042200057,JAJE89,????,,,,,,,,,,,,,,,,,,,,,,
,,,,3,AT2025042300003,VOV2,TV???,,,,,,,,,,,,,,,,,,,,,,
,,,,4,AT2025042200041,HEMEELY,?????,,,,,,,,,,,,,,,,,,,,,,
,,,,5,AT2025041600034,KMS5939,???,,,,,,,,,,,,,,,,,,,,,,
,,,,6,AT2025042400010,YTS111,????? ??,,,,,,,,,,,,,,,,,,,,,,
,,,,7,AT2025042400030,SJUN98,???,,,,,,,,,,,,,,,,,,,,,,
,,,,8,AT2025042300096,DREAMBIZ,?????,,,,,,,,,,,,,,,,,,,,,,
,,,,9,AT2025042300082,BWTCO40,??????,,,,,,,,,,,,,,,,,,,,,,
,,,,2.1,AT2025042200057,JAJE89,????,,,,,,,,,,,,,,,,,,,,,,
,,,,6.1,AT2025042400010,YTS111,????? ??,,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
1 ID ??MD ????? ????? ??? ??? ???? ??? ??? ???? ???? ??? ??? 1??? 1? ?? ??? 1? ???? ???? 2??? 2? ?? ??? 2? ???? ???? 3??? 3? ?? ??? 3? ???? ???? 4???
2 1 ??? AT2025042400050 ????? 163,600 ?? None (??) 8,180 8,099
3 2 ??? AT2025042200057 ???? 350,000 ?? Single (??) 35,000 33,600 35000 0 ?? ?? ?? ?? o 34900 0.00286533 ??? ?? ?? ?? o 33700 0.038575668 ??? ?? ?? ?? x 33600
4 3 ??? AT2025042300003 TV??? 6,790,000 ?? Multiple (??) 48,500 46,560 50000 0 ?? ?? ?? ?? x 46560 ?? ??
5 4 ??? AT2025042200041 ????? 18,700,000 ?? Multiple (??) 1,804,550 1,678,232 2200000 0 ?? ?? ?? ?? x 2000000 0.1 ?? ?? ?? ?? 1700000 0.294117647 ??? ?? ?? ?? 1700000
6 5 ??? AT2025041600034 ??? 760,320 ?? Multiple (??) 73,304 70,372 70000 ?? ??
7 6 ??? AT2025042400010 ????? ?? 780,000 ?? Multiple (??) 75,642 72,617
8 7 ??? AT2025042400030 ??? 313,000 ?? Multiple (??) 31,300 29,735 50000 0 ?? ?? ?? ?? 40000 0.25 ?? ?? ?? ?? 30500 0.639344262 ??? ?? ?? ?? 30500
9 8 ??? AT2025042300096 ????? 706,800 ?? None (??) 68,162 65,436 115800 0 ?? ?? ?? ?? 70000 0.654285714 ?? ?? ?? ?? 69000 0.67826087 ??? ?? ?? ?? 65400
10 9 ??? AT2025042300082 ?????? 12,000 ?? Multiple (??) 1,200 1,188
11 2.1 ??? ID 2 ???? ??(??>??) AT2025042200057 ???? 350,000 ?? Single (??) 35,000 33,250
12 6.1 ??? ID 6 ???? ??(??>??) AT2025042400010 ????? ?? 780000 ?? Multiple (??) 75,642 71,860
13
14
15
16
17 1 AT2025042400050 SOOT777 ?????
18 2 AT2025042200057 JAJE89 ????
19 3 AT2025042300003 VOV2 TV???
20 4 AT2025042200041 HEMEELY ?????
21 5 AT2025041600034 KMS5939 ???
22 6 AT2025042400010 YTS111 ????? ??
23 7 AT2025042400030 SJUN98 ???
24 8 AT2025042300096 DREAMBIZ ?????
25 9 AT2025042300082 BWTCO40 ??????
26 2.1 AT2025042200057 JAJE89 ????
27 6.1 AT2025042400010 YTS111 ????? ??
28
29
30
+2 -2
View File
@@ -1,5 +1,5 @@
# 알고리즘 비교 실험 기본 설정 (H5). E2E: python -m eval_harness.runner --config configs/exp_default.yaml --tenant ktcommerce # 알고리즘 비교 실험 기본 설정 (H5). E2E: python -m eval_harness.runner --config configs/exp_default.yaml --tenant imarketkorea
episodes: 400 # 정책당 협상 에피소드 수 episodes: 600 # 정책당 협상 에피소드 수 (action 11장 탐색 수렴 위해 상향)
seed: 42 # 재현용 (구매자 randomness 페어드) seed: 42 # 재현용 (구매자 randomness 페어드)
max_turns: 5 # 협상 라운드 상한 max_turns: 5 # 협상 라운드 상한
n_good_cards: 3 # 시뮬 구매자: 효과 좋은 카드 수 n_good_cards: 3 # 시뮬 구매자: 효과 좋은 카드 수
+104
View File
@@ -0,0 +1,104 @@
"""FeatureBuyer — 카드 '내용(전략)'과 협력사 '프로필'에 반응하는 시뮬 협력사 (Phase 2·3).
효과를 2축으로 분리한다(성향 조건화가 의미를 가지려면 트레이드오프가 필요):
- 양보력(concession power): 이 카드가 가격을 얼마나 끌어내리는가
- 수락력(accept power) : 이 카드가 합의(수락) 확률을 얼마나 높이는가
전략별 기본 프로필(트레이드오프):
경쟁(1): 양보력↑↑ 수락력↓ — 세게 깎지만 결렬 위험
수용(2): 양보력↓ 수락력↑
고수(3): 양보력·수락력 중간
협력(4): 양보력↓ 수락력↑↑ — 잘 성사되지만 덜 깎임
여기에 협력사 세그먼트 적합도(AFFINITY)가 곱해진다: 전략이 그 협력사에 안 맞으면 둘 다 죽는다.
소형·경쟁多 → 경쟁압박이 잘 먹힘 / 대형·단독 → 협력이 잘 먹힘(압박 역효과)
→ '가격 중시' 고객사는 경쟁 카드(많이 깎음, 결렬 감수), '성사 중시' 고객사는 협력 카드가 정답이
되는 구조. 에이전트는 카드 특징 + 협력사 특징 + 고객사 성향으로 이를 학습해야 한다.
"""
from dataclasses import dataclass
from typing import Dict, Tuple
import numpy as np
from eval_harness.buyer import BuyerResponse, Scenario
# strategy_type: 1=경쟁, 2=수용, 3=고수, 4=협력 (card.nego_cards)
# 전략별 (양보력, 수락력) 기본 프로필 — 트레이드오프의 원천
STRATEGY_PROFILE: Dict[int, Tuple[float, float]] = {
1: (0.90, 0.25), # 경쟁: 세게 깎지만 성사 어려움
2: (0.35, 0.70), # 수용
3: (0.55, 0.50), # 고수: 중간
4: (0.30, 0.90), # 협력: 잘 성사되지만 덜 깎임
}
# 세그먼트별 전략 적합도 m ∈ [0,1] — 전략이 그 협력사에 얼마나 '먹히는가'
AFFINITY: Dict[Tuple[str, str], Dict[int, float]] = {
("small", "multi"): {1: 0.90, 2: 0.45, 3: 0.60, 4: 0.40}, # 소형·경쟁多 → 경쟁압박
("small", "single"): {1: 0.35, 2: 0.60, 3: 0.80, 4: 0.55}, # 소형·단독 → 고수/논리
("big", "multi"): {1: 0.65, 2: 0.50, 3: 0.70, 4: 0.60},
("big", "single"): {1: 0.20, 2: 0.70, 3: 0.50, 4: 0.90}, # 대형·단독 → 협력 (압박 역효과)
}
REVENUE_BIG = 50_000_000 # state config 'high' 경계와 정합
@dataclass
class SupplierProfile:
"""협력사 프로필 — 에피소드마다 달라지는 협상 상대. snapshot 필드와 정합."""
revenue_amount: float
partner_count: int # 이 품목의 대안 협력사 수 (BATNA. 1:1 채팅이어도 다양)
distribution_code: str
@property
def segment(self) -> Tuple[str, str]:
size = "big" if self.revenue_amount > REVENUE_BIG else "small"
comp = "multi" if self.partner_count >= 2 else "single"
return (size, comp)
def sample_supplier(rng: np.random.Generator) -> SupplierProfile:
"""무작위 협력사 생성 (학습 데이터 다양성)."""
return SupplierProfile(
revenue_amount=float(rng.choice([5_000_000, 20_000_000, 80_000_000, 200_000_000])),
partner_count=int(rng.choice([1, 1, 2, 3])), # 단독 비중 높게
distribution_code=str(rng.choice(["A", "B", "C"])),
)
class FeatureBuyer:
"""전략 프로필 x 세그먼트 적합도 기반 협력사 모델. (양보력, 수락력) 2축."""
def __init__(self, supplier: SupplierProfile, card_strategy: Dict[str, int], seed: int = 0,
accept_base: float = 0.08, max_turns: int = 5, jitter: float = 0.05):
self.supplier = supplier
self.card_strategy = card_strategy # {card_number: strategy_type}
self.rng = np.random.default_rng(seed)
self.accept_base = accept_base
self.max_turns = max_turns
self.jitter = jitter
# 숨은 하한가(reservation): 앵커의 94~110%. 앵커보다 높으면(약 60%) 가격만으로는
# 타결 불가 → 수락을 받아내야 함 → 수락력 낮은(경쟁) 카드에 진짜 결렬 위험이 생긴다.
self.floor_ratio = float(self.rng.uniform(0.94, 1.10))
def powers(self, card_number: str) -> Tuple[float, float]:
"""숨은 (양보력, 수락력). 전략 프로필 × 세그먼트 적합도 + 카드별 결정론적 지터."""
strat = self.card_strategy.get(card_number, 3)
conc_base, acc_base = STRATEGY_PROFILE.get(strat, (0.5, 0.5))
m = AFFINITY[self.supplier.segment].get(strat, 0.5)
scale = 0.35 + 0.85 * m # 적합도: 안 맞으면 둘 다 죽음 (0.35~1.2)
j = (hash(card_number) % 1000 / 1000.0 - 0.5) * 2 * self.jitter
c_pow = float(np.clip(conc_base * scale + j, 0.02, 0.98))
a_pow = float(np.clip(acc_base * scale + j, 0.02, 0.98))
return c_pow, a_pow
def respond(self, card_number: str, scenario: Scenario, turn: int, current_price: float) -> BuyerResponse:
c_pow, a_pow = self.powers(card_number)
floor = scenario.anchor_price * self.floor_ratio # 숨은 하한가 (앵커 이하 보장 없음)
concession = (current_price - floor) * (0.10 + 0.55 * c_pow)
new_price = max(floor, current_price - concession)
p_accept = min(0.97, self.accept_base + 0.80 * a_pow + 0.05 * (turn - 1))
accept = bool(self.rng.random() < p_accept)
walked = (not accept) and (turn >= self.max_turns)
return BuyerResponse(accept=accept, new_price=new_price, walked=walked)
+2 -2
View File
@@ -1,6 +1,6 @@
"""eval_harness 러너 — 정책 비교 + 학습곡선 (H5, PoC 본체). """eval_harness 러너 — 정책 비교 + 학습곡선 (H5, PoC 본체).
E2E: python -m eval_harness.runner --config configs/exp_default.yaml --tenant ktcommerce E2E: python -m eval_harness.runner --config configs/exp_default.yaml --tenant imarketkorea
판정: 학습형(qtable_ucb)이 random/static 대비 평균보상·성공률 우상향이면 "학습 루프 유효". 판정: 학습형(qtable_ucb)이 random/static 대비 평균보상·성공률 우상향이면 "학습 루프 유효".
구매자는 카드별 효과가 다른 시뮬(HeuristicBuyer) — 학습 정책만 좋은 카드를 알아내 성과가 오른다. 구매자는 카드별 효과가 다른 시뮬(HeuristicBuyer) — 학습 정책만 좋은 카드를 알아내 성과가 오른다.
@@ -143,7 +143,7 @@ def _print(report: dict):
def main(): def main():
ap = argparse.ArgumentParser(description="협상 정책 비교 하네스 (H5)") ap = argparse.ArgumentParser(description="협상 정책 비교 하네스 (H5)")
ap.add_argument("--config", default="configs/exp_default.yaml") ap.add_argument("--config", default="configs/exp_default.yaml")
ap.add_argument("--tenant", default="ktcommerce") ap.add_argument("--tenant", default="imarketkorea")
ap.add_argument("--save", action="store_true", help="reports/ 에 JSON 저장") ap.add_argument("--save", action="store_true", help="reports/ 에 JSON 저장")
args = ap.parse_args() args = ap.parse_args()
@@ -0,0 +1,52 @@
"""CardCatalogDbRepository — card.nego_cards 에서 카탈로그(action space) read-only 조회.
정렬: number 오름차순(zero-padded NGC-001..NGC-011 이라 문자열 정렬로 안정적) → action_id.
스코프: o2o 기본 제공 카드(user_id IS NULL). 회사 전용 카탈로그는 후속(스코프 확장).
스키마 소유권: card 스키마는 backend/negodata 소유 — read-only. 경량 table()/column() 구성.
"""
from typing import List, Optional, Tuple
from sqlalchemy import asc, case, column, or_, select, table
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.db_session_manager import DB_SESSION_MNG
from common.enums import ErrorType
from common.logger import LOG
from negotiation.cards.ports.card_catalog_port import ICardCatalogRepository
_NEGO_CARDS = table(
"nego_cards",
column("number"), column("user_id"), column("deleted"),
schema="card",
)
_USERS = table("users", column("user_id"), column("company_id"), column("deleted"), schema="company")
class CardCatalogDbRepository(ICardCatalogRepository):
async def get_nego_catalog(self, cdb: AsyncSession, company_id: Optional[object] = None) -> Tuple[ErrorType, List[str]]:
try:
# 스코프: 공용(user_id NULL) + (company_id 주면) 그 회사 유저가 만든 카드.
scope = _NEGO_CARDS.c.user_id.is_(None)
if company_id is not None:
company_users = (
select(_USERS.c.user_id)
.where(_USERS.c.company_id == company_id, _USERS.c.deleted == False) # noqa: E712
.scalar_subquery()
)
scope = or_(scope, _NEGO_CARDS.c.user_id.in_(company_users))
# 정렬: 공용(0) 먼저 → 회사(1) 뒤, 각 그룹 내 number 오름차순.
# 공용 카드의 action_id(0..N-1) 안정성 보장 — 회사 카드 추가는 뒤에 append.
shared_first = case((_NEGO_CARDS.c.user_id.is_(None), 0), else_=1)
query = (
select(_NEGO_CARDS.c.number)
.where(scope, _NEGO_CARDS.c.deleted == False) # noqa: E712
.order_by(shared_first, asc(_NEGO_CARDS.c.number))
)
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_nego_catalog failed.", raise_error=False)
if err_type != ErrorType.SUCCESS or not rows:
return err_type, []
return ErrorType.SUCCESS, [str(r) for r in rows if r]
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, []
@@ -20,6 +20,13 @@ from negotiation.cards.ports.card_script_port import ICardScriptRepository
_NEGO_CARDS = table( _NEGO_CARDS = table(
"nego_cards", "nego_cards",
column("number"), column("script"), column("tone"), column("strategy_type"),
column("created_at"), column("deleted"),
schema="card",
)
_WILD_CARDS = table(
"wild_cards",
column("number"), column("script"), column("created_at"), column("deleted"), column("number"), column("script"), column("created_at"), column("deleted"),
schema="card", schema="card",
) )
@@ -27,17 +34,40 @@ _NEGO_CARDS = table(
class CardScriptDbRepository(ICardScriptRepository): class CardScriptDbRepository(ICardScriptRepository):
async def get_script_by_number(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, Optional[str]]: async def get_script_by_number(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, Optional[str]]:
err, card = await self.get_card_by_number(cdb, number)
return err, (card[0] if card else None)
async def get_wild_card_by_number(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, Optional[str]]:
"""card.wild_cards 멘트 조회 (WC-01~05 선택형 와일드카드/종결 전술 발동용)."""
try: try:
query = ( query = (
select(_NEGO_CARDS.c.script) select(_WILD_CARDS.c.script)
.where(_WILD_CARDS.c.number == number, _WILD_CARDS.c.deleted == False) # noqa: E712
.order_by(desc(_WILD_CARDS.c.created_at))
.limit(1)
)
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_wild_card_script failed.", raise_error=False)
if err_type != ErrorType.SUCCESS or not rows or not rows[0]:
return err_type, None
return ErrorType.SUCCESS, str(rows[0]) if not isinstance(rows[0], tuple) else str(rows[0][0])
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, None
async def get_card_by_number(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, Optional[tuple]]:
try:
query = (
select(_NEGO_CARDS.c.script, _NEGO_CARDS.c.tone, _NEGO_CARDS.c.strategy_type)
.where(_NEGO_CARDS.c.number == number, _NEGO_CARDS.c.deleted == False) # noqa: E712 .where(_NEGO_CARDS.c.number == number, _NEGO_CARDS.c.deleted == False) # noqa: E712
.order_by(desc(_NEGO_CARDS.c.created_at)) .order_by(desc(_NEGO_CARDS.c.created_at))
.limit(1) .limit(1)
) )
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_card_script failed.", raise_error=False) err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_card_script failed.", raise_error=False)
if err_type != ErrorType.SUCCESS or not rows or not rows[0]: if err_type != ErrorType.SUCCESS or not rows or not rows[0] or not rows[0][0]:
return err_type, None return err_type, None
return ErrorType.SUCCESS, str(rows[0]) script, tone, strategy = rows[0]
return ErrorType.SUCCESS, (str(script), int(tone) if tone is not None else None,
int(strategy) if strategy is not None else None)
except Exception as ex: except Exception as ex:
LOG.e_no_callstack(ex) LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, None return ErrorType.DB_RUN_FAILED, None
+120
View File
@@ -0,0 +1,120 @@
"""협상카드 전술 레지스트리 — "멘트 카드 → 전술 카드" 승격 (가격 행동 실행 계층).
카드 멘트에 이미 설계된 카운터 가격 제시({target_price}·{middle_price} 등)를 시스템 상태로
실행한다: 카드가 카운터가를 제시하면 pending_counter_price 로 적재되고, 협력사가 수락하면
그 가격으로 즉시 타결된다(기존 wild_card_1pct 의 offer_1pct 패턴을 일반화).
원칙:
- 구매자(갑) 대리이므로 카운터는 항상 min(counter, target_price) 클램프 — 목표가 초과 제시 금지.
- 협력사 제시가가 이미 카운터 이하면 카운터가 무의미 → None(HOLD 강등, 순수 설득).
- 미등록 카드번호(테넌트 데모 NGC-B*, 회사 커스텀 COMP-* 등)는 HOLD 폴백 → 기존 동작 그대로.
전술 정본은 이 코드 레지스트리다(v1). negodata 카드 편집은 멘트만 담당하고, 전술을 negodata
에서 편집할 필요가 생기면 v2 에서 card.nego_cards 컬럼로 승격해 "DB 우선, 코드 폴백"으로 바꾼다.
"""
from dataclasses import dataclass
from enum import Enum
from typing import Any, Dict, Optional
class PriceAction(str, Enum):
HOLD = "hold" # 카운터 없음 — 재제안 요구(순수 설득, 기존 동작)
COUNTER_TARGET = "counter_target" # 목표가 제시
COUNTER_ANCHOR = "counter_anchor" # 앵커가 제시 (예산 상한 프레이밍)
COUNTER_TARGET_MID = "counter_target_mid" # (anchor+target)/2 — 시드 {target_mid_price}
COUNTER_MID = "counter_mid" # (갑 직전 포지션+협력사 제시가)/2 — 시드 {middle_price}
ONE_PCT = "one_pct" # 제시가 1% 인하 (기존 offer_1pct)
@dataclass(frozen=True)
class TacticSpec:
"""카드 1장의 전술 명세.
min_round: 발동 가능 최소 라운드(협력사 가격 입력 횟수 기준).
max_price_ratio: input_price ≤ anchor×ratio 일 때만 발동 (None=무제한).
closing: 종결 국면(라운드 만료·카드 소진) 우선 전술.
"""
price_action: PriceAction = PriceAction.HOLD
min_round: int = 1
max_price_ratio: Optional[float] = None
closing: bool = False
_DEFAULT = TacticSpec() # HOLD — 미등록 카드 폴백
# 카드번호 → 전술. 시드(init-data.sql) 멘트의 가격 변수와 1:1 정합.
# NGC-001~006: 순수 설득(경쟁 압박/승인 핑계/관계/명분/공정성/TCO) — 가격 변수 없음.
# NGC-008: {internet_lowest_price} 인용이나 데이터 소스 미보유 → v1 HOLD (소스 확보 시 승격).
_TACTICS: Dict[str, TacticSpec] = {
"NGC-007": TacticSpec(PriceAction.COUNTER_ANCHOR), # 예산 상한 안내
"NGC-009": TacticSpec(PriceAction.COUNTER_TARGET), # 조건부 가격 조정
"NGC-010": TacticSpec(PriceAction.COUNTER_TARGET), # 향후 거래 연계
"NGC-011": TacticSpec(PriceAction.COUNTER_TARGET), # 양보 가치 강조
"WC-01": TacticSpec(PriceAction.COUNTER_TARGET, min_round=1), # 목표가 선제안
"WC-02": TacticSpec(PriceAction.COUNTER_TARGET_MID), # 역제안가 제시
"WC-03": TacticSpec(PriceAction.COUNTER_TARGET, closing=True), # 최종 통보(최후통첩)
"WC-04": TacticSpec(PriceAction.COUNTER_TARGET, min_round=2), # 단계적 인하 제안
"WC-05": TacticSpec(PriceAction.COUNTER_MID, closing=True), # 중간값 절충(종결)
}
def tactic_for(card_number: Optional[str]) -> TacticSpec:
"""카드번호의 전술. 미등록/None 은 HOLD(기존 동작)."""
return _TACTICS.get(str(card_number), _DEFAULT) if card_number else _DEFAULT
def tactic_available(spec: TacticSpec, context: Dict[str, Any]) -> bool:
"""발동 조건 평가 — action space 마스킹용. HOLD(설득)는 언제나 가능."""
if spec.price_action is PriceAction.HOLD:
return True
rnd = int(context.get("round") or 0)
if rnd < spec.min_round:
return False
if spec.max_price_ratio is not None:
price = float(context.get("input_price") or 0)
anchor = float(context.get("anchor_price") or 0)
if anchor > 0 and price > anchor * spec.max_price_ratio:
return False
return True
def compute_counter(spec: TacticSpec, context: Dict[str, Any]) -> Optional[int]:
"""전술의 카운터 제시가 계산 (결정론).
- 항상 min(counter, target) 클램프 — 구매자는 목표가 초과로 제시하지 않는다.
- counter ≥ 협력사 제시가(input_price)면 카운터가 무의미(이미 더 싸게 제시받음) → None.
- 필요한 컨텍스트(target/anchor/제시가)가 없으면 None → 호출부가 HOLD 로 강등.
"""
action = spec.price_action
if action is PriceAction.HOLD:
return None
target = float(context.get("target_price") or 0)
anchor = float(context.get("anchor_price") or 0)
price = float(context.get("input_price") or 0)
if target <= 0 or price <= 0:
return None
if action is PriceAction.COUNTER_TARGET:
counter = target
elif action is PriceAction.COUNTER_ANCHOR:
counter = anchor
elif action is PriceAction.COUNTER_TARGET_MID:
counter = (anchor + target) / 2 if anchor > 0 else target
elif action is PriceAction.COUNTER_MID:
# 갑의 직전 포지션(직전 카운터). 첫 카운터 전에는 앵커가 갑의 포지션이다.
prev_customer = float(context.get("prev_customer_price") or anchor or target)
counter = (prev_customer + price) / 2
elif action is PriceAction.ONE_PCT:
counter = price * 0.99
else:
return None
if counter <= 0:
return None
counter = min(counter, target) # 목표가 초과 제시 금지 (가드레일)
counter_i = int(round(counter))
if counter_i >= price:
return None # 제시가가 이미 카운터 이하 → 카운터 무의미
return counter_i
@@ -0,0 +1,28 @@
"""ICardCatalogRepository — 협상카드 카탈로그(action space 정의) DB 조회 포트.
카탈로그 = Q-table 의 action 축을 정의하는 "카드 목록". negodata 가 관리하는 card.nego_cards 가
정본이며, agent 는 이를 조회해 action_id(0..N-1) ↔ 카드번호 매핑을 구성한다. tenant.yaml 의
action_to_card 하드코딩을 대체한다(config 결합 제거 — 카탈로그는 DB, config 는 튜닝만).
주의: 카탈로그 크기 = Q-table action 차원. 카드 수가 바뀌면 재차원화(버전 이벤트)가 필요하므로
카탈로그 변경은 드문 이벤트여야 한다.
"""
from abc import ABC, abstractmethod
from typing import List, Optional, Tuple
from sqlalchemy.ext.asyncio import AsyncSession
from common.enums import ErrorType
class ICardCatalogRepository(ABC):
@abstractmethod
async def get_nego_catalog(self, cdb: AsyncSession, company_id: Optional[object] = None) -> Tuple[ErrorType, List[str]]:
"""action space 를 정의하는 일반 협상카드 번호 목록(정렬됨). action_id = 리스트 인덱스.
company_id(UUID) 주면 공용 카드(user_id NULL) + 그 회사 카드(user_id ∈ 회사 유저)를 함께,
**공용 먼저 → 회사 카드 뒤** 순으로 반환(공용 카드 action_id 안정성 보장). None 이면 공용만.
비었으면([]) 호출부가 파일 action_to_card 로 폴백한다.
"""
...
@@ -21,3 +21,18 @@ class ICardScriptRepository(ABC):
async def get_script_by_number(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, Optional[str]]: async def get_script_by_number(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, Optional[str]]:
"""카드코드(card.nego_cards.number)로 멘트(script 평문/마커)를 조회. 없으면 None.""" """카드코드(card.nego_cards.number)로 멘트(script 평문/마커)를 조회. 없으면 None."""
... ...
async def get_card_by_number(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, Optional[tuple]]:
"""멘트 + 메타 (script, tone, strategy_type) 조회 — LLM 표현층의 톤/전략 지시용.
기본 구현은 script 만 조회하고 메타는 None (파일 소스·구형 더블 호환).
"""
err, script = await self.get_script_by_number(cdb, number)
return err, ((script, None, None) if script else None)
async def get_wild_card_by_number(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, Optional[str]]:
"""와일드카드(card.wild_cards.number) 멘트 조회 — 선택형 WC/종결 전술 발동용.
기본 구현은 미보유(None) — DB 어댑터만 실조회한다(더블 호환).
"""
return ErrorType.SUCCESS, None
@@ -26,9 +26,41 @@ _SESSIONS = table(
column("deleted"), column("deleted"),
schema="negotiation", schema="negotiation",
) )
_ITEMS = table("items", column("item_id"), column("price"), column("deleted"), schema="partner") _ITEMS = table("items", column("item_id"), column("name"), column("price"),
_SUPPLIERS = table("suppliers", column("supplier_id"), column("total_revenue"), column("deleted"), schema="partner") column("internet_lowest_price"), column("deleted"), schema="partner")
_QUOTATIONS = table("quotations", column("qt_id"), column("supplier_type"), column("deleted"), schema="quotation") _SUPPLIERS = table("suppliers", column("supplier_id"), column("name"), column("total_revenue"), column("deleted"), schema="partner")
_QUOTATIONS = table(
"quotations",
column("qt_id"), column("version_id"), column("supplier_type"),
column("start_time"), column("end_time"), column("deleted"),
schema="quotation",
)
# 자율 에이전트 이력 특징용 — agent 소유 learning 스키마 (done 행 = 협상 1건의 최종 결과).
_EXP_LOGS = table(
"experience_logs",
column("session_id"), column("company_id"), column("done"), column("settled_price"),
schema="learning",
)
_VERSION_NEGO_CARDS = table(
"version_nego_cards",
column("version_id"), column("nego_card_id"), column("created_at"), column("deleted"),
schema="card",
)
_VERSION_WILD_CARDS = table(
"version_wild_cards",
column("version_id"), column("wild_card_id"), column("created_at"), column("deleted"),
schema="card",
)
_NEGO_CARDS = table(
"nego_cards",
column("nego_card_id"), column("number"), column("deleted"),
schema="card",
)
_WILD_CARDS = table(
"wild_cards",
column("wild_card_id"), column("number"), column("deleted"),
schema="card",
)
# 상품↔협력사 매핑 (2026-07-07 신설): supply_type = 이 협력사가 이 상품을 공급하는 방식(SupplierType). # 상품↔협력사 매핑 (2026-07-07 신설): supply_type = 이 협력사가 이 상품을 공급하는 방식(SupplierType).
_SUPPLIER_ITEMS = table( _SUPPLIER_ITEMS = table(
"supplier_items", "supplier_items",
@@ -54,14 +86,19 @@ class INegoContextCRUD(ABC):
pass pass
@abstractmethod @abstractmethod
async def get_supply_type(self, cdb: AsyncSession, supplier_id, item_id) -> Tuple[ErrorType, Optional[int]]: async def get_item_name(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, Optional[str]]:
"""이 협력사가 이 상품을 공급하는 방식(supplier_items.supply_type: 0=none/1=유통/2=제조/3=총판). """상품명(items.name). 없으면 None — 카드 스크립트 {product_name} 치환용."""
매핑이 없으면 None."""
pass pass
@abstractmethod @abstractmethod
async def get_quotation_supplier_type(self, cdb: AsyncSession, quotation_id) -> Tuple[ErrorType, Optional[int]]: async def get_supplier_name(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, Optional[str]]:
"""견적의 협력사 유형(quotations.supplier_type — supplier_items 매핑 부재 시 폴백). 미지정 시 None.""" """협력사명(suppliers.name). 없으면 None — 카드 스크립트 {partner_name} 치환용."""
pass
@abstractmethod
async def get_supply_type(self, cdb: AsyncSession, supplier_id, item_id) -> Tuple[ErrorType, Optional[int]]:
"""이 협력사가 이 상품을 공급하는 방식(supplier_items.supply_type: 0=none/1=유통/2=제조/3=총판).
매핑이 없으면 None."""
pass pass
@abstractmethod @abstractmethod
@@ -74,6 +111,27 @@ class INegoContextCRUD(ABC):
"""상품에 연결된 협력사 수 — 협상 세션 이력 기준(supplier_items 매핑 부재 시 폴백).""" """상품에 연결된 협력사 수 — 협상 세션 이력 기준(supplier_items 매핑 부재 시 폴백)."""
pass pass
@abstractmethod
async def get_quotation_card_numbers(self, cdb: AsyncSession, quotation_id) -> Tuple[ErrorType, tuple[list[str], list[str]]]:
"""견적 version_id 에 연결된 (일반카드 번호 목록, 와일드카드 번호 목록). 없으면 빈 목록."""
pass
@abstractmethod
async def get_item_internet_lowest(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, int]:
"""상품 인터넷최저가(items.internet_lowest_price). 미수집이면 0."""
pass
@abstractmethod
async def get_quotation_period(self, cdb: AsyncSession, quotation_id) -> Tuple[ErrorType, Optional[tuple]]:
"""견적 협상 기간 (start_time, end_time). 없으면 None."""
pass
@abstractmethod
async def get_supplier_history(self, cdb: AsyncSession, company_id: str, supplier_id,
exclude_session_id) -> Tuple[ErrorType, tuple]:
"""이 협력사와의 과거 협상 이력 (횟수, 성사율, 평균 타결가/목표가). 없으면 (0, None, None)."""
pass
class NegoContextCRUD(INegoContextCRUD): class NegoContextCRUD(INegoContextCRUD):
async def get_session_row(self, cdb: AsyncSession, session_id) -> Tuple[ErrorType, Optional[tuple]]: async def get_session_row(self, cdb: AsyncSession, session_id) -> Tuple[ErrorType, Optional[tuple]]:
@@ -107,6 +165,67 @@ class NegoContextCRUD(INegoContextCRUD):
LOG.e_no_callstack(ex) LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, 0 return ErrorType.DB_RUN_FAILED, 0
async def get_item_internet_lowest(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, int]:
"""상품의 인터넷최저가(partner.items.internet_lowest_price). 미수집이면 0."""
try:
query = (
select(_ITEMS.c.internet_lowest_price)
.where(_ITEMS.c.item_id == item_id, _ITEMS.c.deleted == False) # noqa: E712
.limit(1)
)
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_item_internet_lowest failed.", raise_error=False)
if err_type != ErrorType.SUCCESS or not rows or not rows[0]:
return err_type, 0
return ErrorType.SUCCESS, int(rows[0])
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, 0
async def get_quotation_period(self, cdb: AsyncSession, quotation_id) -> Tuple[ErrorType, Optional[tuple]]:
"""견적 협상 기간 (start_time, end_time). 자율 에이전트의 마감 잔여율 특징용."""
try:
query = (
select(_QUOTATIONS.c.start_time, _QUOTATIONS.c.end_time)
.where(_QUOTATIONS.c.qt_id == quotation_id, _QUOTATIONS.c.deleted == False) # noqa: E712
.limit(1)
)
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_quotation_period failed.", raise_error=False)
if err_type != ErrorType.SUCCESS or not rows:
return err_type, None
return ErrorType.SUCCESS, (rows[0][0], rows[0][1])
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, None
async def get_supplier_history(self, cdb: AsyncSession, company_id: str, supplier_id,
exclude_session_id) -> Tuple[ErrorType, tuple]:
"""이 협력사와의 과거 협상 이력 집계 → (횟수, 성사율, 평균 타결가/목표가).
소스 = learning.experience_logs 의 종료행(done=True) ⨝ negotiation.sessions
(agent 가 직접 기록한 결과라 카드/자율 모드 무관하게 쌓인다). 이력 없으면 (0, None, None).
"""
try:
query = (
select(_EXP_LOGS.c.settled_price, _SESSIONS.c.target_price)
.select_from(_EXP_LOGS.join(_SESSIONS, _SESSIONS.c.session_id == _EXP_LOGS.c.session_id))
.where(_EXP_LOGS.c.done == True, # noqa: E712
_EXP_LOGS.c.company_id == company_id,
_SESSIONS.c.supplier_id == supplier_id,
_EXP_LOGS.c.session_id != exclude_session_id,
_SESSIONS.c.deleted == False) # noqa: E712
)
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_supplier_history failed.", raise_error=False)
if err_type != ErrorType.SUCCESS or not rows:
return err_type, (0, None, None)
n = len(rows)
settled = [(int(sp), int(tp)) for sp, tp in rows if sp and tp]
success = len([1 for sp, tp in rows if sp]) / n
avg_ratio = (sum(sp / tp for sp, tp in settled) / len(settled)) if settled else None
return ErrorType.SUCCESS, (n, success, avg_ratio)
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, (0, None, None)
async def get_supplier_total_revenue(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, float]: async def get_supplier_total_revenue(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, float]:
try: try:
query = ( query = (
@@ -122,6 +241,36 @@ class NegoContextCRUD(INegoContextCRUD):
LOG.e_no_callstack(ex) LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, 0.0 return ErrorType.DB_RUN_FAILED, 0.0
async def get_item_name(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, Optional[str]]:
try:
query = (
select(_ITEMS.c.name)
.where(_ITEMS.c.item_id == item_id, _ITEMS.c.deleted == False) # noqa: E712
.limit(1)
)
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_item_name failed.", raise_error=False)
if err_type != ErrorType.SUCCESS or not rows or not rows[0]:
return err_type, None
return ErrorType.SUCCESS, str(rows[0])
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, None
async def get_supplier_name(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, Optional[str]]:
try:
query = (
select(_SUPPLIERS.c.name)
.where(_SUPPLIERS.c.supplier_id == supplier_id, _SUPPLIERS.c.deleted == False) # noqa: E712
.limit(1)
)
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_supplier_name failed.", raise_error=False)
if err_type != ErrorType.SUCCESS or not rows or not rows[0]:
return err_type, None
return ErrorType.SUCCESS, str(rows[0])
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, None
async def get_supply_type(self, cdb: AsyncSession, supplier_id, item_id) -> Tuple[ErrorType, Optional[int]]: async def get_supply_type(self, cdb: AsyncSession, supplier_id, item_id) -> Tuple[ErrorType, Optional[int]]:
try: try:
query = ( query = (
@@ -139,21 +288,6 @@ class NegoContextCRUD(INegoContextCRUD):
LOG.e_no_callstack(ex) LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, None return ErrorType.DB_RUN_FAILED, None
async def get_quotation_supplier_type(self, cdb: AsyncSession, quotation_id) -> Tuple[ErrorType, Optional[int]]:
try:
query = (
select(_QUOTATIONS.c.supplier_type)
.where(_QUOTATIONS.c.qt_id == quotation_id, _QUOTATIONS.c.deleted == False) # noqa: E712
.limit(1)
)
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_quotation_supplier_type failed.", raise_error=False)
if err_type != ErrorType.SUCCESS or not rows or rows[0] is None:
return err_type, None
return ErrorType.SUCCESS, int(rows[0])
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, None
async def count_item_suppliers(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, int]: async def count_item_suppliers(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, int]:
try: try:
query = ( query = (
@@ -181,3 +315,63 @@ class NegoContextCRUD(INegoContextCRUD):
except Exception as ex: except Exception as ex:
LOG.e_no_callstack(ex) LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, 0 return ErrorType.DB_RUN_FAILED, 0
async def get_quotation_card_numbers(self, cdb: AsyncSession, quotation_id) -> Tuple[ErrorType, tuple[list[str], list[str]]]:
try:
version_q = (
select(_QUOTATIONS.c.version_id)
.where(_QUOTATIONS.c.qt_id == quotation_id, _QUOTATIONS.c.deleted == False) # noqa: E712
.limit(1)
)
err_type, rows = await DB_SESSION_MNG.execute(cdb, version_q, "get_quotation_version failed.", raise_error=False)
if err_type != ErrorType.SUCCESS:
return err_type, ([], [])
if not rows or rows[0] is None:
return ErrorType.SUCCESS, ([], [])
version_id = rows[0]
nego_q = (
select(_NEGO_CARDS.c.number)
.select_from(
_VERSION_NEGO_CARDS.join(
_NEGO_CARDS,
_VERSION_NEGO_CARDS.c.nego_card_id == _NEGO_CARDS.c.nego_card_id,
)
)
.where(
_VERSION_NEGO_CARDS.c.version_id == version_id,
_VERSION_NEGO_CARDS.c.deleted == False, # noqa: E712
_NEGO_CARDS.c.deleted == False, # noqa: E712
)
.order_by(_VERSION_NEGO_CARDS.c.created_at)
)
n_err, n_rows = await DB_SESSION_MNG.execute(cdb, nego_q, "get_quotation_nego_cards failed.", raise_error=False)
if n_err != ErrorType.SUCCESS:
return n_err, ([], [])
wild_q = (
select(_WILD_CARDS.c.number)
.select_from(
_VERSION_WILD_CARDS.join(
_WILD_CARDS,
_VERSION_WILD_CARDS.c.wild_card_id == _WILD_CARDS.c.wild_card_id,
)
)
.where(
_VERSION_WILD_CARDS.c.version_id == version_id,
_VERSION_WILD_CARDS.c.deleted == False, # noqa: E712
_WILD_CARDS.c.deleted == False, # noqa: E712
)
.order_by(_VERSION_WILD_CARDS.c.created_at)
)
w_err, w_rows = await DB_SESSION_MNG.execute(cdb, wild_q, "get_quotation_wild_cards failed.", raise_error=False)
if w_err != ErrorType.SUCCESS:
return w_err, ([], [])
return ErrorType.SUCCESS, (
[str(r) for r in n_rows if r is not None],
[str(r) for r in w_rows if r is not None],
)
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, ([], [])
+238 -27
View File
@@ -10,18 +10,66 @@ import re
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional from typing import Any, Dict, List, Optional
from negotiation.cards.domain.tactics import compute_counter, tactic_for
from negotiation.chat.service.script_repository import ScriptRepository from negotiation.chat.service.script_repository import ScriptRepository
MAX_ROUNDS = 3 MAX_ROUNDS = 3 # config 미주입 시 폴백 (규칙 정본은 tenant config negotiation.max_counter_rounds)
_PRICE_MODES = ("price",) _PRICE_MODES = ("price",)
_CHOICE_MODES = ("yes_no", "confirm", "delivery_type") _CHOICE_MODES = ("yes_no", "confirm", "delivery_type")
# ---- 완전 자율 모드 (AUTONOMY_MODE, autonomy_store) --------------------------------
# 가격협상 판정 룰(check_price_match/wildcard_entry/iteration_limit)과 카드 선택을
# 정책 행동(수락/역제안/압박/결렬)으로 대체할 때 쓰는 스텝들. autonomy_decider 미주입이면 도달 불가.
_AUTONOMY_TURN_CAP = 12 # 엔지니어링 타임아웃(무한 세션 방지) — 협상 룰이 아니다
_AUTONOMY_PRESS_SCRIPTS = {
1: "동일 품목에 대해 복수 공급처의 견적이 함께 검토되고 있습니다. 현재 제시가로는 우선순위 확보가 어려운 상황입니다. 경쟁력 있는 가격으로 다시 제안해 주시겠어요?",
2: "제안하신 조건의 취지는 충분히 이해했습니다. 저희도 최대한 맞춰보려 합니다. 조금만 더 조정해 주시면 내부 설득이 가능할 것 같습니다. 다시 제안해 주시겠어요?",
3: "내부 산정 기준과 현재 제시가 사이에 아직 차이가 있습니다. 기준에 부합하는 수준으로 재검토하여 다시 제안해 주시기를 부탁드립니다.",
4: "귀사를 장기적으로 함께할 파트너로 검토하고 있습니다. 이번 협상이 원만히 마무리되면 후속 거래 확대도 논의하고 싶습니다. 서로 만족할 수 있는 가격으로 다시 제안해 주시겠어요?",
}
_AUTONOMY_STEPS = {
"자율_역제안": {
"script": "제안해 주신 **{input_price}원**, 내부 검토를 마쳤습니다. **{autonomy_offer}원**이라면 즉시 수락하고 우선협상 대상으로 확정하겠습니다. 수락하시겠습니까?",
"next_input_mode": "yes_no",
"input_options": ["예", "아니오"],
"next_step": {"예": "협상완료", "아니오": "가격협상_재입력"},
"type": "text",
"chat_end": False,
},
# 최종 통보(WC-03 의 자율 버전): 정책이 직전과 같은 금액을 다시 부르는 순간(단조 봉투상
# 더 올릴 수 없음 = 탄약 소진) 발동. 거절하면 협상을 정리한다 — 어정쩡한 반복 대신 명확한 마무리.
"자율_최종제안": {
"script": "지금까지 협의에 성실히 임해 주셔서 감사합니다. **{autonomy_offer}원**은 저희가 제시할 수 있는 마지막 제안입니다. 수락해 주시면 즉시 우선협상 대상으로 확정되며, 어려우시다면 이번 협상은 여기서 마무리하겠습니다.",
"next_input_mode": "yes_no",
"input_options": ["예", "아니오"],
"next_step": {"예": "협상완료", "아니오": "협상실패"},
"type": "text",
"chat_end": False,
},
**{
f"자율_압박_{s}": {
"script": t,
"next_input_mode": "price",
"input_options": [],
"next_step": {"default": "가격협상_확인"},
"type": "text",
"chat_end": False,
}
for s, t in _AUTONOMY_PRESS_SCRIPTS.items()
},
}
# 최종 타결/결렬 스텝. 재협상=협상완료(우선협상 타결), 재견적=결과제출(투찰확정). 둘 다 협상실패=결렬. # 최종 타결/결렬 스텝. 재협상=협상완료(우선협상 타결), 재견적=결과제출(투찰확정). 둘 다 협상실패=결렬.
# 이 스텝들은 chat_end=False(뒤에 협상종료가 옴)라, outcome 을 컨텍스트에 적재했다가 # 이 스텝들은 chat_end=False(뒤에 협상종료가 옴)라, outcome 을 컨텍스트에 적재했다가
# 실제 종료(chat_end=협상종료) 시점에 확정 보고한다 → backend 가 chat_end 에서 DONE/REJECTED 를 옳게 가른다. # 실제 종료(chat_end=협상종료) 시점에 확정 보고한다 → backend 가 chat_end 에서 DONE/REJECTED 를 옳게 가른다.
_SUCCESS_STEPS = ("협상완료", "결과제출") _SUCCESS_STEPS = ("협상완료", "결과제출")
_FAILURE_STEPS = ("협상실패",) _FAILURE_STEPS = ("협상실패",)
# 카운터 제안(pending_counter_price) 수락으로 인정하는 선택 입력.
_ACCEPT_INPUTS = ("예", "수락")
# 프론트는 표시용 문자열로 가격을 보낸다(예: "530,000원"). 천단위 콤마·통화기호("원")·공백 등 # 프론트는 표시용 문자열로 가격을 보낸다(예: "530,000원"). 천단위 콤마·통화기호("원")·공백 등
# 숫자 외 문자를 제거하고 파싱한다. (콤마만 지우면 "원" 때문에 float() 가 실패해 가격 입력이 # 숫자 외 문자를 제거하고 파싱한다. (콤마만 지우면 "원" 때문에 float() 가 실패해 가격 입력이
# 영영 저장되지 않고 같은 step 에 머무는 버그가 났었다.) # 영영 저장되지 않고 같은 step 에 머무는 버그가 났었다.)
@@ -70,8 +118,14 @@ class ChatEngine:
def __init__(self, scripts_repo: ScriptRepository, rq_type: str = "재협상"): def __init__(self, scripts_repo: ScriptRepository, rq_type: str = "재협상"):
self.repo = scripts_repo self.repo = scripts_repo
self.rq_type = rq_type self.rq_type = rq_type
self.scripts = scripts_repo.load_scripts(rq_type) # 자율 스텝은 병합만 해둔다(repo 캐시 오염 방지 위해 새 dict) — decider 미주입 시 도달 불가.
self.scripts = {**scripts_repo.load_scripts(rq_type), **_AUTONOMY_STEPS}
self.step_map = scripts_repo.client_step_mapping() self.step_map = scripts_repo.client_step_mapping()
# 결정 스택 규칙층(Phase 1): 와일드카드 진입 임계·라운드 상한을 테넌트 config 에서 읽는다.
# (하드코딩 1.02/1.05/3 을 데이터화 — 고객사별로 튜닝 가능, 코드 수정 불필요)
self.rules = scripts_repo.config.negotiation
# 완전 자율 모드: ChatService 가 AutonomyStore 정책을 주입하면 가격협상 판정 룰을 대체한다.
self.autonomy_decider = None # Callable[[dict], autonomy_actions.Action]
# ---- public -------------------------------------------------------- # ---- public --------------------------------------------------------
def start(self, session: ChatSession) -> StepView: def start(self, session: ChatSession) -> StepView:
@@ -89,21 +143,33 @@ class ChatEngine:
if price is None: if price is None:
return self._error(session, "가격을 숫자로 입력해 주세요.") return self._error(session, "가격을 숫자로 입력해 주세요.")
session.context["input_price"] = price session.context["input_price"] = price
# 새 가격 제시 = 직전 카운터 제안 거절 확정 → 대기 중 카운터 폐기.
session.context.pop("pending_counter_price", None)
session.context["prev_partner_price"] = price
# 협력사 첫 제시가 — 가격 수용률(첫 제시가 대비 양보율) 동적 계산의 기준값. # 협력사 첫 제시가 — 가격 수용률(첫 제시가 대비 양보율) 동적 계산의 기준값.
session.context.setdefault("first_offer_price", price) session.context.setdefault("first_offer_price", price)
session.context["round"] = session.context.get("round", 0) + 1 session.context["round"] = session.context.get("round", 0) + 1
nxt = self._default_next(node) nxt = self._default_next(node)
elif mode in _CHOICE_MODES: elif mode in _CHOICE_MODES:
# 와일드카드 1% 인하 제안을 수락("예")하면 합의가를 제안가(offer_1pct)로 확정한다. # 자율 역제안/최종제안 수락("예") → 합의가는 에이전트 제안가다.
# (멘트에만 쓰이던 offer_1pct 가 input_price 에 반영되지 않아, 요약/입찰가가 # (카드/와일드카드 경로는 아래 pending_counter_price 일반 메커니즘이 처리하지만
# 직전 제시가로 잡히던 버그 수정 — 수락 시 실제 합의가는 인하가다.) # 자율 스텝은 pending_counter 를 쓰지 않으므로 명시 분기 유지.)
if session.step == "wild_card_1pct" and user_input == "예" and session.context.get("offer_1pct"): if session.step in ("자율_역제안", "자율_최종제안") and user_input == "예" \
session.context["input_price"] = float(session.context["offer_1pct"]) and session.context.get("autonomy_offer"):
session.context["input_price"] = float(session.context["autonomy_offer"])
nxt = self._choice_next(node, user_input, session) nxt = self._choice_next(node, user_input, session)
else: else:
nxt = self._default_next(node) nxt = self._default_next(node)
nxt = self._resolve(nxt, session) nxt = self._resolve(nxt, session)
# 카운터 수락 일반 메커니즘: 카드/와일드카드가 제시한 카운터가(pending_counter_price)를
# 협력사가 수락("예"/"수락")한 채 성공 스텝으로 전이하면 합의가 = 카운터가.
# (구 offer_1pct 특수 분기의 일반화. 거절인데 성공 스텝으로 가는 경로 — 1% 거절 시
# 원 제시가 수락 종결 — 는 카운터를 버리고 기존 input_price 로 타결한다.)
if mode in _CHOICE_MODES and nxt in _SUCCESS_STEPS:
pending = session.context.pop("pending_counter_price", None)
if pending and user_input in _ACCEPT_INPUTS:
session.context["input_price"] = float(pending)
return self._render(session, nxt) return self._render(session, nxt)
# ---- transition ---------------------------------------------------- # ---- transition ----------------------------------------------------
@@ -131,12 +197,20 @@ class ChatEngine:
return nxt return nxt
def _eval_conditions(self, conds: List[dict], session: ChatSession) -> Optional[str]: def _eval_conditions(self, conds: List[dict], session: ChatSession) -> Optional[str]:
"""KT 구매자 관점 조건 평가. """KT 구매자 관점 조건 평가 (임계값은 config negotiation.* — 규칙층 데이터화).
- 협력사 제시가 ≤ anchor → 우선협상(협상완료). - 협력사 제시가 ≤ anchor → 우선협상(협상완료).
- anchor 살짝 초과(≤ anchor*1.05) + 와일드카드 미사용 → 와일드카드로 인하 압박. - anchor 살짝 초과(≤ anchor×wildcard_entry_ratio) + 와일드카드 미사용 → 와일드카드로 인하 압박.
- 설정 카드(action_space) 모두 소진 → 협상실패. - 설정 카드(action_space) 모두 소진 → 협상실패.
- 그 외 → 가격협상(카드 1장 플레이 후 재제안). - 그 외 → 가격협상(카드 1장 플레이 후 재제안).
완전 자율 모드(autonomy_decider 주입)에서는 위 룰 전체를 정책 행동으로 대체한다.
""" """
# 가격협상 판정 지점(check_price_match 포함 조건 리스트)에서만 자율 정책이 개입한다.
if self.autonomy_decider is not None and any(
c.get("condition") == "check_price_match" for c in conds):
nxt = self._autonomy_next(session)
if nxt is not None:
return nxt # 정책 실패(예외) 시에만 아래 룰로 폴백
ctx = session.context ctx = session.context
price = ctx.get("input_price", 0) price = ctx.get("input_price", 0)
anchor = ctx.get("anchor_price", 0) anchor = ctx.get("anchor_price", 0)
@@ -146,37 +220,118 @@ class ChatEngine:
cond = c.get("condition") cond = c.get("condition")
ok = False ok = False
if cond == "check_wildcard_entry": if cond == "check_wildcard_entry":
ok = (not ctx.get("wildcard_used")) and anchor < price <= anchor * 1.05 ok = (
(not ctx.get("wildcard_used"))
and anchor > 0
and anchor < price
and (
price <= anchor * self.rules.wildcard_1pct_ratio
or (bool(ctx.get("allow_selected_wildcards", True))
and price <= anchor * self.rules.wildcard_entry_ratio)
)
)
elif cond == "check_is_supplier_type_c": elif cond == "check_is_supplier_type_c":
ok = False # 공급사 유형 미보유 (PoC 단순화) ok = False # 공급사 유형 미보유 (PoC 단순화)
elif cond == "check_price_match": # = 우선협상: 제시가가 앵커가 이하 elif cond == "check_price_match": # = 우선협상: 제시가가 앵커가 이하
ok = anchor > 0 and price <= anchor ok = anchor > 0 and price <= anchor
elif cond == "check_iteration_limit": # 협상 라운드 상한 또는 카드 소진 elif cond == "check_iteration_limit": # 협상 라운드 상한 또는 카드 소진 → 종결 국면
# round 는 매 가격입력마다 증가(기존가격제시=1). 그 이후 카운터제안이 MAX_ROUNDS 회를 # round 는 매 가격입력마다 증가(기존가격제시=1). 카운터제안이 상한을 넘거나 카드가
# 넘으면 종료한다. 카드선택(RL)이 실패(state ValueError)해도 used_action_ids 가 안 늘어 # 소진되면 곧장 실패가 아니라 **종결 국면**으로 처리한다(실제 MD 협상 방식):
# 카드 소진 조건만으로는 종료되지 않으므로, 라운드 상한을 독립적으로 둬 무한 가격입력을 막는다. # ① 아직 종결 전술을 안 썼으면 → 가격협상으로 보내되 force_closing 마킹
# (선행 chat_server 의 `iteration >= 3` 와 동일한 안전장치.) # (ChatService 가 종결 전술 — 중간값 절충/최후통첩 — 을 강제 발동)
# ② 종결 전술까지 소진(closing_played)이면 → 최종 제시가 ≤ target 은 타결,
# 초과는 결렬(협상실패) — "목표가 초과 타결 금지" 가드레일과 정합.
counter_rounds = max(0, ctx.get("round", 0) - 1) counter_rounds = max(0, ctx.get("round", 0) - 1)
ok = counter_rounds >= MAX_ROUNDS or (cards_total > 0 and cards_used >= cards_total) exhausted = counter_rounds >= self.rules.max_counter_rounds or (cards_total > 0 and cards_used >= cards_total)
if exhausted:
target = ctx.get("target_price", 0)
if not ctx.get("closing_played"):
ctx["force_closing"] = True
return "가격협상"
return "협상완료" if (target > 0 and price <= target) else c.get("next")
ok = False
elif cond == "default": elif cond == "default":
ok = True ok = True
if ok: if ok:
return c.get("next") return c.get("next")
return "가격협상" return "가격협상"
def _autonomy_next(self, session: ChatSession) -> Optional[str]:
"""완전 자율: 정책 행동 → 스텝. 수락/역제안 금액/압박 화법/결렬 타이밍 전부 정책이 결정.
유일한 강제 종료는 턴 상한(_AUTONOMY_TURN_CAP) — 무한 세션 방지용 엔지니어링 타임아웃.
정책 호출이 실패하면 None 을 반환해 기존 룰 평가로 폴백한다(서비스 연속성).
"""
ctx = session.context
if ctx.get("round", 0) > _AUTONOMY_TURN_CAP:
# 턴 상한도 최종제안 보장(봉투 ⑥)을 우회하지 않는다 — 어떤 경로로 끝나든
# "끝내기 전에 한 번 더"(제품 결정)를 거친다. 최종 거절 후에만 협상실패.
if not ctx.get("autonomy_final_asked"):
ctx["autonomy_final_asked"] = True
ctx["autonomy_offer"] = int(ctx.get("target_price", 0))
return "자율_최종제안"
return "협상실패"
try:
act = self.autonomy_decider(ctx)
except Exception: # 정책 오류 → 룰 폴백 (호출부에서 로깅)
return None
session.context["autonomy_action"] = f"{act.kind}:{act.strategy}:{act.counter_q}"
span = max(ctx.get("target_price", 0) - ctx.get("anchor_price", 0), 1.0)
# 탄약소진(같은 금액 재호출) 판정은 '마지막 역제안' 기준 — autonomy_last(마지막 행동)는
# 사이에 낀 설득이 덮어써 판정이 리셋된다 (chat_service 가 counter 마다 별도 보존).
last = ctx.get("autonomy_last_counter") or {}
if act.kind == "accept":
return "협상완료"
if act.kind == "walk":
# 결렬 전 마지막 제안 1회 보장 — "끝내기 전에 한 번 더 물어보고 종료" (제품 결정).
# 최종제안을 이미 거쳤으면(autonomy_final_asked) 그대로 종료한다.
if not ctx.get("autonomy_final_asked"):
ctx["autonomy_final_asked"] = True
# 최종제안 금액 = 목표가. 마지막 기회에 직전 역제안 금액을 반복하면 승인 범위의
# 여지(목표가까지)를 남긴 채 결렬된다 — 최종에는 우리가 수락 가능한 최대치를 부른다.
ctx["autonomy_offer"] = int(ctx.get("target_price", 0))
return "자율_최종제안"
return "협상실패"
if act.kind == "counter":
ctx["autonomy_offer"] = int(round(ctx.get("anchor_price", 0) + act.counter_q * span))
# 직전과 같은 금액을 다시 부름 = 단조 봉투상 더 올릴 수 없음(탄약 소진) → 최종 통보로 전환.
if last.get("kind") == "counter" and act.counter_q <= float(last.get("q", -9)) + 1e-9:
ctx["autonomy_final_asked"] = True
ctx["autonomy_offer"] = int(ctx.get("target_price", 0))
return "자율_최종제안"
return "자율_역제안"
return f"자율_압박_{act.strategy or 3}"
def _pick_wildcard(self, session: ChatSession) -> str: def _pick_wildcard(self, session: ChatSession) -> str:
"""앵커가 살짝 초과 구간에서 인하 압박 카드 선택. """앵커가에 아주 근접(≤ anchor×wildcard_1pct_ratio)한 구간에서만 1% 인하 요청(wild_card_1pct)으로
- 앵커가에 아주 근접(≤ anchor*1.02): 1% 인하 요청(wild_card_1pct) → 앵커가 이하로 유도. 앵커가 이하로 유도한다. 그 외 구간은 일반 가격협상(카드 플레이)으로 돌린다.
- 그 외: 목표 매입가 맞춰달라(wild_card_budget).
과거 여기서 반환하던 '재원부족'(wild_card_budget) 하드코딩 카드는 제거했다 —
견적에서 실제 선택한 와일드카드(중간값 절충·목표가 선제안 등)와 매핑되지 않은 채
'와일드카드를 하나라도 골랐으면' 조건만으로 발동해, 선택하지도 않은 재원부족 멘트가
노출되는 오작동이 있었다.
""" """
ctx = session.context ctx = session.context
price = ctx.get("input_price", 0) price = ctx.get("input_price", 0)
anchor = ctx.get("anchor_price", 0) anchor = ctx.get("anchor_price", 0)
ctx["wildcard_used"] = True if anchor > 0 and price <= anchor * self.rules.wildcard_1pct_ratio:
if anchor > 0 and price <= anchor * 1.02: # 와일드카드는 실제로 노출할 때만 '사용됨'으로 마킹한다 — 가격협상으로 돌아가는
ctx["offer_1pct"] = int(round(price * 0.99)) # 1% 인하가 # 경우에도 마킹하면 이후 라운드에서 정당한 1% 카드까지 억제된다.
ctx["wildcard_used"] = True
ctx["offer_1pct"] = int(round(price * 0.99)) # 1% 인하가 (멘트 변수)
ctx["pending_counter_price"] = ctx["offer_1pct"] # 수락 시 이 가격으로 타결
return "wild_card_1pct" return "wild_card_1pct"
return "wild_card_budget" # 1.02 초과 ~ entry(1.05) 구간: 견적에서 선택한 와일드카드의 전술로 카운터 제시.
# (구현 전에는 이 구간이 일반 가격협상으로 회귀해 선택형 WC 가 영영 발동하지 않던 갭.)
if anchor > 0 and price <= anchor * self.rules.wildcard_entry_ratio:
for number in (ctx.get("selected_wild_card_numbers") or []):
counter = compute_counter(tactic_for(str(number)), ctx)
if counter is not None:
ctx["wildcard_used"] = True
ctx["pending_counter_price"] = counter
ctx["active_wild_card_number"] = str(number)
return "wild_card_dynamic"
return "가격협상"
# ---- render -------------------------------------------------------- # ---- render --------------------------------------------------------
def vars_for(self, session: ChatSession) -> Dict[str, Any]: def vars_for(self, session: ChatSession) -> Dict[str, Any]:
@@ -185,26 +340,82 @@ class ChatEngine:
out = {} out = {}
if "input_price" in ctx: if "input_price" in ctx:
out["input_price"] = int(ctx["input_price"]) out["input_price"] = int(ctx["input_price"])
# 목표가/앵커가: 엔진 내부 파일 스크립트는 {target}/{anchor}, negodata 카드 에디터는
# {target_price}/{anchor_price}(variables.ts) 를 쓴다 — 양쪽 이름 모두 채워 치환 누락 방지.
if "target_price" in ctx: if "target_price" in ctx:
out["target"] = int(ctx["target_price"]) out["target"] = out["target_price"] = int(ctx["target_price"])
if "anchor_price" in ctx: if "anchor_price" in ctx:
out["anchor"] = int(ctx["anchor_price"]) # anchoring_price = DB 시드 기본 카드/sessions 컬럼 표기, anchor_price = 카드 에디터 표기.
out["anchor"] = out["anchor_price"] = out["anchoring_price"] = int(ctx["anchor_price"])
# 카드 에디터 카탈로그의 협력사명/상품명(partner_name·product_name) 치환.
if ctx.get("partner_name"):
out["partner_name"] = str(ctx["partner_name"])
if ctx.get("product_name"):
out["product_name"] = str(ctx["product_name"])
if "offer_1pct" in ctx: if "offer_1pct" in ctx:
out["offer_1pct"] = int(ctx["offer_1pct"]) out["offer_1pct"] = int(ctx["offer_1pct"])
# 인하율 = (기존 공급가 - 제시가) / 기존 공급가 * 100. 기존가 없으면 미표시(0.0). if "autonomy_offer" in ctx:
out["autonomy_offer"] = int(ctx["autonomy_offer"])
# 인터넷 최저가(NGC-008): 수집값이 컨텍스트에 없으면 앵커가로 폴백 — 원형 토큰 노출 방지.
if ctx.get("internet_lowest_price"):
out["internet_lowest_price"] = int(ctx["internet_lowest_price"])
elif "anchor_price" in ctx:
out["internet_lowest_price"] = int(ctx["anchor_price"])
# 고객사 교환·요구 조건(NGC-009/010): 런타임 소스 미구현 — 중립 문구 폴백.
out["customer_condition"] = ctx.get("customer_condition") or "상호 협의된 조건"
# 전술 카운터 변수(카드 시드 멘트의 가격 변수) — tactics.compute_counter 산식과 동일 정의.
anchor = ctx.get("anchor_price") or 0
target = ctx.get("target_price") or 0
if "input_price" in ctx:
out["prev_partner_price"] = int(ctx.get("prev_partner_price") or ctx["input_price"])
prev_customer = ctx.get("prev_customer_price") or anchor
if prev_customer:
out["prev_customer_price"] = int(prev_customer)
if anchor and target:
out["target_mid_price"] = int(round((anchor + target) / 2))
if prev_customer and "input_price" in ctx:
out["middle_price"] = int(round((prev_customer + ctx["input_price"]) / 2))
if ctx.get("pending_counter_price"):
out["counter_price"] = int(ctx["pending_counter_price"])
# 인하율 = (기존 공급가(상품단가) - 제시가) / 기존 공급가 * 100. 기존가 없으면 미표시(0.0).
# 제시가가 기존가보다 높으면(인상 제시) 음수가 나오는데, "-1.3% 인하된 금액" 같은
# 모순 표현이 되므로 discount_rate 는 0 미만 금지하고, 인상/동일/인하를 구분한
# 문구는 discount_phrase 로 별도 제공한다(가격협상_확인 멘트가 사용).
base = ctx.get("item_price") or 0 base = ctx.get("item_price") or 0
if base > 1 and "input_price" in ctx: if base > 1 and "input_price" in ctx:
out["discount_rate"] = f"{((base - ctx['input_price']) / base) * 100:.1f}" rate = ((base - ctx["input_price"]) / base) * 100
out["discount_rate"] = f"{max(0.0, rate):.1f}"
if rate >= 0.05:
out["discount_phrase"] = f"기존 공급가 대비 약 **{rate:.1f}%** 인하된 금액입니다. "
elif rate <= -0.05:
out["discount_phrase"] = (
f"기존 공급가(**{int(base)}원**)보다 약 **{abs(rate):.1f}%** 높은 금액입니다. ")
else:
out["discount_phrase"] = "기존 공급가와 동일한 수준의 금액입니다. "
else: else:
out["discount_rate"] = "0.0" out["discount_rate"] = "0.0"
out["discount_phrase"] = ""
return out return out
def _vars(self, session: ChatSession) -> Dict[str, Any]: def _vars(self, session: ChatSession) -> Dict[str, Any]:
return self.vars_for(session) return self.vars_for(session)
def render_step(self, session: ChatSession, step_key: str) -> StepView:
"""지정 스텝으로 전이·렌더 (공개) — ChatService 가 카드 카운터 제시 시
가격협상 → 가격협상_카운터로 스텝을 전환할 때 사용한다."""
return self._render(session, step_key)
def _render(self, session: ChatSession, step_key: Optional[str]) -> StepView: def _render(self, session: ChatSession, step_key: Optional[str]) -> StepView:
if not step_key or step_key not in self.scripts: if not step_key or step_key not in self.scripts:
return self._error(session, f"다음 단계를 찾을 수 없습니다: {step_key}") return self._error(session, f"다음 단계를 찾을 수 없습니다: {step_key}")
# 가드레일(최후 방어선): 구매자 대리는 목표가 초과로 절대 타결하지 않는다.
# 카운터 클램프·종결 규칙이 정상이면 도달하지 않지만, 스크립트 편집 실수 등으로
# 성공 스텝에 초과가로 진입하면 결렬로 강제 전환한다. (재협상 흐름 한정)
if step_key in _SUCCESS_STEPS and self.rq_type == "재협상":
ctx = session.context
target = ctx.get("target_price") or 0
if target > 0 and ctx.get("input_price", 0) > target:
step_key = "협상실패"
node = self.scripts[step_key] node = self.scripts[step_key]
session.step = step_key session.step = step_key
chat_end = bool(node.get("chat_end")) chat_end = bool(node.get("chat_end"))
@@ -0,0 +1,149 @@
"""InputInterpreter — 협력사 자유 발화를 대화 단계 기대 입력으로 구조화 (Phase 3 이해층).
원칙: "숫자와 결정은 결정론이, 말은 LLM 이" (ScriptNaturalizer 와 동일 철학) —
- LLM 의 역할은 ① 의도 분류(choice|price|unknown) ② 가격 '표현의 위치' 찾기까지다.
가격 숫자 계산은 LLM 출력이 아니라 결정론 한국어 가격 파서(parse_korean_price)가 수행한다.
- 검증: choice 는 허용 선택지 목록에 철자 그대로 있어야 하고, price_text 는 사용자 원문의
부분 문자열이어야 한다(환각 차단). 하나라도 어긋나면 None → 호출부가 원문 그대로 폴백
(기존 엔진의 재질문 흐름 유지 — 협상은 절대 멈추지 않는다).
게이트: tenant llm.enabled + 전역 자격증명(ScriptNaturalizer 와 동일). 미설정이면 무동작 —
기존 버튼/정형 입력 경로는 그대로 두고, 자유 텍스트일 때만 해석을 시도한다.
"""
import asyncio
import json
import re
from dataclasses import dataclass
from typing import Callable, List, Optional
from common.logger import LOG
from negotiation.profiling.config import LlmCredentials
# 정형 가격 입력(버튼/필드) — LLM 없이 기존 결정론 경로로 처리 가능한 형태.
SIMPLE_PRICE_RE = re.compile(r"\s*[\d,]+(\.\d+)?\s*원?\s*")
# 한국어 단위 (큰 단위 → 작은 단위 순서로 등장한다고 가정: "1만 2천 500원")
_KOREAN_UNITS = {"억": 100_000_000, "만": 10_000, "천": 1_000, "백": 100}
_PRICE_TOKEN_RE = re.compile(r"[\d.억만천백]+")
def parse_korean_price(text: str) -> Optional[float]:
"""가격 표현 문자열 → 숫자 (결정론). "10,500원"→10500, "1만 500원"→10500, "만원"→10000,
"1.5만"→15000, "3만2천원"→32000. 해석 불가/0 이하 → None.
"""
t = (text or "").replace(",", "").replace(" ", "").replace("원", "").strip()
if not t:
return None
if re.fullmatch(r"\d+(\.\d+)?", t):
v = float(t)
return v if v > 0 else None
if not re.fullmatch(r"[\d.억만천백]+", t):
return None # 단위·숫자 외 문자 포함 → 해석 불가(안전 폴백)
total, num = 0.0, ""
for ch in t:
if ch.isdigit() or ch == ".":
num += ch
else: # 단위 문자
try:
n = float(num) if num else 1.0 # "만원" = 1만
except ValueError:
return None
total += n * _KOREAN_UNITS[ch]
num = ""
if num:
try:
total += float(num) # 잔여 숫자: "1만500" 의 500
except ValueError:
return None
return total if total > 0 else None
@dataclass
class InterpretedInput:
kind: str # "choice" | "price"
value: str # ChatEngine.advance 에 그대로 전달할 문자열 ("예" / "10500")
source: str # 판단 근거(선택지 원문 또는 가격 표현 원문) — 로깅/투명성용
_SYSTEM = """너는 B2B 구매 협상 챗봇의 입력 해석기다. 협력사(사용자)의 자유 발화를 현재 대화 단계가 기대하는 입력으로 구조화한다.
규칙 (하나라도 어기면 출력은 폐기된다):
- 출력은 JSON 하나만: {"intent": "choice"|"price"|"unknown", "choice": "<선택지 철자 그대로>"|null, "price_text": "<원문 속 가격 표현 그대로>"|null}
- choice 는 발화의 '의미'를 선택지 중 하나에 대응시켜, 그 선택지 문자열을 철자 그대로 복사한다.
예) 선택지 ["예","아니오"]: "네 접니다"/"맞습니다"/"진행해주세요"/"동의합니다" → "예",
"아닌데요"/"제가 아닙니다"/"어렵습니다"/"거절하겠습니다" → "아니오"
- 사용자가 구체적 가격을 제시/역제안하면 intent=price. price_text 는 반드시 사용자 원문에 등장한
표현을 그대로 복사한다(예: "10,500원", "1만 500원"). 숫자를 계산하거나 변형하지 마라.
- 발화가 어느 선택지의 의미인지 정말 판단할 수 없거나 주제와 무관할 때만 intent=unknown."""
def _default_llm_call(messages: List[dict]) -> dict:
"""기본 LLM 호출(동기) — 전역 자격증명으로 chat_json. 테스트에서 주입 대체 지점."""
from negotiation.profiling.infra.llm_adapter import chat_json
return chat_json(messages, temperature=0.0, max_tokens=200)
class InputInterpreter:
def __init__(self, llm_call: Optional[Callable[[List[dict]], dict]] = None,
timeout_seconds: float = 6.0):
self._llm_call = llm_call or _default_llm_call
self._timeout = timeout_seconds
@staticmethod
def available() -> bool:
"""전역 LLM 자격증명이 설정돼 있는가 (테넌트 enabled 게이트는 호출부 몫)."""
return LlmCredentials.from_config().is_configured()
async def interpret(self, user_input: str, *, input_mode: str,
input_options: Optional[List[str]] = None,
step_script: Optional[str] = None) -> Optional[InterpretedInput]:
"""자유 발화 → 기대 입력. 검증 불통과/실패/타임아웃 시 None(호출부 원문 폴백).
step_script: 직전 봇 질문(맥락) — "네 접니다" 같은 발화는 질문 없이는 의도 판단이
애매해 unknown 이 되므로, 무엇에 대한 답인지 함께 준다.
"""
text = (user_input or "").strip()
options = [str(o) for o in (input_options or [])]
if not text:
return None
payload = {
"현재 단계 기대 입력": "가격(숫자)" if input_mode == "price" else "선택지 중 하나",
"선택지": options,
"사용자 발화": text,
}
if step_script:
payload["직전 봇 질문"] = step_script[:300]
messages = [
{"role": "system", "content": _SYSTEM},
{"role": "user", "content": json.dumps(payload, ensure_ascii=False) + "\n\nJSON 으로만 답하라."},
]
try:
result = await asyncio.wait_for(asyncio.to_thread(self._llm_call, messages), self._timeout)
except Exception as ex: # 타임아웃 포함 — 원문 폴백
LOG.w(f"[InputInterpreter] LLM 호출 실패(원문 폴백): {ex}")
return None
if not isinstance(result, dict):
return None
intent = result.get("intent")
if intent == "choice":
choice = result.get("choice")
# 결정: 선택지 목록에 철자 그대로 있어야만 채택 (LLM 이 지어낸 분기 차단).
if isinstance(choice, str) and choice in options:
return InterpretedInput(kind="choice", value=choice, source=choice)
LOG.w(f"[InputInterpreter] 검증 실패: choice={choice!r} ∉ {options}")
return None
if intent == "price":
span = result.get("price_text")
# 환각 차단: 가격 표현은 사용자 원문의 부분 문자열이어야 한다.
if not isinstance(span, str) or not span.strip() or span.strip() not in text:
LOG.w(f"[InputInterpreter] 검증 실패: price_text={span!r} 가 원문에 없음")
return None
price = parse_korean_price(span.strip()) # 숫자 계산은 결정론 파서가
if price is None:
LOG.w(f"[InputInterpreter] 검증 실패: 가격 해석 불가 span={span!r}")
return None
return InterpretedInput(kind="price", value=str(int(price)), source=span.strip())
return None # unknown → 원문 폴백(엔진 재질문)
@@ -0,0 +1,188 @@
"""MentGenerator — 자율 협상 행동을 LLM 이 자연어 멘트로 표현 (v2: 행동은 RL, 문장은 LLM).
역할 분리(안전 설계):
- 무엇을 말할지(수락/역제안 금액/압박 전략/결렬)는 RL 정책이 결정 — LLM 은 표현만 담당.
- 가드레일: 역제안 멘트에 제안 금액이 정확히 포함되지 않으면 폐기, 예외/미설정 시 None
→ 호출부(ChatService)가 기존 템플릿 멘트로 폴백한다. LLM 이 죽어도 협상은 계속된다.
설정: config.local.toml [OpenAIConfig] (Gemini 는 OpenAI 호환 base_url 로 접속).
비활성화: AUTONOMY_LLM=0.
"""
import asyncio
import os
import re
from typing import Optional
from common.logger import LOG
from negotiation.profiling.config import LlmCredentials
_STRATEGY_TONE = {
1: "경쟁 압박형 — 복수 공급처와 비교 검토 중임을 암시하며 긴장감을 준다",
2: "수용 공감형 — 상대 제안의 취지에 공감하며 부드럽게 조정을 요청한다",
3: "기준 고수형 — 내부 산정 기준과 목표가를 근거로 원칙을 지킨다",
4: "협력 파트너형 — 장기 파트너십과 후속 거래 확대 가능성을 강조한다",
}
_SYSTEM = """너는 대기업 구매팀의 가격 협상 챗봇이다. 주어진 '전달 의도'를 자연스러운 한국어 협상 멘트로 바꿔 쓴다.
규칙 (위반 시 출력은 폐기된다):
- 1~3문장, 정중하되 간결하게. 출력은 멘트 텍스트만 (따옴표·설명 없이).
- 금액 숫자는 주어진 그대로 정확히 포함하고 단위는 '원'을 쓴다. 주어지지 않은 숫자·비율을 절대 만들지 않는다.
- 지정된 '화법' 전략 안에서만 말한다. 그 외의 협상 전술(물량·기간 약속, 조건 교환, 거래 연계,
독점 제안, 시장가·최저가 주장, 할인 약속 등)을 지어내지 않는다.
- 회사의 정책·사실을 단정하지 않는다. 주어진 의도에 없는 정보는 말하지 않는다.
- 상대는 협력사(판매자)이고 우리는 구매자다."""
# 생성문 금지어 — 승인되지 않은 커밋/주장 계열. 걸리면 템플릿 폴백(협상은 계속).
_FORBIDDEN = ("보장", "물량", "독점", "무조건", "최저가", "시장 가격", "시장가", "계약 기간",
"법적", "위약", "%")
def _configured() -> bool:
if os.getenv("AUTONOMY_LLM", "1").lower() in ("0", "false", "no"):
return False
try:
return LlmCredentials.from_config().is_configured()
except Exception:
return False
def _digits(s) -> str:
return re.sub(r"[^\d]", "", str(s))
def _history_hints(ctx: dict) -> str:
"""대화 기억 힌트 — 무기억 생성이 '매번 같은 멘트'를 만들던 문제의 해법.
① 직전 우리 제안이 거절된 사실과 이번 제안과의 관계(양보/입장유지)를 짚게 하고
② 직전 봇 멘트를 보여주며 같은 문장 구조·표현의 반복을 금지한다."""
hints = []
prev = ctx.get("autonomy_prev")
if prev and prev.get("kind") == "counter":
anchor, target = float(ctx.get("anchor_price") or 0), float(ctx.get("target_price") or 0)
prev_offer = int(round(anchor + float(prev.get("q", 0.0)) * max(target - anchor, 1.0)))
cur_offer = int(ctx.get("autonomy_offer") or 0)
if cur_offer > prev_offer:
hints.append(f"참고: 직전 라운드에 우리가 {prev_offer:,}원을 제안했으나 거절당했고, "
f"이번에는 {cur_offer - prev_offer:,}원 더 양보한 제안이다. 이 진전을 자연스럽게 짚어라.")
elif cur_offer == prev_offer and cur_offer > 0:
hints.append(f"참고: 직전에 제안한 {prev_offer:,}원을 거절당했지만 같은 금액을 유지한다. "
f"입장이 확고함을 정중하게 전하라.")
elif prev_offer > 0:
hints.append(f"참고: 직전 제안({prev_offer:,}원)이 거절된 뒤의 재제안이다.")
last_ment = ctx.get("autonomy_last_ment")
if last_ment:
hints.append(f'직전 봇 멘트: "{last_ment}" — 이와 같은 문장 구조·표현을 반복하지 말고 다르게 써라.')
return " ".join(hints)
def _prompt_for(step: str, ctx: dict) -> Optional[str]:
price = int(ctx.get("input_price") or 0)
rnd = ctx.get("round", 1)
if step in ("자율_역제안", "자율_최종제안"):
offer = int(ctx.get("autonomy_offer") or 0)
if offer <= 0:
return None
strategy = int((ctx.get("autonomy_last") or {}).get("s") or 3)
tone = _STRATEGY_TONE.get(strategy, _STRATEGY_TONE[3])
final = ("이번이 우리가 제시할 수 있는 마지막 제안이며, 거절하시면 이번 협상은 종료됨을 "
"분명하되 정중하게 밝혀라. " if step == "자율_최종제안" else "")
return (f"상황: 협력사가 {price:,}원을 제시했다(협상 {rnd}라운드). "
f"전달 의도: 우리는 **{offer:,}원**이면 즉시 수락하고 우선협상 대상으로 확정할 수 있다 — "
f"이 핵심 의미는 유지하되 문장 표현은 자유롭게 새로 써라. {final}화법: {tone}. "
f"{_history_hints(ctx)} 마지막에 수락 여부를 물어라.")
if step.startswith("자율_압박_"):
strategy = int(step.rsplit("_", 1)[1])
tone = _STRATEGY_TONE.get(strategy, _STRATEGY_TONE[3])
# 주의: 목표가는 프롬프트에 넣지 않는다 — 압박 중 목표가 노출은 우리 상한을 까는 것
# (상대가 그 밑으로 내려올 이유가 사라진다). 숫자 커밋은 역제안/최종제안에서만.
base = (f"상황: 협력사가 {price:,}원을 제시했다(협상 {rnd}라운드). "
f"전달 의도: 어떤 금액도 언급하지 말고(내부 기준·목표가 숫자 금지), 제시가와 우리 기준의 "
f"거리가 있다는 취지로 가격 재제안을 요청한다. 화법: {tone}. "
f"{_history_hints(ctx)}")
# 시장가 근거 (구 NGC-008 의 자율 버전): 수집된 인터넷최저가가 실재하고 제시가가 그보다
# 높을 때만 사실 근거로 인용을 허용한다 — 미수집 품목에서 지어내는 주장은 가드가 차단.
if _market_evidence(ctx):
il = int(ctx["internet_lowest_price"])
base += (f" 참고 사실(인용 허용되는 유일한 금액): 동일 품목의 인터넷 최저가가 {il:,}원으로 "
f"확인된다. 현재 제시가가 이보다 높다는 점을 근거로 조정 여지를 정중히 짚어라.")
return base
return None
def _market_evidence(ctx: dict) -> bool:
"""시장가 근거 인용 가능 조건: 인터넷최저가 수집됨 + 제시가가 그보다 높음."""
il = int(ctx.get("internet_lowest_price") or 0)
return il > 0 and float(ctx.get("input_price") or 0) > il
def _allowed_amounts(ctx: dict) -> set:
"""멘트에 등장해도 되는 숫자 집합 — 우리가 프롬프트로 준 값들뿐. 이 밖의 금액 = 할루시네이션."""
# 목표가는 화이트리스트에 없다 — 압박 멘트가 목표가를 새면(상한 노출) 즉시 폐기된다.
# 역제안·최종제안의 제안가(autonomy_offer)가 목표가와 같은 경우만 그 값으로 허용된다.
anchor, target = float(ctx.get("anchor_price") or 0), float(ctx.get("target_price") or 0)
out = {int(ctx.get("input_price") or 0), int(ctx.get("autonomy_offer") or 0),
int(ctx.get("round") or 0)}
if _market_evidence(ctx):
out.add(int(ctx["internet_lowest_price"])) # 시장가 근거 인용 시 그 수치만 허용
prev = ctx.get("autonomy_prev")
if prev and prev.get("kind") == "counter":
prev_offer = int(round(anchor + float(prev.get("q", 0.0)) * max(target - anchor, 1.0)))
out |= {prev_offer, abs(int(ctx.get("autonomy_offer") or 0) - prev_offer)}
return {str(v) for v in out if v}
def _guard(step: str, ctx: dict, text: str) -> bool:
"""LLM 출력 검증(할루시네이션 차단) — 실패 시 템플릿 폴백.
① 길이/문장 완결 ② 금지어(승인 안 된 커밋·주장) ③ 숫자 화이트리스트: 멘트의 모든
3자리+ 숫자는 우리가 준 값(제시가·제안가·목표가·직전제안가)이어야 한다 — 지어낸 금액 즉시 폐기.
④ 역제안은 제안 금액 포함 필수."""
if not text or len(text) < 10 or len(text) > 600:
return False
if not text.rstrip().endswith(("다.", "요.", "요?", "까?", "니까?", ".", "?")):
return False # 문장 중간 잘림(thinking 토큰에 한도 소진 등) → 템플릿 폴백
forbidden = _FORBIDDEN
if _market_evidence(ctx):
# 시장가 근거가 정당한 턴에는 '최저가/시장가' 언급을 허용 (수치는 아래 화이트리스트가 검증).
forbidden = tuple(w for w in _FORBIDDEN if w not in ("최저가", "시장가", "시장 가격"))
if any(w in text for w in forbidden):
return False
allowed = _allowed_amounts(ctx)
for num in re.findall(r"\d{3,}", text.replace(",", "")):
if num not in allowed:
return False # 프롬프트에 없던 금액 생성 = 할루시네이션
if step in ("자율_역제안", "자율_최종제안"):
return _digits(ctx.get("autonomy_offer")) in _digits(text)
return True
async def generate(step: str, ctx: dict) -> Optional[str]:
"""자율 스텝 멘트 생성. 미설정/실패/검증불통과 → None (호출부 템플릿 유지)."""
if not _configured():
return None
prompt = _prompt_for(step, ctx)
if prompt is None:
return None
try:
from negotiation.profiling.infra.llm_adapter import chat_complete
# openai SDK 는 동기 — 이벤트루프 블로킹 방지 위해 스레드로 넘긴다.
# max_tokens 넉넉히 — Gemini 2.5 계열은 thinking 토큰이 한도에 포함돼 짧으면 본문이 잘린다.
# 시간 상한: backend→agent 타임아웃(10s)보다 확실히 짧아야 한다 — 초과 시 템플릿 폴백으로
# 협상은 즉시 계속된다("협상 응답 지연" 토스트 방지). LLM_TIMEOUT_S 로 조절.
text = await asyncio.wait_for(
asyncio.to_thread(
chat_complete,
[{"role": "system", "content": _SYSTEM}, {"role": "user", "content": prompt}],
None, False, 0.9, 2048, # temperature 0.9 — 표현 다양성 (의미는 프롬프트 가드)
),
timeout=float(os.getenv("LLM_TIMEOUT_S", "6")),
)
text = (text or "").strip().strip('"')
if _guard(step, ctx, text):
return text
LOG.w(f"[MentGenerator] 가드레일 불통과 → 템플릿 폴백 (step={step})")
return None
except Exception as ex:
LOG.e_no_callstack(f"[MentGenerator] LLM 실패 → 템플릿 폴백: {ex}")
return None
@@ -27,8 +27,7 @@ _ONE_TO_ONE_QT_TYPES = (1, 3)
# 유통 코드: SupplierType(1=distribution 유통, 2=manufacture 제조, 3=sole_agency 총판) # 유통 코드: SupplierType(1=distribution 유통, 2=manufacture 제조, 3=sole_agency 총판)
# → 테넌트 code_map 키(A/B/C). 제조→A, 총판→B, 유통→C (0=none/NULL 은 미지정 → 호출부 기본값). # → 테넌트 code_map 키(A/B/C). 제조→A, 총판→B, 유통→C (0=none/NULL 은 미지정 → 호출부 기본값).
# 소스 우선순위: partner.supplier_items.supply_type(이 협력사×이 상품 매핑, 2026-07-07 신설) # 소스: partner.supplier_items.supply_type(이 협력사×이 상품 매핑).
# → quotations.supplier_type(재견적 1:1 견적 기록 — 매핑 부재 시 폴백).
_SUPPLIER_TYPE_TO_CODE = {2: "A", 3: "B", 1: "C"} _SUPPLIER_TYPE_TO_CODE = {2: "A", 3: "B", 1: "C"}
@@ -40,17 +39,30 @@ class NegotiationDbContext:
target_price: int # 목표 매입가(원) — sessions.target_price target_price: int # 목표 매입가(원) — sessions.target_price
anchor_price: int # 앵커링가 — sessions.anchoring_price(생성 시 박제). 없으면 target(무할인 폴백) anchor_price: int # 앵커링가 — sessions.anchoring_price(생성 시 박제). 없으면 target(무할인 폴백)
item_price: int # 기존 공급가(품목 기준가, items.price) — 인하율 멘트용. 없으면 0 item_price: int # 기존 공급가(품목 기준가, items.price) — 인하율 멘트용. 없으면 0
partner_name: Optional[str] # 협력사명(suppliers.name) — 카드 {partner_name} 치환용. 없으면 None
product_name: Optional[str] # 상품명(items.name) — 카드 {product_name} 치환용. 없으면 None
partner_type: PartnerType # 상품에 연결된 협력사 수(supplier_items 매핑, 없으면 세션 이력) → NONE/SINGLE/MULTIPLE partner_type: PartnerType # 상품에 연결된 협력사 수(supplier_items 매핑, 없으면 세션 이력) → NONE/SINGLE/MULTIPLE
revenue_amount: float # 매출액(원) — suppliers.total_revenue(KTC 미러). 없으면 0 revenue_amount: float # 매출액(원) — suppliers.total_revenue(KTC 미러). 없으면 0
distribution_code: Optional[str] # 유통 코드(A/B/C) — supplier_items.supply_type → quotations.supplier_type. 미지정 시 None distribution_code: Optional[str] # 유통 코드(A/B/C) — supplier_items.supply_type. 미지정 시 None
selected_nego_card_numbers: list[str] # 견적 생성 시 선택된 일반 협상카드 번호(card.nego_cards.number)
selected_wild_card_numbers: list[str] # 견적 생성 시 선택된 와일드카드 번호(card.wild_cards.number)
# ---- 자율 에이전트 v3 상태 특징 소스 (없으면 0/None — 특징은 중립 기본값으로 폴백) ----
internet_lowest_price: int = 0 # items.internet_lowest_price (미수집 0)
deadline_end_ts: Optional[float] = None # 견적 마감(epoch 초) — quotations.end_time
deadline_total_s: Optional[float] = None # 협상 전체 기간(초) — end−start
hist_n: int = 0 # 이 협력사와의 과거 협상 횟수
hist_success: Optional[float] = None # 과거 성사율 (이력 없으면 None)
hist_settle_ratio: Optional[float] = None # 과거 평균 타결가/목표가 (성사 이력 없으면 None)
class NegotiationContextLoader: class NegotiationContextLoader:
def __init__(self, crud: Optional[INegoContextCRUD] = None): def __init__(self, crud: Optional[INegoContextCRUD] = None):
self.crud: INegoContextCRUD = crud or NegoContextCRUD() self.crud: INegoContextCRUD = crud or NegoContextCRUD()
async def load(self, session_id: Optional[str]) -> Optional[NegotiationDbContext]: async def load(self, session_id: Optional[str],
"""session_id 로 협상 컨텍스트 조회. 행이 없거나 조회 실패 시 None(호출부 기본값 폴백).""" company_id: Optional[str] = None) -> Optional[NegotiationDbContext]:
"""session_id 로 협상 컨텍스트 조회. 행이 없거나 조회 실패 시 None(호출부 기본값 폴백).
company_id 는 협력사 이력 집계(experience_logs 테넌트 스코프)용 — 없으면 이력 특징 생략."""
if not session_id: if not session_id:
return None return None
try: try:
@@ -76,15 +88,17 @@ class NegotiationContextLoader:
# 매출액: 협력사 총매출(KTC total_revenue 미러). 미기재 시 0 → 호출부 기본값. # 매출액: 협력사 총매출(KTC total_revenue 미러). 미기재 시 0 → 호출부 기본값.
_, revenue_amount = await self.crud.get_supplier_total_revenue(s, supplier_id) _, revenue_amount = await self.crud.get_supplier_total_revenue(s, supplier_id)
# 유통 코드: 이 협력사×이 상품의 공급 방식(supplier_items.supply_type) 우선. # 유통 코드: 이 협력사×이 상품의 공급 방식(supplier_items.supply_type).
# 매핑이 없으면 견적 기록(quotations.supplier_type) 폴백. 미지정 시 None → 호출부 기본값. # 매핑이 없거나 미지정이면 None → 호출부 기본값.
_, supplier_type = await self.crud.get_supply_type(s, supplier_id, item_id) _, supplier_type = await self.crud.get_supply_type(s, supplier_id, item_id)
if not supplier_type:
_, supplier_type = await self.crud.get_quotation_supplier_type(s, quotation_id)
# 기존 공급가(품목 기준가) — 없으면 0(인하율 멘트 미표시). # 기존 공급가(품목 기준가) — 없으면 0(인하율 멘트 미표시).
_, item_price = await self.crud.get_item_price(s, item_id) _, item_price = await self.crud.get_item_price(s, item_id)
# 카드 스크립트 치환용 이름 — 협력사명/상품명. 없으면 None(호출부 기본값 폴백).
_, partner_name = await self.crud.get_supplier_name(s, supplier_id)
_, product_name = await self.crud.get_item_name(s, item_id)
# 파트너사 유형: 상품에 연결된 협력사 수 — supplier_items 매핑(등록 기준) 우선. # 파트너사 유형: 상품에 연결된 협력사 수 — supplier_items 매핑(등록 기준) 우선.
# 매핑이 아직 없으면 협상 세션 이력 기준 폴백(더미보다 항상 낫다). 실패 시 SINGLE. # 매핑이 아직 없으면 협상 세션 이력 기준 폴백(더미보다 항상 낫다). 실패 시 SINGLE.
err, supplier_count = await self.crud.count_item_suppliers(s, item_id) err, supplier_count = await self.crud.count_item_suppliers(s, item_id)
@@ -93,14 +107,44 @@ class NegotiationContextLoader:
if err != ErrorType.SUCCESS: if err != ErrorType.SUCCESS:
supplier_count = 1 supplier_count = 1
# 견적 생성 모달에서 고른 카드셋. 값이 없으면 운영 DB 기준으로 "선택 카드 없음"이다.
# 데모/직접호출 경로(DB context 없음)만 ChatService 에서 기존 기본 카드셋으로 폴백한다.
_, selected_cards = await self.crud.get_quotation_card_numbers(s, quotation_id)
selected_nego_cards, selected_wild_cards = selected_cards
# ---- 자율 에이전트 v3 특징 소스 (조회 실패는 전부 중립 폴백 — 협상은 계속돼야 한다) ----
_, internet_lowest = await self.crud.get_item_internet_lowest(s, item_id)
_, period = await self.crud.get_quotation_period(s, quotation_id)
deadline_end_ts = deadline_total_s = None
if period and period[1] is not None:
end_ts = period[1].timestamp()
start_ts = period[0].timestamp() if period[0] is not None else None
total = (end_ts - start_ts) if start_ts else None
if total and total > 0:
deadline_end_ts, deadline_total_s = end_ts, total
hist_n, hist_success, hist_settle = 0, None, None
if company_id:
_, hist = await self.crud.get_supplier_history(s, company_id, supplier_id, sid)
hist_n, hist_success, hist_settle = hist
return NegotiationDbContext( return NegotiationDbContext(
rq_type="재협상" if int(qt_type) in _ONE_TO_ONE_QT_TYPES else "재견적", rq_type="재협상" if int(qt_type) in _ONE_TO_ONE_QT_TYPES else "재견적",
target_price=target, target_price=target,
anchor_price=anchor, anchor_price=anchor,
item_price=item_price, item_price=item_price,
partner_name=partner_name,
product_name=product_name,
partner_type=PartnerType.from_count(supplier_count), partner_type=PartnerType.from_count(supplier_count),
revenue_amount=revenue_amount, revenue_amount=revenue_amount,
distribution_code=_SUPPLIER_TYPE_TO_CODE.get(supplier_type) if supplier_type else None, distribution_code=_SUPPLIER_TYPE_TO_CODE.get(supplier_type) if supplier_type else None,
selected_nego_card_numbers=selected_nego_cards,
selected_wild_card_numbers=selected_wild_cards,
internet_lowest_price=internet_lowest,
deadline_end_ts=deadline_end_ts,
deadline_total_s=deadline_total_s,
hist_n=hist_n,
hist_success=hist_success,
hist_settle_ratio=hist_settle,
) )
try: try:
@@ -0,0 +1,144 @@
"""ScriptNaturalizer — 협상 카드 멘트를 LLM 으로 상황에 맞게 자연화 (Phase 2 표현층).
원칙: "숫자와 결정은 결정론이, 말은 LLM 이" —
- 입력은 **치환 전 템플릿**({input_price} 등 placeholder 유지 상태). LLM 은 숫자를 절대 만들지 않는다.
- 상황(라운드·가격구간·수용률)은 **정성 라벨**로만 전달(수치 미노출 → 숫자 환각 원천 차단).
- 검증 실패/타임아웃/미설정 시 None → 호출부가 원본 템플릿 폴백(협상은 절대 안 멈춤).
검증(ScriptVerifier 철학의 플레인 텍스트판):
① {placeholder} 집합이 원본과 정확히 동일(누락·추가 금지)
② 원본에 없던 숫자 등장 금지(가격 환각 차단)
③ 비어있지 않고 길이 폭주 금지
게이트: tenant llm.enabled(기본 false) + 전역 LLM 자격증명(config.local.toml [OpenAIConfig]
또는 OPENAI_API_KEY env). 호출은 스레드로 넘겨 이벤트루프 비차단 + 타임아웃.
"""
import asyncio
import json
import re
from typing import Any, Callable, Dict, List, Optional
from common.logger import LOG
from negotiation.profiling.config import LlmCredentials
_PLACEHOLDER_RE = re.compile(r"\{(\w+)\}")
_DIGITS_RE = re.compile(r"\d+")
# 강조 마커(negodata Slate 편집 정본) — 고객사가 지정한 표시라 자연화가 보존해야 한다.
# 색 마커 {{강조|..}} {{안내|..}} 는 여는 토큰 개수로, 굵게/밑줄은 구분자 개수(짝수=쌍)로 센다.
_COLOR_OPEN_RE = re.compile(r"\{\{(강조|안내)\|")
# 카드 메타 코드 → 프롬프트 라벨 (init-data.sql CardTone/CardStrategyType 정의와 동일)
_TONE_LABEL = {1: "강경", 2: "정중", 3: "우호", 4: "중립", 5: "단호"}
_STRATEGY_LABEL = {1: "경쟁", 2: "수용", 3: "고수", 4: "협력", 5: "선점", 6: "종결"}
_SYSTEM = """너는 B2B 구매 협상 챗봇의 문장 작성기다. 주어진 협상 카드 멘트 '템플릿'을 협상 상황에 맞게 자연스럽게 다시 쓴다.
규칙 (하나라도 어기면 출력은 폐기된다):
- {변수명} 치환자는 철자 그대로 유지한다. 추가/삭제/변경 금지.
- 숫자를 직접 쓰지 마라. 가격·비율 등 모든 수치는 치환자로만 표현한다.
- 강조 마커(**굵게** __밑줄__ {{강조|...}} {{안내|...}})는 **개수와 종류를 그대로 유지**한다.
고객사가 지정한 강조 표시이므로 삭제·추가·종류변경 금지. 감싼 문구는 자연스럽게 바꿔도 되지만
강조된 구절 수만큼 같은 마커로 반드시 다시 감싼다(예: **굵게** 2개면 결과도 **…** 2쌍).
- 새로운 약속·할인 조건·법적 표현을 만들지 마라. 원 템플릿의 협상 의도(전술)는 유지한다.
- 한국어 존댓말, 2~5문장, 채팅 말풍선에 어울리게 간결히.
- 출력은 JSON 하나만: {"script": "다시 쓴 멘트"}"""
def _default_llm_call(messages: List[dict]) -> dict:
"""기본 LLM 호출(동기) — 전역 자격증명으로 chat_json. 테스트에서 monkeypatch 지점."""
from negotiation.profiling.infra.llm_adapter import chat_json
return chat_json(messages, temperature=0.5, max_tokens=600)
class ScriptNaturalizer:
def __init__(self, llm_call: Optional[Callable[[List[dict]], dict]] = None,
timeout_seconds: float = 8.0):
self._llm_call = llm_call or _default_llm_call
self._timeout = timeout_seconds
@staticmethod
def available() -> bool:
"""전역 LLM 자격증명이 설정돼 있는가 (테넌트 enabled 게이트는 호출부 몫)."""
return LlmCredentials.from_config().is_configured()
async def naturalize(self, template: str, *, situation: Optional[Dict[str, Any]] = None,
tone: Optional[int] = None, strategy: Optional[int] = None) -> Optional[str]:
"""템플릿(치환 전)을 상황 맞춤 문장으로 재작성. 실패/검증불통과 시 None(호출부 폴백)."""
if not template or not template.strip():
return None
ctx = dict(situation or {})
if tone in _TONE_LABEL:
ctx["톤"] = _TONE_LABEL[tone]
if strategy in _STRATEGY_LABEL:
ctx["전략"] = _STRATEGY_LABEL[strategy]
messages = [
{"role": "system", "content": _SYSTEM},
{"role": "user", "content":
"템플릿:\n" + template +
"\n\n협상 상황:\n" + json.dumps(ctx, ensure_ascii=False) +
'\n\n규칙대로 다시 써서 {"script": "..."} 로만 출력.'},
]
try:
result = await asyncio.wait_for(asyncio.to_thread(self._llm_call, messages), self._timeout)
except Exception as ex: # 타임아웃 포함 — 폴백
LOG.w(f"[ScriptNaturalizer] LLM 호출 실패(폴백): {ex}")
return None
text = result.get("script") if isinstance(result, dict) else None
if not isinstance(text, str) or not text.strip():
return None
return text if self._verify(template, text) else None
# ---- 검증 ----------------------------------------------------------
@staticmethod
def _verify(template: str, rewritten: str) -> bool:
orig = set(_PLACEHOLDER_RE.findall(template))
new = set(_PLACEHOLDER_RE.findall(rewritten))
if orig != new:
LOG.w(f"[ScriptNaturalizer] 검증 실패: 치환자 불일치 (누락={orig - new}, 추가={new - orig})")
return False
# 원본에 없던 숫자 금지 — 가격/비율 환각 차단 (수치는 치환자로만).
orig_digits = set(_DIGITS_RE.findall(template))
new_digits = set(_DIGITS_RE.findall(rewritten)) - orig_digits
if new_digits:
LOG.w(f"[ScriptNaturalizer] 검증 실패: 새 숫자 등장 {new_digits}")
return False
if len(rewritten) > max(600, len(template) * 4):
LOG.w("[ScriptNaturalizer] 검증 실패: 길이 폭주")
return False
# 강조 마커 보존 — 고객사가 지정한 볼드/밑줄/색을 LLM 이 떨어뜨리면 폐기(원본 폴백).
# 굵게/밑줄: 구분자 총 개수가 같아야 짝(쌍)이 보존됨. 색: 여는 토큰 개수 동일.
if (template.count("**") != rewritten.count("**")
or template.count("__") != rewritten.count("__")
or len(_COLOR_OPEN_RE.findall(template)) != len(_COLOR_OPEN_RE.findall(rewritten))):
LOG.w("[ScriptNaturalizer] 검증 실패: 강조 마커 불일치(볼드/색 소실) → 원본 유지")
return False
return True
def build_situation(context: Dict[str, Any]) -> Dict[str, Any]:
"""세션 컨텍스트 → 정성 상황 라벨 (수치 미노출 — 숫자 환각 차단의 핵심).
가격구간: 제시가 vs 앵커/목표 관계, 라운드: 협상 진행 단계, 인하 진행: 기존 공급가 대비.
"""
out: Dict[str, Any] = {}
rnd = context.get("round") or 0
if rnd:
out["라운드"] = "첫 제안" if rnd <= 1 else ("초반 조율" if rnd == 2 else "막바지 조율")
price = context.get("input_price") or 0
anchor = context.get("anchor_price") or 0
target = context.get("target_price") or 0
if price and anchor and target:
if price <= anchor:
out["가격구간"] = "목표 범위 도달(마무리 국면)"
elif price <= target:
out["가격구간"] = "목표 범위 근접(조율 국면)"
else:
out["가격구간"] = "목표 상회(추가 인하 필요)"
base = context.get("item_price") or 0
if base and price:
rate = (base - price) / base
out["인하 진행"] = "아직 미미" if rate < 0.01 else ("일부 진행" if rate < 0.05 else "상당히 진행")
return out
@@ -38,6 +38,11 @@ class ScriptRepository:
# 카드 멘트 DB 소스(backoffice_db). file 모드면 미사용. # 카드 멘트 DB 소스(backoffice_db). file 모드면 미사용.
self._card_repo: ICardScriptRepository = card_repo or CardScriptDbRepository() self._card_repo: ICardScriptRepository = card_repo or CardScriptDbRepository()
@property
def config(self) -> TenantConfig:
"""테넌트 config 노출 — ChatEngine 이 협상 규칙(negotiation.*)을 읽는다."""
return self._config
# ---- 경로 해석 (_base 폴백) --------------------------------------- # ---- 경로 해석 (_base 폴백) ---------------------------------------
def _resource_path(self, filename: str) -> Optional[str]: def _resource_path(self, filename: str) -> Optional[str]:
scripts_dir = self._config.resources.scripts_dir scripts_dir = self._config.resources.scripts_dir
@@ -89,24 +94,47 @@ class ScriptRepository:
return None return None
return self.format_script(text, variables) return self.format_script(text, variables)
async def resolve_card_script(self, action_id: int, card_id: Optional[str], async def resolve_card_template(self, action_id: int, card_id: Optional[str],
variables: Optional[Dict[str, Any]] = None) -> Optional[str]: prefer_db: bool = False) -> tuple:
"""카드 멘트 해석. cards.source_type == 'backoffice_db' 면 card.nego_cards.script(DB)를 """카드 멘트의 **치환 전 템플릿**과 메타를 해석 → (template, tone, strategy_type).
우선 조회하고, 없거나 file 모드면 scripts_cards.json(파일) 폴백. 변수 치환 후 반환.
DB 멘트는 백오피스(negodata)가 편집한 정본이라 파일보다 우선한다. 마커(**굵게** 등)가 cards.source_type == 'backoffice_db' 면 card.nego_cards(DB, tone/strategy 포함) 우선,
섞여 있어도 agent 는 불투명 텍스트로 취급 — 표현 렌더는 프론트 소유. 없거나 file 모드면 scripts_cards.json(파일, 메타 None) 폴백. 둘 다 없으면 (None, None, None).
치환 전 템플릿을 그대로 주는 이유: LLM 표현층이 placeholder 를 유지한 채 재작성한 뒤
format_script 로 치환해야 숫자를 LLM 이 절대 만지지 않기 때문.
""" """
if self._config.cards.source_type == _CARD_SOURCE_DB and card_id: if (prefer_db or self._config.cards.source_type == _CARD_SOURCE_DB) and card_id:
db_text = await self._fetch_card_script_db(card_id) card = await self._fetch_card_db(card_id)
if db_text: if card:
return self.format_script(db_text, variables) return card # (script, tone, strategy)
return self.card_script(action_id, variables) # 파일 폴백 return self.card_scripts().get(str(action_id)), None, None # 파일 폴백(메타 없음)
async def _fetch_card_script_db(self, card_id: str) -> Optional[str]: async def resolve_card_script(self, action_id: int, card_id: Optional[str],
variables: Optional[Dict[str, Any]] = None,
prefer_db: bool = False) -> Optional[str]:
"""카드 멘트 해석(템플릿 + 변수 치환). DB(정본) 우선 → 파일 폴백. 마커는 불투명 텍스트."""
template, _, _ = await self.resolve_card_template(action_id, card_id, prefer_db=prefer_db)
if not template:
return None
return self.format_script(template, variables)
async def resolve_wild_card_template(self, number: str) -> Optional[str]:
"""선택형 와일드카드(WC-*) 멘트 템플릿 — card.wild_cards(DB, negodata 편집 정본) 조회.
없거나 DB 불가면 None(호출부가 스텝 기본 멘트 폴백)."""
async def _q(s): async def _q(s):
_, text = await self._card_repo.get_script_by_number(s, card_id) _, script = await self._card_repo.get_wild_card_by_number(s, number)
return text return script
try:
return await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
except Exception as ex:
LOG.e_no_callstack(f"[ScriptRepository] 와일드카드 멘트 DB 조회 실패 number={number}: {ex}")
return None
async def _fetch_card_db(self, card_id: str) -> Optional[tuple]:
async def _q(s):
_, card = await self._card_repo.get_card_by_number(s, card_id)
return card
try: try:
return await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q) return await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
@@ -0,0 +1,85 @@
"""완전 자율 협상 행동 공간 (numpy 전용 — 학습(tools)과 서빙(policy)이 공유).
카드 카탈로그 대신 행동의 '의미'만 남긴다:
ACCEPT 현재 제시가로 타결
WALK 협상 결렬 선언
COUNTER(q, s) "C원이면 수락" 역제안. C = anchor + q×(target−anchor), s = 화법 전략
PRESS(s) 설득 압박 (카드의 일반화 — 전략 1경쟁/2수용/3고수/4협력)
특징 벡터(ACTION_DIM=8) = 유형 one-hot(3) + 가격 위치(1) + 전략 one-hot(4).
ScoreNet(상태 + 행동특징) → 스칼라 점수로 후보 30개를 채점해 argmax 한다.
"""
from dataclasses import dataclass
import numpy as np
COUNTER_GRID = [-0.05, 0.0, 0.25, 0.5, 0.75, 1.0] # C = anchor + q×(target−anchor)
ACTION_DIM = 3 + 1 + 4 + 1 # 유형(3) + 위치(1) + 전략(4) + 컷폭(1: 현 제시가 대비 인하 요구율)
# 자율 전용 추가 상태 (v3):
# [0] 직전 역제안 존재(0/1) [1] 직전 역제안 위치 q ← 에피소드 기억(같은 숫자 반복 방지)
# [2] 마감 잔여율(남은시간/전체, 미상 0.5) ← 견적 마감(quotations.end_time)
# [3] 과거 협상 횟수 min(n,5)/5 [4] 과거 성사율(미상 0.5)
# [5] 과거 평균 타결수준 norm((타결가/목표가−0.8)/0.4, 미상 0.5) ← 이 협력사와의 이력(experience_logs)
# [6] 인터넷최저가 갭 clip((최저가−앵커)/앵커/0.1, ±1, 미상 0) ← 숨은 하한가의 관측 가능한 힌트
# 특징은 학습 시뮬에도 동일하게 존재해야 한다(train_full_autonomy 가 대응물을 생성).
EXTRA_STATE_DIM = 7
def extra_state(last_kind: str = "", last_q: float = 0.0, deadline: float = 0.5,
hist_n: float = 0.0, hist_success: float = 0.5, hist_settle: float = 0.5,
internet_gap: float = 0.0) -> np.ndarray:
has_counter = 1.0 if last_kind == "counter" else 0.0
return np.array([
has_counter,
float(np.clip(last_q, -1.0, 1.0)) * has_counter,
float(np.clip(deadline, 0.0, 1.0)),
float(np.clip(hist_n, 0.0, 1.0)),
float(np.clip(hist_success, 0.0, 1.0)),
float(np.clip(hist_settle, 0.0, 1.0)),
float(np.clip(internet_gap, -1.0, 1.0)),
], dtype=np.float32)
def settle_norm(avg_settle_ratio: float) -> float:
"""평균 (타결가/목표가) → 0~1 정규화 (0.8→0, 1.0→0.5, 1.2→1)."""
return float(np.clip((avg_settle_ratio - 0.8) / 0.4, 0.0, 1.0))
def internet_gap_feat(internet_lowest: float, anchor: float) -> float:
"""인터넷최저가의 앵커 대비 갭 (±10% 스케일). 최저가 없으면 0을 쓴다."""
if not internet_lowest or anchor <= 0:
return 0.0
return float(np.clip((internet_lowest - anchor) / anchor / 0.1, -1.0, 1.0))
@dataclass(frozen=True)
class Action:
kind: str # accept | walk | counter | press
counter_q: float = 0.0 # counter 위치 (anchor~target 스팬 비율)
strategy: int = 0 # press/counter 의 화법 전략 (1~4, 0=없음)
def feat(self, price_pos: float, cut: float = 0.0) -> np.ndarray:
"""cut: 이 행동이 요구하는 인하폭 (현 제시가 대비, counter 만 >0) — 대형컷의 무례함을
정책이 지각하게 한다. 갭이 크면 역제안 대신 압박이 낫다는 걸 배우는 근거 특징."""
t = {"accept": [1, 0, 0], "walk": [0, 1, 0]}.get(self.kind, [0, 0, 1])
pos = price_pos if self.kind == "accept" else self.counter_q
s = np.zeros(4, dtype=np.float32)
if self.strategy:
s[self.strategy - 1] = 1.0
return np.concatenate([np.array(t, dtype=np.float32),
np.array([float(np.clip(pos, -1.0, 2.0)),
], dtype=np.float32), s,
np.array([float(np.clip(cut, 0.0, 1.0))], dtype=np.float32)])
def candidate_actions():
"""전 행동 후보: 수락 1 + 결렬 1 + 역제안 6×전략4 + 압박 4 = 30."""
out = [Action("accept"), Action("walk")]
out += [Action("counter", q, s) for q in COUNTER_GRID for s in (1, 2, 3, 4)]
out += [Action("press", 0.0, s) for s in (1, 2, 3, 4)]
return out
ACTIONS = candidate_actions()
+3
View File
@@ -41,6 +41,9 @@ class PolicyContext:
action_space_size: int action_space_size: int
episode: EpisodeState episode: EpisodeState
available_mask: Optional[np.ndarray] = None # None 이면 used_action_ids 로 산출 available_mask: Optional[np.ndarray] = None # None 이면 used_action_ids 로 산출
# 의도층 prior(Phase 1): 갑이 견적에서 고른 카드 순서 등 사전 선호. 방문수로 감쇠되어
# 콜드 스타트 선택만 편향하고 학습(Q)이 쌓이면 영향이 소멸한다 — Q-table 오염 없음.
prior_bonus: Optional[np.ndarray] = None
@dataclass @dataclass
@@ -0,0 +1,132 @@
"""FeatureDQNPolicy — action-as-feature DQN (Phase 2·3).
고정 슬롯 Q(s)→[11개] 대신 ScoreNet(상태벡터 + 카드임베딩) → 스칼라 점수.
결정 시 가용 카드 풀을 순회 채점해 argmax → 카드 추가/삭제/새 카드(zero-shot)에 구조 변화 없음.
협력사 특징은 상태벡터에 포함(feature_builder) → '협력사를 입력으로' 달성.
가변 행동 학습: replay 에 다음 상태의 '가용 카드 임베딩들'을 함께 저장,
target = r + γ · max_{c'∈next_avail} Q(s', c') · (1-done)
"""
import math
import random
from collections import deque
from typing import Dict, List, Optional, Tuple
import numpy as np
import torch
import torch.nn as nn
class ScoreNet(nn.Module):
"""(상태 + 카드임베딩) → 스칼라 점수."""
def __init__(self, state_dim: int, card_dim: int, hidden: int = 128):
super().__init__()
self.net = nn.Sequential(
nn.Linear(state_dim + card_dim, hidden), nn.ReLU(),
nn.Linear(hidden, hidden), nn.ReLU(),
nn.Linear(hidden, 1),
)
def forward(self, x: torch.Tensor) -> torch.Tensor: # x: [B, state+card]
return self.net(x).squeeze(-1) # [B]
class FeatureDQNPolicy:
name = "feature_dqn"
def __init__(self, state_dim: int, card_dim: int, device: str = "cpu",
lr: float = 1e-3, gamma: float = 0.95, hidden: int = 128,
eps_start: float = 1.0, eps_end: float = 0.05, eps_decay: int = 6000,
buffer_size: int = 50_000, batch_size: int = 64, target_sync: int = 500):
self.device = device
self.gamma = gamma
self.batch_size = batch_size
self.target_sync = target_sync
self.q = ScoreNet(state_dim, card_dim, hidden).to(device)
self.tgt = ScoreNet(state_dim, card_dim, hidden).to(device)
self.tgt.load_state_dict(self.q.state_dict())
self.opt = torch.optim.Adam(self.q.parameters(), lr=lr)
self.buf: deque = deque(maxlen=buffer_size)
self.eps_start, self.eps_end, self.eps_decay = eps_start, eps_end, eps_decay
self.steps = 0
self.greedy = False # 평가 모드(탐색 끔)
# ---- 탐색 스케줄 ----------------------------------------------------
def eps(self) -> float:
if self.greedy:
return 0.0
return self.eps_end + (self.eps_start - self.eps_end) * math.exp(-self.steps / self.eps_decay)
# ---- 채점/선택 -------------------------------------------------------
def scores(self, state_feat: np.ndarray, card_embs: np.ndarray) -> np.ndarray:
"""가용 카드 K개 일괄 채점. card_embs: [K, card_dim] → [K]."""
k = card_embs.shape[0]
x = np.concatenate([np.repeat(state_feat[None, :], k, axis=0), card_embs], axis=1)
with torch.no_grad():
return self.q(torch.tensor(x, device=self.device)).cpu().numpy()
def select(self, state_feat: np.ndarray, card_embs: np.ndarray) -> Tuple[int, float, float]:
"""(선택 인덱스, propensity, 선택 점수). 인덱스는 card_embs 행 기준."""
k = card_embs.shape[0]
sc = self.scores(state_feat, card_embs)
e = self.eps()
if random.random() < e:
i = random.randrange(k)
prop = e / k
else:
i = int(sc.argmax())
prop = (1.0 - e) + e / k
return i, prop, float(sc[i])
# ---- 경험/학습 -------------------------------------------------------
def remember(self, state_feat: np.ndarray, card_emb: np.ndarray, reward: float,
next_state_feat: Optional[np.ndarray], next_card_embs: Optional[np.ndarray],
done: bool):
self.buf.append((state_feat, card_emb, reward, next_state_feat, next_card_embs, done))
def train_step(self) -> Optional[float]:
if len(self.buf) < self.batch_size:
return None
batch = random.sample(self.buf, self.batch_size)
# Q(s, a_chosen)
xs = np.stack([np.concatenate([s, c]) for s, c, *_ in batch])
q_sa = self.q(torch.tensor(xs, device=self.device))
# target = r + γ·max_{c'} Q_tgt(s', c') — 가변 후보라 후보 전체를 한 번에 forward 후 세그먼트 max
rewards = torch.tensor([b[2] for b in batch], device=self.device, dtype=torch.float32)
dones = torch.tensor([float(b[5]) for b in batch], device=self.device)
next_rows, owner = [], []
for bi, (_, _, _, s2, cands, done) in enumerate(batch):
if done or s2 is None or cands is None or len(cands) == 0:
continue
for c in cands:
next_rows.append(np.concatenate([s2, c]))
owner.append(bi)
q_next_max = torch.zeros(self.batch_size, device=self.device)
if next_rows:
with torch.no_grad():
q_all = self.tgt(torch.tensor(np.stack(next_rows), device=self.device))
owner_t = torch.tensor(owner, device=self.device)
q_next_max = q_next_max.index_reduce_(0, owner_t, q_all, "amax", include_self=False)
target = rewards + self.gamma * q_next_max * (1.0 - dones)
loss = nn.functional.smooth_l1_loss(q_sa, target)
self.opt.zero_grad()
loss.backward()
self.opt.step()
self.steps += 1
if self.steps % self.target_sync == 0:
self.tgt.load_state_dict(self.q.state_dict())
return float(loss)
# ---- 저장/로드 -------------------------------------------------------
def save(self, path: str):
torch.save(self.q.state_dict(), path)
def load(self, path: str):
sd = torch.load(path, map_location=self.device)
self.q.load_state_dict(sd)
self.tgt.load_state_dict(sd)
+7 -2
View File
@@ -36,7 +36,8 @@ class UCBQTablePolicy(NegotiationPolicy):
avail = [a for a in range(ctx.action_space_size) if a not in used] avail = [a for a in range(ctx.action_space_size) if a not in used]
return avail or list(range(ctx.action_space_size)) # 다 썼으면 전체 허용 return avail or list(range(ctx.action_space_size)) # 다 썼으면 전체 허용
def _ucb_scores(self, state_index: int, available: List[int]) -> np.ndarray: def _ucb_scores(self, state_index: int, available: List[int],
prior: "np.ndarray | None" = None) -> np.ndarray:
q = self.qtable.row(state_index) q = self.qtable.row(state_index)
visits = self.qtable.visit_row(state_index) visits = self.qtable.visit_row(state_index)
total = self.qtable.state_visits(state_index) total = self.qtable.state_visits(state_index)
@@ -45,11 +46,15 @@ class UCBQTablePolicy(NegotiationPolicy):
for a in available: for a in available:
bonus = self.c * math.sqrt(ln / (visits[a] + 1e-6)) bonus = self.c * math.sqrt(ln / (visits[a] + 1e-6))
scores[a] = q[a] + bonus scores[a] = q[a] + bonus
if prior is not None:
# 의도층 prior — 방문수 감쇠: 콜드 스타트 동점(전부 Q=0·bonus=0)일 때만 순서를
# 결정하고, 학습이 쌓이면 1/(1+visits) 로 사라진다.
scores[a] += float(prior[a]) / (1.0 + visits[a])
return scores return scores
def select(self, ctx: PolicyContext) -> ActionDecision: def select(self, ctx: PolicyContext) -> ActionDecision:
available = self._available(ctx) available = self._available(ctx)
scores = self._ucb_scores(ctx.state_index, available) scores = self._ucb_scores(ctx.state_index, available, prior=ctx.prior_bonus)
action_id = int(np.argmax(scores)) action_id = int(np.argmax(scores))
n = len(available) n = len(available)
# ε-greedy 근사 propensity (greedy 액션) # ε-greedy 근사 propensity (greedy 액션)
+152
View File
@@ -0,0 +1,152 @@
"""AutonomyStore — 완전 자율 협상 정책 서빙 (룰 대체, numpy 전용).
AUTONOMY_MODE=1 이면 가격협상 판정 룰(앵커 이하 타결 / 와일드카드 존 / 라운드 상한)과
카드 선택을 전부 이 정책의 행동 결정으로 대체한다:
accept → 협상완료 (제시가 타결) walk → 협상실패
counter → "C원이면 수락" 역제안 스텝 press → 전략별 압박 멘트 스텝
행동의 유일한 유인은 보상 함수다. 남는 제한은 두 가지뿐이며 비즈니스 룰이 아니다:
- 역제안 후보 격자가 [anchor−5%span, target] 안 (행동 공간 정의)
- 세션 턴 상한(엔지니어링 타임아웃, ChatEngine._AUTONOMY_TURN_CAP)
번들: artifacts/autonomy_serving.npz (tools/export_autonomy_serving.py).
불가(플래그 꺼짐/번들 없음)면 None → 기존 룰 엔진 그대로 (즉시 롤백 경로).
"""
import os
from typing import Optional
import numpy as np
from common.logger import LOG
from negotiation.policies.autonomy_actions import (
ACTIONS, Action, extra_state, internet_gap_feat, settle_norm)
from negotiation.qtable.domain.model.snapshot import NegotiationSnapshot
from negotiation.qtable.domain.service.feature_builder import (
build_state_features, build_tenant_features)
_HERE = os.path.dirname(os.path.abspath(__file__))
BUNDLE_PATH = os.path.join(_HERE, "..", "..", "artifacts", "autonomy_serving.npz")
class AutonomyPolicy:
"""세션 컨텍스트 → 상태특징 → 행동(greedy). ChatEngine 에 decider 로 주입된다."""
name = "full_autonomy"
def __init__(self, z, reward_cfg):
self._W = (z["W0"], z["b0"], z["W1"], z["b1"], z["W2"], z["b2"])
self._state_dim = int(z["state_dim"])
self._tenant_feat = build_tenant_features(reward_cfg)
@staticmethod
def _acceptance(ctx: dict) -> float:
base = ctx.get("item_price") or ctx.get("first_offer_price") or 0
cur = ctx.get("input_price") or 0
if base <= 0 or cur <= 0:
return 0.0
return max(0.0, (base - cur) / base)
def decide(self, ctx: dict) -> Action:
"""ChatSession.context → Action. 상태 구성은 ChatService._snapshot 과 동일 규칙."""
snap = NegotiationSnapshot(
revenue_amount=ctx["revenue_amount"], distribution_code=ctx["distribution_code"],
partner_count=ctx["partner_count"], acceptance_ratio=self._acceptance(ctx),
input_price=ctx.get("input_price", ctx["anchor_price"]), anchor_price=ctx["anchor_price"],
target_price=ctx["target_price"], round_number=ctx.get("round", 0),
)
# v3 추가 특징: 직전 역제안 기억 + 마감 잔여율 + 협력사 이력 + 인터넷최저가 갭.
# 소스가 없으면 전부 중립값(0.5/0) — 학습 시뮬의 '미상' 표현과 동일해야 한다.
# 역제안 기억은 autonomy_last_counter(역제안만 갱신) — autonomy_last(마지막 행동)를 쓰면
# 사이에 낀 설득이 기억을 지워 단조 봉투가 뚫린다(counter→press→counter 철회 실버그).
# 시뮬의 last_kind/last_q 도 역제안만 추적하므로 이쪽이 학습 분포와도 일치한다.
last = ctx.get("autonomy_last_counter") or {}
deadline = 0.5
end_ts, total_s = ctx.get("deadline_end_ts"), ctx.get("deadline_total_s")
if end_ts and total_s:
import time
deadline = float(np.clip((end_ts - time.time()) / total_s, 0.0, 1.0))
hist_n = int(ctx.get("hist_n") or 0)
hist_success = float(ctx["hist_success"]) if ctx.get("hist_success") is not None else 0.5
hist_settle = (settle_norm(float(ctx["hist_settle_ratio"]))
if ctx.get("hist_settle_ratio") is not None else 0.5)
sf = np.concatenate([build_state_features(snap), self._tenant_feat, extra_state(
last.get("kind", ""), float(last.get("q", 0.0)),
deadline=deadline, hist_n=min(hist_n, 5) / 5.0,
hist_success=hist_success if hist_n else 0.5,
hist_settle=hist_settle,
internet_gap=internet_gap_feat(float(ctx.get("internet_lowest_price") or 0),
float(snap.anchor_price)),
)])
span = max(snap.target_price - snap.anchor_price, 1.0)
pos = (snap.input_price - snap.anchor_price) / span
# 행동 봉투 (학습 available_actions 와 동일해야 한다):
# ① 목표가 초과 제시가는 '수락' 제외 — 매입 승인 범위(v3.1 착취 방지)
# ② 직전 역제안보다 낮은 금액의 역제안 제외 — 단조 양보 원칙(제안 철회는 협상 예절 위반;
# 올리는 '속도'는 정책 학습, 후퇴 '금지'만 구조로 보장)
# ③ 역제시 해금 조건 — 옛 제품 의미론 복원(제품 결정 2026-07-10): 일반 카드는 설득만,
# 역제시(숫자 제안)는 와일드카드처럼 마무리 수단. 최소 AUTONOMY_MIN_PRESS(기본 2)회
# 설득 이후에만 역제시 후보가 열린다. 해금 후의 타이밍·금액은 정책 학습.
# ④ 마무리 국면 — 제시가가 목표가 0.5% 이내로 붙으면 압박 제외(+역제시 잠금 해제):
# 푼돈 차이에서 '재검토 부탁' 반복은 상대만 지치게 한다. 클로징(역제안/최종제안)하거나 끝내거나.
min_press = int(os.getenv("AUTONOMY_MIN_PRESS", "2"))
near_target = snap.input_price <= snap.target_price * 1.005
counter_locked = (int(ctx.get("autonomy_press_n") or 0) < min_press) and not near_target
last_counter_q = float(last["q"]) if last.get("kind") == "counter" else None
if last_counter_q is not None:
counter_locked = False # 이미 역제시를 시작했으면 잠그지 않는다(단조 봉투가 관리)
# ⑤ 첫 역제안은 앵커가 이하(q ≤ 0)만 — 낮게 개시해 목표가까지 천천히 올라간다
# (제품 결정: 사다리를 다 쓰는 앵커링 개시. 이후 단조 봉투가 상향을 관리).
# ⑥ 결렬(walk)도 해금 전 금지 — 설득 0회에 walk 를 고르면 최종제안 보장(엔진)과 결합해
# '첫 턴 목표가 통보'가 된다(v3.4 라이브 결함). 해금 전에는 설득만 가능.
cands = [a for a in ACTIONS
if not (a.kind == "accept" and snap.input_price > snap.target_price)
and not (a.kind == "counter" and counter_locked)
and not (a.kind == "walk" and counter_locked)
and not (a.kind == "press" and near_target)
and not (a.kind == "counter" and last_counter_q is None and a.counter_q > 1e-9)
and not (a.kind == "counter" and last_counter_q is not None
and a.counter_q < last_counter_q - 1e-9)]
feats = []
for a in cands:
cut = 0.0
if a.kind == "counter":
c = snap.anchor_price + a.counter_q * span
cut = max(0.0, (snap.input_price - c) / max(snap.input_price, 1.0))
feats.append(a.feat(pos, cut))
feats = np.stack(feats)
W0, b0, W1, b1, W2, b2 = self._W
x = np.concatenate([np.repeat(sf[None, :], feats.shape[0], axis=0), feats], axis=1)
h = np.maximum(x @ W0.T + b0, 0.0)
h = np.maximum(h @ W1.T + b1, 0.0)
scores = (h @ W2.T + b2).squeeze(-1)
return cands[int(np.argmax(scores))]
@staticmethod
def counter_price(ctx: dict, act: Action) -> int:
span = max(ctx["target_price"] - ctx["anchor_price"], 1.0)
return int(round(ctx["anchor_price"] + act.counter_q * span))
class AutonomyStore:
_z = None
_load_failed = False
@classmethod
def enabled(cls) -> bool:
return os.getenv("AUTONOMY_MODE", "0").lower() in ("1", "true", "yes")
@classmethod
def policy_for(cls, engine) -> Optional[AutonomyPolicy]:
"""engine: tenancy.registry.TenantEngine. 비활성/번들 없음 → None (룰 엔진 유지)."""
if not cls.enabled() or cls._load_failed:
return None
if cls._z is None:
try:
cls._z = np.load(BUNDLE_PATH, allow_pickle=False)
LOG.i("[Autonomy] 완전 자율 정책 번들 로드 완료 — 협상 판정 룰 대체 모드")
except Exception as ex:
cls._load_failed = True
LOG.e_no_callstack(f"[Autonomy] 번들 로드 실패 → 룰 엔진 유지: {ex}")
return None
return AutonomyPolicy(cls._z, engine.config.reward)
+118
View File
@@ -0,0 +1,118 @@
"""DQNServingStore — action-as-feature DQN 서빙 (선택 전용, 학습 없음).
tools/export_dqn_serving.py 가 만든 dqn_serving.npz(ScoreNet 가중치 + 카드특징 392차원)를
numpy 로 추론한다 — 서빙 컨테이너에 PyTorch 불필요.
역할 분담(계획서 H 트랙으로 가기 전 파일럿):
- 카드 '선택'만 DQN(greedy). Q-table 학습/영속/experience_logs 로깅 경로는 기존 그대로 유지
(Q-learning 은 오프폴리시라 DQN 이 고른 행동으로 갱신해도 유효, 로그는 DQN 오프라인 재학습 재료).
- 폴백: 플래그 꺼짐 / 번들 없음 / 가용 카드 전부 특징 미보유(신규 카드) → None 반환,
호출부(ChatService)가 기존 UCB Q-table 선택으로 진행한다.
활성화: 환경변수 DQN_SERVING=1 (docker-compose agent environment).
신규 카드 주의: 번들에 없는 카드번호는 후보에서 제외된다 — 카드 추가 시
tools/build_card_embeddings.py → tools/export_dqn_serving.py 재실행 후 재배포 필요.
"""
import os
from typing import List, Optional
import numpy as np
from common.logger import LOG
from negotiation.policies.base import ActionDecision, PolicyContext
from negotiation.qtable.domain.service.feature_builder import (
build_state_features, build_tenant_features)
_HERE = os.path.dirname(os.path.abspath(__file__))
BUNDLE_PATH = os.path.join(_HERE, "..", "..", "artifacts", "dqn_serving.npz")
class _Bundle:
def __init__(self, z):
self.W0, self.b0 = z["W0"], z["b0"]
self.W1, self.b1 = z["W1"], z["b1"]
self.W2, self.b2 = z["W2"], z["b2"]
self.state_dim = int(z["state_dim"])
self.card_feats = {str(n): z["card_feats"][i]
for i, n in enumerate(z["card_numbers"])}
def scores(self, state_feat: np.ndarray, card_feats: np.ndarray) -> np.ndarray:
"""가용 카드 K개 일괄 채점: [K, state+card] → [K]."""
k = card_feats.shape[0]
x = np.concatenate([np.repeat(state_feat[None, :], k, axis=0), card_feats], axis=1)
h = np.maximum(x @ self.W0.T + self.b0, 0.0)
h = np.maximum(h @ self.W1.T + self.b1, 0.0)
return (h @ self.W2.T + self.b2).squeeze(-1)
class DQNServingPolicy:
"""UCBQTablePolicy.select 와 동일한 PolicyContext → ActionDecision 계약(선택 전용)."""
name = "feature_dqn"
_EPS = 0.1 # propensity 근사용 ε (UCB 정책과 동일 관례 — OPE 지지 확보용, 선택은 greedy)
def __init__(self, bundle: _Bundle, engine): # engine: tenancy.registry.TenantEngine
self._bundle = bundle
self._mapper = engine.mapper
self._tenant_feat = build_tenant_features(engine.config.reward)
def _available(self, ctx: PolicyContext) -> List[int]:
# UCBQTablePolicy._available 과 동일 규칙 (마스크 → used 제외 → 소진 시 전체 허용)
if ctx.available_mask is not None:
avail = [a for a in range(ctx.action_space_size) if ctx.available_mask[a]]
else:
used = ctx.episode.used_action_ids if ctx.episode else set()
avail = [a for a in range(ctx.action_space_size) if a not in used]
return avail or list(range(ctx.action_space_size))
def select(self, ctx: PolicyContext) -> Optional[ActionDecision]:
"""카드특징이 있는 가용 카드가 없으면 None → 호출부가 Q-table 로 폴백."""
candidates = [] # (action_id, card_feat)
for a in self._available(ctx):
num = self._mapper.get_card_id(a)
feat = self._bundle.card_feats.get(num) if num else None
if feat is not None:
candidates.append((a, feat))
if not candidates:
return None
state_feat = np.concatenate([build_state_features(ctx.snapshot), self._tenant_feat])
if state_feat.shape[0] != self._bundle.state_dim:
LOG.e_no_callstack(
f"[DQNServing] state_dim 불일치: {state_feat.shape[0]} != {self._bundle.state_dim}")
return None
sc = self._bundle.scores(state_feat, np.stack([f for _, f in candidates]))
i = int(sc.argmax())
n = len(candidates)
return ActionDecision(
action_id=candidates[i][0],
propensity=(1.0 - self._EPS) + self._EPS / n,
q_value=float(sc[i]),
ucb_score=float(sc[i]),
available_actions=[a for a, _ in candidates],
)
class DQNServingStore:
"""번들 lazy 로드 + 캐시. 비활성/부재 시 None (호출부 Q-table 폴백)."""
_bundle: Optional[_Bundle] = None
_load_failed = False
@classmethod
def enabled(cls) -> bool:
return os.getenv("DQN_SERVING", "0").lower() in ("1", "true", "yes")
@classmethod
def policy_for(cls, engine) -> Optional[DQNServingPolicy]:
if not cls.enabled() or cls._load_failed:
return None
if cls._bundle is None:
try:
cls._bundle = _Bundle(np.load(BUNDLE_PATH, allow_pickle=False))
LOG.i(f"[DQNServing] 번들 로드 완료: 카드 {len(cls._bundle.card_feats)}장")
except Exception as ex:
cls._load_failed = True # 요청마다 재시도하지 않음
LOG.e_no_callstack(f"[DQNServing] 번들 로드 실패 → Q-table 폴백: {ex}")
return None
return DQNServingPolicy(cls._bundle, engine)
+26 -3
View File
@@ -10,6 +10,7 @@ P5/H 트랙에서 transition_id 기반으로 정교화한다.
import math import math
from typing import Tuple from typing import Tuple
from common.logger import LOG
from negotiation.policies.qtable_policy import UCBQTablePolicy from negotiation.policies.qtable_policy import UCBQTablePolicy
from negotiation.qtable.domain.model.q_table import QTable from negotiation.qtable.domain.model.q_table import QTable
from negotiation.qtable.infra.repository.learning_repository import LearningRepository from negotiation.qtable.infra.repository.learning_repository import LearningRepository
@@ -26,20 +27,42 @@ class QTablePolicyStore:
lr = pol_cfg.learning_rate lr = pol_cfg.learning_rate
gamma = pol_cfg.gamma gamma = pol_cfg.gamma
# 현재 카탈로그 스냅샷(action_id → 카드번호). 버전에 저장해 카드번호 기반 마이그레이션에 쓴다.
card_list = [engine.mapper.get_card_id(i) for i in range(A)]
# cold-start 3단 (계획서 D): # cold-start 3단 (계획서 D):
# ① 활성 버전 있으면 그대로 ② 없고 inherits_base 면 base warm-start 복제(차원 호환 시) # ① 활성 버전 있으면 그대로 ② 없고 inherits_base 면 base warm-start 복제(차원 호환 시)
# ③ 차원 불일치/base 없음 → 휴리스틱 빈 버전 # ③ 차원 불일치/base 없음 → 휴리스틱 빈 버전
err, active = await repo.read(lambda s: repo.get_active_version(s)) err, active = await repo.read(lambda s: repo.get_active_version(s))
if active is not None: if active is not None:
version_id = active.version_id dim_changed = active.action_space_size != A or active.state_space_size != S
# 동일 차원이라도 카탈로그 내용(카드 구성)이 바뀌면 마이그레이션(카드번호 리맵).
# 레거시 버전(action_cards=None)은 옛 구성을 몰라 내용변경 감지 불가 → 차원만 본다.
cards_changed = active.action_cards is not None and list(active.action_cards) != card_list
if dim_changed or cards_changed:
# 카드번호 기반 학습 보존 마이그레이션: 같은 카드의 Q값을 새 action_id 로 이동.
migrated = await repo.migrate_active_version_dim(
old_version=active, state_space_size=S, action_space_size=A,
learning_rate=lr, discount_factor=gamma, version_name=f"v_migrated_a{A}",
action_cards=card_list)
if migrated is not None:
LOG.i(f"[QTablePolicyStore] 카탈로그 변경 마이그레이션 company={engine.company_id} "
f"action {active.action_space_size}→{A} (카드번호 리맵, 학습 보존)")
version_id = migrated or active.version_id
else:
version_id = active.version_id
if active.action_cards is None: # 레거시 버전 backfill → 향후 카탈로그 변경 감지 가능
await repo.set_version_action_cards(version_id, card_list)
else: else:
version_id = None version_id = None
if engine.config.inherits_base: if engine.config.inherits_base:
version_id = await repo.warm_start_from_base( version_id = await repo.warm_start_from_base(
state_space_size=S, action_space_size=A, learning_rate=lr, discount_factor=gamma) state_space_size=S, action_space_size=A, learning_rate=lr, discount_factor=gamma,
action_cards=card_list)
if version_id is None: if version_id is None:
version_id = await repo.get_or_create_active_version( version_id = await repo.get_or_create_active_version(
state_space_size=S, action_space_size=A, learning_rate=lr, discount_factor=gamma) state_space_size=S, action_space_size=A, learning_rate=lr, discount_factor=gamma,
action_cards=card_list)
qtable = QTable(S, A, learning_rate=lr, discount_factor=gamma) qtable = QTable(S, A, learning_rate=lr, discount_factor=gamma)
qrows, vrows = await repo.load_cells(version_id) qrows, vrows = await repo.load_cells(version_id)
@@ -0,0 +1,44 @@
"""build_state_features — snapshot(raw 연속값) → 실수 벡터 (DQN/action-as-feature 용).
state_calculator.build_state(이산화)와 대비되는 연속 표현. 이산화(등급/162칸)를 하지 않고
정규화된 raw 값을 그대로 벡터로 내보낸다. 협력사 특징(매출·경쟁사수·유통)이 벡터에 포함되므로
'협력사를 입력으로'(Phase 3)가 자연스럽게 달성된다.
"""
import numpy as np
from negotiation.qtable.domain.model.snapshot import NegotiationSnapshot
DIST_CLASSES = ("A", "B", "C")
STATE_FEATURE_DIM = 9 # build_state_features 벡터 길이. feature 추가 시 갱신.
TENANT_FEATURE_DIM = 5 # build_tenant_features 벡터 길이.
def build_tenant_features(reward_cfg) -> np.ndarray:
"""고객사 '성향'을 ID 가 아니라 보상 설정값(내용)으로 벡터화 (Phase 3 고객사 조건화).
새 고객사도 tenant.yaml 의 reward 설정만 있으면 즉시 조건화된다 (cold-start 없음).
"""
return np.array([
reward_cfg.max_weight, # 가격 중시 정도 (W↑ = 가격보상 비중↑)
reward_cfg.success_reward / 2.0, # 성사를 얼마나 크게 치는가
-reward_cfg.failure_penalty / 2.0, # 결렬을 얼마나 무서워하는가
reward_cfg.penalty_lambda * 20.0, # 속도 성향 (오래 끌수록 벌점)
reward_cfg.beta, # 앵커 초과달성 보너스 성향
], dtype=np.float32)
def build_state_features(s: NegotiationSnapshot) -> np.ndarray:
"""정규화된 연속 상태 벡터. 등급화 없음 — 990원과 850원이 구별된다."""
dist_onehot = [1.0 if s.distribution_code == c else 0.0 for c in DIST_CLASSES]
anchor = max(s.anchor_price, 1.0)
target = max(s.target_price, 1.0)
return np.array([
min(s.revenue_amount, 5e8) / 5e8, # 협력사 매출 (0~1)
*dist_onehot, # 유통 A/B/C
min(s.partner_count, 5) / 5.0, # 대안 협력사 수 (BATNA)
float(np.clip(s.acceptance_ratio, 0.0, 1.0)), # 수용률
float(np.clip((s.input_price - anchor) / anchor, -1.0, 2.0)), # 앵커 대비 격차 (연속!)
float(np.clip((target - s.input_price) / target, -2.0, 1.0)), # 목표 대비 여유
min(s.round_number, 10) / 10.0, # 라운드
], dtype=np.float32)
@@ -155,8 +155,10 @@ class LearningRepository:
# ---- Q-Table 영속화 (H1) ------------------------------------------- # ---- Q-Table 영속화 (H1) -------------------------------------------
async def get_or_create_active_version(self, *, state_space_size: int, action_space_size: int, async def get_or_create_active_version(self, *, state_space_size: int, action_space_size: int,
learning_rate: float, discount_factor: float, learning_rate: float, discount_factor: float,
scope: int = 2, version_name: str = "v000") -> Optional[uuid.UUID]: scope: int = 2, version_name: str = "v000",
"""활성 버전 version_id 반환. 없으면 v000 을 활성으로 생성. (company_id 스코프)""" action_cards: Optional[List[str]] = None) -> Optional[uuid.UUID]:
"""활성 버전 version_id 반환. 없으면 v000 을 활성으로 생성. (company_id 스코프)
action_cards: 카탈로그 스냅샷(카드번호 목록, index=action_id) — 후일 카드번호 기반 마이그레이션용."""
err, existing = await DB_SESSION_MNG.execute_lambda( err, existing = await DB_SESSION_MNG.execute_lambda(
DBType.MAIN.value, DBWRType.DB_READ.value, lambda s: self.get_active_version(s) DBType.MAIN.value, DBWRType.DB_READ.value, lambda s: self.get_active_version(s)
) )
@@ -170,6 +172,7 @@ class LearningRepository:
version_id=vid, company_id=self.company_id, version_name=version_name, scope=scope, version_id=vid, company_id=self.company_id, version_name=version_name, scope=scope,
state_space_size=state_space_size, action_space_size=action_space_size, state_space_size=state_space_size, action_space_size=action_space_size,
learning_rate=learning_rate, discount_factor=discount_factor, is_active=True, learning_rate=learning_rate, discount_factor=discount_factor, is_active=True,
action_cards=action_cards,
) )
return await DB_SESSION_MNG.insert(s, obj) return await DB_SESSION_MNG.insert(s, obj)
@@ -184,7 +187,8 @@ class LearningRepository:
async def warm_start_from_base(self, *, state_space_size: int, action_space_size: int, async def warm_start_from_base(self, *, state_space_size: int, action_space_size: int,
learning_rate: float, discount_factor: float, visit_decay: float = 0.5, learning_rate: float, discount_factor: float, visit_decay: float = 0.5,
version_name: str = "v000_warmstart_from_base") -> Optional[uuid.UUID]: version_name: str = "v000_warmstart_from_base",
action_cards: Optional[List[str]] = None) -> Optional[uuid.UUID]:
"""공유 베이스(_base)의 Q값/방문수를 자사로 복제해 활성 버전 생성 (cold-start ①, 계획서 D). """공유 베이스(_base)의 Q값/방문수를 자사로 복제해 활성 버전 생성 (cold-start ①, 계획서 D).
차원 불일치/베이스 없음 → None (호출자가 휴리스틱 init 폴백). visit 은 감쇠 복제(탐색 여지). 차원 불일치/베이스 없음 → None (호출자가 휴리스틱 init 폴백). visit 은 감쇠 복제(탐색 여지).
@@ -205,7 +209,7 @@ class LearningRepository:
version_id=vid, company_id=self.company_id, version_name=version_name, scope=2, version_id=vid, company_id=self.company_id, version_name=version_name, scope=2,
base_version_id=base_ver.version_id, state_space_size=state_space_size, base_version_id=base_ver.version_id, state_space_size=state_space_size,
action_space_size=action_space_size, learning_rate=learning_rate, action_space_size=action_space_size, learning_rate=learning_rate,
discount_factor=discount_factor, is_active=True, discount_factor=discount_factor, is_active=True, action_cards=action_cards,
) )
e = await DB_SESSION_MNG.insert(s, ver) e = await DB_SESSION_MNG.insert(s, ver)
if e != ErrorType.SUCCESS: if e != ErrorType.SUCCESS:
@@ -227,6 +231,73 @@ class LearningRepository:
err = await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [_create]) err = await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [_create])
return vid if err == ErrorType.SUCCESS else None return vid if err == ErrorType.SUCCESS else None
async def migrate_active_version_dim(self, *, old_version, state_space_size: int, action_space_size: int,
learning_rate: float, discount_factor: float,
version_name: str = "v_migrated",
action_cards: Optional[List[str]] = None) -> Optional[uuid.UUID]:
"""활성 Q-table 을 새 카탈로그로 마이그레이션 (카드 추가/삭제/재정렬 시).
**카드번호 기반 리맵**: 옛 버전의 action_cards(카드번호 스냅샷)와 새 카탈로그(action_cards)를
비교해, 같은 **카드번호**의 학습값을 새 action_id 로 옮긴다 → 중간 삽입/삭제로 action_id 가
밀려도 학습이 카드에 정확히 따라간다. 새 카드는 fresh, 사라진 카드는 버려진다.
옛 버전에 action_cards 가 없으면(레거시) 위치 기반 폴백(끝 추가/삭제만 안전).
기존 활성 버전은 비활성화하고 새 버전을 활성화한다. 실패 시 None.
"""
qcells, vcells = await self.load_cells(old_version.version_id)
vid = uuid.uuid4()
unique_name = f"{version_name}_{vid.hex[:8]}" # (company_id, version_name) 유니크 충돌 방지
S, A = state_space_size, action_space_size
# 옛 action_id → 새 action_id 리맵 테이블. 카드번호로 매칭(스냅샷 있을 때).
old_cards = list(getattr(old_version, "action_cards", None) or [])
new_cards = list(action_cards or [])
if old_cards and new_cards:
new_index = {num: i for i, num in enumerate(new_cards)}
remap = {old_a: new_index[num] for old_a, num in enumerate(old_cards) if num in new_index}
else:
remap = {a: a for a in range(min(old_version.action_space_size, A))} # 위치 기반 폴백
async def _create(s: AsyncSession) -> ErrorType:
# 기존 활성 비활성화 → 새 버전 활성 삽입 (동시 2개 활성 방지).
e = await DB_SESSION_MNG.add(s, update(QTableVersion).where(
QTableVersion.company_id == self.company_id,
QTableVersion.version_id == old_version.version_id).values(is_active=False))
if e != ErrorType.SUCCESS:
return e
ver = QTableVersion(
version_id=vid, company_id=self.company_id, version_name=unique_name, scope=2,
base_version_id=old_version.version_id, state_space_size=S, action_space_size=A,
learning_rate=learning_rate, discount_factor=discount_factor, is_active=True,
action_cards=new_cards or None,
)
e = await DB_SESSION_MNG.insert(s, ver)
if e != ErrorType.SUCCESS:
return e
qobjs = [QValue(company_id=self.company_id, version_id=vid, state_index=st, action_id=remap[a], q_value=q)
for st, a, q in qcells if st < S and a in remap]
vobjs = [VisitCount(company_id=self.company_id, version_id=vid, state_index=st, action_id=remap[a], count=c)
for st, a, c in vcells if st < S and a in remap]
if qobjs:
e = await DB_SESSION_MNG.insert(s, qobjs)
if e != ErrorType.SUCCESS:
return e
if vobjs:
e = await DB_SESSION_MNG.insert(s, vobjs)
if e != ErrorType.SUCCESS:
return e
return ErrorType.SUCCESS
err = await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [_create])
return vid if err == ErrorType.SUCCESS else None
async def set_version_action_cards(self, version_id, action_cards: List[str]) -> ErrorType:
"""버전의 카탈로그 스냅샷(action_cards) 백필 — 레거시 버전이 향후 카탈로그 변경을 감지하게 한다."""
async def _do(s: AsyncSession) -> ErrorType:
return await DB_SESSION_MNG.add(s, update(QTableVersion).where(
QTableVersion.company_id == self.company_id,
QTableVersion.version_id == version_id).values(action_cards=action_cards))
return await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [_do])
async def load_cells(self, version_id) -> Tuple[List[tuple], List[tuple]]: async def load_cells(self, version_id) -> Tuple[List[tuple], List[tuple]]:
"""(q_cells, visit_cells) — q_cells: (state,action,q), visit_cells: (state,action,count). 자사 스코프.""" """(q_cells, visit_cells) — q_cells: (state,action,q), visit_cells: (state,action,count). 자사 스코프."""
def _q(s): def _q(s):
+2 -3
View File
@@ -20,9 +20,8 @@ from config.server_configs import agent_config
_TENANT_HEADER = "X-Tenant-ID" _TENANT_HEADER = "X-Tenant-ID"
# 테넌트 식별이 필요 없는 경로 (헬스/문서/스키마/데모 UI). # 테넌트 식별이 필요 없는 경로 (헬스/문서/스키마/데모 UI + 전역 카탈로그 리로드=내부 운영).
_WHITELIST_PREFIXES = ("/healthz", "/health", "/v1/health", "/docs", "/redoc", "/openapi.json", "/demo") _WHITELIST_PREFIXES = ("/healthz", "/health", "/v1/health", "/docs", "/redoc", "/openapi.json", "/demo", "/v1/catalog-refresh-all")
class TenantMiddleware(BaseHTTPMiddleware): class TenantMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next): async def dispatch(self, request: Request, call_next):
+30 -3
View File
@@ -6,13 +6,13 @@ PoC: action_id ↔ card_id 매핑을 learning.tenant_action_cards 에 둔다(con
from typing import Optional from typing import Optional
from fastapi import APIRouter, Depends from fastapi import APIRouter, Depends, Request
from pydantic import BaseModel from pydantic import BaseModel
from common.enums import ErrorType from common.enums import EXCEPTION_TENANT_HEADER_MISSING, ErrorType
from negotiation.qtable.infra.repository.learning_repository import LearningRepository from negotiation.qtable.infra.repository.learning_repository import LearningRepository
from router.deps import get_tenant_engine from router.deps import get_tenant_engine
from tenancy.registry import TenantEngine from tenancy.registry import TenantEngine, tenant_registry
router = APIRouter(prefix="/v1", tags=["Card"], responses={404: {"description": "Not found"}}) router = APIRouter(prefix="/v1", tags=["Card"], responses={404: {"description": "Not found"}})
@@ -41,6 +41,33 @@ async def card_update(req: CardUpdateReq, engine: TenantEngine = Depends(get_ten
"action_id": req.action_id, "card_id": req.card_id, "desc": err.name} "action_id": req.action_id, "card_id": req.card_id, "desc": err.name}
@router.post("/catalog-refresh-all", summary="공용 카탈로그 변경 전역 반영(모든 엔진 캐시 클리어)")
async def catalog_refresh_all():
"""공용 카드(card.nego_cards user_id NULL)는 모든 테넌트의 action space 를 정의하므로,
변경 시 전역 반영이 필요하다. 캐시된 엔진을 전부 비워 다음 요청에서 최신 카탈로그로 재조립한다.
o2o 운영/negodata 공용카드 발행 훅에서 호출. 테넌트 헤더 불필요(미들웨어 화이트리스트) — 내부망 전용.
"""
cleared = tenant_registry.clear_all()
return {"success": True, "cleared_engines": cleared}
@router.post("/catalog-refresh", summary="카드 카탈로그 변경 반영(엔진 재조립)")
async def catalog_refresh(request: Request):
"""negodata 가 카드 카탈로그(card.nego_cards)를 추가/삭제(발행)한 뒤 호출한다.
해당 테넌트의 캐시된 엔진을 재조립해 → ① DB 카탈로그로 action space 재구성(type:db)
→ 다음 협상 로드 시 ② 차원 변경이면 Q-table 학습 보존 마이그레이션이 걸린다.
엔진은 캐시되므로 이 호출 없이는 카탈로그 변경이 반영되지 않는다.
"""
tenant_id = getattr(request.state, "tenant_id", None)
if not tenant_id:
raise EXCEPTION_TENANT_HEADER_MISSING
engine = await tenant_registry.reload(tenant_id)
if engine is None:
return {"success": False, "desc": "unregistered tenant or reload failed", "tenant_id": tenant_id}
return {"success": True, "company_id": engine.company_id, "action_space_size": engine.action_space_size}
@router.get("/card-search", summary="카드 검색(전체 매핑 또는 card_id 조회)") @router.get("/card-search", summary="카드 검색(전체 매핑 또는 card_id 조회)")
async def card_search(card_id: Optional[str] = None, engine: TenantEngine = Depends(get_tenant_engine)): async def card_search(card_id: Optional[str] = None, engine: TenantEngine = Depends(get_tenant_engine)):
mapping = await _merged_mapping(engine) mapping = await _merged_mapping(engine)
+4 -1
View File
@@ -13,7 +13,7 @@ class Req_Chat(Req_WebPacketProtocol):
협상 컨텍스트(rq_type/목표가/앵커링가/품목가/매출액/유통코드/파트너 유형)는 요청에 싣지 협상 컨텍스트(rq_type/목표가/앵커링가/품목가/매출액/유통코드/파트너 유형)는 요청에 싣지
않는다 — 세션 시작 시 agent 가 DB 에서 1회 조회해 확정한다(NegotiationContextLoader): 않는다 — 세션 시작 시 agent 가 DB 에서 1회 조회해 확정한다(NegotiationContextLoader):
negotiation.sessions(qt_type·target_price·anchoring_price), partner.items(price), negotiation.sessions(qt_type·target_price·anchoring_price), partner.items(price),
partner.suppliers(total_revenue), quotation.quotations(supplier_type), 상품별 협력사 수. partner.suppliers(total_revenue), partner.supplier_items(supply_type), 상품별 협력사 수.
행이 없으면(데모/테스트 직접 호출) 기본값 폴백. 행이 없으면(데모/테스트 직접 호출) 기본값 폴백.
가격 수용률은 세션 내 라운드별 제시가로 매 턴 동적 계산: max(0, (기존 공급가−현재가)/기존 공급가) 가격 수용률은 세션 내 라운드별 제시가로 매 턴 동적 계산: max(0, (기존 공급가−현재가)/기존 공급가)
— 첫 제시가부터 기존 공급가 대비 인하가 반영되므로 첫 라운드도 실값. 기존 공급가 없으면 첫 제시가 기준. — 첫 제시가부터 기존 공급가 대비 인하가 반영되므로 첫 라운드도 실값. 기존 공급가 없으면 첫 제시가 기준.
@@ -53,6 +53,9 @@ class Res_Chat(Res_WebPacketProtocol):
# 성공 확정 이후 턴(협상완료 요약·협상종료)에 내려주는 합의가. 와일드카드 1% 인하 수락 등 # 성공 확정 이후 턴(협상완료 요약·협상종료)에 내려주는 합의가. 와일드카드 1% 인하 수락 등
# 유저가 직접 입력하지 않은 가격으로 타결될 수 있어, backend 요약/입찰가는 이 값을 최우선 사용한다. # 유저가 직접 입력하지 않은 가격으로 타결될 수 있어, backend 요약/입찰가는 이 값을 최우선 사용한다.
settled_price: Optional[int] = None settled_price: Optional[int] = None
# Phase 3 이해층: 자유 발화를 NLU 로 해석해 진행한 경우, 엔진에 실제 전달된 입력.
# (예: "만원까지는 어렵고 10,500원이면 가능합니다" → "10500") 미해석/정형 입력이면 None.
interpreted_input: Optional[str] = None
class Res_ChatSession(Res_WebPacketProtocol): class Res_ChatSession(Res_WebPacketProtocol):
+334 -12
View File
@@ -7,16 +7,27 @@ ChatEngine(동기 step 전이) + UCB Q-Table(가격협상 카드선택·학습)
import uuid import uuid
from typing import Optional from typing import Optional
import numpy as np
from common.enums import DBType, ErrorType from common.enums import DBType, ErrorType
from common.database.db_session_manager import DB_SESSION_MNG from common.database.db_session_manager import DB_SESSION_MNG
from common.logger import LOG from common.logger import LOG
from config.server_configs import agent_config from config.server_configs import agent_config
from negotiation.chat.service.chat_engine import ChatEngine, ChatSession, StepView from negotiation.cards.domain.tactics import compute_counter, tactic_available, tactic_for
from negotiation.chat.service import ment_generator
from negotiation.chat.service.chat_engine import (
_CHOICE_MODES, _PRICE_MODES, ChatEngine, ChatSession, StepView,
)
from negotiation.chat.service.indicator import compute_indicator from negotiation.chat.service.indicator import compute_indicator
from negotiation.chat.service.input_interpreter import SIMPLE_PRICE_RE, InputInterpreter
from negotiation.chat.service.chat_session_repository import ChatSessionRepository from negotiation.chat.service.chat_session_repository import ChatSessionRepository
from negotiation.chat.service.negotiation_context_loader import NegotiationContextLoader from negotiation.chat.service.negotiation_context_loader import NegotiationContextLoader
from negotiation.chat.service.script_naturalizer import ScriptNaturalizer, build_situation
from negotiation.chat.service.script_repository import ScriptRepository from negotiation.chat.service.script_repository import ScriptRepository
from negotiation.policies.base import EpisodeState, PolicyContext, Transition from negotiation.policies.base import EpisodeState, PolicyContext, Transition
from negotiation.policies.autonomy_actions import ACTIONS as AUTONOMY_ACTIONS
from negotiation.policy.autonomy_store import AutonomyStore
from negotiation.policy.dqn_store import DQNServingStore
from negotiation.policy.model_store import QTablePolicyStore from negotiation.policy.model_store import QTablePolicyStore
from negotiation.qtable.domain.model.snapshot import NegotiationOutcome, NegotiationSnapshot, PartnerType from negotiation.qtable.domain.model.snapshot import NegotiationOutcome, NegotiationSnapshot, PartnerType
from negotiation.qtable.domain.service.reward_calculator import RewardCalculator from negotiation.qtable.domain.service.reward_calculator import RewardCalculator
@@ -31,10 +42,18 @@ _DEFAULT_RQ_TYPE = "재협상"
_DEFAULT_TARGET_PRICE = 10000 # KT 목표 매입가 _DEFAULT_TARGET_PRICE = 10000 # KT 목표 매입가
_DEFAULT_ANCHOR_PRICE = 9900 # 앵커링가(목표가보다 낮음). 제시가 ≤ anchor → 우선협상 _DEFAULT_ANCHOR_PRICE = 9900 # 앵커링가(목표가보다 낮음). 제시가 ≤ anchor → 우선협상
_DEFAULT_REVENUE_AMOUNT = 20_000_000 # 매출액(원) — suppliers.total_revenue 미기재 시 폴백 _DEFAULT_REVENUE_AMOUNT = 20_000_000 # 매출액(원) — suppliers.total_revenue 미기재 시 폴백
_DEFAULT_DISTRIBUTION_CODE = "A" # 유통 코드 — quotations.supplier_type 미지정 시 폴백 _DEFAULT_DISTRIBUTION_CODE = "A" # 유통 코드 — supplier_items.supply_type 미지정 시 폴백
_DEFAULT_PARTNER_NAME = "귀사" # 협력사명 — suppliers.name 미기재/데모 시 폴백(카드 {partner_name})
_DEFAULT_PRODUCT_NAME = "본 상품" # 상품명 — items.name 미기재/데모 시 폴백(카드 {product_name})
class ChatService: class ChatService:
# Phase 2 표현층 / Phase 3 이해층 — 테넌트 llm.enabled + 전역 자격증명일 때만 사용(기본 무동작).
# 클래스 속성인 이유: FastAPI 가 ChatService 를 Depends 로 쓰므로 __init__ 파라미터를 두면
# 쿼리 파라미터로 해석된다. 테스트는 인스턴스 속성으로 덮어 주입한다.
_naturalizer = ScriptNaturalizer()
_interpreter = InputInterpreter()
async def chat(self, engine: TenantEngine, req: Req_Chat) -> Res_Chat: async def chat(self, engine: TenantEngine, req: Req_Chat) -> Res_Chat:
res = Res_Chat() res = Res_Chat()
repo = ScriptRepository(engine.config, agent_config.tenants_dir) repo = ScriptRepository(engine.config, agent_config.tenants_dir)
@@ -44,9 +63,19 @@ class ChatService:
session = await sess_repo.get(req.session_id) if req.session_id else None session = await sess_repo.get(req.session_id) if req.session_id else None
# 새 세션 컨텍스트: 요청 페이로드 대신 DB(negotiation.sessions 등)에서 1회 조회. # 새 세션 컨텍스트: 요청 페이로드 대신 DB(negotiation.sessions 등)에서 1회 조회.
# 행이 없으면(데모/테스트 직접 호출) 기본값 폴백. # 행이 없으면(데모/테스트 직접 호출) 기본값 폴백.
db_ctx = None if session else await NegotiationContextLoader().load(req.session_id) db_ctx = None if session else await NegotiationContextLoader().load(req.session_id, engine.company_id)
rq_type = session.rq_type if session else (db_ctx.rq_type if db_ctx else _DEFAULT_RQ_TYPE) 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) chat_engine = ChatEngine(repo, rq_type=rq_type)
# 완전 자율 모드(AUTONOMY_MODE=1 + 번들 존재): 가격협상 판정 룰·카드 선택을 정책 행동으로 대체.
# decider 를 감싸 결정을 컨텍스트에 기록 → advance() 후 experience_logs 에 적재(_autonomy_learn).
autonomy = AutonomyStore.policy_for(engine)
if autonomy is not None:
def _decide(ctx, _p=autonomy):
act = _p.decide(ctx)
ctx["autonomy_pending"] = {"idx": AUTONOMY_ACTIONS.index(act), "kind": act.kind,
"q": act.counter_q, "s": act.strategy}
return act
chat_engine.autonomy_decider = _decide
# ① step desync 감지: backend 가 본 직전 봇 step(client_step)이 agent 세션 step 과 다르면 경고. # ① step desync 감지: backend 가 본 직전 봇 step(client_step)이 agent 세션 step 과 다르면 경고.
# agent 가 자기 step 을 정답으로 보고 진행하고(응답의 step/client_step 으로 backend 가 따라옴), # agent 가 자기 step 을 정답으로 보고 진행하고(응답의 step/client_step 으로 backend 가 따라옴),
@@ -63,13 +92,22 @@ class ChatService:
) )
if session is None: if session is None:
selected_nego_cards = db_ctx.selected_nego_card_numbers if db_ctx else []
selected_wild_cards = db_ctx.selected_wild_card_numbers if db_ctx else []
# 운영 DB 세션은 견적 version_id 에 묶인 카드만 사용한다. 직접 호출/데모(DB context 없음)는
# 기존 테넌트 기본 action mapping 으로 폴백해 로컬 테스트와 콘솔 데모를 유지한다.
action_space_size = (
min(len(selected_nego_cards), engine.action_space_size)
if db_ctx is not None
else engine.action_space_size
)
# session_id honoring: backend 가 보낸 session_id(= negotiation.sessions.session_id)를 # session_id honoring: backend 가 보낸 session_id(= negotiation.sessions.session_id)를
# 새 uuid 발급 없이 그대로 세션 키로 쓴다. 없으면(직접 호출/데모) 생성. # 새 uuid 발급 없이 그대로 세션 키로 쓴다. 없으면(직접 호출/데모) 생성.
session = ChatSession( session = ChatSession(
session_id=req.session_id or str(uuid.uuid4()), tenant_id=engine.tenant_id, company_id=engine.company_id, session_id=req.session_id or str(uuid.uuid4()), tenant_id=engine.tenant_id, company_id=engine.company_id,
rq_type=rq_type, action_space_size=engine.action_space_size, rq_type=rq_type, action_space_size=action_space_size,
context={ context={
# 매출액 = suppliers.total_revenue, 유통코드 = quotations.supplier_type 매핑 (loader). # 매출액 = suppliers.total_revenue, 유통코드 = supplier_items.supply_type 매핑 (loader).
# 미기재/미지정이면 기본값 폴백. # 미기재/미지정이면 기본값 폴백.
"revenue_amount": db_ctx.revenue_amount if db_ctx and db_ctx.revenue_amount > 0 else _DEFAULT_REVENUE_AMOUNT, "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, "distribution_code": db_ctx.distribution_code if db_ctx and db_ctx.distribution_code else _DEFAULT_DISTRIBUTION_CODE,
@@ -80,14 +118,34 @@ class ChatService:
# 목표가/앵커링가: sessions 행(생성 시 박제된 anchoring_price) → 박제 ‰ → 1% 폴백 (loader). # 목표가/앵커링가: sessions 행(생성 시 박제된 anchoring_price) → 박제 ‰ → 1% 폴백 (loader).
"anchor_price": db_ctx.anchor_price if db_ctx else _DEFAULT_ANCHOR_PRICE, "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, "target_price": db_ctx.target_price if db_ctx else _DEFAULT_TARGET_PRICE,
# 협력사명/상품명 — 카드 스크립트 {partner_name}·{product_name} 치환용(loader). 없으면 폴백.
"partner_name": (db_ctx.partner_name if db_ctx and db_ctx.partner_name else _DEFAULT_PARTNER_NAME),
"product_name": (db_ctx.product_name if db_ctx and db_ctx.product_name else _DEFAULT_PRODUCT_NAME),
"round": 0, "round": 0,
# 기존 공급가(품목 기준가) — 가격협상_확인 인하율 산출용. # 기존 공급가(품목 기준가) — 가격협상_확인 인하율 산출용.
"item_price": db_ctx.item_price if db_ctx else 0, "item_price": db_ctx.item_price if db_ctx else 0,
# 견적 생성 시 선택한 카드. 일반카드는 action_id 0..N-1 에 그대로 매핑한다.
# 1% 인하는 기본 와일드카드로 항상 열고, 재원부족 등 선택형 와일드카드는
# 선택된 와일드카드가 있을 때만 허용한다.
"db_context_loaded": db_ctx is not None,
"selected_nego_card_numbers": selected_nego_cards,
"selected_wild_card_numbers": selected_wild_cards,
"allow_selected_wildcards": True if db_ctx is None else bool(selected_wild_cards),
# ---- 자율 에이전트 v3 특징 소스 (미상이면 키 자체를 중립값으로 — JSON 직렬화 안전) ----
"internet_lowest_price": db_ctx.internet_lowest_price if db_ctx else 0,
"deadline_end_ts": db_ctx.deadline_end_ts if db_ctx else None,
"deadline_total_s": db_ctx.deadline_total_s if db_ctx else None,
"hist_n": db_ctx.hist_n if db_ctx else 0,
"hist_success": db_ctx.hist_success if db_ctx else None,
"hist_settle_ratio": db_ctx.hist_settle_ratio if db_ctx else None,
}, },
) )
view = chat_engine.start(session) view = chat_engine.start(session)
else: else:
view = chat_engine.advance(session, req.user_input) # Phase 3 이해층: 자유 발화(버튼/정형 입력이 아닌 텍스트)를 기대 입력으로 해석.
# 해석 실패/미설정 시 원문 그대로 → 기존 엔진 재질문 흐름 유지.
user_input = await self._interpret_input(engine, chat_engine, session, req.user_input, res)
view = chat_engine.advance(session, user_input)
# 2) 응답 기본 채움 (학습 블록이 가격협상 턴에서 script/indicator 를 덮어쓸 수 있어 먼저 채운다) # 2) 응답 기본 채움 (학습 블록이 가격협상 턴에서 script/indicator 를 덮어쓸 수 있어 먼저 채운다)
res.session_id = session.session_id res.session_id = session.session_id
@@ -104,13 +162,36 @@ class ChatService:
if session.context.get("final_outcome") == "success" and session.context.get("input_price"): if session.context.get("final_outcome") == "success" and session.context.get("input_price"):
res.settled_price = int(session.context["input_price"]) res.settled_price = int(session.context["input_price"])
# 선택형 와일드카드 턴(wild_card_dynamic): 멘트 정본은 card.wild_cards(negodata 편집).
# DB 멘트가 있으면 스텝 기본 멘트를 대체하고, 없으면 기본 멘트(counter_price 치환)로 진행.
if view.step == "wild_card_dynamic" and session.context.get("active_wild_card_number"):
number = session.context["active_wild_card_number"]
template = await repo.resolve_wild_card_template(number)
if template:
if engine.config.llm.enabled and ScriptNaturalizer.available():
template = (await self._naturalizer.naturalize(
template, situation=build_situation(session.context))) or template
res.script = repo.format_script(template, chat_engine.vars_for(session))
res.card_id = number
# 3) 학습 결합 (가격협상 카드선택 → 카드 스크립트·협상지표 / 종료 보상) # 3) 학습 결합 (가격협상 카드선택 → 카드 스크립트·협상지표 / 종료 보상)
if view.error is None and engine.action_space_size > 0: if view.error is None and session.action_space_size > 0:
if view.needs_card_selection: if view.needs_card_selection:
await self._select_and_learn(engine, chat_engine, repo, session, res) await self._select_and_learn(engine, chat_engine, repo, session, res)
elif view.outcome is not None: elif view.outcome is not None:
await self._terminal_learn(engine, session, view.outcome, res) await self._terminal_learn(engine, session, view.outcome, res)
# 3-b) 완전 자율 모드: 정책 결정·종료 결과를 experience_logs 에 적재 (실로그 재학습 재료).
if autonomy is not None and view.error is None:
await self._autonomy_learn(engine, session, view, res)
# 자율 스텝 멘트를 LLM 으로 생성 (행동은 RL, 문장은 LLM). 실패/미설정 → 템플릿 유지.
if view.step.startswith("자율_"):
llm_ment = await ment_generator.generate(view.step, session.context)
if llm_ment:
res.script = llm_ment
# 직전 봇 멘트 보존 — 다음 생성에서 같은 문장 구조 반복을 금지하는 힌트.
session.context["autonomy_last_ment"] = (res.script or "")[:200]
if view.error: if view.error:
res.result.SetResult(ErrorType.NEGO_INVALID_STEP) res.result.SetResult(ErrorType.NEGO_INVALID_STEP)
res.msg = view.error res.msg = view.error
@@ -136,6 +217,53 @@ class ChatService:
res.found = True res.found = True
return res return res
# ---- Phase 3 이해층 (자유 발화 NLU) ---------------------------------
async def _interpret_input(self, engine: TenantEngine, chat_engine: ChatEngine,
session: ChatSession, user_input: Optional[str], res: Res_Chat) -> Optional[str]:
"""자유 발화를 현재 step 의 기대 입력으로 해석해 엔진에 넘길 문자열을 돌려준다.
결정론 fast path 우선: 정형 가격([\\d,]+원?)·버튼 값 그대로면 LLM 을 부르지 않는다.
자유 텍스트 + llm.enabled + 자격증명일 때만 InputInterpreter 호출. 해석 실패/미설정이면
원문 그대로 반환 → 기존 엔진의 재질문/기본분기 흐름이 그대로 동작(협상 불중단).
"""
if user_input is None:
return user_input
raw = str(user_input).strip()
if not raw:
return user_input
node = chat_engine.scripts.get(session.step, {})
mode = node.get("next_input_mode", "null")
options: list = []
if mode in _PRICE_MODES:
if SIMPLE_PRICE_RE.fullmatch(raw):
return user_input # 정형 가격 — 기존 결정론 파서 경로
elif mode in _CHOICE_MODES:
options = self._step_options(node)
if raw in options:
return user_input # 버튼 값 그대로 — 결정론 경로
else:
return user_input # 입력을 받지 않는 스텝
if not (engine.config.llm.enabled and InputInterpreter.available()):
return user_input
out = await self._interpreter.interpret(raw, input_mode=mode, input_options=options,
step_script=node.get("script"))
if out is None:
return user_input
LOG.i(f"[ChatService] NLU: {raw!r} → {out.kind}={out.value!r} (근거={out.source!r}) session={session.session_id}")
res.interpreted_input = out.value # 투명성: backend/front 가 해석 결과를 표시할 수 있게
return out.value
@staticmethod
def _step_options(node: dict) -> list:
"""현재 step 이 허용하는 선택지 — input_options 우선, next_step 분기 키 보강."""
opts = [str(o) for o in (node.get("input_options") or [])]
ns = node.get("next_step")
if isinstance(ns, dict):
for k in ns.keys():
if k != "default" and str(k) not in opts:
opts.append(str(k))
return opts
# ---- 학습 ---------------------------------------------------------- # ---- 학습 ----------------------------------------------------------
@staticmethod @staticmethod
def _acceptance_ratio(context: dict) -> float: def _acceptance_ratio(context: dict) -> float:
@@ -165,6 +293,11 @@ class ChatService:
async def _select_and_learn(self, engine: TenantEngine, chat_engine: ChatEngine, async def _select_and_learn(self, engine: TenantEngine, chat_engine: ChatEngine,
scripts: ScriptRepository, session: ChatSession, res: Res_Chat): scripts: ScriptRepository, session: ChatSession, res: Res_Chat):
# 종결 국면(라운드 만료·카드 소진, 엔진 check_iteration_limit 이 마킹): 규칙층이
# 종결 전술(중간값 절충/최후통첩)을 강제 발동한다 — RL 선택·학습 대상이 아니다.
if session.context.pop("force_closing", False):
await self._play_closing_tactic(engine, chat_engine, scripts, session, res)
return
snap = self._snapshot(session, NegotiationOutcome.ONGOING) snap = self._snapshot(session, NegotiationOutcome.ONGOING)
try: try:
idx = state_index(snap, engine.config.state) idx = state_index(snap, engine.config.state)
@@ -172,11 +305,30 @@ class ChatService:
LOG.e_no_callstack(f"[ChatService] state error: {ex}") LOG.e_no_callstack(f"[ChatService] state error: {ex}")
return return
policy, version_id, repo = await QTablePolicyStore.load(engine) policy, version_id, repo = await QTablePolicyStore.load(engine)
# action space 는 카탈로그 전체(engine.action_space_size)로 고정 — action_id↔카드 대응을
# 견적마다 일정하게 유지해 Q-table 학습 일관성을 지킨다. 견적 선택은 축소가 아니라
# available_mask 로 처리한다(선택 카드만 pickable, 사용분 제외 + 전술 발동조건 AND).
ctx = PolicyContext(state_index=idx, snapshot=snap, action_space_size=engine.action_space_size, ctx = PolicyContext(state_index=idx, snapshot=snap, action_space_size=engine.action_space_size,
available_mask=self._combined_mask(engine, session),
prior_bonus=self._selection_prior(engine, session),
episode=EpisodeState(used_action_ids=set(session.used_action_ids))) episode=EpisodeState(used_action_ids=set(session.used_action_ids)))
decision = policy.select(ctx) # 카드 '선택'은 DQN 서빙(활성 시), 학습/영속은 아래 Q-table 경로 그대로(오프폴리시 갱신).
# DQN 불가(비활성/번들 없음/후보 특징 없음)면 None → 기존 UCB 선택 폴백.
dqn = DQNServingStore.policy_for(engine)
decision = dqn.select(ctx) if dqn is not None else None
selector_name = dqn.name if decision is not None else policy.name
if decision is None:
decision = policy.select(ctx)
session.used_action_ids.add(decision.action_id) session.used_action_ids.add(decision.action_id)
card_id = engine.mapper.get_card_id(decision.action_id) card_id = self._card_id_for_action(engine, session, decision.action_id)
# 전술 실행(재설계): 카드의 가격 행동 — 카운터 제시가를 계산해 세션에 적재한다.
# pending 이 있으면 이 턴은 수락/거절 스텝(가격협상_카운터)으로 전환되고,
# 협력사가 수락하면 이 가격으로 즉시 타결된다(chat_engine 의 수락 메커니즘).
spec = tactic_for(card_id)
counter = compute_counter(spec, session.context) if tactic_available(spec, session.context) else None
if counter is not None:
session.context["pending_counter_price"] = counter
session.context["prev_customer_price"] = counter # 갑의 최신 포지션(middle_price 기준)
reward = RewardCalculator(engine.config.reward, engine.config.state).calculate(snap) reward = RewardCalculator(engine.config.reward, engine.config.state).calculate(snap)
policy.update(Transition(state_index=idx, action_id=decision.action_id, reward=reward.total, done=False)) policy.update(Transition(state_index=idx, action_id=decision.action_id, reward=reward.total, done=False))
await QTablePolicyStore.persist_cell(repo, version_id, policy, idx, decision.action_id) await QTablePolicyStore.persist_cell(repo, version_id, policy, idx, decision.action_id)
@@ -185,7 +337,7 @@ class ChatService:
await self._log(repo, session, idx, decision.action_id, card_id, snap, reward, decision.propensity, done=False) await self._log(repo, session, idx, decision.action_id, card_id, snap, reward, decision.propensity, done=False)
res.card_id = card_id res.card_id = card_id
res.policy = policy.name res.policy = selector_name
res.q_value = decision.q_value res.q_value = decision.q_value
res.updated_q = float(policy.qtable.q[idx, decision.action_id]) res.updated_q = float(policy.qtable.q[idx, decision.action_id])
res.visit_count = int(policy.qtable.visits[idx, decision.action_id]) res.visit_count = int(policy.qtable.visits[idx, decision.action_id])
@@ -195,7 +347,17 @@ class ChatService:
# ① 선택된 카드의 스크립트를 봇 메시지(script)로 출력 ② 협상지표 게이지(indicator_value) 동봉. # ① 선택된 카드의 스크립트를 봇 메시지(script)로 출력 ② 협상지표 게이지(indicator_value) 동봉.
# backend/front 가 indicator/bot_chat_type 패스스루·게이지 렌더 준비 완료 → 값만 채우면 표시된다. # backend/front 가 indicator/bot_chat_type 패스스루·게이지 렌더 준비 완료 → 값만 채우면 표시된다.
# 카드 멘트: backoffice_db 모드면 card.nego_cards.script(negodata 편집 정본), 아니면 파일 폴백. # 카드 멘트: backoffice_db 모드면 card.nego_cards.script(negodata 편집 정본), 아니면 파일 폴백.
card_script = await scripts.resolve_card_script(decision.action_id, card_id, chat_engine.vars_for(session)) template, tone, strategy = await scripts.resolve_card_template(
decision.action_id, card_id,
prefer_db=bool(session.context.get("selected_nego_card_numbers")),
)
# Phase 2 표현층: llm.enabled(테넌트) + 자격증명 있으면 템플릿을 상황 맞춤 자연화.
# placeholder 유지 상태로 재작성 → 검증(치환자/숫자) → 실패·타임아웃 시 원본 폴백.
if template and engine.config.llm.enabled and ScriptNaturalizer.available():
naturalized = await self._naturalizer.naturalize(
template, situation=build_situation(session.context), tone=tone, strategy=strategy)
template = naturalized or template
card_script = scripts.format_script(template, chat_engine.vars_for(session)) if template else None
if card_script: if card_script:
res.script = card_script res.script = card_script
c = session.context c = session.context
@@ -205,6 +367,92 @@ class ChatService:
res.indicator_range = ind[1] res.indicator_range = ind[1]
res.bot_chat_type = "indicator" res.bot_chat_type = "indicator"
# 카운터 제시 카드면 수락/거절 스텝(가격협상_카운터)으로 전환 — 카드 멘트({target_price} 등
# 카운터가 포함)는 그대로 두고, 입력만 [수락|다른 가격 제시] 버튼으로 바꾼다.
if counter is not None:
view2 = chat_engine.render_step(session, "가격협상_카운터")
res.step, res.client_step = view2.step, view2.client_step
res.input_mode, res.input_options = view2.input_mode, view2.input_options
if not card_script:
res.script = view2.script # 카드 멘트 없으면 스텝 기본 카운터 멘트
async def _play_closing_tactic(self, engine: TenantEngine, chat_engine: ChatEngine,
scripts: ScriptRepository, session: ChatSession, res: Res_Chat):
"""종결 국면 강제 전술 — 견적에서 선택한 종결 와일드카드(WC-05 중간값 절충 등) 우선,
없으면 목표가 최후통첩. 최종 카운터를 제시하고 수락/거절 스텝으로 전환한다.
규칙층의 강제 결정이므로 RL 선택/학습을 우회한다."""
ctx = session.context
ctx["closing_played"] = True
# 선택 와일드카드 중 종결 전술 (WC-05/WC-03) — 순서대로 첫 매치.
closing_number = next(
(str(n) for n in (ctx.get("selected_wild_card_numbers") or []) if tactic_for(str(n)).closing),
None,
)
counter = compute_counter(tactic_for(closing_number), ctx) if closing_number else None
if counter is None:
# 폴백 최후통첩: 목표가 제시 (여기 도달 = 제시가 > target 이므로 항상 유효한 카운터).
target = int(ctx.get("target_price") or 0)
counter = target if 0 < target < ctx.get("input_price", 0) else None
if counter is None:
return # 컨텍스트 이상 — 기존 가격협상 스텝 그대로(재제안 요구)
ctx["pending_counter_price"] = counter
ctx["prev_customer_price"] = counter
template = None
if closing_number:
template = await scripts.resolve_wild_card_template(closing_number)
if template and engine.config.llm.enabled and ScriptNaturalizer.available():
template = (await self._naturalizer.naturalize(
template, situation=build_situation(ctx))) or template
view2 = chat_engine.render_step(session, "가격협상_카운터")
res.step, res.client_step = view2.step, view2.client_step
res.input_mode, res.input_options = view2.input_mode, view2.input_options
res.script = scripts.format_script(template, chat_engine.vars_for(session)) if template else view2.script
res.card_id = closing_number
async def _autonomy_learn(self, engine: TenantEngine, session: ChatSession, view: StepView, res: Res_Chat):
"""완전 자율 행동 로깅 — Q-table 은 건드리지 않고 experience_logs 만 적재한다.
action_id = autonomy_actions.ACTIONS 인덱스, card_id = "AUT|종류|위치|전략" (카드 재학습
파이프라인이 임베딩 매칭에서 자동 제외하도록 프리픽스로 구분). 종료 시 최종 보상 행(done=True)을
남겨 retrain 의 에피소드 재구성 규약(카드턴 N + 종료 1)과 정합을 맞춘다.
"""
def _card_id(d) -> str:
return f"AUT|{d['kind']}|{d['q']:g}|{d['s']}"[:40]
ctx = session.context
lrepo = LearningRepository(engine.company_id)
pending = ctx.pop("autonomy_pending", None)
if pending is not None:
snap = self._snapshot(session, NegotiationOutcome.ONGOING)
try:
idx = state_index(snap, engine.config.state) # 로깅 호환용 이산 인덱스
except ValueError:
idx = 0 # 자율 모드는 이산 상태를 쓰지 않으므로 폴백해도 학습 오염 없음
if ctx.get("autonomy_last"):
ctx["autonomy_prev"] = ctx["autonomy_last"] # 직전 결정 보존 — 멘트 생성 힌트(양보 언급)용
ctx["autonomy_last"] = dict(pending, state_index=idx)
if pending.get("kind") == "counter":
# 역제안 기억은 별도 키로 보존 — autonomy_last 는 '마지막 행동'이라 사이에 낀
# 설득이 덮어쓴다. 단조 봉투·탄약소진 판정이 이 기억을 기준으로 해야
# counter→press→counter 에서 제안 철회가 새지 않는다 (게이트가 잡은 실버그).
ctx["autonomy_last_counter"] = dict(pending)
if pending.get("kind") == "press":
# 설득 횟수 누적 — 역제시 해금 조건(autonomy_store ③)의 카운터.
ctx["autonomy_press_n"] = int(ctx.get("autonomy_press_n") or 0) + 1
reward = RewardCalculator(engine.config.reward, engine.config.state).calculate(snap)
await self._log(lrepo, session, idx, pending["idx"], _card_id(pending), snap,
reward, (1.0 - 0.1) + 0.1 / len(AUTONOMY_ACTIONS), done=False)
res.policy = "full_autonomy"
last = ctx.get("autonomy_last")
if view.outcome is not None and last is not None:
oc = NegotiationOutcome.SUCCESS if view.outcome == "success" else NegotiationOutcome.FAILURE
snap = self._snapshot(session, oc)
reward = RewardCalculator(engine.config.reward, engine.config.state).calculate(snap)
res.reward_total = reward.total
await self._log(lrepo, session, last["state_index"], last["idx"], _card_id(last), snap,
reward, None, done=True)
async def _terminal_learn(self, engine: TenantEngine, session: ChatSession, outcome: str, res: Res_Chat): async def _terminal_learn(self, engine: TenantEngine, session: ChatSession, outcome: str, res: Res_Chat):
oc = NegotiationOutcome.SUCCESS if outcome == "success" else NegotiationOutcome.FAILURE oc = NegotiationOutcome.SUCCESS if outcome == "success" else NegotiationOutcome.FAILURE
snap = self._snapshot(session, oc) snap = self._snapshot(session, oc)
@@ -218,9 +466,83 @@ class ChatService:
policy.update(Transition(state_index=last_state, action_id=last_action, reward=reward.total, done=True)) policy.update(Transition(state_index=last_state, action_id=last_action, reward=reward.total, done=True))
await QTablePolicyStore.persist_cell(repo, version_id, policy, last_state, last_action) await QTablePolicyStore.persist_cell(repo, version_id, policy, last_state, last_action)
await self._log(repo, session, last_state, last_action, await self._log(repo, session, last_state, last_action,
engine.mapper.get_card_id(last_action), snap, reward, None, done=True) self._card_id_for_action(engine, session, last_action), snap, reward, None, done=True)
res.updated_q = float(policy.qtable.q[last_state, last_action]) res.updated_q = float(policy.qtable.q[last_state, last_action])
@staticmethod
def _card_id_for_action(engine: TenantEngine, session: ChatSession, action_id: int) -> Optional[str]:
# action_id ↔ 카드는 테넌트 매핑(action_to_card)으로 고정한다. 견적 선택은 available_mask 로
# 걸러지므로 여기서 selected 리스트를 인덱싱하지 않는다 — 인덱싱하면 견적마다 action_id 의미가
# 달라져(같은 action_id 가 다른 카드) Q-table 학습이 오염된다.
return engine.mapper.get_card_id(action_id)
@staticmethod
def _selection_mask(engine: TenantEngine, session: ChatSession) -> Optional[np.ndarray]:
"""견적에서 선택한 카드(selected_nego_card_numbers)만 pickable 로 하는 available_mask.
action space 전체(engine.action_space_size) 크기의 bool 배열. 선택 카드의 action_id 만 True,
이미 사용한 action 은 False. 선택이 없거나(직접호출/데모) 매핑 불가면 None → 전체 허용(폴백).
번호(card.nego_cards.number)와 action_to_card 값이 일치해야 매핑된다.
"""
selected = session.context.get("selected_nego_card_numbers") or []
if not selected:
return None
used = set(session.used_action_ids)
selected_ids = {engine.mapper.get_action_id(str(n)) for n in selected}
selected_ids.discard(None)
if not selected_ids:
return None # 매핑에 없는 번호뿐 → 폴백(전체 허용)
return np.array(
[(a in selected_ids and a not in used) for a in range(engine.action_space_size)],
dtype=bool,
)
@classmethod
def _combined_mask(cls, engine: TenantEngine, session: ChatSession) -> Optional[np.ndarray]:
"""견적 선택 마스크 AND 전술 발동조건 마스크.
결합 결과가 전부 False 면(선택 카드가 모두 발동 불가) 선택 마스크 단독으로 폴백 —
협상은 멈추지 않고(HOLD 설득으로라도 진행), 종결은 라운드 규칙이 처리한다.
"""
sel = cls._selection_mask(engine, session)
tac = cls._tactic_mask(engine, session)
if tac is None:
return sel
if sel is None:
return tac if tac.any() else None
both = sel & tac
return both if both.any() else sel
@staticmethod
def _tactic_mask(engine: TenantEngine, session: ChatSession) -> Optional[np.ndarray]:
"""전술 발동조건(min_round·가격구간)을 만족하는 action 만 True. HOLD(설득)는 항상 True.
전부 True 면 None(마스크 불필요)."""
mask = np.array(
[tactic_available(tactic_for(engine.mapper.get_card_id(a)), session.context)
for a in range(engine.action_space_size)],
dtype=bool,
)
return None if mask.all() else mask
@staticmethod
def _selection_prior(engine: TenantEngine, session: ChatSession) -> Optional[np.ndarray]:
"""의도층 prior(Phase 1) — 견적에서 고른 카드 순서를 콜드 스타트 선호로 반영.
갑이 먼저 고른 카드일수록 높은 보너스(최대 0.3, 순위 선형 감소). UCB 점수에
1/(1+visits) 감쇠로 더해지므로 학습이 쌓이면 Q 가 지배한다(오염 없음).
선택이 2장 미만이면 순서 정보가 무의미 → None.
"""
selected = session.context.get("selected_nego_card_numbers") or []
if len(selected) < 2:
return None
prior = np.zeros(engine.action_space_size)
n = len(selected)
for rank, num in enumerate(selected):
a = engine.mapper.get_action_id(str(num))
if a is not None and a < engine.action_space_size:
prior[a] = 0.3 * (n - rank) / n
return prior if prior.any() else None
async def _log(self, repo: LearningRepository, session, state_index, action_id, card_id, snap, reward, propensity, done): async def _log(self, repo: LearningRepository, session, state_index, action_id, card_id, snap, reward, propensity, done):
data = { data = {
"session_id": session.session_id, "state_index": state_index, "action_id": action_id, "session_id": session.session_id, "state_index": state_index, "action_id": action_id,
+64
View File
@@ -0,0 +1,64 @@
"""회사 프로필(브랜드) DB 조회 — 자동 온보딩 고객사의 {company_name} 을 DB 에서 채운다.
스크립트의 {company_name} 은 지금까지 tenant.yaml resources.company_name(_base 기본값)에서 왔다.
자동 온보딩 고객사(전용 yaml 없음)는 전부 _base 브랜드로 나가므로, 실제 회사명(company.companies.name)을
company_id 로 조회해 엔진 조립 시 덮어쓴다. 회사 정보라 튜닝 오버레이와는 별개 관심사다.
스키마 소유권: company 스키마는 backend/negodata 소유 — read-only. 경량 table()/column() 구성.
"""
import uuid
from abc import ABC, abstractmethod
from typing import Optional, Tuple
from sqlalchemy import column, select, table
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.db_session_manager import DB_SESSION_MNG
from common.enums import DBType, DBWRType, ErrorType
from common.logger import LOG
_COMPANIES = table("companies", column("company_id"), column("name"), column("deleted"), schema="company")
class ICompanyProfileRepository(ABC):
@abstractmethod
async def get_company_name(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, Optional[str]]:
"""company.companies.name by company_id. 없으면 None."""
...
class CompanyProfileRepository(ICompanyProfileRepository):
async def get_company_name(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, Optional[str]]:
try:
query = (
select(_COMPANIES.c.name)
.where(_COMPANIES.c.company_id == company_id, _COMPANIES.c.deleted == False) # noqa: E712
.limit(1)
)
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_company_name failed.", raise_error=False)
if err_type != ErrorType.SUCCESS or not rows or not rows[0]:
return err_type, None
return ErrorType.SUCCESS, str(rows[0])
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, None
async def resolve_company_name(repo: ICompanyProfileRepository, tenant_key: str) -> Optional[str]:
"""tenant_key(= company_id UUID)로 회사명 조회. 비-UUID(데모 테넌트)면 조회 안 함(None).
세션/트랜잭션 경계를 여기서 관리(execute_lambda)한다."""
try:
cid = uuid.UUID(tenant_key)
except (ValueError, TypeError):
return None # imarketkorea 등 데모 테넌트명 → 파일 브랜드 유지
async def _q(s):
_, name = await repo.get_company_name(s, cid)
return name
try:
return await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
except Exception as ex:
LOG.e_no_callstack(f"[company_profile] 회사명 조회 실패 company_id={tenant_key}: {ex}")
return None
+5
View File
@@ -148,6 +148,11 @@ class NegotiationConfig(BaseModel):
anchor_rate: float = 0.01 # 목표가 대비 앵커링 인하율 (기본 1%) anchor_rate: float = 0.01 # 목표가 대비 앵커링 인하율 (기본 1%)
max_rounds: int = 5 # 라운드 상한(보조). 실제 종료는 '카드 소진' 기준. max_rounds: int = 5 # 라운드 상한(보조). 실제 종료는 '카드 소진' 기준.
# 결정 스택 규칙층(Phase 1) — ChatEngine 하드코딩을 테넌트별 데이터로.
wildcard_1pct_ratio: float = 1.02 # 제시가 ≤ anchor×비율 → 1% 인하 와일드카드로 마무리 유도
wildcard_entry_ratio: float = 1.05 # 선택 와일드카드 허용 시 와일드카드 진입 상한(anchor×비율)
max_counter_rounds: int = 3 # 에이전트 카운터 제안 상한(초과 시 협상실패 종료)
def anchor_for(self, target_price: float) -> float: def anchor_for(self, target_price: float) -> float:
return round(target_price * (1.0 - self.anchor_rate)) return round(target_price * (1.0 - self.anchor_rate))
+72 -5
View File
@@ -8,14 +8,34 @@ Chat_server 는 `chat_engine = ChatEngine()` 전역 무인자 싱글톤이라
""" """
import asyncio import asyncio
import uuid
from collections import defaultdict from collections import defaultdict
from typing import Dict, Optional from typing import Dict, Optional
def _as_uuid(key: Optional[str]):
"""key 가 UUID(실 고객사 company_id)면 uuid.UUID 반환, 데모 테넌트명 등이면 None."""
try:
return uuid.UUID(key)
except (ValueError, TypeError):
return None
from common.database.db_session_manager import DB_SESSION_MNG
from common.enums import DBType, DBWRType, ErrorType
from common.logger import LOG from common.logger import LOG
from negotiation.cards.action_card_mapper import ActionCardMapper from negotiation.cards.action_card_mapper import ActionCardMapper
from negotiation.cards.adapters.card_catalog_db import CardCatalogDbRepository
from negotiation.cards.ports.card_catalog_port import ICardCatalogRepository
from tenancy.company_profile_repo import (
CompanyProfileRepository,
ICompanyProfileRepository,
resolve_company_name,
)
from tenancy.config import TenantConfig from tenancy.config import TenantConfig
from tenancy.config_loader import TenantConfigLoader from tenancy.config_loader import TenantConfigLoader
_CARD_SOURCE_DB = "db"
class TenantEngine: class TenantEngine:
"""한 테넌트의 협상 엔진 조립체 (불변 협력자 보관). """한 테넌트의 협상 엔진 조립체 (불변 협력자 보관).
@@ -49,9 +69,13 @@ class EngineFactory:
class TenantEngineRegistry: class TenantEngineRegistry:
def __init__(self, loader: Optional[TenantConfigLoader] = None, factory: type[EngineFactory] = EngineFactory): def __init__(self, loader: Optional[TenantConfigLoader] = None, factory: type[EngineFactory] = EngineFactory,
catalog_repo: Optional[ICardCatalogRepository] = None,
company_repo: Optional[ICompanyProfileRepository] = None):
self._loader = loader or TenantConfigLoader() self._loader = loader or TenantConfigLoader()
self._factory = factory self._factory = factory
self._catalog_repo = catalog_repo or CardCatalogDbRepository()
self._company_repo = company_repo or CompanyProfileRepository()
self._engines: Dict[str, TenantEngine] = {} self._engines: Dict[str, TenantEngine] = {}
self._locks: Dict[str, asyncio.Lock] = defaultdict(asyncio.Lock) self._locks: Dict[str, asyncio.Lock] = defaultdict(asyncio.Lock)
@@ -69,8 +93,7 @@ class TenantEngineRegistry:
return cached return cached
if not self.is_registered(tenant_id): if not self.is_registered(tenant_id):
raise KeyError(f"unregistered tenant: {tenant_id}") raise KeyError(f"unregistered tenant: {tenant_id}")
config = self._loader.load(tenant_id) engine = await self._build(tenant_id)
engine = self._factory.build(config)
self._engines[tenant_id] = engine self._engines[tenant_id] = engine
LOG.i(f"[TenantEngineRegistry] built engine tenant_id={tenant_id} " LOG.i(f"[TenantEngineRegistry] built engine tenant_id={tenant_id} "
f"state={engine.state_space_size} action={engine.action_space_size}") f"state={engine.state_space_size} action={engine.action_space_size}")
@@ -83,11 +106,55 @@ class TenantEngineRegistry:
self._engines.pop(tenant_id, None) self._engines.pop(tenant_id, None)
if not self.is_registered(tenant_id): if not self.is_registered(tenant_id):
return None return None
config = self._loader.load(tenant_id) engine = await self._build(tenant_id)
engine = self._factory.build(config)
self._engines[tenant_id] = engine self._engines[tenant_id] = engine
return engine return engine
# ---- 조립 (카탈로그 DB 유래 반영) ----------------------------------
async def _build(self, tenant_id: str) -> TenantEngine:
config = self._loader.load(tenant_id)
# action_mapping.type == "db" 면 카드 카탈로그(card.nego_cards)에서 action_to_card 를 동적 구성.
# Q-table action 축을 config 파일이 아니라 negodata 카탈로그가 정의한다(결합 제거).
if config.action_mapping.type == _CARD_SOURCE_DB:
await self._apply_db_catalog(config)
# 브랜드: 자동 온보딩 고객사(company_id=UUID)면 company.companies.name 으로 {company_name} 을 덮어쓴다.
# 데모 테넌트(비-UUID)·미조회 시 파일 resources.company_name 유지.
await self._apply_company_brand(config, tenant_id)
return self._factory.build(config)
async def _apply_company_brand(self, config: TenantConfig, tenant_id: str) -> None:
name = await resolve_company_name(self._company_repo, config.company_id or tenant_id)
if name:
config.resources.company_name = name
async def _apply_db_catalog(self, config: TenantConfig) -> None:
"""DB 카탈로그로 config.action_mapping.action_to_card 를 덮어쓴다(성공 시).
공용 카드 + 회사 전용 카드(company_id UUID 인 경우)로 action space 를 구성한다.
비었거나 DB 불가면 config 의 파일 action_to_card 를 그대로 폴백 사용한다."""
cid = _as_uuid(config.company_id or config.tenant_id) # UUID(실 고객사)면 회사 카드 포함
async def _q(s):
_, numbers = await self._catalog_repo.get_nego_catalog(s, cid)
return numbers
try:
numbers = await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
except Exception as ex:
LOG.e_no_callstack(f"[TenantEngineRegistry] 카탈로그 조회 실패 tenant={config.tenant_id}: {ex} → 파일 폴백")
return
if not numbers:
LOG.w(f"[TenantEngineRegistry] 카탈로그 비어있음 tenant={config.tenant_id} → 파일 action_to_card 폴백")
return
config.action_mapping.action_to_card = {str(i): num for i, num in enumerate(numbers)}
def clear_all(self) -> int:
"""캐시된 엔진 전체를 비운다(공용 카탈로그 변경 등 전역 반영용). 반환: 비운 엔진 수.
다음 요청에서 각 테넌트 엔진이 최신 카탈로그/config 로 재조립된다."""
n = len(self._engines)
self._engines.clear()
self._loader.invalidate() # 인자 없이 = 전체 config 캐시 무효화
return n
def cached_tenants(self) -> list[str]: def cached_tenants(self) -> list[str]:
return list(self._engines.keys()) return list(self._engines.keys())
@@ -15,5 +15,7 @@
"가격협상_와일드": "가격협상", "가격협상_와일드": "가격협상",
"협상완료": "협상종료", "협상완료": "협상종료",
"협상실패": "협상종료", "협상실패": "협상종료",
"협상종료": "협상종료" "협상종료": "협상종료",
} "가격협상_카운터": "가격협상",
"wild_card_dynamic": "가격협상"
}
@@ -5,7 +5,9 @@
"editor_script_id": "시작", "editor_script_id": "시작",
"next_input_mode": "null", "next_input_mode": "null",
"input_options": [], "input_options": [],
"next_step": { "default": "서비스안내" }, "next_step": {
"default": "서비스안내"
},
"type": "null", "type": "null",
"chat_end": false "chat_end": false
}, },
@@ -13,8 +15,12 @@
"script": "안녕하세요. {company_name} {service_name}입니다. 본 서비스는 {company_name}와 협력사 간 물품 공급 가격 협상을 위한 것으로, 귀사가 공급 중인 품목의 새로운 가격 협상을 진행합니다. 안내 사항을 확인하신 뒤, 다음 단계로 넘어가려면 [확인]을 눌러 주세요.", "script": "안녕하세요. {company_name} {service_name}입니다. 본 서비스는 {company_name}와 협력사 간 물품 공급 가격 협상을 위한 것으로, 귀사가 공급 중인 품목의 새로운 가격 협상을 진행합니다. 안내 사항을 확인하신 뒤, 다음 단계로 넘어가려면 [확인]을 눌러 주세요.",
"editor_script_id": "서비스안내", "editor_script_id": "서비스안내",
"next_input_mode": "confirm", "next_input_mode": "confirm",
"input_options": ["확인"], "input_options": [
"next_step": { "default": "담당자확인" }, "확인"
],
"next_step": {
"default": "담당자확인"
},
"type": "text", "type": "text",
"chat_end": false "chat_end": false
}, },
@@ -22,8 +28,14 @@
"script": "본 안내는 협력사 포털에 등록된 담당자에게 발송되었습니다. 구매 협상 담당자가 맞는지 다시 한 번 확인 부탁드립니다. 담당자가 맞다면 [예], 맞지 않다면 [아니오]를 선택해 주세요.", "script": "본 안내는 협력사 포털에 등록된 담당자에게 발송되었습니다. 구매 협상 담당자가 맞는지 다시 한 번 확인 부탁드립니다. 담당자가 맞다면 [예], 맞지 않다면 [아니오]를 선택해 주세요.",
"editor_script_id": "담당자확인", "editor_script_id": "담당자확인",
"next_input_mode": "yes_no", "next_input_mode": "yes_no",
"input_options": ["예", "아니오"], "input_options": [
"next_step": { "예": "협상품목안내", "아니오": "담당자확인_아니오" }, "예",
"아니오"
],
"next_step": {
"예": "협상품목안내",
"아니오": "담당자확인_아니오"
},
"type": "text", "type": "text",
"chat_end": false "chat_end": false
}, },
@@ -31,8 +43,14 @@
"script": "[아니오]를 선택하셨습니다. 담당자가 변경되어 정보를 수정하시려면 [정보변경]을, 실수로 선택하신 경우 다시 진행하려면 [돌아가기]를 선택해 주세요.", "script": "[아니오]를 선택하셨습니다. 담당자가 변경되어 정보를 수정하시려면 [정보변경]을, 실수로 선택하신 경우 다시 진행하려면 [돌아가기]를 선택해 주세요.",
"editor_script_id": "담당자확인_아니오", "editor_script_id": "담당자확인_아니오",
"next_input_mode": "yes_no", "next_input_mode": "yes_no",
"input_options": ["돌아가기", "정보변경"], "input_options": [
"next_step": { "돌아가기": "담당자확인", "정보변경": "정보변경_완료" }, "돌아가기",
"정보변경"
],
"next_step": {
"돌아가기": "담당자확인",
"정보변경": "정보변경_완료"
},
"type": "text", "type": "text",
"chat_end": false "chat_end": false
}, },
@@ -49,8 +67,12 @@
"script": "{company_name}는 귀사의 협력에 진심으로 감사드립니다. 이번 가격 협상 품목과 기본 정보를 안내드립니다. 좌측의 상품 정보를 확인해 주세요. 협상이 원만히 마무리되면 더 많은 협력 기회가 마련될 수 있습니다.", "script": "{company_name}는 귀사의 협력에 진심으로 감사드립니다. 이번 가격 협상 품목과 기본 정보를 안내드립니다. 좌측의 상품 정보를 확인해 주세요. 협상이 원만히 마무리되면 더 많은 협력 기회가 마련될 수 있습니다.",
"editor_script_id": "협상품목안내", "editor_script_id": "협상품목안내",
"next_input_mode": "confirm", "next_input_mode": "confirm",
"input_options": ["확인"], "input_options": [
"next_step": { "확인": "기존가격제시" }, "확인"
],
"next_step": {
"확인": "기존가격제시"
},
"type": "text", "type": "text",
"chat_end": false "chat_end": false
}, },
@@ -59,7 +81,9 @@
"editor_script_id": "기존가격제시", "editor_script_id": "기존가격제시",
"next_input_mode": "price", "next_input_mode": "price",
"input_options": [], "input_options": [],
"next_step": { "default": "가격협상_확인" }, "next_step": {
"default": "가격협상_확인"
},
"type": "text", "type": "text",
"chat_end": false "chat_end": false
}, },
@@ -68,22 +92,42 @@
"editor_script_id": "가격협상_재입력", "editor_script_id": "가격협상_재입력",
"next_input_mode": "price", "next_input_mode": "price",
"input_options": [], "input_options": [],
"next_step": { "default": "가격협상_확인" }, "next_step": {
"default": "가격협상_확인"
},
"type": "text", "type": "text",
"chat_end": false "chat_end": false
}, },
"가격협상_확인": { "가격협상_확인": {
"script": "제시하신 가격은 **{input_price}원**으로, 기존 공급가 대비 약 **{discount_rate}%** 인하된 금액입니다. 이 금액으로 제안하시겠습니까? 수정하시려면 [아니오]를 선택해 주세요.", "script": "제시하신 가격은 **{input_price}원**입니다. {discount_phrase}이 금액으로 제안하시겠습니까? 수정하시려면 [아니오]를 선택해 주세요.",
"editor_script_id": "가격협상_확인", "editor_script_id": "가격협상_확인",
"next_input_mode": "yes_no", "next_input_mode": "yes_no",
"input_options": ["예", "아니오"], "input_options": [
"예",
"아니오"
],
"next_step": { "next_step": {
"예": [ "예": [
{ "condition": "check_wildcard_entry", "next": "가격협상_와일드" }, {
{ "condition": "check_is_supplier_type_c", "next": "협상완료" }, "condition": "check_wildcard_entry",
{ "condition": "check_price_match", "next": "협상완료" }, "next": "가격협상_와일드"
{ "condition": "check_iteration_limit", "next": "협상실패" }, },
{ "condition": "default", "next": "가격협상" } {
"condition": "check_is_supplier_type_c",
"next": "협상완료"
},
{
"condition": "check_price_match",
"next": "협상완료"
},
{
"condition": "check_iteration_limit",
"next": "협상실패"
},
{
"condition": "default",
"next": "가격협상"
}
], ],
"아니오": "가격협상_재입력" "아니오": "가격협상_재입력"
}, },
@@ -94,8 +138,14 @@
"script": "제시하신 금액은 **{input_price}원**입니다. 이 금액으로 견적을 제출하시겠습니까? 수정하시려면 [아니오]를 선택해 주세요.", "script": "제시하신 금액은 **{input_price}원**입니다. 이 금액으로 견적을 제출하시겠습니까? 수정하시려면 [아니오]를 선택해 주세요.",
"editor_script_id": "가격협상_확인_버짓", "editor_script_id": "가격협상_확인_버짓",
"next_input_mode": "yes_no", "next_input_mode": "yes_no",
"input_options": ["예", "아니오"], "input_options": [
"next_step": { "예": "협상완료", "아니오": "가격협상_재입력" }, "예",
"아니오"
],
"next_step": {
"예": "협상완료",
"아니오": "가격협상_재입력"
},
"type": "text", "type": "text",
"chat_end": false "chat_end": false
}, },
@@ -104,7 +154,9 @@
"editor_script_id": "가격협상", "editor_script_id": "가격협상",
"next_input_mode": "price", "next_input_mode": "price",
"input_options": [], "input_options": [],
"next_step": { "default": "가격협상_확인" }, "next_step": {
"default": "가격협상_확인"
},
"type": "text", "type": "text",
"chat_end": false "chat_end": false
}, },
@@ -112,8 +164,12 @@
"script": "협조해 주신 덕분에 원만히 협상이 완료되었습니다. 협상 결과를 확인하신 뒤 동의해 주세요. 거래 약정에 따라 일부 조건이 조정될 수 있는 점 참고 부탁드립니다. 성실히 응해 주셔서 감사합니다.", "script": "협조해 주신 덕분에 원만히 협상이 완료되었습니다. 협상 결과를 확인하신 뒤 동의해 주세요. 거래 약정에 따라 일부 조건이 조정될 수 있는 점 참고 부탁드립니다. 성실히 응해 주셔서 감사합니다.",
"editor_script_id": "협상완료", "editor_script_id": "협상완료",
"next_input_mode": "confirm", "next_input_mode": "confirm",
"input_options": ["협상 내용을 확인했으며, 이의가 없음에 동의합니다."], "input_options": [
"next_step": { "default": "협상종료" }, "협상 내용을 확인했으며, 이의가 없음에 동의합니다."
],
"next_step": {
"default": "협상종료"
},
"type": "text", "type": "text",
"chat_end": false "chat_end": false
}, },
@@ -122,7 +178,9 @@
"editor_script_id": "협상실패", "editor_script_id": "협상실패",
"next_input_mode": "null", "next_input_mode": "null",
"input_options": [], "input_options": [],
"next_step": { "default": "협상종료" }, "next_step": {
"default": "협상종료"
},
"type": "text", "type": "text",
"chat_end": false "chat_end": false
}, },
@@ -134,5 +192,21 @@
"next_step": null, "next_step": null,
"type": "text", "type": "text",
"chat_end": true "chat_end": true
},
"가격협상_카운터": {
"script": "제시해 주신 **{input_price}원** 검토했습니다. 저희는 **{counter_price}원**을 제안드립니다. 이 가격으로 진행 가능하시면 '수락'을, 어려우시면 '다른 가격 제시'를 선택해 주세요.",
"editor_script_id": "가격협상_카운터",
"next_input_mode": "yes_no",
"input_options": [
"수락",
"다른 가격 제시"
],
"next_step": {
"수락": "협상완료",
"다른 가격 제시": "가격협상_재입력",
"default": "가격협상_재입력"
},
"type": "text",
"chat_end": false
} }
} }
@@ -5,8 +5,13 @@
"type": "text", "type": "text",
"chat_end": false, "chat_end": false,
"next_input_mode": "yes_no", "next_input_mode": "yes_no",
"input_options": ["예", "아니오"], "input_options": [
"next_step": { "default": "협상완료" }, "예",
"아니오"
],
"next_step": {
"default": "협상완료"
},
"editor_script_id": "wild_card_1pct" "editor_script_id": "wild_card_1pct"
}, },
"wild_card_budget": { "wild_card_budget": {
@@ -15,7 +20,24 @@
"chat_end": false, "chat_end": false,
"next_input_mode": "price", "next_input_mode": "price",
"input_options": [], "input_options": [],
"next_step": { "default": "가격협상_확인_버짓" }, "next_step": {
"default": "가격협상_확인_버짓"
},
"editor_script_id": "wild_card_budget" "editor_script_id": "wild_card_budget"
},
"wild_card_dynamic": {
"script": "저희는 **{counter_price}원**이면 즉시 진행이 가능합니다. 이 가격으로 진행 가능하시면 '수락'을, 어려우시면 '다른 가격 제시'를 선택해 주세요.",
"next_input_mode": "yes_no",
"input_options": [
"수락",
"다른 가격 제시"
],
"next_step": {
"수락": "협상완료",
"다른 가격 제시": "가격협상_재입력",
"default": "가격협상_재입력"
},
"type": "text",
"chat_end": false
} }
} }
+11 -4
View File
@@ -49,9 +49,14 @@ policy:
epsilon: 1.0e-6 epsilon: 1.0e-6
action_mapping: action_mapping:
type: file # db: action_to_card 를 card.nego_cards 카탈로그(user_id NULL, number 순)에서 동적 구성 — 정본.
# 기본 9카드 — 자동 온보딩(신규 company_id) 테넌트가 물려받는 카드 공간(base 정책 162×9와 정합). # 카드가 negodata 에서 추가/삭제되면 action space 가 자동 반영된다(config 수정 불필요).
# 테넌트는 자사 카탈로그(card.nego_cards/tenant_action_cards)로 override 한다. # 아래 action_to_card 는 DB 카탈로그가 비어있을 때만 쓰는 폴백(정합용 스냅샷)이다.
# file: 아래 action_to_card 를 그대로 사용(데모/오프라인).
type: db
# [폴백] 카탈로그 11장(카드_기획문서 일반카드) 스냅샷 — action_id 0~10 ↔ NGC-001~NGC-011.
# Q-table action 차원 = 카탈로그 크기. 견적별 선택은 action space 축소가 아니라 available_mask 로 처리
# (선택 카드만 pickable) — action_id↔카드 대응을 견적마다 일정하게 유지해 학습 일관성 보장.
action_to_card: action_to_card:
"0": "NGC-001" "0": "NGC-001"
"1": "NGC-002" "1": "NGC-002"
@@ -62,6 +67,8 @@ action_mapping:
"6": "NGC-007" "6": "NGC-007"
"7": "NGC-008" "7": "NGC-008"
"8": "NGC-009" "8": "NGC-009"
"9": "NGC-010"
"10": "NGC-011"
cards: cards:
# file: scripts_cards.json(파일) 사용. backoffice_db: card.nego_cards.script(negodata 편집 정본)를 # file: scripts_cards.json(파일) 사용. backoffice_db: card.nego_cards.script(negodata 편집 정본)를
@@ -71,7 +78,7 @@ cards:
connection: {} connection: {}
llm: llm:
enabled: false enabled: true
resources: resources:
language: ko language: ko
+6 -2
View File
@@ -23,7 +23,7 @@ reward:
action_mapping: action_mapping:
type: file type: file
action_to_card: # 동일 차원(9) 유지 → warm-start 가능. 합성 데모 코드(테넌트 B). action_to_card: # 동일 차원(11) 유지 → warm-start 가능. 합성 데모 코드(테넌트 B).
"0": "NGC-B001" "0": "NGC-B001"
"1": "NGC-B002" "1": "NGC-B002"
"2": "NGC-B003" "2": "NGC-B003"
@@ -33,9 +33,13 @@ action_mapping:
"6": "NGC-B007" "6": "NGC-B007"
"7": "NGC-B008" "7": "NGC-B008"
"8": "NGC-B009" "8": "NGC-B009"
"9": "NGC-B010"
"10": "NGC-B011"
llm: llm:
enabled: false enabled: true
# api_key_ref 는 미구현(dead) — 현재 LLM 키는 전역 config.local.toml [OpenAIConfig].api_key
# (또는 OPENAI_API_KEY env) 를 사용한다. 테넌트별 키 분리는 표현층(Phase 2) 본작업에서 구현.
api_key_ref: TENANT_B_OPENAI_API_KEY api_key_ref: TENANT_B_OPENAI_API_KEY
resources: resources:
-30
View File
@@ -1,30 +0,0 @@
# 데모 테넌트 프로파일 (합성/중립값 — CLEANROOM.md).
# tenant_id 는 라우팅 키일 뿐이며, 아래 값은 해당 회사의 실제 운영값이 아니다.
# 실제 운영 시 카드 카탈로그(card.nego_cards)·튜닝값은 테넌트 비공개 소스에서 주입한다.
tenant_id: ktcommerce
inherits_base: true
name: "Demo Tenant A"
company_id: null # P3 시드 시 company.companies.company_id(uuid) 로 채움
action_mapping:
type: file
action_to_card: # 우리 중립 데모 카드 코드(합성). 실제 카드 코드 아님.
"0": "NGC-A001"
"1": "NGC-A002"
"2": "NGC-A003"
"3": "NGC-A004"
"4": "NGC-A005"
"5": "NGC-A006"
"6": "NGC-A007"
"7": "NGC-A008"
"8": "NGC-A009"
llm:
enabled: false # P7 에서 테넌트별 자격증명 주입
api_key_ref: TENANT_A_OPENAI_API_KEY
resources:
language: ko
scripts_dir: resources # 없으면 _base/resources 폴백
company_name: "데모상사 A" # 스크립트 {company_name} 치환값 (합성)
service_name: "Negosium"
+2 -2
View File
@@ -29,7 +29,7 @@ def _reg():
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_4_1_honors_backend_session_id(db_engine): async def test_4_1_honors_backend_session_id(db_engine):
reset_sessions() reset_sessions()
eng = await _reg().get_engine("ktcommerce") eng = await _reg().get_engine("imarketkorea")
svc = ChatService() svc = ChatService()
# 첫 턴: backend 의 session_id 를 그대로 키로 써야 함 (새 uuid 발급 X) # 첫 턴: backend 의 session_id 를 그대로 키로 써야 함 (새 uuid 발급 X)
@@ -53,7 +53,7 @@ async def test_4_4_company_id_auto_onboard():
eng = await _reg().get_engine(COMPANY_ID) eng = await _reg().get_engine(COMPANY_ID)
assert eng.tenant_id == COMPANY_ID assert eng.tenant_id == COMPANY_ID
assert eng.company_id == COMPANY_ID # 학습/세션이 이 company_id 로 격리 assert eng.company_id == COMPANY_ID # 학습/세션이 이 company_id 로 격리
assert eng.action_space_size == 9 # base 기본 카드(162×9 정합) assert eng.action_space_size == 11 # base 기본 카드(162×11 정합)
assert eng.state_space_size == 162 assert eng.state_space_size == 162
+154
View File
@@ -0,0 +1,154 @@
"""협상카드 선택 E2E — 실 DB 왕복으로 "견적에서 고른 카드만 뽑히는지" 검증.
시나리오: 견적 생성 시 협상카드 2장(NGC-003, NGC-007)만 선택 →
version_nego_cards 로 연결 → 협상 세션 시작 → 가격협상 턴 2회 진행.
검증: ① 뽑힌 카드가 선택 2장 안에서만 나옴(선택 마스크) ② 세션 내 중복 없음(사용 마스크)
③ 카탈로그(DB, NGC-001~011) 기준 action space ④ 선택 없으면 전체 카탈로그 허용(폴백).
"""
import os
import uuid as _uuid
from datetime import datetime, timedelta, timezone
import pytest
from sqlalchemy import column, delete, insert, select, table
from common.database.db_session_manager import DB_SESSION_MNG
from common.enums import DBType, DBWRType, ErrorType
from router.v1.chat.protocol import Req_Chat
from services.chat_service import ChatService, reset_sessions
from tenancy.config_loader import TenantConfigLoader
from tenancy.registry import TenantEngineRegistry
_TENANTS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tenants")
_T_SESSIONS = table(
"sessions",
column("session_id"), column("quotation_id"), column("item_id"), column("supplier_id"),
column("qt_number"), column("qt_round"), column("qt_type"), column("target_price"),
column("anchoring_price"), column("status"), column("end_time"),
schema="negotiation",
)
_T_QUOTATIONS = table(
"quotations",
column("qt_id"), column("user_id"), column("qt_setting_id"), column("version_id"),
column("name"), column("number"), column("type"), column("status"),
column("start_time"), column("end_time"),
schema="quotation",
)
_T_VNC = table(
"version_nego_cards",
column("vnc_id"), column("version_id"), column("nego_card_id"),
schema="card",
)
_T_NEGO = table("nego_cards", column("nego_card_id"), column("number"), column("deleted"), schema="card")
async def _card_uuid(number: str):
def _q(s):
return DB_SESSION_MNG.execute(
s, select(_T_NEGO.c.nego_card_id).where(
_T_NEGO.c.number == number, _T_NEGO.c.deleted == False).limit(1)) # noqa: E712
_, rows = await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
return rows[0] if rows else None
@pytest.mark.asyncio
async def test_selected_cards_only_are_played(db_engine):
reset_sessions()
sid, qid, ver_id = _uuid.uuid4(), _uuid.uuid4(), _uuid.uuid4()
iid, sup = _uuid.uuid4(), _uuid.uuid4()
now = datetime.now(timezone.utc)
selected = ["NGC-003", "NGC-007"]
card_ids = {}
for n in selected:
card_ids[n] = await _card_uuid(n)
assert card_ids[n] is not None, f"카탈로그에 {n} 없음(시드 확인)"
def _seed(s_):
async def run(s):
e = await DB_SESSION_MNG.add(s, insert(_T_QUOTATIONS).values(
qt_id=qid, user_id=_uuid.uuid4(), qt_setting_id=_uuid.uuid4(), version_id=ver_id,
name="카드선택E2E", number="QT-CARDSEL-E2E", type=1, status=2,
start_time=now, end_time=now + timedelta(days=1)))
if e != ErrorType.SUCCESS:
return e
for n in selected: # 견적 생성 시 선택한 카드 2장
e = await DB_SESSION_MNG.add(s, insert(_T_VNC).values(
vnc_id=_uuid.uuid4(), version_id=ver_id, nego_card_id=card_ids[n]))
if e != ErrorType.SUCCESS:
return e
return await DB_SESSION_MNG.add(s, insert(_T_SESSIONS).values(
session_id=sid, quotation_id=qid, item_id=iid, supplier_id=sup,
qt_number="QT-CARDSEL-E2E", qt_round=1, qt_type=1,
target_price=10000, anchoring_price=9900, status=2,
end_time=now + timedelta(days=1)))
return run(s_)
err = await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [_seed])
assert err == ErrorType.SUCCESS
try:
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
eng = await reg.get_engine(str(_uuid.uuid4())) # 자동 온보딩(_base type:db → 실 DB 카탈로그)
assert eng.action_space_size == 11 # 카탈로그 11장(NGC-001~011)
svc = ChatService()
played = []
session_id = str(sid)
# 적응형 진행: 카드 전술 재설계 후 카운터 제시 카드(NGC-007 등)는 수락/거절 스텝
# (가격협상_카운터)으로 전환된다 — 거절하고 새 가격을 제시하며 카드 2턴을 유도한다.
prices = iter(["11000", "10600", "10400"])
r = await svc.chat(eng, Req_Chat(session_id=session_id))
for _ in range(14):
if r.step in ("가격협상", "가격협상_카운터") and r.card_id:
played.append(r.card_id)
if len(played) == 2:
break
if r.chat_end:
break
if r.input_mode == "price":
ui = next(prices)
elif r.step == "가격협상_카운터":
ui = "다른 가격 제시"
elif r.input_options:
ui = "예" if "예" in r.input_options else r.input_options[0]
else:
ui = "확인"
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input=ui))
assert len(played) == 2, f"가격협상 카드 턴 2회 기대, 실제 {played}"
# ① 선택한 카드 안에서만 뽑힘 ② 세션 내 중복 없음
assert set(played) <= set(selected), f"선택 밖 카드 발동: {played}"
assert len(set(played)) == 2, f"카드 중복 사용: {played}"
finally:
await DB_SESSION_MNG.execute_lambda_run(
[DBType.MAIN.value],
[lambda s: DB_SESSION_MNG.add(s, delete(_T_SESSIONS).where(_T_SESSIONS.c.session_id == sid)),
lambda s: DB_SESSION_MNG.add(s, delete(_T_VNC).where(_T_VNC.c.version_id == ver_id)),
lambda s: DB_SESSION_MNG.add(s, delete(_T_QUOTATIONS).where(_T_QUOTATIONS.c.qt_id == qid))],
)
@pytest.mark.asyncio
async def test_no_selection_allows_full_catalog(db_engine):
"""선택 카드가 없으면(직접호출/데모) 전체 카탈로그가 허용된다 — 카드가 정상적으로 뽑히는지 기본 검증."""
reset_sessions()
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
eng = await reg.get_engine(str(_uuid.uuid4())) # _base type:db → DB 카탈로그
catalog = {eng.mapper.get_card_id(a) for a in range(eng.action_space_size)}
svc = ChatService()
played = []
sid = None
for ui in [None, "확인", "예", "확인", "11000", "예", "10600", "예", "10600", "예"]:
r = await svc.chat(eng, Req_Chat(session_id=sid, user_input=ui))
sid = r.session_id
if r.step == "가격협상" and r.card_id:
played.append(r.card_id)
if r.chat_end:
break
assert played, "가격협상 카드 턴이 발생해야 함"
assert set(played) <= catalog # 카탈로그(NGC-001~011) 내에서만
assert len(played) == len(set(played)) # 세션 내 중복 없음
+315
View File
@@ -0,0 +1,315 @@
"""카드 전술 재설계 검증 — "멘트 카드 → 전술 카드" (가격 행동 실행 계층).
① 카운터 산식 결정론 + min(counter, target) 클램프 + 무의미 카운터(HOLD 강등)
② 카운터 수락 = 즉시 타결 / 거절 = 재입력 + pending 폐기
③ 목표가 초과 타결 금지 가드(성공 스텝 진입 차단)
④ 선택형 와일드카드(WC-05 중간값 절충) 발동 — 1.02~1.05 구간 갭 해소
⑤ E2E: 견적 선택 카드(NGC-009 조건부 가격 조정)의 카운터를 수락하면 settled=target
⑥ E2E: 협력사가 target 초과를 고수하면 종결 전술(최후통첩) 후 결렬 — 고객사 이득 가드레일
"""
import os
import uuid as _uuid
from datetime import datetime, timedelta, timezone
import pytest
from negotiation.cards.domain.tactics import (
PriceAction, TacticSpec, compute_counter, tactic_available, tactic_for,
)
from negotiation.chat.service.chat_engine import ChatEngine, ChatSession
from negotiation.chat.service.script_repository import ScriptRepository
from tenancy.config_loader import TenantConfigLoader
_TENANTS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tenants")
def _engine() -> ChatEngine:
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("imarketkorea")
return ChatEngine(ScriptRepository(cfg, _TENANTS_DIR), rq_type="재협상")
def _session(step="가격협상_확인", **ctx_over):
ctx = {"input_price": 10300, "anchor_price": 10000, "target_price": 10100,
"round": 1, "allow_selected_wildcards": False}
ctx.update(ctx_over)
return ChatSession(session_id="00000000-0000-0000-0000-00000000e001", tenant_id="imarketkorea",
company_id="imarketkorea", step=step, action_space_size=0, context=ctx)
# ---- ① 카운터 산식 (결정론 + 가드레일 클램프) --------------------------------
def test_counter_formulas_and_clamp():
ctx = {"input_price": 11000, "anchor_price": 9900, "target_price": 10000}
assert compute_counter(tactic_for("NGC-009"), ctx) == 10000 # COUNTER_TARGET
assert compute_counter(tactic_for("NGC-007"), ctx) == 9900 # COUNTER_ANCHOR
assert compute_counter(tactic_for("WC-02"), ctx) == 9950 # (anchor+target)/2
# COUNTER_MID: 갑 직전 포지션 폴백 = anchor → (9900+11000)/2 = 10450 → target 클램프
assert compute_counter(tactic_for("WC-05"), ctx) == 10000
# 갑 직전 포지션이 있으면 그 기준: (9800+11000)/2 = 10400 → 역시 클램프 10000
assert compute_counter(tactic_for("WC-05"), dict(ctx, prev_customer_price=9800)) == 10000
# 클램프 미발동 구간: (9900+10050)/2 = 9975 ≤ target
assert compute_counter(tactic_for("WC-05"), dict(ctx, input_price=10050)) == 9975
def test_counter_meaningless_degrades_to_hold():
"""협력사 제시가가 이미 카운터 이하면 카운터가 무의미 → None(순수 설득 유지)."""
ctx = {"input_price": 9950, "anchor_price": 9900, "target_price": 10000}
assert compute_counter(tactic_for("NGC-009"), ctx) is None # target(10000) ≥ 제시가
assert compute_counter(TacticSpec(PriceAction.COUNTER_ANCHOR), dict(ctx, input_price=9900)) is None
def test_unknown_card_falls_back_to_hold():
"""미등록 카드번호(데모 NGC-B*, 커스텀 COMP-*)는 HOLD — 기존 동작 그대로."""
spec = tactic_for("NGC-B003")
assert spec.price_action is PriceAction.HOLD
assert compute_counter(spec, {"input_price": 11000, "target_price": 10000}) is None
assert tactic_available(spec, {}) is True
def test_tactic_availability_conditions():
assert tactic_available(tactic_for("WC-04"), {"round": 1}) is False # min_round=2
assert tactic_available(tactic_for("WC-04"), {"round": 2}) is True
# ---- ② 카운터 수락/거절 메커니즘 (엔진) ---------------------------------------
def test_accept_counter_settles_at_counter_price():
eng = _engine()
s = _session(step="가격협상_카운터", pending_counter_price=10000)
view = eng.advance(s, "수락")
assert view.step == "협상완료"
assert s.context["input_price"] == 10000 # 합의가 = 카운터가
assert "pending_counter_price" not in s.context
def test_reject_counter_reenters_price_and_discards_pending():
eng = _engine()
s = _session(step="가격협상_카운터", pending_counter_price=10000)
view = eng.advance(s, "다른 가격 제시")
assert view.step == "가격협상_재입력"
# 새 가격 입력이 pending 을 폐기한다 — 이후 우선협상 타결이 옛 카운터로 오염되지 않음
view = eng.advance(s, "9900")
assert "pending_counter_price" not in s.context
assert s.context["input_price"] == 9900
def test_wildcard_1pct_decline_keeps_original_price():
"""1% 인하 거절('아니오')도 협상완료로 가지만 합의가는 원 제시가 — pending 미적용 회귀."""
eng = _engine()
s = _session(step="wild_card_1pct", input_price=10000,
offer_1pct=9900, pending_counter_price=9900)
view = eng.advance(s, "아니오")
assert view.step == "협상완료"
assert s.context["input_price"] == 10000 # 거절 → 카운터 미적용
# ---- ③ 목표가 초과 타결 금지 가드 --------------------------------------------
def test_success_step_guard_rejects_over_target():
eng = _engine()
s = _session(input_price=10800, target_price=10000)
view = eng.render_step(s, "협상완료")
assert view.step == "협상실패" # 초과가 성공 진입 → 결렬 강제
# ---- ④ 선택형 와일드카드 발동 (1.02~1.05 구간 갭 해소) -------------------------
def test_selected_wildcard_fires_in_entry_zone():
eng = _engine()
# 10300: 1pct 존(≤10200) 밖, entry 존(≤10500) 안 + WC-05 선택
s = _session(input_price=10300, allow_selected_wildcards=True,
selected_wild_card_numbers=["WC-05"])
view = eng.advance(s, "예")
assert view.step == "wild_card_dynamic"
# 카운터 = (anchor 10000 + 10300)/2 = 10150 → target(10100) 클램프
assert s.context["pending_counter_price"] == 10100
assert s.context["active_wild_card_number"] == "WC-05"
# 수락 → 그 가격으로 타결
view = eng.advance(s, "수락")
assert view.step == "협상완료" and s.context["input_price"] == 10100
def test_unselected_wildcard_zone_still_falls_to_nego():
"""와일드카드 미선택이면 entry 존이라도 일반 가격협상 — 기존 동작 보존."""
eng = _engine()
s = _session(input_price=10300, allow_selected_wildcards=True, selected_wild_card_numbers=[])
view = eng.advance(s, "예")
assert view.step == "가격협상"
# ---- 인하율 표기 (회귀: 인상 제시가 "-1.3% 인하"로 표기되던 버그) -----------------
def test_discount_never_negative_and_phrase_matches_direction():
eng = _engine()
# 인상 제시(기존 공급가 78000 < 제시 79000): 음수 인하율 금지 + "높은 금액" 문구
s = _session(item_price=78000, input_price=79000)
v = eng.vars_for(s)
assert v["discount_rate"] == "0.0" # 마이너스 인하 표기 금지
assert "높은 금액" in v["discount_phrase"] and "78000원" in v["discount_phrase"]
assert "-" not in v["discount_phrase"]
# 인하 제시: 상품단가(item_price) 기준 인하율
v = eng.vars_for(_session(item_price=78000, input_price=77000))
assert v["discount_rate"] == "1.3"
assert "인하된 금액" in v["discount_phrase"]
# 동일가
v = eng.vars_for(_session(item_price=78000, input_price=78000))
assert "동일한 수준" in v["discount_phrase"]
# 기존가 미보유(신규 협상) → 문구 생략
v = eng.vars_for(_session(item_price=0, input_price=79000))
assert v["discount_phrase"] == "" and v["discount_rate"] == "0.0"
def test_price_confirm_script_renders_raise_correctly():
"""가격협상_확인 멘트 E2E — 인상 제시에 '인하' 표현이 나오지 않는다."""
eng = _engine()
s = _session(step="기존가격제시", item_price=78000, input_price=None, round=0)
s.context.pop("input_price")
view = eng.advance(s, "79000")
assert view.step == "가격협상_확인"
assert "인하" not in view.script # 인상인데 '인하' 금지
assert "높은 금액" in view.script and "79000원" in view.script
# ---- vars_for 전술 변수 치환 ---------------------------------------------------
def test_vars_for_supplies_tactic_variables():
eng = _engine()
s = _session(input_price=10300, prev_customer_price=10000, pending_counter_price=10100)
v = eng.vars_for(s)
assert v["prev_partner_price"] == 10300
assert v["prev_customer_price"] == 10000
assert v["target_mid_price"] == 10050 # (10000+10100)/2
assert v["middle_price"] == 10150 # (10000+10300)/2
assert v["counter_price"] == 10100
# ---- ⑤⑥ E2E (실 DB — 견적 선택 카드 + 서비스 레이어) ---------------------------
from sqlalchemy import column, delete, insert, select, table # noqa: E402
from common.database.db_session_manager import DB_SESSION_MNG # noqa: E402
from common.enums import DBType, DBWRType, ErrorType # noqa: E402
from router.v1.chat.protocol import Req_Chat # noqa: E402
from services.chat_service import ChatService, reset_sessions # noqa: E402
from tenancy.registry import TenantEngineRegistry # noqa: E402
_T_SESSIONS = table(
"sessions",
column("session_id"), column("quotation_id"), column("item_id"), column("supplier_id"),
column("qt_number"), column("qt_round"), column("qt_type"), column("target_price"),
column("anchoring_price"), column("status"), column("end_time"),
schema="negotiation",
)
_T_QUOTATIONS = table(
"quotations",
column("qt_id"), column("user_id"), column("qt_setting_id"), column("version_id"),
column("name"), column("number"), column("type"), column("status"),
column("start_time"), column("end_time"),
schema="quotation",
)
_T_VNC = table("version_nego_cards", column("vnc_id"), column("version_id"), column("nego_card_id"), schema="card")
_T_NEGO = table("nego_cards", column("nego_card_id"), column("number"), column("deleted"), schema="card")
async def _card_uuid(number: str):
def _q(s):
return DB_SESSION_MNG.execute(
s, select(_T_NEGO.c.nego_card_id).where(
_T_NEGO.c.number == number, _T_NEGO.c.deleted == False).limit(1)) # noqa: E712
_, rows = await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
return rows[0] if rows else None
async def _seed_quote_session(sid, selected_numbers, target=10000, anchor=9900):
qid, ver_id, iid, sup = _uuid.uuid4(), _uuid.uuid4(), _uuid.uuid4(), _uuid.uuid4()
now = datetime.now(timezone.utc)
card_ids = {}
for n in selected_numbers:
card_ids[n] = await _card_uuid(n)
assert card_ids[n] is not None, f"카탈로그에 {n} 없음(시드 확인)"
def _seed(s_):
async def run(s):
e = await DB_SESSION_MNG.add(s, insert(_T_QUOTATIONS).values(
qt_id=qid, user_id=_uuid.uuid4(), qt_setting_id=_uuid.uuid4(), version_id=ver_id,
name="전술E2E", number=f"QT-TACTIC-{str(sid)[:8]}", type=1, status=2,
start_time=now, end_time=now + timedelta(days=1)))
if e != ErrorType.SUCCESS:
return e
for n in selected_numbers:
e = await DB_SESSION_MNG.add(s, insert(_T_VNC).values(
vnc_id=_uuid.uuid4(), version_id=ver_id, nego_card_id=card_ids[n]))
if e != ErrorType.SUCCESS:
return e
return await DB_SESSION_MNG.add(s, insert(_T_SESSIONS).values(
session_id=sid, quotation_id=qid, item_id=iid, supplier_id=sup,
qt_number=f"QT-TACTIC-{str(sid)[:8]}", qt_round=1, qt_type=1,
target_price=target, anchoring_price=anchor, status=2,
end_time=now + timedelta(days=1)))
return run(s_)
err = await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [_seed])
assert err == ErrorType.SUCCESS
return qid, ver_id
async def _cleanup(sid, qid, ver_id):
await DB_SESSION_MNG.execute_lambda_run(
[DBType.MAIN.value],
[lambda s: DB_SESSION_MNG.add(s, delete(_T_SESSIONS).where(_T_SESSIONS.c.session_id == sid)),
lambda s: DB_SESSION_MNG.add(s, delete(_T_VNC).where(_T_VNC.c.version_id == ver_id)),
lambda s: DB_SESSION_MNG.add(s, delete(_T_QUOTATIONS).where(_T_QUOTATIONS.c.qt_id == qid))],
)
@pytest.mark.asyncio
async def test_e2e_counter_accept_settles_at_target(db_engine):
"""견적 선택 카드 NGC-009(조건부 가격 조정 → COUNTER_TARGET)의 카운터를 수락하면
합의가 = 목표가(10000) — '수락 즉시 타결' 기획 결정의 E2E 검증."""
reset_sessions()
sid = _uuid.uuid4()
qid, ver_id = await _seed_quote_session(sid, ["NGC-009"])
try:
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
eng = await reg.get_engine(str(_uuid.uuid4()))
svc = ChatService()
session_id = str(sid)
r = None
for ui in [None, "확인", "예", "확인", "11000", "예"]:
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input=ui))
# 가격협상 카드 턴 → NGC-009 카운터(target) 제시 스텝
assert r.step == "가격협상_카운터", f"카운터 스텝 기대, 실제 {r.step}"
assert r.card_id == "NGC-009"
assert r.input_options == ["수락", "다른 가격 제시"]
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input="수락"))
assert r.step == "협상완료"
assert r.settled_price == 10000 # 합의가 = 목표가 (고객사 이득)
finally:
await _cleanup(sid, qid, ver_id)
@pytest.mark.asyncio
async def test_e2e_over_target_ends_in_failure_after_closing(db_engine):
"""협력사가 목표가 초과(11000)를 고수하면: 카드 소진 → 종결 전술(목표가 최후통첩) →
그래도 거절 → 결렬(협상실패). 목표가 초과로는 절대 타결되지 않는다."""
reset_sessions()
sid = _uuid.uuid4()
qid, ver_id = await _seed_quote_session(sid, ["NGC-003"]) # HOLD 카드 1장 → 빠른 소진
try:
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
eng = await reg.get_engine(str(_uuid.uuid4()))
svc = ChatService()
session_id = str(sid)
steps, r = [], None
# 고수 시나리오: 가격은 항상 11000, 카운터는 전부 거절
for ui in [None, "확인", "예", "확인", "11000", "예", "11000", "예"]:
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input=ui))
steps.append(r.step)
# 카드(NGC-003) 소진 → 종결 국면: 목표가 최후통첩 카운터 스텝
assert r.step == "가격협상_카운터", f"종결 카운터 기대, 실제 {steps}"
assert "10000" in r.script # 최후통첩 = 목표가 제시
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input="다른 가격 제시"))
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input="11000"))
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input="예"))
assert r.step == "협상실패" # target 초과 고수 → 결렬
r = await svc.chat(eng, Req_Chat(session_id=session_id, user_input="확인"))
assert r.chat_end and r.outcome == "failure" # backend REJECTED → 개찰 이관
assert r.settled_price is None # 초과가 타결 없음
finally:
await _cleanup(sid, qid, ver_id)
+20 -11
View File
@@ -34,7 +34,7 @@ _T_QUOTATIONS = table(
"quotations", "quotations",
column("qt_id"), column("user_id"), column("qt_setting_id"), column("version_id"), column("qt_id"), column("user_id"), column("qt_setting_id"), column("version_id"),
column("name"), column("number"), column("type"), column("status"), column("name"), column("number"), column("type"), column("status"),
column("start_time"), column("end_time"), column("supplier_type"), column("start_time"), column("end_time"),
schema="quotation", schema="quotation",
) )
_T_ITEMS = table( _T_ITEMS = table(
@@ -80,7 +80,6 @@ async def test_context_loaded_from_db(db_engine):
qt_id=qid, user_id=uuid.uuid4(), qt_setting_id=uuid.uuid4(), version_id=uuid.uuid4(), qt_id=qid, user_id=uuid.uuid4(), qt_setting_id=uuid.uuid4(), version_id=uuid.uuid4(),
name="로더 테스트", number="QT-LOADER-TEST", type=3, status=2, name="로더 테스트", number="QT-LOADER-TEST", type=3, status=2,
start_time=now, end_time=now + timedelta(days=1), start_time=now, end_time=now + timedelta(days=1),
supplier_type=2, # manufacture(제조) → 유통 코드 "A"
)) ))
def _ins_sess(s, session_id, supplier_id): def _ins_sess(s, session_id, supplier_id):
@@ -110,7 +109,7 @@ async def test_context_loaded_from_db(db_engine):
try: try:
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0)) reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
eng = await reg.get_engine("ktcommerce") eng = await reg.get_engine("imarketkorea")
r = await ChatService().chat(eng, Req_Chat(session_id=str(sid))) r = await ChatService().chat(eng, Req_Chat(session_id=str(sid)))
assert r.session_id == str(sid) and r.step == "서비스안내" assert r.session_id == str(sid) and r.step == "서비스안내"
@@ -125,7 +124,7 @@ async def test_context_loaded_from_db(db_engine):
assert c["distribution_code"] == "B" # supplier_items.supply_type=3(총판) → B (매핑 우선) assert c["distribution_code"] == "B" # supplier_items.supply_type=3(총판) → B (매핑 우선)
assert c["partner_count"] == 2 # 매핑 기준 취급 협력사 2곳 → MULTIPLE assert c["partner_count"] == 2 # 매핑 기준 취급 협력사 2곳 → MULTIPLE
# 매핑 삭제 후 새 세션(sid2) → 폴백 경로: 유통코드=quotations.supplier_type, 파트너=세션 이력 # 매핑 삭제 후 새 세션(sid2) → 유통코드는 ChatService 기본값, 파트너는 세션 이력 폴백
err = await DB_SESSION_MNG.execute_lambda_run( err = await DB_SESSION_MNG.execute_lambda_run(
[DBType.MAIN.value], [DBType.MAIN.value],
[lambda s: DB_SESSION_MNG.add(s, delete(_T_SUPPLIER_ITEMS).where(_T_SUPPLIER_ITEMS.c.item_id == iid))], [lambda s: DB_SESSION_MNG.add(s, delete(_T_SUPPLIER_ITEMS).where(_T_SUPPLIER_ITEMS.c.item_id == iid))],
@@ -133,7 +132,7 @@ async def test_context_loaded_from_db(db_engine):
assert err == ErrorType.SUCCESS assert err == ErrorType.SUCCESS
await ChatService().chat(eng, Req_Chat(session_id=str(sid2))) await ChatService().chat(eng, Req_Chat(session_id=str(sid2)))
c2 = (await ChatSessionRepository(eng.company_id).get(str(sid2))).context c2 = (await ChatSessionRepository(eng.company_id).get(str(sid2))).context
assert c2["distribution_code"] == "A" # 폴백: quotations.supplier_type=2(제조) → A assert c2["distribution_code"] == "A" # 매핑 없음 → ChatService 기본값
assert c2["partner_count"] == 2 # 폴백: 세션 이력 distinct supplier 2곳 assert c2["partner_count"] == 2 # 폴백: 세션 이력 distinct supplier 2곳
finally: finally:
await DB_SESSION_MNG.execute_lambda_run( await DB_SESSION_MNG.execute_lambda_run(
@@ -165,7 +164,7 @@ async def test_null_anchoring_falls_back_to_target(db_engine):
assert err == ErrorType.SUCCESS assert err == ErrorType.SUCCESS
try: try:
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0)) reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
eng = await reg.get_engine("ktcommerce") eng = await reg.get_engine("imarketkorea")
await ChatService().chat(eng, Req_Chat(session_id=str(sid))) await ChatService().chat(eng, Req_Chat(session_id=str(sid)))
saved = await ChatSessionRepository(eng.company_id).get(str(sid)) saved = await ChatSessionRepository(eng.company_id).get(str(sid))
assert saved is not None assert saved is not None
@@ -196,10 +195,13 @@ async def test_loader_with_crud_double(db_engine):
async def get_supplier_total_revenue(self, cdb, supplier_id): async def get_supplier_total_revenue(self, cdb, supplier_id):
return ErrorType.SUCCESS, 12_000_000.0 return ErrorType.SUCCESS, 12_000_000.0
async def get_supply_type(self, cdb, supplier_id, item_id): async def get_item_name(self, cdb, item_id):
return ErrorType.SUCCESS, None # 매핑 없음 → 견적 기록 폴백 return ErrorType.SUCCESS, "테스트상품"
async def get_quotation_supplier_type(self, cdb, quotation_id): async def get_supplier_name(self, cdb, supplier_id):
return ErrorType.SUCCESS, "테스트협력사"
async def get_supply_type(self, cdb, supplier_id, item_id):
return ErrorType.SUCCESS, 3 # sole_agency(총판) → "B" return ErrorType.SUCCESS, 3 # sole_agency(총판) → "B"
async def count_item_suppliers(self, cdb, item_id): async def count_item_suppliers(self, cdb, item_id):
@@ -208,15 +210,22 @@ async def test_loader_with_crud_double(db_engine):
async def count_item_session_suppliers(self, cdb, item_id): async def count_item_session_suppliers(self, cdb, item_id):
return ErrorType.SUCCESS, 0 # 이력도 없음 → NONE return ErrorType.SUCCESS, 0 # 이력도 없음 → NONE
async def get_quotation_card_numbers(self, cdb, quotation_id):
return ErrorType.SUCCESS, (["NGC-003", "NGC-008"], ["WC-02"]) # 견적 선택 카드
ctx = await NegotiationContextLoader(crud=_FakeCRUD()).load(str(uuid.uuid4())) ctx = await NegotiationContextLoader(crud=_FakeCRUD()).load(str(uuid.uuid4()))
assert ctx is not None assert ctx is not None
assert ctx.rq_type == "재견적" # qt_type=2(1:N) assert ctx.rq_type == "재견적" # qt_type=2(1:N)
assert ctx.target_price == 50000 assert ctx.target_price == 50000
assert ctx.anchor_price == 50000 # 미박제 → 무할인 폴백(anchor=target) assert ctx.anchor_price == 50000 # 미박제 → 무할인 폴백(anchor=target)
assert ctx.item_price == 7000 assert ctx.item_price == 7000
assert ctx.partner_name == "테스트협력사"
assert ctx.product_name == "테스트상품"
assert ctx.revenue_amount == 12_000_000.0 assert ctx.revenue_amount == 12_000_000.0
assert ctx.distribution_code == "B" # supplier_type=3(총판) → B assert ctx.distribution_code == "B" # supply_type=3(총판) → B
assert ctx.partner_type is PartnerType.NONE assert ctx.partner_type is PartnerType.NONE
assert ctx.selected_nego_card_numbers == ["NGC-003", "NGC-008"]
assert ctx.selected_wild_card_numbers == ["WC-02"]
@pytest.mark.asyncio @pytest.mark.asyncio
@@ -224,7 +233,7 @@ async def test_context_falls_back_without_db_row(db_engine):
"""DB 에 세션 행이 없으면(데모/직접 호출) 기본 컨텍스트로 폴백한다.""" """DB 에 세션 행이 없으면(데모/직접 호출) 기본 컨텍스트로 폴백한다."""
reset_sessions() reset_sessions()
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0)) reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
eng = await reg.get_engine("ktcommerce") eng = await reg.get_engine("imarketkorea")
r = await ChatService().chat(eng, Req_Chat()) r = await ChatService().chat(eng, Req_Chat())
saved = await ChatSessionRepository(eng.company_id).get(r.session_id) saved = await ChatSessionRepository(eng.company_id).get(r.session_id)
assert saved is not None assert saved is not None
+140
View File
@@ -0,0 +1,140 @@
"""Phase 1 결정 스택 잔여분 검증 — 규칙 데이터화 + 선택카드 우선순위 prior.
1. 와일드카드 진입 임계(wildcard_1pct_ratio/entry_ratio)·카운터 라운드 상한(max_counter_rounds)이
하드코딩이 아니라 테넌트 config(negotiation.*)로 주입된다.
2. 의도층 prior: 갑이 견적에서 고른 카드 순서가 콜드 스타트 선택을 결정하고,
학습(Q·방문수)이 쌓이면 영향이 소멸한다 — Q-table 오염 없음.
"""
import os
import numpy as np
import pytest
from negotiation.chat.service.chat_engine import ChatEngine, ChatSession
from negotiation.chat.service.script_repository import ScriptRepository
from negotiation.policies.base import EpisodeState, PolicyContext
from negotiation.policies.qtable_policy import UCBQTablePolicy
from negotiation.qtable.domain.model.q_table import QTable
from negotiation.qtable.domain.model.snapshot import NegotiationSnapshot
from tenancy.config_loader import TenantConfigLoader
_TENANTS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tenants")
def _engine(**rule_overrides) -> ChatEngine:
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("imarketkorea")
for k, v in rule_overrides.items():
setattr(cfg.negotiation, k, v)
return ChatEngine(ScriptRepository(cfg, _TENANTS_DIR), rq_type="재협상")
def _session(price, anchor=10000, rnd=1, **ctx_over):
ctx = {"input_price": price, "anchor_price": anchor, "target_price": anchor + 100,
"round": rnd, "allow_selected_wildcards": False}
ctx.update(ctx_over)
return ChatSession(session_id="00000000-0000-0000-0000-00000000d001", tenant_id="imarketkorea",
company_id="imarketkorea", step="가격협상_확인", action_space_size=0, context=ctx)
# ---- 규칙 데이터화 -----------------------------------------------------------
def test_default_rules_loaded_from_config():
eng = _engine()
assert eng.rules.wildcard_1pct_ratio == 1.02
assert eng.rules.wildcard_entry_ratio == 1.05
assert eng.rules.max_counter_rounds == 3
def test_wildcard_threshold_is_config_driven():
# 기본(1.02): anchor 10000, 제시 10800 → 임계 밖 → 일반 가격협상
view = _engine().advance(_session(10800), "예")
assert view.step == "가격협상"
# 임계를 1.10 으로 완화한 테넌트 → 같은 가격에서 1% 인하 와일드카드 발동
view = _engine(wildcard_1pct_ratio=1.10).advance(_session(10800), "예")
assert view.step == "wild_card_1pct"
def test_max_counter_rounds_is_config_driven():
# round=3(카운터 2회 경과), 제시 11000: 기본 상한 3 → 아직 협상 지속
view = _engine().advance(_session(11000, rnd=3), "예")
assert view.step == "가격협상"
# 상한 1 → 종결 국면 진입: 곧장 실패가 아니라 종결 전술 발동 지점(force_closing)으로
s = _engine(max_counter_rounds=1), _session(11000, rnd=3)
view = s[0].advance(s[1], "예")
assert view.step == "가격협상" and s[1].context.get("force_closing") is True
# 종결 전술까지 소진(closing_played) 후에도 target(10100) 초과 → 결렬
view = _engine(max_counter_rounds=1).advance(_session(11000, rnd=3, closing_played=True), "예")
assert view.step == "협상실패"
# 종결 후 제시가가 target 이하로 내려오면 결렬이 아니라 타결 (새 규칙 — 구현 전엔 무조건 실패)
view = _engine(max_counter_rounds=1).advance(
_session(10050, rnd=3, closing_played=True, wildcard_used=True), "예")
assert view.step == "협상완료"
# ---- 선택카드 우선순위 prior ---------------------------------------------------
def _snap():
return NegotiationSnapshot(revenue_amount=1, distribution_code="A", partner_count=1,
acceptance_ratio=0.1, input_price=900, anchor_price=800, target_price=1000)
def _ctx(prior=None, mask=None, n=11):
return PolicyContext(state_index=0, snapshot=_snap(), action_space_size=n,
available_mask=mask, prior_bonus=prior, episode=EpisodeState())
def test_prior_decides_cold_start_order():
"""콜드 스타트(Q=0·방문 0)에서는 갑이 먼저 고른 카드(높은 prior)가 먼저 나간다."""
qt = QTable(2, 11)
prior = np.zeros(11)
prior[7], prior[2] = 0.3, 0.15 # 선택 순서: action7 → action2
mask = np.zeros(11, dtype=bool)
mask[2] = mask[7] = True
p = UCBQTablePolicy(qt, mark_visits=False)
assert p.select(_ctx(prior=prior, mask=mask)).action_id == 7
def test_prior_decays_as_learning_accumulates():
"""학습이 쌓이면(Q·방문수) prior 는 1/(1+visits) 로 감쇠 — Q 가 지배한다."""
qt = QTable(2, 11)
qt.q[0, 2] = 1.0 # action2 가 학습상 우월
qt.visits[0, 2] = 5
qt.visits[0, 7] = 5 # 탐색 보너스 동률
prior = np.zeros(11)
prior[7] = 0.3 # 갑 선호는 action7
mask = np.zeros(11, dtype=bool)
mask[2] = mask[7] = True
p = UCBQTablePolicy(qt, mark_visits=False)
assert p.select(_ctx(prior=prior, mask=mask)).action_id == 2
def test_no_prior_keeps_existing_behavior():
"""prior 미주입(None) 시 기존 UCB 동작 그대로 — 회귀 없음."""
qt = QTable(2, 4)
qt.q[0] = np.array([1.0, 9.0, 2.0, 0.0])
qt.visits[0] = np.array([5, 5, 5, 5])
p = UCBQTablePolicy(qt, exploration_constant=0.1, mark_visits=False)
assert p.select(_ctx(n=4)).action_id == 1
def test_selection_prior_built_from_quotation_order():
"""ChatService._selection_prior — 견적 선택 순서 → prior 배열 (앞선 선택일수록 큼)."""
from services.chat_service import ChatService
class _Mapper:
_m = {i: f"NGC-B{i + 1:03d}" for i in range(11)}
def get_action_id(self, num):
return next((a for a, c in self._m.items() if c == num), None)
class _Engine:
mapper = _Mapper()
action_space_size = 11
session = ChatSession(session_id="00000000-0000-0000-0000-00000000d002", tenant_id="t", company_id="t",
context={"selected_nego_card_numbers": ["NGC-B008", "NGC-B003"]})
prior = ChatService._selection_prior(_Engine(), session)
assert prior is not None
assert prior[7] > prior[2] > 0 # 먼저 고른 NGC-B008(action7) 이 더 큼
assert prior[[0, 1, 4, 10]].sum() == 0 # 미선택 카드는 0
# 선택이 1장이면 순서 정보가 없어 None
session.context["selected_nego_card_numbers"] = ["NGC-B008"]
assert ChatService._selection_prior(_Engine(), session) is None
+10 -9
View File
@@ -110,7 +110,7 @@ async def test_version_and_cell_persistence(db_engine):
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_service_step_learns_and_isolates(db_engine): async def test_service_step_learns_and_isolates(db_engine):
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0)) reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
eng = await reg.get_engine("ktcommerce") eng = await reg.get_engine("imarketkorea")
svc = NegotiationService() svc = NegotiationService()
def req(): def req():
@@ -126,20 +126,21 @@ async def test_service_step_learns_and_isolates(db_engine):
assert r1.learned is True and r1.policy == "qtable_ucb" assert r1.learned is True and r1.policy == "qtable_ucb"
assert r1.updated_q > 0.0 # 성공 보상으로 Q 상승 assert r1.updated_q > 0.0 # 성공 보상으로 Q 상승
# DB 에서 state 전체 방문 누적 확인 (state 58 = ktcommerce 의 이 snapshot) # DB 에서 state 전체 방문 누적 확인 (state index 는 imarketkorea config 로 동적 계산)
from negotiation.qtable.domain.service.state_calculator import state_index from negotiation.qtable.domain.service.state_calculator import state_index
sidx = state_index(_snap(revenue_amount=20_000_000, acceptance_ratio=0.11, input_price=990, round_number=3), eng.config.state) sidx = state_index(_snap(revenue_amount=20_000_000, acceptance_ratio=0.11, input_price=990, round_number=3), eng.config.state)
repo_kt = LearningRepository("ktcommerce") repo_a = LearningRepository("imarketkorea")
vid = await repo_kt.get_or_create_active_version(state_space_size=162, action_space_size=9, learning_rate=0.1, discount_factor=0.95) vid = await repo_a.get_or_create_active_version(state_space_size=162, action_space_size=9, learning_rate=0.1, discount_factor=0.95)
_, vcells = await repo_kt.load_cells(vid) _, vcells = await repo_a.load_cells(vid)
state_total = sum(c for s, a, c in vcells if s == sidx) state_total = sum(c for s, a, c in vcells if s == sidx)
assert state_total == 3 # 3회 호출 → state 누적 방문 3 assert state_total == 3 # 3회 호출 → state 누적 방문 3
# 테넌트 격리: imarketkorea 는 별도 학습/별도 state # 테넌트 격리: 자동 온보딩 고객사(UUID)는 별도 학습/별도 state
eng2 = await reg.get_engine("imarketkorea") other = "00000000-0000-0000-0000-0000000000c1"
eng2 = await reg.get_engine(other)
ri = await svc.step(eng2, req()) ri = await svc.step(eng2, req())
assert ri.visit_count == 1 assert ri.visit_count == 1
err, ck = await repo_kt.read(lambda s: repo_kt.count_experience(s)) err, ck = await repo_a.read(lambda s: repo_a.count_experience(s))
err, ci = await LearningRepository("imarketkorea").read(lambda s: LearningRepository("imarketkorea").count_experience(s)) err, ci = await LearningRepository(other).read(lambda s: LearningRepository(other).count_experience(s))
assert ck == 3 and ci == 1 # experience 격리 assert ck == 3 and ci == 1 # experience 격리
+2 -2
View File
@@ -35,7 +35,7 @@ def test_card_effectiveness_has_good_cards():
assert len(good) >= 3 # 효과 좋은 카드 존재 → 학습 대상 신호 assert len(good) >= 3 # 효과 좋은 카드 존재 → 학습 대상 신호
@pytest.mark.parametrize("tenant", ["ktcommerce", "imarketkorea"]) @pytest.mark.parametrize("tenant", ["_base", "imarketkorea"])
def test_learning_beats_baseline(tenant): def test_learning_beats_baseline(tenant):
report = run("configs/exp_default.yaml", tenant) report = run("configs/exp_default.yaml", tenant)
pols = report["policies"] pols = report["policies"]
@@ -53,7 +53,7 @@ def test_learning_beats_baseline(tenant):
def test_static_does_not_learn(): def test_static_does_not_learn():
report = run("configs/exp_default.yaml", "ktcommerce") report = run("configs/exp_default.yaml", "imarketkorea")
static = report["policies"]["static"] static = report["policies"]["static"]
# 정적 정책은 항상 고정 카드 → 좋은카드 적중 학습 없음(우연 일치만) # 정적 정책은 항상 고정 카드 → 좋은카드 적중 학습 없음(우연 일치만)
assert static["good_card_hit_rate"] <= report["policies"]["qtable_ucb"]["good_card_hit_rate"] assert static["good_card_hit_rate"] <= report["policies"]["qtable_ucb"]["good_card_hit_rate"]
+161
View File
@@ -0,0 +1,161 @@
"""Phase 3 이해층 검증 — InputInterpreter (자유 발화 NLU → 기대 입력 구조화).
원칙 검증: LLM 은 의도 분류·가격 표현 위치만 찾고, 숫자 계산은 결정론 파서가 한다.
① 한국어 가격 파서 결정론 ② choice 는 선택지 목록 검증 ③ price_text 는 원문 부분문자열 검증
④ 실패/타임아웃 → None(원문 폴백) ⑤ 챗 플로우: 자유 발화로 분기·가격 입력이 진행된다
⑥ LLM 미설정 시 기존(정형 입력) 동작 그대로 — 회귀 없음.
"""
import os
import pytest
from negotiation.chat.service.input_interpreter import (
InputInterpreter, InterpretedInput, parse_korean_price,
)
_TENANTS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tenants")
# ---- 결정론 한국어 가격 파서 -------------------------------------------------
@pytest.mark.parametrize("text,expected", [
("10,500원", 10500),
("10500", 10500),
("1만 500원", 10500),
("1만500원", 10500),
("만원", 10000),
("1.5만", 15000),
("3만2천원", 32000),
("2억", 200_000_000),
("0", None), # 0 이하 무효
("그건 어렵습니다", None), # 가격 아님
("만원에 3개", None), # 잡문자 혼입 → 해석 불가(안전 폴백)
])
def test_parse_korean_price(text, expected):
got = parse_korean_price(text)
assert (got == expected) if expected is not None else (got is None)
# ---- LLM 출력 검증 (환각 차단) ----------------------------------------------
def _fake(reply: dict):
def call(messages):
return reply
return call
@pytest.mark.asyncio
async def test_choice_mapped_to_option():
nat = InputInterpreter(llm_call=_fake({"intent": "choice", "choice": "예", "price_text": None}))
out = await nat.interpret("네 접니다, 말씀하세요", input_mode="yes_no", input_options=["예", "아니오"])
assert out == InterpretedInput(kind="choice", value="예", source="예")
@pytest.mark.asyncio
async def test_choice_outside_options_rejected():
nat = InputInterpreter(llm_call=_fake({"intent": "choice", "choice": "글쎄요", "price_text": None}))
assert await nat.interpret("음...", input_mode="yes_no", input_options=["예", "아니오"]) is None
@pytest.mark.asyncio
async def test_price_span_verified_and_parsed_deterministically():
nat = InputInterpreter(llm_call=_fake({"intent": "price", "choice": None, "price_text": "1만 500원"}))
out = await nat.interpret("저희 마진상 1만 500원까지는 맞춰드릴 수 있습니다", input_mode="price")
assert out is not None and out.kind == "price"
assert out.value == "10500" # 숫자는 결정론 파서 산출(LLM 계산 아님)
assert out.source == "1만 500원"
@pytest.mark.asyncio
async def test_price_span_not_in_text_rejected():
"""LLM 이 원문에 없는 가격 표현을 지어내면 폐기(환각 차단)."""
nat = InputInterpreter(llm_call=_fake({"intent": "price", "choice": None, "price_text": "9,000원"}))
assert await nat.interpret("만원이면 가능합니다", input_mode="price") is None
@pytest.mark.asyncio
async def test_unknown_and_failures_fall_back():
assert await InputInterpreter(llm_call=_fake({"intent": "unknown"})).interpret(
"글쎄요 검토해 볼게요", input_mode="yes_no", input_options=["예", "아니오"]) is None
def boom(messages):
raise RuntimeError("LLM down")
assert await InputInterpreter(llm_call=boom).interpret("네", input_mode="yes_no", input_options=["예"]) is None
def slow(messages):
import time
time.sleep(0.5)
return {"intent": "choice", "choice": "예"}
nat = InputInterpreter(llm_call=slow, timeout_seconds=0.05)
assert await nat.interpret("네", input_mode="yes_no", input_options=["예"]) is None
# ---- 챗 플로우 E2E (fake LLM) ------------------------------------------------
def _routing_fake(messages):
"""단계별 fake — 기대 입력이 가격이면 price, 아니면 '예' choice 로 응답."""
user = messages[-1]["content"]
if "가격(숫자)" in user:
return {"intent": "price", "choice": None, "price_text": "1만 500원"}
return {"intent": "choice", "choice": "예", "price_text": None}
@pytest.mark.asyncio
async def test_chat_flow_free_text_negotiation(db_engine):
"""자유 발화만으로 담당자확인 분기 + 가격 입력이 진행된다 (버튼 없는 '진짜 대화')."""
from router.v1.chat.protocol import Req_Chat
from services.chat_service import ChatService, reset_sessions
from tenancy.config_loader import TenantConfigLoader
from tenancy.registry import TenantEngineRegistry
reset_sessions()
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
eng = await reg.get_engine("imarketkorea")
eng.config.llm.enabled = True
svc = ChatService()
svc._interpreter = InputInterpreter(llm_call=_routing_fake)
orig = InputInterpreter.available
InputInterpreter.available = staticmethod(lambda: True)
try:
sid = None
r = await svc.chat(eng, Req_Chat(session_id=sid)) # 서비스안내
sid = r.session_id
r = await svc.chat(eng, Req_Chat(session_id=sid, user_input="확인")) # 담당자확인 (fast path)
assert r.step == "담당자확인" and r.interpreted_input is None
# 자유 발화 → NLU 가 "예" 로 매핑 → 협상품목안내
r = await svc.chat(eng, Req_Chat(session_id=sid, user_input="네 접니다, 말씀하세요"))
assert r.step == "협상품목안내"
assert r.interpreted_input == "예"
r = await svc.chat(eng, Req_Chat(session_id=sid, user_input="확인")) # 기존가격제시(price)
# 자유 발화 가격 → span "1만 500원" → 결정론 파서 10500 → 가격 저장 후 확인 단계
r = await svc.chat(eng, Req_Chat(session_id=sid, user_input="저희 마진상 1만 500원까지는 맞춰드릴 수 있습니다"))
assert r.step == "가격협상_확인"
assert r.interpreted_input == "10500"
assert "10500" in r.script # 멘트 치환도 해석된 가격으로
finally:
InputInterpreter.available = orig
eng.config.llm.enabled = False
@pytest.mark.asyncio
async def test_chat_flow_without_llm_keeps_legacy_behavior(db_engine):
"""LLM 미설정(available=False)이면 자유 발화는 원문 그대로 엔진에 전달 — 기존 동작 회귀 없음."""
from router.v1.chat.protocol import Req_Chat
from services.chat_service import ChatService, reset_sessions
from tenancy.config_loader import TenantConfigLoader
from tenancy.registry import TenantEngineRegistry
reset_sessions()
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
eng = await reg.get_engine("imarketkorea")
svc = ChatService()
sid = None
r = await svc.chat(eng, Req_Chat(session_id=sid))
sid = r.session_id
r = await svc.chat(eng, Req_Chat(session_id=sid, user_input="확인"))
assert r.step == "담당자확인"
# conftest 가드로 available=False → NLU 미동작, interpreted_input 없음
r = await svc.chat(eng, Req_Chat(session_id=sid, user_input="네 접니다"))
assert r.interpreted_input is None
+5 -5
View File
@@ -29,12 +29,12 @@ async def test_step_requires_tenant_header(client):
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_step_tenant_divergence(client): async def test_step_tenant_divergence(client):
rk = await client.post("/v1/negotiation/step", headers={"X-Tenant-ID": "ktcommerce"}, json=_BODY) rk = await client.post("/v1/negotiation/step", headers={"X-Tenant-ID": "_base"}, json=_BODY)
ri = await client.post("/v1/negotiation/step", headers={"X-Tenant-ID": "imarketkorea"}, json=_BODY) ri = await client.post("/v1/negotiation/step", headers={"X-Tenant-ID": "imarketkorea"}, json=_BODY)
assert rk.status_code == 200 and ri.status_code == 200 assert rk.status_code == 200 and ri.status_code == 200
dk, di = rk.json(), ri.json() dk, di = rk.json(), ri.json()
# 같은 입력이 테넌트 config 에 따라 다른 상태/카드로 갈린다 # 같은 입력이 테넌트 config 에 따라 다른 상태/카드로 갈린다 (_base=공용 NGC-0xx, imk=NGC-Bxxx)
assert dk["card_id"].startswith("NGC-A") assert dk["card_id"].startswith("NGC-0")
assert di["card_id"].startswith("NGC-B") assert di["card_id"].startswith("NGC-B")
assert dk["state_index"] != di["state_index"] assert dk["state_index"] != di["state_index"]
# 응답 형태 # 응답 형태
@@ -49,7 +49,7 @@ async def test_step_tenant_divergence(client):
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_step_invalid_distribution_code_is_domain_error(client): async def test_step_invalid_distribution_code_is_domain_error(client):
body = dict(_BODY, distribution_code="Z") body = dict(_BODY, distribution_code="Z")
r = await client.post("/v1/negotiation/step", headers={"X-Tenant-ID": "ktcommerce"}, json=body) r = await client.post("/v1/negotiation/step", headers={"X-Tenant-ID": "imarketkorea"}, json=body)
assert r.status_code == 200 # HTTP 는 200, 결과코드로 에러 전달(backend 규약) assert r.status_code == 200 # HTTP 는 200, 결과코드로 에러 전달(backend 규약)
assert r.json()["result"]["desc"] == "NEGO_INVALID_STEP" assert r.json()["result"]["desc"] == "NEGO_INVALID_STEP"
@@ -57,5 +57,5 @@ async def test_step_invalid_distribution_code_is_domain_error(client):
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_step_invalid_outcome(client): async def test_step_invalid_outcome(client):
body = dict(_BODY, outcome="maybe") body = dict(_BODY, outcome="maybe")
r = await client.post("/v1/negotiation/step", headers={"X-Tenant-ID": "ktcommerce"}, json=body) r = await client.post("/v1/negotiation/step", headers={"X-Tenant-ID": "imarketkorea"}, json=body)
assert r.json()["result"]["desc"] == "INVALID_REQUEST_DATA" assert r.json()["result"]["desc"] == "INVALID_REQUEST_DATA"
+1 -1
View File
@@ -62,5 +62,5 @@ async def test_tenant_header_required(client):
assert r.json()["result"]["desc"] == "TENANT_HEADER_MISSING" assert r.json()["result"]["desc"] == "TENANT_HEADER_MISSING"
# 헤더가 있으면 미들웨어 통과 (라우트 미존재라 404). # 헤더가 있으면 미들웨어 통과 (라우트 미존재라 404).
r = await client.get("/v1/some-protected-path", headers={"X-Tenant-ID": "ktcommerce"}) r = await client.get("/v1/some-protected-path", headers={"X-Tenant-ID": "imarketkorea"})
assert r.status_code == 404 assert r.status_code == 404
+10 -11
View File
@@ -22,7 +22,7 @@ def _loader() -> TenantConfigLoader:
def test_platform_neutral_defaults_load(): def test_platform_neutral_defaults_load():
cfg = _loader().load("ktcommerce") cfg = _loader().load("_base")
# 우리 플랫폼 중립 기본값 (CLEANROOM.md) # 우리 플랫폼 중립 기본값 (CLEANROOM.md)
assert cfg.state.revenue.thresholds == [10_000_000, 50_000_000] assert cfg.state.revenue.thresholds == [10_000_000, 50_000_000]
@@ -47,12 +47,12 @@ def test_platform_neutral_defaults_load():
def test_state_space_and_action_space_size(): def test_state_space_and_action_space_size():
cfg = _loader().load("ktcommerce") cfg = _loader().load("_base")
assert cfg.state.state_space_size == 162 # 3×3×3×3×2 (차원 구성은 기능적 설계) assert cfg.state.state_space_size == 162 # 3×3×3×3×2 (차원 구성은 기능적 설계)
assert cfg.action_mapping.action_space_size == 9 assert cfg.action_mapping.action_space_size == 11
# 합성 데모 카드 코드 (우리 스킴) # 공용 카드 코드 (파일 폴백 스냅샷 — 정본은 DB 카탈로그)
assert cfg.action_mapping.action_to_card["0"] == "NGC-A001" assert cfg.action_mapping.action_to_card["0"] == "NGC-001"
assert cfg.action_mapping.action_to_card["8"] == "NGC-A009" assert cfg.action_mapping.action_to_card["8"] == "NGC-009"
def test_base_deep_merge_unit(): def test_base_deep_merge_unit():
@@ -77,20 +77,19 @@ def test_second_tenant_overrides_merged_on_base():
assert cfg.policy.type == "ucb" assert cfg.policy.type == "ucb"
# 차원은 데모 테넌트 A 와 동일(162) → base warm-start 호환(P5) # 차원은 데모 테넌트 A 와 동일(162) → base warm-start 호환(P5)
assert cfg.state.state_space_size == 162 assert cfg.state.state_space_size == 162
assert cfg.action_mapping.action_space_size == 9 assert cfg.action_mapping.action_space_size == 11
assert cfg.action_mapping.action_to_card["0"] == "NGC-B001" assert cfg.action_mapping.action_to_card["0"] == "NGC-B001"
def test_base_self_does_not_inherit(): def test_base_self_does_not_inherit():
cfg = _loader().load("_base") cfg = _loader().load("_base")
assert cfg.tenant_id == "_base" assert cfg.tenant_id == "_base"
# _base 는 기본 9카드(자동 온보딩 테넌트가 물려받음, base 정책 162×9 정합) # _base 는 기본 11카드(자동 온보딩 테넌트가 물려받음, base 정책 162×11 정합)
assert cfg.action_mapping.action_space_size == 9 assert cfg.action_mapping.action_space_size == 11
def test_is_registered(): def test_is_registered():
loader = _loader() loader = _loader()
assert loader.is_registered("ktcommerce") is True
assert loader.is_registered("imarketkorea") is True assert loader.is_registered("imarketkorea") is True
# 미등록 company_id(uuid 등)는 _base 자동 온보딩 대상이라 '등록됨'으로 본다. 빈 키만 미등록. # 미등록 company_id(uuid 등)는 _base 자동 온보딩 대상이라 '등록됨'으로 본다. 빈 키만 미등록.
assert loader.is_registered("00000000-0000-0000-0000-000000000001") is True assert loader.is_registered("00000000-0000-0000-0000-000000000001") is True
@@ -99,7 +98,7 @@ def test_is_registered():
def test_no_proprietary_card_codes_or_labels_in_repo(): def test_no_proprietary_card_codes_or_labels_in_repo():
"""클린룸 가드: 독점 카드 코드/ verbatim 라벨이 로드된 config 에 존재하지 않는다.""" """클린룸 가드: 독점 카드 코드/ verbatim 라벨이 로드된 config 에 존재하지 않는다."""
for tid in ("_base", "ktcommerce", "imarketkorea"): for tid in ("_base", "imarketkorea"):
cfg = _loader().load(tid) cfg = _loader().load(tid)
cards = " ".join(cfg.action_mapping.action_to_card.values()) cards = " ".join(cfg.action_mapping.action_to_card.values())
assert "NC26" not in cards # 참고 엔진의 고유 카드 코드 assert "NC26" not in cards # 참고 엔진의 고유 카드 코드
+19 -19
View File
@@ -46,7 +46,7 @@ def _snapshot(**over) -> NegotiationSnapshot:
def test_build_state_deterministic_and_in_range(): def test_build_state_deterministic_and_in_range():
cfg = _cfg("ktcommerce") cfg = _cfg("_base")
snap = _snapshot() snap = _snapshot()
s1 = build_state(snap, cfg.state) s1 = build_state(snap, cfg.state)
s2 = build_state(snap, cfg.state) s2 = build_state(snap, cfg.state)
@@ -65,7 +65,7 @@ def test_encode_index_known_example():
def test_mixed_radix_bijection_over_full_space(): def test_mixed_radix_bijection_over_full_space():
cfg = _cfg("ktcommerce") cfg = _cfg("_base")
dims = state_dims(cfg.state) dims = state_dims(cfg.state)
assert dims == [3, 3, 3, 3, 2] assert dims == [3, 3, 3, 3, 2]
seen = set() seen = set()
@@ -77,17 +77,17 @@ def test_mixed_radix_bijection_over_full_space():
def test_config_injection_changes_classification(): def test_config_injection_changes_classification():
# revenue=20,000,000 원: ktcommerce(th=[10M,50M]) → mid(1), imarketkorea(th=[30M,100M]) → low(0) # revenue=20,000,000 원: _base(th=[10M,50M]) → mid(1), imarketkorea(th=[30M,100M]) → low(0)
snap = _snapshot(revenue_amount=20_000_000) snap = _snapshot(revenue_amount=20_000_000)
kt = build_state(snap, _cfg("ktcommerce").state) base = build_state(snap, _cfg("_base").state)
imk = build_state(snap, _cfg("imarketkorea").state) imk = build_state(snap, _cfg("imarketkorea").state)
assert kt.revenue_idx == 1 assert base.revenue_idx == 1
assert imk.revenue_idx == 0 assert imk.revenue_idx == 0
assert kt != imk # 같은 입력이 테넌트 config 에 따라 다른 상태 assert base != imk # 같은 입력이 테넌트 config 에 따라 다른 상태
def test_distribution_unknown_code_raises(): def test_distribution_unknown_code_raises():
cfg = _cfg("ktcommerce") cfg = _cfg("_base")
snap = _snapshot(distribution_code="Z") # code_map 에 없음 snap = _snapshot(distribution_code="Z") # code_map 에 없음
try: try:
build_state(snap, cfg.state) build_state(snap, cfg.state)
@@ -97,7 +97,7 @@ def test_distribution_unknown_code_raises():
def test_price_zone_and_partner_buckets(): def test_price_zone_and_partner_buckets():
cfg = _cfg("ktcommerce").state cfg = _cfg("_base").state
# 제시가 ≤ 앵커가(9900) → 우선협상 구간(0) # 제시가 ≤ 앵커가(9900) → 우선협상 구간(0)
assert build_state(_snapshot(input_price=9800), cfg).price_zone_idx == 0 assert build_state(_snapshot(input_price=9800), cfg).price_zone_idx == 0
# 제시가 > 앵커가 → 협상 지속 구간(1) # 제시가 > 앵커가 → 협상 지속 구간(1)
@@ -110,28 +110,28 @@ def test_price_zone_and_partner_buckets():
def test_reward_deterministic_and_config_driven(): def test_reward_deterministic_and_config_driven():
snap = _snapshot(outcome=NegotiationOutcome.FAILURE, round_number=2) snap = _snapshot(outcome=NegotiationOutcome.FAILURE, round_number=2)
kt = _cfg("ktcommerce") base = _cfg("_base")
imk = _cfg("imarketkorea") imk = _cfg("imarketkorea")
kt_rc = RewardCalculator(kt.reward, kt.state) # failure_penalty -0.5 base_rc = RewardCalculator(base.reward, base.state) # failure_penalty -0.5
imk_rc = RewardCalculator(imk.reward, imk.state) # failure_penalty -0.7 imk_rc = RewardCalculator(imk.reward, imk.state) # failure_penalty -0.7
r1 = kt_rc.calculate(snap) r1 = base_rc.calculate(snap)
r2 = kt_rc.calculate(snap) r2 = base_rc.calculate(snap)
assert r1 == r2 # 결정론 assert r1 == r2 # 결정론
assert r1.end_reward == -0.5 # config 반영 assert r1.end_reward == -0.5 # config 반영
assert imk_rc.calculate(snap).end_reward == -0.7 assert imk_rc.calculate(snap).end_reward == -0.7
# 성공 라운드 보상이 실패보다 크다 (방향성) # 성공 라운드 보상이 실패보다 크다 (방향성)
success = _snapshot(outcome=NegotiationOutcome.SUCCESS, round_number=0) success = _snapshot(outcome=NegotiationOutcome.SUCCESS, round_number=0)
assert kt_rc.calculate(success).total > kt_rc.calculate(_snapshot(outcome=NegotiationOutcome.FAILURE, round_number=0)).total assert base_rc.calculate(success).total > base_rc.calculate(_snapshot(outcome=NegotiationOutcome.FAILURE, round_number=0)).total
def test_action_card_mapper_roundtrip_and_mask(): def test_action_card_mapper_roundtrip_and_mask():
cfg = _cfg("ktcommerce") cfg = _cfg("_base")
mapper = ActionCardMapper(cfg.action_mapping) mapper = ActionCardMapper(cfg.action_mapping)
assert mapper.action_space_size == 9 assert mapper.action_space_size == 11
assert mapper.get_card_id(0) == "NGC-A001" assert mapper.get_card_id(0) == "NGC-001"
assert mapper.get_action_id("NGC-A001") == 0 assert mapper.get_action_id("NGC-001") == 0
assert mapper.get_card_id(99) is None assert mapper.get_card_id(99) is None
# 중복방지 마스킹: 사용한 action 제외 # 중복방지 마스킹: 사용한 action 제외
@@ -139,7 +139,7 @@ def test_action_card_mapper_roundtrip_and_mask():
assert mask.dtype == np.bool_ assert mask.dtype == np.bool_
assert mask[0] == False and mask[3] == False assert mask[0] == False and mask[3] == False
assert mask[1] == True assert mask[1] == True
assert mask.sum() == 7 assert mask.sum() == 9
# reload 로 다른 테넌트 카드셋 교체 # reload 로 다른 테넌트 카드셋 교체
mapper.reload(_cfg("imarketkorea").action_mapping) mapper.reload(_cfg("imarketkorea").action_mapping)
+139 -13
View File
@@ -27,22 +27,22 @@ def _registry() -> TenantEngineRegistry:
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_two_tenants_distinct_engines(): async def test_two_tenants_distinct_engines():
reg = _registry() reg = _registry()
e1 = await reg.get_engine("ktcommerce") e1 = await reg.get_engine("_base")
e2 = await reg.get_engine("imarketkorea") e2 = await reg.get_engine("imarketkorea")
assert e1 is not e2 assert e1 is not e2
assert e1.tenant_id == "ktcommerce" and e2.tenant_id == "imarketkorea" assert e1.tenant_id == "_base" and e2.tenant_id == "imarketkorea"
# 서로 다른 카드매핑 (다른 카드셋) # 서로 다른 카드매핑 (다른 카드셋 — _base=공용 카탈로그, imk=파일 오버라이드)
assert e1.mapper.get_card_id(0) == "NGC-A001" assert e1.mapper.get_card_id(0) == "NGC-001"
assert e2.mapper.get_card_id(0) == "NGC-B001" assert e2.mapper.get_card_id(0) == "NGC-B001"
# 차원 # 차원
assert e1.state_space_size == 162 and e1.action_space_size == 9 assert e1.state_space_size == 162 and e1.action_space_size == 11
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_engine_cached(): async def test_engine_cached():
reg = _registry() reg = _registry()
a = await reg.get_engine("ktcommerce") a = await reg.get_engine("imarketkorea")
b = await reg.get_engine("ktcommerce") b = await reg.get_engine("imarketkorea")
assert a is b # 캐시 — 동일 인스턴스 assert a is b # 캐시 — 동일 인스턴스
@@ -58,7 +58,7 @@ async def test_concurrent_first_build_once():
return EngineFactory.build(config) return EngineFactory.build(config)
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0), factory=CountingFactory) reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0), factory=CountingFactory)
results = await asyncio.gather(*[reg.get_engine("ktcommerce") for _ in range(12)]) results = await asyncio.gather(*[reg.get_engine("imarketkorea") for _ in range(12)])
# 모두 같은 인스턴스 + 1회만 조립 # 모두 같은 인스턴스 + 1회만 조립
assert all(r is results[0] for r in results) assert all(r is results[0] for r in results)
assert builds["n"] == 1 assert builds["n"] == 1
@@ -69,9 +69,9 @@ async def test_unregistered_company_id_auto_onboards():
reg = _registry() reg = _registry()
# 미등록 company_id(uuid)는 _base 자동 온보딩 → 엔진 생성됨(베이스 9카드, 162 state). # 미등록 company_id(uuid)는 _base 자동 온보딩 → 엔진 생성됨(베이스 9카드, 162 state).
eng = await reg.get_engine("00000000-0000-0000-0000-000000000001") eng = await reg.get_engine("00000000-0000-0000-0000-000000000001")
assert eng.action_space_size == 9 and eng.state_space_size == 162 assert eng.action_space_size == 11 and eng.state_space_size == 162
assert eng.company_id == "00000000-0000-0000-0000-000000000001" assert eng.company_id == "00000000-0000-0000-0000-000000000001"
assert reg.is_registered("ktcommerce") is True assert reg.is_registered("imarketkorea") is True
# 빈 키만 미등록 → KeyError # 빈 키만 미등록 → KeyError
with pytest.raises(KeyError): with pytest.raises(KeyError):
await reg.get_engine("") await reg.get_engine("")
@@ -80,9 +80,9 @@ async def test_unregistered_company_id_auto_onboards():
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_reload_rebuilds_only_that_tenant(): async def test_reload_rebuilds_only_that_tenant():
reg = _registry() reg = _registry()
a = await reg.get_engine("ktcommerce") a = await reg.get_engine("_base")
b = await reg.get_engine("imarketkorea") b = await reg.get_engine("imarketkorea")
reloaded = await reg.reload("ktcommerce") reloaded = await reg.reload("_base")
assert reloaded is not a # 재조립됨 assert reloaded is not a # 재조립됨
assert await reg.get_engine("imarketkorea") is b # 타테넌트는 그대로 assert await reg.get_engine("imarketkorea") is b # 타테넌트는 그대로
@@ -97,6 +97,132 @@ def test_episode_state_is_request_scoped():
assert not hasattr(TenantEngine, "used_action_ids") assert not hasattr(TenantEngine, "used_action_ids")
@pytest.mark.asyncio
async def test_action_space_from_db_catalog(db_engine):
"""action_mapping.type=db(_base) 면 카드 카탈로그(DB)가 action space 를 정의한다 — config 파일이 아님.
negodata 에서 카드가 추가/삭제되면 config 수정 없이 action space 가 반영됨을 의미."""
from common.enums import ErrorType
from negotiation.cards.ports.card_catalog_port import ICardCatalogRepository
class _FakeCatalog(ICardCatalogRepository):
async def get_nego_catalog(self, cdb, company_id=None):
return ErrorType.SUCCESS, ["NGC-001", "NGC-002", "NGC-003"] # 3장짜리 카탈로그(파일은 11장)
reg = TenantEngineRegistry(
loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0),
catalog_repo=_FakeCatalog(),
)
eng = await reg.get_engine("_base") # _base = type:db
assert eng.action_space_size == 3 # DB 카탈로그(3)가 정의 — 파일 폴백(11) 아님
assert eng.mapper.get_card_id(0) == "NGC-001"
assert eng.mapper.get_card_id(2) == "NGC-003"
assert eng.mapper.get_action_id("NGC-002") == 1
@pytest.mark.asyncio
async def test_action_space_falls_back_to_file_when_catalog_empty(db_engine):
"""카탈로그가 비면(신규/미시드 DB) 파일 action_to_card 로 폴백한다."""
from common.enums import ErrorType
from negotiation.cards.ports.card_catalog_port import ICardCatalogRepository
class _EmptyCatalog(ICardCatalogRepository):
async def get_nego_catalog(self, cdb, company_id=None):
return ErrorType.SUCCESS, []
reg = TenantEngineRegistry(
loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0),
catalog_repo=_EmptyCatalog(),
)
eng = await reg.get_engine("_base")
assert eng.action_space_size == 11 # 파일 폴백(11장 스냅샷)
assert eng.mapper.get_card_id(0) == "NGC-001"
@pytest.mark.asyncio
async def test_company_brand_from_db_for_auto_onboard(db_engine):
"""자동 온보딩 고객사(company_id=UUID)는 company.companies.name 으로 {company_name} 을 채운다."""
import uuid as _uuid
from common.enums import ErrorType
from tenancy.company_profile_repo import ICompanyProfileRepository
class _FakeCompany(ICompanyProfileRepository):
async def get_company_name(self, cdb, company_id):
return ErrorType.SUCCESS, "풀무원"
reg = TenantEngineRegistry(
loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0),
company_repo=_FakeCompany(),
)
eng = await reg.get_engine(str(_uuid.uuid4())) # UUID → 자동 온보딩 + 브랜드 DB
assert eng.config.resources.company_name == "풀무원"
@pytest.mark.asyncio
async def test_demo_tenant_keeps_file_brand(db_engine):
"""데모 테넌트(비-UUID)는 회사명 조회 없이 파일 브랜드 유지."""
from common.enums import ErrorType
from tenancy.company_profile_repo import ICompanyProfileRepository
class _FakeCompany(ICompanyProfileRepository):
async def get_company_name(self, cdb, company_id):
return ErrorType.SUCCESS, "USED-ONLY-IF-QUERIED"
reg = TenantEngineRegistry(
loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0),
company_repo=_FakeCompany(),
)
eng = await reg.get_engine("imarketkorea") # 비-UUID → 조회 안 함
assert eng.config.resources.company_name == "데모상사 B"
@pytest.mark.asyncio
async def test_catalog_includes_company_cards(db_engine):
"""per-company 카탈로그: 공용 카드(NGC-*) + 그 회사 유저가 만든 카드 — 공용 먼저 → 회사 뒤."""
import uuid as _uuid
from datetime import datetime, timezone
from sqlalchemy import column, delete, insert, table
from common.database.db_session_manager import DB_SESSION_MNG
from common.enums import DBType, ErrorType
from negotiation.cards.adapters.card_catalog_db import CardCatalogDbRepository
cid, uid, card_id = _uuid.uuid4(), _uuid.uuid4(), _uuid.uuid4()
_USERS = table("users", column("user_id"), column("company_id"), column("id"), column("password"),
column("last_accessed_at"), column("status"), column("role"), schema="company")
_NEGO = table("nego_cards", column("nego_card_id"), column("user_id"), column("name"),
column("number"), column("usage_type"), schema="card")
async def _seed(s):
await DB_SESSION_MNG.add(s, insert(_USERS).values(
user_id=uid, company_id=cid, id="pytest_catalog_user", password="x",
last_accessed_at=datetime.now(timezone.utc), status=1, role=1))
return await DB_SESSION_MNG.add(s, insert(_NEGO).values(
nego_card_id=card_id, user_id=uid, name="회사전용카드", number="COMP-01", usage_type=1))
err = await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [_seed])
assert err == ErrorType.SUCCESS
try:
repo = CardCatalogDbRepository()
_, nums = await DB_SESSION_MNG.execute_lambda(
DBType.MAIN.value, 1, lambda s: repo.get_nego_catalog(s, cid))
assert "COMP-01" in nums # 회사 카드 포함
assert nums[0] == "NGC-001" # 공용이 먼저(action_id 0 안정)
assert nums[-1] == "COMP-01" # 회사 카드는 뒤에 append
assert nums.index("NGC-011") < nums.index("COMP-01") # 공용 전부 → 회사
# company_id 없으면 공용만 (회사 카드 제외)
_, shared_only = await DB_SESSION_MNG.execute_lambda(
DBType.MAIN.value, 1, lambda s: repo.get_nego_catalog(s, None))
assert "COMP-01" not in shared_only
finally:
await DB_SESSION_MNG.execute_lambda_run(
[DBType.MAIN.value],
[lambda s: DB_SESSION_MNG.add(s, delete(_NEGO).where(_NEGO.c.nego_card_id == card_id)),
lambda s: DB_SESSION_MNG.add(s, delete(_USERS).where(_USERS.c.user_id == uid))],
)
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_middleware_header_missing_unregistered_registered(client): async def test_middleware_header_missing_unregistered_registered(client):
# 헤더 누락 → 400 # 헤더 누락 → 400
@@ -110,6 +236,6 @@ async def test_middleware_header_missing_unregistered_registered(client):
assert r.json().get("result", {}).get("desc") != "TENANT_NOT_REGISTERED" assert r.json().get("result", {}).get("desc") != "TENANT_NOT_REGISTERED"
# 등록 테넌트 → 미들웨어 통과 # 등록 테넌트 → 미들웨어 통과
r = await client.get("/v1/protected", headers={"X-Tenant-ID": "ktcommerce"}) r = await client.get("/v1/protected", headers={"X-Tenant-ID": "imarketkorea"})
assert r.status_code == 404 assert r.status_code == 404
assert r.json().get("result", {}).get("desc") != "TENANT_NOT_REGISTERED" assert r.json().get("result", {}).get("desc") != "TENANT_NOT_REGISTERED"
+54 -3
View File
@@ -58,8 +58,8 @@ async def test_warm_start_copies_base_with_decayed_visits(db_engine):
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_cold_start_creates_warmstart_version(db_engine): async def test_cold_start_creates_warmstart_version(db_engine):
await _seed_base() await _seed_base(A=11) # imarketkorea action_space=11 과 차원 일치해야 warm-start
eng = await _reg().get_engine("ktcommerce") # 활성 버전 없음 → cold-start eng = await _reg().get_engine("imarketkorea") # 활성 버전 없음 → cold-start
policy, version_id, repo = await QTablePolicyStore.load(eng) policy, version_id, repo = await QTablePolicyStore.load(eng)
err, ver = await repo.read(lambda s: repo.get_active_version(s)) err, ver = await repo.read(lambda s: repo.get_active_version(s))
assert ver.version_name == "v000_warmstart_from_base" assert ver.version_name == "v000_warmstart_from_base"
@@ -67,6 +67,57 @@ async def test_cold_start_creates_warmstart_version(db_engine):
assert policy.qtable.q[5, 2] == 0.9 assert policy.qtable.q[5, 2] == 0.9
@pytest.mark.asyncio
async def test_catalog_dim_change_migrates_preserving_learning(db_engine):
"""카탈로그 카드 수 변경(9→11) 시 학습 보존 마이그레이션 — 겹치는 셀 복사 + 새 카드 fresh."""
import uuid as _uuid
cid = str(_uuid.uuid4())
# 이 회사 활성 버전을 A=9 로 시드 + 셀 (5,2)=0.9
repo = LearningRepository(cid)
vid = await repo.get_or_create_active_version(
state_space_size=162, action_space_size=9, learning_rate=0.1, discount_factor=0.95,
scope=2, version_name="old_v9")
await repo.upsert_cell(vid, state_index=5, action_id=2, q_value=0.9, count=7)
# 엔진(_base type:db → 카탈로그 11장) 로드 → 9≠11 감지 → 마이그레이션
eng = await _reg().get_engine(cid)
assert eng.action_space_size == 11
policy, new_vid, _ = await QTablePolicyStore.load(eng)
assert str(new_vid) != str(vid) # 새 버전
assert policy.qtable.q[5, 2] == 0.9 # 기존 학습 보존
assert policy.qtable.q[5, 10] == 0.0 # 새 카드(action 10) fresh
assert policy.qtable.visits[5, 2] == 7 # 방문수도 보존
# 새 버전이 활성 · 차원 11
err, active = await repo.read(lambda s: repo.get_active_version(s))
assert str(active.version_id) == str(new_vid) and active.action_space_size == 11
@pytest.mark.asyncio
async def test_migration_remaps_by_card_number(db_engine):
"""카드번호 기반 마이그레이션 — 중간 카드 삭제로 action_id 가 밀려도 학습이 카드를 따라간다."""
import uuid as _uuid
cid = str(_uuid.uuid4())
repo = LearningRepository(cid)
# A=3, action_cards=[NGC-001, NGC-002, NGC-003]. (5,2)=0.9 는 NGC-003 의 학습.
vid = await repo.get_or_create_active_version(
state_space_size=162, action_space_size=3, learning_rate=0.1, discount_factor=0.95,
scope=2, version_name="v_cards3", action_cards=["NGC-001", "NGC-002", "NGC-003"])
await repo.upsert_cell(vid, state_index=5, action_id=2, q_value=0.9, count=4) # NGC-003
await repo.upsert_cell(vid, state_index=5, action_id=0, q_value=0.3, count=2) # NGC-001
_, active = await repo.read(lambda s: repo.get_active_version(s))
# 새 카탈로그: 중간 NGC-002 제거 → [NGC-001, NGC-003] (A=2). NGC-003: old action 2 → new action 1.
new_vid = await repo.migrate_active_version_dim(
old_version=active, state_space_size=162, action_space_size=2,
learning_rate=0.1, discount_factor=0.95, action_cards=["NGC-001", "NGC-003"])
assert new_vid is not None
qcells, _ = await repo.load_cells(new_vid)
qmap = {(st, a): q for st, a, q in qcells}
assert qmap.get((5, 1)) == 0.9 # NGC-003 학습이 새 action_id 1 로 따라감(밀림 보정)
assert qmap.get((5, 0)) == 0.3 # NGC-001 은 그대로 action_id 0
assert (5, 2) not in qmap # 삭제된 NGC-002 자리 없음
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_dimension_mismatch_falls_back_to_heuristic(db_engine): async def test_dimension_mismatch_falls_back_to_heuristic(db_engine):
await _seed_base(S=162, A=9) await _seed_base(S=162, A=9)
@@ -89,7 +140,7 @@ async def test_no_base_returns_none(db_engine):
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_existing_version_not_warmstarted(db_engine): async def test_existing_version_not_warmstarted(db_engine):
await _seed_base() await _seed_base()
eng = await _reg().get_engine("ktcommerce") eng = await _reg().get_engine("imarketkorea")
# 첫 로드 → warm-start 버전 생성 # 첫 로드 → warm-start 버전 생성
await QTablePolicyStore.load(eng) await QTablePolicyStore.load(eng)
# 둘째 로드 → 기존 활성 버전 재사용(중복 warm-start 안 함) # 둘째 로드 → 기존 활성 버전 재사용(중복 warm-start 안 함)
+23 -3
View File
@@ -7,7 +7,7 @@ reset-learning, reset-all, q-table/{versions,switch,current}, experience-logs, t
import pytest import pytest
H = {"X-Tenant-ID": "ktcommerce"} H = {"X-Tenant-ID": "imarketkorea"}
@pytest.mark.asyncio @pytest.mark.asyncio
@@ -66,6 +66,26 @@ async def test_card_update_search(client, db_engine):
assert any(m["card_id"] == "CUSTOM-X" for m in allm["mapping"]) assert any(m["card_id"] == "CUSTOM-X" for m in allm["mapping"])
@pytest.mark.asyncio
async def test_catalog_refresh(client, db_engine):
# 카탈로그 발행 후 엔진 재조립 트리거 — 성공 + action_space 반환. 헤더 없으면 400.
r = await client.post("/v1/catalog-refresh", headers=H)
assert r.status_code == 200
body = r.json()
assert body["success"] and body["action_space_size"] >= 1
r2 = await client.post("/v1/catalog-refresh")
assert r2.status_code == 400
@pytest.mark.asyncio
async def test_catalog_refresh_all_no_tenant_header(client, db_engine):
# 공용 카탈로그 전역 반영 — 테넌트 헤더 없이도 200(화이트리스트) + 캐시 클리어.
await client.post("/v1/catalog-refresh", headers=H) # 엔진 하나 캐시
r = await client.post("/v1/catalog-refresh-all") # 헤더 없음
assert r.status_code == 200
assert r.json()["success"] is True
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_invalidate_and_reset_scoped(client, db_engine): async def test_invalidate_and_reset_scoped(client, db_engine):
# 가격협상 카드선택이 일어나는 긴 경로(850→900→990)로 양 테넌트 데이터 생성 # 가격협상 카드선택이 일어나는 긴 경로(850→900→990)로 양 테넌트 데이터 생성
@@ -77,7 +97,7 @@ async def test_invalidate_and_reset_scoped(client, db_engine):
sid = cr.json()["session_id"] sid = cr.json()["session_id"]
if cr.json().get("chat_end"): if cr.json().get("chat_end"):
break break
H2 = {"X-Tenant-ID": "imarketkorea"} H2 = {"X-Tenant-ID": "00000000-0000-0000-0000-0000000000b2"} # 실고객사 모사(자동 온보딩)
sid2 = None sid2 = None
for ui in convo: for ui in convo:
cr = await client.post("/v1/chat", headers=H2, json={"session_id": sid2, "user_input": ui}) cr = await client.post("/v1/chat", headers=H2, json={"session_id": sid2, "user_input": ui})
@@ -88,7 +108,7 @@ async def test_invalidate_and_reset_scoped(client, db_engine):
before2 = (await client.get("/v1/experience-logs", headers=H2)).json()["total"] before2 = (await client.get("/v1/experience-logs", headers=H2)).json()["total"]
assert before2 >= 1 assert before2 >= 1
# ktcommerce reset-all → imarketkorea 무영향 # imarketkorea reset-all → 타테넌트(H2) 무영향
assert (await client.post("/v1/reset-all", headers=H)).json()["success"] assert (await client.post("/v1/reset-all", headers=H)).json()["success"]
assert (await client.get("/v1/experience-logs", headers=H)).json()["total"] == 0 assert (await client.get("/v1/experience-logs", headers=H)).json()["total"] == 0
assert (await client.get("/v1/experience-logs", headers=H2)).json()["total"] == before2 assert (await client.get("/v1/experience-logs", headers=H2)).json()["total"] == before2
+104 -15
View File
@@ -2,8 +2,8 @@
1. 전체 대화: 서비스안내→담당자확인→협상품목안내→가격협상→와일드카드→협상완료→협상종료(chat_end). 1. 전체 대화: 서비스안내→담당자확인→협상품목안내→가격협상→와일드카드→협상완료→협상종료(chat_end).
2. 가격협상 턴에서 카드 선택 + 학습(card_id, updated_q). 2. 가격협상 턴에서 카드 선택 + 학습(card_id, updated_q).
3. 와일드카드 발동(wild_card_budget) + 종료 보상(success). 3. 와일드카드 발동(wild_card_1pct) + 종료 보상(success).
4. 브랜드 치환 테넌트별(데모상사 A/B), 클린룸(스크립트에 KT 흔적 없음). 4. 브랜드 치환(데모상사 B), 클린룸(스크립트에 KT 흔적 없음).
5. 경험로그 적재 + 종료 후 진행 시 에러. 5. 경험로그 적재 + 종료 후 진행 시 에러.
6. (HTTP) 헤더로 새 세션 시작 + 한 턴 진행. 6. (HTTP) 헤더로 새 세션 시작 + 한 턴 진행.
""" """
@@ -15,6 +15,8 @@ import pytest
from router.v1.chat.protocol import Req_Chat from router.v1.chat.protocol import Req_Chat
from services.chat_service import ChatService, reset_sessions from services.chat_service import ChatService, reset_sessions
from negotiation.chat.service.chat_engine import ChatEngine, ChatSession
from negotiation.chat.service.script_repository import ScriptRepository
from negotiation.qtable.infra.repository.learning_repository import LearningRepository from negotiation.qtable.infra.repository.learning_repository import LearningRepository
from tenancy.config_loader import TenantConfigLoader from tenancy.config_loader import TenantConfigLoader
from tenancy.registry import TenantEngineRegistry from tenancy.registry import TenantEngineRegistry
@@ -42,10 +44,11 @@ async def _run(svc, eng, turns):
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_full_conversation_reaches_completion(db_engine): async def test_full_conversation_reaches_completion(db_engine):
reset_sessions() reset_sessions()
eng = await _reg().get_engine("ktcommerce") eng = await _reg().get_engine("imarketkorea")
svc = ChatService() svc = ChatService()
# anchor=9900, target=10000(기본). 11000(>10395)→가격협상(카드), 10200(9900~10395)→와일드카드, 9800(≤anchor)→우선협상 # anchor=9900, target=10000(기본). 11000(>anchor*1.02)→가격협상(카드),
turns = [None, "확인", "예", "확인", "11000", "예", "10200", "예", "9800", "예", # 10000(anchor<p≤anchor*1.02)→1% 와일드카드→수락하면 협상완료.
turns = [None, "확인", "예", "확인", "11000", "예", "10000", "예", "예",
"협상 내용을 확인했으며, 이의가 없음에 동의합니다."] "협상 내용을 확인했으며, 이의가 없음에 동의합니다."]
out = await _run(svc, eng, turns) out = await _run(svc, eng, turns)
steps = [r.step for r in out] steps = [r.step for r in out]
@@ -56,22 +59,22 @@ async def test_full_conversation_reaches_completion(db_engine):
# 가격협상 카드선택 + 학습 # 가격협상 카드선택 + 학습
nego = [r for r in out if r.step == "가격협상"] nego = [r for r in out if r.step == "가격협상"]
assert nego and nego[0].card_id and nego[0].card_id.startswith("NGC-A") assert nego and nego[0].card_id and nego[0].card_id.startswith("NGC-B")
assert nego[0].updated_q is not None assert nego[0].updated_q is not None
# 와일드카드 발동 # 와일드카드 발동 (1% 인하)
assert any(r.step == "wild_card_budget" for r in out) assert any(r.step == "wild_card_1pct" for r in out)
# 종료 보상(success) # 종료 보상(success)
done = [r for r in out if r.outcome == "success"] done = [r for r in out if r.outcome == "success"]
assert done and done[0].reward_total is not None assert done and done[0].reward_total is not None
# 브랜드 치환 + 클린룸 # 브랜드 치환 + 클린룸
assert "데모상사 A" in out[0].script assert "데모상사 B" in out[0].script
assert not _KT.search(out[0].script) assert not _KT.search(out[0].script)
# 경험로그 적재 # 경험로그 적재
repo = LearningRepository("ktcommerce") repo = LearningRepository("imarketkorea")
err, cnt = await repo.read(lambda s: repo.count_experience(s)) err, cnt = await repo.read(lambda s: repo.count_experience(s))
assert cnt >= 1 assert cnt >= 1
@@ -84,7 +87,7 @@ async def test_wildcard_1pct_accept_settles_at_offer_price(db_engine):
잡히던 버그 — settled_price 가 인하가(예: 19800)로 내려와야 한다. 잡히던 버그 — settled_price 가 인하가(예: 19800)로 내려와야 한다.
""" """
reset_sessions() reset_sessions()
eng = await _reg().get_engine("ktcommerce") eng = await _reg().get_engine("imarketkorea")
svc = ChatService() svc = ChatService()
# anchor=9900(기본). 10000 은 anchor*1.02(10098) 이내 → wild_card_1pct 발동, offer_1pct=9900. # anchor=9900(기본). 10000 은 anchor*1.02(10098) 이내 → wild_card_1pct 발동, offer_1pct=9900.
out = await _run(svc, eng, [None, "확인", "예", "확인", "10000", "예", "예", out = await _run(svc, eng, [None, "확인", "예", "확인", "10000", "예", "예",
@@ -122,10 +125,96 @@ def test_acceptance_ratio_dynamic_calc():
assert calc({"input_price": 9800}) == 0.0 # 기준가 전무(과거 세션 호환) assert calc({"input_price": 9800}) == 0.0 # 기준가 전무(과거 세션 호환)
def test_card_id_fixed_mapping_and_selection_mask():
"""카드 정리 후: action_id↔카드는 테넌트 매핑으로 고정, 견적 선택은 available_mask 로 걸러진다.
(구 인덱스 방식 폐기 — selected[action_id] 인덱싱은 견적마다 action_id 의미가 달라져 Q-table 오염.)"""
class _Mapper:
_m = {i: f"NGC-B{i + 1:03d}" for i in range(11)}
def get_card_id(self, a):
return self._m.get(a)
def get_action_id(self, num):
return next((a for a, c in self._m.items() if c == num), None)
class _Engine:
mapper = _Mapper()
action_space_size = 11
eng = _Engine()
session = ChatSession(
session_id="00000000-0000-0000-0000-000000000001", tenant_id="imarketkorea", company_id="imarketkorea",
context={"selected_nego_card_numbers": ["NGC-B003", "NGC-B008"]}, action_space_size=11,
)
# ① card_id 는 고정 매핑 (선택 리스트 인덱싱 아님)
assert ChatService._card_id_for_action(eng, session, 0) == "NGC-B001"
assert ChatService._card_id_for_action(eng, session, 2) == "NGC-B003"
# ② 선택은 mask 로 — NGC-B003(action 2), NGC-B008(action 7) 만 pickable
mask = ChatService._selection_mask(eng, session)
assert mask is not None and mask[2] and mask[7]
assert not mask[0] and not mask[5] and mask.sum() == 2
# ③ 사용한 action 은 mask 에서 제외
session.used_action_ids = {2}
mask2 = ChatService._selection_mask(eng, session)
assert not mask2[2] and mask2[7] and mask2.sum() == 1
# ④ 선택 없으면 None → 전체 허용(폴백)
session.context["selected_nego_card_numbers"] = []
assert ChatService._selection_mask(eng, session) is None
def test_default_1pct_wildcard_still_runs_without_selected_wildcard():
"""1% 인하는 기본 제공 카드라 DB 견적에서 와일드카드를 선택하지 않아도 발동한다."""
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("imarketkorea")
repo = ScriptRepository(cfg, _TENANTS_DIR)
engine = ChatEngine(repo, rq_type="재협상")
session = ChatSession(
session_id="00000000-0000-0000-0000-000000000002",
tenant_id="imarketkorea",
company_id="imarketkorea",
step="가격협상_확인",
action_space_size=0,
context={
"input_price": 10000,
"anchor_price": 9900,
"target_price": 10000,
"round": 1,
"allow_selected_wildcards": False,
},
)
view = engine.advance(session, "예")
assert view.step == "wild_card_1pct"
def test_budget_wildcard_requires_selected_wildcard_for_db_context():
"""재원부족 구간은 DB 견적에서 와일드카드를 선택했을 때만 발동한다."""
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("imarketkorea")
repo = ScriptRepository(cfg, _TENANTS_DIR)
engine = ChatEngine(repo, rq_type="재협상")
session = ChatSession(
session_id="00000000-0000-0000-0000-000000000003",
tenant_id="imarketkorea",
company_id="imarketkorea",
step="가격협상_확인",
action_space_size=0,
context={
"input_price": 10200,
"anchor_price": 9900,
"target_price": 10000,
"round": 1,
"allow_selected_wildcards": False,
},
)
view = engine.advance(session, "예")
assert view.step == "가격협상"
assert not view.step.startswith("wild_card_")
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_priority_completes_without_wildcard(db_engine): async def test_priority_completes_without_wildcard(db_engine):
reset_sessions() reset_sessions()
eng = await _reg().get_engine("ktcommerce") eng = await _reg().get_engine("imarketkorea")
svc = ChatService() svc = ChatService()
# 첫 제시가가 앵커가(9900) 이하 → 우선협상 → 바로 협상완료(카드/와일드카드 없이) # 첫 제시가가 앵커가(9900) 이하 → 우선협상 → 바로 협상완료(카드/와일드카드 없이)
out = await _run(svc, eng, [None, "확인", "예", "확인", "9800", "예", out = await _run(svc, eng, [None, "확인", "예", "확인", "9800", "예",
@@ -148,7 +237,7 @@ async def test_tenant_brand_isolation(db_engine):
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_advance_after_end_errors(db_engine): async def test_advance_after_end_errors(db_engine):
reset_sessions() reset_sessions()
eng = await _reg().get_engine("ktcommerce") eng = await _reg().get_engine("imarketkorea")
svc = ChatService() svc = ChatService()
out = await _run(svc, eng, [None, "확인", "예", "확인", "1000", "예", out = await _run(svc, eng, [None, "확인", "예", "확인", "1000", "예",
"협상 내용을 확인했으며, 이의가 없음에 동의합니다."]) "협상 내용을 확인했으며, 이의가 없음에 동의합니다."])
@@ -159,12 +248,12 @@ async def test_advance_after_end_errors(db_engine):
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_http_chat_start(client): async def test_http_chat_start(client):
r = await client.post("/v1/chat", headers={"X-Tenant-ID": "ktcommerce"}, json={"rq_type": "재협상"}) r = await client.post("/v1/chat", headers={"X-Tenant-ID": "imarketkorea"}, json={"rq_type": "재협상"})
assert r.status_code == 200 assert r.status_code == 200
d = r.json() d = r.json()
assert d["step"] == "서비스안내" assert d["step"] == "서비스안내"
assert d["input_options"] == ["확인"] assert d["input_options"] == ["확인"]
assert "데모상사 A" in d["script"] assert "데모상사 B" in d["script"]
# 헤더 없으면 400 # 헤더 없으면 400
r2 = await client.post("/v1/chat", json={"rq_type": "재협상"}) r2 = await client.post("/v1/chat", json={"rq_type": "재협상"})
assert r2.status_code == 400 assert r2.status_code == 400
+6 -6
View File
@@ -25,7 +25,7 @@ def _eng():
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_session_persists_and_resumes_across_instances(db_engine): async def test_session_persists_and_resumes_across_instances(db_engine):
reg = _eng() reg = _eng()
eng = await reg.get_engine("ktcommerce") eng = await reg.get_engine("imarketkorea")
# 인스턴스 1: 협상 시작 + 몇 턴 진행 (컨텍스트는 DB 조회 — 행이 없으므로 기본값 폴백) # 인스턴스 1: 협상 시작 + 몇 턴 진행 (컨텍스트는 DB 조회 — 행이 없으므로 기본값 폴백)
svc1 = ChatService() svc1 = ChatService()
@@ -51,19 +51,19 @@ async def test_session_persists_and_resumes_across_instances(db_engine):
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_session_company_scoped(db_engine): async def test_session_company_scoped(db_engine):
reg = _eng() reg = _eng()
eng = await reg.get_engine("ktcommerce") eng = await reg.get_engine("imarketkorea")
svc = ChatService() svc = ChatService()
r = await svc.chat(eng, Req_Chat()) r = await svc.chat(eng, Req_Chat())
sid = r.session_id sid = r.session_id
# 자사(ktcommerce)로는 조회됨 # 자사(imarketkorea)로는 조회됨
assert await ChatSessionRepository(eng.company_id).get(sid) is not None assert await ChatSessionRepository(eng.company_id).get(sid) is not None
# 타테넌트(imarketkorea) company_id 로는 조회 안 됨 (격리) # 타테넌트 company_id 로는 조회 안 됨 (격리)
assert await ChatSessionRepository("imarketkorea").get(sid) is None assert await ChatSessionRepository("00000000-0000-0000-0000-0000000000aa").get(sid) is None
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_get_none_for_missing(db_engine): async def test_get_none_for_missing(db_engine):
repo = ChatSessionRepository("ktcommerce") repo = ChatSessionRepository("imarketkorea")
assert await repo.get(None) is None assert await repo.get(None) is None
assert await repo.get("00000000-0000-0000-0000-000000000000") is None assert await repo.get("00000000-0000-0000-0000-000000000000") is None
+157
View File
@@ -0,0 +1,157 @@
"""Phase 2 표현층 검증 — ScriptNaturalizer (LLM 카드 멘트 자연화).
원칙 검증: LLM 은 말만 다듬고 숫자는 절대 만들지 않는다.
① 치환자 보존 성공 경로 ② 치환자 누락/추가 → 폐기 ③ 새 숫자 → 폐기
④ 타임아웃/예외 → 폐기(폴백) ⑤ 상황 라벨은 정성(수치 미노출)
⑥ 챗 플로우: llm.enabled=True 면 카드 멘트가 자연화본으로, 실패 시 원본으로.
"""
import asyncio
import os
import pytest
from negotiation.chat.service.script_naturalizer import ScriptNaturalizer, build_situation
_TEMPLATE = "제안해 주신 **{input_price}원**, 감사합니다. 한 번 더 검토해 가격을 제안해 주시겠어요?"
def _fake(reply):
"""llm_call 더블 — 고정 응답."""
def call(messages):
return {"script": reply}
return call
@pytest.mark.asyncio
async def test_naturalize_success_preserves_placeholders():
nat = ScriptNaturalizer(llm_call=_fake(
"긍정적으로 검토 중입니다. 다만 **{input_price}원**은 조정 여지가 있어 보입니다. 재제안 부탁드립니다."))
out = await nat.naturalize(_TEMPLATE, situation={"라운드": "초반 조율"}, tone=2, strategy=1)
assert out and "{input_price}" in out and out != _TEMPLATE
@pytest.mark.asyncio
async def test_naturalize_rejects_missing_placeholder():
nat = ScriptNaturalizer(llm_call=_fake("가격 재검토 부탁드립니다.")) # 치환자 삭제됨
assert await nat.naturalize(_TEMPLATE) is None
@pytest.mark.asyncio
async def test_naturalize_rejects_added_placeholder():
nat = ScriptNaturalizer(llm_call=_fake("{input_price}원과 {secret_discount}까지 드리겠습니다."))
assert await nat.naturalize(_TEMPLATE) is None # 원본에 없던 변수 환각
@pytest.mark.asyncio
async def test_naturalize_rejects_new_digits():
nat = ScriptNaturalizer(llm_call=_fake("{input_price}원에서 5% 더 인하해 주시면 즉시 계약하겠습니다."))
assert await nat.naturalize(_TEMPLATE) is None # LLM 이 만든 숫자(5) 금지
@pytest.mark.asyncio
async def test_naturalize_rejects_dropped_emphasis_markers():
"""고객사가 지정한 볼드/색 마커를 LLM 이 떨어뜨리면 폐기 → 원본(스타일 보존) 폴백."""
tmpl = "제안해 주신 **{input_price}원**, {{강조|재검토}} 부탁드립니다."
# 볼드·색 마커를 모두 지운 재작성 → 검증 실패
nat = ScriptNaturalizer(llm_call=_fake("제안해 주신 {input_price}원, 재검토 부탁드립니다."))
assert await nat.naturalize(tmpl) is None
# 마커를 그대로 유지한 재작성 → 통과
nat = ScriptNaturalizer(llm_call=_fake("제시하신 **{input_price}원** 관련, {{강조|재검토}}를 요청드립니다."))
out = await nat.naturalize(tmpl)
assert out and out.count("**") == 2 and "{{강조|" in out
@pytest.mark.asyncio
async def test_naturalize_timeout_falls_back():
def slow(messages):
import time
time.sleep(0.5)
return {"script": _TEMPLATE}
nat = ScriptNaturalizer(llm_call=slow, timeout_seconds=0.05)
assert await nat.naturalize(_TEMPLATE) is None
@pytest.mark.asyncio
async def test_naturalize_exception_falls_back():
def boom(messages):
raise RuntimeError("LLM down")
nat = ScriptNaturalizer(llm_call=boom)
assert await nat.naturalize(_TEMPLATE) is None
def test_build_situation_is_qualitative_only():
"""상황 라벨에 실제 수치가 노출되지 않는다(숫자 환각 차단의 전제)."""
ctx = {"round": 2, "input_price": 10200, "anchor_price": 9900, "target_price": 10000, "item_price": 11000}
s = build_situation(ctx)
assert s["라운드"] == "초반 조율"
assert s["가격구간"] == "목표 상회(추가 인하 필요)"
joined = str(s)
for n in ("10200", "9900", "10000", "11000"):
assert n not in joined # 수치 미노출
@pytest.mark.asyncio
async def test_chat_flow_uses_naturalized_script_when_llm_enabled(db_engine):
"""llm.enabled=True + 자격증명 존재 시 가격협상 카드 멘트가 자연화본(치환 완료)으로 나온다."""
from router.v1.chat.protocol import Req_Chat
from services.chat_service import ChatService, reset_sessions
from tenancy.config_loader import TenantConfigLoader
from tenancy.registry import TenantEngineRegistry
_TENANTS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tenants")
reset_sessions()
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
eng = await reg.get_engine("imarketkorea")
eng.config.llm.enabled = True # 테넌트 게이트 on
svc = ChatService()
svc._naturalizer = ScriptNaturalizer(llm_call=_fake(
"【자연화】 제시해 주신 **{input_price}원** 잘 검토했습니다. 초반 조율 단계이니 한 걸음 더 부탁드립니다."))
# 자격증명 게이트 우회(테스트 환경에 키가 없어도 동작 검증)
orig_available = ScriptNaturalizer.available
ScriptNaturalizer.available = staticmethod(lambda: True)
try:
sid = None
for ui in [None, "확인", "예", "확인", "11000", "예"]:
r = await svc.chat(eng, Req_Chat(session_id=sid, user_input=ui))
sid = r.session_id
assert r.step == "가격협상" and r.card_id
assert r.script.startswith("【자연화】") # LLM 재작성본 사용
assert "11000" in r.script # 치환은 엔진이 수행(숫자 정확)
assert "{input_price}" not in r.script # 치환 완료
finally:
ScriptNaturalizer.available = orig_available
eng.config.llm.enabled = False
@pytest.mark.asyncio
async def test_chat_flow_falls_back_to_template_on_llm_failure(db_engine):
"""LLM 실패 시 카드 원본 멘트로 폴백 — 협상은 절대 멈추지 않는다."""
from router.v1.chat.protocol import Req_Chat
from services.chat_service import ChatService, reset_sessions
from tenancy.config_loader import TenantConfigLoader
from tenancy.registry import TenantEngineRegistry
_TENANTS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tenants")
reset_sessions()
reg = TenantEngineRegistry(loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0))
eng = await reg.get_engine("imarketkorea")
eng.config.llm.enabled = True
def boom(messages):
raise RuntimeError("LLM down")
svc = ChatService()
svc._naturalizer = ScriptNaturalizer(llm_call=boom)
orig_available = ScriptNaturalizer.available
ScriptNaturalizer.available = staticmethod(lambda: True)
try:
sid = None
for ui in [None, "확인", "예", "확인", "11000", "예"]:
r = await svc.chat(eng, Req_Chat(session_id=sid, user_input=ui))
sid = r.session_id
assert r.step == "가격협상" and r.card_id
assert r.script and "11000" in r.script # 원본 템플릿 + 치환으로 정상 응답
finally:
ScriptNaturalizer.available = orig_available
eng.config.llm.enabled = False
+32 -13
View File
@@ -20,7 +20,7 @@ _TENANTS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__fi
_FORBIDDEN = re.compile(r"kt\s*commerce|케이티|커머스|nego-?wiz", re.IGNORECASE) _FORBIDDEN = re.compile(r"kt\s*commerce|케이티|커머스|nego-?wiz", re.IGNORECASE)
def _repo(tenant_id="ktcommerce"): def _repo(tenant_id="imarketkorea"):
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load(tenant_id) cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load(tenant_id)
return ScriptRepository(cfg, _TENANTS_DIR) return ScriptRepository(cfg, _TENANTS_DIR)
@@ -65,11 +65,9 @@ def test_cleanroom_no_proprietary_brand_in_any_resource():
def test_brand_substitution_per_tenant(): def test_brand_substitution_per_tenant():
kt = _repo("ktcommerce").get_step("서비스안내", "재협상")
im = _repo("imarketkorea").get_step("서비스안내", "재협상") im = _repo("imarketkorea").get_step("서비스안내", "재협상")
assert "데모상사 A" in kt["script"] and "Negosium" in kt["script"] assert "데모상사 B" in im["script"] and "Negosium" in im["script"]
assert "데모상사 B" in im["script"] assert "{company_name}" not in im["script"] # 치환 완료
assert "{company_name}" not in kt["script"] # 치환 완료
def test_variable_substitution_and_missing_kept(): def test_variable_substitution_and_missing_kept():
@@ -103,12 +101,16 @@ async def test_resolve_card_script_file_mode_default():
repo = _repo() repo = _repo()
assert repo._config.cards.source_type == "file" assert repo._config.cards.source_type == "file"
# action 0 파일 멘트가 변수 치환되어 나온다 (DB 무접근) # action 0 파일 멘트가 변수 치환되어 나온다 (DB 무접근)
out = await repo.resolve_card_script(0, "NGC-A001", {"input_price": 9800}) out = await repo.resolve_card_script(0, "NGC-B001", {"input_price": 9800})
assert out and "9800" in out assert out and "9800" in out
class _FakeCardRepo: from negotiation.cards.ports.card_script_port import ICardScriptRepository
"""ICardScriptRepository 더블 — DB 없이 카드코드→멘트 매핑만 흉내(세션 인자 무시)."""
class _FakeCardRepo(ICardScriptRepository):
"""ICardScriptRepository 더블 — DB 없이 카드코드→멘트 매핑만 흉내(세션 인자 무시).
포트 상속으로 get_card_by_number 기본 구현(메타 None)을 물려받는다."""
def __init__(self, by_number: dict): def __init__(self, by_number: dict):
self._by = by_number self._by = by_number
@@ -121,9 +123,9 @@ class _FakeCardRepo:
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_resolve_card_script_db_mode_prefers_db(monkeypatch): async def test_resolve_card_script_db_mode_prefers_db(monkeypatch):
"""source_type='backoffice_db': card.nego_cards.script(정본)를 파일보다 우선 사용 + 마커 보존.""" """source_type='backoffice_db': card.nego_cards.script(정본)를 파일보다 우선 사용 + 마커 보존."""
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("ktcommerce") cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("imarketkorea")
cfg.cards.source_type = "backoffice_db" cfg.cards.source_type = "backoffice_db"
fake = _FakeCardRepo({"NGC-A001": "DB 편집 멘트 **{input_price}원** 검토 중입니다."}) fake = _FakeCardRepo({"NGC-B001": "DB 편집 멘트 **{input_price}원** 검토 중입니다."})
repo = ScriptRepository(cfg, _TENANTS_DIR, card_repo=fake) repo = ScriptRepository(cfg, _TENANTS_DIR, card_repo=fake)
# execute_lambda 를 세션 없이 콜백만 실행하도록 대체(순수 단위검증) # execute_lambda 를 세션 없이 콜백만 실행하도록 대체(순수 단위검증)
@@ -132,14 +134,14 @@ async def test_resolve_card_script_db_mode_prefers_db(monkeypatch):
from negotiation.chat.service import script_repository as _sr from negotiation.chat.service import script_repository as _sr
monkeypatch.setattr(_sr.DB_SESSION_MNG, "execute_lambda", _fake_lambda) monkeypatch.setattr(_sr.DB_SESSION_MNG, "execute_lambda", _fake_lambda)
out = await repo.resolve_card_script(0, "NGC-A001", {"input_price": 9800}) out = await repo.resolve_card_script(0, "NGC-B001", {"input_price": 9800})
assert out == "DB 편집 멘트 **9800원** 검토 중입니다." # DB 우선 + 마커(**) 불투명 보존 + 변수 치환 assert out == "DB 편집 멘트 **9800원** 검토 중입니다." # DB 우선 + 마커(**) 불투명 보존 + 변수 치환
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_resolve_card_script_db_mode_falls_back_to_file(monkeypatch): async def test_resolve_card_script_db_mode_falls_back_to_file(monkeypatch):
"""DB 에 해당 카드 멘트가 없으면 파일(scripts_cards.json)로 폴백.""" """DB 에 해당 카드 멘트가 없으면 파일(scripts_cards.json)로 폴백."""
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("ktcommerce") cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("imarketkorea")
cfg.cards.source_type = "backoffice_db" cfg.cards.source_type = "backoffice_db"
fake = _FakeCardRepo({}) # DB 미보유 fake = _FakeCardRepo({}) # DB 미보유
repo = ScriptRepository(cfg, _TENANTS_DIR, card_repo=fake) repo = ScriptRepository(cfg, _TENANTS_DIR, card_repo=fake)
@@ -149,5 +151,22 @@ async def test_resolve_card_script_db_mode_falls_back_to_file(monkeypatch):
from negotiation.chat.service import script_repository as _sr from negotiation.chat.service import script_repository as _sr
monkeypatch.setattr(_sr.DB_SESSION_MNG, "execute_lambda", _fake_lambda) monkeypatch.setattr(_sr.DB_SESSION_MNG, "execute_lambda", _fake_lambda)
out = await repo.resolve_card_script(0, "NGC-A001", {"input_price": 9800}) out = await repo.resolve_card_script(0, "NGC-B001", {"input_price": 9800})
assert out and "9800" in out # 파일 폴백 멘트 assert out and "9800" in out # 파일 폴백 멘트
@pytest.mark.asyncio
async def test_resolve_card_script_prefer_db_for_selected_cards(monkeypatch):
"""견적에서 선택된 백오피스 카드 번호는 file 모드여도 DB 멘트를 우선한다."""
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("imarketkorea")
assert cfg.cards.source_type == "file"
fake = _FakeCardRepo({"2": "선택 카드 DB 멘트 **{input_price}원**"})
repo = ScriptRepository(cfg, _TENANTS_DIR, card_repo=fake)
async def _fake_lambda(_db, _wr, func):
return await func(None)
from negotiation.chat.service import script_repository as _sr
monkeypatch.setattr(_sr.DB_SESSION_MNG, "execute_lambda", _fake_lambda)
out = await repo.resolve_card_script(1, "2", {"input_price": 10200}, prefer_db=True)
assert out == "선택 카드 DB 멘트 **10200원**"
+63
View File
@@ -0,0 +1,63 @@
"""카드 스크립트 → 임베딩 캐시 생성 (action-as-feature 준비, 1회 실행).
card.nego_cards(11장)의 name+script 를 문장 임베딩으로 변환해 artifacts/card_embeddings.npz 에 저장.
새 카드가 추가되면 이 스크립트를 다시 돌리면 된다(그 카드만 임베딩돼 캐시에 합류).
실행:
APP_ENV=local python -m tools.build_card_embeddings
출력:
artifacts/card_embeddings.npz (numbers, names, strategy, tone, embeddings[N,384])
"""
import asyncio
import os
import numpy as np
_HERE = os.path.dirname(os.path.abspath(__file__))
ARTIFACTS = os.path.join(_HERE, "..", "artifacts")
OUT_PATH = os.path.join(ARTIFACTS, "card_embeddings.npz")
MODEL_NAME = "paraphrase-multilingual-MiniLM-L12-v2" # 384차원, 한국어 지원, 로컬/무료
async def load_cards():
"""card.nego_cards 에서 (number, name, script, strategy_type, tone) 로드."""
import asyncpg
conn = await asyncpg.connect(
host="127.0.0.1", port=5432, user="postgres", password="password", database="negosium_db")
try:
rows = await conn.fetch(
"SELECT number, name, script, strategy_type, tone FROM card.nego_cards "
"WHERE deleted = FALSE ORDER BY number")
return [(r["number"], r["name"], r["script"], r["strategy_type"], r["tone"]) for r in rows]
finally:
await conn.close()
def main():
cards = asyncio.run(load_cards())
if not cards:
raise SystemExit("card.nego_cards 가 비어있음 — DB 시드 확인 (docker start negosium-pg)")
print(f"카드 {len(cards)}장 로드: {[c[0] for c in cards]}")
from sentence_transformers import SentenceTransformer
model = SentenceTransformer(MODEL_NAME)
texts = [f"{name}. {script}" for _, name, script, _, _ in cards]
emb = model.encode(texts, normalize_embeddings=True) # [N, 384], 단위벡터
print(f"임베딩 shape: {emb.shape}")
os.makedirs(ARTIFACTS, exist_ok=True)
np.savez(
OUT_PATH,
numbers=np.array([c[0] for c in cards]),
names=np.array([c[1] for c in cards]),
strategy=np.array([c[3] for c in cards], dtype=np.int64),
tone=np.array([c[4] for c in cards], dtype=np.int64),
embeddings=emb.astype(np.float32),
)
print(f"저장: {OUT_PATH}")
if __name__ == "__main__":
main()
+251
View File
@@ -0,0 +1,251 @@
"""기존 Q-Table(UCB) vs action-as-feature DQN 공정 비교 — 고객사 성향 조건화 환경 (최종).
같은 환경(FeatureBuyer 2축 + 협력사·고객사성향 랜덤)에서 동일 에피소드로 학습·평가.
- Q-Table: 이산 state 162칸 + 카드=슬롯. 성향(고객사) 입력 자체가 불가능 → 평균 성향에 수렴
- DQN : 연속 상태 + 성향 벡터 + 카드 특징(임베딩+전략/톤 one-hot)
평가 4종:
① 학습 카드 9장 — 평균보상(진짜 목적함수) + top3 적중(MC 정답 기준)
② zero-shot 11장 — 안 본 카드 2장 포함
③ 새 카드 첫 턴 사용률 — 구조적 차이
④ 성향 극단 테스트 — 같은 협력사, 성향만 바꿨을 때 카드를 바꾸는가
실행: APP_ENV=local python -m tools.compare_qtable_vs_dqn
"""
import random
import numpy as np
import torch
from eval_harness.buyer import Scenario
from eval_harness.feature_buyer import FeatureBuyer, SupplierProfile, sample_supplier
from negotiation.policies.feature_dqn_policy import FeatureDQNPolicy
from negotiation.policies.qtable_policy import UCBQTablePolicy
from negotiation.policies.base import EpisodeState, PolicyContext, Transition
from negotiation.qtable.domain.model.q_table import QTable
from negotiation.qtable.domain.model.snapshot import NegotiationOutcome
from negotiation.qtable.domain.service.feature_builder import (
STATE_FEATURE_DIM, TENANT_FEATURE_DIM, build_state_features)
from negotiation.qtable.domain.service.reward_calculator import RewardCalculator
from negotiation.qtable.domain.service.state_calculator import state_index
from tenancy.config_loader import TenantConfigLoader
from tools.train_feature_dqn import (
ANCHOR, HOLDOUT, MAX_TURNS, TARGET, load_cards, make_snapshot, pref_config, sample_tenant_pref)
# ---- 정책 어댑터 ------------------------------------------------------------------
class DQNAdapter:
name = "feature_dqn"
def __init__(self, policy, feat):
self.p, self.feat = policy, feat
def _sf(self, snap, tf):
return np.concatenate([build_state_features(snap), tf])
def choose(self, snap, tf, avail, greedy):
self.p.greedy = greedy
i, _, _ = self.p.select(self._sf(snap, tf), np.stack([self.feat[c] for c in avail]))
return avail[i]
def learn(self, snap, tf, card, reward, next_snap, next_avail, done):
sf = self._sf(snap, tf)
if done or next_snap is None:
self.p.remember(sf, self.feat[card], reward, None, None, True)
else:
self.p.remember(sf, self.feat[card], reward, self._sf(next_snap, tf),
np.stack([self.feat[c] for c in next_avail]), False)
self.p.train_step()
class QTableAdapter:
"""기존 UCBQTablePolicy. 성향(tf)은 구조상 받을 수 없다 — 이산 state 162칸에 그 축이 없음."""
name = "qtable_ucb"
def __init__(self, all_numbers, state_cfg, lr=0.1, gamma=0.95):
self.numbers = list(all_numbers)
self.a_of = {n: i for i, n in enumerate(self.numbers)}
self.state_cfg = state_cfg
self.qt = QTable(162, len(self.numbers), learning_rate=lr, discount_factor=gamma)
self.pol = UCBQTablePolicy(self.qt)
def choose(self, snap, tf, avail, greedy):
idx = state_index(snap, self.state_cfg)
if greedy:
q = self.qt.row(idx)
return max(avail, key=lambda c: q[self.a_of[c]])
mask = np.zeros(len(self.numbers), dtype=bool)
for c in avail:
mask[self.a_of[c]] = True
ctx = PolicyContext(state_index=idx, snapshot=snap, action_space_size=len(self.numbers),
episode=EpisodeState(), available_mask=mask)
return self.numbers[self.pol.select(ctx).action_id]
def learn(self, snap, tf, card, reward, next_snap, next_avail, done):
idx = state_index(snap, self.state_cfg)
nidx = state_index(next_snap, self.state_cfg) if (next_snap is not None and not done) else None
self.pol.update(Transition(state_index=idx, action_id=self.a_of[card], reward=reward,
next_state_index=nidx, done=done))
class RandomAdapter:
name = "random"
def __init__(self, seed=0):
self.rng = np.random.default_rng(seed)
def choose(self, snap, tf, avail, greedy):
return avail[self.rng.integers(len(avail))]
def learn(self, *a, **k):
pass
# ---- 공용 에피소드 -----------------------------------------------------------------
def run_episode(adapter, sup, tf, pool, strat, rc, seed, learn=True, greedy=False, forced_first=None):
buyer = FeatureBuyer(sup, strat, seed=seed, max_turns=MAX_TURNS)
scenario = Scenario(anchor_price=ANCHOR, target_price=TARGET, revenue_amount=sup.revenue_amount,
distribution_code=sup.distribution_code, partner_count=sup.partner_count)
price0 = TARGET * 1.15
price, used, total_r, first_card = price0, set(), 0.0, None
for turn in range(1, MAX_TURNS + 1):
acceptance = max(0.0, (price0 - price) / price0)
snap = make_snapshot(sup, price, turn, acceptance)
avail = [c for c in pool if c not in used] or list(pool)
if turn == 1 and forced_first is not None:
card = forced_first
else:
card = adapter.choose(snap, tf, avail, greedy)
used.add(card)
if first_card is None:
first_card = card
resp = buyer.respond(card, scenario, turn, price)
price = resp.new_price
done = resp.accept or price <= ANCHOR or turn >= MAX_TURNS
success = resp.accept or price <= ANCHOR
outcome = (NegotiationOutcome.SUCCESS if success
else NegotiationOutcome.FAILURE if done else NegotiationOutcome.ONGOING)
# 채점은 최종 결과 시점만 (중간 턴 0 → γ 부트스트랩으로 전파).
# 진행 중 보상을 누적하면 '질질 끄는 전략'이 부당하게 유리해지는 인공물이 생긴다.
r = rc.calculate(make_snapshot(sup, price, turn, acceptance, outcome)).total if done else 0.0
total_r += r
if learn:
if done:
adapter.learn(snap, tf, card, r, None, None, True)
else:
acc2 = max(0.0, (price0 - price) / price0)
nsnap = make_snapshot(sup, price, turn + 1, acc2)
navail = [c for c in pool if c not in used] or list(pool)
adapter.learn(snap, tf, card, r, nsnap, navail, False)
if done:
return total_r, success, price, first_card
return total_r, False, price, first_card
# ---- MC 정답 랭킹: 이 (협력사, 성향)에서 진짜 좋은 첫 카드 top-k ---------------------
_rand = RandomAdapter(seed=1)
def rank_cards_mc(sup, tf, pool, strat, rc, seed, sims=6, k=3):
means = {}
for c in pool:
rs = [run_episode(_rand, sup, tf, pool, strat, rc, seed=seed + 17 * s,
learn=False, greedy=False, forced_first=c)[0] for s in range(sims)]
means[c] = np.mean(rs)
return sorted(means, key=lambda c: -means[c])[:k]
# ---- 학습/평가 ---------------------------------------------------------------------
def train(adapter, pool, strat, base_reward, state_cfg, episodes, seed):
rng = np.random.default_rng(seed)
for ep in range(1, episodes + 1):
sup = sample_supplier(rng)
rcfg, tf = sample_tenant_pref(rng, base_reward)
rc = RewardCalculator(rcfg, state_cfg)
run_episode(adapter, sup, tf, pool, strat, rc, seed=seed * 100 + ep, learn=True)
def evaluate(adapter, pool, strat, base_reward, state_cfg, n=300, seed0=777, label=""):
from negotiation.qtable.domain.service.feature_builder import build_tenant_features
rng = np.random.default_rng(seed0)
rewards, succ, ratios, hits, holdout_first = [], 0, [], 0, 0
for i in range(n):
sup = sample_supplier(rng)
rcfg, tf = sample_tenant_pref(rng, base_reward)
rc = RewardCalculator(rcfg, state_cfg)
good = rank_cards_mc(sup, tf, pool, strat, rc, seed=seed0 * 7 + i)
r, ok, price, first = run_episode(adapter, sup, tf, pool, strat, rc,
seed=seed0 * 1000 + i, learn=False, greedy=True)
rewards.append(r); succ += ok; ratios.append(price / TARGET)
hits += (first in good); holdout_first += (first in HOLDOUT)
m, ci = float(np.mean(rewards)), float(1.96 * np.std(rewards) / np.sqrt(n))
print(f"{label:<14} mean_rwd={m:.4f} ±{ci:.4f} success={succ/n:.3f} "
f"settled/tgt={np.mean(ratios):.3f} top3_hit={hits/n:.3f} 새카드첫턴={holdout_first/n:.3f}")
def pref_behavior_test(adapters, pool, strat, base_reward, state_cfg):
"""④ 같은 협력사, 성향만 바꿨을 때 카드를 바꾸는가 (greedy).
첫 턴은 '일단 깎기'가 공통 정답이라 성향 차이가 잘 안 드러난다.
→ 협상 중반(가격이 이미 target 근처, 3턴째) 상태를 함께 프로브: 여기서
성사중시는 '마무리(수락 잘 되는) 카드', 가격중시는 '더 깎는 카드'가 갈려야 한다.
"""
from negotiation.qtable.domain.service.feature_builder import build_tenant_features
sups = [SupplierProfile(5_000_000, 3, "A"), # 소형·경쟁多
SupplierProfile(200_000_000, 1, "A")] # 대형·단독
probes = [("첫턴", TARGET * 1.15, 1, 0.0),
("중반(3턴,가격↓)", TARGET * 1.02, 3, 0.11)]
for pr_name, price, turn, acc in probes:
print(f"\n ── 프로브: {pr_name} (price={price:.0f}) ──")
print(f" {'협력사':<13} {'성향':<9} " + " ".join(f"{a.name:<15}" for a in adapters))
for sup in sups:
row = {}
for p, pname in [(0.05, "성사중시"), (0.95, "가격중시")]:
rcfg = pref_config(base_reward, p)
tf = build_tenant_features(rcfg)
picks = []
for a in adapters:
snap = make_snapshot(sup, price, turn, acc)
picks.append(a.choose(snap, tf, pool, True))
seg = f"{sup.segment[0]}·{sup.segment[1]}"
print(f" {seg:<13} {pname:<9} " + " ".join(f"{c}(전략{strat[c]})".ljust(15) for c in picks))
def main(episodes=10000, seed=42):
random.seed(seed); np.random.seed(seed); torch.manual_seed(seed)
numbers, feat, strat = load_cards()
train_pool = [c for c in numbers if c not in HOLDOUT]
tcfg = TenantConfigLoader().load("ktcommerce")
card_dim = feat[numbers[0]].shape[0]
print(f"환경: 2축 FeatureBuyer + 성향 랜덤 · 학습 {episodes}ep · 카드특징 {card_dim}차원 "
f"(임베딩384+전략4+톤4) · 학습 {len(train_pool)}장 / 홀드아웃 {HOLDOUT}")
qt = QTableAdapter(numbers, tcfg.state)
dqn = DQNAdapter(FeatureDQNPolicy(state_dim=STATE_FEATURE_DIM + TENANT_FEATURE_DIM,
card_dim=card_dim, eps_decay=4000), feat)
print("\n[학습] qtable_ucb ...")
train(qt, train_pool, strat, tcfg.reward, tcfg.state, episodes, seed)
print("[학습] feature_dqn ...")
train(dqn, train_pool, strat, tcfg.reward, tcfg.state, episodes, seed)
print("\n=== ① 학습 카드 9장 풀 ===")
evaluate(RandomAdapter(seed), train_pool, strat, tcfg.reward, tcfg.state, label="random")
evaluate(qt, train_pool, strat, tcfg.reward, tcfg.state, label="qtable_ucb")
evaluate(dqn, train_pool, strat, tcfg.reward, tcfg.state, label="feature_dqn")
print("\n=== ② zero-shot 11장 풀 (안 본 카드 2장 포함) ===")
evaluate(RandomAdapter(seed), numbers, strat, tcfg.reward, tcfg.state, label="random")
evaluate(qt, numbers, strat, tcfg.reward, tcfg.state, label="qtable_ucb")
evaluate(dqn, numbers, strat, tcfg.reward, tcfg.state, label="feature_dqn")
print("\n=== ④ 성향 극단 테스트 — 같은 협력사, 성향만 바꾸면 카드를 바꾸는가 (11장 풀) ===")
pref_behavior_test([qt, dqn], numbers, strat, tcfg.reward, tcfg.state)
if __name__ == "__main__":
main()
+5 -5
View File
@@ -9,9 +9,9 @@
실행: 실행:
cd agent cd agent
APP_ENV=local python -m tools.console_demo --tenant ktcommerce # 기본 시나리오 APP_ENV=local python -m tools.console_demo --tenant imarketkorea # 기본 시나리오
APP_ENV=local python -m tools.console_demo --tenant imarketkorea --no-db # DB 로깅 없이 APP_ENV=local python -m tools.console_demo --tenant imarketkorea --no-db # DB 로깅 없이
APP_ENV=local python -m tools.console_demo --tenant ktcommerce --interactive APP_ENV=local python -m tools.console_demo --tenant imarketkorea --interactive
""" """
import argparse import argparse
@@ -74,7 +74,7 @@ def _scenario():
async def run(tenant_id: str, use_db: bool, interactive: bool): async def run(tenant_id: str, use_db: bool, interactive: bool):
loader = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0) loader = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0)
if not loader.is_registered(tenant_id): if not loader.is_registered(tenant_id):
print(f"[!] 미등록 테넌트: {tenant_id}. 등록된 테넌트: ktcommerce, imarketkorea, _base") print(f"[!] 미등록 테넌트: {tenant_id}. 등록된 테넌트: imarketkorea, _base")
return return
registry = TenantEngineRegistry(loader=loader) registry = TenantEngineRegistry(loader=loader)
engine = await registry.get_engine(tenant_id) engine = await registry.get_engine(tenant_id)
@@ -172,7 +172,7 @@ def _interactive_turns():
def main(): def main():
ap = argparse.ArgumentParser(description="협상 의사결정 루프 콘솔 데모 (P0~P4)") ap = argparse.ArgumentParser(description="협상 의사결정 루프 콘솔 데모 (P0~P4)")
ap.add_argument("--tenant", default="ktcommerce", help="테넌트 id (ktcommerce|imarketkorea)") ap.add_argument("--tenant", default="imarketkorea", help="테넌트 id (imarketkorea|_base)")
ap.add_argument("--no-db", action="store_true", help="DB 로깅 비활성화") ap.add_argument("--no-db", action="store_true", help="DB 로깅 비활성화")
ap.add_argument("--interactive", action="store_true", help="턴마다 직접 입력") ap.add_argument("--interactive", action="store_true", help="턴마다 직접 입력")
args = ap.parse_args() args = ap.parse_args()
+42
View File
@@ -0,0 +1,42 @@
"""full_autonomy 체크포인트(.pt) → 서빙 번들(autonomy_serving.npz) export.
dqn_serving 과 동일 패턴: ScoreNet 가중치만 numpy 로 묶어 PyTorch 없이 서빙한다.
행동 특징은 코드(autonomy_actions)가 런타임 생성하므로 번들에는 가중치만 담는다.
실행(호스트, torch 필요): APP_ENV=local python -m tools.export_autonomy_serving
"""
import os
import numpy as np
import torch
from negotiation.policies.autonomy_actions import ACTION_DIM, EXTRA_STATE_DIM
from negotiation.qtable.domain.service.feature_builder import STATE_FEATURE_DIM, TENANT_FEATURE_DIM
_HERE = os.path.dirname(os.path.abspath(__file__))
CKPT_PATH = os.path.join(_HERE, "..", "artifacts", "full_autonomy.pt")
OUT_PATH = os.path.join(_HERE, "..", "artifacts", "autonomy_serving.npz")
STATE_DIM = STATE_FEATURE_DIM + TENANT_FEATURE_DIM + EXTRA_STATE_DIM
def main():
sd = torch.load(CKPT_PATH, map_location="cpu")
W0, b0 = sd["net.0.weight"].numpy(), sd["net.0.bias"].numpy()
W1, b1 = sd["net.2.weight"].numpy(), sd["net.2.bias"].numpy()
W2, b2 = sd["net.4.weight"].numpy(), sd["net.4.bias"].numpy()
assert W0.shape[1] == STATE_DIM + ACTION_DIM, f"입력 차원 불일치: {W0.shape[1]}"
tmp = OUT_PATH + ".tmp"
with open(tmp, "wb") as f:
np.savez(f, W0=W0, b0=b0, W1=W1, b1=b1, W2=W2, b2=b2,
state_dim=STATE_DIM, action_dim=ACTION_DIM)
if os.path.exists(OUT_PATH):
os.replace(OUT_PATH, OUT_PATH + ".prev")
os.replace(tmp, OUT_PATH)
print(f"[저장] {os.path.abspath(OUT_PATH)} (state {STATE_DIM} + action {ACTION_DIM})")
if __name__ == "__main__":
main()
+79
View File
@@ -0,0 +1,79 @@
"""feature_dqn 체크포인트(.pt) → 서빙 번들(dqn_serving.npz) export.
서빙 컨테이너에 PyTorch 를 넣지 않기 위해 ScoreNet(3층 MLP) 가중치와 카드 특징
(임베딩384 + 전략 one-hot4 + 톤 one-hot4 = 392)을 numpy 번들 하나로 묶는다.
추론은 negotiation.policy.dqn_store 의 numpy forward 가 수행한다.
실행(호스트, torch 필요): APP_ENV=local python -m tools.export_dqn_serving
산출: agent/artifacts/dqn_serving.npz (.dockerignore 미제외 → 이미지에 포함)
"""
import os
import numpy as np
import torch
from tools.train_feature_dqn import load_cards
_HERE = os.path.dirname(os.path.abspath(__file__))
CKPT_PATH = os.path.join(_HERE, "..", "artifacts", "feature_dqn_ktcommerce.pt")
OUT_PATH = os.path.join(_HERE, "..", "artifacts", "dqn_serving.npz")
STATE_DIM = 14 # build_state_features(9) + build_tenant_features(5)
CARD_DIM = 392
def _np_forward(x, W0, b0, W1, b1, W2, b2):
h = np.maximum(x @ W0.T + b0, 0.0)
h = np.maximum(h @ W1.T + b1, 0.0)
return h @ W2.T + b2
def export_bundle(sd, out_path: str) -> str:
"""state_dict → 서빙 번들 npz (원자적 교체: .tmp 작성 후 replace). 반환: 절대경로.
retrain_from_logs 재학습 배포도 이 함수를 쓴다 — 검증(torch/numpy 일치)은 main() 전용.
"""
W0, b0 = sd["net.0.weight"].numpy(), sd["net.0.bias"].numpy()
W1, b1 = sd["net.2.weight"].numpy(), sd["net.2.bias"].numpy()
W2, b2 = sd["net.4.weight"].numpy(), sd["net.4.bias"].numpy()
assert W0.shape[1] == STATE_DIM + CARD_DIM, f"입력 차원 불일치: {W0.shape[1]}"
numbers, feat, _ = load_cards()
card_feats = np.stack([feat[n] for n in numbers]).astype(np.float32)
tmp = out_path + ".tmp"
with open(tmp, "wb") as f:
np.savez(
f,
W0=W0, b0=b0, W1=W1, b1=b1, W2=W2, b2=b2,
card_numbers=np.array(numbers), card_feats=card_feats,
state_dim=STATE_DIM, card_dim=CARD_DIM,
)
if os.path.exists(out_path):
os.replace(out_path, out_path + ".prev") # 직전 번들 백업(롤백용)
os.replace(tmp, out_path)
return os.path.abspath(out_path)
def main():
sd = torch.load(CKPT_PATH, map_location="cpu")
# 정합성 검증: torch forward == numpy forward
from negotiation.policies.feature_dqn_policy import ScoreNet
net = ScoreNet(STATE_DIM, CARD_DIM)
net.load_state_dict(sd)
net.eval()
x = np.random.default_rng(0).normal(size=(8, STATE_DIM + CARD_DIM)).astype(np.float32)
with torch.no_grad():
ref = net(torch.tensor(x)).numpy()
W0, b0 = sd["net.0.weight"].numpy(), sd["net.0.bias"].numpy()
W1, b1 = sd["net.2.weight"].numpy(), sd["net.2.bias"].numpy()
W2, b2 = sd["net.4.weight"].numpy(), sd["net.4.bias"].numpy()
out = _np_forward(x, W0, b0, W1, b1, W2, b2).squeeze(-1)
diff = float(np.abs(ref - out).max())
assert diff < 1e-4, f"numpy/torch forward 불일치: {diff}"
path = export_bundle(sd, OUT_PATH)
print(f"[저장] {path} forward 오차 {diff:.2e}")
if __name__ == "__main__":
main()
+61
View File
@@ -0,0 +1,61 @@
"""probe_serving_dqn — 서빙 번들(dqn_serving.npz)의 상황별 카드 선택 프로브.
배포된 모델이 '상황에 맞게' 고르는지 눈으로 확인하는 진단 도구:
협력사 세그먼트 × 고객사 성향 × 협상 국면(가격대)별 선택 카드를 표로 출력한다.
전부 다르길 기대하는 게 아니라, 축을 바꿨을 때 선택이 '움직이는지'를 본다.
실행: APP_ENV=local python -m tools.probe_serving_dqn (numpy 만 필요, DB 불필요)
"""
import numpy as np
from negotiation.qtable.domain.model.snapshot import NegotiationSnapshot
from negotiation.qtable.domain.service.feature_builder import build_state_features, build_tenant_features
from tenancy.config_loader import TenantConfigLoader
from tools.export_dqn_serving import OUT_PATH
from tools.retrain_from_logs import np_scorer_from_bundle
from tools.train_feature_dqn import pref_config
ANCHOR, TARGET = 495_000.0, 500_000.0 # BUGCHECK 견적과 동일 스케일
SUPPLIERS = {
"소형·경쟁多": dict(revenue_amount=5_000_000, partner_count=3, distribution_code="A"),
"소형·단독": dict(revenue_amount=5_000_000, partner_count=1, distribution_code="A"),
"대형·경쟁多": dict(revenue_amount=200_000_000, partner_count=3, distribution_code="A"),
"대형·단독": dict(revenue_amount=200_000_000, partner_count=1, distribution_code="A"),
}
PHASES = { # (라운드, 제시가): 첫턴 높은 가격 / 중반 목표가 근접 / 막판 앵커존 직전
"첫턴(575k)": (1, 575_000.0),
"중반(510k)": (2, 510_000.0),
"막판(501k)": (3, 501_000.0),
}
PREFS = {"성사중시": 0.1, "가격중시": 0.9}
def main():
score = np_scorer_from_bundle(OUT_PATH)
z = np.load(OUT_PATH, allow_pickle=False)
numbers = [str(n) for n in z["card_numbers"]]
feats = z["card_feats"]
base = TenantConfigLoader().load("ktcommerce").reward
for phase, (turn, price) in PHASES.items():
print(f"\n=== {phase} (앵커 {int(ANCHOR):,} / 목표 {int(TARGET):,}) ===")
print(f"{'협력사':<12}" + "".join(f"{p:>16}" for p in PREFS))
for sup_name, sup in SUPPLIERS.items():
row = []
for _, p in PREFS.items():
tf = build_tenant_features(pref_config(base, p))
snap = NegotiationSnapshot(
revenue_amount=sup["revenue_amount"], distribution_code=sup["distribution_code"],
partner_count=sup["partner_count"],
acceptance_ratio=max(0.0, (575_000.0 - price) / 575_000.0),
input_price=price, anchor_price=ANCHOR, target_price=TARGET, round_number=turn,
)
sf = np.concatenate([build_state_features(snap), tf])
row.append(numbers[int(np.argmax(score(sf, feats)))])
print(f"{sup_name:<12}" + "".join(f"{c:>16}" for c in row))
if __name__ == "__main__":
main()
+65
View File
@@ -0,0 +1,65 @@
"""로컬 학습 리셋 — learning 스키마를 비운다 (카드 카탈로그·협상 데이터는 보존).
카탈로그(카드) 구성을 바꾼 뒤 Q-table 을 처음부터 다시 학습시키고 싶을 때 사용한다.
learning.* (버전/Q값/방문수/경험로그/세션/카드매핑) 만 삭제 → 다음 협상부터 fresh 재학습.
card.*·negotiation.*·quotation.* 등 실제 데이터는 건드리지 않는다.
사용 (agent 디렉토리에서):
APP_ENV=local python -m tools.reset_learning # 전체 회사 학습 리셋
APP_ENV=local python -m tools.reset_learning --company <id> # 특정 회사만
APP_ENV=local python -m tools.reset_learning --yes # 확인 프롬프트 생략
"""
import argparse
import asyncio
import asyncpg
from config.server_configs import main_db_config
# 삭제 대상(learning 스키마). 전부 company_id 스코프라 --company 로 회사별 리셋 가능.
_LEARNING_TABLES = [
"q_values", "visit_counts", "experience_logs", "chat_sessions",
"tenant_action_cards", "q_table_versions",
]
async def _reset(company_id: str | None) -> None:
cfg = main_db_config
conn = await asyncpg.connect(
host=cfg.write_host, port=cfg.write_port,
user=cfg.write_id, password=cfg.write_pw, database=cfg.name,
)
try:
total = 0
for t in _LEARNING_TABLES:
if company_id:
res = await conn.execute(f"DELETE FROM learning.{t} WHERE company_id = $1", company_id)
else:
res = await conn.execute(f"DELETE FROM learning.{t}")
n = int(res.split()[-1]) if res else 0
total += n
print(f" learning.{t}: {n} 행 삭제")
scope = f"회사 {company_id}" if company_id else "전체 회사"
print(f"== 학습 리셋 완료: 총 {total} 행 삭제 (scope={scope}) ==")
finally:
await conn.close()
def main() -> None:
p = argparse.ArgumentParser(description="learning 스키마 리셋 (카드/협상 데이터는 보존)")
p.add_argument("--company", help="특정 company_id 만 리셋. 생략 시 전체")
p.add_argument("--yes", action="store_true", help="확인 프롬프트 생략")
args = p.parse_args()
scope = f"회사 {args.company}" if args.company else "전체 회사"
if not args.yes:
ans = input(f"[{main_db_config.name}] learning 스키마({scope})를 비웁니다. 계속? [y/N] ")
if ans.strip().lower() != "y":
print("취소됨.")
return
asyncio.run(_reset(args.company))
if __name__ == "__main__":
main()
+238
View File
@@ -0,0 +1,238 @@
"""retrain_from_logs — experience_logs 실데이터로 feature_dqn 오프라인 재학습 + OPE 게이트.
파이프라인:
① learning.experience_logs 로드(전 테넌트 — 범용 에이전트는 테넌트를 특징으로 조건화하므로 통합 학습)
② 세션별 에피소드 재구성: 카드턴(done=False) N개 + 종료행(done=True) 1개.
보상은 학습 규약(최종 결과 시점만 채점)에 맞춰 종료행 reward 만 쓰고 중간턴은 0.
③ 현재 체크포인트에서 fine-tune (낮은 lr — 시뮬 사전학습 망각 방지)
④ OPE(SNIPS, 궤적 IS): 후보 모델 vs 현재 서빙 번들. 후보가 못 넘으면 배포하지 않는다.
⑤ 통과 시 dqn_serving.npz 원자적 교체(직전본 .prev 백업) → `docker compose build agent && up -d agent` 로 배포.
실행(호스트, torch+DB 필요):
APP_ENV=local python -m tools.retrain_from_logs
환경변수:
MIN_EPISODES(기본 200) 재학습 최소 에피소드 수 — 미달 시 skip (과적합 방지)
EPOCHS(기본 20) / LR(기본 1e-4) / FORCE_DEPLOY=1 (OPE 게이트 무시 — 테스트 전용)
주의: 서빙이 greedy(탐색 없음)라 로그가 선택 편향됨 — OPE 의 유효표본(ESS)이 작으면
게이트가 보수적으로 배포를 막는다. 이는 의도된 동작이다(조용한 성능저하 방지).
"""
import asyncio
import json
import os
from collections import defaultdict
import numpy as np
import torch
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import ExperienceLog
from common.enums import DBType, DBWRType
from negotiation.policies.feature_dqn_policy import FeatureDQNPolicy
from negotiation.qtable.domain.model.snapshot import NegotiationSnapshot
from negotiation.qtable.domain.service.feature_builder import (
STATE_FEATURE_DIM, TENANT_FEATURE_DIM, build_state_features, build_tenant_features)
from sqlalchemy import select
from tenancy.config_loader import TenantConfigLoader
from tools.export_dqn_serving import CKPT_PATH, OUT_PATH, export_bundle
from tools.train_feature_dqn import load_cards
_HERE = os.path.dirname(os.path.abspath(__file__))
RETRAIN_CKPT = os.path.join(_HERE, "..", "artifacts", "feature_dqn_retrained.pt")
REPORT_PATH = os.path.join(_HERE, "..", "artifacts", "retrain_report.json")
MIN_EPISODES = int(os.getenv("MIN_EPISODES", "200"))
EPOCHS = int(os.getenv("EPOCHS", "20"))
LR = float(os.getenv("LR", "1e-4"))
FORCE_DEPLOY = os.getenv("FORCE_DEPLOY") == "1"
PROPENSITY_FALLBACK = 0.9 # 구로그 propensity 누락 시 (UCB/DQN 모두 greedy≈(1-ε)+ε/n)
# ---- ① 로그 로드 -------------------------------------------------------------
async def fetch_logs():
def _q(s):
q = (select(ExperienceLog.company_id, ExperienceLog.session_id, ExperienceLog.card_id,
ExperienceLog.reward, ExperienceLog.done, ExperienceLog.snapshot,
ExperienceLog.propensity, ExperienceLog.turn, ExperienceLog.id)
.where(ExperienceLog.is_invalidated == False) # noqa: E712
.order_by(ExperienceLog.company_id, ExperienceLog.session_id, ExperienceLog.id))
return DB_SESSION_MNG.execute(s, q)
err, rows = await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
return rows
# ---- ② 에피소드 재구성 --------------------------------------------------------
def build_episodes(rows, known_cards: set):
"""→ [{tenant, steps:[(snapshot, card, propensity)], terminal_reward}], 스킵 사유 카운트."""
by_session = defaultdict(list)
for r in rows:
if r[1] is not None:
by_session[(r[0], str(r[1]))].append(r)
episodes, skipped = [], defaultdict(int)
for (company_id, _sid), items in by_session.items():
selects = [r for r in items if not r[4] and r[5]] # done=False, snapshot 有
terminals = [r for r in items if r[4] and r[3] is not None] # done=True, reward 有
if not selects or not terminals:
skipped["종료행/카드턴 없음(미완결 세션)"] += 1
continue
if any(str(r[2] or "").startswith("AUT|") for r in selects):
skipped["완전 자율 세션(카드 재학습 대상 아님)"] += 1
continue
if any(r[2] not in known_cards for r in selects):
skipped["임베딩 없는 카드(파일매핑 테넌트 등)"] += 1
continue
episodes.append(dict(
tenant=company_id,
steps=[(r[5], r[2], r[6] if r[6] else PROPENSITY_FALLBACK) for r in selects],
terminal_reward=float(terminals[-1][3]),
))
return episodes, skipped
def tenant_feat_for(cache: dict, loader: TenantConfigLoader, company_id: str) -> np.ndarray:
"""테넌트 보상설정 → 성향 특징. 미온보딩/로드 실패는 _base 폴백."""
if company_id not in cache:
try:
cfg = loader.load(company_id)
except Exception:
cfg = loader.load("_base")
cache[company_id] = build_tenant_features(cfg.reward)
return cache[company_id]
def to_transitions(episodes, feat, tenant_feats):
"""학습 규약(train_feature_dqn 과 동일): 중간턴 r=0, 종료턴만 terminal_reward. 다음 후보 = 전체 − 사용분."""
all_cards = list(feat.keys())
out = []
for ep in episodes:
tf = tenant_feats[ep["tenant"]]
used = set()
n = len(ep["steps"])
for i, (snap_d, card, _p) in enumerate(ep["steps"]):
sf = np.concatenate([build_state_features(NegotiationSnapshot.from_dict(snap_d)), tf])
used.add(card)
if i == n - 1:
out.append((sf, feat[card], ep["terminal_reward"], None, None, True))
else:
s2_d = ep["steps"][i + 1][0]
s2 = np.concatenate([build_state_features(NegotiationSnapshot.from_dict(s2_d)), tf])
cands = [c for c in all_cards if c not in used] or all_cards
out.append((sf, feat[card], 0.0, s2, np.stack([feat[c] for c in cands]), False))
return out
# ---- ④ OPE (SNIPS, 궤적 단위 IS) ----------------------------------------------
def _greedy_match(score_fn, ep, feat, tf) -> float:
"""궤적 IS 가중치: Π 1[greedy(sᵢ)=aᵢ]/pᵢ. 한 턴이라도 불일치면 0."""
all_cards = list(feat.keys())
w, used = 1.0, set()
for snap_d, card, p in ep["steps"]:
sf = np.concatenate([build_state_features(NegotiationSnapshot.from_dict(snap_d)), tf])
cands = [c for c in all_cards if c not in used] or all_cards
sc = score_fn(sf, np.stack([feat[c] for c in cands]))
if cands[int(np.argmax(sc))] != card:
return 0.0
w /= max(p, 1e-3)
used.add(card)
return w
def snips(score_fn, episodes, feat, tenant_feats):
"""SNIPS 추정치 + 유효표본크기(ESS). 매치 0건이면 (None, 0)."""
ws, rs = [], []
for ep in episodes:
w = _greedy_match(score_fn, ep, feat, tenant_feats[ep["tenant"]])
ws.append(w)
rs.append(ep["terminal_reward"])
ws, rs = np.array(ws), np.array(rs)
if ws.sum() <= 0:
return None, 0.0
est = float((ws * rs).sum() / ws.sum())
ess = float(ws.sum() ** 2 / (ws ** 2).sum())
return est, ess
def np_scorer_from_bundle(path):
"""현재 서빙 번들(npz) → score_fn (dqn_store 와 동일 forward)."""
z = np.load(path, allow_pickle=False)
W0, b0, W1, b1, W2, b2 = z["W0"], z["b0"], z["W1"], z["b1"], z["W2"], z["b2"]
def score(sf, card_feats):
x = np.concatenate([np.repeat(sf[None, :], card_feats.shape[0], axis=0), card_feats], axis=1)
h = np.maximum(x @ W0.T + b0, 0.0)
h = np.maximum(h @ W1.T + b1, 0.0)
return (h @ W2.T + b2).squeeze(-1)
return score
# ---- 메인 ---------------------------------------------------------------------
async def run():
numbers, feat, _ = load_cards()
rows = await fetch_logs()
episodes, skipped = build_episodes(rows, set(numbers))
print(f"로그 {len(rows)}행 → 에피소드 {len(episodes)}개 (스킵: {dict(skipped) or '없음'})")
report = dict(rows=len(rows), episodes=len(episodes), skipped=dict(skipped),
min_episodes=MIN_EPISODES, deployed=False)
if len(episodes) < MIN_EPISODES and not FORCE_DEPLOY:
print(f"[skip] 에피소드 {len(episodes)} < MIN_EPISODES {MIN_EPISODES} — 과적합 위험으로 재학습 안 함")
report["result"] = "skipped_insufficient_data"
return report
loader = TenantConfigLoader()
tenant_feats = {}
for ep in episodes:
tenant_feat_for(tenant_feats, loader, ep["tenant"])
# ③ fine-tune (시뮬 사전학습 체크포인트에서 이어서, 낮은 lr)
transitions = to_transitions(episodes, feat, tenant_feats)
batch = min(64, max(8, len(transitions) // 4))
policy = FeatureDQNPolicy(state_dim=STATE_FEATURE_DIM + TENANT_FEATURE_DIM,
card_dim=feat[numbers[0]].shape[0], lr=LR, batch_size=batch)
if os.path.exists(CKPT_PATH):
policy.load(CKPT_PATH)
print(f"[fine-tune] 시작점: {os.path.basename(CKPT_PATH)} lr={LR} batch={batch}")
policy.buf.extend(transitions)
steps = EPOCHS * max(1, len(transitions) // batch)
losses = [l for _ in range(steps) if (l := policy.train_step()) is not None]
print(f"[fine-tune] {steps} step loss {losses[0]:.4f} → {losses[-1]:.4f}" if losses else "[fine-tune] 스텝 없음")
# ④ OPE 게이트: 후보 vs 현재 서빙
def cand_score(sf, cf):
return policy.scores(sf, cf)
cand_est, cand_ess = snips(cand_score, episodes, feat, tenant_feats)
cur_est, cur_ess = (snips(np_scorer_from_bundle(OUT_PATH), episodes, feat, tenant_feats)
if os.path.exists(OUT_PATH) else (None, 0.0))
print(f"[OPE/SNIPS] 후보 {cand_est} (ESS {cand_ess:.1f}) vs 현재 {cur_est} (ESS {cur_ess:.1f})")
report.update(ope_candidate=cand_est, ope_candidate_ess=cand_ess,
ope_current=cur_est, ope_current_ess=cur_ess)
min_ess = max(3.0, 0.02 * len(episodes))
passed = (cand_est is not None and cand_ess >= min_ess
and (cur_est is None or cand_est >= cur_est - 0.01))
if not passed and not FORCE_DEPLOY:
print(f"[게이트 불통과] 배포하지 않음 (필요 ESS ≥ {min_ess:.1f}). 현재 번들 유지.")
report["result"] = "gate_failed"
return report
# ⑤ 배포: 후보 저장 + 번들 교체 (.prev 백업)
policy.save(RETRAIN_CKPT)
path = export_bundle(policy.q.state_dict(), OUT_PATH)
print(f"[배포] {path} (직전본 → dqn_serving.npz.prev)")
print(" 적용: docker compose build agent && docker compose up -d agent")
report.update(result="deployed" if passed else "force_deployed", deployed=True,
ckpt=os.path.abspath(RETRAIN_CKPT))
return report
def main():
report = asyncio.run(run())
with open(REPORT_PATH, "w", encoding="utf-8") as f:
json.dump(report, f, ensure_ascii=False, indent=2)
print(f"[리포트] {os.path.abspath(REPORT_PATH)}")
if __name__ == "__main__":
main()
+317
View File
@@ -0,0 +1,317 @@
"""결함 회귀 게이트 — 실전에서 발견된 협상 결함을 시나리오로 재생해 서빙 번들을 검증한다.
프로브(probe_serving_dqn)가 '눈으로 보는 행동 표'라면 이것은 '자동 합격/불합격'이다.
모든 검사 항목은 과거 실제 발생했던 결함이며, 하나라도 실패하면 exit 1 — 배포 금지.
재학습 번들은 반드시 이 게이트를 통과한 뒤에만 autonomy_serving.npz 로 교체한다.
검사 대상은 서빙 실물이다: AutonomyPolicy.decide(봉투 마스크 포함) + ChatEngine._autonomy_next
(최종제안 전환) + ment_generator 가드(목표가 누설·할루시네이션). 시뮬 협력사는 스크립트라
결정론적이고, 정책도 greedy 라 실행마다 같은 결과가 나온다. DB/LLM/도커 불필요.
지형은 복수로 검사한다 — v3.4 가 실스케일(423,198)에선 통과하고 드라이브 지형(10,000)에서
'첫 턴 목표가 통보'로 퇴화했던 사고: 한 지형 통과는 다른 지형을 보증하지 않는다.
실행: agent 디렉터리에서 APP_ENV=local python -m tools.test_autonomy_defects [번들경로]
"""
import os
import sys
from types import SimpleNamespace
import numpy as np
from negotiation.chat.service import ment_generator
from negotiation.chat.service.chat_engine import ChatEngine
from negotiation.policy import autonomy_store
from negotiation.policy.autonomy_store import AutonomyPolicy
from tenancy.config_loader import TenantConfigLoader
# 검사 지형: 실제 견적(앵커율 ~1%) + 로컬 드라이브 견적(소액) — 스케일이 달라도 예절은 같아야 한다.
GEOS = {
"실스케일": dict(anchor=418_966, target=423_198, first=540_000, il=459_000),
"소액": dict(anchor=9_900, target=10_000, first=11_500, il=0),
}
MIN_PRESS = int(os.getenv("AUTONOMY_MIN_PRESS", "2"))
_RESULTS = []
def check(name: str, ok: bool, detail: str = ""):
_RESULTS.append((name, ok, detail))
print(f" {'✔' if ok else '✘ FAIL'} {name}" + (f" — {detail}" if detail and not ok else ""))
# ---- 하니스: 서빙 실물 구동 (chat_service 의 ctx 관리 순서를 그대로 재현) ----------------
def base_ctx(geo) -> dict:
return dict(revenue_amount=50_000_000, distribution_code="A", partner_count=3,
item_price=geo["first"], input_price=geo["first"], round=1,
anchor_price=geo["anchor"], target_price=geo["target"],
internet_lowest_price=geo["il"])
def run_scenario(policy, supplier, geo, max_steps=30):
"""정책 결정 → 스텝 전환 → 컨텍스트 부기(chat_service 순서) → 스크립트 협력사 반응 루프.
trace 원소: (step, kind, q, 당시 제시가, autonomy_offer, 결정 시점 press_n)
"""
eng = ChatEngine.__new__(ChatEngine) # _autonomy_next 는 decider 와 ctx 만 쓴다
ctx = base_ctx(geo)
def decide(c):
act = policy.decide(c)
c["autonomy_pending"] = {"kind": act.kind, "q": act.counter_q, "s": act.strategy}
return act
eng.autonomy_decider = decide
sess = SimpleNamespace(context=ctx)
trace, end = [], None
for _ in range(max_steps):
press_n_at = int(ctx.get("autonomy_press_n") or 0)
step = eng._autonomy_next(sess)
pending = ctx.pop("autonomy_pending", None)
if pending: # chat_service 부기: pending → last(+prev), 역제안 별도 보존, press 카운터
if ctx.get("autonomy_last"):
ctx["autonomy_prev"] = ctx["autonomy_last"]
ctx["autonomy_last"] = dict(pending)
if pending["kind"] == "counter":
ctx["autonomy_last_counter"] = dict(pending)
if pending["kind"] == "press":
ctx["autonomy_press_n"] = press_n_at + 1
trace.append((step, (pending or {}).get("kind"), (pending or {}).get("q"),
ctx["input_price"], ctx.get("autonomy_offer"), press_n_at))
if step in ("협상완료", "협상실패"):
end = step
break
if step == "자율_최종제안": # 예→그 금액 타결 / 아니오→협상실패 (엔진 스텝 정의)
end = "협상완료" if supplier.final_yes(ctx) else "협상실패"
break
if step == "자율_역제안" and supplier.counter_yes(ctx):
ctx["input_price"] = ctx["autonomy_offer"]
end = "협상완료"
break
ctx["input_price"] = int(supplier.next_price(ctx))
ctx["round"] = ctx.get("round", 1) + 1
return trace, end, ctx
def fmt(trace):
out = []
for step, kind, q, price, offer, _ in trace:
s = f"{price:,}→{step}"
if kind == "counter":
s += f"({offer:,})"
out.append(s)
return " ".join(out)
# ---- 스크립트 협력사 (결정론, 지형 비율로 정의) -----------------------------------------
class Stubborn:
"""조금씩 내리지만 하한이 목표가 위(×1.028) — 성사 불가능. 역제안·최종 전부 거절.
기대 궤적: 설득 ≥2회 → 앵커 이하 개시 → 단조 상향 사다리 → 최종제안(목표가) → 결렬."""
def __init__(self, geo):
self.floor = int(geo["target"] * 1.028)
def next_price(self, ctx):
return max(self.floor, int(ctx["input_price"] * 0.96))
def counter_yes(self, ctx):
return False
def final_yes(self, ctx):
return False
class HoverNearTarget:
"""목표가 +0.19% 고정 — 마무리 국면. 압박이 나오면 안 되는 구간."""
def __init__(self, geo):
self.price = int(geo["target"] * 1.0019)
def next_price(self, ctx):
return self.price
def counter_yes(self, ctx):
return False
def final_yes(self, ctx):
return False
class Dealable:
"""4% 씩 내려와 목표가 바로 아래까지 협조 — 성사 가능 케이스."""
def __init__(self, geo):
self.floor = int(geo["target"] * 0.9995)
self.accept_from = geo["anchor"] + 0.4 * (geo["target"] - geo["anchor"])
def next_price(self, ctx):
return max(self.floor, int(ctx["input_price"] * 0.96))
def counter_yes(self, ctx):
return ctx["autonomy_offer"] >= self.accept_from # 목표가 부근 제안은 수락
def final_yes(self, ctx):
return True
# ---- 시나리오 검사 (각 항목 = 과거 실제 결함) -------------------------------------------
def assert_defects(tag, trace, end, geo):
anchor, target = geo["anchor"], geo["target"]
near = target * 1.005
# '역제안' 검사는 일반 역제안 스텝만 센다 — 같은 금액 재시도가 자율_최종제안으로 전환된 것은
# 반복이 아니라 설계된 최종 통보(제품 결정: 같은 금액 재호출 = 탄약 소진 → 마지막으로 묻고 종료).
counters = [(i, t) for i, t in enumerate(trace) if t[0] == "자율_역제안"]
presses = [t for t in trace if t[1] == "press"]
if trace and trace[0][3] > near:
check(f"[{tag}] 개시 턴은 설득 (결함: v3.4 첫턴 walk→목표가 통보)",
trace[0][1] == "press", f"첫 결정이 {trace[0][1]}")
if counters:
i0, first = counters[0]
check(f"[{tag}] 첫 역제안은 앵커 이하 (결함: 사다리 꼭대기 개시)",
first[4] <= anchor, f"첫 역제안 {first[4]:,} > 앵커 {anchor:,}")
pressed_before = sum(1 for t in trace[:i0] if t[1] == "press")
if first[3] > near: # 마무리 국면은 해금 예외
check(f"[{tag}] 역제시 해금 전 설득 ≥{MIN_PRESS}회 (결함: 첫턴 역제시)",
pressed_before >= MIN_PRESS, f"설득 {pressed_before}회 만에 역제안")
offers = [t[4] for _, t in counters]
check(f"[{tag}] 역제안 단조 상향 (결함: 제안 철회 423,198→420,024)",
all(b >= a for a, b in zip(offers, offers[1:])), f"철회 발생: {offers}")
check(f"[{tag}] 역제안 ≤ 목표가", all(o <= target for o in offers), f"{offers}")
check(f"[{tag}] 같은 금액 역제안 반복 없음 (결함: 421,082 반복)",
all(b != a for a, b in zip(offers, offers[1:])), f"{offers}")
check(f"[{tag}] 마무리 국면(≤목표가×1.005) 압박 없음 (결함: 802원 푼돈 흥정)",
all(t[3] > near for t in presses), "목표가 코앞에서 압박")
check(f"[{tag}] 목표가 초과 제시가 수락 없음 (결함: 목표가+14% 매입)",
not any(t[1] == "accept" and t[3] > target for t in trace), "")
finals = [t for t in trace if t[0] == "자율_최종제안"]
for f in finals:
check(f"[{tag}] 최종제안 금액 = 목표가 (결함: 직전 금액 재사용 60,548)",
f[4] == target, f"최종제안 {f[4]:,} ≠ 목표가 {target:,}")
# 결렬 의사(walk)로 끝났다면 반드시 최종제안을 거쳤어야 한다 (턴캡 종료는 예외)
walked_direct = any(t[1] == "walk" and t[0] == "협상실패" for t in trace)
capped = trace and trace[-1][0] == "협상실패" and trace[-1][1] is None
check(f"[{tag}] 결렬 전 최종제안 1회 보장 (결함: 최종 의사 확인 없이 종료)",
not walked_direct or capped or bool(finals), "walk 즉시 결렬")
check(f"[{tag}] 종료 보장 (무한 세션 없음)", end is not None, "max_steps 내 미종료")
# ---- 엔진 단위 검사 (정책 무관 — 전환 로직 자체) ----------------------------------------
def engine_unit_tests():
print("\n[엔진 전환 로직 단위 검사]")
geo = GEOS["실스케일"]
target = geo["target"]
def force(kind, q=0.0, s=3):
eng = ChatEngine.__new__(ChatEngine)
eng.autonomy_decider = lambda c: SimpleNamespace(kind=kind, counter_q=q, strategy=s)
return eng
# walk → 최종제안(목표가) → 재차 walk → 협상실패
ctx = base_ctx(geo)
eng = force("walk")
sess = SimpleNamespace(context=ctx)
step1 = eng._autonomy_next(sess)
check("walk 1회차 → 자율_최종제안 전환", step1 == "자율_최종제안", f"got {step1}")
check("walk 전환 최종제안 금액 = 목표가", ctx.get("autonomy_offer") == target,
f"{ctx.get('autonomy_offer')}")
step2 = eng._autonomy_next(sess)
check("walk 2회차(최종 거절 후) → 협상실패", step2 == "협상실패", f"got {step2}")
# 같은 q 역제안 반복 → 최종제안(목표가) 전환
ctx = base_ctx(geo)
ctx["autonomy_last"] = ctx["autonomy_last_counter"] = {"kind": "counter", "q": 0.5, "s": 3}
sess = SimpleNamespace(context=ctx)
step = force("counter", q=0.5)._autonomy_next(sess)
check("같은 금액 재역제안 → 자율_최종제안 전환", step == "자율_최종제안", f"got {step}")
check("탄약소진 최종제안 금액 = 목표가", ctx.get("autonomy_offer") == target,
f"{ctx.get('autonomy_offer')}")
# 턴 상한 — 캡 종료도 최종제안 보장을 우회하지 않는다
ctx = base_ctx(geo)
ctx["round"] = 13
sess = SimpleNamespace(context=ctx)
step = force("press")._autonomy_next(sess)
check("턴 상한 초과(최종 미실시) → 자율_최종제안", step == "자율_최종제안", f"got {step}")
check("턴캡 최종제안 금액 = 목표가", ctx.get("autonomy_offer") == target,
f"{ctx.get('autonomy_offer')}")
step = force("press")._autonomy_next(sess)
check("턴 상한 초과(최종 거절 후) → 협상실패", step == "협상실패", f"got {step}")
# ---- 봉투 마스크 단위 검사 (모델 무관 — 후보 필터 자체) ----------------------------------
def envelope_unit_tests(policy):
print("\n[봉투 마스크 단위 검사]")
geo = GEOS["소액"]
ctx = base_ctx(geo) # 설득 0회, 제시가 목표가 위 → 설득만 가능해야 한다
act = policy.decide(ctx)
check("설득 0회 상태의 결정은 press 만 가능 (walk·counter·accept 잠금)",
act.kind == "press", f"got {act.kind}")
# ---- 멘트 가드 검사 (목표가 누설·할루시네이션 — LLM 호출 없음) ---------------------------
def ment_guard_tests():
print("\n[멘트 가드 검사]")
geo = GEOS["실스케일"]
target, anchor, il = geo["target"], geo["anchor"], geo["il"]
ctx = base_ctx(geo)
prompt = ment_generator._prompt_for("자율_압박_3", ctx)
check("압박 프롬프트에 목표가 숫자 없음 (결함: 목표가 노출 멘트)",
str(target) not in prompt.replace(",", ""), "프롬프트가 목표가를 담고 있음")
leak = f"저희 내부 산정 기준은 {target:,}원입니다. 이 가격에 맞춰 재검토 부탁드립니다."
check("목표가 포함 압박 멘트 → 폐기", not ment_generator._guard("자율_압박_3", ctx, leak), "")
invented = "시장 상황을 고려해 400,000원 수준으로 재검토 부탁드립니다."
check("지어낸 금액 멘트 → 폐기 (할루시네이션)",
not ment_generator._guard("자율_압박_3", ctx, invented), "")
ctx2 = dict(ctx, autonomy_offer=anchor)
ok_ment = f"내부 검토 결과 {anchor:,}원이면 즉시 진행이 가능합니다. 수락해 주시겠습니까?"
check("정상 역제안 멘트(제안가 포함) → 통과",
ment_generator._guard("자율_역제안", ctx2, ok_ment), "")
no_offer = "말씀하신 조건을 검토했고 조정이 필요합니다. 수락해 주시겠습니까?"
check("제안가 없는 역제안 멘트 → 폐기",
not ment_generator._guard("자율_역제안", ctx2, no_offer), "")
ev = f"동일 품목 인터넷 최저가가 {il:,}원으로 확인됩니다. 재검토 부탁드립니다."
check("최저가 인용: 근거 있음(수집됨+제시가>최저가) → 허용",
ment_generator._guard("자율_압박_1", ctx, ev), "")
ctx3 = dict(ctx, internet_lowest_price=0)
ev0 = "동일 품목 인터넷 최저가 대비 높은 수준입니다. 재검토 부탁드립니다."
check("최저가 인용: 미수집 품목 → 폐기 (지어낸 시장 주장)",
not ment_generator._guard("자율_압박_1", ctx3, ev0), "")
def main():
bundle = sys.argv[1] if len(sys.argv) > 1 else autonomy_store.BUNDLE_PATH
z = np.load(bundle, allow_pickle=False)
policy = AutonomyPolicy(z, TenantConfigLoader().load("ktcommerce").reward)
print(f"번들: {os.path.abspath(bundle)} (state_dim={int(z['state_dim'])})")
for geo_name, geo in GEOS.items():
print(f"\n{'─' * 60}\n지형 [{geo_name}] 앵커 {geo['anchor']:,} / 목표 {geo['target']:,} "
f"/ 첫 제시가 {geo['first']:,}")
for tag, sup_cls in (("완고", Stubborn), ("목표가위 고정", HoverNearTarget),
("협조", Dealable)):
trace, end, _ = run_scenario(policy, sup_cls(geo), geo)
full_tag = f"{geo_name}·{tag}"
print(f"\n[{full_tag}] {fmt(trace)} ⇒ {end}")
assert_defects(full_tag, trace, end, geo)
engine_unit_tests()
envelope_unit_tests(policy)
ment_guard_tests()
fails = [(n, d) for n, ok, d in _RESULTS if not ok]
print(f"\n{'=' * 60}\n결과: {len(_RESULTS) - len(fails)}/{len(_RESULTS)} 통과")
if fails:
print("실패 항목 — 이 번들은 배포 금지:")
for n, d in fails:
print(f" ✘ {n} {d}")
sys.exit(1)
print("전 항목 통과 — 배포 가능.")
if __name__ == "__main__":
main()
+148
View File
@@ -0,0 +1,148 @@
"""action-as-feature DQN 학습 (Phase 2·3) — 공용 환경 헬퍼 + 단독 학습 엔트리.
카드 특징 = 스크립트 임베딩(384) + 전략 one-hot(4) + 톤 one-hot(4) = 392차원
상태 특징 = 연속 상태(9) + 고객사 성향(5) = 14차원 ← 협력사·고객사 조건화
학습 환경 = FeatureBuyer(양보력/수락력 2축) + 에피소드마다 협력사·고객사성향 랜덤 샘플링
비교 평가는 tools.compare_qtable_vs_dqn 에서 수행한다.
실행: APP_ENV=local python -m tools.train_feature_dqn
"""
import os
import random
import numpy as np
import torch
from eval_harness.buyer import Scenario
from eval_harness.feature_buyer import FeatureBuyer, sample_supplier
from negotiation.policies.feature_dqn_policy import FeatureDQNPolicy
from negotiation.qtable.domain.model.snapshot import NegotiationOutcome, NegotiationSnapshot
from negotiation.qtable.domain.service.feature_builder import (
STATE_FEATURE_DIM, TENANT_FEATURE_DIM, build_state_features, build_tenant_features)
from negotiation.qtable.domain.service.reward_calculator import RewardCalculator
from tenancy.config_loader import TenantConfigLoader
_HERE = os.path.dirname(os.path.abspath(__file__))
EMB_PATH = os.path.join(_HERE, "..", "artifacts", "card_embeddings.npz")
CKPT_PATH = os.path.join(_HERE, "..", "artifacts", "feature_dqn_ktcommerce.pt")
# zero-shot 실험용 홀드아웃 (전략 1·4 — 남은 풀에도 같은 전략 존재).
# 서빙용 최종 학습은 전체 풀 사용: FULL_POOL=1 python -m tools.train_feature_dqn
HOLDOUT = [] if os.getenv("FULL_POOL") == "1" else ["NGC-002", "NGC-010"]
ANCHOR, TARGET = 8000.0, 10000.0
MAX_TURNS = 5
N_STRATEGY, N_TONE = 4, 4
# ---- 카드 특징: 임베딩 + 전략/톤 one-hot ------------------------------------------
def load_cards():
z = np.load(EMB_PATH, allow_pickle=True)
numbers = [str(n) for n in z["numbers"]]
feat, strat = {}, {}
for i, n in enumerate(numbers):
s, t = int(z["strategy"][i]), int(z["tone"][i])
s_oh = np.eye(N_STRATEGY, dtype=np.float32)[s - 1]
t_oh = np.eye(N_TONE, dtype=np.float32)[t - 1]
feat[n] = np.concatenate([z["embeddings"][i].astype(np.float32), s_oh, t_oh])
strat[n] = s
return numbers, feat, strat
# ---- 고객사 성향: 보상 설정 샘플링 ---------------------------------------------------
def sample_tenant_pref(rng: np.random.Generator, base_cfg):
"""p ∈ [0,1]: 0=성사중시(협력 유리) ↔ 1=가격중시(경쟁 유리). 반환: (RewardConfig, tenant_feat)."""
p = float(rng.uniform(0.0, 1.0))
cfg = base_cfg.model_copy(update=dict(
max_weight=0.25 + 0.60 * p, # 가격보상 비중
min_weight=(0.25 + 0.60 * p) * 0.7,
success_reward=1.6 - 1.2 * p, # 성사중시일수록 성공보상↑
failure_penalty=-(1.4 - 1.1 * p), # 성사중시일수록 결렬이 아픔
beta=0.1 + 0.4 * p,
penalty_lambda=float(rng.uniform(0.005, 0.05)),
))
return cfg, build_tenant_features(cfg)
def pref_config(base_cfg, p: float, lam: float = 0.02):
"""평가용: 성향 p 를 고정해 RewardConfig 생성 (극단 테스트)."""
return base_cfg.model_copy(update=dict(
max_weight=0.25 + 0.60 * p, min_weight=(0.25 + 0.60 * p) * 0.7,
success_reward=1.6 - 1.2 * p, failure_penalty=-(1.4 - 1.1 * p),
beta=0.1 + 0.4 * p, penalty_lambda=lam,
))
def make_snapshot(sup, price: float, turn: int, acceptance: float,
outcome=NegotiationOutcome.ONGOING) -> NegotiationSnapshot:
return NegotiationSnapshot(
revenue_amount=sup.revenue_amount, distribution_code=sup.distribution_code,
partner_count=sup.partner_count, acceptance_ratio=acceptance,
input_price=price, anchor_price=ANCHOR, target_price=TARGET,
round_number=turn, outcome=outcome,
)
# ---- 단독 학습 엔트리 (비교는 compare_qtable_vs_dqn) --------------------------------
def main(episodes=10000, seed=42):
random.seed(seed); np.random.seed(seed); torch.manual_seed(seed)
numbers, feat, strat = load_cards()
train_pool = [c for c in numbers if c not in HOLDOUT]
card_dim = feat[numbers[0]].shape[0]
print(f"카드 {len(numbers)}장 (학습 {len(train_pool)} / 홀드아웃 {HOLDOUT}) card_dim={card_dim}")
tcfg = TenantConfigLoader().load("ktcommerce")
policy = FeatureDQNPolicy(state_dim=STATE_FEATURE_DIM + TENANT_FEATURE_DIM,
card_dim=card_dim, eps_decay=4000, gamma=0.95)
rng = np.random.default_rng(seed)
print(f"=== 학습 {episodes} 에피소드 (협력사·성향 랜덤, CPU) ===")
recent = []
for ep in range(1, episodes + 1):
sup = sample_supplier(rng)
rcfg, tf = sample_tenant_pref(rng, tcfg.reward)
rc = RewardCalculator(rcfg, tcfg.state)
buyer = FeatureBuyer(sup, strat, seed=seed * 100 + ep, max_turns=MAX_TURNS)
scenario = Scenario(anchor_price=ANCHOR, target_price=TARGET, revenue_amount=sup.revenue_amount,
distribution_code=sup.distribution_code, partner_count=sup.partner_count)
price0 = TARGET * 1.15
price, used, total_r = price0, set(), 0.0
for turn in range(1, MAX_TURNS + 1):
acceptance = max(0.0, (price0 - price) / price0)
s = make_snapshot(sup, price, turn, acceptance)
sf = np.concatenate([build_state_features(s), tf])
avail = [c for c in train_pool if c not in used] or list(train_pool)
embs = np.stack([feat[c] for c in avail])
i, _, _ = policy.select(sf, embs)
card = avail[i]; used.add(card)
resp = buyer.respond(card, scenario, turn, price)
price = resp.new_price
done = resp.accept or price <= ANCHOR or turn >= MAX_TURNS
success = resp.accept or price <= ANCHOR
outcome = (NegotiationOutcome.SUCCESS if success
else NegotiationOutcome.FAILURE if done else NegotiationOutcome.ONGOING)
# 최종 결과 시점만 채점 (중간 0 → γ 부트스트랩) — compare 스크립트와 동일 규칙.
r = rc.calculate(make_snapshot(sup, price, turn, acceptance, outcome)).total if done else 0.0
total_r += r
if done:
policy.remember(sf, feat[card], r, None, None, True)
else:
acc2 = max(0.0, (price0 - price) / price0)
s2 = make_snapshot(sup, price, turn + 1, acc2)
navail = [c for c in train_pool if c not in used] or list(train_pool)
policy.remember(sf, feat[card], r, np.concatenate([build_state_features(s2), tf]),
np.stack([feat[c] for c in navail]), False)
policy.train_step()
if done:
break
recent.append(total_r)
if ep % 2000 == 0:
print(f" ep {ep:>6} eps={policy.eps():.3f} 최근2000 평균보상={np.mean(recent[-2000:]):.4f}")
policy.save(CKPT_PATH)
print(f"[저장] {CKPT_PATH}")
return policy
if __name__ == "__main__":
main()
+365
View File
@@ -0,0 +1,365 @@
"""train_full_autonomy — 행동 룰 0개, 완전 자율 협상 에이전트 (v2 시뮬 프로토타입).
기존 시스템의 룰(앵커 이하 강제타결 / 3라운드 강제결렬 / 와일드카드 존 / 카드 카탈로그)을
전부 제거하고, 모든 결정을 에이전트 행동으로 이관한다:
행동 공간 (action-as-feature, ScoreNet 이 후보 열거 채점):
ACCEPT 현재 제시가로 타결 ← '앵커 이하 강제타결' 룰 대체
WALK 협상 결렬 선언 ← '3라운드 강제결렬' 룰 대체
COUNTER(C) "C원이면 수락" 역제안 ← '와일드카드 1%' 룰 대체 (금액도 학습)
PRESS(strategy) 설득 압박(카드의 일반화) ← 카드 카탈로그 대체 (전략만 남음)
룰이 사라진 자리는 보상이 채운다(유일한 스펙):
R = W×R_price + (1−W)×R_end − λ×round (기존 RewardCalculator 그대로)
협상이 끝나는 길: 에이전트의 ACCEPT/WALK, 협력사의 COUNTER 수락, 협력사의 인내심 소진(이탈).
마지막 것은 시스템 룰이 아니라 상대방 특성이다.
베이스라인 = 현행 룰 시스템을 같은 환경에서 재현(앵커타결/1%클로징/3라운드결렬 + 압박).
실행: APP_ENV=local PYTHONUTF8=1 python -m tools.train_full_autonomy
"""
import os
import random
from typing import Optional, Tuple
import numpy as np
import torch
from eval_harness.feature_buyer import AFFINITY, STRATEGY_PROFILE, SupplierProfile, sample_supplier
from negotiation.policies.autonomy_actions import (
ACTION_DIM, ACTIONS, COUNTER_GRID, EXTRA_STATE_DIM, Action, extra_state,
internet_gap_feat, settle_norm as extra_settle)
from negotiation.policies.feature_dqn_policy import FeatureDQNPolicy
from negotiation.qtable.domain.model.snapshot import NegotiationOutcome, NegotiationSnapshot
from negotiation.qtable.domain.service.feature_builder import (
STATE_FEATURE_DIM, TENANT_FEATURE_DIM, build_state_features, build_tenant_features)
from negotiation.qtable.domain.service.reward_calculator import RewardCalculator
from tenancy.config_loader import TenantConfigLoader
from tools.train_feature_dqn import pref_config, sample_tenant_pref
_HERE = os.path.dirname(os.path.abspath(__file__))
CKPT_PATH = os.path.join(_HERE, "..", "artifacts", "full_autonomy.pt")
TARGET = 10000.0
# 앵커율(v3.1): 실운영 기하 정합 — 앵커가 = 목표가×(1−a), a ∈ [0.8%, 6%] 를 에피소드마다 샘플링.
# (기존 고정 20% 폭은 실제(≈1%)와 지형이 달라, 실서비스에서 압박/역제안 밸런스가 어긋났다.)
ANCHOR_RATE_RANGE = (0.008, 0.06)
# 행동 공간(Action/ACTIONS/COUNTER_GRID/ACTION_DIM)은 negotiation.policies.autonomy_actions 공유
# — 서빙(autonomy_store, numpy 전용)과 학습이 같은 인코딩을 쓴다.
# ---- 협력사 모델 (상대 반응: 역제안 수락/재제안 포함) ---------------------------------
class AutonomousBuyer:
"""FeatureBuyer 확장: 역제안(C)에 반응한다. 이탈은 '인내심' — 시스템 룰이 아닌 상대 특성."""
def __init__(self, sup: SupplierProfile, seed: int):
self.sup = sup
self.rng = np.random.default_rng(seed)
# 기질 t ∈ [0,1]: 0=터프(하한 높고 안 물러섬) ↔ 1=수월. 관측 가능한 이력·최저가가
# 이 숨은 기질과 상관되게 생성된다 → 에이전트가 이력/최저가 특징을 읽을 '이유'가 생긴다.
# 하한은 '우리 앵커'가 아니라 협력사 사정(≈목표가 기준)으로 정해진다(v3.1) —
# 하한 > 목표가(≈35%)면 애초에 성사 불가능한 협상이고, 그걸 빨리 알아채고 끊는 것도 실력이다.
t = float(self.rng.uniform(0.0, 1.0))
self.floor = TARGET * float(np.clip(1.12 - 0.24 * t + self.rng.normal(0, 0.02), 0.85, 1.18))
self.patience = int(self.rng.integers(4, 9)) + (1 if t > 0.7 else 0)
# 첫 제시가: 목표가의 105~150% — 실운영(기존 공급가가 목표가를 26%+ 상회) 분포를 덮는다.
# 좁게(110~125%) 학습하면 큰 갭 상황에서 정책이 분포 밖 일반화(대형컷 역제안)를 한다.
self.price = TARGET * float(self.rng.uniform(1.05, 1.50))
# 하한가가 첫 제시가보다 높을 수 없다(자기 하한 밑으로 부르고 시작하는 판매자는 없음).
# 이 보정이 없으면 on_press 의 max(floor,·)가 가격을 '역주행'시키는 비현실이 생긴다.
self.floor = min(self.floor, self.price * 0.98)
self._last_c: Optional[float] = None # 직전 역제안 (같은 숫자 반복 짜증 모델링)
# ---- 관측 가능 부가정보 (v3 특징 소스 — 기질과 상관, 노이즈 있음) ----
self.hist_n = int(self.rng.integers(0, 6)) # 과거 협상 횟수 (0=신규)
if self.hist_n:
self.hist_success = float(np.clip(0.25 + 0.6 * t + self.rng.normal(0, 0.10), 0.0, 1.0))
self.hist_settle_ratio = float(np.clip(1.18 - 0.28 * t + self.rng.normal(0, 0.04), 0.80, 1.30))
else:
self.hist_success = self.hist_settle_ratio = None
# 인터넷최저가: 숨은 하한가의 노이즈 관측치. 60% 확률로만 수집돼 있음(현실: 미수집 흔함).
self.internet_lowest = (self.floor * float(self.rng.uniform(0.98, 1.08))
if self.rng.random() < 0.6 else None)
def _powers(self, strategy: int) -> Tuple[float, float]:
conc, acc = STRATEGY_PROFILE.get(strategy, (0.5, 0.5))
m = AFFINITY[self.sup.segment].get(strategy, 0.5)
scale = 0.35 + 0.85 * m
return conc * scale, acc * scale
def on_press(self, strategy: int, turn: int) -> Tuple[bool, float]:
"""(이탈여부, 새 제시가). 압박이 안 먹히는 세그먼트면 이탈 위험이 실재한다."""
c_pow, a_pow = self._powers(strategy)
walk_p = 0.04 + 0.30 * (1.0 - a_pow) * (turn / self.patience)
if self.rng.random() < walk_p:
return True, self.price
concession = (self.price - self.floor) * (0.10 + 0.55 * c_pow)
self.price = max(self.floor, self.price - concession)
return False, self.price
def on_counter(self, c: float, strategy: int, turn: int) -> Tuple[str, float]:
"""역제안 C 반응: 'accept'(C로 타결) | 'walk' | 'counter'(새 제시가).
현실화(v2): 현 제시가 대비 인하 요구폭(cut)이 클수록 수락률이 급감하고 이탈 위험이 커진다
— 초기 버전에서 에이전트가 't1 원샷 로우볼'로 시뮬 허점을 착취하던 것을 막는다.
압박으로 가격을 충분히 끌어내린 뒤 작은 컷으로 클로징해야 통하는 구조.
"""
_, a_pow = self._powers(strategy or 3)
cut = max(0.0, (self.price - c) / max(self.price, 1.0)) # 인하 요구폭 (현 제시가 대비)
prev_c = self._last_c
repeated = prev_c is not None and abs(c - prev_c) < 1e-6 # 같은 숫자 반복
self._last_c = c
# 양보 상호성(v3.3): 직전 제안보다 올려 부르면(성의 있는 양보) 호의적으로 반응한다.
# 이 신호가 있어야 '상대가 내리면 우리도 조금 올리는' tit-for-tat 이 학습으로 나온다.
warm = 0.0
if prev_c is not None and c > prev_c + 1e-9:
warm = float(np.clip((c - prev_c) / max(self.price - self.floor, 1.0), 0.0, 0.35))
if c >= self.floor:
margin = (c - self.floor) / max(self.floor, 1.0)
p_acc = float(np.clip(0.20 + 0.9 * margin / 0.08, 0.0, 0.95)) * (0.75 + 0.35 * a_pow)
p_acc *= float(np.clip(1.0 - (cut - 0.05) / 0.20, 0.0, 1.0)) # 컷 5% 초과부터 반발, 25%면 수락 0
if repeated:
p_acc *= 0.25 # 이미 거절한 숫자를 또 내밀면 설득력 급감
p_acc *= 1.0 + warm
if self.rng.random() < min(p_acc, 0.97):
return "accept", c
# 모욕적 요구(하한 미달·과도한 원샷 컷·앵무새 반복) → 이탈 위험
low = max(0.0, (self.floor - c) / max(self.floor, 1.0))
p_walk = min(0.5, 2.0 * low) + 0.35 * max(0.0, cut - 0.20) / 0.20 + (0.15 if repeated else 0.0)
if self.rng.random() < min(p_walk * (1.0 - warm), 0.7):
return "walk", self.price
self.price = max(self.floor, c + (self.price - c) * float(self.rng.uniform(0.30, 0.60) + warm))
return "counter", self.price
# ---- 에피소드 실행 (룰 없음 — 종료는 행동 또는 상대 특성으로만) ------------------------
def make_snapshot(sup, price, turn, p0, anchor, outcome=NegotiationOutcome.ONGOING):
return NegotiationSnapshot(
revenue_amount=sup.revenue_amount, distribution_code=sup.distribution_code,
partner_count=sup.partner_count, acceptance_ratio=max(0.0, (p0 - price) / p0),
input_price=price, anchor_price=anchor, target_price=TARGET,
round_number=turn, outcome=outcome)
MIN_PRESS = int(os.getenv("AUTONOMY_MIN_PRESS", "2")) # 역제시 해금에 필요한 최소 설득 횟수
def available_actions(price: float, last_counter_q: Optional[float] = None,
counter_locked: bool = False) -> list:
"""행동 봉투 (serving autonomy_store 와 동일해야 한다):
① 목표가 초과 제시가는 '수락' 제외 — 매입 승인 범위(목표가 초과 수락 착취 방지)
② 직전 역제안 미만 금액의 역제안 제외 — 단조 양보 원칙(제안 철회 금지;
양보 '속도'는 정책이 배우고, 후퇴 '금지'만 구조로 보장)
③ counter_locked: 설득 MIN_PRESS 회 전에는 역제시 잠금 — 옛 제품 의미론
(일반 카드=설득, 역제시=와일드카드 성격의 마무리 수단) 복원
④ 마무리 국면(제시가 ≤ 목표가×1.005): 압박 제외 — 푼돈 차이에서 재검토 요청 반복 방지
⑤ 첫 역제안은 앵커 이하(q ≤ 0)만 — 낮게 개시해 사다리를 다 쓰며 올라간다"""
near_target = price <= TARGET * 1.005
return [a for a in ACTIONS
if not (a.kind == "accept" and price > TARGET)
and not (a.kind == "counter" and counter_locked and not near_target)
and not (a.kind == "walk" and counter_locked and not near_target)
and not (a.kind == "press" and near_target)
and not (a.kind == "counter" and last_counter_q is None and a.counter_q > 1e-9)
and not (a.kind == "counter" and last_counter_q is not None
and a.counter_q < last_counter_q - 1e-9)]
def action_feats(price: float, anchor: float, last_counter_q: Optional[float] = None,
counter_locked: bool = False):
"""현 제시가 기준 (가용 행동 리스트, 특징 [K, ACTION_DIM]). counter 는 컷폭 포함."""
span = max(TARGET - anchor, 1.0)
pos = (price - anchor) / span
acts = available_actions(price, last_counter_q, counter_locked)
rows = []
for a in acts:
cut = 0.0
if a.kind == "counter":
c = anchor + a.counter_q * span
cut = max(0.0, (price - c) / max(price, 1.0))
rows.append(a.feat(pos, cut))
return acts, np.stack(rows)
def run_episode(policy_fn, sup, rc: RewardCalculator, tf: np.ndarray, seed: int,
learner: Optional[FeatureDQNPolicy] = None, trace: Optional[list] = None):
"""policy_fn(state_feat, price_pos) → Action. learner 지정 시 replay 저장+학습."""
buyer = AutonomousBuyer(sup, seed)
p0 = buyer.price
env_rng = np.random.default_rng(seed + 7)
# 앵커율 샘플링(v3.1): 실운영처럼 앵커가 목표가 바로 아래(0.8~6%) — 좁은 스팬 지형에서 학습.
anchor = TARGET * (1.0 - float(env_rng.uniform(*ANCHOR_RATE_RANGE)))
span = max(TARGET - anchor, 1.0)
turn, settled, walked = 0, None, False
last_kind, last_q = "", 0.0 # 직전 역제안 기억 (같은 숫자 반복 방지의 학습 근거)
press_n = 0 # 설득 횟수 — 역제시 해금(MIN_PRESS) 카운터
# 견적 마감(환경 사실): 마감 도달 시 협상은 미타결 종료된다 — 룰이 아니라 세상의 시계.
deadline_turns = int(env_rng.integers(3, 11))
# 관측성 마스크(v3.5): 실서빙은 마감·이력·최저가가 '없는' 세션이 흔하고 로더가 중립값
# (0.5/0)을 대입한다. 시뮬이 항상 다 아는 세계만 학습하면 그 중립 상태가 분포 밖이 된다
# — v3.4 가 라이브 소액 지형에서 첫 턴 결렬로 퇴화한 원인 추정. 세계(마감 종료·상대 특성)는
# 그대로 두고 관측만 가린다: 마감은 40% 미관측(0.5 고정), 15% 는 전부 미상(신규 견적의 전형).
deadline_known = env_rng.random() < 0.6
blind = env_rng.random() < 0.15
if blind:
deadline_known = False
# 협력사 이력·최저가 특징 (에피소드 내 불변)
known_hist = buyer.hist_n and not blind
fixed_extra = dict(
hist_n=min(buyer.hist_n, 5) / 5.0 if not blind else 0.0,
hist_success=buyer.hist_success if known_hist else 0.5,
hist_settle=extra_settle(buyer.hist_settle_ratio) if known_hist else 0.5,
internet_gap=internet_gap_feat(buyer.internet_lowest or 0.0, anchor) if not blind else 0.0,
)
pending = None # (state_feat, action_feat) — 최종 결과 시점만 채점, 중간 r=0
while True:
turn += 1
price = buyer.price
deadline_remain = (max(0.0, (deadline_turns - turn + 1) / deadline_turns)
if deadline_known else 0.5) # 미관측 → 서빙 로더와 동일한 중립값
sf = np.concatenate([build_state_features(make_snapshot(sup, price, turn, p0, anchor)), tf,
extra_state(last_kind, last_q, deadline=deadline_remain, **fixed_extra)])
lcq = last_q if last_kind == "counter" else None
locked = lcq is None and press_n < MIN_PRESS
act = policy_fn(sf, price, anchor, lcq, locked)
if trace is not None:
trace.append((turn, int(price), act))
if act.kind == "accept":
settled = price
elif act.kind == "walk":
walked = True
elif act.kind == "counter":
c = anchor + act.counter_q * span
resp, val = buyer.on_counter(c, act.strategy, turn)
last_kind, last_q = "counter", act.counter_q # 역제안 기억 갱신
if resp == "accept":
settled = c
elif resp == "walk":
walked = True
else: # press
press_n += 1
left, _ = buyer.on_press(act.strategy, turn)
walked = walked or left
if not settled and not walked and turn >= buyer.patience:
walked = True # 인내심 소진(상대 특성) — 시스템 룰 아님
if not settled and not walked and turn >= deadline_turns:
walked = True # 견적 마감 도달(환경 사실) — 미타결 종료
done = settled is not None or walked
final_price = settled if settled is not None else buyer.price
# 성사 보너스는 목표가 이하 타결에만 — v3.1 이 '비싸게라도 성사'로 착취한 보상 구멍의
# 원인 차단(봉투 ① 의 마스크와 이중 방어: 유인 자체를 올바르게). 초과 타결 = 결렬 취급.
outcome = (NegotiationOutcome.SUCCESS if settled is not None and settled <= TARGET
else NegotiationOutcome.FAILURE if done else NegotiationOutcome.ONGOING)
r = rc.calculate(make_snapshot(sup, final_price, turn, p0, anchor, outcome)).total if done else 0.0
if learner is not None:
pos = (price - anchor) / span
cut = 0.0
if act.kind == "counter":
cut = max(0.0, (price - (anchor + act.counter_q * span)) / max(price, 1.0))
af = act.feat(pos, cut)
if pending:
nxt_lcq = last_q if last_kind == "counter" else None
learner.remember(*pending, 0.0, sf,
action_feats(price, anchor, nxt_lcq,
nxt_lcq is None and press_n < MIN_PRESS)[1], False)
pending = (sf, af)
if done:
learner.remember(sf, af, r, None, None, True)
learner.train_step()
if done:
return settled, turn, r
# ---- 정책들 ------------------------------------------------------------------
def dqn_policy(policy: FeatureDQNPolicy):
def f(sf, price, anchor, last_counter_q=None, counter_locked=False):
acts, feats = action_feats(price, anchor, last_counter_q, counter_locked)
i, _, _ = policy.select(sf, feats)
return acts[i]
return f
class RuleBaseline:
"""현행 시스템 룰 재현: 앵커 이하 수락 / 존내 1% 클로징 / 3회 압박 후 결렬."""
def __init__(self):
self.presses, self.closed = 0, False
def __call__(self, sf, price, anchor, last_counter_q=None, counter_locked=False) -> Action:
span = max(TARGET - anchor, 1.0)
if price <= anchor:
return Action("accept")
if price <= anchor * 1.02 and not self.closed:
self.closed = True
return Action("counter", (price * 0.99 - anchor) / span, 3)
if self.presses < 3:
self.presses += 1
return Action("press", 0.0, 3)
return Action("walk")
# ---- 학습/평가 ----------------------------------------------------------------
def evaluate(name, make_policy_fn, base_cfg, tcfg_state, episodes=3000, seed0=777):
rc = RewardCalculator(pref_config(base_cfg, 0.5), tcfg_state)
tf = build_tenant_features(pref_config(base_cfg, 0.5))
rng = np.random.default_rng(seed0)
rewards, settles, rounds = [], [], []
for i in range(episodes):
sup = sample_supplier(rng)
settled, turn, r = run_episode(make_policy_fn(), sup, rc, tf, seed0 * 91 + i)
rewards.append(r)
rounds.append(turn)
if settled is not None:
settles.append(settled / TARGET)
sr = len(settles) / episodes
print(f"{name:<14} 보상 {np.mean(rewards):.4f} ±{np.std(rewards)/np.sqrt(episodes):.4f}"
f" 성사율 {sr:.3f} 타결가/목표 {np.mean(settles):.3f} 평균라운드 {np.mean(rounds):.2f}")
return dict(reward=float(np.mean(rewards)), success=sr,
settle_ratio=float(np.mean(settles)) if settles else None, rounds=float(np.mean(rounds)))
def main(episodes=15000, seed=42):
random.seed(seed); np.random.seed(seed); torch.manual_seed(seed)
tcfg = TenantConfigLoader().load("ktcommerce")
policy = FeatureDQNPolicy(state_dim=STATE_FEATURE_DIM + TENANT_FEATURE_DIM + EXTRA_STATE_DIM,
card_dim=ACTION_DIM, eps_decay=5000, gamma=0.97)
rng = np.random.default_rng(seed)
print(f"=== 완전 자율 학습 {episodes}ep (행동 {len(ACTIONS)}개, 룰 0개) ===")
recent = []
for ep in range(1, episodes + 1):
sup = sample_supplier(rng)
rcfg, tf = sample_tenant_pref(rng, tcfg.reward)
rc = RewardCalculator(rcfg, tcfg.state)
_, _, r = run_episode(dqn_policy(policy), sup, rc, tf, seed * 131 + ep, learner=policy)
recent.append(r)
if ep % 3000 == 0:
print(f" ep {ep:>6} eps={policy.eps():.3f} 최근3000 평균보상={np.mean(recent[-3000:]):.4f}")
policy.save(CKPT_PATH)
print("\n=== 평가 3000ep (중립 성향 p=0.5, 동일 협력사 분포) ===")
policy.greedy = True
evaluate("룰시스템(현행)", lambda: RuleBaseline(), tcfg.reward, tcfg.state)
evaluate("완전자율 DQN", lambda: dqn_policy(policy), tcfg.reward, tcfg.state)
# 궤적 예시 — 에이전트가 룰 없이 뭘 하는지 눈으로
print("\n=== 궤적 예시 (완전자율) ===")
rc = RewardCalculator(pref_config(tcfg.reward, 0.5), tcfg.state)
tf = build_tenant_features(pref_config(tcfg.reward, 0.5))
rng2 = np.random.default_rng(7)
for k in range(3):
sup = sample_supplier(rng2)
trace = []
settled, turn, r = run_episode(dqn_policy(policy), sup, rc, tf, 5000 + k, trace=trace)
seg = "·".join(sup.segment)
print(f"[{seg}] " + " → ".join(
f"t{t}:{p:,}원 {a.kind}{'' if a.kind in ('accept', 'walk') else f'({a.counter_q:.2f},전략{a.strategy})' if a.kind == 'counter' else f'(전략{a.strategy})'}"
for t, p, a in trace) + f" ⇒ {'타결 ' + format(int(settled), ',') + '원' if settled else '결렬'} (r={r:.3f})")
if __name__ == "__main__":
main()
-1
View File
@@ -153,7 +153,6 @@ class quotations(MAIN_BASE):
manager_contact_number = Column(String(20), nullable=True) # 담당자 연락처 manager_contact_number = Column(String(20), nullable=True) # 담당자 연락처
memo = Column(String(100), nullable=True) # 메모 memo = Column(String(100), nullable=True) # 메모
md_price = Column(BigInteger, nullable=True) md_price = Column(BigInteger, nullable=True)
supplier_type = Column(SmallInteger, nullable=True)
iteration = Column(Integer, nullable=False, server_default=text("0")) # 반복 횟수 iteration = Column(Integer, nullable=False, server_default=text("0")) # 반복 횟수
preferred_sp_yn = Column(Boolean, nullable=True) # 선호 공급사 지정 여부 preferred_sp_yn = Column(Boolean, nullable=True) # 선호 공급사 지정 여부
preferred_sp_id = Column(UUID(as_uuid=True), nullable=True) # 선호 공급사(partner.suppliers.supplier_id) preferred_sp_id = Column(UUID(as_uuid=True), nullable=True) # 선호 공급사(partner.suppliers.supplier_id)
+23 -4
View File
@@ -1,12 +1,12 @@
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
from typing import Tuple from typing import Tuple
from sqlalchemy import asc, desc, func, select, update from sqlalchemy import case, func, nulls_last, select, update
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
from common.database.db_session_manager import DB_SESSION_MNG from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import items, quotations, sessions from common.database.model.models import items, quotations, sessions
from common.enums import ErrorType from common.enums import ErrorType, SessionStatus
from common.logger import LOG from common.logger import LOG
@@ -55,7 +55,26 @@ class SessionCRUD(ISessionCRUD):
async def list_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, order, offset, limit) -> Tuple[ErrorType, list]: async def list_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, order, offset, limit) -> Tuple[ErrorType, list]:
try: try:
conds = self.__filters(supplier_id, status, qt_type) conds = self.__filters(supplier_id, status, qt_type)
order_col = desc(quotations.end_time) if order == "desc" else asc(quotations.end_time)
# 정렬 규칙:
# - order 를 명시(asc/desc)하면 그룹 구분 없이 전체를 마감 기준 한 줄로 정렬(전체 정렬).
# - order 가 없으면(기본) UX 그룹 정렬:
# (1) '할 일'(협상생성·협상중)을 위로, 종료(완료·미참여·거부)는 아래로 그룹핑
# (2) 액션 그룹은 마감 임박순, (3) 종료 그룹은 최근 마감순(desc)
# - 어느 경우든 동일 마감은 session_id 로 tie-break → 페이지네이션 안정화.
# end_time 이 실제 NULL 인 견적은 nulls_last 로 맨 뒤로 민다.
if order in ("asc", "desc"):
flat = quotations.end_time.desc() if order == "desc" else quotations.end_time.asc()
order_cols = (nulls_last(flat), sessions.session_id.asc())
else:
# 그룹별로 정렬 방향이 달라, case 로 '자기 그룹 행만 end_time' 을 갖는 키를 만들고
# 반대 그룹은 NULL 로 눌러 간섭을 없앤다. status_rank 가 1차 키라 그룹 경계는 항상 유지.
actionable = sessions.status.in_((SessionStatus.CREATED.value, SessionStatus.IN_PROGRESS.value))
status_rank = case((actionable, 0), else_=1)
action_order = case((actionable, quotations.end_time), else_=None).asc()
done_order = case((~actionable, quotations.end_time), else_=None).desc()
order_cols = (status_rank.asc(), nulls_last(action_order), nulls_last(done_order), sessions.session_id.asc())
query = ( query = (
select( select(
sessions.session_id, sessions.session_id,
@@ -71,7 +90,7 @@ class SessionCRUD(ISessionCRUD):
.join(items, items.item_id == sessions.item_id) .join(items, items.item_id == sessions.item_id)
.join(quotations, quotations.qt_id == sessions.quotation_id) .join(quotations, quotations.qt_id == sessions.quotation_id)
.where(*conds, items.deleted == False, quotations.deleted == False) # noqa: E712 .where(*conds, items.deleted == False, quotations.deleted == False) # noqa: E712
.order_by(order_col) .order_by(*order_cols)
.offset(offset) .offset(offset)
.limit(limit) .limit(limit)
) )
+2 -2
View File
@@ -15,7 +15,7 @@ router = APIRouter(prefix="/v1/negotiation", tags=["Negotiation"], responses={40
path="/sessions", path="/sessions",
response_model=Res_SessionList, response_model=Res_SessionList,
summary="협상 세션 목록", summary="협상 세션 목록",
description="로그인한 공급사의 협상 세션 목록. 필터(status/qt_type, 정수 코드)·마감일 정렬·페이지네이션 지원.", description="로그인한 공급사의 협상 세션 목록. 필터(status/qt_type, 정수 코드)·페이지네이션 지원. 기본 정렬(order 미지정)은 '할 일(협상생성·협상중) 우선 + 마감 임박순', 종료(완료·미참여·거부)는 하단·최근순. order 를 주면 그룹 없이 전체 마감순으로 정렬.",
) )
async def list_sessions( async def list_sessions(
user_info: UserInfo = Depends(IsValidAccessToken), user_info: UserInfo = Depends(IsValidAccessToken),
@@ -23,7 +23,7 @@ async def list_sessions(
service: NegotiationService = Depends(), service: NegotiationService = Depends(),
status: Optional[int] = Query(None, description="세션 상태 코드 (SessionStatus)"), status: Optional[int] = Query(None, description="세션 상태 코드 (SessionStatus)"),
qt_type: Optional[int] = Query(None, description="견적 유형 코드 (QtType: 1=재협상, 2=재견적, 3=신규협상, 4=신규견적)"), qt_type: Optional[int] = Query(None, description="견적 유형 코드 (QtType: 1=재협상, 2=재견적, 3=신규협상, 4=신규견적)"),
order: str = Query("asc", description="마감일 정렬: asc(임박순)/desc"), order: Optional[str] = Query(None, description="마감일 전체 정렬: asc(임박순)/desc(여유순). 미지정 시 기본 그룹 정렬('할 일' 우선 → 종료는 하단·최근순). 지정하면 그룹 없이 전체를 마감 기준으로 정렬."),
page: int = Query(1, ge=1, description="페이지 (1부터)"), page: int = Query(1, ge=1, description="페이지 (1부터)"),
page_size: int = Query(20, ge=1, le=100, description="페이지당 건수 (1~100)"), page_size: int = Query(20, ge=1, le=100, description="페이지당 건수 (1~100)"),
): ):
+7 -2
View File
@@ -105,10 +105,15 @@ async def anchor_seed(db_engine):
{"iid": item_id, "name": f"앵커상품 {code}", "code": f"{MARK}{code}"}, {"iid": item_id, "name": f"앵커상품 {code}", "code": f"{MARK}{code}"},
) )
await conn.execute( await conn.execute(
text("INSERT INTO quotation.quotations (qt_id, user_id, qt_setting_id, version_id, name, number, type, status, start_time, end_time, supplier_type) " text("INSERT INTO quotation.quotations (qt_id, user_id, qt_setting_id, version_id, name, number, type, status, start_time, end_time) "
"VALUES (:qid, gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), :name, :num, 1, 2, now(), now() + interval '2 hours', 1)"), "VALUES (:qid, gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), :name, :num, 1, 2, now(), now() + interval '2 hours')"),
{"qid": qt_id, "name": f"앵커견적 {code}", "num": f"{MARK}{code}"}, {"qid": qt_id, "name": f"앵커견적 {code}", "num": f"{MARK}{code}"},
) )
await conn.execute(
text("INSERT INTO partner.supplier_items (supplier_item_id, supplier_id, item_id, supply_type) "
"VALUES (gen_random_uuid(), :sid, :iid, 1)"),
{"sid": supplier_id, "iid": item_id},
)
await conn.execute( await conn.execute(
text("INSERT INTO negotiation.sessions " text("INSERT INTO negotiation.sessions "
"(session_id, quotation_id, item_id, supplier_id, qt_number, qt_round, qt_type, " "(session_id, quotation_id, item_id, supplier_id, qt_number, qt_round, qt_type, "
+17 -5
View File
@@ -147,12 +147,24 @@ async def test_list_filter_qt_type(client, nego_seed):
assert {i["item_code"] for i in body["items"]} == {f"{MARK}A", f"{MARK}C"} assert {i["item_code"] for i in body["items"]} == {f"{MARK}A", f"{MARK}C"}
async def test_list_order_by_quotation_end_time(client, nego_seed): async def test_list_default_sort_groups_actionable_first(client, nego_seed):
# 기본 정렬(order 미지정): '할 일'(협상생성 A·협상중 B) 우선 → 마감 임박순, 종료(협상완료 C)는 하단.
token = await _login_token(client) token = await _login_token(client)
asc = (await _list(client, token, order="asc")).json()["items"] default = [i["item_code"] for i in (await _list(client, token)).json()["items"]]
desc = (await _list(client, token, order="desc")).json()["items"] # 액션 그룹 임박순(B +1h → A +2h) 뒤에 종료(C). C 는 마감이 가장 멀어도(+3h) 최하단 고정.
assert asc[0]["item_code"] == f"{MARK}B" # +1h 가 가장 임박 assert default == [f"{MARK}B", f"{MARK}A", f"{MARK}C"]
assert desc[0]["item_code"] == f"{MARK}C" # +3h 가 가장 멈
async def test_list_order_param_switches_to_global_sort(client, nego_seed):
# order 를 명시하면 그룹을 무시하고 전체를 마감 기준 한 줄로 정렬한다.
token = await _login_token(client)
asc = [i["item_code"] for i in (await _list(client, token, order="asc")).json()["items"]]
desc = [i["item_code"] for i in (await _list(client, token, order="desc")).json()["items"]]
# asc: 전체 마감 임박순 (B +1h → A +2h → C +3h)
assert asc == [f"{MARK}B", f"{MARK}A", f"{MARK}C"]
# desc: 전체 마감 여유순 — 종료(C)라도 마감이 가장 멀면 최상단으로 올라온다(그룹 무시 증거).
assert desc == [f"{MARK}C", f"{MARK}A", f"{MARK}B"]
async def test_list_pagination(client, nego_seed): async def test_list_pagination(client, nego_seed):
+93
View File
@@ -38,6 +38,9 @@ services:
RELOAD: "1" # uvicorn --reload 활성 → 소스 저장 시 자동 재기동(재빌드 불필요) RELOAD: "1" # uvicorn --reload 활성 → 소스 저장 시 자동 재기동(재빌드 불필요)
SCHEDULER_ENABLED: "1" # 마감 크론 활성(단일 워커라 중복 없음). 운영 다중 워커면 1개 프로세스에서만 1 SCHEDULER_ENABLED: "1" # 마감 크론 활성(단일 워커라 중복 없음). 운영 다중 워커면 1개 프로세스에서만 1
PYTHONUNBUFFERED: "1" # 컨테이너 로그 실시간 출력(stdout 버퍼링 끔) PYTHONUNBUFFERED: "1" # 컨테이너 로그 실시간 출력(stdout 버퍼링 끔)
# ── LPS(인터넷 최저가) 연동 — 미설정이면 연동 비활성으로 조용히 동작 ──
LPS_DB_HOST: host.docker.internal # lps_db 읽기전용(수집 배치·조회 API)
LPS_BASE_URL: http://host.docker.internal:9600 # 검색요청 enqueue. lps-api 컨테이너 사용 시 http://lps-api:9600
volumes: volumes:
- ./negodata/backend:/app # 호스트 소스 = 컨테이너 코드. 이게 있어야 수정이 즉시 반영됨 - ./negodata/backend:/app # 호스트 소스 = 컨테이너 코드. 이게 있어야 수정이 즉시 반영됨
ports: ports:
@@ -64,6 +67,9 @@ services:
environment: environment:
APP_ENV: local APP_ENV: local
DB_HOST: host.docker.internal # 컨테이너→호스트 DB (config.local.toml의 127.0.0.1 override) DB_HOST: host.docker.internal # 컨테이너→호스트 DB (config.local.toml의 127.0.0.1 override)
OPENAI_API_KEY: ${OPENAI_API_KEY:-} # LLM 키 passthrough (호스트 env/.env → 컨테이너). 빈 값이면 toml 폴백
DQN_SERVING: "1" # 카드 선택을 feature_dqn(numpy 서빙)으로. 0 이면 기존 UCB Q-table
AUTONOMY_MODE: "1" # 완전 자율 협상(판정 룰·카드 제거, 정책이 수락/역제안/결렬 결정). 0 이면 룰 엔진
ports: ports:
- "9500:9500" - "9500:9500"
extra_hosts: extra_hosts:
@@ -112,3 +118,90 @@ services:
options: options:
max-size: "10m" max-size: "10m"
max-file: "5" max-file: "5"
# ── LPS (인터넷 최저가 검색) ──────────────────────────────────
# API(요청 접수, lean) + 워커(크롤, 헤드풀 Chromium+Xvfb). DB 는 외부(host.docker.internal).
# 이미지엔 시크릿이 없다(example config 로 빌드) — 실값은 아래 env 로 주입.
# 시크릿 값은 리포 루트 .env 파일에 채운다(.env.example 참고, .env 는 미커밋).
lps-api:
build:
context: ./lps
dockerfile: Dockerfile
container_name: lps-api
environment:
APP_ENV: local
DB_HOST: host.docker.internal # 컨테이너→호스트 DB (example toml 의 127.0.0.1 override)
DB_USER: ${LPS_DB_USER:-postgres}
DB_PASSWORD: ${LPS_DB_PASSWORD:-postgres}
PYTHONUNBUFFERED: "1"
# 멀티코어: PROCESS_COUNT(uvicorn 워커=코어수)를 올리면 커넥션 풀은 자동 산정된다.
# (pool+overflow)×2엔진×PROCESS_COUNT ≤ DB_CONNECTION_BUDGET 를 config 가 스스로 보장.
# 값은 .env 에서 서버별로 조정(compose 수정 불필요). API 병목은 드묾 — 기본 1이면 충분,
# 부하테스트/대량 폴링 대비 시에만 코어 수만큼 상향(예: 4).
PROCESS_COUNT: ${LPS_API_PROCESS_COUNT:-1}
DB_CONNECTION_BUDGET: ${LPS_DB_CONNECTION_BUDGET:-40} # 전용 PG(max_connections≈100)면 90 근처로 상향
ports:
- "9600:9600"
extra_hosts:
- "host.docker.internal:host-gateway"
labels:
autoheal: "true" # HEALTHCHECK 실패 시 autoheal 이 재시작
restart: unless-stopped
logging:
driver: json-file
options: { max-size: "10m", max-file: "5" }
lps-worker:
build:
context: ./lps
dockerfile: Dockerfile.worker # Chromium + Xvfb (headless 는 안티봇에 탐지됨)
container_name: lps-worker
environment:
APP_ENV: local
DB_HOST: host.docker.internal
DB_USER: ${LPS_DB_USER:-postgres}
DB_PASSWORD: ${LPS_DB_PASSWORD:-postgres}
PYTHONUNBUFFERED: "1"
WORKER_CONCURRENCY: "1" # 상품 동시 검색 수(워커별 브라우저 세트, Chrome 4×N)
LPS_PROFILE_DIR: /profiles # Chrome 프로필을 영속 볼륨에 → 재시작해도 cf_clearance 유지(재웜업 회피)
# LPS_FALLBACKS: "gmarket,auction,st11" # 오픈마켓 폴백(기본 OFF — 켜기 전 라이브 스모크로 셀렉터 점검)
# LPS_JOB_DEADLINE_SEC: "300" # 잡 1건 처리 상한(행 방어) — 기본 300s
# ── 시크릿 주입(이미지엔 없음 — 필수). 리포 루트 .env 에 값 채움(.env.example 참고) ──
OPENAI_API_KEY: ${OPENAI_API_KEY:-} # 비면 AI 판정 OFF
NAVER_KEYS: ${NAVER_KEYS:-} # "id1:secret1,id2:secret2" — 비면 네이버 검색 실패
DECODO_HOST: ${DECODO_HOST:-} # DECODO 4종 비면 프록시 미사용(직접 연결)
DECODO_USERNAME: ${DECODO_USERNAME:-}
DECODO_PASSWORD: ${DECODO_PASSWORD:-}
DECODO_PORT_START: ${DECODO_PORT_START:-0}
DECODO_PORT_END: ${DECODO_PORT_END:-0}
DECODO_COST_PER_GB: ${DECODO_COST_PER_GB:-0}
volumes:
- lps-profiles:/profiles # Chrome 프로필(쿠키) 영속
extra_hosts:
- "host.docker.internal:host-gateway"
shm_size: "1gb" # Chrome 는 /dev/shm 을 많이 씀 — 부족하면 탭 크래시
stop_grace_period: 75s # graceful 종료 유예(LPS_SHUTDOWN_GRACE_SEC=60 + 정리 여유) — 기본 10s 면 하던 잡 마무리 전에 SIGKILL
labels:
autoheal: "true" # 하트비트 HEALTHCHECK 실패(행/좀비) 시 autoheal 이 재시작
restart: unless-stopped
logging:
driver: json-file
options: { max-size: "10m", max-file: "5" }
# HEALTHCHECK 실패 컨테이너 자동 재시작 — compose 의 restart 는 '프로세스 종료'만 다루고
# unhealthy 는 표시만 하므로, autoheal 라벨 붙은 컨테이너(lps-api/lps-worker)를 감시해 재시작한다.
# docker.sock 마운트 = 도커 제어 권한이므로 신뢰 환경에서만 사용.
autoheal:
image: willfarrell/autoheal:latest
container_name: autoheal
environment:
AUTOHEAL_CONTAINER_LABEL: autoheal
volumes:
- /var/run/docker.sock:/var/run/docker.sock
restart: unless-stopped
logging:
driver: json-file
options: { max-size: "10m", max-file: "5" }
volumes:
lps-profiles:
@@ -24,19 +24,23 @@ export const SESSION_STATUS_LABEL: Record<SessionStatus, string> = {
export const QtType = { export const QtType = {
RENEGO: 1, // 재협상(1:1) RENEGO: 1, // 재협상(1:1)
REQUOTE: 2, // 재견적(1:N) REQUOTE: 2, // 재견적(1:N)
NEW_NEGO: 3, // 신규협상(1:1)
NEW_QUOTE: 4, // 신규견적(1:N)
} as const } as const
export type QtType = (typeof QtType)[keyof typeof QtType] export type QtType = (typeof QtType)[keyof typeof QtType]
export const QT_TYPE_LABEL: Record<QtType, string> = { export const QT_TYPE_LABEL: Record<QtType, string> = {
[QtType.RENEGO]: '재협상', [QtType.RENEGO]: '재협상',
[QtType.REQUOTE]: '재견적', [QtType.REQUOTE]: '재견적',
[QtType.NEW_NEGO]: '신규협상',
[QtType.NEW_QUOTE]: '신규견적',
} }
// --- 세션 목록 (GET /v1/negotiation/sessions) ---------------------------- // --- 세션 목록 (GET /v1/negotiation/sessions) ----------------------------
export interface SessionListParams { export interface SessionListParams {
status?: number // SessionStatus 코드 필터 status?: number // SessionStatus 코드 필터
qt_type?: number // QtType 코드 필터 qt_type?: number // QtType 코드 필터
order?: 'asc' | 'desc' // 마감(qt_end_time) 정렬, asc=임박순 order?: 'asc' | 'desc' // 생략 시 기본 그룹 정렬('할 일' 우선+임박순, 종료는 하단). 지정 시 그룹 무시하고 전체 마감순(asc=임박/desc=여유)
page?: number page?: number
page_size?: number page_size?: number
} }
+1 -1
View File
@@ -7,7 +7,7 @@ export interface FilterGroupConfig {
} }
export const FILTER_GROUPS: readonly FilterGroupConfig[] = [ export const FILTER_GROUPS: readonly FilterGroupConfig[] = [
{ key: 'type', title: '구분', items: ['재견적', '재협상'] }, { key: 'type', title: '구분', items: ['재견적', '재협상', '신규견적', '신규협상'] },
{ {
key: 'status', key: 'status',
title: '상태', title: '상태',
+672
View File
@@ -0,0 +1,672 @@
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>LPS · 최저가 검색 콘솔 (임시 FE)</title>
<style>
:root{
--bg:#f5f6f8; --surface:#ffffff; --surface-2:#fafbfc;
--border:#e6e8ec; --border-2:#eef0f3;
--text-900:#1a1d24; --text-700:#3d434f; --text-500:#6b7280; --text-400:#9aa1ac;
--primary-600:#4f46e5; --primary-500:#635bff; --primary-50:#eef0ff;
--naver:#03c75a; --coupang:#f0455b; --final:#4f46e5;
--ok-600:#0f9d58; --ok-50:#e7f6ee;
--warn-600:#c77800; --warn-50:#fdf3e3;
--run-600:#2563eb; --run-50:#e8f0ff;
--dead-600:#dc2626; --dead-50:#fdeaea;
--radius:14px; --radius-sm:9px;
--shadow:0 1px 2px rgba(16,24,40,.04), 0 4px 16px rgba(16,24,40,.06);
--mono:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Consolas,monospace;
--sans:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Apple SD Gothic Neo","Noto Sans KR",sans-serif;
}
*{box-sizing:border-box}
html,body{margin:0}
body{background:var(--bg);color:var(--text-900);font-family:var(--sans);font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased}
a{color:var(--primary-600);text-decoration:none}
a:hover{text-decoration:underline}
/* ---- layout ---- */
header.top{position:sticky;top:0;z-index:20;background:rgba(255,255,255,.82);backdrop-filter:saturate(180%) blur(12px);border-bottom:1px solid var(--border)}
.top-inner{max-width:1180px;margin:0 auto;padding:12px 22px;display:flex;align-items:center;gap:16px;flex-wrap:wrap}
.brand{display:flex;align-items:center;gap:11px;font-weight:700;font-size:16px}
.logo{width:30px;height:30px;border-radius:8px;background:linear-gradient(135deg,var(--primary-500),#8b7bff);display:grid;place-items:center;color:#fff;font-size:15px;font-weight:800}
.brand small{display:block;font-weight:500;font-size:11px;color:var(--text-400);letter-spacing:.02em}
.top-spacer{flex:1}
.stat-badges{display:flex;gap:7px;flex-wrap:wrap}
.badge{display:inline-flex;align-items:center;gap:6px;padding:5px 10px;border-radius:999px;font-size:12px;font-weight:600;border:1px solid var(--border);background:var(--surface-2);color:var(--text-700)}
.badge .dot{width:7px;height:7px;border-radius:50%;background:var(--text-400)}
.badge b{font-variant-numeric:tabular-nums}
.badge.pending .dot{background:var(--warn-600)} .badge.running .dot{background:var(--run-600)}
.badge.done .dot{background:var(--ok-600)} .badge.dead .dot{background:var(--dead-600)}
.health{display:inline-flex;align-items:center;gap:7px;font-size:12px;color:var(--text-500);font-weight:600}
.pulse{width:8px;height:8px;border-radius:50%;background:var(--dead-600)}
.pulse.up{background:var(--ok-600);box-shadow:0 0 0 0 rgba(15,157,88,.5);animation:pulse 2s infinite}
@keyframes pulse{0%{box-shadow:0 0 0 0 rgba(15,157,88,.45)}70%{box-shadow:0 0 0 7px rgba(15,157,88,0)}100%{box-shadow:0 0 0 0 rgba(15,157,88,0)}}
main{max-width:1180px;margin:0 auto;padding:22px;display:grid;grid-template-columns:400px 1fr;gap:20px;align-items:start}
@media (max-width:940px){main{grid-template-columns:1fr}}
.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow)}
.card + .card{margin-top:20px}
.card-head{padding:15px 18px;border-bottom:1px solid var(--border-2);display:flex;align-items:center;gap:10px}
.card-head h2{margin:0;font-size:14px;font-weight:700;letter-spacing:-.01em}
.card-head .hint{margin-left:auto;font-size:11.5px;color:var(--text-400);font-weight:500}
.card-head .idx{width:22px;height:22px;border-radius:7px;background:var(--primary-50);color:var(--primary-600);display:grid;place-items:center;font-size:12px;font-weight:800}
.card-body{padding:18px}
/* ---- form ---- */
.field{margin-bottom:13px}
.field:last-child{margin-bottom:0}
.field label{display:block;font-size:12px;font-weight:600;color:var(--text-700);margin-bottom:5px}
.field label .req{color:var(--coupang);margin-left:2px}
.field .sub{font-weight:500;color:var(--text-400);font-size:11px}
input,select,textarea{width:100%;padding:9px 11px;border:1px solid var(--border);border-radius:var(--radius-sm);font-size:13px;font-family:inherit;color:var(--text-900);background:var(--surface);transition:border-color .12s,box-shadow .12s}
input:focus,select:focus,textarea:focus{outline:none;border-color:var(--primary-500);box-shadow:0 0 0 3px var(--primary-50)}
.row2{display:grid;grid-template-columns:1fr 1fr;gap:11px}
.btn{appearance:none;border:1px solid transparent;border-radius:var(--radius-sm);font-family:inherit;font-size:13px;font-weight:600;padding:10px 15px;cursor:pointer;transition:background .12s,border-color .12s,color .12s;display:inline-flex;align-items:center;justify-content:center;gap:7px}
.btn-primary{background:var(--primary-600);color:#fff;width:100%}
.btn-primary:hover{background:var(--primary-500)}
.btn-primary:disabled{background:#c3c6cf;cursor:not-allowed}
.btn-ghost{background:var(--surface);border-color:var(--border);color:var(--text-700)}
.btn-ghost:hover{background:var(--surface-2)}
.btn-sm{padding:7px 11px;font-size:12px}
.examples{display:flex;gap:6px;flex-wrap:wrap;margin-top:2px}
.chip{font-size:11.5px;padding:4px 9px;border-radius:999px;border:1px solid var(--border);background:var(--surface-2);color:var(--text-700);cursor:pointer}
.chip:hover{border-color:var(--primary-500);color:var(--primary-600);background:var(--primary-50)}
/* ---- job tracking ---- */
.empty{padding:38px 20px;text-align:center;color:var(--text-400)}
.empty .big{font-size:30px;margin-bottom:8px;opacity:.5}
.job-meta{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:16px}
.job-id{font-family:var(--mono);font-size:12px;background:var(--surface-2);border:1px solid var(--border-2);padding:4px 8px;border-radius:6px;color:var(--text-700)}
.status-pill{display:inline-flex;align-items:center;gap:6px;padding:5px 11px;border-radius:999px;font-size:12px;font-weight:700}
.status-pill.PENDING{background:var(--warn-50);color:var(--warn-600)}
.status-pill.RUNNING{background:var(--run-50);color:var(--run-600)}
.status-pill.DONE{background:var(--ok-50);color:var(--ok-600)}
.status-pill.DEAD{background:var(--dead-50);color:var(--dead-600)}
.status-pill .spin{width:11px;height:11px;border:2px solid currentColor;border-right-color:transparent;border-radius:50%;animation:spin .7s linear infinite}
@keyframes spin{to{transform:rotate(360deg)}}
.outcome-hero{display:flex;align-items:flex-end;gap:14px;padding:16px;border-radius:var(--radius-sm);background:linear-gradient(135deg,#f7f8ff,#f0f3ff);border:1px solid var(--border-2);margin-bottom:16px}
.outcome-hero.nf{background:linear-gradient(135deg,#fbfbfc,#f4f5f7)}
.price-big{font-size:32px;font-weight:800;letter-spacing:-.02em;line-height:1;font-variant-numeric:tabular-nums}
.price-big .won{font-size:18px;font-weight:700;color:var(--text-500);margin-left:2px}
.src-tag{font-size:11px;font-weight:700;padding:3px 8px;border-radius:6px;color:#fff;letter-spacing:.02em;white-space:nowrap}
.src-tag.naver{background:var(--naver)} .src-tag.coupang{background:var(--coupang)}
.src-tag.gmarket{background:#00b25a} .src-tag.auction{background:#e60012} .src-tag.st11{background:#ff0038}
.src-tag.fallback{position:relative}
.src-tag.fallback::after{content:"크롤";position:absolute;top:-6px;right:-6px;font-size:8px;background:#1a1d24;color:#fff;padding:1px 3px;border-radius:4px;letter-spacing:0}
.ship-tag{display:inline-flex;align-items:center;gap:4px;font-size:10.5px;font-weight:700;padding:2px 7px;border-radius:5px;border:1px solid transparent;white-space:nowrap}
.ship-tag.rocket{background:#eef4ff;color:#2f6fed;border-color:#d5e3ff}
.ship-tag.rocket_merchant{background:#f3eeff;color:#7a4fe0;border-color:#e3d8ff}
.ship-tag.free{background:var(--ok-50);color:var(--ok-600)}
.ship-tag.paid{background:#fbecec;color:var(--dead-600)}
.ship-tag.unknown{background:var(--surface-2);color:var(--text-400);border-color:var(--border-2)}
.outcome-label{font-size:11px;font-weight:700;color:var(--text-500);text-transform:uppercase;letter-spacing:.04em;margin-bottom:6px}
/* funnel / stages */
.stages{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:16px}
.stage{flex:1;min-width:82px;background:var(--surface-2);border:1px solid var(--border-2);border-radius:var(--radius-sm);padding:10px;text-align:center;position:relative}
.stage .st-name{font-size:11px;color:var(--text-500);font-weight:600;margin-bottom:4px;text-transform:capitalize}
.stage .st-io{font-size:15px;font-weight:800;font-variant-numeric:tabular-nums}
.stage .st-io .arr{color:var(--text-400);font-weight:500;margin:0 3px}
.stage .st-drop{font-size:10.5px;color:var(--coupang);font-weight:600;margin-top:2px}
.src-counts{display:flex;gap:8px;margin-bottom:16px}
.src-count{flex:1;border:1px solid var(--border-2);border-radius:var(--radius-sm);padding:10px 12px;background:var(--surface-2)}
.src-count .lbl{font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.03em;margin-bottom:3px}
.src-count .lbl.naver{color:var(--naver)} .src-count .lbl.coupang{color:var(--coupang)}
.src-count .n{font-size:17px;font-weight:800;font-variant-numeric:tabular-nums}
.src-count .err{font-size:11px;color:var(--dead-600);font-weight:600}
/* 몰별 최저가 분해 */
.mall-bars{display:flex;flex-direction:column;gap:7px;margin-bottom:16px}
.mall-bar{display:flex;align-items:center;gap:10px}
.mall-bar .mname{width:112px;flex-shrink:0;font-size:12px;font-weight:600;color:var(--text-700);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:flex;align-items:center;gap:5px}
.mall-bar .mname .sdot{width:7px;height:7px;border-radius:50%;flex-shrink:0}
.mall-bar .track{flex:1;height:22px;background:var(--surface-2);border-radius:6px;position:relative;overflow:hidden}
.mall-bar .fill{position:absolute;left:0;top:0;bottom:0;border-radius:6px;opacity:.16}
.mall-bar .mprice{position:absolute;right:8px;top:0;bottom:0;display:flex;align-items:center;font-size:12px;font-weight:700;font-variant-numeric:tabular-nums;color:var(--text-900)}
.mall-bar.best .mprice{color:var(--ok-600)}
.mall-bar .badge-best{position:absolute;left:8px;top:0;bottom:0;display:flex;align-items:center;font-size:10px;font-weight:800;color:var(--ok-600)}
.sec-title{font-size:12px;font-weight:700;color:var(--text-700);margin:0 0 9px;display:flex;align-items:center;gap:7px}
.sec-title .cnt{font-size:11px;color:var(--text-400);font-weight:600}
/* 검색 원가 계측 */
.metrics{display:grid;grid-template-columns:repeat(4,1fr);gap:8px;margin-bottom:16px}
@media (max-width:520px){.metrics{grid-template-columns:repeat(2,1fr)}}
.metric{border:1px solid var(--border-2);border-radius:var(--radius-sm);padding:10px 11px;background:var(--surface-2)}
.metric .mk{font-size:10.5px;font-weight:700;color:var(--text-400);text-transform:uppercase;letter-spacing:.03em;margin-bottom:4px}
.metric .mv{font-size:16px;font-weight:800;font-variant-numeric:tabular-nums;line-height:1.1}
.metric .mv small{font-size:11px;font-weight:600;color:var(--text-500)}
.metric .msub{font-size:10.5px;color:var(--text-400);font-weight:600;margin-top:2px}
table{width:100%;border-collapse:collapse;font-size:13px}
th{text-align:left;font-size:11px;font-weight:700;color:var(--text-500);text-transform:uppercase;letter-spacing:.03em;padding:8px 10px;border-bottom:1px solid var(--border-2)}
td{padding:9px 10px;border-bottom:1px solid var(--border-2);vertical-align:top}
tr:last-child td{border-bottom:none}
.price-cell{font-weight:700;font-variant-numeric:tabular-nums;white-space:nowrap}
.name-cell{max-width:340px}
.name-cell a{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.rank{display:inline-grid;place-items:center;width:20px;height:20px;border-radius:6px;background:var(--surface-2);border:1px solid var(--border-2);font-size:11px;font-weight:800;color:var(--text-500)}
.rank.top{background:var(--primary-50);color:var(--primary-600);border-color:transparent}
/* ---- chart ---- */
.chart-controls{display:flex;gap:9px;align-items:flex-end;margin-bottom:16px}
.chart-controls .field{flex:1;margin:0}
.chart-wrap{position:relative;width:100%;overflow-x:auto}
svg.chart{display:block;width:100%;height:auto;min-width:520px}
.legend{display:flex;gap:16px;margin-top:12px;flex-wrap:wrap}
.legend-item{display:flex;align-items:center;gap:7px;font-size:12px;font-weight:600;color:var(--text-700);cursor:pointer;user-select:none}
.legend-item .swatch{width:14px;height:3px;border-radius:2px}
.legend-item.off{opacity:.35}
.legend-item .swatch.dashed{background:none!important;border-top:2px dashed}
.chart-tip{position:absolute;pointer-events:none;background:#1a1d24;color:#fff;padding:8px 10px;border-radius:8px;font-size:11.5px;box-shadow:0 6px 24px rgba(0,0,0,.2);opacity:0;transition:opacity .1s;z-index:5;min-width:130px;transform:translate(-50%,-115%)}
.chart-tip .tt-time{color:#9aa1ac;font-size:10.5px;margin-bottom:5px}
.chart-tip .tt-row{display:flex;justify-content:space-between;gap:12px;font-variant-numeric:tabular-nums}
.chart-tip .tt-row .k{display:flex;align-items:center;gap:6px}
.chart-tip .tt-dot{width:7px;height:7px;border-radius:50%}
/* ---- misc ---- */
.toast-wrap{position:fixed;bottom:22px;right:22px;z-index:100;display:flex;flex-direction:column;gap:9px}
.toast{background:#1a1d24;color:#fff;padding:12px 16px;border-radius:10px;font-size:13px;box-shadow:0 8px 30px rgba(0,0,0,.24);display:flex;align-items:center;gap:9px;animation:slideIn .25s ease;max-width:340px}
.toast.err{background:#b91c1c} .toast.ok{background:#0f9d58}
@keyframes slideIn{from{transform:translateX(20px);opacity:0}to{transform:translateX(0);opacity:1}}
.muted{color:var(--text-400)}
.spin-inline{width:13px;height:13px;border:2px solid var(--border);border-right-color:var(--primary-500);border-radius:50%;display:inline-block;animation:spin .7s linear infinite;vertical-align:-2px}
.cfg-row{display:flex;align-items:center;gap:8px;font-size:12px;color:var(--text-500)}
.cfg-row input{width:auto;flex:1;padding:6px 9px;font-size:12px;font-family:var(--mono)}
code{font-family:var(--mono);font-size:12px;background:var(--surface-2);padding:1px 5px;border-radius:4px;border:1px solid var(--border-2)}
</style>
</head>
<body>
<header class="top">
<div class="top-inner">
<div class="brand">
<div class="logo">₩</div>
<div>LPS 최저가 검색 콘솔
<small>임시 프론트엔드 · API 통신 확인용</small>
</div>
</div>
<div class="top-spacer"></div>
<div class="stat-badges" id="queueBadges">
<span class="badge pending"><span class="dot"></span>PENDING <b>–</b></span>
<span class="badge running"><span class="dot"></span>RUNNING <b>–</b></span>
<span class="badge done"><span class="dot"></span>DONE <b>–</b></span>
<span class="badge dead"><span class="dot"></span>DEAD <b>–</b></span>
</div>
<div class="health"><span class="pulse" id="healthDot"></span><span id="healthTxt">확인 중…</span></div>
</div>
</header>
<main>
<!-- ============ LEFT: 검색 요청 ============ -->
<section>
<div class="card">
<div class="card-head"><span class="idx">1</span><h2>검색 요청</h2><span class="hint">POST /v1/lps/search</span></div>
<div class="card-body">
<div class="field">
<label>빠른 예시</label>
<div class="examples" id="examples"></div>
</div>
<form id="searchForm">
<div class="row2">
<div class="field">
<label>상품 코드 <span class="req">*</span> <span class="sub">이력 키</span></label>
<input name="product_code" required placeholder="T1" autocomplete="off"/>
</div>
<div class="field">
<label>우선순위 <span class="sub">job_type</span></label>
<select name="job_type">
<option value="new_product">new_product · 1 (최우선)</option>
<option value="manual" selected>manual · 2 (기본)</option>
<option value="partner">partner · 3</option>
<option value="batch">batch · 4</option>
</select>
</div>
</div>
<div class="field">
<label>상품명 <span class="req">*</span></label>
<input name="product_name" required placeholder="맥심 모카골드 커피믹스" autocomplete="off"/>
</div>
<div class="field">
<label>규격 <span class="sub">자유 서술 — AI가 해석</span></label>
<input name="specification" placeholder="1박스, 160개입" autocomplete="off"/>
</div>
<div class="row2">
<div class="field">
<label>모델명 <span class="sub">선택</span></label>
<input name="model" placeholder="모카골드" autocomplete="off"/>
</div>
<div class="field">
<label>제조사 <span class="sub">선택</span></label>
<input name="company" placeholder="동서식품" autocomplete="off"/>
</div>
</div>
<div class="field">
<label>현재가 <span class="sub">있으면 가격밴드 필터 기준</span></label>
<input name="price" inputmode="numeric" placeholder="25000" autocomplete="off"/>
</div>
<button type="submit" class="btn btn-primary" id="submitBtn">검색 요청 보내기</button>
</form>
</div>
</div>
<div class="card">
<div class="card-head"><h2>API 설정</h2><span class="hint">Base URL</span></div>
<div class="card-body">
<div class="cfg-row">
<input id="baseUrl" value="http://localhost:9600"/>
<button class="btn btn-ghost btn-sm" id="pingBtn">확인</button>
</div>
<p class="muted" style="margin:10px 0 0;font-size:11.5px">
이 페이지는 <code>:5173</code>에서 서빙되어야 CORS가 통과합니다 (<code>serve.sh</code> 참고).
</p>
</div>
</div>
</section>
<!-- ============ RIGHT: 결과 + 그래프 ============ -->
<section>
<!-- 작업 추적 / 상품 정보 -->
<div class="card">
<div class="card-head"><span class="idx">2</span><h2>작업 추적 &amp; 상품 정보</h2><span class="hint" id="jobHint">GET /v1/lps/jobs/{id}</span></div>
<div class="card-body" id="jobBody">
<div class="empty">
<div class="big">📦</div>
왼쪽에서 검색을 요청하면 여기에서<br/>진행 상태와 최저가 결과가 실시간으로 표시됩니다.
</div>
</div>
</div>
<!-- 최저가 이력 그래프 -->
<div class="card">
<div class="card-head"><span class="idx">3</span><h2>최저가 이력 그래프</h2><span class="hint">GET /v1/lps/products/{code}/history</span></div>
<div class="card-body">
<div class="chart-controls">
<div class="field">
<label>상품 코드</label>
<input id="histCode" placeholder="P1" autocomplete="off"/>
</div>
<button class="btn btn-ghost btn-sm" id="loadHistBtn" style="height:37px">이력 불러오기</button>
</div>
<div id="chartArea">
<div class="empty"><div class="big">📈</div>상품 코드를 입력하고 이력을 불러오세요.</div>
</div>
</div>
</div>
</section>
</main>
<div class="toast-wrap" id="toasts"></div>
<script>
"use strict";
const $ = (s,el=document)=>el.querySelector(s);
const $$ = (s,el=document)=>Array.from(el.querySelectorAll(s));
const base = ()=> $("#baseUrl").value.replace(/\/+$/,"");
const won = n => (n==null? "—" : Number(n).toLocaleString("ko-KR"));
const esc = s => (s==null?"":String(s)).replace(/[&<>"]/g,c=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"}[c]));
/* 배송 뱃지: shipping_type + shipping_fee → 라벨. 네이버는 항상 '배송비 별도'. */
function shipBadge(p){
const t=p.shipping_type, fee=p.shipping_fee;
if(p.source==="naver") return `<span class="ship-tag unknown" title="네이버 오픈API는 배송비 제외 상품가입니다">배송비 별도</span>`;
const map={
rocket:["rocket","🚀 로켓"], rocket_merchant:["rocket_merchant","🚀 판매자로켓"],
free:["free","무료배송"], paid:["paid", fee!=null?`배송비 ${won(fee)}원`:"유료배송"],
};
if(t && map[t]) return `<span class="ship-tag ${map[t][0]}">${map[t][1]}</span>`;
return `<span class="ship-tag unknown">배송비 미확인</span>`;
}
/* 실구매가(상품가+확정 배송비). 미확인이면 null. */
function totalPrice(p){ return (typeof p.shipping_fee==="number") ? p.price+p.shipping_fee : null; }
/* 소스 메타: 표시명·색상. gmarket/auction/st11 은 네이버 폴백 크롤 소스. */
const SRC = {
naver: {label:"NAVER", color:"#03c75a", crawl:false},
coupang:{label:"COUPANG",color:"#f0455b", crawl:false},
gmarket:{label:"G마켓", color:"#00b25a", crawl:true},
auction:{label:"옥션", color:"#e60012", crawl:true},
st11: {label:"11번가", color:"#ff0038", crawl:true},
};
function srcColor(s){ return (SRC[s]||{}).color || "#6b7280"; }
function srcTag(p){
const m=SRC[p.source]||{label:p.source};
return `<span class="src-tag ${p.source}${m.crawl?' fallback':''}" title="${m.crawl?'네이버 미커버 → 실사이트 크롤':''}">${esc(m.label)}</span>`;
}
/* 판매몰 표시명: 네이버 가격비교(mall='네이버')는 '여러 판매자 최저가 롤업'임을 명시. */
function mallLabel(p){
if(p.source==="coupang") return "쿠팡";
const m=p.mall_name||(SRC[p.source]||{}).label||"기타";
return (m==="네이버") ? "네이버 가격비교" : m;
}
function isCatalog(p){ return p.source==="naver" && (p.mall_name==="네이버"); }
/* ---------- toast ---------- */
function toast(msg,type=""){
const t=document.createElement("div"); t.className="toast "+type; t.textContent=msg;
$("#toasts").appendChild(t); setTimeout(()=>{t.style.opacity="0";t.style.transition="opacity .3s";setTimeout(()=>t.remove(),300)},3200);
}
/* ---------- fetch helper ---------- */
async function api(path,opts){
const r = await fetch(base()+path, Object.assign({headers:{"Content-Type":"application/json"}},opts));
const txt = await r.text();
let data; try{ data = txt? JSON.parse(txt):{} }catch(e){ throw new Error("응답 파싱 실패: "+txt.slice(0,120)) }
if(!r.ok) throw new Error("HTTP "+r.status+" · "+(data?.result?.desc||txt.slice(0,120)));
if(data?.result && data.result.success===false) throw new Error(data.result.desc||"API 실패");
return data;
}
/* ---------- health + queue polling ---------- */
async function refreshHealth(){
try{
const t = await api("/healthz");
$("#healthDot").className="pulse up";
$("#healthTxt").textContent = "온라인 · "+(typeof t==="string"?t.replace("T"," ").slice(0,19):"");
}catch(e){
$("#healthDot").className="pulse";
$("#healthTxt").textContent="오프라인";
}
}
async function refreshQueue(){
try{
const d = await api("/v1/lps/queue/stats");
const c = d.counts||{};
const b = $$("#queueBadges .badge b");
b[0].textContent=c.PENDING??0; b[1].textContent=c.RUNNING??0; b[2].textContent=c.DONE??0; b[3].textContent=c.DEAD??0;
}catch(e){}
}
function poll(){ refreshHealth(); refreshQueue(); }
poll(); setInterval(poll, 4000);
$("#pingBtn").addEventListener("click",()=>{ refreshHealth(); refreshQueue(); toast("연결 확인 중…"); });
/* ---------- examples ---------- */
const EXAMPLES = [
{label:"맥심 커피", product_code:"T1", product_name:"맥심 모카골드 커피믹스", specification:"1박스, 160개입", company:"동서식품", model:"모카골드", price:"25000"},
{label:"신라면", product_code:"T2", product_name:"농심 신라면", specification:"1박스 40개입", company:"농심", price:"22000"},
{label:"P1 (샘플이력)", product_code:"P1", product_name:"테스트 상품 P1", specification:"", price:""},
];
const exWrap = $("#examples");
EXAMPLES.forEach(ex=>{
const c=document.createElement("button"); c.type="button"; c.className="chip"; c.textContent=ex.label;
c.addEventListener("click",()=>{ for(const k in ex){ if(k==="label")continue; const f=$(`[name=${k}]`); if(f) f.value=ex[k]; } toast("예시 채움: "+ex.label); });
exWrap.appendChild(c);
});
/* ---------- submit search ---------- */
let pollTimer=null;
$("#searchForm").addEventListener("submit", async e=>{
e.preventDefault();
const fd=new FormData(e.target); const item={};
fd.forEach((v,k)=> item[k]=String(v).trim());
if(!item.product_code||!item.product_name){ toast("상품 코드와 상품명은 필수입니다","err"); return; }
const btn=$("#submitBtn"); btn.disabled=true; btn.innerHTML='<span class="spin-inline"></span> 요청 중…';
try{
const d = await api("/v1/lps/search",{method:"POST",body:JSON.stringify({data:[item]})});
const it = (d.items||[])[0]||{};
if(it.duplicated){ toast("이미 처리 중인 활성 작업이라 중복 접수 생략됨","err"); }
else if(it.job_id){ toast("접수 완료 · 추적 시작","ok"); $("#histCode").value=item.product_code; trackJob(it.job_id, item); }
else { toast("접수됐지만 job_id가 없습니다","err"); }
}catch(err){ toast(err.message,"err"); }
finally{ btn.disabled=false; btn.textContent="검색 요청 보내기"; }
});
/* ---------- job tracking (poll until DONE/DEAD) ---------- */
function trackJob(jobId, submitted){
if(pollTimer) clearInterval(pollTimer);
$("#jobHint").textContent = "job "+jobId.slice(0,8)+"…";
let tries=0;
const tick = async ()=>{
tries++;
try{
const d = await api("/v1/lps/jobs/"+jobId);
renderJob(d, submitted);
if(d.status==="DONE"||d.status==="DEAD"){
clearInterval(pollTimer); pollTimer=null;
if(d.status==="DONE" && d.output?.outcome==="found") loadHistory(submitted.product_code);
}
}catch(err){
renderJobError(err.message);
if(tries>3){ clearInterval(pollTimer); pollTimer=null; }
}
};
tick(); pollTimer=setInterval(tick, 1500);
}
function renderJobError(msg){ $("#jobBody").innerHTML=`<div class="empty"><div class="big">⚠️</div>${esc(msg)}</div>`; }
function renderJob(d, submitted){
const st=d.status||"PENDING";
const o=d.output||null;
const spinning=(st==="PENDING"||st==="RUNNING");
let html = `<div class="job-meta">
<span class="status-pill ${st}">${spinning?'<span class="spin"></span>':''}${st}</span>
<span class="job-id">${esc(d.job_id||"")}</span>
<span class="muted" style="font-size:12px">시도 ${d.attempts??0}/${d.max_attempts??"–"}</span>
</div>`;
if(!o && spinning){
html += `<div class="empty" style="padding:26px"><span class="spin-inline"></span>&nbsp; 워커가 네이버·쿠팡을 검색하고 AI가 같은 상품을 판정하는 중…
<div class="muted" style="margin-top:8px;font-size:11.5px">쿠팡 크롤링은 수 초~수십 초 걸릴 수 있습니다.</div></div>`;
$("#jobBody").innerHTML=html; return;
}
if(d.last_error && st==="DEAD"){
html += `<div class="outcome-hero nf"><div><div class="outcome-label">작업 실패 (DEAD)</div><div class="muted" style="font-size:13px">${esc(d.last_error)}</div></div></div>`;
}
if(o){
const found = o.outcome==="found";
const low = o.lowest;
// hero
html += `<div class="outcome-hero ${found?'':'nf'}">
<div style="flex:1">
<div class="outcome-label">${found?'최저가 발견':(o.cached?'네거티브 캐시 (최근 없음)':'같은 상품 없음 · not_found')}</div>
${ found && low ? `<div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap">
<div class="price-big">${won(low.price)}<span class="won">원</span></div>
${srcTag(low)}
${shipBadge(low)}
</div>
<div class="muted" style="font-size:11.5px;margin-top:5px">판매몰 <b style="color:var(--text-700)">${esc(mallLabel(low))}</b>${ isCatalog(low)?` <span title="여러 판매자 중 최저가 롤업 · 배송비 제외">· 여러 판매자 최저가</span>`:``}</div>
${ totalPrice(low)!=null && low.shipping_fee>0 ? `<div class="muted" style="font-size:11.5px;margin-top:2px">실구매가(배송비 포함) <b style="color:var(--text-700)">${won(totalPrice(low))}원</b></div>`:``}
<div class="muted" style="font-size:12px;margin-top:6px">${esc(low.name||"")}</div>`
: `<div class="price-big muted" style="font-size:22px">—</div>` }
</div>
<div style="text-align:right">
<div class="muted" style="font-size:11px">검색어</div>
<div style="font-weight:600;font-size:13px">${esc(o.query||submitted?.product_name||"")}</div>
<div class="muted" style="font-size:11px;margin-top:4px">${o.rounds_tried??0} 라운드${o.round?' · '+esc(o.round):''}</div>
</div>
</div>`;
// source counts
if(o.sources){
html += `<div class="src-counts">`;
for(const src of ["naver","coupang"]){
const s=o.sources[src];
html += `<div class="src-count"><div class="lbl ${src}">${src}</div>`;
if(s && s.error!==undefined) html+=`<div class="err">차단/오류</div>`;
else html += `<div class="n">${s?.count??0}<span class="muted" style="font-size:12px;font-weight:600"> 건</span></div>`;
html+=`</div>`;
}
html += `</div>`;
}
// pipeline stages
if(o.stages && o.stages.length){
html += `<div class="sec-title">파이프라인 단계 <span class="cnt">몇 건이 걸러졌나</span></div><div class="stages">`;
o.stages.forEach(s=>{
const drop=(s.in??0)-(s.out??0);
html += `<div class="stage"><div class="st-name">${esc(s.stage)}</div>
<div class="st-io">${s.in??0}<span class="arr">→</span>${s.out??0}</div>
${drop>0?`<div class="st-drop">−${drop}</div>`:``}</div>`;
});
html += `</div>`;
}
// 검색 원가 계측(리소스/비용/시간)
const mt=o.metrics;
if(mt){
const fmtBytes=b=>{const kb=(b||0)/1024; return kb>=1024?(kb/1024).toFixed(1)+" MB":Math.round(kb)+" KB";};
const c=mt.cost||{}; const total=c.total_usd??(mt.ai?.est_cost_usd||0);
const fc=v=>"$"+(v||0).toFixed((v||0)<0.01?6:4);
const srcMs=mt.source_ms||{};
const srcTxt=Object.entries(srcMs).map(([s,ms])=>`${(SRC[s]||{}).label||s} ${(ms/1000).toFixed(1)}s`).join(" · ");
const crawledTxt=(mt.crawl?.malls_crawled||[]).length?' · 크롤 '+mt.crawl.malls_crawled.map(s=>(SRC[s]||{}).label||s).join(','):'';
html += `<div class="sec-title">검색 원가 <span class="cnt">이 검색 1건이 쓴 리소스·비용·시간</span></div>
<div class="metrics">
<div class="metric"><div class="mk">소요 시간</div><div class="mv">${(mt.duration_ms/1000).toFixed(1)}<small>s</small></div>${srcTxt?`<div class="msub" title="${esc(srcTxt)}">${esc(srcTxt.length>34?srcTxt.slice(0,34)+'…':srcTxt)}</div>`:``}</div>
<div class="metric"><div class="mk">총 비용</div><div class="mv">${fc(total)}</div><div class="msub" title="AI(OpenAI) + DECODO(프록시 대역폭)">AI ${fc(c.ai_usd)} · DECODO ${fc(c.proxy_usd)}</div></div>
<div class="metric"><div class="mk">AI 토큰</div><div class="mv">${won((mt.ai?.prompt_tokens||0)+(mt.ai?.completion_tokens||0))}</div><div class="msub">${mt.ai?.calls||0}회 · in ${won(mt.ai?.prompt_tokens||0)}/out ${won(mt.ai?.completion_tokens||0)}</div></div>
<div class="metric"><div class="mk">크롤 트래픽</div><div class="mv">${fmtBytes(mt.crawl?.html_bytes)}</div><div class="msub" title="프록시 경유 ${fmtBytes(mt.crawl?.proxy_bytes)} (DECODO 과금분)">${mt.crawl?.fetches||0} fetch · 프록시 ${fmtBytes(mt.crawl?.proxy_bytes)}${crawledTxt}</div></div>
</div>`;
}
// 몰별 최저가 분해 (네이버 payload에 이미 들어온 G마켓/옥션/11번가 등을 추가요청 0으로 노출)
const byMall=o.by_mall||[];
if(byMall.length>1){
const maxP=Math.max(...byMall.map(m=>m.price));
html += `<div class="sec-title">몰별 최저가 <span class="cnt">네이버 포함 몰 + 미커버 몰은 직접 크롤(크롤 뱃지)</span></div><div class="mall-bars">`;
byMall.forEach((m,i)=>{
const w=Math.max(8,Math.round(m.price/maxP*100));
const color=srcColor(m.source);
html += `<div class="mall-bar ${i===0?'best':''}">
<div class="mname"><span class="sdot" style="background:${color}"></span>${esc(mallLabel(m))}</div>
<div class="track"><div class="fill" style="width:${w}%;background:${color}"></div>
${i===0?`<div class="badge-best">최저</div>`:``}
<div class="mprice">${won(m.price)}원</div></div>
</div>`;
});
html += `</div>`;
}
// top-N product list
const top=o.top||[];
if(top.length){
html += `<div class="sec-title">같은 상품 최저가 <span class="cnt">상위 ${top.length}개 · 가격은 상품가 기준</span></div>
<table><thead><tr><th>#</th><th>소스 · 판매몰</th><th>상품명</th><th>배송</th><th style="text-align:right">상품가</th></tr></thead><tbody>`;
top.forEach((p,i)=>{
const tot=totalPrice(p);
html += `<tr>
<td><span class="rank ${i===0?'top':''}">${i+1}</span></td>
<td style="white-space:nowrap">${srcTag(p)}<div class="muted" style="font-size:11px;font-weight:600;margin-top:3px">${esc(mallLabel(p))}</div></td>
<td class="name-cell">${p.detail_url?`<a href="${esc(p.detail_url)}" target="_blank" rel="noopener">${esc(p.name)}</a>`:esc(p.name)}</td>
<td>${shipBadge(p)}</td>
<td class="price-cell" style="text-align:right">${won(p.price)}원${ tot!=null&&p.shipping_fee>0?`<div class="muted" style="font-size:10.5px;font-weight:600">+배송 ${won(tot)}</div>`:``}</td>
</tr>`;
});
html += `</tbody></table>`;
}
}
$("#jobBody").innerHTML=html;
}
/* ---------- price history chart (dependency-free SVG) ---------- */
const SERIES=[
{key:"naver", label:"네이버", color:"var(--naver)", raw:"#03c75a", dash:false},
{key:"coupang", label:"쿠팡", color:"var(--coupang)", raw:"#f0455b", dash:false},
{key:"final", label:"최종최저", color:"var(--final)", raw:"#4f46e5", dash:true},
];
const hidden=new Set();
let lastPoints=[];
$("#loadHistBtn").addEventListener("click",()=> loadHistory($("#histCode").value.trim()));
$("#histCode").addEventListener("keydown",e=>{ if(e.key==="Enter") loadHistory(e.target.value.trim()); });
async function loadHistory(code){
if(!code){ toast("상품 코드를 입력하세요","err"); return; }
$("#histCode").value=code;
$("#chartArea").innerHTML=`<div class="empty" style="padding:30px"><span class="spin-inline"></span> 이력 불러오는 중…</div>`;
try{
const d = await api(`/v1/lps/products/${encodeURIComponent(code)}/history?limit=200`);
lastPoints = d.points||[];
renderChart(lastPoints, code);
}catch(err){ $("#chartArea").innerHTML=`<div class="empty"><div class="big">⚠️</div>${esc(err.message)}</div>`; }
}
function renderChart(points, code){
if(!points.length){ $("#chartArea").innerHTML=`<div class="empty"><div class="big">🗒️</div><b>${esc(code)}</b> 상품의 이력이 아직 없습니다.<div class="muted" style="margin-top:6px;font-size:12px">검색이 완료되면 스냅샷이 쌓입니다.</div></div>`; return; }
const W=760,H=300,padL=62,padR=18,padT=18,padB=46;
const iw=W-padL-padR, ih=H-padT-padB;
const vals=[]; points.forEach(p=>SERIES.forEach(s=>{ if(!hidden.has(s.key)&&p[s.key]!=null) vals.push(p[s.key]); }));
let min = vals.length?Math.min(...vals):0, max=vals.length?Math.max(...vals):1;
if(min===max){ min=min*0.9; max=max*1.1||1; }
const pad=(max-min)*0.12; min=Math.max(0,min-pad); max=max+pad;
const n=points.length;
const X = i => padL + (n===1? iw/2 : iw*i/(n-1));
const Y = v => padT + ih*(1-(v-min)/(max-min));
// y ticks
const ticks=5; let yAxis="";
for(let t=0;t<=ticks;t++){ const v=min+(max-min)*t/ticks; const y=Y(v);
yAxis+=`<line x1="${padL}" y1="${y}" x2="${W-padR}" y2="${y}" stroke="var(--border-2)" stroke-width="1"/>`;
yAxis+=`<text x="${padL-8}" y="${y+4}" text-anchor="end" font-size="10" fill="var(--text-400)">${won(Math.round(v))}</text>`;
}
// x labels (sparse)
let xAxis=""; const step=Math.ceil(n/6);
points.forEach((p,i)=>{ if(i%step!==0 && i!==n-1) return; const x=X(i);
const t=(p.triggered_at||"").replace("T"," ").slice(5,16);
xAxis+=`<text x="${x}" y="${H-padB+18}" text-anchor="middle" font-size="9.5" fill="var(--text-400)">${esc(t)}</text>`;
xAxis+=`<line x1="${x}" y1="${padT}" x2="${x}" y2="${padT+ih}" stroke="var(--border-2)" stroke-width="1" stroke-dasharray="2 3" opacity=".5"/>`;
});
// lines + dots
let paths="",dots="";
SERIES.forEach(s=>{
if(hidden.has(s.key)) return;
// build segments skipping nulls
let seg=[];
const flush=()=>{ if(seg.length>1){ paths+=`<polyline points="${seg.map(pt=>pt.x+","+pt.y).join(" ")}" fill="none" stroke="${s.raw}" stroke-width="${s.dash?2.5:2}" ${s.dash?'stroke-dasharray="6 4"':''} stroke-linejoin="round" stroke-linecap="round"/>`; } seg=[]; };
points.forEach((p,i)=>{ const v=p[s.key]; if(v==null){ flush(); return; } const x=X(i),y=Y(v); seg.push({x,y});
dots+=`<circle cx="${x}" cy="${y}" r="3" fill="#fff" stroke="${s.raw}" stroke-width="2"/>`; });
flush();
});
// hover columns
let hover="";
points.forEach((p,i)=>{ const x=X(i);
hover+=`<rect x="${x-(iw/n/2||14)}" y="${padT}" width="${iw/n||28}" height="${ih}" fill="transparent" data-i="${i}" class="hovcol"/>`;
hover+=`<line class="hovline" data-i="${i}" x1="${x}" y1="${padT}" x2="${x}" y2="${padT+ih}" stroke="var(--primary-500)" stroke-width="1" opacity="0"/>`;
});
$("#chartArea").innerHTML=`
<div class="chart-wrap">
<svg class="chart" viewBox="0 0 ${W} ${H}" preserveAspectRatio="xMidYMid meet">
${yAxis}${xAxis}${paths}${dots}${hover}
</svg>
<div class="chart-tip" id="chartTip"></div>
</div>
<div class="legend" id="legend"></div>
<p class="muted" style="font-size:11.5px;margin:12px 0 0">스냅샷 ${n}건 · 점선(최종최저)이 네이버·쿠팡 중 낮은 값을 따라갑니다. 값이 빈 구간은 그 소스에 상품이 없던 시점입니다.</p>
`;
// legend
const lg=$("#legend");
SERIES.forEach(s=>{
const el=document.createElement("div"); el.className="legend-item"+(hidden.has(s.key)?" off":"");
el.innerHTML=`<span class="swatch ${s.dash?'dashed':''}" style="${s.dash?`border-color:${s.raw}`:`background:${s.raw}`}"></span>${s.label}`;
el.addEventListener("click",()=>{ if(hidden.has(s.key))hidden.delete(s.key); else hidden.add(s.key); renderChart(lastPoints,code); });
lg.appendChild(el);
});
// hover interaction
const tip=$("#chartTip"), svg=$(".chart");
$$(".hovcol").forEach(col=>{
col.style.cursor="crosshair";
col.addEventListener("mouseenter",()=>{
const i=+col.dataset.i, p=points[i];
$$(".hovline").forEach(l=>l.setAttribute("opacity", (+l.dataset.i===i)?".5":"0"));
let rows="";
SERIES.forEach(s=>{ if(hidden.has(s.key)) return; const v=p[s.key];
rows+=`<div class="tt-row"><span class="k"><span class="tt-dot" style="background:${s.raw}"></span>${s.label}</span><span>${v==null?'—':won(v)+'원'}</span></div>`; });
tip.innerHTML=`<div class="tt-time">${esc((p.triggered_at||'').replace('T',' ').slice(0,19))} · ${esc(p.outcome||'')}</div>${rows}`;
// position
const bb=svg.getBoundingClientRect(); const scale=bb.width/W; const px=(X(i))*scale; const py=padT*scale+8;
tip.style.left=px+"px"; tip.style.top=py+"px"; tip.style.opacity="1";
});
col.addEventListener("mouseleave",()=>{ tip.style.opacity="0"; $$(".hovline").forEach(l=>l.setAttribute("opacity","0")); });
});
}
</script>
</body>
</html>
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env bash
#
# LPS 임시 프론트엔드 서버 (대화형).
# CORS 때문에 반드시 :5173 에서 서빙해야 lps API(:9600) 호출이 통과한다.
# (lps/config.local.toml 의 cors_origins = http://localhost:5173)
#
set -euo pipefail
cd "$(dirname "$0")"
PORT=5173
echo "── LPS 임시 FE 서버 ──"
echo " API(:9600) 는 별도로 실행돼 있어야 합니다 (lps/run_local_server.sh + worker_main.py)."
echo ""
read -rp "포트 [${PORT}]: " p
PORT="${p:-$PORT}"
# 포트 정리
if lsof -ti:"$PORT" >/dev/null 2>&1; then
echo "[info] 포트 $PORT 사용 중 → 기존 프로세스 종료"
lsof -ti:"$PORT" | xargs kill 2>/dev/null || true
sleep 1
fi
echo "[run] http://localhost:${PORT} (Ctrl+C 로 종료)"
# 브라우저 자동 오픈 (mac)
( sleep 1; command -v open >/dev/null && open "http://localhost:${PORT}" ) &
exec python3 -m http.server "$PORT" --bind 127.0.0.1
+15
View File
@@ -0,0 +1,15 @@
.venv/
venv/
__pycache__/
*.pyc
.pytest_cache/
.git/
tests/
loadtest/
*.md
# Chrome 프로필(쿠키·cf_clearance 세션) — 이미지에 구우면 세션 유출 + 149MB 비대.
# 컨테이너는 빈 프로필로 시작해 웜업으로 쿠키를 만들고 volume(/profiles)에 영속한다.
.profiles/
# 시크릿(OpenAI·DECODO·네이버 키) — 이미지에 굽지 않는다. Dockerfile 이 example 을
# 복사해 넣고, 실값은 compose env 로 주입(server_configs 의 env override).
config/config.local.toml
+5
View File
@@ -0,0 +1,5 @@
# Chrome 프로필(쿠키·cf_clearance 세션) — 로컬 워커 영속 볼륨. 절대 커밋하지 않는다.
.profiles/
# 로컬 워커 하트비트/부하 테스트 로그(기본은 /tmp 지만 상대경로로 뜰 때 대비)
lps_worker_heartbeat
+27
View File
@@ -0,0 +1,27 @@
# LPS API 서버 이미지 — 요청 접수/조회만(브라우저 불필요, lean).
# 크롤은 별도 워커 이미지(Dockerfile.worker, Chromium+Xvfb)가 담당한다.
# 시크릿은 이미지에 굽지 않는다 — config 는 example(플레이스홀더)로 대체되고,
# 실제 값은 compose 의 env(DB_USER/DB_PASSWORD 등)로 주입된다(server_configs override).
FROM python:3.14-slim
WORKDIR /app
# 의존성 먼저 설치 (레이어 캐시 활용) — API 전용 경량 세트
COPY requirements-api.txt .
RUN pip install --no-cache-dir -r requirements-api.txt
COPY . .
# 시크릿 든 config.local.toml 은 .dockerignore 로 제외됨 → example(플레이스홀더)로 대체.
# 실값은 env 주입: DB_HOST/DB_USER/DB_PASSWORD/DB_NAME, PROCESS_COUNT, DB_CONNECTION_BUDGET …
RUN cp config/config.local.toml.example config/config.local.toml
# 항상 APP_ENV=local 로 실행 → config.local.toml(=example 사본) + env override.
ENV APP_ENV=local
EXPOSE 9600
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
CMD python -c "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:9600/healthz', timeout=4).status==200 else 1)"
CMD ["python", "web_main.py"]
+38
View File
@@ -0,0 +1,38 @@
# LPS 워커 이미지 — 크롤용 **헤드풀 Chromium + 가상 디스플레이(Xvfb)**.
# headless Chrome 은 Akamai(쿠팡)·Cloudflare Turnstile(G마켓/옥션)에 탐지돼 통과 못 함(실측 확인).
# → 컨테이너에선 Xvfb(가상 프레임버퍼)로 headful Chromium 을 실행한다.
#
# 빌드/실행:
# docker compose build lps-worker && docker compose up -d lps-worker
# 스텔스 참고: 로컬 Mac 은 실제 Chrome(channel=chrome), 컨테이너는 시스템 chromium(executable_path).
# 프로덕션에서 stealth 가 부족하면 amd64 이미지에 google-chrome-stable 설치 후 LPS_CHROME_CHANNEL=chrome 로 전환.
FROM python:3.14-slim
# chromium(런타임 의존성 apt 가 자동 해결) + Xvfb + 한글 폰트
RUN apt-get update && apt-get install -y --no-install-recommends \
chromium xvfb xauth fonts-nanum ca-certificates \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
# 시크릿 든 config.local.toml 은 .dockerignore 로 제외됨 → example(플레이스홀더)로 대체.
# 실값은 compose env 로 주입: DB_*, OPENAI_API_KEY, DECODO_*(포트 포함), NAVER_KEYS.
RUN cp config/config.local.toml.example config/config.local.toml
ENV APP_ENV=local \
PYTHONUNBUFFERED=1 \
LPS_CHROME_EXECUTABLE=/usr/bin/chromium \
DISPLAY=:99 \
LPS_HEARTBEAT_FILE=/tmp/lps_worker_heartbeat
# 하트비트 신선도(<120s)로 행/좀비 워커 감지. start-period 는 웜업(브라우저 기동) 여유.
HEALTHCHECK --interval=30s --timeout=8s --start-period=120s --retries=3 \
CMD python -c "import os,time,sys; p=os.environ['LPS_HEARTBEAT_FILE']; sys.exit(0 if os.path.exists(p) and time.time()-os.path.getmtime(p)<120 else 1)"
# Xvfb(가상 디스플레이)를 백그라운드로 띄우고 python 을 exec 로 승계 실행.
# → 헤드풀 Chromium 이 :99 에 뜨고, 워커 로그는 그대로 docker logs 로 나온다(xvfb-run 은 로그를 삼킴).
CMD ["bash", "-c", "Xvfb :99 -screen 0 1920x1080x24 -nolisten tcp >/dev/null 2>&1 & sleep 1; exec python worker_main.py"]
Loaded 100 of 369 files, more files were not shown because too many files have changed in this diff. Show more