elelem-openai 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 6c4b0c206227c277a16be4e7844d33904b52cd8a757d628b0ce459d1f8126174
4
- data.tar.gz: ca4edfcaa0e9e0e053b55a3bd6dffe4f5a095bb2c2107d301e03abc42b24571e
3
+ metadata.gz: 12b841599cd4162edf6c16828462247abb71c0c4bd0b28babf7561a7e151890f
4
+ data.tar.gz: 1837c20a048c106334cdeb7e5aa6abfd1f42e3c3f6a98a9eeb1fae5668d8a55e
5
5
  SHA512:
6
- metadata.gz: abc80c1b189c8fa86a4822c9f8c3f29d939fd72811fd4be07e9079414b8960ad226051d3ea7eb563bc807cac295f6afbaea76c3a05dbe67483eab1ae1ee563fc
7
- data.tar.gz: 3acd01b5151829c3e240da5b8d339013aea9c7a6821df0ea3580b87bd98b7038986c258cea0316c37c012620aa7738ce97a62770da18bfb0695fe67426884a2b
6
+ metadata.gz: 8849c6ee53857c9e07382907fddd1374ad499b91a7c44a4ed8e95588dcb53468b93a255c3e401c7ded9cf893119ef053f1087b8e61f79af8d557a6c5d2996712
7
+ data.tar.gz: 3cd7d032b629d725a3046221b9f0cae041aa4a18bbdb8906492fd299975aa93890a2c9dfa03363ce81468f4709db7f923fbe5fbd0a5950e978462aab661870e5
@@ -1,3 +1,3 @@
1
1
  {
2
- ".": "0.4.0"
2
+ ".": "0.5.0"
3
3
  }
