File size: 962 Bytes
39d22a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import openai
import os
from dotenv import load_dotenv

load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY")

def ask_ai(question, history=[]):
    """
    Ask a question to the AI teaching assistant.
    
    Parameters:
        question (str): User's question.
        history (list): Previous conversation history as list of dicts (optional).
    
    Returns:
        answer (str): AI's response.
    """
    # Combine chat history with new question
    messages = history + [{"role": "user", "content": question}]
    
    try:
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",  # or "gpt-4" if you have access
            messages=messages,
            temperature=0.7,
            max_tokens=500
        )
        answer = response['choices'][0]['message']['content']
        return answer, messages + [{"role": "assistant", "content": answer}]
    except Exception as e:
        return f"Error: {str(e)}", history