Class: N2M::Llm::Claude
- Inherits:
-
Object
- Object
- N2M::Llm::Claude
- Defined in:
- lib/n2b/llm/claude.rb
Constant Summary collapse
- API_URI =
URI.parse('https://api.anthropic.com/v1/messages')
- MODELS =
{ 'haiku' => 'claude-3-haiku-20240307', 'sonnet' => 'claude-3-sonnet-20240229', 'sonnet35' => 'claude-3-5-sonnet-20240620' }
Instance Method Summary collapse
-
#initialize(config) ⇒ Claude
constructor
A new instance of Claude.
- #make_request(content) ⇒ Object
Constructor Details
#initialize(config) ⇒ Claude
Returns a new instance of Claude.
7 8 9 |
# File 'lib/n2b/llm/claude.rb', line 7 def initialize(config) @config = config end |
Instance Method Details
#make_request(content) ⇒ Object
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/n2b/llm/claude.rb', line 11 def make_request( content) uri = URI.parse('https://api.anthropic.com/v1/messages') request = Net::HTTP::Post.new(uri) request.content_type = 'application/json' request['X-API-Key'] = @config['access_key'] request['anthropic-version'] = '2023-06-01' request.body = JSON.dump({ "model" => MODELS[@config['model']], "max_tokens" => 1024, "messages" => [ { "role" => "user", "content" => content } ] }) response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| http.request(request) end # check for errors if response.code != '200' puts "Error: #{response.code} #{response.}" puts response.body exit 1 end answer = JSON.parse(response.body)['content'].first['text'] begin File.open('llm_response.json', 'w') do |f| f.write(answer) end # remove everything before the first { and after the last } answer = answer.sub(/.*?\{(.*)\}.*/m, '{\1}') unless answer.start_with?('{') # gsub all \n with \\n that are inside " # answer.gsub!(/"([^"]*)"/) { |match| match.gsub(/\n/, "\\n") } File.open('llm_response.json', 'w') do |f| f.write(answer) end answer = JSON.parse(answer) rescue JSON::ParserError puts "Error parsing JSON: #{answer}" answer = { 'explanation' => answer} end answer end |