Spaces:
Build error
Build error
Download app.py from Alekzan87/load_document_chatbot_2: direct link, hf CLI and curl.
- Browser
- Download file 10.2 kB
-
https://huggingface.co/spaces/Alekzan87/load_document_chatbot_2/resolve/main/app.py
- Command line
-
hf download hf://spaces/Alekzan87/load_document_chatbot_2/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Alekzan87/load_document_chatbot_2/resolve/main/app.py
10.2 kB
| 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) | |