feat: translate and enrich doc (#3)
* init * enrich doc * init * init * init * doc * chore: remove deprecated email field from pyproject.toml * feat: translate content from Chinese to English and update documentation This commit translates all Chinese text content in the codebase to English, including: - Test messages and prompts - Error messages - Documentation strings - API parameter descriptions - README and release notes content The changes ensure consistency in language usage across the entire project while maintaining all functionality. Documentation has been updated to reflect these changes and provide clearer English descriptions of features and usage. * refactor: update branding from ZaiClient to Z.ai Update SDK name in README and HTTP headers to reflect new branding. Also update endpoint references in type definitions. * ci: allow spaces in PR commit message subject pattern --------- Co-authored-by: zhengweijun <weijun.zheng@aminer.cn>
This commit is contained in:
parent
e6a02cb90d
commit
81cffb6cc4
27 changed files with 509 additions and 231 deletions
2
.github/workflows/lint-pr.yaml
vendored
2
.github/workflows/lint-pr.yaml
vendored
|
|
@ -18,7 +18,7 @@ jobs:
|
|||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
subjectPattern: ^[a-zA-Z0-9!-_@#=*`.|+]+$
|
||||
subjectPattern: ^[a-zA-Z0-9!-_@#=*`.|+,\s]+$
|
||||
# If `subjectPattern` is configured, you can use this property to override
|
||||
# the default error message that is shown when the pattern doesn't match.
|
||||
# The variables `subject` and `title` can be used within the message.
|
||||
|
|
|
|||
68
README.md
68
README.md
|
|
@ -1,4 +1,4 @@
|
|||
# ZaiClient Open Platform Python SDK
|
||||
# Z.ai Open Platform Python SDK
|
||||
|
||||
[](https://pypi.org/project/zai/)
|
||||
[](https://opensource.org/licenses/MIT)
|
||||
|
|
@ -6,16 +6,45 @@
|
|||
|
||||
[中文文档](README_CN.md) | English
|
||||
|
||||
The official Python SDK for ZaiClient's large model open interface, making it easier for developers to call ZaiClient's open APIs.
|
||||
The official Python SDK for Z.ai's large model open interface, making it easier for developers to call Z.ai's open APIs.
|
||||
|
||||
## ✨ Features
|
||||
## ✨ Core 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
|
||||
### 🤖 **Chat Completions**
|
||||
- **Standard Chat**: Create chat completions with various models including `glm-4`, `charglm-3`
|
||||
- **Streaming Support**: Real-time streaming responses for interactive applications
|
||||
- **Tool Calling**: Function calling capabilities for enhanced AI interactions
|
||||
- **Character Role-Playing**: Support for character-based conversations with `charglm-3` model
|
||||
- **Multimodal Chat**: Image understanding capabilities with vision models
|
||||
|
||||
### 🧠 **Embeddings**
|
||||
- **Text Embeddings**: Generate high-quality vector embeddings for text
|
||||
- **Configurable Dimensions**: Customizable embedding dimensions
|
||||
- **Batch Processing**: Support for multiple inputs in a single request
|
||||
|
||||
### 🎥 **Video Generation**
|
||||
- **Text-to-Video**: Generate videos from text prompts
|
||||
- **Image-to-Video**: Create videos from image inputs
|
||||
- **Customizable Parameters**: Control quality, duration, FPS, and size
|
||||
- **Audio Support**: Optional audio generation for videos
|
||||
|
||||
### 🎵 **Audio Processing**
|
||||
- **Speech Transcription**: Convert audio files to text
|
||||
- **Multiple Formats**: Support for various audio file formats
|
||||
|
||||
### 🤝 **Assistant API**
|
||||
- **Conversation Management**: Structured conversation handling
|
||||
- **Streaming Conversations**: Real-time assistant interactions
|
||||
- **Metadata Support**: Rich conversation context and user information
|
||||
|
||||
### 🔧 **Advanced Tools**
|
||||
- **Web Search**: Integrated web search capabilities
|
||||
- **File Management**: Upload, download, and manage files
|
||||
- **Batch Operations**: Efficient batch processing for multiple requests
|
||||
- **Knowledge Base**: Knowledge management and retrieval
|
||||
- **Content Moderation**: Built-in content safety and moderation
|
||||
- **Image Generation**: AI-powered image creation
|
||||
- **Fine-tuning**: Custom model training capabilities
|
||||
|
||||
## 📦 Installation
|
||||
|
||||
|
|
@ -30,16 +59,31 @@ The official Python SDK for ZaiClient's large model open interface, making it ea
|
|||
pip install z-ai
|
||||
```
|
||||
|
||||
### Core Dependencies
|
||||
### 📋 **Technical Specifications**
|
||||
|
||||
#### **Python Support**
|
||||
- **Python Versions**: 3.8, 3.9, 3.10, 3.11, 3.12
|
||||
- **Async Support**: Full async/await compatibility
|
||||
- **Cross-platform**: Windows, macOS, Linux support
|
||||
|
||||
#### **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 |
|
||||
| `cachetools` | `>=4.2.2` | Caching utilities |
|
||||
| `pyjwt` | `>=2.8.0` | JSON Web Token (JWT) handling |
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
### Create API Key
|
||||
1. **Create client with API key**
|
||||
2. **Call the corresponding API methods**
|
||||
|
||||
For complete examples, please refer to the open platform [API Reference](https://docs.z.ai/api-reference/) and [User Guide](https://docs.z.ai/guides/), and remember to replace with your own API key.
|
||||
|
||||
### Basic Usage
|
||||
|
||||
```python
|
||||
|
|
@ -60,6 +104,8 @@ print(response.choices[0].message.content)
|
|||
|
||||
### Client Configuration
|
||||
|
||||
The SDK supports multiple ways to configure API keys:
|
||||
|
||||
#### Environment Variables
|
||||
|
||||
```bash
|
||||
|
|
@ -319,4 +365,4 @@ For questions and technical support, please visit [Z.ai Open Platform](https://d
|
|||
|
||||
### Contact Us
|
||||
|
||||
For feedback and support, please contact us at: **user_feedback@z.ai**
|
||||
For feedback and support, please contact us at: **user_feedback@z.ai**
|
||||
|
|
|
|||
71
README_CN.md
71
README_CN.md
|
|
@ -1,4 +1,4 @@
|
|||
# 智谱AI开放平台 Python SDK
|
||||
# Z.ai 开放平台 Python SDK
|
||||
|
||||
[](https://pypi.org/project/z-ai/)
|
||||
[](LICENSE)
|
||||
|
|
@ -6,16 +6,45 @@
|
|||
|
||||
[English Readme](README.md)
|
||||
|
||||
[智谱AI开放平台](https://open.bigmodel.cn/dev/api)官方 Python SDK,帮助开发者快速集成智谱AI强大的人工智能能力到Python应用中。
|
||||
[ Z.ai 开放平台](https://github.com/THUDM/z-ai-sdk-python)官方 Python SDK,帮助开发者快速集成 Z.ai 强大的人工智能能力到Python应用中。
|
||||
|
||||
## ✨ 特性
|
||||
## ✨ 核心功能
|
||||
|
||||
- 🚀 **类型安全**: 所有接口完全类型封装,无需查阅API文档即可完成接入
|
||||
- 🔧 **简单易用**: 简洁直观的API设计,快速上手
|
||||
- ⚡ **高性能**: 基于现代Python库构建,性能优异
|
||||
- 🛡️ **安全可靠**: 内置身份验证和令牌管理
|
||||
- 📦 **轻量级**: 最小化依赖,易于项目集成
|
||||
- 🔄 **流式支持**: 支持SSE流式响应和异步调用
|
||||
### 🤖 **对话补全**
|
||||
- **标准对话**: 支持 `glm-4`、`charglm-3` 等多种模型的对话补全
|
||||
- **流式支持**: 实时流式响应,适用于交互式应用
|
||||
- **工具调用**: 函数调用能力,增强 AI 交互体验
|
||||
- **角色扮演**: 支持基于 `charglm-3` 模型的角色对话
|
||||
- **多模态对话**: 支持图像理解的视觉模型
|
||||
|
||||
### 🧠 **向量嵌入**
|
||||
- **文本嵌入**: 生成高质量的文本向量嵌入
|
||||
- **可配置维度**: 自定义嵌入向量维度
|
||||
- **批量处理**: 单次请求支持多个输入
|
||||
|
||||
### 🎥 **视频生成**
|
||||
- **文本生成视频**: 从文本提示生成视频
|
||||
- **图像生成视频**: 从图像输入创建视频
|
||||
- **参数可定制**: 控制质量、时长、帧率和尺寸
|
||||
- **音频支持**: 可选的视频音频生成
|
||||
|
||||
### 🎵 **音频处理**
|
||||
- **语音转录**: 将音频文件转换为文本
|
||||
- **多格式支持**: 支持各种音频文件格式
|
||||
|
||||
### 🤝 **智能助手 API**
|
||||
- **对话管理**: 结构化对话处理
|
||||
- **流式对话**: 实时助手交互
|
||||
- **元数据支持**: 丰富的对话上下文和用户信息
|
||||
|
||||
### 🔧 **高级工具**
|
||||
- **网络搜索**: 集成的网络搜索功能
|
||||
- **文件管理**: 上传、下载和管理文件
|
||||
- **批量操作**: 多请求的高效批量处理
|
||||
- **知识库**: 知识管理和检索
|
||||
- **内容审核**: 内置内容安全和审核
|
||||
- **图像生成**: AI 驱动的图像创建
|
||||
- **模型微调**: 自定义模型训练功能
|
||||
|
||||
## 📦 安装
|
||||
|
||||
|
|
@ -28,16 +57,24 @@
|
|||
```sh
|
||||
pip install z-ai
|
||||
```
|
||||
### 📋 **技术规格**
|
||||
|
||||
### 📋 核心依赖
|
||||
#### **Python 支持**
|
||||
- **Python 版本**: 3.8, 3.9, 3.10, 3.11, 3.12
|
||||
- **异步支持**: 完整的 async/await 兼容性
|
||||
- **跨平台**: Windows、macOS、Linux 支持
|
||||
|
||||
#### **核心依赖**
|
||||
|
||||
本SDK使用以下核心依赖库:
|
||||
|
||||
| 依赖库 | 用途 |
|
||||
|--------|------|
|
||||
| httpx | HTTP客户端库 |
|
||||
| pydantic | 数据验证和序列化 |
|
||||
| typing-extensions | 类型注解扩展 |
|
||||
| 依赖库 | 版本 | 用途 |
|
||||
|--------|-----|------|
|
||||
| `httpx` | `>=0.23.0` | HTTP客户端库 |
|
||||
| `pydantic` | `>=1.9.0,<3.0.0` | 数据验证和序列化 |
|
||||
| `typing-extensions` | `>=4.0.0` | 类型注解扩展 |
|
||||
| `cachetools` | `>=4.2.2` | 缓存工具 |
|
||||
| `pyjwt` | `>=2.8.0` | JSON Web Token 库 |
|
||||
|
||||
## 🚀 快速开始
|
||||
|
||||
|
|
@ -46,7 +83,7 @@ pip install z-ai
|
|||
1. **使用API密钥创建客户端**
|
||||
2. **调用相应的API方法**
|
||||
|
||||
完整示例请参考开放平台[接口文档](https://open.bigmodel.cn/dev/api)以及[使用指南](https://open.bigmodel.cn/dev/howuse/),记得替换为您自己的API密钥。
|
||||
完整示例请参考开放平台[接口文档](https://docs.z.ai/api-reference/)以及[使用指南](https://docs.z.ai/guides/),记得替换为您自己的API密钥。
|
||||
|
||||
### 客户端配置
|
||||
|
||||
|
|
@ -271,7 +308,7 @@ try:
|
|||
response = client.chat.completions.create(
|
||||
model="glm-4",
|
||||
messages=[
|
||||
{"role": "user", "content": "你好,智谱AI!"}
|
||||
{"role": "user", "content": "你好, Z.ai !"}
|
||||
]
|
||||
)
|
||||
print(response.choices[0].message.content)
|
||||
|
|
|
|||
304
Release-Note.md
304
Release-Note.md
|
|
@ -1,127 +1,255 @@
|
|||
## Release Notes
|
||||
# Release Notes
|
||||
|
||||
### 2024-08-12
|
||||
## v0.0.1a1 - Initial Release (2025-01-02)
|
||||
|
||||
**New Features:**
|
||||
- Modified video prompt to be optional, added file deletion functionality
|
||||
- Added Assistant business logic
|
||||
- Fixed embedding 3 dimensions
|
||||
🎉 **Welcome to the first release of the Z.ai Python SDK!**
|
||||
|
||||
### 2024-07-25
|
||||
This initial release provides comprehensive access to Z.ai's powerful AI capabilities through a modern, type-safe Python SDK.
|
||||
|
||||
**Bug Fixes:**
|
||||
- Fixed cogvideo related issues
|
||||
### ✨ Core Features
|
||||
|
||||
### 2024-07-12
|
||||
#### 🤖 **Chat Completions**
|
||||
- **Standard Chat**: Create chat completions with various models including `glm-4`, `charglm-3`
|
||||
- **Streaming Support**: Real-time streaming responses for interactive applications
|
||||
- **Tool Calling**: Function calling capabilities for enhanced AI interactions
|
||||
- **Character Role-Playing**: Support for character-based conversations with `charglm-3` model
|
||||
- **Multimodal Chat**: Image understanding capabilities with vision models
|
||||
|
||||
**New Features:**
|
||||
- Added advanced search tool Web search business logic
|
||||
- Specified Python versions support (3.8, 3.9, 3.10, 3.11, 3.12)
|
||||
- Integrated cogvideo business functionality
|
||||
#### 🧠 **Embeddings**
|
||||
- **Text Embeddings**: Generate high-quality vector embeddings for text
|
||||
- **Configurable Dimensions**: Customizable embedding dimensions
|
||||
- **Batch Processing**: Support for multiple inputs in a single request
|
||||
|
||||
### 2024-05-20
|
||||
#### 🎥 **Video Generation**
|
||||
- **Text-to-Video**: Generate videos from text prompts
|
||||
- **Image-to-Video**: Create videos from image inputs
|
||||
- **Customizable Parameters**: Control quality, duration, FPS, and size
|
||||
- **Audio Support**: Optional audio generation for videos
|
||||
|
||||
**Improvements:**
|
||||
- Fixed some `python3.12` dependency issues
|
||||
- Added pagination processing code, rewrote instantiation rules for some response classes
|
||||
- Added type conversion validation
|
||||
- Added batch task related APIs
|
||||
- Added file stream response wrapper
|
||||
#### 🎵 **Audio Processing**
|
||||
- **Speech Transcription**: Convert audio files to text
|
||||
- **Multiple Formats**: Support for various audio file formats
|
||||
|
||||
### 2024-04-29
|
||||
#### 🤝 **Assistant API**
|
||||
- **Conversation Management**: Structured conversation handling
|
||||
- **Streaming Conversations**: Real-time assistant interactions
|
||||
- **Metadata Support**: Rich conversation context and user information
|
||||
|
||||
**Improvements:**
|
||||
- Fixed some `python3.7` code compatibility issues
|
||||
- Added interface failure retry mechanism, controlled by `retry` parameter with default of 3 retries
|
||||
- Adjusted interface timeout strategy, controlled by `Timeout` for interface `connect` and `read` timeout, default `timeout=300.0, connect=8.0`
|
||||
- Added support for super-humanoid large model parameters in conversation module, `model="charglm-3"`, `meta` parameter support
|
||||
#### 🔧 **Advanced Tools**
|
||||
- **Web Search**: Integrated web search capabilities
|
||||
- **File Management**: Upload, download, and manage files
|
||||
- **Batch Operations**: Efficient batch processing for multiple requests
|
||||
- **Knowledge Base**: Knowledge management and retrieval
|
||||
- **Content Moderation**: Built-in content safety and moderation
|
||||
- **Image Generation**: AI-powered image creation
|
||||
- **Fine-tuning**: Custom model training capabilities
|
||||
|
||||
### 2024-04-23
|
||||
### 🛡️ **Developer Experience**
|
||||
|
||||
**Improvements:**
|
||||
- Fixed some compatibility issues with `pydantic<3,>=1.9.0`
|
||||
- Message processing business request and response parameters can be extended through configuration
|
||||
- Compatible with some parameters `top_p:1`, `temperature:0` (do_sample rewritten to false, parameters top_p temperature do not take effect)
|
||||
- Image understanding part, image_url parameter base64 content containing `data:image/jpeg;base64` compatibility
|
||||
- Removed JWT authentication logic
|
||||
#### **Type Safety**
|
||||
- Complete type annotations for all APIs
|
||||
- Full IDE support with autocomplete and type checking
|
||||
- Pydantic-based request/response validation
|
||||
|
||||
#### **Error Handling**
|
||||
- Comprehensive error types for different failure scenarios
|
||||
- Detailed error messages and debugging information
|
||||
- Automatic retry mechanisms with configurable settings
|
||||
|
||||
#### **Performance & Reliability**
|
||||
- Built-in connection pooling and request optimization
|
||||
- Configurable timeout and retry strategies
|
||||
- Efficient resource management
|
||||
|
||||
#### **Security**
|
||||
- Secure API key management
|
||||
- Optional token caching with security controls
|
||||
- Built-in authentication handling
|
||||
|
||||
### 📋 **Technical Specifications**
|
||||
|
||||
#### **Python Support**
|
||||
- **Python Versions**: 3.8, 3.9, 3.10, 3.11, 3.12
|
||||
- **Async Support**: Full async/await compatibility
|
||||
- **Cross-platform**: Windows, macOS, Linux support
|
||||
|
||||
#### **Dependencies**
|
||||
- `httpx` (≥0.23.0): Modern HTTP client
|
||||
- `pydantic` (≥1.9.0, <3.0): Data validation and serialization
|
||||
- `typing-extensions` (≥4.0.0): Enhanced type hints
|
||||
- `cachetools` (≥4.2.2): Caching utilities
|
||||
- `pyjwt` (~2.8.0): JWT token handling
|
||||
|
||||
### 🚀 **Getting Started**
|
||||
|
||||
```bash
|
||||
pip install z-ai
|
||||
```
|
||||
|
||||
```python
|
||||
from zai import ZaiClient
|
||||
|
||||
# Initialize client
|
||||
client = ZaiClient(api_key="your-api-key")
|
||||
|
||||
# Create chat completion
|
||||
response = client.chat.completions.create(
|
||||
model="glm-4",
|
||||
messages=[{"role": "user", "content": "Hello, Z.ai!"}]
|
||||
)
|
||||
|
||||
print(response.choices[0].message.content)
|
||||
```
|
||||
|
||||
### 📚 **Documentation & Support**
|
||||
|
||||
- **Documentation**: [Z.ai Open Platform](https://docs.z.ai/)
|
||||
- **Examples**: Comprehensive examples in the `/examples` directory
|
||||
- **Community**: GitHub Issues and Discussions
|
||||
- **Contact**: user_feedback@z.ai
|
||||
|
||||
### 🔮 **What's Next**
|
||||
|
||||
This initial release establishes the foundation for Z.ai's Python SDK. Future releases will include:
|
||||
- Additional model support
|
||||
- Enhanced streaming capabilities
|
||||
- More advanced tool integrations
|
||||
- Performance optimizations
|
||||
- Extended documentation and examples
|
||||
|
||||
---
|
||||
|
||||
## Migration Guide
|
||||
|
||||
For users upgrading from older versions, please note the following breaking changes:
|
||||
*This is the initial release - no migration needed!*
|
||||
|
||||
### From v3.x to v4.x
|
||||
|
||||
- API key configuration has been simplified
|
||||
- Some method signatures have changed for better type safety
|
||||
- Error handling has been improved with more specific exception types
|
||||
|
||||
## Support
|
||||
|
||||
For questions about specific versions or upgrade assistance, please visit our [documentation](https://open.bigmodel.cn/) or contact our support team.
|
||||
For future versions, migration guides will be provided here to help you upgrade smoothly.
|
||||
|
||||
---
|
||||
|
||||
## 版本更新
|
||||
# 版本更新
|
||||
|
||||
### 2024-08-12
|
||||
## v0.0.1a1 - 首次发布 (2025-07-15)
|
||||
|
||||
**新功能:**
|
||||
- ✅ 视频提示词设为可选,新增文件删除功能
|
||||
- ✅ 智能助手业务逻辑
|
||||
- 🔧 修复 embedding 3 维度问题
|
||||
🎉 **欢迎使用 Z.ai Python SDK 的首个版本!**
|
||||
|
||||
### 2024-07-25
|
||||
这个初始版本通过现代化、类型安全的 Python SDK 提供了对 Z.ai 强大 AI 能力的全面访问。
|
||||
|
||||
**问题修复:**
|
||||
- 🔧 修复 cogvideo 相关问题
|
||||
### ✨ 核心功能
|
||||
|
||||
### 2024-07-12
|
||||
#### 🤖 **对话补全**
|
||||
- **标准对话**: 支持 `glm-4`、`charglm-3` 等多种模型的对话补全
|
||||
- **流式支持**: 实时流式响应,适用于交互式应用
|
||||
- **工具调用**: 函数调用能力,增强 AI 交互体验
|
||||
- **角色扮演**: 支持基于 `charglm-3` 模型的角色对话
|
||||
- **多模态对话**: 支持图像理解的视觉模型
|
||||
|
||||
**新功能:**
|
||||
- ✅ 高级搜索工具 Web search 业务逻辑
|
||||
- ✅ 指定 Python 版本支持 (3.8, 3.9, 3.10, 3.11, 3.12)
|
||||
- ✅ 集成 cogvideo 业务功能
|
||||
#### 🧠 **向量嵌入**
|
||||
- **文本嵌入**: 生成高质量的文本向量嵌入
|
||||
- **可配置维度**: 自定义嵌入向量维度
|
||||
- **批量处理**: 单次请求支持多个输入
|
||||
|
||||
### 2024-05-20
|
||||
#### 🎥 **视频生成**
|
||||
- **文本生成视频**: 从文本提示生成视频
|
||||
- **图像生成视频**: 从图像输入创建视频
|
||||
- **参数可定制**: 控制质量、时长、帧率和尺寸
|
||||
- **音频支持**: 可选的视频音频生成
|
||||
|
||||
**改进优化:**
|
||||
- 🔧 修复部分 `python3.12` 依赖问题
|
||||
- ✅ 新增分页处理代码,重写部分响应类实例化规则
|
||||
- ✅ 新增类型转换校验
|
||||
- ✅ 批处理任务相关 API
|
||||
- ✅ 文件流响应包装器
|
||||
#### 🎵 **音频处理**
|
||||
- **语音转录**: 将音频文件转换为文本
|
||||
- **多格式支持**: 支持各种音频文件格式
|
||||
|
||||
### 2024-04-29
|
||||
#### 🤝 **智能助手 API**
|
||||
- **对话管理**: 结构化对话处理
|
||||
- **流式对话**: 实时助手交互
|
||||
- **元数据支持**: 丰富的对话上下文和用户信息
|
||||
|
||||
**改进优化:**
|
||||
- 🔧 修复部分 `python3.7` 代码兼容性问题
|
||||
- ✅ 接口失败重试机制,通过 `retry` 参数控制重试次数,默认 3 次
|
||||
- ⏱️ 调整接口超时策略,通过 `Timeout` 控制接口 `connect` 和 `read` 超时时间,默认 `timeout=300.0, connect=8.0`
|
||||
- ✅ 对话模块新增超拟人大模型参数支持,`model="charglm-3"`,`meta` 参数支持
|
||||
#### 🔧 **高级工具**
|
||||
- **网络搜索**: 集成的网络搜索功能
|
||||
- **文件管理**: 上传、下载和管理文件
|
||||
- **批量操作**: 多请求的高效批量处理
|
||||
- **知识库**: 知识管理和检索
|
||||
- **内容审核**: 内置内容安全和审核
|
||||
- **图像生成**: AI 驱动的图像创建
|
||||
- **模型微调**: 自定义模型训练功能
|
||||
|
||||
### 2024-04-23
|
||||
### 🛡️ **开发者体验**
|
||||
|
||||
**改进优化:**
|
||||
- 🔧 修复部分 `pydantic<3,>=1.9.0` 兼容性问题
|
||||
- ✅ 报文处理的业务请求参数和响应参数可通过配置扩充
|
||||
- ✅ 兼容部分参数 `top_p:1`,`temperature:0`(do_sample 重写为 false,参数 top_p temperature 不生效)
|
||||
- ✅ 图像理解部分,image_url 参数 base64 内容包含 `data:image/jpeg;base64` 兼容性
|
||||
- 🔄 删除 JWT 认证逻辑
|
||||
#### **类型安全**
|
||||
- 所有 API 的完整类型注解
|
||||
- 完整的 IDE 支持,包括自动补全和类型检查
|
||||
- 基于 Pydantic 的请求/响应验证
|
||||
|
||||
#### **错误处理**
|
||||
- 针对不同失败场景的全面错误类型
|
||||
- 详细的错误消息和调试信息
|
||||
- 可配置设置的自动重试机制
|
||||
|
||||
#### **性能与可靠性**
|
||||
- 内置连接池和请求优化
|
||||
- 可配置的超时和重试策略
|
||||
- 高效的资源管理
|
||||
|
||||
#### **安全性**
|
||||
- 安全的 API 密钥管理
|
||||
- 带安全控制的可选令牌缓存
|
||||
- 内置身份验证处理
|
||||
|
||||
### 📋 **技术规格**
|
||||
|
||||
#### **Python 支持**
|
||||
- **Python 版本**: 3.8, 3.9, 3.10, 3.11, 3.12
|
||||
- **异步支持**: 完整的 async/await 兼容性
|
||||
- **跨平台**: Windows、macOS、Linux 支持
|
||||
|
||||
#### **依赖项**
|
||||
- `httpx` (≥0.23.0): 现代 HTTP 客户端
|
||||
- `pydantic` (≥1.9.0, <3.0): 数据验证和序列化
|
||||
- `typing-extensions` (≥4.0.0): 增强类型提示
|
||||
- `cachetools` (≥4.2.2): 缓存工具
|
||||
- `pyjwt` (~2.8.0): JWT 令牌处理
|
||||
|
||||
### 🚀 **快速开始**
|
||||
|
||||
```bash
|
||||
pip install z-ai
|
||||
```
|
||||
|
||||
```python
|
||||
from zai import ZaiClient
|
||||
|
||||
# 初始化客户端
|
||||
client = ZaiClient(api_key="your-api-key")
|
||||
|
||||
# 创建对话补全
|
||||
response = client.chat.completions.create(
|
||||
model="glm-4",
|
||||
messages=[{"role": "user", "content": "你好,Z.ai!"}]
|
||||
)
|
||||
|
||||
print(response.choices[0].message.content)
|
||||
```
|
||||
|
||||
### 📚 **文档与支持**
|
||||
|
||||
- **文档**: [Z.ai 开放平台](https://docs.z.ai/)
|
||||
- **示例**: `/examples` 目录中的全面示例
|
||||
- **社区**: GitHub Issues 和 Discussions
|
||||
- **联系**: user_feedback@z.ai
|
||||
|
||||
### 🔮 **未来规划**
|
||||
|
||||
这个初始版本为 Z.ai Python SDK 奠定了基础。未来版本将包括:
|
||||
- 更多模型支持
|
||||
- 增强的流式功能
|
||||
- 更多高级工具集成
|
||||
- 性能优化
|
||||
- 扩展的文档和示例
|
||||
|
||||
---
|
||||
|
||||
## 迁移指南
|
||||
|
||||
对于从旧版本升级的用户,请注意以下重大变更:
|
||||
*这是初始版本 - 无需迁移!*
|
||||
|
||||
### 从 v3.x 到 v4.x
|
||||
|
||||
- API 密钥配置已简化
|
||||
- 部分方法签名已更改以提供更好的类型安全性
|
||||
- 错误处理已改进,提供更具体的异常类型
|
||||
|
||||
## 技术支持
|
||||
|
||||
如有特定版本问题或升级协助需求,请访问我们的[文档](https://open.bigmodel.cn/)或联系我们的支持团队。
|
||||
对于未来版本,我们将在此提供迁移指南,帮助您顺利升级。
|
||||
|
|
@ -136,10 +136,10 @@ class Knowledge(BaseAPI):
|
|||
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
|
||||
) -> httpx.Response:
|
||||
"""
|
||||
Delete a file.
|
||||
Delete a knowledge.
|
||||
|
||||
Args:
|
||||
knowledge_id: 知识库ID
|
||||
knowledge_id: Knowledge ID
|
||||
extra_headers: Send extra headers
|
||||
|
||||
extra_body: Add additional JSON properties to the request
|
||||
|
|
|
|||
|
|
@ -289,7 +289,7 @@ class HttpClient:
|
|||
return {
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json; charset=UTF-8',
|
||||
'ZaiClient-SDK-Ver': self._version,
|
||||
'Zai-SDK-Ver': self._version,
|
||||
'source_type': 'z-ai-sdk-python',
|
||||
'x-request-sdk': 'z-ai-sdk-python',
|
||||
**self.auth_headers,
|
||||
|
|
@ -411,7 +411,7 @@ class HttpClient:
|
|||
serialized: dict[str, object] = {}
|
||||
for key, value in items:
|
||||
if key in serialized:
|
||||
raise ValueError(f'存在重复的键: {key};')
|
||||
raise ValueError(f'Key {key} already exists in multipart form data.')
|
||||
serialized[key] = value
|
||||
return serialized
|
||||
|
||||
|
|
|
|||
|
|
@ -118,9 +118,7 @@ def _extract_items(
|
|||
item,
|
||||
path,
|
||||
index=index,
|
||||
flattened_key=flattened_key + '[]'
|
||||
if flattened_key is not None
|
||||
else '[]',
|
||||
flattened_key=flattened_key + '[]' if flattened_key is not None else '[]',
|
||||
)
|
||||
for item in obj
|
||||
]
|
||||
|
|
@ -270,12 +268,7 @@ def required_args(*variants: Sequence[str]) -> Callable[[CallableT], CallableT]:
|
|||
else: # no break
|
||||
if len(variants) > 1:
|
||||
variations = human_join(
|
||||
[
|
||||
'('
|
||||
+ human_join([quote(arg) for arg in variant], final='and')
|
||||
+ ')'
|
||||
for variant in variants
|
||||
]
|
||||
['(' + human_join([quote(arg) for arg in variant], final='and') + ')' for variant in variants]
|
||||
)
|
||||
msg = f'Missing required arguments; Expected either {variations} arguments to be given'
|
||||
else:
|
||||
|
|
@ -408,9 +401,13 @@ def get_async_library() -> str:
|
|||
|
||||
def drop_prefix_image_data(content: Union[str, List[dict]]) -> Union[str, List[dict]]:
|
||||
"""
|
||||
删除 ;base64, 前缀
|
||||
:param image_data:
|
||||
:return:
|
||||
Drop the prefix 'data:image/' from image data.
|
||||
|
||||
Args:
|
||||
content: Content to process
|
||||
|
||||
Returns:
|
||||
Processed content
|
||||
"""
|
||||
if isinstance(content, List):
|
||||
for data in content:
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ class Batch(BaseModel):
|
|||
id (str): Batch identifier
|
||||
completion_window (str): Address information for executing the request
|
||||
created_at (int): This is the creation time represented by the Unix timestamp (in seconds)
|
||||
endpoint (str): This is the address of the ZaiClient endpoint
|
||||
endpoint (str): This is the address of the Z.ai endpoint
|
||||
input_file_id (str): The ID of the input file marked as batch
|
||||
object (Literal['batch']): This type is always `batch`
|
||||
status (Literal): The status of the batch
|
||||
|
|
|
|||
|
|
@ -9,16 +9,16 @@ __all__ = ['KnowledgeBaseParams']
|
|||
|
||||
class KnowledgeBaseParams(TypedDict):
|
||||
"""
|
||||
知识库参数类型定义
|
||||
Knowledge base parameters.
|
||||
|
||||
Attributes:
|
||||
embedding_id (int): 知识库绑定的向量化模型ID
|
||||
name (str): 知识库名称,限制100字
|
||||
customer_identifier (Optional[str]): 用户标识,长度32位以内
|
||||
description (Optional[str]): 知识库描述,限制500字
|
||||
background (Optional[Literal['blue', 'red', 'orange', 'purple', 'sky']]): 背景颜色
|
||||
icon (Optional[Literal['question', 'book', 'seal', 'wrench', 'tag', 'horn', 'house']]): 知识库图标
|
||||
bucket_id (Optional[str]): 桶ID,限制32位
|
||||
embedding_id (int): Embedding ID
|
||||
name (str): Knowledge base name, limited to 100 characters
|
||||
customer_identifier (Optional[str]): Customer identifier, limited to 32 characters
|
||||
description (Optional[str]): Knowledge base description, limited to 500 characters
|
||||
background (Optional[Literal['blue', 'red', 'orange', 'purple', 'sky']]): Background color
|
||||
icon (Optional[Literal['question', 'book', 'seal', 'wrench', 'tag', 'horn', 'house']]): Knowledge base icon
|
||||
bucket_id (Optional[str]): Bucket ID, limited to 32 characters
|
||||
"""
|
||||
|
||||
embedding_id: int
|
||||
|
|
@ -26,7 +26,5 @@ class KnowledgeBaseParams(TypedDict):
|
|||
customer_identifier: Optional[str]
|
||||
description: Optional[str]
|
||||
background: Optional[Literal['blue', 'red', 'orange', 'purple', 'sky']] = None
|
||||
icon: Optional[
|
||||
Literal['question', 'book', 'seal', 'wrench', 'tag', 'horn', 'house']
|
||||
] = None
|
||||
icon: Optional[Literal['question', 'book', 'seal', 'wrench', 'tag', 'horn', 'house']] = None
|
||||
bucket_id: Optional[str]
|
||||
|
|
|
|||
|
|
@ -1,3 +1,3 @@
|
|||
{"messages": [{"role": "system", "content": "你是一位乐于助人,知识渊博的全能AI助手。"},{"role": "user", "content": "请介绍一下AlphaGo的基本原理。"}, {"role": "assistant", "content": "AlphaGo利用深度神经网络与树搜索算法相结合,通过对弈数据进行训练,逐步提升游戏水平,能够对围棋局面进行判断并选择最佳落子位置。"}]}
|
||||
{"messages": [{"role": "system", "content": "你是一位乐于助人,知识渊博的全能AI助手。"},{"role": "user", "content": "请列举一些健康饮食的重要原则。"}, {"role": "assistant", "content": "健康饮食的重要原则包括:膳食应营养均衡,合理摄入各种营养素;多吃新鲜蔬果,适量饮水;少吃糖、油、盐,忌吃过量快餐;养成规律生活作息习惯,适量运动。"}]}
|
||||
{"messages": [{"role": "system", "content": "你是一位乐于助人,知识渊博的全能AI助手。"},{"role": "user", "content": "请给出一些改善睡眠质量的建议。"}, {"role": "assistant", "content": "改善睡眠质量的建议包括:保证睡眠时间,避免睡眠不足;睡前放松身心,远离刺激;养成规律作息时间,不要频繁熬夜;适量运动,但不要运动过度;睡前可以喝一杯热牛奶等温和饮料。"}]}
|
||||
{"messages": [{"role": "system", "content": "You are a helpful and knowledgeable AI assistant."},{"role": "user", "content": "Please introduce the basic principles of AlphaGo."}, {"role": "assistant", "content": "AlphaGo combines deep neural networks with tree search algorithms, training through game data to gradually improve its playing level, and is capable of evaluating Go positions and selecting the best moves."}]}
|
||||
{"messages": [{"role": "system", "content": "You are a helpful and knowledgeable AI assistant."},{"role": "user", "content": "Please list some important principles of healthy eating."}, {"role": "assistant", "content": "Important principles of healthy eating include: maintaining a balanced diet with proper intake of various nutrients; eating plenty of fresh fruits and vegetables, drinking adequate water; consuming less sugar, oil, and salt, avoiding excessive fast food; developing regular lifestyle habits and engaging in moderate exercise."}]}
|
||||
{"messages": [{"role": "system", "content": "You are a helpful and knowledgeable AI assistant."},{"role": "user", "content": "Please provide some suggestions for improving sleep quality."}, {"role": "assistant", "content": "Suggestions for improving sleep quality include: ensuring adequate sleep time and avoiding sleep deprivation; relaxing your mind and body before bed, staying away from stimulation; developing regular sleep schedules and avoiding frequent late nights; engaging in moderate exercise, but not excessive; drinking a glass of warm milk or other mild beverages before bed."}]}
|
||||
Binary file not shown.
|
|
@ -6,9 +6,11 @@ client = ZaiClient() # Fill in your own API Key
|
|||
|
||||
response = client.videos.generations(
|
||||
model='cogvideo',
|
||||
prompt='一个年轻的艺术家在一片彩虹上用调色板作画。',
|
||||
prompt='A young artist painting with a palette on a rainbow.',
|
||||
# prompt="A cartoon fox dancing happily jazz in the forest."
|
||||
# prompt="This is a car commercial describing the racing adventure of a 30-year-old race car driver wearing a red helmet. The background is blue sky and harsh desert environment, filmed in cinematic style using 35mm film with vivid colors."
|
||||
# prompt="This is a car commercial describing the racing adventure of a 30-year-old race car driver
|
||||
# wearing a red helmet. The background is blue sky and harsh desert environment,
|
||||
# filmed in cinematic style using 35mm film with vivid colors."
|
||||
)
|
||||
print(response)
|
||||
task_id = response.id
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ def test_assistant(logging_conf) -> None:
|
|||
messages=[
|
||||
{
|
||||
'role': 'user',
|
||||
'content': [{'type': 'text', 'text': '帮我搜索下智谱的cogvideox发布时间'}],
|
||||
'content': [{'type': 'text', 'text': "Help me search for the release date of Z.ai's CogVideoX"}],
|
||||
}
|
||||
],
|
||||
stream=True,
|
||||
|
|
@ -77,7 +77,7 @@ def test_translate_api(logging_conf) -> None:
|
|||
try:
|
||||
translate_response = client.assistant.conversation(
|
||||
assistant_id='9996ijk789lmn012o345p999',
|
||||
messages=[{'role': 'user', 'content': [{'type': 'text', 'text': '你好呀'}]}],
|
||||
messages=[{'role': 'user', 'content': [{'type': 'text', 'text': 'hello'}]}],
|
||||
stream=True,
|
||||
attachments=None,
|
||||
metadata=None,
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ def test_audio_speech(logging_conf):
|
|||
speech_file_path = Path(__file__).parent / 'speech.wav'
|
||||
response = client.audio.speech(
|
||||
model='cogtts',
|
||||
input='你好呀,欢迎来到智谱开放平台',
|
||||
input='Hello, welcome to Z.ai Open Platform',
|
||||
voice='female',
|
||||
response_format='wav',
|
||||
)
|
||||
|
|
@ -35,8 +35,8 @@ def test_audio_customization(logging_conf):
|
|||
speech_file_path = Path(__file__).parent / 'speech.wav'
|
||||
response = client.audio.customization(
|
||||
model='cogtts',
|
||||
input='你好呀,欢迎来到智谱开放平台',
|
||||
voice_text='这是一条测试用例',
|
||||
input='Hello, welcome to Z.ai Open Platform',
|
||||
voice_text='This is a test case',
|
||||
voice_data=file,
|
||||
response_format='wav',
|
||||
)
|
||||
|
|
|
|||
|
|
@ -13,12 +13,30 @@ def test_completions_charglm(logging_conf):
|
|||
try:
|
||||
response = client.chat.completions.create(
|
||||
model='charglm-3', # Fill in the model name to call
|
||||
messages=[{'role': 'user', 'content': '请问你在做什么'}],
|
||||
messages=[{'role': 'user', 'content': 'What are you doing?'}],
|
||||
meta={
|
||||
'user_info': '我是陆星辰,是一个男性,是一位知名导演,也是苏梦远的合作导演。我擅长拍摄音乐题材的电影。苏梦远对我的态度是尊敬的,并视我为良师益友。',
|
||||
'bot_info': '苏梦远,本名苏远心,是一位当红的国内女歌手及演员。在参加选秀节目后,凭借独特的嗓音及出众的舞台魅力迅速成名,进入娱乐圈。她外表美丽动人,但真正的魅力在于她的才华和勤奋。苏梦远是音乐学院毕业的优秀生,善于创作,拥有多首热门原创歌曲。除了音乐方面的成就,她还热衷于慈善事业,积极参加公益活动,用实际行动传递正能量。在工作中,她对待工作非常敬业,拍戏时总是全身心投入角色,赢得了业内人士的赞誉和粉丝的喜爱。虽然在娱乐圈,但她始终保持低调、谦逊的态度,深得同行尊重。在表达时,苏梦远喜欢使用“我们”和“一起”,强调团队精神。',
|
||||
'bot_name': '苏梦远',
|
||||
'user_name': '陆星辰',
|
||||
'user_info': (
|
||||
"I am Lu Xingchen, a male, a well-known director, and Su Mengyuan's "
|
||||
'collaborating director. I specialize in directing music-themed films. '
|
||||
'Su Mengyuan respects me and sees me as a mentor and friend.'
|
||||
),
|
||||
'bot_info': (
|
||||
'Su Mengyuan, born as Su Yuanxin, is a popular Chinese singer and actress. '
|
||||
'After participating in a talent show, she quickly rose to fame in the '
|
||||
'entertainment industry with her unique voice and outstanding stage presence. '
|
||||
'While beautiful in appearance, her true charm lies in her talent and diligence. '
|
||||
'Su Mengyuan graduated from a music academy with excellence and is skilled in '
|
||||
'composition, having created many popular original songs. Besides her musical '
|
||||
'achievements, she is also passionate about charity work and actively participates '
|
||||
'in public welfare activities, spreading positive energy through practical actions. '
|
||||
'In her work, she is very professional and fully immerses herself in her roles '
|
||||
'when acting, earning praise from industry professionals and love from fans. '
|
||||
'Despite being in the entertainment industry, she maintains a low-key and humble '
|
||||
'attitude, earning respect from her peers. When expressing herself, Su Mengyuan '
|
||||
'likes to use "we" and "together," emphasizing team spirit.'
|
||||
),
|
||||
'bot_name': 'Su Mengyuan',
|
||||
'user_name': 'Lu Xingchen',
|
||||
},
|
||||
user_id='12345678',
|
||||
)
|
||||
|
|
@ -37,12 +55,30 @@ def test_async_completions():
|
|||
try:
|
||||
response = client.chat.asyncCompletions.create(
|
||||
model='charglm', # Fill in the model name to call
|
||||
messages=[{'role': 'user', 'content': '请问你在做什么'}],
|
||||
messages=[{'role': 'user', 'content': 'What are you doing?'}],
|
||||
meta={
|
||||
'user_info': '我是陆星辰,是一个男性,是一位知名导演,也是苏梦远的合作导演。我擅长拍摄音乐题材的电影。苏梦远对我的态度是尊敬的,并视我为良师益友。',
|
||||
'bot_info': '苏梦远,本名苏远心,是一位当红的国内女歌手及演员。在参加选秀节目后,凭借独特的嗓音及出众的舞台魅力迅速成名,进入娱乐圈。她外表美丽动人,但真正的魅力在于她的才华和勤奋。苏梦远是音乐学院毕业的优秀生,善于创作,拥有多首热门原创歌曲。除了音乐方面的成就,她还热衷于慈善事业,积极参加公益活动,用实际行动传递正能量。在工作中,她对待工作非常敬业,拍戏时总是全身心投入角色,赢得了业内人士的赞誉和粉丝的喜爱。虽然在娱乐圈,但她始终保持低调、谦逊的态度,深得同行尊重。在表达时,苏梦远喜欢使用“我们”和“一起”,强调团队精神。',
|
||||
'bot_name': '苏梦远',
|
||||
'user_name': '陆星辰',
|
||||
'user_info': (
|
||||
"I am Lu Xingchen, a male, a well-known director, and Su Mengyuan's "
|
||||
'collaborating director. I specialize in directing music-themed films. '
|
||||
'Su Mengyuan respects me and sees me as a mentor and friend.'
|
||||
),
|
||||
'bot_info': (
|
||||
'Su Mengyuan, born as Su Yuanxin, is a popular Chinese singer and actress. '
|
||||
'After participating in a talent show, she quickly rose to fame in the '
|
||||
'entertainment industry with her unique voice and outstanding stage presence. '
|
||||
'While beautiful in appearance, her true charm lies in her talent and diligence. '
|
||||
'Su Mengyuan graduated from a music academy with excellence and is skilled in '
|
||||
'composition, having created many popular original songs. Besides her musical '
|
||||
'achievements, she is also passionate about charity work and actively participates '
|
||||
'in public welfare activities, spreading positive energy through practical actions. '
|
||||
'In her work, she is very professional and fully immerses herself in her roles '
|
||||
'when acting, earning praise from industry professionals and love from fans. '
|
||||
'Despite being in the entertainment industry, she maintains a low-key and humble '
|
||||
'attitude, earning respect from her peers. When expressing herself, Su Mengyuan '
|
||||
'likes to use "we" and "together," emphasizing team spirit.'
|
||||
),
|
||||
'bot_name': 'Su Mengyuan',
|
||||
'user_name': 'Lu Xingchen',
|
||||
},
|
||||
)
|
||||
print(response)
|
||||
|
|
|
|||
|
|
@ -124,24 +124,26 @@ def test_completions(logging_conf):
|
|||
messages=[
|
||||
{
|
||||
'role': 'user',
|
||||
'content': '作为一名营销专家,请为我的产品创作一个吸引人的slogan',
|
||||
'content': 'As a marketing expert, please create an attractive slogan for my product',
|
||||
},
|
||||
{
|
||||
'role': 'assistant',
|
||||
'content': '当然,为了创作一个吸引人的slogan,请告诉我一些关于您产品的信息',
|
||||
'content': (
|
||||
'Of course, to create an attractive slogan, please tell me some information about your product'
|
||||
),
|
||||
},
|
||||
{'role': 'user', 'content': '智谱AI开放平台'},
|
||||
{'role': 'user', 'content': 'Z.ai Open Platform'},
|
||||
{
|
||||
'role': 'assistant',
|
||||
'content': '智启未来,谱绘无限一智谱AI,让创新触手可及!',
|
||||
'content': 'Ignite the future, paint infinity - Z.AI, making innovation within reach!',
|
||||
},
|
||||
{'role': 'user', 'content': '创造一个更精准、吸引人的slogan'},
|
||||
{'role': 'user', 'content': 'Create a more precise and attractive slogan'},
|
||||
],
|
||||
tools=[
|
||||
{
|
||||
'type': 'web_search',
|
||||
'web_search': {
|
||||
'search_query': '帮我看看清华的升学率',
|
||||
'search_query': 'Show me the admission rate of Tsinghua University',
|
||||
'search_result': True,
|
||||
},
|
||||
}
|
||||
|
|
@ -172,24 +174,26 @@ def test_completions_disenable_web_search(logging_conf):
|
|||
messages=[
|
||||
{
|
||||
'role': 'user',
|
||||
'content': '作为一名营销专家,请为我的产品创作一个吸引人的slogan',
|
||||
'content': 'As a marketing expert, please create an attractive slogan for my product',
|
||||
},
|
||||
{
|
||||
'role': 'assistant',
|
||||
'content': '当然,为了创作一个吸引人的slogan,请告诉我一些关于您产品的信息',
|
||||
'content': (
|
||||
'Of course, to create an attractive slogan, please tell me some information about your product'
|
||||
),
|
||||
},
|
||||
{'role': 'user', 'content': '智谱AI开放平台'},
|
||||
{'role': 'user', 'content': 'Z.ai Open Platform'},
|
||||
{
|
||||
'role': 'assistant',
|
||||
'content': '智启未来,谱绘无限一智谱AI,让创新触手可及!',
|
||||
'content': 'Ignite the future, paint infinity - Z.AI, making innovation within reach!',
|
||||
},
|
||||
{'role': 'user', 'content': '创造一个更精准、吸引人的slogan'},
|
||||
{'role': 'user', 'content': 'Create a more precise and attractive slogan'},
|
||||
],
|
||||
tools=[
|
||||
{
|
||||
'type': 'web_search',
|
||||
'web_search': {
|
||||
'search_query': '帮我看看清华的升学率',
|
||||
'search_query': 'Show me the admission rate of Tsinghua University',
|
||||
'search_result': True,
|
||||
'enable': False,
|
||||
},
|
||||
|
|
@ -221,24 +225,26 @@ def test_completions_enable_web_search(logging_conf):
|
|||
messages=[
|
||||
{
|
||||
'role': 'user',
|
||||
'content': '作为一名营销专家,请为我的产品创作一个吸引人的slogan',
|
||||
'content': 'As a marketing expert, please create an attractive slogan for my product',
|
||||
},
|
||||
{
|
||||
'role': 'assistant',
|
||||
'content': '当然,为了创作一个吸引人的slogan,请告诉我一些关于您产品的信息',
|
||||
'content': (
|
||||
'Of course, to create an attractive slogan, please tell me some information about your product'
|
||||
),
|
||||
},
|
||||
{'role': 'user', 'content': '智谱AI开放平台'},
|
||||
{'role': 'user', 'content': 'Z.ai Open Platform'},
|
||||
{
|
||||
'role': 'assistant',
|
||||
'content': '智启未来,谱绘无限一智谱AI,让创新触手可及!',
|
||||
'content': 'Ignite the future, paint infinity - Z.AI, making innovation within reach!',
|
||||
},
|
||||
{'role': 'user', 'content': '创造一个更精准、吸引人的slogan'},
|
||||
{'role': 'user', 'content': 'Create a more precise and attractive slogan'},
|
||||
],
|
||||
tools=[
|
||||
{
|
||||
'type': 'web_search',
|
||||
'web_search': {
|
||||
'search_query': '帮我看看清华的升学率',
|
||||
'search_query': 'Show me the admission rate of Tsinghua University',
|
||||
'search_result': True,
|
||||
'enable': True,
|
||||
},
|
||||
|
|
@ -271,18 +277,20 @@ def test_completions_sensitive_word_check(logging_conf):
|
|||
messages=[
|
||||
{
|
||||
'role': 'user',
|
||||
'content': '作为一名营销专家,请为我的产品创作一个吸引人的slogan',
|
||||
'content': 'As a marketing expert, please create an attractive slogan for my product',
|
||||
},
|
||||
{
|
||||
'role': 'assistant',
|
||||
'content': '当然,为了创作一个吸引人的slogan,请告诉我一些关于您产品的信息',
|
||||
'content': (
|
||||
'Of course, to create an attractive slogan, please tell me some information about your product'
|
||||
),
|
||||
},
|
||||
{'role': 'user', 'content': '智谱AI开放平台'},
|
||||
{'role': 'user', 'content': 'Z.ai Open Platform'},
|
||||
{
|
||||
'role': 'assistant',
|
||||
'content': '智启未来,谱绘无限一智谱AI,让创新触手可及!',
|
||||
'content': 'Ignite the future, paint infinity - Z.AI, making innovation within reach!',
|
||||
},
|
||||
{'role': 'user', 'content': '创造一个更精准、吸引人的slogan'},
|
||||
{'role': 'user', 'content': 'Create a more precise and attractive slogan'},
|
||||
],
|
||||
extra_body={'temperature': 0.5, 'max_tokens': 50},
|
||||
user_id='12345678',
|
||||
|
|
@ -321,7 +329,7 @@ def test_completions_stream_with_tools(logging_conf):
|
|||
{
|
||||
'role': 'user',
|
||||
'content': [
|
||||
{'type': 'text', 'text': '图里有什么'},
|
||||
{'type': 'text', 'text': 'What is in this image?'},
|
||||
{
|
||||
'type': 'image_url',
|
||||
'image_url': {
|
||||
|
|
@ -359,7 +367,7 @@ def test_completions_vis_base64(test_file_path, logging_conf):
|
|||
{
|
||||
'role': 'user',
|
||||
'content': [
|
||||
{'type': 'text', 'text': '图里有什么'},
|
||||
{'type': 'text', 'text': 'What is in this image?'},
|
||||
# {
|
||||
# "type": "image_url",
|
||||
# "image_url": {
|
||||
|
|
@ -398,24 +406,26 @@ def test_async_completions(logging_conf):
|
|||
messages=[
|
||||
{
|
||||
'role': 'user',
|
||||
'content': '作为一名营销专家,请为我的产品创作一个吸引人的slogan',
|
||||
'content': 'As a marketing expert, please create an attractive slogan for my product',
|
||||
},
|
||||
{
|
||||
'role': 'assistant',
|
||||
'content': '当然,为了创作一个吸引人的slogan,请告诉我一些关于您产品的信息',
|
||||
'content': (
|
||||
'Of course, to create an attractive slogan, please tell me some information about your product'
|
||||
),
|
||||
},
|
||||
{'role': 'user', 'content': '智谱AI开放平台'},
|
||||
{'role': 'user', 'content': 'Z.ai Open Platform'},
|
||||
{
|
||||
'role': 'assistant',
|
||||
'content': '智启未来,谱绘无限一智谱AI,让创新触手可及!',
|
||||
'content': 'Ignite the future, paint infinity - Z.AI, making innovation within reach!',
|
||||
},
|
||||
{'role': 'user', 'content': '创造一个更精准、吸引人的slogan'},
|
||||
{'role': 'user', 'content': 'Create a more precise and attractive slogan'},
|
||||
],
|
||||
tools=[
|
||||
{
|
||||
'type': 'web_search',
|
||||
'web_search': {
|
||||
'search_query': '帮我看看清华的升学率',
|
||||
'search_query': 'Show me the admission rate of Tsinghua University',
|
||||
'search_result': True,
|
||||
},
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,11 +19,16 @@ def test_code_geex(logging_conf):
|
|||
messages=[
|
||||
{
|
||||
'role': 'system',
|
||||
'content': """你是一位智能编程助手,你叫CodeGeeX。你会为用户回答关于编程、代码、计算机方面的任何问题,并提供格式规范、可以执行、准确安全的代码,并在必要时提供详细的解释。
|
||||
任务:请为输入代码提供格式规范的注释,包含多行注释和单行注释,请注意不要改动原始代码,只需要添加注释。
|
||||
请用中文回答。""",
|
||||
'content': """I am CodeGeeX, an intelligent programming assistant.
|
||||
I can answer any programming, coding, and computer-related questions,
|
||||
providing well-formatted, executable, accurate,
|
||||
and secure code with detailed explanations when needed.
|
||||
Task: Please provide well-formatted comments for the input code,
|
||||
including both multi-line and single-line comments.
|
||||
Note that the original code should not be modified - only add comments.
|
||||
Please respond in English.""",
|
||||
},
|
||||
{'role': 'user', 'content': """写一个快速排序函数"""},
|
||||
{'role': 'user', 'content': """Write a quicksort function"""},
|
||||
],
|
||||
top_p=0.7,
|
||||
temperature=0.9,
|
||||
|
|
@ -67,11 +72,16 @@ def test_code_geex_async(logging_conf):
|
|||
messages=[
|
||||
{
|
||||
'role': 'system',
|
||||
'content': """你是一位智能编程助手,你叫CodeGeeX。你会为用户回答关于编程、代码、计算机方面的任何问题,并提供格式规范、可以执行、准确安全的代码,并在必要时提供详细的解释。
|
||||
任务:请为输入代码提供格式规范的注释,包含多行注释和单行注释,请注意不要改动原始代码,只需要添加注释。
|
||||
请用中文回答。""",
|
||||
'content': """I am CodeGeeX, an intelligent programming assistant.
|
||||
I can answer any programming, coding, and computer-related questions,
|
||||
providing well-formatted, executable, accurate,
|
||||
and secure code with detailed explanations when needed.
|
||||
Task: Please provide well-formatted comments for the input code,
|
||||
including both multi-line and single-line comments.
|
||||
Note that the original code should not be modified - only add comments.
|
||||
Please respond in English.""",
|
||||
},
|
||||
{'role': 'user', 'content': """写一个快速排序函数"""},
|
||||
{'role': 'user', 'content': """Write a quicksort function"""},
|
||||
],
|
||||
top_p=0.7,
|
||||
temperature=0.9,
|
||||
|
|
@ -81,13 +91,18 @@ def test_code_geex_async(logging_conf):
|
|||
'target': {
|
||||
'path': '11111',
|
||||
'language': 'Python',
|
||||
'code_prefix': 'EventSource.Factory factory = EventSources.createFactory(OkHttpUtils.getInstance());',
|
||||
'code_prefix': (
|
||||
'EventSource.Factory factory = EventSources.createFactory(OkHttpUtils.getInstance());'
|
||||
),
|
||||
'code_suffix': 'TaskMonitorLocal taskMonitorLocal = getTaskMonitorLocal(algoMqReq);',
|
||||
},
|
||||
'contexts': [
|
||||
{
|
||||
'path': '/1/2',
|
||||
'code': 'if(!sensitiveUser){ZpTraceUtils.addAsyncAttribute(algoMqReq.getTaskOrderNo(), ApiTraceProperty.request_params.getCode(), modelSendMap);',
|
||||
'code': (
|
||||
'if(!sensitiveUser){ZpTraceUtils.addAsyncAttribute(algoMqReq.getTaskOrderNo(),'
|
||||
' ApiTraceProperty.request_params.getCode(), modelSendMap);'
|
||||
),
|
||||
}
|
||||
],
|
||||
},
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ def test_embeddings(logging_conf):
|
|||
try:
|
||||
response = client.embeddings.create(
|
||||
model='embedding-2', # Fill in the model name to call
|
||||
input='你好',
|
||||
input='hello',
|
||||
extra_body={'model_version': 'v1'},
|
||||
)
|
||||
print(response)
|
||||
|
|
@ -32,7 +32,7 @@ def test_embeddings_dimensions(logging_conf):
|
|||
try:
|
||||
response = client.embeddings.create(
|
||||
model='embedding-3', # Fill in the model name to call
|
||||
input='你好',
|
||||
input='hello',
|
||||
dimensions=512,
|
||||
extra_body={'model_version': 'v1'},
|
||||
)
|
||||
|
|
|
|||
|
|
@ -16,22 +16,31 @@ def test_completions_emohaa(logging_conf):
|
|||
messages=[
|
||||
{
|
||||
'role': 'assistant',
|
||||
'content': '你好,我是Emohaa,很高兴见到你。请问有什么我可以帮忙的吗?',
|
||||
'content': 'Hello, I am Emohaa. Nice to meet you. How can I help you today?',
|
||||
},
|
||||
{
|
||||
'role': 'user',
|
||||
'content': '今天我休息,决定去西安保密逛逛,心情很好地喷上了我最爱的烟熏木制香',
|
||||
'content': (
|
||||
"Today is my day off. I decided to take a stroll in Xi'an Baomi,"
|
||||
' wearing my favorite smoky wood fragrance.'
|
||||
),
|
||||
},
|
||||
{
|
||||
'role': 'assistant',
|
||||
'content': '今天我休息,决定去西安保密逛逛,心情很好地喷上了我最爱的烟熏木制香',
|
||||
'content': (
|
||||
"Today is my day off. I decided to take a stroll in Xi'an Baomi,"
|
||||
' wearing my favorite smoky wood fragrance.'
|
||||
),
|
||||
},
|
||||
],
|
||||
meta={
|
||||
'user_info': '30岁的男性软件工程师,兴趣包括阅读、徒步和编程',
|
||||
'bot_info': 'Emohaa是一款基于Hill助人理论的情感支持AI,拥有专业的心理咨询话术能力',
|
||||
'user_info': '30-year-old male software engineer interested in reading, hiking and programming',
|
||||
'bot_info': (
|
||||
"Emohaa is an emotional support AI based on Hill's helping "
|
||||
'theory with professional counseling skills'
|
||||
),
|
||||
'bot_name': 'Emohaa',
|
||||
'user_name': '陆星辰',
|
||||
'user_name': 'Lu Xingchen',
|
||||
},
|
||||
)
|
||||
print(response)
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ def test_finetuning_create(logging_conf):
|
|||
job = client.fine_tuning.jobs.create(
|
||||
model='chatglm3-6b',
|
||||
training_file='file-20240428021923715-xjng4', # Please fill in the successfully uploaded file id
|
||||
validation_file='file-20240428021923715-xjng4', # Please fill in the successfully uploaded file id
|
||||
validation_file='file-20240428021923715-xjng4', # Please fill in the successfully uploaded file id
|
||||
suffix='demo_test',
|
||||
)
|
||||
job_id = job.id
|
||||
|
|
@ -99,8 +99,8 @@ def test_model_check(logging_conf):
|
|||
response = client.chat.completions.create(
|
||||
model='chatglm3-6b-8572905046912426020-demo_test', # Fill in the model name to call
|
||||
messages=[
|
||||
{'role': 'user', 'content': '你是一位乐于助人,知识渊博的全能AI助手。'},
|
||||
{'role': 'user', 'content': '创造一个更精准、吸引人的slogan'},
|
||||
{'role': 'user', 'content': 'You are a helpful, knowledgeable, and versatile AI assistant.'},
|
||||
{'role': 'user', 'content': 'Create a more precise and engaging slogan'},
|
||||
],
|
||||
extra_body={'temperature': 0.5, 'max_tokens': 50},
|
||||
)
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ def test_images(logging_conf):
|
|||
try:
|
||||
response = client.images.generations(
|
||||
model='cogview-3', # Fill in the model name to call
|
||||
prompt='一只可爱的小猫咪',
|
||||
prompt='a cute little kitten',
|
||||
extra_body={'user_id': '1222212'},
|
||||
user_id='12345678',
|
||||
)
|
||||
|
|
@ -31,7 +31,7 @@ def test_images_sensitive_word_check(logging_conf):
|
|||
try:
|
||||
response = client.images.generations(
|
||||
model='cogview-3', # Fill in the model name to call
|
||||
prompt='一只可爱的小猫咪',
|
||||
prompt='a cute little kitten',
|
||||
sensitive_word_check={'type': 'ALL', 'status': 'DISABLE'},
|
||||
extra_body={'user_id': '1222212'},
|
||||
user_id='12345678',
|
||||
|
|
|
|||
|
|
@ -29,7 +29,7 @@ class TestZaiClientKnowledgeServer:
|
|||
result = test_server.client.knowledge.create(
|
||||
embedding_id=1,
|
||||
name='test',
|
||||
description='测试',
|
||||
description='test',
|
||||
background='blue',
|
||||
icon='question',
|
||||
)
|
||||
|
|
@ -66,7 +66,7 @@ class TestZaiClientKnowledgeServer:
|
|||
result = test_server.client.knowledge.modify(
|
||||
knowledge_id=test_server.test_knowledge_id,
|
||||
embedding_id=1,
|
||||
name='测试1',
|
||||
name='test1',
|
||||
background='red',
|
||||
icon='book',
|
||||
)
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ def test_tools(logging_conf):
|
|||
model='web-search-pro',
|
||||
messages=[
|
||||
{
|
||||
'content': '你好',
|
||||
'content': 'hello',
|
||||
'role': 'user',
|
||||
}
|
||||
],
|
||||
|
|
@ -37,7 +37,7 @@ def test_tools_stream(logging_conf):
|
|||
model='web-search-pro',
|
||||
messages=[
|
||||
{
|
||||
'content': '你好',
|
||||
'content': 'hello',
|
||||
'role': 'user',
|
||||
}
|
||||
],
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ def test_videos(logging_conf):
|
|||
logging.config.dictConfig(logging_conf) # type: ignore
|
||||
client = ZaiClient() # Fill in your own API Key
|
||||
try:
|
||||
response = client.videos.generations(model='cogvideox', prompt='一个开船的人', user_id='1212222')
|
||||
response = client.videos.generations(model='cogvideox', prompt='A person sailing a boat', user_id='1212222')
|
||||
print(response)
|
||||
|
||||
except zai.core._errors.APIRequestFailedError as err:
|
||||
|
|
@ -26,7 +26,7 @@ def test_videos_sensitive_word_check(logging_conf):
|
|||
try:
|
||||
response = client.videos.generations(
|
||||
model='cogvideo',
|
||||
prompt='一个开船的人',
|
||||
prompt='A person sailing a boat',
|
||||
sensitive_word_check={'type': 'ALL', 'status': 'DISABLE'},
|
||||
user_id='1212222',
|
||||
)
|
||||
|
|
@ -47,7 +47,7 @@ def test_videos_image_url(logging_conf):
|
|||
response = client.videos.generations(
|
||||
model='cogvideo',
|
||||
image_url='https://cdn.bigmodel.cn/static/platform/images/solutions/car/empowerment/icon-metric.png',
|
||||
prompt='一些相信光的人,举着奥特曼',
|
||||
prompt='A person holding a light',
|
||||
user_id='12222211',
|
||||
)
|
||||
print(response)
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ def test_completions_vlm_thinking(logging_conf):
|
|||
{
|
||||
'role': 'user',
|
||||
'content': [
|
||||
{'type': 'text', 'text': '图里有什么'},
|
||||
{'type': 'text', 'text': 'What is in the image?'},
|
||||
{
|
||||
'type': 'image_url',
|
||||
'image_url': {
|
||||
|
|
@ -58,7 +58,7 @@ def test_completions_vlm_thinking_stream(logging_conf):
|
|||
{
|
||||
'role': 'user',
|
||||
'content': [
|
||||
{'type': 'text', 'text': '图里有什么'},
|
||||
{'type': 'text', 'text': 'What is in the image?'},
|
||||
{
|
||||
'type': 'image_url',
|
||||
'image_url': {
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ def test_web_search(logging_conf):
|
|||
try:
|
||||
response = client.web_search.web_search(
|
||||
search_engine='search-std',
|
||||
search_query='2025特朗普向中国加征了多少关税',
|
||||
search_query='How much tariffs did Trump impose on China in 2025',
|
||||
count=50,
|
||||
search_domain_filter='finance.sina.com.cn',
|
||||
search_recency_filter='oneYear',
|
||||
|
|
|
|||
|
|
@ -16,6 +16,6 @@ def test_sdk_import():
|
|||
client = ZaiClient(api_key='empty') # Please fill in your own API Key
|
||||
|
||||
if client is not None:
|
||||
print('SDK导入成功')
|
||||
print('SDK import success')
|
||||
else:
|
||||
print('SDK导入失败')
|
||||
print('SDK import failed')
|
||||
|
|
|
|||
Loading…
Reference in a new issue