# API Integration

Calling the API requires the following processes:

# 1. Preparation

The workflow agent must be published as an API before it can be called via the API. The specific publishing process is as follows:

# 1.1 Publish Workflow as API

After completing the development and debugging of the workflow, click the publish button in the upper right corner of the workflow canvas page to publish it.

In the pop-up page, click the "Configure" button on the right side of the "Publish as API" column to jump to the configuration page for publishing as an API.

# 1.2 Real-Name Authentication

Real-name authentication is required before publishing a workflow as an API. If you have not completed real-name authentication before, you can find the "Go to Authenticate" button in the "Complete Real-Name Authentication" column on the page and click it to jump to the user authentication center page, where developers can complete real-name authentication as prompted. If you have successfully completed real-name authentication before, you can skip this step.

# 1.3 Create Application

If you have not created an application before, or expect to bind this workflow to a new application, you need to create a new application through this step. If you have created an application and want to bind this workflow to an existing application, you can skip this step.

Step 1: When you want to create a new application, find the "Create Now" button in the "Bind Application" column and click it to jump to the application creation page.

Step 2: Fill in the relevant information of the application on the creation page and click the "Submit" button to complete the creation.

# 1.4 Bind Application

Return to the API publishing configuration page, find the "Service Interface Authentication Information" tab, and complete the binding of the workflow and the application in this tab. The specific steps are as follows:

Step 1: Click the drop-down box of "Select the application you want to bind", and all application names under the current account will be displayed. Select the application you need to bind from them.

Notes:

  • If the newly created application name is not found in the drop-down box, refresh the configuration page.
  • Once the application is bound, it cannot be modified. Please choose carefully.

Step 2: After selecting the application, click the "Bind Now" button to complete the application binding. At this time, the interface information required for calling the API, including APIKey, API Secret, and API Flowid, will be displayed.

Note: If there are new changes to your workflow, please click the "Update Binding" button to republish it as an API before calling the API, so that the new changes will take effect in the API call.

# 1.5 Obtain Authorization for Large Models

Before using the API interface for calls, ensure that the bound APPID has authorization for the large models used in your workflow. Developers can claim some free quotas for experience in the Spark API section of the Spark official website (opens new window).

After publishing the workflow and obtaining the relevant large model authorization, you can call the agent API.

# 2. Workflow API Integration

# 2.1 Basic Information

# 2.1.1 Interface Description

Request Method POST
Request URL https://agent-sg-ali.xf-yun.com/workflow/v1/chat/completions (opens new window)

# 2.1.2 Interface Demo

Demo Type Download Address
Java Demo https://astron-oss-s.oss-ap-southeast-1.aliyuncs.com/code/WorkflowRequest.java.zip (opens new window)
Python Demo https://astron-oss-s.oss-ap-southeast-1.aliyuncs.com/code/workflow_openapi_demo_python.py.zip (opens new window)

# 2.1.3 Interface Requirements

Interface Type: Streaming HTTP(S)

Interface Authentication: Click here to view the document (opens new window)

# 2.1.4 Interface Permission Description

If authentication fails or the APPID does not match the current workflow, relevant flow control errors will be returned.

# 2.2 Initiate Session Request

# 2.2.1 Request Protocol Example

{
    "flow_id": "7265177322515169282",
    "uid": "123",
    "parameters": {
        "AGENT_USER_INPUT": "Hello"
    },
    "ext": {
        "bot_id": "workflow",
        "caller": "workflow"
    },
    "stream": true,
    "chat_id": "xxx",
    "history": [
      {
        "role": "user",
        "content_type": "text",
        "content": "Hello"
      },
      {
        "role": "assistant",
        "content_type": "text",
        "content": "Hello, I am your workflow assistant. How can I help you?"
      }
    ]
}

# 2.2.2 Request Parameters

2.2.2.1 Header

Parameter Name Parameter Value Required Description
Authorization Bearer $API_KEY Yes Authentication key. Composition of authentication code: Bearer {API_KEY}:{API_SECRET}

2.2.2.2 Body

