Skip to main content

Invoke a workflow application

This guide explains how to quickly and efficiently integrate an Alibaba Cloud Model Studio Workflow Application into your business system using the DashScope SDK or an HTTP API.

To call the Responses API, see Responses API.
This topic is applicable only to the China (Beijing) region.
Bailian workflows do not support text-to-image models.

Prerequisites

Before you begin, ensure you have completed the following:
  1. You have obtained an API key and set it as an environment variable.
  2. Create a workflow application. Open the workflow list and get the APP_ID from the application card.
  3. If you use the DashScope SDK, you must have the DashScope SDK installed.

Quick start

  • Python
  • Java
  • HTTP
Sample request
import os
import dashscope
from dashscope import DashScopeError

client = dashscope.Client(
    # 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
    api_key=os.getenv("DASHSCOPE_API_KEY"))
try:
    response = client.apps.completions.create(
        app_id='APP_ID',# 替换为实际的应用 ID
        prompt='你是谁?')
    print(response.text)
except DashScopeError as e:
    print(f'request_id={e.request_id}')
    print(f'code={e.code}')
    print(f'message={e.message}')
    print(f'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
Sample response
我是阿里云开发的一款超大规模语言模型,我叫千问。我被设计用来帮助用户生成各种类型的文本,如文章、故事、诗歌、故事等,并能根据不同的场景和需求进行调整和优化。此外,我还能够回答各种问题,提供信息和解释,辅助学习和研究。如果您有任何需要,欢迎随时向我提问!

Multi-turn conversation

Compared with single-turn conversations, multi-turn conversations allow the large model to reference historical conversation information, which better matches everyday communication scenarios.
Usesession_idThe system automatically loads the stored conversation history from the cloud and combines it with the prompt instruction to generate the context. This approach is simple to implement and requires no maintenance.
A session_id is valid for 1 hour and supports a maximum of 50 conversation turns.
Managemessages (Recommended)Maintain a messages array yourself, manually recording and passing the conversation history and new instructions for each turn. The prompt does not need to be passed. You control the context, which is more flexible.
Note: If the request contains both session_id and messages, the system will use messages first.
After you configure the prompt variable historyList in the LLM node and publish the application, initiate the API call.
  • Cloud storage
  • Self-managed
  • Python
  • Java
  • HTTP
Sample request
import os
import dashscope
from dashscope import DashScopeError

def call_with_session():
    client = dashscope.Client(
        # 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
        api_key=os.getenv("DASHSCOPE_API_KEY"))
    try:
        response = client.apps.completions.create(
            app_id='APP_ID',  # 替换为实际的应用 ID
            prompt='你是谁?')

        responseNext = client.apps.completions.create(
                    app_id='APP_ID',  # 替换为实际的应用 ID
                    prompt='你有什么技能?',
                    session_id=response.session_id)  # 上一轮response的session_id

        print('%s\n session_id=%s\n' % (responseNext.text, responseNext.session_id))
        # print('%s\n' % (response.usage))
    except DashScopeError as e:
        print(f'request_id={e.request_id}')
        print(f'code={e.code}')
        print(f'message={e.message}')
        print(f'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')

if __name__ == '__main__':
    call_with_session()
Sample response
我具备多种技能,可以协助你完成各种任务。以下是一些主要的技能:

1. **信息查询**:提供天气、新闻、历史事实、科学知识等各种信息。
2. **语言处理**:翻译文本、纠正语法错误、生成文章和故事。
3. **技术问题解答**:解答编程、软件使用、技术故障排除等问题。
4. **学习辅导**:帮助解答数学、物理、化学等学科的问题。
5. **生活建议**:提供健康、饮食、旅行、购物等方面的建议。
6. **娱乐互动**:讲笑话、玩文字游戏、进行简单的聊天互动。
7. **日程管理**:提醒重要日期、安排日程、设置提醒。
8. **数据分析**:解释数据图表、提供数据分析建议。
9. **情感支持**:倾听你的感受、提供安慰和支持。

如果你有具体的需求或问题,可以直接告诉我,我会尽力帮助你!
 session_id=98ceb3ca0c4e4b05a20a00f913050b42

Streaming output

When a large model receives input, it generates and returns intermediate results in real time. This process, called streaming output, lets you view content as the model generates it, reducing your wait time. To enable streaming output, set the appropriate parameter for your method:
  • Python SDK: set the stream parameter to True.
  • Java SDK: use the streamCall method.
  • HTTP: set X-DashScope-SSE to enable in the Header.
By default, streaming output is non-incremental, meaning each response includes all previously generated content. To enable incremental output, set the corresponding parameter:
  • Python SDK: Set the incremental_output parameter to True.
  • Java SDK: Call the incrementalOutput method with true.
  • HTTP: In the parameters object, set the incremental_output parameter to true.

Streaming mode

The flow_stream_mode parameter controls the streaming output mode for a workflow application. The parameter values are as follows:
message_format_plus(Recommended)Message enhancement mode streams the execution process and results for all nodes in the workflow_message field. Returns the same data structure as message_format.
Requires Python SDK version 1.24.0 or later, or Java SDK version 2.22.18 or later.
message_format(Recommended)In message mode, the execution result of the specified node is returned in a streaming manner and structured in the message field. Prerequisite: The Stream switch for the target node must be enabled in the console.
full_thoughts (Default, not recommended)Full thoughts mode streams execution details for all nodes in the thoughts field and is suitable for debugging.This requires setting the has_thoughts parameter to true.Not recommended for new applications. Use message_format or message_format_plus instead.
  • message_format_plus mode
  • Message format mode
  • full_thoughts mode
This enhanced message mode streams execution status and results for all node types through the workflow_message field. This mode uses the same data structure as the message_format mode but extends streaming support to all node types.
Client-side handling rules:
  • The message.content of all nodes is incremental output and must be appended and concatenated. Some nodes (such as the start node and variable replacement) push only one data packet.
  • When node_is_completed=true, it indicates that the node has finished executing.
  • HTTP
  • Python
  • Java
Sample request
curl --location 'https://dashscope.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion' \
--header 'X-DashScope-SSE: enable' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer YOUR_DASHSCOPE_API_KEY' \
--data '{
    "input": {
        "prompt": "你好"
    },
    "parameters": {
        "flow_stream_mode": "message_format_plus"
    }
}'
Sample responseThe following response example shows the complete streaming of a workflow through a series of Server-Sent Events (SSE):
id:1
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"3d46d9a4ae...","workflow_message":{"node_status":"success","node_type":"Start","node_msg_seq_id":1,"node_name":"开始","message":{"content":"{\"user\":{}}","role":"assistant"},"node_is_completed":true,"node_id":"Start_iEca"},"finish_reason":"null"},"usage":{},"request_id":"0e241c2b-..."}

