All Products
Search
Document Center

Platform For AI:Python SDK

Last Updated:Jun 01, 2026

This topic provides a detailed API reference for the official Python SDK and includes complete code examples for common input and output formats.

Note

To learn about the use cases and working principles of the SDK, see SDK for service calls.

Prerequisites

pip install -U eas-prediction --user

Quick start

Choose a Request class that matches your model's input data format. The following code shows a minimal example of an end-to-end service call that uses a string request. For more examples, see Examples.

#!/usr/bin/env python
from eas_prediction import PredictClient
from eas_prediction import StringRequest

if __name__ == '__main__':
    client = PredictClient('http://182848887922****.cn-shanghai.pai-eas.aliyuncs.com', 'my_service')
    client.set_token('YOUR_SERVICE_TOKEN')
    client.init()

    request = StringRequest('[{}]')
    resp = client.predict(request)
    print(resp)

API reference

The Python SDK provides the following classes, which are grouped by purpose:

Group

Description

Main client

PredictClient: Configures service information such as the endpoint, service name, and token, sends requests, and receives responses.

Input and output

  • StringRequest / StringResponse: Encapsulates inputs and outputs for string-based scenarios, such as custom processors or PMML models.

  • TFRequest / TFResponse: Encapsulates requests and responses for TensorFlow models.

  • TorchRequest / TorchResponse: Encapsulates requests and responses for PyTorch models.

  • BladeRequest / BladeResponse and more. For a complete list of supported types, refer to the SDK.

Queue service

  • QueueClient: An asynchronous queue client used to send data, subscribe to data pushes, and query queue status.

  • Watcher: A queue subscriber created by QueueClient.watch() to receive pushed data.

Common parameters

Endpoint: The endpoint address of the server.

  • For a standard service, set this parameter to the default gateway endpoint. Example: 182848887922***.cn-shanghai.pai-eas.aliyuncs.com.

  • For a VPC direct connection request, set this parameter to the service's VPC direct connection endpoint. The format is <uid>.vpc.<region-id>.pai-eas.aliyuncs.com. Example: 182848887922****.vpc.cn-shanghai.pai-eas.aliyuncs.com.

PredictClient class

Method

Description

PredictClient(endpoint, service_name, custom_url)

  • Creates a PredictClient object.

  • Parameters:

    • Endpoint: The server endpoint address. See Common parameters.

    • service_name: The name of the service.

    • custom_url: The URL of the service. This parameter is optional. Use it only for services that have a non-standard endpoint format (not in the format of <uid>.<region>.pai-eas.aliyuncs.com), such as web UI services. Example: client = PredictClient(custom_url='<url>').

set_endpoint(endpoint)

  • Description: Sets the server endpoint address. See Common parameters.

  • The endpoint parameter specifies the server-side endpoint.

set_service_name(service_name)

  • Description: Sets the name of the service to request.

  • Parameter: service_name. The name of the requested service.

set_endpoint_type(endpoint_type)

  • Description: Sets the gateway type of the server.

  • Parameter: endpoint_type The type of gateway to be set. The following gateway types are supported:

    • ENDPOINT_TYPE_GATEWAY: The default gateway.

    • ENDPOINT_TYPE_DIRECT: Indicates a direct connection request. If you do not set this parameter, the client accesses the service through the gateway by default.

set_token(token)

  • Description: Sets the access token for the service.

  • The token parameter specifies the service access token.

set_retry_count(max_retry_count)

  • Description: Sets the number of retries after a request fails.

  • The max_retry_count parameter specifies the number of retries for a failed request. The default value is 5.

    Important

    The client must resend requests that fail due to intermittent issues, such as server-side process exceptions, server anomalies, or when the persistent connection to the gateway is lost. Therefore, do not set this parameter to 0.

set_max_connection_count(max_connection_count)

  • Description: Sets the maximum number of persistent connections in the client's connection pool. For performance reasons, the client establishes persistent connections with the server and places them in a connection pool. For each request, the client retrieves an idle connection from the connection pool to access the service.

  • The max_connection_count parameter specifies the maximum number of persistent connections in the connection pool, with a default value of 100.

set_timeout(timeout)

  • Description: Sets the request timeout duration.

  • Parameter: timeout specifies the timeout period for a request in milliseconds. The default value is 5000.

init()

Initialize the PredictClient object. After you set the parameters, you need to call the init() method for the settings to take effect.

