Commit
·
17d9293
1
Parent(s):
2c591bd
Add openai support
Browse files- openai_api.py +36 -0
openai_api.py
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import openai
|
2 |
+
from openai import OpenAI
|
3 |
+
import json
|
4 |
+
import os
|
5 |
+
|
6 |
+
# Set your OpenAI API key (replace with your actual key)
|
7 |
+
openai.api_key = os.getenv("OPENAI_KEY")
|
8 |
+
|
9 |
+
# Initialize the OpenAI client
|
10 |
+
client = OpenAI(api_key=openai.api_key)
|
11 |
+
|
12 |
+
def model_api(input, prompt_type):
|
13 |
+
return prompt_type(input)
|
14 |
+
|
15 |
+
def sentiment(text):
|
16 |
+
# Create a prompt for the model
|
17 |
+
prompt = f"""You are trained to analyze and detect the sentiment of the given text.
|
18 |
+
If you are unsure of an answer, you can say "not sure" and recommend the user review manually.
|
19 |
+
Analyze the following text and determine if the sentiment is: Positive, Negative, or Neutral.
|
20 |
+
{text}"""
|
21 |
+
|
22 |
+
# Call the OpenAI API to generate a response
|
23 |
+
response = client.chat.completions.create(
|
24 |
+
model="gpt-3.5-turbo", # Use a powerful model for sentiment analysis
|
25 |
+
messages=[
|
26 |
+
{"role": "system", "content": "You are a helpful assistant."},
|
27 |
+
{"role": "user", "content": prompt}
|
28 |
+
],
|
29 |
+
max_tokens=1, # Limit response to a single word
|
30 |
+
temperature=0 # Keep response consistent
|
31 |
+
)
|
32 |
+
|
33 |
+
# Extract the sentiment from the response
|
34 |
+
sentiment = response.choices[0].message.content.strip().lower()
|
35 |
+
|
36 |
+
return sentiment
|