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" به endpoint صرفاً ثابت می‌کند که شبکه کار می‌کند. این موضوع هیچ چیزی درباره اپلیکیشن شما ثابت نمی‌کند.

قبل از اینکه ترافیک عملیاتی (production) را تغییر مسیر دهید، یک مجموعه تست رفتاری هدفمند را روی ارائه‌دهنده (provider) جدید اجرا کنید:

  • پاسخ متنی معمولی. بررسی کنید که content وجود داشته باشد، از نوع رشته (string) باشد و بتواند بدون خطای تبدیل (casting errors) از خط لوله پاک‌سازی (sanitization pipeline) شما عبور کند.
  • فراخوانی ابزار اجباری (Forced tool call). مقدار tool_choice را روی required تنظیم کنید. تأیید کنید که ارائه‌دهنده به آن احترام می‌گذارد و بررسی کنید که آیا content به صورت null دریافت می‌شود، یا یک رشته خالی، و یا اینکه کلید آن وجود ندارد. هر یک از این حالت‌ها به هندلر (handler) مخصوص به خود نیاز دارند.
  • آرگومان‌های ابزار نامعتبر (Malformed tool arguments). سناریوهایی را ایجاد کنید که در آن‌ها مدل، JSON خراب را در داخل آرگومان‌های ابزار برمی‌گرداند. اطمینان حاصل کنید که پارسر (parser) شما آن‌ها را به جای کرش کردنِ ورکر (worker)، به شکلی صحیح رد می‌کند.
  • پاسخ نزدیک به محدودیت توکن. پنجره بافت (context window) را به چالش بکشید. finish_reason را بررسی کنید. اگر ارائه‌دهنده هنگام کوتاه شدن متن (truncation) چیزی غیرمنتظره برگرداند، منطق خلاصه‌سازی یا تلاش مجدد (retry logic) شما باید بداند چگونه واکنش نشان دهد.

این‌ها تست‌های یکپارچه‌سازی (integration tests) هستند، نه تست‌های واحد (unit tests). آن‌ها رابطه واقعی بین کد شما و ویژگی‌های رفتاری (personality) ارائه‌دهنده را آزمایش می‌کنند. قبل از اینکه مهاجرت را تمام‌شده بدانید، حتماً آن‌ها را پاس کنید.

یک قرارداد داخلی بسازید

تفاوت‌های ارائه‌دهندگان باید در مرز شبکه شما متوقف شوند. اجازه ندهید این تفاوت‌ها به منطق تجاری (business logic) نفوذ کنند.

یک لایه نرمال‌سازی (normalization layer) ایجاد کنید که پاسخ خام SDK را دریافت کرده و شیئی (object) تولید کند که واقعاً متعلق به اپلیکیشن شما باشد. ویژگی‌های خاص هر ارائه‌دهنده را به یک قالب داخلی پایدار نگاشت (map) کنید. اگر ارائه‌دهنده A آرگومان‌های ابزار را به صورت رشته برمی‌گرداند و ارائه‌دهنده B آن‌ها را به صورت شیء برمی‌گرداند، مپر (mapper) شما هر دو را در ساختار ToolRequest خودتان یکسان‌سازی می‌کند. اگر میزان استفاده (usage) موجود نباشد، مپر شما یا آن را تخمین می‌زند یا شکاف موجود را علامت‌گذاری می‌کند، اما هرگز اجازه نمی‌دهد undefined به ماژول‌های ردیابی هزینه شما نفوذ کند.

اگر finish_reason استاندارد نبود، آن را به enum اختصاصی خود از حالت‌های نهایی ترجمه کنید: COMPLETE ،TRUNCATED ،TOOL_CALL ،FILTERED. اپلیکیشن شما باید بر اساس این انتزاع‌های (abstractions) تمیز تصمیم بگیرد که چه کاری انجام دهد، نه با تحلیل رشته‌های خام از یک سرور شخص ثالث.

این لایه، تعویض ارائه‌دهنده را از یک بازیِ «زدن موش» (whack-a-mole) به یک تغییر در یک فایل واحد تبدیل می‌کند. شما مپر را بازنویسی می‌کنید، تست‌های رفتاری را اجرا می‌کنید و به کار خود ادامه می‌دهید. اپلیکیشن شما دست‌نخورده باقی می‌ماند.

یک ارتقای وابستگی، نه یک تغییر تنظیمات ساده

تغییر ارائه‌دهنده LLM مانند تعویض endpointهای CDN نیست. این کار بیشتر شبیه تغییر پایگاه داده از PostgreSQL به MySQL است. شما هرگز فرض نمی‌کنید که یک رشته اتصال (connection string) یکسان به معنای رفتار پرس‌وجوی (query) مشابه است. شما معناشناسی قفل‌گذاری (locking semantics)، مسیرهای مهاجرت و ویژگی‌های عجیب ایندکس‌گذاری را تست خواهید کرد. LLMها نیز شایسته همین احترام هستند. آن‌ها سیستم‌های احتمالی (probabilistic) هستند که در لباس APIهای استاندارد ظاهر شده‌اند و پاسخ‌های آن‌ها حاوی فرض‌هایی درباره قالب‌بندی، کوتاه شدن متن و جریان کنترل است که می‌تواند بدون ایجاد حتی یک خطای شبکه، اپلیکیشن شما را از هم بپاشد.

باگ هرگز در اتصال نبود؛ بلکه در این فرض بود که سازگاری به معنای یکسان بودن است. این‌طور نیست. ساختار را اعتبارسنجی کنید. حالت‌های مرزی (edges) را تست کنید. مالک قرارداد باشید.


Source: The Bug Only Happened After I Switched LLM Providers

Community: GyaanSetu AI on Telegram