Skip to main content
Version: 2026.07.0

Task Lifecycle Code Examples

This guide provides hands-on Python examples for working with tasks in Speech Platform 4 Virtual Appliance. It demonstrates how to create, poll, and delete tasks using the asynchronous REST API flow. For a conceptual overview of how tasks work and a basic structure of asynchronous processing, refer to the Task Lifecycle Overview.

At the end of this guide, you'll find complete Python examples for both media file and voiceprint-based tasks. These examples combine all the steps that are first discussed separately, and demonstrate how to manage Speech Platform 4 tasks in your own projects.

Prerequisites​

Virtual Appliance Setup​

This guide assumes the Speech Platform 4 Virtual Appliance is running on port 8000 of http://<virtual-appliance-address> (replace with your address) and has the necessary models and licenses for your technology use case. For more information on how to install and start the Virtual Appliance, please refer to the Virtual Appliance Installation guide.

Environment Setup​

We are using Python 3.14 and Python library requests 2.32 in this example. You can install the requests library with pip as follows:

pip install requests~=2.32

Example data​

The following files are used throughout this guide and can be downloaded from the example_files.zip archive.

  • Barbara.wav: Audio file used for media-based endpoint.
  • Harry.vp: Voiceprint used for voiceprint-based endpoint.
  • Julia.vp: Voiceprint used for voiceprint-based endpoint.

Feel free to replace these example files with your own data for testing.

Creating a task​

To create a task, send a POST request to your chosen endpoint with the required parameters.

If the request is valid, you'll receive a 202 Accepted response with a unique task_id. The task does not get processed immediately, but is scheduled for processing. You can monitor its progress by polling with the task_id.

If the request is rejected, you'll have to handle the error and fix the request before retrying.

Creating task with media file on input​

This example shows how to create a task for processing a media file. Refer to the technology-specific REST API documentation for required and optional parameters. Parameters can be passed in two ways:

  • Query parameters: Passed in the URL.

  • Configuration parameters: Passed as part of multipart/form-data content type with the field name config and the value as a JSON string. In Python, use json.dumps() to convert the configuration dictionary to a JSON string.

import json
import requests

VIRTUAL_APPLIANCE_ADDRESS = "http://<virtual-appliance-address>:8000" # Replace with your address
MEDIA_FILE_BASED_TECHNOLOGY_NAME = "emotion-recognition" # Replace with your technology endpoint
MEDIA_FILE_BASED_ENDPOINT_URL = f"{VIRTUAL_APPLIANCE_ADDRESS}/api/technology/{MEDIA_FILE_BASED_TECHNOLOGY_NAME}"

audio_path = "Barbara.wav" # Replace with your audio file
params = {} # Add query parameters if needed
config = {} # Add configuration parameters if needed

with open(audio_path, mode="rb") as file:
files = {"file": file}
start_task_response = requests.post(
url=MEDIA_FILE_BASED_ENDPOINT_URL,
files=files,
params=params,
data={"config": json.dumps(config)}
)

print(start_task_response.status_code) # Should print '202'

Creating task with voiceprints on input​

This example shows how to create a task for processing voiceprints. Voiceprints are passed in the request body as an array of Base64-encoded data (shortened for readability):

import requests

VIRTUAL_APPLIANCE_ADDRESS = "http://<virtual-appliance-address>:8000" # Replace with your address
VOICEPRINT_BASED_TECHNOLOGY_NAME = "gender-identification-voiceprints" # Replace with your technology endpoint
VOICEPRINT_BASED_ENDPOINT_URL = f"{VIRTUAL_APPLIANCE_ADDRESS}/api/technology/{VOICEPRINT_BASED_TECHNOLOGY_NAME}"

json_payload = {
"voiceprints": [
"eyNpBWkDY3JjTAAAAADAdlN3aQllbWJlZGRpbmdbJGQjSQIAvES8gD0Aa...",
"eyNpBWkDY3JjbCwoJE1pCWVtYmVkZGluZ1skZCNJAgA8UcehO6orjLzlf...",
]
} # Update with voiceprint(s) you want to use

start_task_response = requests.post(
url=VOICEPRINT_BASED_ENDPOINT_URL,
json=json_payload,
)

