File size: 4,303 Bytes
947fc76
 
 
 
4b7f264
947fc76
 
 
 
 
 
 
 
 
 
 
 
 
484d4dc
947fc76
8a15239
484d4dc
9103797
 
 
947fc76
 
 
9103797
947fc76
4b7f264
947fc76
 
 
4b7f264
947fc76
 
 
4b7f264
947fc76
 
4b7f264
947fc76
 
 
 
 
 
4b7f264
947fc76
 
 
 
 
 
 
 
 
 
 
 
4b7f264
947fc76
 
 
 
 
 
 
 
 
 
 
4b7f264
947fc76
 
4b7f264
947fc76
 
4b7f264
947fc76
 
4b7f264
947fc76
 
 
 
 
 
 
4b7f264
947fc76
 
 
 
 
 
 
 
 
 
 
4b7f264
947fc76
4b7f264
947fc76
 
 
 
 
 
 
 
 
 
 
 
 
4b7f264
947fc76
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# app.py

import os
import secrets
import gradio as gr
import requests
from gpt4all import GPT4All
from supabase import create_client, Client
from functools import lru_cache

# 1. Supabase and Model Setup 🌐
# Get your secrets from Hugging Face Space settings.
SUPABASE_URL = os.environ.get("SUPABASE_URL")
SUPABASE_KEY = os.environ.get("SUPABASE_KEY")
supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)

# Use a smaller, efficient GPT4All model for free-tier compatibility
# The model will be downloaded to the ./models directory if it doesn't exist.
# ...
model_path = "./models"
model_name = "phi-3-mini-4k-instruct-q4.gguf"

# Add this line to create the directory if it doesn't exist
os.makedirs(model_path, exist_ok=True)

if not os.path.exists(f"{model_path}/{model_name}"):
    print(f"Downloading {model_name}...")
    GPT4All(model_name, model_path=model_path, allow_download=True)

model = GPT4All(model_name, model_path=model_path)

# A simple in-memory cache to store user's memory for the current session.
# This works for a free demo where data persistence across restarts isn't required.
user_memory_cache = {}

# 2. Helper Functions for External Data and Verification 🤝
@lru_cache(maxsize=128)
def get_live_data(query):
    """
    Fetches a concise summary from DuckDuckGo's Instant Answer API.
    The @lru_cache decorator stores results to avoid repeated API calls for the same query.
    """
    try:
        search_api = f"https://api.duckduckgo.com/?q={query}&format=json"
        result = requests.get(search_api).json()
        return result.get("AbstractText", "No live data found.")
    except Exception as e:
        return f"Error fetching live data: {str(e)}"

def verify_response(user_prompt, ai_response):
    """
    A simple verification step using the same LLM.
    A more robust solution would use a separate, smaller model.
    """
    verification_prompt = (
        f"Does the following AI response directly address the user's prompt? "
        f"Answer with 'Yes' or 'No'.\n\nPrompt: {user_prompt}\nResponse: {ai_response}"
    )
    # The `generate` method is used here to get a quick response from the LLM
    verification_result = model.generate(verification_prompt)
    return "yes" in verification_result.lower()

# 3. Main Chat Function 🧠
def chat(user_prompt, history):
    """
    The main function that orchestrates the chatbot's response process.
    """
    # Use a unique ID to identify the user's session
    user_id = secrets.token_hex(16)
    
    # 3.1. Get past memory from Supabase
    memory_data = supabase.table("memory").select("query, answer").eq("user_id", user_id).order("created_at").execute()
    memory_string = "\n".join([f"User: {row['query']}\nAI: {row['answer']}" for row in memory_data.data])

    # 3.2. Get live internet data
    live_data = get_live_data(user_prompt)

    # 3.3. Combine context for the LLM
    context = f"Conversation History:\n{memory_string}\n\nLive Data:\n{live_data}\n\nUser: {user_prompt}"

    # 3.4. Generate the initial response
    ai_response = model.generate(context)

    # 3.5. Verify the response
    is_correct = verify_response(user_prompt, ai_response)
    
    final_response = ai_response
    if not is_correct:
        # If verification fails, add a note to the final response
        final_response = f"⚠️ Note: The AI's response may not fully address your prompt.\n\n{ai_response}"

    # 3.6. Store the conversation in Supabase for future memory
    supabase.table("memory").insert({
        "user_id": user_id,
        "query": user_prompt,
        "answer": final_response
    }).execute()
    
    # Add the full interaction to the chat history
    history.append((user_prompt, final_response))
    
    return "", history

# 4. Gradio UI 🎨
with gr.Blocks() as demo:
    gr.Markdown("# GPT4All Hugging Face Chatbot")
    chatbot = gr.Chatbot(label="AI Chatbot")
    msg = gr.Textbox(label="Your Prompt")
    
    # Use Gradio's queue to handle multiple users smoothly
    gr.ChatInterface(
        fn=chat,
        chatbot=chatbot,
        textbox=msg,
        examples=["What is the capital of France?", "Who is the CEO of Google?", "What is the weather like today?"],
        title="GPT4All Live Chatbot",
        theme="soft"
    ).queue()

demo.launch()