基于dashscope在线调用千问大模型

前言

dashscope是阿里云大模型服务平台——灵积提供的在线API组件。基于它,无需本地加载大模型,通过在线方式访问云端大模型来完成对话。 

申请API key

老规矩:要想访问各家云端大模型,需要先申请API key。

对于阿里云,需要先访问:https://dashscope.console.aliyun.com/。然后注册一个账号,接着就可以申请sk-开头的api-key了,如下图所示。

有了key后,就可以点击上面选项:模型体验中心,输入简单的prompt来验证本地电脑访问阿里云网络通信有没有问题:

 代码

下面是一个简单python代码,自己封装message,并添加api-key,并通过在线方式访问Qwen大模型进行对话。

import dashscope
from typing import List
import logging

class Params:
    def __init__(self, model, temperature, api_key, messages):
        self.model = model
        self.temperature = temperature
        self.api_key = api_key
        self.messages = messages #List[Dict[str, str]]
        

class QwenClient:
    def __init__(self, log_verbose: bool = False):
        self.log_verbose = log_verbose
        self.logger = logging.getLogger(__name__)
        if log_verbose:
            self.logger.setLevel(logging.INFO)

    def call_qwen(self, params: Params) -> List[dict]:
        # 加载配置文件,根据需要选择第一个模型        
        if self.log_verbose:
            self.logger.info(f'{self.__class__.__name__}:params: {params}')

        # 初始化生成器对象
        gen = dashscope.Generation()

        # 调用千问API并获取回复
        responses = gen.call(
            model=params.model,
            temperature=params.temperature,
            api_key=params.api_key,
            messages= params.messages,
            result_format='message',
            stream=True,
        )        
        print("responses: ", responses)

        # 处理API返回的结果
        response_list = []
        for resp in responses:
            if resp["status_code"] == 200 and "output" in resp and "choices" in resp["output"]:
                choice = resp["output"]["choices"][0]["message"]["content"]
                response_list.append({"error_code": 0, "text": choice})
            else:
                error_data = {
                    "error_code": resp["status_code"],
                    "text": resp["message"],
                    "error": {
                        "message": resp["message"],
                        "type": "invalid_request_error",
                        "param": None,
                        "code": None,
                    }
                }
                self.logger.error(f"请求千问 API 时发生错误:{error_data}")
                response_list.append(error_data)

        return response_list

# 使用示例
if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    #model_names = ["qwen-turbo"]
    client = QwenClient(log_verbose=True)

    user_input = "你好,请问今天北京天气怎么样?"
    messages = [{"role": "user", "content": user_input}]
    params = Params("qwen-turbo", 0.7, "sk-axxxxxx3b4a2fa1cb1dd7e71a4bee", messages)
    
    responses = client.call_qwen(params)

    print("千问的回答:", responses[-1]["text"])

 需要先安装好组件:dashscope,typing以及logging。本平台是ubuntu20.04,直接输入:python3 xxx.py即可到预期结果:

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ltshan139

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值