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

Inherits:
Task
  • 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 Attribute Summary

Attributes inherited from Task

#function

Instance Method Summary collapse

Constructor Details

#initialize(fn, options = {}) ⇒ LLM::Function::Fork::Task

Parameters:

Options Hash (options):



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

def initialize(fn, options = {})
  super
  @tracer = options.fetch(:tracer, nil)
  @spawned = false
  @waited = false
end

Instance Method Details

#alive?Boolean

Returns:

  • (Boolean)


38
39
40
41
42
43
44
45
46
# File 'lib/llm/function/fork/task.rb', line 38

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

#group_classClass

Returns:

  • (Class)


78
79
80
# File 'lib/llm/function/fork/task.rb', line 78

def group_class
  LLM::Function::Fork::Group
end

#interrupt!nil Also known as: cancel!

Returns:

  • (nil)


50
51
52
53
54
55
56
# File 'lib/llm/function/fork/task.rb', line 50

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
27
28
29
30
31
32
33
34
# File 'lib/llm/function/fork/task.rb', line 22

def spawn
  @span = @tracer&.on_tool_start(
    id: @function.id, name: @function.name,
    arguments: @function.arguments, model: @function.model
  )
  @ch = LLM::Object.from(
    control: xchan(:marshal),
    result: xchan(:marshal, sock: Socket::SOCK_STREAM)
  )
  @pid = Kernel.fork { Fork::Job.new(@function, @ch).call }
  @spawned = true
  self
end

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



61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/llm/function/fork/task.rb', line 61

def wait
  spawn unless @spawned
  kind, data = @ch.result.recv
  raise LLM::Interrupt if kind == :interrupt
  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