mastra-ai/mastra · error

Cohere API key is required. Pass an apiKey or set COHERE_API

Error message

Cohere API key is required. Pass an apiKey or set COHERE_API_KEY.

What it means

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.

Source

Thrown at packages/rag/src/rerank/relevance/cohere/index.ts:30

      is_experimental: boolean;
    };
    billed_units: {
      search_units: number;
    };
  };
}

export class CohereRelevanceScorer implements RelevanceScoreProvider {
  private model: string;
  private apiKey?: string;
  constructor(model: string, apiKey?: string) {
    this.apiKey = apiKey ?? process.env.COHERE_API_KEY;
    this.model = model;
  }

  async getRelevanceScore(query: string, text: string): Promise<number> {
    if (!this.apiKey) {
      throw new Error('Cohere API key is required. Pass an apiKey or set COHERE_API_KEY.');
    }

    const response = await fetch(`https://api.cohere.com/v2/rerank`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${this.apiKey}`,
      },
      body: JSON.stringify({
        query,
        documents: [text],
        model: this.model,
        top_n: 1,
      }),
    });

    if (!response.ok) {
      throw new Error(`Cohere API error: ${response.status} ${await response.text()}`);

View on GitHub (pinned to 75dd419e61)

Solutions

  1. Set the COHERE_API_KEY environment variable (e.g. in .env loaded at startup)
  2. Pass apiKey explicitly: new CohereRelevance({ apiKey: process.env.COHERE_API_KEY })
  3. Verify the env var name is exactly COHERE_API_KEY and that .env is actually loaded before use

Example fix

// before
const reranker = new CohereRelevance({ model: 'rerank-v3.5' });
// after
const reranker = new CohereRelevance({ apiKey: process.env.COHERE_API_KEY, model: 'rerank-v3.5' });
Defensive patterns

Strategy: validation

Validate before calling

const apiKey = explicitApiKey ?? process.env.COHERE_API_KEY;
if (!apiKey) throw new Error('COHERE_API_KEY is not set');

Try / catch

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; }

Prevention

When it happens

Trigger: Instantiating new CohereRelevance() (or via a reranker config) without apiKey and without COHERE_API_KEY set in the environment, then calling getRelevanceScore.

Common situations: 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.

Understand the failure class

Background: "environment variable is not set" and "Missing keys in environment" errors: what missing required env var messages mean and how to fix them — this error's family across 28 libraries.

Related errors


AI-assisted analysis of mastra-ai/mastra@75dd419e61 (2026-08-30). Data as JSON: /api/errors/6020d195c033d961. Report an issue: GitHub.