基于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即可到预期结果:

### DashScope 使用说明 DashScope 是阿里云推出的一套用于自然语言处理的服务集合,支持多种功能,如文本嵌入、重排序(Rerank)、答系统等。以下是关于 DashScope 的使用方法以及其 API 文档的关键信息。 #### 1. 安装与配置 要使用 DashScope 提供的功能,首先需要安装 `dashscope` 库并完成认证设置: ```bash pip install dashscope ``` 接着,在 Python 脚本中导入必要模块,并初始化 API 认证密钥: ```python import dashscope # 设置您的API Key dashscope.api_key = 'your_api_key_here' ``` 上述代码中的 `your_api_key_here` 需替换为您实际申请到的 API 密钥[^1]。 --- #### 2. 文本嵌入示例 DashScope 支持生成高质量的文本嵌入向量,这些向量可以应用于相似度计算、聚类分析等领域。以下是一个简单的例子展示如何创建文本嵌入: ```python from llama_index.embeddings.dashscope import ( DashScopeEmbedding, DashScopeTextEmbeddingModels, DashScopeTextEmbeddingType, ) embedding_model = DashScopeEmbedding( model=DashScopeTextEmbeddingModels.TEXT_EMBEDDING_GTE_BASE, embedding_type=DashScopeTextEmbeddingType.TEXT ) texts_to_embed = ["这是一段测试文本", "这是另一段不同的文本"] embeddings = embedding_model.embed(texts_to_embed) print(embeddings) ``` 此脚本会输出每段输入文本对应的高维向量表示。 --- #### 3. Reranker 功能介绍 除了基本的文本嵌入外,DashScope 还提供了一个名为 **Reranker** 的组件,它能够帮助优化检索系统的性能。具体来说,它可以重新评估候选文档列表的相关性得分,从而筛选出最匹配的结果[^2]。 实现方式通常涉及以下几个步骤: - 利用基础索引技术获取初步结果; - 将这些结果传递给 Reranker 模型进一步精炼; - 输出最终排名靠前的内容作为查询响应。 这种机制特别适合于复杂场景下的精准搜索需求,比如法律咨询平台或者医疗诊断辅助工具开发过程中遇到的大规模数据集管理挑战。 --- #### 4. 更多学习资源推荐 对于希望深入探索该领域的朋友而言,建议查阅下列权威资料来扩展视野: - [DashScope 官方文档](https://dashscope.aliyun.com/api): 获取最新版本特性更新详情及最佳实践案例分享。 - [LangChain 文档](https://python.langchain.com/): 学习如何集成不同框架形成端到端解决方案。 - FAISS GitHub 页面: 掌握高效近似最近邻算法原理及其应用技巧。 - 图书《Information Retrieval》(作者 Christopher D. Manning 等): 奠定扎实理论功底的同时理解现代 IR 技术背后的思想脉络。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

ltshan139

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

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

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

打赏作者

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

抵扣说明:

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

余额充值