← Master Index
Vol. 18 Module 18.1 Lecture

Anthropic SDK

SDKs

How This Lesson Fits the Module & Volume

You just used the OpenAI SDK as the first production client after Vol. 17’s A1111 / ComfyUI studios. Anthropic’s official SDK is the second vendor in Module 18.1: same shipping job (chat, tools, streaming), different Messages API. Teams pick Claude for long context, constitutional-style refusals, computer-use / tool reliability, or simply multi-vendor failover.

Do not learn a second “chat library.” Learn the contract differences you must abstract before FastAPI. Next: Gemini SDK, then Module 18.2 wraps all three.

Learning Objectives

By the end of this lesson, students should be able to:

  • Authenticate the anthropic Python client with ANTHROPIC_API_KEY.
  • Call messages.create with a top-level system string and user/assistant turns.
  • Read content blocks (text vs tool_use) instead of assuming OpenAI’s choices[0].message.
  • Stream events and map them to the same SSE story as Module 18.2.
  • Implement tool use with Anthropic’s block types, not copy-pasted OpenAI payloads.
  • Decide when Claude vs GPT vs Gemini is a product choice vs an adapter behind your API.
Definition

The Anthropic SDK (anthropic Python / TypeScript packages) is the official HTTP client for Claude models. The core method is the Messages API: you send model, max_tokens, optional system, and a list of messages with roles user / assistant. Responses are lists of content blocks (text, tool_use, thinking, …), not a single string field. Like OpenAI’s SDK, it does not contain weights—it only speaks HTTPS.

Contract Differences vs OpenAI

ConcernOpenAI (typical chat)Anthropic Messages
System promptA role: system messageTop-level system= (string or blocks)
Required knobsOften optional max_tokensmax_tokens is required
Assistant textmessage.content string (or parts)content[] blocks; join type=="text"
Toolstools + tool_calls + role: tooltools + tool_use / tool_result blocks
Stop / usagefinish_reason, usagestop_reason, usage.input_tokens / output_tokens
StreamingChatCompletionChunk deltasEvent stream (content_block_delta, …)

Your FastAPI layer should return your JSON ({text, usage, tool_calls}), not leak either vendor’s schema to the browser.

Messages API Sketch

import os from anthropic import Anthropic # pip install anthropic # export ANTHROPIC_API_KEY=sk-ant-... client = Anthropic() # reads ANTHROPIC_API_KEY msg = client.messages.create( model="claude-sonnet-4-5", # SKU; re-read docs before pinning max_tokens=512, system="You are a concise backend tutor. No markdown tables.", messages=[ {"role": "user", "content": "Why is max_tokens required on Messages API?"}, ], ) text = "".join(b.text for b in msg.content if b.type == "text") print(text) print(msg.stop_reason, msg.usage) # Streaming: iterate events, not OpenAI-style choice deltas with client.messages.stream( model="claude-sonnet-4-5", max_tokens=256, messages=[{"role": "user", "content": "Count to five."}], ) as stream: for text in stream.text_stream: print(text, end="", flush=True) # Tool use (Vol. 15 idea, Anthropic blocks): # tools=[{"name": "get_sku", "description": "...", "input_schema": {...}}] # if block.type == "tool_use": run(block.name, block.input); return tool_result

When Teams Reach for Claude

Strengths (typical)

  • Long-context reading / synthesis
  • Cautious refusals; computer-use / tool traces
  • Clear Messages + blocks mental model

Trade-offs

  • Different schema than OpenAI-compat servers
  • Image gen is not the DALL·E catalog job
  • Still a vendor key + ToS + rate limits

Volume map

  • Tools: Vol. 15
  • Agents: LangChain/Crew still wrap this
  • Next SDK: Gemini

Do

  • Pin model + max_tokens + system in config
  • Normalize blocks → your DTO before FastAPI
  • Meter input_tokens / output_tokens

Don’t

  • POST OpenAI messages blobs unchanged to Anthropic
  • Put ANTHROPIC_API_KEY in the frontend
  • Treat “Claude” as one frozen checkpoint

Related Lectures

LectureRole
OpenAI SDKFirst vendor; compare schemas
Gemini SDKThird vendor; multimodal native
Function callingSame loop, tool_use blocks
StreamingMap Anthropic events to SSE
FastAPIAdapter so the browser never sees vendor JSON
Common Misconception

“If I learned OpenAI I already know Anthropic—just change the base URL.” Some proxies emulate OpenAI; the native SDK does not. System prompts, required max_tokens, and content blocks will break naive ports. Second: msg.content is not always a string. Third: a bigger context window is not a license to dump an entire Comfy workflow JSON into the prompt without retrieval. Fourth: Claude is not Automatic1111—it will not run your local SD checkpoint.

Knowledge Check

  1. Short Answer: Which env var does the official Python client read by default? Answer: ANTHROPIC_API_KEY.
  2. True/False: Anthropic requires max_tokens on messages.create. Answer: True.
  3. Multiple Choice: System instructions usually go: (a) top-level system, (b) Redis only, (c) Dockerfile CMD. Answer: (a).
  4. Short Answer: How do you extract assistant prose from a Messages response? Answer: Join text from content blocks where type is text.
  5. True/False: Anthropic tool_use is the same JSON as OpenAI tool_calls. Answer: False—same idea (Vol. 15), different block schema.
  6. Multiple Choice: stop_reason is closest to OpenAI’s: (a) finish_reason, (b) CFG scale, (c) k-means k. Answer: (a).
  7. Short Answer: Why normalize vendor responses in FastAPI? Answer: So clients depend on your DTO, not Anthropic/OpenAI schemas.
  8. True/False: The Anthropic SDK includes Claude weights. Answer: False—HTTPS client only.
  9. Multiple Choice: Next SDK lecture: (a) Gemini, (b) Flask, (c) PCA. Answer: (a).
  10. Short Answer: Name one usage field to meter for Claude. Answer: input_tokens and/or output_tokens.

Key Takeaways

  • Claude is reached via the Messages API and content blocks, not OpenAI choices.
  • system + required max_tokens + stop_reason / token usage.
  • Tools = Vol. 15 loop with tool_use / tool_result.
  • Abstract vendors before Module 18.2; never leak keys or raw schemas.
  • Next: Gemini SDK.
Trainer’s Guide

Lab: Same prompt + one tool on OpenAI and Anthropic. Draw both round-trips. Write a 20-line adapter that returns {text, usage} from either client.

Whiteboard: Two columns: OpenAI message list vs Anthropic system + blocks. Circle what FastAPI should hide.

Recap: Anthropic is a second production SDK with a Messages contract. Continue with Gemini SDK.