elelem-anthropic 0.3.1 → 0.4.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: be25f306620eea1058e26877f669e5baa85f418cddf295e876ef95df32fe8414
4
- data.tar.gz: 6f1526f98d34fca9864d6c7339371594b6e009dbde40858696a5634e62ee7827
3
+ metadata.gz: 85c37180da231da0fe559308f934d995b5488913e95d22aec18384ab424f5c1c
4
+ data.tar.gz: a836f2c4cb64af858ff219cb44281c49deca3456a9feb4508a231522718475f0
5
5
  SHA512:
6
- metadata.gz: 24818e12c1fa5d132a336229cb96d2619fb46e8936d0a95e108148a19c865c38915de41e3a04a1a0cd9365c18da8f0fbe10974d19e004277a127319b69d0703d
7
- data.tar.gz: 2d15b297f467f0d5a1d7daca2c7c5cfc25ac14baa74c72d9f40aa7e614b0898e77e0a9c625e1b145de777b4d839e3ed662ef6f58fd000e64bdfe24e68a93bc84
6
+ metadata.gz: 6bb39ec62837925b51d3499d08d60436357861d805339af2c461fe1a0d832fee4ebaa37006e0650ec6f111c988f1a40bb4ce1bd3c95279169f92895ddb20f958
7
+ data.tar.gz: ceb441c39b98de5d25787aed1d1353d51583954f830db2dd0021732eecedc0e3c6298269dd6274ced4e9536aa9dc3a57c2709325229caae3ecfd2fdb31afe7b8
@@ -1,3 +1,3 @@
1
1
  {
2
- ".": "0.3.1"
2
+ ".": "0.4.0"
3
3
  }
