All Products
Search
Document Center

Chat App Message Service:Call a Function

Last Updated:Jul 13, 2026

This topic describes how to configure the Call a Function component. This component lets you invoke your custom functions in Alibaba Cloud Function Compute from within a flow. You can use it to implement custom business logic, such as data processing, remote service calls, message delivery, and data storage.

Component information

Icon

Name

调用函数@1x (1)

Call a Function

Procedure overview

To use the Call a Function component, you must first activate the Alibaba Cloud Function Compute service and then create a function in Function Compute.

  1. Create and configure a function: Create and configure a function in Function Compute.

  2. Design the function: Design the function in Function Compute.

  3. Configure the component: Configure the Call a Function component in your flow to invoke your custom function from Function Compute.

Prerequisites

The Function Compute service is activated.

1. Create and configure a function

  1. Log on to the Function Compute console. At the top of the page, select a region. We recommend that you select the same region as your flow, for example, Singapore. In the left-side navigation pane, choose Function Management > Functions to go to the Functions page.

  2. On the Functions page, click Create Function > Web Function.

    1. Main configuration: In the Code section, for Runtime, select an appropriate runtime type. This topic uses Built-in Runtimes > Python > Python 3.10 as an example.

      Tab 1 title

      Tab 1 Content

      Tab 2 title

      Tab 2 Content

    2. Configure other parameters as needed.

2. Design the function

Using the provided function template helps you focus on your business logic and quickly deploy a function.

  1. On the Function Details page, click the Code tab and replace the default content of the index.py file with the following template.

    Note

    This code is a WSGI (Web Server Gateway Interface) handler that is compatible with the flow invocation logic. It does not contain any custom business logic. Do not modify the functions or content in this file.

    import json
    from my import *
    # DO NOT CHANGE THIS ENTIRE FILE!
    # handle wsgi request
    # about wsgi: https://wsgi.readthedocs.io/en/latest/learn.html
    def handler(environ, start_response):
        # get request_body
        try:
            request_body_size = int(environ.get('CONTENT_LENGTH', 0))
        except ValueError:
            request_body_size = 0
        request_body = environ['wsgi.input'].read(request_body_size)
        print(request_body)
        # get path info
        path_info = environ['PATH_INFO']
        print(path_info)
        # load http triggering request to json
        # as flow node input args
        body = json.loads(request_body.decode('utf-8'))
        # do custom node process
        if path_info == '/handle_exec':
            output = handle_exec(body['variables'])
        elif path_info == '/handle_awake':
            output = handle_awake(
                body['asyncId'],
                body['async_event_data'],
                body['variables']
            )
        else:
            raise Exception('Invalid path ' + path_info)
        status = '200 OK'
        response_headers = [('Content-type', 'text/plain')]
        start_response(status, response_headers)
        return [json.dumps(output).encode('utf-8')]
    
  2. Create a new script file named my.py and copy the following code into the my.py file.

Note

The following template generates a random number of a specified length based on the random_number_length input variable. It then directs the flow down an even or odd branch based on the number's parity, and outputs two variables to the flow: random and type.

import random
# impl: py spi handle_exec
def handle_exec(variables) -> dict:
    # translate fun request
    random_number_length = variables['random_number_length']
    random_number = generate_random_by_length(random_number_length)
    print("random generated as " + str(random_number))
    if (random_number % 2) == 0:
        number_type = "even"
    else:
        number_type = "odd"
    result = {
        'success': True,
        'message': 'OK',
        'await': False,
        'outputVariables': {
            'random': random_number,
            'type': number_type
        },
        'toBranchCode': number_type
    }
    return result
# impl: py spi handle_awake
def handle_awake(async_id, async_event_data, variables) -> dict:
    return {}
def generate_random_by_length(random_number_length) -> int:
    length = int(random_number_length)
    start = 10 ** (length - 1)
    stop = 10 ** length
    print("from " + str(start) + "(inclusive) to " + str(stop) + "(exclusive)")
    return random.randrange(start, stop)

