Workflow API

更新时间:
复制 MD 格式

Authentication

Field

Parameter passing

Type

Required

Description

Example value

Authorization

header

String

Yes

API-Key

Bearer d1**2a

Routing configuration

Note: The software development kit (SDK) encapsulates routing. If you use the SDK to call the API, you do not need to configure API routing.

Field

Parameter passing

Type

Required

Description

Example value

x-fag-appcode

header

String

Yes

Specifies the application. The value is fixed to aca.

aca

x-fag-servicename

header

String

Yes

The request routing identity. The value varies for different APIs. See the mapping between servicename and APIs.

aca-flow-chat-send-sse

Mapping between x-fag-servicename and APIs

API name

PATH

Value of x-fag-servicename

Workflow chat (streaming)

/v2/api/chat/send

aca-flow-chat-send-sse

Workflow chat (non-streaming)

/v2/api/chat/send

aca-flow-chat-send

Workflow chat

Note

Currently, you can use only service assistant roles created on the Stardust platform for chats.

API

POST /v2/api/chat/send

Request parameters

Request header parameters

Field

Parameter passing

Type

Required

Description

X-AcA-SSE

header

String

No

Specifies whether to enable streaming chat. Set the value to enable to enable streaming chat. Set the value to disable to disable streaming chat.

x-fag-appcode

header

String

Yes

The application identity. The value is fixed as aca.

x-fag-servicename

header

String

Yes

The request routing identity. The value varies for different APIs. See the mapping between x-fag-servicename and APIs in the Routing configuration section above.

Request body parameters

Parameter

Type

Required

Description

messages

array

Yes

The chat history, in chronological order. You can configure the maximum number of chat rounds for platform roles. Each element in the list is in the format of {"role": role, "content": content}. The valid values for `role` are `system`, `user`, and `assistant`. The `role` can be set to `system` only in `messages[0]`. The `user` and `assistant` roles must alternate. The last message must be a user's question.

botProfile

object

Yes

The role settings.

botProfile.characterId

string

Yes

This parameter is required for platform roles.

userProfile

object

Yes

The user settings.

userProfile.userId

string

Yes

The unique ID of the user in your business system. A user cannot have parallel chats. A new chat can be started only after the response to the previous chat is complete.

context

object

Yes

The chat context settings.

context.useChatHistory

boolean

Yes

Using Platform History

context.startParams

object

Yes

The input parameter variables for the start node.

Response parameters

Streaming call response

Parameter

Type

Description

requestId

string

The ID that the system generates to identify the call.

success

boolean

Indicates whether the request was successful.

errorCode

int

The error code.

errorName

string

The error name.

httpStatusCode

int

The HTTP status code.

errorMessage

string

The error message.

flowUsage

list

flowUsage[i].modelName

string

The model name.

flowUsage[i].inputTokens

int

The number of tokens in the input content of the request.

flowUsage[i].outputTokens

int

The number of tokens in the model-generated reply.

choices

array

The message body.

choices[i].messages

array

choices[i].messages[i].finishReason

string

The completion identifier is `stop` if the task is complete, or `"null"` if it is incomplete.

choices[i].messages[i].role

string

The role of the model. The value is fixed as `assistant`.

choices[i].messages[i].roleId

string

The role ID.

choices[i].messages[i].content

string

The message output generated by the model.

choices[i].messages[i].name

string

The role name.

Non-streaming call response

Parameter

Type

Description

requestId

string

The ID that the system generates to identify the call.

success

boolean

Was the return successful?

errorCode

int

The error code.

errorName

string

The error name.

httpStatusCode

int

The HTTP status code.

errorMessage

string

The error message.

data

object

data.flowUsage

list

data.flowUsage[i].modelName

string

The model name.

data.flowUsage[i].inputTokens

int

The number of tokens in the input content of the request.

data.flowUsage[i].outputTokens

int

The number of tokens in the model-generated reply.

data.choices

array

