Skip to main content
In this section, you will build a basic ReAct (Reasoning and Acting) agent from scratch and expose a simple python function as a tool to retrieve the current system time.

Objectives

  1. Expose a Python function as a custom LangChain tool using the base Tool class.
  2. Load prompt templates directly from the LangChain prompt hub.
  3. Configure create_react_agent and handle agent execution loops using AgentExecutor.

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

  1. Define a Python helper function get_current_time that returns system time in H:MM AM/PM format.
  2. Instantiate a custom tool using the Tool(...) constructor mapping to the helper function.
  3. Pull the standard ReAct prompt hwchase17/react from the LangChain prompt hub.
  4. Initialize the chat model (ChatOpenAI) and create the ReAct agent using create_react_agent.
  5. Create an AgentExecutor with verbose=True and 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 the Tool 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