Regardless of your custom logic, the my.py file must contain the following two functions.

Note

These two functions handle flow invocation and event processing, respectively. If you have already configured event handling for the Call a Function component in the flow editor, you do not need to implement event handling logic in your function.

  • def handle_exec(variables) -> dict

  • def handle_awake(async_id, async_event_data, variables) -> dict

The return structure for both functions is fixed, regardless of your custom logic.

  • success: Indicates whether the function call was successful. If set to false, the flow stops with an error.

  • message: A custom message to provide additional information.

  • await: Indicates whether the flow must wait for subsequent event handling. If set to false, the flow immediately proceeds using the returned outputVariables and toBranchCode.

  • outputVariables: A dictionary of key-value pairs passed as output variables to the flow. You can reference these variables in subsequent components. This dictionary is used only when await is false.

  • toBranchCode: A code that determines which branch the flow follows next, based on your multi-branching settings. This code is used only when await is false.

result = {
    'success': True,
    'message': 'OK',
    'await': False,
    'outputVariables': {
        'myVarExample1': 'a',
        'myVarExample2': 'b'
    },
    'toBranchCode': 'example'
}
  1. After you modify the files, click Deploy.

3. Component configuration

Follow these steps to configure the Call a Function component in your flow.

  1. Prerequisites

    To configure this component, access the flow canvas by using an existing flow or creating a new one.

    • Go to the canvas of an existing flow

      In the Chat Flow > Flow Management > Flow Name

    • Create a new flow to open its canvas. For more information, see Create a flow.

  2. On the canvas, click the Call a Function component icon to view its configuration pane on the right.

    In the flow editor, select the Call a Function (FunctionComputeNode) node. The configuration panel opens on the right. The available variables include incomingMessage, wabaId, wabaPhoneNumber, customerPhoneNumber, and customerName. In the HTTP Trigger Settings section, enter the URL and Region (required), and set the Timeout (seconds). In the Runtime Settings section, you can trigger the node by using a webhook or an API and enable the asynchronous trigger switch as needed. After you complete the configuration, click Save.

  3. Configure the component's parameters. For details, see Configuration Details.

  4. After you finish the configuration, click Save. In the dialog box that appears, click Save.

Parameters

Section

Parameter

Description

Execution Settings

Asynchronous Awakening

If enabled, the component runs asynchronously, allowing the flow to pause and later be "awakened" to resume execution.

Asynchronous Wait Timeout

The timeout period for the asynchronous wait, in seconds.

HTTP Trigger Settings

URL

To configure the URL, go to the Function Compute console. In the left-side navigation pane, choose Function Management > Functions. Find your function and click its name to go to the Function Details page. Click the Trigger tab and copy the Internet Endpoint address.

Note

After you enter the function's URL, click Authorize ChatApp to Invoke Your Function to complete the one-time authorization.

Region

The region where your function is deployed, which corresponds to the third segment of the function's ARN.

To find the ARN, go to the Function Compute console. In the left-side navigation pane, choose Function Management > Functions. Find your function and go to its Function Details page. Click the Configuration tab and then click Copy ARN.

Note

For example, if the copied ARN is acs:fc:ap-southeast-1:112xxxxxx4926620:functions/test1,

the region is ap-southeast-1.

Timeout

The timeout for the HTTP request, in seconds.

Parameter Settings

-

If required, configure the input parameters for the function. The parameter names must match the parameters that your function expects to receive. The values can be constants or flow variables.

Multi-branching Settings

-

If required, configure multiple branches for the function's output. The branch Code must match the toBranchCode value returned by your function. If the function returns a branch code that is not defined in the flow, the flow follows the Else branch by default.

Response Settings

-

If required, map the function's output to flow variables. The variable names must match the keys in the outputVariables dictionary returned by your function.