How to Troubleshoot API Key Problems with Google, OpenAI, Azure, and OpenRouter in DeepWiki

DeepWiki resolves API key failures by validating environment variables at client initialization and surfacing provider-specific errors through the ModelClient abstraction, allowing you to diagnose issues via pre-flight checks and structured logging.

DeepWiki (AsyncFuncAI/deepwiki-open) unifies multiple LLM and embedding providers behind a consistent ModelClient interface. Because each provider—Google AI, OpenAI, Azure OpenAI, and OpenRouter—requires distinct authentication tokens, misconfigured API keys represent the most common initialization failure. This guide maps specific error patterns to their root causes in the source code and provides diagnostic scripts to verify your environment before runtime.

Understanding the ModelClient Architecture

DeepWiki abstracts provider-specific logic into subclasses of ModelClient. Each subclass reads credentials from environment variables during __init__ or dedicated initialization methods, raising ValueError immediately if keys are absent.

Provider Client Class Core File
Google AI (Gemini) GoogleEmbedderClient api/google_embedder_client.py
OpenAI OpenAIClient api/openai_client.py
Azure OpenAI AzureAIClient api/azureai_client.py
OpenRouter OpenRouterClient api/openrouter_client.py

All clients implement convert_inputs_to_api_kwargs to build provider-specific payloads and use backoff.on_exception decorators to handle transient network errors. API key validation occurs in _initialize_client (Google), init_sync_client/init_async_client (OpenAI, OpenRouter), or __init__ (Azure).

Common API Key Error Patterns by Provider

Each provider surfaces distinct error messages when authentication fails. Mapping these messages to the source code accelerates resolution.

Google AI (Gemini) – GOOGLE_API_KEY Validation

Symptom: Environment variable GOOGLE_API_KEY must be set

Root Cause: In api/google_embedder_client.py at lines 71–76, _initialize_client checks os.environ.get(self.env_api_key_name) (defaulting to "GOOGLE_API_KEY"). If the result is empty, it raises ValueError immediately.

Fix: Export the key before importing DeepWiki components:

export GOOGLE_API_KEY="your-google-api-key"

OpenAI – OPENAI_API_KEY Validation

Symptom: Environment variable OPENAI_API_KEY must be set

Root Cause: In api/openai_client.py at lines 91–96, init_sync_client and init_async_client read os.environ.get(env_api_key_name) (default "OPENAI_API_KEY"). Absence triggers ValueError.

Fix: Set the variable or pass env_api_key_name if using a custom variable name:

from api.openai_client import OpenAIClient

client = OpenAIClient(env_api_key_name="MY_CUSTOM_KEY")

Azure OpenAI – Multiple Variable Requirements

Symptom: OPENAI_API_KEY not configured or Please check that you have set the AZURE_OPENAI_API_KEY …

Root Cause: Azure requires three variables: AZURE_OPENAI_API_KEY, AZURE_OPENAI_ENDPOINT, and AZURE_OPENAI_VERSION. In api/azureai_client.py at lines 133–138, __init__ validates these; if any are missing, it raises ValueError detailing which variable is absent.

Fix: Export all three variables with valid Azure portal values:

export AZURE_OPENAI_API_KEY="your-azure-key"
export AZURE_OPENAI_ENDPOINT="https://your-resource.openai.azure.com/"
export AZURE_OPENAI_VERSION="2024-02-01"

OpenRouter – OPENROUTER_API_KEY and Streaming Errors

Symptom: OPENROUTER_API_KEY not configured or streaming error messages in the generator output

Root Cause: In api/openrouter_client.py at lines 47–50, init_sync_client checks for OPENROUTER_API_KEY. Unlike other clients, OpenRouter returns an async generator that yields error strings rather than raising exceptions immediately, allowing the UI to remain responsive.

Fix: Set the key and recreate the client:

import os
from api.openrouter_client import OpenRouterClient

os.environ["OPENROUTER_API_KEY"] = "sk-or-v1-..."
client = OpenRouterClient()  # Re-initialisation required

Diagnostic Steps and Troubleshooting Code

Pre-flight Environment Variable Check

Run this script before starting DeepWiki to validate all required variables:

import os
import sys

def verify_key(var_name: str, provider: str):
    if not os.getenv(var_name):
        print(f"[ERROR] {provider}: {var_name} is not set")
        return False
    return True

all_valid = True

# Google AI

all_valid &= verify_key("GOOGLE_API_KEY", "Google AI")

# OpenAI

all_valid &= verify_key("OPENAI_API_KEY", "OpenAI")

# Azure OpenAI

