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

# Building a ReAct Agent

> Orchestrate reasoning loops and execute tools recursively using LangGraph

By combining reasoning and tool execution, we can construct a **ReAct Agent** that runs in a loop to solve problems. This page covers building a complete working agent project.

## 1. The Modern LangChain Agent Stack

To build agents in modern LangChain, we use **LangGraph**, which models agents as state graphs where the LLM decides node transitions (e.g. calling tools vs. returning the final response).

```text theme={null}
User Input ──> [ Agent Loop (LLM) ] ──(decides)──> [ Call Tool ] ──(execute)──> [ Return to Loop ]
                      │
                   (finish)
                      ▼
                 Final Answer
```

## 2. In-Memory Working Agent Project

Let's build a working agent equipped with a math evaluation tool and a dictionary database look-up tool.

### 2.1 Install Dependencies

Run in your terminal:

```bash theme={null}
uv add langgraph langchain-google-genai
```

### 2.2 Complete Code Implementation

Save and run this script:

```python theme={null}
import os
from dotenv import load_dotenv
from langchain_core.tools import tool
from langchain.chat_models import init_chat_model
from langgraph.prebuilt import create_react_agent

# 1. Load environment variables
load_dotenv()

# 2. Define custom tools
@tool
def calculate_math(expression: str) -> str:
    """Evaluates basic mathematical expressions (addition, subtraction, multiplication, division)."""
    try:
        # Using eval safely by restricting scope
        result = eval(expression, {"__builtins__": None}, {})
        return str(result)
    except Exception as e:
        return f"Error evaluating expression: {str(e)}"

@tool
def get_user_email(employee_name: str) -> str:
    """Queries the internal HR directory to find an employee's email address."""
    directory = {
        "alice": "alice@company.com",
        "bob": "bob@company.com",
        "siva": "siva@company.com"
    }
    name_lower = employee_name.lower().strip()
    return directory.get(name_lower, f"User {employee_name} not found in HR directory.")

# 3. Initialize the Chat Model
llm = init_chat_model("gemini-2.5-flash", model_provider="google_genai")

# 4. Bind tools and create the ReAct Agent
tools = [calculate_math, get_user_email]
agent = create_react_agent(llm, tools)

# 5. Run the agent with a multi-step query
# The agent must: 
# 1. Look up Siva's email.
# 2. Calculate the math expression.
# 3. Answer both in a single response.
query = "Find siva's email and calculate 345 * 12."
print(f"Goal: '{query}'\n")

print("Executing Agent Loop...")
inputs = {"messages": [("user", query)]}
response = agent.invoke(inputs)

# 6. Print final conversation trace
print("\n--- Final Agent Response ---")
print(response["messages"][-1].content)
```

**Expected Trace Behavior:**

1. The agent notices `"Find siva's email"` and runs `get_user_email(employee_name="siva")`.
2. The agent notices `"calculate 345 * 12"` and runs `calculate_math(expression="345 * 12")`.
3. The agent merges both observations and outputs: *"Siva's email is [siva@company.com](mailto:siva@company.com) and 345 \* 12 is 4140."*

## 3. Practice Exercises

### Practice 1: Add a Currency Converter Tool

Extend the working agent by adding a new tool `convert_usd_to_eur(amount: float) -> float` that multiplies the USD amount by `0.92`. Run the query: `"Find siva's email and convert 150 USD to EUR."` and print the output.

**Instructions:**

1. Write the `convert_usd_to_eur` tool.
2. Add it to the `tools` list.
3. Call `create_react_agent(llm, tools)`.
4. Invoke the agent and print the final message content.

<Accordion title="Solution">
  ```python theme={null}
  from langchain_core.tools import tool
  from langchain.chat_models import init_chat_model
  from langgraph.prebuilt import create_react_agent

  @tool
  def convert_usd_to_eur(amount: float) -> float:
      """Converts USD currency amount to EUR using a fixed exchange rate."""
      return amount * 0.92

  # Existing tools
  tools = [calculate_math, get_user_email, convert_usd_to_eur]
  llm = init_chat_model("gemini-2.5-flash", model_provider="google_genai")

  agent = create_react_agent(llm, tools)

  query = "Find siva's email and convert 150 USD to EUR."
  inputs = {"messages": [("user", query)]}
  response = agent.invoke(inputs)

  print(response["messages"][-1].content)
  ```
</Accordion>