data/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.5.0](https://github.com/elelem-sh/openai/compare/v0.4.0...v0.5.0) (2026-11-20)
4
+
5
+
6
+ ### Features
7
+
8
+ * take the key from OPENAI_API_KEY_COMMAND, and run it again on a 401 before one retry ([c9587db](https://github.com/elelem-sh/openai/commit/c9587db68bc3d076aec4887265b2fae969f6f610))
9
+
10
+
11
+ ### Bug Fixes
12
+
13
+ * run OPENAI_API_KEY_COMMAND at the first request, fail on a non-zero exit with its stderr, and name both variables when no key is set ([9d915c5](https://github.com/elelem-sh/openai/commit/9d915c5ade00a4154722512f03f6f14b92c1f336))
14
+
3
15
  ## [0.4.0](https://github.com/elelem-sh/openai/compare/v0.3.1...v0.4.0) (2026-11-19)
4
16
 
5
17
 
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Elelem
4
+ module OpenAI
5
+ class KeyCommand
6
+ VARIABLE = "OPENAI_API_KEY_COMMAND"
7
+ COMPLAINT_LIMIT = 500
8
+ SHELL = lambda do |command|
9
+ Tempfile.create("elelem-openai") do |complaint|
10
+ output = IO.popen(command, err: complaint, &:read)
11
+ [output, complaint.tap(&:rewind).read(COMPLAINT_LIMIT), Process.last_status.exitstatus]
12
+ end
13
+ end
14
+
15
+ def initialize(command, run: SHELL)
16
+ @command = command
17
+ @run = run
18
+ end
19
+
20
+ def call
21
+ output, complaint, status = @run.call(@command)
22
+ raise KeyError, failure(status, complaint) unless status&.zero?
23
+
24
+ printed(output)
25
+ rescue SystemCallError => e
26
+ raise KeyError, "#{VARIABLE} could not run: #{e.message}"
27
+ end
28
+
29
+ private
30
+
31
+ def failure(status, complaint)
32
+ said = complaint.to_s.strip
33
+ "#{VARIABLE} failed with status #{status.inspect}: #{@command}#{": #{said}" unless said.empty?}"
34
+ end
35
+
36
+ def printed(output)
37
+ key = output.to_s.strip
38
+ raise KeyError, "#{VARIABLE} printed no key: #{@command}" if key.empty?
39
+
40
+ key
41
+ end
42
+ end
43
+ end
44
+ end
@@ -3,11 +3,12 @@
3
3
  module Elelem
4
4
  module OpenAI
5
5
  class Provider
6
- def initialize(model:, api_key:, base_url: "https://api.openai.com/v1", read_timeout: 3600, open_timeout: 10,
7
- http: nil)
6
+ def initialize(model:, api_key: "", key_command: nil, base_url: "https://api.openai.com/v1", read_timeout: 3600,
7
+ open_timeout: 10, http: nil)
8
8
  @uri = URI.join("#{base_url.chomp("/")}/", "chat/completions")
9
9
  @model = model
10
- @api_key = api_key
10
+ @key_command = key_command
11
+ @api_key = api_key unless key_command
11
12
  @read_timeout = read_timeout
12
13
  @open_timeout = open_timeout
13
14
  @http = http
@@ -73,17 +74,30 @@ module Elelem
73
74
  end
74
75
  end
75
76
 
76
- def stream(body)
77
+ def stream(body, &)
78
+ post(body, &)
79
+ rescue RuntimeError => e
80
+ raise unless renewable?(e)
81
+
82
+ @api_key = nil
83
+ post(body, &)
84
+ end
85
+
86
+ def post(body)
77
87
  http.post(@uri, body:, headers:) do |response|
78
88
  Elelem::HTTP.events(response) { |data| yield JSON.parse(data) }
79
89
  end
80
90
  end
81
91
 
92
+ def renewable?(error) = @key_command && error.message.start_with?("HTTP 401")
93
+
82
94
  # A local server may need no key.
83
95
  def headers
84
- @api_key.to_s.empty? ? {} : { "authorization" => "Bearer #{@api_key}" }
96
+ api_key.to_s.empty? ? {} : { "authorization" => "Bearer #{api_key}" }
85
97
  end
86
98
 
99
+ def api_key = @api_key ||= @key_command.call
100
+
87
101
  def http
88
102
  @http ||= Elelem::HTTP.new(read_timeout: @read_timeout, open_timeout: @open_timeout)
89
103
  end
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Elelem
4
4
  module OpenAI
5
- VERSION = "0.4.0"
5
+ VERSION = "0.5.0"
6
6
  end
7
7
  end
data/lib/elelem/openai.rb CHANGED
@@ -3,24 +3,29 @@
3
3
  require "elelem"
4
4
  require "elelem/http"
5
5
  require "json"
6
+ require "tempfile"
6
7
  require "uri"
7
8
 
8
9
  require_relative "openai/version"
10
+ require_relative "openai/key_command"
9
11
  require_relative "openai/provider"
10
12
 
11
13
  Elelem.configure do |config|
12
14
  # OPENAI_BASE_URL points at any Chat Completions server, such as a local
13
15
  # one that needs no key.
14
- config.provider(:openai) do |model: nil, **|
16
+ config.provider(:openai) do |model: nil, http: nil, **|
15
17
  # A variable that is set but empty counts as unset.
16
18
  env = ->(name) { ENV[name].to_s.strip.then { |v| v.empty? ? nil : v } }
17
19
  custom = env.call("OPENAI_BASE_URL")
18
20
  key = env.call("OPENAI_API_KEY")
19
- raise KeyError, "OPENAI_API_KEY is not set" if key.nil? && custom.nil?
21
+ command = env.call(Elelem::OpenAI::KeyCommand::VARIABLE) unless key
22
+ raise KeyError, "set OPENAI_API_KEY or OPENAI_API_KEY_COMMAND" unless key || command || custom
20
23
 
21
24
  Elelem::OpenAI::Provider.new(
22
25
  model: model || env.call("OPENAI_MODEL") || "gpt-4o",
23
26
  api_key: key.to_s,
27
+ key_command: command && Elelem::OpenAI::KeyCommand.new(command),
28
+ http:,
24
29
  base_url: custom || "https://api.openai.com/v1"
25
30
  )
26
31
  end
@@ -0,0 +1,146 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "socket"
4
+ require "stringio"
5
+
6
+ RSpec.describe Elelem::OpenAI::KeyCommand do
7
+ let(:messages) { [{ role: "user", content: "hi" }] }
8
+
9
+ let(:issuer) do
10
+ Class.new do
11
+ attr_reader :commands
12
+
13
+ def initialize(keys)
14
+ @keys = keys
15
+ @commands = []
16
+ end
17
+
18
+ def call(command)
19
+ @commands << command
20
+ [@keys.shift, "", 0]
21
+ end
22
+ end
23
+ end
24
+
25
+ let(:server) do
26
+ Class.new do
27
+ attr_reader :seen
28
+
29
+ def initialize(accepted)
30
+ @accepted = accepted
31
+ @seen = []
32
+ end
33
+
34
+ def post(_uri, headers: {}, **, &)
35
+ @seen << headers["authorization"]
36
+ raise "HTTP 401: token expired" unless headers["authorization"] == "Bearer #{@accepted}"
37
+
38
+ reply("data: {\"choices\":[{\"delta\":{\"content\":\"hi\"}}]}\n\ndata: [DONE]\n", &)
39
+ end
40
+
41
+ private
42
+
43
+ def reply(events)
44
+ io = Net::BufferedIO.new(StringIO.new("HTTP/1.1 200 OK\r\ncontent-length: #{events.bytesize}\r\n\r\n#{events}"))
45
+ response = Net::HTTPResponse.read_new(io)
46
+ response.reading_body(io, true) { yield response }
47
+ end
48
+ end
49
+ end
50
+
51
+ def said(provider) = [].tap { |seen| provider.fetch(messages, []) { seen << it[:text] } }
52
+
53
+ it "strips the key that the command prints" do
54
+ expect(described_class.new("mint", run: ->(_) { [" sk-printed\n", "", 0] }).call).to eq("sk-printed")
55
+ end
56
+
57
+ it "names the variable and the command when nothing is printed" do
58
+ [nil, "", " \n"].each do |output|
59
+ expect { described_class.new("mint", run: ->(_) { [output, "", 0] }).call }
60
+ .to raise_error(KeyError, "OPENAI_API_KEY_COMMAND printed no key: mint")
61
+ end
62
+ end
63
+
64
+ it "fails with the status and stderr of a command that fails, whatever it printed" do
65
+ [1, 78, nil].each do |status|
66
+ expect { described_class.new("mint", run: ->(_) { ["sk-half", "not signed in\n", status] }).call }
67
+ .to raise_error(KeyError, "OPENAI_API_KEY_COMMAND failed with status #{status.inspect}: mint: not signed in")
68
+ end
69
+ end
70
+
71
+ it "runs at the first request, once, and not when the provider is built" do
72
+ mint = issuer.new(%w[sk-first])
73
+ http = server.new("sk-first")
74
+ provider = Elelem::OpenAI::Provider.new(model: "m", key_command: described_class.new("mint", run: mint), http:)
75
+
76
+ expect(mint.commands).to be_empty
77
+ expect(said(provider) + said(provider)).to eq(%w[hi hi])
78
+ expect(mint.commands).to eq(%w[mint])
79
+ expect(http.seen).to eq(["Bearer sk-first"] * 2)
80
+ end
81
+
82
+ it "runs again on a 401, and the request is retried with the new key" do
83
+ mint = issuer.new(%w[sk-expired sk-fresh])
84
+ http = server.new("sk-fresh")
85
+ provider = Elelem::OpenAI::Provider.new(model: "m", key_command: described_class.new("mint", run: mint), http:)
86
+
87
+ expect(said(provider)).to eq(%w[hi])
88
+ expect(http.seen).to eq(["Bearer sk-expired", "Bearer sk-fresh"])
89
+ expect(said(provider)).to eq(%w[hi])
90
+ expect(mint.commands.size).to eq(2)
91
+ end
92
+
93
+ it "retries once only" do
94
+ mint = issuer.new(%w[sk-one sk-two sk-three])
95
+ http = server.new("sk-never")
96
+ provider = Elelem::OpenAI::Provider.new(model: "m", key_command: described_class.new("mint", run: mint), http:)
97
+
98
+ expect { said(provider) }.to raise_error("HTTP 401: token expired")
99
+ expect(http.seen).to eq(["Bearer sk-one", "Bearer sk-two"])
100
+ end
101
+
102
+ it "leaves a 401 alone when the key is fixed" do
103
+ http = server.new("sk-other")
104
+ provider = Elelem::OpenAI::Provider.new(model: "m", api_key: "sk-test", http:)
105
+
106
+ expect { said(provider) }.to raise_error("HTTP 401: token expired")
107
+ expect(http.seen).to eq(["Bearer sk-test"])
108
+ end
109
+
110
+ it "fails the request when the command prints nothing on the retry" do
111
+ mint = issuer.new(["sk-expired", ""])
112
+ provider = Elelem::OpenAI::Provider.new(model: "m", key_command: described_class.new("mint", run: mint),
113
+ http: server.new("sk-fresh"))
114
+
115
+ expect { said(provider) }.to raise_error(KeyError, /OPENAI_API_KEY_COMMAND/)
116
+ end
117
+
118
+ context "with elelem's own HTTP client and a server that answers 401" do
119
+ let(:listener) { TCPServer.new("127.0.0.1", 0) }
120
+ let(:seen) { [] }
121
+
122
+ around do |example|
123
+ serving = Thread.new { 2.times { refuse(listener.accept) } }
124
+ example.run
125
+ ensure
126
+ serving.kill
127
+ listener.close
128
+ end
129
+
130
+ def refuse(client)
131
+ head = client.readpartial(64 << 10)
132
+ seen << head[/^authorization: (.*)\r$/i, 1]
133
+ client.write("HTTP/1.1 401 Unauthorized\r\ncontent-length: 7\r\nconnection: close\r\n\r\nexpired")
134
+ client.close
135
+ end
136
+
137
+ it "sees the 401 in the wording that the retry looks for" do
138
+ mint = issuer.new(%w[sk-one sk-two])
139
+ provider = Elelem::OpenAI::Provider.new(model: "m", key_command: described_class.new("mint", run: mint),
140
+ base_url: "http://127.0.0.1:#{listener.addr[1]}/v1")
141
+
142
+ expect { said(provider) }.to raise_error(RuntimeError, "HTTP 401: expired")
143
+ expect(seen).to eq(["Bearer sk-one", "Bearer sk-two"])
144
+ end
145
+ end
146
+ end
@@ -2,14 +2,36 @@
2
2
 
3
3
  RSpec.describe "the openai provider" do
4
4
  around do |example|
5
- saved = ENV.to_h.slice("OPENAI_API_KEY", "OPENAI_BASE_URL", "OPENAI_MODEL")
5
+ saved = ENV.to_h.slice(*variables)
6
+ variables.each { ENV.delete(it) }
6
7
  example.run
7
8
  ensure
8
- %w[OPENAI_API_KEY OPENAI_BASE_URL OPENAI_MODEL].each { |k| ENV.delete(k) }
9
+ variables.each { ENV.delete(it) }
9
10
  ENV.update(saved)
10
11
  end
11
12
 
12
- def uri = Elelem::Config.build_provider("openai").instance_variable_get(:@uri).to_s
13
+ def variables = %w[OPENAI_API_KEY OPENAI_API_KEY_COMMAND OPENAI_BASE_URL OPENAI_MODEL]
14
+
15
+ let(:wire) do
16
+ Class.new do
17
+ attr_reader :uri, :body, :headers
18
+
19
+ def post(uri, body:, headers: {})
20
+ @uri = uri
21
+ @body = body
22
+ @headers = headers
23
+ end
24
+ end.new
25
+ end
26
+
27
+ def sent
28
+ Elelem::Config.build_provider("openai", http: wire).fetch([{ role: "user", content: "hi" }], [])
29
+ wire
30
+ end
31
+
32
+ def authorization = sent.headers["authorization"]
33
+
34
+ def uri = sent.uri.to_s
13
35
 
14
36
  it "talks to OpenAI by default" do
15
37
  ENV["OPENAI_API_KEY"] = "sk-test"
@@ -23,6 +45,7 @@ RSpec.describe "the openai provider" do
23
45
  ENV["OPENAI_BASE_URL"] = "http://127.0.0.1:8080/v1"
24
46
 
25
47
  expect(uri).to eq("http://127.0.0.1:8080/v1/chat/completions")
48
+ expect(authorization).to be_nil
26
49
  end
27
50
 
28
51
  it "takes a base URL with a trailing slash, and treats an empty one as unset" do
@@ -38,9 +61,54 @@ RSpec.describe "the openai provider" do
38
61
  ENV.delete("OPENAI_BASE_URL")
39
62
  ENV["OPENAI_MODEL"] = ""
40
63
  ENV["OPENAI_API_KEY"] = "sk-test"
41
- expect(Elelem::Config.build_provider("openai").instance_variable_get(:@model)).to eq("gpt-4o")
64
+ expect(sent.body[:model]).to eq("gpt-4o")
42
65
 
43
66
  ENV["OPENAI_API_KEY"] = ""
44
- expect { Elelem::Config.build_provider("openai") }.to raise_error(KeyError, /OPENAI_API_KEY/)
67
+ expect { Elelem::Config.build_provider("openai") }
68
+ .to raise_error(KeyError, "set OPENAI_API_KEY or OPENAI_API_KEY_COMMAND")
69
+ end
70
+
71
+ it "sends OPENAI_API_KEY as a bearer token" do
72
+ ENV["OPENAI_API_KEY"] = "sk-test"
73
+
74
+ expect(authorization).to eq("Bearer sk-test")
75
+ end
76
+
77
+ it "sends the key that OPENAI_API_KEY_COMMAND prints" do
78
+ ENV["OPENAI_API_KEY_COMMAND"] = "echo sk-printed"
79
+
80
+ expect(authorization).to eq("Bearer sk-printed")
81
+ end
82
+
83
+ it "prefers OPENAI_API_KEY to the command, without running it" do
84
+ ENV["OPENAI_API_KEY"] = "sk-test"
85
+ ENV["OPENAI_API_KEY_COMMAND"] = "false"
86
+
87
+ expect(authorization).to eq("Bearer sk-test")
88
+ end
89
+
90
+ it "runs the command at the first request, not when the provider is built" do
91
+ ENV["OPENAI_API_KEY_COMMAND"] = "false"
92
+
93
+ expect { Elelem::Config.build_provider("openai", http: wire) }.not_to raise_error
94
+ expect { authorization }.to raise_error(KeyError, "OPENAI_API_KEY_COMMAND failed with status 1: false")
95
+ end
96
+
97
+ it "names OPENAI_API_KEY_COMMAND when it prints nothing" do
98
+ ENV["OPENAI_API_KEY_COMMAND"] = "true"
99
+
100
+ expect { authorization }.to raise_error(KeyError, "OPENAI_API_KEY_COMMAND printed no key: true")
101
+ end
102
+
103
+ it "keeps what a failed command wrote to stderr in the error and drops its stdout" do
104
+ ENV["OPENAI_API_KEY_COMMAND"] = "sh -c 'echo sk-half; echo run elelem-gateway login >&2; exit 3'"
105
+
106
+ expect { authorization }.to raise_error(KeyError, /failed with status 3: .*: run elelem-gateway login\z/)
107
+ end
108
+
109
+ it "names OPENAI_API_KEY_COMMAND when the command does not exist" do
110
+ ENV["OPENAI_API_KEY_COMMAND"] = "elelem-no-such-command"
111
+
112
+ expect { authorization }.to raise_error(KeyError, /OPENAI_API_KEY_COMMAND could not run: .*elelem-no-such-command/)
45
113
  end
46
114
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: elelem-openai
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.4.0
4
+ version: 0.5.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - mo khan
@@ -75,9 +75,11 @@ files:
75
75
  - Rakefile
76
76
  - exe/elelem-openai
77
77
  - lib/elelem/openai.rb
78
+ - lib/elelem/openai/key_command.rb
78
79
  - lib/elelem/openai/provider.rb
79
80
  - lib/elelem/openai/version.rb
80
81
  - release-please-config.json
82
+ - spec/elelem/openai/key_command_spec.rb
81
83
  - spec/elelem/openai/provider_spec.rb
82
84
  - spec/elelem/openai/registration_spec.rb
83
85
  - spec/elelem/openai/round_trip_spec.rb