From APIs to Agents
What an agent is
Coding agents (Claude Code, Codex) look complex but the core is simple. Industry advice: keep the agent/orchestration simple. Simple scales better.
- LLM - the reasoning engine
- Tools - external functions the LLM can call (read file, write file, list directory, run Python, search)
- Loop - feed tool output back to the LLM until it decides it is done
Libraries (LangChain, LangGraph, CrewAI) only abstract this. They give ready-made tools and ways to connect agents. Learn one, but it is better to build your own orchestrator than to depend on them too much. Frameworks all do the same thing.
Tool calls and the system prompt
Tool call - a normal function (e.g. read_file) that the backend runs when the LLM writes its name.
- LLM is autoregressive, so it writes the tool name token by token
- The name must match exactly.
read_directoryinstead of the defined name -> function does not run - Parameters must be right too (a search tool needs a query)
System prompt - text injected before every conversation, written by the builder (Anthropic, OpenAI, or you).
- Says who the agent is (a coding agent)
- Lists available tools and how to invoke them
- Gives rules, restrictions, examples
Example
Task: write a Python file that sums two numbers. Agent calls list directory -> sees src folder and package file -> no add.py, so calls write_file(add.py) -> 'file created successfully' -> optionally verifies by listing again -> writes the code -> final reply: run it with python add.py.
Each turn the whole previous context goes back into the context window. That is how agents do not forget, and why context limits get hit.
Cloud vs local agents and sandboxes
- Local: tools run in your terminal, e.g. pwd shows your machine's directory
- Cloud: provider clones your repo into a temporary directory and runs tools there
Sandbox - an isolated environment carved out of a bigger server. It cannot reach the rest of the machine or other users' sandboxes.
- Spins up when the session starts, repo is cloned in
- Dies when the session or request ends, nothing is retained
- Resource-limited: e.g. 1 GB slice of a 128 GB server
- Even if compromised, attacker sees only that one repo
Cron jobs and OpenClaw-style agents
Cron job - a scheduled task. When the schedule or trigger is met, the function runs on its own.
- Example: a good-morning message sent when the agent detects you are about to wake up
- Apps already use this: reminder notifications at the time you usually order
- The key addition that made OpenClaw-style agents popular, along with memory/context optimisations
- Codex and Claude Code now have a loop feature that schedules a recurring task
Memory systems and context limits
Advertised context can be 1 million tokens, but the effective window is about 300K. After that the model forgets.
- Store conversations, tool calls and results (maybe as a graph)
- Retrieve only what is relevant to the current query
- Compress with a small LLM to use as few tokens as possible
- Practical trick: summarise after N steps and dump old context to a file the agent can read if needed
Why loops beat one-shot, and why tools
ReAct - Reason + Act (not front-end React). Reason: think. Act: run a tool. Observe: read the result. Repeat until done.
Example
What is 123 x 123? Think: it is a multiplication -> pick calculate tool -> pass two numbers and the operator -> tool returns 15129 -> LLM answers.
- Why loop beats one-shot: the model can fetch current data instead of relying on old training data
- Why tools for maths: an LLM is a non-deterministic next-token predictor and may hallucinate; a calculator is right 100% of the time
- The LLM leaves the loop when it has enough information; it answers directly if no tool fits
Other points: a plain API call is single-turn. Agents with several independent sub-agents (security, code writing, code review) report to a main agent. Thinking models use many more tokens, so they cost more.
Web search and robots.txt
- Early search tools used the Wikipedia API
- Exa - search built for LLM agents. Returns links, the LLM picks one, the page HTML goes back to the LLM
- robots.txt - plain text file in a site's root that guides crawlers on which pages they can or cannot access. Some sites (x.com) block agents
Hallucination in agents
Hallucination - generating plausible but incorrect or fabricated information. It follows from LLMs being next-token predictors.
- Misinterpreting or inventing a tool name
- Missing context leading to wrong information
- Never exiting the ReAct loop (just one kind)
- Example: a model used for a legal case invented hearings, dates and judges that did not exist
Guardrails: if a tool fails, the agent should admit it cannot answer instead of making up a reply. Also block dangerous commands like rm -rf and ask permission before pushing to GitHub.
Calling an LLM API via OpenRouter
OpenRouter - one API key for many hosted models, including free ones. Same interface as OpenAI, only the base URL differs. Setup: create account -> create API key -> save it in Colab Secrets as OPENROUTER_API_KEY -> enable notebook access.
from openai import OpenAI
from google.colab import userdata
client = OpenAI(base_url="https://openrouter.ai/api/v1",
api_key=userdata.get("OPENROUTER_API_KEY"))
r = client.chat.completions.create(
model="openrouter/free",
messages=[{"role":"user","content":"Capital of India in one word"}],
temperature=0, max_tokens=50)
print(r.choices[0].message.content)- Response also reports input and output token counts and the model used
- Temperature 0: almost the same answer each run. Temperature 2: each answer very different
- Some free models give empty content or ignore temperature
Memory in multi-turn chat
Each API call is independent. Memory = pass the previous question and answer along with the next question.
Example
Turn 1: 'What is a derivative?' -> answer. Turn 2 sends turn 1 plus 'Give an example with x squared'. The model knows it should use derivatives. Asked alone, it would not know.
Input tokens grow every turn because history is included. The model is not re-asked old questions; it just sees them as context.
Function calling with JSON tool definitions
- Define each tool: type=function, name (get_weather), description (so the LLM knows what it does), parameters (city)
- Pass
tools=[...]along with messages - The model replies with a tool call (function name + arguments), it does not run anything
- Our code runs the function, appends the result, calls the model again
Example
'Weather in Tokyo?' -> model asks for get_weather(city=Tokyo) -> our fake function returns 22°C, partly cloudy -> model replies with those values. In real use the function calls a weather API.
Building a ReAct agent
- System prompt: you are a helpful assistant, here are the tools, always start with a thought, use one action at a time, give a final answer in a set format
- Messages start with system prompt, then user query
- Loop up to 10 iterations: call LLM -> parse action -> run tool -> append observation -> repeat; stop on final answer
- Only the client.chat.completions.create call and prompt structure need remembering; printing code is cosmetic
Example
123 x 123: iteration 1 failed with a format issue (model invented an undefined function). Iteration 2: thought 'straightforward multiplication', action calculate, observation 15129. Iteration 3: final answer.
- Wikipedia tool failed in the demo, so the agent admitted it could not answer instead of guessing (guardrail behaviour)
- Multi-hop question (who was born first, Shakespeare or Leonardo) needs several tool calls
A simple coding agent
| Tool | Parameters | How it works |
|---|---|---|
| read_file | path | open and read, return JSON content |
| write_file | path, content | create dirs, write, return success and bytes |
| run_python | code | subprocess: python3 -c code |
| list_files | path | os.listdir, return JSON |
Same recipe as before: system prompt with tool descriptions, ReAct format and rules, then the user query. Demos: write is_prime to prime.py with a test script, then create employee.csv with 10 rows and analyse it. Weak free models sometimes fail; a stronger model succeeded.
Ways to improve the agent
- Context management - the agent resends everything each iteration, so summarise after N steps
- Planning - write a plan (markdown checklist) first and tick items off
- Multi-agent - plain Python functions, e.g. a researcher (search tool) and a coder (file tools)
- Add web browsing and guardrails
- Recent idea (recursive language models): set up a code environment at the start and run needed tools together instead of one call per step
Glossary
- Agent
- An LLM that calls tools in a loop until it has a final answer.
- Tool call
- A function the LLM requests by exact name and arguments; the backend runs it.
- System prompt
- Pre-written instructions injected before the user's prompt describing the agent, tools and rules.
- ReAct
- Reason, Act, Observe loop from a 2022 paper.
- Cron job
- A scheduled task that runs automatically.
- Sandbox
- Isolated temporary environment inside a bigger server.
- OpenRouter
- Service giving one OpenAI-compatible API for many models.
- robots.txt
- File telling crawlers which pages they may access.
- Hallucination
- Plausible but fabricated model output.
- Guardrails
- Rules limiting what an agent may do or say, e.g. admit tool failure.