ZhipuAI Python SDK
ZhipuAI is the official Python SDK for accessing the large model APIs from ZhipuAI Open Platform. It provides a convenient, type-safe, and high-performance interface for interacting with ZhipuAI models like GLM series, supporting chat completions, embeddings, and other AI capabilities. The library maintains an active development status, with frequent updates indicated by its versioning scheme, reflecting ongoing enhancements and feature additions to the ZhipuAI platform.
Common errors
-
APIStatusError: error code:1211 Model does not exist
cause Attempting to use a model that is deprecated, misspelled, or not available for your account/region.fixVerify the model name against the ZhipuAI official documentation. Ensure you are using a currently supported model (e.g., `glm-4`). -
APIStatusError: error code:1214 Invalid message format
cause The `messages` array in a chat completion request contains an invalid structure, often related to `tool_use` or `tool_result` roles with missing or incorrectly formatted `content` fields.fixReview the structure of your `messages` array, especially when integrating tool calls. Ensure all required fields for each message type are present and correctly formatted, avoiding empty content where not allowed. -
zhipuai.APITimeoutError: Request timed out
cause The API request took longer than the configured timeout duration, often due to network issues, complex model computations, or high load on the API.fixIncrease the `timeout` parameter when initializing the `ZhipuAI` client or when making the request. You can also configure `max_retries` for transient network issues. Example: `client = ZhipuAI(api_key=api_key, timeout=httpx.Timeout(timeout=120.0, connect=10.0), max_retries=5)`.
Warnings
- breaking When upgrading from v3.x to v4.x (current major version), significant changes were introduced including simplified API key configuration, modified method signatures for improved type safety, and more specific exception types for error handling. Code written for v3.x will likely require adaptation.
- gotcha ZhipuAI has released a new Python SDK, `z-ai-sdk-python`, and recommends using it for better, faster, and long-term support. While `zhipuai` is currently active, users should be aware of this future-oriented recommendation.
- gotcha API keys should never be hardcoded in your application. They are sensitive credentials and should be managed securely, ideally using environment variables.
- gotcha The SDK might default to specific models in some integrations that could become deprecated or invalid over time, leading to 'Model does not exist' errors.
- gotcha Using consecutive `tool_use`/`tool_result` chains with empty user content can result in 'API Error 1214 — Invalid message format'.
Install
-
pip install zhipuai
Imports
- ZhipuAI
from zhipuai import ZhipuAI
Quickstart
import os
from zhipuai import ZhipuAI
# It's recommended to set your API key as an environment variable (ZHIPUAI_API_KEY)
# For quick testing, you can pass it directly, but avoid in production.
api_key = os.environ.get('ZHIPUAI_API_KEY', 'YOUR_API_KEY_HERE')
if api_key == 'YOUR_API_KEY_HERE':
print("Warning: Please set the ZHIPUAI_API_KEY environment variable or replace 'YOUR_API_KEY_HERE'.")
exit()
client = ZhipuAI(api_key=api_key)
try:
response = client.chat.completions.create(
model="glm-4",
messages=[
{"role": "user", "content": "Hello, ZhipuAI!"}
]
)
print("ZhipuAI Response:")
print(response.choices[0].message.content)
except Exception as e:
print(f"An error occurred: {e}")