pip install anthropic★Official Python SDK. Also@anthropic-ai/sdk(TS), plus Go/Java/Ruby/C#/PHP.import anthropic client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY★The zero-arg client resolves credentials from the environment — don't hardcode keys.anthropic.AsyncAnthropic()for asyncio. Auto-retries 429/5xx (max_retries=2).export ANTHROPIC_API_KEY="sk-ant-..."Get a key from console.anthropic.com. Samemessages.createsurface onAnthropicBedrock,AnthropicVertex& Foundry client classes (partner pricing).
resp = client.messages.create( model="claude-opus-5", max_tokens=16000, messages=[{"role":"user", "content":"Capital of France?"}])★The one call you use everywhere.messagesis a list of{"role","content"};max_tokensis required.for block in resp.content: if block.type == "text": print(block.text)★resp.contentis a list of content blocks (text,thinking,tool_use, ...). Check.type— don't assumecontent[0].text.resp.stop_reason · resp.usage.input_tokens / .output_tokens★stop_reason:end_turn,max_tokens,tool_use,pause_turn,refusal.usagereports billed tokens.# don't lowball max_tokens — hitting the cap truncates mid-thoughttipModel max output is 128K (Opus/Sonnet 5) / 64K (Haiku 4.5). Hitting the cap givesstop_reason: "max_tokens".
"claude-opus-5" # 1M ctx · $5 / $25 per 1M · the default★Anthropic's flagship general model — use it unless you have a reason not to. Adaptive thinking on by default. 128K max output."claude-sonnet-5" # 1M ctx · $2 / $10 · high-volume workhorse★Cheaper, still very capable — good for production volume."claude-haiku-4-5"(200K, $1/$5) for simple, speed-critical tasks."claude-fable-5-1" # 1M ctx · $10 / $50 · most capableThe most capable widely-released model for the hardest reasoning/agentic work."claude-opus-4-8"is the prior Opus ($5/$25).m = client.models.retrieve("claude-opus-5"); m.max_input_tokens [x for x in client.models.list() if x.capabilities["thinking"]...]Query live capabilities (context window, vision, thinking, effort, structured outputs) instead of hardcoding. ⚠️ Model IDs are complete — never append a date suffix.
client.messages.create(..., max_tokens=16000, system="You are a terse Python expert.", messages=[...])★Thesystemprompt is a top-level parameter (not a message). Set behavior/persona/format there.messages = [ {"role":"user", "content":"My name is Alice."}, {"role":"assistant", "content":"Hi Alice!"}, {"role":"user", "content":"What's my name?"}]★The API is stateless — send the full history each turn. First message must beuser; append the model's replies asassistant...., temperature=1.0, stop_sequences=["\n\n"]Standard sampling & stop controls. (Thinking models restricttemperature/top_p— leave them default there.)# assistant prefill returns 400 on current modelschangedPrefilling the last assistant turn is rejected on Opus 5 / Sonnet 5 / Fable / the 4.6+ family. Use structured outputs or a system instruction to control format instead.
with client.messages.stream(model="claude-opus-5", max_tokens=64000, messages=[...]) as stream: for text in stream.text_stream: print(text, end="")★text_streamyields text deltas — the chat-UI pattern. Stream anything with long input/output or highmax_tokensto avoid HTTP timeouts.final = stream.get_final_message() # complete Message when done★Use the helper to get the full assembled response instead of hand-collecting events. (Async:async with.)for event in stream: if event.type == "content_block_delta": ...Iterate raw events (message_start,content_block_deltaincl.input_json_deltafor streaming tool args) for fine-grained handling.
client.messages.create(..., thinking={"type":"adaptive", "display":"summarized"}, output_config={"effort":"high"}, messages=[...])★Adaptive thinking lets Claude decide when/how much to reason (on by default on Opus 5).display:"summarized"streams a readable summary.output_config={"effort": "low"|"medium"|"high"|"xhigh"|"max"}★Effort (defaulthigh) trades thoroughness for token spend.xhighfor coding/agentic;lowfor simple/high-volume routes.# budget_tokens is removed on current models (400 if sent)changedThe old fixed thinking-budget is gone on Opus 5 / Sonnet 5 / Fable / 4.7-4.8 — use adaptive thinking +effort. Echothinkingblocks back unchanged when continuing on the same model.