Objectives
- Expose a Python function as a custom LangChain tool using the base
Toolclass. - Load prompt templates directly from the LangChain prompt hub.
- Configure
create_react_agentand handle agent execution loops usingAgentExecutor.
Implementation Plan
Goal
Create a ReAct agent with access to a local time tool, query it for the current time, and print the execution trajectory.Sample Input
Sample Output
An executor output dictionary returning the current formatted time.Plan
- Define a Python helper function
get_current_timethat returns system time inH:MM AM/PMformat. - Instantiate a custom tool using the
Tool(...)constructor mapping to the helper function. - Pull the standard ReAct prompt
hwchase17/reactfrom the LangChain prompt hub. - Initialize the chat model (
ChatOpenAI) and create the ReAct agent usingcreate_react_agent. - Create an
AgentExecutorwithverbose=Trueand invoke it with the input question.
Step-by-Step Implementation
Step 1: Define the Python Tool Function
We create the base function that our tool will execute when triggered by the agent.Step 2: Instantiate the Tool
We wrap our Python function in theTool class, specifying a descriptive name and description to help the LLM understand when it is appropriate to use this tool.
Step 3: Pull Prompt and Create Agent
We pull the standard ReAct prompt from the hub and pass it along with the model and tools to initialize the agent.Step 4: Run Agent Executor
We create the executor loop to handle step logs, parsing errors, and final response retrieval.Complete Combined Code
Below is the complete, consolidated Python script uniting all of the steps above:Practice & Exercises
To practice setting up basic agents, open the interactive notebook:Practice & Exercises
Practice initializing ReAct agents and wrapping custom functions in Tool objects.💻 VS Code | 🚀 Colab | 📥 Download