Create chatbot.py
Browse files- utils/chatbot.py +32 -0
utils/chatbot.py
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import openai
|
2 |
+
import os
|
3 |
+
from dotenv import load_dotenv
|
4 |
+
|
5 |
+
load_dotenv()
|
6 |
+
openai.api_key = os.getenv("OPENAI_API_KEY")
|
7 |
+
|
8 |
+
def ask_ai(question, history=[]):
|
9 |
+
"""
|
10 |
+
Ask a question to the AI teaching assistant.
|
11 |
+
|
12 |
+
Parameters:
|
13 |
+
question (str): User's question.
|
14 |
+
history (list): Previous conversation history as list of dicts (optional).
|
15 |
+
|
16 |
+
Returns:
|
17 |
+
answer (str): AI's response.
|
18 |
+
"""
|
19 |
+
# Combine chat history with new question
|
20 |
+
messages = history + [{"role": "user", "content": question}]
|
21 |
+
|
22 |
+
try:
|
23 |
+
response = openai.ChatCompletion.create(
|
24 |
+
model="gpt-3.5-turbo", # or "gpt-4" if you have access
|
25 |
+
messages=messages,
|
26 |
+
temperature=0.7,
|
27 |
+
max_tokens=500
|
28 |
+
)
|
29 |
+
answer = response['choices'][0]['message']['content']
|
30 |
+
return answer, messages + [{"role": "assistant", "content": answer}]
|
31 |
+
except Exception as e:
|
32 |
+
return f"Error: {str(e)}", history
|