The message body.

data.choices[i].messages

array

data.choices[i].messages[i].finishReason

string

The completion identifier is "stop" if the process is complete, and "null" otherwise.

data.choices[i].messages[i].role

string

The role of the model. The value is fixed as `assistant`.

data.choices[i].messages[i].roleId

string

The role ID.

data.choices[i].messages[i].content

string

The message output generated by the model.

data.choices[i].messages[i].name

string

The role name.

Examples

Workflow chat call example

Call example

curl --location "https://nlp.aliyuncs.com/v2/api/chat/send" \
  -H "Authorization: Bearer {YOUR_API_KEY}" \
  -H "X-AcA-DataInspection: enable" \
  -H "X-AcA-SSE: enable" \
  -H "x-fag-servicename: aca-flow-chat-send-sse" \
  -H "x-fag-appcode: aca" \
  -H "Content-Type: application/json" \
  -d '{
    "messages": [
      {
        "role": "user",
        "content": "(Decides internally) This is the last time I will say this to you."
      },
      {
        "role": "assistant",
        "content": "(Looks up in surprise) Oh? What is it?"
      },
      {
        "role": "user",
        "content": "I want to exercise today. Tell me the benefits of exercising."
      }
    ],
    "botProfile": {
      "characterId": "aa7b98327d564d49a997ec67bfdaf68e"
    },
    "userProfile": {
      "userId": "123456",
      "basicInfo": "df"
    },
    "scenario": {
      "description": ""
    },
    "context": {
      "useChatHistory": true
    }
  }'
/**
 * API name: Workflow chat
 * Environment requirement: Java 17 or later
 */
public class Example {
    private static final String URL = "https://nlp.aliyuncs.com/v2/api/chat/send";
    private static final String API_KEY = "Bearer {YOUR_API_KEY}";

    public static void main(String[] args) throws Exception {
        // Non-streaming call
        nonStreamingCall();

        // Streaming call
//        streamingCall();
    }

    private static void nonStreamingCall() throws Exception {
        System.out.println("=== Non-streaming call example ===");
        // Set characterId to the service assistant ID, not the role ID.
        String jsonBody = """
        {
         "messages": [
             {
                 "role": "user",
                 "content": "(Decides internally) This is the last time I will say this to you."
             },
             {
                 "role": "assistant",
                 "content": "(Looks up in surprise) Oh? What is it?"
             },
             {
                 "role": "user",
                 "content": "I want to exercise today. Tell me the benefits of exercising."
             }
         ],
         "botProfile": {
             "characterId": "aa7b98327d564d49a997ec67bfdaf68e"
         },
         "userProfile": {
             "userId": "123456",
             "basicInfo": "df"
             },
         "scenario": {
              "description": ""
          },
          "context": {
              "useChatHistory": true
          }
        }
        """;

        HttpClient client = HttpClient.newHttpClient();

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(URL))
                .headers(
                        "Authorization", API_KEY,
                        "X-AcA-DataInspection", "enable",
                        // Fixed servicename
                        "x-fag-servicename", "aca-flow-chat-send",
                        "x-fag-appcode", "aca",
                        "Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonBody))
                .build();

        // Synchronous call
        HttpResponse<String> response = client.send(
                request,
                HttpResponse.BodyHandlers.ofString()
        );

        String responseBody = response.body();
        System.out.println("Response data: " + responseBody);
    }

