File size: 1,482 Bytes
2c3b1dc | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | import requests
LABELS = ["sadness", "joy", "love", "anger", "fear", "surprise"]
FEW_SHOT_EXAMPLES = """Message: "I got the promotion!"
Answer: joy
Message: "I bought this and I'm not happy with it"
Answer: anger
Message: "I'm not afraid of you"
Answer: joy
Message: "I am afraid of the dark"
Answer: fear
Message: "This isn't what I expected"
Answer: sadness
Message: "I can't stop thinking about her"
Answer: love"""
def classify(text, model="llama3.2:3b"):
prompt = f"""Classify the emotion in each message as exactly one word from: sadness, joy, love, anger, fear, surprise.
Pay close attention to negation words like "not", "isn't", "don't" — they reverse or change the emotion.
{FEW_SHOT_EXAMPLES}
Message: "{text}"
Answer:"""
response = requests.post(
"http://localhost:11434/api/generate",
json={"model": model, "prompt": prompt, "stream": False},
)
raw = response.json()["response"].strip().lower()
first_line = raw.splitlines()[0] if raw else ""
for label in LABELS:
if label in first_line:
return label
for label in LABELS:
if label in raw:
return label
return "surprise"
if __name__ == "__main__":
tests = [
"I'm not happy",
"I'm not afraid",
"I am afraid",
"I bought this and I'm not happy with it",
]
for t in tests:
print(f"{t!r} -> {classify(t)}") |