elelem-openai 0.1.0 → 0.3.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: c2511ba39bea276751dfc81eceaf8094b605c622c3efbc90a724d122a71633ec
4
- data.tar.gz: dc6766dbbc65c1f3a8d1bbbe243fec6ee8be484f20d68c34e81d95ef1e627fc6
3
+ metadata.gz: 9a36ddc50d065fb25f3a8a5d0308010322a2fd716f3c27ca7adb2d5c24adfb3c
4
+ data.tar.gz: 486ebb30a04b0b0b46d11d3f7b0732013031cc2ae732518e1fbc42c0c695981e
5
5
  SHA512:
6
- metadata.gz: cf64f3f829b8a3f1ee2accdd07ab46300b977f443c4e16280c051923101835e9877acccda4a683e552ce60ff00ec34f86b5da13123bd8d8447015cd0978cf021
7
- data.tar.gz: 9ab07797af1de29d9db456781e0e83bd028de1cc00ff103031481a97cb32aa368266517173539f071cb7b503e0088bcf0e7888b114b6e11d12ea619f94efb775
6
+ metadata.gz: f32724ce6db9368254e07bdb84bdff5dca38bae1aa0aba6663fce3d300ba13cdaba15c8eea6898fc671f19931a71525bd404b815b5ec6e06c8c454db896af220
7
+ data.tar.gz: 1d09a9640327f840d614170e37b789c1bb57b0a633a6efe881098ed409adc3ba6a6c1d319bb72132886ade1439b516b77ef4c7fc54ee98b0646ae6467905041b
@@ -0,0 +1,61 @@
1
+ name: Release
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ workflow_dispatch:
7
+
8
+ permissions: {}
9
+
10
+ concurrency:
11
+ group: release
12
+ cancel-in-progress: false
13
+
14
+ jobs:
15
+ test:
16
+ runs-on: ubuntu-latest
17
+ permissions:
18
+ contents: read
19
+ steps:
20
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
21
+ with:
22
+ persist-credentials: false
23
+ - uses: ruby/setup-ruby@3ff19f5e2baf30647122352b96108b1fbe250c64 # v1.299.0
24
+ with:
25
+ ruby-version: "4.0"
26
+ bundler-cache: true
27
+ - run: bin/test
28
+ - run: bin/lint
29
+
30
+ release-please:
31
+ needs: test
32
+ runs-on: ubuntu-latest
33
+ permissions:
34
+ contents: write
35
+ issues: write
36
+ pull-requests: write
37
+ outputs:
38
+ release_created: ${{ steps.release.outputs.release_created }}
39
+ steps:
40
+ - id: release
41
+ uses: googleapis/release-please-action@45996ed1f6d02564a971a2fa1b5860e934307cf7 # v5.0.0
42
+ with:
43
+ config-file: release-please-config.json
44
+ manifest-file: .release-please-manifest.json
45
+
46
+ publish:
47
+ needs: release-please
48
+ if: needs.release-please.outputs.release_created == 'true'
49
+ runs-on: ubuntu-latest
50
+ permissions:
51
+ contents: write
52
+ id-token: write
53
+ steps:
54
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
55
+ with:
56
+ persist-credentials: false
57
+ - uses: ruby/setup-ruby@3ff19f5e2baf30647122352b96108b1fbe250c64 # v1.299.0
58
+ with:
59
+ ruby-version: "4.0"
60
+ bundler-cache: true
61
+ - uses: rubygems/release-gem@7f9650160c1a4e7989fdc9855807bdbd421d8b6b # v1.4.1
@@ -0,0 +1,3 @@
1
+ {
2
+ ".": "0.3.0"
3
+ }
data/.rspec ADDED
@@ -0,0 +1 @@
1
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,62 @@
1
+ AllCops:
2
+ NewCops: enable
3
+ TargetRubyVersion: 4.0
4
+ SuggestExtensions: false
5
+ Exclude:
6
+ - "pkg/**/*"
7
+ - "bin/**/*"
8
+ - "vendor/**/*"
9
+ - "fixtures/**/*"
10
+
11
+ Metrics:
12
+ Enabled: false
13
+
14
+ Naming/PredicateMethod:
15
+ AllowedMethods:
16
+ - call
17
+ - run
18
+ - summarize
19
+ - prompt
20
+
21
+ Naming/MethodParameterName:
22
+ AllowedNames:
23
+ - me
24
+ - id
25
+ - as
26
+ - io
27
+
28
+ Style/GlobalVars:
29
+ Exclude:
30
+ - "spec/**/*"
31
+
32
+ Lint/EmptyBlock:
33
+ Exclude:
34
+ - "spec/**/*"
35
+
36
+ Lint/UselessDefaultValueArgument:
37
+ Enabled: false
38
+
39
+ Lint/RedundantRequireStatement:
40
+ Enabled: false
41
+
42
+ Lint/UnusedBlockArgument:
43
+ IgnoreEmptyBlocks: true
44
+ AllowUnusedKeywordArguments: true
45
+
46
+ Style/Documentation:
47
+ Enabled: false
48
+
49
+ Style/FormatStringToken:
50
+ Enabled: false
51
+
52
+ Style/FrozenStringLiteralComment:
53
+ Enabled: true
54
+
55
+ Style/StringLiterals:
56
+ EnforcedStyle: double_quotes
57
+
58
+ Style/StringLiteralsInInterpolation:
59
+ EnforcedStyle: double_quotes
60
+
61
+ Layout/LineLength:
62
+ Max: 120
data/CHANGELOG.md ADDED
@@ -0,0 +1,18 @@
1
+ # Changelog
2
+
3
+ ## [0.3.0](https://github.com/elelem-sh/openai/compare/v0.2.0...v0.3.0) (2026-11-16)
4
+
5
+
6
+ ### Features
7
+
8
+ * accept model: from provider_options, fall back to ENV ([3f0360c](https://github.com/elelem-sh/openai/commit/3f0360c6ced4bbfaa21e9aa97cd79161ae01fdd4))
9
+
10
+
11
+ ### Bug Fixes
12
+
13
+ * add rspec to Gemfile so bundle exec rspec runs at all ([15cbcc0](https://github.com/elelem-sh/openai/commit/15cbcc0d85b61c820b87d0be77ed86aa77a34ee6))
14
+ * empty OpenAI model and key settings count as unset, and a missing key fails at start ([c443200](https://github.com/elelem-sh/openai/commit/c44320031cfeb97155071601e9f0f021a0c5c647))
15
+ * OPENAI_BASE_URL points elelem-openai at any Chat Completions server (elelem-sh/elelem.sh[#26](https://github.com/elelem-sh/openai/issues/26)) ([387e821](https://github.com/elelem-sh/openai/commit/387e8219f38fb16b30e0883a71e3a3de0663558f))
16
+ * OPENAI_BASE_URL takes a trailing slash, an empty value is unset, and no key sends no header ([5dbb125](https://github.com/elelem-sh/openai/commit/5dbb125cf9119406745e945090a2502e0409f0c7))
17
+ * require elelem ~> 0.12, the floor builtins/skills actually need ([d9e5880](https://github.com/elelem-sh/openai/commit/d9e588035a36a0122014695b8d8cd874048de63a))
18
+ * send earlier tool calls in the Chat Completions shape and omit empty tools (elelem-sh/elelem.sh[#26](https://github.com/elelem-sh/openai/issues/26)) ([9a51d90](https://github.com/elelem-sh/openai/commit/9a51d90cb687f292a089a67a2180abc818515f48))
@@ -0,0 +1,128 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Elelem
4
+ module OpenAI
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)
8
+ @uri = URI.join("#{base_url.chomp("/")}/", "chat/completions")
9
+ @model = model
10
+ @api_key = api_key
11
+ @read_timeout = read_timeout
12
+ @open_timeout = open_timeout
13
+ @http = http
14
+ end
15
+
16
+ def fetch(messages, tools = [], &)
17
+ tool_calls = {}
18
+ body = build_request_body(messages, tools)
19
+
20
+ stream(body) do |event|
21
+ handle_event(event, tool_calls, &)
22
+ end
23
+
24
+ finalize_tool_calls(tool_calls, &)
25
+ end
26
+
27
+ private
28
+
29
+ def build_request_body(messages, tools)
30
+ body = { model: @model, messages: messages.map { |m| normalize(m) }, stream: true }
31
+ tools.empty? ? body : body.merge(tools:, tool_choice: "auto")
32
+ end
33
+
34
+ # elelem keeps tool calls as {id, name, arguments: Hash}. Chat Completions
35
+ # wants {id, type: "function", function: {name, arguments: "<json>"}}.
36
+ def normalize(message)
37
+ calls = message[:tool_calls]
38
+ return message unless calls
39
+
40
+ message.merge(tool_calls: calls.map { |call| to_openai(call) })
41
+ end
42
+
43
+ def to_openai(call)
44
+ arguments = call[:arguments]
45
+ arguments = JSON.generate(arguments || {}) unless arguments.is_a?(String)
46
+ { id: call[:id], type: "function", function: { name: call[:name], arguments: } }
47
+ end
48
+
49
+ def handle_event(event, tool_calls, &block)
50
+ delta = event.dig("choices", 0, "delta") || {}
51
+
52
+ block.call(type: "saying", text: delta["content"]) if delta["content"]
53
+
54
+ accumulate_tool_calls(delta["tool_calls"], tool_calls) if delta["tool_calls"]
55
+ end
56
+
57
+ def accumulate_tool_calls(incoming_tool_calls, tool_calls)
58
+ incoming_tool_calls.each do |tool_call|
59
+ index = tool_call["index"]
60
+ tool_calls[index] ||= { id: nil, name: nil, args: String.new }
61
+ tool_calls[index][:id] ||= tool_call["id"]
62
+ tool_calls[index][:name] ||= tool_call.dig("function", "name")
63
+ tool_calls[index][:args] << tool_call.dig("function", "arguments").to_s
64
+ end
65
+ end
66
+
67
+ def stream(body, &)
68
+ http.post(@uri, api_key: @api_key, body:) do |response|
69
+ raise "HTTP #{response.code}: #{response.body}" unless response.is_a?(Net::HTTPSuccess)
70
+
71
+ read_sse_stream(response, &)
72
+ end
73
+ end
74
+
75
+ def http
76
+ @http ||= HttpAdapter.new(read_timeout: @read_timeout, open_timeout: @open_timeout)
77
+ end
78
+
79
+ def read_sse_stream(response)
80
+ buffer = String.new
81
+
82
+ response.read_body do |chunk|
83
+ buffer << chunk
84
+
85
+ while (index = buffer.index("\n"))
86
+ line = buffer.slice!(0, index + 1).strip
87
+ next unless line.start_with?("data: ") && line != "data: [DONE]"
88
+
89
+ yield JSON.parse(line.delete_prefix("data: "))
90
+ end
91
+ end
92
+ end
93
+
94
+ def finalize_tool_calls(tool_calls, &block)
95
+ tool_calls.values.map do |tool_call|
96
+ {
97
+ id: tool_call[:id],
98
+ name: tool_call[:name],
99
+ arguments: tool_call[:args].strip.empty? ? {} : JSON.parse(tool_call[:args])
100
+ }.tap { |result| block.call(result.merge(type: "doing")) }
101
+ end
102
+ end
103
+
104
+ class HttpAdapter
105
+ def initialize(read_timeout:, open_timeout:)
106
+ @read_timeout = read_timeout
107
+ @open_timeout = open_timeout
108
+ end
109
+
110
+ def post(uri, api_key:, body:, &)
111
+ request = Net::HTTP::Post.new(uri)
112
+ request["content-type"] = "application/json"
113
+ request["authorization"] = "Bearer #{api_key}" unless api_key.to_s.empty?
114
+ request.body = JSON.generate(body)
115
+
116
+ http = Net::HTTP.new(uri.host, uri.port)
117
+ http.use_ssl = uri.scheme == "https"
118
+ http.read_timeout = @read_timeout
119
+ http.open_timeout = @open_timeout
120
+
121
+ http.start do |conn|
122
+ conn.request(request, &)
123
+ end
124
+ end
125
+ end
126
+ end
127
+ end
128
+ end
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Elelem
4
4
  module OpenAI
5
- VERSION = "0.1.0"
5
+ VERSION = "0.3.0"
6
6
  end
7
7
  end
data/lib/elelem/openai.rb CHANGED
@@ -6,11 +6,22 @@ require "net/http"
6
6
  require "uri"
7
7
 
8
8
  require_relative "openai/version"
9
- require_relative "openai/client"
9
+ require_relative "openai/provider"
10
10
 
11
- Elelem::Providers.register(:openai) do
12
- Elelem::OpenAI::Client.new(
13
- model: ENV.fetch("OPENAI_MODEL", "gpt-4o"),
14
- api_key: ENV.fetch("OPENAI_API_KEY")
15
- )
11
+ Elelem.configure do |config|
12
+ # OPENAI_BASE_URL points at any Chat Completions server, such as a local
13
+ # one that needs no key.
14
+ config.provider(:openai) do |model: nil, **|
15
+ # A variable that is set but empty counts as unset.
16
+ env = ->(name) { ENV[name].to_s.strip.then { |v| v.empty? ? nil : v } }
17
+ custom = env.call("OPENAI_BASE_URL")
18
+ key = env.call("OPENAI_API_KEY")
19
+ raise KeyError, "OPENAI_API_KEY is not set" if key.nil? && custom.nil?
20
+
21
+ Elelem::OpenAI::Provider.new(
22
+ model: model || env.call("OPENAI_MODEL") || "gpt-4o",
23
+ api_key: key.to_s,
24
+ base_url: custom || "https://api.openai.com/v1"
25
+ )
26
+ end
16
27
  end
@@ -0,0 +1,12 @@
1
+ {
2
+ "bootstrap-sha": "2f7154ed8f9f02512e4375fb413cb1db9600b036",
3
+ "packages": {
4
+ ".": {
5
+ "release-type": "ruby",
6
+ "package-name": "elelem-openai",
7
+ "version-file": "lib/elelem/openai/version.rb",
8
+ "bump-minor-pre-major": true,
9
+ "include-component-in-tag": false
10
+ }
11
+ }
12
+ }
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ RSpec.describe Elelem::OpenAI::Provider::HttpAdapter do
4
+ def sent_headers(api_key)
5
+ seen = nil
6
+ conn = double("conn").tap { |c| allow(c).to receive(:request) { |req| seen = req } }
7
+ http = double("http", "use_ssl=": nil, "read_timeout=": nil, "open_timeout=": nil).tap do |h|
8
+ allow(h).to receive(:start).and_yield(conn)
9
+ end
10
+ allow(Net::HTTP).to receive(:new).and_return(http)
11
+ adapter = described_class.new(read_timeout: 1, open_timeout: 1)
12
+ adapter.post(URI("http://h/v1/chat/completions"), api_key: api_key, body: {})
13
+ seen
14
+ end
15
+
16
+ it "sends the key as a bearer token" do
17
+ expect(sent_headers("sk-test")["authorization"]).to eq("Bearer sk-test")
18
+ end
19
+
20
+ it "sends no authorization header without a key" do
21
+ expect(sent_headers("")["authorization"]).to be_nil
22
+ end
23
+ end
@@ -0,0 +1,109 @@
1
+ # frozen_string_literal: true
2
+
3
+ RSpec.describe Elelem::OpenAI::Provider do
4
+ subject(:provider) do
5
+ described_class.new(model: "gpt-4o", api_key: "sk-test", http:, **params)
6
+ end
7
+
8
+ let(:params) { {} }
9
+ let(:messages) { [{ role: "user", content: "hi" }] }
10
+ let(:body) { http.body }
11
+
12
+ let(:response) do
13
+ Net::HTTPOK.new("1.1", "200", "OK").tap do |res|
14
+ allow(res).to receive(:read_body).and_yield(sse(events))
15
+ end
16
+ end
17
+
18
+ let(:events) { [] }
19
+
20
+ let(:http) do
21
+ Class.new do
22
+ attr_reader :body
23
+
24
+ def initialize(response)
25
+ @response = response
26
+ end
27
+
28
+ def post(_uri, body:, **)
29
+ @body = body
30
+ yield @response
31
+ end
32
+ end.new(response)
33
+ end
34
+
35
+ def sse(events)
36
+ events.map { |event| "data: #{JSON.generate(event)}\n" }.join << "data: [DONE]\n"
37
+ end
38
+
39
+ describe "#fetch" do
40
+ it "leaves out tools and tool_choice when there are no tools" do
41
+ provider.fetch(messages, [])
42
+
43
+ expect(body).to eq(model: "gpt-4o", messages:, stream: true)
44
+ end
45
+
46
+ it "sends tools with tool_choice auto" do
47
+ tools = [{ type: "function", function: { name: "read" } }]
48
+ provider.fetch(messages, tools)
49
+
50
+ expect(body).to include(tools:, tool_choice: "auto")
51
+ end
52
+
53
+ it "sends earlier tool calls in the Chat Completions shape" do
54
+ history = messages + [
55
+ { role: "assistant", content: "", tool_calls: [{ id: "1", name: "read", arguments: { "path" => "a.rb" } }] },
56
+ { role: "tool", tool_call_id: "1", content: "{}" }
57
+ ]
58
+ provider.fetch(history, [])
59
+
60
+ expect(body[:messages][1][:tool_calls]).to eq(
61
+ [{ id: "1", type: "function", function: { name: "read", arguments: '{"path":"a.rb"}' } }]
62
+ )
63
+ expect(body[:messages][2]).to eq(history[2])
64
+ end
65
+
66
+ context "with a text delta" do
67
+ let(:events) { [{ "choices" => [{ "delta" => { "content" => "hi" } }] }] }
68
+
69
+ it "yields a saying block" do
70
+ seen = []
71
+
72
+ provider.fetch(messages, []) { |event| seen << event }
73
+
74
+ expect(seen).to eq([{ type: "saying", text: "hi" }])
75
+ end
76
+ end
77
+
78
+ context "with a streamed tool call split across chunks" do
79
+ let(:first_chunk) do
80
+ { "index" => 0, "id" => "1", "function" => { "name" => "read", "arguments" => '{"path":' } }
81
+ end
82
+ let(:second_chunk) { { "index" => 0, "function" => { "arguments" => '"a.rb"}' } } }
83
+
84
+ let(:events) do
85
+ [
86
+ { "choices" => [{ "delta" => { "tool_calls" => [first_chunk] } }] },
87
+ { "choices" => [{ "delta" => { "tool_calls" => [second_chunk] } }] }
88
+ ]
89
+ end
90
+
91
+ it "accumulates arguments across chunks into parsed json" do
92
+ result = provider.fetch(messages, []) {}
93
+
94
+ expect(result).to eq([{ id: "1", name: "read", arguments: { "path" => "a.rb" } }])
95
+ end
96
+ end
97
+
98
+ context "with a tool call that has no arguments" do
99
+ let(:events) do
100
+ [{ "choices" => [{ "delta" => { "tool_calls" => [{ "index" => 0, "id" => "1",
101
+ "function" => { "name" => "read" } }] } }] }]
102
+ end
103
+
104
+ it "takes them as an empty hash" do
105
+ expect(provider.fetch(messages, []) {}).to eq([{ id: "1", name: "read", arguments: {} }])
106
+ end
107
+ end
108
+ end
109
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ RSpec.describe "the openai provider" do
4
+ around do |example|
5
+ saved = ENV.to_h.slice("OPENAI_API_KEY", "OPENAI_BASE_URL", "OPENAI_MODEL")
6
+ example.run
7
+ ensure
8
+ %w[OPENAI_API_KEY OPENAI_BASE_URL OPENAI_MODEL].each { |k| ENV.delete(k) }
9
+ ENV.update(saved)
10
+ end
11
+
12
+ def uri = Elelem::Config.build_provider("openai").instance_variable_get(:@uri).to_s
13
+
14
+ it "talks to OpenAI by default" do
15
+ ENV["OPENAI_API_KEY"] = "sk-test"
16
+ ENV.delete("OPENAI_BASE_URL")
17
+
18
+ expect(uri).to eq("https://api.openai.com/v1/chat/completions")
19
+ end
20
+
21
+ it "uses OPENAI_BASE_URL, with no key needed" do
22
+ ENV.delete("OPENAI_API_KEY")
23
+ ENV["OPENAI_BASE_URL"] = "http://127.0.0.1:8080/v1"
24
+
25
+ expect(uri).to eq("http://127.0.0.1:8080/v1/chat/completions")
26
+ end
27
+
28
+ it "takes a base URL with a trailing slash, and treats an empty one as unset" do
29
+ ENV["OPENAI_API_KEY"] = "sk-test"
30
+ ENV["OPENAI_BASE_URL"] = "http://127.0.0.1:8080/v1/"
31
+ expect(uri).to eq("http://127.0.0.1:8080/v1/chat/completions")
32
+
33
+ ENV["OPENAI_BASE_URL"] = ""
34
+ expect(uri).to eq("https://api.openai.com/v1/chat/completions")
35
+ end
36
+
37
+ it "treats an empty model as unset, and an empty key as missing for OpenAI" do
38
+ ENV.delete("OPENAI_BASE_URL")
39
+ ENV["OPENAI_MODEL"] = ""
40
+ ENV["OPENAI_API_KEY"] = "sk-test"
41
+ expect(Elelem::Config.build_provider("openai").instance_variable_get(:@model)).to eq("gpt-4o")
42
+
43
+ ENV["OPENAI_API_KEY"] = ""
44
+ expect { Elelem::Config.build_provider("openai") }.to raise_error(KeyError, /OPENAI_API_KEY/)
45
+ end
46
+ end
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ # A fake Chat Completions server that rejects a history in the wrong shape,
4
+ # the way the API does with a 400.
5
+ RSpec.describe "a tool call round trip through Elelem::Agent" do
6
+ let(:server) do
7
+ Class.new do
8
+ attr_reader :requests
9
+
10
+ def initialize
11
+ @requests = []
12
+ end
13
+
14
+ def post(_uri, body:, **)
15
+ @requests << body
16
+ problem = invalid(body[:messages])
17
+ events = @requests.size == 1 ? tool_call : reply
18
+ yield(problem ? bad_request(problem) : ok(events))
19
+ end
20
+
21
+ private
22
+
23
+ def invalid(messages)
24
+ messages.flat_map { |m| m[:tool_calls] || [] }.find do |call|
25
+ call[:type] != "function" || !call.dig(:function, :arguments).is_a?(String)
26
+ end
27
+ end
28
+
29
+ def tool_call
30
+ call = { "index" => 0, "id" => "c1", "function" => { "name" => "now", "arguments" => "{}" } }
31
+ [{ "choices" => [{ "delta" => { "tool_calls" => [call] } }] }]
32
+ end
33
+
34
+ def reply = [{ "choices" => [{ "delta" => { "content" => "It is noon." } }] }]
35
+
36
+ def ok(events)
37
+ Net::HTTPOK.new("1.1", "200", "OK").tap do |res|
38
+ data = events.map { |e| "data: #{JSON.generate(e)}\n" }.join << "data: [DONE]\n"
39
+ res.define_singleton_method(:read_body) { |&block| block.call(data) }
40
+ end
41
+ end
42
+
43
+ def bad_request(problem)
44
+ Net::HTTPBadRequest.new("1.1", "400", "Bad Request").tap do |res|
45
+ res.define_singleton_method(:body) { "invalid tool call: #{problem}" }
46
+ end
47
+ end
48
+ end.new
49
+ end
50
+
51
+ it "calls the tool, sends its result back, and gets the reply" do
52
+ toolbox = Elelem::Toolbox.new
53
+ toolbox.add("now", description: "Time", params: {}) { { time: "noon" } }
54
+ provider = Elelem::OpenAI::Provider.new(model: "gpt-4o", api_key: "sk-test", http: server)
55
+
56
+ reply = Elelem::Agent.new(provider, toolbox: toolbox, output: Elelem::NullOutput.new).turn("What time is it?")
57
+
58
+ expect(reply).to eq("It is noon.")
59
+ expect(server.requests.size).to eq(2)
60
+ end
61
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../lib/elelem/openai"
4
+
5
+ RSpec.configure do |config|
6
+ config.disable_monkey_patching!
7
+
8
+ config.expect_with :rspec do |c|
9
+ c.syntax = :expect
10
+ end
11
+ 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.1.0
4
+ version: 0.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - mo khan
@@ -13,30 +13,36 @@ dependencies:
13
13
  name: elelem
14
14
  requirement: !ruby/object:Gem::Requirement
15
15
  requirements:
16
- - - "~>"
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '0.13'
19
+ - - "<"
17
20
  - !ruby/object:Gem::Version
18
- version: '0.10'
21
+ version: '1'
19
22
  type: :runtime
20
23
  prerelease: false
21
24
  version_requirements: !ruby/object:Gem::Requirement
22
25
  requirements:
23
- - - "~>"
26
+ - - ">="
27
+ - !ruby/object:Gem::Version
28
+ version: '0.13'
29
+ - - "<"
24
30
  - !ruby/object:Gem::Version
25
- version: '0.10'
31
+ version: '1'
26
32
  - !ruby/object:Gem::Dependency
27
33
  name: json
28
34
  requirement: !ruby/object:Gem::Requirement
29
35
  requirements:
30
36
  - - "~>"
31
37
  - !ruby/object:Gem::Version
32
- version: '2.21'
38
+ version: '3.0'
33
39
  type: :runtime
34
40
  prerelease: false
35
41
  version_requirements: !ruby/object:Gem::Requirement
36
42
  requirements:
37
43
  - - "~>"
38
44
  - !ruby/object:Gem::Version
39
- version: '2.21'
45
+ version: '3.0'
40
46
  - !ruby/object:Gem::Dependency
41
47
  name: net-http
42
48
  requirement: !ruby/object:Gem::Requirement
@@ -73,19 +79,31 @@ executables:
73
79
  extensions: []
74
80
  extra_rdoc_files: []
75
81
  files:
82
+ - ".github/workflows/release.yml"
83
+ - ".release-please-manifest.json"
84
+ - ".rspec"
85
+ - ".rubocop.yml"
86
+ - CHANGELOG.md
76
87
  - LICENSE.txt
77
88
  - Rakefile
78
89
  - exe/elelem-openai
79
90
  - lib/elelem/openai.rb
80
- - lib/elelem/openai/client.rb
91
+ - lib/elelem/openai/provider.rb
81
92
  - lib/elelem/openai/version.rb
82
- homepage: https://src.mokhan.ca/elelem/openai
93
+ - release-please-config.json
94
+ - spec/elelem/openai/http_adapter_spec.rb
95
+ - spec/elelem/openai/provider_spec.rb
96
+ - spec/elelem/openai/registration_spec.rb
97
+ - spec/elelem/openai/round_trip_spec.rb
98
+ - spec/spec_helper.rb
99
+ homepage: https://elelem.sh
83
100
  licenses:
84
101
  - MIT
85
102
  metadata:
86
103
  allowed_push_host: https://rubygems.org
87
- homepage_uri: https://src.mokhan.ca/elelem/openai
88
- source_code_uri: https://src.mokhan.ca/elelem/openai
104
+ homepage_uri: https://elelem.sh
105
+ source_code_uri: https://github.com/elelem-sh/openai
106
+ rubygems_mfa_required: 'true'
89
107
  rdoc_options: []
90
108
  require_paths:
91
109
  - lib
@@ -100,7 +118,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
100
118
  - !ruby/object:Gem::Version
101
119
  version: '0'
102
120
  requirements: []
103
- rubygems_version: 4.0.20
121
+ rubygems_version: 4.0.6
104
122
  specification_version: 4
105
123
  summary: An OpenAI provider plugin for elelem.
106
124
  test_files: []
@@ -1,95 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module Elelem
4
- module OpenAI
5
- class Client
6
- def initialize(model:, api_key:, base_url: "https://api.openai.com/v1", read_timeout: 3600, open_timeout: 10)
7
- @uri = URI.join("#{base_url}/", "chat/completions")
8
- @model = model
9
- @api_key = api_key
10
- @read_timeout = read_timeout
11
- @open_timeout = open_timeout
12
- end
13
-
14
- def fetch(messages, tools = [], &block)
15
- tool_calls = {}
16
- body = build_request_body(messages, tools)
17
-
18
- stream(body) do |event|
19
- handle_event(event, tool_calls, &block)
20
- end
21
-
22
- finalize_tool_calls(tool_calls, &block)
23
- end
24
-
25
- private
26
-
27
- def build_request_body(messages, tools)
28
- { model: @model, messages:, stream: true, tools:, tool_choice: "auto" }
29
- end
30
-
31
- def handle_event(event, tool_calls, &block)
32
- delta = event.dig("choices", 0, "delta") || {}
33
-
34
- block.call(type: "saying", text: delta["content"]) if delta["content"]
35
-
36
- accumulate_tool_calls(delta["tool_calls"], tool_calls) if delta["tool_calls"]
37
- end
38
-
39
- def accumulate_tool_calls(incoming_tool_calls, tool_calls)
40
- incoming_tool_calls.each do |tool_call|
41
- index = tool_call["index"]
42
- tool_calls[index] ||= { id: nil, name: nil, args: String.new }
43
- tool_calls[index][:id] ||= tool_call["id"]
44
- tool_calls[index][:name] ||= tool_call.dig("function", "name")
45
- tool_calls[index][:args] << tool_call.dig("function", "arguments").to_s
46
- end
47
- end
48
-
49
- def stream(body)
50
- request = Net::HTTP::Post.new(@uri)
51
- request["content-type"] = "application/json"
52
- request["authorization"] = "Bearer #{@api_key}"
53
- request.body = JSON.generate(body)
54
-
55
- http = Net::HTTP.new(@uri.host, @uri.port)
56
- http.use_ssl = @uri.scheme == "https"
57
- http.read_timeout = @read_timeout
58
- http.open_timeout = @open_timeout
59
-
60
- http.start do |conn|
61
- conn.request(request) do |response|
62
- raise "HTTP #{response.code}: #{response.body}" unless response.is_a?(Net::HTTPSuccess)
63
-
64
- read_sse_stream(response) { |event| yield event }
65
- end
66
- end
67
- end
68
-
69
- def read_sse_stream(response)
70
- buffer = String.new
71
-
72
- response.read_body do |chunk|
73
- buffer << chunk
74
-
75
- while (index = buffer.index("\n"))
76
- line = buffer.slice!(0, index + 1).strip
77
- next unless line.start_with?("data: ") && line != "data: [DONE]"
78
-
79
- yield JSON.parse(line.delete_prefix("data: "))
80
- end
81
- end
82
- end
83
-
84
- def finalize_tool_calls(tool_calls, &block)
85
- tool_calls.values.map do |tool_call|
86
- {
87
- id: tool_call[:id],
88
- name: tool_call[:name],
89
- arguments: JSON.parse(tool_call[:args])
90
- }.tap { |result| block.call(result.merge(type: "doing")) }
91
- end
92
- end
93
- end
94
- end
95
- end