for var in ["AZURE_OPENAI_API_KEY", "AZURE_OPENAI_ENDPOINT", "AZURE_OPENAI_VERSION"]:
    all_valid &= verify_key(var, "Azure OpenAI")

# OpenRouter

all_valid &= verify_key("OPENROUTER_API_KEY", "OpenRouter")

if all_valid:
    print("[SUCCESS] All API keys configured correctly")
else:
    sys.exit(1)

Runtime Client Re-initialization

If you update environment variables in a running process, you must recreate the client instance:

import os
from api.openai_client import OpenAIClient

# Initial failure due to missing key

try:
    client = OpenAIClient()
except ValueError as e:
    print(f"Initial error: {e}")

# Update environment

os.environ["OPENAI_API_KEY"] = "sk-new-key"

# Re-create client with new key

client = OpenAIClient()
print("Client initialized successfully")

Debugging HTTP 401/403 Errors

Enable debug logging to inspect sanitized request payloads:

import logging
from api.google_embedder_client import GoogleEmbedderClient

logging.basicConfig(level=logging.DEBUG)

client = GoogleEmbedderClient()

# Debug output will show sanitized kwargs via safe_log_kwargs

Quick Checklist for Resolving API Key Issues

  1. Export variables before runtime – Set GOOGLE_API_KEY, OPENAI_API_KEY, AZURE_OPENAI_API_KEY, AZURE_OPENAI_ENDPOINT, AZURE_OPENAI_VERSION, and OPENROUTER_API_KEY before importing DeepWiki components.

  2. Validate variable names – Azure requires three distinct variables; OpenRouter and OpenAI use single keys; Google uses GOOGLE_API_KEY.

  3. Check key format – Remove whitespace, ensure OpenAI/OpenRouter keys include the sk- prefix, and verify Azure keys match the portal format.

  4. Test network connectivity – Confirm firewall/VPN rules allow outbound HTTPS to api.openai.com, generativelanguage.googleapis.com, or your Azure endpoint.

  5. Verify scopes and quota – Check provider dashboards to ensure the key has embedding and chat permissions and has not exceeded rate limits.

  6. Recreate clients after fixes – Environment variable changes require reinstantiating GoogleEmbedderClient, OpenAIClient, AzureAIClient, or OpenRouterClient.

  7. Enable debug logging – Set logging level to DEBUG to view sanitized request payloads in safe_log_kwargs and identify 401/403 root causes.

Summary

  • DeepWiki validates API keys at client initialization in api/google_embedder_client.py, api/openai_client.py, api/azureai_client.py, and api/openrouter_client.py.
  • Google, OpenAI, and Azure raise ValueError immediately when environment variables are missing, while OpenRouter returns streaming error generators.
  • Azure requires three variables (AZURE_OPENAI_API_KEY, AZURE_OPENAI_ENDPOINT, AZURE_OPENAI_VERSION), making it the most complex to configure.
  • Use pre-flight validation scripts to check environment variables before runtime, and always recreate client instances after updating keys.

Frequently Asked Questions

What environment variables does DeepWiki require for Azure OpenAI?

DeepWiki requires three environment variables for Azure OpenAI: AZURE_OPENAI_API_KEY for authentication, AZURE_OPENAI_ENDPOINT for the resource URL, and AZURE_OPENAI_VERSION for the API version. The AzureAIClient class in api/azureai_client.py validates all three at lines 133–138 and raises ValueError if any are missing.

Why does OpenRouter return streaming errors instead of raising exceptions?

Unlike other providers that raise ValueError during initialization, OpenRouterClient in api/openrouter_client.py returns an async generator that yields error messages when OPENROUTER_API_KEY is missing. This design choice keeps the UI responsive by allowing the application to handle errors gracefully within the streaming loop rather than crashing at startup.

How do I fix a 401 Unauthorized error in DeepWiki?

A 401 error indicates the API key is present but invalid or expired. First, verify the key format matches the provider requirements—OpenAI keys start with sk-, Azure keys use the portal format, and Google keys follow the Generative AI format. Then recreate the client instance after updating the environment variable, as shown in api/openai_client.py where init_sync_client reads the key at initialization time.

Can I pass API keys directly instead of using environment variables?

Yes, all DeepWiki client classes accept an optional env_api_key_name parameter that specifies which environment variable to read, or you can modify the initialization logic in api/google_embedder_client.py, api/openai_client.py, or api/openrouter_client.py to accept direct string arguments. However, environment variables remain the recommended approach to prevent accidental key exposure in logs or stack traces, as the clients use safe_log_kwargs to sanitize output.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →