10. Claude API

13 cards

Review this deck
All cards in this deck

Install the SDK

`npm install @anthropic-ai/sdk`; `pip install anthropic`; the SDK reads `ANTHROPIC_API_KEY` automatically.

Main request fields

`model`, `max_tokens`, `system`, `messages` (starting with `user`), `tools`, `output_config`.

Reading text from a response

Filter blocks with `type === "text"`; the first block may be `thinking` (empty content by default).

Multi-turn conversations

Push the assistant's whole `response.content` (including thinking, tool_use) into the history; treat history as append-only.

`stop_reason: max_tokens`

Output was truncated; raise `max_tokens`, use streaming, or ask for shorter output; do not patch the JSON yourself.

`stop_reason: refusal`

The model refused for safety; read `stop_details`, do not treat `content` as a valid answer.

Setting effort via the API

`output_config: { effort: "low" }`; Opus 5.5 cannot turn thinking off, `budget_tokens` returns 400.

Prefill on current models

Returns 400; replace it with structured outputs `output_config: { format: { type: "json_schema", schema } }`.

Forcing tool calls on Opus 5.5, Sonnet 5.5, Fable 5.2

`tool_choice` `any`/`tool` returns 400; use `auto` + instructions + `strict: true` + check for `tool_use`.

What structured outputs guarantee

JSON syntax and schema; they do not guarantee correct content, which must be measured with evals.

Getting the full message when streaming

TypeScript `client.messages.stream(...).finalMessage()`; Python `stream.get_final_message()`.

Sending tool results

All `tool_result`s of one turn in a single user message; a failed tool returns `is_error: true`; cap the number of loop iterations.

`strict: true` on a tool

Input always matches the schema; the schema needs `additionalProperties: false` and `required`.

10. Claude API – Flashcards – Claude | Học Dev