fix: clear error messages for missing API keys on provider switch
Previously, switching to zhipuai/openrouter/xai via /model would throw a confusing 'OPENAI_API_KEY missing' error from the OpenAI SDK. Now createClientFromConfig validates API keys before constructing the client, throwing errors that name the correct env var (e.g. ZHIPUAI_API_KEY). Also fixes the misleading 'as anthropic' type cast in the /model handler to validate against MODEL_PROVIDERS and use the ModelProvider type.
This commit is contained in:
+18
-3
@@ -3,6 +3,21 @@ import { AnthropicClient, OpenAIClient, OllamaClient, LlamaCppClient, GeminiClie
|
||||
import type { ModelClient, RetryConfig, ModelTier } from '../models/index.js';
|
||||
import { logger } from '../logger.js';
|
||||
|
||||
/**
|
||||
* Resolve an API key from config or environment variable.
|
||||
* Throws a clear error naming the expected env var if neither source provides a key.
|
||||
*/
|
||||
function requireApiKey(cfg: ModelConfig, envVar: string): string {
|
||||
const key = cfg.api_key ?? process.env[envVar];
|
||||
if (!key) {
|
||||
throw new Error(
|
||||
`API key required for ${cfg.provider}. ` +
|
||||
`Set ${envVar} environment variable or provide api_key in config.`
|
||||
);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a ModelClient from a provider config entry.
|
||||
* Dispatches on the `provider` field so all tiers and fallback entries
|
||||
@@ -41,19 +56,19 @@ export function createClientFromConfig(cfg: ModelConfig): ModelClient {
|
||||
case 'openrouter':
|
||||
return new OpenAIClient({
|
||||
model: cfg.model,
|
||||
apiKey: cfg.api_key ?? process.env.OPENROUTER_API_KEY,
|
||||
apiKey: requireApiKey(cfg, 'OPENROUTER_API_KEY'),
|
||||
baseURL: cfg.endpoint ?? 'https://openrouter.ai/api/v1',
|
||||
});
|
||||
case 'zhipuai':
|
||||
return new OpenAIClient({
|
||||
model: cfg.model,
|
||||
apiKey: cfg.api_key ?? process.env.ZHIPUAI_API_KEY,
|
||||
apiKey: requireApiKey(cfg, 'ZHIPUAI_API_KEY'),
|
||||
baseURL: cfg.endpoint ?? 'https://api.z.ai/api/paas/v4',
|
||||
});
|
||||
case 'xai':
|
||||
return new OpenAIClient({
|
||||
model: cfg.model,
|
||||
apiKey: cfg.api_key ?? process.env.XAI_API_KEY,
|
||||
apiKey: requireApiKey(cfg, 'XAI_API_KEY'),
|
||||
baseURL: cfg.endpoint ?? 'https://api.x.ai/v1',
|
||||
});
|
||||
case 'bedrock':
|
||||
|
||||
Reference in New Issue
Block a user