technology · ai

AI Cheatsheets

KDP Book Manifest & Metadata
Click to Expand & CopyManifest

Use the copy buttons below to copy metadata verbatim into the Amazon KDP Publishing forms.

Book Title
Subtitle
Target Audience
BISAC Subject Code
Keywords (Comma Separated)
Book Description (HTML)
KDP Categories
  • Books > Computers & Technology > Programming > AI
  • Books > Computers & Technology > Web Development

AI Cheatsheets

One-Page Quick References from Core Syntax to Advanced Patterns

usefulcheatsheets.com

AI Cheatsheets

First Edition: 2026

Copyright © 2026 by usefulcheatsheets.com. All rights reserved.

No part of this book may be reproduced in any form or by any electronic or mechanical means, including information storage and retrieval systems, without written permission from the publisher, except for the use of brief quotations in a book review.

Publisher: usefulcheatsheets.comISBN: Not ApplicableBISAC Subject Code: COM051000

Welcome to AI

AI is a key topic in Technology development.

This reference book compiles comprehensive cheatsheets covering everything from fundamentals to advanced patterns.

Use this book as a daily reference or read it linearly to build your knowledge.

How to Use This Book

Each page is a visual cheatsheet with core concepts, practical steps, code snippets, and warnings.

usefulcheatsheets.com | Introduction
Useful Cheatsheetsusefulcheatsheets.com
Claude API Basics
Chapter 01 · Page 5
Beginner

Claude API Basics

A quick reference for making your first Claude API call, picking a model, and reading the response.

TL;DR

  1. 01Install the Anthropic SDK and set your ANTHROPIC_API_KEY variable.
  2. 02Call client.messages.create() with a model, prompt, and max_tokens.
  3. 03Check stop_reason before reading content to handle responses safely.

Tips

  1. 01Pin an exact model ID like claude-opus-4-8 in production so a later model update never silently changes your app's behavior.
  2. 02Set max_tokens generously for long or open-ended replies, since Claude stops the moment it reaches that limit, even mid-sentence.

Warnings

  1. 01max_tokens is required on every request — omitting it raises a validation error before Claude even sees your prompt.
  2. 02Never hard-code an API key in source control; load it from an environment variable or a secrets manager instead.
Notes
Useful Cheatsheetsusefulcheatsheets.com
Claude API Basics
Chapter 01 · Page 6
Beginner

Claude API Basics

(continued)

Installation and Auth

  • pip install anthropic

    Installs the Python SDK from PyPI so you can start calling Claude.

    pip install anthropic
  • npm install @anthropic-ai/sdk

    Installs the TypeScript and Node SDK for JavaScript projects.

    npm install @anthropic-ai/sdk
  • ANTHROPIC_API_KEY

    Stores your API key as an environment variable instead of hard-coding it.

    export ANTHROPIC_API_KEY="sk-ant-..."
Notes
Useful Cheatsheetsusefulcheatsheets.com
Claude API Basics
Chapter 01 · Page 7
Beginner

Claude API Basics

(continued)

Your First Request

  • Anthropic()

    Creates a client that reads the API key from the environment automatically.

    import anthropic
    client = anthropic.Anthropic()
  • messages.create()

    Sends a prompt to Claude with a model, max_tokens, and a messages array.

    message = client.messages.create(
        model="claude-opus-4-8",
        max_tokens=1024,
        messages=[{"role": "user", "content": "Explain closures in one paragraph."}]
    )
  • system parameter

    Gives Claude a persistent role or persona for the whole conversation.

    message = client.messages.create(
        model="claude-opus-4-8",
        max_tokens=1024,
        system="You are a concise technical writer.",
        messages=[{"role": "user", "content": "Explain closures."}]
    )
  • max_tokens

    Caps the response length; short answers need less, long docs need more.

    # Short answers: 256-512  |  Long docs: 4096-8192  |  Max: 128000
Notes
Useful Cheatsheetsusefulcheatsheets.com
Claude API Basics
Chapter 01 · Page 8
Beginner

Claude API Basics

(continued)

Reading the Response

  • content[0].text

    Reads the text of Claude's reply from the response object.

    print(message.content[0].text)
  • stop_reason

    Explains why generation stopped: end_turn, max_tokens, tool_use, or refusal.

    if message.stop_reason == "end_turn":
        print(message.content[0].text)
  • usage

    Reports input and output token counts so you can track cost.

    print(message.usage.input_tokens)
    print(message.usage.output_tokens)
  • message.model

    Confirms which model actually served the request.

    print(message.model)  # e.g. "claude-opus-4-8"
Notes
Useful Cheatsheetsusefulcheatsheets.com
Claude API Basics
Chapter 01 · Page 9
Beginner

Claude API Basics

(continued)

Choosing a Model

  • Claude Opus 4.8

    Best for hard reasoning and agentic tasks; the default for most new integrations.

    claude-opus-4-8
  • Claude Sonnet 5

    Near-Opus quality on coding and agentic work at a lower cost.

    claude-sonnet-5
  • Claude Haiku 4.5

    Fastest and cheapest option for high-volume tasks like tagging or routing.

    claude-haiku-4-5
  • Claude Fable 5

    Anthropic's most capable model for the hardest, longest-horizon tasks.

    claude-fable-5
