Class: LLM::Function::Fork::Task

Inherits:
Object
  • Object
show all
Defined in:
lib/llm/function/fork/task.rb

Overview

The Task class wraps a fork-backed function call and exchanges control and result messages with the child process.

Instance Method Summary collapse

Constructor Details

#initialize(function, tracer: nil, span: nil) ⇒ LLM::Function::Fork::Task

Parameters:



13
14
15
16
17
18
# File 'lib/llm/function/fork/task.rb', line 13

def initialize(function, tracer: nil, span: nil)
  @function = function
  @tracer = tracer
  @span = span
  @waited = false
end

Instance Method Details

#alive?Boolean

Returns:

  • (Boolean)


30
31
32
33
34
35
36
37
38
# File 'lib/llm/function/fork/task.rb', line 30

def alive?
  return false if @waited
  result = ::Process.waitpid(@pid, ::Process::WNOHANG)
  @waited = !result.nil?
  !@waited
rescue Errno::ECHILD
  @waited = true
  false
end

#interrupt!nil Also known as: cancel!

Returns:

  • (nil)


42
43
44
45
46
47
48
# File 'lib/llm/function/fork/task.rb', line 42

def interrupt!
  return nil if @waited
  @ch.control.write(:interrupt)
  nil
rescue Errno::ESRCH, IOError
  nil
end

#spawnLLM::Function::Fork::Task



22
23
24
25
26
# File 'lib/llm/function/fork/task.rb', line 22

def spawn
  @ch = LLM::Object.from(control: xchan(:marshal), result: xchan(:marshal))
  @pid = Kernel.fork { Fork::Job.new(@function, @ch).call }
  self
end

#waitLLM::Function::Return Also known as: value



53
54
55
56
57
58
59
60
61
62
63
# File 'lib/llm/function/fork/task.rb', line 53

def wait
  kind, data = @ch.result.recv
  raise ArgumentError, "Unknown fork message: #{kind.inspect}" unless kind == :result
  result = Return.new(data[:id], data[:name], data[:value])
  reap
  @tracer&.on_tool_finish(result:, span: @span)
  result
ensure
  reap
  [@ch.control, @ch.result].each { _1.close unless _1.closed? }
end