Souk's Notes - Unofficial Summaries

Unofficial, machine-generated summaries, as of 2026-11-09.

Claude AcademyClaude with Amazon Bedrock: 18-Being specific
  • Guidelines narrow the range of outputs an open prompt produces. Without guidance, a short-story prompt could produce 200 or 2,000 words, one character or five, and a wildly varying structure.
  • Quality guidelines shape the output; process steps shape the reasoning. Quality guidelines set length, structure and content, for example under 1,000 words with at least one supporting character. Process steps dictate a sequence: brainstorm 3 talents, pick the best, outline the scene that reveals it, then brainstorm supporting characters.
  • Adding guidelines roughly doubled the meal-plan score. Six guidelines (accurate calories, protein/fat/carb amounts, meal timing, only foods that fit the restrictions, portions in grams, budget-friendly if mentioned) raised the score from 3.92 to 7.86. A process-steps version scored 7.3.
  • Use process steps for hard problems that need multiple angles. They are recommended for troubleshooting, decision making, critical thinking, or whenever Claude should take a wider view. The example is a sales team's 30% quarterly drop, examined across market conditions, individual performance, organizational changes and customer feedback.
Claude AcademyClaude with Amazon Bedrock: 17-Being clear and direct
  • Open with a plain instruction and an action verb, not a question. The lesson calls the first line the most important part of the prompt. "Write three paragraphs about how solar panels work" replaces a rambling query about rooftop sun panels. "Identify three countries that use geothermal energy. Include generation stats for each" replaces a chatty question.
  • Rewriting only the opening line raised the score substantially. Changing "What should this person eat?" to "Generate a one-day meal plan for an athlete that meets their dietary restrictions" lifted the eval score from 2.32 to 3.92.
Claude AcademyClaude with Amazon Bedrock: 16-Prompt engineering
  • Prompt engineering is a loop: evaluate, apply a technique, re-evaluate. You set a goal, write an initial prompt, evaluate it, apply one technique and evaluate again. The running example generates one-day meal plans for athletes from their height, weight, goal and dietary restrictions.
  • An evaluator class generates datasets and grades cases concurrently. PromptEvaluator(max_concurrent_tasks=...) speeds up runs; the lesson advises starting low, around 3, to avoid rate-limit errors. generate_dataset takes a task description, an input spec and a number of cases. run_evaluation accepts extra criteria such as a daily calorie total, a macronutrient breakdown, and meals with exact foods, portions and timing.
  • A weak baseline score is expected and useful. The naive "What should this person eat?" prompt scored 2.3 out of 10 in the output.html report; the screenshot shows 50 test cases and a 0.0% pass rate. That score becomes the baseline for the techniques that follow.
Claude AcademyClaude with Amazon Bedrock: 15-Code based grading
  • Syntax validators score output full marks if it parses, zero otherwise. validate_json uses json.loads, validate_python uses ast.parse and validate_regex uses re.compile, each returning 10 or 0. Each test case carries a "format" field (json, python or regex) that selects its validator.
  • Tighter instructions and prefilling help outputs pass the code grader. Suggested additions to the prompt are "Respond only with Python, JSON, or a plain Regex" and "Do not add any comments or commentary or explanation". A prefilled code fence with stop sequences helps as well.
  • Average the model and syntax scores, weighting by what matters. The simple combination is (model_score + syntax_score) / 2, and the weights can be adjusted. The lesson says a single score means little on its own; its value comes from comparing scores across prompt iterations.
Claude AcademyClaude with Amazon Bedrock: 14-Model based grading
  • Graders come in three kinds: code, model or human. Code graders run programmatic checks such as length, required or banned words, JSON/Python/regex syntax and readability. Model graders make an extra API call to judge quality, instruction following, completeness, helpfulness and safety. Human graders are the most flexible but slow and tedious.
  • Define the criteria first, then assign each to a grader type. For the code-generation prompt, format (code only) and valid syntax go to a code grader. Task following goes to a model grader because it needs flexibility.
  • Ask the grader for strengths, weaknesses and reasoning, not just a score. The grader prompt asks for 1–3 strengths, 1–3 weaknesses, reasoning and a 1–10 score as JSON, using the prefill and stop-sequence technique. The lesson says that without this context, models tend to default to middling scores around 6.
  • Averaging grader scores gives a trackable but imperfect metric. run_test_case now records the score and reasoning, and run_eval prints the mean. The lesson concedes that model graders can be somewhat inconsistent.
Claude AcademyClaude with Amazon Bedrock: 13-Running the eval
  • The pipeline is three nested functions: run, test, evaluate. run_prompt merges a test case into the template and calls Claude. run_test_case runs the prompt and grades the result, for now with a hardcoded score of 10. run_eval loops over the dataset and collects an output, test_case and score record for each case.
  • Even a small run is slow before optimization. The lesson warns that a full dataset can take 30+ seconds even with Claude Haiku. The unconstrained version 1 prompt also returns verbose output.
  • Grading, not orchestration, is where evaluation gets hard. The lesson calls this simple loop the foundation most AI evaluation systems are built on. In its view the real sophistication lies in the grading logic and in prompt optimization.
Claude AcademyClaude with Amazon Bedrock: 12-Generating test datasets
  • The example prompt must return only AWS code, without explanation. The goal is to turn a task description into a Python function, a JSON configuration or a regex, with no headers, footers or explanation. Version 1 is simply "Please provide a solution to the following task: {task}".
  • Test cases can be hand-written or generated by a fast model. generate_dataset asks Haiku for 3 AWS tasks as a JSON array of {"task": ...} objects. It uses the "json" prefill and "" stop sequence so the output parses. Generated tasks included extracting account IDs from ARNs, JSON schemas for EC2 configurations and regexes for S3 bucket names.
  • Save the dataset to disk and enlarge it for production. It is written to dataset.json so it doesn't have to be regenerated each time. Three cases are enough for development, but the lesson says production evaluation needs far more examples, with more variety.
Claude AcademyClaude with Amazon Bedrock: 11-A typical eval workflow
  • The loop: draft, build a dataset, run, grade, revise, repeat. First draft a prompt. Then build a dataset of inputs, by hand or generated by Claude; real ones run from tens to thousands of records. Merge each input into the template and send it to Claude, grade each question-answer pair, then change the prompt and rerun.
  • A grader scores each answer, and the average becomes the metric. Scores run from 1 to 10 (10 is perfect, 4 has room for improvement, 1 is poor or wrong). The three sample questions scored 10, 4 and 9, for an average of 7.66.
  • Comparing averages across versions shows which prompt is better. Adding "Answer the question with ample detail" raised the score from 7.66 to 8.7. The lesson reads this as a sign the change improved performance across its test cases.
Claude AcademyClaude with Amazon Bedrock: 10-Prompt evaluation
  • Engineering improves prompts; evaluation measures whether they actually work. Prompt engineering is the craft, with techniques such as multishot prompting and XML tags. Prompt evaluation is automated testing that checks outputs against expected answers, compares prompt versions and reviews outputs for errors.
  • Testing a prompt once, or a few times, is a trap. Option 1, testing once, risks breaking in production on unexpected inputs. Option 2 patches a corner case or two but still misses what real users send. The instructor says all engineers fall into both, themselves included.
  • An evaluation pipeline with objective scores justifies its upfront cost. Option 3 scores the prompt and iterates on the data, at the price of more work and cost. The lesson argues that learning evaluation first is what lets you measure whether later prompt-engineering techniques help.
Claude AcademyClaude with Amazon Bedrock: 09-Structured data
  • By default, structured output arrives wrapped in headers and commentary. For an example app that generates AWS EventBridge rules, Claude returns a heading, a fenced json block and an explanatory sentence. Users then can't copy the whole response as usable JSON.
  • Prefill the opening code fence and stop at the closing one. If the assistant message is prefilled with "json" and the stop sequence is "", Claude skips its own header and halts before closing the block, so only the JSON is returned. It can then be strip()ped and validated with json.loads.
  • The same delimiter trick works for any copyable format. It applies to Python snippets, bulleted lists, CSV and config files: identify the delimiters Claude would naturally put around the content, prefill the opening one and stop on the closing one.
Claude AcademyClaude with Amazon Bedrock: 08-Controlling model output
  • A prefilled assistant message steers how the response begins. If the message list ends with an assistant turn such as "Coffee is better because", Claude continues from that text without repeating it, so the caller has to join the two parts. Prefills like "Tea is better because" or "They are the same because" steer the answer elsewhere.
  • Stop sequences end generation the moment a listed string appears. They are set as stopSequences in inferenceConfig. "Count from 1 to 10" with stop sequence "5" returns "1, 2, 3, 4,", because the stop string itself is excluded. With several sequences, generation halts at whichever appears first. Suggested uses are controlling length, stopping at breakpoints in structured output and not running past delimiters.
Claude AcademyClaude with Amazon Bedrock: 07-Streaming
  • Streaming shows text as it's generated, not after a long wait. The lesson says a complete response can otherwise take 10–30 seconds. converse_stream returns at once with a stream object, a generator that yields events as text is produced.
  • Only contentBlockDelta events carry the text to display. Events arrive in a fixed order: messageStart, many contentBlockDelta, contentBlockStop, messageStop, then metadata. Each chunk is at event["contentBlockDelta"]["delta"]["text"], and the chunks are concatenated into the full message.
  • Real apps forward chunks to the frontend and store the result. The suggested pattern sends each chunk over WebSockets or Server-Sent Events, updates the UI live, saves the complete message when streaming ends and handles errors that occur mid-stream.
Claude AcademyClaude with Amazon Bedrock: 06-Temperature
  • Temperature reshapes the probabilities used to sample each token. Generation runs through tokenization, prediction and sampling. In the example, "about" has a 30% chance of coming next and "would" 20%. Near 0 the top token becomes near-certain, and at 0 the output is deterministic. Near 1 the probability spreads more evenly, illustrated as 23% down to 9% across seven tokens.
  • Match the temperature range to how much creativity the task needs. Low (0.0–0.3) suits factual answers, coding, data extraction and moderation. Medium (0.4–0.7) suits summarization, educational content, problem-solving and constrained creative writing. High (0.8–1.0) suits brainstorming, creative writing, marketing and jokes.
  • The default is maximally creative, so lower it for precision. The default temperature is 1.0, and you override it with inferenceConfig: {"temperature": ...}. For movie ideas, 1.0 produced an origami-master fantasy. At 0.0 the model returned near-identical "time-traveling archaeologist/historian" plots run after run.
Claude AcademyClaude with Amazon Bedrock: 05-System prompts
  • Assigning a role beats listing do's and don'ts per message. Putting rules in each user message means anticipating every edge case. The lists grow unwieldy, users can see the internal instructions, and the rules don't adapt to the question. A system prompt such as "You are an AWS cloud support specialist" instead has Claude respond as that professional naturally would.
  • A role prompt narrows answers and declines off-topic requests in character. Without it, "How do I host a Postgres database?" got an answer covering multiple cloud providers and self-hosting. With the AWS specialist prompt, the answer kept to RDS, Aurora and EC2 with AWS setup steps, and a request for a bread recipe was politely declined.
  • The system prompt is a top-level, non-empty converse parameter. It is passed as system=[{"text": ...}] and cannot be an empty string. It can change between requests but not partway through a single messages list. Some models on Anthropic's own API accept system-role messages mid-conversation, but Bedrock does not support this.
Claude AcademyClaude with Amazon Bedrock: 04-Multi-Turn conversations
  • Neither the service nor the model stores any conversation history. Each Bedrock API call is independent. Sent alone, the follow-up "And 3 more?" gets a reply with no context, so the application must keep the full message list itself and resend all of it with every request.
  • Helper functions append user and assistant turns to one list. The lesson defines add_user_message, add_assistant_message and chat. After "What's 1+1?" and its answer are appended, the follow-up correctly yields "2 + 3 = 5".
  • Message roles must strictly alternate between user and assistant. The API requires the pattern user → assistant → user → assistant and does not allow two messages with the same role in a row.
