-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathask_openai.py
More file actions
executable file
·48 lines (37 loc) · 1.38 KB
/
ask_openai.py
File metadata and controls
executable file
·48 lines (37 loc) · 1.38 KB
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
#!/usr/bin/env python3
import os
import sys
from dotenv import load_dotenv
from openai import OpenAI
def ask_openai(prompt):
load_dotenv()
openai_api_key = os.getenv("OPENAI_API_KEY")
if not openai_api_key:
print("Missing OpenAI API Key")
sys.exit(1)
client = OpenAI(api_key=openai_api_key)
try:
response = client.chat.completions.create(model="gpt-3.5-turbo-0125",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": prompt}
])
# Write response to a file
with open("response.json", "w") as f:
f.write(str(response))
return response.choices[0].message.content.strip()
except Exception as e:
print("Error while fetching quote:", e)
return None
if __name__ == "__main__":
while True:
question = input("Enter a question (or type 'exit' to quit): ")
if question.lower() == 'exit':
print("Exiting the chat.")
break
answer = ask_openai(question)
if answer:
print(answer)
print() # Empty line
else:
print("Failed to fetch answer from OpenAI.")