调用样例

重要

模型插件调用需"申请体验"并通过后才可使用,否则API调用将返回错误状态码。

本文给出了调用部分插件的CURL命令和SDK样例,样例中用CURL命令或SDK请求大模型并触发插件的调用。

您可以查看文档插件调用详细说明,按需改造调用代码,修改请求中的参数以获得不同的结果。

样例使用方法

前提条件

SDK调用

说明

需要使用您的API-KEY替换示例中的YOUR_DASHSCOPE_API_KEY,再执行Python代码。

同时满足:

Python SDK version: dashscope>=1.13.1

代码才能正常运行。

注意

Java SDK暂不支持插件功能。

API-KEY设置

export DASHSCOPE_API_KEY=YOUR_DASHSCOPE_API_KEY

CURL命令调用

说明

需要使用您的API-KEY替换示例中的<your-dashscope-api-key> ,代码才能正常运行。

插件调用样例

文字识别

请求样例

from http import HTTPStatus
import dashscope


def call_with_messages():
    plugins = {'ocr': {}}  # choose the desired plugin(s).
    messages = [{'role': 'system', 'content': 'You are a helpful assistant.'},
                {'role': 'user',
                    'content': '识别一下这个图片上的文字:https://dashscope.oss-cn-beijing.aliyuncs.com/samples/plugin/20231124161643.jpg'
                }]
    response = dashscope.Generation.call(
        model='qwen-plus',
        messages=messages,
        result_format='message',  # set the result to be 'message' format.
        plugins=plugins,
    )
    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()
curl -v --location --request POST 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation' \
--header 'Authorization: Bearer <your-dashscope-api-key>' \
--header 'Content-Type: application/json' \
--header 'X-DashScope-Plugin: {"ocr":{}}' \
--data-raw '{
  "model": "qwen-plus",
  "input": {
    "messages": [
      {
        "role": "system",
        "content": "You are a helpful assistant."
      },
      {
        "role": "user",
        "content": "识别一下这个图片上的文字:https://dashscope.oss-cn-beijing.aliyuncs.com/samples/plugin/20231124161643.jpg"
      }
    ]
  },
  "parameters": {
    "result_format": "message",
    "seed": 42
  }
}'

返回结果

使用Shell和Python SDK,返回的结果格式上稍有不同,以实际返回内容为准。结果中主要内容如下

{
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "messages": [
                    {
                        "role": "assistant",
                        "plugin_call": {
                            "name": "ocr",
                            "arguments": "{\"imageUrl\": \"https://dashscope.oss-cn-beijing.aliyuncs.com/samples/plugin/20231124161643.jpg\"}"
                        },
                        "content": "Thought: 我应该使用OCR插件来识别图片中的文字。"
                    },
                    {
                        "role": "plugin",
                        "name": "ocr",
                        "content": "{\"errMsg\": null, \"code\": 200, \"success\": true, \"requestId\": null, \"content\": \"全球数字化出海服务平台 我们致力于提供全球领先的数字外贸服务,帮助每一个中小企业成为跨国公司。 让世界更小,生意更大 \"}",
                        "status": {
                            "code": 200,
                            "name": "Success",
                            "message": "Success."
                        }
                    },
                    {
                        "role": "assistant",
                        "content": "Thought: 我现在可以作答了。\nFinal Answer: 该图片的文字是:“全球数字化出海服务平台 我们致力于提供全球领先的数字外贸服务,帮助每一个中小企业成为跨国公司。 让世界更小,生意更大”。"
                    }
                ]
            }
        ]
    },
    "usage": {
        "total_tokens": 221,
        "output_tokens": 175,
        "input_tokens": 46
    },
    "request_id": "9c19db96-e34a-9b65-bf22-e205dbf7d36b"
}

计算器

请求样例

from http import HTTPStatus
import dashscope


def call_with_messages():
    plugins = {'calculator': {}}  # choose the desired plugin(s).
    messages = [{'role': 'system', 'content': 'You are a helpful assistant.'},
                {'role': 'user', 'content': '12345*98765是多少'}]
    response = dashscope.Generation.call(
        model='qwen-plus',
        messages=messages,
        result_format='message',  # set the result to be 'message' format.
        plugins=plugins,
    )
    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()
