techlifeadventuresVol. 03 · Nov 2026
Build Your First AI Agent in Python: A Beginner Guide
·12 min read·Development

Build Your First AI Agent in Python: A Beginner Guide

Build a research agent in about 180 lines of Python on the Claude API: web search, saved notes, memory, and the tool-use loop, explained step by step.

Updated November 2026. The first version of this tutorial used LangChain's AgentExecutor, which LangChain has since moved out of its main package, and it described free API tiers that do not exist. I rewrote it on the plain Anthropic Python SDK so there is less to go out of date. Code written against anthropic 2.6.0.

An AI agent is a program that lets a language model decide which tools to call, runs those tools, feeds the results back, and repeats until the job is done. That loop is the whole idea. Frameworks wrap it, but you learn more by writing it once yourself.

In this tutorial you will build a small research assistant that can:

  1. search the web for current information,
  2. save findings to a notes file and read them back,
  3. remember the conversation within a session,
  4. stop itself if it gets stuck.

It is about 180 lines of Python with two dependencies. You need basic Python (functions, dictionaries, loops), Python 3.10 or later, and an Anthropic API key.

How an agent works

Every agent, from this one to a coding agent like Claude Code, runs the same loop:

text
send the conversation + tool list to the model
  -> model replies with text, or asks to call a tool
  -> if it asked for a tool: run it, append the result, go round again
  -> if it replied with text: done

The model never runs anything itself. It returns a structured request ("call save_note with these arguments"), and your code decides whether to run it. That split matters later when we talk about safety.

There are two kinds of tools in this tutorial:

  • Server tools run on Anthropic's side. You declare them and Claude uses them inside a single API call. We use the built-in web search tool, so there is no search API key to manage.
  • Client tools are functions you write. Claude asks for them by name, your loop runs them, and you send the result back.

Step 1: Set up the project

bash
mkdir research-agent
cd research-agent
python -m venv venv

# Windows
venv\Scripts\activate
# macOS / Linux
source venv/bin/activate

pip install anthropic python-dotenv

Get an API key from the Claude Console. The API is pay-as-you-go, so you will need to add credit before your first call. Put the key in a .env file:

text
ANTHROPIC_API_KEY=your-key-here

And keep it out of git with a .gitignore:

text
.env
venv/
__pycache__/
research_notes.json

That .gitignore is not a formality. When I audited this site I found an API key that had shipped to every visitor's browser because it sat in the wrong file. Secrets leak through boring mistakes.

Step 2: Model, prompt and tools

Create research_agent.py and start with the setup:

python
#a5d6ff">"""A small research assistant built directly on the Claude API."""

import json
from datetime import datetime
from pathlib import Path

import anthropic
from dotenv import load_dotenv

load_dotenv() # reads ANTHROPIC_API_KEY from .env
client = anthropic.Anthropic()

MODEL = #a5d6ff">"claude-opus-5-5" # swap for "claude-haiku-5-5" to spend less while learning
MAX_STEPS = 10 # hard stop so a confused agent cannot loop forever
NOTES_FILE = Path(#a5d6ff">"research_notes.json")

SYSTEM_PROMPT = #a5d6ff">"""You are a research assistant. Help the user research a topic
and keep useful notes.

  • Use web_search for anything recent or anything you are not sure about.
  • Only state facts that come from your search results, and cite the source URL.
  • If you could not find something, say so. Do not guess.
  • When you find something worth keeping, save it with save_note.
  • Keep answers short and organised under headings."#a5d6ff">""

On model choice: as of November 2026 the Claude lineup is Fable 5.1 (most capable), Opus 5.5, Sonnet 5.5 and Haiku 5.5. Opus 5.5 is a good default for agent work. Haiku 5.5 is far cheaper and fine for experimenting with the loop. Check the models page for current IDs and prices before you pick.

The "do not guess" line in the prompt is there for a reason. Models fill gaps confidently. In my own work, an agent with no real ticket to cite made one up, and the fake ID ended up in published release notes. A prompt instruction will not prevent that on its own, but it helps, and it is free.

Now the tool definitions. Each client tool has a name, a description, and a JSON Schema for its inputs:

python
TOOLS = [
    # A server tool: Anthropic runs the search. We never see a tool_use for it.
    {#a5d6ff">"type": "web_search_20260209", "name": "web_search", "max_uses": 5},
    # Client tools: Claude asks, our code runs them.
    {
        #a5d6ff">"name": "save_note",
        #a5d6ff">"description": (
            #a5d6ff">"Save a research finding to the user's notes file. Use this when the "
            "user asks you to save something, or when you find a fact worth keeping. #a5d6ff">"
            "Include the source URL in the content.#a5d6ff">"
        ),
        "input_schema#a5d6ff">": {
            "type#a5d6ff">": "object",
            "properties#a5d6ff">": {
                "title#a5d6ff">": {"type": "string", "description": "Short title, under 10 words"},
                "content#a5d6ff">": {"type": "string", "description": "The finding, with its source URL"},
                "tags#a5d6ff">": {
                    "type#a5d6ff">": "array",
                    "items#a5d6ff">": {"type": "string"},
                    "description#a5d6ff">": "Optional lowercase tags, e.g. ['solar', 'perovskite']",
                },
            },
            "required#a5d6ff">": ["title", "content"],
        },
    },
    {
        "name#a5d6ff">": "list_notes",
        "description#a5d6ff">": (
            "List notes the user has already saved. Use this before searching when the #a5d6ff">"
            "user asks what they have already researched.#a5d6ff">"
        ),
        "input_schema#a5d6ff">": {
            "type#a5d6ff">": "object",
            "properties#a5d6ff">": {
                "tag#a5d6ff">": {"type": "string", "description": "Optional tag to filter by"},
            },
        },
    },
]