Claude AcademyClaude with Amazon Bedrock: 03-Making a request
  • A request needs a runtime client, a model ID and a user message. The client is boto3.client("bedrock-runtime", region_name="us-west-2"), the call is client.converse(modelId=..., messages=[...]), and the generated text sits at response["output"]["message"]["content"][0]["text"].
  • Inference profiles avoid misleading errors from regional model availability. Not every model is hosted in every AWS region, and calling one from a region without it returns a cryptic "model doesn't exist" error. An inference profile routes the request to a region that hosts the model. Profile IDs are listed under "Cross-region inference" in the Bedrock console, not the main model catalog. The course uses us.anthropic.claude-haiku-4-5-20251001-v1:0 for Claude Haiku 4.5.
  • Message content is a list so one message can be multimodal. User and assistant messages share the same role-plus-content-list structure, with blocks for text, images (for example png bytes) or other media. The lesson says this shared format is what makes it simple to chain requests into conversations.
Claude AcademyClaude with Amazon Bedrock: 02-Accessing the API
  • Your server, not the browser, brokers every request to the model. The user's message goes to your server, which uses the Bedrock client to send it to AWS Bedrock with a model ID (such as Claude Haiku or Claude Sonnet). Bedrock returns an assistant message with the generated text, and the server forwards it back to the user's browser.
Claude AcademyClaude with Amazon Bedrock: 01-Overview of Claude Models
  • Three model tiers trade intelligence against speed and cost. All three share core capabilities (text generation, coding, image analysis): Opus is the most intelligent, at moderate latency and higher cost; Sonnet is the balanced default, with strong coding and precise edits to complex codebases; Haiku is the fastest and cheapest. The course's examples use Claude Haiku 4.5.
  • The fastest tier reasons only when given an explicit thinking budget. Haiku 4.5 supports extended thinking with a token budget, but unlike Opus and Sonnet it won't decide on its own how much reasoning a request needs. The lesson positions it for real-time, user-facing apps, with thinking held in reserve for occasional harder tasks.
  • Teams often mix models within a single application. The suggested split is Haiku for speed-critical user-facing interactions, Sonnet for main business logic and Opus for complex reasoning, so each part is tuned for its own cost and performance needs.
Claude AcademyBuilding with the Claude API: 67-Workflows vs agents
  • Workflows trade flexibility for accuracy and testability. A workflow is a predefined series of Claude calls for a known problem, so each step focuses on one subtask; the lesson says this gives higher accuracy, more predictable execution and far easier evaluation, at the cost of upfront design work and a constrained UX in which the exact inputs must be known.
  • Agents trade reliability for flexibility. Given basic tools and left to plan, an agent can combine them in unexpected ways, handle situations nobody anticipated and ask the user for more input. The stated costs are a lower task-completion rate and behaviour that is harder to instrument, test and evaluate, because the steps aren't known ahead of time.
  • Default to workflows; use agents only when truly required. The lesson's reasoning is that the engineer's job is to solve problems reliably, and users want a product that works consistently rather than a "fancy agent". Agents are reserved for unpredictable, varied requests that need creative problem-solving.
Claude AcademyBuilding with the Claude API: 66-Environment inspection
  • Agents act blindly unless they can observe their results. In computer use, every action such as typing or clicking is immediately followed by a screenshot, because a click might navigate, open a menu or change anything else, and without seeing the result Claude cannot tell whether the action succeeded.
  • Read before writing. Claude should read a file's current contents before modifying it; the example shows Claude reading 31 lines of main.py before adding a 5-line get_items route for "/items", so the change doesn't break existing code.
  • System prompts can direct an agent to verify its own output. For a video-generation agent, the lesson suggests instructing it to run whisper.cpp through bash to produce timestamped captions that check dialogue placement, and to use FFmpeg to extract screenshots at regular intervals for visual inspection, then compare the result against the original requirements.
  • Design every action around how Claude will know it worked. Inspection is said to improve progress tracking, error detection, quality checks before a task is declared complete, and adaptation. In practice that means reading files before edits, screenshotting after UI actions, checking API responses and validating generated content.
Claude AcademyBuilding with the Claude API: 65-Agents and tools
  • Agents get a goal and tools, not a fixed sequence. That suits varied, unpredictable tasks, since one agent built to work reasonably well can be deployed across many problems. The lesson flags that this flexibility costs reliability and money, and that reliable, economical task completion is often harder with agents.
  • Simple tools chain into surprisingly complex capabilities. With get_current_datetime, add_duration_to_datetime and set_reminder, Claude answers "what day of the week is it in 11 days?" by chaining the first two and sets a gym reminder for next Wednesday with all three. Asked "when does my 90-day warranty expire?", it recognises it must first ask when the item was bought.
  • Give agents reasonably abstract tools, not hyper-specialized ones. Claude Code has generic bash, read, write, edit, glob and grep, but no "refactor code", "install dependencies", "run tests" or "create migration" tool. The lesson credits that abstraction with letting it handle programming scenarios its developers never planned for.
  • Combinable tools let one agent serve both automated and interactive flows. A social-media video agent with bash (for FFmpeg), generate_image, text_to_speech and post_media can create and post a video outright, or generate a sample image, ask for approval, then proceed. The lesson argues that adapting to user feedback this way would be difficult in a rigid workflow.
Claude AcademyBuilding with the Claude API: 64-Routing workflows
  • One generic prompt can't serve requests needing different handling. In a social-media video-script generator, "programming" calls for educational content with clear definitions while "surfing" calls for entertainment built on excitement and visual appeal.
  • Routing categorizes first, then dispatches to a specialized prompt. The example defines six genres, each with its own template: Entertainment, Educational, Comedy, Personal vlog, Reviews and Storytelling. An initial Claude call asked to categorize "Python functions" against that list returns "Educational", and the educational template then generates the script.
  • Each input goes to exactly one pipeline, not all of them. Each pipeline can carry its own workflow, prompts or tools, which is what lets it be tightly optimized for its category.
  • Routing pays only when categories are clear and classification reliable. The lesson's conditions are diverse request types, categories that cover the use cases, a categorization step Claude handles reliably, and a specialization benefit that outweighs the routing step's overhead. Customer service bots and content-generation tools are the cited fits.
Claude AcademyBuilding with the Claude API: 63-Chaining workflows
  • Chaining splits a large task into focused sequential steps. The example is a six-step social-media pipeline: find trending Twitter topics, select one, research it and write a short-video script (those three with Claude), make the video with an AI avatar and text-to-speech, then post it. The stated benefits are keeping Claude on one aspect at a time, handling subtasks that can't be parallelized, and room for non-LLM processing between steps.
  • Long prompts with many constraints get some constraints ignored. Asking for a technical article with no mention of AI authorship, no emojis, no clichés and a professional tone can still return an emoji-filled article calling itself your "friendly neighborhood AI assistant".
  • Accept an imperfect draft, then run a targeted revision pass. The second call hands back the article with numbered steps: remove any AI self-identification, remove all emojis, and replace cringey writing with what a technical writer would produce. The lesson says this works because Claude can focus entirely on revising instead of balancing creation against constraint adherence.
Claude AcademyBuilding with the Claude API: 62-Parallelization workflows
  • One prompt juggling many criteria gives less reliable decisions. In a material-designer app that picks metal, polymer, ceramic, composite, elastomer or wood from a photo of a part, a bare prompt lacks criteria, and one massive prompt holding every material's criteria forces Claude to weigh them all simultaneously.
  • Split into independent parallel evaluations, then aggregate. The same image goes to Claude several times at once, each request carrying one material's criteria, and all the analyses then feed a final Claude call that compares them and recommends a material. The sub-tasks need not be identical; each can have its own prompt, tools or criteria.
  • Parallel sub-prompts can be tuned and extended independently. A weak metal analysis can be refined without touching the others, and adding a material is just one more request that can't interfere with existing criteria; the lesson also claims more consistent results from the reduced load per request.
  • Use it only when the decision decomposes into independent pieces. The signals given are multiple criteria, several options to compare, or several domains of expertise, and each sub-task must be able to run on its own and contribute a distinct analysis.
Claude AcademyBuilding with the Claude API: 61-Agents and workflows
  • Choose by how well you can picture the steps. Workflows fit when the exact flow is known in advance or the app's UX constrains users to a set of tasks; agents fit when you don't know what task or parameters Claude will receive. The lesson notes that the earlier tool-use exercises in the course were already agents.
  • Image-to-CAD is a workflow because its steps are known. Users drop in an image of a metal part and get a STEP file: Claude describes the object, models it with the CadQuery library, a rendering is made, and Claude grades the rendering against the original image and fixes any issues.
  • The evaluator-optimizer pattern loops a producer against a grader. The producer creates output, the grader checks it against criteria, and rejected output goes back with feedback until the grader accepts it. The lesson offers such named patterns as repeatable recipes that have worked for other engineers, while stressing that naming one does nothing until the code is written.
Claude AcademyBuilding with the Claude API: 60-Adding MCP servers to Claude Code
  • Claude Code's built-in MCP client lets servers extend it. Servers can expose tools (actions), prompts (templates) and resources (data). One is registered with claude mcp add [server-name] [command-to-start-server], for example claude mcp add documents uv run main.py, and Claude Code connects to it automatically on startup.
  • A custom server tool gets used automatically when relevant. With a document_path_to_markdown tool on the server, asking Claude to "Convert the tests/fixtures/mcp_docs.docx file to markdown" makes it call that tool and return the converted content.
  • Combining servers tailors Claude to your existing workflow. Listed integrations are sentry-mcp, playwright-mcp, figma-context-mcp, mcp-atlassian (Confluence and Jira), firecrawl-mcp-server and slack-mcp. The suggested setup pairs Sentry for production errors, Jira for ticket requirements and Slack for team notifications with custom servers for internal tools.
Claude AcademyBuilding with the Claude API: 59-Claude Code in action
  • /init writes a CLAUDE.md that carries project context forward. Claude scans the codebase's structure, dependencies, style and architecture and records build commands, guidelines and patterns in a file included in every later conversation. CLAUDE.md files come in project (shared), local (not checked into git) and user (all projects) scopes, and # adds a note to any of them.
  • Feed context, then plan, then implement. Have Claude read the relevant files first so it sees existing patterns, then ask for a plan while telling it explicitly not to write code yet, then ask it to implement. The worked example reads math.py and document.py, plans a document_path_to_markdown tool reusing the existing binary_document_to_markdown function, then says "Implement the plan".
  • A test-driven variant gives Claude clear success criteria. After feeding context, Claude brainstorms test cases, writes the most relevant ones, then iterates on the code until they pass; the lesson says this often produces more robust code.
  • Treat Claude Code as an effort multiplier, not a code generator. It is pitched as a collaborator across five phases (Discover, Design, Build, Deploy, Support and Scale) that can also stage and commit to git, run tests and manage dependencies, with /clear resetting context. Results are said to scale with the context and structure provided.
Claude AcademyBuilding with the Claude API: 58-Claude Code setup
  • Claude Code is a terminal assistant extensible through MCP. It ships with file search, read and edit, terminal command execution and web access, and MCP servers can add tools for databases, APIs or other services. It runs on macOS, Windows (natively or inside WSL) and Linux.
  • Setup is an install plus running claude to log in. Install via Step 1 of the Claude Code quickstart, then the first claude run prompts for an Anthropic account login; the full guide is at docs.anthropic.com.
