Skip to content
Kward Search API index

Class: Kward::PluginCodexResponses

Inherits:
Object
  • Object
show all
Defined in:
lib/kward/plugins/codex_responses.rb

Overview

Adapts Kward's normal Codex provider stream to the plugin Responses event contract without exposing the configured credentials.

Defined Under Namespace

Classes: AuthenticationError, RequestError

Instance Method Summary collapse

Constructor Details

#initialize(client: Kward::Client.new) ⇒ PluginCodexResponses

Returns a new instance of PluginCodexResponses.



19
20
21
# File 'lib/kward/plugins/codex_responses.rb', line 19

def initialize(client: Kward::Client.new)
  @client = client
end

Instance Method Details

#stream(model:, input:, instructions: nil, text: nil, max_output_tokens: nil, cancellation: nil) ⇒ Object

Streams Kward Codex events using the normal configured Codex credentials and endpoint, translating them to Responses-shaped events for plugins.



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/kward/plugins/codex_responses.rb', line 25

def stream(model:, input:, instructions: nil, text: nil, max_output_tokens: nil, cancellation: nil)
  messages = input_messages(input, instructions)
  output_text = +""
  emit_text = lambda do |delta|
    next unless delta.is_a?(String) && !delta.empty?

    output_text << delta
    yield "type" => "response.output_text.delta", "delta" => delta
  end

  result = @client.chat(
    messages,
    provider: "codex",
    provider_required: true,
    model: model,
    max_tokens: max_output_tokens,
    text_format: text,
    cancellation: cancellation,
    on_assistant_delta: emit_text
  )
  emit_text.call(result["content"]) if output_text.empty? && result["content"].is_a?(String)
  yield "type" => "response.completed", "response" => { "id" => "codex-#{SecureRandom.hex(12)}", "usage" => result["usage"] }
  nil
rescue Kward::Client::AuthenticationError => error
  raise AuthenticationError, error.message
rescue Kward::Client::RequestError => error
  raise RequestError, error.code
end