Module: PWN::AI::Anthropic

Defined in:
lib/pwn/ai/anthropic.rb

Overview

This plugin interacts with Anthropic's Claude API. It provides methods to list models, generate completions, and chat. API documentation: https://docs.anthropic.com/en/api Obtain an API key from https://console.anthropic.com/

Class Method Summary collapse

Class Method Details

.authorsObject

Author(s)

0day Inc. support@0dayinc.com



467
468
469
470
471
# File 'lib/pwn/ai/anthropic.rb', line 467

public_class_method def self.authors
  "AUTHOR(S):
    0day Inc. <support@0dayinc.com>
  "
end

.chat(opts = {}) ⇒ Object

Supported Method Parameters

response = PWN::AI::Anthropic.chat( request: 'required - message to Anthropic', model: 'optional - model to use for text generation (defaults to PWN::Env[:anthropic][:model])', temp: 'optional - creative response float (defaults to PWN::Env[:anthropic][:temp])', system_role_content: 'optional - context to set up the model behavior for conversation (Default: PWN::Env[:anthropic][:system_role_content])', response_history: 'optional - pass response back in to have a conversation', speak_answer: 'optional speak answer using PWN::Plugins::Voice.text_to_speech (Default: nil)', timeout: 'optional timeout in seconds (defaults to 900)', spinner: 'optional - display spinner (defaults to false)' )



360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
# File 'lib/pwn/ai/anthropic.rb', line 360

public_class_method def self.chat(opts = {})
  engine = PWN::Env[:ai][:anthropic]
  request = opts[:request]
  max_prompt_length = engine[:max_prompt_length] ||= 200_000
  request_trunc_idx = ((max_prompt_length - 1) / 3.36).floor
  request = request[0..request_trunc_idx]

  model = opts[:model] ||= engine[:model]
  raise 'ERROR: Model is required.  Call #get_models method for details' if model.nil?

  temp = opts[:temp].to_f ||= engine[:temp].to_f
  temp = 1 if temp.zero?

  rest_call = 'messages'

  response_history = opts[:response_history]

  system_role_content = opts[:system_role_content] ||= engine[:system_role_content]

  system_role = {
    role: 'system',
    content: system_role_content
  }

  user_role = {
    role: 'user',
    content: request
  }

  response_history ||= { choices: [system_role] }

  http_body = {
    model: model,
    max_tokens: engine[:max_tokens] || 128_000,
    temperature: temp,
    system: system_role_content,
    messages: []
  }

  if response_history[:choices].length > 1
    response_history[:choices][1..].each do |message|
      next if message[:role] == 'system'

      http_body[:messages].push(role: message[:role].to_s, content: message[:content].to_s)
    end
  end

  http_body[:messages].push(role: 'user', content: request)

  timeout = opts[:timeout]
  spinner = opts[:spinner]

  response = anthropic_rest_call(
    http_method: :post,
    rest_call: rest_call,
    http_body: http_body,
    timeout: timeout,
    spinner: spinner
  )

  json_resp = JSON.parse(response, symbolize_names: true)
  raise "Anthropic API Error: #{json_resp[:error] || json_resp}" if json_resp[:error] || json_resp[:type] == 'error'

  assistant_content = if json_resp[:content] && json_resp[:content].is_a?(Array) && json_resp[:content].first
                        json_resp[:content].first[:text]
                      else
                        ''
                      end
  assistant_resp = {
    role: 'assistant',
    content: assistant_content
  }

  # Build choices for PWN compatibility: [system, ...history..., user, assistant]
  json_resp[:choices] = [system_role] + http_body[:messages]
  json_resp[:choices].push(assistant_resp)

  # Ensure compatibility fields
  json_resp[:id] ||= "msg_#{SecureRandom.hex(8)}"
  json_resp[:object] ||= 'message'
  json_resp[:model] ||= model

  if json_resp[:usage].is_a?(Hash)
    inp_tokens = json_resp[:usage][:input_tokens] || 0
    out_tokens = json_resp[:usage][:output_tokens] || 0
    json_resp[:usage][:total_tokens] = inp_tokens + out_tokens
  else
    json_resp[:usage] = { input_tokens: 0, output_tokens: 0, total_tokens: 0 }
  end

  speak_answer = true if opts[:speak_answer]

  if speak_answer
    answer = assistant_resp[:content]
    text_path = "/tmp/#{SecureRandom.hex}.pwn_voice"
    File.write(text_path, answer)
    PWN::Plugins::Voice.text_to_speech(text_path: text_path)
    File.unlink(text_path)
  end

  json_resp
