Class: Spectre::Openrouter::Completions
- Inherits:
-
Object
- Object
- Spectre::Openrouter::Completions
- Defined in:
- lib/spectre/openrouter/completions.rb
Constant Summary collapse
- API_URL =
'https://openrouter.ai/api/v1/chat/completions'- DEFAULT_MODEL =
'openai/gpt-4o-mini'- DEFAULT_TIMEOUT =
60
Class Method Summary collapse
-
.create(messages:, model: DEFAULT_MODEL, json_schema: nil, tools: nil, **args) ⇒ Hash
Generate a completion based on user messages and optional tools.
Class Method Details
.create(messages:, model: DEFAULT_MODEL, json_schema: nil, tools: nil, **args) ⇒ Hash
Generate a completion based on user messages and optional tools
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/spectre/openrouter/completions.rb', line 24 def self.create(messages:, model: DEFAULT_MODEL, json_schema: nil, tools: nil, **args) cfg = Spectre.openrouter_configuration api_key = cfg&.api_key raise APIKeyNotConfiguredError, 'API key is not configured' unless api_key () uri = URI(API_URL) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.read_timeout = args.fetch(:read_timeout, DEFAULT_TIMEOUT) http.open_timeout = args.fetch(:open_timeout, DEFAULT_TIMEOUT) headers = { 'Content-Type' => 'application/json', 'Authorization' => "Bearer #{api_key}" } headers['HTTP-Referer'] = cfg.referer if cfg.respond_to?(:referer) && cfg.referer headers['X-Title'] = cfg.app_title if cfg.respond_to?(:app_title) && cfg.app_title request = Net::HTTP::Post.new(uri.path, headers) max_tokens = args[:max_tokens] request.body = generate_body(, model, json_schema, max_tokens, tools).to_json response = http.request(request) unless response.is_a?(Net::HTTPSuccess) raise "OpenRouter API Error: #{response.code} - #{response.}: #{response.body}" end parsed_response = JSON.parse(response.body) handle_response(parsed_response) rescue JSON::ParserError => e raise "JSON Parse Error: #{e.}" end |