I am facing issue in running sentiment analysis api with openai while I have fullfilled all the basic code which i got from google bard
API
Dec 24
1h ago
This is the first time Zikriya has posted — let’s welcome them to our community!
Zikriya
1h
import openai
Set your OpenAI API key (replace with your actual key)
openai.api_key = “my key was here Now I have removed it”
def sentiment_analysis(text):
“”"Analyzes the sentiment of a given text using OpenAI’s completions API.
Args:
text (str): The text to analyze.
Returns:
str: The determined sentiment (positive, negative, or not sure).
"""
Create a prompt for the model
prompt = f"""You are trained to analyze and detect the sentiment of the given text.
If you are unsure of an answer, you can say "not sure" and recommend the user review manually.
Analyze the following text and determine if the sentiment is: Positive, Negative, or Neutral.
{text}"""
Call the OpenAI API to generate a response
response = openai.Completion.create(
model="text-davinci-003", # Use a powerful model for sentiment analysis
prompt=prompt,
max_tokens=1, # Limit response to a single word
n=1,
stop=None,
temperature=0 # Keep response consistent
)
Extract the sentiment from the response
sentiment = response.choices[0].text.strip().lower()
return sentiment
Example usage
input_text = “I’m very happy with the product!”
sentiment = sentiment_analysis(input_text)
print(input_text, “: Sentiment is:”, sentiment)