{"record":{"id":"d1541397aefac8e5","repo":"abhigyanpatwari/GitNexus","slug":"openai-api-key-is-required-but-was-not-provided","errorCode":null,"errorMessage":"OpenAI API key is required but was not provided","messagePattern":"OpenAI API key is required but was not provided","errorType":"validation","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"gitnexus-web/src/core/llm/agent.ts","lineNumber":179,"sourceCode":"When generating diagrams:\n- NO special characters in node labels: quotes, (), /, &, <, >\n- Wrap labels with spaces in quotes: A[\"My Label\"]\n- Use simple IDs: A, B, C or auth, db, api\n- Flowchart: graph TD or graph LR (not flowchart)\n- Keep diagrams focused — 5-10 nodes max\n- Always test mentally: would this parse?\n\nBAD:  A[User's Data] --> B(Process & Save)\nGOOD: A[\"User Data\"] --> B[\"Process and Save\"]\n`;\n\nexport const createChatModel = (config: ProviderConfig): BaseChatModel => {\n  switch (config.provider) {\n    case 'openai': {\n      const openaiConfig = config as OpenAIConfig;\n\n      if (!openaiConfig.apiKey || openaiConfig.apiKey.trim() === '') {\n        throw new Error('OpenAI API key is required but was not provided');\n      }\n\n      return new ChatOpenAI({\n        apiKey: openaiConfig.apiKey,\n        modelName: openaiConfig.model,\n        temperature: openaiConfig.temperature ?? 0.1,\n        maxTokens: openaiConfig.maxTokens,\n        configuration: {\n          apiKey: openaiConfig.apiKey,\n          ...(openaiConfig.baseUrl ? { baseURL: openaiConfig.baseUrl } : {}),\n        },\n        streaming: true,\n      });\n    }\n\n    case 'azure-openai': {\n      const azureConfig = config as AzureOpenAIConfig;\n      return new AzureChatOpenAI({","sourceCodeStart":161,"sourceCodeEnd":197,"githubUrl":"https://github.com/abhigyanpatwari/GitNexus/blob/d540b00184d71a896261ee02670da9a92d59d8f7/gitnexus-web/src/core/llm/agent.ts#L161-L197","documentation":"Thrown by createChatModel() in the 'openai' provider branch when config.apiKey is falsy or whitespace-only. The GitNexus web agent requires a non-empty OpenAI API key to instantiate ChatOpenAI; this guard fails fast at model construction rather than letting LangChain surface a cryptic 401 on the first request.","triggerScenarios":"Calling createChatModel({ provider: 'openai', apiKey: '', ... }) or omitting apiKey entirely (undefined). Also fires when apiKey contains only whitespace, since the check uses .trim() === ''.","commonSituations":"The OPENAI_API_KEY env var wasn't set when the web app loaded; the key was cleared from settings but the provider stayed 'openai'; a .env change that didn't restart the Vite dev server; deploying without provisioning the secret.","solutions":["Set the OpenAI API key in the provider settings UI (or the backing env var) and reload","Ensure the key is non-empty and non-whitespace — the guard uses .trim()","If developing locally, restart `npm run dev` after changing .env so Vite picks up the new value","Switch to a different provider (e.g. ollama, which needs no key) if you don't have an OpenAI key"],"exampleFix":"// before — key missing or empty\ncreateChatModel({ provider: 'openai', apiKey: '', model: 'gpt-4o' }); // throws\n\n// after — supply a non-empty key\ncreateChatModel({ provider: 'openai', apiKey: process.env.OPENAI_API_KEY!, model: 'gpt-4o' });","handlingStrategy":"validation","validationCode":"function hasOpenAIKey(cfg: { apiKey?: string }): boolean {\n  return typeof cfg.apiKey === 'string' && cfg.apiKey.trim().length > 0;\n}\nif (cfg.provider === 'openai' && !hasOpenAIKey(cfg)) {\n  throw new Error('Configure an OpenAI API key before starting the agent');\n}","typeGuard":"function isOpenAIConfigReady(cfg: unknown): cfg is { provider: 'openai'; apiKey: string } {\n  return typeof cfg === 'object' && cfg !== null\n    && (cfg as any).provider === 'openai'\n    && typeof (cfg as any).apiKey === 'string'\n    && (cfg as any).apiKey.trim().length > 0;\n}","tryCatchPattern":"try {\n  createChatModel({ provider: 'openai', apiKey, model });\n} catch (e) {\n  if (e instanceof Error && /OpenAI API key is required/.test(e.message)) {\n    promptUserForKey('openai');\n    return;\n  }\n  throw e;\n}","preventionTips":["Read the key from a single source (env or settings) and validate non-empty before agent construction","Restart the Vite dev server after changing .env so the new value is picked up","Treat whitespace-only keys as missing (the guard uses .trim())","Provide a no-key fallback provider (ollama) for users without an OpenAI account"],"tags":["llm","openai","config","api-key"],"backgroundTag":null,"analyzedSha":"d540b00184d71a896261ee02670da9a92d59d8f7","analyzedAt":"2026-08-12T19:50:25.132Z","schemaVersion":2},"datasetVersion":"2026-08-12T23:17:12.415Z"}