Assemble an AI agent using LangChain. Build RAG pipelines, write custom calculation tools, and implement a ReAct planning loop.
Domain / Environment
Generative AI / Conda VM
Difficulty
Advanced (4/5)
Course Module
Generative AI & AI Agents
Deliverables
AI Agent script & ReAct trace logs
1. System Architecture & ReAct Loop
The diagram below displays the ReAct (Reasoning and Acting) agent workflow. The agent receives a query, decides whether to query the document database (RAG) or use the custom calculator tool, runs the selected action, and returns the final answer.
2. Part 1: Step-by-Step Action Items & Key Execution Steps
STEP 1
Activate Python Virtual Environment
Point the terminal execution environment to the course conda sandbox environment.
$ conda activate ds_ai_ml
This targets active python libraries to the isolated virtual sandbox.
STEP 2
Create Project Folders inside Linux VM
Create a dedicated folder for the project files inside your guest VM home folder directory.
$ mkdir -p ~/Projects/agent_app && cd ~/Projects/agent_app
This sets up the working directory layout for the agent code.
STEP 3
Install LangChain via Pip
Install the required LangChain core library inside the active conda session.
$ pip install langchain-core numpy
This installs the `langchain-core` library to define custom tools, prompts, and run loops.
STEP 4
Create agent script file in VS Code
Launch VS Code and create the agent script file.
Launch VS Code via terminal "code ." -> New File -> Type: react_agent.py -> Paste Python code -> Save file
This registers the custom tools, vector database, and ReAct loop in `react_agent.py`.
STEP 5
Run and Verify the ReAct agent
Execute the script to run the agent planning loop and verify tool usage.
$ python react_agent.py
This runs the agent loop, showing the ReAct planning steps, database queries, and tool execution outputs.
3. Agent Execution Flow
The flowchart below outlines the agent execution flow. It details the steps from query parsing and choosing tools to executing calculations, updating context, and returning the final answer.
4. Part 2: Complete Deliverable Assets & Production Templates
To run the agent, we need the Python script file. Below is a line-by-line explanation of the code, followed by the combined template.
Step-by-Step Code Construction
Lines 1 - 5
Import LangChain core tools
Include system packages, LangChain tool decorators, and prompt templates in the script.
from langchain_core.tools import tool
from langchain_core.prompts import PromptTemplate
import os
import re
These imports pull custom tool decorators and prompt formatting utilities from LangChain.
Lines 6 - 20
Define Custom RAG and Calculator Tools
Define two Python functions with the `@tool` decorator to retrieve customer details and run calculations.
@tool
def query_salary_database(employee_id: str) -> str:
"""Queries salary database using employee ID."""
database = {"5": "50000.00", "12": "85000.00"}
return database.get(employee_id, "Employee ID not found")
@tool
def calculate_bonus(salary: float, rate: float) -> float:
"""Calculates employee bonus based on salary and rate."""
return salary * rate
This registers the functions as LangChain tools, enabling the agent to load and execute them.
Lines 21 - 42
Implement Agent Decision Loop
Write the ReAct execution loop. The agent reasons about user queries, calls the appropriate tools, and updates the observation log.
# Run loop
thought = "I need to check the salary database first."
observation_1 = query_salary_database.run("5")
thought_2 = f"Salary is {observation_1}. Now I need to calculate the 10% bonus."
observation_2 = calculate_bonus.run({"salary": float(observation_1), "rate": 0.1})
final_answer = f"The bonus for employee ID 5 is ${observation_2}."
This parses the inputs, queries the salary database, calculates the bonus, and prints the final answer.
Production templates
1. Python script (Save as ~/Projects/agent_app/react_agent.py):
# react_agent.py - Custom LangChain Agent with RAG and Calculator toolsfrom langchain_core.tools import tool
from langchain_core.prompts import PromptTemplate
import re
# 1. Define Tools
@tool
defquery_employee_database(employee_id: str) -> str:
"""Queries the internal database to retrieve salary and contract details using the employee ID."""
db = {
"5": "Salary: $50000.00, Contract: Full-time",
"12": "Salary: $85000.00, Contract: Full-time",
"22": "Salary: $42000.00, Contract: Part-time"
}
return db.get(employee_id.strip(), "Employee ID not found")
@tool
defcalculate_percentage_bonus(salary_str: str) -> str:
"""Calculates a 10% bonus for a given salary amount string (e.g. '$50000.00')."""
try:
# Extract numeric float values
val = float(re.sub(r'[^\d.]', '', salary_str))
bonus = val * 0.1
return f"${bonus:.2f}"
except Exception as e:
return f"Error parsing salary value: {e}"defrun_react_agent(query):
print(f"User Query: \"{query}\"")
# 2. Configure Prompt Template
react_template = """Question: {query}
Thought: I need to retrieve the employee's salary details from the database first.
Action: query_employee_database(employee_id="5")
Observation: {observation_1}
Thought: I have the salary details. Now I need to calculate the 10% bonus.
Action: calculate_percentage_bonus(salary_str="{salary_val}")
Observation: {observation_2}
Thought: I have calculated the bonus. I can now provide the final answer.
Final Answer: {final_answer}"""# 3. Simulate ReAct execution loop
print("\n[Agent Execution Logs]")
# Step 1: Thought & Action
print("Thought 1: I need to retrieve the employee's salary details from the database first.")
print("Calling Tool: query_employee_database(employee_id='5')...")
obs_1 = query_employee_database.invoke("5")
print(f"Observation 1: {obs_1}")
# Step 2: Thought & Action
print("Thought 2: I have the salary details. Now I need to calculate the 10% bonus.")
print("Calling Tool: calculate_percentage_bonus(salary_str='$50000.00')...")
obs_2 = calculate_percentage_bonus.invoke(obs_1)
print(f"Observation 2: {obs_2}")
# Step 3: Final Answer
ans = f"Employee ID 5 has a {obs_1}. The calculated 10% bonus is {obs_2}."
print("\n[Final Agent Answer]")
print(ans)
defmain():
print("=== Starting LangChain ReAct Agent Application ===")
query = "Check the salary for employee ID 5 and calculate a 10% bonus."
run_react_agent(query)
print("\n=== LangChain AI Agent Demonstration Completed! ===")
if __name__ == "__main__":
main()
5. Deliverables Summary
Verify that the following configurations and outputs exist inside your project workspace.