id:2
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"3d46d9a4ae...","workflow_message":{"node_status":"executing","node_type":"LLM","node_msg_seq_id":1,"node_name":"大模型1","message":{"content":"{\"result\":\"你好\",\"reasoningContent\":\"\"}","role":"assistant"},"node_is_completed":false,"node_id":"LLM_NPem"},"finish_reason":"null"},"usage":{},"request_id":"0e241c2b-..."}

id:3
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"3d46d9a4ae...","workflow_message":{"node_status":"executing","node_type":"LLM","node_msg_seq_id":2,"node_name":"大模型1","message":{"content":"{\"result\":\"呀!有什么\",\"reasoningContent\":\"\"}","role":"assistant"},"node_is_completed":false,"node_id":"LLM_NPem"},"finish_reason":"null"},"usage":{},"request_id":"0e241c2b-..."}

id:4
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"3d46d9a4ae...","workflow_message":{"node_status":"success","node_type":"LLM","node_msg_seq_id":10,"node_name":"大模型1","message":{"content":"","role":"assistant"},"node_is_completed":true,"node_id":"LLM_NPem"},"finish_reason":"null"},"usage":{"models":[{"input_tokens":15,"output_tokens":50,"model_id":"qwen-plus-latest"}]},"request_id":"0e241c2b-..."}

id:5
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"3d46d9a4ae...","workflow_message":{"node_status":"success","node_type":"End","node_msg_seq_id":2,"node_name":"结束","message":{"content":"","role":"assistant"},"node_is_completed":true,"node_id":"End_pmAh"},"finish_reason":"null"},"usage":{"models":[{"input_tokens":15,"output_tokens":50,"model_id":"qwen-plus-latest"}]},"request_id":"0e241c2b-..."}

id:6
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"3d46d9a4ae...","finish_reason":"stop","text":"你好呀!有什么可以帮您的吗?"},"usage":{"models":[{"input_tokens":15,"output_tokens":50,"model_id":"qwen-plus-latest"}]},"request_id":"0e241c2b-..."}

Node Execution Status

