Class: Anthropic::Helpers::Threads::BetaMessageThread

Inherits:
Object
  • Object
show all
Defined in:
lib/anthropic/helpers/threads/beta_message_thread.rb,
sig/anthropic/helpers/threads/beta_message_thread.rbs

Overview

A conversation that the API keeps between requests, so that each turn sends only the messages that are new. Create one with client.beta.messages.thread(...).

A thread runs one turn at a time and is not safe for concurrent use.

Instance Method Summary collapse

Constructor Details

#initialize(client, params:, unsupported_request_behavior: :error) ⇒ BetaMessageThread

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a new instance of BetaMessageThread.

Parameters:

  • client (Anthropic::Client)
  • params (Hash{Symbol=>Object}) —

    the fields of create, with messages as the seed

  • unsupported_request_behavior (Symbol) (defaults to: :error) —

    :error or :continue_unthreaded



315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
# File 'lib/anthropic/helpers/threads/beta_message_thread.rb', line 315

def initialize(client, params:, unsupported_request_behavior: :error)
  unless UNSUPPORTED_REQUEST_BEHAVIORS.include?(unsupported_request_behavior)
    raise ArgumentError.new(
      "`unsupported_request_behavior` must be `:error` or `:continue_unthreaded`, " \
      "got #{unsupported_request_behavior.inspect}"
    )
  end

  @client = client
  @unsupported_request_behavior = unsupported_request_behavior
  @fields, @request_options = split_params(params)
  @history = @fields.delete(:messages).to_a.map { Entry.given(_1) }
  @anchor = Create.new
  # The index in the history at which the reply of the turn in progress goes, `nil` when none is.
  @turn = nil
  # How many of the messages before that index were passed to the call that started the turn.
  @passed = 0
end

Instance Method Details

#append(*messages) ⇒ void

This method returns an undefined value.

Stages messages for the next turn without sending them.



97
98
99
100
# File 'lib/anthropic/helpers/threads/beta_message_thread.rb', line 97

def append(*messages)
  messages.each { @history << Entry.given(_1) unless repeats_last_reply?(_1) }
  nil
end

#appended_after(count) ⇒ Array<Hash{Symbol=>Object}>

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

The messages after the first count and after the reply to those, if one was recorded. As in #append, the last reply appended again does not count.

Parameters:

  • count (Integer)

Returns:

  • (Array<Hash{Symbol=>Object}>)


219
220
221
222
223
224
# File 'lib/anthropic/helpers/threads/beta_message_thread.rb', line 219

def appended_after(count)
  rest = @history.drop(count)
  rest.shift unless rest.first&.reply_id.nil?
  last_reply = @history.first(count).reverse_each.find { _1.param[:role].to_s == "assistant" }
  rest.reject { _1.wire == last_reply&.wire }.map(&:param)
end

#check_create_only_fields!(params) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

A continue leaves out system and tools, so the API cannot reject a change.

Parameters:

  • params (Hash{Symbol=>Object})

Raises:



246
247
248
# File 'lib/anthropic/helpers/threads/beta_message_thread.rb', line 246

def check_create_only_fields!(params)
  refuse_change!(create_only_fields(wire_request(params.slice(:system, :system_, :tools)).first))
end

#end_turn ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Ends the turn in progress, if any, with no reply. The thread takes back the messages that were passed to the call.



303
304
305
306
# File 'lib/anthropic/helpers/threads/beta_message_thread.rb', line 303

def end_turn
  @history.slice!(@turn - @passed, @passed) unless @turn.nil?
  @turn = nil
end

#fork ⇒ Anthropic::Helpers::Threads::BetaMessageThread

Returns a new, independent thread with this thread's history and request fields. It sends no request.



123
# File 'lib/anthropic/helpers/threads/beta_message_thread.rb', line 123

def fork = dup.tap(&:start_new_thread)

#messages ⇒ Array<Hash{Symbol=>Object}>

The whole history: every message that was sent, every reply, and the messages staged for the next turn.

Returns:

  • (Array<Hash{Symbol=>Object}>) —

    frozen



75
# File 'lib/anthropic/helpers/threads/beta_message_thread.rb', line 75

def messages = @history.map(&:param).freeze

#params ⇒ Hash{Symbol=>Object}

What client.beta.messages.thread takes to create a thread that behaves the same, with messages set to the whole history.

Returns:

  • (Hash{Symbol=>Object}) —

    a frozen copy



86
87
88
89
90
# File 'lib/anthropic/helpers/threads/beta_message_thread.rb', line 86

def params
  options = @request_options.empty? ? {} : {request_options: @request_options}
  given = {**@fields, **options, unsupported_request_behavior: @unsupported_request_behavior}
  Anthropic::Internal::Util.deep_frozen_copy(given).merge(messages:).freeze
end

#previous_message_id ⇒ String?

The reply the next turn continues from, or nil when the next turn starts a new thread.

Returns:

  • (String, nil)


80
# File 'lib/anthropic/helpers/threads/beta_message_thread.rb', line 80

def previous_message_id = @anchor.is_a?(Continue) ? @anchor.previous_message_id : nil

#record_partial_reply(reply) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Ends a turn whose stream ended after message_start and before message_stop. The API holds either the whole reply or none of it, so the next turn starts a new thread.

Parameters:



291
292
293
294
295
# File 'lib/anthropic/helpers/threads/beta_message_thread.rb', line 291