curl -v --location --request POST 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation' \
--header 'Authorization: Bearer <your-dashscope-api-key>' \
--header 'Content-Type: application/json' \
--header 'X-DashScope-Plugin: {"calculator":{}}' \
--data-raw '{
  "model": "qwen-plus",
  "input": {
    "messages": [
      {
        "role": "system",
        "content": "You are a helpful assistant."
      },
      {
        "role": "user",
        "content": "12345*98765是多少"
      }
    ]
  },
  "parameters": {
    "result_format": "message",
    "seed": 42
  }
}'

返回结果

使用Shell和Python SDK,返回的结果格式上稍有不同,以实际返回内容为准。结果中主要内容如下

{
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "messages": [
                    {
                        "role": "assistant",
                        "plugin_call": {
                            "name": "calculator",
                            "arguments": "{\"payload__input__text\": \"12345 * 98765\"}"
                        },
                        "content": "Thought: 我应该使用计算器API来进行数学计算。"
                    },
                    {
                        "role": "plugin",
                        "name": "calculator",
                        "content": "{\"equations\": [\"12345 * 98765\"], \"results\": [1219253925.0]}",
                        "status": {
                            "code": 200,
                            "name": "Success",
                            "message": "success"
                        }
                    },
                    {
                        "role": "assistant",
                        "content": "Thought: 我现在可以作答了。\nFinal Answer: 12345*98765的结果是1219253925。"
                    }
                ]
            }
        ]
    },
    "usage": {
        "total_tokens": 134,
        "output_tokens": 116,
        "input_tokens": 18
    },
    "request_id": "2cc7d894-bde2-9181-88ac-85f95dff5e3c"
}

图片生成

请求样例

from http import HTTPStatus
import dashscope


def call_with_messages():
    plugins = {'text_to_image': {}}  # choose the desired plugin(s).
    messages = [{'role': 'system', 'content': 'You are a helpful assistant.'},
                {'role': 'user', 'content': '一只猫,黑色'}]
    response = dashscope.Generation.call(
        model='qwen-plus',
        messages=messages,
        result_format='message',  # set the result to be 'message' format.
        plugins=plugins,
    )
    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()
curl -v --location --request POST 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation' \
--header 'Authorization: Bearer <your-dashscope-api-key>' \
--header 'Content-Type: application/json' \
--header 'X-DashScope-Plugin: {"text_to_image":{}}' \
--data-raw '{
  "model": "qwen-plus",
  "input": {
    "messages": [
      {
        "role": "system",
        "content": "You are a helpful assistant."
      },
      {
        "role": "user",
        "content": "一只猫,黑色"
      }
    ]
  },
  "parameters": {
    "result_format": "message",
    "seed": 42
  }
}'

返回结果

使用Shell和Python SDK,返回的结果格式上稍有不同,以实际返回内容为准。结果中主要内容如下

{
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "messages": [
                    {
                        "role": "assistant",
                        "plugin_call": {
                            "name": "text_to_image",
                            "arguments": "{\"payload__parameters__size\": \"512*512\", \"payload__parameters__oss_signed_url\": \"true\", \"payload__input__prompt\": \"black cat\", \"payload__input__negative_prompt\": \"\"}"
                        },
                        "content": "Thought: 需要使用text_to_image API生成一张黑色的猫的图片。"
                    },
                    {
                        "role": "plugin",
                        "name": "text_to_image",
                        "content": "{\"url\": \"http://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/1d/44/20231121/ps_a74ad35c/43241cb2-bba0-9323-abee-55e7d91cf44e.png?Expires=1700623514&OSSAccessKeyId=LTAI5tGx7yvUcG32Vzcw****&Signature=xnj%2B8uv%2B5Ur46tbYPWGrbIQ49Zk%3D\"}",
                        "status": {
                            "code": 200,
                            "name": "Success",
                            "message": "success"
                        }
                    },
                    {
                        "role": "assistant",
                        "content": "Thought: 成功生成了一张黑色的猫的图片。\nFinal Answer: 黑色猫插件可以用来生成一张含有黑色猫元素的图片。插件输入一个含有黑色猫元素的提示,并将其转换为英文格式的字符串。输出结果是一张可下载的黑色猫图片。\n\n要使用此插件,请确保您的参数大小设置为“512 * 512”,并启用生成下载链接。现在可以开始使用此插件来生成您自己的黑色猫图片了!"
                    }
                ]
            }
        ]
    },
    "usage": {
        "total_tokens": 341,
        "output_tokens": 331,
        "input_tokens": 10
    },
    "request_id": "43241cb2-bba0-9323-abee-55e7d91cf44e"
}

