Class: OpenAI::Responses::Session

Inherits:
Object
  • Object
show all
Includes:
WebSocket::Protocol
Defined in:
lib/openai/helpers/responses_websocket/session.rb

Overview

Owns one connection and one Async reader. Use only its lanes to receive.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(task:, client:, limits:, request_options:, websocket_base_url:, transport:, transport_options:) ⇒ Session

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 Session.



439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
# File 'lib/openai/helpers/responses_websocket/session.rb', line 439

def initialize(task:, client:, limits:, request_options:, websocket_base_url:, transport:, transport_options:)
  @task = task
  @client = client
  @limits = limits
  @request_options = request_options
  @websocket_base_url = websocket_base_url
  @transport = transport
  @transport_options = transport_options
  @owner = Thread.current
  @lanes = {}
  @lane_ids = {}
  # Steering targets a response ID, independently of the lane sending the command.
  @pending_steers = {}
  @events = 0
  @bytes = 0
  @closed = false
  @default = lane(nil)
end

Instance Attribute Details

#default ⇒ Object (readonly)

Returns the value of attribute default.



393
394
395
# File 'lib/openai/helpers/responses_websocket/session.rb', line 393

def default
  @default
end

#limits ⇒ Object (readonly)

Returns the value of attribute limits.



393
394
395
# File 'lib/openai/helpers/responses_websocket/session.rb', line 393

def limits
  @limits
end

Class Method Details

.open(client:, limits:, request_options: nil, websocket_base_url: nil, transport: nil, transport_options: {}) ⇒ Object

Raises:

  • (ArgumentError)


395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
# File 'lib/openai/helpers/responses_websocket/session.rb', line 395

def self.open(
  client:,
  limits:,
  request_options: nil,
  websocket_base_url: nil,
  transport: nil,
  transport_options: {}
)
  raise ArgumentError, "A block is required to open a Responses session." unless block_given?

  begin
    require "async"
    require "async/queue"
    require "async/condition"

  rescue LoadError
    raise OpenAI::Errors::Error, "Responses sessions require the async gem.", cause: nil
  end

  Sync do |task|
    session = new(
      task: task,
      client: client,
      limits: limits,
      request_options: request_options,
      websocket_base_url: websocket_base_url,
      transport: transport,
      transport_options: transport_options
    )
    begin
      session.start
      yield(session)
    ensure
      pending_error = $ERROR_INFO
      begin
        session.close
      rescue StandardError
        raise if pending_error.nil?
      end
    end
  end
end

Instance Method Details

#assert_owner! ⇒ 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.

Raises:



590
591
592
# File 'lib/openai/helpers/responses_websocket/session.rb', line 590

def assert_owner!
  raise SessionError, "Responses sessions are single-thread owned." unless Thread.current.equal?(@owner)
end

#check_reader! ⇒ 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.

Raises:

  • (@error)


584
585
586
587
# File 'lib/openai/helpers/responses_websocket/session.rb', line 584

def check_reader!
  raise @error if @error
  raise SessionError, "The Responses connection closed before another event arrived." if @closed || @ended
end

#close ⇒ Object



507
508
509
510
511
512
513
514
515
516
517
518
# File 'lib/openai/helpers/responses_websocket/session.rb', line 507

def close
  assert_owner!
  return if @closed

  @closed = true
  stop_reader
  @lanes.each_value(&:discard)
  @lanes.clear
  @lane_ids.clear
  @pending_steers.clear
  nil
end

#consumed(bytes) ⇒ 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.



595
596
597
598
# File 'lib/openai/helpers/responses_websocket/session.rb', line 595

def consumed(bytes)
  @events -= 1
  @bytes -= bytes
end

#detach(value) ⇒ 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.



601
602
603
604
# File 'lib/openai/helpers/responses_websocket/session.rb', line 601

def detach(value)
  @lanes.delete(value.stream_id) if @lanes[value.stream_id].equal?(value)
  value.discard
end

#encode_client_event(event) ⇒ 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.



558
559
560
561
# File 'lib/openai/helpers/responses_websocket/session.rb', line 558

def encode_client_event(event)
  assert_owner!
  @connection.encode_client_event(event)
end

#lane(stream_id) ⇒ Object

Raises:



458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
# File 'lib/openai/helpers/responses_websocket/session.rb', line 458

def lane(stream_id)
  assert_owner!
  raise SessionError, "The Responses session is closed." if @closed

  unless stream_id.nil? || (stream_id.is_a?(String) && /\A[A-Za-z0-9_.-]{1,256}\z/.match?(stream_id))
    raise ArgumentError, "Invalid Responses WebSocket stream ID."
  end

  stream_id = stream_id&.dup&.freeze
  raise ArgumentError, "The Responses lane is already registered." if @lane_ids.key?(stream_id)
  raise BufferError, "The Responses session exceeded max_lanes." if @lane_ids.length >= @limits.max_lanes

  value = SessionLane.new(self, stream_id, @pending_steers)
  @lane_ids[stream_id] = true
  @lanes[stream_id] = value
end

#reconnect(restore:, client: @client, request_options: @request_options) ⇒ Object

Replace the transport explicitly; old lane state is lost, never replayed. The restore callback registers new lanes and supplies application state.

Raises:



477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
# File 'lib/openai/helpers/responses_websocket/session.rb', line 477

def reconnect(restore:, client: @client, request_options: @request_options)
  assert_owner!
  raise SessionError, "The Responses session is closed." if @closed
  raise SessionError, "The Responses session is already reconnecting." if @reconnecting

  @reconnecting = true
  restored = false
  begin
    @lanes.each_value { |value|
      value.discard(
        StateLostError.new("The Responses connection was replaced; restore application state explicitly.")
      )
    }
    stop_reader
    @lanes.clear
    @lane_ids.clear
    @pending_steers.clear
    @default = lane(nil)
    @client = client
    @request_options = request_options
    start
    restore.call(self)
    restored = true
    self
  ensure
    close unless restored
    @reconnecting = false
  end
end

#send_event(event) ⇒ 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.



564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
# File 'lib/openai/helpers/responses_websocket/session.rb', line 564

def send_event(event)
  assert_owner!
  check_reader!
  prior_raw_command_sent = @raw_command_sent
  @raw_command_sent = true unless event[:type].to_s == "response.create"
  @connection.send_event(event)
rescue OpenAI::Errors::ResponsesClientEventError
  @raw_command_sent = prior_raw_command_sent
  raise
rescue OpenAI::Errors::ResponsesSendError => error
  @error = error
  raise
ensure
  if @connection.poisoned?
    @error ||= OpenAI::Errors::ResponsesSendError.new(url: @connection.url)
    stop_reader
  end
end

#start ⇒ 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.



521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
# File 'lib/openai/helpers/responses_websocket/session.rb', line 521

def start
  @ended = false
  @error = nil
  @raw_command_sent = false
  generation = @generation = Object.new
  ready = Async::Queue.new
  opened = false
  @reader = @task.async do
    begin
      @client
        .responses
        .connect(
          request_options: @request_options,
          websocket_base_url: @websocket_base_url,
          transport: @transport,
          transport_options: @transport_options
        ) do |connection|
          @connection = connection
          opened = true
          ready.enqueue(true)
          connection.each { |event| dispatch(event) }
        end

    rescue StandardError => error
      @error = error if @generation.equal?(generation)
    ensure
      @ended = true if @generation.equal?(generation)
      ready.enqueue(false) unless opened
      @lanes.each_value(&:wake)
    end
  end

  raise @error || SessionError.new("The Responses connection did not open.") unless ready.dequeue
  nil
end