I'll help you create a Jupyter notebook (.ipynb) file that demonstrates a LangGraph ReAct agent with parallel tool calling and RAG capabilities. Here's the code:
python Copy code
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# LangGraph ReAct Agent with Parallel Tool Calling and RAG\n",
"\n",
"This notebook demonstrates how to create a ReAct agent using LangGraph that can execute tool calling and RAG (Retrieval Augmented Generation) in parallel."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"source": [
"# Install required packages\n",
"!pip install langgraph langchain chromadb anthropic"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"source": [
"from typing import Annotated, Sequence, Tuple, TypedDict, Union\n",
"from langgraph.graph import Graph, StateGraph\n",
"from langchain_core.messages import BaseMessage, HumanMessage\n",
"from langchain_anthropic import ChatAnthropic\n",
"from langchain_core.tools import BaseTool\n",
"from langchain_community.vectorstores import Chroma\n",
"from langchain_core.embeddings import Embeddings\n",
"from langchain.embeddings import OpenAIEmbeddings\n",
"import asyncio\n",
"from operator import itemgetter"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"source": [
"# Define the state schema\n",
"class AgentState(TypedDict):\n",
" messages: Sequence[BaseMessage]\n",
" next_step: str\n",
" parallel_results: dict\n",
" final_answer: Union[str, None]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"source": [
"# Initialize the LLM\n",
"llm = ChatAnthropic(model=\"claude-3-sonnet-20240229\")\n",
"\n",
"# Initialize embeddings\n",
"embeddings = OpenAIEmbeddings()\n",
"\n",
"# Initialize vector store\n",
"vectorstore = Chroma(\n",
" collection_name=\"demo_collection\",\n",
" embedding_function=embeddings\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"source": [
"# Define example tools\n",
"class Calculator(BaseTool):\n",
" name = \"calculator\"\n",
" description = \"Useful for performing mathematical calculations\"\n",
" \n",
" def _run(self, query: str) -> str:\n",
" try:\n",
" return str(eval(query))\n",
" except:\n",
" return \"Error in calculation\"\n",
"\n",
"calculator = Calculator()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"source": [
"# Define parallel execution functions\n",
"async def run_tool_and_rag(state: AgentState) -> AgentState:\n",
" # Run tool calling and RAG in parallel\n",
" tool_task = asyncio.create_task(run_tool(state))\n",
" rag_task = asyncio.create_task(run_rag(state))\n",
" \n",
" results = await asyncio.gather(tool_task, rag_task)\n",
" \n",
" state['parallel_results'] = {\n",
" 'tool_result': results[0],\n",
" 'rag_result': results[1]\n",
" }\n",
" return state\n",
"\n",
"async def run_tool(state: AgentState) -> str:\n",
" # Example tool execution\n",
" return calculator._run(\"2 + 2\")\n",
"\n",
"async def run_rag(state: AgentState) -> str:\n",
" # Example RAG query\n",
" results = vectorstore.similarity_search(\"sample query\", k=1)\n",
" return results[0].page_content if results else \"\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"source": [
"# Define the agent's decision making function\n",
"def decide_next_step(state: AgentState) -> AgentState:\n",
" messages = state['messages']\n",
" \n",
" # Add agent's decision making logic here\n",
" response = llm.invoke(messages)\n",
" \n",
" # Parse response and decide next step\n",
" if \"final_answer\" in response.content.lower():\n",
" state['next_step'] = \"finish\"\n",
" state['final_answer'] = response.content\n",
" else:\n",
" state['next_step'] = \"continue\"\n",
" state['messages'].append(response)\n",
" \n",
" return state"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"source": [
"# Create the graph\n",
"workflow = StateGraph(AgentState)\n",
"\n",
"# Add nodes\n",
"workflow.add_node(\"parallel_execution\", run_tool_and_rag)\n",
"workflow.add_node(\"decide\", decide_next_step)\n",
"\n",
"# Add edges\n",
"workflow.add_edge(\"parallel_execution\", \"decide\")\n",
"workflow.add_conditional_edges(\n",
" \"decide\",\n",
" lambda x: x[\"next_step\"],\n",
" {\n",
" \"continue\": \"parallel_execution\",\n",
" \"finish\": \"end\"\n",
" }\n",
")\n",
"\n",
"# Set entry point\n",
"workflow.set_entry_point(\"parallel_execution\")\n",
"\n",
"# Compile\n",
"graph = workflow.compile()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"source": [
"# Example usage\n",
"inputs = {\n",
" \"messages\": [HumanMessage(content=\"What is 2+2 and find relevant information from the database?\")],\n",
" \"next_step\": \"continue\",\n",
" \"parallel_results\": {},\n",
" \"final_answer\": None\n",
"}\n",
"\n",
"# Run the graph\n",
"result = graph.invoke(inputs)\n",
"print(result['final_answer'])"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.0"
}
},
"nbformat": 4,
"nbformat_minor": 4
}