The output.thoughts[] array in the response returns execution information for each node, in execution order. The response field of each element is a JSON string containing the following fields:
FieldTypeDescription
nodeIdstringNode ID.
nodeNamestringNode name.
nodeTypestringNode type, such as Start, LLM, or Script.
nodeStatusstringNode execution status. See the table below for valid values.
nodeResultstringNode output, as a JSON string. Not returned for nodes without output, such as the Start node.
nodeExecTimestringNode execution duration, such as 1167ms. Not returned while the node is still running.
Valid values for nodeStatus:
ValueDescription
successThe node ran successfully.
failThe node failed.
skipThe node was skipped and did not run.
executingThe node is running and nodeResult is empty. In streaming mode, a node first returns executing, then returns its final status once complete.

Analysis

When a workflow application uses a deep thinking model, the model reasons through one or more steps before generating a final response. This improves the model's accuracy on complex tasks such as logical reasoning, code generation, and mathematical calculations.
A workflow application can contain multiple large model nodes, and the thinking mode must be configured for each node individually. This mode cannot be controlled dynamically via the API's enable_thinking parameter.

Thinking process

  • Set has_thoughts to true when calling the API.
  • Alternatively, reference the reasoningContent variable of the specified LLM node in the flow output node or the end node within the application in the console.
The model returns the following: reasoningContent: Returned in the reasoningContent field. Response content: In the result field. Since deep thinking increases response time, we recommend using streaming output for a better experience. The following is an example:
  • Python
  • Java
  • curl
Sample request
import json
import os
import dashscope
from dashscope import DashScopeError

try:
    client = dashscope.Client(
        # 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
        api_key=os.getenv('DASHSCOPE_API_KEY'))
    stream = client.apps.completions.create(
        app_id='APP_ID',# 替换为实际的应用 ID
        prompt='你是谁?',
        stream=True,  # 是否流式输出,True:流式输出;False(默认值): 非流式输出
        incremental_output=True,  # 是否增量输出,True:增量输出;False(默认值): 非增量输出
        has_thoughts=True,  # 是否返回思考过程,True:返回;False(默认值): 不返回
    )

except DashScopeError as e:
    print(f"API请求异常: {str(e)}")
    exit(1)

# 定义完整思考过程
reasoning_content = []
# 定义完整回复
answer_content = []
# 判断是否结束思考过程并开始回复
is_answering = False

def print_section(title):
    """打印带装饰的分段标题"""
    print(f"\n{'=' * 20} {title} {'=' * 20}\n", flush=True)

print_section("思考过程")

for chunk in stream:
    # 跳过空数据块
    if not chunk.thoughts:
        continue

    # 解析 JSON 数据
    for thought in chunk.thoughts:
        try:
            response_json = json.loads(thought.response)
            node_result = response_json.get('nodeResult', {})

            if isinstance(node_result, str):
                node_result = json.loads(node_result)

            extracted_reasoning_content = node_result.get('reasoningContent', '')
            extracted_result = node_result.get('result', '')
            node_name = response_json.get('nodeName', '')

            # 处理思考过程
            if extracted_reasoning_content and not is_answering:
                reasoning_content.append(extracted_reasoning_content)
                print(extracted_reasoning_content, end="", flush=True)

            # 处理回答内容
            if extracted_result and node_name != "结束":
                answer_content.append(extracted_result)
                if not is_answering:
                    print_section("完整回复")
                    is_answering = True
                print(extracted_result, end="", flush=True)

        except json.JSONDecodeError as e:
            print(f"JSON解析错误: {str(e)}")

# 最终结果整合
final_reasoning = "".join(reasoning_content)
final_answer = "".join(answer_content)

# 如果您需要打印完整思考过程与完整回复,请将以下代码解除注释后运行
# print_section("完整思考过程")
# print(final_reasoning)
# print_section("完整回复")
# print(final_answer)

Parameter passing

To adapt a workflow for different business scenarios, you can pass custom parameters through the biz_params field in an API call. To do this, add a custom parameter (for example, the city name city) in the Start Node, reference the city and query variables in the Prompt, and then Publish the application.
  • Python
  • Java
  • HTTP
Sample request
import os
import dashscope
from dashscope import DashScopeError

client = dashscope.Client(
    # 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
    api_key=os.getenv("DASHSCOPE_API_KEY"))
# 工作流和智能体编排应用自定义参数传递
biz_params = {"city": "杭州"}
try:
    response = client.apps.completions.create(
        app_id='APP_ID',  # 替换为实际的应用 ID
        prompt='查询这个城市的行政区域划分',
        biz_params=biz_params  # 传递业务参数
    )
    print(f'{response.text}')  # 处理只输出文本text
