{"record":{"id":"d99dff1be7d5fed3","repo":"rohitg00/agentmemory","slug":"openai-api-error-response-status-text","errorCode":null,"errorMessage":"OpenAI API error (${response.status}): ${text}","messagePattern":"OpenAI API error \\((.+?)\\): (.+?)","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"src/providers/openai.ts","lineNumber":128,"sourceCode":"          method: \"POST\",\n          headers: buildAuthHeaders(this.apiKey, this.isAzure),\n          body: JSON.stringify(body),\n        },\n        this.timeoutMs,\n      );\n    } catch (err) {\n      const aborted = err instanceof Error && err.name === \"AbortError\";\n      if (aborted) {\n        throw new Error(\n          `OpenAI API request timed out after ${this.timeoutMs}ms — set OPENAI_TIMEOUT_MS (or AGENTMEMORY_LLM_TIMEOUT_MS) to raise the bound or check the provider status.`,\n        );\n      }\n      throw err;\n    }\n\n    if (!response.ok) {\n      const text = await response.text();\n      throw new Error(`OpenAI API error (${response.status}): ${text}`);\n    }\n\n    const data = (await response.json()) as {\n      choices?: Array<{\n        message?: { content?: string; reasoning?: string; reasoning_content?: string };\n      }>;\n    };\n    const message = data.choices?.[0]?.message;\n    const content = message?.content;\n    if (content) {\n      return content;\n    }\n    // Fallback: some thinking models return reasoning but no content.\n    // DeepSeek V4 / Qwen3 / GLM / Kimi return `reasoning_content`;\n    // older OpenAI o-series + some compatibles return `reasoning`. #627\n    const reasoning = message?.reasoning ?? message?.reasoning_content;\n    if (reasoning) {\n      return reasoning;","sourceCodeStart":110,"sourceCodeEnd":146,"githubUrl":"https://github.com/rohitg00/agentmemory/blob/e04ba88819c365c9acf9d6661ea802143e728bd6/src/providers/openai.ts#L110-L146","documentation":"OpenAIProvider.call throws this when the Chat Completions HTTP response status is not ok; the raw response body text is included for diagnosis. It surfaces upstream rejections — 401 auth, 404 unknown model, 429 quota/rate limit, 5xx outage — with the provider's own error payload appended.","triggerScenarios":"compress() or summarize() via OpenAIProvider.call() where fetch resolves with response.ok === false; wrong OPENAI_API_KEY, nonexistent or deprecated model id, quota exhausted, or OpenAI-side 5xx.","commonSituations":"Revoked/rotated key not updated in env (401 'Incorrect API key'); model name typo like 'gpt-4o-mni' (404); hitting usage tier limits (429); org billing issue (insufficient_quota); pointing OPENAI_BASE_URL at a compatible endpoint that rejects the request shape.","solutions":["Inspect the appended response text for OpenAI's error code and message","If 401: regenerate and re-export OPENAI_API_KEY","If 404: correct the config.model to a valid model id","If 429/insufficient_quota: wait, add billing credit, or lower request rate; retry with backoff","If 5xx: retry later or switch provider via createFallbackProvider"],"exampleFix":"// before\nmodel: 'gpt-4o-mni' // OpenAI API error (404): model not found\n\n// after\nmodel: 'gpt-4o-mini'","handlingStrategy":"try-catch","validationCode":"if (!process.env.OPENAI_API_KEY) throw new Error('OPENAI_API_KEY not set');\nif (!/^[a-z0-9.\\/-]+$/i.test(config.model ?? '')) throw new Error(`Suspicious model id: ${config.model}`);","typeGuard":null,"tryCatchPattern":"try {\n  return await provider.call(prompt);\n} catch (e) {\n  const m = /OpenAI API error \\((\\d+)\\)/.exec(String(e));\n  const status = m ? Number(m[1]) : 0;\n  if (status === 429 || status >= 500) return retryWithBackoff(() => provider.call(prompt));\n  if (status === 401 || status === 404) throw new Error(`OpenAI config problem (${status}); check key/model`, { cause: e });\n  throw e;\n}","preventionTips":["Rotate keys centrally and redeploy rather than editing prod env by hand","Pin and periodically revalidate the model id against the OpenAI catalog","Track usage/quota and alert before 429/insufficient_quota hits","Test the provider with a 1-token request at service startup to fail fast on auth/model errors"],"tags":["network","api-error","openai","http-status"],"backgroundTag":"upstream-api-error","analyzedSha":"e04ba88819c365c9acf9d6661ea802143e728bd6","analyzedAt":"2026-08-30T01:07:40.754Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}