-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadaptive_rag.py
394 lines (357 loc) · 14.1 KB
/
adaptive_rag.py
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
#################################################################
# Adaptive RAG: Adaptive RAG is a strategy for RAG that unites: #
# (1).query analysis #
# (2).active / self-corrective RAG #
# #
# Paper: https://arxiv.org/abs/2403.14403 #
#################################################################
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from typing import Annotated, Sequence, Literal, Union, Final
from dotenv import load_dotenv
import os
from typing import Literal
from langchain_core.prompts import ChatPromptTemplate
from pydantic import BaseModel, Field
from langchain import hub
from langchain_core.output_parsers import StrOutputParser
from langchain_community.tools.tavily_search import TavilySearchResults
from typing import List
from typing_extensions import TypedDict
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_community.document_loaders import WebBaseLoader
from langchain_community.vectorstores import Chroma
from langgraph.graph import END, StateGraph, START
from IPython.display import Image, display
from langchain.schema import Document
load_dotenv()
class ModelTools():
DEFAULT_MODEL: Final = "openai"
MODEL_TEMPERATURE: Final = 0
OPENAI_MODEL_NAME: Final = "gpt-4o" # or gpt-4o-mini
OPENAI_EMBEDDING_MODEL_NAME: Final = "text-embedding-3-large"
OPENAI_API_KEY: Final = os.getenv("OPENAI_API_KEY")
OPENAI_BASE_URL: Final = os.getenv("OPENAI_BASE_URL")
@staticmethod
def get_llm(
model_name: str = DEFAULT_MODEL,
with_tools: bool = False
) -> Union[ChatOpenAI]:
if model_name == "openai":
llm = ChatOpenAI(
model_name=ModelTools.OPENAI_MODEL_NAME,
temperature=ModelTools.MODEL_TEMPERATURE,
openai_api_key=ModelTools.OPENAI_API_KEY,
base_url=ModelTools.OPENAI_BASE_URL,
)
else:
raise ValueError(f"Model {model_name} not found")
if with_tools:
llm = llm.bind_tools(tools)
return llm
@staticmethod
def get_embed(model_name: str = DEFAULT_MODEL) -> Union[OpenAIEmbeddings]:
if model_name == "openai":
embd = OpenAIEmbeddings(
model=ModelTools.OPENAI_EMBEDDING_MODEL_NAME,
openai_api_key=ModelTools.OPENAI_API_KEY,
base_url=ModelTools.OPENAI_BASE_URL,
)
return embd
################
# Create Index #
################
# Set embeddings
embd = ModelTools.get_embed()
# Docs to index
urls = [
"https://lilianweng.github.io/posts/2023-06-23-agent/",
"https://lilianweng.github.io/posts/2023-03-15-prompt-engineering/",
"https://lilianweng.github.io/posts/2023-10-25-adv-attack-llm/",
]
# Load
docs = [WebBaseLoader(url).load() for url in urls]
docs_list = [item for sublist in docs for item in sublist]
# Splict
text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
chunk_size=500,
chunk_overlap=0,
)
# Add to vectorstore
vectorstore = Chroma.from_documents(
documents=docs_list,
collection_name="rag-chroma",
embedding=embd,
)
retriever = vectorstore.as_retriever()
#######################################
# Web Search Tool: Question Re-writer #
#######################################
web_search_tool = TavilySearchResults(k=3)
######################
# Define Graph State #
######################
class GraphState(TypedDict):
"""Represents the state of our graph.
Args:
question (str): question
generation (str): LLM generation
document (str): list of documents
"""
question: str
generation: str
documents: List[str]
#####################
# Define Graph Flow #
#####################
def retrieve(state: GraphState):
"""Retrieve documents"""
print(f"retrieve ————>")
question = state["question"]
# Retrieval
documents = retriever.invoke(question)
return {"documents": documents, "question": question}
class GradeDocuments(BaseModel):
"""Binary score for relevance check on retrieved documents"""
binary_score: str = Field(
description="Documents are relevant to the question, 'yes' or 'no'"
)
def grade_documents(state: GraphState):
# Prompt
system = """
You are a grader assessing relevance of a retrieved document to a user question. \n
If the document contains keyword(s) or semantic meaning related to the user question, grade it as relevant. \n
Give a binary score 'yes' or 'no' score to indicate whether the document is relevant to the question.
"""
grade_prompt = ChatPromptTemplate.from_messages([
("system", system),
("human", "Retrieved document: \n\n {document} \n\n User question: {question}")
])
llm = ModelTools.get_llm()
structured_llm_grader = llm.with_structured_output(GradeDocuments)
retrieval_grader = grade_prompt | structured_llm_grader
"""Determines whether the retrieved documents are relevant to the question"""
print(f"grade_documents ————>")
question = state["question"]
documents = state["documents"] # TODO: bug here: KeyError('documents')
# Score each doc
filtered_docs = []
for d in documents:
score = retrieval_grader.invoke({"question": question, "document": d.page_content})
grade = score.binary_score
if grade == "yes":
print(f"grade_documents ————> document relevant")
filtered_docs.append(d)
else:
print(f"grade_documents ————> document not relevant")
continue
return {"documents": filtered_docs, "question": question}
def generate(state: GraphState):
"""
You are an assistant for question-answering tasks.
Use the following pieces of retrieved context to answer the question.
If you don't know the answer, just say that you don't konw.
Use three sentences maximum and keep the answer concise.
Question: {question}
Context: {context}
Answer:
"""
prompt = hub.pull("rlm/rag-prompt")
def format_docs(docs):
return "\n\n".join(doc.page_content for doc in docs) # Post-processing
llm = ModelTools.get_llm()
rag_chain = prompt | llm | StrOutputParser()
"""Generate answer"""
print(f"generate ————>")
question = state["question"]
documents = state["documents"]
# RAG generation
generation = rag_chain.invoke({"context": documents, "question": question})
# TODO: bug here: NameError("name 'generation' is not defined")
return {"documents": documents, "question": question, "generation": generation}
def transform_query(state: GraphState):
system = """
You a question re-writer that converts an input question to a better version that is optimized \n
for vectorstore retrieval. Look at the input and try to reason about the underlying semantic intent / meaning.
"""
re_write_prompt = ChatPromptTemplate.from_messages([
("system", system),
("human", "Here is the initial question: \n\n {question} \n Formulate an improved question.")
])
llm = ModelTools.get_llm()
question_rewriter = re_write_prompt | llm | StrOutputParser()
"""Transform the query to produce a better question"""
print(f"transform_query ————>")
question = state["question"]
documents = state["documents"]
# Re-write question
better_question = question_rewriter.invoke({"question": question})
return {"documents": documents, "question": better_question}
def web_search(state):
"""Web search based on the re-phrased question"""
print(f"web_search ————>")
question = state["question"]
# Web search
docs = web_search_tool.invoke({"query": question})
web_results = "\n".join([d["content"] for d in docs])
web_results = Document(page_content=web_results)
return {"documents": web_results, "question": question}
################
# Define Edges #
################
class RouteQuery(BaseModel):
"""Route a user query to the most relevant datasource."""
datasource: Literal["vectorstore", "web_search"] = Field(
...,
description="Given a user question choose to route it to web search or a vectorstore."
)
def route_question(state: GraphState):
system = """
You are an expert at routing a user question to a vectorstore or web search.
The vectorstore contains documents related to agents, prompt engineering, and adversarial attacks.
Use the vectorstore for questions on these topics. Otherwise, use web-search.
"""
route_prompt = ChatPromptTemplate.from_messages([
("system", system),
("human", "{question}"),
])
llm = ModelTools.get_llm()
structured_llm_router = llm.with_structured_output(RouteQuery)
question_router = route_prompt | structured_llm_router
"""Route question to web search or RAG"""
print(f"route_question ————>")
question = state["question"]
source = question_router.invoke({"question": question})
if source.datasource == "web_search":
print(f"route_question ————> go to web search")
return "web_search"
elif source.datasource == "vectorstore":
print(f"route_question ————> go to RAG")
return "vectorstore"
def decide_to_generate(state: GraphState):
"""Determines whether to generate an answer, or re-generate a question"""
print(f"route_question ————>")
state["question"]
filtered_documents = state["documents"]
if not filtered_documents:
# All documents have been filtered check_relevance
# We will re-generate a new query
print(f"decide_to_generate ————> go to re-generate a new query")
return "transform_query"
else:
# We have relevant documents, so generate answer
print(f"decide_to_generate ————> go to generate answer")
return "generate"
class GradeHallucinations(BaseModel):
"""Binary score for hallucination present in generation answer."""
binary_score: str = Field(
description="Answer is grounded in the facts, 'yes' or 'no'"
)
class GradeAnswer(BaseModel):
"""Binary score to assess answer addressses question"""
binary_score: str = Field(
description="Answer addresses the question, 'yes' or 'no'"
)
def grade_generation_v_documents_and_question(state: GraphState):
system = """
You are a grader assessing whether an LLM generation is grounded in /
supported by a set of retrieved facts. \n
Give a binary score 'yes' or 'no',
'Yes' means that the answer is grounded in / supported by the set of facts.
"""
hallucination_prompt = ChatPromptTemplate.from_messages([
("system", system),
("human", "Set of facts: \n\n {documents} \n\n LLM generation: {generation}")
])
llm = ModelTools.get_llm()
structured_llm_grader = llm.with_structured_output(GradeHallucinations)
hallucination_grader = hallucination_prompt | structured_llm_grader
"""
Determines whether the generation is grounded in the document
and answers question.
"""
print(f"grade_generation_v_documents_and_question ————>")
question = state["question"]
documents = state["documents"]
generation = state["generation"]
score = hallucination_grader.invoke({
"documents": documents,
"generation": generation,
})
grade = score.binary_score
# 1.Check hallucination
if grade == "yes":
print(f"grade_generation_v_documents_and_question ————> \
generation is grounded in documents")
# 2.Check question-answering
# ---------------------------------------------------------------------------------
system = """
You are a grader assessing whether an answer addresses / resolves a question \n
Give a binary score 'yes' or 'no'.
'Yes' means that the answer resolves the question.
"""
answer_prompt = ChatPromptTemplate.from_messages([
("system", system),
("human", "User question: \n\n {question} \n\n LLM generation: {generation}"),
])
llm = ModelTools.get_llm()
structured_llm_grader = llm.with_structured_output(GradeAnswer)
answer_grader = answer_prompt | structured_llm_grader
# ---------------------------------------------------------------------------------
score = answer_grader.invoke({
"question": question,
"generation": generation,
})
grade = score.binary_score
if grade == "yes":
print(f"grade_generation_v_documents_and_question ————> \
generation addresses question")
return "useful"
else:
print(f"grade_generation_v_documents_and_question ————> \
generation does not addresses question")
return "not useful"
else:
print(f"grade_generation_v_documents_and_question ————> \
generation is not grounded in documents")
return "not supported"
#################
# Compile Graph #
#################
workflow = StateGraph(GraphState)
# Define the nodes
workflow.add_node("retrieve", retrieve)
workflow.add_node("grade_documents", grade_documents)
workflow.add_node("generate", generate)
workflow.add_node("transform_query", transform_query)
workflow.add_node("web_search", web_search)
# Build graph
workflow.add_conditional_edges(
START,
route_question,
{
"web_search": "web_search",
"vectorstore": "retrieve",
}
)
workflow.add_edge("web_search", "generate")
workflow.add_edge("retrieve", "grade_documents")
workflow.add_conditional_edges(
"grade_documents",
decide_to_generate,
{
"generate": "generate",
"transform_query": "transform_query",
}
)
workflow.add_edge("transform_query", "retrieve")
workflow.add_conditional_edges(
"generate",
grade_generation_v_documents_and_question,
{
"not supported": "generate",
"useful": END,
"not useful": "transform_query",
}
)
# Compile
graph = workflow.compile()