What actually happens under the hood of an AI agent?
There are several frameworks available today that make building AI agents easier. However, before diving into frameworks, I wanted to understand the fundamental engineering concepts behind AI agents by building one myself.
In this tutorial, we will build a working AI agent from scratch using Python, a locally running LLM and Playwright.
We won't use LangChain, CrewAI or any other agent framework.
We will implement everything ourselves, understand why each component exists, and gradually connect them to build a functioning AI agent.
This is the first part of my Building in Public: AI Agent Harness series, where I will be learning and exploring AI agent engineering by building a real-world project.
What are we building?
By the end of this tutorial, our AI agent will be able to understand and execute the following natural language instruction:
Navigate to https://dev.to, scroll down twice by 600 pixels each time, and take a screenshot.
The interesting part is that we won't hardcode the sequence of browser actions into our final application.
Instead, we will provide the LLM with a set of tools and let it decide which tools to use, which arguments to provide and when to stop.
Technology stack
- Python — Our application and agent harness.
- Ollama — Running an LLM locally.
- Qwen 3.5 — Our local language model.
- Playwright — Interacting with the browser.
There are no paid LLM APIs involved.
Step 1: Setting up the project
Let's start by creating a project directory.
mkdir buildInPublicAIHarness cd buildInPublicAIHarness Create a Python virtual environment:
python3 -m venv .venv Activate it:
source .venv/bin/activate Install the required Python dependencies:
pip install ollama playwright Install the Chromium browser binaries for Playwright:
python -m playwright install chromium For this tutorial, I already have Ollama installed on my machine and am running Qwen 3.5 locally.
You can check which models are installed on your machine using:
ollama list I will be using qwen3.5:latest throughout this tutorial. If you are using a different model, make sure it supports tool calling.
Our final project structure will look like this:
buildInPublicAIHarness/ ├── .venv/ ├── main.py ├── llm.py ├── browser_tools.py └── tool_schemas.py We will create these files as we progress through the tutorial.
Step 2: Start with traditional browser automation
Before introducing an LLM, let's understand what we are trying to automate.
Create a file called main.py and add the following code:
from playwright.sync_api import sync_playwright with sync_playwright() as p: browser = p.chromium.launch( headless=False, slow_mo=1000 ) page = browser.new_page() page.goto("https://www.dev.to") page.screenshot(path="screenshot.png") browser.close() print("Screenshot saved to screenshot.png") Run the script:
python3 main.py You should see a Chromium browser open, navigate to dev.to and save a screenshot inside your project directory.
Understanding the Playwright code
The following line introduces an interesting Python concept:
with sync_playwright() as p: sync_playwright() creates a context manager for Playwright's synchronous API.
The with statement manages the lifecycle of Playwright and ensures that its resources are cleaned up when we leave the block.
The variable p represents the initialized Playwright instance.
We then launch Chromium and create a browser page.
browser = p.chromium.launch( headless=False, slow_mo=1000 ) page = browser.new_page() headless=False allows us to see the browser, while slow_mo=1000 slows down operations so that we can observe what is happening.
At this point, we have traditional browser automation, not an AI agent.
Every action and its execution order have been explicitly defined by us.
Let's change that.
Step 3: Connect Python to our local LLM
Create a new file called llm.py.
import ollama model = "qwen3.5:latest" messages = [ { "role": "user", "content": "Hello, how are you doing today?" } ] response: ollama.ChatResponse = ollama.chat( model, messages ) print(response.message.content) Run the file:
python3 llm.py If everything is configured correctly, you should receive a response from your locally running LLM.
Understanding messages
Notice that we are passing a list of messages to the LLM.
messages = [ { "role": "user", "content": "Hello, how are you doing today?" } ] There are four message roles that will be particularly important for our AI agent:
| Role | Responsibility |
|---|---|
system | Defines the behaviour and instructions of the agent |
user | Contains the user's objective |
assistant | Contains responses generated by the LLM |
tool | Contains the results of executed tools |
For now, we are only using the user role. We will introduce the other roles as we progress.
Also, instead of printing only response.message.content, try printing the entire response object.
You will notice that the response contains additional information, including token counts, execution duration, model information and potentially tool calls.
We will use some of this information later.
Step 4: Create tools for our AI agent
What exactly is a tool in the context of an AI agent?
A tool can simply be an ordinary Python function that performs a specific operation.
The LLM can request that function to be executed, but our Python application is responsible for actually executing it.
Let's create three tools:
- Navigate to a website.
- Scroll down a specified number of pixels.
- Take a screenshot.
Create a new file called browser_tools.py.
from playwright.sync_api import Page def navigate(page: Page, url: str) -> str: page.goto(url) return f"Successfully navigated to {url}" def scroll_down(page: Page, pixels: int) -> str: page.mouse.wheel(0, pixels) return f"Successfully scrolled down {pixels} pixels" def take_screenshot(page: Page, filename: str) -> str: page.screenshot(path=(filename + ".png")) return f"Successfully created the file {filename}.png" These are simple, independent Python functions.
Notice that each function accepts a page object.
This allows all three functions to operate on the same browser page instead of opening a new browser every time a tool is called.
Another important detail is that each function returns a descriptive string.
These strings will eventually be sent back to the LLM as feedback.
Testing our tools independently
Before introducing the LLM, let's make sure our tools work.
Update main.py:
from browser_tools import navigate, scroll_down, take_screenshot from playwright.sync_api import sync_playwright with sync_playwright() as p: browser = p.chromium.launch( headless=False, slow_mo=1000 ) page = browser.new_page() call_browser_navigate = navigate( page, "https://dev.to" ) print(call_browser_navigate) call_scroll_down = scroll_down(page, 600) print(call_scroll_down) call_take_screenshot = take_screenshot( page, "firstscreenshot" ) print(call_take_screenshot) Run main.py again.
You should see the browser navigate to dev.to, scroll down and create a file called firstscreenshot.png.
We now have reusable browser tools, but our LLM doesn't know anything about them yet.
Step 5: Introduce tool schemas
How does an LLM know which Python functions are available to it?
How does it know what those functions do and which arguments they accept?
This is where tool schemas come into play.
A tool schema is a structured description of a function that we provide to the LLM.
Create a file called tool_schemas.py.
Let's start by defining the schema for our navigation tool.
navigate_tool = { "type": "function", "function": { "name": "navigate", "description": "Navigate the browser to a given URL.", "parameters": { "type": "object", "properties": { "url": { "type": "string", "description": "The website URL to navigate to." } }, "required": ["url"] } } } Let's understand the different parts of this schema.
| Property | Purpose |
|---|---|
name | The name the LLM uses to request the function |
description | Helps the LLM decide when to use the function |
parameters | Describes the arguments accepted by the function |
properties | Defines individual arguments and their types |
required | Specifies which arguments are mandatory |
The schema follows the JSON Schema format for describing function parameters.
Why haven't we included the page parameter?
Our actual Python function accepts two parameters:
def navigate(page: Page, url: str) -> str: However, our tool schema only describes the url parameter.
This is intentional.
The LLM doesn't have access to our Playwright page object, and it doesn't need to know how Playwright is initialized.
Our Python application will provide the page object internally.
The LLM decides what to do, while our application handles how to do it.
Step 6: Let the LLM request a tool call
Now that we have a tool schema, let's provide it to our LLM.
Update llm.py:
import ollama from tool_schemas import navigate_tool model = "qwen3.5:latest" messages = [ { "role": "user", "content": "Navigate to https://dev.to" } ] response = ollama.chat( model, messages, tools=[navigate_tool] ) print(response.message.tool_calls) Run the file:
python3 llm.py Here is the actual response I received from my local model:
[ToolCall(function=Function(name='navigate', arguments={'url': 'https://dev.to'}))] This is where things start getting interesting.
Instead of simply generating a textual response, the LLM has returned a structured request to execute a function.
It has independently identified:
- The function name:
navigate - The required argument:
url - The argument value:
https://dev.to
However, no browser action has been performed yet.
The LLM has only expressed its intention to execute the function.
It is our responsibility to interpret this response and execute the requested action.
Understanding the tool call object
The tool_calls property contains a list because an LLM can request multiple tool calls in a single response.
We can iterate over it:
if response.message.tool_calls: for tool_call in response.message.tool_calls: print(tool_call.function.name) print(tool_call.function.arguments) Output:
navigate {'url': 'https://dev.to'} We now have the two pieces of information required to dynamically execute a Python function.
Step 7: Refactor our LLM communication
Currently, llm.py is a standalone script.
However, our main application needs to communicate with the LLM whenever required.
Let's wrap our existing logic inside a reusable function.
Replace the contents of llm.py with:
import ollama def call_llm( messages: list, tools: list ) -> ollama.ChatResponse: model = "qwen3.5:latest" return ollama.chat( model, messages, tools=tools ) Now, our llm.py has a single responsibility: communicating with the LLM and returning its response.
A Python mistake I encountered
While implementing this function, I initially wrote:
return ollama.chat(model, messages, tools) This resulted in the following error:
TypeError: Client.chat() takes from 1 to 3 positional arguments but 4 were given The reason is that Ollama's tools parameter is a keyword-only argument.
We must explicitly specify its name:
return ollama.chat(model, messages, tools=tools) Building this agent has also been a great opportunity to revisit fundamental Python concepts.
Step 8: Create a function registry
The LLM has provided us with a function name as a string:
function_name = "navigate" But how do we convert this string into an actual Python function?
In Python, functions are first-class objects. This means we can assign them to variables, pass them as arguments and store them inside dictionaries.
For example:
def greet(name): return f"Hello {name}" functions = { "greet": greet } selected_function = functions["greet"] print(selected_function("Developer")) Output:
Hello Developer This technique is called function dispatching.
Let's apply it to our agent.
Replace the contents of main.py with:
from browser_tools import navigate, scroll_down, take_screenshot from llm import call_llm from tool_schemas import navigate_tool messages = [ { "role": "user", "content": "Navigate to https://dev.to" } ] available_tools = { "navigate": navigate, "scroll_down": scroll_down, "take_screenshot": take_screenshot } llm_response = call_llm(messages, [navigate_tool]) if llm_response.message.tool_calls: for tool_call in llm_response.message.tool_calls: function_name = tool_call.function.name selected_function = available_tools[function_name] print(function_name) print(selected_function) Run the script.
You should receive something similar to:
navigate <function navigate at 0x104a8b310> The memory address will be different on your machine.
We have successfully converted a string generated by the LLM into a reference to an actual Python function.
Our available_tools dictionary acts as a function registry.
Step 9: Execute the requested function
We know which function the LLM wants to execute.
We also know which arguments it has generated.
The remaining challenge is passing those arguments dynamically.
Understanding dictionary unpacking
Consider the following Python function:
def introduce(name, age): print(f"My name is {name} and I am {age} years old.") Normally, we would call it like this:
introduce(name="Alex", age=25) However, Python also allows us to unpack a dictionary into keyword arguments using **.
arguments = { "name": "Alex", "age": 25 } introduce(**arguments) Both function calls produce the same result.
This is particularly useful for AI agents because different tools may accept different arguments.
In our case, the LLM returns:
arguments = { "url": "https://dev.to" } We can dynamically execute the selected function using:
selected_function(page, **arguments) Notice that we supply the page object ourselves, while the remaining arguments come from the LLM.
Connecting the LLM to Playwright
Update main.py:
from browser_tools import navigate, scroll_down, take_screenshot from playwright.sync_api import sync_playwright from llm import call_llm from tool_schemas import navigate_tool messages = [ { "role": "user", "content": "Navigate to https://dev.to" } ] available_tools = { "navigate": navigate, "scroll_down": scroll_down, "take_screenshot": take_screenshot } with sync_playwright() as p: browser = p.chromium.launch( headless=False, slow_mo=1000 ) page = browser.new_page() llm_response = call_llm(messages, [navigate_tool]) if llm_response.message.tool_calls: for tool_call in llm_response.message.tool_calls: function_name = tool_call.function.name arguments = tool_call.function.arguments selected_function = available_tools[function_name] returned_value = selected_function(page, **arguments) print(returned_value) Run the application.
For the first time, our LLM will be able to control an actual browser through our Python application.
We are no longer explicitly calling:
navigate(page, "https://dev.to") Instead, we are letting the LLM select the function and provide its arguments.
This is an important milestone, but there is still something missing.
Step 10: Return tool execution results to the LLM
Our Python application successfully navigated to the website and printed the result.
But the LLM has no idea whether the operation was successful.
It requested a tool call, but we haven't provided any feedback.
To solve this, we need to maintain a conversation history.
Immediately after calling the LLM, append its response to our messages list:
messages.append(llm_response.message) Then, after executing the requested function, create a tool message:
tool_message = { "role": "tool", "tool_name": function_name, "content": returned_value } messages.append(tool_message) Our conversation history now contains three messages:
User: Navigate to https://dev.to Assistant: Request navigate(url="https://dev.to") Tool: Successfully navigated to https://dev.to We can now send this updated conversation history back to the LLM.
Here is the updated Playwright block in main.py. Keep the imports, messages and function registry from the previous step.
with sync_playwright() as p: browser = p.chromium.launch( headless=False, slow_mo=1000 ) page = browser.new_page() llm_response = call_llm(messages, [navigate_tool]) messages.append(llm_response.message) if llm_response.message.tool_calls: for tool_call in llm_response.message.tool_calls: function_name = tool_call.function.name arguments = tool_call.function.arguments selected_function = available_tools[function_name] returned_value = selected_function(page, **arguments) print(returned_value) tool_message = { "role": "tool", "tool_name": function_name, "content": returned_value } messages.append(tool_message) after_tool_call_llm_call = call_llm( messages, [navigate_tool] ) print(after_tool_call_llm_call.message.content) Here is the output I received:
Successfully navigated to https://dev.to I've successfully navigated to https://dev.to. The site is now loaded and ready for you to browse. Dev.to is a community platform for software developers where they can share articles, learn new skills, and connect with other developers. We have successfully completed the entire tool-calling lifecycle.
The LLM requested an action, our application executed it, and the result was returned to the LLM.
This feedback mechanism is fundamental to how AI agents work.
Step 11: Build the agent loop
Currently, we are explicitly calling the LLM twice.
The first call requests an action, and the second call processes its result.
But what happens if the user requests multiple actions?
The LLM might need three, five or even ten calls to complete the task. We cannot predict this beforehand.
This is where we introduce the agent loop.
An agent loop repeatedly performs the following operations:
- Send the conversation history to the LLM.
- Receive the LLM's response.
- Check whether it contains any tool calls.
- Execute the requested tools.
- Append their results to the conversation history.
- Repeat until the LLM stops requesting tools.
Conceptually, it looks like this:
User instruction | v Call the LLM <----------------+ | | v | Are there tool calls? | / \ | No Yes | | | | v v | Final response Execute tools | | | | v v | Finish Append tool results --+ We can implement this using a simple while True loop.
Replace the Playwright block in main.py with the following:
with sync_playwright() as p: browser = p.chromium.launch( headless=False, slow_mo=1000 ) page = browser.new_page() while True: print("Calling LLM...") llm_response = call_llm(messages, [navigate_tool])Source:https://dev.to/adityaaamalik/building-an-ai-agent-from-scratch-with-python-ollama-and-playwright-part-1-2oggRelated posts