Claude AcademyBuilding with the Claude API: 57-Anthropic apps: Claude Code and computer use
  • Claude Code and Computer Use are studied as working agents. The module runs Claude Code, then Computer Use, then agents in general, using the two apps to show tool integration, multi-step execution, environmental interaction and autonomous problem-solving that will inform building your own agents.
  • Computer Use extends Claude from text to a full desktop. Its tools let Claude browse websites, operate desktop applications and navigate visual interfaces, which the lesson says dramatically expands what's possible; Claude Code, by contrast, is the terminal assistant for editing files, fixing bugs and answering coding questions.
Claude AcademyBuilding with the Claude API: 56-Prompts in the client
  • Client prompt support is two thin wrappers over the session. list_prompts returns result.prompts from the session, and get_prompt(prompt_name, args) returns result.messages, a conversation that can be fed straight into Claude.
  • Prompt arguments arrive as keyword arguments on the server. The client's args dictionary must contain the keys the server's prompt function expects, such as doc_id for format_document, and the server interpolates them into the template.
  • In the CLI, prompts surface as slash commands. Typing / lists prompts; choosing "format" asks which document (e.g. plan.md), sends the interpolated prompt to Claude, and Claude can then use tools to fetch more data and finish the task. The lesson asks that prompts be relevant to the server, thoroughly tested and designed to work with its tools.
Claude AcademyBuilding with the Claude API: 55-Defining prompts
  • Server-authored prompts beat what users would write themselves. A user's "convert report.pdf to markdown" works, but a tested prompt with specific formatting, structure and output rules gives more consistent, higher-quality results. The lesson frames prompts as the server author's domain expertise, worth offering only for tasks central to the server.
  • A prompt is a decorated function that returns messages. @mcp.prompt(name="format", description=...) wraps format_document(doc_id: str = Field(...)), which returns [base.UserMessage(prompt)] using base from mcp.server.fastmcp.prompts. The example prompt tells Claude to add headers, bullets and tables and to use the edit_document tool.
  • Check interpolation in the MCP Inspector before shipping. In the Prompts section, selecting "format" with doc_id outlook.pdf and clicking Get Prompt shows the generated messages, here one message with role "user".
Claude AcademyBuilding with the Claude API: 54-Accessing resources
  • Resources put data directly in the prompt, skipping tool calls. When a user types "@report.pdf", the app fetches it through the MCP client and includes its contents in the prompt to Claude, which the lesson says is faster and more efficient than having Claude call a tool for it.
  • read_resource takes the first content item and parses by MIME type. It calls session().read_resource(AnyUrl(uri)) and uses result.contents[0]; a TextResourceContents with mimeType application/json goes through json.loads, anything else returns as text. It needs json and pydantic's AnyUrl.
  • The client is a building block; application logic stays separate. Other parts of the app call read_resource to list resources or fold their data into prompts, while the client alone handles communication with the server.
Claude AcademyBuilding with the Claude API: 53-Defining resources
  • Resources expose data like GET handlers; tools perform actions. The motivating feature is @-mentions of documents: list all documents for autocomplete when the user types @, and inject a mentioned document's contents into the prompt. The client sends a ReadResourceRequest whose URI acts as the resource's address.
  • Direct resources use static URIs; templated ones take parameters. docs://documents backs list_docs (application/json), while docs://documents/{doc_id} backs fetch_doc (text/plain), which raises a ValueError for an unknown id. The Python SDK parses URI parameters into keyword arguments for the function.
  • MIME types are hints to clients; the SDK handles serialization. Resources can return strings, JSON or binary, and return values are serialized automatically with no manual conversion to JSON strings.
  • The Inspector lists the two kinds separately. Running uv run mcp dev mcp_server.py shows static resources under Resources and parameterized ones under Resource Templates; clicking one shows the exact response a client would get, such as the JSON list of names from docs://documents.
Claude AcademyBuilding with the Claude API: 52-Implementing a client
  • Real projects usually build an MCP client or a server, not both. The course builds both only so the two sides can be seen working together.
  • A custom MCPClient class wraps the SDK's ClientSession for cleanup. The ClientSession is the actual connection to the server and needs proper resource cleanup, which the wrapper class handles automatically.
  • Two methods cover the app's needs: list tools and call tools. list_tools returns result.tools from the session, and call_tool(tool_name, tool_input) passes Claude's chosen tool and input to the server. A test harness using async with MCPClient(command="uv", args=["run", "mcp_server.py"]) should print the read_doc_contents and edit_document definitions.
  • End to end, the client fetches tools and executes Claude's calls. Asking "What is the contents of the report.pdf document?" sends the tools with the question, Claude picks read_doc_contents, the client runs it, and the result about the 20m condenser tower goes back to Claude for its answer.
Claude AcademyBuilding with the Claude API: 51-The server inspector
  • The Inspector tests a server without wiring up an application. mcp dev mcp_server.py starts a development server on port 6277 with a local browser URL, and Connect launches the server, exposing Resources, Prompts, Tools, Ping, Sampling and Roots tabs. The lesson warns the interface is under active development and may look different.
  • Test tools by listing, filling parameters and running, then chain checks. In Tools, "List Tools" shows read_doc_contents and edit_document; running the reader with "deposition.md" returns its text. After an edit, re-running the read tool confirms the change, giving a fast change-test-debug loop in isolation.
Claude AcademyBuilding with the Claude API: 50-Defining tools with MCP
  • The Python SDK generates tool schemas from decorators and type hints. FastMCP("DocumentMCP", log_level="ERROR") creates the server in one line, and @mcp.tool(name=..., description=...) with Pydantic Field descriptions produces the JSON schema Claude needs. The stated gains are built-in validation, less boilerplate, and type safety with IDE support.
  • The example server reads and edits documents held in memory. Six documents sit in a dict keyed by id (deposition.md, report.pdf, financials.docx, outlook.pdf, plan.md, spec.txt). read_doc_contents returns one by id, and edit_document does find-and-replace via Python's replace(), with old_str described as having to match exactly, including whitespace.
  • Raise descriptive errors Claude can act on. Both tools raise ValueError(f"Doc with id {doc_id} not found") for an unknown id, a message the lesson says Claude can understand and potentially respond to.
Claude AcademyBuilding with the Claude API: 49-Project setup
  • The project is a CLI chatbot over in-memory documents. An MCP client handles the user's side of the conversation and a custom MCP server manages documents with read and update tools. Real projects typically build only one side, exposing a service as a server or connecting to existing servers as a client.
  • Setup is an API key, dependencies, then a test run. From cli_project.zip, put the Anthropic API key in .env, install with uv (recommended) or pip, and start with uv run main.py or python main.py; the main files are main.py, mcp_client.py and mcp_server.py.
  • Verify the baseline with a question whose answer you know. Ask "what's 1+1?" and confirm the answer is actually 2, not merely that a reply appeared; that proves the key, dependencies and chat loop work. A question like "what do the documents say?" can only be answered by the model alone at this point, because the document tools don't exist yet.
  • Match verification effort to the cost of being wrong. A broken setup costs every later lesson while checking costs two questions, so after each new layer (a tool, a data source, an MCP server) ask one known-answer question before building the next. The lesson's maxim: a baseline you have verified is the only baseline you can debug against.
Claude AcademyBuilding with the Claude API: 48-MCP clients
  • MCP is transport agnostic. Client and server most commonly run on the same machine and talk over standard input/output, but they can also connect over HTTP, WebSockets or other network protocols.
  • Two message pairs do most of the work. ListToolsRequest/ListToolsResult asks the server what tools it provides; CallToolRequest/CallToolResult asks it to run one with given arguments and returns the output.
  • One tool-using query passes through every component in turn. For "What repositories do I have?", the app gets the tool list via the client, sends query plus tools to Claude, receives a tool-use request, has the client send a CallToolRequest that the MCP server turns into a GitHub call, then returns the result to Claude for the final answer. The lesson concedes this is many steps but argues each component has a clear responsibility, with the client hiding the server communication.
Claude AcademyBuilding with the Claude API: 47-Introducing MCP
  • MCP moves tool authoring and execution off your server. Without it, a GitHub chatbot needs a schema and a function for every capability (repositories, pull requests, issues, projects and more), all of which you write, test and maintain. An MCP server wraps the outside service and supplies those tools ready-made, alongside prompts and resources.
  • Anyone can write an MCP server; providers often ship official ones. The lesson's example is that AWS might release an official server with tools for its services.
  • MCP differs from tool use in who does the work. Calling an API directly means authoring the tool definitions yourself; with MCP someone else has already written the schemas and functions. The lesson calls "MCP is just tool use" a misconception: the two are complementary, not the same.
Claude AcademyBuilding with the Claude API: 46-Code execution and the Files API
  • The Files API uploads once, then references by file ID. Instead of base64-encoding an image or PDF into every message, you upload it in a separate call, get back metadata with a unique ID, and cite that ID in later messages; useful for repeated references and large files.
  • Code execution is a server-side tool you don't implement. You include the predefined schema ({"type": "code_execution_20250522", "name": "code_execution"}) and Claude can run Python, several times per conversation if needed, in an isolated Docker container with no network access, as in computing pi to the 50th decimal place.
  • With no network, the Files API is the container's door. Data goes in as a container_upload block carrying the file ID, and generated files come out as code_execution_output blocks whose file IDs are downloaded through the Files API. Responses interleave text, server tool use (the code) and code execution tool result blocks, often over several execution cycles.
  • One request can produce a full analysis with plots. Uploading streaming.csv (subscription tier, viewing hours, churn) and asking for the major drivers of churn with at least one detailed plot yields a downloadable multi-panel chart; it reports 500 users, a 38.6% churn rate and customer-service interactions as the top driver.
  • The pairing generalizes to any computational task you delegate. The lesson lists image processing, document parsing and transformation, mathematical modeling and custom report generation, with you controlling inputs and outputs through the Files API.
Claude AcademyBuilding with the Claude API: 45-Prompt caching in action
  • Cache tool schemas by marking only the last tool. The lesson adds cache_control: {"type": "ephemeral"} to a copy of the final tool in the list, copying both the list and that tool rather than editing tools[-1] in place, so later reordering doesn't leave a stray cache field behind.
  • System prompts must become a text block to be cached. The plain string is wrapped as [{"type": "text", "text": system, "cache_control": {"type": "ephemeral"}}], because the string form has nowhere to put the cache field.
  • The usage fields show whether the cache was written or read. The first request reports the tokens written in cache_creation_input_tokens; follow-ups report the same count in cache_read_input_tokens; any change shows up as fresh creation tokens, and a single changed character invalidates the cache for that component.
  • Caching is layered: tools, then system prompt, then messages. Changing only the system prompt gives a partial read for the tools plus a write for the new prompt, so you pay only for what changed. That partial read happens only if the tools alone reach the minimum length, since a breakpoint under the minimum writes nothing.
  • It pays off for stable, frequently repeated context. The default cache lives 5 minutes and is refreshed free on each use, with a 1-hour option at extra cost. The lesson says this suits apps making frequent calls with consistent tools and system prompts, not long-term storage.
Claude AcademyBuilding with the Claude API: 44-Rules of prompt caching
  • Caching is opt-in, through manually placed cache breakpoints. Nothing is cached automatically. You add cache_control: {"type": "ephemeral"} to a block, which requires the longhand text-block form because the shorthand string has no place for the field.
  • Everything up to the breakpoint is cached, and must match exactly. Content after the breakpoint is processed normally. A follow-up only gets the cache if everything up to and including the breakpoint is identical, so even adding "please" forces a full reprocess.
  • A breakpoint caches all earlier messages, across roles. A breakpoint in the last user message also covers the earlier user and assistant messages. Breakpoints also work on system prompts, tool definitions, image blocks and tool use/result blocks, and the lesson calls system prompts and tools the best candidates because they rarely change.
  • Order is tools, system prompt, messages; up to four breakpoints. Knowing this order lets you put one breakpoint after the tools and another partway through the conversation history, so a change in one part doesn't throw away the cache for the parts before it.
  • Content under the minimum length is silently left uncached. For Claude Haiku 4.5, the course's model, the cached prefix must total at least 4,096 tokens across all the blocks, not per block. No error is returned; the only sign is that cache_creation_input_tokens and cache_read_input_tokens both come back 0.