rescue StandardError => e
  raise e
end

.chat_with_tools(opts = {}) ⇒ Object

Supported Method Parameters

response = PWN::AI::Anthropic.chat_with_tools( messages: 'required - OpenAI-format messages array (system/user/assistant/tool)', tools: 'optional - OpenAI tools array [function:{...}]', tool_choice: 'optional - "auto" | "none" | "required" | function:{name:..}', model: 'optional - overrides PWN::Env[:anthropic][:model]', temp: 'optional - temperature (defaults to PWN::Env[:anthropic][:temp] || 1)', max_tokens: 'optional - defaults to PWN::Env[:anthropic][:max_tokens] || 128_000', timeout: 'optional - seconds (default 900)', spinner: 'optional - display spinner (default false)' )



163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
# File 'lib/pwn/ai/anthropic.rb', line 163

public_class_method def self.chat_with_tools(opts = {})
  engine   = PWN::Env[:ai][:anthropic]
  messages = opts[:messages]
  raise 'ERROR: messages array is required' if messages.nil? || messages.empty?

  model = opts[:model] ||= engine[:model]
  raise 'ERROR: Model is required.  Call #get_models method for details' if model.nil?

  temp = opts[:temp].to_f
  temp = engine[:temp].to_f.nonzero? || 1 if temp.zero?

  system_str, anth_messages = oa_messages_to_anthropic(messages: messages)

  http_body = {
    model: model,
    max_tokens: opts[:max_tokens] || engine[:max_tokens] || 128_000,
    temperature: temp,
    messages: anth_messages
  }
  http_body[:system] = system_str if system_str && !system_str.empty?

  if opts[:tools] && !opts[:tools].empty?
    http_body[:tools] = opts[:tools].map do |t|
      fn = t[:function] || t['function'] || t
      {
        name: fn[:name] || fn['name'],
        description: fn[:description] || fn['description'],
        input_schema: fn[:parameters] || fn['parameters'] || { type: 'object', properties: {} }
      }
    end
    http_body[:tool_choice] = anth_tool_choice(choice: opts[:tool_choice]) if opts[:tool_choice]
  end

  response = anthropic_rest_call(
    http_method: :post,
    rest_call: 'messages',
    http_body: http_body,
    timeout: opts[:timeout],
    spinner: opts[:spinner]
  )
  return nil if response.nil?

  json_resp = JSON.parse(response, symbolize_names: true)
  raise "Anthropic API Error: #{json_resp[:error] || json_resp}" if json_resp[:error] || json_resp[:type] == 'error'

  anthropic_resp_to_oa(response: json_resp)
rescue StandardError => e
  raise e
end

.get_modelsObject

Supported Method Parameters

models = PWN::AI::Anthropic.get_models



127
128
129
130
131
132
133
# File 'lib/pwn/ai/anthropic.rb', line 127

public_class_method def self.get_models
  models = anthropic_rest_call(rest_call: 'models')

  JSON.parse(models, symbolize_names: true)[:data]
rescue StandardError => e
  raise e
end

.helpObject

Display Usage for this Module



475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
# File 'lib/pwn/ai/anthropic.rb', line 475

public_class_method def self.help
  puts "USAGE:
    models = #{self}.get_models

    response = #{self}.chat(
      request: 'required - message to Anthropic',
      model: 'optional - model to use for text generation (defaults to PWN::Env[:ai][:anthropic][:model])',
      temp: 'optional - creative response float (defaults to PWN::Env[:ai][:anthropic][:temp])',
      system_role_content: 'optional - context to set up the model behavior for conversation (Default: PWN::Env[:ai][:anthropic][:system_role_content])',
      response_history: 'optional - pass response back in to have a conversation',
      speak_answer: 'optional speak answer using PWN::Plugins::Voice.text_to_speech (Default: nil)',
      timeout: 'optional - timeout in seconds (defaults to 900)',
      spinner: 'optional - display spinner (defaults to false)'
    )

    #{self}.authors
  "
end