2025-12-07 17:50:08 +02:00
|
|
|
from utils.llm import query_llama
|
2025-12-07 17:15:09 +02:00
|
|
|
|
|
|
|
|
async def analyze_sentiment(messages: list) -> tuple[str, float]:
|
|
|
|
|
"""
|
2025-12-07 17:50:08 +02:00
|
|
|
Analyze the sentiment of a conversation using llama.cpp
|
2025-12-07 17:15:09 +02:00
|
|
|
Returns a tuple of (sentiment description, positivity score from 0-1)
|
|
|
|
|
"""
|
|
|
|
|
# Combine the last few messages for context (up to 5)
|
|
|
|
|
messages_to_analyze = messages[-5:] if len(messages) > 5 else messages
|
|
|
|
|
conversation_text = "\n".join([
|
|
|
|
|
f"{'Bot' if msg['is_bot_message'] else 'User'}: {msg['content']}"
|
|
|
|
|
for msg in messages_to_analyze
|
|
|
|
|
])
|
|
|
|
|
|
|
|
|
|
prompt = f"""Analyze the sentiment and tone of this conversation snippet between a user and a bot.
|
|
|
|
|
Focus on the overall mood, engagement level, and whether the interaction seems positive/neutral/negative.
|
|
|
|
|
Give a brief 1-2 sentence summary and a positivity score from 0-1 where:
|
|
|
|
|
0.0-0.3 = Negative/Hostile
|
|
|
|
|
0.3-0.7 = Neutral/Mixed
|
|
|
|
|
0.7-1.0 = Positive/Friendly
|
|
|
|
|
|
|
|
|
|
Conversation:
|
|
|
|
|
{conversation_text}
|
|
|
|
|
|
|
|
|
|
Format your response exactly like this example:
|
|
|
|
|
Summary: The conversation is friendly and engaging with good back-and-forth.
|
|
|
|
|
Score: 0.85
|
|
|
|
|
|
|
|
|
|
Response:"""
|
|
|
|
|
|
|
|
|
|
try:
|
2025-12-07 17:50:08 +02:00
|
|
|
response = await query_llama(prompt)
|
2025-12-07 17:15:09 +02:00
|
|
|
if not response or 'Score:' not in response:
|
|
|
|
|
return "Could not analyze sentiment", 0.5
|
|
|
|
|
|
|
|
|
|
# Parse the response
|
|
|
|
|
lines = response.strip().split('\n')
|
|
|
|
|
summary = lines[0].replace('Summary:', '').strip()
|
|
|
|
|
score = float(lines[1].replace('Score:', '').strip())
|
|
|
|
|
|
|
|
|
|
return summary, score
|
|
|
|
|
except Exception as e:
|
|
|
|
|
print(f"Error in sentiment analysis: {e}")
|
|
|
|
|
return "Error analyzing sentiment", 0.5
|