wikimentor / modules /ai_engine.py
Rizzhi's picture
Create modules/ai_engine.py
51c18e6 verified
import os
import re
import requests
# No need for streamlit import
# No need for dotenv as secrets are loaded directly by Hugging Face Spaces environment
# from dotenv import load_dotenv
# load_dotenv() # Removed for deployment on Hugging Face Spaces
GROQ_API_KEY = os.getenv("GROQ_API_KEY") # Access API key from environment variables
# Ensure the API key is available. If not, provide a clear message.
if not GROQ_API_KEY:
print("Error: GROQ_API_KEY environment variable not set.")
# In a real app, you might want to raise an exception or handle this more robustly.
# For now, functions will return an error message if the key is missing.
GROQ_URL = "https://api.groq.com/openai/v1/chat/completions"
MODEL = "llama3-8b-8192" # Ensure this model is available and correctly spelled
HEADERS = {
"Authorization": f"Bearer {GROQ_API_KEY}",
"Content-Type": "application/json"
}
def call_groq(prompt, system="You are a helpful and concise AI tutor."):
"""
Makes a call to the Groq API with the given prompt and system message.
Handles API key availability and potential request errors.
"""
if not GROQ_API_KEY:
return "⚠️ API Key not configured. Please set GROQ_API_KEY in Hugging Face Space secrets."
payload = {
"model": MODEL,
"messages": [
{"role": "system", "content": system},
{"role": "user", "content": prompt}
],
"temperature": 0.7
}
try:
res = requests.post(GROQ_URL, headers=HEADERS, json=payload)
res.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
return res.json()["choices"][0]["message"]["content"]
except requests.exceptions.HTTPError as http_err:
print(f"Groq API HTTP error: {http_err} - {res.text}")
return f"⚠️ Groq API HTTP error: {http_err}. Details: {res.text}"
except requests.exceptions.ConnectionError as conn_err:
print(f"Groq API connection error: {conn_err}")
return "⚠️ Connection error to Groq API. Check network or API endpoint."
except requests.exceptions.Timeout as timeout_err:
print(f"Groq API timeout error: {timeout_err}")
return "⚠️ Groq API request timed out."
except requests.exceptions.RequestException as req_err:
print(f"Groq API request error: {req_err}")
return "⚠️ An unexpected error occurred with the Groq API request."
except Exception as e:
print(f"An unexpected error occurred: {e}")
return f"⚠️ An unexpected error occurred: {e}"
# Removed @st.cache_data decorator
def mentor_chat_response(query):
"""
Generates a mentor-style response for a given query using Groq.
"""
prompt = f"Explain this concept clearly in simple terms:\n\n{query}"
return call_groq(prompt)
# Removed @st.cache_data decorator
def generate_flashcards(text):
"""
Generates 5 flashcards (Q&A pairs) based on the provided text content using Groq.
Truncates text if it's too long.
"""
if len(text) > 2000:
text = text[:2000] # Truncate text if it's too long for the prompt
prompt = f"""Create 5 flashcards based on this content:\n\n{text}\n\nFormat:\nQ: ...\nA: ..."""
raw = call_groq(prompt)
print("🧠 RAW FLASHCARD RESPONSE:\n", raw) # For debugging
cards = []
# Split by "Q:" to get individual flashcard blocks. [1:] to skip empty string before first Q.
blocks = re.split(r"Q:\s*", raw)[1:]
for block in blocks:
# Split each block by "A:" to separate question and answer
parts = block.strip().split("A:")
if len(parts) == 2:
q = parts[0].strip()
# Take only the first line of the answer, assuming A: ends the answer section
a = parts[1].strip().split("\n")[0]
cards.append({"question": q, "answer": a})
return cards