predict(request)

  • Description: Submits a prediction request to an online prediction service.

  • The request parameter is an abstract class, and you can pass different types of request, such as StringRequest or TFRequest.

  • Return value: The Response object that corresponds to the request.

StringRequest class

Method

Description

StringRequest(request_data)

  • Creates a StringRequest object.

  • Parameter: request_data specifies the request string to be sent.

StringResponse class

Method

Description

to_string()

  • Description: Converts a StringResponse object to a string.

  • Return value: The response body.

TFRequest class

Method

Description

TFRequest(signature_name)

  • Creates a TFRequest object.

  • Parameter: signature_name specifies the Signature Name in the model to be requested.

add_feed(self, input_name, shape, data_type, content)

  • Description: Sets the required input data for a TensorFlow model.

  • Parameters:

    • input_name: The alias of the input tensor.

    • shape: The tensor shape of the input tensor.

    • data_type: The data type of the input tensor. The supported types are:

      • TFRequest.DT_FLOAT

      • TFRequest.DT_DOUBLE

      • TFRequest.DT_INT8

      • TFRequest.DT_INT16

      • TFRequest.DT_INT32

      • TFRequest.DT_INT64

      • TFRequest.DT_STRING

      • TFRequest.TF_BOOL

    • content: The content of the input tensor, represented by a flattened one-dimensional array.

add_fetch(self, output_name)

  • Description: Sets the alias of the tensor to be output when you request a TensorFlow online prediction service model.

  • The output_name parameter specifies the alias of the output Tensor.

    This parameter is optional for SavedModel models. If this parameter is not set, all outputs are returned.

    This parameter is required for frozen models.

to_string()

  • Description: Serializes the TFRequest ProtoBuf object into a string.

  • Return value: The serialized string of the TFRequest object.

TFResponse class

Method

Description

get_tensor_shape(output_name)

  • Description: Gets the tensor shape of the output tensor with the specified alias.

  • The output_name parameter specifies the alias of the Tensor whose shape you want to obtain.

  • Return value: The tensor shape of the output.

get_values(output_name)

  • Description: Gets the data vector of the output tensor.

  • The output_name parameter is the alias of the output Tensor.

  • Return value: This method returns the output as a one-dimensional array. Use get_tensor_shape() to retrieve the tensor's shape and reshape the array. The method returns different types of result arrays based on the type of the output.

TorchRequest class

Method

Description

TorchRequest()

Creates a TorchRequest object.

add_feed(self, index, shape, data_type, content)

  • Description: Sets the required input tensor for a PyTorch model.

  • Parameters:

    • index: The index of the input tensor.

    • shape: The tensor shape of the input tensor.

    • data_type: The data type of the input tensor. The supported types are:

      • TFRequest.DT_FLOAT

      • TFRequest.DT_DOUBLE

      • TFRequest.DT_INT8

      • TFRequest.DT_INT16

      • TFRequest.DT_INT32

      • TFRequest.DT_INT64

      • TFRequest.DT_STRING

      • TFRequest.TF_BOOL

    • content: The content of the input tensor, represented by a flattened one-dimensional array.

add_fetch(self, output_index)

  • Description: Sets the index of the tensor to be output when you request a PyTorch online prediction service model. This method is optional. If you do not call this method to set the index of the output tensor, all outputs are returned.

  • Parameter: output_index specifies the Index of the output Tensor.

to_string()

  • Description: Serializes the TorchRequest ProtoBuf object into a string.

  • Return value: The serialized string of the TorchRequest object.

TorchResponse class

Method

Description

get_tensor_shape(output_index)

  • Description: Gets the tensor shape of the output tensor with the specified index.

  • Parameters: output_index: The index of the output tensor whose shape you want to retrieve.

  • Return value: The shape of the output tensor that corresponds to the specified index.

get_values(output_index)

  • Description: Gets the data vector of an output tensor. This method returns the output as a one-dimensional array. You can use the get_tensor_shape() method to get the shape of the corresponding tensor and reshape it into the required multi-dimensional tensor. The method returns different types of result arrays based on the type of the output.

  • Parameter: output_index specifies the index of the output Tensor to retrieve.

  • Return value: The data array of the resulting tensor.

QueueClient class

Method

Description

QueueClient(endpoint, queue_name)

  • Creates a QueueClient object.

  • Parameters:

    • Endpoint: The endpoint address of the server.

    • queue_name: The name of the queue service.

set_token(token)

  • Description: Sets the authentication token for the queue service.

  • Parameter: token is the token for the queue service.

