Class: LittleGhost::Workflow::Invocation

Inherits:
Object
  • Object
show all
Defined in:
lib/little_ghost/workflow.rb

Overview

Hold one lazy agent call inside a workflow composition. Workflow implementations normally use only its output method or return the object as the final invocation.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input:, history:, context:, build:, on_usage:) ⇒ Invocation

:nodoc:



58
59
60
61
62
63
64
65
66
67
# File 'lib/little_ghost/workflow.rb', line 58

def initialize(input:, history:, context:, build:, on_usage:) # :nodoc:
  @input = input
  @history = history
  @context = context
  @build = build
  @on_usage = on_usage
  @mutex = Mutex.new
  @consumed = false
  @closed = false
end

Instance Attribute Details

#resultObject (readonly)

:nodoc:



56
57
58
# File 'lib/little_ghost/workflow.rb', line 56

def result
  @result
end

Instance Method Details

#closeObject

:nodoc:



112
113
114
115
116
117
118
119
120
# File 'lib/little_ghost/workflow.rb', line 112

def close # :nodoc:
  agent = @mutex.synchronize do
    return if @closed

    @closed = true
    @agent
  end
  agent&.close
end

#consumed?Boolean

:nodoc:

Returns:

  • (Boolean)


108
109
110
# File 'lib/little_ghost/workflow.rb', line 108

def consumed? # :nodoc:
  @mutex.synchronize { @consumed }
end

#each(checkpoint: nil) ⇒ Object

:nodoc:



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/little_ghost/workflow.rb', line 69

def each(checkpoint: nil) # :nodoc:
  return enum_for(__method__, checkpoint:) unless block_given?

  agent, options = @mutex.synchronize do
    raise Error, "workflow invocation is already closed" if @closed
    raise ProtocolError, "workflow invocation was already consumed" if @consumed

    @consumed = true
    @agent, options = @build.call
    [@agent, options]
  end
  begin
    agent.stream(
      @input,
      history: @history,
      context: @context,
      **options,
      checkpoint:
    ).each do |event|
      @result = event.data[:result] if event.type == :invocation_stop
      @usage = event.data[:usage] if event.type == :invocation_error
      yield event
    end
  ensure
    report_usage if @intermediate
    close
  end
end

#outputObject

Consumes this invocation when necessary and returns RunResult#output.

A structured agent returns its validated value; an ordinary agent returns response text. Intermediate usage is recorded for the workflow total.



102
103
104
105
106
# File 'lib/little_ghost/workflow.rb', line 102

def output
  @intermediate = true
  each {} unless consumed?
  result&.output
end