Skip to content

Improve RubyLLM::Chat#with_params (#265) by allowing to override default params #303

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions lib/ruby_llm/provider.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,19 @@ def complete(messages, tools:, temperature:, model:, connection:, params: {}, sc
normalized_temperature = maybe_normalize_temperature(temperature, model)

payload = Utils.deep_merge(
params,
render_payload(
messages,
tools: tools,
temperature: normalized_temperature,
model: model,
stream: block_given?,
schema: schema
)
),
params
)

payload.compact!

if block_given?
stream_response connection, payload, &
else
Expand Down
10 changes: 5 additions & 5 deletions lib/ruby_llm/utils.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,12 @@ def to_safe_array(item)
end
end

def deep_merge(params, payload)
params.merge(payload) do |_key, params_value, payload_value|
if params_value.is_a?(Hash) && payload_value.is_a?(Hash)
deep_merge(params_value, payload_value)
def deep_merge(hash1, hash2)
hash1.merge(hash2) do |_key, value1, value2|
if value1.is_a?(Hash) && value2.is_a?(Hash)
deep_merge(value1, value2)
else
payload_value
value2
end
end
end
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions spec/ruby_llm/chat_request_options_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,21 @@
json_response = JSON.parse('{' + response.content) # rubocop:disable Style/StringConcatenation
expect(json_response).to eq({ 'result' => 8 })
end

it "#{provider}/#{model} can override max_tokens param with a custom value" do # rubocop:disable RSpec/ExampleLength
chat = RubyLLM
.chat(model: model, provider: provider)
.with_params(max_tokens: 2)

chat.add_message(
role: :user,
content: 'Always answer with "Once upon a time"'
)

response = chat.complete

expect(response.content).to eq('Once upon') # Only 2 tokens
end
end

# Providers [:openrouter, :bedrock] supports a {top_k: ...} param to remove low-probability next tokens.
Expand Down