← govind p lal
AI and ML Bootcamp · Lecture 9 · lecture notes

From APIs to Agents

In short — How do tools like Claude Code and Codex actually work? An agent is an LLM, some tools and a loop. This lecture builds one from first principles: calling an LLM API through OpenRouter, passing history for memory, defining tools, running a ReAct loop, and extending it to a small coding agent.

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.

needs inforun functionenough infoobservationUser queryLLMreasoning engineTool callTool outputFinal answer
The agent loop: call a tool until the LLM has enough information.

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.

System prompt - text injected before every conversation, written by the builder (Anthropic, OpenAI, or you).

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

Sandbox - an isolated environment carved out of a bigger server. It cannot reach the rest of the machine or other users' sandboxes.

Cron jobs and OpenClaw-style agents

Cron job - a scheduled task. When the schedule or trigger is met, the function runs on its own.

Memory systems and context limits

Advertised context can be 1 million tokens, but the effective window is about 300K. After that the model forgets.

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.

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

Hallucination in agents

Hallucination - generating plausible but incorrect or fabricated information. It follows from LLMs being next-token predictors.

!

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)

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

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.

resultUser questionModel + toolsTool call requestOur code runs toolFinal answer
Function-calling round trip.

Building a ReAct agent

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.

A simple coding agent

ToolParametersHow it works
read_filepathopen and read, return JSON content
write_filepath, contentcreate dirs, write, return success and bytes
run_pythoncodesubprocess: python3 -c code
list_filespathos.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

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.