ScratchGPT / app.py
WillemVH's picture
Update app.py
87d3941 verified
import scratchattach as sa
from groq import Groq
import os
from flask import Flask, request
import requests
import re
from threading import Thread
sessionid = os.getenv("ID")
useridname = os.getenv("USR")
# Initialize Scratch session
session = sa.login_by_id(sessionid, username=useridname)
cloud = session.connect_cloud("1183313747")
client = cloud.requests()
# Initialize Groq client
groq_client = Groq(api_key="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")
# Global chat history list
chat_history = [
{
"role": "system",
"content": "You are a helpful AI assistant that only responds in plain text. Also, you are on scratch. like ur literally an api on scratch.mit.edu. Please be as kind as you can and make sure all code works before sharing. Thanks!"
}
]
# Request 1: Get Groq response (with context retention)
@client.request
def get_groq_response(user_input):
global chat_history
try:
# Add user input to history
chat_history.append({"role": "user", "content": user_input})
# Get response from Groq (with full history)
chat_completion = groq_client.chat.completions.create(
messages=chat_history,
model="deepseek-r1-distill-llama-70b",
)
# Extract and store the AI's response
ai_response = chat_completion.choices[0].message.content
chat_history.append({"role": "assistant", "content": ai_response})
return ai_response
except Exception as e:
return f"Error: {str(e)}"
# Request 2: Clear chat history
@client.request
def clear_history():
global chat_history
chat_history = [
{
"role": "system",
"content": "You are a helpful AI assistant that only responds in plain text. Also, you are on scratch. like ur literally an api on scratch.mit.edu. Please be as kind as you can and make sure all code works before sharing. Thanks!"
}
]
return "Chat history cleared!"
client.start(thread=True)
app = Flask(__name__)
@app.route('/')
def index():
return """
Go to https://scratch.mit.edu/projects/1183313747/ for a live demo of this program.
"""