All Products
Search
Document Center

Chat App Message Service:Configure the Call a Function node

Last Updated:Sep 14, 2024

This topic describes how to configure the Call a Function node. This node is configured to invoke the custom function that you create in Alibaba Cloud Function Compute in a chat flow. This node allows you to implement custom business logic in a chat flow, such as data processing, remote service calls, message delivery, and data storage.

Node information

Node icon

image

Node name

Call a Function

Overall procedure

When you use the Call a Function node, you need to create and design a function in the Function Compute console. For more information about Function Compute, see What is Function Compute? To use the Call a Function node, perform the following steps:

  1. Create a function: Create a function in the Function Compute console.

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

  3. Configure the Call a Function node: Configure the Call a Function node in your chat flow. This helps you invoke the function that you create in the Function Compute console to implement custom business logic.

Prerequisites

Function Compute is activated.

Create a function

The following section describes how to create a function. Before you create a function, you must create a service.

  1. Log on to the Function Compute console. In the left-side navigation pane, click Services & Functions. In the top navigation bar, select a region from the drop-down list. We recommend that you select the region in which your chat flow is created.image

    Note

    If Services & Functions is not displayed in the left-side navigation pane, click Back to Function Compute 2.0 in the upper-right corner of the page and try again.

  2. Click Create Service to create a service. After a service is created, the Functions page appears.

  3. Click Create Function to create a function. The following table describes the key parameters. You can configure other parameters based on your business requirements.image

    Parameter

    Description

    Example

    Basic Settings - Handler Type

    Select HTTP Handler.

    image

    Advanced Settings - Handler

    Keep the default setting index.handler.

    image

    Trigger Configurations - Request Methods

    Select POST at least. POST indicates that your chat flow invokes the function by using the POST method.

    image

    Trigger Configurations - Disable Internet URL

    Select No. Your chat flow is not deployed in your virtual private cloud (VPC) and needs to access the function over the Internet.

    Trigger Configurations - Authentication Method

    Select Signature Authentication. Your chat flow ensures the validity of request parameters for function invocation by using the signature authentication method of Function Compute. You do not need to configure additional signature rules.

Design the function

The function template of Chat Flow allows you to implement custom business logic and deploy a simple and available function with ease. In the following example, a Python function is used.

  1. Create a function whose runtime environment is Python. When you create a function, select a Python environment for the Runtime parameter. For more information, see the Create a function section of this topic.image

  2. On the function details page, replace the default content of the index.py file with the following template code on the Code tab. The sample code is a Web Server Gateway Interface (WSGI) handler compatible with the invocation logic of Chat Flow and does not include your custom business logic. You do not need to modify the function and content in the code.image

    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')]
  3. Create a script file named my.py and import the file to the index.py file by using the from my import * statement. You can also specify a custom name for the script file.

  4. Enter the following code in the my.py file.

    Note

    The following sample code is used to generate a random number of a specified length based on the value of the random_number_length variable of your chat flow, and to return the branch code even or odd depending on the parity of the number. Additionally, the random and type variables are returned to your chat flow.

    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)

    The my.py file must contain the following functions regardless of your custom business logic.

    Note

    In the following sample code, the first function is used to invoke the custom function in your chat flow when the node is triggered, and the second function is used to invoke the custom function in your chat flow when the node is awakened after asynchronous events are handled. If you turn on Support awake in an asynchronous way, the chat flow waits for asynchronous event handling. In most cases, you do not need to turn on the switch.

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

    The structure of response parameters for the two functions is fixed regardless of your custom business logic.

    Note
    • success: indicates whether the function invocation is successful. If the invocation fails, the chat flow throws an error and terminates.

    • message: the prompt message, which can be customized.

    • await: indicates whether the chat flow waits for asynchronous event handling. The chat flow waits for asynchronous event handling when Support awake in asynchronous way is turned on. In most cases, you do not need to turn on the switch. If the value is False, the chat flow uses the output variables and branch code to determine the next step.

    • outputVariables: the names and values of variables that are returned to the chat flow. You can reference these variables in subsequent steps. The variables are used by the chat flow only when the value of the await parameter is False.

    • toBranchCode: the branch code that is returned to the chat flow. The branch code is returned when Enable Multi-Branching is turned on. The chat flow determines the next step based on the branch code and the chat flow configurations. The branch code is used by the chat flow only when the value of the await parameter is False.

    result = {
        'success': True,
        'message': 'OK',
        'await': False,
        'outputVariables': {
            'myVarExample1': 'a',
            'myVarExample2': 'b'
        },
        'toBranchCode': 'example'
    }

Configure the Call a Function node

The following section describes how to configure the Call a Function node to invoke the function that you create in the Function Compute console to implement custom business logic.

  1. In the Chat App Message Service console, click Chat Flow in the left-side navigation pane. On the Flow Management tab, click the name of the chat flow to be edited to go to the chat flow orchestration page.image

  2. Click the Call a Function node icon on the canvas.image

  3. In the Configure section, configure the node based on your business requirements. For more information about the configuration details, see the Parameter description section of this topic.

  4. Click Save.

Parameter description

Section

Parameter

Description

Example

Run Settings

Support awake in asynchronous way

After you turn on Support awake in asynchronous way, the function can be invoked asynchronously when the node is triggered or awakened.

image

Asynchronous wait timeout (seconds)

Specify the asynchronous timeout period. Unit: seconds.

HTTP Trigger Settings

URL

Enter the endpoint of the HTTP trigger. You can perform the following steps to obtain the endpoint: Log on to the Function Compute console. In the left-side navigation pane, click Services & Functions. On the page that appears, click the name of the desired service. On the Functions page that appears, click the name of the desired function. On the function details page, click the Trigger Management (URL) tab and view the endpoint next to Public Endpoint.

Note

If you use the node for the first time, click Authorize us to invoke your functions and complete the authorization.

image

Region

Enter the region that corresponds to the third segment of the Alibaba Cloud Resource Name (ARN). You can perform the following steps to obtain the region: Log on to the Function Compute console. In the left-side navigation pane, click Services & Functions. On the page that appears, click the name of the desired service. On the Functions page that appears, click the name of the desired function. On the function details page, click the Configurations tab and view the ARN in the Basic Settings section.

image

Timeout (seconds)

Specify a custom timeout period.

image

Parameter Settings

-

Add parameters that you want to pass to the function based on your business requirements. The keys are the names of the parameters, and the values of the parameters are constants or variables of your chat flow.

image

Multi-branch Settings

-

Turn on or off Enable Multi-Branching based on your business requirements. The specified branch code corresponds to the branch code returned by your function. If your function returns a branch code that is not specified in the chat flow, the chat flow enters the Else branch.

image

Response Settings

-

Configure the response parameters of the function as variables of the chat flow. The variable names you enter must match the names of the variables returned by your function.

image