The Browser Use Agent Loop, Step by Step, With Real Logs

7 min read

A browser agent is a loop. The model looks, writes something, the harness runs it, the model looks again. The details of that loop decide how fast the agent is, how much it costs and how it fails. This part walks through the loop in browser-use 1.0.9, from the source code, and runs it for real.

Animation: one step is one model request. The model writes a Python cell, the REPL runs it on Chrome over CDP, the output goes back, and the run ends with finish or finish_from_repl.

Problem: a loop with no rules never ends, or ends too early

An unbounded loop can spin forever on a broken page. A loop that stops on the first error gives up on pages that just needed a retry. And a loop that runs out of budget mid-task can lose everything it already found.

The loop needs four rules: what one step is, when to stop, what to do on errors and how to hand back the result.

What one step is

In 1.0, one step is one model request. The model gets exactly one function tool, python, and two output tools, finish and finish_from_repl. Each python call runs one cell in a persistent REPL, so variables survive between steps.

The loop lives in browser_use/agent/loop.py (1,391 lines in 1.0.9). The key pieces:

PieceWhat the source does
python() toolRuns one cell, logs step N: <first line>, returns text output plus screenshots
DELIVERY_TOOLS['finish_from_repl', 'finish']
Session defaultstimeout_s 1700, cell_timeout_s 120, vision True
delivery_at()90% of the time budget. After that, the model is pushed to deliver
Request limitUsageLimits(request_limit=max_steps+1): the extra request is the delivery turn
Run statusescompleted, max_steps, timeout, error
Model timeoutsMODEL_TIMEOUT_S 300 seconds, STREAM_TIMEOUT_S 930 seconds

Hand-drawn loop: task and system prompt go to the model, which makes a tool call python(code), one cell; the REPL runs it on Chrome via CDP; text output and screenshots go back to the model for the next step; when done the model calls finish(result) or finish_from_repl(expr). max_steps is 100 by default, timeout 1700 seconds, and the last request offers finish tools only

sequenceDiagram
  participant U as Your code
  participant L as Agent loop
  participant M as Model
  participant R as REPL worker
  participant C as Chrome
  U->>L: agent.run(max_steps=100, timeout=1700)
  loop each step
    L->>M: history + last output + screenshot
    M-->>L: python(code)
    L->>R: run cell (120 s cap)
    R->>C: CDP commands
    C-->>R: results
    R-->>L: stdout, errors, images
  end
  L->>M: delivery turn: finish tools only
  M-->>L: finish_from_repl(expression)
  L-->>U: result.status, final_result()

How we ran the loop without a real model

We wanted every code block in this series to run for real, on real pages. But a real model makes runs random and costly. So most runs use a scripted model: a Pydantic AI FunctionModel that returns fixed python tool calls. Everything else is real: the browser-use 1.0.9 Agent, its loop, its REPL worker, browser-harness, the CDP websocket and headless Chromium loading the real page.

This works because 1.0 is built on Pydantic AI, and Agent(llm=...) accepts any Pydantic AI model object. Here is the full script for the first run:

python
import asyncio, json, logging, sys
from pydantic_ai.messages import ModelResponse, ToolCallPart
from pydantic_ai.models.function import FunctionModel, AgentInfo
from browser_use import Agent, Browser

logging.basicConfig(level=logging.INFO, format='%(name)s %(message)s', stream=sys.stdout)

CELLS = [
    "new_tab('https://news.ycombinator.com'); wait_for_load(); page_info()",
    "rows = js(\"return [...document.querySelectorAll('.titleline > a')].slice(0,5).map(a => a.textContent)\")\nrows",
    "screenshot()",
]
step = {'i': 0}

def scripted(messages, info: AgentInfo):
    i = step['i']; step['i'] += 1
    if i == 0:
        print('TOOLS OFFERED TO THE MODEL:', [t.name for t in info.function_tools])
    if i < len(CELLS):
        return ModelResponse(parts=[ToolCallPart('python', {'code': CELLS[i]})])
    return ModelResponse(parts=[ToolCallPart('finish_from_repl', {'expression': 'json.dumps(rows)', 'success': True})])

async def main():
    agent = Agent('Get the top 5 Hacker News titles', llm=FunctionModel(scripted), browser=Browser('chromium'), judge=False)
    r = await agent.run(max_steps=10)
    print('STATUS', r.status, 'STEPS', r.number_of_steps(), 'SUCCESS', r.success)
    print('RESULT', r.final_result())

asyncio.run(main())

Real output, November 28, 2026, about 20:25 IST (HTTP request lines and the task line trimmed):

