### Python Example: Text-to-Video Generation with Polling Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/api-reference/videos.md This example demonstrates how to start a text-to-video generation and then poll for its completion using `retrieve_videos_result`. It prints the video URL and thumbnail upon success or failure. ```python from zai import ZaiClient import time client = ZaiClient(api_key="your-api-key") # Start video generation response = client.videos.generations( model="cogvideox-3", prompt="A cat is playing with a ball in a sunny garden", quality="quality", size="1920x1080", fps=30 ) task_id = response.id print(f"Generation started, task_id: {task_id}") # Poll for completion while True: result = client.videos.retrieve_videos_result(id=task_id) print(f"Status: {result.task_status}") if result.task_status == "SUCCESS": for video in result.video_result: print(f"Video URL: {video.url}") print(f"Thumbnail: {video.cover_image_url}") break elif result.task_status == "FAIL": print("Video generation failed") break time.sleep(10) # Poll every 10 seconds ``` -------------------------------- ### Python Example: Image-to-Video Generation Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/api-reference/videos.md This example shows how to initiate an image-to-video generation. It prints the task ID and suggests polling for the result using `retrieve_videos_result`. ```python response = client.videos.generations( model="cogvideox-3", image_url="https://example.com/image.jpg", quality="speed", # Faster generation size="1280x720", fps=30, movement_amplitude="medium" ) print(f"Task ID: {response.id}") # Poll for result using retrieve_videos_result() ``` -------------------------------- ### ZhipuAiClient Initialization Example Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/CLIENT.md Example demonstrating how to initialize and use the ZhipuAiClient for interactions with the Z.ai API in mainland China. ```APIDOC ## Example ```python from zai import ZhipuAiClient # Initialize for mainland China client = ZhipuAiClient(api_key="your-api-key-here") # All API resources available same as ZaiClient response = client.chat.completions.create( model="glm-5.2", messages=[{"role": "user", "content": "Hello"}] ) ``` ``` -------------------------------- ### Python Example: High-Quality 4K Video Generation Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/api-reference/videos.md This example demonstrates generating a high-quality 4K video with a high frame rate and audio. It prints the task ID for tracking. ```python response = client.videos.generations( model="cogvideox-3", prompt="A drone flying over snow-covered mountains at sunrise", quality="quality", # Prioritize quality size="3840x2160", # 4K resolution fps=60, # High frame rate with_audio=True ) task_id = response.id print(f"High-quality 4K generation started: {task_id}") ``` -------------------------------- ### Install Z.ai SDK via pip Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/README.md Install the Z.ai SDK using pip. Ensure Python 3.8+ and pip are installed. ```bash pip install zai-sdk ``` -------------------------------- ### Python Example: Multiple Images to Video Generation Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/api-reference/videos.md This example shows how to generate a video from a list of image URLs. It specifies the model, image URLs, quality, size, and frame rate. ```python image_urls = [ "https://example.com/img1.jpg", "https://example.com/img2.jpg", "https://example.com/img3.jpg" ] response = client.videos.generations( model="cogvideox-3", image_url=image_urls, # Multiple images quality="speed", size="1024x1024", fps=30 ) ``` -------------------------------- ### Python Example: Video Generation with Tracking and Polling Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/api-reference/videos.md This example shows how to initiate video generation with custom `request_id` and `user_id`, and then poll for the result with a timeout. It handles success, failure, and timeout scenarios. ```python import time response = client.videos.generations( model="cogvideox-3", prompt="A sunset over the ocean", request_id="video_001", user_id="user_12345", quality="quality", size="1920x1080" ) task_id = response.id max_wait = 600 # 10 minutes start_time = time.time() # Poll until completion or timeout while time.time() - start_time < max_wait: result = client.videos.retrieve_videos_result(id=task_id) if result.task_status == "SUCCESS": print("✓ Generation complete") for video in result.video_result: print(f" URL: {video.url}") return result elif result.task_status == "FAIL": print("✗ Generation failed") return None print(f" Still processing... ({int(time.time() - start_time)}s)") time.sleep(5) print("✗ Generation timeout") return None ``` -------------------------------- ### Python Example: Different Aspect Ratios for Video Generation Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/api-reference/videos.md This example demonstrates generating videos with different aspect ratios: portrait (9:16), landscape (21:9), and square (1:1). It shows how to specify `aspect_ratio` and `size` accordingly. ```python # Portrait (mobile-friendly) response1 = client.videos.generations( model="cogvideox-3", prompt="A person dancing", aspect_ratio="9:16", size="1080x1920" ) # Landscape (cinema-style) response2 = client.videos.generations( model="cogvideox-3", prompt="Cinematic landscape shot", aspect_ratio="21:9", size="2520x1080" ) # Square (social media) response3 = client.videos.generations( model="cogvideox-3", prompt="Artistic animation", aspect_ratio="1:1", size="1024x1024" ) ``` -------------------------------- ### Python Example: Fast Generation Mode Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/api-reference/videos.md This example prioritizes speed for real-time applications by setting the quality to 'speed' and enabling `off_peak` usage. It's suitable for quick animations. ```python # Prioritize speed for real-time applications response = client.videos.generations( model="cogvideox-3", prompt="Quick animation: a ball bouncing", quality="speed", size="1280x720", fps=30, off_peak=True # Use off-peak slot if available ) ``` -------------------------------- ### Resource Management with Context Manager Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/CLIENT.md Example showing how to use the ZaiClient with a context manager (`with` statement) for automatic resource cleanup. ```APIDOC ### Resource Management Both clients implement proper cleanup: ```python with ZaiClient(api_key="your-api-key") as client: response = client.chat.completions.create( model="glm-5.2", messages=[{"role": "user", "content": "Test"}] ) # Client automatically cleaned up after with block ``` ``` -------------------------------- ### Manual Resource Management Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/CLIENT.md Example demonstrating manual cleanup of the ZaiClient instance using the `close()` method. ```APIDOC Or manual cleanup: ```python client = ZaiClient(api_key="your-api-key") try: # Use client... finally: client.close() ``` ``` -------------------------------- ### Example Usage of ZhipuAiClient Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/CLIENT.md Demonstrates initializing the ZhipuAiClient and making a chat completion request. This client is configured for mainland China. ```python from zai import ZhipuAiClient # Initialize for mainland China client = ZhipuAiClient(api_key="your-api-key-here") # All API resources available same as ZaiClient response = client.chat.completions.create( model="glm-5.2", messages=[{"role": "user", "content": "Hello"}] ) ``` -------------------------------- ### Error Handling Example Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/CLIENT.md Example demonstrating how to handle potential API errors when using ZaiClient, including authentication, timeout, and general status errors. ```APIDOC ### Error Handling Example ```python from zai import ZaiClient import zai client = ZaiClient(api_key="your-api-key") try: response = client.chat.completions.create( model="glm-5.2", messages=[{"role": "user", "content": "Hello"}] ) except zai.core.APIAuthenticationError as e: print(f"Authentication failed: {e}") except zai.core.APITimeoutError as e: print(f"Request timed out: {e}") except zai.core.APIStatusError as e: print(f"API error: {e.status_code}") ``` ``` -------------------------------- ### Sample SDK Debug Output Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/configuration.md Example of debug log output from the Zai SDK, showing request method, body, response status, and timing information. ```log DEBUG:zai.core._http_client:POST /chat/completions DEBUG:zai.core._http_client:Request body: {...} DEBUG:zai.core._http_client:Response status: 200 DEBUG:zai.core._http_client:Response time: 1.234s ``` -------------------------------- ### Video Generation and Retrieval Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/README.md This example demonstrates video generation using the Z-AI SDK. It includes parameters for model selection, prompt, quality, audio inclusion, size, and frame rate. After generation, it shows how to retrieve the video result using the response ID. ```python from zai import ZaiClient client = ZaiClient(api_key="your-api-key") # Generate video response = client.videos.generations( model="cogvideox-3", prompt="A cat is playing with a ball.", quality="quality", # Output mode, "quality" for quality priority, "speed" for speed priority with_audio=True, # Whether to include audio size="1920x1080", # Video resolution, supports up to 4K (e.g., "3840x2160") fps=30, # Frame rate, can be 30 or 60 max_wait_time=300, # Maximum wait time (seconds) ) print(response) # Get video result result = client.videos.retrieve_videos_result(id=response.id) print(result) ``` -------------------------------- ### Create Batch from File Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/api-reference/batches.md Example of creating a batch job by uploading a file containing batch requests. It first uploads the file and then uses the file ID to create the batch. ```python from zai import ZaiClient client = ZaiClient(api_key="your-api-key") # First, upload batch requests file file_response = client.files.create( file=open("batch_requests.jsonl", "rb"), purpose="batch" ) file_id = file_response.id # Create batch job batch = client.batches.create( endpoint="/v1/chat/completions", input_file_id=file_id, completion_window="one-day" ) print(f"Batch created: {batch.id}") print(f"Status: {batch.status}") ``` -------------------------------- ### Chat Completion with Tool Call Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/README.md This example demonstrates how to create a chat completion that can utilize tools. The 'tools' parameter is used to specify available tools, such as 'web_search', along with their configurations. The response will contain the tool call if applicable. ```python from zai import ZaiClient # Initialize client client = ZaiClient(api_key="your-api-key") # Create chat completion response = client.chat.completions.create( model='glm-5.1', messages=[ {'role': 'system', 'content': 'You are a helpful assistant.'}, {'role': 'user', 'content': 'What is artificial intelligence?'}, ], tools=[ { 'type': 'web_search', 'web_search': { 'search_query': 'What is artificial intelligence?', 'search_result': True, }, } ], temperature=0.5, max_tokens=2000, ) print(response) ``` -------------------------------- ### Module Structure Refactoring Example Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/Release-Note.md Illustrates the reorganized directory structure for API resources within the SDK. This change aims to improve code organization and maintainability. ```treeview src/zai/api_resource/ ├── embeddings/ │ ├── __init__.py │ └── embeddings.py ├── files/ │ ├── __init__.py │ └── files.py ├── images/ │ ├── __init__.py │ └── images.py └── batch/ ├── __init__.py └── batches.py ``` -------------------------------- ### ZaiClient Error Handling Example Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/CLIENT.md Shows how to handle potential API errors, including authentication, timeouts, and general status errors, when using the ZaiClient. ```python from zai import ZaiClient import zai client = ZaiClient(api_key="your-api-key") try: response = client.chat.completions.create( model="glm-5.2", messages=[{"role": "user", "content": "Hello"}] ) except zai.core.APIAuthenticationError as e: print(f"Authentication failed: {e}") except zai.core.APITimeoutError as e: print(f"Request timed out: {e}") except zai.core.APIStatusError as e: print(f"API error: {e.status_code}") ``` -------------------------------- ### Type Definitions Reorganization Example Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/Release-Note.md Shows the refactored structure for type definitions, organizing related types into dedicated submodules. This enhances clarity and modularity. ```treeview src/zai/types/ ├── batch/ │ ├── __init__.py │ ├── batch.py │ ├── batch_create_params.py │ ├── batch_error.py │ ├── batch_list_params.py │ └── batch_request_counts.py ├── image/ │ ├── __init__.py │ └── image.py ├── embeddings/ │ ├── __init__.py │ └── embeddings.py └── [other organized modules...] ``` -------------------------------- ### Streaming Chat Response Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/api-reference/chat.md This example shows how to receive chat completions as a stream of data. It's useful for real-time applications where immediate feedback is desired. ```python client = ZaiClient(api_key="your-api-key") stream = client.chat.completions.create( model="glm-5.1", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Tell me a story."} ], stream=True ) for chunk in stream: if chunk.choices[0].delta.content: print(chunk.choices[0].delta.content, end='', flush=True) ``` -------------------------------- ### Set Environment Variables for API Configuration Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/configuration.md Set ZAI_API_KEY and ZAI_BASE_URL environment variables for authentication and custom API endpoints. Examples provided for Unix/Linux/macOS, Windows PowerShell, and Windows Command Prompt. ```bash # Unix/Linux/macOS export ZAI_API_KEY="your-api-key" export ZAI_BASE_URL="https://api.z.ai/api/paas/v4" ``` ```powershell # Windows (PowerShell) $env:ZAI_API_KEY="your-api-key" $env:ZAI_BASE_URL="https://api.z.ai/api/paas/v4" ``` ```cmd # Windows (Command Prompt) set ZAI_API_KEY=your-api-key set ZAI_BASE_URL=https://api.z.ai/api/paas/v4 ``` -------------------------------- ### Web Search with Tracking Parameters Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/api-reference/web-search.md Executes a web search and includes tracking parameters like request_id and user_id. This is useful for logging and monitoring search requests. The example also demonstrates logging the completion time and result count. ```python import time response = client.web_search.web_search( search_query="my research topic", request_id="search_001", user_id="user_12345", count=10 ) # Log search with timing search_timestamp = int(time.time()) print(f"Search completed at {search_timestamp}") print(f"Request ID: search_001") print(f"Results: {len(response.search_result)}") ``` -------------------------------- ### List All Batch Jobs Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/api-reference/batches.md This method lists all batch jobs. It supports pagination using the 'after' parameter to specify a starting point and 'limit' to control the number of results. Optional extra headers, body parameters, and timeouts are also supported. ```python def list( self, *, after: str | NotGiven = NOT_GIVEN, limit: int | NotGiven = NOT_GIVEN, extra_headers: Headers | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> SyncCursorPage[Batch]: ``` -------------------------------- ### Set Up Client Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/INDEX.md Initializes the Z-AI client with an API key. ```APIDOC ## Set Up Client ### Description Initializes the Z-AI client with an API key. ### Method ```python from zai import ZaiClient client = ZaiClient(api_key="your-api-key") ``` ``` -------------------------------- ### Set Up Z-AI Client Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/INDEX.md Initialize the ZaiClient with your API key. This is the first step before making any requests. ```python from zai import ZaiClient client = ZaiClient(api_key="your-api-key") ``` -------------------------------- ### Initialize ZaiClient with Options Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/configuration.md Demonstrates how to initialize the ZaiClient with various configuration parameters including API key, base URL, timeout, max retries, custom headers, and source channel. ```python from zai import ZaiClient client = ZaiClient( api_key="your-api-key", base_url="https://api.z.ai/api/paas/v4", timeout=30.0, max_retries=3, http_client=None, custom_headers={"Custom-Header": "value"}, disable_token_cache=True, source_channel="python-sdk" ) ``` -------------------------------- ### Embeddings API Reference Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/MANIFEST.txt Reference for generating text embeddings, with details on batch processing and examples for semantic search. ```APIDOC ## Embeddings API ### Description Enables the creation of text embeddings, which are numerical representations of text data. Supports batch processing for efficiency and provides examples for semantic search applications. ### Methods - **create()**: Generates embeddings for provided text. - **Batch Processing**: Information on processing multiple text inputs simultaneously. - **Semantic Search Examples**: Demonstrations of how to use embeddings for search functionalities. ``` -------------------------------- ### Load API Key and Base URL from .env File Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/README.md Configure the ZaiClient by loading API credentials and base URL from a local .env file. Ensure the .env file is in the project root. ```dotenv ZAI_API_KEY=your-api-key ZAI_BASE_URL=https://api.z.ai/api/paas/v4 ``` ```python from dotenv import load_dotenv load_dotenv() from zai import ZaiClient client = ZaiClient() ``` -------------------------------- ### Handling APIServerFlowExceedError Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/errors.md Catch APIServerFlowExceedError when the server is overloaded (503 Service Unavailable). This example indicates that a back-off strategy should be implemented. ```python try: response = client.chat.completions.create(...) except zai.core.APIServerFlowExceedError as e: print("Server overloaded, please retry later") # Implement back-off strategy ``` -------------------------------- ### Upload File for Fine-tuning Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/api-reference/files.md Upload a file from a local path for fine-tuning purposes. Ensure the file is opened in binary read mode. ```python from zai import ZaiClient client = ZaiClient(api_key="your-api-key") # Upload from file path file_response = client.files.create( file=open("training_data.jsonl", "rb"), purpose="fine-tune" ) print(f"File ID: {file_response.id}") print(f"Status: {file_response.status}") ``` -------------------------------- ### Initialize ZaiClient with Explicit API Key Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/CLIENT.md Use this snippet to initialize the ZaiClient when you have your API key readily available. This is the most straightforward way to authenticate. ```python from zai import ZaiClient # Initialize with explicit API key client = ZaiClient(api_key="your-api-key-here") ``` -------------------------------- ### Initialize ZaiClient and Create Chat Completion Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/Release-Note.md Initialize the ZaiClient with your API key and create a chat completion using the glm-4 model. Replace 'your-api-key' with your actual Z.ai API key. ```python from zai import ZaiClient # Initialize client client = ZaiClient(api_key="your-api-key") # Create chat completion response = client.chat.completions.create( model="glm-4", messages=[{"role": "user", "content": "Hello, Z.ai!"}] ) print(response.choices[0].message.content) ``` -------------------------------- ### Semantic Search Example Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/api-reference/embeddings.md Perform semantic search by generating embeddings for a query and a list of documents, then calculating similarity. Requires NumPy for vector operations. ```python client = ZaiClient(api_key="your-api-key") # Generate embedding for search query query = "best practices for Python" query_response = client.embeddings.create( input=query, model="embedding-3" ) query_embedding = query_response.data[0].embedding # Generate embeddings for documents documents = [ "Python coding standards and best practices", "JavaScript tutorial for beginners", "Database design patterns", "Python performance optimization" ] doc_response = client.embeddings.create( input=documents, model="embedding-3" ) # Calculate similarity (dot product or cosine) import numpy as np query_vec = np.array(query_embedding) doc_vecs = [np.array(doc.embedding) for doc in doc_response.data] # Cosine similarity similarities = [ np.dot(query_vec, doc_vec) / (np.linalg.norm(query_vec) * np.linalg.norm(doc_vec)) for doc_vec in doc_vecs ] # Rank documents ranked = sorted(zip(documents, similarities), key=lambda x: x[1], reverse=True) print("Top results:") for doc, score in ranked: print(f" {score:.3f}: {doc}") ``` -------------------------------- ### Basic Z.ai SDK Usage Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/README.md Demonstrates how to create a client and make a chat completion request. Use ZaiClient for overseas regions and ZhipuAiClient for Mainland China regions. ```python from zai import ZaiClient, ZhipuAiClient # For Overseas users, create the ZaiClient client = ZaiClient(api_key="your-api-key") # For Chinese users, create the ZhipuAiClient client = ZhipuAiClient(api_key="your-api-key") # Create chat completion response = client.chat.completions.create( model="glm-5.2", messages=[ {"role": "user", "content": "Hello, Z.ai!"} ] ) print(response.choices[0].message.content) ``` -------------------------------- ### Adjusting Speech Speed and Volume Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/api-reference/audio.md Allows for fine-tuning speech output by adjusting speed and volume parameters. Examples show generating slow/quiet and fast/loud speech. ```python # Slow and quiet slow_response = client.audio.speech( model="glm-tts", input="Speak slowly", voice="tongtong", speed=0.7, # 70% of normal speed volume=0.5 # 50% volume ) # Fast and loud fast_response = client.audio.speech( model="glm-tts", input="Speak quickly", voice="tongtong", speed=1.5, # 150% of normal speed volume=2.0 # 200% volume ) with open("slow.pcm", "wb") as f: f.write(slow_response.content) with open("fast.pcm", "wb") as f: f.write(fast_response.content) ``` -------------------------------- ### Configure Client Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/INDEX.md Initializes the Z-AI client with an API key, timeout, and maximum retries. ```APIDOC ## Configure Client ### Description Initializes the Z-AI client with an API key, timeout, and maximum retries. ### Method ```python client = ZaiClient( api_key="key", timeout=30.0, max_retries=3 ) ``` ``` -------------------------------- ### Handling APIAuthenticationError Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/errors.md Catch APIAuthenticationError when API credentials are invalid or missing, indicated by a 401 Unauthorized status. The example demonstrates initializing the client with an invalid API key. ```python try: client = zai.ZaiClient(api_key="invalid-key") response = client.chat.completions.create( model="glm-5.2", messages=[{"role": "user", "content": "Hello"}] ) except zai.core.APIAuthenticationError as e: print("Authentication failed - check your API key") ``` -------------------------------- ### Generate Videos using Z-AI SDK Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/INDEX.md Create videos from a text prompt using a video generation model. Requires specifying the model and prompt. ```python response = client.videos.generations( model="cogvideox-3", prompt="A cat playing" ) ``` -------------------------------- ### Handling APIRequestFailedError Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/errors.md Catch APIRequestFailedError for issues with invalid request parameters or malformed data, indicated by a 400 Bad Request status. The example shows how to trigger this error with an invalid model name. ```python try: response = client.chat.completions.create( model="invalid-model", messages=[{"role": "user", "content": "Hello"}] ) except zai.core.APIRequestFailedError as e: print(f"Invalid request: {e}") print(f"Status code: {e.status_code}") ``` -------------------------------- ### Retrieve Batch Job Details Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/api-reference/batches.md Use this method to get detailed information about a specific batch job using its ID. It supports optional extra headers and body parameters, as well as request timeouts. ```python def retrieve( self, batch_id: str, *, extra_headers: Headers | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Batch: ``` -------------------------------- ### API Key Management with .env Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/Release-Note.md Demonstrates the recommended way to load API keys using environment variables and the python-dotenv library. Ensure your API key is stored in a .env file in your project's root directory. ```python # Before (still works) from zai import ZaiClient client = ZaiClient(api_key="your-key") # Enhanced (recommended) import os from zai import ZaiClient from dotenv import load_dotenv load_dotenv() api_key = os.getenv('ZAI_API_KEY') client = ZaiClient(api_key=api_key) ``` -------------------------------- ### ZaiClient Resource Management with Context Manager Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/CLIENT.md Demonstrates using the ZaiClient with a `with` statement for automatic resource cleanup. The client is automatically closed after the block. ```python with ZaiClient(api_key="your-api-key") as client: response = client.chat.completions.create( model="glm-5.2", messages=[{"role": "user", "content": "Test"}] ) # Client automatically cleaned up after with block ``` -------------------------------- ### Configure Z.ai SDK with Environment Variables Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/README.md Set the API key and optionally the base URL using environment variables. This is a common method for configuring SDKs. ```bash export ZAI_API_KEY="your-api-key" export ZAI_BASE_URL="https://api.z.ai/api/paas/v4/" # Optional ``` -------------------------------- ### Image Generation with Different Sizes and Styles Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/api-reference/images.md Demonstrates generating images with various size, style, and quality parameters to achieve different aesthetic outcomes, from professional headshots to epic landscapes. ```python # Standard high-definition response1 = client.images.generations( prompt="Professional headshot portrait", size="512x512", style="natural", quality="hd" ) # Wide landscape response2 = client.images.generations( prompt="Epic fantasy landscape", size="1536x1024", style="vivid" ) # Portrait response3 = client.images.generations( prompt="Beautiful woman in elegant dress", size="768x1024", quality="standard" ) ``` -------------------------------- ### Initialize ZaiClient from Environment Variable Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/CLIENT.md Initialize ZaiClient without explicitly providing an API key. The client will automatically attempt to read the key from the ZAI_API_KEY environment variable. Ensure the environment variable is set before running. ```python client = ZaiClient() # reads ZAI_API_KEY from environment ``` -------------------------------- ### Generating Speech with Different Voices Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/api-reference/audio.md Demonstrates how to generate speech using a list of available voices. Each generated speech is saved as a WAV file. ```python voices = ["tongtong", "chuichui", "xiaochen"] for voice in voices: response = client.audio.speech( model="glm-tts", input="Hello everyone!", voice=voice, response_format="wav" ) with open(f"speech_{voice}.wav", "wb") as f: f.write(response.content) print(f"Generated speech_{voice}.wav") ``` -------------------------------- ### Batch Video Generation and Polling Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/api-reference/videos.md Shows how to initiate multiple video generation tasks concurrently and then poll for their completion status, retrieving video URLs upon success. ```python prompts = [ "A cat playing with yarn", "Dog running through a field", "Bird flying in the sky", ] # Start all generations tasks = [] for i, prompt in enumerate(prompts): response = client.videos.generations( model="cogvideox-3", prompt=prompt, size="1280x720", request_id=f"batch_001_{i+1}" ) tasks.append((prompt, response.id)) print(f"Started: {prompt} -> {response.id}") # Poll all tasks until complete import time completed = {} while len(completed) < len(tasks): for prompt, task_id in tasks: if task_id in completed: continue result = client.videos.retrieve_videos_result(id=task_id) if result.task_status == "SUCCESS": completed[task_id] = result.video_result[0].url print(f"✓ {prompt}") elif result.task_status == "FAIL": completed[task_id] = None print(f"✗ {prompt}") if len(completed) < len(tasks): time.sleep(10) print("\nResults:") for prompt, task_id in tasks: url = completed.get(task_id) print(f" {prompt}: {url}") ``` -------------------------------- ### Upload Voice Sample for Cloning Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/api-reference/files.md Upload a voice sample file for voice cloning. The file must be opened in binary read mode. ```python # Upload voice for voice cloning file_response = client.files.create( file=open("voice_sample.wav", "rb"), purpose="voice-clone-input" ) print(f"Voice sample uploaded: {file_response.id}") ``` -------------------------------- ### Batch Video Generation Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/api-reference/videos.md Shows how to generate multiple videos concurrently by submitting a list of prompts and then polling for their results. ```APIDOC ## Batch Video Generation ### Description This example demonstrates how to generate multiple videos in a batch. It first initiates all generation tasks and then continuously polls for their completion status, printing the URLs of successfully generated videos. ### Method `client.videos.generations()` and `client.videos.retrieve_videos_result()` ### Parameters for `generations()` - **model** (string) - Required - The model to use for video generation. - **prompt** (string) - Required - The text prompt describing the desired video content. - **size** (string) - Required - The desired resolution of the video (e.g., "1280x720"). - **request_id** (string) - Optional - A unique identifier for the request, useful for tracking. ### Parameters for `retrieve_videos_result()` - **id** (string) - Required - The ID of the video generation task to retrieve results for. ### Request Example ```python prompts = [ "A cat playing with yarn", "Dog running through a field", "Bird flying in the sky", ] # Start all generations tasks = [] for i, prompt in enumerate(prompts): response = client.videos.generations( model="cogvideox-3", prompt=prompt, size="1280x720", request_id=f"batch_001_{i+1}" ) tasks.append((prompt, response.id)) print(f"Started: {prompt} -> {response.id}") # Poll all tasks until complete import time completed = {} while len(completed) < len(tasks): for prompt, task_id in tasks: if task_id in completed: continue result = client.videos.retrieve_videos_result(id=task_id) if result.task_status == "SUCCESS": completed[task_id] = result.video_result[0].url print(f"✓ {prompt}") elif result.task_status == "FAIL": completed[task_id] = None print(f"✗ {prompt}") if len(completed) < len(tasks): time.sleep(10) print("\nResults:") for prompt, task_id in tasks: url = completed.get(task_id) print(f" {prompt}: {url}") ``` ### Response #### Success Response (from `retrieve_videos_result`) - **task_status** (string) - The status of the video generation task (e.g., "SUCCESS", "FAIL"). - **video_result** (array) - A list containing the video generation results. For successful tasks, it typically contains one item. - **url** (string) - The URL of the generated video if the task was successful. ``` -------------------------------- ### Configure Z-AI Client Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/INDEX.md Configure the ZaiClient with additional parameters like timeout and maximum retries for enhanced control. ```python client = ZaiClient( api_key="key", timeout=30.0, max_retries=3 ) ``` -------------------------------- ### Saving Speech in Multiple Formats Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/api-reference/audio.md Shows how to generate speech output in different formats, specifically PCM and WAV, and save them to files. ```python text = "This is a test message." # Generate as PCM (default) response_pcm = client.audio.speech( model="glm-tts", input=text, voice="tongtong", response_format="pcm" ) # Generate as WAV response_wav = client.audio.speech( model="glm-tts", input=text, voice="tongtong", response_format="wav" ) with open("output.pcm", "wb") as f: f.write(response_pcm.content) with open("output.wav", "wb") as f: f.write(response_wav.content) ``` -------------------------------- ### Set API Key using Environment Variable Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/README.md Configure the ZaiClient by setting the ZAI_API_KEY environment variable. The ZaiClient automatically reads this variable. ```bash export ZAI_API_KEY="your-api-key" ``` -------------------------------- ### Create Batch with Metadata Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/api-reference/batches.md Creates a batch job and attaches custom metadata to it for organization or tracking. ```python batch = client.batches.create( endpoint="/v1/chat/completions", input_file_id="file_xyz", metadata={ "project": "research-2024", "experiment": "summarization-v2", "team": "nlp" } ) print(f"Batch {batch.id} created with metadata") ``` -------------------------------- ### create Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/api-reference/files.md Upload a file to the platform. This method allows for uploading files with specified purposes and optional details for retrieval or fine-tuning. ```APIDOC ## Method: create ### Description Upload a file to the platform. This method allows for uploading files with specified purposes and optional details for retrieval or fine-tuning. ### Method Signature ```python def create( self, *, file: FileTypes = None, upload_detail: List[UploadDetail] = None, purpose: Literal['fine-tune', 'retrieval', 'batch', 'voice-clone-input'], knowledge_id: str = None, sentence_size: int = None, extra_headers: Headers | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> FileObject ``` ### Parameters #### Required Parameters - **purpose** (Literal['fine-tune', 'retrieval', 'batch', 'voice-clone-input']) - Purpose of the file upload. Determines how file is used. #### Optional Parameters - **file** (FileTypes) - File to upload. Can be file object or file path. Required if `upload_detail` not provided. - **upload_detail** (List[UploadDetail]) - Detailed upload information. Required if `file` not provided. - **knowledge_id** (str) - Knowledge base ID for retrieval purpose. - **sentence_size** (int) - Sentence size for text splitting in retrieval. - **extra_headers** (Headers) - Additional HTTP headers. - **extra_body** (Body) - Additional body parameters. - **timeout** (float | httpx.Timeout) - Request timeout. ### Return Type `FileObject` - Uploaded file information: - `id` (str): Unique file identifier - `object` (str): Object type ('file') - `created_at` (int): Unix timestamp of creation - `filename` (str): Original filename - `purpose` (str): Upload purpose - `size` (int): File size in bytes - `status` (str): File processing status ('uploaded', 'processed', 'failed') - `status_details` (Optional[str]): Additional status information ### Throws - `APIStatusError`: Base API error with status code - `APIAuthenticationError`: Invalid or missing API key (401) - `APIRequestFailedError`: Invalid request parameters (400) - `APIReachLimitError`: Rate limit exceeded (429) - `APIInternalError`: Server error (500) - `APIServerFlowExceedError`: Server overloaded (503) - `APITimeoutError`: Request timeout - `ValueError`: If neither `file` nor `upload_detail` provided ``` -------------------------------- ### Environment Variables for Configuration Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/CLIENT.md Details on environment variables that can be used to configure the ZhipuAiClient and ZaiClient, including API key and base URL. ```APIDOC ## Configuration ### Environment Variables Both client classes read from environment variables for configuration: | Variable | Description | Example | |----------|-------------|---------| | `ZAI_API_KEY` | API key for authentication | `sk_xxxxx` | | `ZAI_BASE_URL` | Custom base URL for API endpoint | `https://api.z.ai/api/paas/v4` | ``` -------------------------------- ### Configure Custom HTTP Client Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/configuration.md Use your own httpx.Client for advanced configuration such as timeouts, connection limits, and custom headers. The SDK manages the lifecycle of the provided client; do not call close() on it. ```python import httpx from zai import ZaiClient # Create custom HTTP client http_client = httpx.Client( timeout=30.0, limits=httpx.Limits(max_connections=100, max_keepalive_connections=50), headers={"User-Agent": "MyApp/1.0"} ) # Use with SDK client = ZaiClient( api_key="key", http_client=http_client ) # Client will use your http_client # Don't call close() on client - you manage the http_client ``` -------------------------------- ### Create Batch Requests File Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/api-reference/batches.md Prepares and writes chat completion requests to a JSONL file, then uploads the file and creates a batch job. This is useful for preparing custom batch requests. ```python import json # Prepare batch requests requests = [ { "custom_id": "summary-1", "params": { "model": "glm-5.2", "messages": [{"role": "user", "content": "Summarize: The quick brown fox..."}], "max_tokens": 100 } }, { "custom_id": "summary-2", "params": { "model": "glm-5.2", "messages": [{"role": "user", "content": "Summarize: Python is a programming..."}], "max_tokens": 100 } }, ] # Write to JSONL file with open("batch_requests.jsonl", "w") as f: for request in requests: f.write(json.dumps(request) + "\n") # Upload and create batch file_response = client.files.create( file=open("batch_requests.jsonl", "rb"), purpose="batch" ) batch = client.batches.create( endpoint="/v1/chat/completions", input_file_id=file_response.id ) print(f"Batch {batch.id} submitted with {len(requests)} requests") ``` -------------------------------- ### Upload and Manage Files using Z-AI SDK Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/INDEX.md Upload files for purposes like batch processing. The file must be opened in binary read mode. ```python response = client.files.create( file=open("data.jsonl", "rb"), purpose="batch" ) ``` -------------------------------- ### Initialize ZaiClient with Custom Endpoint Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/configuration.md Configure the ZaiClient to use a custom API endpoint by providing the base_url parameter. ```python from zai import ZaiClient client = ZaiClient( api_key="your-api-key", base_url="https://custom.api.endpoint/v4" ) ``` -------------------------------- ### Configure Z.ai SDK with Code Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/README.md Configure the ZaiClient or ZhipuAiClient directly within your Python code by passing the API key and an optional base URL. ```python from zai import ZaiClient, ZhipuAiClient client = ZaiClient( api_key="your-api-key", base_url="https://api.z.ai/api/paas/v4/" # Optional ) # if you want to use Zhipu's domain service zhipu_client = ZhipuAiClient( api_key="your-api-key", base_url="https://open.bigmodel.cn/api/paas/v4/" # Optional ) ``` -------------------------------- ### Initialize ZhipuAiClient for Mainland China Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/CLIENT.md Initialize the ZhipuAiClient for use with mainland China API endpoints. Requires an API key. ```python ZhipuAiClient( *, api_key: str | None = None, base_url: str | httpx.URL | None = None, timeout: Union[float, Timeout, None, NotGiven] = NOT_GIVEN, max_retries: int = ZAI_DEFAULT_MAX_RETRIES, http_client: httpx.Client | None = None, custom_headers: Mapping[str, str] | None = None, disable_token_cache: bool = True, _strict_response_validation: bool = False, source_channel: str | None = None, ) -> None ``` -------------------------------- ### List All Files Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/api-reference/files.md Retrieve a list of all uploaded files. The total count and details for each file are printed. ```python files_list = client.files.list() print(f"Total files: {len(files_list.data)}") for file in files_list.data: print(f" {file.id}: {file.filename} ({file.size} bytes)") ``` -------------------------------- ### List Files with Filtering and Pagination Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/api-reference/files.md Use this method to retrieve a list of files. You can filter by purpose, paginate results using `limit` and `after`, and sort the output. Ensure to check `has_more` for subsequent requests. ```python def list( self, *, purpose: str | NotGiven = NOT_GIVEN, limit: int | NotGiven = NOT_GIVEN, after: str | NotGiven = NOT_GIVEN, order: str | NotGiven = NOT_GIVEN, extra_headers: Headers | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ListOfFileObject: pass ``` -------------------------------- ### Upload Files Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/README.md Upload a file for batch processing. The file should be opened in binary read mode and its purpose specified. ```python response = client.files.create( file=open("data.jsonl", "rb"), purpose="batch" ) print(f"File ID: {response.id}") ``` -------------------------------- ### List Batches with Pagination Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/api-reference/batches.md Lists batches using pagination, collecting all batches and then summarizing them by status. ```python all_batches = [] cursor = None while True: if cursor: page = client.batches.list(after=cursor, limit=20) else: page = client.batches.list(limit=20) all_batches.extend(page.data) if not page.has_more: break cursor = page.data[-1].id print(f"Total batches: {len(all_batches)}") # Show status summary by_status = {} for batch in all_batches: status = batch.status by_status[status] = by_status.get(status, 0) + 1 for status, count in by_status.items(): print(f" {status}: {count}") ``` -------------------------------- ### Production Configuration for ZaiClient Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/configuration.md Configure ZaiClient for production with specific timeouts, max retries, and custom headers for environment and version tracking. Logging is set to WARNING level. ```python import logging from zai import ZaiClient import httpx logging.basicConfig(level=logging.WARNING) client = ZaiClient( api_key="your-api-key", # Use env var in production timeout=httpx.Timeout( timeout=30.0, connect=5.0, read=25.0 ), max_retries=3, custom_headers={ "X-App-Version": "1.0", "X-Environment": "production" } ) ``` -------------------------------- ### Chat with AI using Z-AI SDK Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/INDEX.md Use this snippet to initiate a chat conversation with an AI model. Requires a ZaiClient instance. ```python response = client.chat.completions.create( model="glm-5.2", messages=[{"role": "user", "content": "Hello"}] ) ``` -------------------------------- ### Use Context Manager for Automatic Cleanup Source: https://github.com/zai-org/z-ai-sdk-python/blob/main/_autodocs/configuration.md The recommended way to use ZaiClient is with a context manager. This ensures the client is automatically closed when exiting the block, preventing resource leaks. ```python from zai import ZaiClient with ZaiClient(api_key="key") as client: response = client.chat.completions.create(...) # Client automatically closed after block ```