|
from llms import LLM |
|
from utils.remote_client import execute_remote_task |
|
|
|
def sentiment_analysis(text: str, model: str, custom_instructions: str = "", use_llm: bool = True) -> str: |
|
""" |
|
Analyze sentiment of text using either LLM or traditional (Modal API) method. |
|
|
|
Args: |
|
text: The text to analyze |
|
model: The model to use |
|
custom_instructions: Optional instructions for LLM |
|
use_llm: Whether to use LLM or traditional method |
|
""" |
|
if not text.strip(): |
|
return "" |
|
if use_llm: |
|
return _sentiment_with_llm(text, model, custom_instructions) |
|
else: |
|
return _sentiment_with_traditional(text, model) |
|
|
|
def _sentiment_with_llm(text: str, model: str, custom_instructions: str = "") -> str: |
|
try: |
|
llm = LLM(model=model) |
|
prompt = ( |
|
f"Analyze the sentiment of the following text. Return ONLY one value: 'positive', 'negative', or 'neutral'.\n" + |
|
(f"{custom_instructions}\n" if custom_instructions else "") + |
|
f"Text: {text}\nSentiment:" |
|
) |
|
result = llm.generate(prompt) |
|
return result.strip() |
|
except Exception as e: |
|
print(f"Error in LLM sentiment analysis: {str(e)}") |
|
return "Oops! Something went wrong. Please try again later." |
|
|
|
def _sentiment_with_traditional(text: str, model: str) -> str: |
|
try: |
|
payload = { |
|
"text": text, |
|
"model": model, |
|
"task": "sentiment" |
|
} |
|
resp = execute_remote_task("classification", payload) |
|
if "error" in resp: |
|
return "Oops! Something went wrong. Please try again later." |
|
return resp.get("labels", "") |
|
except Exception as e: |
|
print(f"Error in traditional sentiment analysis: {str(e)}") |
|
return "Oops! Something went wrong. Please try again later." |
|
|