Claude AcademyBuilding with the Claude API: 43-Prompt caching
  • Without caching, Claude discards its input preprocessing after each request. The lesson describes tokenizing, creating embeddings and adding context from the surrounding text before any output is generated. All of that is thrown away once the response is sent.
  • Repeated content means repeated work. In a follow-up that refines a summary of the same long text, Claude has to redo all the preprocessing on input it handled moments earlier.
  • Caching stores that work so identical input can reuse it. The first request writes to the cache, which the lesson likens to a lookup table, and follow-ups read from it. Cached portions run faster and cost less.
  • The benefit is narrow: frequent, identical content within a short window. The cache lasts 5 minutes by default, refreshed free on each reuse, or 1 hour at a higher cache-write price. The lesson's examples are asking many questions about one large document and iterative editing against fixed base content.
Claude AcademyBuilding with the Claude API: 42-Citations
  • Citations let users check answers against your documents. The lesson's point is that without them, users can't tell whether an answer, such as how Earth's atmosphere formed, came from the supplied document or from training data.
  • Enable them with two fields on the document block. Add a title (e.g. "earth.pdf") and "citations": {"enabled": True} next to the base64 PDF source.
  • Responses become structured, with source data on each claim. Each citation carries cited_text, document_index (which matters when you send several documents), document_title, and start_page_number/end_page_number.
  • The value comes from building a UI on top of them. The example shows numbered citation markers that users can hover over to see the source passage, so they can verify claims and read the surrounding context.
  • Plain-text sources work too, with character positions instead of pages. You use a text source with media_type text/plain. The lesson recommends citations wherever accuracy, authoritative sources or transparency matter.
Claude AcademyBuilding with the Claude API: 41-PDF support
  • PDF input works almost exactly like image input. You change the file to .pdf, rename image_bytes to file_bytes for clarity, set the block type to "document", and set media_type to "application/pdf". The base64 encoding and the paired text prompt stay the same.
  • Claude reads more of a PDF than its text. The lesson says it handles embedded images and charts, tables and their relationships, and the document's structure and formatting. It presents this as a one-stop way to extract information, shown by a one-sentence summary of a Wikipedia article on Earth saved as a PDF.
Claude AcademyBuilding with the Claude API: 40-Image support
  • Image inputs have hard limits and cost tokens by size. A request can carry up to 600 images (100 on models with a 200k-token context window), each at most 10MB after base64 encoding, and at most 8000px per side for one image or 2000px when sending several. Images go in as base64 or a URL, and cost ⌈width/28⌉ × ⌈height/28⌉ tokens.
  • Images are just another content block in the user message. You put an image block with a base64 source and media type next to a text block with the question, and Claude replies with text as usual.
  • Simple image prompts give unreliable answers. Asked "How many marbles are in this image?", Claude answered 13 when there were 12. The lesson's point is that the usual prompt-engineering techniques apply to images too.
  • Step-by-step methods and worked examples fix accuracy. A prompt that has Claude number each marble and then recount row by row from the bottom-left got 12. So did a one-shot prompt that first showed an image labeled as having 11 marbles.
  • Real tasks need structured, multi-step prompts. The lesson's insurance example rates fire risk from satellite imagery instead of sending inspectors. The prompt walks through finding the residence, measuring tree overhang in bands (0–25% up to 75%+), checking fire paths and defensible space, and assigning a 1–4 rating with one sentence of findings per step.
Claude AcademyBuilding with the Claude API: 39-Extended thinking
  • Extended thinking gives Claude a visible scratchpad before it answers. The response becomes a thinking block followed by a text block. The lesson says this improves reasoning and accuracy on hard problems and shows how Claude reached its answer, at the price of paying for thinking tokens, more latency, and more complex response handling.
  • Reach for thinking only after prompt optimization falls short. The lesson's rule is to run your prompt evaluations without thinking first and enable it only if accuracy still misses the requirement. It also notes that thinking doesn't work with message pre-filling and limits how temperature can be used.
  • Thinking blocks are signed so they can't be tampered with. A cryptographic signature proves the thinking text wasn't modified, which the lesson says stops developers from altering the reasoning in ways that could steer the model toward unsafe behavior.
  • Flagged reasoning comes back as an encrypted redacted block. When internal safety systems flag the thinking, the block still holds the reasoning in encrypted form, so the full message can be sent back in later turns without losing context. A special trigger string can force a redacted block, so you can test that your code handles one without crashing.
  • Enable it with a thinking object and a budget below max_tokens. You send thinking: {"type": "enabled", "budget_tokens": ...}. budget_tokens must be at least 1024 and max_tokens must exceed it; the lesson's helper sets max_tokens to the budget plus 1000.
Claude AcademyBuilding with the Claude API: 38-A Multi-Index RAG pipeline
  • A shared index interface lets one Retriever combine search methods. VectorIndex and BM25Index both expose add_document() and search(). A Retriever class takes any number of indexes, adds each document to every index, sends each query to all of them, and merges the results.
  • Reciprocal rank fusion merges rankings that use different score scales. Each chunk scores Σ 1/(k + rank) across the indexes, with k usually 60 but set to 1 in the example. Vector ranks of Section 2, 7, 6 and BM25 ranks of 6, 2, 7 give Section 2 0.833, Section 6 0.75 and Section 7 0.583, so the chunk that ranked well in both comes out on top.
  • Hybrid retrieval fixed the vector-only misranking. For "what happened with INC-2023-Q4-011?", vector search alone put financial analysis (Section 3) second. The hybrid retriever returned Cybersecurity Incident Response (Section 10), then Software Engineering's Project Phoenix (Section 2), then Legal Developments (Section 5).
  • New search methods plug in without changing the Retriever. Any index that implements the same SearchIndex protocol, such as keyword, graph or domain-specific search, joins the fusion automatically. The lesson says this keeps each implementation focused and testable.
Claude AcademyBuilding with the Claude API: 37-BM25 lexical search
  • Semantic search can miss exact-term lookups like IDs. Searching for incident "INC-2023-Q4-011" returned the cybersecurity section, which does contain it, but also a financial analysis section that never mentions it, because embeddings match on concepts rather than exact terms.
  • The fix is to run semantic and lexical search together, then merge. Embeddings find conceptually related text and classic text search finds exact matches. The lesson presents the two as complementary, so combining them handles both concept questions and specific lookups.
  • BM25 ranks documents by how rare the matched terms are. It tokenizes the query, counts how often each term appears across the documents, gives rare terms more weight (a common word like "a" gets little, the incident ID a lot), and returns the documents with the most high-weight terms.
  • On the ID query, BM25 put the right sections first. A BM25Index filled with section chunks ranked Software Engineering (about 0.27) and Cybersecurity Analysis (0.33) ahead of Methodology (0.94), and both of the top two contain the incident ID.
Claude AcademyBuilding with the Claude API: 36-Implementing the RAG flow
  • The basic pipeline is five steps from chunking to search. You split report.md into sections with chunk_by_section, embed all chunks in one batch call, add each embedding to a VectorIndex, embed the user's question, and search the index for the nearest chunks.
  • Store each chunk's text next to its embedding. A search that returns only vectors is useless. Each vector is stored with {"content": chunk}, or at least a reference to the text, so results come back as readable text.
  • The test query found the right section, but only narrowly. "What did the software engineering dept do last year?" returned Section 2: Software Engineering at cosine distance 0.71, just ahead of Methodology at 0.72, where lower means closer. The lesson notes that this approach fails in some cases, which later lessons address.
Claude AcademyBuilding with the Claude API: 35-The full RAG flow
  • Chunking, embedding and storage all happen before any query. In the lesson's toy model, every embedding has two dimensions: medical and software. A Medical Research chunk about "bug" XDR-47 embeds as [0.97, 0.34], and a Software Engineering chunk about "infection vectors" as [0.30, 0.97]. These are normalized to length 1.0 ([0.944, 0.331] and [0.295, 0.955]) and stored in a vector database, and the pipeline then waits for a user.
  • The query is embedded the same way, then matched by nearness. A question about what the software engineering department did embeds as [0.1, 0.89], which normalizes to [0.112, 0.993], and the database returns the software chunk as the closest.
  • Cosine similarity measures how close two vectors point. It runs from -1 (opposite) through 0 (unrelated) to 1 (same direction). The query scores 0.983 against the software chunk and 0.398 against the medical one. Vector databases often report cosine distance (1 − similarity) instead, where values near 0 mean similar.
  • The retrieved chunk and the question go into one prompt for Claude. The template wraps them in <user_question> and <report> tags under an instruction to answer the user's question about the document.
Claude AcademyBuilding with the Claude API: 34-Text embeddings
  • Finding relevant chunks is a search problem, usually solved by meaning. Semantic search compares embeddings of the question and of each chunk instead of matching keywords. The example question "How many bugs did engineers fix this year?" has to work around a medical chunk that uses "bug" for a pathogen.
  • An embedding is a list of numbers whose dimensions humans can't read. Each value runs from -1 to +1 and acts as a score for some feature of the text. Labels like "how happy" or "how formal" are only illustrations; the model learns what each dimension means during training.
  • Anthropic offers no embedding model, so the course uses VoyageAI. That means a separate account and API key (free to start) stored as VOYAGE_API_KEY in .env. A small generate_embedding helper calls voyageai.Client().embed with model voyage-3-large and input_type="query", and returns a list of floats.
Claude AcademyBuilding with the Claude API: 33-Text chunking strategies
  • Bad chunking puts the wrong context in the prompt. In the lesson's example, "How many bugs did engineers fix this year?" can pull up a medical-research chunk that calls the pathogen XDR-47 a "bug" instead of the software engineering section, and the model then answers wrongly.
  • Size-based chunking is simple but cuts words and context. Equal-length slices (a 325-character text into three of about 108) work on any content but split words ("signific"/"ant") and separate headers from their text. Overlap between chunks reduces this; chunk_by_char defaults to 150 characters with 20 of overlap.
  • Splitting on document structure gives the cleanest chunks. Splitting Markdown on \n## turns each section into one complete chunk. It depends on guaranteed formatting, which plain text and PDFs often lack.
  • Semantic chunking produces the most relevant chunks but costs the most. It groups consecutive sentences by how related NLP judges them to be. Sentence-based chunking is the practical middle ground: split on sentence punctuation with a regex and group, for example, 5 sentences with 1 of overlap.
  • The right choice depends on what you can guarantee about the documents. Use structure-based when you control the format (such as internal reports), sentence-based for most prose, and size-based for anything, including code. The lesson says size-based with overlap is often the production default because it reliably gives reasonable chunks.
Claude AcademyBuilding with the Claude API: 32-Introducing Retrieval Augmented Generation
  • Putting a whole document in the prompt breaks down at scale. For an 800-page financial filing, the full text may exceed the prompt limit. The lesson adds that Claude gets less effective on very long prompts, and that larger prompts cost more and run slower.
  • RAG sends only the chunks relevant to the question. The document is split into chunks ahead of time. At query time you find the relevant chunk, such as "Risk Factors" for a question about company risks, and include only that in the prompt. This scales to very large documents and to many documents, with cheaper, faster prompts.
  • RAG trades simplicity for scale and adds design work. It needs a preprocessing step, a way to search for "relevant" chunks, and a choice among many chunking methods, and the retrieved chunks may still lack context Claude needs. The lesson says to weigh whether this complexity is worth it for your application.
