Spaces:
Build error
Build error
File size: 10,245 Bytes
9658a3a f811e7c 6f4cc7a 9658a3a f811e7c 6f4cc7a 9658a3a b64bf72 9658a3a 6503f13 b64bf72 9658a3a 6503f13 c1a9087 f811e7c c1a9087 9658a3a 6503f13 9658a3a f811e7c 9658a3a f811e7c 9658a3a f811e7c 9658a3a f811e7c 9658a3a f811e7c 9658a3a 6503f13 9658a3a f811e7c 9658a3a f811e7c 9658a3a f811e7c 9658a3a f811e7c 9658a3a f811e7c 9658a3a f811e7c 9658a3a f811e7c 9658a3a f811e7c 9658a3a f811e7c e11aa7e 9658a3a e11aa7e 9658a3a e11aa7e 9658a3a 6503f13 c1a9087 6503f13 c1a9087 6503f13 f811e7c c1a9087 6503f13 f811e7c 6503f13 c1a9087 9658a3a 6503f13 | 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 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 | import os
from dotenv import load_dotenv
from langchain_groq import ChatGroq
from typing import Optional
from langchain_pinecone import PineconeVectorStore
from pinecone import Pinecone
from langchain_openai import OpenAIEmbeddings, ChatOpenAI
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langgraph.graph import StateGraph
from langgraph.prebuilt import tools_condition
from langgraph.prebuilt import ToolNode
from langchain_core.messages import HumanMessage, SystemMessage, AIMessage
from langgraph.checkpoint.memory import MemorySaver
from langchain.tools.retriever import create_retriever_tool
from pydantic import BaseModel
from langchain_community.document_loaders import PyPDFLoader, Docx2txtLoader
from langchain_core.documents import Document
from langgraph.graph import MessagesState
import gradio as gr
import uuid
# Load environment variables
load_dotenv()
# Access environment variables
PINECONE_API_KEY = os.environ["PINECONE_API_KEY"]
OPENAI_API_KEY = os.environ["OPENAI_API_KEY"]
GROQ_API_KEY = os.environ["GROQ_API_KEY"]
LANGCHAIN_API_KEY = os.environ["LANGCHAIN_API_KEY"]
# Set environment variables (if needed by your environment)
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
os.environ["GROQ_API_KEY"] = GROQ_API_KEY
os.environ["LANGCHAIN_API_KEY"] = LANGCHAIN_API_KEY
os.environ["PINECONE_API_KEY"] = PINECONE_API_KEY
os.environ["LANGCHAIN_TRACING_V2"] = "true"
os.environ["LANGCHAIN_ENDPOINT"] = "https://api.smith.langchain.com"
os.environ["LANGCHAIN_PROJECT"] = "Demo Upwork"
# Initialize Pinecone client
pc = Pinecone(api_key=PINECONE_API_KEY)
index_name = "goldmine-amazon"
# Initialize embeddings
embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
# Initialize LLM
llama_3_1 = "llama-3.1-8b-instant"
llama_3_3 = "llama-3.3-70b-versatile"
gpt = "gpt-4o-mini"
# llm = ChatOpenAI(model=gpt, temperature=0.2)
llm = ChatGroq(model=llama_3_3, temperature=0.2)
def delete_vectors():
"""Delete all vectors in the Pinecone index."""
try:
index = pc.Index(index_name)
index.delete(delete_all=True)
return "All vectors in the index have been successfully deleted."
except Exception as e:
return f"An error occurred while deleting vectors: {str(e)}"
def process_docs_and_get_retriever(
doc_path: str, collection_name: str = "user_data", k: int = 4
):
"""
Load a document (PDF or DOCX), split its content,
add it to Pinecone, and return a retriever.
"""
if doc_path.endswith(".pdf"):
try:
loader = PyPDFLoader(doc_path)
docs = loader.load_and_split()
except Exception as e:
print(f"Error loading PDF: {e}")
return None
elif doc_path.endswith(".docx"):
try:
loader = Docx2txtLoader(doc_path)
docs = loader.load()
except Exception as e:
print(f"Error loading DOCX: {e}")
return None
else:
print("Unsupported file format. Please provide a .pdf or .docx file.")
return None
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=500,
chunk_overlap=50,
separators=["# ", "## ", "### ", "\n\n", "\n- ", ". ", " "],
)
splits = text_splitter.split_documents(docs)
vector_store = PineconeVectorStore.from_documents(
documents=splits, embedding=embeddings, index_name=index_name
)
return "All Data added"
def process_text_as_retriever(text: str):
"""
Process plain text, split it into chunks, add to Pinecone, and return a retriever.
"""
docs = [Document(page_content=text)]
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=500,
chunk_overlap=50,
separators=["# ", "## ", "### ", "\n\n", "\n- ", ". ", " "],
)
splits = text_splitter.split_documents(docs)
vector_store = PineconeVectorStore.from_documents(
documents=splits, embedding=embeddings, index_name=index_name
)
return vector_store.as_retriever(search_kwargs={"k": 4})
def recreate_retriever():
"""Recreate the retriever dynamically using Pinecone."""
vector_store = PineconeVectorStore(index_name=index_name, embedding=embeddings)
return vector_store.as_retriever(search_kwargs={"k": 4})
# Optionally load an initial document
doc_path = "./data/docs/goldmine.docx"
retriever_doc = process_docs_and_get_retriever(doc_path)
print("Retriever is ready:", retriever_doc)
tools = []
retriever = recreate_retriever()
retriever_tool = create_retriever_tool(
retriever, "retriever_tool", "Search and return information for user query."
)
tools.append(retriever_tool)
class State(MessagesState):
query: str
doc_path: Optional[str]
def vector_data(state: State):
if "doc_path" in state and state["doc_path"]:
print("\n\n********** ADDING DATA TO VECTOR STORE **********\n\n")
doc_path = state["doc_path"]
process_docs_and_get_retriever(doc_path)
return {
"doc_path": "",
"messages": [
AIMessage(content="Document successfully added to the knowledge base.")
],
}
else:
return {"doc_path": ""}
def call_model(state: State):
messages = state.get("messages", [])
query = state.get("query", "").strip()
if not query:
return {
"messages": [
AIMessage(
content="No query provided. You can now ask questions about the uploaded document."
)
]
}
sys_msg = SystemMessage(
content="""You are a helpful assistant.
Your main task is to assist the user by providing accurate information using the retriever_tool.
Reply in the same language as the user's query.
If you do not find the information needed to answer the user's question, clearly state:
'I do not have the information you are looking for. If you just added new information, you might try asking your question again.'
Then, politely ask the user to update the knowledge base with relevant details.
Do not use any tool for greetings or small talk.
Do not provide answers based on assumptions or unsupported information.
Always rely solely on the retrieved content."""
)
message = HumanMessage(content=query)
messages.append(message)
print(f"WE ARE PASSING THIS TO THE LLM: \n\n*******\n{messages}\n*******\n\n")
llm_with_tools = llm.bind_tools(tools)
response = llm_with_tools.invoke([sys_msg] + messages)
return {"messages": response}
# Build workflow
workflow = StateGraph(State)
workflow.add_node("vector_data", vector_data)
workflow.add_node("call_model", call_model)
workflow.add_node("tools", ToolNode(tools))
workflow.set_entry_point("vector_data")
workflow.add_edge("vector_data", "call_model")
workflow.add_conditional_edges(
"call_model", tools_condition, path_map=["tools", "__end__"]
)
workflow.add_edge("tools", "call_model")
memory = MemorySaver()
react_graph = workflow.compile(checkpointer=memory)
# Global thread ID
thread_id_number = str(uuid.uuid4())
def call_graph(user_input, config, doc_path=None):
"""
Processes the user input and document path with the graph.
Args:
user_input (str): The user's query.
config (dict): Graph configuration including thread ID.
doc_path (str, optional): Path to the document being processed.
"""
state = {}
if user_input:
state["query"] = user_input
if doc_path:
state["doc_path"] = doc_path
events = react_graph.stream(state, config, stream_mode="values")
response = None
for event in events:
if "messages" in event and event["messages"]:
response = event["messages"][-1].content
if doc_path and not user_input:
response = "Document successfully added to the knowledge base."
return response
def process_user_input(message, file):
global thread_id_number
print(f"DEBUG: Received message: {message}")
print(f"DEBUG: Received file: {file}")
config = {"configurable": {"thread_id": thread_id_number}}
user_text = message.get("text", "").strip() if message else ""
doc_path = None
if message and "files" in message and message["files"]:
doc_path = message["files"][0]
if user_text or doc_path:
try:
response = call_graph(
user_input=user_text, config=config, doc_path=doc_path
)
print(f"DEBUG: AI Response: {response}")
if response and isinstance(response, str) and response.strip():
return response
else:
return "I'm processing your request. Please wait..."
except Exception as e:
print(f"ERROR: {e}")
return "An error occurred while processing your request. Please try again."
else:
return (
"No message or document provided. Please send a query or attach a document."
)
def reset_thread_and_delete():
"""
Reset the global thread_id_number to treat the next user messages as a new conversation.
Also delete all vectors in the Pinecone index.
"""
global thread_id_number
thread_id_number = str(uuid.uuid4())
status = delete_vectors()
# Return only the deletion status now; we are NOT trying to clear the chat box.
return status
with gr.Blocks() as app:
chat_interface = gr.ChatInterface(
fn=process_user_input,
type="messages",
multimodal=True,
title="Multimodal Chatbot",
description="Ask questions and optionally upload a document (PDF or DOCX).",
)
with gr.Row():
delete_btn = gr.Button("🧹 Delete All Vectors (Knowledge Base)", variant="stop")
deletion_status = gr.Textbox(
label="Deletion Status",
interactive=False,
placeholder="Deletion status will appear here...",
)
# Now we only return the deletion status
delete_btn.click(
fn=reset_thread_and_delete,
inputs=[],
outputs=deletion_status,
api_name="delete_vectors",
)
app.launch(ssr_mode=False)
|