print(start_task_response.status_code) # Should print '202'

Task polling​

The response to the "Start Task" request includes a Location header with the full polling URL. Alternatively, you can construct the polling URL by appending a slash (/) and the task_id to the endpoint URL.

To check the state of a task or retrieve its result after processing completes, send a GET request to the polling URL. The response includes the current task state, and the result or error (if processing has already finished).

When a task finishes successfully, the response includes the result field with the processing result. If the task fails, the error field contains the error message, and you'll have to handle the error.

import json
import time
import requests

polling_url = start_task_response.headers["Location"] # From the task creation response

# Alternatively, construct the URL manually:
# task_id = start_task_response.json()["task"]["task_id"]
# polling_url = ENDPOINT_URL + "/" + task_id

while True:
polling_task_response = requests.get(polling_url)
polling_task_response_json = polling_task_response.json()
task_state = polling_task_response_json["task"]["state"]
if task_state in {"done", "failed", "rejected", "cancelled"}:
break
time.sleep(5)

print(polling_task_response_json)

Task deletion​

It is possible to delete any task, regardless of its state. See the Task Lifecycle Overview for possible task states and their meaning. A task that has already finished (states done, rejected or failed) is deleted immediately. A task that is still processing (states pending or running) is marked as cancelled and deleted as soon as possible.

It is not necessary to clean up a task manually, since finished tasks are automatically removed after a configurable expiration period. However, you can choose to delete a task if the results are no longer needed, and you want to free up processing and/or memory resources before the automatic clean-up takes effect.

To delete a task, send a DELETE request to the api/tasks endpoint with the task_id as the final part of the URL. If the request succeeds, the REST API responds with the 204 status code.

import requests

task_id = start_task_response.json()["task"]["task_id"] # From the start task response
delete_task_response = requests.delete(f"{VIRTUAL_APPLIANCE_ADDRESS}/api/tasks/{task_id}")
print(delete_task_response.status_code) # Should print '204'

Error handling​

Errors can occur during both task creation and task processing. Each error object contains machine-readable and human-readable error information, with details about the error, if available. For automation purposes, rely on the machine-readable information (error type) to handle errors programmatically.

For a complete and up-to-date list of possible error responses, check the REST API Reference. Refer to the technology-specific REST API documentation to learn what errors are possible for each technology.

Handling errors during task creation​

If an error occurs during task creation (typically due to missing or invalid parameters, request malformation, request size limit violation) no task is created. Instead, an error object is returned directly in the response with a 4xx or 5xx status code.

Failure to send the mandatory media file results in a response with the 422 status code with the request.validation-error error type.

import requests

VIRTUAL_APPLIANCE_ADDRESS = "http://<virtual-appliance-address>:8000" # Replace with your address
TECHNOLOGY_NAME = "emotion-recognition" # Replace with your technology endpoint
MEDIA_FILE_BASED_ENDPOINT_URL = f"{VIRTUAL_APPLIANCE_ADDRESS}/api/technology/{TECHNOLOGY_NAME}"

start_task_response = requests.post(
url=MEDIA_FILE_BASED_ENDPOINT_URL,
)

print(start_task_response.status_code) # Should print '422'

The error looks as follows:

{
"type": "request.validation-error",
"message": "Request validation error.",
"detail": [
{
"location": ["body", "file"],
"message": "Field required",
"type": "missing"
}
]
}

Adding the mandatory media file resolves the issue and results in a 202 status code, as is shown in the section Creating task with media file on input and in the Full Python code example.

Handling errors during task processing​

If an error occurs during task processing, due to an error that can be discovered only during processing, the task state becomes failed or rejected. Since the error object is tied to the task, it remains available in the error field and stays in memory until the task expires.

Requesting invalid language of transcription results in an error during processing. In this case, the task is initially created and scheduled for processing.

import requests

VIRTUAL_APPLIANCE_ADDRESS = "http://<virtual-appliance-address>:8000" # Replace with your address
TECHNOLOGY_NAME = "speech-to-text" # Replace with your technology endpoint
MEDIA_FILE_BASED_ENDPOINT_URL= f"{VIRTUAL_APPLIANCE_ADDRESS}/api/technology/{TECHNOLOGY_NAME}"

