File size: 853 Bytes
9b28320
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8a9836
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from langchain.tools import tool
from transformers import pipeline

class SentimentTools:
    def __init__(self):
        self.sentiment_pipeline = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")

    @tool("Analyze Sentiment")
    def analyze_sentiment(self, text):
        """Analyzes the sentiment of a given text."""
        # Limit the input text to 512 tokens to ensure faster processing
        truncated_text = ' '.join(text.split()[:512])
        result = self.sentiment_pipeline(truncated_text)[0]
        sentiment = result['label']
        score = result['score']

        if sentiment == 'POSITIVE':
            return "Positive" if score > 0.6 else "Neutral"
        elif sentiment == 'NEGATIVE':
            return "Negative" if score > 0.6 else "Neutral"
        else:
            return "Neutral"