-
-
Notifications
You must be signed in to change notification settings - Fork 227
Improve OpenRouter Support #144
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
c7ff2c9
3f24270
6e68ca4
73c7784
540d102
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,83 @@ | ||
# frozen_string_literal: true | ||
|
||
module RubyLLM | ||
module Providers | ||
module OpenRouter | ||
# Chat methods of the OpenRouter API integration | ||
module Chat | ||
def completion_url | ||
'chat/completions' | ||
end | ||
|
||
module_function | ||
|
||
def render_payload(messages, tools:, temperature:, model:, stream: false) # rubocop:disable Metrics/MethodLength | ||
{ | ||
model: model, | ||
messages: format_messages(messages), | ||
temperature: temperature, | ||
stream: stream, | ||
provider: format_provider_options # @todo Allow for assistant overriding | ||
}.tap do |payload| | ||
if tools.any? | ||
payload[:tools] = tools.map { |_, tool| tool_for(tool) } | ||
payload[:tool_choice] = 'auto' | ||
end | ||
payload[:stream_options] = { include_usage: true } if stream | ||
end | ||
end | ||
|
||
def parse_completion_response(response) # rubocop:disable Metrics/MethodLength | ||
data = response.body | ||
return if data.empty? | ||
|
||
raise Error.new(response, data.dig('error', 'message')) if data.dig('error', 'message') | ||
|
||
message_data = data.dig('choices', 0, 'message') | ||
return unless message_data | ||
|
||
Message.new( | ||
role: :assistant, | ||
content: message_data['content'], | ||
tool_calls: parse_tool_calls(message_data['tool_calls']), | ||
input_tokens: data['usage']['prompt_tokens'], | ||
output_tokens: data['usage']['completion_tokens'], | ||
model_id: data['model'] | ||
) | ||
end | ||
|
||
def format_messages(messages) | ||
messages.map do |msg| | ||
{ | ||
role: format_role(msg.role), | ||
content: self::Media.format_content(msg.content), | ||
tool_calls: format_tool_calls(msg.tool_calls), | ||
tool_call_id: msg.tool_call_id | ||
}.compact | ||
end | ||
end | ||
|
||
def format_role(role) | ||
case role | ||
when :system | ||
'developer' | ||
else | ||
role.to_s | ||
end | ||
end | ||
|
||
def format_provider_options | ||
{ | ||
order: @connection.config.openrouter_provider_order, | ||
allow_fallbacks: @connection.config.openrouter_provider_allow_fallbacks, | ||
require_parameters: @connection.config.openrouter_provider_require_parameters, | ||
data_collection: @connection.config.openrouter_provider_data_collection, | ||
ignore: @connection.config.openrouter_provider_ignore, | ||
quantizations: @connection.config.openrouter_provider_quantizations, | ||
sort: @connection.config.openrouter_provider_sort | ||
}.compact | ||
end | ||
end | ||
end | ||
end | ||
end |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
# frozen_string_literal: true | ||
|
||
module RubyLLM | ||
module Providers | ||
module OpenRouter | ||
# Handles formatting of media content (images, audio) for OpenRouter APIs | ||
module Media | ||
module_function | ||
|
||
def format_content(content) # rubocop:disable Metrics/MethodLength | ||
return content unless content.is_a?(Array) | ||
|
||
content.map do |part| | ||
case part[:type] | ||
when 'image' | ||
format_image(part) | ||
when 'input_audio' | ||
format_audio(part) | ||
when 'pdf' | ||
format_pdf(part) | ||
else | ||
part | ||
end | ||
end | ||
end | ||
|
||
# @see https://openrouter.ai/docs/features/images-and-pdfs#image-inputs | ||
def format_image(part) | ||
{ | ||
type: 'image_url', | ||
image_url: { | ||
url: format_image_url(part[:source]), | ||
detail: 'auto' | ||
} | ||
} | ||
end | ||
|
||
def format_image_url(source) | ||
if source[:type] == 'base64' | ||
"data:#{source[:media_type]};base64,#{source[:data]}" | ||
else | ||
source[:url] | ||
end | ||
end | ||
|
||
def format_audio(part) | ||
{ | ||
type: 'input_audio', | ||
input_audio: part[:input_audio] | ||
} | ||
end | ||
|
||
# @see https://openrouter.ai/docs/features/images-and-pdfs#pdf-support | ||
def format_pdf(part) | ||
{ | ||
type: 'file', | ||
file: { | ||
filename: File.basename(part[:source]), | ||
file_data: format_file_data(part[:content] || part[:source]) | ||
} | ||
} | ||
end | ||
|
||
def format_file_data(source) | ||
source = Faraday.get(source).body if source.start_with?('http') | ||
|
||
"data:application/pdf;base64,#{Base64.strict_encode64(source)}" | ||
end | ||
end | ||
end | ||
end | ||
end |
Large diffs are not rendered by default.
Large diffs are not rendered by default.
Large diffs are not rendered by default.
Large diffs are not rendered by default.
Large diffs are not rendered by default.
Large diffs are not rendered by default.
Large diffs are not rendered by default.
Large diffs are not rendered by default.
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
# frozen_string_literal: true | ||
|
||
require 'spec_helper' | ||
|
||
RSpec.describe RubyLLM::Chat do | ||
include_context 'with configured RubyLLM' | ||
|
||
describe 'pdf model' do | ||
shared_examples 'PDF_MODELS' do |model, provider| | ||
it "#{provider}/#{model} understands PDFs" do # rubocop:disable RSpec/MultipleExpectations | ||
chat = RubyLLM.chat(model: model, provider: provider) | ||
response = chat.ask('Summarize this document', with: { pdf: pdf_locator }) | ||
expect(response.content).not_to be_empty | ||
|
||
response = chat.ask 'go on' | ||
expect(response.content).not_to be_empty | ||
end | ||
|
||
it "#{provider}/#{model} handles multiple PDFs" do # rubocop:disable RSpec/MultipleExpectations | ||
chat = RubyLLM.chat(model: model, provider: provider) | ||
# Using same file twice for testing | ||
response = chat.ask('Compare these documents', with: { pdf: [pdf_locator, pdf_locator] }) | ||
expect(response.content).not_to be_empty | ||
|
||
response = chat.ask 'go on' | ||
expect(response.content).not_to be_empty | ||
end | ||
end | ||
|
||
PDF_MODELS.each do |model_info| | ||
model = model_info[:model] | ||
provider = model_info[:provider] | ||
|
||
context 'with Paths' do | ||
let(:pdf_locator) { File.expand_path('../fixtures/sample.pdf', __dir__) } | ||
|
||
it_behaves_like 'PDF_MODELS', model, provider | ||
end | ||
|
||
context 'with URLs' do | ||
let(:pdf_locator) { 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf' } | ||
|
||
it_behaves_like 'PDF_MODELS', model, provider | ||
end | ||
end | ||
end | ||
end |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Was this necessary?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, as previously explained, the module-based system has scoping issues. This file is deeply called by the other modules, so in order to have this file call the correct version of the
Media
file, which is not the OpenAI version, it needs to be scoped to the current runtime.I attempted to make this fix universal, so that other people don't run into this bug; you asked me to roll it back where it wasn't necessary. So I did, but I can not roll it back in this location if I want the correct version of the Media object to be invoked at runtime.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the explanation, makes sense!