Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,15 +2,17 @@ import gradio as gr
|
|
| 2 |
from huggingface_hub import InferenceClient
|
| 3 |
from typing import List, Tuple
|
| 4 |
import logging
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
# Configure logging
|
| 7 |
logging.basicConfig(
|
| 8 |
level=logging.INFO,
|
| 9 |
format="%(asctime)s - %(levelname)s - %(message)s",
|
| 10 |
)
|
| 11 |
logger = logging.getLogger(__name__)
|
| 12 |
|
| 13 |
-
# Initialize the InferenceClient
|
| 14 |
try:
|
| 15 |
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
| 16 |
logger.info("Successfully initialized InferenceClient")
|
|
@@ -18,6 +20,34 @@ except Exception as e:
|
|
| 18 |
logger.error(f"Failed to initialize InferenceClient: {str(e)}")
|
| 19 |
raise
|
| 20 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
def respond(
|
| 22 |
message: str,
|
| 23 |
history: List[Tuple[str, str]],
|
|
@@ -27,7 +57,7 @@ def respond(
|
|
| 27 |
top_p: float,
|
| 28 |
) -> str:
|
| 29 |
"""
|
| 30 |
-
Generates an educational response
|
| 31 |
Args:
|
| 32 |
message (str): The student's input question or query.
|
| 33 |
history (List[Tuple[str, str]]): Chat history with student and AI teacher messages.
|
|
@@ -37,9 +67,6 @@ def respond(
|
|
| 37 |
top_p (float): Controls diversity via nucleus sampling.
|
| 38 |
Yields:
|
| 39 |
str: The AI teacher's response, streamed token by token.
|
| 40 |
-
Raises:
|
| 41 |
-
ValueError: If input parameters are invalid.
|
| 42 |
-
RuntimeError: If the API call fails.
|
| 43 |
"""
|
| 44 |
# Validate input parameters
|
| 45 |
if not message.strip():
|
|
@@ -51,8 +78,16 @@ def respond(
|
|
| 51 |
if top_p < 0.1 or top_p > 1.0:
|
| 52 |
raise ValueError("top_p must be between 0.1 and 1.0")
|
| 53 |
|
| 54 |
-
#
|
| 55 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
for user_msg, assistant_msg in history:
|
| 57 |
if user_msg:
|
| 58 |
messages.append({"role": "user", "content": user_msg})
|
|
@@ -72,6 +107,8 @@ def respond(
|
|
| 72 |
token = message.choices[0].delta.content or ""
|
| 73 |
response += token
|
| 74 |
yield response
|
|
|
|
|
|
|
| 75 |
except Exception as e:
|
| 76 |
logger.error(f"Error during chat completion: {str(e)}")
|
| 77 |
raise RuntimeError("Failed to generate response from the model")
|
|
@@ -80,7 +117,6 @@ def main():
|
|
| 80 |
"""
|
| 81 |
Sets up and launches the Gradio ChatInterface for the AI Teacher chatbot.
|
| 82 |
"""
|
| 83 |
-
# Define default system message for an AI teacher
|
| 84 |
default_system_message = (
|
| 85 |
"You are an AI Teacher, a knowledgeable and patient educator dedicated to helping students and learners. "
|
| 86 |
"Your goal is to explain concepts clearly, provide step-by-step guidance, and encourage critical thinking. "
|
|
@@ -88,7 +124,6 @@ def main():
|
|
| 88 |
"Be supportive, professional, and engaging in all interactions."
|
| 89 |
)
|
| 90 |
|
| 91 |
-
# Create Gradio ChatInterface with settings compatible with older Gradio versions
|
| 92 |
demo = gr.ChatInterface(
|
| 93 |
fn=respond,
|
| 94 |
additional_inputs=[
|
|
@@ -104,7 +139,6 @@ def main():
|
|
| 104 |
value=512,
|
| 105 |
step=1,
|
| 106 |
label="Maximum Response Length",
|
| 107 |
-
info="Controls the maximum length of the AI Teacher's response.",
|
| 108 |
),
|
| 109 |
gr.Slider(
|
| 110 |
minimum=0.1,
|
|
@@ -112,7 +146,6 @@ def main():
|
|
| 112 |
value=0.7,
|
| 113 |
step=0.1,
|
| 114 |
label="Response Creativity",
|
| 115 |
-
info="Lower values make responses more focused and precise.",
|
| 116 |
),
|
| 117 |
gr.Slider(
|
| 118 |
minimum=0.1,
|
|
@@ -120,7 +153,6 @@ def main():
|
|
| 120 |
value=0.95,
|
| 121 |
step=0.05,
|
| 122 |
label="Response Diversity",
|
| 123 |
-
info="Lower values focus on more likely and relevant answers.",
|
| 124 |
),
|
| 125 |
],
|
| 126 |
title="AI Teacher: Your Study Companion",
|
|
@@ -138,7 +170,6 @@ def main():
|
|
| 138 |
""",
|
| 139 |
)
|
| 140 |
|
| 141 |
-
# Launch the application
|
| 142 |
try:
|
| 143 |
logger.info("Launching Gradio interface for AI Teacher")
|
| 144 |
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
| 2 |
from huggingface_hub import InferenceClient
|
| 3 |
from typing import List, Tuple
|
| 4 |
import logging
|
| 5 |
+
from collections import deque
|
| 6 |
+
import re
|
| 7 |
|
| 8 |
+
# Configure logging
|
| 9 |
logging.basicConfig(
|
| 10 |
level=logging.INFO,
|
| 11 |
format="%(asctime)s - %(levelname)s - %(message)s",
|
| 12 |
)
|
| 13 |
logger = logging.getLogger(__name__)
|
| 14 |
|
| 15 |
+
# Initialize the InferenceClient
|
| 16 |
try:
|
| 17 |
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
| 18 |
logger.info("Successfully initialized InferenceClient")
|
|
|
|
| 20 |
logger.error(f"Failed to initialize InferenceClient: {str(e)}")
|
| 21 |
raise
|
| 22 |
|
| 23 |
+
# Memory storage for learning from past queries
|
| 24 |
+
MEMORY = deque(maxlen=100) # Store up to 100 query-response pairs
|
| 25 |
+
|
| 26 |
+
def add_to_memory(query: str, response: str):
|
| 27 |
+
"""Add a query-response pair to memory."""
|
| 28 |
+
MEMORY.append({"query": query, "response": response})
|
| 29 |
+
logger.info("Added query-response pair to memory")
|
| 30 |
+
|
| 31 |
+
def find_relevant_context(query: str, max_contexts: int = 2) -> str:
|
| 32 |
+
"""Retrieve relevant past queries and responses based on simple keyword matching."""
|
| 33 |
+
query_words = set(re.findall(r'\w+', query.lower()))
|
| 34 |
+
relevant = []
|
| 35 |
+
|
| 36 |
+
for mem in MEMORY:
|
| 37 |
+
mem_words = set(re.findall(r'\w+', mem["query"].lower()))
|
| 38 |
+
overlap = len(query_words & mem_words) / max(len(query_words), 1)
|
| 39 |
+
if overlap > 0.3: # Threshold for relevance
|
| 40 |
+
relevant.append(mem)
|
| 41 |
+
if len(relevant) >= max_contexts:
|
| 42 |
+
break
|
| 43 |
+
|
| 44 |
+
if relevant:
|
| 45 |
+
context = "\n".join(
|
| 46 |
+
[f"Past Query: {mem['query']}\nPast Response: {mem['response']}" for mem in relevant]
|
| 47 |
+
)
|
| 48 |
+
return f"Relevant past interactions:\n{context}\n\n"
|
| 49 |
+
return ""
|
| 50 |
+
|
| 51 |
def respond(
|
| 52 |
message: str,
|
| 53 |
history: List[Tuple[str, str]],
|
|
|
|
| 57 |
top_p: float,
|
| 58 |
) -> str:
|
| 59 |
"""
|
| 60 |
+
Generates an educational response using past interactions for context.
|
| 61 |
Args:
|
| 62 |
message (str): The student's input question or query.
|
| 63 |
history (List[Tuple[str, str]]): Chat history with student and AI teacher messages.
|
|
|
|
| 67 |
top_p (float): Controls diversity via nucleus sampling.
|
| 68 |
Yields:
|
| 69 |
str: The AI teacher's response, streamed token by token.
|
|
|
|
|
|
|
|
|
|
| 70 |
"""
|
| 71 |
# Validate input parameters
|
| 72 |
if not message.strip():
|
|
|
|
| 78 |
if top_p < 0.1 or top_p > 1.0:
|
| 79 |
raise ValueError("top_p must be between 0.1 and 1.0")
|
| 80 |
|
| 81 |
+
# Retrieve relevant past interactions
|
| 82 |
+
context = find_relevant_context(message)
|
| 83 |
+
|
| 84 |
+
# Construct the message history with memory context
|
| 85 |
+
messages = [
|
| 86 |
+
{
|
| 87 |
+
"role": "system",
|
| 88 |
+
"content": system_message + "\n\nUse the following past interactions to inform your response if relevant:\n" + context,
|
| 89 |
+
}
|
| 90 |
+
]
|
| 91 |
for user_msg, assistant_msg in history:
|
| 92 |
if user_msg:
|
| 93 |
messages.append({"role": "user", "content": user_msg})
|
|
|
|
| 107 |
token = message.choices[0].delta.content or ""
|
| 108 |
response += token
|
| 109 |
yield response
|
| 110 |
+
# Store the query and final response in memory
|
| 111 |
+
add_to_memory(message, response)
|
| 112 |
except Exception as e:
|
| 113 |
logger.error(f"Error during chat completion: {str(e)}")
|
| 114 |
raise RuntimeError("Failed to generate response from the model")
|
|
|
|
| 117 |
"""
|
| 118 |
Sets up and launches the Gradio ChatInterface for the AI Teacher chatbot.
|
| 119 |
"""
|
|
|
|
| 120 |
default_system_message = (
|
| 121 |
"You are an AI Teacher, a knowledgeable and patient educator dedicated to helping students and learners. "
|
| 122 |
"Your goal is to explain concepts clearly, provide step-by-step guidance, and encourage critical thinking. "
|
|
|
|
| 124 |
"Be supportive, professional, and engaging in all interactions."
|
| 125 |
)
|
| 126 |
|
|
|
|
| 127 |
demo = gr.ChatInterface(
|
| 128 |
fn=respond,
|
| 129 |
additional_inputs=[
|
|
|
|
| 139 |
value=512,
|
| 140 |
step=1,
|
| 141 |
label="Maximum Response Length",
|
|
|
|
| 142 |
),
|
| 143 |
gr.Slider(
|
| 144 |
minimum=0.1,
|
|
|
|
| 146 |
value=0.7,
|
| 147 |
step=0.1,
|
| 148 |
label="Response Creativity",
|
|
|
|
| 149 |
),
|
| 150 |
gr.Slider(
|
| 151 |
minimum=0.1,
|
|
|
|
| 153 |
value=0.95,
|
| 154 |
step=0.05,
|
| 155 |
label="Response Diversity",
|
|
|
|
| 156 |
),
|
| 157 |
],
|
| 158 |
title="AI Teacher: Your Study Companion",
|
|
|
|
| 170 |
""",
|
| 171 |
)
|
| 172 |
|
|
|
|
| 173 |
try:
|
| 174 |
logger.info("Launching Gradio interface for AI Teacher")
|
| 175 |
demo.launch(server_name="0.0.0.0", server_port=7860)
|