data/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.4.0](https://github.com/elelem-sh/anthropic/compare/v0.3.1...v0.4.0) (2026-11-19)
4
+
5
+
6
+ ### Features
7
+
8
+ * cache prompts and stream over a kept-alive connection ([a0a5c67](https://github.com/elelem-sh/anthropic/commit/a0a5c67964d61f012a697c668776d5b8d38515ee))
9
+
10
+
11
+ ### Bug Fixes
12
+
13
+ * leave out an empty system prompt and say when the context window is full ([df97854](https://github.com/elelem-sh/anthropic/commit/df97854090f78afd3e2528fee7c3522e11957219))
14
+ * say when a reply hits max_tokens or is refused ([d7f36d1](https://github.com/elelem-sh/anthropic/commit/d7f36d1b2dd731c08b8688d19ec3c9b72edbfeb5))
15
+
16
+
17
+ ### Performance Improvements
18
+
19
+ * keep the gcloud token for three minutes instead of asking on every request ([bf84f19](https://github.com/elelem-sh/anthropic/commit/bf84f19e8a6139105a5734befcc754a57a817ab0))
20
+
3
21
  ## [0.3.1](https://github.com/elelem-sh/anthropic/compare/v0.3.0...v0.3.1) (2026-11-18)
4
22
 
5
23
 
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Elelem
4
+ module Anthropic
5
+ # An access token from gcloud, kept for a few minutes because asking
6
+ # gcloud takes about a second. gcloud renews a token well before it
7
+ # expires, so one kept for 3 minutes stays valid.
8
+ class GcloudToken
9
+ COMMAND = %w[gcloud auth application-default print-access-token].freeze
10
+ KEEP = 180
11
+
12
+ def initialize(clock: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) })
13
+ @clock = clock
14
+ end
15
+
16
+ def call
17
+ refresh if @token.nil? || @clock.call >= @expires
18
+ @token
19
+ end
20
+
21
+ private
22
+
23
+ def refresh
24
+ output, status = Open3.capture2(*COMMAND)
25
+ raise "#{COMMAND.join(" ")} failed; run gcloud auth application-default login" unless status.success?
26
+
27
+ @token = output.strip
28
+ @expires = @clock.call + KEEP
29
+ end
30
+ end
31
+ end
32
+ end
@@ -12,6 +12,12 @@ module Elelem
12
12
  # adaptive thinking, and the API picks a default effort per model.
13
13
  EFFORTS = %w[low medium high xhigh max].freeze
14
14
 
15
+ # Each step of a turn resends the whole conversation. The marker on the
16
+ # system prompt caches it and the tools for every turn; the top-level
17
+ # marker caches the conversation so far, so each step pays only for
18
+ # what is new.
19
+ CACHE = { type: "ephemeral" }.freeze
20
+
15
21
  # An empty variable counts as unset.
16
22
  def self.options_from(env)
17
23
  value = ->(name) { env[name].to_s.strip.then { |v| v.empty? ? nil : v } }
@@ -64,12 +70,31 @@ module Elelem
64
70
  handle_content_block_start(event, tool_calls)
65
71
  when "content_block_delta"
66
72
  handle_content_block_delta(event, tool_calls, &)
73
+ when "message_start"
74
+ log_usage(event.dig("message", "usage"))
75
+ when "message_delta"
76
+ log_usage(event["usage"])
77
+ stopped(event.dig("delta", "stop_reason"))
67
78
  when "error"
68
79
  # e.g. overloaded_error mid-stream. Without this the reply is silently empty.
69
80
  raise "#{event.dig("error", "type")}: #{event.dig("error", "message")}"
70
81
  end
71
82
  end
72
83
 
84
+ # Raises before a cut-off tool call is parsed.
85
+ def stopped(reason)
86
+ case reason
87
+ when "max_tokens" then raise "the reply hit max_tokens (#{@max_tokens}); raise ANTHROPIC_MAX_TOKENS"
88
+ when "model_context_window_exceeded" then raise "the conversation no longer fits the model's context window"
89
+ when "refusal" then raise "the model declined to answer"
90
+ end
91
+ end
92
+
93
+ # cache_read_input_tokens shows whether prompt caching works.
94
+ def log_usage(usage)
95
+ Elelem.logger.debug("anthropic: usage #{JSON.generate(usage)}") if usage
96
+ end
97
+
73
98
  def handle_content_block_start(event, tool_calls)
74
99
  content_block = event["content_block"]
75
100
  return unless content_block["type"] == "tool_use"
@@ -103,55 +128,29 @@ module Elelem
103
128
  tool_calls
104
129
  end
105
130
 
106
- def stream(messages, system_prompt, tools, &)
131
+ def stream(messages, system_prompt, tools)
107
132
  body = build_request_body(messages, system_prompt, tools)
108
133
 
109
134
  http.post(@uri, headers:, body:) do |response|
110
- raise "HTTP #{response.code}: #{response.body}" unless response.is_a?(Net::HTTPSuccess)
111
-
112
- read_sse_stream(response, &)
135
+ Elelem::HTTP.events(response) { |data| yield JSON.parse(data) }
113
136
  end
114
137
  end
115
138
 
116
139
  def http
117
- @http ||= HttpAdapter.new(read_timeout: @read_timeout, open_timeout: @open_timeout)
140
+ @http ||= Elelem::HTTP.new(read_timeout: @read_timeout, open_timeout: @open_timeout)
118
141
  end
119
142
 
120
143
  def build_request_body(messages, system_prompt, tools)
121
- body = { max_tokens: @max_tokens, messages:, stream: true }
144
+ body = { max_tokens: @max_tokens, messages:, stream: true, cache_control: CACHE }
122
145
  body[:thinking] = @thinking if @thinking
123
146
  body[:output_config] = { effort: @effort } if @effort
124
147
  body[:model] = @model unless @version
125
148
  body[:anthropic_version] = @version if @version
126
- body[:system] = system_prompt if system_prompt
149
+ body[:system] = [{ type: "text", text: system_prompt, cache_control: CACHE }] unless system_prompt.to_s.empty?
127
150
  body[:tools] = unwrap_tools(tools) unless tools.empty?
128
151
  body
129
152
  end
130
153
 
131
- def read_sse_stream(response)
132
- buffer = String.new
133
-
134
- response.read_body do |chunk|
135
- buffer << chunk
136
-
137
- while (index = buffer.index("\n\n"))
138
- raw_event = buffer.slice!(0, index + 2)
139
- event = parse_sse(raw_event)
140
- yield event if event
141
- end
142
- end
143
- end
144
-
145
- def parse_sse(raw)
146
- line = raw.lines.find { |l| l.start_with?("data: ") }
147
- return nil unless line
148
-
149
- data = line.delete_prefix("data: ").strip
150
- return nil if data == "[DONE]"
151
-
152
- JSON.parse(data)
153
- end
154
-
155
154
  def extract_system(messages)
156
155
  system_messages, other_messages = messages.partition { |message| message[:role] == "system" }
157
156
  system_content = system_messages.first&.dig(:content)
@@ -217,29 +216,6 @@ module Elelem
217
216
  }
218
217
  end
219
218
  end
220
-
221
- class HttpAdapter
222
- def initialize(read_timeout:, open_timeout:)
223
- @read_timeout = read_timeout
224
- @open_timeout = open_timeout
225
- end
226
-
227
- def post(uri, headers:, body:, &)
228
- request = Net::HTTP::Post.new(uri)
229
- request["content-type"] = "application/json"
230
- headers.each { |k, v| request[k] = v }
231
- request.body = JSON.generate(body)
232
-
233
- http = Net::HTTP.new(uri.host, uri.port)
234
- http.use_ssl = uri.scheme == "https"
235
- http.read_timeout = @read_timeout
236
- http.open_timeout = @open_timeout
237
-
238
- http.start do |conn|
239
- conn.request(request, &)
240
- end
241
- end
242
- end
243
219
  end
244
220
  end
245
221
  end
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Elelem
4
4
  module Anthropic
5
- VERSION = "0.3.1"
5
+ VERSION = "0.4.0"
6
6
  end
7
7
  end
@@ -1,11 +1,13 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "elelem"
4
+ require "elelem/http"
4
5
  require "json"
5
- require "net/http"
6
+ require "open3"
6
7
  require "uri"
7
8
 
8
9
  require_relative "anthropic/documents"
10
+ require_relative "anthropic/gcloud_token"
9
11
  require_relative "anthropic/provider"
10
12
  require_relative "anthropic/version"
11
13
 
@@ -37,9 +39,10 @@ Elelem.configure do |config|
37
39
  model ||= Elelem::Anthropic.env("VERTEX_MODEL", "claude-sonnet-5-5")
38
40
  project = Elelem::Anthropic.env("GOOGLE_CLOUD_PROJECT")
39
41
  region = Elelem::Anthropic.env("GOOGLE_CLOUD_REGION", "us-east5")
42
+ token = Elelem::Anthropic::GcloudToken.new
40
43
  Elelem::Anthropic::Provider.new(
41
44
  endpoint: "https://#{region}-aiplatform.googleapis.com/v1/projects/#{project}/locations/#{region}/publishers/anthropic/models/#{model}:streamRawPredict",
42
- headers: -> { { "Authorization" => "Bearer #{`gcloud auth application-default print-access-token`.strip}" } },
45
+ headers: -> { { "Authorization" => "Bearer #{token.call}" } },
43
46
  model: model,
44
47
  version: "vertex-2023-10-16",
45
48
  **Elelem::Anthropic::Provider.options_from(ENV)
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ RSpec.describe Elelem::Anthropic::GcloudToken do
4
+ subject(:token) { described_class.new(clock: -> { clock.first }) }
5
+
6
+ let(:clock) { [0] }
7
+ let(:ok) { instance_double(Process::Status, success?: true) }
8
+
9
+ before { allow(Open3).to receive(:capture2).and_return(["first\n", ok], ["second\n", ok]) }
10
+
11
+ it "asks gcloud once for a few minutes of requests" do
12
+ expect(Array.new(3) { token.call }).to eq(%w[first first first])
13
+ expect(Open3).to have_received(:capture2).once
14
+ end
15
+
16
+ it "asks again once the kept token is three minutes old" do
17
+ token.call
18
+ clock[0] = 179
19
+ expect(token.call).to eq("first")
20
+
21
+ clock[0] = 180
22
+ expect(token.call).to eq("second")
23
+ end
24
+
25
+ it "fails when gcloud does instead of sending an empty token" do
26
+ allow(Open3).to receive(:capture2).and_return(["", instance_double(Process::Status, success?: false)])
27
+
28
+ expect { token.call }.to raise_error(/gcloud auth application-default login/)
29
+ end
30
+ end
@@ -42,7 +42,8 @@ RSpec.describe Elelem::Anthropic::Provider do
42
42
  it "sends model and messages by default" do
43
43
  provider.fetch(messages, [])
44
44
 
45
- expect(body).to eq(max_tokens: 64_000, messages:, stream: true, model: "claude-opus-4-5-20250514")
45
+ expect(body).to eq(max_tokens: 64_000, messages:, stream: true, cache_control: { type: "ephemeral" },
46
+ model: "claude-opus-4-5-20250514")
46
47
  end
47
48
 
48
49
  it "omits tools when empty" do
@@ -63,10 +64,33 @@ RSpec.describe Elelem::Anthropic::Provider do
63
64
  it "extracts a system message out of messages" do
64
65
  provider.fetch([{ role: "system", content: "be terse" }, *messages], [])
65
66
 
66
- expect(body[:system]).to eq("be terse")
67
+ expect(body[:system]).to eq([{ type: "text", text: "be terse", cache_control: { type: "ephemeral" } }])
67
68
  expect(body[:messages]).to eq(messages)
68
69
  end
69
70
 
71
+ it "leaves out an empty system prompt" do
72
+ provider.fetch([{ role: "system", content: "" }, *messages], [])
73
+
74
+ expect(body).not_to have_key(:system)
75
+ end
76
+
77
+ it "caches the system prompt and tools, and the conversation so far" do
78
+ provider.fetch([{ role: "system", content: "be terse" }, *messages], [])
79
+
80
+ expect(body[:cache_control]).to eq(type: "ephemeral")
81
+ expect(body.dig(:system, 0, :cache_control)).to eq(type: "ephemeral")
82
+ end
83
+
84
+ it "reads events split by CRLF" do
85
+ allow(response).to receive(:read_body)
86
+ .and_yield(%(data: {"type":"content_block_delta","delta":{"type":"text_delta","text":"hi"}}\r\n\r\n))
87
+ seen = []
88
+
89
+ provider.fetch(messages, []) { |event| seen << event }
90
+
91
+ expect(seen).to eq([{ type: "saying", text: "hi" }])
92
+ end
93
+
70
94
  context "with thinking, effort and max_tokens set" do
71
95
  let(:params) { { max_tokens: 8000, thinking: { type: "adaptive", display: "summarized" }, effort: "low" } }
72
96
 
@@ -89,6 +113,56 @@ RSpec.describe Elelem::Anthropic::Provider do
89
113
  end
90
114
  end
91
115
 
116
+ context "with a tool call cut off at max_tokens" do
117
+ let(:params) { { max_tokens: 100 } }
118
+ let(:events) do
119
+ [
120
+ { "type" => "content_block_start",
121
+ "content_block" => { "type" => "tool_use", "id" => "1", "name" => "write" } },
122
+ { "type" => "content_block_delta",
123
+ "delta" => { "type" => "input_json_delta", "partial_json" => '{"path":"a.rb","con' } },
124
+ { "type" => "message_delta", "delta" => { "stop_reason" => "max_tokens" } }
125
+ ]
126
+ end
127
+
128
+ it "says so instead of failing to parse half the arguments" do
129
+ expect { provider.fetch(messages, []) {} }
130
+ .to raise_error("the reply hit max_tokens (100); raise ANTHROPIC_MAX_TOKENS")
131
+ end
132
+ end
133
+
134
+ context "with a conversation too long for the model" do
135
+ let(:events) { [{ "type" => "message_delta", "delta" => { "stop_reason" => "model_context_window_exceeded" } }] }
136
+
137
+ it "raises" do
138
+ expect { provider.fetch(messages, []) {} }.to raise_error(/no longer fits the model's context window/)
139
+ end
140
+ end
141
+
142
+ context "with a refusal" do
143
+ let(:events) { [{ "type" => "message_delta", "delta" => { "stop_reason" => "refusal" } }] }
144
+
145
+ it "raises" do
146
+ expect { provider.fetch(messages, []) {} }.to raise_error("the model declined to answer")
147
+ end
148
+ end
149
+
150
+ context "with usage" do
151
+ let(:events) do
152
+ [{ "type" => "message_start", "message" => { "usage" => { "cache_read_input_tokens" => 900 } } },
153
+ { "type" => "message_delta", "delta" => { "stop_reason" => "end_turn" }, "usage" => { "output_tokens" => 5 } }]
154
+ end
155
+
156
+ it "logs it, to show whether the cache is read" do
157
+ allow(Elelem.logger).to receive(:debug)
158
+
159
+ provider.fetch(messages, []) {}
160
+
161
+ expect(Elelem.logger).to have_received(:debug).with('anthropic: usage {"cache_read_input_tokens":900}')
162
+ expect(Elelem.logger).to have_received(:debug).with('anthropic: usage {"output_tokens":5}')
163
+ end
164
+ end
165
+
92
166
  context "with text and thinking deltas" do
93
167
  let(:events) do
94
168
  [
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: elelem-anthropic
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.3.1
4
+ version: 0.4.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - mo khan
@@ -15,7 +15,7 @@ dependencies:
15
15
  requirements:
16
16
  - - ">="
17
17
  - !ruby/object:Gem::Version
18
- version: '0.13'
18
+ version: '0.16'
19
19
  - - "<"
20
20
  - !ruby/object:Gem::Version
21
21
  version: '1'
@@ -25,7 +25,7 @@ dependencies:
25
25
  requirements:
26
26
  - - ">="
27
27
  - !ruby/object:Gem::Version
28
- version: '0.13'
28
+ version: '0.16'
29
29
  - - "<"
30
30
  - !ruby/object:Gem::Version
31
31
  version: '1'
@@ -43,20 +43,6 @@ dependencies:
43
43
  - - ">="
44
44
  - !ruby/object:Gem::Version
45
45
  version: '2.18'
46
- - !ruby/object:Gem::Dependency
47
- name: net-http
48
- requirement: !ruby/object:Gem::Requirement
49
- requirements:
50
- - - "~>"
51
- - !ruby/object:Gem::Version
52
- version: '0.9'
53
- type: :runtime
54
- prerelease: false
55
- version_requirements: !ruby/object:Gem::Requirement
56
- requirements:
57
- - - "~>"
58
- - !ruby/object:Gem::Version
59
- version: '0.9'
60
46
  - !ruby/object:Gem::Dependency
61
47
  name: uri
62
48
  requirement: !ruby/object:Gem::Requirement
@@ -92,11 +78,13 @@ files:
92
78
  - exe/elelem-cxml
93
79
  - lib/elelem/anthropic.rb
94
80
  - lib/elelem/anthropic/documents.rb
81
+ - lib/elelem/anthropic/gcloud_token.rb
95
82
  - lib/elelem/anthropic/provider.rb
96
83
  - lib/elelem/anthropic/version.rb
97
84
  - lib/elelem/vertex.rb
98
85
  - release-please-config.json
99
86
  - spec/elelem/anthropic/documents_spec.rb
87
+ - spec/elelem/anthropic/gcloud_token_spec.rb
100
88
  - spec/elelem/anthropic/options_spec.rb
101
89
  - spec/elelem/anthropic/provider_spec.rb
102
90
  - spec/elelem/anthropic/registration_spec.rb
@@ -123,7 +111,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
123
111
  - !ruby/object:Gem::Version
124
112
  version: '0'
125
113
  requirements: []
126
- rubygems_version: 4.0.6
114
+ rubygems_version: 4.0.20
127
115
  specification_version: 4
128
116
  summary: An Anthropic provider plugin for elelem.
129
117
  test_files: []