A Python client library for interacting with the Z.AI API, providing easy access to advanced language models for chat completions, streaming responses, and more.
pip install requests
Clone the repository:
git clone https://github.com/iotbackdoor/zai-python-sdk.git
cd zai-python-sdk
from zai.client import ZAIClient
# Initialize client with automatic authentication
client = ZAIClient(auto_auth=True)
# Simple chat completion
response = client.simple_chat(
message="What is the capital of France?",
model="glm-4.5v"
)
print(response.content)
- Automatic guest token authentication
- Support for multiple AI models
- Streaming and non-streaming responses
- Customizable model parameters
- Modular architecture for flexibility
- Comprehensive error handling
- Verbose mode for debugging
client = ZAIClient(
token=None, # Optional: Bearer token for authentication
base_url="https://chat.z.ai", # API base URL
timeout=180, # Request timeout in seconds
auto_auth=True, # Auto-fetch guest token if no token provided
verbose=False # Enable debug output
)
response = client.simple_chat(
message="Your message here",
model="glm-4.5v", # or "0727-360B-API"
enable_thinking=True, # Enable thinking mode
temperature=0.7, # Control randomness (0.0-2.0)
top_p=0.9, # Control diversity (0.0-1.0)
max_tokens=500 # Maximum response length
)
from zai.models import MCPFeature
chat = client.create_chat(
title="My Chat",
models=["glm-4.5v"],
initial_message="Hello",
enable_thinking=True,
features=[
MCPFeature("mcp", "vibe-coding", "hidden")
]
)
# Stream completion with custom chat
for chunk in client.stream_completion(
chat_id="your-chat-id",
messages=[
{"role": "user", "content": "Tell me a story"}
],
model="0727-360B-API",
enable_thinking=True
):
if chunk.phase == "answer":
print(chunk.delta_content, end="")
# Get complete response without streaming
response = client.complete_chat(
chat_id="your-chat-id",
messages=[
{"role": "user", "content": "Explain quantum computing"}
],
model="glm-4.5v"
)
print(response.content)
print(response.thinking) # If thinking mode was enabled
- glm-4.5v: Advanced visual understanding and analysis model
- 0727-360B-API: Most advanced model, proficient in coding and tool use
The SDK includes predefined model configurations in custom_models.py
:
from zai.custom_models import get_preset, list_presets
# List available presets
print(list_presets())
# Output: ['creative', 'code', 'balanced', 'research', 'brainstorm', 'conservative']
# Get a preset configuration
preset = get_preset('code')
# Returns optimized parameters for code generation
response = client.simple_chat(
message="Write a creative story",
model="glm-4.5v",
temperature=1.2, # Higher for more creativity
top_p=0.95, # Higher for more diversity
max_tokens=2000 # Longer responses
)
from zai.core.exceptions import ZAIError
try:
response = client.simple_chat(
message="Hello",
model="glm-4.5v"
)
except ZAIError as e:
print(f"API Error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
# Enable verbose output to see API requests and responses
client = ZAIClient(auto_auth=True, verbose=True)
# Use your own authentication token
client = ZAIClient(
token="your-bearer-token",
auto_auth=False # Disable automatic token fetching
)
The SDK is organized into modular components:
client.py
- Main client interfacecore/
- Core functionalityhttp_client.py
- HTTP request handlingauth.py
- Authentication managementexceptions.py
- Custom exceptions
operations/
- API operationschat.py
- Chat operationsmodel.py
- Model operationsstreaming.py
- Streaming operations
utils/
- Utility functionssse_parser.py
- Server-Sent Events parsing
models.py
- Data models and structurescustom_models.py
- Predefined model configurations
- Python 3.7+
- requests
The SDK raises ZAIError
exceptions for API-related errors:
- Authentication errors when token is invalid or expired
- Network errors for connection issues
- API errors for invalid requests or server issues
Contributions are welcome. Please ensure your code follows the existing style and includes appropriate documentation.
This project is licensed under the MIT License.
Developed by iotbackdoor
For issues, questions, or suggestions, please open an issue on the GitHub repository.