
This course includes our updated coding exercises so you can practice your skills as you learn.
See a demo
Welcome to Claude API in Python: Build AI Agents and RAG Apps. This is a 2026 hands-on developer path.
Start here in Introduction: create an Anthropic API key, set up Python, and make your first Messages API call. Then continue through Claude API Overview, AI Application Architecture (including a from-scratch RAG pipeline and lab), Tool Calling with Claude, and Memory. The Memory section includes persistent per-user memory, expiry and filtering, and a local read-only MCP server, with hands-on labs on these three lectures: “Memory that survives restart, and stays per user,” “Expiring, deleting, and filtering memory,” and “A local read-only MCP server.”
If you already know LLMs and prompting, treat the last section, AI Foundations, as an optional refresher. You can start coding in the next setup lecture, Create Your Anthropic API Key.
A one-page course map is attached to this lecture. If I sound fast, use the player's playback speed. Turn on captions — captions are available in English (with auto-generated Korean). Post questions in Q&A. Never paste a real API key into a notebook, a question, or a file you might upload. Usage is billed.
Create an Anthropic API key in the Claude Console and store it only as the ANTHROPIC_API_KEY environment variable. This is the first setup step on the 2026 Messages API path. Never paste a real key into a notebook, lecture file, or Q&A. API usage is billed.
Set up a clean Python environment for the rest of the course in about four minutes: Python, a virtual environment, the Anthropic SDK, and your API key loaded safely, without the key ever appearing in your code.
You'll learn:
- Check your Python version: the Anthropic Python SDK needs Python 3.10 or later.
- Create and activate a virtual environment: python3 -m venv .venv, then source .venv/bin/activate (macOS/Linux) or .venv\Scripts\activate (Windows).
- Install the pinned SDK so your output matches the course: pip install anthropic==2.12.0 python-dotenv.
- Keep your key out of your code: the SDK reads ANTHROPIC_API_KEY from the environment. Put it in a .env file (loaded with python-dotenv, and listed in .gitignore) or export it in your shell.
- Verify everything with check_env.py, which confirms the key is set without ever printing it, then make a first call with first_call.py.
- If a key ever leaks (a commit, a screenshot, a screen recording), delete it in the Claude Console and create a new one.
Resources:
- 11_python_env_setup.zip: check_env.py, first_call.py (add --fake to run offline, no key needed), fake_claude.py, .env.example (placeholder only), .gitignore, requirements.txt, offline tests, and the coding exercise starter.
- Python_Env_Setup_Cheat_Sheet.pdf: every command, the .env and Python snippets, the key rules, and a 3-question self-check.
Versions checked 22 Nov 2026 (anthropic 2.12.0, python-dotenv 1.2.4, claude-haiku-5-5). Never paste a real key into code, notebooks, screenshots or chat.
Next: Coding Exercise "A Key Checker That Can't Leak Your Key" (8 tests, runs in the browser).
Every feature in this course, from RAG to agents, is built on one call: the Messages API. In this lecture you make that call, read the reply properly, and work out exactly what it cost.
You'll learn:
- The three required parts of a request: model, max_tokens (a ceiling on output tokens) and messages.
- How to read a reply safely: join the text blocks instead of reading content[0], because Claude 5.x models think adaptively and a reply can start with a thinking block.
- What stop_reason tells you: end_turn means finished, max_tokens means the reply was cut off.
- What a token is, and how to count tokens before you send with client.messages.count_tokens (free to call).
- How pricing works: output tokens cost 5x input tokens on every current Claude model (Haiku 5.5: $0.10 in / $0.50 out per million tokens), and thinking tokens are billed as output.
- How to write a cheap, reliable classifier: a small max_tokens, thinking turned off, and a fallback label.
Resources:
- 08_first_messages_call.zip: hello_messages.py, tokens_demo.py, classify_demo.py, an offline fake client (--fake, no API key needed), tests, and the coding exercise.
- First_Messages_Cheat_Sheet.pdf: the call, the response fields, the price table, and a 3-question self-check.
Prices are a snapshot from 22 Nov 2026. Check the Anthropic pricing page before relying on them. Set ANTHROPIC_API_KEY in your shell; never put a key in your code.
Next: Coding Exercise "Read a Reply and Price It" (8 tests, runs in the browser).
Make your first Claude call production-ready with three small upgrades: stream the reply with messages.stream so users see words right away, handle API errors so you retry only what's retryable (429 and 5xx/529, never 400/401/404), and log tokens, cost, latency and request IDs for every call. You'll run stream_demo.py, errors_demo.py and call_logger.py against claude-haiku-5-5, and see simulated 429 and 529 responses with --fake. Download the example code and the cheat sheet in Resources, then write your own retry policy and cost meter in the practice lab.
Join a private Facebook group called ChatGPT and Gen I for content for enrolled students to connect with instructors and classmates, ask questions, and discuss gen AI topics.
What can the Claude API actually do, and when should you use each part of it? This lecture walks through the main capabilities and tells you what each one is for, when to pick it, and where we use it later in the course:
- Text in, text out: summarize, extract, classify, write and answer, with a 1M-token context window
- Vision and PDFs: send images and PDFs directly, with no OCR step
- Tool use: client tools that your code runs, and server tools such as web search that run on Anthropic's side
- Structured outputs: replies that match your JSON schema
- Streaming: the same price with a better user experience
- Thinking and effort: low, medium, high, xhigh or max. Thinking tokens are billed as output.
- Cost: output costs 5x input (Haiku 5.5 is $0.10 in and $0.50 out per million tokens), so output-heavy jobs such as role play and long writing are where the bill is
- Cutting cost: prompt caching, and the Message Batches API at 50% off, with most batches finishing within an hour
- Citations: answers that cite exact passages, which matters for RAG
Resources:
- API_Capabilities_Cheat_Sheet.pdf: one-page capability map, the cost rule and a 3-question quiz
- 10_api_capabilities_examples.zip: cost_shapes.py works out the cost of input-heavy and output-heavy jobs, the Batch discount, and the same job on each model. It needs no API key. Run it with: python cost_shapes.py. The zip also has offline tests (pytest -q).
Prices are a dated snapshot of the Claude pricing page (22 Nov 2026): platform.claude.com/docs/en/about-claude/pricing
Move from a single Messages API call to a small application pattern: send a prompt, read the response, and think about how this call sits inside a larger app. This lecture is part of the 2026 Messages API path in Claude API Overview.
Choose the right model for latency among haiku, sonnet, and opus. Consider baseline latency and time to first token as key metrics, and use streaming to improve perceived speed.
Your app works on your laptop. Then real traffic arrives and requests start coming back with a 429. This lecture shows you the limits that apply to your account, which one your traffic hits first, and how to handle each kind of 429 correctly.
You'll learn:
Spend limits vs rate limits: a monthly spend cap per usage tier (Start $500, Build $1,000, Scale $200,000, Custom by arrangement; new organizations may start on an Evaluation tier), and per-minute rate limits for each model.
The three per-minute limits: requests (RPM), input tokens (ITPM) and output tokens (OTPM). Haiku 5.5 on the Start tier: 4,000 RPM, 2,000,000 ITPM, 400,000 OTPM. The token bucket refills continuously, so a short burst can still return a 429.
Which limit binds first: with 3,000-token prompts, input tokens per minute caps you at 666 requests/min on Start. Cache reads don't count toward ITPM, so an 80% cache hit rate takes the same traffic to 1,000 requests/min (now limited by OTPM).
The three kinds of 429, all rate_limit_error: a rate limit (honour the retry-after header), a ramp limit (ramp_limit_exceeded: grow traffic gradually), and the monthly spend cap (enforced_spend_limit_reached, no retry-after: never retry it; raise your limit or move up a tier).
Exponential backoff for retryable 429s, and why you never retry a spend cap.
Resources:
09_rate_limits.zip: throughput.py (which limit binds, per tier, with --cache-hit), headers_demo.py (read your live anthropic-ratelimit-* headers; --fake for offline), backoff_demo.py (simulated rate-limit / ramp / spend-cap 429s), tests, and the exercise starter.
Rate_Limits_Cheat_Sheet.pdf: the tier table, reading headers, the three 429s, and a 3-question self-check.
Set ANTHROPIC_API_KEY in your shell, and never put a key in your code. Limits and prices are from Anthropic's docs as of 22 Nov 2026; your organization's real numbers are on the Console's Rate limits page and in the response headers.
Next: Coding Exercise "Plan for Your Rate Limits" (8 tests, runs in the browser). You'll write binding_limit, kind_of_429 and wait_seconds.
Navigate the retrieval augmented generation architecture for AI applications. See how a datastore feeds embeddings into a vector database for fast semantic retrieval and LLM-driven responses.
A from-scratch walkthrough of the first half of a retrieval-augmented generation (RAG) pipeline: what RAG is, how the system fits together, loading a lease document into a notebook, splitting it into chunks, and embedding those chunks so they can be stored and searched. No LangChain or LlamaIndex: every step is plain Python.
Note: the notebook on screen was adapted from an earlier guide, so you may spot an old openai install line and an "OPENAI API KEY" heading. Use the updated Claude-only code pack attached to this lecture (claude_rag_pipeline_claude_sdk.zip) instead. It reads your key from the ANTHROPIC_API_KEY environment variable and runs offline tests without one.
Insert the embeddings into a local LanceDB table, then retrieve the top-k chunks for a question with semantic search. We ask "What is the issue date of the lease?" and then change the question to see how the retrieved passages change. Reranking comes in the next lecture.
Build a prompt that includes the retrieved context, call Claude with the Messages API, and ask for an answer with a citation. Then experiment with chunk size, top-k and the base prompt, and learn why you shouldn't change the embedding model (and re-index) more often than you need to. The Claude-only code pack is attached to Part 1.
"Agent" is the most overused word in AI. This lecture gives you a precise definition, shows the exact loop behind every agent in this course, and explains when you should build a plain workflow instead.
You'll learn:
- Workflow vs agent, using Anthropic's definitions from "Building effective agents": in a workflow, your code decides the steps; in an agent, Claude decides which tool to call, in what order, and when it's done.
- Why most production systems are workflows (predictable, cheaper, easier to test), and when to reach for an agent: when you can't write the steps down ahead of time.
- The agent loop: one model, tools, and a loop keyed on stop_reason. On tool_use, run every tool call, send all the results back in one turn, and go again. On end_turn, you have the answer.
- Why you must cap the loop yourself: the API won't stop a runaway loop. At the cap, return an honest partial answer.
- Where memory and RAG fit: they add context and tools, not extra models.
- How to keep agents fast: every step is a model call, so use fewer steps, parallel tool calls, a streamed final answer, and a fast model such as Haiku 5.5 where it's good enough.
Resources:
- 12_what_are_ai_agents.zip: agent_loop.py (a live two-tool agent with a hard step cap), an offline fake Claude (--fake, no API key needed; --max-steps 2 shows the honest partial answer), tests, and the coding exercise starter.
- What_are_AI_Agents_Cheat_Sheet.pdf: workflow vs agent, the loop in code, the rules, and a 3-question self-check.
Set ANTHROPIC_API_KEY in your shell, and never put a key in your code. Model names are current as of 22 Nov 2026.
Next: Coding Exercise "Write the Agent Loop" (7 tests, runs in the browser). You'll write agent_loop() against a fake Claude.
Get Claude to return data your code can trust. In this lecture you use JSON structured outputs to make Claude's reply match a schema, parse it straight into a Pydantic model with messages.parse, and turn on strict tool use so every tool call input matches your tool's schema. You'll also see the cases you still have to handle: refusals, max_tokens cut-offs, and enum casing. Download the example code and the cheat sheet in Resources, then complete the practice lab.
Make your agent fast and safe when Claude asks for several tools at once. In this lecture you run every tool call from one turn in parallel, send all the tool_result blocks back together in a single user message, and keep the history valid so the API never rejects it. You'll also handle tool failures with is_error, add timeouts so one slow tool can't stall the turn, cap the loop with MAX_STEPS, and see when to use disable_parallel_tool_use. Download the example code and the cheat sheet in Resources, then complete the practice lab.
U24 showed that compaction is lossy, not memory. This lecture sorts five ideas people casually call memory: conversation history, retrieved snippets, persistent app memory, the prompt cache, and the context window. You'll learn the test in one sentence: if the process dies, only what you persisted remains. We'll walk a five-row table, catch the mistake of calling a compacted summary "memory," and run a required demo that restarts Python without a store so a preference spoken only in chat is gone. Persistent app memory lives in your application — a file, a database, or the client-side memory tool whose /memories files you execute — and we do not write a store yet. That is the next lecture. Everything runs offline. No API key is required.
What you'll learn:
Sort conversation history, retrieved snippets, persistent app memory, the prompt cache, and the context window, and explain each in one sentence
Apply the restart test: if the process dies, only what you persisted remains
Refuse to call compacted history "memory" — a summary put back into the messages array is still conversation history
Explain why the prompt cache (a short-TTL cost and latency optimization) and the context window (a per-request token budget) are not a preference store
U25 showed that a preference spoken only in chat is gone when Python restarts with no store. This lecture writes that preference — and a new fact, "Alex prefers concise citations." — under a per-user root your application owns: data/users/<id>/memories/. You'll learn the MemoryRecord fields (text, source, created_at, expires_at), resolve every path before a write, and refuse "..", absolute paths, and symlink escapes so nothing lands outside that user's folder. A client-side memory tool, if you use one, still means your app stores the file and enforces the policy. We'll write two records for alex, run the required path-traversal failure case, then restart Python and load alex's store so the U25 preference now survives. Everything runs offline. No API key is required.
What you'll learn:
Write a MemoryRecord with text, source, created_at, and expires_at under data/users/<id>/memories/
Explain why the application, not the API, owns storage and path policy
Reject path traversal (".."), absolute paths, and symlink escapes, and write nothing when a path is refused
Load a per-user store after a process restart so a preference spoken in chat now survives
U26 wrote a preference under a per-user root your application owns. This lecture proves two things about that store. Persistence means a new process can load the same application data root — not the same Python object still sitting in memory. After we quit, MemoryStore.load for alex still has “Alex prefers concise citations.” Isolation means Blair cannot list Alex’s files: the same data root, user_id blair, returns an empty list. The required failure case is accidentally passing Alex’s memories folder as data_root when user_id is blair. That load is refused with DataRootRejected, and Alex’s files are not listed. Everything runs offline. No API key is required.
What you'll learn:
Explain why persistence means a new process can load the same application data root
Load Alex’s store after a real process quit and still see the preference
Show that MemoryStore.load for blair against the same data root does not list Alex’s files
Reject a per-user folder passed as data_root (the required failure case) so Alex’s files are not listed
U27 left expires_at on the MemoryRecord and did not filter on it. This lecture adds three rules to that store. If expires_at is in the past, list_memories does not return the record — the file may still be on disk. delete removes the file, so a scratch note is actually gone. And a write whose text contains a secret is rejected: the only token we use is the synthetic dummy sk-ant-dummy-not-real from data/synthetic_secrets/dummy.env. It is not a real key. Do not paste real credentials into memory. The required failure case is a filter miss that would write that dummy token; scan_for_secrets catches it. U31 will not auto-save raw MCP text without this filter. Everything runs offline. No API key is required.
What you'll learn:
Skip a MemoryRecord whose expires_at is in the past, without deleting the file
Delete a memory file so it is gone from disk and from the list
Reject a write that contains the synthetic dummy secret, and write nothing
Show a filter miss being caught by a test, so a dummy secret cannot silently land on disk
U02 introduced two MCP transports: local stdio and remote HTTP(S). This lecture stays on local stdio. Your Python process is the MCP client. It spawns a read-only MCP server rooted at data/mcp_sources/, lists the tools (list_dir and read_file — there is no write tool), and reads ranger_probe_bulletin.md, which contains the phrase "Replace the dust cap after every logging run." Listing that root does not show Alex's memories under data/users/. A path such as ../../users/alex/memories/citations.json is rejected. The Messages API mcp_servers parameter is for remote HTTP servers only; local stdio is a client you run. We do not call the Claude API in this lecture, and no API key is required. Allowlisting those tools in your agent loop is the next lecture. Remote-connector auth is U31.
What you'll learn:
Explain the U02 contrast in one minute: local stdio (your process spawns the server and speaks JSON-RPC on stdin/stdout) versus remote HTTP(S)
Root a local read-only MCP server at data/mcp_sources/ so a directory listing cannot see data/users/ memories
Spawn the server from Python, list the read-only tools, and read ranger_probe_bulletin.md
Reject path traversal through the MCP root (and absolute paths and symlink escapes) so Alex's memories are not read
This is a hands-on course on building applications with Anthropic's Claude API in Python. You start with an API key, a Python virtual environment, and your first Messages API call. From there you build retrieval-augmented generation (RAG), tool use, a bounded agent loop, and persistent per-user memory. It is aimed at developers who know basic Python and are new to building with LLMs.
What you build and practice:
A first Messages API call: read the reply safely, count tokens, and work out what the call cost
Streaming replies, retrying only retryable errors, and logging tokens, cost, and latency
A rate-limit plan: which per-minute limit your traffic hits first, and how to handle each kind of 429
A RAG pipeline in plain Python with no framework: chunk a document, embed it into a local LanceDB table, retrieve, rerank, and have Claude answer with citations
Tool calls: tool schemas, structured outputs and strict tool use, input validation against an allowlist, valid tool history, and parallel tool calls with tool errors
A bounded agent loop that stops at a step cap and returns an honest partial answer
Cited answers with Claude's web search tool, and a research assistant built with tool use
Persistent memory under a per-user root that survives a restart, keeps users isolated, and can be expired, deleted, and filtered for secrets
A local read-only MCP server over stdio that lists its tools and rejects path traversal, plus an exercise that bridges MCP tools to Claude tool use
You practice with 15 in-browser coding exercises that run automated tests, 4 quizzes, 1 practice test, and 1 AI role play. Several lectures also include a hands-on Udemy lab, including Streaming, Structured Outputs, Parallel Tool Calls, and three Memory lectures. Newer lectures attach a code pack and a one-page cheat sheet. English captions are available.
The course was updated in 2026. Newer lectures use the current Python SDK and Claude Haiku 5.5. Some earlier recordings remain, and where an older video's on-screen code differs, use the updated code pack attached to that lecture. The last section, AI Foundations, is an optional refresher on LLMs, transformers, prompting, evaluating prompts and models, RAG, and MCP. It is mostly conceptual.
You need basic Python (3.10 or newer) and should be comfortable running scripts from a terminal. No prior AI experience is needed. The live demos use your own Anthropic API key, and usage is billed. Many examples also run offline with a fake client, and the Memory and local MCP lectures need no key at all. This course does not cover fine-tuning, multi-agent systems, or deploying to cloud infrastructure.
This course is for Python developers who want to build Claude-powered applications, and for technical leads who want to see how these pieces fit together.