File size: 9,971 Bytes
d35f0b4
 
 
 
cab10e5
 
d35f0b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cab10e5
d35f0b4
cab10e5
 
d35f0b4
4036c2e
cab10e5
d35f0b4
 
4036c2e
cab10e5
 
 
 
4036c2e
cab10e5
 
 
 
4036c2e
d35f0b4
cab10e5
d35f0b4
4036c2e
d35f0b4
 
 
cab10e5
d35f0b4
 
cab10e5
d35f0b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cab10e5
 
 
 
d35f0b4
 
 
 
 
 
cab10e5
d35f0b4
cab10e5
d35f0b4
 
cab10e5
d35f0b4
 
 
 
 
 
 
cab10e5
 
 
d35f0b4
cab10e5
 
d35f0b4
 
 
cab10e5
 
 
 
 
 
d35f0b4
 
cab10e5
 
 
 
d35f0b4
cab10e5
d35f0b4
 
 
 
 
 
 
 
 
 
cab10e5
d35f0b4
 
cab10e5
d35f0b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cab10e5
d35f0b4
 
 
 
 
 
 
 
 
 
 
 
cab10e5
 
d35f0b4
 
 
cab10e5
 
d35f0b4
 
 
 
 
 
 
 
 
 
 
 
cab10e5
d35f0b4
 
 
cab10e5
d35f0b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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

PINECONE_API_KEY = os.getenv("PINECONE_API_KEY")

# Set environment variables
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")
os.environ["GROQ_API_KEY"] = os.getenv("GROQ_API_KEY")
os.environ["LANGCHAIN_API_KEY"] = os.getenv("LANGCHAIN_API_KEY")
os.environ["PINECONE_API_KEY"] = os.getenv("PINECONE_API_KEY")
os.environ["LANGCHAIN_TRACING_V2"] = "true"
os.environ["LANGCHAIN_ENDPOINT"] = "https://api.smith.langchain.com"
os.environ["LANGCHAIN_PROJECT"] = "Demo Upwork"
# os.environ["PINECONE_API_KEY"] = PINECONE_API_KEY

# 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
gpt = "gpt-4o-mini"
llm = ChatOpenAI(model=gpt, temperature=0.2)


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.
    """
    # Step 1: Determine document type and load it
    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

    # Step 2: Split the text into manageable chunks
    text_splitter = RecursiveCharacterTextSplitter(
        chunk_size=500,
        chunk_overlap=50,
        separators=["# ", "## ", "### ", "\n\n", "\n- ", ". ", " "],
    )
    splits = text_splitter.split_documents(docs)

    # Step 3: Initialize Pinecone vector store and add documents
    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 it to Pinecone, and return a retriever.
    """
    # Create Document object from text
    docs = [Document(page_content=text)]

    # Split the text into manageable chunks
    text_splitter = RecursiveCharacterTextSplitter(
        chunk_size=500,
        chunk_overlap=50,
        separators=["# ", "## ", "### ", "\n\n", "\n- ", ". ", " "],
    )
    splits = text_splitter.split_documents(docs)

    # Initialize Pinecone vector store and add documents
    vector_store = PineconeVectorStore.from_documents(
        documents=splits, embedding=embeddings, index_name=index_name
    )

    # Create and return the retriever
    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})


# Initialize first document if needed
doc_path = "./data/docs/goldmine.docx"
retriever_doc = process_docs_and_get_retriever(doc_path)
print("Retriever is ready:", retriever_doc)

# Create tools
tools = []
retriever = recreate_retriever()
retriever_tool = create_retriever_tool(
    retriever,
    "retriever_tool",
    "Search and return information for user query.",
)
tools.append(retriever_tool)


# Rest of the code remains the same...
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. 
        Always answer based only on the information retrieved with the retriever_tool.
        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 provide answers based on assumptions, external knowledge, 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}


# Setup 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)


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.

    Returns:
        str: The response from the graph.
    """
    # Prepare the initial state
    state = {}

    # Add the query if it exists
    if user_input:
        state["query"] = user_input

    # Add `doc_path` if it exists
    if doc_path:
        state["doc_path"] = doc_path

    # Stream events from the graph
    events = react_graph.stream(state, config, stream_mode="values")

    response = None  # Initialize response
    for event in events:
        # Retrieve the last message content from the graph's output
        if "messages" in event and event["messages"]:
            response = event["messages"][-1].content

    # Handle case where no query but document is uploaded
    if doc_path and not user_input:
        response = "Document successfully added to the knowledge base."

    return response


# Generate a persistent thread ID once
thread_id_number = str(uuid.uuid4())


def process_user_input(message, file):
    global thread_id_number  # Ensure we're using the same thread ID across calls

    # Debug input
    print(f"DEBUG: Received message: {message}")
    print(f"DEBUG: Received file: {file}")

    # Reuse the existing thread ID for the graph configuration
    config = {"configurable": {"thread_id": thread_id_number}}

    # Extract user message
    user_text = message.get("text", "").strip() if message else ""

    # Extract doc_path from message["files"]
    doc_path = None
    if message and "files" in message and message["files"]:
        doc_path = message["files"][0]  # First file in the list

    # Call the graph with the extracted text and/or document path
    if user_text or doc_path:  # Ensure at least one input is provided
        try:
            response = call_graph(
                user_input=user_text, config=config, doc_path=doc_path
            )
            print(f"DEBUG: AI Response: {response}")

            # Return meaningful content
            if response and isinstance(response, str) and response.strip():
                return response
            else:
                return "I'm processing your request. Please wait for further results or actions."
        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."
        )


# Gradio interface
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).",
    )

# Launch the app
app.launch()