To construct a LangGraph workflow that integrates tools, recursive refinement, human interaction, and Retrieval-Augmented Generation (RAG), you can follow the example below. This workflow involves an agent that processes user queries, utilizes external tools for information retrieval, iteratively refines its responses, and incorporates human feedback to enhance accuracy.
1. Define the Tools
First, create tools for context retrieval. For instance, you can define a tool that searches for relevant documents:
from langchain_core.tools import tool
from langchain_community.document_loaders import UnstructuredURLLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.vectorstores import Chroma
from langchain_openai.embeddings import OpenAIEmbeddings
@tool
def retrieve_context(query: str):
"""Search for relevant documents."""
urls = [
"https://docs.python.org/3/tutorial/index.html",
"https://realpython.com/python-basics/",
"https://www.learnpython.org/"
]
loader = UnstructuredURLLoader(urls=urls)
docs = loader.load()
text_splitter = RecursiveCharacterTextSplitter(chunk_size=100, chunk_overlap=50)
doc_splits = text_splitter.split_documents(docs)
vectorstore = Chroma.from_documents(
documents=doc_splits,
collection_name="python_docs",
embedding=OpenAIEmbeddings(),
)
retriever = vectorstore.as_retriever()
results = retriever.invoke(query)
return "\n".join([doc.page_content for doc in results])
This tool loads documents from specified URLs, splits them into manageable chunks, creates a vector store, and retrieves relevant documents based on the query.
2. Set Up the Agent and Tools
Next, define the agent (Language Model) and bind the tools to it:
from langchain_openai.chat_models import ChatOpenAI
from langgraph.prebuilt import ToolNode
tools = [retrieve_context]
tool_node = ToolNode(tools)
model = ChatOpenAI(model="gpt-3.5-turbo", temperature=0).bind_tools(tools)
Here, ChatOpenAI is initialized with the desired model, and the tools are bound to it using bind_tools.
3. Define the Workflow with LangGraph
Now, construct the LangGraph workflow:
from langgraph.graph import END, START, StateGraph, MessagesState
def should_continue(state: MessagesState) -> str:
messages = state['messages']
last_message = messages[-1]
if last_message.tool_calls:
return "tools"
return END
def call_model(state: MessagesState):
messages = state['messages']
response = model.invoke(messages)
return {"messages": [response]}
workflow = StateGraph(MessagesState)
workflow.add_node("agent", call_model)
workflow.add_node("tools", tool_node)
workflow.add_edge(START, "agent")
workflow.add_conditional_edges("agent", should_continue)
workflow.add_edge("tools", "agent")
In this setup:
call_model invokes the Language Model with the current state messages.
should_continue determines whether to proceed to the tools node or end the workflow based on the agent's response.
- The workflow cycles between the agent and tools nodes, allowing for recursive refinement.
4. Incorporate Human-in-the-Loop Interaction
To include human feedback, you can introduce an interrupt in the workflow:
from langgraph.types import Command
def human_approval(state: MessagesState):
last_message = state['messages'][-1]
user_feedback = interrupt(
{
"question": "Is this response satisfactory?",
"llm_output": last_message.content
}
)
if user_feedback.lower() == 'yes':
return END
else:
return "agent"
workflow.add_node("human_approval", human_approval)
workflow.add_edge("agent", "human_approval")
workflow.add_conditional_edges("human_approval", lambda state: END if state['messages'][-1].content == 'yes' else "agent")
In this addition:
human_approval function prompts the user to approve or disapprove the agent's response.
- The workflow directs to the
human_approval node after the agent's response.
- Based on user feedback, the workflow either ends or returns to the agent for further refinement.
5. Execute the Workflow
Finally, compile and run the workflow:
from langgraph.checkpoint.memory import MemorySaver
checkpointer = MemorySaver()
app = workflow.compile(checkpointer=checkpointer)
final_state = app.invoke(
{"messages": [HumanMessage(content="Explain what a list is in Python")]},
config={"configurable": {"thread_id": 42}}
)
print(final_state["messages"][-1].content)
This execution initiates the workflow with a user query, processes it through the defined nodes, and outputs the final refined response.
By following this structure, you create a LangGraph workflow that effectively utilizes tools for information retrieval, allows for recursive refinement of responses, and incorporates human feedback to ensure accuracy and relevance.
For a more detailed guide and additional context, you can refer to the article "Building an Agentic RAG with LangGraph: A Step-by-Step Guide" by Wendell Rodrigues, Ph.D[1].