audio_path = "Barbara.wav" # Replace with your audio file
params = {
"language": "xx", # Using invalid language code
}

with open(audio_path, mode="rb") as file:
files = {"file": file}
start_task_response = requests.post(
url=MEDIA_FILE_BASED_ENDPOINT_URL,
files={"file": file},
params=params,
)
print(start_task_response.status_code) # Should print '202'

When you start polling for the task result, you receive task with rejected state and error field containing error details. In this example, the response looks as follows:

{
"task": {
"task_id": "b19d343a-da23-4a81-9dfb-c66765cc4e0c",
"state": "rejected"
},
"error": {
"type": "task.validation-error",
"message": "Language xx is not available."
}
}

Updating the invalid language code to a valid one, for example en, and repeating the request results in a successful task processing without errors.

Full Python code​

Here is a complete working example that creates two tasks, one with a media file and one with voiceprints. Then, it polls for their results. Task deletion is omitted, because it is an optional step to use when needed. The code is organized into functions for clarity and reusability.

import json
import requests
import time

VIRTUAL_APPLIANCE_ADDRESS = "http://<virtual-appliance-address>:8000" # Replace with your address

# Endpoint for media file based technology
MEDIA_FILE_BASED_TECHNOLOGY_NAME = "emotion-recognition" # Replace with your technology endpoint
MEDIA_FILE_BASED_ENDPOINT_URL = f"{VIRTUAL_APPLIANCE_ADDRESS}/api/technology/{MEDIA_FILE_BASED_TECHNOLOGY_NAME}"

# Endpoint for voiceprint based technology
VOICEPRINT_BASED_TECHNOLOGY_NAME = "gender-identification-voiceprints" # Replace with your technology endpoint
VOICEPRINT_BASED_ENDPOINT_URL = f"{VIRTUAL_APPLIANCE_ADDRESS}/api/technology/{VOICEPRINT_BASED_TECHNOLOGY_NAME}"


def poll_result(polling_url, polling_interval=5):
"""Poll the task endpoint until processing completes."""
while True:
polling_task_response = requests.get(polling_url)
polling_task_response .raise_for_status()
polling_task_response_json = polling_task_response .json()
task_state = polling_task_response_json["task"]["state"]
if task_state in {"done", "failed", "rejected", "cancelled"}:
break
time.sleep(polling_interval)
return polling_task_response


def run_media_based_task(audio_path, params=None, config=None):
"""Create a media-based task and wait for results."""
if params is None:
params = {}
if config is None:
config = {}

with open(audio_path, mode="rb") as file:
files = {"file": file}
start_task_response = requests.post(
url=MEDIA_FILE_BASED_ENDPOINT_URL,
files=files,
params=params,
data={"config": json.dumps(config)},
)
start_task_response.raise_for_status()
polling_url = start_task_response.headers["Location"]
task_result = poll_result(polling_url)
return task_result.json()


def run_voiceprint_based_task(json_payload):
"""Create a voiceprint-based task and wait for results."""
start_task_response = requests.post(
url=VOICEPRINT_BASED_ENDPOINT_URL,
json=json_payload,
)
start_task_response.raise_for_status()
polling_url = start_task_response.headers["Location"]
task_result = poll_result(polling_url)
return task_result.json()


audio_path = "Barbara.wav" # Replace with your audio file
params = {} # Add query parameters if needed
config = {} # Add configuration parameters if needed

print(f"Creating task for file: {audio_path}.")
media_file_based_task = run_media_based_task(audio_path, params=params, config=config)
media_file_based_task_result = media_file_based_task["result"]
print(json.dumps(media_file_based_task_result, indent=2))

voiceprint_files = ["Harry.vp", "Julia.vp"]

print(f"Creating task for voiceprints: {voiceprint_files}.")

voiceprints = []
for voiceprint_file in voiceprint_files:
with open(voiceprint_file) as f:
voiceprints.append(f.read())

# Adjust payload based on the requirements of individual technologies
voiceprint_based_task = run_voiceprint_based_task(
{"voiceprints": voiceprints}
)
voiceprint_based_task_result = voiceprint_based_task["result"]
print(json.dumps(voiceprint_based_task_result, indent=2))