11from uuid import UUID
22from typing import List
3- from sqlalchemy import select , delete
3+ from sqlalchemy import select , delete , text
4+ from sqlalchemy .orm import joinedload
45from sqlalchemy .ext .asyncio import AsyncSession
56from app .models .chat import Chat
6- from app .schemas .chat import ChatCreate , ChatUpdate , ChatResponse
7+ from app .models .category import Category
8+ from app .schemas .chat import (
9+ ChatCreate ,
10+ ChatUpdate ,
11+ ChatResponse ,
12+ ModelResponse ,
13+ ChatWithModelResponse ,
14+ )
15+ from app .enum .chat import RoleEnum
716from app .utils .to_snake_case import camel_to_snake
17+ from app .utils .chat_model_selector import route_to_model
18+ from app .enum .category import CategoryNameEnum
19+ from app .models .category import Category
820
921
1022# 생성
@@ -14,20 +26,62 @@ async def create_chat(
1426 storage_id : UUID ,
1527 category_id : UUID ,
1628 chat_data : ChatCreate ,
17- ) -> ChatResponse :
29+ ) -> ChatWithModelResponse :
1830
19- new_chat = Chat (
31+ user_chat = Chat (
2032 user_id = user_id ,
2133 storage_id = storage_id ,
2234 category_id = category_id ,
2335 role = chat_data .role ,
2436 content = chat_data .content ,
37+ created_at = chat_data .created_at ,
2538 )
26-
27- db .add (new_chat )
39+ db .add (user_chat )
2840 await db .commit ()
29- await db .refresh (new_chat )
30- return new_chat
41+ await db .refresh (user_chat )
42+
43+ # ✅ 카테고리 이름 직접 SQL로 조회 (ENUM)
44+ result = await db .execute (
45+ text (
46+ """
47+ SELECT category_name
48+ FROM categories
49+ WHERE id = :category_id
50+ """
51+ ),
52+ {"category_id" : str (category_id )},
53+ )
54+ row = result .first ()
55+
56+ if row is None :
57+ raise ValueError ("❌ 해당 category_id에 대한 카테고리를 찾을 수 없습니다." )
58+
59+ category_enum = CategoryNameEnum [row .category_name ]
60+
61+ # ✅ GPT 호출
62+ if chat_data .role == RoleEnum .USER :
63+ model_func = route_to_model (category_enum )
64+ gpt_response = model_func (chat_data .content )
65+
66+ assistant_chat = Chat (
67+ user_id = user_id ,
68+ storage_id = storage_id ,
69+ category_id = category_id ,
70+ role = RoleEnum .ASSISTANT ,
71+ content = gpt_response ,
72+ )
73+ db .add (assistant_chat )
74+ await db .commit ()
75+ await db .refresh (assistant_chat )
76+
77+ return ChatWithModelResponse (
78+ chat = user_chat , model_response = ModelResponse (content = gpt_response )
79+ )
80+
81+ # assistant role이 아닌 경우
82+ return ChatWithModelResponse (
83+ chat = user_chat , model_response = ModelResponse (content = "" )
84+ )
3185
3286
3387# 단일 채팅 조회
0 commit comments