The request succeeded. The response was valid JSON. The SDK stayed quiet. And yet the application collapsed.
This is the story of what happens when you treat an LLM provider swap like a configuration change instead of a structural gamble. You paste in a new base URL, swap the API key, and keep the request body identical because the docs promise an OpenAI-compatible endpoint. For a basic "hello world" prompt, it works. You celebrate. Then real traffic hits, and the seams split open.
The Illusion of Wire Compatibility
Compatibility at the HTTP layer is shallow. A 200 status code and a JSON body mean the server accepted your message. It does not mean the server thinks the same way as the previous one. OpenAI-compatible endpoints share a request shape, but they do not share a behavioral contract. Two providers can ingest identical payloads and return answers that diverge in subtle, destructive ways.
Your code makes assumptions. You assume message.content is a string because it always was before. You assume a tool call arrives with clean, parseable JSON. You assume finish_reason signals what you think it signals. These assumptions are invisible until they are fatal.
Consider the crash that started it all:
const text = response.choices[0].message.content.trim();
This line looks innocent. It worked for weeks. Then the new provider returned a tool call. In that moment, message.content was not an empty string. It was null. The actual payload lived inside message.tool_calls, but the parser had already moved on, calling .trim() on nothing. The API did not throw. The network layer did not complain. Your own parser killed the request.
Where Providers Quietly Diverge
The differences do not announce themselves in changelogs. They sit in the margins of the response object, waiting for edge cases.
Tool-call formatting. One provider sends tool arguments as a pre-validated JSON object. Another sends them as an escaped string inside a field. A third might split a long tool call across multiple streaming deltas, forcing you to buffer chunks before you can even see if the structure is valid. If your application expects a single parseable blob, it chokes.
Finish reasons. OpenAI uses specific strings like "stop", "length", "tool_calls", and "content_filter". A compatible provider might return "end_turn" or simply omit the field when the model hits the token ceiling. If your retry or fallback logic waits for "length" to detect truncation, it will sit idle while the user sees a half-finished answer.
Usage fields. Some providers strip token counts from streaming responses to shave milliseconds off latency. Others append usage only to the final chunk, or omit it entirely in non-streaming calls. If you charge customers per token and your accounting code expects usage.total_tokens to exist in every response object, your billing pipeline will silently record zeros.
Streaming behavior. Server-sent events are supposed to be standard, yet providers flush buffers at different frequencies. Event boundaries vary. One provider terminates a stream with a [DONE] signal. Another drops the connection cleanly with no sentinel at all. If your client blocks waiting for a specific closing marker, it hangs.
Errors and timeouts. A rate limit might arrive as a 429 with a retry-after header from one provider, and as a vague 502 from another. Some providers accept the request and then go quiet for two minutes before a network timeout. The OpenAI SDK will not magically normalize these into the exception types your logs expect.
Defensive Parsing for Unpredictable Shapes
The fix is not to trust the schema. The fix is to treat every response as a suspect.
Do not assume content is a string. Check it before you touch it.
const content = response.choices?.[0]?.message?.content;
const text = typeof content === "string" ? content.trim() : "";
Do not assume tool arguments are valid JSON. The model proposes an action. Your code must decide whether that proposal is safe enough to execute. Wrap every tool argument parse in a try-catch. If JSON.parse throws, treat the tool call as malformed garbage and route it to a failure handler. A hallucinated bracket or a missing quote should never bubble up as an unhandled exception.
If tool_calls exists but content is missing, your application should recognize a state transition. The user did not get a chat reply. The system got a work order. Those are two different paths, and your router should know the difference before it attempts string manipulation.
Behavioral Tests Before You Deploy
Пінгування ендпоінту повідомленням «hi» доводить, що мережа працює. Це нічого не говорить про ваш застосунок.
Перш ніж перенаправляти продуктивний трафік, запустіть цілеспрямований набір поведінкових тестів проти нового провайдера:
- Звичайна текстова відповідь. Переконайтеся, що
contentіснує, є рядком і може бути пропущений через ваш конвеєр санітизації без помилок приведення типів. - Примусовий виклик інструменту (tool call). Встановіть
tool_choiceнаrequired. Підтвердьте, що провайдер дотримується цього налаштування, і перевірте, чи приходитьcontentякnull, порожній рядок або відсутній ключ. Кожен із цих станів потребує власного обробника. - Некоректні аргументи інструменту. Створюйте сценарії, де модель повертає пошкоджений JSON усередині аргументів інструменту. Переконайтеся, що ваш парсер коректно відхиляє їх, а не призводить до збою воркера.
- Відповідь поблизу ліміту токенів. Вичерпайте контекстне вікно. Перевірте
finish_reason. Якщо провайдер повертає щось неочікуване під час урізання (truncation), ваша логіка підбиття підсумків або повторних спроб повинна знати, як на це реагувати.
Це інтеграційні тести, а не юніт-тести. Вони перевіряють реальний взаємозв'язок між вашим кодом і «особистістю» провайдера. Пройдіть їх, перш ніж вважати міграцію завершеною.
Створіть внутрішній контракт
Відмінності між провайдерами мають зупинятися на межі вашої мережі. Не дозволяйте їм проникати в бізнес-логіку.
Створіть шар нормалізації, який споживає сиру відповідь SDK і видає об'єкт, яким фактично володіє ваш застосунок. Перетворіть специфічні особливості провайдерів у стабільний внутрішній формат. Якщо Провайдер А повертає аргументи інструментів як рядки, а Провайдер B — як об'єкти, ваш мапер має звести обидва варіанти до вашої власної структури ToolRequest. Якщо дані про використання відсутні, ваш мапер або оцінює їх, або позначає прогалини, але ніколи не дозволяє undefined просочитися у ваші модулі відстеження витрат.
Якщо finish_reason є нестандартним, перетворіть його на власний enum кінцевих станів: COMPLETE, TRUNCATED, TOOL_CALL, FILTERED. Ваш застосунок має приймати рішення на основі цих чистих абстракцій, а не шляхом аналізу сирих рядків із стороннього сервера.
Цей шар перетворює заміну провайдера з гри «вгадай-що» (whack-a-mole) на зміну в одному файлі. Ви переписуєте мапер, запускаєте поведінкові тести та рухаєтеся далі. Ваш застосунок залишається недоторканим.
Оновлення залежності, а не зміна конфігурації
Зміна провайдерів LLM — це не те саме, що заміна ендпоінтів CDN. Це ближче до переходу з PostgreSQL на MySQL. Ви ніколи не припустите, що однаковий рядок підключення означає ідентичну поведінку запитів. Ви б тестували семантику блокувань, шляхи міграції та особливості індексації. LLM заслуговують на таку ж повагу. Це ймовірнісні системи, що маскуються під стандартні API, і їхні відповіді містять припущення щодо форматування, урізання та потоку керування, які можуть зруйнувати ваш застосунок, не викликавши жодної мережевої помилки.
Помилка ніколи не була в підключенні. Вона була в припущенні, що сумісність означає ідентичність. Це не так. Перевіряйте структуру. Тестуйте граничні випадки. Контролюйте контракт.
Джерело: The Bug Only Happened After I Switched LLM Providers
Спільнота: GyaanSetu AI on Telegram
