The post has been translated automatically. Original language: Russian
On December 2, OpenAI released the official library for Go version 4.0.0. This is a major release: the module has moved to a new path with the v4 suffix, the APIs that the service has already disabled have been removed from the library, and some of the behavior has changed so that the code on the third version can start sending other requests, although it will continue to compile. There are ten incompatible changes in the release notes, and a separate migration guide is attached to them.
What was removed
The main removal concerns the Assistants API and the beta version of Threads. According to the migration guide, the Assistants API itself was disabled on August 26, 2026, so the Beta.Assistants, Beta clients were removed from the SDK.Threads and their related types. Substitution is a combination of Conversations and Responses: a conversation is created through Conversations.New, requests go through Responses.New, streaming output is via Responses.NewStreaming.
The Videos API has also been removed: The Sora API was disabled on September 24, 2026, and there is no direct replacement. At the same time, the constants of outdated models have been removed. For three of them, the management names a replacement, for example, instead of GPT-3.5 Turbo 0613, GPT-5.6 Terra is proposed, but advises you to run the replacement on your tests first.
Security: HTTPS and webhook keys
- Authentication requests to the remote server are now sent only over HTTPS. If regular http is specified in the base address or in the OPENAI_BASE_URL variable, it must be replaced. There is a WithUnsafeAllowHTTP option for local tests, but it only allows localhost and loopback addresses.
- Outdated "raw" webhook signing keys must be at least 24 bytes long. The usual secrets with the whsec_ prefix work as before.
- Workload identity token cache is no longer shared by clients with different HTTP settings. In order for the tokens to be reused, the client or transport should be created once.
- The azidentity package no longer stretches as an SDK dependency: applications that log into Azure via Microsoft Entra ID connect it themselves.
Changes that the compiler does not catch
The most insidious part of the release is serialization. Optional Boolean fields now distinguish between "not set" and false. In the third version, if you set MaxConcurrentSubagents without Enabled, the enabled field with the value false went into the request; now it is not sent, and for the previous behavior false must be specified explicitly. Mandatory nested objects are always serialized, even empty ones.
The priority of headers has also changed: the options for a specific call now overlap the typed parameters. If the idempotence key is set both in the parameters and through WithHeader, the value will be removed from the option.
The remaining changes break the assembly, and they are easier to find: embeddings can come in a float array or a base64 string, MultiGrader accepts a dictionary of named evaluators, the compression result in Responses includes saved input messages, and the types of delegation tool selection in the Live API have been renamed.
What does this mean in practice?
The update is not limited to replacing v3 with v4 in imports. The order I would choose is:
1. Change the imports, run go mod tidy and make sure that the project is going to Go 1.26 or later — this version is required by the management.
2. Find all base addresses with http: internal proxies and gateways to LLM often work without TLS and will stop accepting the key after the update.
3. Compare the query bodies before and after the update. Tests that check only the responses will not notice the missing enabled: false or an empty object that now disappears in the request.
4. Check the places where the headers are set by both the parameter and the call option.
5. If the code still called Assistants, it no longer works on the service side, and updating the SDK is a good reason to switch to Conversations and Responses.
A separate module for Vertex remains on the third branch, its imports do not need to be changed.
The draft text was prepared with the participation of AI, the facts were checked against the original source — the official release notes and the migration guide for the OpenAI library for Go on GitHub
2 декабря OpenAI выпустила официальную библиотеку для Go версии 4.0.0. Это мажорный релиз: модуль переехал на новый путь с суффиксом v4, из библиотеки убраны API, которые сервис уже отключил, а часть поведения изменилась так, что код на третьей версии может начать отправлять другие запросы, хотя и продолжит компилироваться. В заметках к релизу десять несовместимых изменений, к ним приложено отдельное руководство по миграции.
Что убрали
Главное удаление касается Assistants API и бета-версии Threads. По данным руководства по миграции, сам Assistants API отключён 26 августа 2026 года, поэтому из SDK убраны клиенты Beta.Assistants, Beta.Threads и связанные с ними типы. Замена — связка Conversations и Responses: беседа создаётся через Conversations.New, запросы идут через Responses.New, потоковый вывод — через Responses.NewStreaming.
Убран и Videos API: Sora API отключён 24 сентября 2026 года, прямой замены нет. Заодно удалены константы устаревших моделей. Для трёх из них руководство называет замену, например вместо GPT-3.5 Turbo 0613 предлагается GPT-5.6 Terra, но советует сначала прогнать замену на своих тестах.
Безопасность: HTTPS и ключи вебхуков
- Запросы с аутентификацией к удалённому серверу теперь идут только по HTTPS. Если в базовом адресе или в переменной OPENAI_BASE_URL указан обычный http, его нужно заменить. Для локальных тестов есть опция WithUnsafeAllowHTTP, но она разрешает только localhost и loopback-адреса.
- Устаревшие «сырые» ключи подписи вебхуков должны быть не короче 24 байт. Обычные секреты с префиксом whsec_ работают как раньше.
- Кеш токенов workload identity больше не общий для клиентов с разными HTTP-настройками. Чтобы токены переиспользовались, клиента или транспорт стоит создавать один раз.
- Пакет azidentity больше не тянется как зависимость SDK: приложения, которые входят в Azure через Microsoft Entra ID, подключают его сами.
Изменения, которые не ловит компилятор
Самая коварная часть релиза — сериализация. Необязательные булевы поля теперь различают «не задано» и false. В третьей версии, если задать MaxConcurrentSubagents без Enabled, в запрос уходило поле enabled со значением false; теперь оно не отправляется, и для прежнего поведения false нужно указать явно. Обязательные вложенные объекты сериализуются всегда, даже пустые.
Поменялся и приоритет заголовков: опции конкретного вызова теперь перекрывают типизированные параметры. Если ключ идемпотентности задан и в параметрах, и через WithHeader, уйдёт значение из опции.
Остальные изменения ломают сборку, и их проще найти: эмбеддинги могут приходить массивом float или строкой base64, MultiGrader принимает словарь именованных оценщиков, результат сжатия в Responses включает сохранённые входные сообщения, переименованы типы выбора инструментов делегирования в Live API.
Что это значит на практике
Обновление не сводится к замене v3 на v4 в импортах. Порядок, который я бы выбрал:
1. Сменить импорты, выполнить go mod tidy и убедиться, что проект собирается на Go 1.26 или новее — такую версию требует руководство.
2. Найти все базовые адреса с http: внутренние прокси и шлюзы к LLM часто работают без TLS и после обновления перестанут принимать ключ.
3. Сравнить тела запросов до и после обновления. Тесты, которые проверяют только ответы, не заметят пропавшее enabled: false или пустой объект, который теперь уходит в запросе.
4. Проверить места, где заголовки задаются и параметром, и опцией вызова.
5. Если код ещё вызывал Assistants, он уже не работает на стороне сервиса, и обновление SDK — хороший повод перейти на Conversations и Responses.
Отдельный модуль для Vertex остаётся на третьей ветке, его импорты менять не нужно.
Черновик текста подготовлен с участием ИИ, факты сверены с первоисточником — официальные release notes и руководство по миграции библиотеки OpenAI для Go на GitHub
Comments 2
Newest Popular