Claude AcademyBuilding with the Claude API: 31-The web search tool
  • Web search runs entirely on Anthropic's side; you supply only a schema. You add {"type": "web_search_20250305", "name": "web_search", "max_uses": 5} to the tools list and Claude decides when to search. Your organization must first enable the tool in the console settings.
  • max_uses limits how many searches Claude may chain. One search returns several results, but Claude may run follow-up searches based on them, and the cap prevents excessive calls.
  • allowed_domains limits results to sources you trust. The lesson's example restricts medical and exercise questions to nih.gov (PubMed) to get evidence-based answers instead of random blog content.
  • The response's block types are meant to map onto UI elements. Text blocks, the ServerToolUseBlock with the exact query, a WebSearchToolResultBlock of individual results with titles and URLs, and citation blocks with quoted supporting text. The lesson suggests showing sources as a list at the top and citations inline with domain, title, URL and quote.
Claude AcademyBuilding with the Claude API: 30-The text edit tool
  • The text editor tool gives Claude a full set of file operations. It can view files and directories, view line ranges, replace text, create files and insert at given lines. The lesson says this lets Claude act as a software engineer from the start.
  • Claude knows the schema, but you write the implementation. Claude only requests file operations; your code must actually perform the create, read, replace and so on. This is the reverse of custom tools, where you write both the schema and the function.
  • You send a short, version-specific schema stub that Claude expands. Claude 3 models use type text_editor_20250124 named str_replace_editor; later models use text_editor_20250728 named str_replace_based_edit_tool.
  • Its value is file editing inside your own applications. In the example, Claude views main.py, rewrites it with a function that computes pi to 5 digits, and creates test.py with unit tests. The lesson pitches the tool for programmatic editing, environments without a capable editor, and rebuilding AI-editor features in your own app.
Claude AcademyBuilding with the Claude API: 29-Fine grained tool calling
  • Streamed tool arguments arrive as InputJsonEvents. Each event carries partial_json, the new fragment, and snapshot, the JSON accumulated so far.
  • By default the API holds chunks until each top-level key validates. It buffers, say, the whole abstract value, checks that key-value pair against the tool schema, then sends the buffered chunks together before moving on to meta. That is why tool streaming arrives as pauses followed by bursts.
  • Fine-grained tool calling turns off that validation for immediate chunks. Passing fine_grained=True sends chunks as soon as Claude generates them, so a nested value like word_count can appear before its parent object is finished.
  • Without validation, your code must handle invalid JSON. Claude may produce something like "word_count": undefined, so parsing the snapshot needs a JSONDecodeError handler. The lesson notes that with validation on, the API might instead wrap bad values in strings that may not match your schema.
  • Default buffering is fine for most apps. The lesson recommends fine-grained mode only for live progress display, early processing of partial arguments, or when the delays hurt the user experience, and only if you are prepared to write robust JSON error handling.
Claude AcademyBuilding with the Claude API: 28-Using multiple tools
  • Once tool handling exists, a new tool takes four small steps. Write the function, define its schema, add the schema to the tools list in run_conversation, and add an elif case for it in the run_tool router.
  • The reminder example chains tools because Claude can't reliably do date arithmetic. The three tools are get current datetime, add duration to datetime (included because Claude is imperfect at date addition), and set a reminder. For "177 days after Jan 1st, 2050", Claude computed June 27, 2050 with the duration tool, then called set_reminder.
  • One assistant message can pair explanation with a tool call. The conversation history shows assistant messages containing both a TextBlock and a ToolUseBlock, followed by tool-result messages and further assistant turns.
Claude AcademyBuilding with the Claude API: 27-Implementing multiple turns
  • Keep calling Claude until stop_reason is no longer "tool_use". run_conversation sends the messages with the tool schemas, appends the assistant reply, and stops if stop_reason != "tool_use". Otherwise it runs the requested tools, appends their results as a user message, and loops.
  • Every tool-use block needs a matching tool-result block. One response can contain several tool-use blocks (for example "10 + 10" and "30 + 30"). run_tools filters the content for tool_use blocks and builds one tool_result per block, tied to it by tool_use_id, with the output as a JSON string.
  • Failed tools still return a result, flagged as an error. Each call is wrapped in try/except, and on an exception the result block carries "Error: {e}" with is_error: True, so Claude always gets an answer for every request.
  • A name-to-function router keeps the loop unchanged as tools grow. run_tool dispatches on the tool name with **tool_input, so adding a tool means adding one branch rather than touching the conversation logic.
Claude AcademyBuilding with the Claude API: 26-Multi-turn conversations with tools
  • One question can require several tool calls in a row. For "What day is 103 days from today?", Claude first asks for get_current_datetime, then, once it has that result, for add_duration_to_datetime, and only then answers. The application has to run this back-and-forth automatically.
  • The fix is a loop that runs until Claude stops asking for tools. Each turn appends Claude's response to the history, runs any requested tools, and sends the result blocks back as a user message.
  • The helpers must handle whole messages, not just text. add_user_message/add_assistant_message now accept a string, a list of blocks or a Message object (they use .content when given one). chat accepts a tools list and returns the full message so no blocks are lost, and a text_from_message helper joins the text blocks for display.
Claude AcademyBuilding with the Claude API: 25-Sending tool results
  • Run the tool by unpacking Claude's input as keyword arguments. The tool-use block's .input is a dictionary, so the call is get_current_datetime(**response.content[1].input).
  • Results go back as tool_result blocks inside a user message. Each carries a tool_use_id matching the request's id, the output serialized as a string in content, and is_error.
  • Matching ids keep parallel tool calls straight. When "What's 10 + 10 and what's 30 + 30?" produces two tool-use blocks (ids ab3 and po9), results can come back in any order, here po9's 60 before ab3's 20, because the ids tell Claude which result answers which request.
  • The follow-up needs the full history and the tool schema again. The history is the original user message, the assistant tool-use message, and the user tool-result message. The schema must still be passed even if no further call is expected, because Claude needs it to understand the tool references in the history.
Claude AcademyBuilding with the Claude API: 24-Handling message blocks
  • With tools enabled, Claude's reply can contain several blocks. Passing a tools list of JSON schemas can produce an assistant message with a text block explaining what Claude is doing and a ToolUse block. The ToolUse block has an id, the function name (e.g. get_current_datetime), a dictionary of inputs (e.g. date_format "%H:%M:%S") and type tool_use.
  • Store the entire content list in the history, not just the text. Claude keeps no history of its own, so you append {"role": "assistant", "content": response.content} to keep both blocks for the next call. Text-only versions of add_user_message/add_assistant_message need updating to handle this.
  • A tool call takes two round trips. You send the user message with the schema, receive text plus a tool-use block, run the function yourself, send the result back with the full history, and then get Claude's final answer.
Claude AcademyBuilding with the Claude API: 23-Tool schemas
  • A tool spec has a name, a description and an input_schema. The input_schema uses standard JSON Schema, a long-established data-validation spec that the AI field adopted, not something specific to Claude.
  • The description tells Claude when to use the tool. The lesson recommends about 3–4 sentences covering what the tool does, when to use it and what it returns, plus a detailed description for each argument.
  • Have Claude write the schema for you. Paste the function and Anthropic's tool-use documentation into Claude and ask for "a valid JSON schema spec for the purposes of tool calling" that follows the documented best practices.
  • Name each schema after its function and type it with ToolParam. The convention is get_current_datetime next to get_current_datetime_schema. Wrapping the dict in anthropic.types.ToolParam isn't required, but the lesson says it prevents type errors when the schema is passed to the API.
