zhipuai


Namezhipuai JSON
Version 2.1.5.20250801 PyPI version JSON
download
home_pageNone
SummaryA SDK library for accessing big model apis from ZhipuAI
upload_time2025-08-01 11:16:16
maintainerNone
docs_urlNone
authorZhipu AI
requires_python!=2.7.*,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,!=3.7.*,>=3.8
licenseNone
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # ZhipuAI Open Platform Python SDK

[![PyPI version](https://img.shields.io/pypi/v/zhipuai.svg)](https://pypi.org/project/zhipuai/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Python](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)

[中文文档](README_CN.md) | English

The official Python SDK for ZhipuAI's large model open interface, making it easier for developers to call ZhipuAI's open APIs.

## ✨ Features

- **Type Safety**: Complete type annotations for all interfaces
- **Easy Integration**: Simple initialization and intuitive method calls
- **High Performance**: Built-in connection pooling and request optimization
- **Secure**: Automatic token caching and secure API key management
- **Lightweight**: Minimal dependencies with efficient resource usage
- **Streaming Support**: Real-time streaming responses for chat completions

## 📦 Installation

### Requirements

- **Python**: 3.9+
- **Package Manager**: pip

### Install via pip

```bash
pip install zhipuai
```

### Core Dependencies

| Package | Version | Purpose |
|---------|---------|----------|
| `httpx` | `>=0.23.0` | HTTP client for API requests |
| `pydantic` | `>=1.9.0,<3.0.0` | Data validation and serialization |
| `typing-extensions` | `>=4.0.0` | Enhanced type hints support |

## 🚀 Quick Start

### Basic Usage

```python
from zhipuai import ZhipuAI

# Initialize client
client = ZhipuAI(api_key="your-api-key")

# Create chat completion
response = client.chat.completions.create(
    model="glm-4",
    messages=[
        {"role": "user", "content": "Hello, ZhipuAI!"}
    ]
)
print(response.choices[0].message.content)
```

### Client Configuration

#### Environment Variables

```bash
export ZHIPUAI_API_KEY="your-api-key"
export ZHIPUAI_BASE_URL="https://open.bigmodel.cn/api/paas/v4/"  # Optional
```

#### Code Configuration

```python
from zhipuai import ZhipuAI

client = ZhipuAI(
    api_key="your-api-key",
    base_url="https://open.bigmodel.cn/api/paas/v4/"  # Optional
)
```

### Advanced Configuration

Customize client behavior with additional parameters:

```python
from zhipuai import ZhipuAI
import httpx

client = ZhipuAI(
    api_key="your-api-key",
    timeout=httpx.Timeout(timeout=300.0, connect=8.0),  # Request timeout
    max_retries=3,  # Retry attempts
    base_url="https://open.bigmodel.cn/api/paas/v4/"  # Custom API endpoint
)
```

## 📖 Usage Examples

### Basic Chat

```python
from zhipuai import ZhipuAI

client = ZhipuAI(api_key="your-api-key")  # Uses environment variable ZHIPUAI_API_KEY
response = client.chat.completions.create(
    model="glm-4",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "What is artificial intelligence?"}
    ],
    tools=[
        {
            "type": "web_search",
            "web_search": {
                "search_query": "Search the Zhipu",
                "search_result": True,
            }
        }
    ],
    extra_body={"temperature": 0.5, "max_tokens": 50}
)
print(response)
```

### Streaming Chat

```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
)

for chunk in response:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta)
```

### Multimodal Chat

```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")
base64_image = encode_image("path/to/your/image.jpg")

response = client.chat.completions.create(
    model="glm-4v",
    extra_body={"temperature": 0.5, "max_tokens": 50},
    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}"
                    }
                }
            ]
        }
    ]
)
print(response)
```

### Character Role-Playing

```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)
```

### Assistant Conversation

```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)
```

### Video Generation

```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)
```

## 🚨 Error Handling

The SDK provides comprehensive error handling:

```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}")
```

### Error Codes

| Status Code | Error Type | Description |
|-------------|------------|-------------|
| 400 | `APIRequestFailedError` | Invalid request parameters |
| 401 | `APIAuthenticationError` | Authentication failed |
| 429 | `APIReachLimitError` | Rate limit exceeded |
| 500 | `APIInternalError` | Internal server error |
| 503 | `APIServerFlowExceedError` | Server overloaded |
| N/A | `APIStatusError` | General API error |

## 📈 Version Updates

For detailed version history and update information, please see [Release-Note.md](Release-Note.md).

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## 🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## 📞 Support

For questions and technical support, please visit [ZhipuAI Open Platform](https://open.bigmodel.cn/) or check our documentation.
  


            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "zhipuai",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "!=2.7.*,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,!=3.7.*,>=3.8",
    "maintainer_email": null,
    "keywords": null,
    "author": "Zhipu AI",
    "author_email": null,
    "download_url": "https://files.pythonhosted.org/packages/3c/23/49aae9dc28443ab7d29f9b15ab3b1ceec634210c1ed24ee1c9fa34167351/zhipuai-2.1.5.20250801.tar.gz",
    "platform": null,
    "description": "# ZhipuAI Open Platform Python SDK\n\n[![PyPI version](https://img.shields.io/pypi/v/zhipuai.svg)](https://pypi.org/project/zhipuai/)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![Python](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)\n\n[\u4e2d\u6587\u6587\u6863](README_CN.md) | English\n\nThe official Python SDK for ZhipuAI's large model open interface, making it easier for developers to call ZhipuAI's open APIs.\n\n## \u2728 Features\n\n- **Type Safety**: Complete type annotations for all interfaces\n- **Easy Integration**: Simple initialization and intuitive method calls\n- **High Performance**: Built-in connection pooling and request optimization\n- **Secure**: Automatic token caching and secure API key management\n- **Lightweight**: Minimal dependencies with efficient resource usage\n- **Streaming Support**: Real-time streaming responses for chat completions\n\n## \ud83d\udce6 Installation\n\n### Requirements\n\n- **Python**: 3.9+\n- **Package Manager**: pip\n\n### Install via pip\n\n```bash\npip install zhipuai\n```\n\n### Core Dependencies\n\n| Package | Version | Purpose |\n|---------|---------|----------|\n| `httpx` | `>=0.23.0` | HTTP client for API requests |\n| `pydantic` | `>=1.9.0,<3.0.0` | Data validation and serialization |\n| `typing-extensions` | `>=4.0.0` | Enhanced type hints support |\n\n## \ud83d\ude80 Quick Start\n\n### Basic Usage\n\n```python\nfrom zhipuai import ZhipuAI\n\n# Initialize client\nclient = ZhipuAI(api_key=\"your-api-key\")\n\n# Create chat completion\nresponse = client.chat.completions.create(\n    model=\"glm-4\",\n    messages=[\n        {\"role\": \"user\", \"content\": \"Hello, ZhipuAI!\"}\n    ]\n)\nprint(response.choices[0].message.content)\n```\n\n### Client Configuration\n\n#### Environment Variables\n\n```bash\nexport ZHIPUAI_API_KEY=\"your-api-key\"\nexport ZHIPUAI_BASE_URL=\"https://open.bigmodel.cn/api/paas/v4/\"  # Optional\n```\n\n#### Code Configuration\n\n```python\nfrom zhipuai import ZhipuAI\n\nclient = ZhipuAI(\n    api_key=\"your-api-key\",\n    base_url=\"https://open.bigmodel.cn/api/paas/v4/\"  # Optional\n)\n```\n\n### Advanced Configuration\n\nCustomize client behavior with additional parameters:\n\n```python\nfrom zhipuai import ZhipuAI\nimport httpx\n\nclient = ZhipuAI(\n    api_key=\"your-api-key\",\n    timeout=httpx.Timeout(timeout=300.0, connect=8.0),  # Request timeout\n    max_retries=3,  # Retry attempts\n    base_url=\"https://open.bigmodel.cn/api/paas/v4/\"  # Custom API endpoint\n)\n```\n\n## \ud83d\udcd6 Usage Examples\n\n### Basic Chat\n\n```python\nfrom zhipuai import ZhipuAI\n\nclient = ZhipuAI(api_key=\"your-api-key\")  # Uses environment variable ZHIPUAI_API_KEY\nresponse = client.chat.completions.create(\n    model=\"glm-4\",\n    messages=[\n        {\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},\n        {\"role\": \"user\", \"content\": \"What is artificial intelligence?\"}\n    ],\n    tools=[\n        {\n            \"type\": \"web_search\",\n            \"web_search\": {\n                \"search_query\": \"Search the Zhipu\",\n                \"search_result\": True,\n            }\n        }\n    ],\n    extra_body={\"temperature\": 0.5, \"max_tokens\": 50}\n)\nprint(response)\n```\n\n### Streaming Chat\n\n```python\nfrom zhipuai import ZhipuAI\n\nclient = ZhipuAI(api_key=\"your-api-key\")\nresponse = client.chat.completions.create(\n    model=\"glm-4\",\n    messages=[\n        {\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},\n        {\"role\": \"user\", \"content\": \"Tell me a story about AI.\"}\n    ],\n    stream=True\n)\n\nfor chunk in response:\n    if chunk.choices[0].delta.content:\n        print(chunk.choices[0].delta)\n```\n\n### Multimodal Chat\n\n```python\nimport base64\nfrom zhipuai import ZhipuAI\n\ndef encode_image(image_path):\n    \"\"\"Encode image to base64 format\"\"\"\n    with open(image_path, \"rb\") as image_file:\n        return base64.b64encode(image_file.read()).decode('utf-8')\n\nclient = ZhipuAI(api_key=\"your-api-key\")\nbase64_image = encode_image(\"path/to/your/image.jpg\")\n\nresponse = client.chat.completions.create(\n    model=\"glm-4v\",\n    extra_body={\"temperature\": 0.5, \"max_tokens\": 50},\n    messages=[\n        {\n            \"role\": \"user\",\n            \"content\": [\n                {\n                    \"type\": \"text\",\n                    \"text\": \"What's in this image?\"\n                },\n                {\n                    \"type\": \"image_url\",\n                    \"image_url\": {\n                        \"url\": f\"data:image/jpeg;base64,{base64_image}\"\n                    }\n                }\n            ]\n        }\n    ]\n)\nprint(response)\n```\n\n### Character Role-Playing\n\n```python\nfrom zhipuai import ZhipuAI\n\nclient = ZhipuAI(api_key=\"your-api-key\")\nresponse = client.chat.completions.create(\n    model=\"charglm-3\",\n    messages=[\n        {\n            \"role\": \"user\",\n            \"content\": \"Hello, how are you doing lately?\"\n        }\n    ],\n    meta={\n        \"user_info\": \"I am a film director who specializes in music-themed movies.\",\n        \"bot_info\": \"You are a popular domestic female singer and actress with outstanding musical talent.\",\n        \"bot_name\": \"Xiaoya\",\n        \"user_name\": \"Director\"\n    }\n)\nprint(response)\n```\n\n### Assistant Conversation\n\n```python\nfrom zhipuai import ZhipuAI\n\nclient = ZhipuAI(api_key=\"your-api-key\")\nresponse = client.assistant.conversation(\n    assistant_id=\"your_assistant_id\", # You can use 65940acff94777010aa6b796 for testing\n    model=\"glm-4-assistant\",\n    messages=[\n        {\n            \"role\": \"user\",\n            \"content\": [{\n                \"type\": \"text\",\n                \"text\": \"Help me search for the latest ZhipuAI product information\"\n            }]\n        }\n    ],\n    stream=True,\n    attachments=None,\n    metadata=None,\n    request_id=\"request_1790291013237211136\",\n    user_id=\"12345678\"\n)\n\nfor chunk in response:\n    print(chunk)\n```\n\n### Video Generation\n\n```python\nfrom zhipuai import ZhipuAI\n\nclient = ZhipuAI(api_key=\"your-api-key\")\nresponse = client.videos.generations(\n    model=\"cogvideox-2\",\n    prompt=\"A beautiful sunset beach scene\",\n    quality=\"quality\",          # Output mode: use \"quality\" for higher quality, \"speed\" for faster generation\n    with_audio=True,            # Generate video with background audio\n    size=\"1920x1080\",           # Video resolution (up to 4K, e.g. \"3840x2160\")\n    fps=30,                     # Frames per second (choose 30 fps or 60 fps)\n    user_id=\"user_12345\"\n)\n\n# Generation may take some time\nresult = client.videos.retrieve_videos_result(id=response.id)\nprint(result)\n```\n\n## \ud83d\udea8 Error Handling\n\nThe SDK provides comprehensive error handling:\n\n```python\nfrom zhipuai import ZhipuAI\nimport zhipuai\n\nclient = ZhipuAI()\n\ntry:\n    response = client.chat.completions.create(\n        model=\"glm-4\",\n        messages=[\n            {\"role\": \"user\", \"content\": \"Hello, ZhipuAI!\"}\n        ]\n    )\n    print(response.choices[0].message.content)\n    \nexcept zhipuai.APIStatusError as err:\n    print(f\"API Status Error: {err}\")\nexcept zhipuai.APITimeoutError as err:\n    print(f\"Request Timeout: {err}\")\nexcept Exception as err:\n    print(f\"Other Error: {err}\")\n```\n\n### Error Codes\n\n| Status Code | Error Type | Description |\n|-------------|------------|-------------|\n| 400 | `APIRequestFailedError` | Invalid request parameters |\n| 401 | `APIAuthenticationError` | Authentication failed |\n| 429 | `APIReachLimitError` | Rate limit exceeded |\n| 500 | `APIInternalError` | Internal server error |\n| 503 | `APIServerFlowExceedError` | Server overloaded |\n| N/A | `APIStatusError` | General API error |\n\n## \ud83d\udcc8 Version Updates\n\nFor detailed version history and update information, please see [Release-Note.md](Release-Note.md).\n\n## \ud83d\udcc4 License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## \ud83e\udd1d Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request.\n\n## \ud83d\udcde Support\n\nFor questions and technical support, please visit [ZhipuAI Open Platform](https://open.bigmodel.cn/) or check our documentation.\n  \n\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "A SDK library for accessing big model apis from ZhipuAI",
    "version": "2.1.5.20250801",
    "project_urls": null,
    "split_keywords": [],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "2a974aea38358f2f16d3b40234aeaa901154d52a2e852f4e538f0d60533de1ac",
                "md5": "4b267d42285fc4918bbf51a24f3fbfda",
                "sha256": "25b9c3d7eb584c39565836f9e9c00851beab5c7ac1991df949b40703dd99c34e"
            },
            "downloads": -1,
            "filename": "zhipuai-2.1.5.20250801-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "4b267d42285fc4918bbf51a24f3fbfda",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "!=2.7.*,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,!=3.7.*,>=3.8",
            "size": 116286,
            "upload_time": "2025-08-01T11:16:14",
            "upload_time_iso_8601": "2025-08-01T11:16:14.795856Z",
            "url": "https://files.pythonhosted.org/packages/2a/97/4aea38358f2f16d3b40234aeaa901154d52a2e852f4e538f0d60533de1ac/zhipuai-2.1.5.20250801-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "3c2349aae9dc28443ab7d29f9b15ab3b1ceec634210c1ed24ee1c9fa34167351",
                "md5": "1d4938155a8e1e994e94f46f590f7ca7",
                "sha256": "1735638eb5ffb5e34dd977be4f5f6e8bbb59076b2c4e0d1cc0f59324006cc5d9"
            },
            "downloads": -1,
            "filename": "zhipuai-2.1.5.20250801.tar.gz",
            "has_sig": false,
            "md5_digest": "1d4938155a8e1e994e94f46f590f7ca7",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "!=2.7.*,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,!=3.7.*,>=3.8",
            "size": 68934,
            "upload_time": "2025-08-01T11:16:16",
            "upload_time_iso_8601": "2025-08-01T11:16:16.075354Z",
            "url": "https://files.pythonhosted.org/packages/3c/23/49aae9dc28443ab7d29f9b15ab3b1ceec634210c1ed24ee1c9fa34167351/zhipuai-2.1.5.20250801.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-08-01 11:16:16",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "zhipuai"
}
        
Elapsed time: 0.97141s