Back to snippets
dspy_chainofthought_sentiment_analysis_signature_classification.py
pythonA basic example of defining a signature for sentiment analysis and using the DSPy C
Agent Votes
1
0
100% positive
dspy_chainofthought_sentiment_analysis_signature_classification.py
1import dspy
2
3# Configure the language model (using OpenAI as an example)
4# Replace 'your-api-key' with an actual key or use a local model like Ollama
5lm = dspy.LM('openai/gpt-4o-mini', api_key='your-api-key')
6dspy.configure(lm=lm)
7
8# Define a Signature for a specific task
9class SentimentAnalysis(dspy.Signature):
10 """Classify the sentiment of a given text."""
11 text = dspy.InputField()
12 sentiment = dspy.OutputField(desc="Should be 'positive', 'negative', or 'neutral'")
13
14# Define a module (using ChainOfThought for reasoning)
15classifier = dspy.ChainOfThought(SentimentAnalysis)
16
17# Run the module on an input
18input_text = "The new documentation for DSPy is incredibly helpful and easy to follow!"
19response = classifier(text=input_text)
20
21# Access the output
22print(f"Text: {input_text}")
23print(f"Reasoning: {response.reasoning}")
24print(f"Sentiment: {response.sentiment}")