Claude AcademyBuilding with the Claude API: 22-Tool functions
  • A tool function is a plain Python function Claude triggers. It runs automatically when Claude decides it needs more information or an action. The first one built is get_current_datetime(date_format="%Y-%m-%d %H:%M:%S"), which returns datetime.now() formatted to whatever string Claude passes, such as "%H:%M".
  • Validate inputs and raise clear errors, because Claude reads them. Function and parameter names should be descriptive, and bad inputs should raise informative errors (the weather example's "Location cannot be empty"; here, an empty date_format raises ValueError). Claude sees the message and may retry with corrected arguments. The next step is a JSON schema describing the function to Claude.
Claude AcademyBuilding with the Claude API: 21-Project overview
  • Reminder-setting exposes three gaps that tools must fill. For a request like "Set a reminder for my doctor's appointment. It's a week from Thursday", the lesson says Claude may know the date but not the exact time, doesn't always add durations reliably far into the future, and has no way to set a reminder.
  • The project builds one tool per gap, simplest first. The tools are get current date time, add duration to date time, and set a reminder. The stated principle is to extend the model with tools where it falls short, rather than working around the limits in the prompt.
Claude AcademyBuilding with the Claude API: 20-Introducing tool use
  • Tools give Claude live information its training data lacks. Without them, a question like the weather in San Francisco gets "I don't have access to up-to-date weather information"; tools connect Claude to current data, APIs, databases and other systems.
  • Tool use is a four-message round trip through your server. You send the question with instructions on how to get extra data; Claude decides it needs more and asks for specific data; your server fetches it (e.g. from a weather API); you send the result back and Claude answers using both the question and the fresh data.
Claude AcademyBuilding with the Claude API: 19-Providing examples
  • Examples teach Claude corner cases instructions struggle to describe. In tweet sentiment classification, sarcasm ("the best movie I've seen since 'Plan 9 from Outer Space'") reads as positive but is negative. Adding a plain positive example and a sarcastic one ("Oh yeah, I really needed a flight delay tonight! Excellent!" → Negative), with a note on sarcasm, addresses it; one-shot sets a pattern and multi-shot covers several scenarios.
  • Use your eval's top-scoring outputs as examples. Input/output pairs that scored 10 (or the highest available) show what "perfect" looks like for your task, and examples should target your most common failure cases.
  • Wrap examples in tags and say why they're ideal. Use <sample_input> / <ideal_output> tags, label them explicitly ("Here is an example input with an ideal response"), and follow with a sentence explaining what makes the output good. That way Claude learns the reasoning as well as the format.
Claude AcademyBuilding with the Claude API: 18-Structure with XML tags
  • XML tags mark where instructions end and interpolated data begins. With large pasted content, such as 20 pages of sales records, or mixed content like code alongside documentation, Claude can lose track of which text is which. Wrapping each part (<sales_records>, <my_code>, <docs>) gives clear boundaries.
  • Descriptive, made-up tag names work better than generic ones. No official tag set is needed: <sales_records> beats <data>, and <athlete_information> groups height, weight, goal and restrictions as one unit. The lesson concedes gains on simple prompts may be small and grow as prompts become longer and more varied.
Claude AcademyBuilding with the Claude API: 17-Being specific
  • Output guidelines give Claude a target; use them almost always. Listing qualities the output must have — length, structure, required elements, tone — narrows an open request like a short story about a hidden talent (200 or 2,000 words, one character or five). The lesson calls these a safety net for nearly every prompt.
  • Specific guidelines roughly doubled the meal-plan eval score. Six guidelines (accurate daily calories; protein, fat and carb amounts; meal timing; only foods fitting restrictions; portions in grams; budget-friendly if mentioned) moved the score from 3.92 to 7.86.
  • Process steps make Claude reason through complex problems systematically. For troubleshooting, decisions, critical thinking or multi-angle problems, list steps to follow first. The example walks a 30% sales drop through market metrics, industry changes, individual performance, organizational changes and customer feedback, rather than letting Claude fix on one cause; professional prompts often combine steps with output guidelines.
Claude AcademyBuilding with the Claude API: 16-Being clear and direct
  • Open with a plain instruction led by an action verb. The lesson calls the first line the most important part of a prompt: use simple language, state the task outright, and give instructions rather than questions, starting with verbs like "Write", "Create" or "Generate". A rambling query about "those solar panel things" becomes "Write three paragraphs about how solar panels work."
  • Rewriting just the opening line raised the meal-plan eval score. Replacing "What should this person eat?" with "Generate a one-day meal plan for an athlete that meets their dietary restrictions" names the action, the deliverable and the constraints. The score rose from 2.32 to 3.92.
Claude AcademyBuilding with the Claude API: 15-Prompt engineering
  • Prompt engineering is a measured loop, one change at a time. The steps are set a goal, write an initial prompt, evaluate, apply a technique and re-evaluate, repeating the last two. The lesson says each change should be evaluated on its own so you know which techniques actually help.
  • The running example is a one-day athlete meal plan. Inputs are height, weight, goal and dietary restrictions (the illustration: 180cm, 75kg, maintain weight and improve power, lactose intolerant, about 3,000 calories). The deliberately naive baseline asks only "What should this person eat?"
  • The provided PromptEvaluator handles dataset generation and grading. Concurrency is set by max_concurrent_tasks, and the lesson advises starting low (around 3) to avoid rate-limit errors. Development datasets should stay at 2–3 cases for fast iteration, and extra_criteria adds grading requirements (calorie total, macronutrient breakdown, exact foods, portions and timing).
  • A very low first score is normal and gives the baseline. The evaluator produces a score plus an HTML report with per-case reasoning; the first attempt scores 2.3 out of 10, which the lesson calls typical, and the report shows where the prompt fails.
Claude AcademyBuilding with the Claude API: 14-Code based grading
  • Syntax is checked by trying to parse the output. Three validators return 10 if parsing succeeds and 0 if it fails: json.loads for JSON, ast.parse for Python and re.compile for regex. This covers the format and valid-syntax criteria, leaving task following to the model grader.
  • Each test case must name its expected format. A "format" field (e.g. "python") tells the code grader which validator to run, and the dataset-generation prompt can be updated to emit it automatically.
  • Tighter instructions and a generic code prefill improve compliance. The prompt adds "Respond only with Python, JSON, or a plain Regex" and "Do not add any comments or commentary or explanation", and prefills "```code" so Claude starts raw code without the language being fixed in advance.
  • Combine model and syntax scores, then improve on the baseline. The simple approach averages the two equally, with weights adjustable by use case. The lesson says the baseline is neither good nor bad in itself; what matters is whether prompt changes raise it.
Claude AcademyBuilding with the Claude API: 13-Model based grading
  • Graders come in three kinds with different strengths. Code graders run programmatic checks (length, required or banned words, JSON/Python/regex syntax, readability); model graders use another API call to judge quality, instruction following, completeness, helpfulness and safety; human graders are the most flexible but slow and tedious. Each returns a usable signal, usually 1–10.
  • Define the criteria first, then assign each to a grader. For the code-generation prompt, the criteria are format (only Python, JSON or regex), valid syntax and task following. The first two suit a code grader; task following goes to a model grader because it needs flexible judgement.
  • Ask the model grader for reasoning, not just a score. grade_by_model asks for 1–3 strengths, 1–3 weaknesses, reasoning and a 1–10 score as JSON (via prefill and stop sequence). The lesson says that without the surrounding analysis, models default to middling scores around 6.
  • Average the per-case scores into one metric to track. run_test_case now records the grader's score and reasoning, and run_eval prints the mean. The lesson concedes model graders can be capricious but says they give a consistent baseline for measuring improvement.
Claude AcademyBuilding with the Claude API: 12-Running the eval
  • Three small functions make up most of an eval pipeline. run_prompt merges a test case into the template and calls Claude, run_test_case runs it and attaches a score, and run_eval loops over the dataset collecting {output, test_case, score} results. The lesson says this is most of what any eval pipeline does; the complexity lies in better prompts, grading and performance.
  • Grading is the missing piece, stubbed for now. The score is hardcoded to 10 so the pipeline can be tested end to end, with real graders to follow. A full run takes around 30 seconds even on Claude Haiku, and outputs are verbose because the prompt has no formatting instructions yet.
Claude AcademyBuilding with the Claude API: 11-Generating test datasets
  • The worked eval targets clean AWS code output with no explanation. The prompt under test must return Python, JSON or a regex for AWS tasks, with no extra explanation, headers or footers. Version 1 is deliberately bare: "Please provide a solution to the following task: {task}".
  • Have Claude generate the test dataset, using a fast model. The lesson recommends a faster model such as Haiku for this step. generate_dataset() asks for an array of {"task": ...} objects solvable with a single function, JSON object or regex, uses the "json" prefill and "" stop sequence to get parseable JSON, requests 3 cases, and saves them to dataset.json.
Claude AcademyBuilding with the Claude API: 10-A typical eval workflow
  • An eval runs a prompt template over a dataset of realistic inputs. The five steps are draft a prompt, build a dataset, merge each input into the template and send it to Claude, grade the outputs, then change the prompt and repeat. The example dataset has three questions ("What's 2+2?", oatmeal, distance to the Moon); real ones run to tens, hundreds or thousands of records, built by hand or generated with Claude.
  • A grader turns outputs into an average score you can compare. The grader sees each question and answer and scores 1–10; the example scores 10, 4 and 9 average 7.66. Adding "Answer the question with ample detail" lifts the hypothetical rerun to 8.7, and the higher-scoring version is the one to keep.
Claude AcademyBuilding with the Claude API: 09-Prompt evaluation
  • Prompt engineering writes better prompts; prompt evaluation measures them. Engineering is the toolkit (multishot prompting, XML-tag structure and other practices); evaluation is automated testing against expected answers, comparing prompt versions and reviewing outputs for errors.
  • Testing a prompt once or a few times is a trap. The lesson's three paths after drafting: test once and ship (high risk of breaking in production), test a few times and patch a corner case or two (users still supply inputs you never considered), or score it in an evaluation pipeline and iterate on objective metrics. The instructor says the first two catch all engineers, including themself.
  • An eval pipeline costs more upfront but catches failures before users do. Its stated payoff is finding weaknesses before production, comparing versions objectively and iterating on measured improvement.
Claude AcademyBuilding with the Claude API: 08-Structured data
  • Prefill plus a stop sequence yields raw output without commentary. By default Claude wraps generated JSON in a markdown code fence and adds an explanation, which breaks copy-and-use flows like the lesson's AWS EventBridge rule generator. Prefilling the assistant message with "json" makes Claude continue with only the JSON, and `stop_sequences=[""]ends generation when it tries to close the fence;json.loads(text.strip())` cleans up stray newlines.
  • Use whatever wrapper Claude naturally adds as prefill and stop. The lesson says the technique applies equally to Python snippets, bulleted lists, CSV and other formatted content: identify the wrapper (usually a code fence for code) and use it for both.
Claude AcademyBuilding with the Claude API: 07-Response streaming
  • Streaming removes the dead wait before a response appears. A response can take 10–30 seconds to generate; with streaming, the server forwards text chunks to the client as they arrive, all within a single request to Claude.
  • A stream is a sequence of typed events; only deltas carry text. The order is MessageStart, ContentBlockStart, repeated ContentBlockDelta, ContentBlockStop, MessageDelta and MessageStop, enabled by stream=True on messages.create. ContentBlockDelta holds the generated text to display.
  • The SDK's stream helper yields just text, then the full message. client.messages.stream(...) exposes stream.text_stream for text-only iteration, and stream.get_final_message() afterward returns the assembled message for storage or further processing.
Claude AcademyBuilding with the Claude API: 06-Temperature
  • Temperature reshapes the next-token probabilities Claude samples from. It is a value from 0 to 1. In the lesson's example, "about" at 30% becomes 100% at temperature 0 (fully deterministic), while near 1 the seven candidates spread out to between 9% and 23% each, giving more varied output.
  • Match temperature to the task. The lesson's ranges: 0.0–0.3 for factual answers, coding, data extraction and moderation; 0.4–0.7 for summarization, educational content, problem-solving and constrained creative writing; 0.8–1.0 for brainstorming, creative writing, marketing and jokes.
  • Higher temperature makes variety more likely but doesn't guarantee it. In the movie-idea test, temperature 0.0 consistently returned the same time-traveling-archaeologist premise, while 1.0 varied themes and plots, though similar outputs can still recur. The chat helper gains a temperature=1.0 parameter passed through to the request.
Claude AcademyBuilding with the Claude API: 05-System prompts
  • A system prompt makes Claude respond as a given role would. Passed as a plain string in the system parameter, it shapes tone and approach and keeps Claude on task. In the math-tutor example ("How do I solve 5x + 2 = 3 for x?"), Claude without one gives the full worked solution; with "You are a patient math tutor. Do not directly answer..." it asks guiding questions about the first step instead.
  • Include the system parameter only when one is provided. The API does not accept system=None, so the reusable chat(messages, system=None) builds a params dictionary and adds system conditionally before calling client.messages.create(**params).
Claude AcademyBuilding with the Claude API: 04-Multi-Turn conversations
  • The API is stateless; Claude remembers nothing between requests. A follow-up like "Write another sentence" sent alone gets a sentence on some random topic, because the earlier quantum-computing exchange was never stored by the API or Claude.
  • Conversation memory is your code's job: resend the full history. You keep a list of messages, append Claude's reply as an assistant message and the next question as a user message, then send the whole list each time. The lesson builds three helpers for this — add_user_message, add_assistant_message and chat — reused through the rest of the course.
Claude AcademyBuilding with the Claude API: 03-Making a request
  • Keep the API key in a .env file, never in code. The setup installs anthropic<1 and python-dotenv, stores ANTHROPIC_API_KEY in a .env file loaded with load_dotenv(), and adds .env to .gitignore so the key is not committed. The client is created with Anthropic() and the course uses model "claude-haiku-4-5".
  • max_tokens is a safety ceiling, not a length target. client.messages.create() takes model, max_tokens and messages; with max_tokens=1000, Claude writes what it judges appropriate and is cut off only if it reaches 1,000 tokens.
  • Messages are role-tagged dictionaries forming the conversation. Each has a role of "user" (human-written) or "assistant" (Claude-generated) and a content string. The response object carries metadata, and the generated text itself is at message.content[0].text.
Claude AcademyBuilding with the Claude API: 02-Getting an API key
  • A new API key is displayed only once, so copy it immediately. At platform.claude.com, the path is Get API Keys, then Create Key, choosing the "Default" workspace and a name (the course uses "Anthropic Course"). The key appears in a single pop-up; if the window is closed before copying, the advice is to delete that key and generate a new one.
Claude AcademyBuilding with the Claude API: 01-Accessing the API
  • Never call the API from client code; route through your server. Requests need a secret API key, and anything shipped to a web or mobile client can be extracted and used for unauthorized calls, so the app talks to your server, which holds the key. Official SDKs exist for Python, TypeScript, JavaScript, Go and Ruby, or plain HTTP works.
  • Every request carries four required fields. They are the API key, the model name (e.g. "claude-haiku-4-5"), a list of messages holding the user's input, and max tokens, a cap on how much Claude may generate.
  • Claude generates text one token at a time, sampling rather than maximizing. Input is tokenized, each token turned into an embedding (a list of numbers covering a word's possible meanings, such as the four senses of "quantum"), refined by surrounding context, then passed to an output layer that assigns next-word probabilities. Claude mixes probability with controlled randomness rather than always taking the top word (the example shows "Quantum" at 30%), appends the choice, and repeats.
  • Generation stops on one of three conditions, reported back to you. Claude checks after each token whether it has hit max tokens, emitted an end-of-sequence token, or hit a predefined stop sequence. The response returns the message text, input and output token usage, and the stop reason, which the lesson says your application logic should handle.
Mr. GlobalOil Prices Set To Rise Significantly
  • The post-election price drop is already half reversed. Brent was up $4.60 a barrel on the day after losing $8.55 the day before, and wholesale diesel recovered 16 cents a gallon of the 32 cents it lost. He reads this as the market recovering from the election shock, and expects gasoline and diesel not to fall as far as many people thought.
  • Steep backwardation shows a physically tight oil market. He points to the spread between the current Brent futures contract and the next month, about $3.50 a barrel and widening sharply on the day, and stresses this is a prompt spread rather than the physical price. His reading: the market is much tighter now than traders expect it to be by February.
  • Falling Persian Gulf loadings explain the tightness and point higher. Export loadings in the Persian Gulf have dropped by about 4 million barrels a day over the last couple of weeks compared with early October, which he calls the easiest way to gauge flow through the Strait of Hormuz. He treats it as one data point, but expects oil prices to rise unless there is some resolution.
Professor G MarketsDavid Brooks on What Happened to American Conservatism
  • This post includes paid content that is not available publicly. See the original source.
Dwarkesh PatelThe benchmark where AIs have to lie to win
  • Models gained sharply at deception and multi-agent reasoning within months. Across 386 games pitting one model's good team against another's evil team in Blood on the Clocktower (about $20,000 of API credits), GPT-6 Astra (September) sits about 430 Elo above Claude Opus 4.6 (February), winning roughly 92% of games against it. He reads this as gains in long-term coherence, coordination and strategic reasoning.
  • Evil teams now run multi-step schemes involving deliberate self-sacrifice. An Astra Demon posing as an Investigator fingered his own expendable minion, whose execution was then confirmed evil, making the Demon the most trusted player. In an Opus 5.5 game, an evil heiress who inherits the Demon role joined the mob against the real Demon and pre-arranged that the claimed Saint be executed next if the game didn't end, which won the game for evil.
  • The leading models win by refusing to take evidence at face value. OpenAI's GPT-5.4 trailed Opus 4.6 as recently as March; OpenAI gained 580 Elo to Astra, which beats 5.4 about 97% of the time, mostly through better play on the good side. In a mirrored deal where a poisoned Slayer's shot missed the Demon, Claude villagers declared the suspect cleared, while GPT villagers deduced the sabotage and won; daily private Demon-probability estimates showed GPT converging faster and more accurately.
  • Smarter players overall favor neither side, so the benchmark resists saturation. Evil's win rate drifts slightly down as both teams get stronger, but not distinguishably from chance; because the bar is set by the opposing models, he argues it won't saturate. A small, non-rigorous test of a half Opus 5.5, half GPT-5.6 Sol team over about 130 games did, if anything, worse than either model alone, not significantly.
  • AI largely built and refined the environment, implying better RL-environment building. He replaced the human Storyteller with a hand- or AI-set probability table; Claude ran over 20 revision loops, launching dozens of games and having subagents audit every log for unfairness, sometimes overnight without him. He infers AIs have likely become much better at building the RL environments used to train them. The code and a play-against-AIs site are at clocktowerbench.com.
All Things FinancialLike lemmings, when you realize everyone else is going to run, you also want to run 11-5-2026
  • Alta Banka died when its political patron lost power. He reports that the Serbian lender, ninth largest in the country and never designated systemically important, served tens of thousands of Russian emigrés; after Vučić's SNS lost the election, large withdrawals and conversions began on October 27, about 140 million left on October 28–29, and on October 30 it stopped some transfers and missed overnight loan repayments.
  • Above-market deposit rates were a classic pre-failure signature of negative carry. Alta paid a weighted 3.13% on deposits against 1.59% for other Serbian banks, and paid public-sector depositors 5.61% in dinars versus 4.58% in euros, steering them into dinars. About a quarter of deposits came from the public sector; the top three depositors held over 10%, the top ten over 21%.
  • An outsized cash ratio is a red flag, not safety. Alta held 25% in cash, a figure he also attributes to Ueno; he says banks normally hold 3–4% and in 50 years he has never seen 25%. Alta's reported cash of €370M (over $400M) was not there when needed. He calls it "probably" fraud — his inference, not established. Staff were reportedly paid early and told to move their money elsewhere.
  • Paraguay's Ueno Bank was a crony capture of state money. By his account, a former Ueno chairman (2021–23) was appointed to lead the central bank, President Peña's son held the shares, and pension and health funds held roughly 355–380 (units unclear) in Ueno bonds — the bank using state money to buy its own debt. He claims 60% of Paraguayans lost money and that Peña has resigned.
  • The same failure template keeps repeating, and structure predicts it. He says it has played out five more times in the last 13 months (Iran, Brazil, Azerbaijan, Bangladesh, Cambodia): captured public deposits that make a bank look too political to fail, owners detained within 48 hours, normal statements within 24–72 hours of closure. Structure, not size, predicts failure, and depositors can check it in 10 minutes; runs spread because depositors cannot tell good banks from bad.
Professor G MarketsRepublicans Fear Midterms were an “Extinction-Level Event”
  • This post includes paid content that is not available publicly. See the original source.
murat.energyOil fell but still 40% higher than prewar. Top things about oil and gas today, November 5th #shorts
  • Hopes for a war-ending deal sank oil and gas, but crude remains elevated. On Wednesday (November 4th, as of the November 5th video) Brent fell more than 8% to close at $94.62 and WTI closed at about $88, putting Brent under $100 for the first time since October 7th; the host says traders were betting the election result pushes Washington to end the Iran war without escalation. He notes Brent was in the high $60s before the war, so it is still about 40% higher, and European gas futures fell about 18% that week to around 85 on the same deal hopes.
  • Gulf shipping is still being hit and moving far less fuel. Two projectiles struck a tanker off Qatar on November 4th. Vortexa reports Gulf oil exports fell to 17 million bpd in October from 18.9 million bpd in September, with refined products at just 3.1 million bpd, which the host calls about half of normal.
  • Ukraine's drone campaign keeps knocking out Russian refineries. Drones set fire to the Ryazan refinery, one of Russia's big plants, overnight into November 5th, injuring one person, following hits at Yaroslavl and Kirishi that week and four refineries hit over four days the previous weekend. Russia's ban on diesel exports by producers runs until January 31st.
  • US diesel inventories are at a two-decade low while China holds supply back. The EIA says US distillate stocks fell to 99.3 million barrels, the lowest since May 2003 and about 13% below the 5-year average. China sold only about 500,000 tons (3.7 million barrels) of diesel for November loading, against 1.85 million tons (about 13.8 million barrels) in September.
  • The host expects prices to stay higher for longer despite swings. His bottom line rests on refineries making less diesel, export bans still in place, and Hormuz shipping very little refined product; he adds OPEC's figure that freight and insurance now make up about 30% of the cost of a barrel shipped to Asia, up from about 5% in January.
Loss DogLIZ Is In the House: How to Handle the Market MELTDOWN | 11.05 | One Lucky Dog
synopsis

Scott and Tony, with Tom away and guest Liz joining for the second half, read the day as a real, orderly selloff concentrated in the NASDAQ. Over the show the NASDAQ went from down 500 to down about 1,400 (roughly 5.5%) and E-mini S&Ps fell as much as 240 (about 3%). The VIX rose from near 18 to as high as 28 before easing under 23. Their prescription was not to hide. Elevated volatility is opportunity, so sell premium or put on spreads now, but keep unit size where it was, defend losers early, and never double up on the belief that the market has to rally. They split on whether the move counts as a crash, and agreed it is not a bottom.

The open. The hosts call it a two-sided market with the NASDAQ "on a death spiral". The losses came on the same day as rallies elsewhere: the Dow and Russell were initially up and Apple was a contrarian gainer. Nvidia broke $200 and reached about $182, AMD fell $62, Micron traded near $690–730 against a high near $1,250, and Tesla fell to about $350. One host, already short the NASDAQ, kept adding and covering into rallies. Oil near $89, down from about $105, is read as fear coming off the table on the geopolitical side. The hosts say they are surprised bonds haven't sold off.

Question of the day: news. Asked whether following news helps retail traders, one host wants all the information he can get but avoids social media rabbit holes. He sits between Tom, who says news doesn't matter, and the other host. He argues consequences have been building: rates higher, oil elevated, and tariffs that one politician claims cost constituents $4,500 a year, against the $1,500–2,000 he has heard elsewhere. Both expect financial media to blame newly elected anti-data-center governors, and dismiss that because they take office in January. Their own explanation is that the stocks were overcooked, and price is not mean-reverting.

Viewer mechanics. Monthly strikes are sparser than weeklies because market makers add strikes when demand appears. One host says he has pushed exchanges to make strikes closing-only if no opening trade comes within a day or two, calling illiquid options "vehicles for fraud". For two short December QQQ 670 puts with QQQ at 668, the advice is to roll down or sell one 20–30 delta call. A short put that grows from about 20 delta to 35–40 needs defending, and the 21-day exit is a guideline for winners only. A viewer who quit their job to trade is told to allow about a year so they see both up and down markets. On futures, one host sizes an E-mini as about $25,000–26,000 of exposure at 5–10% of the account, giving $50,000 minimum ($25,000 for a micro), and the other would double that. Rolling one side of an iron condor to another expiration loses the single-cycle margin benefit. Equity pre- and post-market trades are real, and a broker that blocks them should be replaced.

Tony's trades. These were placed the day before and were mostly defined risk. One exception is a naked short put on a roughly $50 stock with an IV rank of 79, down 10 cents. An unfilled trade needing $2,300 of buying power would have been down $37.

Liz on the tape. Liz argues new traders feel this as worse than it is, since the S&P has only given back the summer. The hosts counter that individual names are down 30–50%. On why it is hard to get short in a selloff, they say traders are conditioned to expect snapback rallies and feel they are selling into the hole. They read a rising VIX on a down day as the market "believing" the move. One host warns that his old clearing firm, Apex, raised requirements after five consecutive VIX closes above 25 and immediately above 30. Naked short options then cost more to hold.

Gold and the zebra. Liz treats gold and silver as an investment rather than a trade. She automatically buys small amounts of GLD and SLV, about half a percent of her account each, and separately sells puts as trades. In an IRA she prefers a zebra to a poor man's covered call: sell one 50 delta call and buy two 70 delta calls, at roughly 10–15% of the capital the stock would cost, then sell a call against it.

Crash or not. One host calls the move too orderly to be a crash, putting the threshold at S&Ps down 400–500 and the NASDAQ below 26,000. That is his side of a standing bet whose other side is new highs near 31,600. Liz and the other host argue that wiping out a year in a month is a crash. Supporting the bear case, one host cites FINRA margin debt at record highs, about $1.2 trillion, back in August. Viewer polls: 63% say QQQ won't make new highs this year, and 55% say this is not the beginning of a crash.

Stock ideas. For Nvidia, December 170 puts were about $9 (about 30 delta) and 160 puts about $6 (23 delta). Liz prefers jade lizards to strangles in case the market rubber-bands upward. The hosts call Nvidia safer than AMD or Micron. They defend short selling as necessary for rational prices and warn against shorting low-float names. For a Dell strangle with the puts in the money and the stock about $320, they lean toward covering all or part. The hosts' pitch occupied one segment: Liz and Jenny's Level Up show launching on the Cboe floor on December 1, and the One Lucky Dog app awaiting Apple approval.

Close. One host says he raised size for the first time in the decline, from about 30% to 60% of normal. Another says to widen spreads and move them closer to the money rather than add units. Their advice to someone uncomfortable is to close everything, because the market will still be there. A position the market forces you to adjust is, they say, the message to size smaller.

  • The selloff is a violent down move; whether it's a crash is disputed. During the show the NASDAQ fell from down 500 to down roughly 1,400 (about 5.5%) and E-mini S&Ps fell as much as 240 (about 3%). One host calls it too orderly to be a crash and sets the bar at S&Ps down 400–500 and NASDAQ below 26,000. The other side, guest Liz among them, argues that erasing a year of gains in a month is a crash.
  • Overcooked AI names are being repriced and needn't revert. The hosts cite Micron from about $1,250 to under $700, Cerebras from roughly $350 after a $175 IPO to about $82, and Nvidia from $240 in October to about $182. They reject the expected media explanation, newly elected governors opposed to data centers, because those governors don't take office until January.
  • Elevated volatility is the "opportunity index", but discipline sets size. Their argument is "if not now, when": sell premium or use spreads while implied volatility is high, because volatility mean-reverts faster than price. Keep unit size unchanged and move strikes closer to the money. One host says he went from about 30% to 60% of normal size; another treats a VIX close above 25 as the warning line.
  • Defend losers by delta, not by the 21-day guideline. The hosts say taking off positions at 21 days to expiration is an offensive rule for winners. A short put sold near 20 delta that reaches 35–40 needs action now. For two short QQQ 670 puts with the ETF at 668, one suggests rolling down or selling one 20–30 delta call to cut delta. Positions sized too big force action at the worst moment.
  • Futures need a larger account than their margin suggests. One host treats an E-mini S&P as about $25,000–26,000 of exposure per contract and a micro as a tenth of that, sizing at 5–10% of the account. That implies at least $50,000 for an E-mini, or $25,000 for a micro. The other would double those minimums and calls a $26,000 NASDAQ contract too much for a $100,000 account.
Loss DogTrading Discipline: Position Sizing in a Volatile Market #tradingstrategy #trading #markets
  • Add size slowly into a selloff, never double or triple. One host says he added size for the first time in the whole move lower that day, taking his positions from roughly 30% to roughly 60% of normal, with E-mini S&P futures 80–100 handles above where they then stood after a 60-handle rally. He says he is not calling a bottom and is still not at full size because he is afraid too.
  • Discipline means sizing to the account, not to conviction. The hosts warn against assuming "it's got to rally" and doubling or tripling a position; the speaker describes adjusting delta up and down slowly instead. He frames "if not now, when" as an argument for trading through the volatility, while conceding the day's losses outran his recent wins.
Crosstalk SolutionsThis $39 KVM Is the Size of a Postage Stamp
  • The JetKVM Mini is a cheap, tiny KVM-over-IP the host recommends. It costs $39 for the Ethernet version and $42 for the Wi-Fi version, with three-packs also offered. At recording it was sold out until the end of November. The host calls it small enough to keep in a tech bag. The maker sent him an Ethernet and a wireless unit free; he says the video is not sponsored.
  • The hardware is basic, but the remote session was responsive. The unit is about postage-stamp size and roughly an inch thick, with full-size HDMI, Ethernet and two USB-C ports. Its screen is not a touchscreen and is driven by two side buttons. Testing against a Raspberry Pi, the host found the session impressively responsive, with stats for video stability, playback delay and packet loss.
  • Firmware updates arrive fast, and Tailscale support landed this way. The host says the maker emailed him new firmware two or three times a week. When he asked about Tailscale, the maker added it in a firmware update later that same day. The host's idea: pre-join a unit to your tailnet, ship it to a client, and it connects once plugged in.
  • The KVM's Tailscale client supports at most 64 tailnet devices. Login worked, but the KVM then refused to connect because Crosstalk's tailnet holds hundreds of devices. Crosstalk uses Tailscale to reach its customers' PBX systems without opening firewall ports. The host says most users will not hit the limit; he would need a second tailnet to test it fully.
  • The web interface covers the usual KVM tools. It offers paste and copy-from-screen, Wake-on-LAN, a virtual keyboard, keyboard macros, compact and full-screen views, and a dark theme. It also has virtual media, which the host guesses uses the second USB port to mount a thumb drive or external disk to the connected machine.
Mr. GlobalCould Traders Keep Oil Prices High To Sabotage The Election For Trump?
  • Traders could not have held oil high for months to sink Republicans. He takes on a theory, spreading over the previous 24 hours, that traders, corporations or countries kept prices up to make Trump and the Republicans lose the midterms; he says it serves to shift blame off the administration and to misinform. A large position in thin trading can exaggerate a move for hours or a couple of days, but not for months.
  • The market is far too big to corner. The world produces over 100 million barrels a day, about $10 billion a day and over $300 billion a month physically. CME says its energy futures and options average nearly $200 billion notional daily, which he scales to about $4 trillion in 20 trading days and $12 trillion in three months, before ICE Brent (over 57 million contracts of 1,000 barrels in March), swaps, physical cargoes and hedgers.
  • Every dollar of overpricing recruits sellers who push it back down. Taking a case of oil worth $70 held at $90, he argues producers would hedge, countries and storage operators would sell, trading firms would arbitrage and hedge funds would short. The conspirators would have to absorb that selling every day for months, needing hundreds of billions in risk capital against trillions in market activity.
  • A small, hidden premium sustained for years is plausible. He says oil companies or OPEC could add $2 or $3 a barrel by under-reporting inventories and similar invisible means, accumulating trillions over time. That is a different thing from a $20 a barrel inflation, and from a quick billion-dollar bet around a Trump announcement that recovers by noon.
  • A real crisis explains the prices without any conspiracy. He cites the Iran war, the closure of the Strait of Hormuz, constrained product supply, inventory pressure and diesel shortages. He reads the current fall in prices as traders pricing in a possible US pullout from Iran after the administration blamed the election result on the war.
Professor G MarketsDemocrats Sweep Congress — And Stocks Explode Higher
  • This post includes paid content that is not available publicly. See the original source.
Dr. Jon KrohnWhy AI Agents Need Their Own 70,000-Year-Old Language Revolution (with Vijoy Pandey)
  • Connectivity protocols tell you agents are up, not that they agree. Pandey says the OpenTelemetry observability stack Outshift pushed with Microsoft about a year before recording reports uptime and reasoning-engine health, but not what happens when agents exchange meaning. The host's question frames this against the 16% accuracy seen at three cognitive failures between agents.
  • Multi-agent work needs three semantic steps, mirroring human teams. Pandey lays them out as shared intent (grounding, discovering unfamiliar terms, resolving conflicts), then coordination and negotiation in which each agent gives up some of its local optimum for a global one, then verification that the goal was met, which he likens to a year-end performance review.
  • Agents are where humans were before language, by his analogy. Pandey calls the stack the "Internet of Cognition" and compares it to the cognitive revolution roughly 70,000 years ago, when language moved humans from individual to collective intelligence. He argues 40-plus years of networking connected data endpoints, and "intelligence endpoints" now need a new protocol layer for meaning, set out in a paper on "L9 protocols" late the previous year.
  • The connectivity layer has converged; the cognition layer is missing. Pandey reports that over the roughly 9 months since his last appearance, AGNTCY, A2A and MCP, all under the Linux Foundation, have converged on a common stack for describing, discovering, identifying and messaging agents, including AGNTCY's SLIM secure low-latency messaging layer.
  • A shipped monitor triggers correction protocols only on drift. Pandey says OXP, an observability and explainability platform built on OTel traces, measures intent, coordination and verification drift, and works like lane correction in a car. On intent drift it triggers Accord, a four-phase protocol producing a locked intent contract agents commit to before work, and on consensus drift Concord, which resolves conflicts mid-task. Both are released and usable as a skill, a sidecar (Envoy or eBPF), or bindings over A2A, MCP and SLIM, while ordinary gRPC, MCP or A2A traffic is left untouched.
Master InvestorPioneers Don't Always Win: Dan Niles on Anthropic & OpenAI
  • A pulled Anthropic IPO would signal the AI top is in. Responding to Frost on Anthropic's S-1 filing and plan to list within weeks, Niles calls a failed deal "horrific" and says it would raise the question of whether the top came back in June. His forecast is that the deal does get done, but possibly raising less money at a much lower valuation than expected 30 to 90 days ago.
  • Anthropic is the stronger company; OpenAI gets squeezed. In Niles's view Anthropic is best placed to raise money because it is such a good enterprise tool. He argues OpenAI is stuck between Anthropic in enterprise and Google in consumer.
  • Tech pioneers often aren't the eventual winners. Niles cites AOL and Netscape in the internet era, Nokia (once 40% of smartphone share), IBM in PCs, MySpace in social media, and Webvan. He uses these to argue that the companies starting the AI cycle won't necessarily dominate it.
Mr. GlobalOil Prices Tumble On Midterm Election Results. Is This Sustainable?
  • Oil fell on the election because the administration blamed the war. Brent fell about $9 a barrel to $94 and WTI about $8; wholesale diesel fell over 30 cents a gallon and gasoline nearly 20 cents. Trump called an assessment that the Iran war cost them the election largely true, and he expects gasoline could drop below $4 a gallon and diesel below $6 within a week or so.
  • Even the lower prices sit far above normal November levels. Over the last 10 years November gasoline has averaged around $2.75 to $2.80 a gallon nationally and diesel about $3.65, and he recalls the 280s last November. Gas at $3.90 to $4 would be relief, but still well above where it would be without the crisis.
  • The drop is emotional and could reverse on a single headline. Markets price expected peace before supply improves, but global refining capacity is unchanged and a failed negotiation or attack could turn prices. He cites EIA figures: Brent started July at $72 after Hormuz reopened under the MOU, strikes resumed by July 7, and Brent was back over $100 by July 23. He worries about flare-ups before Democrats take their seats, depending on Trump's reaction.
  • Depleted inventories mean relief requires sustained surplus supply. The IEA reported in October that observed global oil inventories at end-September were more than half a billion barrels below end-February. He argues returning to normal needs production well above consumption, and notes the EIA outlook says resolving export constraints is required to replenish stocks.
  • Winter's seasonal gasoline relief will be weaker this year. Butane, used in winter blends, is at record highs, and winter shifts demand from gasoline to diesel rather than fixing supply. US gasoline demand fell over 600,000 barrels a day one week, then rebounded by over 400,000 barrels a day in the latest report.
All Things FinancialThe curtain on a government of the many, run for the few, for themselves not for the many 11-4-2026
  • Tariffs survive the Democratic wave, but vanity tariffs will go. His prediction after the "blue tsunami": the overall tariff regime stays, while punitive ones aimed at leaders — 50% on Brazil over Lula, 50% on Canada — disappear. He also floats, without forecasting it, the Electoral College giving way to the popular vote.
  • Taxpayer subsidies to data centers should buy taxpayers equity. He questions whether an administration ready to bail out AI companies still will, and whether Democrats would demand something in return. Using the reported $1.7B Texas tax break for Elon Musk as the example, he argues the subsidy should be converted into an equity stake for the state's residents.
  • Private equity marks its own valuations up to collect fees. Contrasting the dot-com model he ran on a syndicate desk — small IPO, follow-on raises, founders selling stock as a taxable event — he says private rounds are priced by agreement among insiders with no market, and funds earn 2% on the marked value. He cites OpenAI cutting its valuation to roughly $900B from $1.2T to raise $60B, and calls OpenAI and Anthropic "worthless."
  • Borrowing against inflated private shares lets founders never pay tax. Banks such as Morgan Stanley, JPMorgan and Goldman lend founders cash against private stake values, so no sale and no taxable event occurs; he dates the practice to about 2013. Biden's rejected proposal would have made each new up-round valuation taxable, which he argues is not a wealth tax but a fix for financial engineering that would also discipline inflated marks.
  • Fiscal need will force the rich to pay, eventually. He predicts that states and the country, needing money for new supply chains and factories, will end the tax-driven migration to Texas and Florida — "not today, not tomorrow." The politics of the new Congress are unknowable, but in his view the money will be asked of those who have it.