except DashScopeError as e:
    print(f'request_id={e.request_id}')
    print(f'code={e.code}')
    print(f'message={e.message}')
    print(f'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
Sample response
杭州市,作为浙江省的省会城市,其行政区域划分包括10个市辖区:上城区、拱墅区、西湖区、滨江区、萧山区、余杭区、临平区、钱塘区、富阳区、临安区。每个区都有其独特的特色和发展重点。

- 上城区:位于杭州市中心地带,是杭州的政治、经济、文化中心之一。
- 拱墅区:以运河文化为特色,拥有众多历史文化遗产。
- 西湖区:著名的西湖风景区就位于此区,是旅游观光的重要目的地。
- 滨江区:高新技术产业聚集地,阿里巴巴等知名企业坐落于此。
- 萧山区:东南部的一个行政区,经济发展迅速,特别是制造业方面。
- 余杭区:近年来发展快速,尤其是互联网经济领域,阿里巴巴总部也设在这里(注:阿里巴巴总部实际位于滨江区)。
- 临平区:新成立的行政区,旨在促进该地区经济社会全面发展。
- 钱塘区:同样是一个较新的行政区划调整结果,强调创新发展和生态保护相结合。
- 富阳区:位于杭州西南方向,以其丰富的自然景观和悠久的历史文化著称。
- 临安区:地处杭州西部,以生态优美闻名,并且有着深厚的文化底蕴。

请注意,随着时间推移,具体的城市规划可能会有所变化,请参考最新的官方信息。

File Q&A

You can upload files to your application and use a large model for file Q&A. You can also configure a file parsing node to enable your workflow to receive and parse various file types, such as documents, images, videos, and audio. You can then use the extracted content for analysis, summarization, or Q&A.
  1. Build a workflow that supports file Q&A
    1. Configure the Start node: In the Start node, add a custom parameter to receive the file URL. For example, name it file_url and set the type to File. For multiple files, select Array[File].
    2. (Optional) Add a parsing node: Add a file parsing node and use file_url as the input variable for this node.
    3. Configure the large model node
      • Reference parsing output variables: If you configured a parsing node, add its text output variables, such as markdownContent or ASRInfo, to a downstream node, such as the LLM Node, to process the file content.
      • Reference the custom variable: In the Prompt of the LLM Node, reference the custom variable from the Start Node.
    4. Publish the application: Check the node configuration. After your tests pass, Publish the workflow application.
    Note: The file URL you pass must be publicly accessible.
    Related documentation: Workflow application node descriptions.
  2. Call the application You can provide a file to the application in two ways:
    1. Test in the console On the application details page, go to the test pane. Under the file_url input parameter, upload a local file or paste a file URL to run a quick test.
    2. Call via API In the API request, pass the file URL in the biz_params field. The key name in biz_params must exactly match the parameter name you set in the Start node (in this example, file_url).
      • Python
      • Java
      • HTTP
      Sample request
      """
      阿里云百炼 Application SDK 调用示例(流式输出)
      """
      import os
      import dashscope
      from dashscope import DashScopeError
      
      # 若没有配置环境变量,可替换为:api_key="sk-xxx"
      # 但不建议在生产环境中硬编码 API Key
      client = dashscope.Client(api_key=os.getenv("DASHSCOPE_API_KEY"))
      try:
          stream = client.apps.completions.create(
              app_id='APP_ID',  # 替换为实际的应用 ID
              prompt='一句话总结文件内容',
              stream=True,           # 流式输出
              incremental_output=True,  # 增量输出
              biz_params={
                  # 单文件格式(控制台参数类型: File)
                  # 参数名必须与控制台定义的参数名保持一致
                  'file_url': {
                      "url": "https://dashscope.oss-cn-beijing.aliyuncs.com/audios/welcome.mp3",  # 必填
                      # "name": "welcome.mp3",  # 控制台引用了则必填
                      # "type": "audio",        # 控制台引用了则必填,可选值:image/document/audio/video/custom
                      # "source": "localFile",  # 控制台引用了则必填
                      # "mimeType": "audio"     # 控制台引用了则必填,可选值:image/png 等
                  }
                  # 多文件格式(控制台参数类型: Array<File>)
                  # 'file_url': [
                  #     {"url": "https://www.berkshirehathaway.com/letters/2024ltr.pdf", "name": "文件1.pdf"},
                  #     {"url": "https://www.berkshirehathaway.com/letters/2024ltr.pdf", "name": "文件2.pdf"}
                  # ]
              }
          )
      
          # 处理流式响应
          for response in stream:
              if response.text:
                  print(response.text, end='')
      
          print()  # 换行
      except DashScopeError as e:
          print(f'request_id={e.request_id}')
          print(f'code={e.code}')
          print(f'message={e.message}')
          print(f'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
      
      Sample response
      该文件内容仅为一句欢迎语:“欢迎你使用阿里云。”
      

Private network calls

Call applications on Alibaba Cloud Model Studio over a private network to improve data transmission security and efficiency.
  1. Add a PrivateLink connection and associate your workspace: In the Model Studio console, add a PrivateLink connection for your VPC, and then associate the target workspace with the connection.
  2. Replace the domain name: Replace the public domain name in the API request URL, dashscope.aliyuncs.com, with the private domain name that is generated after the workspace is associated. For example: https://{WorkspaceId}-{VpcId}.cn-beijing.maas.aliyuncs.com/api/v1/
  3. Make the request.
    • Python
    • Java
    • HTTP
    import os
    import dashscope
    from dashscope import DashScopeError
    # 配置私网域名:显式指定base_url
    client = dashscope.Client(
        # 若没有配置环境变量,可用阿里云百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        base_url='https://{WorkspaceId}-{VpcId}.cn-beijing.maas.aliyuncs.com/api/v1/')
    try:
        response = client.apps.completions.create(
            app_id='APP_ID',# 替换为实际的应用 ID
            prompt='你是谁?')
        print(response.text)
    except DashScopeError as e:
        print(f'request_id={e.request_id}')
        print(f'code={e.code}')
        print(f'message={e.message}')
        print(f'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
    

API reference

For a complete list of application invocation parameters, see the DashScope API reference for workflows and legacy agent applications.

Error code

If a call fails and returns an error message, see Error Messages.

Billing

Billing for a workflow application is based on the billable nodes it executes, such as large model and knowledge base nodes.
  • Billing unit: Each billable node has its own billing unit. For example, a large model node is billed based on the number of tokens.
  • Total cost: The total cost of a single workflow API call is the sum of costs for all billable nodes in its execution path.

Build and use applications

To learn about configuring workflow applications, including node descriptions and how to import and export workflows, see Workflow applications.

Use the prompt assistance tool

For information about using the Prompt supporting tool within an application, see Prompt engineering.

Convert text to speech

To convert text responses from the model into speech, see Real-time speech synthesis - CosyVoice/Sambert.

Explore advanced usage

To call applications using the Responses API, see Responses API.

FAQ

1. Why does my workflow work correctly in the console but fail or produce unexpected results when I make an API call?

This issue typically stems from version or parameter mismatches. Check the following:
  • Ensure the application is published: An API call uses the last published version of your workflow. Changes saved in the console but not published do not affect API calls. Click "Publish" to apply your changes.
  • Validate custom parameters (biz_params): The key names and data types of the biz_params in an API request must exactly match the parameters defined in the workflow's start node. For example, if the start node defines a string parameter named city, the API call must pass {"city": "some_value"}.
  • Check the input content: Verify that the prompt or messages content in your API call matches the content and format you used when testing in the console, especially for prompts with specific formatting requirements.
  1. Verify that the class and package names in your import statements are correct.
  2. Add the dependency: If you use Maven or Gradle for project management, add the latest DashScope Java SDK dependency to your pom.xml or build.gradle file. You can find the latest version number on Maven.
<!-- https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>dashscope-sdk-java</artifactId>
    <version>在此处填写最新版本号,例如2.16.4</version>
</dependency>
// https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java
implementation group: 'com.alibaba', name: 'dashscope-sdk-java', version: '在此处填写最新版本号,例如2.16.4'
  1. Upgrade the SDK: Older SDK versions may not include the features or classes you need. If you have already added the DashScope Java SDK dependency, confirm that you are using the latest version. If not, upgrade it by updating the version number in your pom.xml or build.gradle file.
<!-- https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>dashscope-sdk-java</artifactId>
    <version>请将此处的版本号修改为最新版本</version>
</dependency>
// https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java
implementation group: 'com.alibaba', name: 'dashscope-sdk-java', version: '请将此处的版本号修改为最新版本'
  1. Reload your project to apply the changes.
  2. Rerun the code sample.