山大软院创新实训之大模型篇(一)——AutoDL部署ChatGLM
1. 环境配置
首先下载大模型。这里下载采用的地址是阿里魔搭上的Chatglm-6b-(chat)地址。
mkdir models
cd models
apt update
apt install git-lfs
git clone https://www.modelscope.cn/ZhipuAI/chatglm3-6b.git
然后下载项目,安装依赖。
mkdir webcodes
cd webcodes
git clone https://github.com/THUDM/ChatGLM3.git
pip install -r requirements.txt
配置过程中遇到了JSON bug,采用修复代码如下。在 modelscope/hub/api.py
中,更新方法以处理非JSON响应:
def get_model_branches_and_tags_details(self, model_name_or_path):
r = self._send_request("GET", f"/path/to/endpoint/{model_name_or_path}")
logging.debug(f"Response status code: {r.status_code}")
logging.debug(f"Response content: {r.text}")
if r.status_code != 200:
logging.error(f"Request failed with status code {r.status_code}")
raise ValueError(f"Request failed with status code {r.status_code}")
try:
d = r.json()
except requests.exceptions.JSONDecodeError as e:
logging.error(f"Failed to decode JSON: {e}")
logging.error(f"Response text: {r.text}")
raise ValueError(f"Failed to decode JSON: {e}")
return d
至此环境配置完成。
2. 环境测试
实现一个使用Python调用远程ChatGLM API的程序示例。使用requests
库来发送HTTP请求(在代码中我隐去了我的IP地址等信息)。
import requests
import json
def call_chatglm_api(api_url, api_key, prompt):
headers = {
'Content-Type': 'application/json',
'Authorization': f'Bearer {api_key}'
}
data = {
'prompt': prompt,
'max_length': 200,
'temperature': 0.7,
'top_p': 0.9
}
response = requests.post(api_url, headers=headers, data=json.dumps(data))
if response.status_code == 200:
response_data = response.json()
return response_data.get('response', 'No response field in API response')
else:
return f"Error: {response.status_code}, {response.text}"
if __name__ == "__main__":
# Replace these with your actual API URL and API Key
api_url = "https://your-chatglm-api-endpoint.com/v1/chat"
api_key = "your_api_key"
# Replace this with your actual prompt
prompt = "你好"
response = call_chatglm_api(api_url, api_key, prompt)
print(f"ChatGLM Response: {response}")
call_chatglm_api
函数:接收api_url
(API的URL)、api_key
(用于身份验证的API密钥)和prompt
(发送给ChatGLM的提示)。使用HTTP POST请求发送数据到API,处理响应、并返回API的回复。
模型效果如下,至此配置完成。