1- # Placeholder for AI service integration logic
2-
3- import uuid
4- from typing import Sequence
5-
6- from app .models import Character , Message
7-
1+ import os
2+ from typing import Optional
83
4+ from gemini_provider import GeminiAIProvider
5+ from openai_provider import OpenAIProvider
6+ from base import AIProvider
7+ def get_active_provider () -> Optional [AIProvider ]:
8+ """
9+ Trả về một AIProvider đã khởi tạo, dựa trên cấu hình môi trường.
10+ Ưu tiên OpenAI nếu có, fallback về Gemini nếu không.
11+ """
12+ gemini_key = os .getenv ("GEMINI_API_KEY" )
13+ if gemini_key :
14+ print ("[AI Service] Using GeminiAIProvider." )
15+ return GeminiAIProvider (api_key = gemini_key , model_name = "gemini-1.5-flash" )
16+
17+
18+ openai_key = os .getenv ("OPENAI_API_KEY" )
19+ if openai_key :
20+ print ("[AI Service] Using OpenAIProvider." )
21+ return OpenAIProvider (model_name = "gpt-4o" )
22+ print ("[AI Service] No valid AI provider found." )
23+ return None
924def get_ai_response (
10- * , character : Character , history : Sequence [Message ]
25+ * , character : Character , history : list [Message ]
1126) -> str :
1227 """
13- Placeholder function to simulate getting a response from an AI model .
28+ Gọi phản hồi AI dựa trên character và lịch sử hội thoại .
1429
1530 Args:
16- character: The character the user is talking to .
17- history: A sequence of recent messages in the conversation .
31+ character: Đối tượng nhân vật (Character) dùng để cung cấp system_prompt .
32+ history: Danh sách các tin nhắn lịch sử, bao gồm user message cuối .
1833
1934 Returns:
20- A string containing the AI's response .
35+ Chuỗi phản hồi từ AI.
2136 """
22- last_user_message = next ((msg .content for msg in reversed (history ) if msg .sender == "user" ), None )
23-
24- response = (
25- f"Okay, you said: '{ last_user_message } '. As { character .name } , I'm still under development!"
26- if last_user_message
27- else f"Hi! I'm { character .name } . Thanks for starting a chat!"
28- )
29- print (f"---> AI Service called for Character: { character .name } " )
30- print (f"---> History: { [(msg .sender , msg .content ) for msg in history ]} " )
31- print (f"---> AI Response: { response } " )
32-
33- return response
37+ provider = get_active_provider ()
38+
39+ if not provider :
40+ return "AI service is not available due to missing API configuration."
41+
42+ print (f"\n [AI Service] Character: { character .name } " )
43+ print (f"[AI Service] Provider: { type (provider ).__name__ } " )
44+
45+ try :
46+ response = provider .get_completion (character = character , history = history )
47+ return response
48+ except Exception as e :
49+ print (f"[AI Service] Error during response generation: { e } " )
50+ return "An error occurred while generating the AI response."
0 commit comments