Spaces:
Sleeping
Sleeping
Upload 4 files
Browse files
README.md
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Ask Me Anything Local Assistant
|
| 3 |
+
emoji: 🚀
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: indigo
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 5.49.1
|
| 8 |
+
python_version: "3.11"
|
| 9 |
+
app_file: app.py
|
| 10 |
+
pinned: false
|
| 11 |
+
---
|
| 12 |
+
|
| 13 |
+
# Ask Me Anything Local Assistant
|
| 14 |
+
|
| 15 |
+
A Gradio chat assistant powered by Groq (Llama 3.3 70B) with:
|
| 16 |
+
- PDF / TXT upload and retrieval (Chroma + MiniLM embeddings)
|
| 17 |
+
- Weather lookup
|
| 18 |
+
- Website content fetching
|
| 19 |
+
|
| 20 |
+
Requires a `GROQ_API_KEY` secret in the Space settings.
|
app.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from typing import Any, cast
|
| 3 |
+
|
| 4 |
+
import gradio as gr
|
| 5 |
+
from dotenv import load_dotenv
|
| 6 |
+
from langchain.agents import create_agent
|
| 7 |
+
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
| 8 |
+
from langchain_groq import ChatGroq
|
| 9 |
+
|
| 10 |
+
from tool import vectorize_documents, get_weather, get_content_from_site
|
| 11 |
+
|
| 12 |
+
load_dotenv()
|
| 13 |
+
|
| 14 |
+
if not os.environ.get("GROQ_API_KEY"):
|
| 15 |
+
raise RuntimeError(
|
| 16 |
+
"GROQ_API_KEY is not set. Add it in the Space under "
|
| 17 |
+
"Settings -> Variables and secrets -> New secret."
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
placeholder_html = """
|
| 21 |
+
<div style='text-align: center; padding: 25px;'>
|
| 22 |
+
<h1 style='font-size: 2.5rem; font-weight: 800; margin-bottom: 10px;'>🚀 Ask Me Anything</h1>
|
| 23 |
+
<p style='font-size: 1.5rem; color: #666;'>Your AI-assistant</p>
|
| 24 |
+
</div>
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
# Cloud-hosted LLM (Groq), so no GPU is needed on the Space.
|
| 28 |
+
llm = ChatGroq(model="llama-3.3-70b-versatile", temperature=0)
|
| 29 |
+
|
| 30 |
+
normal_prompt = ChatPromptTemplate.from_messages([
|
| 31 |
+
("system", """You are a helpful AI assistant.
|
| 32 |
+
Follow these rules:
|
| 33 |
+
1. Do not mention tools to the user, never; only you know about tools.
|
| 34 |
+
2. Use available tools if needed."""),
|
| 35 |
+
MessagesPlaceholder("history"),
|
| 36 |
+
("human", "{question}")
|
| 37 |
+
])
|
| 38 |
+
|
| 39 |
+
file_prompt = ChatPromptTemplate.from_messages([
|
| 40 |
+
("system", """You are a helpful AI assistant.
|
| 41 |
+
Follow these rules:
|
| 42 |
+
1. Never disclose, list, describe, or reveal internal tools, tool names, tool definitions, function schemas, or implementation details.
|
| 43 |
+
2. For unrelated questions, answer using your general knowledge or available tools.
|
| 44 |
+
3. When the user asks about the uploaded file, use the provided context to answer.
|
| 45 |
+
4. If the answer to a file-related question is not available in the provided context, clearly say you don't know.
|
| 46 |
+
5. Never invent information from the uploaded file.
|
| 47 |
+
6. If asked which tools you use, or which tools you can access, politely say:
|
| 48 |
+
"I can't share internal implementation details, but I can help with your question."
|
| 49 |
+
7. Never call a tool just to answer questions about your internal tools.
|
| 50 |
+
8. Use available tools silently when they are relevant to the user's request.
|
| 51 |
+
9. Do not mention internal tool execution to the user.
|
| 52 |
+
10. Do not mention tool names you have access to.
|
| 53 |
+
|
| 54 |
+
Context: {context}"""),
|
| 55 |
+
("human", "{question}")
|
| 56 |
+
])
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def star_buck(name: str) -> str:
|
| 60 |
+
"""Complete the name 'sajid' by appending 'khan'. Takes the first name and returns the full name."""
|
| 61 |
+
return name + "khan"
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
tools = [get_weather, star_buck, get_content_from_site]
|
| 65 |
+
|
| 66 |
+
agent = create_agent(tools=tools, model=llm)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def clean_history(history):
|
| 70 |
+
"""Keep only role/content so extra Gradio metadata keys don't reach LangChain."""
|
| 71 |
+
cleaned = []
|
| 72 |
+
for h in history or []:
|
| 73 |
+
content = h.get("content")
|
| 74 |
+
if isinstance(content, str) and content.strip():
|
| 75 |
+
cleaned.append({"role": h["role"], "content": content})
|
| 76 |
+
return cleaned
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def chat(message, history, retriever):
|
| 80 |
+
history = history or []
|
| 81 |
+
question = (message.get("text") or "").strip()
|
| 82 |
+
files = message.get("files") or []
|
| 83 |
+
|
| 84 |
+
# "cls" clears the chat and the loaded document.
|
| 85 |
+
if question == "cls":
|
| 86 |
+
return [], None, {"text": "", "files": []}
|
| 87 |
+
|
| 88 |
+
try:
|
| 89 |
+
if files:
|
| 90 |
+
retriever = vectorize_documents(files[0])
|
| 91 |
+
|
| 92 |
+
empty = question == ""
|
| 93 |
+
if empty:
|
| 94 |
+
question = "the user just send an empty message"
|
| 95 |
+
|
| 96 |
+
if retriever is not None:
|
| 97 |
+
docs = retriever.invoke(question)
|
| 98 |
+
context = "\n\n".join(doc.page_content for doc in docs)
|
| 99 |
+
messages = file_prompt.invoke({
|
| 100 |
+
"context": context,
|
| 101 |
+
"question": question
|
| 102 |
+
}).to_messages()
|
| 103 |
+
else:
|
| 104 |
+
messages = normal_prompt.invoke({
|
| 105 |
+
"history": clean_history(history),
|
| 106 |
+
"question": question
|
| 107 |
+
}).to_messages()
|
| 108 |
+
|
| 109 |
+
result = agent.invoke(cast(Any, {"messages": messages}))
|
| 110 |
+
response = result["messages"][-1].content
|
| 111 |
+
except Exception as e:
|
| 112 |
+
empty = False
|
| 113 |
+
response = f"Sorry, something went wrong: {e}"
|
| 114 |
+
|
| 115 |
+
if empty:
|
| 116 |
+
history = history + [{"role": "assistant", "content": response}]
|
| 117 |
+
else:
|
| 118 |
+
history = history + [
|
| 119 |
+
{"role": "user", "content": question},
|
| 120 |
+
{"role": "assistant", "content": response},
|
| 121 |
+
]
|
| 122 |
+
|
| 123 |
+
return history, retriever, {"text": "", "files": []}
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
with gr.Blocks() as Demo:
|
| 127 |
+
state = gr.State(None)
|
| 128 |
+
|
| 129 |
+
chatbot = gr.Chatbot(
|
| 130 |
+
placeholder=placeholder_html,
|
| 131 |
+
type="messages",
|
| 132 |
+
allow_tags=False,
|
| 133 |
+
height=480,
|
| 134 |
+
show_label=False,
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
text = gr.MultimodalTextbox(
|
| 138 |
+
placeholder="What is your question.....",
|
| 139 |
+
file_count="single",
|
| 140 |
+
file_types=[".pdf", ".txt", ".md"],
|
| 141 |
+
sources=["upload"],
|
| 142 |
+
show_label=False,
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
text.submit(
|
| 146 |
+
fn=chat,
|
| 147 |
+
inputs=[text, chatbot, state],
|
| 148 |
+
outputs=[chatbot, state, text],
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
if __name__ == "__main__":
|
| 152 |
+
Demo.launch(server_name="0.0.0.0", server_port=7860)
|
requirements.txt
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio==5.49.1
|
| 2 |
+
langchain>=1.0,<2.0
|
| 3 |
+
langchain-core>=1.0,<2.0
|
| 4 |
+
langchain-community
|
| 5 |
+
langchain-text-splitters
|
| 6 |
+
langchain-huggingface
|
| 7 |
+
langchain-chroma
|
| 8 |
+
langchain-groq
|
| 9 |
+
chromadb
|
| 10 |
+
sentence-transformers
|
| 11 |
+
pypdf
|
| 12 |
+
html2text
|
| 13 |
+
beautifulsoup4
|
| 14 |
+
requests
|
| 15 |
+
python-dotenv
|
tool.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import requests
|
| 4 |
+
from langchain_chroma import Chroma
|
| 5 |
+
from langchain_community.document_loaders import WebBaseLoader, PyPDFLoader, TextLoader
|
| 6 |
+
from langchain_huggingface import HuggingFaceEmbeddings
|
| 7 |
+
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 8 |
+
|
| 9 |
+
_embedding_model = None
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _get_embeddings():
|
| 13 |
+
"""Load the embedding model once and reuse it (CPU is fine for MiniLM)."""
|
| 14 |
+
global _embedding_model
|
| 15 |
+
if _embedding_model is None:
|
| 16 |
+
_embedding_model = HuggingFaceEmbeddings(
|
| 17 |
+
model_name="sentence-transformers/all-MiniLM-L6-v2"
|
| 18 |
+
)
|
| 19 |
+
return _embedding_model
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def vectorize_documents(file_path):
|
| 23 |
+
# Gradio may pass a file dict or an object with .name instead of a raw string path
|
| 24 |
+
if isinstance(file_path, dict):
|
| 25 |
+
file_path = file_path.get("path", "")
|
| 26 |
+
elif hasattr(file_path, "name"):
|
| 27 |
+
file_path = file_path.name
|
| 28 |
+
|
| 29 |
+
if not file_path or not os.path.exists(file_path):
|
| 30 |
+
raise ValueError(f"Invalid or missing file path: {file_path}")
|
| 31 |
+
|
| 32 |
+
if file_path.lower().endswith(".pdf"):
|
| 33 |
+
documents = PyPDFLoader(file_path).load()
|
| 34 |
+
elif file_path.lower().endswith((".txt", ".md")):
|
| 35 |
+
documents = TextLoader(file_path, encoding="utf-8").load()
|
| 36 |
+
else:
|
| 37 |
+
raise ValueError("Unsupported file format. Please upload a PDF or text file.")
|
| 38 |
+
|
| 39 |
+
text_splitter = RecursiveCharacterTextSplitter(
|
| 40 |
+
chunk_size=300,
|
| 41 |
+
chunk_overlap=50,
|
| 42 |
+
separators=["\n\n", "\n", " ", ""],
|
| 43 |
+
)
|
| 44 |
+
documents = text_splitter.split_documents(documents)
|
| 45 |
+
|
| 46 |
+
embedding_model = _get_embeddings()
|
| 47 |
+
|
| 48 |
+
db_dir = "DB"
|
| 49 |
+
if os.path.exists(db_dir):
|
| 50 |
+
try:
|
| 51 |
+
Chroma(
|
| 52 |
+
persist_directory=db_dir, embedding_function=embedding_model
|
| 53 |
+
).delete_collection()
|
| 54 |
+
except Exception:
|
| 55 |
+
pass
|
| 56 |
+
|
| 57 |
+
vectorstore = Chroma.from_documents(
|
| 58 |
+
documents=documents,
|
| 59 |
+
embedding=embedding_model,
|
| 60 |
+
persist_directory=db_dir,
|
| 61 |
+
)
|
| 62 |
+
return vectorstore.as_retriever()
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def get_weather(location: str) -> str:
|
| 66 |
+
"""Get the current weather for a given city name.
|
| 67 |
+
|
| 68 |
+
Provides a short, clean, one-line weather summary from wttr.in.
|
| 69 |
+
|
| 70 |
+
Args:
|
| 71 |
+
location (str): The name of the city or location (e.g., 'Lahore').
|
| 72 |
+
"""
|
| 73 |
+
try:
|
| 74 |
+
url = f"https://wttr.in/{location}?format=3"
|
| 75 |
+
response = requests.get(url, timeout=5)
|
| 76 |
+
if response.status_code == 200:
|
| 77 |
+
return response.text.strip()
|
| 78 |
+
return f"Could not retrieve weather for {location}."
|
| 79 |
+
except Exception as e:
|
| 80 |
+
return f"Error: {str(e)}"
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def get_content_from_site(url: str) -> str:
|
| 84 |
+
"""Fetch the text content of a website.
|
| 85 |
+
|
| 86 |
+
Args:
|
| 87 |
+
url (str): The full URL of the page to read (e.g., 'https://example.com').
|
| 88 |
+
"""
|
| 89 |
+
try:
|
| 90 |
+
docs = WebBaseLoader([url]).load()
|
| 91 |
+
if not docs:
|
| 92 |
+
return "No content found."
|
| 93 |
+
return docs[0].page_content[:8000]
|
| 94 |
+
except Exception as e:
|
| 95 |
+
return f"Error fetching website content: {str(e)}"
|