Understanding Workflow Context

Every step in a Sample Workflow has access to a context object (ctx) that provides essential information and utilities for the current workflow run. This context allows steps to communicate with each other, access user information, and interact with the backend system.

The WorkflowRunContext Class

The workflow context is implemented through the WorkflowRunContext class, which provides the following key capabilities:

Properties

  • backend_token: Authentication token for making API calls to the SampleHC backend
  • current_user: Information about the user who initiated the workflow (dict with name and email fields)
  • resume_data: Data used when resuming a suspended workflow
  • scope: Additional scoped data for the step that you’re on. For example, loops will have i and item in scope.

Key Methods

get_step_result(step_id: str)

Retrieves the output from a previous step in the workflow by its step ID.

# Example: Get the result from a previous step
previous_result = ctx.get_step_result("document-upload")
documents = previous_result["documents"]

This method is essential for passing data between workflow steps, allowing later steps to build upon the results of earlier ones.

get_start_data()

Retrieves the initial data that was provided when the workflow was started.

# Example: Access the initial workflow data
start_data = ctx.get_start_data()
initial_params = start_data.get("params", {})

Using Context in Workflow Steps

In Automated Steps

def process_documents(ctx):
    # Access previous step results
    uploaded_docs = ctx.get_step_result("upload-step")

    # Access user information
    user_name = ctx.current_user["name"]
    user_email = ctx.current_user["email"]

    # Process the documents
    processed_docs = []
    for doc in uploaded_docs["documents"]:
        # Your processing logic here
        processed_docs.append(process_single_doc(doc))

    return {"processed_documents": processed_docs}

workflow.then(
    Step("process-docs", process_documents)
)

Best Practices

  1. Step ID Consistency: Use clear, descriptive step IDs that make it easy to reference them in later steps.

  2. Data Validation: Ensure the output is what you expect from previous steps before using it.

  3. Context Security: The context includes authentication tokens, so be careful when logging or exposing context data.