{"record":{"id":"478ccf39458b9dbb","repo":"Mintplex-Labs/anything-llm","slug":"e-message-478ccf","errorCode":null,"errorMessage":"${e.message}","messagePattern":"\\$\\{e\\.message\\}","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"server/utils/AiProviders/cohere/index.js","lineNumber":91,"sourceCode":"    userPrompt = \"\",\n  }) {\n    const prompt = {\n      role: \"system\",\n      content: `${systemPrompt}${this.#appendContext(contextTexts)}`,\n    };\n    return [prompt, ...chatHistory, { role: \"user\", content: userPrompt }];\n  }\n\n  async getChatCompletion(messages = null, { temperature = 0.7 }) {\n    const result = await LLMPerformanceMonitor.measureAsyncFunction(\n      this.openai.chat.completions\n        .create({\n          model: this.model,\n          messages,\n          temperature,\n        })\n        .catch((e) => {\n          throw new Error(e.message);\n        })\n    );\n\n    if (\n      !result.output.hasOwnProperty(\"choices\") ||\n      result.output.choices.length === 0\n    )\n      return null;\n\n    const promptTokens = result.output.usage?.prompt_tokens || 0;\n    const completionTokens = result.output.usage?.completion_tokens || 0;\n    return {\n      textResponse: result.output.choices[0].message.content,\n      metrics: {\n        prompt_tokens: promptTokens,\n        completion_tokens: completionTokens,\n        total_tokens: promptTokens + completionTokens,\n        outputTps: completionTokens / result.duration,","sourceCodeStart":73,"sourceCodeEnd":109,"githubUrl":"https://github.com/Mintplex-Labs/anything-llm/blob/526360e320da9d1b36074be5ed64fe76e5bbfbbd/server/utils/AiProviders/cohere/index.js#L73-L109","documentation":"This error re-throws the underlying message from the OpenAI SDK when the Cohere OpenAI-compatible chat completions endpoint (/compatibility/v1/chat/completions) rejects the request. The .catch handler unwraps the SDK error into a plain Error, discarding the original error type, status code, and stack trace. Any failure surfaced by the OpenAI client (auth, rate limit, invalid model, malformed messages, network timeout) collapses into this single opaque message.","triggerScenarios":"Calling getChatCompletion with a model string Cohere does not serve (e.g. a deprecated command model), an expired or revoked COHERE_API_KEY, exceeding the per-minute request quota, sending message objects that violate the OpenAI schema (missing role/content), or a network interruption between the server and api.cohere.ai.","commonSituations":"Operators who rotate API keys but forget to update the AnythingLLM env config; switching the COHERE_MODEL_PREF to a model id that was retired; transient 429 rate-limiting during bulk document processing; on-prem deployments behind a proxy that strips or mangles the Authorization header.","solutions":["Read the raw e.message — it usually contains the HTTP status (e.g. '401 Unauthorized', '429 Too Many Requests') which pinpoints the cause.","Verify COHERE_API_KEY is current and has not been revoked in the Cohere dashboard.","Confirm COHERE_MODEL_PREF is a live model id listed in Cohere's /v1/models endpoint.","If the message indicates 429, reduce concurrency or implement request spacing before retrying.","Patch the catch to preserve the original error: `.catch((e) => { throw e; })` so the SDK's structured error (status, headers) survives."],"exampleFix":"// before\n.catch((e) => {\n  throw new Error(e.message);\n})\n\n// after — preserve the original SDK error (status code, response body)\n// simply rethrow, or augment context without discarding the type:\n.catch((e) => {\n  const status = e?.status ?? e?.response?.status;\n  e.message = `Cohere chat completion failed${status ? ` (HTTP ${status})` : \"\"}: ${e.message}`;\n  throw e;\n})","handlingStrategy":"try-catch","validationCode":"if (!process.env.COHERE_API_KEY) throw new Error('COHERE_API_KEY is not set');\nconst validModels = await fetch('https://api.cohere.ai/compatibility/v1/models', {\n  headers: { Authorization: `Bearer ${process.env.COHERE_API_KEY}` },\n}).then(r => r.json());\nif (!validModels.data?.some(m => m.id === modelId))\n  throw new Error(`Model ${modelId} is not available on Cohere`);","typeGuard":"/** Cohere returns an OpenAI-shaped error with a `status` field. */\nfunction isCohereApiError(e) {\n  return (\n    e instanceof Error &&\n    (typeof e.status === 'number' ||\n      /401|403|404|429|5\\d{2}/.test(e.message))\n  );\n}","tryCatchPattern":"try {\n  const result = await cohere.getChatCompletion(messages, { temperature });\n} catch (e) {\n  if (/429|rate/i.test(e.message)) {\n    await sleep(backoffMs);\n    return retry();\n  }\n  if (/401|403|unauthorized/i.test(e.message))\n    throw new Error('Cohere API key is invalid or revoked — update COHERE_API_KEY');\n  throw e;\n}","preventionTips":["Validate COHERE_API_KEY and the model id against the /v1/models endpoint before the first chat call.","Implement request spacing to avoid 429 rate limits during bulk operations.","Log the full SDK error (not just e.message) during development to preserve the HTTP status."],"tags":["cohere","openai-sdk","chat-completion","api-error","error-rewrap"],"backgroundTag":null,"analyzedSha":"526360e320da9d1b36074be5ed64fe76e5bbfbbd","analyzedAt":"2026-08-13T01:45:47.170Z","schemaVersion":2},"datasetVersion":"2026-08-13T04:17:16.726Z"}