anthropic-rb 0.4.0 → 0.5.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: b5e066105f3157621c27e2f974ed43bde9f14e6e55187d1d7a4f095b79a5a1ba
4
- data.tar.gz: f32d479f7ec06c29a0347f69084a4378a64d69233d78ed280f5a1c924e15d708
3
+ metadata.gz: 47751095db1f8f6ad2e30c5161f0137dd8eba0838a2c0a2ccce8cb51aefa278e
4
+ data.tar.gz: 5de9082d8b07c9f19ec20eeb4dee0525f7797585dbcb208563b85ef040bd2f0f
5
5
  SHA512:
6
- metadata.gz: 90040c86504a3dfd28e0093d1b8525252387f4e978271908aa158d1cffe10a3dd5766aadc243bc31f45ca6dd38ecf1259d009b2da9f2f78670fcc114c76574a3
7
- data.tar.gz: 8ca46c62fe204b3b2403cce1267b6661f43c52159c8d31877b9d2522be604427996eedcbac67ba22a1b6df703259ededd98ea2b86d49755d7aa057835458321c
6
+ metadata.gz: 4d5be01a84c735f0bf815cba09cd591da94085cf65cf5387c839eba1f3b0c52ed1af63f26b7044d0d8a1c968bfb10bb7efe030f560e378c4ca7b1e70a5e37d44
7
+ data.tar.gz: c8dd64d95f97c348839e12cc52bbdbdbbaccab310eeff232db99120bcc74584c31781296686d3a9fac6077f94492311d6c49c22b9f330f8754038b8ff958f180
data/.reek.yml CHANGED
@@ -4,10 +4,22 @@ detectors:
4
4
  - Anthropic#self.api_key=
5
5
  TooManyStatements:
6
6
  exclude:
7
+ - 'Anthropic::Api::Concerns::Validatable#schema'
8
+ - 'Anthropic::BaseApi#beta_config'
9
+ - 'Anthropic::BaseApi#version_config'
10
+ - 'Anthropic::Bootstrapper#self.load_betas'
11
+ - 'Anthropic::Bootstrapper#self.load_versions'
7
12
  - 'Anthropic::Client#self.post'
8
13
  BooleanParameter:
9
14
  exclude:
10
15
  - 'Anthropic::Messages#initialize'
11
16
  DuplicateMethodCall:
12
17
  exclude:
18
+ - 'Anthropic::BaseApi#version_config'
13
19
  - 'Anthropic::Messages#create'
20
+ InstanceVariableAssumption:
21
+ exclude:
22
+ - 'Anthropic::BaseApi'
23
+ NestedIterators:
24
+ exclude:
25
+ - 'Anthropic::Bootstrapper#self.load_versions'
data/CHANGELOG.md CHANGED
@@ -2,6 +2,15 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.5.0] - 2024-04-22
6
+
7
+ ### Updated
8
+
9
+ - Refactored project for maintainability.
10
+
11
+ ### Breaking Changes
12
+ - You must now pass the beta ID when enabling a beta feature. The only current beta is for Tools (id: tools-2024-04-04). Previously, you would pass `true` to enable the beta.
13
+
5
14
  ## [0.4.0] - 2024-04-20
6
15
 
7
16
  ### Added
@@ -57,7 +66,8 @@
57
66
 
58
67
  - Initial release
59
68
 
60
- [Unreleased]: https://github.com/dickdavis/anthropic-rb/compare/v0.4.0...HEAD
69
+ [Unreleased]: https://github.com/dickdavis/anthropic-rb/compare/v0.5.0...HEAD
70
+ [0.5.0]: https://github.com/dickdavis/anthropic-rb/compare/v0.4.0...v0.5.0
61
71
  [0.4.0]: https://github.com/dickdavis/anthropic-rb/compare/v0.3.0...v0.4.0
62
72
  [0.3.0]: https://github.com/dickdavis/anthropic-rb/compare/v0.2.5...v0.3.0
63
73
  [0.2.5]: https://github.com/dickdavis/anthropic-rb/compare/v0.2.3...v0.2.5
data/README.md CHANGED
@@ -62,7 +62,7 @@ end
62
62
  # { type: 'message_stop' }
