File size: 2,149 Bytes
eb0b460
 
04d0676
3e77d68
 
 
 
04d0676
4a898e7
 
eb0b460
ebc45d6
eb0b460
 
 
 
 
 
 
9a2d29a
 
 
87d3941
9a2d29a
 
eb0b460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a2d29a
 
 
87d3941
9a2d29a
 
eb0b460
 
3e77d68
 
 
 
 
 
 
 
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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.
    """