Notes
Useful Cheatsheetsusefulcheatsheets.com
Claude API Basics
Chapter 01 · Page 10
Beginner

Claude API Basics

(FAQ)

FAQ

Set the ANTHROPIC_API_KEY environment variable and the SDK reads it automatically when you create a client. Pass api_key directly to the constructor only if you manage multiple keys or a secrets manager.

Start with claude-opus-4-8 for most new integrations — it balances reasoning quality with cost. Switch to claude-haiku-4-5 for high-volume, latency-sensitive tasks like tagging or routing, and reach for claude-sonnet-5 as a faster, cheaper middle ground.

stop_reason explains why Claude stopped generating: end_turn means a normal finish, max_tokens means the response got cut off, tool_use means Claude called a tool, and refusal means the safety classifier declined the request. Always check it before reading content.

The Messages API requires model, max_tokens, and messages on every request. Missing any of these — most often max_tokens — fails validation before the request is sent, so double-check your payload against the required fields first.

Append each turn to the messages array in order, alternating user and assistant roles. Claude has no memory between calls, so you must resend the full history on every request.

messages = [
    {"role": "user", "content": "What is a closure?"},
    {"role": "assistant", "content": "A closure captures variables from its enclosing scope."},
    {"role": "user", "content": "Give me a JavaScript example."},
]
Useful Cheatsheetsusefulcheatsheets.com
Claude API Basics
Chapter 01 · Page 11
Beginner

Claude API Basics

(In Practice)
In Practice

Send a Prompt, Read the Reply

Sends a single prompt to Claude, checks the stop reason, and prints the response text and token usage.

  1. 01Creating the client once and reusing it avoids re-reading credentials on every call.
  2. 02Passing max_tokens and model explicitly keeps the request valid and predictable in production.
  3. 03Checking stop_reason before touching content prevents crashes when a response is truncated or refused.
  4. 04Printing usage after every call makes token cost visible instead of a surprise on the bill.
import anthropic

client = anthropic.Anthropic()

message = client.messages.create(
    model="claude-opus-4-8",
    max_tokens=1024,
    system="You are a concise technical writer.",
    messages=[{"role": "user", "content": "Explain what a closure is, in two sentences."}]
)

if message.stop_reason == "end_turn":
    print(message.content[0].text)
elif message.stop_reason == "max_tokens":
    print("Response was cut off - increase max_tokens")
elif message.stop_reason == "refusal":
    print("Request declined by safety classifier")

print(f"Tokens used: {message.usage.input_tokens} in / {message.usage.output_tokens} out")
Takeaway

Always check stop_reason before reading content — it tells you whether the response is complete, truncated, or refused.

Useful Cheatsheetsusefulcheatsheets.com
Claude API Tool Use
Chapter 02 · Page 12
Intermediate

Claude API Tool Use

A quick reference for defining tools, running the agentic loop, and using the SDK tool runner with Claude.

TL;DR

  1. 01Define tools with a name, description, and JSON Schema input_schema.
  2. 02When stop_reason is tool_use, run the tool and send results back.
  3. 03Use the SDK's tool runner to handle the agentic loop automatically.

Tips

  1. 01Use tool_choice: {type: "tool"} to force a specific tool call instead of asking Claude for structured JSON.
  2. 02Write clear, prescriptive tool descriptions that say exactly when Claude should call them, not just what they do.

Warnings

  1. 01Always send the full assistant content block, including tool_use blocks, back in the next turn or you'll get a validation error.
  2. 02Return every tool_result for a turn in a single message — splitting them across messages trains Claude to stop making parallel calls.
Notes
Useful Cheatsheetsusefulcheatsheets.com
Claude API Tool Use
Chapter 02 · Page 13
Intermediate

Claude API Tool Use

(continued)

Define a Tool

  • input_schema

    Defines a tool's inputs as JSON Schema with a name and description.

    tools = [{
        "name": "get_weather",
        "description": "Returns current weather for a given city.",
        "input_schema": {
            "type": "object",
            "properties": {"city": {"type": "string"}},
            "required": ["city"]
        }
    }]
  • tools parameter

    Passes the tools array to messages.create() alongside the prompt.

    message = client.messages.create(
        model="claude-opus-4-8",
        max_tokens=1024,
        tools=tools,
        messages=[{"role": "user", "content": "Weather in Tokyo?"}]
    )
  • description field

    Tells Claude exactly when to call the tool, not just what it does.

    "description": "Call this when the user asks about current weather."
  • required array

    Marks which input fields Claude must always provide.

    "required": ["city"]
Notes
Useful Cheatsheetsusefulcheatsheets.com
Claude API Tool Use
Chapter 02 · Page 14
Intermediate

Claude API Tool Use

(continued)