63
63
  ```
64
64
 
65
- You can also experiment with the new tools beta by passing the `beta` flag when calling the API. This will ensure each request includes the correct beta header.
65
+ You can also experiment with the new tools beta by passing the `beta` name when calling the API. This will ensure each request includes the correct beta header and validate properly.
66
66
 
67
67
  ```ruby
68
68
  tools = [
@@ -79,7 +79,7 @@ tools = [
79
79
  }
80
80
  ]
81
81
 
82
- Anthropic.messages(beta: true).create(
82
+ Anthropic.messages(beta: 'tools-2024-04-04').create(
83
83
  model: 'claude-3-opus-20240229',
84
84
  max_tokens: 200,
85
85
  tools:,
data/anthropic-rb.gemspec CHANGED
@@ -24,7 +24,7 @@ Gem::Specification.new do |spec|
24
24
  (File.expand_path(f) == __FILE__) ||
25
25
  f.start_with?(*%w[bin/ spec/ .git .github/ Gemfile])
26
26
  end
27
- end
27
+ end + Dir.glob('lib/**/*.json')
28
28
  spec.bindir = 'exe'
29
29
  spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
30
30
  spec.require_paths = ['lib']
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'concerns/requestable'
4
+ require_relative 'concerns/validatable'
5
+
6
+ module Anthropic
7
+ ##
8
+ # Provides a base class for APIs
9
+ class BaseApi
10
+ include Anthropic::Api::Concerns::Requestable
11
+ include Anthropic::Api::Concerns::Validatable
12
+
13
+ def initialize(beta: nil)
14
+ @beta = beta
15
+ end
16
+
17
+ private
18
+
19
+ attr_reader :beta
20
+
21
+ def api
22
+ self.class.name.split('::').last.downcase
23
+ end
24
+
25
+ def version_config
26
+ return @version_config if defined?(@version_config)
27
+
28
+ @version_config ||= catch(:version_found) do
29
+ found_config = Anthropic.versions[api.to_sym].find { |config| config['version'] == Anthropic.api_version }
30
+ unless found_config
31
+ raise Anthropic::Errors::UnsupportedApiVersionError, "Unsupported API version: #{Anthropic.api_version}"
32
+ end
33
+
34
+ throw :version_found, found_config
35
+ end
36
+ end
37
+
38
+ def beta_config
39
+ return @beta_config if defined?(@beta_config)
40
+
41
+ @beta_config = catch(:beta_found) do
42
+ found_config = Anthropic.betas.find { |config| config['id'] == beta }
43
+ raise Anthropic::Errors::UnsupportedBetaError, "#{beta} not supported" unless found_config
44
+
45
+ throw :beta_found, found_config
46
+ end
47
+ end
48
+
49
+ def beta_loaded?(name)
50
+ return false unless beta
51
+
52
+ beta_config['id'] == name
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Anthropic
4
+ module Api
5
+ ##
6
+ # Provides bindings for the Anthropic completions API
7
+ class Completions < BaseApi
8
+ def create(**params, &)
9
+ validate!(params)
10
+ return post(params) unless params[:stream]
11
+
12
+ post_as_stream(params, &)
13
+ end
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Anthropic
4
+ module Api
5
+ module Concerns
6
+ ##
7
+ # Provides helpers for sending API requests
8
+ module Requestable
9
+ def post(params)
10
+ Anthropic::Client.post(uri, params, additional_headers)
11
+ end
12
+
13
+ def post_as_stream(params, &)
14
+ Anthropic::Client.post_as_stream(uri, params, additional_headers, &)
15
+ end
16
+
17
+ def uri
18
+ "#{Anthropic.api_host}#{version_config['endpoint']}"
19
+ end
20
+
21
+ def additional_headers
22
+ {}.merge(beta_headers)
23
+ end
24
+
25
+ def beta_headers
26
+ return {} unless beta
27
+
28
+ header = beta_config['header']
29
+ raise Anthropic::Errors::InvalidBetaConfigurationError, "Missing header: #{beta}" unless header
30
+
31
+ header
32
+ end
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Anthropic
4
+ module Api
5
+ module Concerns
6
+ ##
7
+ # Provides helpers for validating params against the API schema
8
+ module Validatable
9
+ def validate!(params)
10
+ JSON::Validator.validate!(schema, params)
11
+ rescue JSON::Schema::ValidationError => error
12
+ raise Anthropic::Errors::SchemaValidationError, error.message
13
+ end
14
+
15
+ def schema
16
+ api_schema = version_config['schema']
17
+
18
+ unless api_schema
19
+ raise Anthropic::Errors::MissingSchemaError, "Missing schema for API version: #{Anthropic.api_version}"
20
+ end
21
+
22
+ if beta
23
+ beta_schema = beta_config['schema']
24
+ raise Anthropic::Errors::InvalidBetaConfigurationError, "Missing beta schema: #{beta}" unless beta_schema
25
+
26
+ api_schema['properties'].merge!(beta_schema)
27
+ end
28
+
29
+ api_schema
30
+ end
31
+ end
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Anthropic
4
+ module Api
5
+ ##
6
+ # Provides bindings for the Anthropic messages API
7
+ class Messages < BaseApi
8
+ def create(**params, &)
9
+ streaming = params[:stream]
10
+ if streaming && beta_loaded?('tools-2024-04-04')
11
+ raise Anthropic::Errors::UnsupportedBetaUseError, 'Tool use is not yet supported in streaming mode'
12
+ end
13
+
14
+ validate!(params)
15
+ return post(params) unless streaming
16
+
17
+ post_as_stream(params, &)
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,26 @@
1
+ {
2
+ "id": "tools-2024-04-04",
3
+ "name": "Tools",
4
+ "description": "Equips Claude with custom tools for interacting with clients for a wide variety of tasks.",
5
+ "documentation": "https://docs.anthropic.com/claude/docs/tool-use",
6
+ "header" : { "anthropic-beta": "tools-2024-04-04" },
7
+ "schema": {
8
+ "tools": {
9
+ "type": "array",
10
+ "items": {
11
+ "type": "object",
12
+ "properties": {
13
+ "name": {
14
+ "type": "string"
15
+ },
16
+ "description": {
17
+ "type": "string"
18
+ },
19
+ "input_schema": {
20
+ "type": "object"
21
+ }
22
+ }
23
+ }
24
+ }
25
+ }
26
+ }
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'httpx'
4
+
5
+ module Anthropic
6
+ ##
7
+ # Provides methods for bootstrapping the Anthropic gem
8
+ module Bootstrapper
9
+ def self.load_betas
10
+ current_dir = File.dirname(__FILE__)
11
+ directory_path = File.join(current_dir, 'betas')
12
+
13
+ raise "Directory not found: #{directory_path}" unless Dir.exist?(directory_path)
14
+
15
+ file_paths = Dir.glob(File.join(directory_path, '*.json'))
16
+
17
+ file_paths.map do |file_path|
18
+ JSON.parse(File.read(file_path))
19
+ end
20
+ end
21
+
22
+ # rubocop:disable Metrics/MethodLength, Metrics/AbcSize
23
+ def self.load_versions
24
+ current_dir = File.dirname(__FILE__)
25
+ directory_path = File.join(current_dir, 'versions')
26
+
27
+ raise "Directory not found: #{directory_path}" unless Dir.exist?(directory_path)
28
+
29
+ versions = {}
30
+
31
+ Dir.glob(File.join(directory_path, '*')).each do |subdirectory_path|
32
+ next unless File.directory?(subdirectory_path)
33
+
34
+ subdirectory_name = File.basename(subdirectory_path)
35
+ file_paths = Dir.glob(File.join(subdirectory_path, '*.json'))
36
+
37
+ versions[subdirectory_name.to_sym] = file_paths.map do |file_path|
38
+ JSON.parse(File.read(file_path))
39
+ end
40
+ end
41
+
42
+ versions
43
+ end
44
+ # rubocop:enable Metrics/MethodLength, Metrics/AbcSize
45
+ end
46
+ end
@@ -3,31 +3,6 @@
3
3
  require 'httpx'
4
4
 
5
5
  module Anthropic
6
- ##
7
- # Error when the request is malformed.
8
- class BadRequestError < StandardError; end
9
- ##
10
- # Error when the API key is invalid.
11
- class AuthenticationError < StandardError; end
12
- ##
13
- # Error when the account does not have permission for the operation.
14
- class PermissionDeniedError < StandardError; end
15
- ##
16
- # Error when the resource is not found.
17
- class NotFoundError < StandardError; end
18
- ##
19
- # Error when the resource already exists.
20
- class ConflictError < StandardError; end
21
- ##
22
- # Error when the resource cannot be processed.
23
- class UnprocessableEntityError < StandardError; end
24
- ##
25
- # Error when the request exceeds the rate limit.
26
- class RateLimitError < StandardError; end
27
- ##
28
- # Error when the server experienced an internal error.
29
- class InternalServerError < StandardError; end
30
-
31
6
  ##
32
7
  # Provides a client for sending HTTP requests.
33
8
  class Client
@@ -47,21 +22,21 @@ module Anthropic
47
22
  when 200
48
23
  response_body
49
24
  when 400
50
- raise Anthropic::BadRequestError, response_body
25
+ raise Anthropic::Errors::BadRequestError, response_body
51
26
  when 401
52
- raise Anthropic::AuthenticationError, response_body
27
+ raise Anthropic::Errors::AuthenticationError, response_body
53
28
  when 403
54
- raise Anthropic::PermissionDeniedError, response_body
29
+ raise Anthropic::Errors::PermissionDeniedError, response_body
55
30
  when 404
56
- raise Anthropic::NotFoundError, response_body
31
+ raise Anthropic::Errors::NotFoundError, response_body
57
32
  when 409
58
- raise Anthropic::ConflictError, response_body
33
+ raise Anthropic::Errors::ConflictError, response_body
59
34
  when 422
60
- raise Anthropic::UnprocessableEntityError, response_body
35
+ raise Anthropic::Errors::UnprocessableEntityError, response_body
61
36
  when 429
62
- raise Anthropic::RateLimitError, response_body
37
+ raise Anthropic::Errors::RateLimitError, response_body
63
38
  when 500
64
- raise Anthropic::InternalServerError, response_body
39
+ raise Anthropic::Errors::InternalServerError, response_body
65
40
  end
66
41
  end
67
42
 
@@ -86,21 +61,21 @@ module Anthropic
86
61
  rescue HTTPX::HTTPError => error
87
62
  case error.response.status
88
63
  when 400
89
- raise Anthropic::BadRequestError
64
+ raise Anthropic::Errors::BadRequestError
90
65
  when 401
91
- raise Anthropic::AuthenticationError
66
+ raise Anthropic::Errors::AuthenticationError
92
67
  when 403
93
- raise Anthropic::PermissionDeniedError
68
+ raise Anthropic::Errors::PermissionDeniedError
94
69
  when 404
95
- raise Anthropic::NotFoundError
70
+ raise Anthropic::Errors::NotFoundError
96
71
  when 409
97
- raise Anthropic::ConflictError
72
+ raise Anthropic::Errors::ConflictError
98
73
  when 422
99
- raise Anthropic::UnprocessableEntityError
74
+ raise Anthropic::Errors::UnprocessableEntityError
100
75
  when 429
101
- raise Anthropic::RateLimitError
76
+ raise Anthropic::Errors::RateLimitError
102
77
  when 500
103
- raise Anthropic::InternalServerError
78
+ raise Anthropic::Errors::InternalServerError
104
79
  end
105
80
  end
106
81
  # rubocop:enable Metrics/AbcSize, Metrics/MethodLength, Metrics/CyclomaticComplexity
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Anthropic
4
+ module Errors
5
+ # Error for when the provided beta is not supported
6
+ class UnsupportedBetaError < StandardError; end
7
+
8
+ # Error for when a beta feature is configured incorrectly
9
+ class InvalidBetaConfigurationError < StandardError; end
10
+
11
+ # Error for when a beta feature is not used correctly
12
+ class UnsupportedBetaUseError < StandardError; end
13
+ end
14
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Anthropic
4
+ module Errors
5
+ ##
6
+ # Error when the request is malformed.
7
+ class BadRequestError < StandardError; end
8
+ ##
9
+ # Error when the API key is invalid.
10
+ class AuthenticationError < StandardError; end
11
+ ##
12
+ # Error when the account does not have permission for the operation.
13
+ class PermissionDeniedError < StandardError; end
14
+ ##
15
+ # Error when the resource is not found.
16
+ class NotFoundError < StandardError; end
17
+ ##
18
+ # Error when the resource already exists.
19
+ class ConflictError < StandardError; end
20
+ ##
21
+ # Error when the resource cannot be processed.
22
+ class UnprocessableEntityError < StandardError; end
23
+ ##
24
+ # Error when the request exceeds the rate limit.
25
+ class RateLimitError < StandardError; end
26
+ ##
27
+ # Error when the server experienced an internal error.
28
+ class InternalServerError < StandardError; end
29
+ end
30
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Anthropic
4
+ module Errors
5
+ # Error for when the API version is not supported.
6
+ class UnsupportedApiVersionError < StandardError; end
7
+
8
+ # Error for when API version is missing a schema.
9
+ class MissingSchemaError < StandardError; end
10
+
11
+ # Error for when the provided params do not match the API schema
12
+ class SchemaValidationError < StandardError; end
13
+ end
14
+ end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Anthropic
4
- VERSION = '0.4.0'
4
+ VERSION = '0.5.0'
5
5
  end
@@ -0,0 +1,45 @@
1
+ {
2
+ "version": "2023-06-01",
3
+ "endpoint": "/v1/complete",
4
+ "schema": {
5
+ "type": "object",
6
+ "required": [
7
+ "model",
8
+ "prompt",
9
+ "max_tokens_to_sample"
10
+ ],
11
+ "properties": {
12
+ "model": {
13
+ "type": "string"
14
+ },
15
+ "prompt": {
16
+ "type": "string"
17
+ },
18
+ "max_tokens_to_sample": {
19
+ "type": "integer"
20
+ },
21
+ "stop_sequences": {
22
+ "type": "array",
23
+ "items": {
24
+ "type": "string"
25
+ }
26
+ },
27
+ "temperature": {
28
+ "type": "number"
29
+ },
30
+ "top_k": {
31
+ "type": "integer"
32
+ },
33
+ "top_p": {
34
+ "type": "number"
35
+ },
36
+ "metadata": {
37
+ "type": "object"
38
+ },
39
+ "stream": {
40
+ "type": "boolean"
41
+ }
42
+ },
43
+ "additionalProperties": false
44
+ }
45
+ }
@@ -0,0 +1,48 @@
1
+ {
2
+ "version": "2023-06-01",
3
+ "endpoint": "/v1/messages",
4
+ "schema": {
5
+ "type": "object",
6
+ "required": [
7
+ "model",
8
+ "messages",
9
+ "max_tokens"
10
+ ],
11
+ "properties": {
12
+ "model": {
13
+ "type": "string"
14
+ },
15
+ "messages": {
16
+ "type": "array"
17
+ },
18
+ "max_tokens": {
19
+ "type": "integer"
20
+ },
21
+ "system": {
22
+ "type": "string"
23
+ },
24
+ "stop_sequences": {
25
+ "type": "array",
26
+ "items": {
27
+ "type": "string"
28
+ }
29
+ },
30
+ "temperature": {
31
+ "type": "number"
32
+ },
33
+ "top_k": {
34
+ "type": "integer"
35
+ },
36
+ "top_p": {
37
+ "type": "number"
38
+ },
39
+ "metadata": {
40
+ "type": "object"
41
+ },
42
+ "stream": {
43
+ "type": "boolean"
44
+ }
45
+ },
46
+ "additionalProperties": false
47
+ }
48
+ }
data/lib/anthropic.rb CHANGED
@@ -4,24 +4,20 @@ require 'httpx'
4
4
  require 'json'
5
5
  require 'json-schema'
6
6
 
7
- require_relative 'anthropic/client'
8
- require_relative 'anthropic/completions'
9
- require_relative 'anthropic/messages'
10
- require_relative 'anthropic/version'
7
+ Dir[File.join(__dir__, 'anthropic/', '**', '*.rb')].each { |file| require_relative file }
11
8
 
12
9
  ##
13
10
  # Namespace for anthropic-rb gem
14
11
  module Anthropic
15
- ##
16
- # Default error class
17
- class Error < StandardError; end
18
-
19
12
  def self.setup
20
13
  yield self
14
+ @betas = Bootstrapper.load_betas
15
+ @versions = Bootstrapper.load_versions
21
16
  end
22
17
 
23
18
  def self.reset
24
19
  @api_key = nil
20
+ @api_host = nil
25
21
  @api_version = nil
26
22
  end
27
23
 
@@ -33,6 +29,14 @@ module Anthropic
33
29
  @api_key = api_key
34
30
  end
35
31
 
32
+ def self.api_host
33
+ @api_host || ENV.fetch('ANTHROPIC_API_HOST', 'https://api.anthropic.com')
34
+ end
35
+
36
+ def self.api_host=(api_host = nil)
37
+ @api_host = api_host
38
+ end
39
+
36
40
  def self.api_version
37
41
  @api_version || ENV.fetch('ANTHROPIC_API_VERSION', '2023-06-01')
38
42
  end
@@ -41,11 +45,19 @@ module Anthropic
41
45
  @api_version = api_version
42
46
  end
43
47
 
48
+ def self.betas
49
+ @betas
50
+ end
51
+
52
+ def self.versions
53
+ @versions
54
+ end
55
+
44
56
  def self.completions
45
- Completions.new
57
+ Anthropic::Api::Completions.new
46
58
  end
47
59
 
48
60
  def self.messages(...)
49
- Messages.new(...)
61
+ Anthropic::Api::Messages.new(...)
50
62
  end
51
63
  end
data/sanity_check.rb ADDED
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'anthropic'
4
+
5
+ Anthropic.setup do |config|
6
+ config.api_key = ENV.fetch('ANTHROPIC_API_KEY')
7
+ end
8
+
9
+ puts "\nTesting non-streaming messages API"
10
+ puts Anthropic.messages.create(
11
+ model: 'claude-2.1',
12
+ max_tokens: 200,
13
+ messages: [{ role: 'user', content: 'Yo what up?' }]
14
+ )
15
+
16
+ puts "\nTesting streaming messages API"
17
+ Anthropic.messages.create(
18
+ model: 'claude-2.1',
19
+ max_tokens: 200,
20
+ messages: [{ role: 'user', content: 'Yo what up?' }],
21
+ stream: true
22
+ ) { |event| puts event }
23
+
24
+ puts "\nTesting tools beta"
25
+ tools = [
26
+ {
27
+ name: 'get_weather',
28
+ description: 'Get the current weather in a given location',
29
+ input_schema: {
30
+ type: 'object',
31
+ properties: {
32
+ location: { type: 'string' }
33
+ },
34
+ required: ['location']
35
+ }
36
+ }
37
+ ]
38
+
39
+ puts Anthropic.messages(beta: 'tools-2024-04-04').create(
40
+ model: 'claude-3-opus-20240229',
41
+ max_tokens: 200,
42
+ tools:,
43
+ messages: [{ role: 'user', content: 'What is the weather like in Nashville?' }]
44
+ )
45
+
46
+ puts "\nTesting completions API"
47
+ puts Anthropic.completions.create(
48
+ model: 'claude-2',
49
+ max_tokens_to_sample: 200,
50
+ prompt: 'Human: Yo what up?\n\nAssistant:'
51
+ )
52
+
53
+ puts "\nTesting streaming completions API"
54
+ Anthropic.completions.create(
55
+ model: 'claude-2',
56
+ max_tokens_to_sample: 200,
57
+ prompt: 'Human: Yo what up?\n\nAssistant:',
58
+ stream: true
59
+ ) { |event| puts event }
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: anthropic-rb
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
  - Dick Davis
8
8
  autorequire:
9
9
  bindir: exe
10
10
  cert_chain: []
11
- date: 2024-04-20 00:00:00.000000000 Z
11
+ date: 2024-04-23 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: httpx
@@ -56,10 +56,21 @@ files:
56
56
  - Rakefile
57
57
  - anthropic-rb.gemspec
58
58
  - lib/anthropic.rb
59
+ - lib/anthropic/api/base_api.rb
60
+ - lib/anthropic/api/completions.rb
61
+ - lib/anthropic/api/concerns/requestable.rb
62
+ - lib/anthropic/api/concerns/validatable.rb
63
+ - lib/anthropic/api/messages.rb
64
+ - lib/anthropic/betas/tools-2024-04-04.json
65
+ - lib/anthropic/bootstrapper.rb
59
66
  - lib/anthropic/client.rb
60
- - lib/anthropic/completions.rb
61
- - lib/anthropic/messages.rb
67
+ - lib/anthropic/errors/betas.rb
68
+ - lib/anthropic/errors/requests.rb
69
+ - lib/anthropic/errors/versions.rb
62
70
  - lib/anthropic/version.rb
71
+ - lib/anthropic/versions/completions/2023-06-01.json
72
+ - lib/anthropic/versions/messages/2023-06-01.json
73
+ - sanity_check.rb
63
74
  - sig/anthropic/rb.rbs
64
75
  homepage: https://github.com/dickdavis/anthropic-rb
65
76
  licenses:
@@ -1,54 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module Anthropic
4
- ##
5
- # Provides bindings for the Anthropic completions API
6
- class Completions
7
- # Error for when the API version is not supported.
8
- class UnsupportedApiVersionError < StandardError; end
9
-
10
- V1_SCHEMA = {
11
- type: 'object',
12
- required: %w[model prompt max_tokens_to_sample],
13
- properties: {
14
- model: { type: 'string' },
15
- prompt: { type: 'string' },
16
- max_tokens_to_sample: { type: 'integer' },
17
- stop_sequences: { type: 'array', items: { type: 'string' } },
18
- temperature: { type: 'number' },
19
- top_k: { type: 'integer' },
20
- top_p: { type: 'number' },
21
- metadata: { type: 'object' },
22
- stream: { type: 'boolean' }
23
- },
24
- additionalProperties: false
25
- }.freeze
26
-
27
- def initialize
28
- @endpoint = 'https://api.anthropic.com/v1/complete'
29
- end
30
-
31
- def create(**params, &)
32
- JSON::Validator.validate!(schema_for_api_version, params)
33
- return Anthropic::Client.post(endpoint, params) unless params[:stream]
34
-
35
- Anthropic::Client.post_as_stream(endpoint, params, &)
36
- rescue JSON::Schema::ValidationError => error
37
- raise ArgumentError, error.message
38
- end
39
-
40
- private
41
-
42
- attr_reader :endpoint
43
-
44
- def schema_for_api_version
45
- api_version = Anthropic.api_version
46
- case api_version
47
- when '2023-06-01'
48
- V1_SCHEMA
49
- else
50
- raise UnsupportedApiVersionError, "Unsupported API version: #{api_version}"
51
- end
52
- end
53
- end
54
- end
@@ -1,76 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module Anthropic
4
- ##
5
- # Provides bindings for the Anthropic messages API
6
- class Messages
7
- # Error for when the API version is not supported.
8
- class UnsupportedApiVersionError < StandardError; end
9
-
10
- # Error for when a beta feature is not used correctly
11
- class UnsupportedBetaOptionError < StandardError; end
12
-
13
- ENDPOINT = 'https://api.anthropic.com/v1/messages'
14
- V1_SCHEMA = {
15
- type: 'object',
16
- required: %w[model messages max_tokens],
17
- properties: {
18
- model: { type: 'string' },
19
- messages: { type: 'array' },
20
- max_tokens: { type: 'integer' },
21
- system: { type: 'string' },
22
- stop_sequences: { type: 'array', items: { type: 'string' } },
23
- temperature: { type: 'number' },
24
- tools: {
25
- type: 'array',
26
- items: {
27
- name: { type: 'string' },
28
- description: { type: 'string' },
29
- input_schema: { type: 'object' }
30
- }
31
- },
32
- top_k: { type: 'integer' },
33
- top_p: { type: 'number' },
34
- metadata: { type: 'object' },
35
- stream: { type: 'boolean' }
36
- },
37
- additionalProperties: false
38
- }.freeze
39
-
40
- def initialize(beta: false)
41
- @beta = beta
42
- end
43
-
44
- def create(**params, &)
45
- raise UnsupportedBetaOptionError, 'Tool use is not yet supported in streaming mode' if params[:stream] && beta
46
-
47
- JSON::Validator.validate!(schema_for_api_version, params)
48
-
49
- return Anthropic::Client.post(ENDPOINT, params, additional_headers) unless params[:stream]
50
-
51
- Anthropic::Client.post_as_stream(ENDPOINT, params, additional_headers, &)
52
- rescue JSON::Schema::ValidationError => error
53
- raise ArgumentError, error.message
54
- end
55
-
56
- private
57
-
58
- attr_reader :beta
59
-
60
- def schema_for_api_version
61
- api_version = Anthropic.api_version
62
- case api_version
63
- when '2023-06-01'
64
- V1_SCHEMA
65
- else
66
- raise UnsupportedApiVersionError, "Unsupported API version: #{api_version}"
67
- end
68
- end
69
-
70
- def additional_headers
71
- return {} unless beta
72
-
73
- { 'anthropic-beta' => 'tools-2024-04-04' }
74
- end
75
- end
76
- end