万豪酒店预定推荐

请求样例

from http import HTTPStatus
import dashscope


def call_with_messages():
    plugins = {'haozhu_recommend_hotel': {}}  # choose the desired plugin(s).
    messages = [{'role': 'system', 'content': 'You are a helpful assistant.'},
                {'role': 'user', 'content': '你好,给我查询一下三亚的酒店'}]
    response = dashscope.Generation.call(
        model='qwen-plus',
        messages=messages,
        result_format='message',  # set the result to be 'message' format.
        plugins=plugins,
    )
    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()
curl -v --location --request POST 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation' \
--header 'Authorization: Bearer <your-dashscope-api-key>' \
--header 'Content-Type: application/json' \
--header 'X-DashScope-Plugin: {"haozhu_recommend_hotel":{}}' \
--data-raw '{
  "model": "qwen-plus",
  "input": {
    "messages": [
      {
        "role": "system",
        "content": "You are a helpful assistant."
      },
      {
        "role": "user",
        "content": "你好,给我查询一下三亚的酒店"
      }
    ]
  },
  "parameters": {
    "result_format": "message",
    "seed": 42
  }
}'

返回结果

使用Shell和Python SDK,返回的结果格式上稍有不同,以实际返回内容为准。结果中主要内容如下

{
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "messages": [
                    {
                        "role": "assistant",
                        "plugin_call": {
                            "name": "酒店推荐插件",
                            "arguments": "{\"cityNames\": \"三亚\"}"
                        },
                        "content": "Thought: 需要调用酒店推荐插件 API 来查询酒店。"
                    },
                    {
                        "role": "plugin",
                        "name": "酒店推荐插件",
                        "content": "[{\"name\": \"三亚山海天大酒店,傲途格精选\", \"snippet\": \"位于三亚市,地址是大东海海韵路77号,近大东海旅游区,属于大东海商圈,品牌为傲途格,酒店特色有信用住、无边泳池、SPA等。\", \"url\": \"checkIn=2023-11-21&checkOut=2023-11-22&shid=53131055&cityCode=460200\"}, {\"name\": \"三亚艾迪逊酒店\", \"snippet\": \"位于三亚市,地址是海棠湾 海棠湾北路100号,近免税店,近亚特兰蒂斯水世界,属于海棠湾商圈,品牌为艾迪逊,最低会员价2498元,酒店特色有信用住、迷人海景、ins风等。\", \"url\": \"checkIn=2023-11-21&checkOut=2023-11-22&shid=52427440&cityCode=460200\"}, {\"name\": \"三亚喜来登度假酒店\", \"snippet\": \"位于三亚市,地址是亚龙湾国家旅游度假区龙海路19号,近亚龙湾沙滩,属于亚龙湾商圈,品牌为喜来登,最低会员价925元,酒店特色有信用住、景观泳池、迷人海景等。\", \"url\": \"checkIn=2023-11-21&checkOut=2023-11-22&shid=10047214&cityCode=460200\"}]",
                        "status": {
                            "code": 200,
                            "name": "Success",
                            "message": "Success."
                        }
                    },
                    {
                        "role": "assistant",
                        "content": "Thought: 查询到了三亚的酒店信息。\nFinal Answer: 给您找到了三亚的酒店信息:\n\n| 名称 | 地址 | 特色 |\n| --- | --- | --- |\n| 三亚山海天大酒店,傲途格精选 | 大东海海韵路77号,近大东海旅游区 | 信用住、无边泳池、SPA |\n| 三亚艾迪逊酒店 | 海棠湾 海棠湾北路100号,近免税店,近亚特兰蒂斯水世界 | 信用住、迷人海景、ins风 |\n| 三亚喜来登度假酒店 | 亚龙湾国家旅游度假区龙海路19号,近亚龙湾沙滩 | 信用住、景观泳池、迷人海景 |\n\n可以根据需要选择适合自己的酒店。"
                    }
                ]
            }
        ]
    },
    "usage": {
        "total_tokens": 614,
        "output_tokens": 600,
        "input_tokens": 14
    },
    "request_id": "a02a6a51-ab62-9ece-9283-93289715cefc"
}

