{"record":{"id":"2398039a096da285","repo":"mastra-ai/mastra","slug":"could-not-find-api-key-process-env-envvardisplay","errorCode":null,"errorMessage":"Could not find API key process.env.${envVarDisplay} for model id ${modelId}","messagePattern":"Could not find API key process\\.env\\.(.+?) for model id (.+?)","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"packages/core/src/llm/model/gateways/models-dev.ts","lineNumber":325,"sourceCode":"    return customBaseUrl || interpolateUrlTemplate(template, envVars);\n  }\n\n  getApiKey(modelId: string): Promise<string> {\n    const [provider, model] = modelId.split('/');\n    if (!provider || !model) {\n      throw new Error(`Could not identify provider from model id ${modelId}`);\n    }\n    const config = this.providerConfigs[provider];\n\n    if (!config) {\n      throw new Error(`Could not find config for provider ${provider} with model id ${modelId}`);\n    }\n\n    const apiKey = resolveApiKeyFromEnv(config.apiKeyEnvVar);\n\n    if (!apiKey) {\n      const envVarDisplay = Array.isArray(config.apiKeyEnvVar) ? config.apiKeyEnvVar.join(' or ') : config.apiKeyEnvVar;\n      throw new Error(`Could not find API key process.env.${envVarDisplay} for model id ${modelId}`);\n    }\n\n    return Promise.resolve(apiKey);\n  }\n\n  async resolveLanguageModel({\n    modelId,\n    providerId,\n    apiKey,\n    headers,\n  }: {\n    modelId: string;\n    providerId: string;\n    apiKey: string;\n    headers?: Record<string, string>;\n  }): Promise<GatewayLanguageModel> {\n    const baseURL = this.buildUrl(`${providerId}/${modelId}`);\n","sourceCodeStart":307,"sourceCodeEnd":343,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/packages/core/src/llm/model/gateways/models-dev.ts#L307-L343","documentation":"The ModelsDev gateway's getApiKey() resolves the provider's API key from environment variables listed in the provider's apiKeyEnvVar config (a single name or an array of alternates). When resolveApiKeyFromEnv finds none of them set, it throws this error naming the expected env var(s) and the model id. It exists so model resolution fails fast with a clear message instead of sending unauthenticated requests.","triggerScenarios":"Calling getApiKey(modelId) (directly or via gateway model resolution, e.g. agent('provider/model')) when none of process.env entries in config.apiKeyEnvVar for the provider are set. E.g. using 'openai/gpt-4o' without OPENAI_API_KEY, or 'netlify/...' without NETLIFY_TOKEN/NETLIFY_SITE_ID.","commonSituations":"Forgetting to load a .env file (no dotenv call, or .env in the wrong directory); setting the var in the shell but running under a service manager/CI that doesn't inherit it; deploying to serverless where secrets were never added; a typo'd env var name; switching providers and reusing the old key var; the provider requiring one of several vars but none set.","solutions":["Set the env var named in the message (or any one of the listed alternates) before starting the app: export OPENAI_API_KEY=... or put it in .env and ensure dotenv is loaded at startup.","Verify the variable is actually visible to the process: add a startup check like if (!process.env.OPENAI_API_KEY) throw ... or log Object.keys(process.env) in CI/serverless.","If the key is set under a different name, check whether the gateway supports a custom apiKeyEnvVar / provider config override and point it at your var.","If you pass an explicit API key via provider options instead of env, confirm you're using the code path that accepts it (e.g. Mastra model config with apiKey) so getApiKey's env lookup isn't reached."],"exampleFix":"// before\nconst agent = new Agent({ name: 'a', model: 'openai/gpt-4o' });\n// after (ensure the key exists before constructing/running)\nimport 'dotenv/config';\nif (!process.env.OPENAI_API_KEY) {\n  throw new Error('OPENAI_API_KEY is required for openai/gpt-4o');\n}\nconst agent = new Agent({ name: 'a', model: 'openai/gpt-4o' });","handlingStrategy":"validation","validationCode":"function requireEnv(name: string | string[]) {\n  const vars = Array.isArray(name) ? name : [name];\n  const found = vars.find(v => process.env[v]);\n  if (!found) throw new Error(`Missing required env var: ${vars.join(' or ')}`);\n  return process.env[found]!;\n}\nrequireEnv('OPENAI_API_KEY'); // call before creating/using the model","typeGuard":"function hasApiKey(vars: string[], env: NodeJS.ProcessEnv = process.env): env is NodeJS.ProcessEnv & Record<string, string> {\n  return vars.some(v => typeof env[v] === 'string' && env[v].length > 0);\n}","tryCatchPattern":"try {\n  const agent = new Agent({ model: 'openai/gpt-4o' });\n} catch (e) {\n  if (e instanceof Error && e.message.includes('Could not find API key')) {\n    console.error('Set the provider API key env var:', e.message);\n    process.exit(1);\n  }\n  throw e;\n}","preventionTips":["Load .env at the true entry point (import 'dotenv/config' first line) and commit a .env.example listing all provider keys.","Fail fast at startup with a one-time env presence check for every provider you use.","In CI/serverless, add explicit secret configuration and a pre-deploy env audit step.","Watch for near-miss names (OPENAI_KEY vs OPENAI_API_KEY) in a lint rule or startup assert."],"tags":["environment","api-key","configuration","model-gateway"],"backgroundTag":"missing-env-var","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}