The Agentic Loop

  • tool_use stop_reason

    Signals Claude wants to call a tool instead of finishing the reply.

    if message.stop_reason == "tool_use":
        # extract tool calls, run them, send results back
  • extract tool calls

    Filters the response content for tool_use blocks to find what Claude called.

    tool_calls = [b for b in message.content if b.type == "tool_use"]
  • tool_result block

    Packages a tool's output with the matching tool_use_id to send back.

    tool_results.append({
        "type": "tool_result",
        "tool_use_id": call.id,
        "content": str(result)
    })
  • loop until end_turn

    Repeats the call-execute-respond cycle until Claude stops calling tools.

    while message.stop_reason == "tool_use":
        message = client.messages.create(...)
Notes
Useful Cheatsheetsusefulcheatsheets.com
Claude API Tool Use
Chapter 02 · Page 15
Intermediate

Claude API Tool Use

(continued)

SDK Tool Runner

  • @beta_tool

    Turns a plain Python function into a tool with an auto-generated schema.

    from anthropic.lib.beta import beta_tool
    
    @beta_tool
    def get_weather(city: str) -> str:
        """Returns current weather for a given city."""
        return f"Sunny, 22C in {city}"
  • tool_runner()

    Runs the full call-execute-loop cycle automatically until Claude is done.

    runner = client.beta.messages.tool_runner(
        model="claude-opus-4-8",
        max_tokens=1024,
        tools=[get_weather],
        messages=[{"role": "user", "content": "Weather in Tokyo?"}]
    )
  • until_done()

    Blocks until the loop finishes and returns Claude's final response.

    final_message = runner.until_done()
    print(final_message.content[0].text)
Notes
Useful Cheatsheetsusefulcheatsheets.com
Claude API Tool Use
Chapter 02 · Page 16
Intermediate

Claude API Tool Use

(continued)

Tool Choice Control

  • tool_choice: auto

    Lets Claude decide whether to call a tool; this is the default.

    tool_choice={"type": "auto"}
  • tool_choice: tool

    Forces Claude to call one specific named tool on this turn.

    tool_choice={"type": "tool", "name": "get_weather"}
  • tool_choice: none

    Disables tool calls mid-conversation once you have the data you need.

    tool_choice={"type": "none"}
  • disable_parallel_tool_use

    Forces exactly one tool call per turn when call order matters.

    tool_choice={"type": "auto", "disable_parallel_tool_use": True}
Notes
Useful Cheatsheetsusefulcheatsheets.com
Claude API Tool Use
Chapter 02 · Page 17
Intermediate

Claude API Tool Use

(FAQ)

FAQ

Give the tool a name, a clear description of when to use it, and an input_schema written as JSON Schema. Claude reads the description to decide whether and when to call the tool, so be specific about the trigger condition, not just what the tool does.

The response comes back with stop_reason: "tool_use" and one or more tool_use content blocks containing the tool name, input, and an ID. Execute the tool yourself, then send the result back as a tool_result block with a matching tool_use_id.

Use the tool runner for most custom-tool agents — it handles the call-execute-loop cycle automatically and still gives you hooks for approval gates and logging. Write a manual loop only when you need full control over the request shape or want to avoid the beta dependency.

Set tool_choice to {"type": "tool", "name": "your_tool"} to require that exact tool on the next turn. Use {"type": "any"} to require some tool call, or {"type": "none"} to disable tools mid-conversation.

Yes — by default Claude can request multiple tool calls in a single turn, and your code should execute them and return every result in one combined message. Set disable_parallel_tool_use: true on tool_choice if your workflow needs exactly one tool call per turn.

tool_calls = [b for b in message.content if b.type == "tool_use"]
for call in tool_calls:
    print(call.name, call.input, call.id)
Useful Cheatsheetsusefulcheatsheets.com
Claude API Tool Use
Chapter 02 · Page 18
Intermediate

Claude API Tool Use

(In Practice)
In Practice

Build a Weather Tool Loop

Defines a weather tool, sends a prompt, and runs the tool_use loop until Claude returns a final text answer.

  1. 01Defining input_schema up front lets Claude know exactly what arguments the tool expects.
  2. 02Checking stop_reason for tool_use avoids treating a tool call as a finished answer.
  3. 03Sending back a tool_result with the matching tool_use_id tells Claude which call the output belongs to.
  4. 04Looping until end_turn handles the case where Claude chains more than one tool call.
import anthropic

client = anthropic.Anthropic()
tools = [{
    "name": "get_weather",
    "description": "Call this when the user asks about current weather in a city.",
    "input_schema": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}
}]

messages = [{"role": "user", "content": "What's the weather in Tokyo?"}]
message = client.messages.create(model="claude-opus-4-8", max_tokens=1024, tools=tools, messages=messages)

while message.stop_reason == "tool_use":
    tool_calls = [b for b in message.content if b.type == "tool_use"]
    messages.append({"role": "assistant", "content": message.content})
    results = [{"type": "tool_result", "tool_use_id": c.id, "content": "Sunny, 22C"} for c in tool_calls]
    messages.append({"role": "user", "content": results})
    message = client.messages.create(model="claude-opus-4-8", max_tokens=1024, tools=tools, messages=messages)

print(message.content[0].text)
Takeaway

Always resend the full assistant content block, including tool_use blocks, on the next turn.

Preview: AI Cheatsheets