PDF解析

请求样例

from http import HTTPStatus
import dashscope


def call_with_messages():
    plugins = {'pdf_extracter': {}}  # choose the desired plugin(s).
    messages = [{'role': 'system', 'content': 'You are a helpful assistant.'},
                {'role': 'user', 'content': [
                    {'text': '总结文档'},
                    {'file': 'https://qianwen-res.oss-cn-beijing.aliyuncs.com/QWEN_TECHNICAL_REPORT.pdf'}]
                 }]
    response = dashscope.Generation.call(
        model='qwen-plus',
        messages=messages,
        result_format='message',  # set the result to be 'message' format.
        plugins=plugins,
    )
    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()
curl -v --location --request POST 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation' \
--header 'Authorization: Bearer <your-dashscope-api-key>' \
--header 'Content-Type: application/json' \
--header 'X-DashScope-Plugin: {"pdf_extracter":{}}' \
--data-raw '{
  "model": "qwen-plus",
  "input": {
    "messages": [
      {
        "role": "system",
        "content": "You are a helpful assistant."
      },
      {
        "role": "user",
        "content": [
          {
            "text": "总结文档"
          },
          {
            "file": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/QWEN_TECHNICAL_REPORT.pdf"
          }
        ]
      }
    ]
  },
  "parameters": {
    "result_format": "message",
    "seed": 42
  }
}'

返回结果

使用Shell和Python SDK,返回的结果格式上稍有不同,以实际返回内容为准。结果中主要内容如下

{
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": "这篇文档主要介绍了QWEN系列的大语言模型,包括其基本的预训练模型、聊天模型和专门针对编程和数学的模型。这些模型在各种下游任务上都表现出色,并且具有高级工具使用和计划能力,可用于创建代理应用程序。此外,还介绍了一些专门针对编码和数学的模型,它们在与开源模型相比时显示出显著的性能提升。"
                }
            }
        ]
    },
    "usage": {
        "total_tokens": 90,
        "output_tokens": 82,
        "input_tokens": 8
    },
    "request_id": "f8616d2e-6e4a-990e-a953-0eb5e7561614"
}

Python代码解释器

列方程并求解

请求样例

from http import HTTPStatus
import dashscope


def call_with_messages():
    plugins = {'code_interpreter': {}}  # choose the desired plugin(s).
    messages = [{'role': 'system', 'content': 'You are a helpful assistant.'},
                {'role': 'user', 'content': '有若干只鸡兔同在一个笼子里,从上面数,有100个头,从下面数,有334只脚。问笼中各有多少只鸡和兔?'}]
    response = dashscope.Generation.call(
        model='qwen-plus',
        messages=messages,
        result_format='message',  # set the result to be 'message' format.
        plugins=plugins,
    )
    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()
curl -v --location --request POST 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation' \
--header 'Authorization: Bearer <your-dashscope-api-key>' \
--header 'Content-Type: application/json' \
--header 'X-DashScope-Plugin: {"code_interpreter":{}}' \
--data-raw '{
  "model": "qwen-plus",
  "input": {
    "messages": [
      {
        "role": "system",
        "content": "You are a helpful assistant."
      },
      {
        "role": "user",
        "content": "有若干只鸡兔同在一个笼子里,从上面数,有100个头,从下面数,有334只脚。问笼中各有多少只鸡和兔?"
      }
    ]
  },
  "parameters": {
    "result_format": "message",
    "seed": 42
  }
}'

返回结果

使用Shell和Python SDK,返回的结果格式上稍有不同,以实际返回内容为准。结果中主要内容如下

