D'autres AWS SDK exemples sont disponibles dans le GitHub dépôt AWS Doc SDK Examples
Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.
Exemples de Step Functions utilisés SDK pour Python (Boto3)
Les exemples de code suivants vous montrent comment effectuer des actions et implémenter des scénarios courants à l'aide de AWS SDK for Python (Boto3) with Step Functions.
Les principes de base sont des exemples de code qui vous montrent comment effectuer les opérations essentielles au sein d'un service.
Les actions sont des extraits de code de programmes plus larges et doivent être exécutées dans leur contexte. Alors que les actions vous montrent comment appeler des fonctions de service individuelles, vous pouvez les visualiser dans leur contexte dans leurs scénarios associés.
Les scénarios sont des exemples de code qui vous montrent comment accomplir des tâches spécifiques en appelant plusieurs fonctions au sein d'un service ou en les combinant à d'autres Services AWS.
Chaque exemple inclut un lien vers le code source complet, où vous trouverez des instructions sur la façon de configurer et d'exécuter le code en contexte.
Mise en route
Les exemples de code suivants montrent comment commencer à utiliser Step Functions.
- SDKpour Python (Boto3)
-
Note
Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS
. import boto3 def hello_stepfunctions(stepfunctions_client): """ Use the AWS SDK for Python (Boto3) to create an AWS Step Functions client and list the state machines in your account. This list might be empty if you haven't created any state machines. This example uses the default settings specified in your shared credentials and config files. :param stepfunctions_client: A Boto3 Step Functions Client object. """ print("Hello, Step Functions! Let's list up to 10 of your state machines:") state_machines = stepfunctions_client.list_state_machines(maxResults=10) for sm in state_machines["stateMachines"]: print(f"\t{sm['name']}: {sm['stateMachineArn']}") if __name__ == "__main__": hello_stepfunctions(boto3.client("stepfunctions"))
-
Pour API plus de détails, reportez-vous ListStateMachinesà la section AWS SDKpour la référence Python (Boto3). API
-
Rubriques
Principes de base
L’exemple de code suivant illustre comment :
Créez une activité.
Créez une machine à états à partir d'une définition du langage Amazon States qui contient l'activité créée précédemment en tant qu'étape.
Exécutez la machine d'état et répondez à l'activité en saisissant l'entrée de l'utilisateur.
Obtenez le statut final et le résultat une fois l'exécution terminée, puis nettoyez les ressources.
- SDKpour Python (Boto3)
-
Note
Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS
. Exécutez un scénario interactif à une invite de commande.
class StateMachineScenario: """Runs an interactive scenario that shows how to get started using Step Functions.""" def __init__(self, activity, state_machine, iam_client): """ :param activity: An object that wraps activity actions. :param state_machine: An object that wraps state machine actions. :param iam_client: A Boto3 AWS Identity and Access Management (IAM) client. """ self.activity = activity self.state_machine = state_machine self.iam_client = iam_client self.state_machine_role = None def prerequisites(self, state_machine_role_name): """ Finds or creates an IAM role that can be assumed by Step Functions. A role of this kind is required to create a state machine. The state machine used in this example does not call any additional services, so it needs no additional permissions. :param state_machine_role_name: The name of the role. :return: Data about the role. """ trust_policy = { "Version": "2012-10-17", "Statement": [ { "Sid": "", "Effect": "Allow", "Principal": {"Service": "states.amazonaws.com"}, "Action": "sts:AssumeRole", } ], } try: role = self.iam_client.get_role(RoleName=state_machine_role_name) print(f"Prerequisite IAM role {state_machine_role_name} already exists.") except ClientError as err: if err.response["Error"]["Code"] == "NoSuchEntity": role = None else: logger.error( "Couldn't get prerequisite IAM role %s. Here's why: %s: %s", state_machine_role_name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise if role is None: try: role = self.iam_client.create_role( RoleName=state_machine_role_name, AssumeRolePolicyDocument=json.dumps(trust_policy), ) except ClientError as err: logger.error( "Couldn't create prerequisite IAM role %s. Here's why: %s: %s", state_machine_role_name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise self.state_machine_role = role["Role"] def find_or_create_activity(self, activity_name): """ Finds or creates a Step Functions activity. :param activity_name: The name of the activity. :return: The Amazon Resource Name (ARN) of the activity. """ print("First, let's set up an activity and state machine.") activity_arn = self.activity.find(activity_name) if activity_arn is None: activity_arn = self.activity.create(activity_name) print( f"Activity {activity_name} created. Its Amazon Resource Name (ARN) is " f"{activity_arn}." ) else: print(f"Activity {activity_name} already exists.") return activity_arn def find_or_create_state_machine( self, state_machine_name, activity_arn, state_machine_file ): """ Finds or creates a Step Functions state machine. :param state_machine_name: The name of the state machine. :param activity_arn: The ARN of an activity that is used as a step in the state machine. This ARN is injected into the state machine definition that's used to create the state machine. :param state_machine_file: The path to a file containing the state machine definition. :return: The ARN of the state machine. """ state_machine_arn = self.state_machine.find(state_machine_name) if state_machine_arn is None: with open(state_machine_file) as state_machine_file: state_machine_def = state_machine_file.read().replace( "{{DOC_EXAMPLE_ACTIVITY_ARN}}", activity_arn ) state_machine_arn = self.state_machine.create( state_machine_name, state_machine_def, self.state_machine_role["Arn"], ) print(f"State machine {state_machine_name} created.") else: print(f"State machine {state_machine_name} already exists.") print("-" * 88) print(f"Here's some information about state machine {state_machine_name}:") state_machine_info = self.state_machine.describe(state_machine_arn) for field in ["name", "status", "stateMachineArn", "roleArn"]: print(f"\t{field}: {state_machine_info[field]}") return state_machine_arn def run_state_machine(self, state_machine_arn, activity_arn): """ Run the state machine. The state machine used in this example is a simple chat simulation. It contains an activity step in a loop that is used for user interaction. When the state machine gets to the activity step, it waits for an external application to get task data and submit a response. This function acts as the activity application by getting task input and responding with user input. :param state_machine_arn: The ARN of the state machine. :param activity_arn: The ARN of the activity used as a step in the state machine. :return: The ARN of the run. """ print( f"Let's run the state machine. It's a simplistic, non-AI chat simulator " f"we'll call ChatSFN." ) user_name = q.ask("What should ChatSFN call you? ", q.non_empty) run_input = {"name": user_name} print("Starting state machine...") run_arn = self.state_machine.start(state_machine_arn, json.dumps(run_input)) action = None while action != "done": activity_task = self.activity.get_task(activity_arn) task_input = json.loads(activity_task["input"]) print(f"ChatSFN: {task_input['message']}") action = task_input["actions"][ q.choose("What now? ", task_input["actions"]) ] task_response = {"action": action} self.activity.send_task_success( activity_task["taskToken"], json.dumps(task_response) ) return run_arn def finish_state_machine_run(self, run_arn): """ Wait for the state machine run to finish, then print final status and output. :param run_arn: The ARN of the run to retrieve. """ print(f"Let's get the final output from the state machine:") status = "RUNNING" while status == "RUNNING": run_output = self.state_machine.describe_run(run_arn) status = run_output["status"] if status == "RUNNING": print( "The state machine is still running, let's wait for it to finish." ) wait(1) elif status == "SUCCEEDED": print(f"ChatSFN: {json.loads(run_output['output'])['message']}") else: print(f"Run status: {status}.") def cleanup( self, state_machine_name, state_machine_arn, activity_name, activity_arn, state_machine_role_name, ): """ Clean up resources created by this example. :param state_machine_name: The name of the state machine. :param state_machine_arn: The ARN of the state machine. :param activity_name: The name of the activity. :param activity_arn: The ARN of the activity. :param state_machine_role_name: The name of the role used by the state machine. """ if q.ask( "Do you want to delete the state machine, activity, and role created for this " "example? (y/n) ", q.is_yesno, ): self.state_machine.delete(state_machine_arn) print(f"Deleted state machine {state_machine_name}.") self.activity.delete(activity_arn) print(f"Deleted activity {activity_name}.") self.iam_client.delete_role(RoleName=state_machine_role_name) print(f"Deleted role {state_machine_role_name}.") def run_scenario(self, activity_name, state_machine_name): print("-" * 88) print("Welcome to the AWS Step Functions state machines demo.") print("-" * 88) activity_arn = self.find_or_create_activity(activity_name) state_machine_arn = self.find_or_create_state_machine( state_machine_name, activity_arn, "../../../resources/sample_files/chat_sfn_state_machine.json", ) print("-" * 88) run_arn = self.run_state_machine(state_machine_arn, activity_arn) print("-" * 88) self.finish_state_machine_run(run_arn) print("-" * 88) self.cleanup( state_machine_name, state_machine_arn, activity_name, activity_arn, self.state_machine_role["RoleName"], ) print("-" * 88) print("\nThanks for watching!") print("-" * 88) if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") try: stepfunctions_client = boto3.client("stepfunctions") iam_client = boto3.client("iam") scenario = StateMachineScenario( Activity(stepfunctions_client), StateMachine(stepfunctions_client), iam_client, ) scenario.prerequisites("doc-example-state-machine-chat") scenario.run_scenario("doc-example-activity", "doc-example-state-machine") except Exception: logging.exception("Something went wrong with the demo.")
Définissez une classe qui englobe les actions des machines à états.
class StateMachine: """Encapsulates Step Functions state machine actions.""" def __init__(self, stepfunctions_client): """ :param stepfunctions_client: A Boto3 Step Functions client. """ self.stepfunctions_client = stepfunctions_client def create(self, name, definition, role_arn): """ Creates a state machine with the specific definition. The state machine assumes the provided role before it starts a run. :param name: The name to give the state machine. :param definition: The Amazon States Language definition of the steps in the the state machine. :param role_arn: The Amazon Resource Name (ARN) of the role that is assumed by Step Functions when the state machine is run. :return: The ARN of the newly created state machine. """ try: response = self.stepfunctions_client.create_state_machine( name=name, definition=definition, roleArn=role_arn ) except ClientError as err: logger.error( "Couldn't create state machine %s. Here's why: %s: %s", name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return response["stateMachineArn"] def find(self, name): """ Find a state machine by name. This requires listing the state machines until one is found with a matching name. :param name: The name of the state machine to search for. :return: The ARN of the state machine if found; otherwise, None. """ try: paginator = self.stepfunctions_client.get_paginator("list_state_machines") for page in paginator.paginate(): for state_machine in page.get("stateMachines", []): if state_machine["name"] == name: return state_machine["stateMachineArn"] except ClientError as err: logger.error( "Couldn't list state machines. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise def describe(self, state_machine_arn): """ Get data about a state machine. :param state_machine_arn: The ARN of the state machine to look up. :return: The retrieved state machine data. """ try: response = self.stepfunctions_client.describe_state_machine( stateMachineArn=state_machine_arn ) except ClientError as err: logger.error( "Couldn't describe state machine %s. Here's why: %s: %s", state_machine_arn, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return response def start(self, state_machine_arn, run_input): """ Start a run of a state machine with a specified input. A run is also known as an "execution" in Step Functions. :param state_machine_arn: The ARN of the state machine to run. :param run_input: The input to the state machine, in JSON format. :return: The ARN of the run. This can be used to get information about the run, including its current status and final output. """ try: response = self.stepfunctions_client.start_execution( stateMachineArn=state_machine_arn, input=run_input ) except ClientError as err: logger.error( "Couldn't start state machine %s. Here's why: %s: %s", state_machine_arn, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return response["executionArn"] def describe_run(self, run_arn): """ Get data about a state machine run, such as its current status or final output. :param run_arn: The ARN of the run to look up. :return: The retrieved run data. """ try: response = self.stepfunctions_client.describe_execution( executionArn=run_arn ) except ClientError as err: logger.error( "Couldn't describe run %s. Here's why: %s: %s", run_arn, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return response def delete(self, state_machine_arn): """ Delete a state machine and all of its run data. :param state_machine_arn: The ARN of the state machine to delete. """ try: response = self.stepfunctions_client.delete_state_machine( stateMachineArn=state_machine_arn ) except ClientError as err: logger.error( "Couldn't delete state machine %s. Here's why: %s: %s", state_machine_arn, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return response
Définissez une classe qui englobe les actions d'activité.
class Activity: """Encapsulates Step Function activity actions.""" def __init__(self, stepfunctions_client): """ :param stepfunctions_client: A Boto3 Step Functions client. """ self.stepfunctions_client = stepfunctions_client def create(self, name): """ Create an activity. :param name: The name of the activity to create. :return: The Amazon Resource Name (ARN) of the newly created activity. """ try: response = self.stepfunctions_client.create_activity(name=name) except ClientError as err: logger.error( "Couldn't create activity %s. Here's why: %s: %s", name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return response["activityArn"] def find(self, name): """ Find an activity by name. This requires listing activities until one is found with a matching name. :param name: The name of the activity to search for. :return: If found, the ARN of the activity; otherwise, None. """ try: paginator = self.stepfunctions_client.get_paginator("list_activities") for page in paginator.paginate(): for activity in page.get("activities", []): if activity["name"] == name: return activity["activityArn"] except ClientError as err: logger.error( "Couldn't list activities. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise def get_task(self, activity_arn): """ Gets task data for an activity. When a state machine is waiting for the specified activity, a response is returned with data from the state machine. When a state machine is not waiting, this call blocks for 60 seconds. :param activity_arn: The ARN of the activity to get task data for. :return: The task data for the activity. """ try: response = self.stepfunctions_client.get_activity_task( activityArn=activity_arn ) except ClientError as err: logger.error( "Couldn't get a task for activity %s. Here's why: %s: %s", activity_arn, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return response def send_task_success(self, task_token, task_response): """ Sends a success response to a waiting activity step. A state machine with an activity step waits for the activity to get task data and then respond with either success or failure before it resumes processing. :param task_token: The token associated with the task. This is included in the response to the get_activity_task action and must be sent without modification. :param task_response: The response data from the activity. This data is received and processed by the state machine. """ try: self.stepfunctions_client.send_task_success( taskToken=task_token, output=task_response ) except ClientError as err: logger.error( "Couldn't send task success. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise def delete(self, activity_arn): """ Delete an activity. :param activity_arn: The ARN of the activity to delete. """ try: response = self.stepfunctions_client.delete_activity( activityArn=activity_arn ) except ClientError as err: logger.error( "Couldn't delete activity %s. Here's why: %s: %s", activity_arn, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return response
-
Pour API plus de détails, consultez les rubriques suivantes dans le AWS SDKdocument de référence Python (Boto3). API
-
Actions
L'exemple de code suivant montre comment utiliserCreateActivity
.
- SDKpour Python (Boto3)
-
Note
Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS
. class Activity: """Encapsulates Step Function activity actions.""" def __init__(self, stepfunctions_client): """ :param stepfunctions_client: A Boto3 Step Functions client. """ self.stepfunctions_client = stepfunctions_client def create(self, name): """ Create an activity. :param name: The name of the activity to create. :return: The Amazon Resource Name (ARN) of the newly created activity. """ try: response = self.stepfunctions_client.create_activity(name=name) except ClientError as err: logger.error( "Couldn't create activity %s. Here's why: %s: %s", name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return response["activityArn"]
-
Pour API plus de détails, reportez-vous CreateActivityà la section AWS SDKpour la référence Python (Boto3). API
-
L'exemple de code suivant montre comment utiliserCreateStateMachine
.
- SDKpour Python (Boto3)
-
Note
Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS
. class StateMachine: """Encapsulates Step Functions state machine actions.""" def __init__(self, stepfunctions_client): """ :param stepfunctions_client: A Boto3 Step Functions client. """ self.stepfunctions_client = stepfunctions_client def create(self, name, definition, role_arn): """ Creates a state machine with the specific definition. The state machine assumes the provided role before it starts a run. :param name: The name to give the state machine. :param definition: The Amazon States Language definition of the steps in the the state machine. :param role_arn: The Amazon Resource Name (ARN) of the role that is assumed by Step Functions when the state machine is run. :return: The ARN of the newly created state machine. """ try: response = self.stepfunctions_client.create_state_machine( name=name, definition=definition, roleArn=role_arn ) except ClientError as err: logger.error( "Couldn't create state machine %s. Here's why: %s: %s", name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return response["stateMachineArn"]
-
Pour API plus de détails, reportez-vous CreateStateMachineà la section AWS SDKpour la référence Python (Boto3). API
-
L'exemple de code suivant montre comment utiliserDeleteActivity
.
- SDKpour Python (Boto3)
-
Note
Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS
. class Activity: """Encapsulates Step Function activity actions.""" def __init__(self, stepfunctions_client): """ :param stepfunctions_client: A Boto3 Step Functions client. """ self.stepfunctions_client = stepfunctions_client def delete(self, activity_arn): """ Delete an activity. :param activity_arn: The ARN of the activity to delete. """ try: response = self.stepfunctions_client.delete_activity( activityArn=activity_arn ) except ClientError as err: logger.error( "Couldn't delete activity %s. Here's why: %s: %s", activity_arn, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return response
-
Pour API plus de détails, reportez-vous DeleteActivityà la section AWS SDKpour la référence Python (Boto3). API
-
L'exemple de code suivant montre comment utiliserDeleteStateMachine
.
- SDKpour Python (Boto3)
-
Note
Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS
. class StateMachine: """Encapsulates Step Functions state machine actions.""" def __init__(self, stepfunctions_client): """ :param stepfunctions_client: A Boto3 Step Functions client. """ self.stepfunctions_client = stepfunctions_client def delete(self, state_machine_arn): """ Delete a state machine and all of its run data. :param state_machine_arn: The ARN of the state machine to delete. """ try: response = self.stepfunctions_client.delete_state_machine( stateMachineArn=state_machine_arn ) except ClientError as err: logger.error( "Couldn't delete state machine %s. Here's why: %s: %s", state_machine_arn, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return response
-
Pour API plus de détails, reportez-vous DeleteStateMachineà la section AWS SDKpour la référence Python (Boto3). API
-
L'exemple de code suivant montre comment utiliserDescribeExecution
.
- SDKpour Python (Boto3)
-
Note
Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS
. def describe_run(self, run_arn): """ Get data about a state machine run, such as its current status or final output. :param run_arn: The ARN of the run to look up. :return: The retrieved run data. """ try: response = self.stepfunctions_client.describe_execution( executionArn=run_arn ) except ClientError as err: logger.error( "Couldn't describe run %s. Here's why: %s: %s", run_arn, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return response
-
Pour API plus de détails, reportez-vous DescribeExecutionà la section AWS SDKpour la référence Python (Boto3). API
-
L'exemple de code suivant montre comment utiliserDescribeStateMachine
.
- SDKpour Python (Boto3)
-
Note
Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS
. class StateMachine: """Encapsulates Step Functions state machine actions.""" def __init__(self, stepfunctions_client): """ :param stepfunctions_client: A Boto3 Step Functions client. """ self.stepfunctions_client = stepfunctions_client def describe(self, state_machine_arn): """ Get data about a state machine. :param state_machine_arn: The ARN of the state machine to look up. :return: The retrieved state machine data. """ try: response = self.stepfunctions_client.describe_state_machine( stateMachineArn=state_machine_arn ) except ClientError as err: logger.error( "Couldn't describe state machine %s. Here's why: %s: %s", state_machine_arn, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return response
-
Pour API plus de détails, reportez-vous DescribeStateMachineà la section AWS SDKpour la référence Python (Boto3). API
-
L'exemple de code suivant montre comment utiliserGetActivityTask
.
- SDKpour Python (Boto3)
-
Note
Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS
. class Activity: """Encapsulates Step Function activity actions.""" def __init__(self, stepfunctions_client): """ :param stepfunctions_client: A Boto3 Step Functions client. """ self.stepfunctions_client = stepfunctions_client def get_task(self, activity_arn): """ Gets task data for an activity. When a state machine is waiting for the specified activity, a response is returned with data from the state machine. When a state machine is not waiting, this call blocks for 60 seconds. :param activity_arn: The ARN of the activity to get task data for. :return: The task data for the activity. """ try: response = self.stepfunctions_client.get_activity_task( activityArn=activity_arn ) except ClientError as err: logger.error( "Couldn't get a task for activity %s. Here's why: %s: %s", activity_arn, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return response
-
Pour API plus de détails, reportez-vous GetActivityTaskà la section AWS SDKpour la référence Python (Boto3). API
-
L'exemple de code suivant montre comment utiliserListActivities
.
- SDKpour Python (Boto3)
-
Note
Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS
. class Activity: """Encapsulates Step Function activity actions.""" def __init__(self, stepfunctions_client): """ :param stepfunctions_client: A Boto3 Step Functions client. """ self.stepfunctions_client = stepfunctions_client def find(self, name): """ Find an activity by name. This requires listing activities until one is found with a matching name. :param name: The name of the activity to search for. :return: If found, the ARN of the activity; otherwise, None. """ try: paginator = self.stepfunctions_client.get_paginator("list_activities") for page in paginator.paginate(): for activity in page.get("activities", []): if activity["name"] == name: return activity["activityArn"] except ClientError as err: logger.error( "Couldn't list activities. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise
-
Pour API plus de détails, reportez-vous ListActivitiesà la section AWS SDKpour la référence Python (Boto3). API
-
L'exemple de code suivant montre comment utiliserListStateMachines
.
- SDKpour Python (Boto3)
-
Note
Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS
. Recherchez une machine à états par son nom en effectuant une recherche dans la liste des machines à états correspondant au compte.
class StateMachine: """Encapsulates Step Functions state machine actions.""" def __init__(self, stepfunctions_client): """ :param stepfunctions_client: A Boto3 Step Functions client. """ self.stepfunctions_client = stepfunctions_client def find(self, name): """ Find a state machine by name. This requires listing the state machines until one is found with a matching name. :param name: The name of the state machine to search for. :return: The ARN of the state machine if found; otherwise, None. """ try: paginator = self.stepfunctions_client.get_paginator("list_state_machines") for page in paginator.paginate(): for state_machine in page.get("stateMachines", []): if state_machine["name"] == name: return state_machine["stateMachineArn"] except ClientError as err: logger.error( "Couldn't list state machines. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise
-
Pour API plus de détails, reportez-vous ListStateMachinesà la section AWS SDKpour la référence Python (Boto3). API
-
L'exemple de code suivant montre comment utiliserSendTaskSuccess
.
- SDKpour Python (Boto3)
-
Note
Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS
. class Activity: """Encapsulates Step Function activity actions.""" def __init__(self, stepfunctions_client): """ :param stepfunctions_client: A Boto3 Step Functions client. """ self.stepfunctions_client = stepfunctions_client def send_task_success(self, task_token, task_response): """ Sends a success response to a waiting activity step. A state machine with an activity step waits for the activity to get task data and then respond with either success or failure before it resumes processing. :param task_token: The token associated with the task. This is included in the response to the get_activity_task action and must be sent without modification. :param task_response: The response data from the activity. This data is received and processed by the state machine. """ try: self.stepfunctions_client.send_task_success( taskToken=task_token, output=task_response ) except ClientError as err: logger.error( "Couldn't send task success. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise
-
Pour API plus de détails, reportez-vous SendTaskSuccessà la section AWS SDKpour la référence Python (Boto3). API
-
L'exemple de code suivant montre comment utiliserStartExecution
.
- SDKpour Python (Boto3)
-
Note
Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS
. class StateMachine: """Encapsulates Step Functions state machine actions.""" def __init__(self, stepfunctions_client): """ :param stepfunctions_client: A Boto3 Step Functions client. """ self.stepfunctions_client = stepfunctions_client def start(self, state_machine_arn, run_input): """ Start a run of a state machine with a specified input. A run is also known as an "execution" in Step Functions. :param state_machine_arn: The ARN of the state machine to run. :param run_input: The input to the state machine, in JSON format. :return: The ARN of the run. This can be used to get information about the run, including its current status and final output. """ try: response = self.stepfunctions_client.start_execution( stateMachineArn=state_machine_arn, input=run_input ) except ClientError as err: logger.error( "Couldn't start state machine %s. Here's why: %s: %s", state_machine_arn, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return response["executionArn"]
-
Pour API plus de détails, reportez-vous StartExecutionà la section AWS SDKpour la référence Python (Boto3). API
-
Scénarios
L'exemple de code suivant montre comment créer une application de AWS Step Functions messagerie qui extrait les enregistrements de messages d'une table de base de données.
- SDKpour Python (Boto3)
-
Montre comment utiliser le AWS SDK for Python (Boto3) with AWS Step Functions pour créer une application de messagerie qui récupère les enregistrements de messages d'une table Amazon DynamoDB et les envoie via Amazon Simple Queue Service (Amazon). SQS La machine d'état intègre une AWS Lambda fonction permettant de scanner la base de données à la recherche de messages non envoyés.
Créez une machine d’état qui extrait et met à jour des enregistrements de message d’une table Amazon DynamoDB.
Mettez à jour la définition de la machine à états pour envoyer également des messages à Amazon Simple Queue Service (AmazonSQS).
Démarrez et arrêtez les exécutions de la machine.
Connectez-vous à Lambda, DynamoDB et SQS Amazon depuis une machine à états en utilisant des intégrations de services.
Pour obtenir le code source complet et les instructions de configuration et d'exécution, consultez l'exemple complet sur GitHub
. Les services utilisés dans cet exemple
DynamoDB
Lambda
Amazon SQS
Step Functions
L'exemple de code suivant montre comment créer et orchestrer des applications d'IA génératives avec Amazon Bedrock et Step Functions.
- SDKpour Python (Boto3)
-
Le scénario Amazon Bedrock Serverless Prompt Chaining montre comment AWS Step FunctionsAmazon Bedrock https://docs.aws.amazon.com/bedrock/latest/userguide/agents.html peut être utilisé pour créer et orchestrer des applications d'IA générative complexes, sans serveur et hautement évolutives. Il contient les exemples pratiques suivants :
-
Rédigez une analyse d'un roman donné pour un blog littéraire. Cet exemple illustre une chaîne d'instructions simple et séquentielle.
-
Générez une courte histoire sur un sujet donné. Cet exemple montre comment l'IA peut traiter de manière itérative une liste d'éléments qu'elle a précédemment générée.
-
Créez un itinéraire pour un week-end de vacances vers une destination donnée. Cet exemple montre comment paralléliser plusieurs invites distinctes.
-
Présentez des idées de films à un utilisateur humain agissant en tant que producteur de films. Cet exemple montre comment paralléliser la même invite avec différents paramètres d'inférence, comment revenir à une étape précédente de la chaîne et comment inclure une entrée humaine dans le flux de travail.
-
Planifiez un repas en fonction des ingrédients que l'utilisateur a à portée de main. Cet exemple montre comment les chaînes d'appels peuvent intégrer deux conversations distinctes liées à l'IA, deux personnages de l'IA engageant un débat entre eux pour améliorer le résultat final.
-
Trouvez et résumez le GitHub référentiel le plus populaire du moment. Cet exemple illustre le chaînage de plusieurs agents d'IA qui interagissent avec des agents externesAPIs.
Pour le code source complet et les instructions de configuration et d'exécution, consultez le projet complet sur GitHub
. Les services utilisés dans cet exemple
Amazon Bedrock
Amazon Bedrock Runtime
Agents Amazon Bedrock
Temps d'exécution des agents Amazon Bedrock
Step Functions
-