File size: 9,421 Bytes
df0bb25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from typing import TypedDict, Annotated, List
from typing_extensions import List, TypedDict

from dotenv import load_dotenv
import chainlit as cl
import operator

from langchain.prompts import ChatPromptTemplate
from langchain.retrievers.contextual_compression import ContextualCompressionRetriever
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_cohere import CohereRerank
from langchain_community.document_loaders import DirectoryLoader
from langchain_community.tools.arxiv.tool import ArxivQueryRun
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_core.documents import Document
from langchain_core.messages import BaseMessage, HumanMessage
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langchain_qdrant import QdrantVectorStore
from langgraph.graph import START, StateGraph, END
from langgraph.graph.message import add_messages
from langgraph.prebuilt import ToolNode
from qdrant_client import QdrantClient
from qdrant_client.http.models import Distance, VectorParams

from langgraph.graph import START, StateGraph
from typing_extensions import List, TypedDict
from langchain_core.documents import Document



load_dotenv()

##-----------------------------------------------------------------------------------
#                       reading data
##-----------------------------------------------------------------------------------

path = "Data/"
loader = DirectoryLoader(path, glob="*.html")
docs = loader.load()



##-----------------------------------------------------------------------------------
#                       OTHER TOOLS
##-----------------------------------------------------------------------------------
tavily_tool = TavilySearchResults(max_results=5)
arxiv_tool = ArxivQueryRun()




##-----------------------------------------------------------------------------------
#                       R - PREPATION OF THE GRAPH RAG
##-----------------------------------------------------------------------------------
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1024, chunk_overlap=128)
split_documents = text_splitter.split_documents(docs)

embeddings = OpenAIEmbeddings(model="text-embedding-3-small")

client = QdrantClient(":memory:")

client.create_collection(
    collection_name="obesity_challange",
    vectors_config=VectorParams(size=1536, distance=Distance.COSINE),
)

vector_store = QdrantVectorStore(
    client=client,
    collection_name="obesity_challange",
    embedding=embeddings,
)

_ = vector_store.add_documents(documents=split_documents)

retriever = vector_store.as_retriever(search_kwargs={"k": 5})

def retrieve_adjusted(state):
    compressor = CohereRerank(model="rerank-v3.5", top_n=10)
    compression_retriever = ContextualCompressionRetriever(
        base_compressor=compressor, base_retriever=retriever, search_kwargs={"k": 5}
    )
    retrieved_docs = compression_retriever.invoke(state["question"])
    return {"context": retrieved_docs}


RAG_PROMPT = """\
You are a helpful assistant who answers questions based on provided context. You must only use the provided context, and cannot use your own knowledge.
### Question
{question}
### Context
{context}
"""



##-----------------------------------------------------------------------------------
#                       G - PREPARATION OF GRAPH RAG
##-----------------------------------------------------------------------------------

rag_prompt = ChatPromptTemplate.from_template(RAG_PROMPT)

llm = ChatOpenAI(model="gpt-4o-mini")

def generate(state):
  docs_content = "\n\n".join(doc.page_content for doc in state["context"])
  messages = rag_prompt.format_messages(question=state["question"], context=docs_content)
  response = llm.invoke(messages)
  return {"response" : response.content}


##-----------------------------------------------------------------------------------
#                       GRAPH RAG 
##-----------------------------------------------------------------------------------


class State(TypedDict):
  question: str
  context: List[Document]
  response: str

graph_rag_builder = StateGraph(State).add_sequence([retrieve_adjusted, generate])
graph_rag_builder.add_edge(START, "retrieve_adjusted")
graph_rag = graph_rag_builder.compile()


##-----------------------------------------------------------------------------------
#                       TOOLS PREPATION FOR AGENT
##-----------------------------------------------------------------------------------

@tool
def obesity_rag_tool(question: str) -> str:
  """Useful for when you need to answer questions about artificial intelligence. Input should be a fully formed question."""
  response = graph_rag.invoke({"question" : question})
  return {
        "messages": [HumanMessage(content=response["response"])],
        "context": response["context"]
    }

