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}}
相关推荐
yuanpan18 分钟前
.net/C#进程间通信技术方案总结
开发语言·c#·.net
吃面不喝汤6627 分钟前
破解 Qt QProcess 在 Release 模式下的“卡死”之谜
开发语言·qt
@十八子德月生34 分钟前
8天Python从入门到精通【itheima】-1~5
大数据·开发语言·python·学习
jiunian_cn35 分钟前
【c++】异常详解
java·开发语言·数据结构·c++·算法·visual studio
martian6651 小时前
信创生态核心技术栈:数据库与中间件
开发语言·中间件·系统架构·系统安全·创业创新
Bl_a_ck1 小时前
开发环境(Development Environment)
开发语言·前端·javascript·typescript·ecmascript
每天一个秃顶小技巧2 小时前
02.Golang 切片(slice)源码分析(一、定义与基础操作实现)
开发语言·后端·python·golang
安特尼3 小时前
招行数字金融挑战赛数据赛道赛题一
人工智能·python·机器学习·金融·数据分析
serve the people3 小时前
解决osx-arm64平台上conda默认源没有提供 python=3.7 的官方编译版本的问题
开发语言·python·conda
柒七爱吃麻辣烫3 小时前
在Linux中安装JDK并且搭建Java环境
java·linux·开发语言