### Install and Use Z.AI Python SDK Source: https://docs.z.ai/guides/image/cogview-4 Instructions for installing the Z.AI Python SDK and a code example to verify the installation and generate an image. The SDK simplifies interaction with the Z.AI API for image generation. ```bash # Install latest version pip install zai-sdk # Or specify version pip install zai-sdk==0.0.4 ``` ```python import zai print(zai.__version__) ``` ```python from zai import ZaiClient client = ZaiClient(api_key="your-api-key") response = client.images.generations( model="cogView-4-250304", prompt="A cute little kitten sitting on a sunny windowsill, with the background of blue sky and white clouds.", ) print(response.data[0].url) ``` -------------------------------- ### Python SDK Installation and Usage Source: https://context7 Guide to installing the Z.AI Python SDK via pip, poetry, or uv, and a basic example of using the SDK for chat completions. ```APIDOC ## Python SDK Installation Install and configure the official Z.AI Python SDK ```bash # Install via pip (Python 3.8+ required) pip install zai-sdk # Or with poetry poetry add zai-sdk # Or with uv uv add zai-sdk ``` ```python from zai import ZaiClient # Initialize client client = ZaiClient(api_key="your-api-key") # Basic chat completion response = client.chat.completions.create( model="glm-4.6", messages=[ {"role": "system", "content": "You are a helpful AI assistant."}, {"role": "user", "content": "Explain quantum computing in simple terms"} ], temperature=1.0, max_tokens=4096 ) print(response.choices[0].message.content) # Output: # Quantum computing uses quantum mechanics principles like superposition # and entanglement to process information. Unlike classical computers that # use bits (0 or 1), quantum computers use qubits that can be both 0 and 1 # simultaneously, enabling exponentially faster calculations for specific problems... ``` ``` -------------------------------- ### Install Zai SDK Source: https://docs.z.ai/guides/video/cogvideox-3 Installs the Zai SDK using pip. Supports installing the latest version or a specific version. This is a prerequisite for all Zai SDK functionalities. ```bash # Install latest version pip install zai-sdk # Or specify version pip install zai-sdk==0.0.4 ``` -------------------------------- ### Python: Install OpenAI SDK Source: https://docs.z.ai/guides/llm/glm-4-32b-0414-128k This section provides instructions for installing and verifying the OpenAI Python SDK. It covers installing the latest version using pip and a command to check the installed version. ```bash # Install or upgrade to latest version pip install --upgrade 'openai>=1.0' ``` ```python python -c "import openai; print(openai.__version__)" ``` -------------------------------- ### Verify Zai SDK Installation Source: https://docs.z.ai/guides/video/cogvideox-3 Verifies the Zai SDK installation by checking the installed version. This confirms that the SDK has been successfully installed and is accessible in the Python environment. ```python import zai print(zai.__version__) ``` -------------------------------- ### Install OpenCode CLI Source: https://docs.z.ai/devpack/tool/opencode Provides instructions for installing the OpenCode CLI using either a curl script or npm. This is the initial step to get OpenCode running on your system. ```bash curl -fsSL https://opencode.ai/install | bash ``` ```bash npm install -g opencode-ai ``` -------------------------------- ### Python: SDK Installation and API Calls Source: https://docs.z.ai/guides/vlm/glm-4.5v Provides instructions for installing the `zai-sdk` Python package using pip, verifying the installation, and making basic and streaming API calls to the Z.AI chat completions endpoint. The code initializes the `ZaiClient` with an API key and demonstrates how to structure the messages payload for image and text content. ```bash # Install the latest version pip install zai-sdk # Or specify a version pip install zai-sdk==0.0.4 ``` ```python import zai print(zai.__version__) ``` ```python from zai import ZaiClient client = ZaiClient(api_key="") # Enter your own APIKey response = client.chat.completions.create( model="glm-4.5v", # Enter the name of the model you want to call messages=[ { "content": [ { "type": "image_url", "image_url": { "url": "https://cloudcovert-1305175928.cos.ap-guangzhou.myqcloud.com/%E5%9B%BE%E7%89%87grounding.PNG" } }, { "type": "text", "text": "Where is the second bottle of beer from the right on the table? Provide coordinates in [[xmin,ymin,xmax,ymax]] format" } ], "role": "user" } ], thinking={ "type":"enabled" } ) print(response.choices[0].message) ``` ```python from zai import ZaiClient client = ZaiClient(api_key="") # Enter your own APIKey response = client.chat.completions.create( model="glm-4.5v", # Enter the name of the model you want to call messages=[ { "content": [ { "type": "image_url", "image_url": { "url": "https://cloudcovert-1305175928.cos.ap-guangzhou.myqcloud.com/%E5%9B%BE%E7%89%87grounding.PNG" } }, { "type": "text", "text": "Where is the second bottle of beer from the right on the table? Provide coordinates in [[xmin,ymin,xmax,ymax]] format" } ], "role": "user" } ], thinking={ "type":"enabled" }, stream=True ) for chunk in response: if chunk.choices[0].delta.reasoning_content: print(chunk.choices[0].delta.reasoning_content, end='', flush=True) if chunk.choices[0].delta.content: print(chunk.choices[0].delta.content, end='', flush=True) ``` -------------------------------- ### Java SDK Setup and Usage for GLM-4.6 Source: https://docs.z.ai/guides/llm/glm-4.6 Details on integrating GLM-4.6 using the official Java SDK. Includes Maven and Gradle dependency information, and a code example for making a basic chat completion request. Requires an API key and specifies model and messages. ```xml ai.z.openapi zai-sdk 0.0.6 ``` ```groovy implementation 'ai.z.openapi:zai-sdk:0.0.6' ``` ```java import ai.z.openapi.ZaiClient; import ai.z.openapi.service.model.ChatCompletionCreateParams; import ai.z.openapi.service.model.ChatCompletionResponse; import ai.z.openapi.service.model.ChatMessage; import ai.z.openapi.service.model.ChatMessageRole; import ai.z.openapi.service.model.ChatThinking; import java.util.Arrays; public class BasicChat { public static void main(String[] args) { // Initialize client ZaiClient client = ZaiClient.builder() .apiKey("your-api-key") .build(); // Create chat completion request ChatCompletionCreateParams request = ChatCompletionCreateParams.builder() .model("glm-4.6") .messages(Arrays.asList( ChatMessage.builder() .role(ChatMessageRole.USER.value()) .content("As a marketing expert, please create an attractive slogan for my product.") .build(), ChatMessage.builder() .role(ChatMessageRole.ASSISTANT.value()) ``` -------------------------------- ### Install and Verify Z.AI Python SDK Source: https://docs.z.ai/guides/llm/glm-4-32b-0414-128k This section details how to install the Z.AI Python SDK using pip. It provides commands for installing the latest version or a specific version. It also includes a Python snippet to verify the installed SDK version. ```bash # Install latest version pip install zai-sdk # Or specify version pip install zai-sdk==0.0.4 ``` ```python import zai print(zai.__version__) ``` -------------------------------- ### Install Z.AI Java SDK with Maven and Gradle Source: https://docs.z.ai/guides/llm/glm-4-32b-0414-128k This section provides instructions for adding the Z.AI Java SDK to your project using Maven and Gradle. It includes the necessary dependency snippets for both build tools. ```xml ai.z.openapi zai-sdk 0.0.6 ``` ```groovy implementation 'ai.z.openapi:zai-sdk:0.0.6' ``` -------------------------------- ### Java SDK Setup Source: https://context7 Instructions for adding the Z.AI Java SDK dependency to Maven or Gradle projects, followed by an example of using the SDK for chat completions. ```APIDOC ## Java SDK Setup Integrate Z.AI with Maven or Gradle projects ```xml ai.z.openapi zai-sdk 0.0.6 ``` ```groovy // Gradle dependency (Gradle 6.0+) implementation 'ai.z.openapi:zai-sdk:0.0.6' ``` ```java import ai.z.openapi.ZaiClient; import ai.z.openapi.service.model.*; import java.util.Arrays; public class BasicChat { public static void main(String[] args) { // Initialize client ZaiClient client = ZaiClient.builder() .apiKey("your-api-key") .build(); // Create chat completion request ChatCompletionCreateParams request = ChatCompletionCreateParams.builder() .model("glm-4.6") .messages(Arrays.asList( ChatMessage.builder() .role(ChatMessageRole.SYSTEM.value()) .content("You are a coding assistant") .build(), ChatMessage.builder() .role(ChatMessageRole.USER.value()) .content("Write a Java method to reverse a string") .build() )) .temperature(0.7) .maxTokens(2048) .stream(false) .build(); // Get response ChatCompletionResponse response = client.chat().createChatCompletion(request); String content = response.getData() .getChoices() .get(0) .getMessage() .getContent(); System.out.println(content); // Output: // public String reverseString(String input) { // if (input == null) return null; // return new StringBuilder(input).reverse().toString(); // } } } ``` ``` -------------------------------- ### Python SDK for GLM-4.6 Integration Source: https://docs.z.ai/guides/llm/glm-4.6 Provides instructions for installing and using the official Python SDK (zai-sdk) to interact with the GLM-4.6 API. Includes examples for verifying installation, making basic chat completions, and handling streaming responses. ```bash # Install latest version pip install zai-sdk # Or specify version pip install zai-sdk==0.0.4 ``` ```python import zai print(zai.__version__) ``` ```python from zai import ZaiClient client = ZaiClient(api_key="your-api-key") # Your API Key response = client.chat.completions.create( model="glm-4.6", messages=[ {"role": "user", "content": "As a marketing expert, please create an attractive slogan for my product."}, {"role": "assistant", "content": "Sure, to craft a compelling slogan, please tell me more about your product."}, {"role": "user", "content": "Z.AI Open Platform"} ], thinking={ "type": "enabled", }, max_tokens=4096, temperature=1.0 ) # Get complete response print(response.choices[0].message) ``` ```python from zai import ZaiClient client = ZaiClient(api_key="your-api-key") # Your API Key response = client.chat.completions.create( model="glm-4.6", messages=[ {"role": "user", "content": "As a marketing expert, please create an attractive slogan for my product."}, {"role": "assistant", "content": "Sure, to craft a compelling slogan, please tell me more about your product."}, {"role": "user", "content": "Z.AI Open Platform"} ], thinking={ "type": "enabled", # Optional: "disabled" or "enabled", default is "enabled" }, stream=True, max_tokens=4096, temperature=0.6 ) # Stream response for chunk in response: if chunk.choices[0].delta.reasoning_content: print(chunk.choices[0].delta.reasoning_content, end='', flush=True) if chunk.choices[0].delta.content: print(chunk.choices[0].delta.content, end='', flush=True) ``` -------------------------------- ### Zai SDK Basic Call Example Source: https://docs.z.ai/guides/image/cogview-4 A basic Python example demonstrating how to interact with the Zai SDK. This snippet is intended to show the initial setup and a simple call pattern. ```python # This is a placeholder for the actual code example that was truncated. # It would typically show how to initialize the SDK and make a call. # Example: # from zai.client import Client # client = Client(api_key="YOUR_API_KEY") # response = client.generate_text(prompt="Hello, world!") # print(response) ``` -------------------------------- ### Verify OpenAI Python SDK Installation Source: https://docs.z.ai/guides/llm/glm-4.6 A simple command to verify that the OpenAI Python SDK has been installed correctly and to check its version. ```python python -c "import openai; print(openai.__version__)" ``` -------------------------------- ### Install and Use OpenCode in VS Code Source: https://docs.z.ai/devpack/tool/opencode Details the process of installing and using the OpenCode extension within VS Code and its forks. It covers automatic installation via the terminal and keyboard shortcuts for launching and interacting with OpenCode. ```bash opencode ``` -------------------------------- ### Install OpenAI Python SDK Source: https://docs.z.ai/guides/llm/glm-4.6 Instructions to install or upgrade the OpenAI Python SDK to the latest version using pip. This is a prerequisite for using the Z.AI API with Python. ```bash # Install or upgrade to latest version pip install --upgrade 'openai>=1.0' ``` -------------------------------- ### Z.AI Python SDK: Chat Completion Source: https://docs.z.ai/api-reference/introduction This example demonstrates how to install and use the official Z.AI Python SDK to perform chat completions. It covers SDK installation via pip, verifying the installed version, and a usage example showing client initialization, request creation, and retrieving the response content. ```bash # Install latest version pip install zai-sdk # Or specify version pip install zai-sdk==0.0.3.3 ``` ```python import zai print(zai.__version__) ``` ```python from zai import ZaiClient # Initialize client client = ZaiClient(api_key="YOUR_API_KEY") # Create chat completion request response = client.chat.completions.create( model="glm-4.6", messages=[ { "role": "system", "content": "You are a helpful AI assistant." }, { "role": "user", "content": "Hello, please introduce yourself." } ] ) # Get response print(response.choices[0].message.content) ``` -------------------------------- ### Install and Use Z.AI Java SDK Source: https://docs.z.ai/guides/llm/glm-4.5 Details on how to add the Z.AI Java SDK to your project using Maven or Gradle. It also includes a basic example of initializing the client and creating a chat completion request. ```xml ai.z.openapi zai-sdk 0.0.6 ``` ```groovy implementation 'ai.z.openapi:zai-sdk:0.0.6' ``` ```java import ai.z.openapi.ZaiClient; import ai.z.openapi.service.model.ChatCompletionCreateParams; import ai.z.openapi.service.model.ChatCompletionResponse; import ai.z.openapi.service.model.ChatMessage; import ai.z.openapi.service.model.ChatMessageRole; import ai.z.openapi.service.model.ChatThinking; import java.util.Arrays; public class BasicChat { public static void main(String[] args) { // Initialize client ZaiClient client = ZaiClient.builder() .apiKey("your-api-key") .build(); // Create chat completion request ChatCompletionCreateParams request = ChatCompletionCreateParams.builder() .model("glm-4.5") ``` -------------------------------- ### Install and Use Z.AI Java SDK Source: https://docs.z.ai/guides/image/cogview-4 This section details how to add the Z.AI Java SDK as a Maven or Gradle dependency and provides a Java code example for generating an image using the CogView-4 model. It requires an API key for authentication. ```xml ai.z.openapi zai-sdk 0.0.6 ``` ```groovy implementation 'ai.z.openapi:zai-sdk:0.0.6' ``` ```java import ai.z.openapi.ZaiClient; import ai.z.openapi.core.Constants; import ai.z.openapi.service.image.CreateImageRequest; import ai.z.openapi.service.image.ImageResponse; public class CogView4Example { public static void main(String[] args) { ZaiClient client = ZaiClient.builder().apiKey("YOUR_API_KEY").build(); // Create image generation request CreateImageRequest request = CreateImageRequest.builder() .model(Constants.ModelCogView4250304) .prompt("A cute little kitten sitting on a sunny windowsill, with the background of blue sky and white clouds.") .size("1024x1024") .build(); ImageResponse response = client.images().createImage(request); System.out.println(response.getData()); } } ``` -------------------------------- ### OpenCode IDE Integration Source: https://docs.z.ai/scenario-example/develop-tools/opencode Explains how to integrate OpenCode with IDEs like VS Code. Installation is typically automatic upon running `opencode` in the integrated terminal. Includes shortcuts for quick launching and starting new sessions. ```bash open VS Code Open the integrated terminal Run `opencode` ``` -------------------------------- ### Install OpenAI Node.js SDK Source: https://docs.z.ai/guides/overview/quick-start Instructions for installing the OpenAI Node.js SDK using both npm and yarn package managers. ```bash # Install or upgrade to latest version npm install openai # Or using yarn yarn add openai ``` -------------------------------- ### Install and Use Z.AI Python SDK Source: https://docs.z.ai/guides/llm/glm-4.5 Provides instructions for installing the Z.AI Python SDK using pip and demonstrates how to make basic and streaming chat completion calls. Includes verifying the installed SDK version. ```bash # Install latest version pip install zai-sdk # Or specify version pip install zai-sdk==0.0.4 ``` ```python import zai print(zai.__version__) ``` ```python from zai import ZaiClient client = ZaiClient(api_key="your-api-key") # Your API Key response = client.chat.completions.create( model="glm-4.5", messages=[ {"role": "user", "content": "As a marketing expert, please create an attractive slogan for my product."}, {"role": "assistant", "content": "Sure, to craft a compelling slogan, please tell me more about your product."}, {"role": "user", "content": "Z.AI Open Platform"} ], thinking={ "type": "enabled", }, max_tokens=4096, temperature=0.6 ) # Get complete response print(response.choices[0].message) ``` ```python from zai import ZaiClient client = ZaiClient(api_key="your-api-key") # Your API Key response = client.chat.completions.create( model="glm-4.5", messages=[ {"role": "user", "content": "As a marketing expert, please create an attractive slogan for my product."}, {"role": "assistant", "content": "Sure, to craft a compelling slogan, please tell me more about your product."}, {"role": "user", "content": "Z.AI Open Platform"} ], thinking={ "type": "enabled", # Optional: "disabled" or "enabled", default is "enabled" }, stream=True, max_tokens=4096, temperature=0.6 ) # Stream response for chunk in response: if chunk.choices[0].delta.reasoning_content: print(chunk.choices[0].delta.reasoning_content, end='', flush=True) if chunk.choices[0].delta.content: print(chunk.choices[0].delta.content, end='', flush=True) ``` -------------------------------- ### Install Z.AI Python SDK using pip Source: https://docs.z.ai/guides/develop/python/introduction Installs the Z.AI Python SDK using pip. Supports installing the latest version or a specific version. ```bash pip install zai-sdk # Or specify version pip install zai-sdk==0.0.4 ``` -------------------------------- ### Install ZAI MCP Server via Command Line Source: https://docs.z.ai/devpack/mcp/vision-mcp-server This bash command installs and adds the ZAI MCP server to your environment using npx. It requires replacing 'your_api_key' with your actual API key. This method is suitable for quick setup via the command line. ```bash claude mcp add -s user zai-mcp-server --env Z_AI_API_KEY=your_api_key Z_AI_MODE=ZAI -- npx -y "@z_ai/mcp-server" ``` -------------------------------- ### OpenAI Node.js SDK Usage Example for Chat Completion Source: https://docs.z.ai/guides/overview/quick-start Demonstrates how to use the OpenAI Node.js SDK to perform chat completions with Z.AI. It includes client setup with API key and base URL, and making an asynchronous chat completion request. ```javascript import OpenAI from "openai"; const client = new OpenAI({ apiKey: "your-Z.AI-api-key", baseURL: "https://api.z.ai/api/paas/v4/" }); async function main() { const completion = await client.chat.completions.create({ model: "glm-4.6", messages: [ { role: "system", content: "You are a helpful AI assistant." }, { role: "user", content: "Hello, please introduce yourself." } ] }); console.log(completion.choices[0].message.content); } main(); ``` -------------------------------- ### OpenAI Python SDK: Chat Completion with Z.AI API Source: https://docs.z.ai/api-reference/introduction This example shows how to use the OpenAI Python SDK to interact with the Z.AI API for chat completions. It covers SDK installation and a usage example where the client is initialized with the Z.AI API key and base URL. The code demonstrates creating a chat completion request and printing the model's response. ```bash # Install or upgrade to latest version pip install --upgrade 'openai>=1.0' ``` ```python python -c "import openai; print(openai.__version__)" ``` ```python from openai import OpenAI client = OpenAI( api_key="your-Z.AI-api-key", base_url="https://api.z.ai/api/paas/v4/" ) completion = client.chat.completions.create( model="glm-4.6", messages=[ {"role": "system", "content": "You are a smart and creative novelist"}, {"role": "user", "content": "Please write a short fairy tale story as a fairy tale master"} ] ) print(completion.choices[0].message.content) ``` -------------------------------- ### ViduQ1 Text-to-Video Generation with Python SDK Source: https://docs.z.ai/guides/video/vidu-q1 This section demonstrates how to use the Zai Python SDK to generate videos from text prompts. It includes instructions for installing the SDK and provides a code example for initializing the client and calling the video generation function with relevant parameters. ```bash # Install latest version pip install zai-sdk # Or specify version pip install zai-sdk==0.0.4 ``` ```python import zai print(zai.__version__) ``` ```python from zai import ZaiClient client = ZaiClient(api_key="your-api-key") response = client.videos.generations( model="viduq1-text", prompt="Peter Rabbit driving a car, wandering on the road, with a happy and joyful expression on his face.", style="general", duration=5, aspect_ratio="16:9", size="1920x1080", movement_amplitude="auto" ) print(response) ``` -------------------------------- ### OpenAI Node.js SDK: Chat Completion with Z.AI API Source: https://docs.z.ai/api-reference/introduction This example demonstrates using the OpenAI Node.js SDK to perform chat completions with the Z.AI API. It includes instructions for installing the SDK using npm or yarn. The usage example shows client initialization with the Z.AI API key and base URL, making an asynchronous chat completion request, and logging the response. ```bash # Install or upgrade to latest version npm install openai # Or using yarn yarn add openai ``` ```javascript import OpenAI from "openai"; const client = new OpenAI({ apiKey: "your-Z.AI-api-key", baseURL: "https://api.z.ai/api/paas/v4/" }); async function main() { const completion = await client.chat.completions.create({ model: "glm-4.6", messages: [ { role: "system", content: "You are a helpful AI assistant." }, { role: "user", content: "Hello, please introduce yourself." } ] }); console.log(completion.choices[0].message.content); } main(); ``` -------------------------------- ### Start and End Frame Video Generation with Zai SDK Source: https://docs.z.ai/guides/video/cogvideox-3 Generates a video by providing URLs for the start and end frames using the Zai SDK. This feature allows for controlled animation between two specified images. Requires API key and configuration of model, prompt, quality, audio, resolution, and frame rate. ```python from zai import ZaiClient # Initialize client, please fill in your own APIKey client = ZaiClient(api_key="your-api-key") # Define URLs for first frame and last frame sample_first_frame = "https://gd-hbimg.huaban.com/ccee58d77afe8f5e17a572246b1994f7e027657fe9e6-qD66In_fw1200webp" sample_last_frame = "https://gd-hbimg.huaban.com/cc2601d568a72d18d90b2cc7f1065b16b2d693f7fa3f7-hDAwNq_fw1200webp" # Call video generation API (assuming image_urls is supported) response = client.videos.generations( model="cogvideox-3", # Video generation model to use image_url=[sample_first_frame, sample_last_frame], # List of URLs for first and last frames prompt="Animate the scene", quality="quality", # Output mode, "quality" for quality priority, "speed" for speed priority with_audio=True, size="1920x1080", # Video resolution, supports up to 4K (e.g., "3840x2160") fps=30, # Frame rate, can be 30 or 60 ) # Print response print(response) # Get video result result = client.videos.retrieve_videos_result(id=response.id) print(result) ``` -------------------------------- ### POST /api/paas/v4/chat/completions (cURL) Source: https://docs.z.ai/guides/llm/glm-4.6 This endpoint allows you to interact with the GLM-4.6 model for chat completions. Examples are provided for both basic and streaming calls. ```APIDOC ## POST /api/paas/v4/chat/completions ### Description This endpoint is used to send messages to the GLM-4.6 model and receive completions. It supports both standard and streaming responses. ### Method POST ### Endpoint https://api.z.ai/api/paas/v4/chat/completions ### Parameters #### Headers - **Content-Type** (string) - Required - `application/json` - **Authorization** (string) - Required - `Bearer your-api-key` #### Request Body - **model** (string) - Required - Specifies the model to use, e.g., `glm-4.6`. - **messages** (array) - Required - An array of message objects, each with `role` (user/assistant) and `content`. - **thinking** (object) - Optional - Enables enhanced reasoning. Example: `{"type": "enabled"}`. - **stream** (boolean) - Optional - If set to `true`, the response will be streamed. - **max_tokens** (integer) - Optional - The maximum number of tokens to generate. - **temperature** (float) - Optional - Controls randomness, values typically between 0 and 2. ### Request Example (Basic Call) ```json { "model": "glm-4.6", "messages": [ { "role": "user", "content": "As a marketing expert, please create an attractive slogan for my product." }, { "role": "assistant", "content": "Sure, to craft a compelling slogan, please tell me more about your product." }, { "role": "user", "content": "Z.AI Open Platform" } ], "thinking": { "type": "enabled" }, "max_tokens": 4096, "temperature": 1.0 } ``` ### Request Example (Streaming Call) ```json { "model": "glm-4.6", "messages": [ { "role": "user", "content": "As a marketing expert, please create an attractive slogan for my product." }, { "role": "assistant", "content": "Sure, to craft a compelling slogan, please tell me more about your product." }, { "role": "user", "content": "Z.AI Open Platform" } ], "thinking": { "type": "enabled" }, "stream": true, "max_tokens": 4096, "temperature": 0.6 } ``` ### Response #### Success Response (200) (Response structure varies based on whether `stream` is true or false. For non-streaming, it's a ChatCompletion object. For streaming, it's a stream of ChatCompletionChunk objects.) #### Response Example (Non-Streaming) ```json { "id": "chatcmpl-xxxxxxxxxxxxxxxxxxxxx", "object": "chat.completion", "created": 1677652288, "model": "glm-4.6", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "Z.AI: Innovate. Integrate. Inspire." }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 100, "completion_tokens": 10, "total_tokens": 110 } } ``` ``` -------------------------------- ### Java SDK - Chat Completions Source: https://docs.z.ai/guides/llm/glm-4.6 Utilize the Zai Java SDK to integrate GLM-4.6 capabilities into your Java applications. Includes dependency information and basic call examples. ```APIDOC ## Java SDK - Chat Completions ### Description This section provides instructions for using the official Java SDK to integrate with the GLM-4.6 model. It covers dependency management and demonstrates how to perform basic chat completion calls. ### Installation **Maven** ```xml ai.z.openapi zai-sdk 0.0.6 ``` **Gradle (Groovy)** ```groovy implementation 'ai.z.openapi:zai-sdk:0.0.6' ``` ### Basic Call ```java import ai.z.openapi.ZaiClient; import ai.z.openapi.service.model.ChatCompletionCreateParams; import ai.z.openapi.service.model.ChatCompletionResponse; import ai.z.openapi.service.model.ChatMessage; import ai.z.openapi.service.model.ChatMessageRole; import ai.z.openapi.service.model.ChatThinking; import java.util.Arrays; public class BasicChat { public static void main(String[] args) { // Initialize client ZaiClient client = ZaiClient.builder() .apiKey("your-api-key") .build(); // Create chat completion request ChatCompletionCreateParams request = ChatCompletionCreateParams.builder() .model("glm-4.6") .messages(Arrays.asList( ChatMessage.builder() .role(ChatMessageRole.USER.value()) .content("As a marketing expert, please create an attractive slogan for my product.") .build(), ChatMessage.builder() .role(ChatMessageRole.ASSISTANT.value()) .content("Sure, to craft a compelling slogan, please tell me more about your product.") .build(), ChatMessage.builder() .role(ChatMessageRole.USER.value()) .content("Z.AI Open Platform") .build() )) .thinking(ChatThinking.builder().type("enabled").build()) .maxTokens(4096) .temperature(1.0) .build(); // Make the API call ChatCompletionResponse response = client.chat.completions.create(request); // Process the response if (response != null && response.getChoices() != null && !response.getChoices().isEmpty()) { System.out.println("Assistant: " + response.getChoices().get(0).getMessage().getContent()); } } } ``` ### Parameters - **apiKey** (String) - Required - Your Z.AI API key. - **model** (String) - Required - The model identifier, e.g., `"glm-4.6"`. - **messages** (List<ChatMessage>) - Required - A list of message objects, each containing `role` and `content`. - **role** (String) - Required - Role of the author (`"user"` or `"assistant"`). - **content** (String) - Required - The content of the message. - **thinking** (ChatThinking) - Optional - Configuration for the thinking process. Example: `ChatThinking.builder().type("enabled").build()`. - **maxTokens** (Integer) - Optional - The maximum number of tokens to generate in the completion. - **temperature** (Double) - Optional - Controls the randomness of the generated text. ``` -------------------------------- ### Text-to-Video Generation with Zai SDK Source: https://docs.z.ai/guides/video/cogvideox-3 Generates a video from a text prompt using the Zai SDK. Requires an API key and specifies model, prompt, quality, audio inclusion, resolution, and frame rate. Retrieves the video generation result. ```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 ) print(response) # Get video result result = client.videos.retrieve_videos_result(id=response.id) print(result) ``` -------------------------------- ### Python SDK - Chat Completions Source: https://docs.z.ai/guides/llm/glm-4.6 Integrate GLM-4.6 into your Python applications using the Zai Python SDK for chat completions. Examples cover basic and streaming calls. ```APIDOC ## Python SDK - Chat Completions ### Description This section details how to use the official Python SDK to interact with the GLM-4.6 model for chat-based interactions. It includes installation instructions and examples for both basic and streaming responses. ### Installation ```bash # Install latest version pip install zai-sdk # Or specify version pip install zai-sdk==0.0.4 ``` ### Verification ```python import zai print(zai.__version__) ``` ### Basic Call ```python from zai import ZaiClient client = ZaiClient(api_key="your-api-key") # Your API Key response = client.chat.completions.create( model="glm-4.6", messages=[ {"role": "user", "content": "As a marketing expert, please create an attractive slogan for my product."}, {"role": "assistant", "content": "Sure, to craft a compelling slogan, please tell me more about your product."}, {"role": "user", "content": "Z.AI Open Platform"} ], thinking={ "type": "enabled", }, max_tokens=4096, temperature=1.0 ) # Get complete response print(response.choices[0].message) ``` ### Streaming Call ```python from zai import ZaiClient client = ZaiClient(api_key="your-api-key") # Your API Key response = client.chat.completions.create( model="glm-4.6", messages=[ {"role": "user", "content": "As a marketing expert, please create an attractive slogan for my product."}, {"role": "assistant", "content": "Sure, to craft a compelling slogan, please tell me more about your product."}, {"role": "user", "content": "Z.AI Open Platform"} ], thinking={ "type": "enabled", # Optional: "disabled" or "enabled", default is "enabled" }, stream=True, max_tokens=4096, temperature=0.6 ) # Stream response for chunk in response: if chunk.choices[0].delta.reasoning_content: print(chunk.choices[0].delta.reasoning_content, end='', flush=True) if chunk.choices[0].delta.content: print(chunk.choices[0].delta.content, end='', flush=True) ``` ### Parameters - **api_key** (string) - Required - Your Z.AI API key. - **model** (string) - Required - Specifies the model to use, e.g., `glm-4.6`. - **messages** (list of dict) - Required - A list of message dictionaries, each with `role` and `content`. - **thinking** (dict) - Optional - Enables or disables enhanced reasoning. Example: `{"type": "enabled"}`. - **stream** (bool) - Optional - Set to `True` for streaming responses. - **max_tokens** (int) - Optional - Maximum tokens to generate. - **temperature** (float) - Optional - Controls response randomness. ``` -------------------------------- ### Create ZaiClient by Direct API Key Setting (Java) Source: https://docs.z.ai/guides/develop/java/introduction This Java example illustrates initializing the ZaiClient by directly providing your Z.AI API key during client construction. Use this method if environment variables are not feasible. Requires Java 1.8+. ```java import ai.z.openapi.ZaiClient; public class QuickStart { public static void main(String[] args) { // Set API Key directly ZaiClient client = ZaiClient.builder() .apiKey("YOUR_API_KEY") .build(); } } ``` -------------------------------- ### Generate Videos using cURL Source: https://context7 cURL examples for generating videos via the Z.AI API. Includes an initial POST request to start generation and a GET request to check the status and retrieve the video URL upon completion. ```bash # cURL example - Video generation curl -X POST "https://api.z.ai/api/paas/v4/videos/generations" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{ "model": "cogvideox-3", "prompt": "Ocean waves crashing on a beach at sunset", "quality": "speed", "with_audio": true, "size": "1920x1080", "fps": 30, "duration": 5 }' # Response: { "id": "video_task_123", "video_result": [{ "status": "processing", "url": "", "cover_image_url": "" }] } # Check status curl -X GET "https://api.z.ai/api/paas/v4/videos/video_task_123" \ -H "Authorization: Bearer YOUR_API_KEY" # Response (when complete): { "id": "video_task_123", "video_result": [{ "status": "success", "url": "https://cdn.z.ai/videos/gen_123.mp4", "cover_image_url": "https://cdn.z.ai/videos/gen_123_cover.jpg" }] } ``` -------------------------------- ### Image-to-Video Generation with Zai SDK Source: https://docs.z.ai/guides/video/cogvideox-3 Generates a video from a given image URL using the Zai SDK. Requires an API key, image URL, prompt, and allows configuration of model, quality, audio, resolution, and frame rate. Fetches the video generation result. ```python from zai import ZaiClient # Initialize the client, please fill in your own APIKey. client = ZaiClient(api_key="your-api-key") # Define the URL address of the image. image_url = "https://img.iplaysoft.com/wp-content/uploads/2019/free-images/free_stock_photo.jpg" # 替换为您的图片URL地址 # Call the video generation interface. response = client.videos.generations( model="cogvideox-3", # The video generation model used. image_url=image_url, # Please provide the image URL or Base64 encoding. prompt="Make the picture move.", quality="quality", # Output mode: "quality" prioritizes quality, and "speed" prioritizes speed. with_audio=True, size="1920x1080", # Video resolution, supports up to 4K (e.g., "3840x2160"). fps=30, # Frame rate, optional values are 30 or 60. ) # Print the returned result. print(response) # Get video result result = client.videos.retrieve_videos_result(id=response.id) print(result) ``` -------------------------------- ### Install and Use Z.AI Python SDK for Chat Completions Source: https://docs.z.ai/guides/overview/quick-start This section provides instructions for installing and using the official Z.AI Python SDK to make chat completions API calls. It includes commands for installing the SDK via pip and a Python script demonstrating client initialization and request creation. Remember to replace 'YOUR_API_KEY' with your valid API key. ```bash # Install latest version pip install zai-sdk # Or specify version pip install zai-sdk==0.0.4 ``` ```python from zai import ZaiClient # Initialize client client = ZaiClient(api_key="YOUR_API_KEY") # Create chat completion request response = client.chat.completions.create( model="glm-4.6", messages=[ { "role": "system", "content": "You are a helpful AI assistant." }, { "role": "user", "content": "Hello, please introduce yourself." } ] ) # Get response print(response.choices[0].message.content) ``` -------------------------------- ### Python Chat Completion with Z.AI API Source: https://docs.z.ai/guides/llm/glm-4.6 Example of how to perform a chat completion using the OpenAI Python SDK to interact with the Z.AI API. It shows client initialization with API key and base URL, creating a chat completion request with system and user messages, and printing the response. ```python from openai import OpenAI client = OpenAI( api_key="your-Z.AI-api-key", base_url="https://api.z.ai/api/paas/v4/" ) completion = client.chat.completions.create( model="glm-4.6", messages=[ {"role": "system", "content": "You are a smart and creative novelist"}, {"role": "user", "content": "Please write a short fairy tale story as a fairy tale master"} ] ) print(completion.choices[0].message.content) ``` -------------------------------- ### Install Claude Code with npm Source: https://docs.z.ai/devpack/quick-start Installs the Claude Code package globally using npm. Ensure Node.js 18 or a later version is installed as a prerequisite. After installation, run `claude` to start the interactive interface. ```bash # Open your terminal and install Claude Code npm install -g @anthropic-ai/claude-code # Create your working directory (e.g., `your-project`) and navigate to it using `cd` cd your-project # After installation, run `claude` to enter the Claude Code interactive interface claude ```