Debian Codegraph @

MIGRATION.md

raw
1 # Migrating to v1
2
3 - [Upgrading](#upgrading)
4 - [Environment requirements](#environment-requirements)
5 - [The SDK is built on `httpx2`](#the-sdk-is-built-on-httpx2)
6 - [`.with_raw_response` returns the new response classes](#with_raw_response-returns-the-new-response-classes)
7 - [Removed: the legacy Text Completions API](#removed-the-legacy-text-completions-api)
8 - [Removed: deprecated request parameters](#removed-deprecated-request-parameters)
9 - [Removed: deprecated type aliases and exports](#removed-deprecated-type-aliases-and-exports)
10 - [Removed: deprecated helper arguments and behaviour](#removed-deprecated-helper-arguments-and-behaviour)
11 - [Header names are matched case-insensitively](#header-names-are-matched-case-insensitively)
12 - [bytes header values no longer work](#bytes-header-values-no-longer-work)
13 - [Bedrock: a region is now required](#bedrock-a-region-is-now-required)
14 - [Bedrock: unknown streaming events are skipped](#bedrock-unknown-streaming-events-are-skipped)
15 - [Quick reference](#quick-reference)
16
17 ## Upgrading
18
19 ```sh
20 pip install --upgrade "anthropic>=1,<2"
21 ```
22
23 If you use Claude Code, the fastest route through the rest of this guide is to let it do the edits:
24 run `/claude-api upgrade python` in your project and review the diff.
25
26 A type checker (`pyright` / `mypy`) will flag almost everything below as an error after upgrading, which makes
27 it a good checklist even if you don't normally run one.
28
29 ## Environment requirements
30
31 The minimum supported Python version has increased from 3.9 to 3.10.
32
33 Nothing else about your environment needs to change. In particular Pydantic v1 and v2 both remain supported.
34
35 ## The SDK is built on `httpx2`
36
37 The SDK's HTTP layer moved from `httpx`, which is no longer actively maintained, to [`httpx2`](https://github.com/pydantic/httpx2) - an API-compatible fork maintained by the Pydantic team.
38
39 `httpx2` is a drop-in continuation of `httpx`, with the same classes, same behaviour, and security fixes included.
40 This only affects code that hands `httpx` objects **to** the SDK or inspects the ones it gets **back**.
41
42 If you only ever pass plain values (`timeout=30.0`, `max_retries=3`, …) there is _likely_ nothing for you to do.
43 The exception is tooling that hooks `httpx` itself rather than your code — tracing / APM instrumentation and HTTP
44 mocking libraries. Those keep working but silently stop seeing the SDK's requests until you point them at `httpx2`;
45 see [Tracing, instrumentation and mocking libraries](#tracing-instrumentation-and-mocking-libraries) below.
46
47 ### Custom HTTP clients, transports, timeouts and limits
48
49 Anything you construct from `httpx` and pass to the client must now come from `httpx2`. The simplest edit is
50 to alias the import; the SDK's own re-exports (`anthropic.Timeout`, `anthropic.DefaultHttpxClient`,
51 `anthropic.DefaultAsyncHttpxClient`, `anthropic.DefaultAioHttpClient`) already point at `httpx2` and keep working
52 unchanged.
53
54 ```python
55 # Before
56 import httpx
57 from anthropic import Anthropic, DefaultHttpxClient
58
59 client = Anthropic(
60 timeout=httpx.Timeout(60.0, connect=5.0),
61 http_client=DefaultHttpxClient(
62 proxy="http://my.proxy.example",
63 transport=httpx.HTTPTransport(local_address="0.0.0.0"),
64 ),
65 )
66
67 # After
68 import httpx2 as httpx # or `import httpx2` and rename the references
69 from anthropic import Anthropic, DefaultHttpxClient
70
71 client = Anthropic(
72 timeout=httpx.Timeout(60.0, connect=5.0),
73 http_client=DefaultHttpxClient(
74 proxy="http://my.proxy.example",
75 transport=httpx.HTTPTransport(local_address="0.0.0.0"),
76 ),
77 )
78 ```
79
80 Passing an `httpx.Client` / `httpx.AsyncClient` (from the old package) as `http_client=` raises a `TypeError`
81 at construction time, so this cannot fail silently.
82
83 If you would rather not edit imports — or other code in your application still imports `httpx` and has to
84 share clients, transports or exception types with the SDK — call `httpx2.alias_httpx()` once at start-up instead.
85 It makes `import httpx` (and `import httpcore`) resolve to `httpx2` (and `httpcore2`) for the whole process. It has
86 to run before anything imports `httpx` (it raises a `RuntimeError` otherwise), and it is meant for applications:
87 a library should never call it on behalf of its users.
88
89 ```python
90 # the very first lines of your entry point
91 import httpx2
92
93 httpx2.alias_httpx()
94
95 import httpx # this is now the httpx2 module
96
97 assert httpx.Client is httpx2.Client
98 ```
99
100 ### Response and error objects
101
102 The objects the SDK returns are now `httpx2` types: `APIStatusError.response`, `APIConnectionError.request`,
103 `response.http_response` / `.headers` / `.url` on raw responses, and the `response=` argument your custom
104 `http_client` event hooks receive. They have exactly the same attributes as before; only `isinstance` checks and
105 type annotations that name `httpx.Response` / `httpx.Request` / `httpx.Headers` need to switch to `httpx2`.
106
107 ```python
108 # Before
109 def log_failure(err: anthropic.APIStatusError) -> None:
110 response: httpx.Response = err.response
111 print(response.status_code, response.headers.get("request-id"))
112
113
114 # After
115 def log_failure(err: anthropic.APIStatusError) -> None:
116 response: httpx2.Response = err.response
117 print(response.status_code, response.headers.get("request-id"))
118 ```
119
120 ### `aiohttp` support
121
122 `pip install anthropic[aiohttp]` and `http_client=DefaultAioHttpClient()` work as they did before.
123 However the `aiohttp` extra no longer installs the `httpx_aiohttp` package as it now ships inside the SDK.
124
125 ### Tracing, instrumentation and mocking libraries
126
127 Libraries that observe or stub HTTP traffic by patching `httpx` — for example OpenTelemetry's
128 `HTTPXClientInstrumentor`, Sentry's `httpx` integration, [`respx`](https://lundberg.github.io/respx/),
129 `pytest-httpx` or `vcrpy` — patch the `httpx` package, which the SDK no longer uses. These libraries can silently
130 fail, making it difficult to identify failure points. You can holistically fix this by running `httpx2.alias_httpx()`
131 before anything else imports `httpx`.
132
133 In an application, call it at the top of your entry point as shown above. Under pytest, an early plugin is the
134 least intrusive way to run it before `respx` / `pytest-httpx` and your test modules are imported:
135
136 ```python
137 # tests/_alias_httpx.py
138 import httpx2
139
140 httpx2.alias_httpx() # makes `import httpx` / `import httpcore` resolve to httpx2 / httpcore2
141 ```
142
143 ```toml
144 # pyproject.toml
145 [tool.pytest.ini_options]
146 addopts = "-p tests._alias_httpx"
147 pythonpath = ["."]
148 ```
149
150 ### Removed old `httpx` re-exports
151
152 The top-level `anthropic.Transport` and `anthropic.ProxiesTypes` exports were unused aliases of `httpx` types and
153 are gone. Use `httpx2.BaseTransport`, `httpx2.AsyncBaseTransport` and `httpx2.Proxy` (or a proxy URL string) directly.
154
155 ## `.with_raw_response` returns the new response classes
156
157 `.with_raw_response` used to return a `LegacyAPIResponse` class for both the sync and the async client. It now returns
158 the same `APIResponse` / `AsyncAPIResponse` classes that `.with_streaming_response` already used. Two things change:
159
160 **On the async client, reading the response is now async.** `parse()`, `read()`, `text()` and `json()` are
161 coroutines on `AsyncAPIResponse`.
162
163 ```python
164 # Before
165 response = await client.messages.with_raw_response.create(...)
166 print(response.headers["request-id"])
167 message = response.parse()
168
169 # After
170 response = await client.messages.with_raw_response.create(...)
171 print(response.headers["request-id"]) # metadata is still plain attribute access
172 message = await response.parse()
173 ```
174
175 **`.text` and `.content` became methods.** This applies to the sync client too. The new classes also expose
176 `json()` and the `iter_bytes()` / `iter_text()` / `iter_lines()` iterators directly, which previously meant
177 reaching for the underlying `response.http_response`.
178
179 | `LegacyAPIResponse` (before) | `APIResponse` (sync, after) | `AsyncAPIResponse` (async, after) |
180 | ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | --------------------------------------------- |
181 | `response.parse()` | `response.parse()` | `await response.parse()` |
182 | `response.text` | `response.text()` | `await response.text()` |
183 | `response.content` | `response.read()` | `await response.read()` |
184 | — (only `response.http_response.json()`) | `response.json()` | `await response.json()` |
185 | — (only `response.http_response.iter_bytes()` …) | `response.iter_bytes()` / `.iter_text()` / `.iter_lines()` | `async for chunk in response.iter_bytes():` … |
186 | `.headers`, `.status_code`, `.url`, `.request_id`, `.retries_taken`, `.http_response`, `.elapsed` | unchanged | unchanged |
187
188 ## Removed: the legacy Text Completions API
189
190 `client.completions.create()` (the `/v1/complete` endpoint), its types (`Completion`,
191 `CompletionCreateParams`) and the `anthropic.HUMAN_PROMPT` / `anthropic.AI_PROMPT` prompt constants have been
192 removed. Every current model is served through the Messages API, which has been the recommended interface since
193 2023 — see [Using the Messages API](https://platform.claude.com/docs/en/build-with-claude/working-with-messages)
194 if you still have code calling the legacy endpoint.
195
196 ## Removed: deprecated request parameters
197
198 These parameters were deprecated by the API and are no longer accepted by the generated methods (passing them is
199 a `TypeError`, and a type checker flags it). They are also gone from the per-request `params` of
200 `messages.batches.create()`, where a type checker flags the key but the SDK still forwards it at runtime:
201
202 | Method(s) | Removed parameter | Use instead |
203 | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
204 | `messages.create()`, `messages.stream()`, `messages.parse()` and their `beta.messages` counterparts, `beta.messages.tool_runner()`, and the per-request `params` of `messages.batches.create()` | `temperature`, `top_p`, `top_k` | Remove them. Current models do not use these sampling parameters; for an older model that still does, pass them through `extra_body` (see below). |
205 | `beta.messages.create()`, `beta.messages.count_tokens()`, batch request params | `output_format` | `output_config={"format": {...}}` — see [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs). The `output_format=MyModel` argument of the `parse()` / `stream()` / `count_tokens()` / `tool_runner()` **helpers** still takes a type; those helpers no longer accept a schema dict there either. |
206
207 ```python
208 # Before
209 client.beta.messages.create(
210 ...,
211 temperature=0.2,
212 output_format={"type": "json_schema", "schema": Order.model_json_schema()},
213 )
214
215 # After
216 client.beta.messages.create(
217 ...,
218 output_config={"format": {"type": "json_schema", "schema": Order.model_json_schema()}},
219 )
220 # or let the helper build the schema and parse the result:
221 client.beta.messages.parse(..., output_format=Order)
222 ```
223
224 The sampling parameters are only gone from the method signatures, not from the API: models that predate the
225 change still honour them. If you are pinned to such a model and really need a sampling setting, pass it through
226 `extra_body`, which is merged into the request JSON as-is (for `messages.batches.create()`, put the key straight into
227 the request's `params` dict):
228
229 ```python
230 # Before
231 client.messages.create(..., model="claude-sonnet-4-6", temperature=0.2)
232
233 # After
234 client.messages.create(..., model="claude-sonnet-4-6", extra_body={"temperature": 0.2})
235 ```
236
237 The `output_format=` argument of `messages.parse()` / `stream()` / `count_tokens()` and `beta.messages.parse()` /
238 `stream()` / `tool_runner()` now only accepts a **type**. `messages.stream()`,
239 `messages.count_tokens()` and `beta.messages.stream()` used to accept a raw schema dict there too and forward it as
240 `output_config.format`; that form raises a `TypeError` now. Pass schema dicts via `output_config` and keep
241 `output_format=` for classes — the `DeprecationWarning` that `beta.messages.parse()` / `stream()` / `tool_runner()` used to
242 emit for the class form is gone, since that is now the only form they take:
243
244 ```python
245 # Before
246 client.messages.count_tokens(..., output_format={"type": "json_schema", "schema": {...}})
247 client.messages.count_tokens(..., output_format=Order)
248
249 # After
250 client.messages.count_tokens(..., output_config={"format": {"type": "json_schema", "schema": {...}}})
251 client.messages.count_tokens(..., output_format=Order) # unchanged
252 ```
253
254 ## Removed: deprecated type aliases and exports
255
256 | Removed | Replacement |
257 | ------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- |
258 | `anthropic.types.beta.BetaBase64PDFBlockParam` | `anthropic.types.beta.BetaRequestDocumentBlockParam` |
259 | `anthropic.Transport`, `anthropic.ProxiesTypes` (and `anthropic._types.AsyncTransport` / `ProxiesDict`) | `httpx2.BaseTransport`, `httpx2.Proxy` (`httpx2.AsyncBaseTransport`) |
260 | `anthropic.HUMAN_PROMPT`, `anthropic.AI_PROMPT` | none — see [the Text Completions section](#removed-the-legacy-text-completions-api) |
261 | `anthropic.lib.tools.agent_toolset.READ_MAX_BYTES` | `anthropic.lib.tools.agent_toolset.DEFAULT_MAX_FILE_BYTES` |
262
263 ## Removed: deprecated helper arguments and behaviour
264
265 ### `messages.parse(stream=True)`
266
267 `parse()` always performs a non-streaming request; the `stream` argument never worked and has been removed from
268 `messages.parse()` / `beta.messages.parse()`. Use the streaming helper, which supports the same structured
269 output types:
270
271 ```python
272 # Before (which would crash)
273 client.messages.parse(..., output_format=Order, stream=True)
274
275 # After
276 with client.messages.stream(..., output_format=Order) as stream:
277 for event in stream:
278 ...
279 order = stream.get_final_message().parsed_output
280 ```
281
282 ### `tool_runner(compaction_control=...)`
283
284 Client-side compaction in the tool runner (the `compaction_control=` argument and the `CompactionControl` dict)
285 has been removed in favour of server-side compaction, which summarises the conversation inside the API instead of
286 with an extra client round-trip:
287
288 ```python
289 # Before
290 runner = client.beta.messages.tool_runner(
291 ...,
292 compaction_control={"enabled": True, "context_token_threshold": 100_000},
293 )
294
295 # After
296 runner = client.beta.messages.tool_runner(
297 ...,
298 betas=["compact-2026-01-12"],
299 context_management={
300 "edits": [
301 {"type": "compact_20260112", "trigger": {"type": "input_tokens", "value": 100_000}}
302 ]
303 },
304 )
305 ```
306
307 The trigger threshold must be at least 50,000 tokens. See [compaction](https://platform.claude.com/docs/en/build-with-claude/compaction)
308 for the other options (`pause_after_compaction`, custom `instructions`).
309
310 ### Raw bytes as `body=` on `client.get/post/put/patch/delete`
311
312 The low-level request methods accepted `bytes` for `body=` with a deprecation warning. `body=` is now always
313 JSON-serialised and raw payloads go through `content=` (which also accepts iterators for streaming uploads):
314
315 ```python
316 # Before
317 client.post("/v1/example", body=b"raw payload", cast_to=httpx.Response)
318
319 # After
320 client.post("/v1/example", content=b"raw payload", cast_to=httpx2.Response)
321 ```
322
323 ### `isinstance(stream, anthropic.Stream)` for message streams
324
325 `MessageStream` / `AsyncMessageStream` (what `client.messages.stream()` yields) stopped inheriting from
326 `Stream` / `AsyncStream` many releases ago; a compatibility shim kept `isinstance()` checks passing with a
327 `DeprecationWarning`. The shim is gone, so such checks now return `False`. Check for the concrete classes instead:
328
329 ```python
330 # Before
331 from anthropic import Stream
332
333 if isinstance(obj, Stream):
334 ...
335
336 # After
337 from anthropic.lib.streaming import MessageStream
338
339 if isinstance(obj, MessageStream):
340 ... # or `Stream` if you really mean a raw `create(stream=True)` stream
341 ```
342
343 ## Header names are matched case-insensitively
344
345 HTTP header names are case-insensitive, and the SDK now treats them that way everywhere it merges headers. An entry
346 in `default_headers`, `extra_headers`, `with_options(default_headers=...)` or the `ANTHROPIC_CUSTOM_HEADERS`
347 environment variable replaces a header of the same name whatever its casing — including the headers the SDK sets
348 itself — instead of being sent alongside it, and `omit` removes one the same way.
349
350 ```python
351 from anthropic import Anthropic, omit
352
353 client = Anthropic(default_headers={"USER-AGENT": "my-app/1.0"})
354 client.messages.create(..., extra_headers={"x-api-key": other_key, "X-Stainless-Timeout": omit})
355
356 # Before: sent `User-Agent: Anthropic/Python ...` and `USER-AGENT: my-app/1.0`, both API keys,
357 # and still sent `x-stainless-timeout`
358 # After: sends `USER-AGENT: my-app/1.0`, only `x-api-key: <other_key>`, and no `x-stainless-timeout` header
359 ```
360
361 If you relied on two casings of a name producing two header lines, send one comma-joined value instead.
362
363 ## `bytes` header values no longer work
364
365 Previously even though the type annotations did not allow it, you could pass `bytes` as header values, this now raises an error:
366
367 ```python
368 # Before (worked despite the type error)
369 client.messages.create(..., extra_headers={"X-Signature": signature_bytes})
370
371 # After
372 client.messages.create(..., extra_headers={"X-Signature": signature_bytes.decode()})
373 ```
374
375 ## Bedrock: a region is now required
376
377 `AnthropicBedrock` / `AsyncAnthropicBedrock` used to log a warning and silently fall back to `us-east-1` when no
378 AWS region could be found. They now raise a `ValueError` at construction time instead.
379
380 The region is resolved from, in order:
381
382 - the `aws_region=` argument
383 - the `AWS_REGION` / `AWS_DEFAULT_REGION` environment variables
384 - the configuration of the boto3 session for the given `aws_profile` (previously the profile argument was ignored for region lookup).
385
386 ```python
387 # Before — implicitly us-east-1 if nothing was configured
388 client = AnthropicBedrock()
389
390 # After
391 client = AnthropicBedrock(aws_region="us-east-1") # or export AWS_REGION / configure your profile
392 ```
393
394 ## Bedrock: unknown streaming events are skipped
395
396 Previously all streaming events that the Bedrock API returned would be yielded by the SDK, now they are skipped.
397
398 The only known case this affects is an `amazon-bedrock-invocationMetrics` event.
399
400 If you made use of this event please open an issue to let us know.
401
402 ## Quick reference
403
404 | You have… | Do this |
405 | ------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
406 | Python 3.9 | upgrade to Python ≥ 3.10 |
407 | `import httpx` objects passed to / received from the SDK | `import httpx2 as httpx` (or rename); annotations `httpx.X` → `httpx2.X` |
408 | `respx` / `pytest-httpx` / `vcrpy`, or OpenTelemetry / Sentry `httpx` instrumentation | run `httpx2.alias_httpx()` before anything imports `httpx` |
409 | `httpx_aiohttp` in your requirements | drop it; `anthropic[aiohttp]` is enough |
410 | `await client.….with_raw_response.…()` then `.parse()` / `.text` / `.content` | `await response.parse()` / `await response.text()` / `await response.read()` |
411 | sync `.with_raw_response` then `.text` / `.content` | `response.text()` / `response.read()` |
412 | `client.completions.create()`, `HUMAN_PROMPT`, `AI_PROMPT` | move to `client.messages.create()` |
413 | `temperature=` / `top_p=` / `top_k=` on message methods | remove; use `extra_body={"temperature": ...}` if an older model still needs it |
414 | `output_format={...}` (a schema dict) on any message method or helper | `output_config={"format": {...}}`; helpers keep `output_format=Model` for a class |
415 | `BetaBase64PDFBlockParam` | `BetaRequestDocumentBlockParam` |
416 | `anthropic.Transport` / `ProxiesTypes` (or `anthropic._types.AsyncTransport`) | `httpx2.BaseTransport` / `Proxy` / `AsyncBaseTransport` |
417 | `messages.parse(stream=True)` | `messages.stream(...)` |
418 | `tool_runner(compaction_control=...)` | server-side `context_management` compaction |
419 | `client.post(..., body=b"...")` | `content=b"..."` |
420 | `isinstance(x, Stream)` meant for message streams | `isinstance(x, MessageStream)` |
421 | two casings of one header name across `default_headers` / `extra_headers` | the later one now replaces the earlier; join the values yourself if you need both |
422 | `bytes` header values | `.decode()` them — header values must be `str` |
423 | `AnthropicBedrock()` with no region configured | pass `aws_region=` or set `AWS_REGION` |
424 | `agent_toolset.READ_MAX_BYTES` | `DEFAULT_MAX_FILE_BYTES` |