Spaces:
Runtime error
Runtime error
modified app.py to contain graph
Browse filesFiles changed (6)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225from langchain.tools.retriever import create_retriever_toolfrom typing import Annotated, Literal, Sequence, TypedDictfrom typing import Annotated, Sequence, TypedDictfrom langchain_core.messages import BaseMessagefrom langgraph.graph.message import add_messagesfrom langchain import hubfrom langchain_core.messages import BaseMessage, HumanMessagefrom langchain_core.output_parsers import StrOutputParserfrom langchain_core.prompts import PromptTemplatefrom langchain_openai import ChatOpenAIfrom pydantic import BaseModel, Fieldfrom langgraph.prebuilt import tools_conditionfrom aimakerspace.vectordatabase import VectorDatabaseretriever_tool = create_retriever_tool(retriever,"retrieve_blog_posts","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.",)tools = [retriever_tool]class AgentState(TypedDict):# The add_messages function defines how an update should be processed# Default is to replace. add_messages says "append"messages: Annotated[Sequence[BaseMessage], add_messages]### Edgesdef grade_documents(state) -> Literal["generate", "rewrite"]:"""Determines whether the retrieved documents are relevant to the question.Args:state (messages): The current stateReturns:str: A decision for whether the documents are relevant or not"""# Data modelclass grade(BaseModel):"""Binary score for relevance check."""binary_score: str = Field(description="Relevance score 'yes' or 'no'")# LLMmodel = ChatOpenAI(temperature=0, model="gpt-4o-mini", streaming=True)# LLM with tool and validationllm_with_tool = model.with_structured_output(grade)# Promptprompt = PromptTemplate(template="""You are a grader assessing relevance of a retrieved document to a user question. \nHere is the retrieved document: \n\n {context} \n\nHere is the user question: {question} \nIf the document contains keyword(s) or semantic meaning related to the user question, grade it as relevant. \nGive a binary score 'yes' or 'no' score to indicate whether the document is relevant to the question.""",input_variables=["context", "question"],)# Chainchain = prompt | llm_with_toolmessages = state["messages"]last_message = messages[-1]question = messages[0].contentdocs = last_message.contentscored_result = chain.invoke({"question": question, "context": docs})score = scored_result.binary_scoreif score == "yes":print("---DECISION: DOCS RELEVANT---")return "generate"else:print("---DECISION: DOCS NOT RELEVANT---")print(score)return "rewrite"### Nodesdef agent(state):"""Invokes the agent model to generate a response based on the current state. Giventhe question, it will decide to retrieve using the retriever tool, or simply end.Args:state (messages): The current stateReturns:dict: The updated state with the agent response appended to messages"""print("---CALL AGENT---")messages = state["messages"]model = ChatOpenAI(temperature=0, streaming=True, model="gpt-4o-mini")model = model.bind_tools(tools)response = model.invoke(messages)# We return a list, because this will get added to the existing listreturn {"messages": [response]}def rewrite(state):"""Transform the query to produce a better question.Args:state (messages): The current stateReturns:dict: The updated state with re-phrased question"""print("---TRANSFORM QUERY---")messages = state["messages"]question = messages[0].contentmsg = [HumanMessage(content=f""" \nLook at the input and try to reason about the underlying semantic intent / meaning. \nHere is the initial question:\n ------- \n{question}\n ------- \nFormulate an improved question: """,)]# Gradermodel = ChatOpenAI(temperature=0, model="gpt-4o-mini", streaming=True)response = model.invoke(msg)return {"messages": [response]}def generate(state):"""Generate answerArgs:state (messages): The current stateReturns:dict: The updated state with re-phrased question"""print("---GENERATE---")messages = state["messages"]question = messages[0].contentlast_message = messages[-1]docs = last_message.content# Promptprompt = hub.pull("rlm/rag-prompt")# LLMllm = ChatOpenAI(model_name="gpt-4o-mini", temperature=0, streaming=True)# Post-processingdef format_docs(docs):return "\n\n".join(doc.page_content for doc in docs)# Chainrag_chain = prompt | llm | StrOutputParser()# Runresponse = rag_chain.invoke({"context": docs, "question": question})return {"messages": [response]}from langgraph.graph import END, StateGraph, STARTfrom langgraph.prebuilt import ToolNode# Define a new graphworkflow = StateGraph(AgentState)# Define the nodes we will cycle betweenworkflow.add_node("agent", agent) # agentretrieve = ToolNode([retriever_tool])workflow.add_node("retrieve", retrieve) # retrievalworkflow.add_node("rewrite", rewrite) # Re-writing the questionworkflow.add_node("generate", generate) # Generating a response after we know the documents are relevant# Call agent node to decide to retrieve or notworkflow.add_edge(START, "agent")# Decide whether to retrieveworkflow.add_conditional_edges("agent",# Assess agent decisiontools_condition,{# Translate the condition outputs to nodes in our graph"tools": "retrieve",END: END,},)# Edges taken after the `action` node is called.workflow.add_conditional_edges("retrieve",# Assess agent decisiongrade_documents,)workflow.add_edge("generate", END)workflow.add_edge("rewrite", "agent")# Compilegraph = workflow.compile()
3 unmodified lines45678910113 unmodified linesfrom typing import Listimport osimport asyncioclass EmbeddingModel:def __init__(self, embeddings_model_name: str = "text-embedding-3-small"):load_dotenv()3 unmodified lines456789101112133 unmodified linesfrom typing import Listimport osimport asynciofrom dotenv import load_dotenvload_dotenv()print(os.getenv('OPENAI_API_KEY'))class EmbeddingModel:def __init__(self, embeddings_model_name: str = "text-embedding-3-small"):load_dotenv()
13 unmodified lines1415161718197 unmodified lines27282930313233343536373839404142434445462 unmodified lines49505152535455565758596014 unmodified lines757677787980818283848525 unmodified lines11111211311411511611711811912012113 unmodified linesfrom langchain_text_splitters import RecursiveCharacterTextSplitter# from langchain_experimental.text_splitter import SemanticChunker# from langchain_openai.embeddings import OpenAIEmbeddingssystem_template = """\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."""7 unmodified lines"""user_role_prompt = UserRolePrompt(user_prompt_template)class RetrievalAugmentedQAPipeline:def __init__(self, llm: ChatOpenAI(), vector_db_retriever: VectorDatabase) -> None:self.llm = llmself.vector_db_retriever = vector_db_retrieverasync def arun_pipeline(self, user_query: str):context_list = self.vector_db_retriever.search_by_text(user_query, k=4)context_prompt = ""for context in context_list:context_prompt += context[0] + "\n"formatted_system_prompt = system_role_prompt.create_message()formatted_user_prompt = user_role_prompt.create_message(question=user_query, context=context_prompt)async def generate_response():2 unmodified linesreturn {"response": generate_response(), "context": context_list}text_splitter = RecursiveCharacterTextSplitter()# try:# api_key = os.environ["OPENAI_API_KEY"]# except KeyError:# print("Environment variable OPENAI_API_KEY not found")# text_splitter = SemanticChunker(OpenAIEmbeddings(api_key=api_key), breakpoint_threshold_type="standard_deviation")def process_text_file(file: AskFileResponse):import tempfile14 unmodified lineselse:raise ValueError("Provide a .txt or .pdf file")texts = [x.page_content for x in text_splitter.transform_documents(documents)]# texts = [x.page_content for x in text_splitter.split_documents(documents)]return texts@cl.on_chat_startasync def on_chat_start():files = None25 unmodified lineschat_openai = ChatOpenAI()# Create a chainretrieval_augmented_qa_pipeline = RetrievalAugmentedQAPipeline(vector_db_retriever=vector_db,llm=chat_openai)# Let the user know that the system is readymsg.content = f"Processing `{file.name}` done. You can now ask questions!"13 unmodified lines141516171819202122237 unmodified lines3132333435363738394041424344454647482 unmodified lines51525354555657585960616214 unmodified lines77787980818283848525 unmodified lines11111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334413 unmodified linesfrom langchain_text_splitters import RecursiveCharacterTextSplitter# from langchain_experimental.text_splitter import SemanticChunker# from langchain_openai.embeddings import OpenAIEmbeddingsimport importlibsystem_template = """\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."""7 unmodified lines"""user_role_prompt = UserRolePrompt(user_prompt_template)class AgenticRAGPipeline:def __init__(self, graph: StateGraph, vector_db_retriever: VectorDatabase) -> None:self.graph = graphself.vector_db_retriever = vector_db_retrieverasync def run_pipeline(self, user_query: str):state = self.graph.execute({"text": user_query, "chunk_size": 100})context_list = state["retriever"]context_prompt = "\n".join(context_list)formatted_system_prompt = system_role_prompt.create_message()formatted_user_prompt = user_role_prompt.create_message(question=user_query, context=context_prompt)async def generate_response():2 unmodified linesreturn {"response": generate_response(), "context": context_list}text_splitter = RecursiveCharacterTextSplitter()def process_text_file(file: AskFileResponse):import tempfile14 unmodified lineselse:raise ValueError("Provide a .txt or .pdf file")texts = [x.page_content for x in text_splitter.transform_documents(documents)]return texts@cl.on_chat_startasync def on_chat_start():files = None25 unmodified lineschat_openai = ChatOpenAI()retriever = vector_db"""Graph code here"""from langchain.tools.retriever import create_retriever_toolfrom typing import Annotated, Literal, Sequence, TypedDictfrom typing import Annotated, Sequence, TypedDictfrom langchain_core.messages import BaseMessagefrom langgraph.graph.message import add_messagesfrom langchain import hubfrom langchain_core.messages import BaseMessage, HumanMessagefrom langchain_core.output_parsers import StrOutputParserfrom langchain_core.prompts import PromptTemplatefrom langchain_openai import ChatOpenAIfrom pydantic import BaseModel, Fieldfrom langgraph.prebuilt import tools_conditionfrom aimakerspace.vectordatabase import VectorDatabaseretriever_tool = create_retriever_tool(retriever,"retrieve_blog_posts","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.",)tools = [retriever_tool]class AgentState(TypedDict):# The add_messages function defines how an update should be processed# Default is to replace. add_messages says "append"messages: Annotated[Sequence[BaseMessage], add_messages]### Edgesdef grade_documents(state) -> Literal["generate", "rewrite"]:"""Determines whether the retrieved documents are relevant to the question.Args:state (messages): The current stateReturns:str: A decision for whether the documents are relevant or not"""# Data modelclass grade(BaseModel):"""Binary score for relevance check."""binary_score: str = Field(description="Relevance score 'yes' or 'no'")# LLMmodel = ChatOpenAI(temperature=0, model="gpt-4o-mini", streaming=True)# LLM with tool and validationllm_with_tool = model.with_structured_output(grade)# Promptprompt = PromptTemplate(template="""You are a grader assessing relevance of a retrieved document to a user question. \nHere is the retrieved document: \n\n {context} \n\nHere is the user question: {question} \nIf the document contains keyword(s) or semantic meaning related to the user question, grade it as relevant. \nGive a binary score 'yes' or 'no' score to indicate whether the document is relevant to the question.""",input_variables=["context", "question"],)# Chainchain = prompt | llm_with_toolmessages = state["messages"]last_message = messages[-1]question = messages[0].contentdocs = last_message.contentscored_result = chain.invoke({"question": question, "context": docs})score = scored_result.binary_scoreif score == "yes":print("---DECISION: DOCS RELEVANT---")return "generate"else:print("---DECISION: DOCS NOT RELEVANT---")print(score)return "rewrite"### Nodesdef agent(state):"""Invokes the agent model to generate a response based on the current state. Giventhe question, it will decide to retrieve using the retriever tool, or simply end.Args:state (messages): The current stateReturns:dict: The updated state with the agent response appended to messages"""print("---CALL AGENT---")messages = state["messages"]model = ChatOpenAI(temperature=0, streaming=True, model="gpt-4o-mini")model = model.bind_tools(tools)response = model.invoke(messages)# We return a list, because this will get added to the existing listreturn {"messages": [response]}def rewrite(state):"""Transform the query to produce a better question.Args:state (messages): The current stateReturns:dict: The updated state with re-phrased question"""print("---TRANSFORM QUERY---")messages = state["messages"]question = messages[0].contentmsg = [HumanMessage(content=f""" \nLook at the input and try to reason about the underlying semantic intent / meaning. \nHere is the initial question:\n ------- \n{question}\n ------- \nFormulate an improved question: """,)]# Gradermodel = ChatOpenAI(temperature=0, model="gpt-4o-mini", streaming=True)response = model.invoke(msg)return {"messages": [response]}def generate(state):"""Generate answerArgs:state (messages): The current stateReturns:dict: The updated state with re-phrased question"""print("---GENERATE---")messages = state["messages"]question = messages[0].contentlast_message = messages[-1]docs = last_message.content# Promptprompt = hub.pull("rlm/rag-prompt")# LLMllm = ChatOpenAI(model_name="gpt-4o-mini", temperature=0, streaming=True)# Post-processingdef format_docs(docs):return "\n\n".join(doc.page_content for doc in docs)# Chainrag_chain = prompt | llm | StrOutputParser()# Runresponse = rag_chain.invoke({"context": docs, "question": question})return {"messages": [response]}from langgraph.graph import END, StateGraph, STARTfrom langgraph.prebuilt import ToolNode# Define a new graphworkflow = StateGraph(AgentState)# Define the nodes we will cycle betweenworkflow.add_node("agent", agent) # agentretrieve = ToolNode([retriever_tool])workflow.add_node("retrieve", retrieve) # retrievalworkflow.add_node("rewrite", rewrite) # Re-writing the questionworkflow.add_node("generate", generate) # Generating a response after we know the documents are relevant# Call agent node to decide to retrieve or notworkflow.add_edge(START, "agent")# Decide whether to retrieveworkflow.add_conditional_edges("agent",# Assess agent decisiontools_condition,{# Translate the condition outputs to nodes in our graph"tools": "retrieve",END: END,},)# Edges taken after the `action` node is called.workflow.add_conditional_edges("retrieve",# Assess agent decisiongrade_documents,)workflow.add_edge("generate", END)workflow.add_edge("rewrite", "agent")# Compilegraph = workflow.compile()"""END GRAPH CODE"""# Create a chainretrieval_augmented_qa_pipeline = AgenticRAGPipeline(graph=graph, vector_db_retriever=vector_db)# Let the user know that the system is readymsg.content = f"Processing `{file.name}` done. You can now ask questions!"
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137import osfrom typing import Listfrom chainlit.types import AskFileResponsefrom aimakerspace.text_utils import CharacterTextSplitter, TextFileLoaderfrom aimakerspace.openai_utils.prompts import ( UserRolePrompt, SystemRolePrompt, AssistantRolePrompt,)from aimakerspace.openai_utils.embedding import EmbeddingModelfrom aimakerspace.vectordatabase import VectorDatabasefrom aimakerspace.openai_utils.chatmodel import ChatOpenAIimport chainlit as clfrom langchain_text_splitters import RecursiveCharacterTextSplitter# from langchain_experimental.text_splitter import SemanticChunker# from langchain_openai.embeddings import OpenAIEmbeddings
system_template = """\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."""system_role_prompt = SystemRolePrompt(system_template)
user_prompt_template = """\Context:{context}Question:{question}"""user_role_prompt = UserRolePrompt(user_prompt_template)
class RetrievalAugmentedQAPipeline: def __init__(self, llm: ChatOpenAI(), vector_db_retriever: VectorDatabase) -> None: self.llm = llm self.vector_db_retriever = vector_db_retriever
async def arun_pipeline(self, user_query: str): context_list = self.vector_db_retriever.search_by_text(user_query, k=4)
context_prompt = "" for context in context_list: context_prompt += context[0] + "\n"
formatted_system_prompt = system_role_prompt.create_message()
formatted_user_prompt = user_role_prompt.create_message(question=user_query, context=context_prompt)
async def generate_response(): async for chunk in self.llm.astream([formatted_system_prompt, formatted_user_prompt]): yield chunk
return {"response": generate_response(), "context": context_list}
text_splitter = RecursiveCharacterTextSplitter()# try:# api_key = os.environ["OPENAI_API_KEY"]# except KeyError:# print("Environment variable OPENAI_API_KEY not found")# text_splitter = SemanticChunker(OpenAIEmbeddings(api_key=api_key), breakpoint_threshold_type="standard_deviation")
def process_text_file(file: AskFileResponse): import tempfile from langchain_community.document_loaders.pdf import PyPDFLoader
with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=file.name) as temp_file: temp_file_path = temp_file.name
with open(temp_file_path, "wb") as f: f.write(file.content)
if file.type == 'text/plain': text_loader = TextFileLoader(temp_file_path) documents = text_loader.load_documents() elif file.type == 'application/pdf': pdf_loader = PyPDFLoader(temp_file_path) documents = pdf_loader.load() else: raise ValueError("Provide a .txt or .pdf file") texts = [x.page_content for x in text_splitter.transform_documents(documents)] # texts = [x.page_content for x in text_splitter.split_documents(documents)] return texts
@cl.on_chat_startasync def on_chat_start(): files = None
# Wait for the user to upload a file while files == None: files = await cl.AskFileMessage( content="Please upload a Text file or a PDF to begin!", accept=["text/plain", "application/pdf"], max_size_mb=12, timeout=180, ).send()
file = files[0]
msg = cl.Message( content=f"Processing `{file.name}`...", disable_human_feedback=True ) await msg.send()
# load the file texts = process_text_file(file)
print(f"Processing {len(texts)} text chunks")
# Create a dict vector store vector_db = VectorDatabase() vector_db = await vector_db.abuild_from_list(texts) chat_openai = ChatOpenAI()
# Create a chain retrieval_augmented_qa_pipeline = RetrievalAugmentedQAPipeline( vector_db_retriever=vector_db, llm=chat_openai ) # Let the user know that the system is ready msg.content = f"Processing `{file.name}` done. You can now ask questions!" await msg.update()
cl.user_session.set("chain", retrieval_augmented_qa_pipeline)
@cl.on_messageasync def main(message): chain = cl.user_session.get("chain")
msg = cl.Message(content="") result = await chain.arun_pipeline(message.content)
async for stream_resp in result["response"]: await msg.stream_token(stream_resp)
await msg.send()3 unmodified lines45673 unmodified lineslangchain_communitylangchain_experimentallangchain_openaipypdf3 unmodified lines4567891011123 unmodified lineslangchain_communitylangchain_experimentallangchain_openaipypdftiktokenlangchainhublangchainlanggraphlangchain-text-splitters
AgenticRAG/agentic_rag.py+225
AgenticRAG/aimakerspace/openai_utils/embedding.py+3-1
AgenticRAG/app.py+243-20
AgenticRAG/previous_app.pyAdded+137
AgenticRAG/requirements.txt+6-1
agentic_rag.pyAdded