Spaces:
Sleeping
Sleeping
axeronis commited on
Commit ·
076e37b
1
Parent(s): 90be4ab
refactor: Add LLM modular package
Browse files
backend/app/services/llm/__init__.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
LLM Package
|
| 3 |
+
|
| 4 |
+
Modular LLM client implementation.
|
| 5 |
+
Supports Gemini with extensibility for other providers.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from .base import (
|
| 9 |
+
LLMAPIError,
|
| 10 |
+
RateLimitError,
|
| 11 |
+
TranscriptionError,
|
| 12 |
+
BaseLLMClient
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
__all__ = [
|
| 16 |
+
"LLMAPIError",
|
| 17 |
+
"RateLimitError",
|
| 18 |
+
"TranscriptionError",
|
| 19 |
+
"BaseLLMClient"
|
| 20 |
+
]
|
backend/app/services/llm/analysis.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Lead Analysis Module
|
| 3 |
+
|
| 4 |
+
Functions for analyzing leads: psychotype detection, heat score calculation.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import logging
|
| 8 |
+
from typing import List, Dict, Any, Optional
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
# =============================================================================
|
| 14 |
+
# Psychotype Analysis Prompts
|
| 15 |
+
# =============================================================================
|
| 16 |
+
|
| 17 |
+
PSYCHOTYPE_PROMPT = """Analyze these user messages and determine their DISC personality type.
|
| 18 |
+
|
| 19 |
+
Messages:
|
| 20 |
+
{messages}
|
| 21 |
+
|
| 22 |
+
Rules:
|
| 23 |
+
1. Even a single "Hi" or greeting can indicate a type (usually Influential or Steady)
|
| 24 |
+
2. Short direct messages = Dominant
|
| 25 |
+
3. Friendly, emoji-filled = Influential
|
| 26 |
+
4. Polite, patient = Steady
|
| 27 |
+
5. Detailed, analytical = Conscientious
|
| 28 |
+
|
| 29 |
+
Return ONLY one of: dominant, influential, steady, conscientious
|
| 30 |
+
If truly unclear, return "steady" as the safest default.
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
HEAT_SCORE_PROMPT = """Calculate lead heat score (0-100) based on:
|
| 34 |
+
|
| 35 |
+
Conversation:
|
| 36 |
+
{conversation}
|
| 37 |
+
|
| 38 |
+
BANT Data:
|
| 39 |
+
- Budget: {budget}
|
| 40 |
+
- Authority: {authority}
|
| 41 |
+
- Need: {need}
|
| 42 |
+
- Timeline: {timeline}
|
| 43 |
+
|
| 44 |
+
Scoring guide:
|
| 45 |
+
- 80-100: Ready to buy, all BANT clear
|
| 46 |
+
- 60-79: High interest, most BANT clear
|
| 47 |
+
- 40-59: Moderate interest, exploring
|
| 48 |
+
- 20-39: Low interest, just browsing
|
| 49 |
+
- 0-19: Not qualified, spam, or hostile
|
| 50 |
+
|
| 51 |
+
Return ONLY a number from 0 to 100.
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# =============================================================================
|
| 56 |
+
# Analysis Functions
|
| 57 |
+
# =============================================================================
|
| 58 |
+
|
| 59 |
+
async def analyze_psychotype_impl(client, messages: List[str]) -> str:
|
| 60 |
+
"""
|
| 61 |
+
Detect user's DISC personality type from messages.
|
| 62 |
+
|
| 63 |
+
Returns: dominant, influential, steady, or conscientious
|
| 64 |
+
"""
|
| 65 |
+
if not messages:
|
| 66 |
+
return "steady" # Default for empty input
|
| 67 |
+
|
| 68 |
+
messages_text = "\n".join(f"- {msg}" for msg in messages[-5:]) # Last 5
|
| 69 |
+
prompt = PSYCHOTYPE_PROMPT.format(messages=messages_text)
|
| 70 |
+
|
| 71 |
+
try:
|
| 72 |
+
response = await client.generate_response(
|
| 73 |
+
prompt=prompt,
|
| 74 |
+
temperature=0.1 # Low temperature for consistency
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
result = response["text"].strip().lower()
|
| 78 |
+
|
| 79 |
+
# Validate result
|
| 80 |
+
valid_types = ["dominant", "influential", "steady", "conscientious"]
|
| 81 |
+
for valid_type in valid_types:
|
| 82 |
+
if valid_type in result:
|
| 83 |
+
return valid_type
|
| 84 |
+
|
| 85 |
+
return "steady" # Default if parsing fails
|
| 86 |
+
|
| 87 |
+
except Exception as e:
|
| 88 |
+
logger.error(f"Psychotype analysis failed: {e}")
|
| 89 |
+
return "steady"
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
async def calculate_heat_score_impl(
|
| 93 |
+
client,
|
| 94 |
+
conversation_text: str,
|
| 95 |
+
bant_data: Dict[str, Optional[str]]
|
| 96 |
+
) -> int:
|
| 97 |
+
"""
|
| 98 |
+
Calculate lead heat score (0-100).
|
| 99 |
+
"""
|
| 100 |
+
prompt = HEAT_SCORE_PROMPT.format(
|
| 101 |
+
conversation=conversation_text[:2000], # Limit length
|
| 102 |
+
budget=bant_data.get("budget") or "Unknown",
|
| 103 |
+
authority=bant_data.get("authority") or "Unknown",
|
| 104 |
+
need=bant_data.get("need") or "Unknown",
|
| 105 |
+
timeline=bant_data.get("timeline") or "Unknown"
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
try:
|
| 109 |
+
response = await client.generate_response(
|
| 110 |
+
prompt=prompt,
|
| 111 |
+
temperature=0.1
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
result = response["text"].strip()
|
| 115 |
+
|
| 116 |
+
# Extract number
|
| 117 |
+
import re
|
| 118 |
+
numbers = re.findall(r'\d+', result)
|
| 119 |
+
if numbers:
|
| 120 |
+
score = int(numbers[0])
|
| 121 |
+
return min(100, max(0, score)) # Clamp to 0-100
|
| 122 |
+
|
| 123 |
+
return 30 # Default moderate score
|
| 124 |
+
|
| 125 |
+
except Exception as e:
|
| 126 |
+
logger.error(f"Heat score calculation failed: {e}")
|
| 127 |
+
return 30
|
backend/app/services/llm/base.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
LLM Base Client
|
| 3 |
+
|
| 4 |
+
Base classes and exceptions for LLM clients.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import logging
|
| 8 |
+
from typing import Optional, List, Dict, Any
|
| 9 |
+
from abc import ABC, abstractmethod
|
| 10 |
+
|
| 11 |
+
logger = logging.getLogger(__name__)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
# =============================================================================
|
| 15 |
+
# Exceptions
|
| 16 |
+
# =============================================================================
|
| 17 |
+
|
| 18 |
+
class LLMAPIError(Exception):
|
| 19 |
+
"""Base exception for LLM API errors."""
|
| 20 |
+
pass
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class RateLimitError(LLMAPIError):
|
| 24 |
+
"""Raised when rate limit is exceeded."""
|
| 25 |
+
pass
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class TranscriptionError(LLMAPIError):
|
| 29 |
+
"""Raised when audio transcription fails."""
|
| 30 |
+
pass
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# =============================================================================
|
| 34 |
+
# Base Client Interface
|
| 35 |
+
# =============================================================================
|
| 36 |
+
|
| 37 |
+
class BaseLLMClient(ABC):
|
| 38 |
+
"""Abstract base class for LLM clients."""
|
| 39 |
+
|
| 40 |
+
@abstractmethod
|
| 41 |
+
async def generate_response(
|
| 42 |
+
self,
|
| 43 |
+
prompt: str,
|
| 44 |
+
system_instruction: Optional[str] = None,
|
| 45 |
+
context: Optional[List[Dict[str, str]]] = None,
|
| 46 |
+
temperature: Optional[float] = None
|
| 47 |
+
) -> Dict[str, Any]:
|
| 48 |
+
"""Generate AI response."""
|
| 49 |
+
pass
|
| 50 |
+
|
| 51 |
+
@abstractmethod
|
| 52 |
+
async def analyze_psychotype(self, messages: List[str]) -> str:
|
| 53 |
+
"""Detect user's DISC personality type."""
|
| 54 |
+
pass
|
| 55 |
+
|
| 56 |
+
@abstractmethod
|
| 57 |
+
async def calculate_heat_score(
|
| 58 |
+
self,
|
| 59 |
+
conversation_text: str,
|
| 60 |
+
bant_data: Dict[str, Optional[str]]
|
| 61 |
+
) -> int:
|
| 62 |
+
"""Calculate lead heat score (0-100)."""
|
| 63 |
+
pass
|
| 64 |
+
|
| 65 |
+
@abstractmethod
|
| 66 |
+
async def generate_11_point_summary(
|
| 67 |
+
self,
|
| 68 |
+
conversation_text: str,
|
| 69 |
+
lead_name: str,
|
| 70 |
+
psychotype: str,
|
| 71 |
+
heat_score: int,
|
| 72 |
+
business_description: str = "",
|
| 73 |
+
tenant_settings: Optional[Dict[str, Any]] = None
|
| 74 |
+
) -> Dict[str, Any]:
|
| 75 |
+
"""Generate comprehensive 11-point AI summary."""
|
| 76 |
+
pass
|
| 77 |
+
|
| 78 |
+
@abstractmethod
|
| 79 |
+
async def transcribe_audio(
|
| 80 |
+
self,
|
| 81 |
+
audio_bytes: bytes,
|
| 82 |
+
mime_type: str = "audio/mp3"
|
| 83 |
+
) -> str:
|
| 84 |
+
"""Transcribe audio to text."""
|
| 85 |
+
pass
|