Outputs

Outputs are the results of a service.

TL;DR

  • Define outputs using the output keyword in the service class

  • Outputs can have default values

  • Outputs can be validated by type (validated when the service succeeds)

Define Outputs

You define outputs using the output keyword in the service class.

class AI::Chat < ApplicationService
  output :messages
  output :cost
end

Write Outputs

Outputs function similarly to instance variables created with attr_accessor.

class AI::Chat < ApplicationService
  # Steps
  step :chat

  # Outputs
  output :messages
  output :cost

  private

  def chat
    self.messages = ["Hello!", "Hi, how are you?"]
    self.cost = 0.0013
  end
end

To set outputs programmatically, use the outputs.set method or hash syntax.

Type Validation

You can specify the type of output using the type option. The output type will be validated when the service successfully completes.

You can specify multiple allowed types using an array.

Type Enforcement (Enabled by Default)

By default, all outputs must have a type option. This helps catch type-related bugs early and makes your services self-documenting.

To disable type enforcement for outputs in a specific service:

See the Configuration documentation for more details.

Sorbet Runtime Types

Outputs support Sorbet runtime types for type validation:

See the Sorbet Runtime Types documentation for more details.

Default Values

Set default values for outputs using the default option. The default value will be automatically set before the execution of steps.

Removing Inherited Outputs

When inheriting from a parent service, you can remove outputs using remove_output:

What's Next?

Next, learn about context.

Next: Context

Last updated