A Practical Guide to LLM API Migration: From Evaluation to Rollback

    When LLM providers deprecate old API versions, developers face challenges beyond simply updating the model name. Differences in context length, multimodal inputs, streaming responses, error codes, and billing often arise. This guide outlines a practical, step-by-step migration process covering evaluation, verification, adaptation, canary release, and rollback.

    When LLM providers take old API versions offline, most developers face issues beyond just changing the model name. Context length, multimodal input formats, streaming responses, error codes, and billing methods may all differ. This article provides a directly applicable migration process in the order of “evaluation, verification, adaptation, canary release, and rollback.”

    1. Confirm Scope Before Migration

    First, confirm three things from official announcements and documentation: the offline time of the old model, the name of the recommended new model, and deprecated fields in the old API. Record this information in a migration ticket to avoid relying solely on memory or community rumors.

    You also need to inventory your API consumers. Use your gateway or logs to count call volumes by model name, listing every service, feature, and owner that calls the old model. Uninventoried consumers are often the first to encounter issues after migration.

    2. Verify Differences Between Old and New APIs

    The table below lists items to verify one by one during migration. Refer to the provider’s official documentation for specific values; the table only provides the direction for inspection.

    Check Item Old Model Common Format New Model Items to Confirm
    Model Name Old version identifier New version identifier; whether it distinguishes between thinking and non-thinking modes
    Image Input URL, Base64, or both supported Single image size limit, supported formats, video support
    Multimodal Content String or list structure type field and nested structure for each element in the list
    Context Length Max tokens of the old model Max input and max output tokens of the new model
    Streaming Response Chunk format and end marker Consistency with old version; whether incremental field names have changed
    Session Management Reliance on server-side session ID Whether changed to client-side maintenance of historical messages
    Error Codes Rate limiting, context overflow, auth error codes New codes and corresponding retry suggestions

    If the old code relies on server-side sessions, you must migrate to client-side session management, sending necessary historical messages with each request.

    3. Code Adaptation Example

    The following example assumes the service is compatible with the common Chat Completions format. Actual URLs, field names, and authentication methods must be modified according to the official documentation. API keys should be read from environment variables, not hardcoded in code or logs.

    1. import os
    2. import time
    3. import json
    4. import requests
    5. BASE_URL = os.environ["LLM_BASE_URL"] # e.g., https://api.example.com/v1, refer to official docs
    6. API_KEY = os.environ["LLM_API_KEY"] # Read from environment variables, do not hardcode in code
    7. MODEL_NAME = os.environ.get("LLM_MODEL", "your-new-model-name")
    8. TIMEOUT = (5, 60) # Connection timeout 5s, read timeout 60s
    9. MAX_RETRIES = 3
    10. RETRYABLE_STATUS = {429, 500, 502, 503, 504}
    11. def build_messages(prompt, image_url=None):
    12. if not image_url:
    13. return [{"role": "user", "content": prompt}]
    14. return [{
    15. "role": "user",
    16. "content": [
    17. {"type": "text", "text": prompt},
    18. {"type": "image_url", "image_url": {"url": image_url}},
    19. ],
    20. }]
    21. def call_llm(prompt, image_url=None, max_tokens=2000):
    22. payload = {
    23. "model": MODEL_NAME,
    24. "messages": build_messages(prompt, image_url),
    25. "max_tokens": max_tokens,
    26. "stream": True,
    27. }
    28. headers = {
    29. "Authorization": f"Bearer {API_KEY}",
    30. "Content-Type": "application/json",
    31. }
    32. url = f"{BASE_URL}/chat/completions"
    33. for attempt in range(1, MAX_RETRIES + 1):
    34. try:
    35. resp = requests.post(url, headers=headers, json=payload,
    36. timeout=TIMEOUT, stream=True)
    37. except requests.RequestException:
    38. if attempt == MAX_RETRIES:
    39. raise
    40. time.sleep(2 ** attempt)
    41. continue
    42. if resp.status_code in RETRYABLE_STATUS and attempt < MAX_RETRIES:
    43. resp.close()
    44. time.sleep(2 ** attempt)
    45. continue
    46. if resp.status_code != 200:
    47. detail = resp.text[:500]
    48. resp.close()
    49. raise RuntimeError(f"HTTP {resp.status_code}: {detail}")
    50. return collect_stream(resp)
    51. raise RuntimeError("Retry limit exceeded")
    52. def collect_stream(resp):
    53. parts = []
    54. for raw_line in resp.iter_lines(decode_unicode=True):
    55. if not raw_line or not raw_line.startswith("data:"):
    56. continue
    57. data = raw_line[len("data:"):].strip()
    58. if data == "[DONE]":
    59. break
    60. try:
    61. chunk = json.loads(data)
    62. except json.JSONDecodeError:
    63. print(f"Unparsable streaming data: {data[:200]}")
    64. continue
    65. choices = chunk.get("choices") or []
    66. if not choices:
    67. continue
    68. delta = choices[0].get("delta") or {}
    69. if delta.get("content"):
    70. parts.append(delta["content"])
    71. resp.close()
    72. return "".join(parts)

    Key points of the code:

    1. Timeouts are divided into connection and read timeouts. Streaming requests have longer read times and require separate settings.
    2. Only retry on 429 and 5xx status codes using exponential backoff. Errors like 401 and 400 are meaningless to retry and should raise an exception immediately.
    3. Parse streaming responses line by line using “data:” and stop when the end marker is reached. Log unparsable data instead of silently discarding it.
    4. In multimodal requests, images must be placed in the content list, separate from text. The print statement in the example should be replaced with a formal logging component.

    When handling context overflow, follow this order: keep the system prompt and the latest user message, start deleting from the oldest history messages, and reserve space for max_tokens output. Token counts should be estimated using the provider’s counting method, not just roughly calculated by character count.

    4. Adjustments for Long-Context Applications

    When the new model supports a longer context, you can reduce the number of retrieval chunks and directly load larger document sections. However, long contexts increase the input tokens per request and the time to first token (TTFT). During migration, compare the two strategies in terms of accuracy, latency, and cost; do not default to full-text input just because the window is larger.

    For RAG system migrations, note three additional points. First, recall quality needs separate evaluation. With a larger window, the model might ignore content located in the middle of the text; use a test set that includes answer positions to verify. Second, documents sent to the model must be desensitized—phone numbers, ID numbers, internal accounts, and other sensitive information should not be sent to third-party services.