Spaces:
Runtime error
Runtime error
modified app.py to contain graph
Browse files- AgenticRAG/agentic_rag.py +225 -0
- AgenticRAG/aimakerspace/openai_utils/embedding.py +3 -1
- AgenticRAG/app.py +243 -20
- AgenticRAG/previous_app.py +137 -0
- AgenticRAG/requirements.txt +6 -1
- agentic_rag.py +0 -0
AgenticRAG/agentic_rag.py
CHANGED
@@ -0,0 +1,225 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from langchain.tools.retriever import create_retriever_tool
|
2 |
+
from typing import Annotated, Literal, Sequence, TypedDict
|
3 |
+
from typing import Annotated, Sequence, TypedDict
|
4 |
+
from langchain_core.messages import BaseMessage
|
5 |
+
from langgraph.graph.message import add_messages
|
6 |
+
from langchain import hub
|
7 |
+
from langchain_core.messages import BaseMessage, HumanMessage
|
8 |
+
from langchain_core.output_parsers import StrOutputParser
|
9 |
+
from langchain_core.prompts import PromptTemplate
|
10 |
+
from langchain_openai import ChatOpenAI
|
11 |
+
from pydantic import BaseModel, Field
|
12 |
+
from langgraph.prebuilt import tools_condition
|
13 |
+
|
14 |
+
from aimakerspace.vectordatabase import VectorDatabase
|
15 |
+
|
16 |
+
|
17 |
+
|
18 |
+
retriever_tool = create_retriever_tool(
|
19 |
+
retriever,
|
20 |
+
"retrieve_blog_posts",
|
21 |
+
"Search and return information about the responsible and ethical use of AI along with the development of policies and practices to protect civil rights and promote democratic values in the building, deployment, and government of automated systems.",
|
22 |
+
)
|
23 |
+
|
24 |
+
tools = [retriever_tool]
|
25 |
+
|
26 |
+
|
27 |
+
|
28 |
+
|
29 |
+
class AgentState(TypedDict):
|
30 |
+
# The add_messages function defines how an update should be processed
|
31 |
+
# Default is to replace. add_messages says "append"
|
32 |
+
messages: Annotated[Sequence[BaseMessage], add_messages]
|
33 |
+
|
34 |
+
|
35 |
+
|
36 |
+
|
37 |
+
### Edges
|
38 |
+
|
39 |
+
|
40 |
+
def grade_documents(state) -> Literal["generate", "rewrite"]:
|
41 |
+
"""
|
42 |
+
Determines whether the retrieved documents are relevant to the question.
|
43 |
+
|
44 |
+
Args:
|
45 |
+
state (messages): The current state
|
46 |
+
|
47 |
+
Returns:
|
48 |
+
str: A decision for whether the documents are relevant or not
|
49 |
+
"""
|
50 |
+
|
51 |
+
# Data model
|
52 |
+
class grade(BaseModel):
|
53 |
+
"""Binary score for relevance check."""
|
54 |
+
|
55 |
+
binary_score: str = Field(description="Relevance score 'yes' or 'no'")
|
56 |
+
|
57 |
+
# LLM
|
58 |
+
model = ChatOpenAI(temperature=0, model="gpt-4o-mini", streaming=True)
|
59 |
+
|
60 |
+
# LLM with tool and validation
|
61 |
+
llm_with_tool = model.with_structured_output(grade)
|
62 |
+
|
63 |
+
# Prompt
|
64 |
+
prompt = PromptTemplate(
|
65 |
+
template="""You are a grader assessing relevance of a retrieved document to a user question. \n
|
66 |
+
Here is the retrieved document: \n\n {context} \n\n
|
67 |
+
Here is the user question: {question} \n
|
68 |
+
If the document contains keyword(s) or semantic meaning related to the user question, grade it as relevant. \n
|
69 |
+
Give a binary score 'yes' or 'no' score to indicate whether the document is relevant to the question.""",
|
70 |
+
input_variables=["context", "question"],
|
71 |
+
)
|
72 |
+
|
73 |
+
# Chain
|
74 |
+
chain = prompt | llm_with_tool
|
75 |
+
|
76 |
+
messages = state["messages"]
|
77 |
+
last_message = messages[-1]
|
78 |
+
|
79 |
+
question = messages[0].content
|
80 |
+
docs = last_message.content
|
81 |
+
|
82 |
+
scored_result = chain.invoke({"question": question, "context": docs})
|
83 |
+
|
84 |
+
score = scored_result.binary_score
|
85 |
+
|
86 |
+
if score == "yes":
|
87 |
+
print("---DECISION: DOCS RELEVANT---")
|
88 |
+
return "generate"
|
89 |
+
|
90 |
+
else:
|
91 |
+
print("---DECISION: DOCS NOT RELEVANT---")
|
92 |
+
print(score)
|
93 |
+
return "rewrite"
|
94 |
+
|
95 |
+
### Nodes
|
96 |
+
|
97 |
+
|
98 |
+
def agent(state):
|
99 |
+
"""
|
100 |
+
Invokes the agent model to generate a response based on the current state. Given
|
101 |
+
the question, it will decide to retrieve using the retriever tool, or simply end.
|
102 |
+
|
103 |
+
Args:
|
104 |
+
state (messages): The current state
|
105 |
+
|
106 |
+
Returns:
|
107 |
+
dict: The updated state with the agent response appended to messages
|
108 |
+
"""
|
109 |
+
print("---CALL AGENT---")
|
110 |
+
messages = state["messages"]
|
111 |
+
model = ChatOpenAI(temperature=0, streaming=True, model="gpt-4o-mini")
|
112 |
+
model = model.bind_tools(tools)
|
113 |
+
response = model.invoke(messages)
|
114 |
+
# We return a list, because this will get added to the existing list
|
115 |
+
return {"messages": [response]}
|
116 |
+
|
117 |
+
|
118 |
+
def rewrite(state):
|
119 |
+
"""
|
120 |
+
Transform the query to produce a better question.
|
121 |
+
|
122 |
+
Args:
|
123 |
+
state (messages): The current state
|
124 |
+
|
125 |
+
Returns:
|
126 |
+
dict: The updated state with re-phrased question
|
127 |
+
"""
|
128 |
+
|
129 |
+
print("---TRANSFORM QUERY---")
|
130 |
+
messages = state["messages"]
|
131 |
+
question = messages[0].content
|
132 |
+
|
133 |
+
msg = [
|
134 |
+
HumanMessage(
|
135 |
+
content=f""" \n
|
136 |
+
Look at the input and try to reason about the underlying semantic intent / meaning. \n
|
137 |
+
Here is the initial question:
|
138 |
+
\n ------- \n
|
139 |
+
{question}
|
140 |
+
\n ------- \n
|
141 |
+
Formulate an improved question: """,
|
142 |
+
)
|
143 |
+
]
|
144 |
+
|
145 |
+
# Grader
|
146 |
+
model = ChatOpenAI(temperature=0, model="gpt-4o-mini", streaming=True)
|
147 |
+
response = model.invoke(msg)
|
148 |
+
return {"messages": [response]}
|
149 |
+
|
150 |
+
|
151 |
+
def generate(state):
|
152 |
+
"""
|
153 |
+
Generate answer
|
154 |
+
|
155 |
+
Args:
|
156 |
+
state (messages): The current state
|
157 |
+
|
158 |
+
Returns:
|
159 |
+
dict: The updated state with re-phrased question
|
160 |
+
"""
|
161 |
+
print("---GENERATE---")
|
162 |
+
messages = state["messages"]
|
163 |
+
question = messages[0].content
|
164 |
+
last_message = messages[-1]
|
165 |
+
|
166 |
+
docs = last_message.content
|
167 |
+
|
168 |
+
# Prompt
|
169 |
+
prompt = hub.pull("rlm/rag-prompt")
|
170 |
+
|
171 |
+
# LLM
|
172 |
+
llm = ChatOpenAI(model_name="gpt-4o-mini", temperature=0, streaming=True)
|
173 |
+
|
174 |
+
# Post-processing
|
175 |
+
def format_docs(docs):
|
176 |
+
return "\n\n".join(doc.page_content for doc in docs)
|
177 |
+
|
178 |
+
# Chain
|
179 |
+
rag_chain = prompt | llm | StrOutputParser()
|
180 |
+
|
181 |
+
# Run
|
182 |
+
response = rag_chain.invoke({"context": docs, "question": question})
|
183 |
+
return {"messages": [response]}
|
184 |
+
|
185 |
+
from langgraph.graph import END, StateGraph, START
|
186 |
+
from langgraph.prebuilt import ToolNode
|
187 |
+
|
188 |
+
# Define a new graph
|
189 |
+
workflow = StateGraph(AgentState)
|
190 |
+
|
191 |
+
# Define the nodes we will cycle between
|
192 |
+
workflow.add_node("agent", agent) # agent
|
193 |
+
retrieve = ToolNode([retriever_tool])
|
194 |
+
workflow.add_node("retrieve", retrieve) # retrieval
|
195 |
+
workflow.add_node("rewrite", rewrite) # Re-writing the question
|
196 |
+
workflow.add_node(
|
197 |
+
"generate", generate
|
198 |
+
) # Generating a response after we know the documents are relevant
|
199 |
+
# Call agent node to decide to retrieve or not
|
200 |
+
workflow.add_edge(START, "agent")
|
201 |
+
|
202 |
+
# Decide whether to retrieve
|
203 |
+
workflow.add_conditional_edges(
|
204 |
+
"agent",
|
205 |
+
# Assess agent decision
|
206 |
+
tools_condition,
|
207 |
+
{
|
208 |
+
# Translate the condition outputs to nodes in our graph
|
209 |
+
"tools": "retrieve",
|
210 |
+
END: END,
|
211 |
+
},
|
212 |
+
)
|
213 |
+
|
214 |
+
# Edges taken after the `action` node is called.
|
215 |
+
workflow.add_conditional_edges(
|
216 |
+
"retrieve",
|
217 |
+
# Assess agent decision
|
218 |
+
grade_documents,
|
219 |
+
)
|
220 |
+
workflow.add_edge("generate", END)
|
221 |
+
workflow.add_edge("rewrite", "agent")
|
222 |
+
|
223 |
+
# Compile
|
224 |
+
graph = workflow.compile()
|
225 |
+
|
AgenticRAG/aimakerspace/openai_utils/embedding.py
CHANGED
@@ -4,8 +4,10 @@ import openai
|
|
4 |
from typing import List
|
5 |
import os
|
6 |
import asyncio
|
|
|
7 |
|
8 |
-
|
|
|
9 |
class EmbeddingModel:
|
10 |
def __init__(self, embeddings_model_name: str = "text-embedding-3-small"):
|
11 |
load_dotenv()
|
|
|
4 |
from typing import List
|
5 |
import os
|
6 |
import asyncio
|
7 |
+
from dotenv import load_dotenv
|
8 |
|
9 |
+
load_dotenv()
|
10 |
+
print(os.getenv('OPENAI_API_KEY'))
|
11 |
class EmbeddingModel:
|
12 |
def __init__(self, embeddings_model_name: str = "text-embedding-3-small"):
|
13 |
load_dotenv()
|
AgenticRAG/app.py
CHANGED
@@ -14,6 +14,10 @@ import chainlit as cl
|
|
14 |
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
15 |
# from langchain_experimental.text_splitter import SemanticChunker
|
16 |
# from langchain_openai.embeddings import OpenAIEmbeddings
|
|
|
|
|
|
|
|
|
17 |
|
18 |
system_template = """\
|
19 |
Use the following context to answer a users question. If you cannot find the answer in the context, say you don't know the answer."""
|
@@ -27,20 +31,18 @@ Question:
|
|
27 |
"""
|
28 |
user_role_prompt = UserRolePrompt(user_prompt_template)
|
29 |
|
30 |
-
class
|
31 |
-
def __init__(self,
|
32 |
-
self.
|
33 |
self.vector_db_retriever = vector_db_retriever
|
34 |
|
35 |
-
async def
|
36 |
-
|
|
|
37 |
|
38 |
-
context_prompt = ""
|
39 |
-
for context in context_list:
|
40 |
-
context_prompt += context[0] + "\n"
|
41 |
|
42 |
formatted_system_prompt = system_role_prompt.create_message()
|
43 |
-
|
44 |
formatted_user_prompt = user_role_prompt.create_message(question=user_query, context=context_prompt)
|
45 |
|
46 |
async def generate_response():
|
@@ -49,12 +51,12 @@ class RetrievalAugmentedQAPipeline:
|
|
49 |
|
50 |
return {"response": generate_response(), "context": context_list}
|
51 |
|
|
|
|
|
|
|
52 |
text_splitter = RecursiveCharacterTextSplitter()
|
53 |
-
|
54 |
-
|
55 |
-
# except KeyError:
|
56 |
-
# print("Environment variable OPENAI_API_KEY not found")
|
57 |
-
# text_splitter = SemanticChunker(OpenAIEmbeddings(api_key=api_key), breakpoint_threshold_type="standard_deviation")
|
58 |
|
59 |
def process_text_file(file: AskFileResponse):
|
60 |
import tempfile
|
@@ -75,11 +77,9 @@ def process_text_file(file: AskFileResponse):
|
|
75 |
else:
|
76 |
raise ValueError("Provide a .txt or .pdf file")
|
77 |
texts = [x.page_content for x in text_splitter.transform_documents(documents)]
|
78 |
-
# texts = [x.page_content for x in text_splitter.split_documents(documents)]
|
79 |
return texts
|
80 |
|
81 |
|
82 |
-
|
83 |
@cl.on_chat_start
|
84 |
async def on_chat_start():
|
85 |
files = None
|
@@ -111,11 +111,234 @@ async def on_chat_start():
|
|
111 |
|
112 |
chat_openai = ChatOpenAI()
|
113 |
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
118 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
119 |
|
120 |
# Let the user know that the system is ready
|
121 |
msg.content = f"Processing `{file.name}` done. You can now ask questions!"
|
|
|
14 |
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
15 |
# from langchain_experimental.text_splitter import SemanticChunker
|
16 |
# from langchain_openai.embeddings import OpenAIEmbeddings
|
17 |
+
import importlib
|
18 |
+
|
19 |
+
|
20 |
+
|
21 |
|
22 |
system_template = """\
|
23 |
Use the following context to answer a users question. If you cannot find the answer in the context, say you don't know the answer."""
|
|
|
31 |
"""
|
32 |
user_role_prompt = UserRolePrompt(user_prompt_template)
|
33 |
|
34 |
+
class AgenticRAGPipeline:
|
35 |
+
def __init__(self, graph: StateGraph, vector_db_retriever: VectorDatabase) -> None:
|
36 |
+
self.graph = graph
|
37 |
self.vector_db_retriever = vector_db_retriever
|
38 |
|
39 |
+
async def run_pipeline(self, user_query: str):
|
40 |
+
state = self.graph.execute({"text": user_query, "chunk_size": 100})
|
41 |
+
context_list = state["retriever"]
|
42 |
|
43 |
+
context_prompt = "\n".join(context_list)
|
|
|
|
|
44 |
|
45 |
formatted_system_prompt = system_role_prompt.create_message()
|
|
|
46 |
formatted_user_prompt = user_role_prompt.create_message(question=user_query, context=context_prompt)
|
47 |
|
48 |
async def generate_response():
|
|
|
51 |
|
52 |
return {"response": generate_response(), "context": context_list}
|
53 |
|
54 |
+
|
55 |
+
|
56 |
+
|
57 |
text_splitter = RecursiveCharacterTextSplitter()
|
58 |
+
|
59 |
+
|
|
|
|
|
|
|
60 |
|
61 |
def process_text_file(file: AskFileResponse):
|
62 |
import tempfile
|
|
|
77 |
else:
|
78 |
raise ValueError("Provide a .txt or .pdf file")
|
79 |
texts = [x.page_content for x in text_splitter.transform_documents(documents)]
|
|
|
80 |
return texts
|
81 |
|
82 |
|
|
|
83 |
@cl.on_chat_start
|
84 |
async def on_chat_start():
|
85 |
files = None
|
|
|
111 |
|
112 |
chat_openai = ChatOpenAI()
|
113 |
|
114 |
+
retriever = vector_db
|
115 |
+
"""Graph code here"""
|
116 |
+
|
117 |
+
from langchain.tools.retriever import create_retriever_tool
|
118 |
+
from typing import Annotated, Literal, Sequence, TypedDict
|
119 |
+
from typing import Annotated, Sequence, TypedDict
|
120 |
+
from langchain_core.messages import BaseMessage
|
121 |
+
from langgraph.graph.message import add_messages
|
122 |
+
from langchain import hub
|
123 |
+
from langchain_core.messages import BaseMessage, HumanMessage
|
124 |
+
from langchain_core.output_parsers import StrOutputParser
|
125 |
+
from langchain_core.prompts import PromptTemplate
|
126 |
+
from langchain_openai import ChatOpenAI
|
127 |
+
from pydantic import BaseModel, Field
|
128 |
+
from langgraph.prebuilt import tools_condition
|
129 |
+
|
130 |
+
from aimakerspace.vectordatabase import VectorDatabase
|
131 |
+
|
132 |
+
retriever_tool = create_retriever_tool(
|
133 |
+
retriever,
|
134 |
+
"retrieve_blog_posts",
|
135 |
+
"Search and return information about the responsible and ethical use of AI along with the development of policies and practices to protect civil rights and promote democratic values in the building, deployment, and government of automated systems.",
|
136 |
+
)
|
137 |
+
|
138 |
+
tools = [retriever_tool]
|
139 |
+
|
140 |
+
|
141 |
+
|
142 |
+
class AgentState(TypedDict):
|
143 |
+
# The add_messages function defines how an update should be processed
|
144 |
+
# Default is to replace. add_messages says "append"
|
145 |
+
messages: Annotated[Sequence[BaseMessage], add_messages]
|
146 |
+
|
147 |
+
|
148 |
+
|
149 |
+
|
150 |
+
### Edges
|
151 |
+
|
152 |
+
|
153 |
+
def grade_documents(state) -> Literal["generate", "rewrite"]:
|
154 |
+
"""
|
155 |
+
Determines whether the retrieved documents are relevant to the question.
|
156 |
+
|
157 |
+
Args:
|
158 |
+
state (messages): The current state
|
159 |
+
|
160 |
+
Returns:
|
161 |
+
str: A decision for whether the documents are relevant or not
|
162 |
+
"""
|
163 |
+
|
164 |
+
# Data model
|
165 |
+
class grade(BaseModel):
|
166 |
+
"""Binary score for relevance check."""
|
167 |
+
|
168 |
+
binary_score: str = Field(description="Relevance score 'yes' or 'no'")
|
169 |
+
|
170 |
+
# LLM
|
171 |
+
model = ChatOpenAI(temperature=0, model="gpt-4o-mini", streaming=True)
|
172 |
+
|
173 |
+
# LLM with tool and validation
|
174 |
+
llm_with_tool = model.with_structured_output(grade)
|
175 |
+
|
176 |
+
# Prompt
|
177 |
+
prompt = PromptTemplate(
|
178 |
+
template="""You are a grader assessing relevance of a retrieved document to a user question. \n
|
179 |
+
Here is the retrieved document: \n\n {context} \n\n
|
180 |
+
Here is the user question: {question} \n
|
181 |
+
If the document contains keyword(s) or semantic meaning related to the user question, grade it as relevant. \n
|
182 |
+
Give a binary score 'yes' or 'no' score to indicate whether the document is relevant to the question.""",
|
183 |
+
input_variables=["context", "question"],
|
184 |
+
)
|
185 |
+
|
186 |
+
# Chain
|
187 |
+
chain = prompt | llm_with_tool
|
188 |
+
|
189 |
+
messages = state["messages"]
|
190 |
+
last_message = messages[-1]
|
191 |
+
|
192 |
+
question = messages[0].content
|
193 |
+
docs = last_message.content
|
194 |
+
|
195 |
+
scored_result = chain.invoke({"question": question, "context": docs})
|
196 |
+
|
197 |
+
score = scored_result.binary_score
|
198 |
+
|
199 |
+
if score == "yes":
|
200 |
+
print("---DECISION: DOCS RELEVANT---")
|
201 |
+
return "generate"
|
202 |
+
|
203 |
+
else:
|
204 |
+
print("---DECISION: DOCS NOT RELEVANT---")
|
205 |
+
print(score)
|
206 |
+
return "rewrite"
|
207 |
+
|
208 |
+
### Nodes
|
209 |
+
|
210 |
+
|
211 |
+
def agent(state):
|
212 |
+
"""
|
213 |
+
Invokes the agent model to generate a response based on the current state. Given
|
214 |
+
the question, it will decide to retrieve using the retriever tool, or simply end.
|
215 |
+
|
216 |
+
Args:
|
217 |
+
state (messages): The current state
|
218 |
+
|
219 |
+
Returns:
|
220 |
+
dict: The updated state with the agent response appended to messages
|
221 |
+
"""
|
222 |
+
print("---CALL AGENT---")
|
223 |
+
messages = state["messages"]
|
224 |
+
model = ChatOpenAI(temperature=0, streaming=True, model="gpt-4o-mini")
|
225 |
+
model = model.bind_tools(tools)
|
226 |
+
response = model.invoke(messages)
|
227 |
+
# We return a list, because this will get added to the existing list
|
228 |
+
return {"messages": [response]}
|
229 |
+
|
230 |
+
|
231 |
+
def rewrite(state):
|
232 |
+
"""
|
233 |
+
Transform the query to produce a better question.
|
234 |
+
|
235 |
+
Args:
|
236 |
+
state (messages): The current state
|
237 |
+
|
238 |
+
Returns:
|
239 |
+
dict: The updated state with re-phrased question
|
240 |
+
"""
|
241 |
+
|
242 |
+
print("---TRANSFORM QUERY---")
|
243 |
+
messages = state["messages"]
|
244 |
+
question = messages[0].content
|
245 |
+
|
246 |
+
msg = [
|
247 |
+
HumanMessage(
|
248 |
+
content=f""" \n
|
249 |
+
Look at the input and try to reason about the underlying semantic intent / meaning. \n
|
250 |
+
Here is the initial question:
|
251 |
+
\n ------- \n
|
252 |
+
{question}
|
253 |
+
\n ------- \n
|
254 |
+
Formulate an improved question: """,
|
255 |
+
)
|
256 |
+
]
|
257 |
+
|
258 |
+
# Grader
|
259 |
+
model = ChatOpenAI(temperature=0, model="gpt-4o-mini", streaming=True)
|
260 |
+
response = model.invoke(msg)
|
261 |
+
return {"messages": [response]}
|
262 |
+
|
263 |
+
|
264 |
+
def generate(state):
|
265 |
+
"""
|
266 |
+
Generate answer
|
267 |
+
|
268 |
+
Args:
|
269 |
+
state (messages): The current state
|
270 |
+
|
271 |
+
Returns:
|
272 |
+
dict: The updated state with re-phrased question
|
273 |
+
"""
|
274 |
+
print("---GENERATE---")
|
275 |
+
messages = state["messages"]
|
276 |
+
question = messages[0].content
|
277 |
+
last_message = messages[-1]
|
278 |
+
|
279 |
+
docs = last_message.content
|
280 |
+
|
281 |
+
# Prompt
|
282 |
+
prompt = hub.pull("rlm/rag-prompt")
|
283 |
+
|
284 |
+
# LLM
|
285 |
+
llm = ChatOpenAI(model_name="gpt-4o-mini", temperature=0, streaming=True)
|
286 |
+
|
287 |
+
# Post-processing
|
288 |
+
def format_docs(docs):
|
289 |
+
return "\n\n".join(doc.page_content for doc in docs)
|
290 |
+
|
291 |
+
# Chain
|
292 |
+
rag_chain = prompt | llm | StrOutputParser()
|
293 |
+
|
294 |
+
# Run
|
295 |
+
response = rag_chain.invoke({"context": docs, "question": question})
|
296 |
+
return {"messages": [response]}
|
297 |
+
|
298 |
+
from langgraph.graph import END, StateGraph, START
|
299 |
+
from langgraph.prebuilt import ToolNode
|
300 |
+
|
301 |
+
# Define a new graph
|
302 |
+
workflow = StateGraph(AgentState)
|
303 |
+
|
304 |
+
# Define the nodes we will cycle between
|
305 |
+
workflow.add_node("agent", agent) # agent
|
306 |
+
retrieve = ToolNode([retriever_tool])
|
307 |
+
workflow.add_node("retrieve", retrieve) # retrieval
|
308 |
+
workflow.add_node("rewrite", rewrite) # Re-writing the question
|
309 |
+
workflow.add_node(
|
310 |
+
"generate", generate
|
311 |
+
) # Generating a response after we know the documents are relevant
|
312 |
+
# Call agent node to decide to retrieve or not
|
313 |
+
workflow.add_edge(START, "agent")
|
314 |
+
|
315 |
+
# Decide whether to retrieve
|
316 |
+
workflow.add_conditional_edges(
|
317 |
+
"agent",
|
318 |
+
# Assess agent decision
|
319 |
+
tools_condition,
|
320 |
+
{
|
321 |
+
# Translate the condition outputs to nodes in our graph
|
322 |
+
"tools": "retrieve",
|
323 |
+
END: END,
|
324 |
+
},
|
325 |
+
)
|
326 |
+
|
327 |
+
# Edges taken after the `action` node is called.
|
328 |
+
workflow.add_conditional_edges(
|
329 |
+
"retrieve",
|
330 |
+
# Assess agent decision
|
331 |
+
grade_documents,
|
332 |
)
|
333 |
+
workflow.add_edge("generate", END)
|
334 |
+
workflow.add_edge("rewrite", "agent")
|
335 |
+
|
336 |
+
# Compile
|
337 |
+
graph = workflow.compile()
|
338 |
+
|
339 |
+
"""END GRAPH CODE"""
|
340 |
+
# Create a chain
|
341 |
+
retrieval_augmented_qa_pipeline = AgenticRAGPipeline(graph=graph, vector_db_retriever=vector_db)
|
342 |
|
343 |
# Let the user know that the system is ready
|
344 |
msg.content = f"Processing `{file.name}` done. You can now ask questions!"
|
AgenticRAG/previous_app.py
ADDED
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from typing import List
|
3 |
+
from chainlit.types import AskFileResponse
|
4 |
+
from aimakerspace.text_utils import CharacterTextSplitter, TextFileLoader
|
5 |
+
from aimakerspace.openai_utils.prompts import (
|
6 |
+
UserRolePrompt,
|
7 |
+
SystemRolePrompt,
|
8 |
+
AssistantRolePrompt,
|
9 |
+
)
|
10 |
+
from aimakerspace.openai_utils.embedding import EmbeddingModel
|
11 |
+
from aimakerspace.vectordatabase import VectorDatabase
|
12 |
+
from aimakerspace.openai_utils.chatmodel import ChatOpenAI
|
13 |
+
import chainlit as cl
|
14 |
+
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
15 |
+
# from langchain_experimental.text_splitter import SemanticChunker
|
16 |
+
# from langchain_openai.embeddings import OpenAIEmbeddings
|
17 |
+
|
18 |
+
system_template = """\
|
19 |
+
Use the following context to answer a users question. If you cannot find the answer in the context, say you don't know the answer."""
|
20 |
+
system_role_prompt = SystemRolePrompt(system_template)
|
21 |
+
|
22 |
+
user_prompt_template = """\
|
23 |
+
Context:
|
24 |
+
{context}
|
25 |
+
Question:
|
26 |
+
{question}
|
27 |
+
"""
|
28 |
+
user_role_prompt = UserRolePrompt(user_prompt_template)
|
29 |
+
|
30 |
+
class RetrievalAugmentedQAPipeline:
|
31 |
+
def __init__(self, llm: ChatOpenAI(), vector_db_retriever: VectorDatabase) -> None:
|
32 |
+
self.llm = llm
|
33 |
+
self.vector_db_retriever = vector_db_retriever
|
34 |
+
|
35 |
+
async def arun_pipeline(self, user_query: str):
|
36 |
+
context_list = self.vector_db_retriever.search_by_text(user_query, k=4)
|
37 |
+
|
38 |
+
context_prompt = ""
|
39 |
+
for context in context_list:
|
40 |
+
context_prompt += context[0] + "\n"
|
41 |
+
|
42 |
+
formatted_system_prompt = system_role_prompt.create_message()
|
43 |
+
|
44 |
+
formatted_user_prompt = user_role_prompt.create_message(question=user_query, context=context_prompt)
|
45 |
+
|
46 |
+
async def generate_response():
|
47 |
+
async for chunk in self.llm.astream([formatted_system_prompt, formatted_user_prompt]):
|
48 |
+
yield chunk
|
49 |
+
|
50 |
+
return {"response": generate_response(), "context": context_list}
|
51 |
+
|
52 |
+
text_splitter = RecursiveCharacterTextSplitter()
|
53 |
+
# try:
|
54 |
+
# api_key = os.environ["OPENAI_API_KEY"]
|
55 |
+
# except KeyError:
|
56 |
+
# print("Environment variable OPENAI_API_KEY not found")
|
57 |
+
# text_splitter = SemanticChunker(OpenAIEmbeddings(api_key=api_key), breakpoint_threshold_type="standard_deviation")
|
58 |
+
|
59 |
+
def process_text_file(file: AskFileResponse):
|
60 |
+
import tempfile
|
61 |
+
from langchain_community.document_loaders.pdf import PyPDFLoader
|
62 |
+
|
63 |
+
with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=file.name) as temp_file:
|
64 |
+
temp_file_path = temp_file.name
|
65 |
+
|
66 |
+
with open(temp_file_path, "wb") as f:
|
67 |
+
f.write(file.content)
|
68 |
+
|
69 |
+
if file.type == 'text/plain':
|
70 |
+
text_loader = TextFileLoader(temp_file_path)
|
71 |
+
documents = text_loader.load_documents()
|
72 |
+
elif file.type == 'application/pdf':
|
73 |
+
pdf_loader = PyPDFLoader(temp_file_path)
|
74 |
+
documents = pdf_loader.load()
|
75 |
+
else:
|
76 |
+
raise ValueError("Provide a .txt or .pdf file")
|
77 |
+
texts = [x.page_content for x in text_splitter.transform_documents(documents)]
|
78 |
+
# texts = [x.page_content for x in text_splitter.split_documents(documents)]
|
79 |
+
return texts
|
80 |
+
|
81 |
+
|
82 |
+
|
83 |
+
@cl.on_chat_start
|
84 |
+
async def on_chat_start():
|
85 |
+
files = None
|
86 |
+
|
87 |
+
# Wait for the user to upload a file
|
88 |
+
while files == None:
|
89 |
+
files = await cl.AskFileMessage(
|
90 |
+
content="Please upload a Text file or a PDF to begin!",
|
91 |
+
accept=["text/plain", "application/pdf"],
|
92 |
+
max_size_mb=12,
|
93 |
+
timeout=180,
|
94 |
+
).send()
|
95 |
+
|
96 |
+
file = files[0]
|
97 |
+
|
98 |
+
msg = cl.Message(
|
99 |
+
content=f"Processing `{file.name}`...", disable_human_feedback=True
|
100 |
+
)
|
101 |
+
await msg.send()
|
102 |
+
|
103 |
+
# load the file
|
104 |
+
texts = process_text_file(file)
|
105 |
+
|
106 |
+
print(f"Processing {len(texts)} text chunks")
|
107 |
+
|
108 |
+
# Create a dict vector store
|
109 |
+
vector_db = VectorDatabase()
|
110 |
+
vector_db = await vector_db.abuild_from_list(texts)
|
111 |
+
|
112 |
+
chat_openai = ChatOpenAI()
|
113 |
+
|
114 |
+
# Create a chain
|
115 |
+
retrieval_augmented_qa_pipeline = RetrievalAugmentedQAPipeline(
|
116 |
+
vector_db_retriever=vector_db,
|
117 |
+
llm=chat_openai
|
118 |
+
)
|
119 |
+
|
120 |
+
# Let the user know that the system is ready
|
121 |
+
msg.content = f"Processing `{file.name}` done. You can now ask questions!"
|
122 |
+
await msg.update()
|
123 |
+
|
124 |
+
cl.user_session.set("chain", retrieval_augmented_qa_pipeline)
|
125 |
+
|
126 |
+
|
127 |
+
@cl.on_message
|
128 |
+
async def main(message):
|
129 |
+
chain = cl.user_session.get("chain")
|
130 |
+
|
131 |
+
msg = cl.Message(content="")
|
132 |
+
result = await chain.arun_pipeline(message.content)
|
133 |
+
|
134 |
+
async for stream_resp in result["response"]:
|
135 |
+
await msg.stream_token(stream_resp)
|
136 |
+
|
137 |
+
await msg.send()
|
AgenticRAG/requirements.txt
CHANGED
@@ -4,4 +4,9 @@ openai
|
|
4 |
langchain_community
|
5 |
langchain_experimental
|
6 |
langchain_openai
|
7 |
-
pypdf
|
|
|
|
|
|
|
|
|
|
|
|
4 |
langchain_community
|
5 |
langchain_experimental
|
6 |
langchain_openai
|
7 |
+
pypdf
|
8 |
+
tiktoken
|
9 |
+
langchainhub
|
10 |
+
langchain
|
11 |
+
langgraph
|
12 |
+
langchain-text-splitters
|
agentic_rag.py
ADDED
File without changes
|