{"record":{"id":"6020d195c033d961","repo":"mastra-ai/mastra","slug":"cohere-api-key-is-required-pass-an-apikey-or-set","errorCode":null,"errorMessage":"Cohere API key is required. Pass an apiKey or set COHERE_API_KEY.","messagePattern":"Cohere API key is required\\. Pass an apiKey or set COHERE_API_KEY\\.","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"packages/rag/src/rerank/relevance/cohere/index.ts","lineNumber":30,"sourceCode":"      is_experimental: boolean;\n    };\n    billed_units: {\n      search_units: number;\n    };\n  };\n}\n\nexport class CohereRelevanceScorer implements RelevanceScoreProvider {\n  private model: string;\n  private apiKey?: string;\n  constructor(model: string, apiKey?: string) {\n    this.apiKey = apiKey ?? process.env.COHERE_API_KEY;\n    this.model = model;\n  }\n\n  async getRelevanceScore(query: string, text: string): Promise<number> {\n    if (!this.apiKey) {\n      throw new Error('Cohere API key is required. Pass an apiKey or set COHERE_API_KEY.');\n    }\n\n    const response = await fetch(`https://api.cohere.com/v2/rerank`, {\n      method: 'POST',\n      headers: {\n        'Content-Type': 'application/json',\n        Authorization: `Bearer ${this.apiKey}`,\n      },\n      body: JSON.stringify({\n        query,\n        documents: [text],\n        model: this.model,\n        top_n: 1,\n      }),\n    });\n\n    if (!response.ok) {\n      throw new Error(`Cohere API error: ${response.status} ${await response.text()}`);","sourceCodeStart":12,"sourceCodeEnd":48,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/packages/rag/src/rerank/relevance/cohere/index.ts#L12-L48","documentation":"The CohereRelevance re-ranker calls the Cohere rerank API and needs an API key. The key is resolved from the apiKey constructor option or the COHERE_API_KEY environment variable at construction time; getRelevanceScore throws this error immediately if neither was set.","triggerScenarios":"Instantiating new CohereRelevance() (or via a reranker config) without apiKey and without COHERE_API_KEY set in the environment, then calling getRelevanceScore.","commonSituations":"Forgetting to load .env (dotenv not imported); env var named COHERE_APIKEY or CO_API_KEY by mistake; key set only in CI secrets but missing locally.","solutions":["Set the COHERE_API_KEY environment variable (e.g. in .env loaded at startup)","Pass apiKey explicitly: new CohereRelevance({ apiKey: process.env.COHERE_API_KEY })","Verify the env var name is exactly COHERE_API_KEY and that .env is actually loaded before use"],"exampleFix":"// before\nconst reranker = new CohereRelevance({ model: 'rerank-v3.5' });\n// after\nconst reranker = new CohereRelevance({ apiKey: process.env.COHERE_API_KEY, model: 'rerank-v3.5' });","handlingStrategy":"validation","validationCode":"const apiKey = explicitApiKey ?? process.env.COHERE_API_KEY;\nif (!apiKey) throw new Error('COHERE_API_KEY is not set');","typeGuard":null,"tryCatchPattern":"try { return await reranker.getRelevanceScore(q, t); } catch (e) { if (e instanceof Error && e.message.includes('API key is required')) throw new ConfigError('Set COHERE_API_KEY'); throw e; }","preventionTips":["Load .env at process start (dotenv/config) before constructing rerankers","Fail fast at startup: assert required env vars exist once, not per request","Never rely on env vars being present in runtime environments you don't control (CI, edge, serverless)"],"tags":["configuration","api-key","cohere","environment"],"backgroundTag":"missing-env-var","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}