    private static void streamingCall() {
        System.out.println("=== Streaming call example ===");
        // Set characterId to the service assistant ID, not the role ID.
        String jsonBody = """
        {
         "messages": [
             {
                 "role": "user",
                 "content": "(Decides internally) This is the last time I will say this to you."
             },
             {
                 "role": "assistant",
                 "content": "(Looks up in surprise) Oh? What is it?"
             },
             {
                 "role": "user",
                 "content": "I want to exercise today. Tell me the benefits of exercising."
             }
         ],
         "botProfile": {
             "characterId": "aa7b98327d564d49a997ec67bfdaf68e"
         },
         "userProfile": {
             "userId": "123456",
             "basicInfo": "df"
             },
         "scenario": {
              "description": ""
          },
          "context": {
              "useChatHistory": true
          }
        }
        """;

        HttpClient client = HttpClient.newHttpClient();

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(URL))
                .headers(
                        "Authorization", API_KEY,
                        "X-AcA-DataInspection", "enable",
                        "X-AcA-SSE", "enable",
                        // Fixed servicename
                        "x-fag-servicename", "aca-flow-chat-send-sse",
                        "x-fag-appcode", "aca",
                        "Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonBody))
                .build();

        // Asynchronously process the SSE stream
        CompletableFuture<Void> future = client.sendAsync(request, HttpResponse.BodyHandlers.ofLines())
                .thenApply(HttpResponse::body)
                .thenAccept(stream -> {
                    stream.forEach(line -> {
                        System.out.println("Streaming response data: " + line);
                    });
                });

        // Keep the main thread waiting
        future.join();
    }
}
import requests

URL = "https://nlp.aliyuncs.com/v2/api/chat/send"

# API name: Workflow chat
# Environment requirement: Python 3.10 or later
def call(messages, api_key, model_name):
    headers = {
        "Content-Type": "application/json",
        "x-fag-servicename": "aca-flow-chat-send",
        # Enable this configuration for streaming calls
        # "x-fag-servicename": "aca-flow-chat-send-sse",
        "x-fag-appcode": "aca",
        "Authorization": f"Bearer {api_key}",
        "X-AcA-DataInspection": "enable"
    }

    payload = {
        "messages": messages,
        "model": model_name,
        # Set characterId to the service assistant ID, not the role ID.
        "botProfile": {
            "characterId": "aa7b98327d564d49a997ec67bfdaf68e"
        },
        "userProfile": {
            "userId": "123456",
            "basicInfo": "df"
        },
        "scenario": {
            "description": ""
        },
        "context": {
            "useChatHistory": True
        }
    }

    response = requests.post(URL, json=payload, headers=headers)
    # Print the raw response content line by line
    for line in response.iter_lines():
        if line:
            print(line.decode('utf-8'))
    # Check the response status and throw an exception if an error occurs
    response.raise_for_status()
    return response


if __name__ == "__main__":
    messages = [
        {
            "role": "user",
            "content": "(Decides internally) This is the last time I will say this to you."
        },
        {
            "role": "assistant",
            "content": "(Looks up in surprise) Oh? What is it?"
        },
        {
            "role": "user",
            "content": "I want to exercise today. Tell me the benefits of exercising."
        }
    ]
    api_key = "YOUR_API_KEY"
    model_name = "xingchen-plus-latest"
    try:
        response = call(messages, api_key, model_name)
    except requests.HTTPError as e:
        print(f"Request error: {e}")
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
)

// API name: Workflow chat
// Environment requirement: Go 1.20 or later

const URL = "https://nlp.aliyuncs.com/v2/api/chat/send"

func call(messages []map[string]interface{}, apiKey string, modelName string) (*http.Response, error) {
    payload := map[string]interface{}{
        "messages": messages,
        "model":    modelName,
        "botProfile": map[string]interface{}{
            "characterId": "aa7b98327d564d49a997ec67bfdaf68e", // Set characterId to the service assistant ID, not the role ID.
        },
        "userProfile": map[string]interface{}{
            "userId":    "123456",
            "basicInfo": "df",
        },
        "scenario": map[string]interface{}{
            "description": "",
        },
        "context": map[string]interface{}{
            "useChatHistory": true,
        },
    }

    payloadBytes, err := json.Marshal(payload)
    if err != nil {
        return nil, err
    }

    req, err := http.NewRequest("POST", URL, bytes.NewBuffer(payloadBytes))
    if err != nil {
        return nil, err
    }

    req.Header.Set("Content-Type", "application/json")
    // req.Header.Set("x-fag-servicename", "aca-flow-chat-send-sse") // Enable this configuration for streaming calls
    req.Header.Set("x-fag-servicename", "aca-flow-chat-send")
    req.Header.Set("x-fag-appcode", "aca")
    req.Header.Set("Authorization", "Bearer "+apiKey)
    req.Header.Set("X-AcA-DataInspection", "enable")
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        return nil, err
    }

    // Print the raw response content line by line
    defer resp.Body.Close()
    body, _ := io.ReadAll(resp.Body)
    fmt.Println(string(body))

    if resp.StatusCode != http.StatusOK {
        return nil, fmt.Errorf("Request error, status code: %d", resp.StatusCode)
    }

    return resp, nil
}