{
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "messages": [
                    {
                        "role": "assistant",
                        "plugin_call": {
                            "name": "code_interpreter",
                            "arguments": "```py\nfrom sympy import symbols, Eq, solve\n\nx, y = symbols('x y')\neq1 = Eq(x + y, 100) # number of heads\neq2 = Eq(2*x + 4*y, 334) # number of legs\n\nsolution = solve((eq1, eq2), (x, y))\n\nchickens = solution[x]\nrabbits = solution[y]\n\nchickens, rabbits\n```"
                        },
                        "content": "Thought: 设鸡的数量为x,兔子的数量为y。根据题意,可以列出以下两个方程:x + y = 100(头的数量)2x + 4y = 334(脚的数量)。 我需要使用代码解释器API来运行代码。"
                    },
                    {
                        "role": "plugin",
                        "name": "code_interpreter",
                        "content": "execute_result:\n\n```\n(33, 67)\n```",
                        "status": {
                            "code": 200,
                            "name": "success",
                            "message": "Success."
                        }
                    },
                    {
                        "role": "assistant",
                        "content": "Thought: 根据代码的执行结果,鸡的数量是33只,兔子的数量是67只。\nFinal Answer: 笼中有33只鸡和67只兔子。"
                    }
                ]
            }
        ]
    },
    "usage": {
        "total_tokens": 276,
        "output_tokens": 228,
        "input_tokens": 48
    },
    "request_id": "f9a3c2e0-55ba-9e7f-b386-b9efe90003ac"
}

绘制函数图像

请求样例

from http import HTTPStatus
import dashscope


def call_with_messages():
    plugins = {'code_interpreter': {}}  # choose the desired plugin(s).
    messages = [{'role': 'system', 'content': 'You are a helpful assistant.'},
                {'role': 'user', 'content': '画一个y=x^2的函数图'}]
    response = dashscope.Generation.call(
        model='qwen-plus',
        messages=messages,
        result_format='message',  # set the result to be 'message' format.
        plugins=plugins,
    )
    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()
curl -v --location --request POST 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation' \
--header 'Authorization: Bearer <your-dashscope-api-key>' \
--header 'Content-Type: application/json' \
--header 'X-DashScope-Plugin: {"code_interpreter":{}}' \
--data-raw '{
  "model": "qwen-plus",
  "input": {
    "messages": [
      {
        "role": "system",
        "content": "You are a helpful assistant."
      },
      {
        "role": "user",
        "content": "画一个y=x^2的函数图"
      }
    ]
  },
  "parameters": {
    "result_format": "message",
    "seed": 42
  }
}'

返回结果

使用Shell和Python SDK,返回的结果格式上稍有不同,以实际返回内容为准。结果中主要内容如下

{
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "messages": [
                    {
                        "role": "assistant",
                        "plugin_call": {
                            "name": "code_interpreter",
                            "arguments": "```py\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx = np.linspace(-10, 10, 400)\ny = x**2\n\nplt.plot(x, y)\nplt.title('Function Graph: $y=x^2$')\nplt.grid(True)\nplt.show()\n```"
                        },
                        "content": "Thought: 我可以使用代码解释器API来绘制函数图像。假定我们需要在-10到10之间绘制函数图像。"
                    },
                    {
                        "role": "plugin",
                        "name": "code_interpreter",
                        "content": "![fig-001](https://dashscope-cn-beijing.oss-cn-beijing.aliyuncs.com/code-interpreter/temp_files/code-output-20231121-033437.859289.png?OSSAccessKeyId=LTAI5tKHB4j1Cmo6kRtd****&Expires=1700539477&Signature=cjWRl7y%2FKyJiyLgCf2fUk9uZV8A%3D)",
                        "status": {
                            "code": 200,
                            "name": "success",
                            "message": "Success."
                        }
                    },
                    {
                        "role": "assistant",
                        "content": "Thought: 函数图成功绘制出来了。\nFinal Answer: 函数y=x^2的图像成功生成。"
                    }
                ]
            }
        ]
    },
    "usage": {
        "total_tokens": 269,
        "output_tokens": 254,
        "input_tokens": 15
    },
    "request_id": "47f1da7f-6833-9122-868c-c29cfa658728"
}