The post has been translated automatically. Original language: Russian
From November 30 to December 3, three versions of the official Python SDK for the Claude API were released.: 2.15.0, 2.16.0 and 2.17.0. These are not cosmetics. The exception you get when the connection is terminated has changed, the limits of the built-in bash tool for agents have increased, and the exchange of tokens over unencrypted HTTP is now allowed only for the local address. If the SDK is in production without a hard version commit, it's worth checking the error handling.
Disconnecting the connection now gives one exception.
In version 2.17.0, a connection terminated in the middle of a thread results in an APIConnectionError exception. This also applies to streams in JSONL format, such as the results of Message Batches. Timeouts come as its APITimeoutError subclass, and the original HTTP client error is stored in the __cause__ field. Previously, in such cases, low-level transport exceptions could get out, and developers caught them directly. Now this code needs to be translated to APIConnectionError.
Another change concerns repetitions. If the response came with the x-should-retry: false header, the dangling response body is no longer requested again. The server explicitly said that a replay is not necessary, and the SDK takes this into account.
Stricter authentication
- Token exchange over regular HTTP is allowed only for localhost, 127.0.0.1 and ::1 addresses, and only if there is an exact match. A localhost address with a subdomain now raises a CredentialsError.
- In 2.15.0, the 401 response resets the cached token even when max_retries=0.
- There is also a fixed loop in which several processes with one input updated each other's tokens in a circle.
- The default SDK headers and credentials are now visible in the APIRequest.headers. The intermediate layer can remove the anthropic-workspace-id and the anthropic-user-profile-id by assigning them the omit value.
Tools for agents: bash and file editing
Version 2.16.0 significantly changes the built-in bash tool. One command now takes 295 seconds instead of 120, and the total tool timeout has increased from 150 to 325 seconds. The output is truncated by 30,000 characters, and previously the SDK left the last 100 KiB. If the shell is killed along with background tasks due to timeout or cancellation, the tool refuses to make new calls until the restart parameter is passed.
The tool runner and environment worker now have the max_concurrent_calls option. By default, the calls go one at a time, and the None value removes the restriction. In 2.17.0, edits with replace_all, after which the file would exceed max_file_bytes (256 KiB by default), are rejected, and the file remains unchanged.
Schemes and cache of promptov
In transform_schema(), the field descriptions next to $ref are now saved in the final schema. The authors explicitly warn that the cache of promptos may change because of this. Since 2.16.0, the JSON schema is generated once, and for reassembly, Model.model_json_schema() must be passed on each call. The Claude Sonnet 4.5 models removed from support have also been removed from the SDK.
What does this mean in practice?
First of all, look in the code for intercepting HTTP client exceptions around streaming and batch results. After upgrading to 2.17.0, such blocks will stop firing, and the breakage will go higher up the stack unprocessed. If you have metrics for error types, the "breakage" and "timeout" series can be redistributed.
If the agent is working with long builds or migrations via bash, the new limits provide a margin. But check the orchestrator's own timeouts: the agent can now hold the command for almost five minutes. Separately, consider the mandatory restart after the shell is killed, otherwise the agent will receive refusals.
For those who use a local token proxy using an internal name without TLS, it is better to switch to HTTPS or to the exact localhost in advance. And compare the cost of requests before and after the update: changing schemes can temporarily reset the cache of promptos.
The draft text was prepared with the participation of AI, the facts are checked against the original source — official release notes of the Anthropic Python SDK on GitHub
С 30 ноября по 3 декабря вышли три версии официального Python SDK для API Claude: 2.15.0, 2.16.0 и 2.17.0. Это не косметика. Поменялось, какое исключение вы получаете при обрыве соединения, выросли лимиты встроенного инструмента bash для агентов, а обмен токенов по незашифрованному HTTP теперь разрешён только для локального адреса. Если SDK стоит в продакшене без жёсткой фиксации версии, стоит проверить обработку ошибок.
Обрыв соединения теперь даёт одно исключение
В версии 2.17.0 соединение, оборвавшееся посреди потока, приводит к исключению APIConnectionError. Это касается и потоков в формате JSONL, например результатов Message Batches. Таймауты приходят как его подкласс APITimeoutError, а исходная ошибка HTTP-клиента сохраняется в поле __cause__. Раньше в таких случаях наружу могли попадать низкоуровневые исключения транспорта, и разработчики ловили их напрямую. Теперь такой код нужно перевести на APIConnectionError.
Ещё одно изменение касается повторов. Если ответ пришёл с заголовком x-should-retry: false, оборванное тело ответа больше не запрашивается повторно. Сервер явно сказал, что повтор не нужен, и SDK это учитывает.
Строже аутентификация
- Обмен токенов по обычному HTTP разрешён только для адресов localhost, 127.0.0.1 и ::1, и только при точном совпадении. Адрес вида localhost с поддоменом теперь вызывает CredentialsError.
- В 2.15.0 ответ 401 сбрасывает закешированный токен даже при max_retries=0.
- Там же исправлен цикл, в котором несколько процессов с одним входом обновляли токены друг друга по кругу.
- В заголовках APIRequest.headers теперь видны заголовки и учётные данные SDK по умолчанию. Промежуточный слой может убрать anthropic-workspace-id и anthropic-user-profile-id, присвоив им значение omit.
Инструменты для агентов: bash и правка файлов
Версия 2.16.0 заметно меняет встроенный инструмент bash. На одну команду теперь отводится 295 секунд вместо 120, общий таймаут инструмента вырос со 150 до 325 секунд. Вывод обрезается по 30 000 символов, а раньше SDK оставлял последние 100 КиБ. Если по таймауту или отмене shell убивается вместе с фоновыми задачами, инструмент отказывается выполнять новые вызовы, пока не передан параметр restart.
У раннера инструментов и воркера окружения появилась опция max_concurrent_calls. По умолчанию вызовы идут по одному, а значение None снимает ограничение. В 2.17.0 правки с replace_all, после которых файл превысил бы max_file_bytes (по умолчанию 256 КиБ), отклоняются, и файл остаётся без изменений.
Схемы и кеш промптов
В transform_schema() описания полей, стоящие рядом с $ref, теперь сохраняются в итоговой схеме. Авторы прямо предупреждают, что из-за этого может смениться кеш промптов. С 2.16.0 JSON-схема генерируется один раз, а для пересборки на каждом вызове нужно передавать Model.model_json_schema(). Также из SDK убраны снятые с поддержки модели Claude Sonnet 4.5.
Что это значит на практике
Первым делом поищите в коде перехват исключений HTTP-клиента вокруг стриминга и пакетных результатов. После обновления до 2.17.0 такие блоки перестанут срабатывать, и обрыв уйдёт выше по стеку необработанным. Если у вас есть метрики по типам ошибок, ряды «обрыв» и «таймаут» могут перераспределиться.
Если агент работает с длинными сборками или миграциями через bash, новые лимиты дают запас. Но проверьте собственные таймауты оркестратора: агент теперь может держать команду почти пять минут. Отдельно учтите обязательный restart после убитого shell, иначе агент будет получать отказы.
Тем, кто ходит на локальный прокси токенов по внутреннему имени без TLS, лучше заранее перейти на HTTPS или на точный localhost. И сравните стоимость запросов до и после обновления: смена схем может на время сбросить кеш промптов.
Черновик текста подготовлен с участием ИИ, факты сверены с первоисточником — официальные release notes Anthropic Python SDK на GitHub
Comments 0
Newest Popular