### Install ZhipuAI SDK Source: https://github.com/metaglm/zhipuai-sdk-python-v4/blob/main/README.md Command to install the ZhipuAI Python package via pip. ```bash pip install zhipuai ``` -------------------------------- ### Video Generation with ZhipuAI SDK Source: https://github.com/metaglm/zhipuai-sdk-python-v4/blob/main/README.md Provides a Python example for generating videos using the ZhipuAI SDK. It demonstrates setting parameters such as model, prompt, quality, audio inclusion, resolution, and FPS, and then retrieving the generation result. ```python from zhipuai import ZhipuAI client = ZhipuAI(api_key="your-api-key") response = client.videos.generations( model="cogvideox-2", prompt="A beautiful sunset beach scene", quality="quality", # Output mode: use "quality" for higher quality, "speed" for faster generation with_audio=True, # Generate video with background audio size="1920x1080", # Video resolution (up to 4K, e.g. "3840x2160") fps=30, # Frames per second (choose 30 fps or 60 fps) user_id="user_12345" ) # Generation may take some time result = client.videos.retrieve_videos_result(id=response.id) print(result) ``` -------------------------------- ### Assistant Conversation with ZhipuAI SDK Source: https://github.com/metaglm/zhipuai-sdk-python-v4/blob/main/README.md Shows how to initiate a conversation with an assistant using the ZhipuAI SDK. This example highlights the use of `assistant_id`, streaming responses, and handling message content which can include various types. ```python from zhipuai import ZhipuAI client = ZhipuAI(api_key="your-api-key") response = client.assistant.conversation( assistant_id="your_assistant_id", # You can use 65940acff94777010aa6b796 for testing model="glm-4-assistant", messages=[ { "role": "user", "content": [ { "type": "text", "text": "Help me search for the latest ZhipuAI product information" } ] } ], stream=True, attachments=None, metadata=None, request_id="request_1790291013237211136", user_id="12345678" ) for chunk in response: print(chunk) ``` -------------------------------- ### Voice Cloning (Audio Customization) with ZhipuAI Python SDK Source: https://context7.com/metaglm/zhipuai-sdk-python-v4/llms.txt This example demonstrates how to clone a voice using a sample audio file with the ZhipuAI Python SDK. It allows for personalized text-to-speech by synthesizing speech in a cloned voice. The `custom-tts` model is used, requiring a voice sample and reference text. ```python from zhipuai import ZhipuAI client = ZhipuAI(api_key="your-api-key") # Clone voice from sample audio with open("voice_sample.wav", "rb") as voice_file: response = client.audio.customization( model="custom-tts", input="This text will be spoken in the cloned voice.", voice_text="Reference text that matches the voice sample", voice_data=voice_file, response_format="mp3", request_id="voice_clone_12345" ) # Save the cloned voice output with open("cloned_output.mp3", "wb") as f: f.write(response.content) ``` -------------------------------- ### Assistant Conversations with Streaming and Querying Source: https://context7.com/metaglm/zhipuai-sdk-python-v4/llms.txt Facilitates interaction with pre-configured intelligent assistants, supporting streaming responses and conversation context. Includes examples for querying assistant support information and conversation usage history. ```python from zhipuai import ZhipuAI client = ZhipuAI(api_key="your-api-key") # Streaming assistant conversation response = client.assistant.conversation( assistant_id="65940acff94777010aa6b796", # Test assistant ID model="glm-4-assistant", messages=[{ "role": "user", "content": [{"type": "text", "text": "Help me search for the latest ZhipuAI product information"}] }], stream=True, request_id="request_12345", user_id="user_12345" ) for chunk in response: print(chunk) # Query available assistants support_info = client.assistant.query_support( assistant_id_list=["65940acff94777010aa6b796"], request_id="request_67890" ) print(support_info) # Query conversation usage history usage = client.assistant.query_conversation_usage( assistant_id="65940acff94777010aa6b796", page=1, page_size=10 ) print(usage) ``` -------------------------------- ### Perform Chat Completions Source: https://github.com/metaglm/zhipuai-sdk-python-v4/blob/main/README.md Examples of standard chat completion requests, including system prompts, user messages, and tool integration. ```python from zhipuai import ZhipuAI client = ZhipuAI(api_key="your-api-key") response = client.chat.completions.create( model="glm-4", messages=[{"role": "user", "content": "Hello, ZhipuAI!"}] ) print(response.choices[0].message.content) ``` -------------------------------- ### Manage Knowledge Bases with ZhipuAI Python SDK Source: https://context7.com/metaglm/zhipuai-sdk-python-v4/llms.txt Provides examples for creating, querying, modifying, and deleting knowledge bases for retrieval-augmented generation (RAG) applications. This involves specifying embedding models, names, descriptions, and icons. It also shows how to check capacity usage and list existing knowledge bases. ```python from zhipuai import ZhipuAI client = ZhipuAI(api_key="your-api-key") # Create a knowledge base kb = client.knowledge.create( embedding_id=3, # Embedding model ID name="Product Documentation", description="Knowledge base for product-related queries", background="blue", icon="book" ) print(f"Knowledge Base ID: {kb.id}") # Query all knowledge bases knowledge_bases = client.knowledge.query(page=1, size=10) for kb in knowledge_bases.list: print(f"KB: {kb.name}, ID: {kb.id}") # Check knowledge base capacity usage usage = client.knowledge.used() print(f"Used: {usage.used}, Total: {usage.total}") # Modify knowledge base client.knowledge.modify( knowledge_id=kb.id, embedding_id=3, name="Updated Product Documentation", description="Updated description" ) # Delete knowledge base client.knowledge.delete(knowledge_id=kb.id) ``` -------------------------------- ### File Parser with ZhipuAI Python SDK Source: https://context7.com/metaglm/zhipuai-sdk-python-v4/llms.txt This example shows how to use the ZhipuAI Python SDK's file parser to extract content from documents like PDFs. It covers creating a parsing task with different tool types and retrieving the parsed content as text or a download link. Supported `file_type` includes 'pdf'. ```python from zhipuai import ZhipuAI client = ZhipuAI(api_key="your-api-key") # Create a file parsing task with open("document.pdf", "rb") as f: task = client.file_parser.create( file=f, file_type="pdf", tool_type="zhipu-pro" # Options: "simple", "doc2x", "tencent", "zhipu-pro" ) print(f"Task ID: {task.task_id}") # Retrieve parsed content as text content = client.file_parser.content( task_id=task.task_id, format_type="text" ) print(content.content.decode('utf-8')) # Or get download link link_response = client.file_parser.content( task_id=task.task_id, format_type="download_link" ) ``` -------------------------------- ### Speech-to-Text (Audio Transcriptions) with ZhipuAI Python SDK Source: https://context7.com/metaglm/zhipuai-sdk-python-v4/llms.txt This snippet shows how to transcribe audio files to text using the ZhipuAI Python SDK. It includes examples for transcribing a local audio file and handling streaming transcription for longer audio inputs. The `whisper-1` model is used for transcription. ```python from zhipuai import ZhipuAI client = ZhipuAI(api_key="your-api-key") # Transcribe audio file with open("audio_sample.wav", "rb") as audio_file: response = client.audio.transcriptions.create( file=audio_file, model="whisper-1", request_id="transcription_12345" ) print(f"Transcription: {response.choices[0].message.content}") # Streaming transcription with open("long_audio.wav", "rb") as audio_file: response = client.audio.transcriptions.create( file=audio_file, model="whisper-1", stream=True ) for chunk in response: if chunk.choices[0].delta.content: print(chunk.choices[0].delta.content, end="") ``` -------------------------------- ### Generate Multiple Text Embeddings with ZhipuAI Python SDK Source: https://context7.com/metaglm/zhipuai-sdk-python-v4/llms.txt This snippet demonstrates how to generate embeddings for multiple text inputs using the ZhipuAI Python SDK. It utilizes the `embeddings.create` method and iterates through the response to print the dimension of each embedding. Ensure you have the ZhipuAI SDK installed and an API key configured. ```python from zhipuai import ZhipuAI client = ZhipuAI(api_key="your-api-key") response = client.embeddings.create( model="embedding-3", input=[ "Machine learning is a subset of artificial intelligence.", "Deep learning uses neural networks with multiple layers.", "Natural language processing enables computers to understand text." ] ) for i, item in enumerate(response.data): print(f"Text {i+1} embedding dimension: {len(item.embedding)}") ``` -------------------------------- ### Moderate Content with ZhipuAI Python SDK Source: https://context7.com/metaglm/zhipuai-sdk-python-v4/llms.txt Demonstrates how to use the ZhipuAI Python SDK's moderation API to check text content for policy violations and sensitive information. Examples include moderating single texts and multiple texts, and accessing the flagged status and category details of the results. ```python from zhipuai import ZhipuAI client = ZhipuAI(api_key="your-api-key") # Single text moderation response = client.moderations.create( model="moderation-1", input="This is a sample text to check for content policy violations." ) print(f"Flagged: {response.flagged}") print(f"Categories: {response.categories}") # Multiple text moderation response = client.moderations.create( model="moderation-1", input=[ "First text to moderate", "Second text to moderate", "Third text to moderate" ] ) for result in response.results: print(f"Flagged: {result.flagged}") ``` -------------------------------- ### Initialize ZhipuAI Client Source: https://context7.com/metaglm/zhipuai-sdk-python-v4/llms.txt Demonstrates how to initialize the ZhipuAI client using an API key, environment variables, or advanced configuration with custom timeouts and retry logic. Requires the 'zhipuai' and 'httpx' libraries. ```python from zhipuai import ZhipuAI import httpx # Basic initialization with API key client = ZhipuAI(api_key="your-api-key") # Or use environment variable ZHIPUAI_API_KEY import os os.environ["ZHIPUAI_API_KEY"] = "your-api-key" client = ZhipuAI() # Advanced configuration with custom settings client = ZhipuAI( api_key="your-api-key", base_url="https://open.bigmodel.cn/api/paas/v4", timeout=httpx.Timeout(timeout=300.0, connect=8.0), max_retries=3 ) ``` -------------------------------- ### Initialize and Configure ZhipuAI Client Source: https://github.com/metaglm/zhipuai-sdk-python-v4/blob/main/README.md Methods to initialize the ZhipuAI client using API keys, environment variables, or custom configurations like timeouts and retries. ```python from zhipuai import ZhipuAI import httpx # Basic initialization client = ZhipuAI(api_key="your-api-key") # Advanced configuration client = ZhipuAI( api_key="your-api-key", timeout=httpx.Timeout(timeout=300.0, connect=8.0), max_retries=3, base_url="https://open.bigmodel.cn/api/paas/v4/" ) ``` ```bash export ZHIPUAI_API_KEY="your-api-key" export ZHIPUAI_BASE_URL="https://open.bigmodel.cn/api/paas/v4/" ``` -------------------------------- ### Manage Fine-Tuning Jobs with ZhipuAI Python SDK Source: https://context7.com/metaglm/zhipuai-sdk-python-v4/llms.txt Demonstrates how to create, retrieve, list, cancel, and delete fine-tuning jobs using the ZhipuAI Python SDK. This involves specifying model, training/validation files, hyperparameters, and a suffix for custom models. It also shows how to retrieve job status, list events for logs, and manage job lifecycle. ```python from zhipuai import ZhipuAI client = ZhipuAI(api_key="your-api-key") # Create a fine-tuning job job = client.fine_tuning.jobs.create( model="glm-4", training_file="file_training_123", validation_file="file_validation_456", hyperparameters={ "n_epochs": 3, "learning_rate_multiplier": 0.1, "batch_size": 4 }, suffix="my-custom-model" ) print(f"Fine-tuning job ID: {job.id}") print(f"Status: {job.status}") # Retrieve job status job_status = client.fine_tuning.jobs.retrieve(fine_tuning_job_id=job.id) print(f"Job status: {job_status.status}") print(f"Trained tokens: {job_status.trained_tokens}") # List all fine-tuning jobs jobs = client.fine_tuning.jobs.list(limit=10) for j in jobs.data: print(f"Job: {j.id}, Status: {j.status}, Model: {j.model}") # List job events (training logs) events = client.fine_tuning.jobs.list_events( fine_tuning_job_id=job.id, limit=20 ) for event in events.data: print(f"[{event.created_at}] {event.message}") # Cancel a running job cancelled_job = client.fine_tuning.jobs.cancel(fine_tuning_job_id=job.id) print(f"Job cancelled: {cancelled_job.status}") # Delete a completed job deleted_job = client.fine_tuning.jobs.delete(fine_tuning_job_id=job.id) ``` ``` -------------------------------- ### Character Role-Playing with ZhipuAI SDK Source: https://github.com/metaglm/zhipuai-sdk-python-v4/blob/main/README.md Demonstrates how to use the ZhipuAI SDK to engage in character role-playing. This involves setting up the client with an API key and defining user and bot personas within the messages payload for a more immersive interaction. ```python from zhipuai import ZhipuAI client = ZhipuAI(api_key="your-api-key") response = client.chat.completions.create( model="charglm-3", messages=[ { "role": "user", "content": "Hello, how are you doing lately?" } ], meta={ "user_info": "I am a film director who specializes in music-themed movies.", "bot_info": "You are a popular domestic female singer and actress with outstanding musical talent.", "bot_name": "Xiaoya", "user_name": "Director" } ) print(response) ``` -------------------------------- ### File Management with ZhipuAI Python SDK Source: https://context7.com/metaglm/zhipuai-sdk-python-v4/llms.txt This code snippet illustrates file management operations using the ZhipuAI Python SDK, including uploading files for fine-tuning, listing uploaded files, downloading file content, and deleting files. It covers the `files.create`, `files.list`, `files.content`, and `files.delete` methods. ```python from zhipuai import ZhipuAI client = ZhipuAI(api_key="your-api-key") # Upload a file for fine-tuning with open("training_data.jsonl", "rb") as f: file_object = client.files.create( file=f, purpose="fine-tune" ) print(f"File ID: {file_object.id}") print(f"Filename: {file_object.filename}") # List uploaded files files = client.files.list( purpose="fine-tune", limit=10, order="desc" ) for file in files.data: print(f"File: {file.filename}, ID: {file.id}, Size: {file.bytes}") # Download file content content = client.files.content(file_id="file_123456") with open("downloaded_file.jsonl", "wb") as f: f.write(content.content) # Delete a file result = client.files.delete(file_id="file_123456") print(f"Deleted: {result.deleted}") ``` -------------------------------- ### Perform Web Searches with ZhipuAI Python SDK Source: https://context7.com/metaglm/zhipuai-sdk-python-v4/llms.txt Illustrates how to perform web searches using the ZhipuAI Python SDK, both directly via the web search API and through the tools API with streaming. This allows retrieving real-time information from the internet, specifying search queries, engines, counts, recency filters, and content sizes. ```python from zhipuai import ZhipuAI client = ZhipuAI(api_key="your-api-key") # Direct web search API response = client.web_search.web_search( search_query="Latest developments in artificial intelligence 2024", search_engine="google", count=10, search_recency_filter="month", content_size="medium", search_intent=True, location="us" ) for result in response.search_result: print(f"Title: {result.title}") print(f"URL: {result.link}") print(f"Snippet: {result.content}") print("---") # Web search via tools API with streaming response = client.tools.web_search( model="web-search-pro", messages=[{"role": "user", "content": "What are the latest AI news?"}], stream=True, scope="general", recent_days=7 ) for chunk in response: print(chunk) ``` -------------------------------- ### Create Chat Completions Source: https://context7.com/metaglm/zhipuai-sdk-python-v4/llms.txt Shows how to generate chat completions using GLM models, including basic requests, enabling web search tools, and setting custom parameters like temperature and max tokens. Requires the 'zhipuai' library. ```python from zhipuai import ZhipuAI client = ZhipuAI(api_key="your-api-key") # Basic chat completion response = client.chat.completions.create( model="glm-4", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "What is artificial intelligence?"} ] ) print(response.choices[0].message.content) # Chat with web search tool enabled response = client.chat.completions.create( model="glm-4", messages=[ {"role": "user", "content": "What are the latest AI news today?"} ], tools=[ { "type": "web_search", "web_search": { "search_query": "latest AI news", "search_result": True } } ], extra_body={"temperature": 0.7, "max_tokens": 1024} ) print(response.choices[0].message.content) ``` -------------------------------- ### Process Data in Batches with ZhipuAI Python SDK Source: https://context7.com/metaglm/zhipuai-sdk-python-v4/llms.txt Shows how to create, retrieve, list, and cancel batch jobs for asynchronous processing of large volumes of requests. This includes specifying input file IDs, endpoints for chat completions or embeddings, completion windows, and metadata. It also demonstrates retrieving batch status and request counts. ```python from zhipuai import ZhipuAI client = ZhipuAI(api_key="your-api-key") # Create batch job from uploaded JSONL file batch = client.batches.create( input_file_id="file_batch_input_123", endpoint="/v1/chat/completions", # or "/v1/embeddings" completion_window="24h", metadata={"description": "Customer support batch"}, auto_delete_input_file=True ) print(f"Batch ID: {batch.id}") print(f"Status: {batch.status}") # Retrieve batch status batch_status = client.batches.retrieve(batch_id=batch.id) print(f"Status: {batch_status.status}") print(f"Request counts: {batch_status.request_counts}") # List all batches batches = client.batches.list(limit=10) for b in batches.data: print(f"Batch: {b.id}, Status: {b.status}") # Cancel a batch cancelled = client.batches.cancel(batch_id=batch.id) print(f"Cancelled: {cancelled.status}") ``` -------------------------------- ### Fine-Tuning Models with ZhipuAI Python SDK Source: https://context7.com/metaglm/zhipuai-sdk-python-v4/llms.txt This snippet outlines the process of initiating and managing fine-tuning jobs using the ZhipuAI Python SDK. Fine-tuning allows you to customize AI models with your specific training data for improved performance on specialized tasks. The code requires an API key and prepared training data. ```python from zhipuai import ZhipuAI client = ZhipuAI(api_key="your-api-key") # Further code for fine-tuning job creation and management would go here. ``` -------------------------------- ### Video Generation Source: https://context7.com/metaglm/zhipuai-sdk-python-v4/llms.txt Create AI-generated videos from text prompts with customizable resolution, frame rate, and audio options. Video generation is asynchronous, requiring polling for results. ```APIDOC ## Video Generation ### Description Create AI-generated videos from text prompts with customizable resolution, frame rate, and audio options. Video generation is asynchronous, requiring polling for results. ### Method POST ### Endpoint /v4/videos/generations ### Parameters #### Query Parameters - **model** (string) - Required - The video generation model to use (e.g., "cogvideox-2"). - **prompt** (string) - Required - The text description for the video to generate. - **quality** (string) - Optional - The quality setting for the video generation ("quality" or "speed"). - **with_audio** (boolean) - Optional - Whether to include background audio. - **size** (string) - Optional - The desired resolution of the video (e.g., "1920x1080"). - **fps** (integer) - Optional - The frames per second for the video (30 or 60). - **user_id** (string) - Optional - A unique identifier for the user. ### Request Example ```python { "model": "cogvideox-2", "prompt": "A beautiful sunset beach scene with gentle waves", "quality": "quality", "with_audio": true, "size": "1920x1080", "fps": 30, "user_id": "user_12345" } ``` ### Response #### Success Response (200) - **id** (string) - The ID of the video generation task. ### Method GET ### Endpoint /v4/videos/retrieve_videos_result ### Parameters #### Query Parameters - **id** (string) - Required - The ID of the video generation task to retrieve results for. ### Response #### Success Response (200) - **task_status** (string) - The status of the video generation task (e.g., "SUCCESS", "FAIL"). - **video_result** (array) - A list of video results if the task was successful. - **url** (string) - The URL of the generated video. ``` -------------------------------- ### Text-to-Speech (Audio Speech) with ZhipuAI Python SDK Source: https://context7.com/metaglm/zhipuai-sdk-python-v4/llms.txt This code demonstrates text-to-speech conversion using the ZhipuAI Python SDK. It covers both non-streaming and streaming audio generation, allowing you to save the output to MP3 files. Key parameters include `model`, `input`, `voice`, `response_format`, `encode_format`, and `stream`. ```python from zhipuai import ZhipuAI client = ZhipuAI(api_key="your-api-key") # Non-streaming audio generation response = client.audio.speech( model="tts-1", input="Hello, welcome to ZhipuAI. This is a text-to-speech demonstration.", voice="alloy", response_format="mp3", encode_format="mp3", stream=False, request_id="audio_12345" ) # Save audio to file with open("output.mp3", "wb") as f: f.write(response.content) # Streaming audio generation response = client.audio.speech( model="tts-1", input="This is a streaming audio example with real-time output.", voice="alloy", encode_format="mp3", stream=True ) with open("stream_output.mp3", "wb") as f: for chunk in response: f.write(chunk.audio) ``` -------------------------------- ### Error Handling with ZhipuAI SDK Source: https://github.com/metaglm/zhipuai-sdk-python-v4/blob/main/README.md Illustrates comprehensive error handling for the ZhipuAI SDK in Python. It shows how to catch specific API errors like `APIStatusError`, `APITimeoutError`, and general exceptions, providing informative messages for each. ```python from zhipuai import ZhipuAI import zhipuai client = ZhipuAI() try: response = client.chat.completions.create( model="glm-4", messages=[ {"role": "user", "content": "Hello, ZhipuAI!"} ] ) print(response.choices[0].message.content) except zhipuai.APIStatusError as err: print(f"API Status Error: {err}") except zhipuai.APITimeoutError as err: print(f"Request Timeout: {err}") except Exception as err: print(f"Other Error: {err}") ``` -------------------------------- ### Multimodal Chat with Images Source: https://github.com/metaglm/zhipuai-sdk-python-v4/blob/main/README.md Shows how to encode an image to base64 and send it as part of a multimodal chat completion request. ```python import base64 def encode_image(image_path): with open(image_path, "rb") as image_file: return base64.b64encode(image_file.read()).decode('utf-8') base64_image = encode_image("path/to/your/image.jpg") response = client.chat.completions.create( model="glm-4v", messages=[{ "role": "user", "content": [ {"type": "text", "text": "What's in this image?"}, {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"}} ] }] ) ``` -------------------------------- ### Character Role-Playing with CharGLM-3 Source: https://context7.com/metaglm/zhipuai-sdk-python-v4/llms.txt Utilize the CharGLM-3 model to create immersive character interactions with customizable personas for both the bot and user, enabling rich role-playing experiences. ```APIDOC ## Character Role-Playing ### Description Create immersive character interactions using the CharGLM-3 model with customizable personas for both the bot and user, enabling rich role-playing experiences. ### Method POST ### Endpoint /v4/chat/completions ### Parameters #### Request Body - **model** (string) - Required - The model to use for generation (e.g., "charglm-3"). - **messages** (array) - Required - A list of message objects representing the conversation history. - **role** (string) - Required - The role of the message sender ('user' or 'assistant'). - **content** (string) - Required - The content of the message. - **meta** (object) - Optional - Metadata for customizing the interaction. - **user_info** (string) - Optional - Information about the user's persona. - **bot_info** (string) - Optional - Information about the bot's persona. - **bot_name** (string) - Optional - The name of the bot. - **user_name** (string) - Optional - The name of the user. ### Request Example ```python { "model": "charglm-3", "messages": [ {"role": "user", "content": "Hello, how are you doing lately?"} ], "meta": { "user_info": "I am a film director who specializes in music-themed movies.", "bot_info": "You are a popular domestic female singer and actress with outstanding musical talent.", "bot_name": "Xiaoya", "user_name": "Director" } } ``` ### Response #### Success Response (200) - **choices** (array) - A list of message choices. - **message** (object) - **content** (string) - The generated response content. ``` -------------------------------- ### Invoking Custom Agents with Streaming and Async Results Source: https://context7.com/metaglm/zhipuai-sdk-python-v4/llms.txt Allows invocation of custom AI agents for specialized tasks, supporting streaming responses and both synchronous and asynchronous execution. Demonstrates how to retrieve results for long-running agent tasks. ```python from zhipuai import ZhipuAI client = ZhipuAI(api_key="your-api-key") # Invoke agent with streaming response = client.agents.invoke( agent_id="your_agent_id", messages=[{"role": "user", "content": "Help me analyze this data"}], stream=True, user_id="user_12345", custom_variables={"key": "value"} ) for chunk in response: print(chunk) # Get async result for long-running agent tasks result = client.agents.async_result( agent_id="your_agent_id", async_id="async_task_id", conversation_id="conversation_id" ) print(result) ``` -------------------------------- ### Implement Exception Handling for ZhipuAI API Requests Source: https://context7.com/metaglm/zhipuai-sdk-python-v4/llms.txt This snippet demonstrates how to wrap ZhipuAI API calls in a try-except block to handle various SDK-specific exceptions. It covers common error scenarios including authentication, rate limiting, and server-side failures to ensure application stability. ```python from zhipuai import ZhipuAI import zhipuai client = ZhipuAI(api_key="your-api-key") try: response = client.chat.completions.create( model="glm-4", messages=[{"role": "user", "content": "Hello!"}] ) print(response.choices[0].message.content) except zhipuai.APIAuthenticationError as e: print(f"Authentication failed: {e}") print(f"Status code: {e.status_code}") except zhipuai.APIReachLimitError as e: print(f"Rate limit exceeded: {e}") except zhipuai.APIRequestFailedError as e: print(f"Invalid request: {e}") print(f"Response: {e.response.text}") except zhipuai.APIInternalError as e: print(f"Server error: {e}") except zhipuai.APIServerFlowExceedError as e: print(f"Server overloaded: {e}") except zhipuai.APITimeoutError as e: print(f"Request timed out: {e}") except zhipuai.APIConnectionError as e: print(f"Connection error: {e}") except zhipuai.APIStatusError as e: print(f"API error: {e}") print(f"Status: {e.status_code}") except zhipuai.ZhipuAIError as e: print(f"ZhipuAI error: {e}") ``` -------------------------------- ### Streaming Chat Responses Source: https://github.com/metaglm/zhipuai-sdk-python-v4/blob/main/README.md Demonstrates how to handle real-time streaming responses from the ZhipuAI API by iterating through chunks. ```python response = client.chat.completions.create( model="glm-4", messages=[{"role": "user", "content": "Tell me a story about AI."}], stream=True ) for chunk in response: if chunk.choices[0].delta.content: print(chunk.choices[0].delta) ``` -------------------------------- ### Image Generation Source: https://context7.com/metaglm/zhipuai-sdk-python-v4/llms.txt Generate images from text prompts using AI models. Supports various sizes, styles, and quality settings for customized image creation. ```APIDOC ## Image Generation ### Description Generate images from text prompts using AI models. Supports various sizes, styles, and quality settings for customized image creation. ### Method POST ### Endpoint /v4/images/generations ### Parameters #### Query Parameters - **prompt** (string) - Required - The text description for the image to generate. - **model** (string) - Required - The image generation model to use (e.g., "cogview-3"). - **size** (string) - Optional - The desired size of the generated image (e.g., "1024x1024"). - **quality** (string) - Optional - The quality setting for the image generation (e.g., "standard"). - **n** (integer) - Optional - The number of images to generate. - **request_id** (string) - Optional - A unique identifier for the request. - **user_id** (string) - Optional - A unique identifier for the user. ### Request Example ```python { "prompt": "A futuristic city skyline at sunset with flying cars", "model": "cogview-3", "size": "1024x1024", "quality": "standard", "n": 1, "request_id": "img_request_12345", "user_id": "user_12345" } ``` ### Response #### Success Response (200) - **data** (array) - A list of generated image objects. - **url** (string) - The URL of the generated image. ``` -------------------------------- ### Stream Chat Completions Source: https://context7.com/metaglm/zhipuai-sdk-python-v4/llms.txt Enables streaming responses for chat completions, allowing real-time, token-by-token output suitable for interactive applications. Requires the 'zhipuai' library. ```python from zhipuai import ZhipuAI client = ZhipuAI(api_key="your-api-key") response = client.chat.completions.create( model="glm-4", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Tell me a story about AI."} ], stream=True ) # Process streaming chunks for chunk in response: if chunk.choices[0].delta.content: print(chunk.choices[0].delta.content, end="", flush=True) print() # New line after completion ``` -------------------------------- ### Video Generation with ZhipuAI and Polling Source: https://context7.com/metaglm/zhipuai-sdk-python-v4/llms.txt Creates AI-generated videos from text prompts with customizable resolution, frame rate, and audio. This process is asynchronous, requiring polling to retrieve the final video URL upon successful generation. ```python from zhipuai import ZhipuAI import time client = ZhipuAI(api_key="your-api-key") # Start video generation response = client.videos.generations( model="cogvideox-2", prompt="A beautiful sunset beach scene with gentle waves", quality="quality", # "quality" for higher quality, "speed" for faster with_audio=True, # Include background audio size="1920x1080", # Video resolution fps=30, # Frames per second (30 or 60) user_id="user_12345" ) print(f"Video generation started: {response.id}") # Poll for results while True: result = client.videos.retrieve_videos_result(id=response.id) if result.task_status == "SUCCESS": print(f"Video URL: {result.video_result[0].url}") break elif result.task_status == "FAIL": print("Video generation failed") break time.sleep(10) ``` -------------------------------- ### Assistant Conversations Source: https://context7.com/metaglm/zhipuai-sdk-python-v4/llms.txt Interact with pre-configured intelligent assistants that have specialized capabilities. Assistants support streaming responses and can maintain conversation context. ```APIDOC ## Assistant Conversations ### Description Interact with pre-configured intelligent assistants that have specialized capabilities. Assistants support streaming responses and can maintain conversation context. ### Method POST ### Endpoint /v4/assistant/conversation ### Parameters #### Query Parameters - **assistant_id** (string) - Required - The ID of the assistant to interact with. - **model** (string) - Required - The model to use for the conversation (e.g., "glm-4-assistant"). - **messages** (array) - Required - A list of message objects representing the conversation history. - **role** (string) - Required - The role of the message sender ('user' or 'assistant'). - **content** (array) - Required - The content of the message, which can include text or other types. - **type** (string) - Required - The type of content (e.g., "text"). - **text** (string) - Required - The text content. - **stream** (boolean) - Optional - Whether to stream the response. - **request_id** (string) - Optional - A unique identifier for the request. - **user_id** (string) - Optional - A unique identifier for the user. ### Request Example (Streaming) ```python { "assistant_id": "65940acff94777010aa6b796", "model": "glm-4-assistant", "messages": [ {"role": "user", "content": [{"type": "text", "text": "Help me search for the latest ZhipuAI product information"}]} ], "stream": true, "request_id": "request_12345", "user_id": "user_12345" } ``` ### Response #### Success Response (200) - **chunk** (string) - For streaming responses, each chunk of the assistant's reply. ### Method POST ### Endpoint /v4/assistant/query_support ### Parameters #### Query Parameters - **assistant_id_list** (array) - Required - A list of assistant IDs to query support information for. - **request_id** (string) - Optional - A unique identifier for the request. ### Response #### Success Response (200) - **support_info** (object) - Information about the supported features of the assistants. ### Method POST ### Endpoint /v4/assistant/query_conversation_usage ### Parameters #### Query Parameters - **assistant_id** (string) - Required - The ID of the assistant. - **page** (integer) - Optional - The page number for the usage history. - **page_size** (integer) - Optional - The number of items per page. ### Response #### Success Response (200) - **usage** (object) - Conversation usage history. ``` -------------------------------- ### Multimodal Chat with Vision Source: https://context7.com/metaglm/zhipuai-sdk-python-v4/llms.txt Utilizes the GLM-4V model for multimodal chat, allowing image analysis via URLs or base64-encoded data combined with text prompts. Requires 'zhipuai' and 'base64' libraries. ```python import base64 from zhipuai import ZhipuAI def encode_image(image_path): """Encode image to base64 format""" with open(image_path, "rb") as image_file: return base64.b64encode(image_file.read()).decode('utf-8') client = ZhipuAI(api_key="your-api-key") # Using base64-encoded image base64_image = encode_image("path/to/your/image.jpg") response = client.chat.completions.create( model="glm-4v", messages=[{ "role": "user", "content": [ {"type": "text", "text": "What's in this image? Describe it in detail."}, { "type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"} } ] }], extra_body={"temperature": 0.5, "max_tokens": 500} ) print(response.choices[0].message.content) # Using image URL response = client.chat.completions.create( model="glm-4v", messages=[{ "role": "user", "content": [ {"type": "text", "text": "Describe this image"}, {"type": "image_url", "image_url": {"url": "https://example.com/image.jpg"}} ] }] ) print(response.choices[0].message.content) ``` -------------------------------- ### Image Generation with ZhipuAI Source: https://context7.com/metaglm/zhipuai-sdk-python-v4/llms.txt Generates images from text prompts using AI models, offering customization for size, style, and quality. The response provides URLs to the generated images. ```python from zhipuai import ZhipuAI client = ZhipuAI(api_key="your-api-key") response = client.images.generations( prompt="A futuristic city skyline at sunset with flying cars", model="cogview-3", size="1024x1024", quality="standard", n=1, request_id="img_request_12345", user_id="user_12345" ) # Access generated image URLs for image in response.data: print(f"Image URL: {image.url}") ``` -------------------------------- ### Agents Source: https://context7.com/metaglm/zhipuai-sdk-python-v4/llms.txt Invoke custom AI agents for specialized tasks. Agents can be configured with custom variables and support both synchronous and asynchronous execution. ```APIDOC ## Agents ### Description Invoke custom AI agents for specialized tasks. Agents can be configured with custom variables and support both synchronous and asynchronous execution. ### Method POST ### Endpoint /v4/agents/invoke ### Parameters #### Query Parameters - **agent_id** (string) - Required - The ID of the agent to invoke. - **messages** (array) - Required - A list of message objects representing the conversation history. - **role** (string) - Required - The role of the message sender ('user' or 'assistant'). - **content** (string) - Required - The content of the message. - **stream** (boolean) - Optional - Whether to stream the response. - **user_id** (string) - Optional - A unique identifier for the user. - **custom_variables** (object) - Optional - Key-value pairs for custom variables. ### Request Example (Streaming) ```python { "agent_id": "your_agent_id", "messages": [ {"role": "user", "content": "Help me analyze this data"} ], "stream": true, "user_id": "user_12345", "custom_variables": {"key": "value"} } ``` ### Response #### Success Response (200) - **chunk** (string) - For streaming responses, each chunk of the agent's output. ### Method POST ### Endpoint /v4/agents/async_result ### Parameters #### Query Parameters - **agent_id** (string) - Required - The ID of the agent. - **async_id** (string) - Required - The ID of the asynchronous task. - **conversation_id** (string) - Required - The ID of the conversation. ### Response #### Success Response (200) - **result** (object) - The result of the asynchronous agent task. ``` -------------------------------- ### Character Role-Playing with CharGLM-3 Source: https://context7.com/metaglm/zhipuai-sdk-python-v4/llms.txt Enables immersive character interactions by defining personas for both the user and the bot. This feature utilizes the CharGLM-3 model to facilitate rich role-playing experiences. ```python from zhipuai import ZhipuAI client = ZhipuAI(api_key="your-api-key") response = client.chat.completions.create( model="charglm-3", messages=[ {"role": "user", "content": "Hello, how are you doing lately?"} ], meta={ "user_info": "I am a film director who specializes in music-themed movies.", "bot_info": "You are a popular domestic female singer and actress with outstanding musical talent.", "bot_name": "Xiaoya", "user_name": "Director" } ) print(response.choices[0].message.content) ``` -------------------------------- ### Text Embeddings Source: https://context7.com/metaglm/zhipuai-sdk-python-v4/llms.txt Generate vector embeddings for text inputs, useful for semantic search, similarity comparison, and RAG (Retrieval-Augmented Generation) applications. ```APIDOC ## Text Embeddings ### Description Generate vector embeddings for text inputs, useful for semantic search, similarity comparison, and RAG (Retrieval-Augmented Generation) applications. ### Method POST ### Endpoint /v4/embeddings/create ### Parameters #### Query Parameters - **model** (string) - Required - The embedding model to use (e.g., "embedding-3"). - **input** (string or array) - Required - The text or list of texts to generate embeddings for. - **dimensions** (integer) - Optional - The desired dimensionality of the embeddings. ### Request Example ```python { "model": "embedding-3", "input": "What is machine learning?", "dimensions": 1024 } ``` ### Response #### Success Response (200) - **data** (array) - A list of embedding objects. - **embedding** (array) - The generated vector embedding. ``` -------------------------------- ### Text Embeddings Generation with ZhipuAI Source: https://context7.com/metaglm/zhipuai-sdk-python-v4/llms.txt Generates vector embeddings for text inputs, essential for applications like semantic search, similarity comparison, and Retrieval-Augmented Generation (RAG). ```python from zhipuai import ZhipuAI client = ZhipuAI(api_key="your-api-key") # Single text embedding response = client.embeddings.create( model="embedding-3", input="What is machine learning?", dimensions=1024 ) print(f"Embedding dimension: {len(response.data[0].embedding)}") print(f"Embedding: {response.data[0].embedding[:5]}...") # First 5 values ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.