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
  • 单轮对话
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()
{"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}}
  • 多轮对话
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')
  • 流式输出
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()
  • 定义工具
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()
{'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}}

相关推荐

  1. golang调用阿里的接口

    2024-04-21 00:58:04       15 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-21 00:58:04       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-21 00:58:04       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-21 00:58:04       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-21 00:58:04       20 阅读

热门阅读

  1. 【Cookie,Session,Token,JWT的区别】

    2024-04-21 00:58:04       11 阅读
  2. Android 单一音量控制

    2024-04-21 00:58:04       13 阅读
  3. Spark面试整理-Spark集成Hive

    2024-04-21 00:58:04       15 阅读
  4. 4月20日,每日信息差

    2024-04-21 00:58:04       13 阅读
  5. Python框架django项目

    2024-04-21 00:58:04       15 阅读
  6. oepncv android 使用笔记

    2024-04-21 00:58:04       13 阅读
  7. 使用leaflet给地图添加蒙版(超级详细免费看)

    2024-04-21 00:58:04       15 阅读
  8. 个人开发者,Spring Boot 项目如何部署

    2024-04-21 00:58:04       14 阅读