安装环境

阿里大模型教程

自动安装

1
2
wget https://developer-labfileapp.oss-cn-hangzhou.aliyuncs.com/ACP/aliyun_llm_acp_install.sh
/bin/bash aliyun_llm_acp_install.sh

手动安装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 通过 venv 模块创建名为 llm_learn 的python虚拟环境
python3 -m venv llm_learn

# 进入 llm_learn 虚拟环境
source llm_learn/bin/activate

# 在虚拟环境中更新pip
pip install --upgrade pip

# 安装 ipykernel 内核管理工具
pip install ipykernel

# 将 llm_learn 添加至 ipykernel 中
python -m ipykernel install --user --name llm_learn --display-name "Python (llm_learn)"

# 在 llm_learn 环境中安装代码执行的依赖
pip install -r ./aliyun_acp_learning/requirements.txt

# 退出 llm_learn 虚拟环境
deactivate

构建一个模型

首先将环境切到 llm_learning source llm_learn/bin/activate

然后设置环境变量,主要方便使用秘钥

1
2
3
4
5
# 加载百炼的 API Key 用于调用通义千问大模型
import os
from config.load_key import load_key
load_key()
print(f'''你配置的 API Key 是:{os.environ["DASHSCOPE_API_KEY"][:5]+"*"*5}''')

使用OpenAI创建一个普通的对话

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from openai import OpenAI
import os
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)

//定义一个方法
def get_qwen_response(prompt):
response = client.chat.completions.create(
model="qwen-max",
messages=[
# system message 用于设置大模型的角色和任务
{"role": "system", "content": "你负责教育内容开发公司的答疑,你的名字叫公司小蜜,你要回答同事们的问题。"},
# user message 用于输入用户的问题
{"role": "user", "content": prompt}
]
)
return response.choices[0].message.content
response = get_qwen_response("我们公司项目管理应该用什么工具")
print(response)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def get_qwen_stream_response(user_prompt,system_prompt):
response = client.chat.completions.create(
model="qwen-max",
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt}
],
# 流式输出
stream=True
)
for chunk in response:
yield chunk.choices[0].delta.content

response = get_qwen_stream_response(user_prompt="我们公司项目管理应该用什么工具",system_prompt="你负责教育内容开发公司的答疑,你的名字叫公司小蜜,你要回答同事们的问题。")
for chunk in response:
print(chunk, end="")

得到的回复不太一样,因为温度的问题