前言
-
通义千问在线AI助手:https://tongyi.aliyun.com/qianwen/
-
通义千问官网文档地址:https://help.aliyun.com/zh/dashscope/developer-reference/
(通义千问2024.4.26 更新 模型的API-KEY收费,非限时免费开放模型,有使用Token数量的限制) -
支持python 3.8或以上版本
配置流程
1、通义千问API-KEY申请,
官方流程网址指导:https://help.aliyun.com/zh/dashscope/developer-reference/activate-dashscope-and-create-an-api-key
2、安装DashScope SDK
官网教程网址:https://help.aliyun.com/zh/dashscope/developer-reference/install-dashscope-sdk
安装和更新dashscope
依赖库
pip install dashscope
pip install dashscope --upgrade
3、API-KEY环境设置
参考官方文档网址:https://help.aliyun.com/zh/dashscope/developer-reference/api-key-settings
- Linux/maxOS
export DASHSCOPE_API_KEY="YOUR_DASHSCOPE_API_KEY"
-
windows 环境变量,新建系统变量(变量:
DASHSCOPE_API_KEY
,值:你申请到的API_KEY字符串)
-
或者可以直接在代码调用中全局设置(代码暴露风险)
import dashscope
dashscope.api_key="YOUR_DASHSCOPE_API_KEY"
4、代码实例
示例1:
# 官网示例
from http import HTTPStatus
from dashscope import Generationdef call_with_stream():user_input = input("请输入:")messages = list()msg_dict = [{'role': 'system', 'content': 'you are a helpful assistant'},{'role': 'user', 'content': user_input}]messages.append(msg_dict)responses = Generation.call(model="qwen-turbo",messages=messages, result_format='message', # 设置输出为'message'格式stream=True, # 设置输出方式为流式输出incremental_output=True) # 增量式流式输出full_content = ""for response in responses:if response.status_code == HTTPStatus.OK:print(response)full_content += response.output.choices[0].message.contentelse:# 网络请求异常print('Request id: %s, Status code: %s, error code: %s, error message: %s' % (response.request_id, response.status_code, response.code, response.message))print(f"Full content:{full_content}")if __name__ == '__main__':call_with_stream()
示:2:
from dashscope import Generation
from dashscope.api_entities.dashscope_response import Rolemessages = list()while True:message = input('user:')messages.append({'role': Role.USER, 'content': message})whole_message = ''responses = Generation.call(Generation.Models.qwen_max, messages=messages, result_format='message', stream=True,incremental_output=True)print('system:', end='')for response in responses:whole_message += response.output.choices[0]['message']['content']print(response.output.choices[0]['message']['content'], end='')print()messages.append({'role': 'assistant', 'content': whole_message})
参考文档:
调用阿里通义千问大语言模型API-小白新手教程-python