python免费调用阿里云通义千问(q-wen-max)大模型API

文章目录

通义千问

通义千问,是基于阿里巴巴达摩院在自然语言处理领域的研究和积累。采用更先进的算法和更优化的模型结构,能够更准确地理解和生成自然语言、代码、表格等文本。

支持更多定制化需求。除了基本的文本生成和问答能力,还支持更多的定制化需求,可以针对不同场景和应用进行扩展和定制,提供更加个性化的服务和解决方案。

开通免费API Key

网址:https://bailian.console.aliyun.com/?spm=5176.28515448.J_TC9GqcHi2edq9zUs9ZsDQ.1.11fc38b19UJPh6#/home

进入阿里云大模型服务百炼平台,可以看到所有通义千问模型,选择适当的模型进行调用。

创建好API Key之后,进入阿里云服务百炼的个人账号即可看到调用需要的API Key。

产品文档中有详尽的参数设置以及使用指引和具体的各种调用代码。


python调用阿里云通义千问API
  • 单轮对话
python 复制代码
import random
from http import HTTPStatus
from dashscope import Generation
import dashscope
dashscope.api_key  = "sk-xxxx"

def call_with_messages():
    messages = [{'role': 'system', 'content': 'You are a helpful assistant.'},
                {'role': 'user', 'content': '如何做西红柿炒鸡蛋?'}]
    response = Generation.call("qwen-turbo",
                               messages=messages,
                               # 设置随机数种子seed,如果没有设置,则随机数种子默认为1234
                               seed=random.randint(1, 10000),
                               # 将输出设置为"message"格式
                               result_format='message')
    if response.status_code == HTTPStatus.OK:
        print(response)
    else:
        print('Request id: %s, Status code: %s, error code: %s, error message: %s' % (
            response.request_id, response.status_code,
            response.code, response.message
        ))


if __name__ == '__main__':
    call_with_messages()
python 复制代码
{"status_code": 200, "request_id": "d7823140-7709-9545-8849-f256e5ee7d5a", "code": "", "message": "", "output": {"text": null, "finish_reason": null, "choices": [{"finish_reason": "stop", "message": {"role": "assistant", "content": "材料:\n西红柿2个,鸡蛋3个,油适量,盐适量,糖适量,葱花适量\n\n步骤:\n\n1. 西红柿洗净切块,鸡蛋打入碗中搅拌均匀。\n\n2. 热锅凉油,油热后倒入鸡蛋液,用筷子快速搅拌,炒至半熟后盛出备用。\n\n3. 锅中再加少许油,放入西红柿块,中小火慢慢翻煮,让西红柿出汁。\n\n4. 当西红柿软烂出汁时,加入适量的糖,可以中和西红柿的酸味。\n\n5. 加入炒好的鸡蛋,继续翻煮均匀,让鸡蛋充分吸收西红柿的汁水。\n\n6. 最后撒上适量的盐调味,撒上葱花提香,翻煮均匀即可出锅。\n\n7. 可以根据个人口味适当调整糖和盐的量。\n\n这样一道美味的西红柿炒鸡蛋就做好了,色泽红亮,酸甜适口,营养丰富。"}}]}, "usage": {"input_tokens": 25, "output_tokens": 206, "total_tokens": 231}}
  • 多轮对话
python 复制代码
from dashscope import Generation

def get_response(messages):
    response = Generation.call("qwen-turbo",
                               messages=messages,
                               # 将输出设置为"message"格式
                               result_format='message')
    return response

messages = [{'role': 'system', 'content': 'You are a helpful assistant.'}]

# 您可以自定义设置对话轮数,当前为3
for i in range(3):
    user_input = input("请输入:")
    messages.append({'role': 'user', 'content': user_input})
    assistant_output = get_response(messages).output.choices[0]['message']['content']
    messages.append({'role': 'assistant', 'content': assistant_output})
    print(f'用户输入:{user_input}')
    print(f'模型输出:{assistant_output}')
    print('\n')
  • 流式输出
