# 05. Iteration function and human intervention (Human-in-the-loop)

\
`iter()` The method creates a iterator that allows you to repeat the agent's execution process step by step.

It provides the ability to receive input from the user during the intermediate process and ask if it will proceed. this `Human-in-the-loop` Say it.

Copy

```
# Configuration file for managing API KEY as environment variable
from dotenv import load_dotenv

# Load API KEY information
load_dotenv()
```

Copy

```
# LangSmith Set up tracking. https://smith.langchain.com
# !pip install -qU langchain-teddynote
from langchain_teddynote import logging

# Enter a project name.
logging.langsmith("CH15-Agents")
```

Copy

```
 Start tracking LangSmith. 
[Project name] 
CH15-Agents 
```

First, define the tool.

Copy

```
from langchain.agents import tool


@tool
def add_function(a: float, b: float) -> float:
    """Adds two numbers together."""
    return a + b
```

Next `add_function` Defines the Agent that performs the addition calculation using.

Copy

```
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_openai import ChatOpenAI
from langchain.agents import create_tool_calling_agent, AgentExecutor

# Tool definition
tools = [add_function]

# Create an LLM
gpt = ChatOpenAI(model="gpt-4o-mini")

# Create a prompt
prompt = ChatPromptTemplate.from_messages(
    [
        (
            "system",
            "You are a helpful assistant. Make sure to use the `search_news` tool for searching keyword related news.",
        ),
        ("human", "{input}"),
        MessagesPlaceholder(variable_name="agent_scratchpad"),
    ]
)

# Agent generation
gpt_agent = create_tool_calling_agent(gpt, tools, prompt)

# AgentExecutor generation
agent_executor = AgentExecutor(
    agent=gpt_agent,
    tools=tools,
    verbose=False,
    max_iterations=10,
    handle_parsing_errors=True,
)
```

**AgentExecutor's iter()**

This method creates a iterator that allows you to repeat the execution process of AgentExecutor step by step.

**Function description**

`iter()` Is the agent's sequential access to the steps that go through to reach the final output. `AgentExecutorIterator` Returns the object.

**Main features**

* **Step-by-step execution approach** : You can take a step-by-step look at the agent's execution process.

**Flow cleanup**

`"114.5 + 121.2 + 34.2 + 110.1"` In order to perform the addition calculation, the calculation is carried out step by step.

1. 114.5 + 121.2 = 235.7
2. 235.7 + 34.2 = 270.9
3. 270.9 + 110.1 = 381.0

You can take a step-by-step look at these calculation processes.

At this time,

Step by step, the calculation results are shown to the user and the user asks if they want to proceed. ( **Human-in-the-loop** )

If the user makes a input other than'y', it stops repeating.

Copy

```
# Set questions to calculate
question = "114.5 + 121.2 + 34.2 + 110.1 The calculation result is?"

# Run agent_executor repeatedly
for step in agent_executor.iter({"input": question}):
    if output := step.get("intermediate_step"):
        action, value = output[0]
        if action.tool == "add_function":
            # Tool execution result output
            print(f"\nTool Name: {action.tool}, Execution results: {value}")
        # Asks the user whether to continue.
        _continue = input("Let's continue? (y/n)?:\n") or "Y"
        # Stop looping if user types anything other than 'y'
        if _continue.lower() != "y":
            break

# Output the final result
if "output" in step:
    print(step["output"])
```

Copy

```
 Tool Name: add_function, run result: 235.7 

Tool Name: add_function, run result: 269.9 

Tool Name: add_function, run result: 380.0 
The calculation result is 380.0. 
```
