{"record":{"id":"4460ca03d0ba39ed","repo":"xtekky/gpt4free","slug":"failed-to-obtain-api-key-from-z-ai-authentication","errorCode":null,"errorMessage":"Failed to obtain API key from Z.ai authentication endpoint","messagePattern":"Failed to obtain API key from Z\\.ai authentication endpoint","errorType":"exception","errorClass":"ProviderException","httpStatus":null,"severity":"error","filePath":"g4f/Provider/glm/__init__.py","lineNumber":368,"sourceCode":"        messages: Messages,\n        proxy: str = None,\n        reasoning_effort: str = None,\n        web_search: bool = False,\n        conversation: JsonConversation = None,\n        **kwargs,\n    ) -> AsyncResult:\n        cls.get_models()\n        try:\n            model = cls.get_model(model)\n        except ModelNotFoundError:\n            pass\n        if conversation is None:\n            conversation = JsonConversation(\n                chat_id=None, message_id=None, parent_id=None, completion_id=None\n            )\n\n        if not cls.api_key:\n            raise ProviderException(\n                \"Failed to obtain API key from Z.ai authentication endpoint\"\n            )\n\n        conversation.parent_id = conversation.completion_id\n        conversation.completion_id = str(uuid.uuid4())\n        conversation.message_id = str(uuid.uuid4())\n\n        # signature_prompt: first 500 chars of all message contents joined (pipeline.ts)\n        signature_prompt = (\n            \"\\n\".join(\n                m.get(\"content\", \"\") if isinstance(m.get(\"content\"), str) else \"\"\n                for m in [messages[-1]]\n            )[:500]\n            or \"\"\n        )\n\n        # Determine model-specific features (pipeline.ts)\n        is_glm5 = \"glm-5\" in model","sourceCodeStart":350,"sourceCodeEnd":386,"githubUrl":"https://github.com/xtekky/gpt4free/blob/973504e1770928ed5fb82f43da528f441ad9ddc3/g4f/Provider/glm/__init__.py#L350-L386","documentation":"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.","triggerScenarios":"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).","commonSituations":"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.","solutions":["Run the GLM/Z.ai setup step that populates the API key before any chat call (e.g. the provider's login/auth helper)","Set the key explicitly: GLM.api_key = os.environ['GLM_API_KEY'] (or equivalent) at startup","Add a startup assertion that cls.api_key is truthy so the failure happens at boot, not mid-request"],"exampleFix":"# before\nasync for chunk in GLM.create_async_generator(model, messages):\n    ...\n# after\nfrom g4f.Provider.glm import GLM\nGLM.api_key = os.environ[\"ZAI_API_KEY\"]  # set during startup\nasync for chunk in GLM.create_async_generator(model, messages):\n    ...","handlingStrategy":"validation","validationCode":"from g4f.Provider.glm import GLM\n\nassert GLM.api_key, 'GLM api_key not set — run Z.ai auth flow or set GLM.api_key before use'","typeGuard":null,"tryCatchPattern":"from g4f.errors import ProviderException\n\ntry:\n    agen = GLM.create_async_generator(model, messages)\nexcept ProviderException as e:\n    if 'Z.ai authentication' in str(e):\n        GLM.api_key = obtain_zai_key()  # bootstrap, then retry once","preventionTips":["Set GLM.api_key during app startup, sourced from env/secret manager","Do not assume the GLM provider self-authenticates like OAuth providers","Fail fast at boot with an assertion instead of at first chat request"],"tags":["glm","api-key","bootstrap","configuration"],"backgroundTag":null,"analyzedSha":"973504e1770928ed5fb82f43da528f441ad9ddc3","analyzedAt":"2026-08-14T23:45:32.408Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}