xtekky/gpt4free · error · ProviderException

Failed to obtain API key from Z.ai authentication endpoint

Error message

Failed to obtain API key from Z.ai authentication endpoint

What it means

ProviderException raised at the top of the GLM provider's main entry (create_async_generator) when cls.api_key is falsy. Unlike OAuth providers, GLM expects the API key to have been obtained beforehand (e.g. from the Z.ai authentication endpoint during setup); reaching the chat path with no key means that bootstrap step never ran or failed, and the request would be guaranteed 401 anyway.

Source

Thrown at g4f/Provider/glm/__init__.py:368

        messages: Messages,
        proxy: str = None,
        reasoning_effort: str = None,
        web_search: bool = False,
        conversation: JsonConversation = None,
        **kwargs,
    ) -> AsyncResult:
        cls.get_models()
        try:
            model = cls.get_model(model)
        except ModelNotFoundError:
            pass
        if conversation is None:
            conversation = JsonConversation(
                chat_id=None, message_id=None, parent_id=None, completion_id=None
            )

        if not cls.api_key:
            raise ProviderException(
                "Failed to obtain API key from Z.ai authentication endpoint"
            )

        conversation.parent_id = conversation.completion_id
        conversation.completion_id = str(uuid.uuid4())
        conversation.message_id = str(uuid.uuid4())

        # signature_prompt: first 500 chars of all message contents joined (pipeline.ts)
        signature_prompt = (
            "\n".join(
                m.get("content", "") if isinstance(m.get("content"), str) else ""
                for m in [messages[-1]]
            )[:500]
            or ""
        )

        # Determine model-specific features (pipeline.ts)
        is_glm5 = "glm-5" in model

View on GitHub (pinned to 973504e177)

Solutions

  1. Run the GLM/Z.ai setup step that populates the API key before any chat call (e.g. the provider's login/auth helper)
  2. Set the key explicitly: GLM.api_key = os.environ['GLM_API_KEY'] (or equivalent) at startup
  3. Add a startup assertion that cls.api_key is truthy so the failure happens at boot, not mid-request

Example fix

# before
async for chunk in GLM.create_async_generator(model, messages):
    ...
# after
from g4f.Provider.glm import GLM
GLM.api_key = os.environ["ZAI_API_KEY"]  # set during startup
async for chunk in GLM.create_async_generator(model, messages):
    ...
Defensive patterns

Strategy: validation

Validate before calling

from g4f.Provider.glm import GLM

assert GLM.api_key, 'GLM api_key not set — run Z.ai auth flow or set GLM.api_key before use'

Try / catch

from g4f.errors import ProviderException

try:
    agen = GLM.create_async_generator(model, messages)
except ProviderException as e:
    if 'Z.ai authentication' in str(e):
        GLM.api_key = obtain_zai_key()  # bootstrap, then retry once

Prevention

When it happens

Trigger: Invoking GLM chat completions before any code path populated GLM.api_key — setup skipped, the key-fetch helper failed silently earlier, or the class was used in a fresh process without re-initialization (class attribute not persisted).

Common situations: Assuming the provider self-authenticates like the OAuth providers; a failed earlier login leaving api_key None; multi-process deployments where only one worker performed setup.

Understand the failure class

Related errors


AI-assisted analysis of xtekky/gpt4free@973504e177 (2026-08-14). Data as JSON: /api/errors/4460ca03d0ba39ed. Report an issue: GitHub.