# GLMsAPIWrapper
**Repository Path**: ezemeti/GLMsAPIWrapper
## Basic Information
- **Project Name**: GLMsAPIWrapper
- **Description**: 根据ChatGLM官网的调用智能体API,封装了API调用,并且支持连文对话等等!
- **Primary Language**: Unknown
- **License**: Not specified
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 0
- **Created**: 2024-07-01
- **Last Updated**: 2024-07-01
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# 调用ChatGLM智能体

## 简介
> 具备开发能力的创作者可以通过API调用的方式使用智能体,方便将智能体应用于更多业务场景中。API基本覆盖清言C端页面所有功能,包含文本对话,文生图,图片解读,联网搜索,文档解析,Python代码执行,外部API调用等。接入前请通过创作者中心获取api_key及api_secret. 当前仅支持通过API方式调用创作者自己创建的智能体。
## 创建智能体
首先打开智谱清言,注册登录
[ChatGLM官网](https://chatglm.cn/)
### 1. 创建智能体
1. 打开智谱清言,注册登录
2. 点击创建智能体
3. 描述智能体
4. 继续配置完善智能体
根据自己的需求继续完善智能体配置
5. 添加知识库
知识库是智能体最核心的部分,知识库可以理解为智能体所掌握的知识库。知识库支持文档格式,网络路径格式等等。
知识库支持多种格式,目前支持的格式有:
网址链接格式:
知识库限制:
6. 记住智能体ID
### 2. 获取api_key及api_secret
1. 点击已创建好的智能体
2. 打开创作者中心
3. 打开API管理, 获取api_key及api_secret
## 快速开始
### 1. 安装依赖
```bash
pip install requests
```
### 2. 封装调用智能体API代码
首先创建`GLMsAPIWrapper.py`文件,并写入以下代码
```python
import requests
import json
class GLMsAPIWrapper:
def __init__(self, api_key, api_secret, assistant_id):
self.api_key = api_key
self.api_secret = api_secret
self.assistant_id = assistant_id
self.access_token = self.get_access_token(api_key, api_secret)
self.conversation_id = None # 用于存储会话ID
def get_access_token(self, api_key, api_secret):
url = "https://chatglm.cn/chatglm/assistant-api/v1/get_token"
data = {
"api_key": api_key,
"api_secret": api_secret
}
response = requests.post(url, json=data)
token_info = response.json()
return token_info['result']['access_token']
def handle_response(self, data_dict):
message = data_dict.get("message")
if message:
content = message.get("content")
if content:
response_type = content.get("type")
if response_type == "text":
return content.get("text", "No text provided")
elif response_type == "image":
images = content.get("image", [])
image_urls = ", ".join(image.get("image_url") for image in images)
return image_urls
elif response_type == "code":
return content.get('code')
elif response_type == "execution_output":
return content.get('content')
elif response_type == "system_error":
return content.get('content')
elif response_type == "tool_calls":
# 检查 'tool_calls' 是否存在
if 'tool_calls' in data_dict:
return data_dict['tool_calls']
else:
return "No tool calls found in the response"
elif response_type == "browser_result":
content = json.loads(content.get("content", "{}"))
return f"Browser Result - Title: {content.get('title')} URL: {content.get('url')}"
# 如果没有匹配的响应类型,返回一个默认的消息
return "Unsupported response type"
def send_message(self, prompt, new_conversation=False, file_list=None, meta_data=None):
url = "https://chatglm.cn/chatglm/assistant-api/v1/stream"
headers = {
"Authorization": f"Bearer {self.access_token}",
"Content-Type": "application/json"
}
data = {
"assistant_id": self.assistant_id,
"prompt": prompt,
}
# 根据new_conversation的值决定是否使用现有的conversation_id
if not new_conversation and self.conversation_id:
data["conversation_id"] = self.conversation_id
elif new_conversation:
self.conversation_id = None # 如果是新的对话,先清除之前的会话ID
if file_list:
data["file_list"] = file_list
if meta_data:
data["meta_data"] = meta_data
output = None # Initialize output variable to store the final output
with requests.post(url, json=data, headers=headers, stream=True) as response:
if response.status_code == 200:
for line in response.iter_lines():
if line:
decoded_line = line.decode('utf-8')
if decoded_line.startswith('data:'):
decoded_line = line.decode('utf-8')
if decoded_line.startswith('data:'):
data_dict = json.loads(decoded_line[5:])
output = self.handle_response(data_dict)
# 如果是新的对话,保存返回的conversation_id
if 'conversation_id' in data_dict and new_conversation:
self.conversation_id = data_dict['conversation_id']
else:
output = "Request failed", response.status_code
return {"output":output,"conversation_id":self.conversation_id} # Return the final output after processing all lines
```
### 3. 代码讲解
#### 类定义
```python
class GLMsAPIWrapper:
```
定义了一个名为`GLMsAPIWrapper`的类。
#### 初始化方法 `__init__`
```python
def __init__(self, api_key, api_secret, assistant_id):
```
- **参数**:
- `api_key`: API密钥,用于身份验证。
- `api_secret`: API密钥对应的密钥,增强安全性。
- `assistant_id`: 智能体ID,标识与哪个聊天智能体进行交互。
- **内部操作**:
- 初始化实例变量:`api_key`, `api_secret`, `assistant_id`, 并调用`get_access_token`方法获取访问令牌。
- 设置`conversation_id`为`None`,用于跟踪对话会话ID。
#### 方法 `get_access_token`
```python
def get_access_token(self, api_key, api_secret):
```
- **功能**:向指定URL发送POST请求,携带`api_key`和`api_secret`,获取访问令牌。
- **返回**:从响应中提取的访问令牌字符串。
#### 方法 `handle_response`
```python
def handle_response(self, data_dict):
```
- **功能**:处理API响应中的数据字典,根据响应类型返回不同的内容。
- **处理逻辑**:
- 文本(`text`):直接返回文本内容。
- 图像(`image`):构建并返回所有图像URL的字符串。
- 代码(`code`):返回代码内容。
- 执行输出(`execution_output`):返回执行输出的内容。
- 系统错误(`system_error`):返回错误内容。
- 工具调用(`tool_calls`):检查并返回工具调用信息,若不存在则返回提示信息。
- 浏览器结果(`browser_result`):解析并格式化返回的浏览器结果标题和URL。
- **默认**:如果响应类型不支持,则返回“Unsupported response type”。
#### 方法 `send_message`
```python
def send_message(self, prompt, new_conversation=False, file_list=None, meta_data=None):
```
- **功能**:向API发送消息,支持流式响应处理,可以开始新对话或继续现有对话。
- **参数**:
- `prompt`: 要发送的消息内容。
- `new_conversation`: 布尔值,指示是否开启新对话。
- `file_list`: 附加文件列表(可选)。
- `meta_data`: 附加元数据(可选)。
- **过程**:
- 准备请求头和数据,根据`new_conversation`决定是否携带`conversation_id`。
- 发起POST请求到指定的流式URL,实时处理响应行。
- 解码并处理每行响应数据,调用`handle_response`处理内容。
- 若开启新对话且收到`conversation_id`,则更新实例的`conversation_id`。
- 最终返回包含处理后的输出及当前`conversation_id`的字典。
### 4. 调用示例
首先导入GLMsAPIWrapper文件,
```python
from GLMsAPIWrapper import GLMsAPIWrapper
```
创建一个实例,并传入API密钥、API密钥密钥和智能体ID。
```python
api_key = "your_api_key"
api_secret = "your_api_secret"
assistant_id = "your_assistant_id"
wrapper = GLMsAPIWrapper(api_key, api_secret, assistant_id)
```
可以通过调用`send_message`方法来发送消息,并接收响应。
首先,我们来发送一条消息,并开启新对话。
```python
response = wrapper.send_message("你好", new_conversation=True)
```
继续发送消息,并继续现有对话。
你可以像这样发送消息:
```python
response = wrapper.send_message("你好", new_conversation=False)
```
`new_conversation=False`表示继续现有对话,此时`wrapper.send_message`会使用之前保存的`conversation_id`。默认情况下,`new_conversation`为`False`。
完整代码示例:
```python
from GLMsAPIWrapper import GLMsAPIWrapper
api_key = "your_api_key" # 替换为你的API密钥
api_secret = "your_api_secret" # 替换为你的API密钥密钥
assistant_id = "your_assistant_id" # 替换为你的智能体ID
wrapper = GLMsAPIWrapper(api_key, api_secret, assistant_id)
response = wrapper.send_message("你好", new_conversation=True) # 发送消息,开启新对话
print(response) # 打印响应内容
# 继续对话
response = wrapper.send_message("你好", new_conversation=False) # 发送消息,继续现有对话。当new_conversation为False时,会继续使用之前保存的conversation_id
print(response) # 打印响应内容
```
## 克隆代码
你可以使用Gitee提供的克隆命令来克隆代码。
1. 打开终端或命令行。
2. 运行以下命令,克隆代码。
```bash
git clone https://gitee.com/ezemeti/GLMsAPIWrapper.git
```
3. 公众号