init(uid=None,gid='eas')

  • Description: Initializes a QueueClient object.

  • Parameters:

    • uid: The user ID of the client registered with the server. The uid of each client instance must be unique. A uid can be registered only once. The server distributes pushed data evenly among different uids.

    • Gid: The group ID of the client registered with the server. By default, all clients belong to the same group. If different groups exist, a copy of the same data is pushed to all groups.

set_logger(logger=None)

  • Description: Sets a logger object for the QueueClient. By default, runtime warning messages are printed to the standard output. To disable this information, set the logger object to None.

  • Parameter: logger. Specifies the logging object to configure.

truncate(index)

  • Description: Truncates data in the queue before the specified index.

  • Parameter: index: Specifies the index of the data at which to truncate the queue.

put(data,tags:dict={})

  • Description: Writes a piece of data to the queue.

  • Parameters:

    • data: The content of the data to be written to the queue.

    • tags (optional): The tags of the data to be written to the queue.

  • Return value:

    • index: The index value of the currently written data in the queue. You can use this value to query data from the queue.

    • requestId: The automatically generated request ID of the currently written data in the queue. The request ID is a special tag that can also be used to query data in the queue.

get(request_id=None, index=0, length=1, timeout='5s', auto_delete=True, tags={})

  • Description: Queries data from the queue based on specified conditions.

  • Parameters:

    • request_id: The request ID of the data to query. If this parameter is specified, the query scans up to length records starting from index. If data with the specified request ID is found, it is returned. Otherwise, an empty result is returned.

    • index: The starting index of the data to query. The default value is 0, which indicates that the query starts from the first piece of data in the queue.

    • length: The number of data pieces to query. A maximum of length data pieces are returned, starting from and including the index.

    • timeout: The query wait time. If the number of data pieces in the queue reaches length within the wait time, the data is returned immediately. Otherwise, the query stops when the timeout is reached.

    • auto_delete: Specifies whether to automatically delete queried data from the queue. If you set this parameter to False, you can query the data repeatedly. You can call the delete() method to manually delete the data.

    • tags: A DICT of tags used for filtering. The query traverses length data pieces starting from the specified index and returns data that contains the specified tags.

  • Return value: The queried data from the queue, as a DataFrame.

attributes()

  • Description: Gets the attributes of the queue, such as the total length of the queue and the current data length.

  • Return value: attrs: The attributes of the queue. The data type is DICT.

delete(indexes)

  • Description: Deletes data with the specified index from the queue.

  • Parameter: indexes: The index or indexes of the data to be removed from the queue. This parameter supports a single index of the String type or a list of indexes of the List type.

search(index)

  • Description: Queries the queuing information of the data.

  • Parameters: index: The index of the data to be queried.

  • Return value: The data queuing information of type JSONObject, which includes the following fields:

    • ConsumerId: The ID of the instance that is processing the data.

    • IsPending: Indicates whether the data is being processed.

      • True indicates that the data is being processed.

      • False indicates that the data is in the queue.

    • WaitCount: The number of data pieces that are waiting in the queue ahead of the current data piece. This field is valid only when IsPending is False. If IsPending is True, the value is 0.

    Example of returned content:

    • The response {'ConsumerId': 'eas.****', 'IsPending': False, 'WaitCount':2} indicates that the request is being queued.

    • The log shows search error:Code 404, Message: b'no data in stream' and returns {}. This indicates that the data was not found in the queue. This may occur because the data has been successfully processed by the server and a result has been returned, or the index parameter is configured incorrectly. Please check and confirm.

watch(index, window, index_only=False, auto_commit=False)

  • Description: Subscribes to data in the queue. The queue service pushes data to the client based on the specified conditions.

  • Parameters:

    • index: The starting index for the data subscription.

    • window: The subscription window size. This is the maximum amount of data that the queue service can push to a single client instance at a time.

      Note

      If pushed data is not committed, the server does not push new data. If N pieces of data are committed, the service queue pushes N new pieces of data to the client. This ensures that the number of data items being processed by the client at any one time does not exceed the window size, which limits client concurrency.

    • index_only: Specifies whether to push only the index value.

    • auto_commit: Specifies whether to automatically commit the data after it is pushed. We recommend that you set this to False. Manually commit data after you receive the pushed data and complete the computation. If an instance fails before the computation is complete, the uncommitted data on the instance is distributed by the queue service to other instances for processing.

  • Return value: A watcher object that you can use to read the pushed data.

commit(index)

  • Description: Commits data with the specified index.

    Note

    A commit indicates that the data pushed by the service queue has been processed. The data can then be cleared from the queue and does not need to be pushed to other instances.

  • Parameter: index: The list of index values for the data to be committed to the queue. This parameter supports a single index of the String type or a list of multiple indexes.

Watcher class

Method

Description

run()

  • Description: Runs a Watcher, establishes a WebSocket connection with the server to receive data pushes, and returns the results to the caller in real time.

  • Return value: A DataFrame object that is pushed from the queue service to the client in real time.

close()

Description: Closes a Watcher object to terminate the back-end data connection.

Note

A client can have only one active Watcher at a time. You must close the current Watcher before starting a new one.

Examples

Synchronous inference example (by input/output format)

Select the sample code based on the input and output types of the service.

String

Users who deploy services with a custom processor typically use strings for service calls, such as for PMML model services. The following code shows a sample program.

#!/usr/bin/env python

from eas_prediction import PredictClient
from eas_prediction import StringRequest

if __name__ == '__main__':
    client = PredictClient('http://182848887922****.cn-shanghai.pai-eas.aliyuncs.com', 'scorecard_pmml_example')
    client.set_token('YWFlMDYyZDNmNTc3M2I3MzMwYmY0MmYwM2Y2MTYxMTY4NzBkNzdj****')
    client.init()

    request = StringRequest('[{"fea1": 1, "fea2": 2}]')
    for x in range(0, 1000000):
        resp = client.predict(request)
        print(resp)

TensorFlow

If you use TensorFlow, use TFRequest and TFResponse as the input and output data formats. The following code shows a sample.

#!/usr/bin/env python

from eas_prediction import PredictClient
from eas_prediction import StringRequest
from eas_prediction import TFRequest

if __name__ == '__main__':
    client = PredictClient('http://182848887922****.cn-shanghai.pai-eas.aliyuncs.com', 'mnist_saved_model_example')
    client.set_token('YTg2ZjE0ZjM4ZmE3OTc0NzYxZDMyNmYzMTJjZTQ1YmU0N2FjMTAy****')
    client.init()

    #request = StringRequest('[{}]')
    req = TFRequest('predict_images')
    req.add_feed('images', [1, 784], TFRequest.DT_FLOAT, [1] * 784)
    for x in range(0, 1000000):
        resp = client.predict(req)
        print(resp)

PyTorch

If you use PyTorch, use TorchRequest and TorchResponse as the input and output data formats. The following code shows a sample.

#!/usr/bin/env python

from eas_prediction import PredictClient
from eas_prediction import TorchRequest

if __name__ == '__main__':
    client = PredictClient('http://182848887922****.cn-shanghai.pai-eas.aliyuncs.com', 'pytorch_gpu_wl')
    client.init()

    req = TorchRequest()
    req.add_feed(0, [1, 3, 224, 224], TorchRequest.DT_FLOAT, [1] * 150528)
    # req.add_fetch(0)
    import time
    st = time.time()
    timer = 0
    for x in range(0, 10):
        resp = client.predict(req)
        timer += (time.time() - st)
        st = time.time()
        print(resp.get_tensor_shape(0))
        # print(resp)
    print("average response time: %s s" % (timer / 10) )

BladeProcessor

If you use BladeProcessor, use BladeRequest and BladeResponse as the input and output data formats. The following code shows a sample.

#!/usr/bin/env python

from eas_prediction import PredictClient
from eas_prediction import BladeRequest

if __name__ == '__main__':
    client = PredictClient('http://182848887922****.cn-shanghai.pai-eas.aliyuncs.com', 'nlp_model_example')
    client.init()

    req = BladeRequest()

    req.add_feed('input_data', 1, [1, 360, 128], BladeRequest.DT_FLOAT, [0.8] * 85680)
    req.add_feed('input_length', 1, [1], BladeRequest.DT_INT32, [187])
    req.add_feed('start_token', 1, [1], BladeRequest.DT_INT32, [104])
    req.add_fetch('output', BladeRequest.DT_FLOAT)
    import time
    st = time.time()
    timer = 0
    for x in range(0, 10):
        resp = client.predict(req)
        timer += (time.time() - st)
        st = time.time()
        # print(resp)
        # print(resp.get_values('output'))
        print(resp.get_tensor_shape('output'))
    print("average response time: %s s" % (timer / 10) )

BladeProcessor compatible with the default TensorFlow interface

BladeProcessor users can use TFRequest and TFResponse as the input and output data formats. These formats are compatible with the default TensorFlow interface of Elastic Algorithm Service (EAS). The following code shows a sample.

#!/usr/bin/env python

from eas_prediction import PredictClient
from eas_prediction.blade_tf_request import TFRequest # Need Importing blade TFRequest

if __name__ == '__main__':
    client = PredictClient('http://182848887922****.cn-shanghai.pai-eas.aliyuncs.com', 'nlp_model_example')
    client.init()

    req = TFRequest(signature_name='predict_words')

    req.add_feed('input_data', [1, 360, 128], TFRequest.DT_FLOAT, [0.8] * 85680)
    req.add_feed('input_length', [1], TFRequest.DT_INT32, [187])
    req.add_feed('start_token', [1], TFRequest.DT_INT32, [104])
    req.add_fetch('output')
    import time
    st = time.time()
    timer = 0
    for x in range(0, 10):
        resp = client.predict(req)
        timer += (time.time() - st)
        st = time.time()
        # print(resp)
        # print(resp.get_values('output'))
        print(resp.get_tensor_shape('output'))
    print("average response time: %s s" % (timer / 10) )

Example of calling a service using a VPC direct connection

To use a direct connection, configure a Virtual Private Cloud (VPC) for the service. For more information, see Use Elastic Algorithm Service (EAS) resource groups and Access public or internal resources from EAS. This calling method requires only one additional line of code compared to the normal method: client.set_endpoint_type(ENDPOINT_TYPE_DIRECT). This method is ideal for services with high traffic and concurrency. The following code provides an example.

#!/usr/bin/env python

from eas_prediction import PredictClient
from eas_prediction import StringRequest
from eas_prediction import TFRequest
from eas_prediction import ENDPOINT_TYPE_DIRECT

if __name__ == '__main__':
    # The format of a VPC direct connection endpoint is <uid>.vpc.<region-id>.pai-eas.aliyuncs.com. You can find the endpoint on the Invocation Information tab of the service details page in the EAS console.
    client = PredictClient('http://182848887922****.vpc.cn-hangzhou.pai-eas.aliyuncs.com', 'mnist_saved_model_example')
    client.set_token('M2FhNjJlZDBmMzBmMzE4NjFiNzZhMmUxY2IxZjkyMDczNzAzYjFi****')
    client.set_endpoint_type(ENDPOINT_TYPE_DIRECT)
    client.init()

    request = TFRequest('predict_images')
    request.add_feed('images', [1, 784], TFRequest.DT_FLOAT, [1] * 784)
    for x in range(0, 1000000):
        resp = client.predict(request)
        print(resp)

Example: Sending and subscribing to data in a queue service

You can use QueueClient to send data to a queue service, query data, check the service status, and subscribe to data pushes. The following demo shows an example with two threads. One thread sends data to the queue service. The other thread uses a Watcher to subscribe to the pushed data.

#!/usr/bin/env python

from eas_prediction import QueueClient
import threading

if __name__ == '__main__':
    endpoint = '182848887922****.cn-shanghai.pai-eas.aliyuncs.com'
    queue_name = 'test_group.qservice/sink'
    token = 'YmE3NDkyMzdiMzNmMGM3ZmE4ZmNjZDk0M2NiMDA3OTZmNzc1MTUx****'

    queue = QueueClient(endpoint, queue_name)
    queue.set_token(token)
    queue.init()
    queue.set_timeout(30000)

    # truncate all messages in the queue
    attributes = queue.attributes()
    if 'stream.lastEntry' in attributes:
        queue.truncate(int(attributes['stream.lastEntry']) + 1)

    count = 100
    # create a thread to send messages to the queue
    def send_thread():
        for i in range(count):
            index, request_id = queue.put('[{}]')
            print('send: ', i, index, request_id)

    # create a thread to watch messages from the queue
    def watch_thread():
        watcher = queue.watch(0, 5, auto_commit=True)
        i = 0
        for x in watcher.run():
            print('recv: ', i, x.index, x.tags['requestId'])
            i += 1
            if i == count:
                break
        watcher.close()

    thread1 = threading.Thread(target=watch_thread)
    thread2 = threading.Thread(target=send_thread)

    thread1.start()
    thread2.start()

    thread1.join()
    thread2.join()

Troubleshooting

For information about the symptoms, causes, and troubleshooting of exceptions from Python SDK calls, see the 'Troubleshooting call exceptions' section in Service Call SDK. These exceptions include common issues with authentication, routing, connection, and the server.

For a complete list of service status codes, error message descriptions, and suggested solutions, see Appendix: Service status codes and common errors.