text
INFO     [browser_use.agent.loop] step 1: new_tab('https://news.ycombinator.com'); wait_for_load(); page_info()
INFO     [browser_use.agent.loop] step 2: rows = js("return [...document.querySelectorAll('.titleline > a')].slice(0,5).map(a => a.textContent)")
INFO     [browser_use.agent.loop] step 3: screenshot()
INFO     [browser_use.agent.service] completed in 4 steps, 4s
TOOLS OFFERED TO THE MODEL: ['python']
STATUS completed STEPS 4 SUCCESS True
RESULT ["Farewell", "Claude Code sabotage: preliminary benchmarking", "Audible removes download option for purchased audiobooks", "Show HN: Luciole Mono \u2013 terminal font designed for legibility", "GGUF LLM Models with Hidden Malware on Hugging Face Reached 2400 Victims"]

Three things to notice:

  • The model is offered one tool, python. That is the whole 1.0 design in one line.
  • Three cells plus one delivery call is four steps.
  • finish_from_repl delivered the value of a REPL variable. The model never had to retype the five titles. That saves output tokens and avoids copy errors.

What the model actually sees after each cell

The scripted runner also prints the exact tool return the model would read. A clean cell returns its printed output and the value of the last expression, like a notebook. A failed cell returns the Python traceback. Here is a real failure from a custom-tools run in Part 5, where a JavaScript snippet used a bare return:

text
Error: Traceback (most recent call last):
RuntimeError: JavaScript evaluation failed at line 0, column 50: SyntaxError: Illegal return statement

There is no special retry logic. The migration guide says the 0.x knobs like max_failures and loop detection are gone, because "failed cells are retried by the model within max_steps". The error text is the feedback. The model reads it and writes a better cell.

Problem: what a real model does with that freedom

We also ran the same loop with real models. The only LLM key with quota for this series was a Cloudflare Workers AI account, so we used two open-weight models, gpt-oss-20b and gpt-oss-120b, through browser-use's ChatOpenAI class and a small local adapter. The adapter flattened message content to plain strings and dropped images, because the Workers AI endpoint rejected list content. So these runs had no vision.

The task was: "Open https://news.ycombinator.com and return the title of the top story."

Modelmax_stepsStatusRequestsInput tokensOutput tokensWall timeRight answer?
gpt-oss-20b6max_steps714,74369353.8 sNo
gpt-oss-120b10completed1134,1661,24358.7 sNo, empty result

Neither model got the title. The step logs show why. Both reached for selectors from older Hacker News markup, .storylink and a.titlelink, which return nothing on today's page. The 120b model then spent steps dumping table rows and finished with an empty string. These are small open models without screenshots, so this is not a verdict on browser-use. It shows the main failure mode of a code-writing agent: confident code based on stale memory of a site. The system prompt's advice to "Prefer the accessibility tree for discovery" exists for exactly this.

A third attempt with gemma-4-26b made one good request and then hit the account's daily free limit (HTTP 429), so we stopped real-model runs there.

Problem: every step resends the whole history

Look at the input token column again. 11 requests used 34,166 input tokens. That is because each request carries the system prompt, the task and every earlier cell and output. Our adapter logged the prompt size of each request:

gpt-oss-120b: prompt tokens per request
4518.53099.51680.5191712158222873251642770529586321373849840669415010428211
Data from the sources listed below.

It more than doubled over 11 requests, from 1,917 to 4,282 tokens. With screenshots on, each step would add images too. Part 9 covers how 1.0 fights this with compaction and caching.

Our scripted Hacker News run, as a sequence:

sequenceDiagram
  participant M as Scripted model
  participant R as REPL
  participant C as Chromium
  M->>R: step 1: new_tab(HN), wait_for_load, page_info
  R->>C: CDP navigate and wait
  C-->>R: loaded
  M->>R: step 2: rows = js(...)
  R->>C: Runtime.evaluate
  C-->>R: 5 titles
  M->>R: step 3: screenshot()
  R->>C: Page.captureScreenshot
  M->>R: step 4: finish_from_repl(json.dumps(rows))
  R-->>M: completed in 4 steps

How the loop ends

The loop can end four ways, and result.status tells you which:

  • completed: the model called finish or finish_from_repl.
  • max_steps: the request limit was hit. The final request is a delivery turn that offers only the finish tools, so the model can still hand back what it has.
  • timeout: past the time budget. From 90% of it, the model is told to deliver.
  • error: a provider failure. 1.0 returns this status instead of raising.

For long jobs, the REPL also has checkpoint(name, data, partial=True). It writes data to the workspace and becomes result.partial if the run dies. Part 11 uses it.

Try this

Write a scripted model that returns a cell with a deliberate typo, like pritn('hi'). Run it with max_steps=3 and read result.messages. You will see the exact traceback a real model would get, and you will see the forced delivery turn at the end.

Sources