Download app.py from Artech15/Ar_Bot_2: direct link, hf CLI and curl.
- Browser
- Download file 4.3 kB
-
https://huggingface.co/spaces/Artech15/Ar_Bot_2/resolve/main/app.py
- Command line
-
hf download hf://spaces/Artech15/Ar_Bot_2/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Artech15/Ar_Bot_2/resolve/main/app.py
4.3 kB
| # 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 🤝 | |
| 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() |