Skip to content

Commit be6286c

Browse files
committed
fix: unclear error when AI API key is missing or empty (#2925)
1 parent f16a214 commit be6286c

1 file changed

Lines changed: 25 additions & 1 deletion

File tree

‎src/AI/Service.cs‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,31 @@ public string ExtraHeaders
102102
public OpenAIClient GetOpenAIClient()
103103
{
104104
if (string.IsNullOrEmpty(CachedApiKey))
105-
CachedApiKey = ApiKeyManager.Get(Server)?.GetRawApiKey() ?? string.Empty;
105+
{
106+
var apiKey = ApiKeyManager.Get(Server);
107+
if (apiKey == null)
108+
{
109+
throw new InvalidOperationException(
110+
$"No API key configured for '{Server}'. " +
111+
"Please set it in Preferences → AI. " +
112+
"If you upgraded from an older version, your previous key was not migrated and must be re-configured.");
113+
}
114+
115+
// `GetRawApiKey` may return null when the environment variable is missing.
116+
CachedApiKey = apiKey.GetRawApiKey() ?? string.Empty;
117+
if (string.IsNullOrEmpty(CachedApiKey))
118+
{
119+
throw new InvalidOperationException(apiKey.Storage switch
120+
{
121+
ApiKeyStorage.EnvironmentVariable =>
122+
$"Environment variable '{apiKey.KeyToAccess}' is not set or is empty.",
123+
ApiKeyStorage.SystemKeychain =>
124+
$"Failed to read the API key for '{Server}' from the system keychain.",
125+
_ =>
126+
$"The API key for '{Server}' is empty. Please re-configure it in Preferences → AI.",
127+
});
128+
}
129+
}
106130

107131
var credential = new ApiKeyCredential(CachedApiKey);
108132
if (Server.Contains("openai.azure.com/", StringComparison.Ordinal))

0 commit comments

Comments
 (0)