def record_partial_reply(reply)
  @history.insert(@turn, Entry.received(reply, partial: true)) unless reply.nil?
  start_new_thread
  @turn = nil
end

#record_reply(request, reply) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Ends the turn in progress with reply, from which the next turn continues. The API may hold a refused turn, which a continue cannot remove, so such a turn ends with no reply and the next turn starts a new thread.

Parameters:



261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# File 'lib/anthropic/helpers/threads/beta_message_thread.rb', line 261

def record_reply(request, reply)
  if reply.stop_reason == Anthropic::Models::Beta::BetaStopReason::REFUSAL
    start_new_thread
    return end_turn
  end

  @history.insert(@turn, Entry.received(reply))
  unless @anchor.is_a?(Unthreaded)
    @anchor = Continue.new(
      previous_message_id: reply.id,
      created_with: request.created_with,
      after_not_found: @anchor.is_a?(Create) && @anchor.after_not_found
    )
    # What the turn that created the thread sent is the thread's from then on.
    @fields = {**@fields.except(:system_, :tools), **request.create_only}
    # A thread keeps one model, so the API does not hold a reply that a fallback model wrote.
    start_new_thread if reply.usage.iterations.to_a.any? { _1 in {type: :fallback_message} }
  end
  adopt_container(reply)
  @turn = nil
end

#replace_params(params) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Replaces the request fields, the request options and the history. messages that begin with the recorded messages keep the thread, and the rest is staged. Any other list is staged as a whole and starts a new thread.

Parameters:

  • params (Hash{Symbol=>Object})


195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/anthropic/helpers/threads/beta_message_thread.rb', line 195

def replace_params(params)
  check_idle!
  fields, options = split_params(params)
  history = fields.delete(:messages).to_a.map { Entry.given(_1) }
  if history.first(recorded.length).map(&:wire) == recorded.map(&:wire)
    history[0, recorded.length] = recorded
  else
    start_new_thread
  end

  @fields = fields
  @request_options = options
  @history = history
  nil
end

#send_message(*messages, **params) ⇒ Anthropic::Models::Beta::BetaMessage

Sends the messages staged with #append, followed by messages, as one turn and returns the reply. params takes the keywords of #update and applies to this turn only.

Parameters:

Returns:

Raises:

  • (Anthropic::Errors::Error) —

    if another turn is in progress on this thread, or if the turn continues the thread and changes system_ or tools



153
154
155
156
157
158
159
160
161
162
163
# File 'lib/anthropic/helpers/threads/beta_message_thread.rb', line 153

def send_message(*messages, **params)
  overrides = start_turn(messages, params)
  begin
    request, reply = send_request(*overrides) { @client.beta.messages.create(_1) }
    parse_reply!(reply, request)
    record_reply(request, reply)
    reply
  ensure
    end_turn
  end
end

#start_new_thread ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Makes the next turn start a new thread with the whole history.



231
232
233
234
# File 'lib/anthropic/helpers/threads/beta_message_thread.rb', line 231

def start_new_thread
  @anchor = Create.new unless @anchor.is_a?(Unthreaded)
  nil
end

#stream(*messages, **params) ⇒ Anthropic::Streaming::MessageStream

Sends the next turn like #send_message and returns the stream of the reply. The turn is in progress until the stream ends or is closed.

Parameters:

Returns:

  • (Anthropic::Streaming::MessageStream)

Raises:

  • (Anthropic::Errors::Error) —

    if another turn is in progress on this thread, or if the turn continues the thread and changes system_ or tools



176
177
178
179
180
181
182
183
184
# File 'lib/anthropic/helpers/threads/beta_message_thread.rb', line 176

def stream(*messages, **params)
  overrides = start_turn(messages, params)
  begin
    request, raw_stream = send_request(*overrides) { @client.beta.messages.stream_raw(_1) }
    stream = Stream.new(raw_stream:, thread: self, request:)
  ensure
    end_turn if stream.nil?
  end
end

#tool_runner(max_iterations: nil) ⇒ Anthropic::Helpers::Tools::Runner

Creates a tool runner that runs over this thread. It sends no request.

Parameters:

  • max_iterations (Integer, nil) (defaults to: nil)
  • max_iterations: (Integer, nil) (defaults to: nil)

Returns:



130
131
132
133
134
135
136
137
138
139
140
# File 'lib/anthropic/helpers/threads/beta_message_thread.rb', line 130

def tool_runner(max_iterations: nil)
  # As in `#start_turn`.
  history = @history.last&.partial ? @history[...-1] : @history
  Anthropic::Helpers::Tools::Runner.new(
    @client,
    # The runner's params are those of its requests, and the thread applies its own behavior.
    params: {**params.except(:unsupported_request_behavior), messages: history.map(&:param)},
    max_iterations:,
    thread: self
  )
end

#update(**params) ⇒ void

This method returns an undefined value.

Changes the thread's request fields for every later turn, where nil removes a field. It sends no request. system_ and tools cannot change once a turn has created the thread.

Parameters:

  • params (Hash{Symbol=>Object})

Raises:

  • (ArgumentError) —

    if messages, thread or stream is given



110
111
112
113
114
115
116
117
# File 'lib/anthropic/helpers/threads/beta_message_thread.rb', line 110

def update(**params)
  fields, options = split_params(params)
  reject_key!(fields, :messages, "Use `#append` to add messages to a message thread.")

  @fields = overlay(@fields, fields)
  @request_options = overlay(@request_options, options)
  nil
end