Class: RubyLLM::AiSdk::Request

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby_llm/ai_sdk/request.rb

Overview

The body useChat posts on every turn: the chat id and the full list of UI messages. A Request reads the two things the server acts on, the last user message and the approval decisions on the last assistant message.

request = RubyLLM::AiSdk::Request.parse(request.raw_post)
request.text      # => "Refund order 42"
request.approvals # => []

Defined Under Namespace

Classes: Approval

Constant Summary collapse

DATA_URL =

:nodoc:

%r{\Adata:[^,]*;base64,(?<data>.*)\z}m

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(body) ⇒ Request

Returns a new instance of Request.



36
37
38
39
# File 'lib/ruby_llm/ai_sdk/request.rb', line 36

def initialize(body)
  @id = body['id']
  @messages = body.fetch('messages', [])
end

Instance Attribute Details

#id ⇒ Object (readonly)

The chat id useChat was created with.



26
27
28
# File 'lib/ruby_llm/ai_sdk/request.rb', line 26

def id
  @id
end

#messages ⇒ Object (readonly)

The UI messages as posted, an array of Hashes.



29
30
31
# File 'lib/ruby_llm/ai_sdk/request.rb', line 29

def messages
  @messages
end

Class Method Details

.parse(body) ⇒ Object

Returns a Request parsed from a JSON body.



32
33
34
# File 'lib/ruby_llm/ai_sdk/request.rb', line 32

def self.parse(body)
  new(JSON.parse(body))
end

Instance Method Details

#approvals ⇒ Object

Returns the Approval decisions recorded on the last assistant message, an empty array when there are none.



65
66
67
68
69
70
71
# File 'lib/ruby_llm/ai_sdk/request.rb', line 65

def approvals
  return [] unless last_message&.fetch('role', nil) == 'assistant'

  parts_where('state' => 'approval-responded').map do |part|
    Approval.new(tool_call_id: part['toolCallId'], approved: part.dig('approval', 'approved'))
  end
end

#files ⇒ Object

Returns the files attached to the last user message as sources Chat#ask accepts with with:. Hosted files come through as their URL; data URLs are decoded into an Attachment with the file's name.



57
58
59
60
61
# File 'lib/ruby_llm/ai_sdk/request.rb', line 57

def files
  return [] unless last_message&.fetch('role', nil) == 'user'

  parts_of_type('file').map { |part| file_source(part) }
end

#message_id ⇒ Object

Returns the id of the last message, or nil when there is none.



42
43
44
# File 'lib/ruby_llm/ai_sdk/request.rb', line 42

def message_id
  last_message&.fetch('id', nil)
end

#text ⇒ Object

Returns the text of the last message when it comes from the user, with its text parts joined by newlines, or nil otherwise.



48
49
50
51
52
# File 'lib/ruby_llm/ai_sdk/request.rb', line 48

def text
  return unless last_message&.fetch('role', nil) == 'user'

  parts_of_type('text').map { |part| part['text'] }.join("\n")
end