Update app.py
Browse files
app.py
CHANGED
|
@@ -1,70 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
system_message,
|
| 9 |
-
max_tokens,
|
| 10 |
-
temperature,
|
| 11 |
-
top_p,
|
| 12 |
-
hf_token: gr.OAuthToken,
|
| 13 |
-
):
|
| 14 |
"""
|
| 15 |
-
|
|
|
|
| 16 |
"""
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
-
|
|
|
|
| 26 |
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
max_tokens=max_tokens,
|
| 30 |
-
stream=True,
|
| 31 |
-
temperature=temperature,
|
| 32 |
-
top_p=top_p,
|
| 33 |
-
):
|
| 34 |
-
choices = message.choices
|
| 35 |
-
token = ""
|
| 36 |
-
if len(choices) and choices[0].delta.content:
|
| 37 |
-
token = choices[0].delta.content
|
| 38 |
|
| 39 |
-
|
| 40 |
-
|
| 41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
""
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
minimum=0.1,
|
| 55 |
-
maximum=1.0,
|
| 56 |
-
value=0.95,
|
| 57 |
-
step=0.05,
|
| 58 |
-
label="Top-p (nucleus sampling)",
|
| 59 |
-
),
|
| 60 |
-
],
|
| 61 |
-
)
|
| 62 |
|
|
|
|
| 63 |
with gr.Blocks() as demo:
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
-
|
| 70 |
-
demo.launch()
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import secrets
|
| 5 |
import gradio as gr
|
| 6 |
+
import requests
|
| 7 |
+
from gpt4all import GPT4All
|
| 8 |
+
from supabase import create_client, Client
|
| 9 |
+
from functools import lru_cache
|
| 10 |
+
|
| 11 |
+
# 1. Supabase and Model Setup 🌐
|
| 12 |
+
# Get your secrets from Hugging Face Space settings.
|
| 13 |
+
SUPABASE_URL = os.environ.get("SUPABASE_URL")
|
| 14 |
+
SUPABASE_KEY = os.environ.get("SUPABASE_KEY")
|
| 15 |
+
supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)
|
| 16 |
+
|
| 17 |
+
# Use a smaller, efficient GPT4All model for free-tier compatibility
|
| 18 |
+
# The model will be downloaded to the ./models directory if it doesn't exist.
|
| 19 |
+
model_name = "ggml-gpt4all-v1.3-4b-snoozy.bin"
|
| 20 |
+
model_path = "./models"
|
| 21 |
+
if not os.path.exists(f"{model_path}/{model_name}"):
|
| 22 |
+
print(f"Downloading {model_name}...")
|
| 23 |
+
GPT4All(model_name, model_path=model_path, allow_download=True)
|
| 24 |
+
model = GPT4All(model_name, model_path=model_path)
|
| 25 |
|
| 26 |
+
# A simple in-memory cache to store user's memory for the current session.
|
| 27 |
+
# This works for a free demo where data persistence across restarts isn't required.
|
| 28 |
+
user_memory_cache = {}
|
| 29 |
|
| 30 |
+
# 2. Helper Functions for External Data and Verification 🤝
|
| 31 |
+
@lru_cache(maxsize=128)
|
| 32 |
+
def get_live_data(query):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
"""
|
| 34 |
+
Fetches a concise summary from DuckDuckGo's Instant Answer API.
|
| 35 |
+
The @lru_cache decorator stores results to avoid repeated API calls for the same query.
|
| 36 |
"""
|
| 37 |
+
try:
|
| 38 |
+
search_api = f"https://api.duckduckgo.com/?q={query}&format=json"
|
| 39 |
+
result = requests.get(search_api).json()
|
| 40 |
+
return result.get("AbstractText", "No live data found.")
|
| 41 |
+
except Exception as e:
|
| 42 |
+
return f"Error fetching live data: {str(e)}"
|
| 43 |
|
| 44 |
+
def verify_response(user_prompt, ai_response):
|
| 45 |
+
"""
|
| 46 |
+
A simple verification step using the same LLM.
|
| 47 |
+
A more robust solution would use a separate, smaller model.
|
| 48 |
+
"""
|
| 49 |
+
verification_prompt = (
|
| 50 |
+
f"Does the following AI response directly address the user's prompt? "
|
| 51 |
+
f"Answer with 'Yes' or 'No'.\n\nPrompt: {user_prompt}\nResponse: {ai_response}"
|
| 52 |
+
)
|
| 53 |
+
# The `generate` method is used here to get a quick response from the LLM
|
| 54 |
+
verification_result = model.generate(verification_prompt)
|
| 55 |
+
return "yes" in verification_result.lower()
|
| 56 |
|
| 57 |
+
# 3. Main Chat Function 🧠
|
| 58 |
+
def chat(user_prompt, history):
|
| 59 |
+
"""
|
| 60 |
+
The main function that orchestrates the chatbot's response process.
|
| 61 |
+
"""
|
| 62 |
+
# Use a unique ID to identify the user's session
|
| 63 |
+
user_id = secrets.token_hex(16)
|
| 64 |
+
|
| 65 |
+
# 3.1. Get past memory from Supabase
|
| 66 |
+
memory_data = supabase.table("memory").select("query, answer").eq("user_id", user_id).order("created_at").execute()
|
| 67 |
+
memory_string = "\n".join([f"User: {row['query']}\nAI: {row['answer']}" for row in memory_data.data])
|
| 68 |
|
| 69 |
+
# 3.2. Get live internet data
|
| 70 |
+
live_data = get_live_data(user_prompt)
|
| 71 |
|
| 72 |
+
# 3.3. Combine context for the LLM
|
| 73 |
+
context = f"Conversation History:\n{memory_string}\n\nLive Data:\n{live_data}\n\nUser: {user_prompt}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
+
# 3.4. Generate the initial response
|
| 76 |
+
ai_response = model.generate(context)
|
| 77 |
|
| 78 |
+
# 3.5. Verify the response
|
| 79 |
+
is_correct = verify_response(user_prompt, ai_response)
|
| 80 |
+
|
| 81 |
+
final_response = ai_response
|
| 82 |
+
if not is_correct:
|
| 83 |
+
# If verification fails, add a note to the final response
|
| 84 |
+
final_response = f"⚠️ Note: The AI's response may not fully address your prompt.\n\n{ai_response}"
|
| 85 |
|
| 86 |
+
# 3.6. Store the conversation in Supabase for future memory
|
| 87 |
+
supabase.table("memory").insert({
|
| 88 |
+
"user_id": user_id,
|
| 89 |
+
"query": user_prompt,
|
| 90 |
+
"answer": final_response
|
| 91 |
+
}).execute()
|
| 92 |
+
|
| 93 |
+
# Add the full interaction to the chat history
|
| 94 |
+
history.append((user_prompt, final_response))
|
| 95 |
+
|
| 96 |
+
return "", history
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
|
| 98 |
+
# 4. Gradio UI 🎨
|
| 99 |
with gr.Blocks() as demo:
|
| 100 |
+
gr.Markdown("# GPT4All Hugging Face Chatbot")
|
| 101 |
+
chatbot = gr.Chatbot(label="AI Chatbot")
|
| 102 |
+
msg = gr.Textbox(label="Your Prompt")
|
| 103 |
+
|
| 104 |
+
# Use Gradio's queue to handle multiple users smoothly
|
| 105 |
+
gr.ChatInterface(
|
| 106 |
+
fn=chat,
|
| 107 |
+
chatbot=chatbot,
|
| 108 |
+
textbox=msg,
|
| 109 |
+
examples=["What is the capital of France?", "Who is the CEO of Google?", "What is the weather like today?"],
|
| 110 |
+
title="GPT4All Live Chatbot",
|
| 111 |
+
theme="soft"
|
| 112 |
+
).queue()
|
| 113 |
|
| 114 |
+
demo.launch()
|
|
|