> ## Documentation Index
> Fetch the complete documentation index at: https://genai.codewithsiva.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# 1. Agent & Tools Basics

> Build a basic ReAct agent with a simple custom tool

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

```python theme={null}
{"input": "What time is it?"}
```

#### 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.

```python theme={null}
def get_current_time(*args, **kwargs):
    """Returns the current time in H:MM AM/PM format."""
    import datetime
    now = datetime.datetime.now()
    return now.strftime("%I:%M %p")
```

### 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.

```python theme={null}
from langchain_core.tools import Tool

tools = [
    Tool(
        name="Time",
        func=get_current_time,
        description="Useful for when you need to know the current time",
    ),
]
```

### 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.

```python theme={null}
from langchain import hub
from langchain.agents import create_react_agent
from langchain.chat_models import init_chat_model

prompt = hub.pull("hwchase17/react")
llm = init_chat_model("llama-3.3-70b-versatile", model_provider="groq", temperature=0)

agent = create_react_agent(
    llm=llm,
    tools=tools,
    prompt=prompt,
    stop_sequence=True,
)
```

### Step 4: Run Agent Executor

We create the executor loop to handle step logs, parsing errors, and final response retrieval.

```python theme={null}
from langchain.agents import AgentExecutor

agent_executor = AgentExecutor.from_agent_and_tools(
    agent=agent,
    tools=tools,
    verbose=True,
)

response = agent_executor.invoke({"input": "What time is it?"})
print("response:", response)
```

## Complete Combined Code

Below is the complete, consolidated Python script uniting all of the steps above:

```python theme={null}
from dotenv import load_dotenv
from langchain import hub
from langchain.agents import (
    AgentExecutor,
    create_react_agent,
)
from langchain_core.tools import Tool
from langchain.chat_models import init_chat_model

# Load environment variables from .env file
load_dotenv()


# Define a very simple tool function that returns the current time
def get_current_time(*args, **kwargs):
    """Returns the current time in H:MM AM/PM format."""
    import datetime  # Import datetime module to get current time

    now = datetime.datetime.now()  # Get current time
    return now.strftime("%I:%M %p")  # Format time in H:MM AM/PM format


# List of tools available to the agent
tools = [
    Tool(
        name="Time",  # Name of the tool
        func=get_current_time,  # Function that the tool will execute
        # Description of the tool
        description="Useful for when you need to know the current time",
    ),
]

# Pull the prompt template from the hub
prompt = hub.pull("hwchase17/react")

# Initialize a Groq model using core abstractions
llm = init_chat_model(
    "llama-3.3-70b-versatile", model_provider="groq", temperature=0
)

# Create the ReAct agent using the create_react_agent function
agent = create_react_agent(
    llm=llm,
    tools=tools,
    prompt=prompt,
    stop_sequence=True,
)

# Create an agent executor from the agent and tools
agent_executor = AgentExecutor.from_agent_and_tools(
    agent=agent,
    tools=tools,
    verbose=True,
)

# Run the agent with a test query
response = agent_executor.invoke({"input": "What time is it?"})

# Print the response from the agent
print("response:", response)
```

## Practice & Exercises

To practice setting up basic agents, open the interactive notebook:

<CardGroup cols={1}>
  <Card title="Practice & Exercises" icon="laptop-code">
    Practice initializing ReAct agents and wrapping custom functions in Tool objects.

    [💻 VS Code](vscode://file/Users/sivaprasad/Downloads/GenAI%20With%20Python/public/notebooks/langchain/1_agent_tools_basics.ipynb) | [🚀 Colab](https://colab.research.google.com/github/prasad230776/genai-course/blob/master/public/notebooks/langchain/1_agent_tools_basics.ipynb) | <a href="/public/notebooks/langchain/1_agent_tools_basics.ipynb" download>📥 Download</a>
  </Card>
</CardGroup>
