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.
import osimport timeimport jsonimport requestsBASE_URL = os.environ["LLM_BASE_URL"] # e.g., https://api.example.com/v1, refer to official docsAPI_KEY = os.environ["LLM_API_KEY"] # Read from environment variables, do not hardcode in codeMODEL_NAME = os.environ.get("LLM_MODEL", "your-new-model-name")TIMEOUT = (5, 60) # Connection timeout 5s, read timeout 60sMAX_RETRIES = 3RETRYABLE_STATUS = {429, 500, 502, 503, 504}def build_messages(prompt, image_url=None):if not image_url:return [{"role": "user", "content": prompt}]return [{"role": "user","content": [{"type": "text", "text": prompt},{"type": "image_url", "image_url": {"url": image_url}},],}]def call_llm(prompt, image_url=None, max_tokens=2000):payload = {"model": MODEL_NAME,"messages": build_messages(prompt, image_url),"max_tokens": max_tokens,"stream": True,}headers = {"Authorization": f"Bearer {API_KEY}","Content-Type": "application/json",}url = f"{BASE_URL}/chat/completions"for attempt in range(1, MAX_RETRIES + 1):try:resp = requests.post(url, headers=headers, json=payload,timeout=TIMEOUT, stream=True)except requests.RequestException:if attempt == MAX_RETRIES:raisetime.sleep(2 ** attempt)continueif resp.status_code in RETRYABLE_STATUS and attempt < MAX_RETRIES:resp.close()time.sleep(2 ** attempt)continueif resp.status_code != 200:detail = resp.text[:500]resp.close()raise RuntimeError(f"HTTP {resp.status_code}: {detail}")return collect_stream(resp)raise RuntimeError("Retry limit exceeded")def collect_stream(resp):parts = []for raw_line in resp.iter_lines(decode_unicode=True):if not raw_line or not raw_line.startswith("data:"):continuedata = raw_line[len("data:"):].strip()if data == "[DONE]":breaktry:chunk = json.loads(data)except json.JSONDecodeError:print(f"Unparsable streaming data: {data[:200]}")continuechoices = chunk.get("choices") or []if not choices:continuedelta = choices[0].get("delta") or {}if delta.get("content"):parts.append(delta["content"])resp.close()return "".join(parts)
Key points of the code:
- Timeouts are divided into connection and read timeouts. Streaming requests have longer read times and require separate settings.
- 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.
- Parse streaming responses line by line using “data:” and stop when the end marker is reached. Log unparsable data instead of silently discarding it.
- In multimodal requests, images must be placed in the
contentlist, separate from text. Theprintstatement 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.