The descriptions are the most important text in the file. Claude reads them to decide when to call each tool. "Save a note" is vague; "use this when the user asks you to save something, or when you find a fact worth keeping" tells the model when. If your agent picks the wrong tool, fix the description before you touch anything else.

max_uses: 5 caps how many searches Claude can run per request. Web search is billed at $10 per 1,000 searches on top of tokens, per Anthropic's pricing page, so a cap is worth having. If your organisation has web search turned off in Console settings, you will need to enable it.

Step 3: Write the client tools

These are ordinary Python functions. Notes go into a JSON file so they survive restarts:

python
def load_notes() -> list[dict]:
    if NOTES_FILE.exists():
        return json.loads(NOTES_FILE.read_text(encoding=#a5d6ff">"utf-8"))
    return []

def save_note(title: str, content: str, tags: list[str] | None = None) -> str:
notes = load_notes()
note = {
#a5d6ff">"id": len(notes) + 1,
#a5d6ff">"title": title,
#a5d6ff">"content": content,
#a5d6ff">"tags": [t.lower() for t in (tags or [])],
#a5d6ff">"saved_at": datetime.now().isoformat(timespec="seconds"),
}
notes.append(note)
NOTES_FILE.write_text(json.dumps(notes, indent=2), encoding=#a5d6ff">"utf-8")
return f#a5d6ff">"Saved note #{note['id']}: {title}"

def list_notes(tag: str | None = None) -> str:
notes = load_notes()
if tag:
notes = [n for n in notes if tag.lower() in n[#a5d6ff">"tags"]]
if not notes:
return #a5d6ff">"No notes found."
return #a5d6ff">"\n\n".join(f"#{n['id']} {n['title']}\n{n['content']}" for n in notes)

def run_tool(name: str, tool_input: dict) -> tuple[str, bool]:
#a5d6ff">"""Run one client tool. Returns (output, is_error)."""
try:
if name == #a5d6ff">"save_note":
return save_note(tool_input), False
if name == #a5d6ff">"list_notes":
return list_notes(tool_input), False
return f#a5d6ff">"Unknown tool: {name}", True
except Exception as exc: # tell Claude what went wrong instead of crashing
return f#a5d6ff">"Tool failed: {exc}", True

Two habits worth copying from run_tool:

  • Return errors to the model instead of crashing. A tool result marked is_error lets Claude retry with different arguments or tell the user what failed.
  • Make empty results say so. "No notes found." is unambiguous. An empty string is not, and a model will happily treat silence as success.

Step 4: The agent loop

This is the part every framework hides. Here it is in full:

python
def run_agent(messages: list) -> anthropic.types.Message:
    #a5d6ff">"""The agent loop: call Claude, run any tools it asks for, repeat."""
    for _ in range(MAX_STEPS):
        response = client.messages.create(
            model=MODEL,
            max_tokens=16000,
            system=SYSTEM_PROMPT,
            tools=TOOLS,
            messages=messages,
        )
        # Always keep Claude's full reply in the history, not just the text.
        messages.append({"role#a5d6ff">": "assistant", "content": response.content})

for block in response.content:
if block.type == "server_tool_use#a5d6ff">":
print(f" [searching] {block.input.get(#a5d6ff">'query', '')}")

if response.stop_reason == "pause_turn#a5d6ff">":
continue # a long server-side search paused; sending it back resumes it
if response.stop_reason != "tool_use#a5d6ff">":
return response # end_turn, max_tokens or refusal: we are done

tool_results = []
for block in response.content:
if block.type == "tool_use#a5d6ff">":
print(f" [tool] {block.name} {json.dumps(block.input)}#a5d6ff">")
output, is_error = run_tool(block.name, block.input)
tool_results.append({
"type#a5d6ff">": "tool_result",
"tool_use_id#a5d6ff">": block.id,
"content#a5d6ff">": output,
"is_error#a5d6ff">": is_error,
})
# All results for one turn go back together, in a single user message.
messages.append({"role#a5d6ff">": "user", "content": tool_results})

raise RuntimeError(f"Agent did not finish within {MAX_STEPS} steps")

What each piece does:

  • stop_reason tells you why Claude stopped. tool_use means "run these tools and come back". end_turn means it has answered. pause_turn means a server-side tool (our web search) hit its internal step limit mid-turn; you send the reply back unchanged and the server carries on. max_tokens and refusal are also possible, and the next function handles them.
  • Append response.content, not just the text. The reply contains tool requests, search results and other blocks the next call needs. Keeping only the text breaks the conversation.
  • tool_use_id links each result to the request that asked for it.
  • One user message for all results. If Claude asks for two tools at once, both results go back together.
  • MAX_STEPS is your circuit breaker. Without it, a model that keeps calling the same tool will keep spending your money.

Step 5: Memory and the chat loop

The agent's short-term memory is just the messages list. Each new question is appended to it, so Claude sees the whole session.

python
def reply_text(response: anthropic.types.Message) -> str:
    if response.stop_reason == #a5d6ff">"refusal":
        return #a5d6ff">"(Claude declined this request.)"
    text = #a5d6ff">"".join(b.text for b in response.content if b.type == "text")
    if response.stop_reason == #a5d6ff">"max_tokens":
        text += #a5d6ff">"\n(Reply was cut off at max_tokens.)"
    return text

def main() -> None:
print(#a5d6ff">"Research assistant. Type 'notes' to see saved notes, 'quit' to exit.")
messages: list = [] # the conversation is the agent's short-term memory
while True:
user_input = input("
\nYou: #a5d6ff">").strip()
if user_input.lower() in {"quit#a5d6ff">", "exit"}:
break
if user_input.lower() == "notes#a5d6ff">":
print(list_notes())
continue
if not user_input:
continue
start = len(messages)
messages.append({"role#a5d6ff">": "user", "content": user_input})
try:
response = run_agent(messages)
print(f"\nAssistant: {reply_text(response)}#a5d6ff">")
except (anthropic.APIError, RuntimeError) as exc:
print(f"\nError: {exc}#a5d6ff">")
del messages[start:] # drop the unfinished turn so the history stays valid

if __name__ == "__main__":
main()

The notes file is the long-term memory: it outlives the session, and list_notes lets Claude read it back.

Step 6: Run it

bash
python research_agent.py

Try a sequence like this:

text
You: What has happened with perovskite solar cell efficiency records this year?
You: Save the two most important findings, tagged solar.
You: What did I save about solar?
You: Tell me more about the second one.

The first prompt should trigger a few [searching] lines. The second should call save_note twice. The third should call list_notes. The fourth tests memory: "the second one" only makes sense if the conversation history is intact.

Common problems:

  • Authentication error: the .env file is not in the folder you ran the script from, or the key is wrong.
  • Rate limit (429): you are sending requests faster than your account tier allows. The SDK already retries a few times; wait and try again.
  • Claude never calls your tool: rewrite the tool description to say plainly when to use it.
  • Answers with no sources: tighten the system prompt, and check the search actually ran (look for [searching] lines).

The shortcut: the SDK's tool runner

Once you understand the loop, you do not have to write it every time. The Python SDK includes a tool runner (in beta) that runs the same loop for you and builds tool schemas from type hints and docstrings:

python
from anthropic import beta_tool

@beta_tool
def save_note(title: str, content: str) -> str:
#a5d6ff">"""Save a research finding to the user's notes file.

Args:
title: Short title, under 10 words.
content: The finding, with its source URL.
#a5d6ff">"""
... # same body as before

runner = client.beta.messages.tool_runner(
model="claude-opus-5-5#a5d6ff">",
max_tokens=16000,
system=SYSTEM_PROMPT,
tools=[{"type#a5d6ff">": "web_search_20260209", "name": "web_search", "max_uses": 5}, save_note],
messages=[{"role#a5d6ff">": "user", "content": "Find and save one recent perovskite record."}],
)
final_message = runner.until_done()

I would still write the manual version first. When something goes wrong in a framework, you need to know what the loop underneath was doing.

Before you give an agent real power

This agent can only search and write to one local file, so the stakes are low. The moment a tool can send email, change a database or spend money, the rules change:

  • Gate anything irreversible. Your loop decides whether to run each tool. Ask a human before sending, deleting or paying.
  • Treat fetched text as data, not instructions. A web page can contain text written to manipulate the model. I cover this in AI coding agent security.
  • Check facts before they leave your system. If the agent cites an ID, a number or a URL, verify it against the source.
  • Log every tool call. When an agent does something strange, the log is how you find out why.

For long sessions, avoid editing or trimming earlier turns to save tokens. Recent Claude models can reject a history that was changed after the fact. Start a new session with a short summary instead, or look at the API's compaction feature.

Where to go next


Related Reading:

Enjoying this article?

Get posts like this in your inbox. No spam, unsubscribe anytime.

Share this article
Vinod Kurien Alex

Vinod Kurien Alex

Engineering Manager with 20+ years in software. Writing about AI, careers, and the Indian tech industry.

Related Articles

© 2026 TechLife AdventuresBuilt with care · v3.2.1