Comparing changes
v0.2.0
→
v0.3.0
10 commits
16 files changed
Commits
Changed files (16)
lib
net
spec
bin/setup
@@ -1,8 +1,8 @@
-#!/usr/bin/env bash
-set -euo pipefail
-IFS=$'\n\t'
-set -vx
+#!/bin/sh
-bundle install
+set -e
+[ -z "$DEBUG" ] || set -x
+
+cd "$(dirname "$0")/.."
-# Do any other automated setup that you need to do here
+bundle install
bin/shipit
@@ -0,0 +1,8 @@
+#!/bin/sh
+
+set -e
+[ -z "$DEBUG" ] || set -x
+
+cd "$(dirname "$0")/.."
+
+bundle exec rake release
bin/test
@@ -0,0 +1,8 @@
+#!/bin/sh
+
+set -e
+[ -z "$DEBUG" ] || set -x
+
+cd "$(dirname "$0")/.."
+
+bundle exec rspec
lib/net/llm/anthropic.rb
@@ -3,21 +3,22 @@
module Net
module Llm
class Anthropic
- attr_reader :api_key, :model
+ attr_reader :api_key, :model, :http
- def initialize(api_key:, model: "claude-3-5-sonnet-20241022")
+ def initialize(api_key:, model: "claude-3-5-sonnet-20241022", http: Net::Llm.http)
@api_key = api_key
@model = model
+ @http = http
end
def messages(messages, system: nil, max_tokens: 1024, tools: nil, &block)
- uri = URI("https://api.anthropic.com/v1/messages")
+ url = "https://api.anthropic.com/v1/messages"
payload = build_payload(messages, system, max_tokens, tools, block_given?)
if block_given?
- stream_request(uri, payload, &block)
+ stream_request(url, payload, &block)
else
- post_request(uri, payload)
+ post_request(url, payload)
end
end
@@ -35,51 +36,41 @@ module Net
payload
end
- def post_request(uri, payload)
- http = Net::HTTP.new(uri.hostname, uri.port)
- http.use_ssl = true
+ def headers
+ {
+ "x-api-key" => api_key,
+ "anthropic-version" => "2023-06-01"
+ }
+ end
- request = Net::HTTP::Post.new(uri)
- request["x-api-key"] = api_key
- request["anthropic-version"] = "2023-06-01"
- request["Content-Type"] = "application/json"
- request.body = payload.to_json
+ def post_request(url, payload)
+ handle_response(http.post(url, headers: headers, body: payload))
+ end
- response = http.start { |h| h.request(request) }
- raise "HTTP #{response.code}: #{response.body}" unless response.is_a?(Net::HTTPSuccess)
- JSON.parse(response.body)
+ def handle_response(response)
+ if response.is_a?(Net::HTTPSuccess)
+ JSON.parse(response.body)
+ else
+ { "code" => response.code, "body" => response.body }
+ end
end
- def stream_request(uri, payload, &block)
- http = Net::HTTP.new(uri.hostname, uri.port)
- http.use_ssl = true
- http.read_timeout = 3600
-
- request = Net::HTTP::Post.new(uri)
- request["x-api-key"] = api_key
- request["anthropic-version"] = "2023-06-01"
- request["Content-Type"] = "application/json"
- request.body = payload.to_json
-
- http.start do |h|
- h.request(request) do |response|
- unless response.is_a?(Net::HTTPSuccess)
- raise "HTTP #{response.code}: #{response.body}"
- end
+ def stream_request(url, payload, &block)
+ http.post(url, headers: headers, body: payload) do |response|
+ raise "HTTP #{response.code}" unless response.is_a?(Net::HTTPSuccess)
- buffer = ""
- response.read_body do |chunk|
- buffer += chunk
+ buffer = ""
+ response.read_body do |chunk|
+ buffer += chunk
- while (event = extract_sse_event(buffer))
- next if event[:data].nil? || event[:data].empty?
- next if event[:data] == "[DONE]"
+ while (event = extract_sse_event(buffer))
+ next if event[:data].nil? || event[:data].empty?
+ next if event[:data] == "[DONE]"
- json = JSON.parse(event[:data])
- block.call(json)
+ json = JSON.parse(event[:data])
+ block.call(json)
- break if json["type"] == "message_stop"
- end
+ break if json["type"] == "message_stop"
end
end
end
lib/net/llm/ollama.rb
@@ -3,111 +3,89 @@
module Net
module Llm
class Ollama
- attr_reader :host, :model
+ attr_reader :host, :model, :http
- def initialize(host: "localhost:11434", model: "llama2")
+ def initialize(host: "localhost:11434", model: "llama2", http: Net::Llm.http)
@host = host
@model = model
+ @http = http
end
def chat(messages, &block)
- uri = build_uri("/api/chat")
+ url = build_url("/api/chat")
payload = { model: model, messages: messages, stream: block_given? }
if block_given?
- stream_request(uri, payload, &block)
+ stream_request(url, payload, &block)
else
- post_request(uri, payload)
+ post_request(url, payload)
end
end
def generate(prompt, &block)
- uri = build_uri("/api/generate")
+ url = build_url("/api/generate")
payload = { model: model, prompt: prompt, stream: block_given? }
if block_given?
- stream_request(uri, payload, &block)
+ stream_request(url, payload, &block)
else
- post_request(uri, payload)
+ post_request(url, payload)
end
end
def embeddings(input)
- uri = build_uri("/api/embed")
+ url = build_url("/api/embed")
payload = { model: model, input: input }
- post_request(uri, payload)
+ post_request(url, payload)
end
def tags
- uri = build_uri("/api/tags")
- get_request(uri)
+ url = build_url("/api/tags")
+ response = http.get(url)
+ handle_response(response)
end
def show(name)
- uri = build_uri("/api/show")
+ url = build_url("/api/show")
payload = { name: name }
- post_request(uri, payload)
+ post_request(url, payload)
end
private
- def build_uri(path)
+ def build_url(path)
base = host.start_with?("http://", "https://") ? host : "http://#{host}"
- URI("#{base}#{path}")
+ "#{base}#{path}"
end
- def get_request(uri)
- http = Net::HTTP.new(uri.hostname, uri.port)
- http.use_ssl = uri.scheme == "https"
- request = Net::HTTP::Get.new(uri)
- request["Accept"] = "application/json"
-
- response = http.start { |h| h.request(request) }
- raise "HTTP #{response.code}: #{response.body}" unless response.is_a?(Net::HTTPSuccess)
- JSON.parse(response.body)
+ def post_request(url, payload)
+ response = http.post(url, body: payload)
+ handle_response(response)
end
- def post_request(uri, payload)
- http = Net::HTTP.new(uri.hostname, uri.port)
- http.use_ssl = uri.scheme == "https"
- request = Net::HTTP::Post.new(uri)
- request["Accept"] = "application/json"
- request["Content-Type"] = "application/json"
- request.body = payload.to_json
-
- response = http.start { |h| h.request(request) }
- raise "HTTP #{response.code}: #{response.body}" unless response.is_a?(Net::HTTPSuccess)
- JSON.parse(response.body)
+ def handle_response(response)
+ if response.is_a?(Net::HTTPSuccess)
+ JSON.parse(response.body)
+ else
+ { "code" => response.code, "body" => response.body }
+ end
end
- def stream_request(uri, payload, &block)
- http = Net::HTTP.new(uri.hostname, uri.port)
- http.use_ssl = uri.scheme == "https"
- http.read_timeout = 3600
-
- request = Net::HTTP::Post.new(uri)
- request["Accept"] = "application/json"
- request["Content-Type"] = "application/json"
- request.body = payload.to_json
-
- http.start do |h|
- h.request(request) do |response|
- unless response.is_a?(Net::HTTPSuccess)
- raise "HTTP #{response.code}: #{response.body}"
- end
+ def stream_request(url, payload, &block)
+ http.post(url, body: payload) do |response|
+ raise "HTTP #{response.code}" unless response.is_a?(Net::HTTPSuccess)
- buffer = ""
- response.read_body do |chunk|
- buffer += chunk
+ buffer = ""
+ response.read_body do |chunk|
+ buffer += chunk
- while (message = extract_message(buffer))
- next if message.empty?
+ while (message = extract_message(buffer))
+ next if message.empty?
- json = JSON.parse(message)
- block.call(json)
+ json = JSON.parse(message)
+ block.call(json)
- break if json["done"]
- end
+ break if json["done"]
end
end
end
lib/net/llm/openai.rb
@@ -0,0 +1,50 @@
+# frozen_string_literal: true
+
+module Net
+ module Llm
+ class OpenAI
+ attr_reader :api_key, :base_url, :model, :http
+
+ def initialize(api_key:, base_url: "https://api.openai.com/v1", model: "gpt-4o-mini", http: Net::Llm.http)
+ @api_key = api_key
+ @base_url = base_url
+ @model = model
+ @http = http
+ end
+
+ def chat(messages, tools)
+ handle_response(http.post(
+ "#{base_url}/chat/completions",
+ headers: headers,
+ body: { model: model, messages: messages, tools: tools, tool_choice: "auto" }
+ ))
+ end
+
+ def models
+ handle_response(http.get("#{base_url}/models", headers: headers))
+ end
+
+ def embeddings(input, model: "text-embedding-ada-002")
+ handle_response(http.post(
+ "#{base_url}/embeddings",
+ headers: headers,
+ body: { model: model, input: input },
+ ))
+ end
+
+ private
+
+ def headers
+ { "Authorization" => Net::Hippie.bearer_auth(api_key) }
+ end
+
+ def handle_response(response)
+ if response.is_a?(Net::HTTPSuccess)
+ JSON.parse(response.body)
+ else
+ { "code" => response.code, "body" => response.body }
+ end
+ end
+ end
+ end
+end
lib/net/llm/version.rb
@@ -2,6 +2,6 @@
module Net
module Llm
- VERSION = "0.2.0"
+ VERSION = "0.3.0"
end
end
lib/net/llm.rb
@@ -1,76 +1,21 @@
# frozen_string_literal: true
require_relative "llm/version"
+require_relative "llm/openai"
require_relative "llm/ollama"
require_relative "llm/anthropic"
-require "net/http"
+require "net/hippie"
require "json"
-require "uri"
module Net
module Llm
class Error < StandardError; end
- DEFAULT_TIMEOUT = 60 * 2
- class OpenAI
- attr_reader :api_key, :base_url, :model
-
- def initialize(api_key:, base_url: "https://api.openai.com/v1", model: "gpt-4o-mini")
- @api_key = api_key
- @base_url = base_url
- @model = model
- end
-
- def chat(messages, tools, timeout: DEFAULT_TIMEOUT)
- uri = URI("#{base_url}/chat/completions")
- request = Net::HTTP::Post.new(uri)
- request["Authorization"] = "Bearer #{api_key}"
- request["Content-Type"] = "application/json"
- request.body = { model: model, messages: messages, tools: tools, tool_choice: "auto" }.to_json
-
- http = Net::HTTP.new(uri.hostname, uri.port)
- http.use_ssl = true
- http.open_timeout = timeout
- http.read_timeout = timeout
- http.write_timeout = timeout if http.respond_to?(:write_timeout=)
-
- response = http.start { |h| h.request(request) }
- raise "HTTP #{response.code}: #{response.body}" unless response.is_a?(Net::HTTPSuccess)
- JSON.parse(response.body)
- end
-
- def models(timeout: DEFAULT_TIMEOUT)
- uri = URI("#{base_url}/models")
- request = Net::HTTP::Get.new(uri)
- request["Authorization"] = "Bearer #{api_key}"
-
- http = Net::HTTP.new(uri.hostname, uri.port)
- http.use_ssl = true
- http.open_timeout = timeout
- http.read_timeout = timeout
-
- response = http.start { |h| h.request(request) }
- raise "HTTP #{response.code}: #{response.body}" unless response.is_a?(Net::HTTPSuccess)
- JSON.parse(response.body)
- end
-
- def embeddings(input, model: "text-embedding-ada-002", timeout: DEFAULT_TIMEOUT)
- uri = URI("#{base_url}/embeddings")
- request = Net::HTTP::Post.new(uri)
- request["Authorization"] = "Bearer #{api_key}"
- request["Content-Type"] = "application/json"
- request.body = { model: model, input: input }.to_json
-
- http = Net::HTTP.new(uri.hostname, uri.port)
- http.use_ssl = true
- http.open_timeout = timeout
- http.read_timeout = timeout
- http.write_timeout = timeout if http.respond_to?(:write_timeout=)
-
- response = http.start { |h| h.request(request) }
- raise "HTTP #{response.code}: #{response.body}" unless response.is_a?(Net::HTTPSuccess)
- JSON.parse(response.body)
- end
+ def self.http
+ @http ||= Net::Hippie::Client.new(
+ read_timeout: 3600,
+ open_timeout: 10
+ )
end
end
end
spec/net/llm/anthropic_spec.rb
@@ -81,7 +81,9 @@ RSpec.describe Net::Llm::Anthropic do
stub_request(:post, "https://api.anthropic.com/v1/messages")
.to_return(status: 401, body: "Unauthorized")
- expect { client.messages(messages) }.to raise_error(/HTTP 401/)
+ result = client.messages(messages)
+ expect(result["code"]).to eq("401")
+ expect(result["body"]).to eq("Unauthorized")
end
end
spec/net/llm/ollama_spec.rb
@@ -57,7 +57,9 @@ RSpec.describe Net::Llm::Ollama do
stub_request(:post, "http://localhost:11434/api/chat")
.to_return(status: 500, body: "Server error")
- expect { client.chat(messages) }.to raise_error(/HTTP 500/)
+ result = client.chat(messages)
+ expect(result["code"]).to eq("500")
+ expect(result["body"]).to eq("Server error")
end
end
spec/net/llm/openai_spec.rb
@@ -0,0 +1,124 @@
+# frozen_string_literal: true
+
+RSpec.describe Net::Llm::OpenAI do
+ let(:api_key) { "test-key" }
+ let(:client) { described_class.new(api_key: api_key) }
+
+ describe "#initialize" do
+ it "sets default base_url" do
+ expect(client.base_url).to eq("https://api.openai.com/v1")
+ end
+
+ it "sets default model" do
+ expect(client.model).to eq("gpt-4o-mini")
+ end
+
+ it "allows custom base_url" do
+ custom_client = described_class.new(api_key: api_key, base_url: "https://custom.com/v1")
+ expect(custom_client.base_url).to eq("https://custom.com/v1")
+ end
+
+ it "allows custom model" do
+ custom_client = described_class.new(api_key: api_key, model: "gpt-4")
+ expect(custom_client.model).to eq("gpt-4")
+ end
+ end
+
+ describe "#chat" do
+ let(:messages) { [{ role: "user", content: "Hello" }] }
+ let(:tools) { [] }
+ let(:response_body) { { choices: [{ message: { content: "Hi" } }] }.to_json }
+
+ it "makes a POST request to chat/completions" do
+ stub_request(:post, "https://api.openai.com/v1/chat/completions")
+ .with(
+ headers: {
+ "Authorization" => "Bearer #{api_key}",
+ "Content-Type" => "application/json"
+ },
+ body: hash_including(
+ model: "gpt-4o-mini",
+ messages: messages,
+ tools: tools,
+ tool_choice: "auto"
+ )
+ )
+ .to_return(status: 200, body: response_body)
+
+ result = client.chat(messages, tools)
+ expect(result["choices"][0]["message"]["content"]).to eq("Hi")
+ end
+
+ it "raises on HTTP error" do
+ stub_request(:post, "https://api.openai.com/v1/chat/completions")
+ .to_return(status: 401, body: "Unauthorized")
+
+ result = client.chat(messages, tools)
+ expect(result["code"]).to eq("401")
+ expect(result["body"]).to eq("Unauthorized")
+ end
+ end
+
+ describe "#models" do
+ let(:response_body) { { data: [{ id: "gpt-4o-mini" }] }.to_json }
+
+ it "makes a GET request to models" do
+ stub_request(:get, "https://api.openai.com/v1/models")
+ .with(headers: { "Authorization" => "Bearer #{api_key}" })
+ .to_return(status: 200, body: response_body)
+
+ result = client.models
+ expect(result["data"]).to be_an(Array)
+ expect(result["data"][0]["id"]).to eq("gpt-4o-mini")
+ end
+
+ it "raises on HTTP error" do
+ stub_request(:get, "https://api.openai.com/v1/models")
+ .to_return(status: 500, body: "Server error")
+
+ result = client.models
+ expect(result["code"]).to eq("500")
+ expect(result["body"]).to eq("Server error")
+ end
+ end
+
+ describe "#embeddings" do
+ let(:input) { "Hello world" }
+ let(:response_body) { { data: [{ embedding: [0.1, 0.2, 0.3] }] }.to_json }
+
+ it "makes a POST request to embeddings" do
+ stub_request(:post, "https://api.openai.com/v1/embeddings")
+ .with(
+ headers: {
+ "Authorization" => "Bearer #{api_key}",
+ "Content-Type" => "application/json"
+ },
+ body: hash_including(
+ model: "text-embedding-ada-002",
+ input: input
+ )
+ )
+ .to_return(status: 200, body: response_body)
+
+ result = client.embeddings(input)
+ expect(result["data"][0]["embedding"]).to eq([0.1, 0.2, 0.3])
+ end
+
+ it "allows custom model" do
+ stub_request(:post, "https://api.openai.com/v1/embeddings")
+ .with(body: hash_including(model: "text-embedding-3-small"))
+ .to_return(status: 200, body: response_body)
+
+ client.embeddings(input, model: "text-embedding-3-small")
+ end
+
+ it "raises on HTTP error" do
+ stub_request(:post, "https://api.openai.com/v1/embeddings")
+ .to_return(status: 400, body: "Bad request")
+
+ result = client.embeddings(input)
+ expect(result["code"]).to eq("400")
+ expect(result["body"]).to eq("Bad request")
+ end
+ end
+end
spec/net/llm_spec.rb
@@ -5,120 +5,3 @@ RSpec.describe Net::Llm do
expect(Net::Llm::VERSION).not_to be nil
end
end
-
-RSpec.describe Net::Llm::OpenAI do
- let(:api_key) { "test-key" }
- let(:client) { described_class.new(api_key: api_key) }
-
- describe "#initialize" do
- it "sets default base_url" do
- expect(client.base_url).to eq("https://api.openai.com/v1")
- end
-
- it "sets default model" do
- expect(client.model).to eq("gpt-4o-mini")
- end
-
- it "allows custom base_url" do
- custom_client = described_class.new(api_key: api_key, base_url: "https://custom.com/v1")
- expect(custom_client.base_url).to eq("https://custom.com/v1")
- end
-
- it "allows custom model" do
- custom_client = described_class.new(api_key: api_key, model: "gpt-4")
- expect(custom_client.model).to eq("gpt-4")
- end
- end
-
- describe "#chat" do
- let(:messages) { [{ role: "user", content: "Hello" }] }
- let(:tools) { [] }
- let(:response_body) { { choices: [{ message: { content: "Hi" } }] }.to_json }
-
- it "makes a POST request to chat/completions" do
- stub_request(:post, "https://api.openai.com/v1/chat/completions")
- .with(
- headers: {
- "Authorization" => "Bearer #{api_key}",
- "Content-Type" => "application/json"
- },
- body: hash_including(
- model: "gpt-4o-mini",
- messages: messages,
- tools: tools,
- tool_choice: "auto"
- )
- )
- .to_return(status: 200, body: response_body)
-
- result = client.chat(messages, tools)
- expect(result["choices"][0]["message"]["content"]).to eq("Hi")
- end
-
- it "raises on HTTP error" do
- stub_request(:post, "https://api.openai.com/v1/chat/completions")
- .to_return(status: 401, body: "Unauthorized")
-
- expect { client.chat(messages, tools) }.to raise_error(/HTTP 401/)
- end
- end
-
- describe "#models" do
- let(:response_body) { { data: [{ id: "gpt-4o-mini" }] }.to_json }
-
- it "makes a GET request to models" do
- stub_request(:get, "https://api.openai.com/v1/models")
- .with(headers: { "Authorization" => "Bearer #{api_key}" })
- .to_return(status: 200, body: response_body)
-
- result = client.models
- expect(result["data"]).to be_an(Array)
- expect(result["data"][0]["id"]).to eq("gpt-4o-mini")
- end
-
- it "raises on HTTP error" do
- stub_request(:get, "https://api.openai.com/v1/models")
- .to_return(status: 500, body: "Server error")
-
- expect { client.models }.to raise_error(/HTTP 500/)
- end
- end
-
- describe "#embeddings" do
- let(:input) { "Hello world" }
- let(:response_body) { { data: [{ embedding: [0.1, 0.2, 0.3] }] }.to_json }
-
- it "makes a POST request to embeddings" do
- stub_request(:post, "https://api.openai.com/v1/embeddings")
- .with(
- headers: {
- "Authorization" => "Bearer #{api_key}",
- "Content-Type" => "application/json"
- },
- body: hash_including(
- model: "text-embedding-ada-002",
- input: input
- )
- )
- .to_return(status: 200, body: response_body)
-
- result = client.embeddings(input)
- expect(result["data"][0]["embedding"]).to eq([0.1, 0.2, 0.3])
- end
-
- it "allows custom model" do
- stub_request(:post, "https://api.openai.com/v1/embeddings")
- .with(body: hash_including(model: "text-embedding-3-small"))
- .to_return(status: 200, body: response_body)
-
- client.embeddings(input, model: "text-embedding-3-small")
- end
-
- it "raises on HTTP error" do
- stub_request(:post, "https://api.openai.com/v1/embeddings")
- .to_return(status: 400, body: "Bad request")
-
- expect { client.embeddings(input) }.to raise_error(/HTTP 400/)
- end
- end
-end
CHANGELOG.md
@@ -1,5 +1,14 @@
## [Unreleased]
+## [0.3.0] - 2025-10-08
+### Changed
+- Refactored all providers to use net-hippie HTTP client
+- Reduced code duplication across providers
+- Improved error handling consistency
+
+### Added
+- Added net-hippie dependency for cleaner HTTP interactions
+
## [0.2.0] - 2025-10-08
- Add Ollama provider with streaming support
Gemfile
@@ -11,3 +11,5 @@ gem "rake", "~> 13.0"
gem "rspec", "~> 3.0"
gem "webmock", "~> 3.25", group: :development
+
+gem "net-hippie", "~> 1.4"
Gemfile.lock
@@ -1,7 +1,7 @@
PATH
remote: .
specs:
- net-llm (0.2.0)
+ net-llm (0.3.0)
json (~> 2.0)
net-http (~> 0.6)
uri (~> 1.0)
@@ -11,6 +11,7 @@ GEM
specs:
addressable (2.8.7)
public_suffix (>= 2.0.2, < 7.0)
+ base64 (0.3.0)
bigdecimal (3.3.0)
cgi (0.4.2)
crack (1.0.0)
@@ -26,8 +27,16 @@ GEM
rdoc (>= 4.0.0)
reline (>= 0.4.2)
json (2.13.2)
+ logger (1.7.0)
+ net-hippie (1.4.0)
+ base64 (~> 0.1)
+ json (~> 2.0)
+ logger (~> 1.0)
+ net-http (~> 0.6)
+ openssl (~> 3.0)
net-http (0.6.0)
uri
+ openssl (3.3.1)
psych (5.2.2)
date
stringio
@@ -65,6 +74,7 @@ PLATFORMS
DEPENDENCIES
irb
+ net-hippie (~> 1.4)
net-llm!
rake (~> 13.0)
rspec (~> 3.0)
README.md
@@ -171,6 +171,22 @@ tools = [
response = client.messages(messages, tools: tools)
```
+## Error Handling
+
+All non-streaming API methods return error information as a hash when requests fail:
+
+```ruby
+response = client.chat(messages, tools)
+
+if response["code"]
+ puts "Error #{response["code"]}: #{response["body"]}"
+else
+ puts response.dig('choices', 0, 'message', 'content')
+end
+```
+
+Streaming methods still raise exceptions on HTTP errors.
+
## API Coverage
### OpenAI