Artech15 commited on
Commit
947fc76
·
verified ·
1 Parent(s): bc53b19

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +99 -55
app.py CHANGED
@@ -1,70 +1,114 @@
 
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
 
 
 
4
 
5
- def respond(
6
- message,
7
- history: list[dict[str, str]],
8
- system_message,
9
- max_tokens,
10
- temperature,
11
- top_p,
12
- hf_token: gr.OAuthToken,
13
- ):
14
  """
15
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
 
16
  """
17
- client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
 
 
 
 
 
18
 
19
- messages = [{"role": "system", "content": system_message}]
20
-
21
- messages.extend(history)
 
 
 
 
 
 
 
 
 
22
 
23
- messages.append({"role": "user", "content": message})
 
 
 
 
 
 
 
 
 
 
24
 
25
- response = ""
 
26
 
27
- for message in client.chat_completion(
28
- messages,
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
- response += token
40
- yield response
41
 
 
 
 
 
 
 
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- chatbot = gr.ChatInterface(
47
- respond,
48
- type="messages",
49
- additional_inputs=[
50
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
51
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
52
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
53
- gr.Slider(
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
- with gr.Sidebar():
65
- gr.LoginButton()
66
- chatbot.render()
67
-
 
 
 
 
 
 
 
 
 
68
 
69
- if __name__ == "__main__":
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()