Fixing 404 model_not_found on OpenAI-Compatible APIs: Engineering Checklist
Debug 404 model_not_found and 400 route errors on OpenAI-compatible gateways: /v1 URL bugs, model slugs, Responses vs Chat mismatches, and curl scripts.
Read as MarkdownYou point an existing OpenAI SDK client at a new gateway, swap the API key, deploy to staging, and the first health check comes back with:
{
"error": {
"message": "The model `gpt-6.2-sol` does not exist or you do not have access to it.",
"type": "invalid_request_error",
"code": "model_not_found"
}
}When that happens during a cutover or an on-call incident, developers usually start guessing model aliases at random. That wastes twenty minutes because 404 model_not_found (and its close cousin 400 invalid_request_error on OpenAI-compatible gateways) has only six real root causes, and half of them have nothing to do with the model name string itself.
"OpenAI-compatible" means the HTTP envelope matches (Authorization: Bearer, JSON message payloads, SSE streaming chunks). It does not guarantee identical model IDs, identical endpoint coverage across /v1/chat/completions and /v1/responses, or identical base URL parsing across SDK versions. Use this incident checklist in order; stop the moment a check fails.
The 5-minute triage matrix
Run these six checks top to bottom before changing application business logic:
| Check | What breaks silently | Fast verification | Typical fix |
|---|---|---|---|
| 1. Effective request URL | Double /v1/v1/... or missing /v1 suffix | Log full resolved URL or run curl -v | Normalize base_url to https://api.toklab.ai/v1 |
| 2. Model slug vs provider prefix | Sent openai/gpt-6.2-sol instead of gpt-6.2-sol | Query GET /v1/models with the same key | Copy exact id from /v1/models response |
| 3. Endpoint mismatch | Called /chat/completions with an image/video or Responses-only slug | Check model route table | Route to /v1/responses, /v1/images/generations, or /v1/videos/generations |
| 4. Key scope, balance, or tier | Key belongs to wrong workspace, restricted group, or stale env | Test a known baseline slug with same Authorization header | Rotate or re-scope key; verify active env vars |
| 5. SDK & framework caching | Old OPENAI_BASE_URL or memoized client singleton survives deploy | Print client.base_url at runtime | Clear singleton cache; restart worker processes |
| 6. Retired or typoed snapshot | Hardcoded preview slug or uppercase letter (GPT-6.2-Sol) | Diff slug byte-for-byte against /v1/models | Switch to canonical lowercase live ID |
Check 1: Catch base URL /v1 duplication and missing paths
The single most common false 404 during gateway migrations is a malformed URL path rather than a bad model ID. Different SDKs and wrapper libraries disagree on whether baseURL should end with /v1 or not:
- Official
openaiPython and Node SDKs expectbase_url="https://api.toklab.ai/v1"and append/chat/completions,/responses, or/modelsdirectly. - Some LangChain, LiteLLM, or custom
fetchwrappers append/v1/chat/completionsautomatically. Passinghttps://api.toklab.ai/v1into one of those wrappers producesPOST https://api.toklab.ai/v1/v1/chat/completions, which returns a generic HTTP404that looks deceptively like a missing model if your error logger only prints the status code. - Trailing slashes and reverse proxies can also break path joining (
https://api.toklab.ai/v1//responsesor a proxy stripping/v1).
Before debugging model names, print the exact outgoing URL in your HTTP client or test directly with curl -i. On TokLab, the canonical base URL is https://api.toklab.ai/v1, with no trailing slash.
Check 2: Strip or fix provider namespace prefixes
OpenAI-compatible gateways split into two naming camps:
- Vendor-prefixed registries (such as OpenRouter or LiteLLM routing tables) require prefixes like
openai/gpt-6.2-soloranthropic/claude-opus-5-5. - Flat canonical slugs (such as direct OpenAI and TokLab) expect the bare model slug, for example
gpt-6.2-sol,gpt-6.2-astra,gpt-image-2.6-sunburst, ordreamina-seedance-2-5.
If you migrate code from a prefixed router to TokLab and leave openai/ attached, the gateway receives "model": "openai/gpt-6.2-sol", fails to match any registered route, and returns model_not_found. Case sensitivity matters too: GPT-6.2-Sol is not the same string as gpt-6.2-sol, and stray whitespace from a .env file ("gpt-6.2-sol ") triggers the exact same 404.
Check 3: Verify endpoint compatibility (Responses vs Chat vs Media)
A model can exist on your account and still fail with 404 or 400 if you send it to the wrong path. Modern multi-modal gateways do not funnel every model through /v1/chat/completions:
- Language models like GPT-6.2 Sol and GPT-6.2 Astra accept both
POST /v1/responsesandPOST /v1/chat/completionson TokLab, though OpenAI's newest features (hosted multi-agent subagents, strict Responses schemas) live on/v1/responses. Sending Responses-only parameters (reasoning.effort,max_output_tokens) to/v1/chat/completions, or sending legacy sampling flags (temperature,top_p) to reasoning models, triggers400validation errors rather than404, which many wrappers collapse into a generic "model call failed" log line. - Anthropic-format models may require
POST /v1/messagesrather than/v1/chat/completionsdepending on the model contract. - Image and video models never run on
/v1/chat/completions. Callinggpt-image-2.6-flare(GPT Image 2.6),kling-image-4-0(Kling Image 4.0),dreamina-seedance-2-5, orminimax-h3against a chat endpoint fails immediately. On TokLab, image generation and editing both hitPOST /v1/images/generations, video models hitPOST /v1/videos/generations, and both return an async task ID polled atGET /v1/tasks/{id}.
Check 4: Isolate API key scope, account state, and stale env vars
OpenAI's error template deliberately groups two distinct failures into one message: "The model does not exist or you do not have access to it." Gateways mirror that wording to avoid leaking private model catalogs. That means a 404 model_not_found can actually be an authorization or configuration problem:
- Mixed-up credentials: Your staging container updated
OPENAI_BASE_URL=https://api.toklab.ai/v1whileOPENAI_API_KEYstill holds an upstream OpenAI key. The reverse happens just as often: you passTOKLAB_API_KEYwhile the SDK quietly readsOPENAI_BASE_URLfrom a default profile pointing atapi.openai.com. - Restricted key or tier: Enterprise or scoped keys may only allow a subset of models, or a newly created key may lack access to a restricted preview tier.
- Region or compliance gating: Some upstream providers restrict specific flagship checkpoints by region or billing tier even when the slug appears in public docs.
Test with a single known-good baseline slug (such as gpt-6.2-sol) using the exact bearer token from the failing process. If the baseline fails too, you have a credential or URL bug, not a model-slug bug.
Check 5: Run a 10-second curl /v1/models diagnostic against TokLab
Never debug a gateway issue exclusively inside an application framework that hides raw HTTP status codes and response bodies. Run this self-contained shell diagnostic against https://api.toklab.ai/v1 to verify your key, list live slugs, and fire a minimal smoke request in one pass:
#!/usr/bin/env bash
set -euo pipefail
BASE_URL="${TOKLAB_BASE_URL:-https://api.toklab.ai/v1}"
TARGET_MODEL="${1:-gpt-6.2-sol}"
if [[ -z "${TOKLAB_API_KEY:-}" ]]; then
echo "ERROR: TOKLAB_API_KEY is not set." >&2
exit 1
fi
echo "1) Checking /models at ${BASE_URL}/models ..."
MODELS_JSON="$(curl -sS -w "\n%{http_code}" "${BASE_URL}/models" \
-H "Authorization: Bearer ${TOKLAB_API_KEY}")"
HTTP_CODE="$(echo "$MODELS_JSON" | tail -n1)"
BODY="$(echo "$MODELS_JSON" | sed '$d')"
echo "HTTP status: ${HTTP_CODE}"
if [[ "$HTTP_CODE" != "200" ]]; then
echo "$BODY"
exit 1
fi
echo "2) Searching for exact slug '${TARGET_MODEL}' ..."
if echo "$BODY" | grep -Fq "\"id\":\"${TARGET_MODEL}\"" || echo "$BODY" | grep -Fq "\"id\": \"${TARGET_MODEL}\""; then
echo "MATCH FOUND: ${TARGET_MODEL} is active for this key."
else
echo "NO EXACT MATCH for '${TARGET_MODEL}'. Closest matches:"
echo "$BODY" | tr ',' '\n' | grep '"id"' | grep -i "${TARGET_MODEL%%-*}" | head -n 15 || true
exit 2
fi
echo "3) Sending minimal /responses smoke test ..."
curl -sS -i "${BASE_URL}/responses" \
-H "Authorization: Bearer ${TOKLAB_API_KEY}" \
-H "Content-Type: application/json" \
-d "{
\"model\": \"${TARGET_MODEL}\",
\"input\": \"Reply with the single word OK.\",
\"max_output_tokens\": 16
}"Save that snippet as check-toklab-model.sh and run bash check-toklab-model.sh gpt-6.2-sol (or any slug you are onboarding). Within seconds it proves three things independently: whether your URL and bearer token authenticate cleanly, whether the exact model ID exists in your key's live catalog, and whether the target endpoint accepts a minimal request.
Check 6: Hunt down SDK caching and silent config overrides
If curl succeeds on the exact same machine where your Node or Python service still throws model_not_found, the bug is inside your runtime configuration layer:
- Module-level client singletons: In serverless or long-lived worker pools,
new OpenAI({ baseURL: process.env.OPENAI_BASE_URL })evaluated at import time ignores environment updates applied later by a secrets loader. Instantiate the client after secrets are hydrated and logclient.baseURL(never the full API key) once on boot. - Environment variable precedence: The official OpenAI SDK automatically reads
OPENAI_BASE_URLandOPENAI_API_KEYif you omit constructor arguments. If you configureTOKLAB_API_KEYin.env.localbut forget to passbaseURLexplicitly, the SDK silently sends your TokLab key tohttps://api.openai.com/v1, or sends a TokLab-only model ID likedreamina-seedance-2-5to OpenAI, where it returns404 model_not_found. - Hardcoded fallback constants: Multi-agent frameworks frequently keep a secondary
summarizer_modelortool_modelburied inside a default config file. Your primary model string was updated togpt-6.2-sol, while a background compaction step still calls an old snapshot ID.
Distinguishing 404 model_not_found from 400, 401, and 403 in logs
Many application wrappers collapse every non-2xx gateway response into one generic exception message, which sends on-call engineers hunting for typos in a model slug that was completely valid. Log the raw HTTP status code alongside error.type, error.code, and the exact request path so your alerts point straight to the failing layer:
404with empty or HTML body (no JSONerror.code): Almost always a base URL path bug such as/v1/v1/chat/completionsor a missing/v1prefix, not a model catalog mismatch.404with JSONcode: "model_not_found": The request reached the gateway route, but the model ID did not match any active route for your key. Check provider prefixes, capitalization, whitespace, and key scope.400 invalid_request_error: The model ID resolved fine, but your payload violated the model's contract, such as passingtemperatureto a reasoning model, omittingratioon a text-to-video request, or sending a Responses field to Chat Completions.401or403: Authentication or account permission failure. Never retry401,403, or404 model_not_foundin an exponential backoff loop; retrying a bad slug five times only adds latency and noisy logs without any chance of succeeding.
Framework-specific traps when migrating SDKs
Even after your curl check passes, three popular client libraries have subtle defaults that re-introduce 404 or 400 errors during a migration:
- Vercel AI SDK (
@ai-sdk/openai): Newer versions route OpenAI provider calls to/v1/responsesby default when usingopenai('gpt-6.2-sol'), whereascreateOpenAI({ baseURL: 'https://api.toklab.ai/v1', apiKey }).chat('model-id')targets/v1/chat/completions. If a model only supports one of those routes, or if you pass Responses-only provider options into.chat(), you will see route or validation failures that look identical unless you inspect the outgoing path. - LangChain and LlamaIndex wrappers: Some wrapper versions construct URLs from
OPENAI_API_BASEwhile others readOPENAI_BASE_URL, and several older templates append/v1unconditionally. Always passbaseURLexplicitly in code rather than relying on ambiguous legacy environment variable aliases. - Multi-provider routers and proxy sidecars: If your service sits behind an internal reverse proxy or corporate egress gateway, verify that the proxy does not strip the
Authorizationheader on cross-host redirects or rewrite/v1/modelsinto a cached response from an earlier staging deploy.
Quick engineering FAQ
Why did a model slug work yesterday and return model_not_found today?
Upstream vendors retire dated preview snapshots far more aggressively than traditional REST APIs. Check GET /v1/models first; if the snapshot disappeared, switch to the stable family slug (such as gpt-6.2-sol or gpt-6.2-astra) in your central capability map.
Can I use the exact same model ID across every OpenAI-compatible provider?
No. Request and streaming schemas are portable, but model catalogs are provider-specific. Some aggregators require vendor namespaces (openai/...), while TokLab and direct OpenAI use canonical flat slugs. Keeping a thin capability-to-slug map in config isolates your application code from naming differences.
Should my retry middleware retry 404 model_not_found?
Never retry the identical model ID on 404. Either fail fast and page on-call if it is a single-model pipeline, or immediately step to the next verified fallback slug in your capability chain without waiting through exponential backoff delays.
Preventing model_not_found in production
Once the incident is resolved, add two lightweight guardrails so a renamed snapshot or misconfigured staging secret cannot take down user traffic again.
Guardrail 1: Startup catalog validation
At service boot (or in a CI smoke step right after deploy), fetch GET /v1/models and assert that every required model ID in your application config is present before accepting traffic.
import os
from openai import OpenAI
REQUIRED_MODELS = ["gpt-6.2-sol", "gpt-6.2-astra"]
def assert_models_available() -> None:
client = OpenAI(
api_key=os.environ["TOKLAB_API_KEY"],
base_url="https://api.toklab.ai/v1",
)
available = {model.id for model in client.models.list().data}
missing = [m for m in REQUIRED_MODELS if m not in available]
if missing:
raise RuntimeError(
f"Missing required TokLab models at startup: {missing}. "
f"Base URL: {client.base_url}"
)Guardrail 2: Capability-based model map with structured fallback
Never scatter raw model strings across forty source files. Map internal capability names ("default-chat", "deep-review", "hero-image") in one central config file, and only fall back on explicit model_not_found errors. Never silently swallow 400 schema errors that indicate a real bug in your payload.
const CAPABILITY_MODELS = {
defaultChat: ['gpt-6.2-sol'],
deepReview: ['gpt-6.2-astra', 'gpt-6.2-sol'],
} as const;
export function resolveModelChain(
capability: keyof typeof CAPABILITY_MODELS
): readonly string[] {
return CAPABILITY_MODELS[capability];
}Separating capability names from vendor slugs turns future model upgrades into a one-line config change instead of a repo-wide find-and-replace. To check every active slug across text, image, and video endpoints and verify live pricing before wiring your config, browse the TokLab models directory and TokLab pricing.