python 复制代码
from http import HTTPStatus
from dashscope import Generation

def call_with_stream():
    messages = [
        {'role': 'user', 'content': '如何做西红柿炖牛腩?'}]
    responses = Generation.call("qwen-turbo",
                                messages=messages,
                                result_format='message',  # 设置输出为'message'格式
                                stream=True, # 设置输出方式为流式输出
                                incremental_output=True  # 增量式流式输出
                                )
    for response in responses:
        if response.status_code == HTTPStatus.OK:
            print(response.output.choices[0]['message']['content'],end='')
        else:
            print('Request id: %s, Status code: %s, error code: %s, error message: %s' % (
                response.request_id, response.status_code,
                response.code, response.message
            ))


if __name__ == '__main__':
    call_with_stream()
  • 定义工具
python 复制代码
import json
from dashscope import Generation
from datetime import datetime

# 定义工具列表,模型在选择使用哪个工具时会参考工具的name和description
tools = [
    # 工具1 获取当前时刻的时间
    {"type": "function",
     "function" :{"name": "get_current_time",
                 "description": "当你想知道现在的时间时非常有用。",
                 # 因为获取当前时间不需要设置参数,因此这里的parameters设置为空字典
                 "parameters": {}}},
    # 工具2 获取指定城市的天气
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "当你想查询指定城市的天气时非常有用。",
            # 模型在决策输入工具的参数时会参考parameters信息
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "城市或县区,比如北京市、杭州市、余杭区等。"
                    }
                    }
                },
                "required": [
                    "location"
                ]
            }
        }
]


def call_with_messages():
    # 此处的content是用户的问题
    messages = [
            {
                "content": "北京天气怎么样?", # 您也可以用"北京天气怎么样?"进行测试
                "role": "user"
            }]

    response = Generation.call(
            model='qwen-turbo',
            messages=messages,
            tools=tools,
            seed=random.randint(1, 10000),  # 设置随机数种子seed,如果没有设置,则随机数种子默认为1234
            result_format='message' # 将输出设置为message形式
        )
    print(response.output.choices[0].message['tool_calls'][0])
    print(response)

if __name__ == '__main__':
    call_with_messages()
python 复制代码
{'function': {'name': 'get_current_weather', 'arguments': '{"location": "北京市"}'}, 'id': '', 'type': 'function'}
{"status_code": 200, "request_id": "82a610b3-f225-9e4c-9294-e1883ab023e4", "code": "", "message": "", "output": {"text": null, "finish_reason": null, "choices": [{"finish_reason": "tool_calls", "message": {"role": "assistant", "content": "", "tool_calls": [{"function": {"name": "get_current_weather", "arguments": "{\"location\": \"北京市\"}"}, "id": "", "type": "function"}]}}]}, "usage": {"input_tokens": 224, "output_tokens": 18, "total_tokens": 242}}
相关推荐
知识分享小能手2 分钟前
mysql学习教程,从入门到精通,SQL DISTINCT 子句 (16)
大数据·开发语言·sql·学习·mysql·数据分析·数据库开发
Huazzi.3 分钟前
算法题解:斐波那契数列(C语言)
c语言·开发语言·算法
意如流水任东西6 分钟前
[C++]类和对象(上)
开发语言·c++
清纯世纪11 分钟前
基于深度学习的图像分类或识别系统(含全套项目+PyQt5界面)
开发语言·python·深度学习
孤寂大仙v12 分钟前
【C++】STL----stack和queue常见用法
开发语言·c++
孤华暗香16 分钟前
Python快速入门 —— 第三节:类与对象
开发语言·python
didiplus17 分钟前
【趣学Python算法100例】百钱百鸡
python·算法·百钱百鸡
pzx_00130 分钟前
【内积】内积计算公式及物理意义
数据结构·python·opencv·算法·线性回归
一丝晨光31 分钟前
逻辑运算符
java·c++·python·kotlin·c#·c·逻辑运算符
元气代码鼠32 分钟前
C语言程序设计(进阶)
c语言·开发语言·算法