Parameter Name Parameter Type Required Description
flow_id string Yes Workflow ID
uid string No User ID
stream bool Yes Whether to enable streaming return. Streaming: true; Non-streaming: false
ext object No Used to specify some additional fields, such as some hidden plugin fields (not used for now)
parameters object Yes Input parameters and their values of the workflow start node. You can view the parameter list on the orchestration page of the specified workflow. {"input1": "xxxxx", "input2": "xxxxx"}
chat_id string No Session ID, used to distinguish different workflow sessions, with a maximum length of 32 characters
history array of history_message object No Collection of historical conversation information [history_message object]. For example: [{"role": "user", "content_type": "text", "content": "Hello" },{"role": "assistant", "content_type": "text", "content": "Hello, I am your workflow assistant. How can I help you?" }]

2.2.2.3 history_message Object

Parameter Name Parameter Type Required Value Range Default Value Description
role string Yes user, assistant The entity that sent this message. user: indicates the message is sent by the user. assistant: indicates the message is a reply from the workflow.
content_type string No text, image text The type of message content, currently only two types are supported. If not filled in, the default type is text. text: indicates plain text. image: indicates image type.
content string Yes Message content. If it is an image type, the image URL needs to be filled in here

When processing the history_message object, the role of the first element must be user. The interaction history should be spliced in the order of user -> assistant -> user -> assistant. By default, a pair of interactions between user and assistant is regarded as one round of conversation. Fill in in the order of conversation time from first to last. For example: [{first time},{second time}...]

[
  // Splice conversation history information:
  {"role": "user", "content_type" : "text", "content": "What are the famous foods in Hunan?"},              // User's first question. role is user, indicating it is the user's question
  {"role": "assistant", "content_type" : "text", "content": "Hunan has xxxxxxx"},        // AI's first reply. role is assistant, indicating it is the AI's reply
]

# 2.3 Response

# 2.3.1 Response Protocol Example

2.3.1.1 Streaming Result Example

Streaming Output Process Frame

{
  "code": 0,
  "message": "Success",
  "id": "cha000c0076@dx191c21ce879b8f3532",
  "created": 123412324431,
  "workflow_step": {
    "seq": 0,
    "progress": 0.4
  },
  "choices": [
    {
      "delta": {
        "role": "assistant",
        "content": "Hello,",
        "reasoning_content": ""
      },
      "index": 0,
      "finish_reason": null
    }
  ]
}

Streaming Output End Frame