tool_belt = [
    tavily_tool,
    arxiv_tool,
    obesity_rag_tool
]


##-----------------------------------------------------------------------------------
#                       MODELS WITH TOOLS
##-----------------------------------------------------------------------------------

model = ChatOpenAI(model="gpt-4.1-mini", temperature=0)
model = model.bind_tools(tool_belt)

##-----------------------------------------------------------------------------------
#                       AGENT GRAPH
##-----------------------------------------------------------------------------------

class AgentState(TypedDict):
  messages: Annotated[list, add_messages]
  context: List[Document]

tool_node = ToolNode(tool_belt)

uncompiled_graph = StateGraph(AgentState)

def call_model(state):
  messages = state["messages"]
  response = model.invoke(messages)
  return {
        "messages": [response],
        "context": state.get("context", [])
    }

uncompiled_graph.add_node("agent", call_model)
uncompiled_graph.add_node("action", tool_node)

uncompiled_graph.set_entry_point("agent")

def should_continue(state):
  last_message = state["messages"][-1]

  if last_message.tool_calls:
    return "action"

  return END

uncompiled_graph.add_conditional_edges(
    "agent",
    should_continue
)

uncompiled_graph.add_edge("action", "agent")

compiled_graph = uncompiled_graph.compile()

#------------------------------------------------------------------------

# @cl.on_chat_start
# async def start():
#   cl.user_session.set("graph", compiled_graph)
#   await cl.Message(content="Hello! I'm ready to help with your questions.").send()

# @cl.on_message
# async def handle(message: cl.Message):
#   graph = cl.user_session.get("graph")
#   state = {"messages" : [HumanMessage(content=message.content)]}
#   response = await graph.ainvoke(state)
#   await cl.Message(content=response["messages"][-1].content).send()

@cl.on_chat_start
async def start():
    # Initialize with the compiled graph
    cl.user_session.set("graph", compiled_graph)
    
    # Initialize an empty state with the structure expected by your graph
    initial_state = {"messages": [], "context": []}
    cl.user_session.set("state", initial_state)
    
    # Send a welcome message to the UI
    welcome_message = """
# πŸ‘‹ Hello! I am a specialized assistant focused on obesity research and health information.

I'm designed to provide evidence-based information from trusted sources including:
- πŸ“š NIH Director's Blog on obesity research
- πŸ”¬ Scientific definitions and classifications
- πŸ“Š Data-driven insights about health impacts
- 🩺 Information about treatment approaches

**My goal is to provide accurate, non-judgmental information about obesity as a health condition.**

How can I assist with your obesity-related questions today?
    """
    
    await cl.Message(content=welcome_message).send()

@cl.on_message
async def handle(message: cl.Message):
    # Show typing indicator
    thinking = cl.Message(content="Thinking...")
    await thinking.send()
    
    try:
        # Get the graph and current state
        graph = cl.user_session.get("graph")
        current_state = cl.user_session.get("state", {"messages": [], "context": []})
        
        # Add the new user message to the existing messages
        updated_messages = current_state["messages"] + [HumanMessage(content=message.content)]
        
        # Create an updated state
        updated_state = {
            "messages": updated_messages,
            "context": current_state.get("context", [])
        }
        
        # Invoke the graph with the updated state
        response = await graph.ainvoke(updated_state)
        
        # Store the updated state for the next interaction
        cl.user_session.set("state", response)
        
        # Remove the typing indicator
        await thinking.remove()
        
        # Get the latest message (the AI's response)
        if response["messages"] and len(response["messages"]) > len(updated_messages):
            ai_message = response["messages"][-1]
            await cl.Message(content=ai_message.content).send()
        else:
            # Fallback if no new message was added
            await cl.Message(content="I'm sorry, I couldn't generate a response.").send()
            
    except Exception as e:
        # Handle any errors
        error_message = f"Error processing your request: {str(e)}"
        await thinking.update(content=error_message)
        print(f"Error: {str(e)}")