Class: AISpec::Core::Providers::OpenRouter
- Defined in:
- lib/aispec/core/providers/open_router.rb
Constant Summary collapse
- BASE_URI =
"https://openrouter.ai/api/v1/chat/completions"
Instance Attribute Summary
Attributes inherited from Base
Instance Method Summary collapse
- #generate(prompt, system_prompt: nil, temperature: 0.7, **_params) ⇒ Object
-
#initialize(model: "openai/gpt-4o-mini", api_key: nil, **options) ⇒ OpenRouter
constructor
A new instance of OpenRouter.
Methods inherited from Base
Constructor Details
#initialize(model: "openai/gpt-4o-mini", api_key: nil, **options) ⇒ OpenRouter
Returns a new instance of OpenRouter.
13 14 15 16 |
# File 'lib/aispec/core/providers/open_router.rb', line 13 def initialize(model: "openai/gpt-4o-mini", api_key: nil, **) super(model: model, **) @api_key = api_key || ENV["OPENROUTER_API_KEY"] end |
Instance Method Details
#generate(prompt, system_prompt: nil, temperature: 0.7, **_params) ⇒ Object
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 59 60 61 62 63 64 |
# File 'lib/aispec/core/providers/open_router.rb', line 18 def generate(prompt, system_prompt: nil, temperature: 0.7, **_params) return fallback_mock_if_no_key(prompt) unless @api_key && !@api_key.empty? = [] << { role: "system", content: system_prompt } if system_prompt << { role: "user", content: prompt } payload = { model: @model || "openai/gpt-4o-mini", messages: , temperature: temperature } uri = URI.parse(BASE_URI) start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC) req = Net::HTTP::Post.new(uri.path, { "Content-Type" => "application/json", "Authorization" => "Bearer #{@api_key}", "HTTP-Referer" => "https://github.com/wilburhimself/aispec", "X-Title" => "AISpec Framework" }) req.body = JSON.generate(payload) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.read_timeout = AISpec.configuration.timeout res = http.request(req) elapsed_ms = (Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time) * 1000.0 if res.is_a?(Net::HTTPSuccess) data = JSON.parse(res.body) output = data.dig("choices", 0, "message", "content") || "" tokens = data.dig("usage", "total_tokens") || 0 build_response( output: output, latency_ms: elapsed_ms, tokens: tokens, cost: 0.0005, raw: data ) else raise "OpenRouter API Error (#{res.code}): #{res.body}" end end |