feat(backend): 협상 채팅(chat) API + agent 위임
- /v1/negotiation/sessions/{id}/chat/{init,messages,send} 추가
- agent(9500) 위임 어댑터(IAgentClient) + mock(use_mock) 격리 → agent 미연동 시 1402 graceful degrade
- negotiation.chats 메시지 영속화(meta JSONB) + 종료 시 세션 입찰/거부 확정(단일 트랜잭션)
- 동시전송 가드(유저 메시지 pre-claim/CHAT_IN_PROGRESS) + 실패 시 롤백, 마감/만료 분기, init 만료 정리
- ChatSender enum, chat 에러코드(1400~1403), chats ORM 모델, AgentConfig
- 테스트 10건(test_chat.py), AGENT_INTEGRATION.md 연동 규약 문서
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
d199c1dec1
commit
dcce82a630
14 files changed
+1124
-2
No files matched your search
@@ -0,0 +1,57 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
from fastapi.security import HTTPAuthorizationCredentials
|
||||
|
||||
from common.models.gmodel import UserInfo
|
||||
from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse, security
|
||||
from services.chat_service import ChatService
|
||||
from .chat_protocol import Req_ChatSend, Res_ChatInit, Res_ChatMessages, Res_ChatSend
|
||||
|
||||
router = APIRouter(prefix="/v1/negotiation", tags=["Negotiation Chat"], responses={404: {"description": "Not found"}})
|
||||
|
||||
|
||||
@router.get(
|
||||
path="/sessions/{session_id}/chat/init",
|
||||
response_model=Res_ChatInit,
|
||||
summary="채팅 진입(상품·견적 메타)",
|
||||
description="채팅 화면 진입용. 상품/견적 정보 + 현재 세션 상태 + 마감 시각(타이머)을 반환한다. 소유(공급사) 검증.",
|
||||
)
|
||||
async def chat_init(
|
||||
session_id: str,
|
||||
user_info: UserInfo = Depends(IsValidAccessToken),
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
service: ChatService = Depends(),
|
||||
):
|
||||
return RemoveNoneResponse(await service.init(user_info, credentials.credentials, session_id))
|
||||
|
||||
|
||||
@router.get(
|
||||
path="/sessions/{session_id}/chat/messages",
|
||||
response_model=Res_ChatMessages,
|
||||
summary="대화 히스토리",
|
||||
description="세션의 대화 말풍선 목록(seq 오름차순). 비어 있고 협상중이면 오프닝 메시지를 생성해 포함한다.",
|
||||
)
|
||||
async def chat_messages(
|
||||
session_id: str,
|
||||
user_info: UserInfo = Depends(IsValidAccessToken),
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
service: ChatService = Depends(),
|
||||
):
|
||||
return RemoveNoneResponse(await service.messages(user_info, credentials.credentials, session_id))
|
||||
|
||||
|
||||
@router.post(
|
||||
path="/sessions/{session_id}/chat/send",
|
||||
response_model=Res_ChatSend,
|
||||
summary="협상 한 턴 전송",
|
||||
description="유저 입력을 보내고 agent 가 만든 봇 응답 1건을 반환한다(append-only). 종료 시 세션 입찰을 확정한다.",
|
||||
)
|
||||
async def chat_send(
|
||||
session_id: str,
|
||||
req: Req_ChatSend,
|
||||
user_info: UserInfo = Depends(IsValidAccessToken),
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
service: ChatService = Depends(),
|
||||
):
|
||||
return RemoveNoneResponse(
|
||||
await service.send(user_info, credentials.credentials, session_id, req.user_input_type, req.user_input)
|
||||
)
|
||||
@@ -0,0 +1,66 @@
|
||||
"""채팅(chat) 라우터 프로토콜 — backend ↔ 프론트 계약.
|
||||
|
||||
agent Res_Chat → 이 ChatMessage 매핑:
|
||||
step→step, client_step→display_step, script→script,
|
||||
input_mode→next_input_mode, input_options→next_input_type, chat_end→chat_end.
|
||||
indicator/summary/reject 는 이번 범위 외(예약 필드, 기본 None).
|
||||
"""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
# 말풍선 한 건. sender 는 ChatSender 정수 코드(1=BOT, 2=USER)로 내려가고 라벨 매핑은 프론트가 한다.
|
||||
class ChatMessage(WebPacketProtocol):
|
||||
chat_id: str = ""
|
||||
session_id: str = ""
|
||||
seq: int = 0
|
||||
sender: int = 0 # ChatSender 코드
|
||||
script: str = ""
|
||||
user_input_type: Optional[str] = None # 유저 입력 종류: text|percent|price
|
||||
step: str = ""
|
||||
display_step: str = "" # agent client_step
|
||||
next_input_mode: Optional[str] = None # confirm|yes_no|percent|price|delivery_type
|
||||
next_input_type: Optional[list[str]] = None # 다음 입력 선택지
|
||||
chat_end: bool = False
|
||||
indicator_value: Optional[float] = None # (범위 외 예약) 협상 지표
|
||||
bot_chat_type: Optional[str] = None # (범위 외 예약) indicator|summary 등
|
||||
|
||||
|
||||
# 채팅 진입 — 상품/견적 메타 + 현재 세션 상태 + 마감 시각(타이머용)
|
||||
class Res_ChatInit(Res_WebPacketProtocol):
|
||||
session_id: str = ""
|
||||
session_status: int = 0 # SessionStatus 코드
|
||||
quotation_id: str = ""
|
||||
quotation_end_time: str = "" # ISO 8601 (마감 시각)
|
||||
quotation_memo: str = ""
|
||||
item_id: str = ""
|
||||
item_name: str = ""
|
||||
item_code: str = ""
|
||||
item_image: str = ""
|
||||
item_price: int = 0
|
||||
item_model_name: str = ""
|
||||
item_maker_name: str = ""
|
||||
item_spec: str = ""
|
||||
item_lead_time: str = ""
|
||||
item_min_order_quantity: str = ""
|
||||
item_vat_yn: Optional[bool] = None
|
||||
item_delivery_fee_yn: Optional[bool] = None
|
||||
|
||||
|
||||
# 대화 히스토리(재진입 복원)
|
||||
class Res_ChatMessages(Res_WebPacketProtocol):
|
||||
items: list[ChatMessage] = []
|
||||
|
||||
|
||||
# 한 턴 전송. user_input 은 버튼 텍스트 또는 가격/퍼센트 문자열.
|
||||
class Req_ChatSend(WebPacketProtocol):
|
||||
user_input_type: Optional[str] = None # text|percent|price
|
||||
user_input: str = ""
|
||||
|
||||
|
||||
# append-only: 새 봇 메시지 1건 + 갱신된 세션 상태만 반환(전체 refetch 회피)
|
||||
class Res_ChatSend(Res_WebPacketProtocol):
|
||||
message: Optional[ChatMessage] = None
|
||||
session_status: int = 0
|
||||
Reference in new issue
Block a user