Spaces:
Running
Running
axeronis commited on
Commit ·
bbc6d21
1
Parent(s): 07bb838
feat: complete multimodal integration (Telegram/WhatsApp incoming media support)
Browse files- backend/app/api/meta_webhooks.py +65 -6
- backend/app/api/telegram_webhook.py +82 -9
- backend/app/services/ai_core/base.py +4 -2
- backend/app/services/ai_core/response_generator.py +35 -13
- backend/app/services/llm_client.py +26 -24
- backend/app/services/message_processor.py +20 -6
- backend/app/services/meta_whatsapp.py +33 -1
backend/app/api/meta_webhooks.py
CHANGED
|
@@ -124,14 +124,26 @@ async def process_whatsapp_event(tenant_id: UUID, payload: dict):
|
|
| 124 |
msg_type = message.get("type")
|
| 125 |
text = ""
|
| 126 |
is_voice = False
|
|
|
|
|
|
|
| 127 |
|
| 128 |
if msg_type == "text":
|
| 129 |
text = message["text"]["body"]
|
| 130 |
elif msg_type == "audio":
|
| 131 |
-
|
| 132 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
else:
|
| 134 |
-
text = f"[{msg_type}
|
| 135 |
|
| 136 |
# Use unified processor
|
| 137 |
await process_whatsapp_message(
|
|
@@ -139,7 +151,8 @@ async def process_whatsapp_event(tenant_id: UUID, payload: dict):
|
|
| 139 |
sender_id=sender_id,
|
| 140 |
sender_name=sender_name,
|
| 141 |
text=text,
|
| 142 |
-
is_voice=is_voice
|
|
|
|
| 143 |
)
|
| 144 |
|
| 145 |
except (IndexError, KeyError) as e:
|
|
@@ -151,9 +164,14 @@ async def process_whatsapp_message(
|
|
| 151 |
sender_id: str,
|
| 152 |
sender_name: str,
|
| 153 |
text: str,
|
| 154 |
-
is_voice: bool = False
|
|
|
|
| 155 |
):
|
| 156 |
"""Process WhatsApp message using unified MessageProcessor."""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
async with async_session_maker() as session:
|
| 158 |
try:
|
| 159 |
tenant = await session.get(Tenant, tenant_id)
|
|
@@ -161,13 +179,54 @@ async def process_whatsapp_message(
|
|
| 161 |
logger.error(f"Tenant {tenant_id} not found")
|
| 162 |
return
|
| 163 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
# Build incoming message
|
| 165 |
incoming = IncomingMessage(
|
| 166 |
channel="whatsapp",
|
| 167 |
sender_id=sender_id,
|
| 168 |
sender_name=sender_name,
|
| 169 |
text=text,
|
| 170 |
-
is_voice=is_voice
|
|
|
|
|
|
|
| 171 |
)
|
| 172 |
|
| 173 |
# Process with unified MessageProcessor
|
|
|
|
| 124 |
msg_type = message.get("type")
|
| 125 |
text = ""
|
| 126 |
is_voice = False
|
| 127 |
+
media_id = None
|
| 128 |
+
media_mime = None
|
| 129 |
|
| 130 |
if msg_type == "text":
|
| 131 |
text = message["text"]["body"]
|
| 132 |
elif msg_type == "audio":
|
| 133 |
+
media_id = message["audio"]["id"]
|
| 134 |
+
media_mime = message["audio"].get("mime_type")
|
| 135 |
+
is_voice = True # Will transcribe
|
| 136 |
+
text = "[Voice Message]"
|
| 137 |
+
elif msg_type == "image":
|
| 138 |
+
media_id = message["image"]["id"]
|
| 139 |
+
media_mime = message["image"].get("mime_type")
|
| 140 |
+
text = message["image"].get("caption", "[Image]")
|
| 141 |
+
elif msg_type == "document":
|
| 142 |
+
media_id = message["document"]["id"]
|
| 143 |
+
media_mime = message["document"].get("mime_type")
|
| 144 |
+
text = message["document"].get("caption", "[Document]")
|
| 145 |
else:
|
| 146 |
+
text = f"[{msg_type} not supported]"
|
| 147 |
|
| 148 |
# Use unified processor
|
| 149 |
await process_whatsapp_message(
|
|
|
|
| 151 |
sender_id=sender_id,
|
| 152 |
sender_name=sender_name,
|
| 153 |
text=text,
|
| 154 |
+
is_voice=is_voice,
|
| 155 |
+
media_id=media_id
|
| 156 |
)
|
| 157 |
|
| 158 |
except (IndexError, KeyError) as e:
|
|
|
|
| 164 |
sender_id: str,
|
| 165 |
sender_name: str,
|
| 166 |
text: str,
|
| 167 |
+
is_voice: bool = False,
|
| 168 |
+
media_id: Optional[str] = None
|
| 169 |
):
|
| 170 |
"""Process WhatsApp message using unified MessageProcessor."""
|
| 171 |
+
from app.core.supabase import supabase_client
|
| 172 |
+
import time
|
| 173 |
+
import re
|
| 174 |
+
|
| 175 |
async with async_session_maker() as session:
|
| 176 |
try:
|
| 177 |
tenant = await session.get(Tenant, tenant_id)
|
|
|
|
| 179 |
logger.error(f"Tenant {tenant_id} not found")
|
| 180 |
return
|
| 181 |
|
| 182 |
+
# Message Processing Vars
|
| 183 |
+
media_url = None
|
| 184 |
+
media_type = None
|
| 185 |
+
|
| 186 |
+
# Handle Media Download
|
| 187 |
+
if media_id:
|
| 188 |
+
try:
|
| 189 |
+
wa_service = get_whatsapp_cloud_service()
|
| 190 |
+
content, mime = await wa_service.download_media(tenant, media_id)
|
| 191 |
+
|
| 192 |
+
if is_voice:
|
| 193 |
+
try:
|
| 194 |
+
# Transcribe Voice
|
| 195 |
+
llm = get_llm_client()
|
| 196 |
+
transcript = await llm.transcribe_audio(content, mime_type=mime)
|
| 197 |
+
text = f"[Voice] {transcript}"
|
| 198 |
+
except Exception as e:
|
| 199 |
+
logger.error(f"Transcription failed: {e}")
|
| 200 |
+
text += " (Failed to transcribe)"
|
| 201 |
+
|
| 202 |
+
# Upload to Supabase
|
| 203 |
+
if supabase_client:
|
| 204 |
+
bucket = "chat-attachments"
|
| 205 |
+
ts = int(time.time())
|
| 206 |
+
# safe name? We don't have filename from WA easily, use generic
|
| 207 |
+
ext = mime.split('/')[-1]
|
| 208 |
+
filename = f"wa_{media_id}.{ext}"
|
| 209 |
+
path = f"{tenant.id}/incoming/{ts}_{filename}"
|
| 210 |
+
|
| 211 |
+
supabase_client.storage.from_(bucket).upload(
|
| 212 |
+
path=path, file=content, file_options={"content-type": mime}
|
| 213 |
+
)
|
| 214 |
+
media_url = supabase_client.storage.from_(bucket).get_public_url(path)
|
| 215 |
+
media_type = mime
|
| 216 |
+
logger.info(f"📎 WhatsApp Media uploaded: {media_url}")
|
| 217 |
+
|
| 218 |
+
except Exception as e:
|
| 219 |
+
logger.error(f"WhatsApp Media processing failed: {e}")
|
| 220 |
+
|
| 221 |
# Build incoming message
|
| 222 |
incoming = IncomingMessage(
|
| 223 |
channel="whatsapp",
|
| 224 |
sender_id=sender_id,
|
| 225 |
sender_name=sender_name,
|
| 226 |
text=text,
|
| 227 |
+
is_voice=is_voice,
|
| 228 |
+
media_url=media_url,
|
| 229 |
+
media_type=media_type
|
| 230 |
)
|
| 231 |
|
| 232 |
# Process with unified MessageProcessor
|
backend/app/api/telegram_webhook.py
CHANGED
|
@@ -42,19 +42,27 @@ async def handle_telegram_webhook(
|
|
| 42 |
logger.info(f"📩 Telegram Webhook: {list(data.keys())} | Msg Keys: {list(message_data.keys())}")
|
| 43 |
|
| 44 |
chat_id = str(message_data.get("chat", {}).get("id"))
|
| 45 |
-
text = message_data.get("text", "")
|
| 46 |
|
| 47 |
# Check for Voice OR Audio
|
| 48 |
voice = message_data.get("voice") or message_data.get("audio") or {}
|
| 49 |
voice_file_id = voice.get("file_id")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
user_data = message_data.get("from", {})
|
| 52 |
username = user_data.get("username", "")
|
| 53 |
first_name = user_data.get("first_name", "")
|
| 54 |
|
| 55 |
-
if not text and not voice_file_id:
|
| 56 |
-
logger.warning(f"⚠️ Ignored message with no
|
| 57 |
-
return {"status": "
|
| 58 |
|
| 59 |
# Process in background
|
| 60 |
background_tasks.add_task(
|
|
@@ -63,6 +71,8 @@ async def handle_telegram_webhook(
|
|
| 63 |
chat_id=chat_id,
|
| 64 |
text=text,
|
| 65 |
voice_file_id=voice_file_id,
|
|
|
|
|
|
|
| 66 |
username=username,
|
| 67 |
first_name=first_name
|
| 68 |
)
|
|
@@ -75,12 +85,17 @@ async def process_telegram_message(
|
|
| 75 |
chat_id: str,
|
| 76 |
text: str,
|
| 77 |
voice_file_id: str | None,
|
|
|
|
|
|
|
| 78 |
username: str,
|
| 79 |
first_name: str
|
| 80 |
):
|
| 81 |
"""Background task: Process Telegram message using unified MessageProcessor."""
|
| 82 |
from app.services.telegram_service import telegram_service
|
| 83 |
-
|
|
|
|
|
|
|
|
|
|
| 84 |
async with async_session_maker() as session:
|
| 85 |
try:
|
| 86 |
# 1. Get Tenant & Bot Token
|
|
@@ -94,12 +109,68 @@ async def process_telegram_message(
|
|
| 94 |
logger.error(f"No Telegram token for tenant {tenant_id}")
|
| 95 |
return
|
| 96 |
|
| 97 |
-
# 2.
|
| 98 |
is_voice = False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
if voice_file_id:
|
| 100 |
-
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
# 3. Build incoming message
|
| 104 |
sender_name = f"{first_name} {username}".strip() or f"TG User {chat_id}"
|
| 105 |
|
|
@@ -108,7 +179,9 @@ async def process_telegram_message(
|
|
| 108 |
sender_id=chat_id,
|
| 109 |
sender_name=sender_name,
|
| 110 |
text=text,
|
| 111 |
-
is_voice=is_voice
|
|
|
|
|
|
|
| 112 |
)
|
| 113 |
|
| 114 |
# 4. Process with unified MessageProcessor
|
|
|
|
| 42 |
logger.info(f"📩 Telegram Webhook: {list(data.keys())} | Msg Keys: {list(message_data.keys())}")
|
| 43 |
|
| 44 |
chat_id = str(message_data.get("chat", {}).get("id"))
|
| 45 |
+
text = message_data.get("text", "") or message_data.get("caption", "")
|
| 46 |
|
| 47 |
# Check for Voice OR Audio
|
| 48 |
voice = message_data.get("voice") or message_data.get("audio") or {}
|
| 49 |
voice_file_id = voice.get("file_id")
|
| 50 |
+
|
| 51 |
+
# Check for Photo (array)
|
| 52 |
+
photo_list = message_data.get("photo", [])
|
| 53 |
+
photo_file_id = photo_list[-1]["file_id"] if photo_list else None
|
| 54 |
+
|
| 55 |
+
# Check for Document
|
| 56 |
+
doc = message_data.get("document", {})
|
| 57 |
+
doc_file_id = doc.get("file_id")
|
| 58 |
|
| 59 |
user_data = message_data.get("from", {})
|
| 60 |
username = user_data.get("username", "")
|
| 61 |
first_name = user_data.get("first_name", "")
|
| 62 |
|
| 63 |
+
if not text and not voice_file_id and not photo_file_id and not doc_file_id:
|
| 64 |
+
logger.warning(f"⚠️ Ignored message with no content. Keys: {list(message_data.keys())}")
|
| 65 |
+
return {"status": "ignored_no_content"}
|
| 66 |
|
| 67 |
# Process in background
|
| 68 |
background_tasks.add_task(
|
|
|
|
| 71 |
chat_id=chat_id,
|
| 72 |
text=text,
|
| 73 |
voice_file_id=voice_file_id,
|
| 74 |
+
photo_file_id=photo_file_id,
|
| 75 |
+
doc_file_id=doc_file_id,
|
| 76 |
username=username,
|
| 77 |
first_name=first_name
|
| 78 |
)
|
|
|
|
| 85 |
chat_id: str,
|
| 86 |
text: str,
|
| 87 |
voice_file_id: str | None,
|
| 88 |
+
photo_file_id: str | None,
|
| 89 |
+
doc_file_id: str | None,
|
| 90 |
username: str,
|
| 91 |
first_name: str
|
| 92 |
):
|
| 93 |
"""Background task: Process Telegram message using unified MessageProcessor."""
|
| 94 |
from app.services.telegram_service import telegram_service
|
| 95 |
+
from app.core.supabase import supabase_client
|
| 96 |
+
import time
|
| 97 |
+
import re
|
| 98 |
+
|
| 99 |
async with async_session_maker() as session:
|
| 100 |
try:
|
| 101 |
# 1. Get Tenant & Bot Token
|
|
|
|
| 109 |
logger.error(f"No Telegram token for tenant {tenant_id}")
|
| 110 |
return
|
| 111 |
|
| 112 |
+
# 2. Process Media (Voice, Photo, Doc)
|
| 113 |
is_voice = False
|
| 114 |
+
media_url = None
|
| 115 |
+
media_type = None
|
| 116 |
+
|
| 117 |
+
# Helper to download file
|
| 118 |
+
async def download_file(file_id: str) -> tuple[bytes, str, str]:
|
| 119 |
+
async with httpx.AsyncClient() as client:
|
| 120 |
+
file_res = await client.get(f"https://api.telegram.org/bot{bot_token}/getFile?file_id={file_id}")
|
| 121 |
+
if not file_res.json().get("ok"): return None, None, None
|
| 122 |
+
path = file_res.json()["result"]["file_path"]
|
| 123 |
+
url = f"https://api.telegram.org/file/bot{bot_token}/{path}"
|
| 124 |
+
|
| 125 |
+
data_res = await client.get(url)
|
| 126 |
+
data_res.raise_for_status()
|
| 127 |
+
|
| 128 |
+
# Guess MIME/Name
|
| 129 |
+
ext = path.split('.')[-1].lower() if '.' in path else "bin"
|
| 130 |
+
mime_map = {
|
| 131 |
+
"jpg": "image/jpeg",
|
| 132 |
+
"jpeg": "image/jpeg",
|
| 133 |
+
"png": "image/png",
|
| 134 |
+
"webp": "image/webp",
|
| 135 |
+
"oga": "audio/ogg",
|
| 136 |
+
"ogg": "audio/ogg",
|
| 137 |
+
"mp3": "audio/mpeg",
|
| 138 |
+
"pdf": "application/pdf",
|
| 139 |
+
"txt": "text/plain"
|
| 140 |
+
}
|
| 141 |
+
mime = mime_map.get(ext, "application/octet-stream")
|
| 142 |
+
return data_res.content, path.split('/')[-1], mime
|
| 143 |
+
|
| 144 |
+
# Handle Voice
|
| 145 |
if voice_file_id:
|
| 146 |
+
try:
|
| 147 |
+
text = await transcribe_telegram_voice(bot_token, voice_file_id)
|
| 148 |
+
is_voice = True
|
| 149 |
+
# Optional: We could also upload the voice file if needed
|
| 150 |
+
except Exception as e:
|
| 151 |
+
logger.error(f"Voice processing failed: {e}")
|
| 152 |
|
| 153 |
+
# Handle Photo / Document
|
| 154 |
+
target_file_id = photo_file_id or doc_file_id
|
| 155 |
+
if target_file_id:
|
| 156 |
+
try:
|
| 157 |
+
content, name, mime = await download_file(target_file_id)
|
| 158 |
+
if content and supabase_client:
|
| 159 |
+
bucket = "chat-attachments"
|
| 160 |
+
ts = int(time.time())
|
| 161 |
+
safe_name = re.sub(r'[^a-zA-Z0-9_\-\.]', '_', name)
|
| 162 |
+
# Store in incoming path
|
| 163 |
+
path = f"{tenant.id}/incoming/{ts}_{safe_name}"
|
| 164 |
+
|
| 165 |
+
supabase_client.storage.from_(bucket).upload(
|
| 166 |
+
path=path, file=content, file_options={"content-type": mime}
|
| 167 |
+
)
|
| 168 |
+
media_url = supabase_client.storage.from_(bucket).get_public_url(path)
|
| 169 |
+
media_type = mime
|
| 170 |
+
logger.info(f"📎 Media uploaded: {media_url}")
|
| 171 |
+
except Exception as e:
|
| 172 |
+
logger.error(f"Media upload failed: {e}")
|
| 173 |
+
|
| 174 |
# 3. Build incoming message
|
| 175 |
sender_name = f"{first_name} {username}".strip() or f"TG User {chat_id}"
|
| 176 |
|
|
|
|
| 179 |
sender_id=chat_id,
|
| 180 |
sender_name=sender_name,
|
| 181 |
text=text,
|
| 182 |
+
is_voice=is_voice,
|
| 183 |
+
media_url=media_url,
|
| 184 |
+
media_type=media_type
|
| 185 |
)
|
| 186 |
|
| 187 |
# 4. Process with unified MessageProcessor
|
backend/app/services/ai_core/base.py
CHANGED
|
@@ -45,7 +45,9 @@ class AICore:
|
|
| 45 |
tenant: Tenant,
|
| 46 |
lead: Lead,
|
| 47 |
user_message: str,
|
| 48 |
-
conversation_history: List[Message]
|
|
|
|
|
|
|
| 49 |
) -> Dict[str, Any]:
|
| 50 |
"""
|
| 51 |
Generate AI sales response with PERSISTENT MEMORY (Gemini Cache).
|
|
@@ -54,7 +56,7 @@ class AICore:
|
|
| 54 |
"""
|
| 55 |
from .response_generator import generate_sales_response_impl
|
| 56 |
return await generate_sales_response_impl(
|
| 57 |
-
self, session, tenant, lead, user_message, conversation_history
|
| 58 |
)
|
| 59 |
|
| 60 |
# =========================================================================
|
|
|
|
| 45 |
tenant: Tenant,
|
| 46 |
lead: Lead,
|
| 47 |
user_message: str,
|
| 48 |
+
conversation_history: List[Message],
|
| 49 |
+
media_url: Optional[str] = None,
|
| 50 |
+
media_type: Optional[str] = None
|
| 51 |
) -> Dict[str, Any]:
|
| 52 |
"""
|
| 53 |
Generate AI sales response with PERSISTENT MEMORY (Gemini Cache).
|
|
|
|
| 56 |
"""
|
| 57 |
from .response_generator import generate_sales_response_impl
|
| 58 |
return await generate_sales_response_impl(
|
| 59 |
+
self, session, tenant, lead, user_message, conversation_history, media_url, media_type
|
| 60 |
)
|
| 61 |
|
| 62 |
# =========================================================================
|
backend/app/services/ai_core/response_generator.py
CHANGED
|
@@ -6,12 +6,17 @@ Handles generation of AI sales responses:
|
|
| 6 |
- Chat history formatting
|
| 7 |
"""
|
| 8 |
|
| 9 |
-
from typing import List, Dict, Any, TYPE_CHECKING
|
| 10 |
from datetime import datetime
|
| 11 |
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
|
|
|
| 12 |
|
| 13 |
from app.models.lead import Lead, Message
|
| 14 |
from app.models.tenant import Tenant
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
if TYPE_CHECKING:
|
| 17 |
from .base import AICore
|
|
@@ -27,7 +32,9 @@ async def generate_sales_response_impl(
|
|
| 27 |
tenant: Tenant,
|
| 28 |
lead: Lead,
|
| 29 |
user_message: str,
|
| 30 |
-
conversation_history: List[Message]
|
|
|
|
|
|
|
| 31 |
) -> Dict[str, Any]:
|
| 32 |
"""
|
| 33 |
Generate AI sales response with PERSISTENT MEMORY (Gemini Cache).
|
|
@@ -36,7 +43,7 @@ async def generate_sales_response_impl(
|
|
| 36 |
1. Smart Context: Get Playbook Stage & Booking Slots (Dynamic)
|
| 37 |
2. Persistent Memory: Get cached Tenant Context (Static: KB, Products, Persona)
|
| 38 |
3. Interference: Inject dynamic context into prompt.
|
| 39 |
-
4. Generation: Gemini 1.5 Flash uses Cache + Dynamic Context.
|
| 40 |
"""
|
| 41 |
# Import here to avoid circular imports
|
| 42 |
from .lead_analyzer import extract_and_update_bant
|
|
@@ -66,7 +73,7 @@ async def generate_sales_response_impl(
|
|
| 66 |
|
| 67 |
# 3. MEMORY RETRIEVAL (The "Big Brain")
|
| 68 |
memory_manager = get_memory_manager()
|
| 69 |
-
cache_name = await memory_manager.get_valid_memory(session, tenant)
|
| 70 |
|
| 71 |
# 4. DYNAMIC CONTEXT (Things that change per request)
|
| 72 |
dynamic_context = f"""
|
|
@@ -83,18 +90,33 @@ Goal: {current_stage.ai_goal if current_stage else 'Assist user'}
|
|
| 83 |
# 5. Format conversation history
|
| 84 |
chat_history = format_chat_history(conversation_history)
|
| 85 |
|
| 86 |
-
# 6.
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
full_static_context = await memory_manager.build_tenant_context(session, tenant)
|
| 91 |
final_system_instruction = full_static_context + "\n\n" + dynamic_context
|
| 92 |
|
| 93 |
response = await ai_core.llm.generate_response(
|
| 94 |
prompt=user_message,
|
| 95 |
system_instruction=final_system_instruction,
|
| 96 |
-
context=None,
|
| 97 |
-
chat_history=chat_history
|
|
|
|
| 98 |
)
|
| 99 |
|
| 100 |
return {
|
|
@@ -102,9 +124,9 @@ Goal: {current_stage.ai_goal if current_stage else 'Assist user'}
|
|
| 102 |
"prompt_tokens": response["prompt_tokens"],
|
| 103 |
"completion_tokens": response["completion_tokens"],
|
| 104 |
"total_tokens": response["total_tokens"],
|
| 105 |
-
"rag_context_used": False,
|
| 106 |
-
"products_found": True,
|
| 107 |
-
"scripts_used": 0
|
| 108 |
}
|
| 109 |
|
| 110 |
|
|
|
|
| 6 |
- Chat history formatting
|
| 7 |
"""
|
| 8 |
|
| 9 |
+
from typing import List, Dict, Any, TYPE_CHECKING, Optional
|
| 10 |
from datetime import datetime
|
| 11 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 12 |
+
import httpx
|
| 13 |
+
from google.genai import types
|
| 14 |
|
| 15 |
from app.models.lead import Lead, Message
|
| 16 |
from app.models.tenant import Tenant
|
| 17 |
+
from app.core.logging import get_logger
|
| 18 |
+
|
| 19 |
+
logger = get_logger(__name__)
|
| 20 |
|
| 21 |
if TYPE_CHECKING:
|
| 22 |
from .base import AICore
|
|
|
|
| 32 |
tenant: Tenant,
|
| 33 |
lead: Lead,
|
| 34 |
user_message: str,
|
| 35 |
+
conversation_history: List[Message],
|
| 36 |
+
media_url: Optional[str] = None,
|
| 37 |
+
media_type: Optional[str] = None
|
| 38 |
) -> Dict[str, Any]:
|
| 39 |
"""
|
| 40 |
Generate AI sales response with PERSISTENT MEMORY (Gemini Cache).
|
|
|
|
| 43 |
1. Smart Context: Get Playbook Stage & Booking Slots (Dynamic)
|
| 44 |
2. Persistent Memory: Get cached Tenant Context (Static: KB, Products, Persona)
|
| 45 |
3. Interference: Inject dynamic context into prompt.
|
| 46 |
+
4. Generation: Gemini 1.5 Flash uses Cache + Dynamic Context + VISION/AUDIO.
|
| 47 |
"""
|
| 48 |
# Import here to avoid circular imports
|
| 49 |
from .lead_analyzer import extract_and_update_bant
|
|
|
|
| 73 |
|
| 74 |
# 3. MEMORY RETRIEVAL (The "Big Brain")
|
| 75 |
memory_manager = get_memory_manager()
|
| 76 |
+
# cache_name = await memory_manager.get_valid_memory(session, tenant) # Deprecating single cache ref
|
| 77 |
|
| 78 |
# 4. DYNAMIC CONTEXT (Things that change per request)
|
| 79 |
dynamic_context = f"""
|
|
|
|
| 90 |
# 5. Format conversation history
|
| 91 |
chat_history = format_chat_history(conversation_history)
|
| 92 |
|
| 93 |
+
# 6. HANDLE MULTIMODAL INPUT (Download Media)
|
| 94 |
+
media_parts = []
|
| 95 |
+
if media_url:
|
| 96 |
+
logger.info(f"👁️ Processing visual/audio input: {media_url}")
|
| 97 |
+
try:
|
| 98 |
+
async with httpx.AsyncClient() as client:
|
| 99 |
+
res = await client.get(media_url)
|
| 100 |
+
res.raise_for_status()
|
| 101 |
+
media_bytes = res.content
|
| 102 |
+
# Create Part
|
| 103 |
+
# mime_type fallback
|
| 104 |
+
mime = media_type or ("image/jpeg" if ".jpg" in media_url else "audio/ogg")
|
| 105 |
+
media_parts.append(types.Part.from_bytes(data=media_bytes, mime_type=mime))
|
| 106 |
+
except Exception as e:
|
| 107 |
+
logger.error(f"❌ Failed to download multimodal content: {e}")
|
| 108 |
+
dynamic_context += f"\n[SYSTEM ERROR]: user sent media at {media_url} but AI could not access it. Apologize and ask for re-upload if crucial."
|
| 109 |
+
|
| 110 |
+
# 7. ALWAYS inject full context (cache logic simplified)
|
| 111 |
full_static_context = await memory_manager.build_tenant_context(session, tenant)
|
| 112 |
final_system_instruction = full_static_context + "\n\n" + dynamic_context
|
| 113 |
|
| 114 |
response = await ai_core.llm.generate_response(
|
| 115 |
prompt=user_message,
|
| 116 |
system_instruction=final_system_instruction,
|
| 117 |
+
context=None,
|
| 118 |
+
chat_history=chat_history,
|
| 119 |
+
media_parts=media_parts
|
| 120 |
)
|
| 121 |
|
| 122 |
return {
|
|
|
|
| 124 |
"prompt_tokens": response["prompt_tokens"],
|
| 125 |
"completion_tokens": response["completion_tokens"],
|
| 126 |
"total_tokens": response["total_tokens"],
|
| 127 |
+
"rag_context_used": False,
|
| 128 |
+
"products_found": True,
|
| 129 |
+
"scripts_used": 0
|
| 130 |
}
|
| 131 |
|
| 132 |
|
backend/app/services/llm_client.py
CHANGED
|
@@ -79,7 +79,8 @@ class GeminiLLMClient:
|
|
| 79 |
context: Optional[str] = None, # Cache Name
|
| 80 |
chat_history: Optional[List[Dict[str, Any]]] = None,
|
| 81 |
temperature: Optional[float] = None,
|
| 82 |
-
max_retries: int = 3
|
|
|
|
| 83 |
) -> Dict[str, Any]:
|
| 84 |
"""Internal Gemini call."""
|
| 85 |
|
|
@@ -92,42 +93,43 @@ class GeminiLLMClient:
|
|
| 92 |
|
| 93 |
for attempt in range(max_retries):
|
| 94 |
try:
|
| 95 |
-
# 1. Prepare Model
|
| 96 |
model_name = self.default_model_name
|
| 97 |
|
| 98 |
-
# If retrieving from cache, the SDK usually allows passing the cache name
|
| 99 |
-
# directly in the generate_content call or creating a specific model reference.
|
| 100 |
-
# In google-genai SDK, we can often just pass the cache name in `cached_content` arg.
|
| 101 |
-
cached_content_name = None
|
| 102 |
-
|
| 103 |
if context and isinstance(context, str) and context.startswith("cachedContents/"):
|
| 104 |
-
# ENABLE MEMORY: Use the cached context
|
| 105 |
logger.info(f"🧠 Using Persistent Memory: {context}")
|
| 106 |
-
cached_content_name = context
|
| 107 |
-
# When using cache, system_instruction is often embedded in cache,
|
| 108 |
-
# but we can overlay prompt.
|
| 109 |
|
| 110 |
# 2. Prepare Contents (Chat History + Prompt)
|
| 111 |
contents = []
|
| 112 |
|
|
|
|
| 113 |
if chat_history:
|
| 114 |
for msg in chat_history:
|
| 115 |
role = "user" if msg.get("role") in ["user", "human"] else "model"
|
|
|
|
|
|
|
|
|
|
| 116 |
content_text = msg.get("content") or msg.get("text", "")
|
| 117 |
-
|
| 118 |
-
types.
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
|
| 124 |
-
#
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
|
|
|
|
|
|
| 131 |
|
| 132 |
# 3. Execute Call
|
| 133 |
loop = asyncio.get_event_loop()
|
|
|
|
| 79 |
context: Optional[str] = None, # Cache Name
|
| 80 |
chat_history: Optional[List[Dict[str, Any]]] = None,
|
| 81 |
temperature: Optional[float] = None,
|
| 82 |
+
max_retries: int = 3,
|
| 83 |
+
media_parts: Optional[List[Any]] = None # List of types.Part
|
| 84 |
) -> Dict[str, Any]:
|
| 85 |
"""Internal Gemini call."""
|
| 86 |
|
|
|
|
| 93 |
|
| 94 |
for attempt in range(max_retries):
|
| 95 |
try:
|
| 96 |
+
# 1. Prepare Model
|
| 97 |
model_name = self.default_model_name
|
| 98 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
if context and isinstance(context, str) and context.startswith("cachedContents/"):
|
|
|
|
| 100 |
logger.info(f"🧠 Using Persistent Memory: {context}")
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
# 2. Prepare Contents (Chat History + Prompt)
|
| 103 |
contents = []
|
| 104 |
|
| 105 |
+
# History
|
| 106 |
if chat_history:
|
| 107 |
for msg in chat_history:
|
| 108 |
role = "user" if msg.get("role") in ["user", "human"] else "model"
|
| 109 |
+
parts = []
|
| 110 |
+
|
| 111 |
+
# Text part
|
| 112 |
content_text = msg.get("content") or msg.get("text", "")
|
| 113 |
+
if content_text:
|
| 114 |
+
parts.append(types.Part.from_text(text=content_text))
|
| 115 |
+
|
| 116 |
+
# Media parts (if passed in history structure)
|
| 117 |
+
if msg.get("parts"):
|
| 118 |
+
# Assuming parts are already types.Part objects or compatible
|
| 119 |
+
parts.extend(msg["parts"])
|
| 120 |
+
|
| 121 |
+
if parts:
|
| 122 |
+
contents.append(types.Content(role=role, parts=parts))
|
| 123 |
|
| 124 |
+
# Current Turn
|
| 125 |
+
current_parts = []
|
| 126 |
+
if prompt:
|
| 127 |
+
current_parts.append(types.Part.from_text(text=prompt))
|
| 128 |
+
|
| 129 |
+
if media_parts:
|
| 130 |
+
current_parts.extend(media_parts)
|
| 131 |
+
|
| 132 |
+
contents.append(types.Content(role="user", parts=current_parts))
|
| 133 |
|
| 134 |
# 3. Execute Call
|
| 135 |
loop = asyncio.get_event_loop()
|
backend/app/services/message_processor.py
CHANGED
|
@@ -40,6 +40,7 @@ class IncomingMessage:
|
|
| 40 |
text: str,
|
| 41 |
is_voice: bool = False,
|
| 42 |
media_url: Optional[str] = None,
|
|
|
|
| 43 |
raw_payload: Optional[Dict[str, Any]] = None
|
| 44 |
):
|
| 45 |
self.channel = channel
|
|
@@ -48,6 +49,7 @@ class IncomingMessage:
|
|
| 48 |
self.text = text
|
| 49 |
self.is_voice = is_voice
|
| 50 |
self.media_url = media_url
|
|
|
|
| 51 |
self.raw_payload = raw_payload or {}
|
| 52 |
|
| 53 |
|
|
@@ -162,14 +164,18 @@ async def save_user_message(
|
|
| 162 |
session: AsyncSession,
|
| 163 |
tenant_id: UUID,
|
| 164 |
conversation_id: UUID,
|
| 165 |
-
text: str
|
|
|
|
|
|
|
| 166 |
) -> Message:
|
| 167 |
"""Save incoming user message to database."""
|
| 168 |
message = Message(
|
| 169 |
tenant_id=tenant_id,
|
| 170 |
conversation_id=conversation_id,
|
| 171 |
sender_type="user",
|
| 172 |
-
content=text
|
|
|
|
|
|
|
| 173 |
)
|
| 174 |
session.add(message)
|
| 175 |
await session.flush()
|
|
@@ -205,7 +211,9 @@ async def generate_ai_response(
|
|
| 205 |
tenant: Tenant,
|
| 206 |
lead: Lead,
|
| 207 |
user_message: str,
|
| 208 |
-
conversation_history: List[Message]
|
|
|
|
|
|
|
| 209 |
) -> Dict[str, Any]:
|
| 210 |
"""Generate AI sales response using AICore."""
|
| 211 |
ai_core = get_ai_core()
|
|
@@ -215,7 +223,9 @@ async def generate_ai_response(
|
|
| 215 |
tenant=tenant,
|
| 216 |
lead=lead,
|
| 217 |
user_message=user_message,
|
| 218 |
-
conversation_history=conversation_history
|
|
|
|
|
|
|
| 219 |
)
|
| 220 |
|
| 221 |
return response
|
|
@@ -270,7 +280,9 @@ async def process_incoming_message(
|
|
| 270 |
session=session,
|
| 271 |
tenant_id=tenant.id,
|
| 272 |
conversation_id=conversation.id,
|
| 273 |
-
text=message.text
|
|
|
|
|
|
|
| 274 |
)
|
| 275 |
|
| 276 |
await session.commit()
|
|
@@ -283,7 +295,9 @@ async def process_incoming_message(
|
|
| 283 |
tenant=tenant,
|
| 284 |
lead=lead,
|
| 285 |
user_message=message.text,
|
| 286 |
-
conversation_history=history
|
|
|
|
|
|
|
| 287 |
)
|
| 288 |
|
| 289 |
# 5. Save AI Message
|
|
|
|
| 40 |
text: str,
|
| 41 |
is_voice: bool = False,
|
| 42 |
media_url: Optional[str] = None,
|
| 43 |
+
media_type: Optional[str] = None,
|
| 44 |
raw_payload: Optional[Dict[str, Any]] = None
|
| 45 |
):
|
| 46 |
self.channel = channel
|
|
|
|
| 49 |
self.text = text
|
| 50 |
self.is_voice = is_voice
|
| 51 |
self.media_url = media_url
|
| 52 |
+
self.media_type = media_type
|
| 53 |
self.raw_payload = raw_payload or {}
|
| 54 |
|
| 55 |
|
|
|
|
| 164 |
session: AsyncSession,
|
| 165 |
tenant_id: UUID,
|
| 166 |
conversation_id: UUID,
|
| 167 |
+
text: str,
|
| 168 |
+
media_url: Optional[str] = None,
|
| 169 |
+
media_type: Optional[str] = None
|
| 170 |
) -> Message:
|
| 171 |
"""Save incoming user message to database."""
|
| 172 |
message = Message(
|
| 173 |
tenant_id=tenant_id,
|
| 174 |
conversation_id=conversation_id,
|
| 175 |
sender_type="user",
|
| 176 |
+
content=text,
|
| 177 |
+
media_url=media_url,
|
| 178 |
+
media_type=media_type
|
| 179 |
)
|
| 180 |
session.add(message)
|
| 181 |
await session.flush()
|
|
|
|
| 211 |
tenant: Tenant,
|
| 212 |
lead: Lead,
|
| 213 |
user_message: str,
|
| 214 |
+
conversation_history: List[Message],
|
| 215 |
+
media_url: Optional[str] = None,
|
| 216 |
+
media_type: Optional[str] = None
|
| 217 |
) -> Dict[str, Any]:
|
| 218 |
"""Generate AI sales response using AICore."""
|
| 219 |
ai_core = get_ai_core()
|
|
|
|
| 223 |
tenant=tenant,
|
| 224 |
lead=lead,
|
| 225 |
user_message=user_message,
|
| 226 |
+
conversation_history=conversation_history,
|
| 227 |
+
media_url=media_url,
|
| 228 |
+
media_type=media_type
|
| 229 |
)
|
| 230 |
|
| 231 |
return response
|
|
|
|
| 280 |
session=session,
|
| 281 |
tenant_id=tenant.id,
|
| 282 |
conversation_id=conversation.id,
|
| 283 |
+
text=message.text,
|
| 284 |
+
media_url=message.media_url,
|
| 285 |
+
media_type=message.media_type
|
| 286 |
)
|
| 287 |
|
| 288 |
await session.commit()
|
|
|
|
| 295 |
tenant=tenant,
|
| 296 |
lead=lead,
|
| 297 |
user_message=message.text,
|
| 298 |
+
conversation_history=history,
|
| 299 |
+
media_url=message.media_url,
|
| 300 |
+
media_type=message.media_type
|
| 301 |
)
|
| 302 |
|
| 303 |
# 5. Save AI Message
|
backend/app/services/meta_whatsapp.py
CHANGED
|
@@ -181,7 +181,39 @@ class WhatsAppCloudService:
|
|
| 181 |
logger.warning(f"Failed to mark message read: {e}")
|
| 182 |
return False
|
| 183 |
|
| 184 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
whatsapp_cloud_service = WhatsAppCloudService()
|
| 186 |
def get_whatsapp_cloud_service() -> WhatsAppCloudService:
|
| 187 |
return whatsapp_cloud_service
|
|
|
|
| 181 |
logger.warning(f"Failed to mark message read: {e}")
|
| 182 |
return False
|
| 183 |
|
| 184 |
+
async def download_media(
|
| 185 |
+
self,
|
| 186 |
+
tenant: Tenant,
|
| 187 |
+
media_id: str
|
| 188 |
+
) -> tuple[bytes, str]:
|
| 189 |
+
"""
|
| 190 |
+
Download media from WhatsApp Cloud API.
|
| 191 |
+
Returns (content_bytes, mime_type).
|
| 192 |
+
"""
|
| 193 |
+
if not tenant.meta_wa_config:
|
| 194 |
+
raise ValueError("Tenant has no Meta WhatsApp configuration")
|
| 195 |
+
|
| 196 |
+
token = tenant.meta_wa_config.get("access_token")
|
| 197 |
+
|
| 198 |
+
# 1. Get Media URL
|
| 199 |
+
url = f"{self.BASE_URL}/{media_id}"
|
| 200 |
+
|
| 201 |
+
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
| 202 |
+
res = await client.get(url, headers=self._get_headers(token))
|
| 203 |
+
res.raise_for_status()
|
| 204 |
+
media_info = res.json()
|
| 205 |
+
media_url = media_info.get("url")
|
| 206 |
+
mime_type = media_info.get("mime_type", "application/octet-stream")
|
| 207 |
+
|
| 208 |
+
if not media_url:
|
| 209 |
+
raise ValueError("Could not retrieve media URL")
|
| 210 |
+
|
| 211 |
+
# 2. Download Binary
|
| 212 |
+
# NOTE: Media URL requires Authorization header too
|
| 213 |
+
media_res = await client.get(media_url, headers=self._get_headers(token))
|
| 214 |
+
media_res.raise_for_status()
|
| 215 |
+
|
| 216 |
+
return media_res.content, mime_type
|
| 217 |
whatsapp_cloud_service = WhatsAppCloudService()
|
| 218 |
def get_whatsapp_cloud_service() -> WhatsAppCloudService:
|
| 219 |
return whatsapp_cloud_service
|