{
  "code": 0,
  "message": "Success",
  "id": "spf0016609f@dx193193f43cba44d782",
  "created": 123412324431,
  "workflow_step": {
    "seq": 6,
    "progress": 1
  },
  "choices": [
    {
      "delta": {
        "role": "assistant",
        "content": "",
        "reasoning_content": ""
      },
      "index": 0,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 1,
    "completion_tokens": 0,
    "total_tokens": 9
  }
}

2.3.1.2 Non-Streaming Result Example

{
  "code": 0,
  "message": "Success",
  "id": "cha000b0003@dx1905cd86d6bb86d552",
  "choices": [
    {
      "delta": {
        "role": "assistant",
        "content": "Hello, I am the Spark Cognitive Intelligence Model built by iFLYTEK.\nIf you have any questions or need help, please feel free to tell me! I will do my best to provide you with answers and support. How can I help you?",
        "reasoning_content": ""
      },
      "index": 0,
      "finish_reason": "stop",
      "finish_reason": ""
    }
  ],
  "usage": {
    "prompt_tokens": 6,
    "completion_tokens": 42,
    "total_tokens": 48
  }
}

2.3.1.3 Interrupt Event

When there is a Q&A node in the workflow, the workflow will be interrupted.

Q&A Node Interrupt Frame (Direct Answer)

{
  "code": 0,
  "message": "Success",
  "id": "cha000c0076@dx191c21ce879b8f3532",
  "created": 123412324431,
  "workflow_step": {
    "seq": 0,
    "progress": 0.4
  },
  "choices": [
    {
      "delta": {
        "role": "assistant",
        "content": "Hello,",
        "reasoning_content": ""
      },
      "index": 0,
      "finish_reason": "interrupt"
    }
  ],
  "event_data": {
        "event_id": "7336690112690499584",
        "event_type": "interrupt",
        "need_reply": true,
        "value": {
            "type": "direct",
            "content": "Which of the following packages do you want to purchase?"
        }
    }
}

Q&A Node Interrupt Frame (Option Answer)

{
  "code": 0,
  "message": "Success",
  "id": "cha000c0076@dx191c21ce879b8f3532",
  "created": 123412324431,
  "workflow_step": {
    "seq": 0,
    "progress": 0.4
  },
  "choices": [
    {
      "delta": {
        "role": "assistant",
        "content": "Hello,",
        "reasoning_content": ""
      },
      "index": 0,
      "finish_reason": null
    }
  ],
  "event_data": {
        "event_id": "7336690112690499584",
        "event_type": "interrupt",
        "need_reply": false,
        "value": {
            "type": "option",
            "content": "Please select your package",
            "option": [
                {
                    "id": "A",
                    "text": "Annual Package"
                },
                {
                    "id": "B",
                    "text": "Monthly Package"
                }
            ]
        }
    }
}

2.3.1.4 Exception Result

{
    "code": 20805,
    "message": "flow id : 7265177322515169282 is in draft status, please publish",
    "id": "spf00dc0001@hf193621572a96806782",
    "created": 1732517393,
    "choices": [
        {
            "delta": {
                "role": "assistant",
                "content": "",
                        "reasoning_content": ""
            },
            "finish_reason": "stop"
        }
    ],
    "workflow_step": {
        "seq": 0,
        "progress": 1.0
    },
    "usage": {
        "prompt_tokens": 0,
        "completion_tokens": 0,
        "total_tokens": 0
    }
}

# 2.3.2 Response Parameters

2.3.2.1 Response Data Parameters

Parameter Name Type Required Parameter Description
code int Yes Error code, 0 for success, non-0 indicates an error
message string Yes Error message description
id string Yes Server session ID
created int Yes Conversation creation timestamp, unit: seconds
workflow_step object Yes Workflow step
workflow_step.seq int Yes Sequence number of the returned data, value range [0,9999999]
workflow_step.progress float Yes Workflow progress
choices array Yes
choices.delta object Yes
choices.delta.role string Yes Role of the workflow
choices.delta.content string Yes Content output by the workflow
choices.delta.reasoning_content string Yes Reasoning chain content of the workflow
choices.index int Yes Result sequence number of the workflow, used in multiple candidates
choices.finish_reason string Yes Indicates the reason for the termination of workflow generation, which is an enumeration value.
- stop: Normal end. The workflow is executed and terminated normally. For specific results or error reasons, refer to the code field.
- interrupt: Execution interrupted. The workflow is interrupted at an intermediate node, and subsequent processing is required according to the event_data event data.
- ping: Heartbeat signal. A signal sent by the workflow to maintain the connection when executing long tasks, which does not mean the execution is over.
usage object No Token metering, only provided in the workflow end frame
usage.prompt_tokens int Yes Tokens requested by the workflow from the large model
usage.completion_tokens int Yes Replies from the large model in the workflow
usage.total_tokens int Yes Total token consumption of the workflow
event_data object No Event data
event_data.event_id str Yes Event ID, used as a marker for the resume interface to resume the event
event_data.event_type str Yes Event type, "interrupt" when interrupted
event_data.need_reply bool Yes Whether the Q&A node requires a reply
event_data.value object Yes Details of interrupted data
event_data.value.type str Yes Question type, enumeration values: - direct: Direct answer - option: Option answer
event_data.value.content str Yes User's question content
event_data.value.option array No Option content for option answers

2.3.2.2 Supplementary Instructions on Result Format

In addition to plain text type, the model results will include the following markup languages to meet typesetting requirements, and it is recommended that integrators adapt to them:

  • markdown (tables, lists, etc.)

# 2.4 Resume Workflow Execution

When your workflow executes to a Q&A node, the workflow will be temporarily interrupted and return the corresponding event ID and the question set in the workflow. At this time, developers should call this interface to upload the user's reply, event ID and other information to resume the execution of the workflow.

# 2.4.1 Basic Information

2.4.1.1 Interface Description

Request Method POST
Request URL https://agent-sg-ali.xf-yun.com/workflow/v1/resume (opens new window)

2.4.1.2 Interface Demo

Demo Type Download Address
Python Demo https://astron-oss-s.oss-ap-southeast-1.aliyuncs.com/code/workflow_open_api_resume.py.zip (opens new window)

2.4.1.3 Interface Requirements

Interface Type: Streaming HTTP(S)

# 2.4.2 Request

2.4.2.1 Request Protocol Example

{
    "event_id": "123456789012345",
    "event_type": "resume",
    "content": "My name is:xxxx, Age:xxxx"
}

2.4.2.2 Request Parameters

  1. Header
Parameter Name Parameter Value Required Description
Authorization Bearer $API_KEY Yes Authentication key. Composition of authentication code: Bearer {API_KEY}:{API_SECRET}
  1. Body
Parameter Name Parameter Type Required Description
event_id string Yes Event ID. Returned by the chat and resume interfaces when an interrupt event occurs, used to identify multiple events generated by one request in the same workflow, with the same value.
event_type string No Used to process events, default to resume. resume: Resume; ignore: Ignore; abort: End
content string Yes Answer content. For option answers, only pass option information A-Z

# 2.4.3 Response

2.4.3.1 Response Protocol Example

  1. Streaming Result Example

Streaming Output Process Frame

{
  "code": 0,
  "message": "Success",
  "id": "cha000c0076@dx191c21ce879b8f3532",
  "created": 123412324431,
  "workflow_step": {
    "seq": 0,
    "progress": 0.4
  },
  "choices": [
    {
      "delta": {
        "role": "assistant",
        "content": "Hello,",
        "reasoning_content": ""
      },
      "index": 0,
      "finish_reason": null
    }
  ]
}

Streaming Output End Frame

{
  "code": 0,
  "message": "Success",
  "id": "spf0016609f@dx193193f43cba44d782",
  "created": 123412324431,
  "workflow_step": {
    "seq": 6,
    "progress": 1
  },
  "choices": [
    {
      "delta": {
        "role": "assistant",
        "content": "",
        "reasoning_content": ""
      },
      "index": 0,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 1,
    "completion_tokens": 0,
    "total_tokens": 9
  }
}
  1. Non-Streaming Result Example
{
  "code": 0,
  "message": "Success",
  "id": "cha000b0003@dx1905cd86d6bb86d552",
  "choices": [
    {
      "delta": {
        "role": "assistant",
        "content": "Hello, I am the Spark Cognitive Intelligence Model built by iFLYTEK.\nIf you have any questions or need help, please feel free to tell me! I will do my best to provide you with answers and support. How can I help you?",
        "reasoning_content": ""
      },
      "index": 0,
      "finish_reason": "stop",
      "finish_reason": ""
    }
  ],
  "usage": {
    "prompt_tokens": 6,
    "completion_tokens": 42,
    "total_tokens": 48
  }
}
  1. Interrupt Event

When there is a Q&A node in the workflow, the workflow will be interrupted.

Q&A Node Interrupt Frame (Direct Answer)

{
  "code": 0,
  "message": "Success",
  "id": "cha000c0076@dx191c21ce879b8f3532",
  "created": 123412324431,
  "workflow_step": {
    "seq": 0,
    "progress": 0.4
  },
  "choices": [
    {
      "delta": {
        "role": "assistant",
        "content": "Hello,",
        "reasoning_content": ""
      },
      "index": 0,
      "finish_reason": null
    }
  ],
  "event_data": {
        "event_id": "7336690112690499584",
        "event_type": "interrupt",
        "need_reply": true,
        "value": {
            "type": "direct",
            "content": "Which of the following packages do you want to purchase?"
        }
    }
}

Q&A Node Interrupt Frame (Option Answer)

{
  "code": 0,
  "message": "Success",
  "id": "cha000c0076@dx191c21ce879b8f3532",
  "created": 123412324431,
  "workflow_step": {
    "seq": 0,
    "progress": 0.4
  },
  "choices": [
    {
      "delta": {
        "role": "assistant",
        "content": "Hello,",
        "reasoning_content": ""
      },
      "index": 0,
      "finish_reason": null
    }
  ],
  "event_data": {
        "event_id": "7336690112690499584",
        "event_type": "interrupt",
        "need_reply": false,
        "value": {
            "type": "option",
            "content": "Please select your package",
            "option": [
                {
                    "id": "A",
                    "text": "Annual Package"
                },
                {
                    "id": "B",
                    "text": "Monthly Package"
                }
            ]
        }
    }
}
  1. Exception Result
{
    "code": 20805,
    "message": "flow id : 7265177322515169282 is in draft status, please publish",
    "id": "spf00dc0001@hf193621572a96806782",
    "created": 1732517393,
    "choices": [
        {
            "delta": {
                "role": "assistant",
                "content": "",
                        "reasoning_content": ""
            },
            "finish_reason": "stop"
        }
    ],
    "workflow_step": {
        "seq": 0,
        "progress": 1.0
    },
    "usage": {
        "prompt_tokens": 0,
        "completion_tokens": 0,
        "total_tokens": 0
    }
}

2.4.3.2 Response Parameter Description

  1. Response Data Parameters
Parameter Name Type Required Parameter Description
code int Yes Error code, 0 for success, non-0 indicates an error
message string Yes Error message description
id string Yes Server session ID
created int Yes Conversation creation timestamp, unit: seconds
workflow_step object Yes Workflow step
workflow_step.seq int Yes Sequence number of the returned data, value range [0,9999999]
workflow_step.progress float Yes Workflow progress
choices array Yes
choices.delta object Yes
choices.delta.role string Yes Role of the workflow
choices.delta.content string Yes Content output by the workflow
choices.delta.reasoning_content string Yes Reasoning chain content of the workflow
choices.index int Yes Result sequence number of the workflow, used in multiple candidates
choices.finish_reason string Yes When the workflow reaches a natural stopping point or a stop sequence provided by the user, it will set finish_reason to "stop"
usage object No Token metering, only provided in the workflow end frame
usage.prompt_tokens int Yes Tokens requested by the workflow from the large model
usage.completion_tokens int Yes Replies from the large model in the workflow
usage.total_tokens int Yes Total token consumption of the workflow
event_data object No Event data
event_data.event_id str Yes Event ID, used as a marker for the resume interface to resume the event
event_data.event_type str Yes Event type, "interrupt" when interrupted
event_data.need_reply bool Yes Whether the Q&A node requires a reply
event_data.value object Yes Details of interrupted data
event_data.value.type str Yes Question type, enumeration values: - direct: Direct answer - option: Option answer
event_data.value.content str Yes User's question content
event_data.value.option array No Option content for option answers
  1. Supplementary Instructions on Result Format

In addition to plain text type, the model results will include the following markup languages to meet typesetting requirements, and it is recommended that integrators adapt to them:

  • markdown (tables, lists, etc.)

# 2.5 File Upload

# 2.5.1 Basic Information

2.5.1.1 Interface Description

Request Method POST
Request URL https://agent-sg-ali.xf-yun.com/workflow/v1/upload_file (opens new window)

2.5.1.2 Interface Demo

curl -X POST 'https://agent-sg-ali.xf-yun.com/workflow/v1/upload_file' \
--header 'Authorization: Bearer {api_key}' \
--form 'file=@localfile;type=image/[png|jpeg|jpg|webp|gif]

2.5.1.3 Interface Requirements

Interface Type: Streaming HTTP(S)

Interface Authentication: Bearer Authentication

# 2.5.2 Request Parameters

2.5.2.1 Header

Parameter Name Type Required Parameter Description
Authorization string Yes Authentication key. Composition of authentication code: Bearer {API_KEY}:{API_SECRET}
Content-Type string Yes multipart/form-data

2.5.2.2 Body

Parameter Name Type Required Parameter Description
file file Yes File to be uploaded

# 2.5.3 Response

2.5.3.1 Response Protocol Example

{
  "code": 0,
  "message": "success",
  "sid": "spf001b23c7@dx1939b17d9e3a4f3700",
  "data": {
      "url": "xxxxxxxxxx"
  }
}

2.5.3.2 Response Parameter Description

Parameter Name Type Parameter Description
code integer Error code
message string Error description
sid string Session ID
data object Error code
data.url string Access external link of the file

# 3. Error Code List

# 3.1 Workflow Errors

Error Code Description
20201 Corresponding Flow ID not found
20202 Invalid Flow ID
20204 Workflow not published
20207 Workflow is in draft status

# 3.2 Model Errors

Error Code Description
20303 Model request failed
20350 Error occurred while upgrading to WebSocket
20351 Error reading user's message via WebSocket
20352 Error sending message to user via WebSocket
20353 Incorrect format of user's message
20354 Schema error of user data
20355 Incorrect value of user parameters
20356 User concurrency error: The current user is already connected, and the same user cannot connect from multiple places at the same time.
20357 User traffic limited: The service is processing the user's current question, and a new request can only be sent after the processing is completed. (You must wait for the large model to reply completely before sending the next question)
20358 Insufficient service capacity, contact staff
20359 Failed to establish connection with the engine
20360 Error receiving data from the engine
20361 Error sending data to the engine
20362 Internal engine error
20363 Input content failed review, suspected of violating regulations, please adjust the input content again
20364 Output content involves sensitive information, failed review, and subsequent results cannot be displayed to users
20365 appid is in the blacklist
20366 appid authorization error. For example: this function is not activated, the corresponding version is not activated, insufficient tokens, concurrency exceeds authorization, etc.
20367 Failed to clear history
20368 Indicates that the content of this session has a tendency to involve violating information; it is recommended that developers give users a prompt that the input involves violations after receiving this error code
20369 Service is busy, please try again later
20370 Abnormal parameters for requesting the engine, engine schema check failed
20371 Engine network exception
20372 Token quantity exceeds the upper limit. The total number of words in the conversation history + question is too large, and the input needs to be simplified
20373 Authorization error: the appId has no authorization for the relevant function or the business volume exceeds the limit
20374 Authorization error: daily flow control exceeded. Exceeded the limit of the maximum daily access volume
20375 Authorization error: second-level flow control exceeded. Second-level concurrency exceeds the authorized number of channels
20376 Authorization error: concurrency flow control exceeded. The number of concurrent channels exceeds the authorized number of channels
20380 External large model request failed

# 3.3 API Authorization

Error Code Description
20900 Authentication failed: authorization restriction, service unauthorized or authorization expired
20901 Metering authentication failed: service exceeded limit, total business sessions exceeded limit or daily flow control exceeded
20902 Authentication failed: service exceeded limit, QPS second-level flow control exceeded
20903 Concurrency authentication failed: service exceeded limit, number of concurrent channels exceeded

# 3.4 Text-to-Image

Error Code Description
21200 Image generation failed
21201 Image storage failed
21203 Incorrect format of user's message
21204 Schema error of user data
21205 Incorrect value of user parameters
21206 Insufficient service capacity
21207 Input failed review
21208 Images generated by the model involve sensitive information, failed review
21209 Text-to-image timeout

# 3.5 Tool Errors

Error Code Description
21800 Tool request failed
21801 Tool initialization failed
21802 Tool JSON protocol parsing failed
21803 Tool protocol verification failed
21804 Tool OpenAPI protocol parsing failed
21805 Unsupported tool body type
21806 Tool server does not exist
21807 Official tool request failed
21808 Tool does not exist
21809 Tool Operation does not exist
21810 Tool request failed, connection exception
21811 Third-party tool execution failed
21812 Third-party tool request failed

# 3.6 Node Execution Errors

Error Code Description
20500 Knowledge base request exception
20501 Knowledge base node execution exception
20502 Knowledge base parameter exception
22500 Incorrect start node protocol
22600 Incorrect end node protocol
22601 End node execution failed
22701 Message node execution failed
21900 Parameter extraction failed
21600 Code execution failed
21601 Code interpreter node construction failed
21602 The type of result returned by the code node does not meet the requirements
21603 Code execution timeout
22801 Workflow node execution failed
22802 Incorrect format of the execution response result of the workflow node
22900 Variable node execution failed
23100 Branch node execution failed
23200 Iteration node execution failed
23300 Large model node execution failed
23400 Tool node execution failed
23500 Text splicing node execution failed
23700 Agent node execution failed
23800 Q&A node execution failed

# 3.7 Session

Error Code Description
20804 OpenAPI output timeout
23900 The conversation has timed out or does not exist