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
إرسال طلب "ping" إلى نقطة النهاية (endpoint) برسالة "hi" يثبت أن الشبكة تعمل، لكنه لا يثبت شيئاً عن تطبيقك.
قبل إعادة توجيه حركة مرور الإنتاج (production traffic)، قم بتشغيل مجموعة اختبارات سلوكية مستهدفة ضد المزود الجديد:
- استجابة نصية عادية. تحقق من وجود
contentوأنه عبارة عن سلسلة نصية (string)، وأنه يمكن تمريره عبر خط معالجة التطهير (sanitization pipeline) الخاص بك دون حدوث أخطاء في تحويل النوع (casting errors). - استدعاء أداة إجباري. اضبط
tool_choiceعلىrequired. تأكد من التزام المزود بذلك، وتحقق مما إذا كانتcontentتصل كقيمةnullأو سلسلة نصية فارغة أو مفتاح مفقود. كل حالة من هذه الحالات تحتاج إلى معالج (handler) خاص بها. - وسائط أدوات غير صالحة. قم بحقن سيناريوهات حيث تعيد النماذج JSON تالفاً داخل وسائط الأدوات. تأكد من أن المحلل (parser) الخاص بك يرفضها بسلاسة بدلاً من تسبب تعطل العامل (worker).
- استجابة قريبة من حد الرموز (token limit). قم باختبار أقصى حدود نافذة السياق (context window). تحقق من
finish_reason. إذا أعاد المزود شيئاً غير متوقع عند حدوث الاقتطاع (truncation)، فيجب أن يعرف منطق التلخيص أو إعادة المحاولة لديك كيفية التصرف.
هذه اختبارات تكامل (integration tests)، وليست اختبارات وحدة (unit tests). فهي تختبر العلاقة الحقيقية بين الكود الخاص بك وشخصية المزود. اجتز هذه الاختبارات قبل أن تعتبر عملية النقل قد تمت.
بناء عقد داخلي
يجب أن تتوقف اختلافات المزودين عند حدود شبكتك. لا تسمح لها بالتسرب إلى منطق العمل (business logic).
أنشئ طبقة تسوية (normalization layer) تستهلك استجابة SDK الخام وتصدر كائناً (object) يمتلكه تطبيقك فعلياً. قم برسم خرائط للخصائص الغريبة الخاصة بالمزود إلى تنسيق داخلي مستقر. إذا كان المزود A يعيد وسائط الأدوات كسلاسل نصية والمزود B يعيد كائنات، فإن أداة الربط (mapper) الخاصة بك تقوم بتسطيح كليهما في هيكل ToolRequest الخاص بك. إذا كان الاستخدام مفقوداً، فإن أداة الربط إما تقدره أو تشير إلى الفجوة، لكنها لا تسمح أبداً بتسرب undefined إلى وحدات تتبع التكلفة لديك.
إذا كان finish_reason غير قياسي، فقم بترجمته إلى تعداد (enum) خاص بك للحالات النهائية: COMPLETE و TRUNCATED و TOOL_CALL و FILTERED. يجب أن يقرر تطبيقك ما يجب فعله بناءً على هذه التجريدات (abstractions) النظيفة، وليس عن طريق استشعار السلاسل النصية الخام من خادم طرف ثالث.
تحول هذه الطبقة عملية تبديل المزودين من لعبة مطاردة مستمرة (whack-a-mole) إلى تغيير في ملف واحد فقط. تقوم بإعادة كتابة أداة الربط، وتشغيل الاختبارات السلوكية، وتنتقل لما بعد ذلك. يظل تطبيقك دون تغيير.
ترقية تبعية، وليس مجرد تعديل إعدادات
إن تغيير مزودي LLM لا يشبه تبديل نقاط نهاية CDN. بل هو أقرب إلى تغيير قاعدة بياناتك من PostgreSQL إلى MySQL. لن تفترض أبداً أن سلسلة الاتصال نفسها تعني سلوك استعلام متطابق. ستقوم باختبار دلالات القفل (locking semantics)، ومسارات الهجرة، وغرائب الفهرسة. تستحق نماذج LLM نفس الاحترام. فهي أنظمة احتمالية تتنكر في هيئة واجهات برمجة تطبيقات (APIs) قياسية، وتحمل استجاباتها افتراضات حول التنسيق، والاقتطاع، وتدفق التحكم التي يمكن أن تحطم تطبيقك دون إطلاق خطأ شبكة واحد.
لم يكن الخطأ أبداً في الاتصال. بل كان في الافتراض بأن التوافق يعني التطابق. وهو ليس كذلك. تحقق من الهيكل. اختبر الحالات الحدية (edges). امتلك العقد.
المصدر: The Bug Only Happened After I Switched LLM Providers
المجتمع: GyaanSetu AI on Telegram