func main() {
    messages := []map[string]interface{}{
        {
            "role":    "user",
            "content": "(Decides internally) This is the last time I will say this to you.",
        },
        {
            "role":    "assistant",
            "content": "(Looks up in surprise) Oh? What is it?",
        },
        {
            "role":    "user",
            "content": "I want to exercise today. Tell me the benefits of exercising.",
        },
    }

    apiKey := "YOUR_API_KEY"
    modelName := "xingchen-plus-latest"

    _, err := call(messages, apiKey, modelName)
    if err != nil {
        fmt.Printf("Request error: %v\n", err)
    }
}

Response example

{
    "requestId": "52379bd8-c3aa-448f-ae30-4f77605f9b34",
    "code": 200,
    "data": {
        "requestId": "52379bd8-c3aa-448f-ae30-4f77605f9b34",
        "context": {
            "chatRoomId": 72461773,
            "sessionId": "ed6d144a47ed47be91bc825424360a5b",
            "chatId": "b3dd055fcfbc430698a899dbdcc8ca48",
            "answerId": "5263fe064ade49649593edd07a8ebf72",
            "messageId": "5263fe064ade49649593edd07a8ebf72",
            "enableDataInspection": true,
            "isSave": true,
            "requestId": "52379bd8-c3aa-448f-ae30-4f77605f9b34",
            "characterPk": 1987826121,
            "characterName": "Psychological Companion Bot",
            "characterId": "aa7b98327d564d49a997ec67bfdaf68e",
            "origin": "pass_v2",
            "bizSrc": "PAAS",
            "voiceSend": false,
            "chatLockKey": "chat_5ed33fdb8d9d4d1489e44efb5c41312b_123456_aa7b98327d564d49a997ec67bfdaf68e",
            "useChatHistory": true,
            "hasReplacedCsiText": false
        },
        "flowUsage": [
            {
                "inputTokens": 1305,
                "outputTokens": 71,
                "modelName": "xingchen-plus-0403"
            },
            {
                "inputTokens": 428,
                "outputTokens": 79,
                "modelName": "xingchen-plus-0403"
            }
        ],
        "output": "Exercising is a great idea. It not only helps you stay healthy but also boosts your mood. When you exercise, your body releases endorphins, which are chemicals that make you feel happy. Regular exercise can also improve heart and lung function, boost your immune system, enhance sleep quality, and even help you better manage stress and anxiety. If you like, I can help you plan a workout routine that suits you.",
        "choices": [
            {
                "messages": [
                    {
                        "role": "assistant",
                        "content": "Exercising is a great idea. It not only helps you stay healthy but also boosts your mood. When you exercise, your body releases endorphins, which are chemicals that make you feel happy. Regular exercise can also improve heart and lung function, boost your immune system, enhance sleep quality, and even help you better manage stress and anxiety. If you like, I can help you plan a workout routine that suits you.",
                        "finishReason": "stop",
                        "tempMessage": false,
                        "useMessage": true,
                        "validMessage": true,
                        "functionMessage": false
                    }
                ],
                "stopReason": "stop"
            }
        ],
        "sumRT": 6082
    },
    "success": true
}