ruby_llm 2.1.1 → 2.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/README.md +160 -120
- data/app/assets/javascripts/ruby_llm/chat_message_controller.js +163 -0
- data/app/assets/javascripts/ruby_llm/dompurify.js +9 -0
- data/app/assets/javascripts/ruby_llm/marked.js +71 -0
- data/config/importmap.rb +5 -0
- data/lib/generators/ruby_llm/agent/agent_generator.rb +11 -3
- data/lib/generators/ruby_llm/agent/templates/agent.rb.tt +6 -3
- data/lib/generators/ruby_llm/chat_ui/chat_ui_generator.rb +201 -55
- data/lib/generators/ruby_llm/chat_ui/templates/agents/chat_agent.rb.tt +15 -0
- data/lib/generators/ruby_llm/chat_ui/templates/controllers/answers_controller.rb.tt +31 -0
- data/lib/generators/ruby_llm/chat_ui/templates/controllers/chats_controller.rb.tt +16 -5
- data/lib/generators/ruby_llm/chat_ui/templates/controllers/messages_controller.rb.tt +27 -9
- data/lib/generators/ruby_llm/chat_ui/templates/controllers/models_controller.rb.tt +1 -1
- data/lib/generators/ruby_llm/chat_ui/templates/controllers/queued_messages_controller.rb.tt +14 -0
- data/lib/generators/ruby_llm/chat_ui/templates/javascript/chat_message_controller.js +1 -0
- data/lib/generators/ruby_llm/chat_ui/templates/jobs/chat_response_job.rb.tt +5 -8
- data/lib/generators/ruby_llm/chat_ui/templates/jobs/resume_interrupted_chats_job.rb.tt +7 -0
- data/lib/generators/ruby_llm/chat_ui/templates/migrations/add_reply_error_migration.rb.tt +5 -0
- data/lib/generators/ruby_llm/chat_ui/templates/tailwind/views/chats/_files.html.erb.tt +15 -0
- data/lib/generators/ruby_llm/chat_ui/templates/tailwind/views/chats/_form.html.erb.tt +5 -7
- data/lib/generators/ruby_llm/chat_ui/templates/tailwind/views/chats/_model_select.html.erb.tt +7 -0
- data/lib/generators/ruby_llm/chat_ui/templates/tailwind/views/chats/show.html.erb.tt +32 -3
- data/lib/generators/ruby_llm/chat_ui/templates/tailwind/views/messages/_assistant.html.erb.tt +17 -2
- data/lib/generators/ruby_llm/chat_ui/templates/tailwind/views/messages/_attachments.html.erb.tt +14 -0
- data/lib/generators/ruby_llm/chat_ui/templates/tailwind/views/messages/_error.html.erb.tt +1 -1
- data/lib/generators/ruby_llm/chat_ui/templates/tailwind/views/messages/_form.html.erb.tt +28 -18
- data/lib/generators/ruby_llm/chat_ui/templates/tailwind/views/messages/_queued_message.html.erb.tt +18 -0
- data/lib/generators/ruby_llm/chat_ui/templates/tailwind/views/messages/_system.html.erb.tt +1 -1
- data/lib/generators/ruby_llm/chat_ui/templates/tailwind/views/messages/_tool_calls.html.erb.tt +4 -1
- data/lib/generators/ruby_llm/chat_ui/templates/tailwind/views/messages/_user.html.erb.tt +4 -2
- data/lib/generators/ruby_llm/chat_ui/templates/tailwind/views/messages/tool_calls/_default.html.erb.tt +1 -1
- data/lib/generators/ruby_llm/chat_ui/templates/tailwind/views/messages/tool_results/_default.html.erb.tt +4 -2
- data/lib/generators/ruby_llm/chat_ui/templates/tailwind/views/questions/_question.html.erb.tt +102 -0
- data/lib/generators/ruby_llm/chat_ui/templates/test/agents/chat_agent_test.rb.tt +28 -0
- data/lib/generators/ruby_llm/chat_ui/templates/test/application_system_test_case.rb.tt +5 -0
- data/lib/generators/ruby_llm/chat_ui/templates/test/system/chats_test.rb.tt +240 -0
- data/lib/generators/ruby_llm/chat_ui/templates/views/answers/create.turbo_stream.erb.tt +6 -0
- data/lib/generators/ruby_llm/chat_ui/templates/views/chats/_files.html.erb.tt +15 -0
- data/lib/generators/ruby_llm/chat_ui/templates/views/chats/_form.html.erb.tt +5 -7
- data/lib/generators/ruby_llm/chat_ui/templates/views/chats/_model_select.html.erb.tt +7 -0
- data/lib/generators/ruby_llm/chat_ui/templates/views/chats/_questions.html.erb.tt +13 -0
- data/lib/generators/ruby_llm/chat_ui/templates/views/chats/show.html.erb.tt +29 -3
- data/lib/generators/ruby_llm/chat_ui/templates/views/messages/_assistant.html.erb.tt +16 -2
- data/lib/generators/ruby_llm/chat_ui/templates/views/messages/_attachments.html.erb.tt +14 -0
- data/lib/generators/ruby_llm/chat_ui/templates/views/messages/_error.html.erb.tt +1 -1
- data/lib/generators/ruby_llm/chat_ui/templates/views/messages/_form.html.erb.tt +26 -16
- data/lib/generators/ruby_llm/chat_ui/templates/views/messages/_queued_message.html.erb.tt +8 -0
- data/lib/generators/ruby_llm/chat_ui/templates/views/messages/_system.html.erb.tt +1 -1
- data/lib/generators/ruby_llm/chat_ui/templates/views/messages/_tool_calls.html.erb.tt +4 -1
- data/lib/generators/ruby_llm/chat_ui/templates/views/messages/_user.html.erb.tt +3 -2
- data/lib/generators/ruby_llm/chat_ui/templates/views/messages/create.turbo_stream.erb.tt +1 -0
- data/lib/generators/ruby_llm/chat_ui/templates/views/messages/tool_calls/_default.html.erb.tt +1 -1
- data/lib/generators/ruby_llm/chat_ui/templates/views/messages/tool_results/_default.html.erb.tt +3 -2
- data/lib/generators/ruby_llm/chat_ui/templates/views/questions/_question.html.erb.tt +79 -0
- data/lib/generators/ruby_llm/evaluation/evaluation_generator.rb +43 -0
- data/lib/generators/ruby_llm/evaluation/templates/evaluation.rb.tt +9 -0
- data/lib/generators/ruby_llm/evaluation/templates/evaluation.yml.tt +4 -0
- data/lib/generators/ruby_llm/generator_helpers.rb +116 -3
- data/lib/generators/ruby_llm/install/install_generator.rb +5 -47
- data/lib/generators/ruby_llm/install/templates/create_chats_migration.rb.tt +4 -0
- data/lib/generators/ruby_llm/install/templates/create_messages_migration.rb.tt +5 -3
- data/lib/generators/ruby_llm/install/templates/create_ruby_llm_records_migration.rb.tt +41 -1
- data/lib/generators/ruby_llm/install/templates/initializer.rb.tt +2 -1
- data/lib/generators/ruby_llm/install/templates/message_model.rb.tt +1 -2
- data/lib/generators/ruby_llm/judge/judge_generator.rb +35 -0
- data/lib/generators/ruby_llm/judge/templates/judge.rb.tt +2 -0
- data/lib/generators/ruby_llm/mcp/mcp_generator.rb +58 -0
- data/lib/generators/ruby_llm/mcp/templates/mcp.rb.tt +7 -0
- data/lib/generators/ruby_llm/provider/scaffold.rb +5 -12
- data/lib/generators/ruby_llm/provider/templates/core/provider.rb.erb +6 -0
- data/lib/generators/ruby_llm/provider/templates/gem/chat_spec.rb.erb +0 -1
- data/lib/generators/ruby_llm/provider/templates/gem/chat_streaming_spec.rb.erb +0 -1
- data/lib/generators/ruby_llm/provider/templates/gem/moderation_spec.rb.erb +1 -1
- data/lib/generators/ruby_llm/sandbox/sandbox_generator.rb +68 -0
- data/lib/generators/ruby_llm/sandbox/templates/sandbox.rb.tt +3 -0
- data/lib/generators/ruby_llm/skill/skill_generator.rb +48 -0
- data/lib/generators/ruby_llm/tool/templates/tailwind/tool_call.html.erb.tt +1 -1
- data/lib/generators/ruby_llm/tool/templates/tailwind/tool_result.html.erb.tt +1 -1
- data/lib/generators/ruby_llm/tool/templates/tool.rb.tt +0 -3
- data/lib/generators/ruby_llm/tool/templates/tool_call.html.erb.tt +1 -1
- data/lib/generators/ruby_llm/tool/templates/tool_result.html.erb.tt +1 -1
- data/lib/generators/ruby_llm/tool/tool_generator.rb +1 -5
- data/lib/generators/ruby_llm/upgrade/templates/upgrade_ruby_llm_to_2_2.rb.tt +164 -0
- data/lib/generators/ruby_llm/upgrade/upgrade_generator.rb +41 -3
- data/lib/ruby_llm/accounting/operation.rb +73 -0
- data/lib/ruby_llm/accounting/usage.rb +74 -24
- data/lib/ruby_llm/active_record/acts_as.rb +78 -11
- data/lib/ruby_llm/active_record/attachment_helpers.rb +10 -4
- data/lib/ruby_llm/active_record/batch.rb +67 -9
- data/lib/ruby_llm/active_record/chat_agent_hooks.rb +17 -0
- data/lib/ruby_llm/active_record/chat_approvals.rb +74 -0
- data/lib/ruby_llm/active_record/chat_cancellation.rb +106 -0
- data/lib/ruby_llm/active_record/chat_column_guard.rb +51 -0
- data/lib/ruby_llm/active_record/chat_file.rb +37 -0
- data/lib/ruby_llm/active_record/chat_files.rb +30 -0
- data/lib/ruby_llm/active_record/chat_helper.rb +73 -0
- data/lib/ruby_llm/active_record/chat_methods.rb +516 -297
- data/lib/ruby_llm/active_record/chat_placeholders.rb +67 -0
- data/lib/ruby_llm/active_record/chat_questions.rb +177 -0
- data/lib/ruby_llm/active_record/chat_queue.rb +133 -0
- data/lib/ruby_llm/active_record/chat_reply_error.rb +35 -0
- data/lib/ruby_llm/active_record/chat_run.rb +51 -0
- data/lib/ruby_llm/active_record/chat_tool_call_state.rb +77 -0
- data/lib/ruby_llm/active_record/chunk_methods.rb +49 -0
- data/lib/ruby_llm/active_record/claim_heartbeat.rb +149 -0
- data/lib/ruby_llm/active_record/file_store.rb +269 -0
- data/lib/ruby_llm/active_record/mcp_credential.rb +24 -9
- data/lib/ruby_llm/active_record/message_broadcasting.rb +85 -0
- data/lib/ruby_llm/active_record/message_methods.rb +83 -11
- data/lib/ruby_llm/active_record/model.rb +37 -9
- data/lib/ruby_llm/active_record/provider_file.rb +21 -4
- data/lib/ruby_llm/active_record/queued_message.rb +50 -0
- data/lib/ruby_llm/active_record/record.rb +3 -1
- data/lib/ruby_llm/active_record/run_claims.rb +636 -0
- data/lib/ruby_llm/active_record/solid_queue_shutdown.rb +33 -0
- data/lib/ruby_llm/active_record/system_instructions.rb +30 -0
- data/lib/ruby_llm/active_record/tool_call.rb +55 -4
- data/lib/ruby_llm/active_record/usage.rb +79 -9
- data/lib/ruby_llm/agent/callbacks.rb +98 -0
- data/lib/ruby_llm/agent/context_budget.rb +26 -0
- data/lib/ruby_llm/agent/join_callbacks.rb +28 -0
- data/lib/ruby_llm/agent/model_options.rb +56 -0
- data/lib/ruby_llm/agent/ownership.rb +22 -0
- data/lib/ruby_llm/agent/tool_conversion.rb +19 -0
- data/lib/ruby_llm/agent.rb +621 -236
- data/lib/ruby_llm/agent_tool.rb +91 -0
- data/lib/ruby_llm/aliases.json +93 -91
- data/lib/ruby_llm/attachment.rb +101 -20
- data/lib/ruby_llm/batch.rb +132 -46
- data/lib/ruby_llm/cached_content.rb +4 -4
- data/lib/ruby_llm/chat/agent_run.rb +22 -0
- data/lib/ruby_llm/chat/context_budget.rb +119 -0
- data/lib/ruby_llm/chat/file_references.rb +256 -0
- data/lib/ruby_llm/chat/message_queue.rb +56 -0
- data/lib/ruby_llm/chat/ownership.rb +18 -0
- data/lib/ruby_llm/chat/rescuable.rb +48 -0
- data/lib/ruby_llm/chat/run.rb +32 -0
- data/lib/ruby_llm/chat/tool_call_ids.rb +46 -0
- data/lib/ruby_llm/chat/tool_call_state.rb +126 -0
- data/lib/ruby_llm/chat/tool_concurrency.rb +90 -49
- data/lib/ruby_llm/chat/tool_search.rb +36 -1
- data/lib/ruby_llm/chat/tool_sequences.rb +84 -0
- data/lib/ruby_llm/chat.rb +1671 -334
- data/lib/ruby_llm/chunk.rb +27 -1
- data/lib/ruby_llm/citation.rb +2 -1
- data/lib/ruby_llm/code_execution/language.rb +28 -0
- data/lib/ruby_llm/code_execution/node_installation.rb +56 -0
- data/lib/ruby_llm/code_execution/packages.rb +241 -0
- data/lib/ruby_llm/code_execution/ruby_installation.rb +170 -0
- data/lib/ruby_llm/code_execution/workspace.rb +314 -0
- data/lib/ruby_llm/code_execution.rb +781 -0
- data/lib/ruby_llm/configuration.rb +152 -5
- data/lib/ruby_llm/content_filter.rb +68 -0
- data/lib/ruby_llm/cost.rb +68 -41
- data/lib/ruby_llm/downloaded_file.rb +10 -9
- data/lib/ruby_llm/embedding.rb +30 -45
- data/lib/ruby_llm/embedding_request.rb +1 -1
- data/lib/ruby_llm/error.rb +167 -14
- data/lib/ruby_llm/evaluation/dataset.rb +5 -4
- data/lib/ruby_llm/evaluation/evidence.rb +5 -3
- data/lib/ruby_llm/evaluation/report.rb +7 -3
- data/lib/ruby_llm/evaluation/result.rb +1 -1
- data/lib/ruby_llm/evaluation.rb +2 -1
- data/lib/ruby_llm/fallback.rb +32 -4
- data/lib/ruby_llm/file_store/converters/ocr.rb +28 -0
- data/lib/ruby_llm/file_store/converters/office/markup.rb +148 -0
- data/lib/ruby_llm/file_store/converters/office/outline.rb +193 -0
- data/lib/ruby_llm/file_store/converters/office/prose.rb +161 -0
- data/lib/ruby_llm/file_store/converters/office/workbook.rb +187 -0
- data/lib/ruby_llm/file_store/converters/office/zip.rb +149 -0
- data/lib/ruby_llm/file_store/converters/office.rb +106 -0
- data/lib/ruby_llm/file_store/converters/text.rb +27 -0
- data/lib/ruby_llm/file_store/converters.rb +84 -0
- data/lib/ruby_llm/file_store/directory.rb +190 -0
- data/lib/ruby_llm/file_store/memory.rb +75 -0
- data/lib/ruby_llm/file_store/tools/base.rb +99 -0
- data/lib/ruby_llm/file_store/tools/delete.rb +48 -0
- data/lib/ruby_llm/file_store/tools/edit.rb +155 -0
- data/lib/ruby_llm/file_store/tools/list.rb +57 -0
- data/lib/ruby_llm/file_store/tools/read.rb +126 -0
- data/lib/ruby_llm/file_store/tools/search.rb +208 -0
- data/lib/ruby_llm/file_store/tools/write.rb +40 -0
- data/lib/ruby_llm/file_store/tools.rb +39 -0
- data/lib/ruby_llm/file_store.rb +372 -0
- data/lib/ruby_llm/files/saving.rb +14 -0
- data/lib/ruby_llm/image.rb +67 -45
- data/lib/ruby_llm/input_required_error.rb +28 -0
- data/lib/ruby_llm/judge/builder.rb +6 -1
- data/lib/ruby_llm/judge.rb +1 -1
- data/lib/ruby_llm/judgment.rb +6 -24
- data/lib/ruby_llm/mcp/client.rb +50 -24
- data/lib/ruby_llm/mcp/collection.rb +39 -2
- data/lib/ruby_llm/mcp/content.rb +7 -2
- data/lib/ruby_llm/mcp/error.rb +8 -2
- data/lib/ruby_llm/mcp/http.rb +117 -37
- data/lib/ruby_llm/mcp/input_request.rb +3 -112
- data/lib/ruby_llm/mcp/input_required_error.rb +3 -21
- data/lib/ruby_llm/mcp/insufficient_scope_error.rb +27 -0
- data/lib/ruby_llm/mcp/listener.rb +7 -1
- data/lib/ruby_llm/mcp/oauth.rb +102 -39
- data/lib/ruby_llm/mcp/outages.rb +172 -0
- data/lib/ruby_llm/mcp/resource.rb +9 -6
- data/lib/ruby_llm/mcp/resource_template.rb +3 -2
- data/lib/ruby_llm/mcp/session_expired.rb +10 -2
- data/lib/ruby_llm/mcp/stdio.rb +66 -18
- data/lib/ruby_llm/mcp/task.rb +13 -40
- data/lib/ruby_llm/mcp/tool.rb +34 -11
- data/lib/ruby_llm/mcp.rb +123 -59
- data/lib/ruby_llm/message.rb +217 -23
- data/lib/ruby_llm/model/modalities.rb +1 -1
- data/lib/ruby_llm/model/pricing.rb +26 -4
- data/lib/ruby_llm/model/pricing_category.rb +38 -15
- data/lib/ruby_llm/model/pricing_tier.rb +3 -2
- data/lib/ruby_llm/model.rb +24 -6
- data/lib/ruby_llm/models/lookup.rb +37 -4
- data/lib/ruby_llm/models/registry.rb +4 -19
- data/lib/ruby_llm/models.json +49086 -39251
- data/lib/ruby_llm/models.rb +66 -38
- data/lib/ruby_llm/moderation.rb +10 -30
- data/lib/ruby_llm/ocr.rb +5 -22
- data/lib/ruby_llm/open_telemetry/attributes.rb +68 -19
- data/lib/ruby_llm/open_telemetry/content.rb +105 -0
- data/lib/ruby_llm/open_telemetry.rb +18 -4
- data/lib/ruby_llm/prompt/context.rb +2 -2
- data/lib/ruby_llm/prompt.rb +7 -5
- data/lib/ruby_llm/protocol/binary_streaming.rb +2 -8
- data/lib/ruby_llm/protocol/cache_lifetime.rb +22 -0
- data/lib/ruby_llm/protocol/native_content.rb +69 -0
- data/lib/ruby_llm/protocol/replayed_arguments.rb +28 -0
- data/lib/ruby_llm/protocol/stream_accumulator.rb +73 -33
- data/lib/ruby_llm/protocol/streaming.rb +105 -22
- data/lib/ruby_llm/protocol/tool_namespaces.rb +100 -0
- data/lib/ruby_llm/protocol/unsupported_operations.rb +42 -0
- data/lib/ruby_llm/protocol.rb +127 -106
- data/lib/ruby_llm/protocols/anthropic/batches.rb +41 -4
- data/lib/ruby_llm/protocols/anthropic/block_binding.rb +30 -0
- data/lib/ruby_llm/protocols/anthropic/chat.rb +135 -60
- data/lib/ruby_llm/protocols/anthropic/files.rb +9 -0
- data/lib/ruby_llm/protocols/anthropic/media.rb +14 -14
- data/lib/ruby_llm/protocols/anthropic/models.rb +16 -10
- data/lib/ruby_llm/protocols/anthropic/streaming.rb +43 -22
- data/lib/ruby_llm/protocols/anthropic/tools.rb +36 -24
- data/lib/ruby_llm/protocols/anthropic.rb +61 -6
- data/lib/ruby_llm/protocols/azure/speech/transcription.rb +125 -0
- data/lib/ruby_llm/protocols/azure/speech.rb +14 -0
- data/lib/ruby_llm/protocols/bedrock/batches.rb +26 -8
- data/lib/ruby_llm/protocols/bedrock/event_stream.rb +205 -0
- data/lib/ruby_llm/protocols/bedrock/files.rb +15 -6
- data/lib/ruby_llm/protocols/bedrock/guardrails.rb +1 -1
- data/lib/ruby_llm/protocols/bedrock/rerank.rb +2 -0
- data/lib/ruby_llm/protocols/chat_completions/chat.rb +158 -58
- data/lib/ruby_llm/protocols/chat_completions/content_filters.rb +45 -0
- data/lib/ruby_llm/protocols/chat_completions/embedding_batches.rb +15 -15
- data/lib/ruby_llm/protocols/chat_completions/embeddings.rb +26 -3
- data/lib/ruby_llm/protocols/chat_completions/images.rb +7 -9
- data/lib/ruby_llm/protocols/chat_completions/media.rb +20 -20
- data/lib/ruby_llm/protocols/chat_completions/moderation.rb +8 -5
- data/lib/ruby_llm/protocols/chat_completions/speech.rb +8 -2
- data/lib/ruby_llm/protocols/chat_completions/streaming.rb +38 -17
- data/lib/ruby_llm/protocols/chat_completions/think_tags.rb +148 -0
- data/lib/ruby_llm/protocols/chat_completions/tools.rb +15 -28
- data/lib/ruby_llm/protocols/chat_completions/transcription.rb +17 -2
- data/lib/ruby_llm/protocols/chat_completions.rb +4 -0
- data/lib/ruby_llm/protocols/cohere/batches.rb +15 -8
- data/lib/ruby_llm/protocols/cohere/chat.rb +47 -25
- data/lib/ruby_llm/protocols/cohere/datasets.rb +6 -2
- data/lib/ruby_llm/protocols/cohere/embeddings.rb +7 -5
- data/lib/ruby_llm/protocols/cohere/media.rb +7 -7
- data/lib/ruby_llm/protocols/cohere/rerank.rb +2 -1
- data/lib/ruby_llm/protocols/cohere/streaming.rb +26 -11
- data/lib/ruby_llm/protocols/cohere/tools.rb +17 -28
- data/lib/ruby_llm/protocols/cohere/transcription.rb +5 -4
- data/lib/ruby_llm/protocols/converse/batches.rb +2 -24
- data/lib/ruby_llm/protocols/converse/chat.rb +210 -75
- data/lib/ruby_llm/protocols/converse/media.rb +24 -22
- data/lib/ruby_llm/protocols/converse/reasoning.rb +23 -9
- data/lib/ruby_llm/protocols/converse/streaming.rb +68 -220
- data/lib/ruby_llm/protocols/converse.rb +17 -1
- data/lib/ruby_llm/protocols/deepgram/speech.rb +1 -2
- data/lib/ruby_llm/protocols/deepgram/streaming_transcription.rb +1 -3
- data/lib/ruby_llm/protocols/deepgram/transcription.rb +28 -19
- data/lib/ruby_llm/protocols/deepgram.rb +3 -2
- data/lib/ruby_llm/protocols/deepseek/files.rb +1 -1
- data/lib/ruby_llm/protocols/elevenlabs/assets.rb +6 -4
- data/lib/ruby_llm/protocols/elevenlabs/flows/images.rb +4 -0
- data/lib/ruby_llm/protocols/elevenlabs/speech.rb +3 -3
- data/lib/ruby_llm/protocols/elevenlabs/streaming_transcription.rb +5 -2
- data/lib/ruby_llm/protocols/elevenlabs/transcription.rb +6 -3
- data/lib/ruby_llm/protocols/files.rb +27 -12
- data/lib/ruby_llm/protocols/gemini/batches.rb +74 -5
- data/lib/ruby_llm/protocols/gemini/caches.rb +4 -4
- data/lib/ruby_llm/protocols/gemini/chat.rb +118 -51
- data/lib/ruby_llm/protocols/gemini/embedding_batches.rb +9 -5
- data/lib/ruby_llm/protocols/gemini/embeddings.rb +3 -3
- data/lib/ruby_llm/protocols/gemini/file_transcription.rb +4 -0
- data/lib/ruby_llm/protocols/gemini/files.rb +5 -4
- data/lib/ruby_llm/protocols/gemini/images.rb +11 -9
- data/lib/ruby_llm/protocols/gemini/live_transcription.rb +1 -1
- data/lib/ruby_llm/protocols/gemini/long_decode.rb +104 -0
- data/lib/ruby_llm/protocols/gemini/media.rb +31 -28
- data/lib/ruby_llm/protocols/gemini/retry_info.rb +29 -0
- data/lib/ruby_llm/protocols/gemini/schemas.rb +126 -0
- data/lib/ruby_llm/protocols/gemini/speech.rb +9 -3
- data/lib/ruby_llm/protocols/gemini/streaming.rb +37 -13
- data/lib/ruby_llm/protocols/gemini/tools.rb +18 -10
- data/lib/ruby_llm/protocols/gemini/transcription.rb +13 -9
- data/lib/ruby_llm/protocols/gemini/videos.rb +14 -3
- data/lib/ruby_llm/protocols/gemini.rb +16 -0
- data/lib/ruby_llm/protocols/gpustack/responses.rb +3 -3
- data/lib/ruby_llm/protocols/gpustack/tokenization.rb +14 -0
- data/lib/ruby_llm/protocols/interactions/chat.rb +29 -14
- data/lib/ruby_llm/protocols/interactions/content.rb +19 -14
- data/lib/ruby_llm/protocols/interactions/streaming.rb +1 -1
- data/lib/ruby_llm/protocols/interactions/tools.rb +10 -13
- data/lib/ruby_llm/protocols/interactions/videos.rb +99 -0
- data/lib/ruby_llm/protocols/interactions.rb +1 -0
- data/lib/ruby_llm/protocols/invoke_model/cohere_embeddings.rb +28 -10
- data/lib/ruby_llm/protocols/invoke_model/embedding_batches.rb +1 -1
- data/lib/ruby_llm/protocols/invoke_model/nova_embeddings.rb +45 -11
- data/lib/ruby_llm/protocols/invoke_model/stability_images.rb +5 -2
- data/lib/ruby_llm/protocols/invoke_model/titan_multimodal_embeddings.rb +11 -3
- data/lib/ruby_llm/protocols/invoke_model.rb +21 -2
- data/lib/ruby_llm/protocols/meta/transcription/stream.rb +108 -0
- data/lib/ruby_llm/protocols/meta/transcription.rb +76 -0
- data/lib/ruby_llm/protocols/minimax/files.rb +58 -0
- data/lib/ruby_llm/protocols/minimax/images.rb +54 -0
- data/lib/ruby_llm/protocols/minimax/speech.rb +53 -0
- data/lib/ruby_llm/protocols/minimax/transcription.rb +82 -0
- data/lib/ruby_llm/protocols/minimax/videos.rb +93 -0
- data/lib/ruby_llm/protocols/minimax.rb +21 -0
- data/lib/ruby_llm/protocols/mistral/conversations/chat.rb +44 -21
- data/lib/ruby_llm/protocols/mistral/files.rb +6 -4
- data/lib/ruby_llm/protocols/mistral/multi_completion.rb +15 -4
- data/lib/ruby_llm/protocols/moonshot/files.rb +48 -0
- data/lib/ruby_llm/protocols/openai/batches.rb +3 -2
- data/lib/ruby_llm/protocols/openai/decisions.rb +10 -6
- data/lib/ruby_llm/protocols/openai/files.rb +13 -6
- data/lib/ruby_llm/protocols/openrouter/batches.rb +13 -17
- data/lib/ruby_llm/protocols/openrouter/responses.rb +6 -10
- data/lib/ruby_llm/protocols/perplexity/agent.rb +19 -35
- data/lib/ruby_llm/protocols/perplexity/batches.rb +37 -0
- data/lib/ruby_llm/protocols/perplexity/files.rb +19 -9
- data/lib/ruby_llm/protocols/responses/approvals.rb +12 -11
- data/lib/ruby_llm/protocols/responses/chat.rb +165 -75
- data/lib/ruby_llm/protocols/responses/citation_markers.rb +167 -0
- data/lib/ruby_llm/protocols/responses/compaction.rb +2 -2
- data/lib/ruby_llm/protocols/responses/media.rb +17 -9
- data/lib/ruby_llm/protocols/responses/streaming.rb +71 -12
- data/lib/ruby_llm/protocols/responses/token_counting.rb +1 -1
- data/lib/ruby_llm/protocols/responses/tools.rb +48 -1
- data/lib/ruby_llm/protocols/responses.rb +21 -0
- data/lib/ruby_llm/protocols/system_one/responses.rb +12 -5
- data/lib/ruby_llm/protocols/vertexai/files.rb +4 -3
- data/lib/ruby_llm/protocols/vertexai/text_to_speech.rb +116 -0
- data/lib/ruby_llm/protocols/xai/files.rb +13 -6
- data/lib/ruby_llm/protocols/zai/files.rb +37 -0
- data/lib/ruby_llm/provider.rb +128 -31
- data/lib/ruby_llm/providers/anthropic.rb +5 -1
- data/lib/ruby_llm/providers/azure/chat.rb +17 -3
- data/lib/ruby_llm/providers/azure/chat_completions.rb +1 -0
- data/lib/ruby_llm/providers/azure/decisions.rb +17 -0
- data/lib/ruby_llm/providers/azure/embeddings.rb +1 -2
- data/lib/ruby_llm/providers/azure/media.rb +6 -6
- data/lib/ruby_llm/providers/azure/mistral.rb +17 -0
- data/lib/ruby_llm/providers/azure/models.rb +16 -2
- data/lib/ruby_llm/providers/azure/moderation.rb +16 -0
- data/lib/ruby_llm/providers/azure/responses.rb +9 -0
- data/lib/ruby_llm/providers/azure/videos.rb +2 -2
- data/lib/ruby_llm/providers/azure.rb +43 -1
- data/lib/ruby_llm/providers/bedrock/anthropic/batches.rb +32 -0
- data/lib/ruby_llm/providers/bedrock/anthropic.rb +134 -0
- data/lib/ruby_llm/providers/bedrock/auth.rb +12 -3
- data/lib/ruby_llm/providers/bedrock/connection.rb +19 -0
- data/lib/ruby_llm/providers/bedrock/mantle/anthropic.rb +5 -1
- data/lib/ruby_llm/providers/bedrock/mantle/chat_completions.rb +2 -2
- data/lib/ruby_llm/providers/bedrock/mantle/responses.rb +12 -2
- data/lib/ruby_llm/providers/bedrock/mantle/voxtral.rb +1 -1
- data/lib/ruby_llm/providers/bedrock/mantle.rb +7 -0
- data/lib/ruby_llm/providers/bedrock/models.rb +1 -7
- data/lib/ruby_llm/providers/bedrock.rb +51 -8
- data/lib/ruby_llm/providers/cohere.rb +5 -1
- data/lib/ruby_llm/providers/deepgram/chat.rb +25 -0
- data/lib/ruby_llm/providers/deepgram.rb +21 -2
- data/lib/ruby_llm/providers/deepseek/chat.rb +7 -16
- data/lib/ruby_llm/providers/deepseek/responses.rb +25 -8
- data/lib/ruby_llm/providers/deepseek.rb +5 -1
- data/lib/ruby_llm/providers/elevenlabs.rb +2 -1
- data/lib/ruby_llm/providers/gemini.rb +13 -1
- data/lib/ruby_llm/providers/gpustack/chat.rb +23 -3
- data/lib/ruby_llm/providers/gpustack/embeddings.rb +2 -2
- data/lib/ruby_llm/providers/gpustack/media.rb +8 -8
- data/lib/ruby_llm/providers/gpustack/transcription.rb +14 -6
- data/lib/ruby_llm/providers/gpustack.rb +1 -1
- data/lib/ruby_llm/providers/hetzner/chat.rb +23 -6
- data/lib/ruby_llm/providers/hetzner.rb +5 -1
- data/lib/ruby_llm/providers/meta/responses.rb +81 -0
- data/lib/ruby_llm/providers/meta.rb +37 -0
- data/lib/ruby_llm/providers/minimax/anthropic.rb +95 -0
- data/lib/ruby_llm/providers/minimax/chat_completions.rb +48 -0
- data/lib/ruby_llm/providers/minimax/responses.rb +52 -0
- data/lib/ruby_llm/providers/minimax.rb +104 -0
- data/lib/ruby_llm/providers/mistral/chat.rb +34 -4
- data/lib/ruby_llm/providers/mistral/chat_completions/batches.rb +5 -14
- data/lib/ruby_llm/providers/mistral/embeddings.rb +1 -12
- data/lib/ruby_llm/providers/mistral/input_tokens.rb +35 -0
- data/lib/ruby_llm/providers/mistral/media.rb +8 -8
- data/lib/ruby_llm/providers/mistral/transcription.rb +8 -6
- data/lib/ruby_llm/providers/mistral.rb +13 -1
- data/lib/ruby_llm/providers/moonshot/capabilities.rb +16 -0
- data/lib/ruby_llm/providers/moonshot/chat.rb +100 -0
- data/lib/ruby_llm/providers/moonshot/documents.rb +79 -0
- data/lib/ruby_llm/providers/moonshot/responses.rb +55 -0
- data/lib/ruby_llm/providers/moonshot.rb +54 -0
- data/lib/ruby_llm/providers/ollama/chat.rb +5 -6
- data/lib/ruby_llm/providers/ollama/embeddings.rb +41 -0
- data/lib/ruby_llm/providers/ollama/media.rb +6 -6
- data/lib/ruby_llm/providers/ollama/speech.rb +24 -0
- data/lib/ruby_llm/providers/ollama.rb +13 -1
- data/lib/ruby_llm/providers/ollama_cloud.rb +22 -1
- data/lib/ruby_llm/providers/openai/responses.rb +8 -0
- data/lib/ruby_llm/providers/openai.rb +7 -3
- data/lib/ruby_llm/providers/openrouter/chat.rb +15 -9
- data/lib/ruby_llm/providers/openrouter/embeddings.rb +12 -8
- data/lib/ruby_llm/providers/openrouter/images.rb +16 -10
- data/lib/ruby_llm/providers/openrouter/judgments.rb +47 -0
- data/lib/ruby_llm/providers/openrouter/media.rb +5 -5
- data/lib/ruby_llm/providers/openrouter/models.rb +19 -7
- data/lib/ruby_llm/providers/openrouter/streaming.rb +4 -4
- data/lib/ruby_llm/providers/openrouter/videos.rb +1 -1
- data/lib/ruby_llm/providers/openrouter.rb +32 -5
- data/lib/ruby_llm/providers/perplexity/chat.rb +3 -3
- data/lib/ruby_llm/providers/perplexity/embeddings.rb +1 -1
- data/lib/ruby_llm/providers/perplexity/media.rb +6 -6
- data/lib/ruby_llm/providers/perplexity.rb +13 -2
- data/lib/ruby_llm/providers/typesafe.rb +1 -1
- data/lib/ruby_llm/providers/vertexai/anthropic.rb +5 -1
- data/lib/ruby_llm/providers/vertexai/credentials.rb +27 -3
- data/lib/ruby_llm/providers/vertexai/embed_content.rb +1 -1
- data/lib/ruby_llm/providers/vertexai/embeddings.rb +2 -3
- data/lib/ruby_llm/providers/vertexai/gemini.rb +1 -1
- data/lib/ruby_llm/providers/vertexai/mistral.rb +5 -0
- data/lib/ruby_llm/providers/vertexai/models.rb +24 -2
- data/lib/ruby_llm/providers/vertexai/transcription.rb +2 -2
- data/lib/ruby_llm/providers/vertexai/videos.rb +1 -1
- data/lib/ruby_llm/providers/vertexai.rb +56 -9
- data/lib/ruby_llm/providers/xai/chat.rb +3 -3
- data/lib/ruby_llm/providers/xai/chat_completions/batches.rb +8 -3
- data/lib/ruby_llm/providers/xai/images.rb +9 -4
- data/lib/ruby_llm/providers/xai/models.rb +2 -2
- data/lib/ruby_llm/providers/xai/responses.rb +10 -0
- data/lib/ruby_llm/providers/xai/speech.rb +2 -2
- data/lib/ruby_llm/providers/xai/transcription.rb +14 -9
- data/lib/ruby_llm/providers/xai/videos.rb +1 -1
- data/lib/ruby_llm/providers/xai.rb +9 -1
- data/lib/ruby_llm/providers/zai/chat.rb +117 -0
- data/lib/ruby_llm/providers/zai/ocr.rb +65 -0
- data/lib/ruby_llm/providers/zai/token_counting.rb +25 -0
- data/lib/ruby_llm/providers/zai/videos.rb +67 -0
- data/lib/ruby_llm/providers/zai.rb +66 -0
- data/lib/ruby_llm/question.rb +390 -0
- data/lib/ruby_llm/queued_message.rb +74 -0
- data/lib/ruby_llm/railtie.rb +43 -0
- data/lib/ruby_llm/request_shape/part.rb +2 -2
- data/lib/ruby_llm/request_shape/problem.rb +2 -2
- data/lib/ruby_llm/request_shape/tool_round.rb +2 -2
- data/lib/ruby_llm/request_shape/turn.rb +2 -2
- data/lib/ruby_llm/request_shape.rb +1 -1
- data/lib/ruby_llm/rerank.rb +10 -37
- data/lib/ruby_llm/research_job.rb +26 -13
- data/lib/ruby_llm/sandbox/landlock.rb +78 -0
- data/lib/ruby_llm/sandbox/mxc.rb +137 -0
- data/lib/ruby_llm/sandbox.rb +141 -0
- data/lib/ruby_llm/search_results.rb +9 -4
- data/lib/ruby_llm/server_tool_call.rb +1 -1
- data/lib/ruby_llm/skill/loader.rb +131 -0
- data/lib/ruby_llm/skill.rb +263 -0
- data/lib/ruby_llm/speech.rb +25 -53
- data/lib/ruby_llm/stored_file.rb +94 -0
- data/lib/ruby_llm/support/cancellation.rb +4 -4
- data/lib/ruby_llm/support/deprecated_enumerable.rb +13 -0
- data/lib/ruby_llm/support/deprecated_job_predicates.rb +24 -0
- data/lib/ruby_llm/support/inspectable.rb +1 -1
- data/lib/ruby_llm/support/instrumentation.rb +6 -5
- data/lib/ruby_llm/support/rescuable.rb +84 -0
- data/lib/ruby_llm/support/utils.rb +26 -3
- data/lib/ruby_llm/task.rb +126 -0
- data/lib/ruby_llm/test_helper.rb +129 -0
- data/lib/ruby_llm/thinking.rb +3 -3
- data/lib/ruby_llm/tokens.rb +52 -12
- data/lib/ruby_llm/tool.rb +339 -5
- data/lib/ruby_llm/tool_call/collection.rb +132 -0
- data/lib/ruby_llm/tool_call.rb +68 -6
- data/lib/ruby_llm/tools/provider_tools.rb +23 -0
- data/lib/ruby_llm/tools/search.rb +118 -0
- data/lib/ruby_llm/transcription/segment.rb +67 -0
- data/lib/ruby_llm/transcription/wav_audio.rb +2 -1
- data/lib/ruby_llm/transcription.rb +25 -49
- data/lib/ruby_llm/transcription_chunk.rb +9 -9
- data/lib/ruby_llm/transport/connection.rb +146 -33
- data/lib/ruby_llm/transport/error_middleware.rb +94 -49
- data/lib/ruby_llm/transport/event_stream_parser.rb +18 -4
- data/lib/ruby_llm/transport/json_response.rb +9 -3
- data/lib/ruby_llm/transport/log_formatter.rb +20 -0
- data/lib/ruby_llm/transport/release_request.rb +35 -0
- data/lib/ruby_llm/transport/websocket_connection.rb +26 -30
- data/lib/ruby_llm/uploaded_file.rb +15 -6
- data/lib/ruby_llm/version.rb +1 -1
- data/lib/ruby_llm/video.rb +34 -10
- data/lib/ruby_llm/video_job.rb +55 -42
- data/lib/ruby_llm/web_source.rb +38 -0
- data/lib/ruby_llm/workflow.rb +2 -2
- data/lib/ruby_llm.rb +63 -25
- data/lib/tasks/ruby_llm/evaluations.rb +1 -1
- data/skills/rubyllm/SKILL.md +128 -54
- data/skills/rubyllm/references/cost-and-tracing.md +8 -0
- data/skills/rubyllm/references/files-code-and-context.md +6 -0
- data/skills/rubyllm/references/operations.md +8 -0
- data/skills/rubyllm/references/rails-chats.md +22 -0
- data/skills/rubyllm/references/tools-and-agents.md +11 -0
- metadata +213 -14
- data/lib/generators/ruby_llm/chat_ui/templates/helpers/messages_helper.rb.tt +0 -25
- data/lib/generators/ruby_llm/upgrade/templates/upgrade_ruby_llm_to_2_1.rb.tt +0 -78
data/lib/ruby_llm/chat.rb
CHANGED
|
@@ -16,26 +16,51 @@ module RubyLLM
|
|
|
16
16
|
# chat.with_instructions("Be terse.").with_tools(Weather)
|
|
17
17
|
#
|
|
18
18
|
# #ask runs the conversation loop, executing tools until the model answers
|
|
19
|
-
# or a call
|
|
20
|
-
# expose individual operations.
|
|
21
|
-
#
|
|
19
|
+
# or a call waits on a person. #ask_later, #generate, #run_tools, and
|
|
20
|
+
# #step expose individual operations. Answer what a paused call asks,
|
|
21
|
+
# an approval included (see #pending_questions), then #complete carries
|
|
22
|
+
# it on. #queue adds a message from anywhere, even while the loop runs,
|
|
23
|
+
# and the loop takes it between two moves.
|
|
22
24
|
#
|
|
23
|
-
#
|
|
25
|
+
# Read the conversation through #messages.
|
|
24
26
|
class Chat # rubocop:disable Metrics/ClassLength
|
|
25
|
-
include Enumerable
|
|
26
27
|
include Support::Inspectable
|
|
28
|
+
include Support::DeprecatedEnumerable
|
|
27
29
|
include ToolSearch
|
|
30
|
+
include ToolSequences
|
|
31
|
+
prepend AgentRun
|
|
32
|
+
prepend Rescuable
|
|
33
|
+
prepend Ownership
|
|
28
34
|
|
|
29
35
|
# The provider-neutral options #with_compaction accepts.
|
|
30
36
|
COMPACTION_OPTIONS = %i[at instructions pause_after].freeze
|
|
31
37
|
THINKING_OPTIONS = %i[effort budget display].freeze
|
|
38
|
+
TOOL_OPTIONS = %i[choice calls concurrency rounds].freeze
|
|
32
39
|
PAUSED = Object.new.freeze
|
|
40
|
+
TOOL_CHOICE_MODES = %i[auto none required].freeze
|
|
41
|
+
AGENT_RUN_KEY = :ruby_llm_agent_run
|
|
42
|
+
COPIED_STATE = %i[
|
|
43
|
+
@usage_entries @tools @tool_deferrals @mcp @mcp_deferrals @tool_prefs @headers @attachment_replacements
|
|
44
|
+
@tool_call_state
|
|
45
|
+
].freeze
|
|
33
46
|
UNFINISHED_TOOL_RESULT = { error: 'The tool call did not finish.' }.to_json.freeze
|
|
34
|
-
|
|
47
|
+
# Not a RubyLLM::Error, which a record takes for a failed request and
|
|
48
|
+
# answers by removing the round.
|
|
49
|
+
class StalledToolRound < StandardError; end # :nodoc:
|
|
50
|
+
private_constant :THINKING_OPTIONS, :TOOL_OPTIONS, :PAUSED, :TOOL_CHOICE_MODES, :AGENT_RUN_KEY, :COPIED_STATE,
|
|
51
|
+
:UNFINISHED_TOOL_RESULT, :StalledToolRound
|
|
35
52
|
|
|
36
53
|
# The Model the chat sends requests to.
|
|
37
54
|
attr_reader :model
|
|
38
55
|
|
|
56
|
+
# Returns the id of the Model the chat sends requests to.
|
|
57
|
+
#
|
|
58
|
+
# chat.model_id # => "gpt-6-luna"
|
|
59
|
+
#
|
|
60
|
+
def model_id
|
|
61
|
+
model.id
|
|
62
|
+
end
|
|
63
|
+
|
|
39
64
|
# The Provider instance handling requests for the current model.
|
|
40
65
|
attr_reader :provider
|
|
41
66
|
|
|
@@ -78,26 +103,46 @@ module RubyLLM
|
|
|
78
103
|
# explicitly disabled, or +nil+ when not configured.
|
|
79
104
|
attr_reader :compaction
|
|
80
105
|
|
|
106
|
+
# The shares of the context window set with #with_context_budget, or
|
|
107
|
+
# else Configuration#context_budget. Returns +nil+ when not configured.
|
|
108
|
+
attr_reader :context_budget
|
|
109
|
+
|
|
81
110
|
# The opaque per-user identifier set with #with_end_user, or
|
|
82
111
|
# +nil+.
|
|
83
112
|
attr_reader :end_user
|
|
84
113
|
|
|
114
|
+
# Whoever the chat's usage is attributed to: the owner set with
|
|
115
|
+
# #with_owner, or else, for a persisted chat, the record its
|
|
116
|
+
# +acts_as_chat+ declaration names with +owner:+. Returns +nil+ when
|
|
117
|
+
# neither is set.
|
|
118
|
+
def owner
|
|
119
|
+
@owner || @run.owner
|
|
120
|
+
end
|
|
121
|
+
|
|
85
122
|
# The Fallback models tried in order when generation fails.
|
|
86
123
|
attr_reader :fallbacks
|
|
87
124
|
|
|
88
125
|
# Whether #with_citations asked the provider for citations.
|
|
89
126
|
attr_reader :citations
|
|
90
127
|
|
|
128
|
+
# The code execution options set with #with_code_execution, +false+
|
|
129
|
+
# when explicitly disabled, or +nil+ when not configured.
|
|
130
|
+
attr_reader :code_execution
|
|
131
|
+
|
|
132
|
+
# The Skill objects given with #with_skills, empty without skills.
|
|
133
|
+
attr_reader :skills
|
|
134
|
+
|
|
91
135
|
# The Context this chat sends requests through, or +nil+ for the global
|
|
92
136
|
# configuration.
|
|
93
137
|
attr_reader :context
|
|
94
138
|
|
|
95
139
|
attr_reader :tool_prefs, :fallback_errors, :usage_entries # :nodoc:
|
|
96
140
|
|
|
97
|
-
# Returns the +choice+, +calls+, and +
|
|
141
|
+
# Returns the +choice+, +calls+, +concurrency+, and +rounds+ set with
|
|
98
142
|
# #with_tool_options, with +nil+ for anything left at the default.
|
|
99
143
|
def tool_options
|
|
100
|
-
{ choice: tool_prefs[:choice], calls: tool_prefs[:calls], concurrency: concurrency
|
|
144
|
+
{ choice: tool_prefs[:choice], calls: tool_prefs[:calls] || @tool_call_cap, concurrency: concurrency,
|
|
145
|
+
rounds: @tool_rounds }
|
|
101
146
|
end
|
|
102
147
|
|
|
103
148
|
# Creates a chat with +model:+, or with the configured default model
|
|
@@ -128,7 +173,7 @@ module RubyLLM
|
|
|
128
173
|
@mcp_deferrals = {}
|
|
129
174
|
@provider_tools = []
|
|
130
175
|
@tool_prefs = { choice: nil, calls: nil }
|
|
131
|
-
|
|
176
|
+
apply_tool_concurrency(nil)
|
|
132
177
|
@provider_options = {}
|
|
133
178
|
@headers = {}
|
|
134
179
|
@schema = nil
|
|
@@ -136,25 +181,68 @@ module RubyLLM
|
|
|
136
181
|
@citations = false
|
|
137
182
|
@caching = nil
|
|
138
183
|
@compaction = nil
|
|
184
|
+
@context_budget = @config.context_budget
|
|
185
|
+
@code_execution = nil
|
|
186
|
+
@code_execution_tool = nil
|
|
187
|
+
@skills = []
|
|
188
|
+
@skill_loader = build_skill_loader
|
|
189
|
+
@file_references = nil
|
|
190
|
+
@file_tools = []
|
|
139
191
|
@end_user = nil
|
|
140
192
|
@fallbacks = []
|
|
141
193
|
@fallback_errors = Fallback::DEFAULT_ERRORS
|
|
194
|
+
@drop_unsupported = false
|
|
195
|
+
@answering_fallback = false
|
|
142
196
|
@callbacks = Hash.new { |callbacks, name| callbacks[name] = [] }
|
|
143
197
|
@attachment_replacements = {}.compare_by_identity
|
|
144
198
|
@cancelled = false
|
|
145
|
-
@
|
|
146
|
-
@
|
|
147
|
-
@
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
199
|
+
@run = Run.new
|
|
200
|
+
@tool_call_state = ToolCallState.new
|
|
201
|
+
@message_queue = build_message_queue
|
|
202
|
+
end
|
|
203
|
+
|
|
204
|
+
##
|
|
205
|
+
# :method: dup
|
|
206
|
+
# :call-seq: dup()
|
|
207
|
+
#
|
|
208
|
+
# Returns an independent copy of the chat, for branching a conversation.
|
|
209
|
+
# The copy starts with the same messages, tools, options, and callbacks,
|
|
210
|
+
# and changes to either chat leave the other alone. #clone does the
|
|
211
|
+
# same.
|
|
212
|
+
#
|
|
213
|
+
# branch = chat.dup
|
|
214
|
+
# branch.ask "What if we used Postgres instead?"
|
|
215
|
+
# chat.messages.length # unchanged
|
|
216
|
+
#
|
|
217
|
+
# Tool instances, connected MCP servers, and the provider connection
|
|
218
|
+
# are shared. A cancellation or a run in progress stays with the
|
|
219
|
+
# original. The copy starts with the same queued messages in a queue
|
|
220
|
+
# of its own.
|
|
221
|
+
|
|
222
|
+
def initialize_copy(source) # :nodoc:
|
|
223
|
+
super
|
|
224
|
+
@messages = @messages.map { |message| coerce_message(message.dup) }
|
|
225
|
+
COPIED_STATE.each { |name| instance_variable_set(name, instance_variable_get(name).dup) }
|
|
226
|
+
@provider_tools = Support::Utils.deep_dup(@provider_tools)
|
|
227
|
+
@provider_options = Support::Utils.deep_dup(@provider_options)
|
|
228
|
+
@callbacks = @callbacks.dup.transform_values!(&:dup)
|
|
229
|
+
@skill_loader = build_skill_loader
|
|
230
|
+
@tool_search_tool = nil
|
|
231
|
+
with_code_execution(**@code_execution) if @code_execution
|
|
232
|
+
if @file_references
|
|
233
|
+
with_file_store(file_store, inline_limit: @file_references.inline_limit, tools: @file_references.tools)
|
|
234
|
+
end
|
|
235
|
+
@message_queue = build_message_queue(@message_queue.to_a) if @message_queue.is_a?(MessageQueue)
|
|
236
|
+
@cancelled = false
|
|
151
237
|
end
|
|
152
238
|
|
|
153
239
|
# Adds +message+ as a user message and runs the conversation loop,
|
|
154
240
|
# executing tools until the model answers or a call needs approval.
|
|
155
241
|
# Returns the latest assistant Message; check #waiting? before
|
|
156
242
|
# treating it as a final answer. Attach files with +with:+. An
|
|
157
|
-
# MCP::Prompt adds its messages instead.
|
|
243
|
+
# MCP::Prompt adds its messages instead, and takes no attachments.
|
|
244
|
+
# Messages still in the queue
|
|
245
|
+
# (see #queue) join the conversation first, in order.
|
|
158
246
|
# A given block receives streamed Chunk objects as they arrive.
|
|
159
247
|
#
|
|
160
248
|
# String attachments read local paths or fetch URLs. Only pass trusted,
|
|
@@ -182,11 +270,16 @@ module RubyLLM
|
|
|
182
270
|
# chats = tickets.map { |t| RubyLLM.chat.ask_later(t.body) }
|
|
183
271
|
# RubyLLM.batch(chats)
|
|
184
272
|
#
|
|
273
|
+
# Every message still in the queue (see #queue) joins the conversation
|
|
274
|
+
# first, in order, whether it steers or not.
|
|
275
|
+
#
|
|
185
276
|
# Raises PendingToolCallsError while the last response has unanswered
|
|
186
|
-
# tool calls: finish the round first, recording #approve or #
|
|
277
|
+
# tool calls: finish the round first, recording #approve or #decline
|
|
187
278
|
# decisions for calls that require approval.
|
|
188
279
|
def ask_later(message = nil, with: nil)
|
|
189
280
|
raise_if_pending_tool_calls!
|
|
281
|
+
raise_if_prompt_attachments!(message, with)
|
|
282
|
+
take_queued_messages
|
|
190
283
|
if message.is_a?(MCP::Prompt)
|
|
191
284
|
message.messages.each { |prompt_message| add_message(prompt_message) }
|
|
192
285
|
else
|
|
@@ -203,9 +296,12 @@ module RubyLLM
|
|
|
203
296
|
def generate(&)
|
|
204
297
|
raise_if_cancelled!
|
|
205
298
|
|
|
206
|
-
return generate_once(&) if fallbacks.empty?
|
|
299
|
+
return generate_once(&) if fallbacks.empty? && !@drop_unsupported
|
|
207
300
|
|
|
208
301
|
with_model_restored { generate_with_fallbacks(&) }
|
|
302
|
+
rescue CancelledError
|
|
303
|
+
@cancelled = false
|
|
304
|
+
raise
|
|
209
305
|
end
|
|
210
306
|
|
|
211
307
|
# Executes the tool calls pending in the latest response and appends
|
|
@@ -215,7 +311,7 @@ module RubyLLM
|
|
|
215
311
|
# was declared with Tool.requires_approval only execute once #approve
|
|
216
312
|
# records a decision; denied calls receive a structured denial result,
|
|
217
313
|
# and undecided calls stay pending. Does nothing when no tool calls
|
|
218
|
-
# are pending. Calls paused on
|
|
314
|
+
# are pending. Calls paused on a Task resume once. The chat
|
|
219
315
|
# is then ready for the next #generate, or the next batch round.
|
|
220
316
|
# Returns +self+.
|
|
221
317
|
def run_tools
|
|
@@ -223,9 +319,10 @@ module RubyLLM
|
|
|
223
319
|
|
|
224
320
|
message = pending_tool_response
|
|
225
321
|
execute_pending_tool_calls(message) if message
|
|
322
|
+
raise_if_cancelled!
|
|
226
323
|
self
|
|
227
324
|
rescue CancelledError
|
|
228
|
-
|
|
325
|
+
stop_tool_round
|
|
229
326
|
raise
|
|
230
327
|
end
|
|
231
328
|
|
|
@@ -233,75 +330,205 @@ module RubyLLM
|
|
|
233
330
|
# if any are unanswered, otherwise generates the next response.
|
|
234
331
|
# Returns the Message that move produced, and +nil+ once there is
|
|
235
332
|
# nothing left to do or the chat is #waiting?.
|
|
333
|
+
#
|
|
334
|
+
# Unless tool calls are pending, every message in the queue (see
|
|
335
|
+
# #queue) joins the conversation before the model is asked, whether it
|
|
336
|
+
# steers or not.
|
|
236
337
|
def step(&)
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
raise_if_cancelled!
|
|
240
|
-
return generate(&) unless pending_tool_response
|
|
241
|
-
|
|
242
|
-
before = messages.length
|
|
243
|
-
run_tools
|
|
244
|
-
messages.last if messages.length > before
|
|
245
|
-
rescue CancelledError
|
|
246
|
-
cancel_tasks
|
|
247
|
-
raise
|
|
338
|
+
advance(steering_only: false, &)
|
|
248
339
|
end
|
|
249
340
|
|
|
250
341
|
# Runs the conversation loop until #complete? or #waiting? is +true+.
|
|
251
342
|
# Returns the last conversation Message, or +nil+ for an empty chat.
|
|
343
|
+
# While the chat is #waiting?, returns the assistant Message that holds
|
|
344
|
+
# the pending tool calls, even after other tools in the round have run.
|
|
252
345
|
# Used after #ask_later; #ask calls #complete for you.
|
|
253
346
|
#
|
|
254
347
|
# When a pending tool call requires approval and no decision has been
|
|
255
348
|
# recorded, or waits on input for an MCP server, the loop pauses.
|
|
256
|
-
# Record #approve, #
|
|
257
|
-
# #complete again to continue. A tool call that
|
|
258
|
-
#
|
|
259
|
-
# without waiting, and continues once it
|
|
349
|
+
# Record #approve, #answer, or #decline decisions, then call
|
|
350
|
+
# #complete again to continue. A tool call that returns a Task pauses
|
|
351
|
+
# the loop too, and each #complete resumes it once with Tool#resume,
|
|
352
|
+
# without waiting, and continues once it has a result. For an MCP tool,
|
|
353
|
+
# that checks on its MCP::Task.
|
|
354
|
+
#
|
|
355
|
+
# A turn starts once a question is in place. When the model has
|
|
356
|
+
# answered the last one, every message in the queue joins first, in
|
|
357
|
+
# order, and starts the next turn. Within a turn, only messages that
|
|
358
|
+
# steer join, after each round of tool results and after the answer,
|
|
359
|
+
# so the turn goes on until the model has answered them. Messages
|
|
360
|
+
# queued with <tt>steer: false</tt> wait for the turn to end. A
|
|
361
|
+
# #complete on an unanswered chat, such as one after #ask_later, a
|
|
362
|
+
# retry, or a pause for an approval, continues that turn: only
|
|
363
|
+
# messages that steer join. See #queue.
|
|
260
364
|
def complete(&)
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
365
|
+
resuming = !answered?
|
|
366
|
+
run_tools if pending_tasks.any?
|
|
367
|
+
continue_turn(steering_only: resuming, &)
|
|
368
|
+
end
|
|
369
|
+
|
|
370
|
+
# Runs the loop like #complete. With <tt>steering_only: true</tt> the
|
|
371
|
+
# loop goes on with the turn that is running, so messages queued with
|
|
372
|
+
# <tt>steer: false</tt> stay queued.
|
|
373
|
+
def continue_turn(steering_only: true, &) # :nodoc:
|
|
374
|
+
rounds = 0
|
|
375
|
+
within_run do
|
|
376
|
+
until settled?(steering_only) || waiting?
|
|
377
|
+
boundary = !pending_tool_response
|
|
378
|
+
raise_if_tool_rounds_spent!(rounds) if boundary
|
|
379
|
+
move = advance(steering_only:, &)
|
|
380
|
+
break if placeholder?(move)
|
|
381
|
+
|
|
382
|
+
rounds += 1 if boundary && pending_tool_response
|
|
383
|
+
stalled = stalled_round?(stalled, generated: boundary, move:)
|
|
384
|
+
steering_only ||= boundary
|
|
385
|
+
end
|
|
386
|
+
end
|
|
387
|
+
@cancelled = false
|
|
388
|
+
turn_result
|
|
264
389
|
end
|
|
265
390
|
|
|
266
391
|
# Returns whether the chat has no pending response or tool execution:
|
|
267
|
-
# nothing is staged,
|
|
392
|
+
# nothing is staged, the model answered without requesting tools, or a
|
|
393
|
+
# tool ended the turn with Tool#halt once its round finished,
|
|
394
|
+
# and no queued message steers the turn. Messages queued with
|
|
395
|
+
# <tt>steer: false</tt> don't count, so the chat is complete while
|
|
396
|
+
# they wait for the next #complete.
|
|
268
397
|
def complete?
|
|
269
|
-
|
|
398
|
+
settled?(true)
|
|
399
|
+
end
|
|
270
400
|
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
401
|
+
# Adds +message+ to the queue: a user message that waits outside the
|
|
402
|
+
# conversation until the loop takes it. Call it at any time, from any
|
|
403
|
+
# thread, even while #complete runs in another one. Attach files with
|
|
404
|
+
# +with:+, as with #ask. Returns the QueuedMessage.
|
|
405
|
+
#
|
|
406
|
+
# chat.queue "Use the EU file instead"
|
|
407
|
+
# chat.queue "Then email it to me", steer: false
|
|
408
|
+
# chat.queue "Check this one too", with: "q3.pdf", sender: current_user
|
|
409
|
+
#
|
|
410
|
+
# A message that steers, the default, joins the turn that is running:
|
|
411
|
+
# after the next round of tool results, or once the model finishes its
|
|
412
|
+
# answer, which then goes on to answer it too. Pass <tt>steer: false</tt>
|
|
413
|
+
# to wait for the turn to end instead: #complete returns, the chat is
|
|
414
|
+
# #complete?, and the next #ask, #ask_later, or #complete on the
|
|
415
|
+
# answered chat takes the message, as does a #step with no tool calls
|
|
416
|
+
# pending. Steering messages can join before waiting ones queued
|
|
417
|
+
# earlier. Messages that join together become separate user messages,
|
|
418
|
+
# oldest first.
|
|
419
|
+
#
|
|
420
|
+
# Nothing is taken while the chat is #waiting?, and #cancel leaves the
|
|
421
|
+
# queue as it is. Queueing never runs the loop: when nothing is
|
|
422
|
+
# running, call #complete. +sender+, whoever queued the message, is
|
|
423
|
+
# stored with it and handed back without RubyLLM interpreting it.
|
|
424
|
+
def queue(message = nil, with: nil, steer: true, sender: nil)
|
|
425
|
+
@message_queue.push(content: message, attachments: with, steer:, sender:)
|
|
426
|
+
end
|
|
427
|
+
|
|
428
|
+
# Returns the messages waiting in the queue, as QueuedMessage objects,
|
|
429
|
+
# oldest first.
|
|
430
|
+
def queued_messages
|
|
431
|
+
@message_queue.to_a
|
|
432
|
+
end
|
|
433
|
+
|
|
434
|
+
# Takes +queued+, a QueuedMessage or its id, out of the queue before the
|
|
435
|
+
# loop takes it. Returns +true+, or +false+ when it is no longer queued:
|
|
436
|
+
# the loop took it into the conversation, or it was withdrawn already.
|
|
437
|
+
# QueuedMessage#withdraw does the same from the message.
|
|
438
|
+
#
|
|
439
|
+
# chat.withdraw(queued) # => true
|
|
440
|
+
#
|
|
441
|
+
def withdraw(queued)
|
|
442
|
+
!@message_queue.delete(queued).nil?
|
|
443
|
+
end
|
|
444
|
+
|
|
445
|
+
# Adds every queued message to the conversation, without asking the
|
|
446
|
+
# model, and returns the user Message objects they became, oldest
|
|
447
|
+
# first. Each message joins through #around_join and runs
|
|
448
|
+
# #after_message, whether it steers or not.
|
|
449
|
+
#
|
|
450
|
+
# chat.queue "Use the EU file"
|
|
451
|
+
# chat.queue "Then email it to me", steer: false
|
|
452
|
+
# chat.join_queued_messages.map(&:content) # => ["Use the EU file", "Then email it to me"]
|
|
453
|
+
#
|
|
454
|
+
# Raises PendingToolCallsError while the last response has unanswered
|
|
455
|
+
# tool calls, as #ask_later does.
|
|
456
|
+
def join_queued_messages
|
|
457
|
+
raise_if_pending_tool_calls!
|
|
458
|
+
take_queued_messages
|
|
459
|
+
end
|
|
460
|
+
|
|
461
|
+
# Adds every queued message to the conversation, or with
|
|
462
|
+
# <tt>steering_only: true</tt> only those that steer, and runs
|
|
463
|
+
# #after_message for each one that joined. Returns the joined messages.
|
|
464
|
+
def take_queued_messages(steering_only: false) # :nodoc:
|
|
465
|
+
joined = []
|
|
466
|
+
@message_queue.take(steering_only:) do |message|
|
|
467
|
+
next unless message
|
|
468
|
+
|
|
469
|
+
joined << message
|
|
470
|
+
run_callbacks(:after_message, messages.last)
|
|
471
|
+
end
|
|
472
|
+
joined
|
|
473
|
+
end
|
|
474
|
+
|
|
475
|
+
# Runs the #around_join callbacks for +queued+, outermost first, around
|
|
476
|
+
# the given block, which adds the message with the attributes the
|
|
477
|
+
# callbacks pass to +join+. Returns the message, or +nil+ when a
|
|
478
|
+
# callback withdrew it. Takes the message back out of the conversation
|
|
479
|
+
# when a callback raises.
|
|
480
|
+
def run_around_join(queued, &add) # :nodoc:
|
|
481
|
+
joined = nil
|
|
482
|
+
size = messages.length
|
|
483
|
+
innermost = ->(**attributes) { joined ||= add.call(**attributes) }
|
|
484
|
+
chain = @callbacks[:around_join].reverse.reduce(innermost) do |inner, callback|
|
|
485
|
+
lambda do |**outer|
|
|
486
|
+
callback.call(queued, lambda { |**attributes|
|
|
487
|
+
inner.call(**outer, **attributes)
|
|
488
|
+
joined
|
|
489
|
+
})
|
|
490
|
+
end
|
|
276
491
|
end
|
|
492
|
+
chain.call
|
|
493
|
+
joined
|
|
494
|
+
rescue StandardError
|
|
495
|
+
messages.slice!(size..)
|
|
496
|
+
raise
|
|
277
497
|
end
|
|
278
498
|
|
|
279
|
-
# Records approval for +tool_call+,
|
|
280
|
-
# #
|
|
281
|
-
#
|
|
499
|
+
# Records approval for +tool_call+, the approval Question from
|
|
500
|
+
# #pending_questions, its ToolCall, or its id, so the next #complete or
|
|
501
|
+
# #run_tools executes a local tool or records permission for the
|
|
502
|
+
# provider to execute a remote tool on the next request. Returns
|
|
503
|
+
# +self+. Question#approve does the same.
|
|
282
504
|
#
|
|
283
505
|
# chat.approve(tool_call)
|
|
284
506
|
# chat.complete
|
|
285
507
|
#
|
|
286
|
-
|
|
508
|
+
# With <tt>remember: true</tt>, later calls to the same tool run without
|
|
509
|
+
# asking for the rest of the chat.
|
|
510
|
+
#
|
|
511
|
+
# chat.approve(tool_call, remember: true)
|
|
512
|
+
#
|
|
513
|
+
# Approving a call that already has a result remembers nothing.
|
|
514
|
+
#
|
|
515
|
+
# A +run_code+ call that asks for another sandbox is approved one call
|
|
516
|
+
# at a time: passing <tt>remember: true</tt> for it raises
|
|
517
|
+
# ArgumentError, and the approval never applies to another call.
|
|
518
|
+
# Raises ArgumentError for a Question that is not an approval.
|
|
519
|
+
def approve(tool_call, remember: false)
|
|
520
|
+
tool_call = Question.decided_call(tool_call, 'answer')
|
|
521
|
+
name = remembered_tool_identity(tool_call) if remember
|
|
287
522
|
record_tool_call_decision(tool_call, true)
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
# Records denial for +tool_call+, a ToolCall or its id. The next
|
|
291
|
-
# #complete or #run_tools appends a structured denial result instead
|
|
292
|
-
# of executing a local tool, or sends a refusal for a remote tool on the
|
|
293
|
-
# next request. The model continues from there. Returns
|
|
294
|
-
# +self+.
|
|
295
|
-
def deny(tool_call)
|
|
296
|
-
record_tool_call_decision(tool_call, false)
|
|
523
|
+
@tool_call_state.remember(name) if name && !tool_call_answered?(tool_call)
|
|
524
|
+
self
|
|
297
525
|
end
|
|
298
526
|
|
|
299
527
|
# Returns whether the conversation can't continue until something
|
|
300
528
|
# outside it happens: every remaining pending tool call waits on an
|
|
301
|
-
#
|
|
302
|
-
# #complete stops here, and #
|
|
303
|
-
#
|
|
304
|
-
# #step here too:
|
|
529
|
+
# answer to a question, a Task, or a run in another process.
|
|
530
|
+
# #complete stops here, and #pending_questions and #pending_tasks tell
|
|
531
|
+
# what it waits on. Stop a loop you drive with #step here too:
|
|
305
532
|
#
|
|
306
533
|
# chat.step until chat.complete? || chat.waiting?
|
|
307
534
|
#
|
|
@@ -309,112 +536,142 @@ module RubyLLM
|
|
|
309
536
|
response = pending_tool_response
|
|
310
537
|
return false unless response
|
|
311
538
|
|
|
312
|
-
pending = pending_tool_calls(response)
|
|
313
|
-
pending.any? && pending.all?
|
|
539
|
+
pending = pending_tool_calls(response)
|
|
540
|
+
pending.any? && pending.all? do |tool_call|
|
|
541
|
+
approval_pending?(tool_call) || paused?(tool_call) ||
|
|
542
|
+
running_elsewhere?(tool_call) || sequence_blocked?(tool_call) || exclusive_blocked?(tool_call)
|
|
543
|
+
end
|
|
314
544
|
end
|
|
315
545
|
|
|
316
|
-
# Returns
|
|
317
|
-
#
|
|
318
|
-
#
|
|
319
|
-
# #
|
|
320
|
-
#
|
|
321
|
-
# then call #complete again. Tool calls that need no approval still
|
|
322
|
-
# execute before the loop pauses.
|
|
546
|
+
# Returns the questions the conversation waits on a person to answer,
|
|
547
|
+
# as Question objects, in the order the model made their calls: the
|
|
548
|
+
# approvals of tools declared with Tool.requires_approval, which ask
|
|
549
|
+
# before the tool runs, and the questions tools ask with Tool#ask and
|
|
550
|
+
# MCP servers ask while they work. Empty when nothing waits on a person.
|
|
323
551
|
#
|
|
324
|
-
#
|
|
325
|
-
#
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
# Returns the tool calls from the latest response that require approval
|
|
331
|
-
# and have no recorded decision, as an array of ToolCall objects. Pairs
|
|
332
|
-
# with #approve and #deny. ToolCall#remote? identifies provider-executed calls.
|
|
552
|
+
# chat.ask "Book me a flight to Lisbon"
|
|
553
|
+
# question = chat.pending_questions.first
|
|
554
|
+
# question.message # => "Window or aisle?", or nil for an approval
|
|
555
|
+
# question.answer "window" # as the person chose; approve or decline an approval
|
|
556
|
+
# chat.complete
|
|
333
557
|
#
|
|
334
|
-
# chat.
|
|
335
|
-
# chat.approve(chat.pending_approvals.first)
|
|
558
|
+
# chat.pending_questions.select(&:approval?).each { |question| puts question.tool_call.name }
|
|
336
559
|
#
|
|
337
|
-
|
|
560
|
+
# #complete carries each call on once nothing it asked waits for an
|
|
561
|
+
# answer. Calls that need no answer still run before the loop pauses.
|
|
562
|
+
# Consults each pending tool's approval resolver when one is declared,
|
|
563
|
+
# so resolvers must be idempotent reads.
|
|
564
|
+
def pending_questions
|
|
338
565
|
response = pending_tool_response
|
|
339
566
|
return [] unless response
|
|
340
567
|
|
|
341
|
-
pending_tool_calls(response).
|
|
342
|
-
|
|
568
|
+
pending_tool_calls(response).flat_map do |tool_call|
|
|
569
|
+
next [Question.approval(tool_call, chat: self)] if approval_pending?(tool_call)
|
|
343
570
|
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
# input or an approval decision, and at least one waits on input.
|
|
347
|
-
def awaiting_input?
|
|
348
|
-
waiting? && pending_inputs.any?
|
|
571
|
+
unanswered_questions(tool_call)
|
|
572
|
+
end
|
|
349
573
|
end
|
|
350
574
|
|
|
351
|
-
#
|
|
352
|
-
#
|
|
353
|
-
#
|
|
575
|
+
# Answers +question+, a Question from #pending_questions or its id, as
|
|
576
|
+
# Question#answer describes, and returns +self+. Answering an approval
|
|
577
|
+
# approves its call. Takes the ActionController::Parameters a form
|
|
578
|
+
# sends for several fields, and keeps only the fields the question asks
|
|
579
|
+
# for. A question already answered, or one whose call has finished,
|
|
580
|
+
# stays as it is, so a form sent twice is safe, and of two answers to
|
|
581
|
+
# one approval at once, the first stands. #approve instead records a
|
|
582
|
+
# decision whatever came before.
|
|
354
583
|
#
|
|
355
|
-
# chat.
|
|
356
|
-
# chat.answer(
|
|
584
|
+
# chat.answer(question, "window")
|
|
585
|
+
# chat.answer(params[:question_id], params[:answer])
|
|
586
|
+
# chat.complete
|
|
357
587
|
#
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
588
|
+
# Raises ArgumentError for a question the chat never asked, and for an
|
|
589
|
+
# answer the question can't take.
|
|
590
|
+
def answer(question, value = nil, **values)
|
|
591
|
+
pending = pending_question(question)
|
|
592
|
+
response = pending&.response_to(value, values)
|
|
593
|
+
return self unless pending && settle_question(pending, response)
|
|
361
594
|
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
.map { |data| MCP::InputRequest.from_h(data, tool_call:) }
|
|
365
|
-
.reject(&:answered?)
|
|
366
|
-
end
|
|
595
|
+
question.respond(response) if question.is_a?(Question)
|
|
596
|
+
self
|
|
367
597
|
end
|
|
368
598
|
|
|
369
|
-
#
|
|
370
|
-
#
|
|
371
|
-
#
|
|
372
|
-
#
|
|
373
|
-
#
|
|
374
|
-
#
|
|
375
|
-
#
|
|
376
|
-
#
|
|
599
|
+
# Declines +question+, a Question from #pending_questions, its id, or
|
|
600
|
+
# the ToolCall of an approval, and returns +self+. A declined
|
|
601
|
+
# approval's call doesn't run: the next #complete or #run_tools gives
|
|
602
|
+
# the model a refusal instead, or sends one for a remote tool on the
|
|
603
|
+
# next request, unless another decision came first, also once the chat
|
|
604
|
+
# no longer offers the call's tool. A tool that asked
|
|
605
|
+
# gets +nil+ from Tool#ask. A +note+ tells the model why: it is the
|
|
606
|
+
# declined approval's result in place of the plain refusal, and it
|
|
607
|
+
# follows the result of a tool whose question was declined. A Hash
|
|
608
|
+
# +note+ is the declined approval's whole result, as given, and
|
|
609
|
+
# follows a tool's result as JSON. A blank note counts as none. A question already answered, or one whose call
|
|
610
|
+
# has finished, stays as it is.
|
|
611
|
+
#
|
|
612
|
+
# chat.decline(question)
|
|
613
|
+
# chat.decline(params[:question_id], "The order shipped already")
|
|
377
614
|
# chat.complete
|
|
378
615
|
#
|
|
379
|
-
|
|
380
|
-
|
|
616
|
+
# Raises ArgumentError for a question the chat never asked.
|
|
617
|
+
def decline(question, note = nil)
|
|
618
|
+
pending = pending_question(question)
|
|
619
|
+
response = Question.declined(note)
|
|
620
|
+
return self unless pending && settle_question(pending, response)
|
|
621
|
+
|
|
622
|
+
question.respond(response) if question.is_a?(Question)
|
|
623
|
+
self
|
|
381
624
|
end
|
|
382
625
|
|
|
383
|
-
# Returns
|
|
384
|
-
#
|
|
385
|
-
|
|
386
|
-
|
|
626
|
+
# Returns whether +tool_call+ requires approval and has no recorded
|
|
627
|
+
# decision.
|
|
628
|
+
def approval_pending?(tool_call) # :nodoc:
|
|
629
|
+
return false if tool_call.malformed_arguments? || skipped_result(tool_call) || capped_tool_call?(tool_call)
|
|
630
|
+
return approval_decision(nil, tool_call).nil? if tool_call.remote?
|
|
631
|
+
|
|
632
|
+
tool = tool_for(tool_call)
|
|
633
|
+
return false unless tool&.requires_approval?(tool_call)
|
|
634
|
+
|
|
635
|
+
approval_decision(tool, tool_call).nil?
|
|
636
|
+
end
|
|
637
|
+
|
|
638
|
+
# Returns the Task objects that tool calls wait on, as they were when
|
|
639
|
+
# the chat last checked, with an MCP::Task for each MCP tool call.
|
|
640
|
+
# Task#refresh checks on one without resuming the chat; #complete
|
|
641
|
+
# resumes every call with Tool#resume.
|
|
387
642
|
#
|
|
388
643
|
# chat.pending_tasks.each { |task| puts "#{task.tool_call.name}: #{task.status_message}" }
|
|
389
644
|
#
|
|
645
|
+
# A task that is Task#input_required? waits on a person, as the
|
|
646
|
+
# questions in #pending_questions do, so there is no point in checking
|
|
647
|
+
# on it before they act:
|
|
648
|
+
#
|
|
649
|
+
# notify(chat.owner) if chat.pending_questions.any? || chat.pending_tasks.any?(&:input_required?)
|
|
650
|
+
#
|
|
651
|
+
# Check on the others after their Task#poll_interval:
|
|
652
|
+
#
|
|
653
|
+
# sleep chat.pending_tasks.first.poll_interval
|
|
654
|
+
# chat.complete
|
|
655
|
+
#
|
|
390
656
|
def pending_tasks
|
|
391
657
|
response = pending_tool_response
|
|
392
658
|
return [] unless response
|
|
393
659
|
|
|
394
|
-
pending_tool_calls(response).
|
|
660
|
+
pending_tool_calls(response).filter_map do |tool_call|
|
|
395
661
|
state = tool_call_input(tool_call)
|
|
396
662
|
task_for(tool_call, state) if state&.key?('task') && !unanswered?(state)
|
|
397
663
|
end
|
|
398
664
|
end
|
|
399
665
|
|
|
400
|
-
#
|
|
401
|
-
#
|
|
402
|
-
#
|
|
403
|
-
#
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
#
|
|
409
|
-
# Returns +self+.
|
|
410
|
-
def decline(request)
|
|
411
|
-
settle_input(request, &:decline)
|
|
412
|
-
end
|
|
413
|
-
|
|
414
|
-
# Cancels the current in-flight chat operation. The next cancellation
|
|
415
|
-
# checkpoint raises CancelledError and clears the flag so the chat can be
|
|
416
|
-
# reused. The MCP tasks that pending tool calls wait on are cancelled
|
|
417
|
-
# then too; see #pending_tasks.
|
|
666
|
+
# Cancels the current in-flight chat operation. Every cancellation
|
|
667
|
+
# checkpoint raises CancelledError until the operation ends, so tool
|
|
668
|
+
# calls running concurrently all stop, and the flag is cleared then so
|
|
669
|
+
# the chat can be reused. The tasks that pending tool calls wait on are
|
|
670
|
+
# cancelled then too; see #pending_tasks. Tool calls left without a
|
|
671
|
+
# result are closed as unfinished, so the next #ask can go on and no
|
|
672
|
+
# tool runs twice. A tool that already returned keeps its result. The
|
|
673
|
+
# text a cancelled stream showed stays as a reply that is
|
|
674
|
+
# Message#cancelled?.
|
|
418
675
|
def cancel
|
|
419
676
|
@cancelled = true
|
|
420
677
|
self
|
|
@@ -460,6 +717,10 @@ module RubyLLM
|
|
|
460
717
|
#
|
|
461
718
|
# chat.with_tools(*Catalog.tools, defer: true)
|
|
462
719
|
#
|
|
720
|
+
# A namespaced tool is registered under its namespace and name joined,
|
|
721
|
+
# as in <tt>:crm_customer_lookup</tt>. Raises ArgumentError when that
|
|
722
|
+
# key belongs to another tool.
|
|
723
|
+
#
|
|
463
724
|
# To replace the registered tools, clear them first:
|
|
464
725
|
#
|
|
465
726
|
# chat.with_tools(nil).with_tools(NewTool)
|
|
@@ -470,10 +731,16 @@ module RubyLLM
|
|
|
470
731
|
@tool_deferrals.clear
|
|
471
732
|
end
|
|
472
733
|
tools.flatten.compact.each do |tool|
|
|
734
|
+
tool = tool.to_tool if tool.respond_to?(:to_tool)
|
|
473
735
|
tool = tool.new if tool.is_a?(Class)
|
|
474
|
-
name = tool.
|
|
736
|
+
name = tool.qualified_name.to_sym
|
|
737
|
+
existing = @tools[name]
|
|
738
|
+
if existing && [existing.namespace, existing.name.to_s] != [tool.namespace, tool.name.to_s]
|
|
739
|
+
raise ArgumentError, "Two tools are named #{name}. Rename one with `tool :#{name}, as:`"
|
|
740
|
+
end
|
|
741
|
+
|
|
475
742
|
@tools[name] = tool
|
|
476
|
-
@tool_deferrals[name] = defer.nil? ? tool.
|
|
743
|
+
@tool_deferrals[name] = defer.nil? ? tool.deferred? : defer
|
|
477
744
|
end
|
|
478
745
|
self
|
|
479
746
|
end
|
|
@@ -483,13 +750,16 @@ module RubyLLM
|
|
|
483
750
|
# MCP servers connected with #with_mcp. MCP tools that only the UI of
|
|
484
751
|
# an MCP App may call are left out; see MCP::Tool#visibility.
|
|
485
752
|
#
|
|
486
|
-
#
|
|
753
|
+
# A namespaced tool's key joins its namespace and name, as in
|
|
754
|
+
# <tt>:crm_customer_lookup</tt>. Raises ArgumentError when two tools
|
|
755
|
+
# share a key.
|
|
487
756
|
def tools
|
|
488
757
|
offered = @tools.reject { |_, tool| hidden_from_model?(tool) }
|
|
489
|
-
|
|
758
|
+
built_in = [@code_execution_tool, (@skill_loader if skills.any?), *@file_tools, tool_search_tool]
|
|
759
|
+
[*built_in, *mcp.reachable_tools].compact.each_with_object(offered) do |tool, tools|
|
|
490
760
|
next if hidden_from_model?(tool)
|
|
491
761
|
|
|
492
|
-
name = tool.
|
|
762
|
+
name = tool.qualified_name.to_sym
|
|
493
763
|
raise ArgumentError, "Two tools are named #{name}. Rename one with `tool :#{name}, as:`" if tools.key?(name)
|
|
494
764
|
|
|
495
765
|
tools[name] = tool
|
|
@@ -511,6 +781,10 @@ module RubyLLM
|
|
|
511
781
|
# model their tools. The servers are contacted when the chat first
|
|
512
782
|
# needs their tools. Pass +nil+ to disconnect them all. Returns +self+.
|
|
513
783
|
#
|
|
784
|
+
# The chat closes the servers it built from a class when it disconnects
|
|
785
|
+
# them, or when another server takes their name. Instances you pass in
|
|
786
|
+
# stay open: close them with MCP#close.
|
|
787
|
+
#
|
|
514
788
|
# chat.with_mcp(Linear.new(user: current_user), Files)
|
|
515
789
|
# chat.mcp.linear
|
|
516
790
|
#
|
|
@@ -523,12 +797,12 @@ module RubyLLM
|
|
|
523
797
|
#
|
|
524
798
|
def with_mcp(*servers, defer: nil)
|
|
525
799
|
if servers == [nil]
|
|
800
|
+
@mcp.disconnect(self)
|
|
526
801
|
@mcp = MCP::Collection.new
|
|
527
802
|
@mcp_deferrals.clear
|
|
528
803
|
else
|
|
529
804
|
servers.flatten.compact.each do |server|
|
|
530
|
-
server = server
|
|
531
|
-
@mcp << server
|
|
805
|
+
server = @mcp.connect(server, self)
|
|
532
806
|
@mcp_deferrals[server.name.to_sym] = defer
|
|
533
807
|
end
|
|
534
808
|
end
|
|
@@ -540,13 +814,19 @@ module RubyLLM
|
|
|
540
814
|
# keywords whose options use the provider's own vocabulary, and raw
|
|
541
815
|
# Hashes passed to the provider verbatim, so provider tools RubyLLM has
|
|
542
816
|
# no alias for yet work without a gem update. Entries add to any tools
|
|
543
|
-
# enabled earlier
|
|
817
|
+
# enabled earlier. Enabling an alias again replaces its options, and an
|
|
818
|
+
# identical raw Hash or MCP server is not repeated, so a chat sends
|
|
819
|
+
# each tool once. Pass +nil+ to clear them all. Returns +self+.
|
|
544
820
|
#
|
|
545
821
|
# chat.with_provider_tools(:web_search)
|
|
546
822
|
# chat.with_provider_tools(:web_search, :code_execution)
|
|
547
823
|
# chat.with_provider_tools(web_search: { allowed_domains: ["ruby-lang.org"] })
|
|
548
824
|
# chat.with_provider_tools({ type: "web_search_20260318", name: "web_search" })
|
|
549
825
|
#
|
|
826
|
+
# Raw client-toolset declarations also use this method. Their member
|
|
827
|
+
# calls run through application tools registered with #with_tools and
|
|
828
|
+
# Tool.namespace, and appear in Message#tool_calls.
|
|
829
|
+
#
|
|
550
830
|
# The tool steps the model ran come back on
|
|
551
831
|
# Message#server_tool_calls, citations from search tools on
|
|
552
832
|
# Message#citations, and per-use billing counters on
|
|
@@ -560,30 +840,43 @@ module RubyLLM
|
|
|
560
840
|
return self
|
|
561
841
|
end
|
|
562
842
|
|
|
563
|
-
|
|
843
|
+
additions = RubyLLM::Tools::ProviderTools.normalize(tools, tools_with_options)
|
|
844
|
+
@provider_tools = RubyLLM::Tools::ProviderTools.merge(@provider_tools, additions)
|
|
564
845
|
self
|
|
565
846
|
end
|
|
566
847
|
|
|
567
848
|
# Configures how the model uses the registered tools. +choice:+
|
|
568
849
|
# constrains tool use to +:auto+, +:none+, +:required+, a tool name, or
|
|
569
850
|
# a Tool class. +calls:+ limits how many tool calls one response may
|
|
570
|
-
# contain
|
|
851
|
+
# contain: +:one+ (or +1+) and +:many+ ask the provider, and a larger
|
|
852
|
+
# Integer runs at most that many of a response's calls to the chat's
|
|
853
|
+
# tools, in the response's order. Each call past it gets an error
|
|
854
|
+
# result straight away, without running or asking for approval, and
|
|
855
|
+
# emits one +tool_calls_capped.ruby_llm+ event per response. It is off
|
|
856
|
+
# by default. +concurrency:+ runs tool calls
|
|
571
857
|
# concurrently: +true+ or +:threads+ for threads, +:fibers+ for fibers.
|
|
572
|
-
#
|
|
573
|
-
#
|
|
574
|
-
#
|
|
858
|
+
# +rounds:+ limits how many model responses that ask for tools one
|
|
859
|
+
# #complete may run, however many calls each holds. It is off by
|
|
860
|
+
# default. Once the last round's results are saved, #complete raises
|
|
861
|
+
# ToolRoundLimitError instead of asking the model again, and another
|
|
862
|
+
# #complete continues with a fresh count, as does a pause for a person.
|
|
863
|
+
# #step is not limited. An omitted option is left unchanged; passing
|
|
864
|
+
# +nil+ explicitly resets that option (+concurrency: nil+ returns to the
|
|
865
|
+
# configured default, +rounds: nil+ removes the limit). Returns +self+.
|
|
575
866
|
#
|
|
576
867
|
# chat.with_tools(Weather, Search).with_tool_options(choice: :required)
|
|
577
868
|
# chat.with_tool_options(calls: :one, concurrency: :threads)
|
|
869
|
+
# chat.with_tool_options(rounds: 25, calls: 50)
|
|
578
870
|
# chat.with_tool_options(choice: nil)
|
|
579
871
|
#
|
|
580
872
|
def with_tool_options(**options)
|
|
581
873
|
options.each do |option, value|
|
|
582
874
|
case option
|
|
583
875
|
when :choice then apply_tool_choice(value)
|
|
584
|
-
when :calls then
|
|
585
|
-
when :concurrency then
|
|
586
|
-
|
|
876
|
+
when :calls then apply_tool_calls(value)
|
|
877
|
+
when :concurrency then apply_tool_concurrency(value)
|
|
878
|
+
when :rounds then @tool_rounds = normalize_rounds(value)
|
|
879
|
+
else raise ArgumentError, "Unknown tool option: #{option}. Valid options are: #{TOOL_OPTIONS.join(', ')}"
|
|
587
880
|
end
|
|
588
881
|
end
|
|
589
882
|
self
|
|
@@ -604,7 +897,7 @@ module RubyLLM
|
|
|
604
897
|
# +assume_model_exists:+ is false.
|
|
605
898
|
#
|
|
606
899
|
# chat.with_model('claude-sonnet-5')
|
|
607
|
-
# chat.with_model('gpt-
|
|
900
|
+
# chat.with_model('gpt-6.1-sol', protocol: :chat_completions)
|
|
608
901
|
#
|
|
609
902
|
def with_model(model_id, provider: nil, protocol: nil, assume_model_exists: false)
|
|
610
903
|
model_id ||= @config.default_model
|
|
@@ -615,17 +908,43 @@ module RubyLLM
|
|
|
615
908
|
end
|
|
616
909
|
|
|
617
910
|
# Sets fallback models to try, in order, when generation fails. +on:+
|
|
618
|
-
# selects the error classes that trigger a fallback; the default
|
|
619
|
-
# transient provider and network errors.
|
|
620
|
-
#
|
|
911
|
+
# selects the error classes that trigger a fallback; the default,
|
|
912
|
+
# Fallback::DEFAULT_ERRORS, covers transient provider and network errors.
|
|
913
|
+
# Keep it unless you have a reason: providers signal overload as HTTP 529
|
|
914
|
+
# (OverloadedError) or 503 (ServiceUnavailableError), so a list narrowed
|
|
915
|
+
# by name misses some, and an +on:+ that adds an error should splat the
|
|
916
|
+
# default list into it. Cancelling the chat never triggers a fallback,
|
|
917
|
+
# and neither does another process taking over a persisted chat or an
|
|
918
|
+
# error your streaming block raises. Pass +nil+ to remove all fallbacks
|
|
919
|
+
# and restore the default error classes. Returns +self+.
|
|
920
|
+
#
|
|
921
|
+
# While a fallback is left, a timeout, a failed connection, or a retry
|
|
922
|
+
# wait longer than two seconds moves on to it at once instead of
|
|
923
|
+
# retrying the same model. A fallback that took over answers the rest
|
|
924
|
+
# of that #complete, including its tool rounds; the next one starts on
|
|
925
|
+
# the chat's own model.
|
|
621
926
|
#
|
|
622
927
|
# chat.with_fallbacks("gpt-4.1-mini", "claude-haiku-4-5")
|
|
623
928
|
# chat.with_fallbacks(nil)
|
|
624
929
|
#
|
|
625
|
-
|
|
930
|
+
# With <tt>drop_unsupported: true</tt>, when a model rejects a parameter
|
|
931
|
+
# with UnsupportedParameterError, the chat retries that model without
|
|
932
|
+
# it: the temperature, thinking, the output cap, citations, or a key of
|
|
933
|
+
# #with_provider_options. A model that rejects another parameter is
|
|
934
|
+
# retried without that one too, and each is dropped at most once. The
|
|
935
|
+
# next model starts again from the request as written. The chat keeps
|
|
936
|
+
# its settings for later requests. #before_fallback and
|
|
937
|
+
# #after_fallback receive each retry as a Fallback from the model to
|
|
938
|
+
# itself, whose Fallback#dropped_parameter names the parameter. Without
|
|
939
|
+
# the option, nothing is ever dropped.
|
|
940
|
+
#
|
|
941
|
+
# chat.with_temperature(0.2).with_fallbacks(drop_unsupported: true)
|
|
942
|
+
#
|
|
943
|
+
def with_fallbacks(*models, on: Fallback::DEFAULT_ERRORS, drop_unsupported: false)
|
|
626
944
|
fallback_models = models.flatten.compact
|
|
627
945
|
@fallbacks = fallback_models.map { |model| Fallback.build(model) }
|
|
628
946
|
@fallback_errors = fallback_models.empty? ? Fallback::DEFAULT_ERRORS : Array(on).flatten.compact
|
|
947
|
+
@drop_unsupported = drop_unsupported
|
|
629
948
|
self
|
|
630
949
|
end
|
|
631
950
|
|
|
@@ -687,9 +1006,12 @@ module RubyLLM
|
|
|
687
1006
|
end
|
|
688
1007
|
|
|
689
1008
|
# Returns the thinking options resolved for the current model, or +nil+
|
|
690
|
-
# when thinking was not configured or needs no provider control.
|
|
1009
|
+
# when thinking was not configured or needs no provider control. When
|
|
1010
|
+
# the model registry has no thinking controls for the model, returns
|
|
1011
|
+
# the request itself, <tt>{ enabled: true }</tt> or
|
|
1012
|
+
# <tt>{ enabled: false }</tt>; the request then raises ArgumentError.
|
|
691
1013
|
def thinking
|
|
692
|
-
config =
|
|
1014
|
+
config = @thinking&.resolve(@model, strict: false)
|
|
693
1015
|
return unless config
|
|
694
1016
|
|
|
695
1017
|
{
|
|
@@ -716,23 +1038,25 @@ module RubyLLM
|
|
|
716
1038
|
end
|
|
717
1039
|
|
|
718
1040
|
# Enables provider prompt caching. With no arguments the provider's
|
|
719
|
-
# default behavior applies; options
|
|
720
|
-
#
|
|
721
|
-
# RubyLLM.cache to attach an explicit
|
|
722
|
-
#
|
|
1041
|
+
# default behavior applies; options apply where supported. +ttl:+ is
|
|
1042
|
+
# a lifetime as a provider String, seconds, or a Duration. Pass a
|
|
1043
|
+
# CachedContent from RubyLLM.cache to attach an explicit content cache,
|
|
1044
|
+
# or +id:+ with its name. Pass +false+ to stop RubyLLM from sending cache
|
|
723
1045
|
# controls or rendering explicit cache boundaries. A provider may still
|
|
724
1046
|
# cache prompts implicitly. Passing +nil+ raises ArgumentError.
|
|
725
1047
|
# Returns +self+.
|
|
726
1048
|
#
|
|
727
1049
|
# chat.with_caching
|
|
728
1050
|
# chat.with_caching(ttl: "1h")
|
|
729
|
-
# chat.with_caching(
|
|
1051
|
+
# chat.with_caching(ttl: 1.hour)
|
|
1052
|
+
# chat.with_caching(cache)
|
|
730
1053
|
# chat.with_caching(false)
|
|
731
1054
|
#
|
|
732
1055
|
def with_caching(options = {})
|
|
733
1056
|
options = {} if options == true
|
|
1057
|
+
options = { id: options } if options.is_a?(CachedContent)
|
|
734
1058
|
unless options == false || options.is_a?(Hash)
|
|
735
|
-
raise ArgumentError, 'with_caching accepts true, false, or caching options'
|
|
1059
|
+
raise ArgumentError, 'with_caching accepts true, false, a CachedContent, or caching options'
|
|
736
1060
|
end
|
|
737
1061
|
|
|
738
1062
|
@caching = options == false ? false : options.transform_keys(&:to_sym).freeze
|
|
@@ -773,6 +1097,203 @@ module RubyLLM
|
|
|
773
1097
|
self
|
|
774
1098
|
end
|
|
775
1099
|
|
|
1100
|
+
# Keeps tool results within shares of the model's context window, from
|
|
1101
|
+
# the model registry, in place of Configuration#context_budget. Pass
|
|
1102
|
+
# +nil+ to remove the budget. Returns +self+.
|
|
1103
|
+
#
|
|
1104
|
+
# +per_result+:: a tool result longer than this share is cut when it
|
|
1105
|
+
# is added, ending with a note that tells the model to
|
|
1106
|
+
# ask for less.
|
|
1107
|
+
# +per_request+:: when a request would take more than this share, the
|
|
1108
|
+
# oldest tool results are left out of what is sent,
|
|
1109
|
+
# each replaced by a one-line note. The transcript
|
|
1110
|
+
# keeps them. The results of the latest round go out
|
|
1111
|
+
# whenever they fit. The cut point moves in steps, so
|
|
1112
|
+
# the request prefix, and the provider's prompt cache,
|
|
1113
|
+
# hold for many rounds.
|
|
1114
|
+
#
|
|
1115
|
+
# +window+:: the context window in tokens, for a model the registry
|
|
1116
|
+
# has no window for. It wins over the registry's.
|
|
1117
|
+
#
|
|
1118
|
+
# chat.with_context_budget(per_result: 0.25, per_request: 0.7)
|
|
1119
|
+
# chat.with_context_budget(window: 128_000, per_request: 0.7)
|
|
1120
|
+
#
|
|
1121
|
+
# Shares are above 0 and at most 1. Sizes are estimated from
|
|
1122
|
+
# characters, at two a token. A result a file store already saved as
|
|
1123
|
+
# a file (see #with_file_store) is short enough to keep. Without a
|
|
1124
|
+
# known window the budget does nothing, and the chat logs a warning
|
|
1125
|
+
# once.
|
|
1126
|
+
def with_context_budget(budget = {}, **shares)
|
|
1127
|
+
@context_budget = ContextBudget.normalize(budget, **shares)
|
|
1128
|
+
@context_budget_chosen = true
|
|
1129
|
+
@context_budget_warned = false
|
|
1130
|
+
self
|
|
1131
|
+
end
|
|
1132
|
+
|
|
1133
|
+
# Lets the model run code in a Sandbox. The model gets one tool,
|
|
1134
|
+
# +run_code+, that runs Ruby, Python, JavaScript, or a shell script in a fresh run
|
|
1135
|
+
# directory, with read-only copies of the conversation's files, and
|
|
1136
|
+
# returns the output and every file the code writes there as
|
|
1137
|
+
# attachments on the tool result. With #with_file_store, runs work with
|
|
1138
|
+
# the chat's files instead: with FileStore::Directory, in the store's
|
|
1139
|
+
# folder, where attachments are at their own paths. With other stores,
|
|
1140
|
+
# runs still have read-only copies of the conversation's files
|
|
1141
|
+
# in +attachments/+, copy in the other files the model names, and what
|
|
1142
|
+
# the code writes is saved back. The options are:
|
|
1143
|
+
#
|
|
1144
|
+
# +sandbox+:: the sandbox every call runs in. Default:
|
|
1145
|
+
# Configuration#sandbox.
|
|
1146
|
+
# +escalate_to+:: sandboxes the model may ask for, one call at a time,
|
|
1147
|
+
# as an Array named after their classes
|
|
1148
|
+
# (WorkspaceSandbox is +workspace+) or a Hash of names
|
|
1149
|
+
# to sandboxes. Each call that asks waits for #approve.
|
|
1150
|
+
# +languages+:: the languages the model may use, from +:ruby+,
|
|
1151
|
+
# +:python+, +:javascript+, and +:shell+. Default: Ruby
|
|
1152
|
+
# and shell, plus Python and JavaScript when their
|
|
1153
|
+
# packages are declared.
|
|
1154
|
+
# +gems+:: gems installed once and available to every Ruby run.
|
|
1155
|
+
# +python+:: Python packages installed once and available to every
|
|
1156
|
+
# Python run.
|
|
1157
|
+
# +npm+:: npm packages installed once, without their install scripts,
|
|
1158
|
+
# and available to every JavaScript run.
|
|
1159
|
+
# +gem_home+:: a GEM_HOME with gems already installed, used instead
|
|
1160
|
+
# of +gems+.
|
|
1161
|
+
# +virtualenv+:: a Python virtualenv with packages already installed,
|
|
1162
|
+
# used instead of +python+.
|
|
1163
|
+
# +node_modules+:: a +node_modules+ directory with packages already
|
|
1164
|
+
# installed, used instead of +npm+.
|
|
1165
|
+
# +mounts+:: directories mounted read-only in each run directory, keyed
|
|
1166
|
+
# by their path there, or a Proc called before each run
|
|
1167
|
+
# that returns them.
|
|
1168
|
+
#
|
|
1169
|
+
# Accepts keywords or an options Hash. Pass +false+ to disable it.
|
|
1170
|
+
# Passing +nil+ raises ArgumentError. Returns +self+.
|
|
1171
|
+
#
|
|
1172
|
+
# chat.with_code_execution
|
|
1173
|
+
# chat.with_code_execution(gems: %w[prawn], python: %w[pandas matplotlib])
|
|
1174
|
+
# chat.with_code_execution(sandbox: ReadOnlySandbox, escalate_to: [WorkspaceSandbox, OnlineSandbox])
|
|
1175
|
+
# chat.with_code_execution(mounts: { "templates" => "app/templates/reports" })
|
|
1176
|
+
# chat.with_code_execution(false)
|
|
1177
|
+
#
|
|
1178
|
+
# Raises ConfigurationError when no sandbox is configured. Code never
|
|
1179
|
+
# runs outside a sandbox. To run code on the provider's servers
|
|
1180
|
+
# instead, use <tt>with_provider_tools(:code_execution)</tt>.
|
|
1181
|
+
def with_code_execution(enabled = true, **options)
|
|
1182
|
+
options = CodeExecution.options(enabled, options)
|
|
1183
|
+
@code_execution_tool = if options
|
|
1184
|
+
CodeExecution.new(
|
|
1185
|
+
sandbox: options[:sandbox],
|
|
1186
|
+
attachments: -> { messages.flat_map(&:attachments) },
|
|
1187
|
+
file_store: -> { file_store },
|
|
1188
|
+
attached_files: -> { @file_references&.attached_files(messages).to_a },
|
|
1189
|
+
written: ->(file) { run_callbacks(:after_file_write, file) },
|
|
1190
|
+
skills: -> { skills.to_h { |skill| [Skill::Loader.mount_path(skill), skill.path] } },
|
|
1191
|
+
chat: self,
|
|
1192
|
+
config: -> { @config },
|
|
1193
|
+
package_cache_dir: @config.package_cache_dir,
|
|
1194
|
+
approval: ->(tool_call) { escalation_approved?(tool_call) },
|
|
1195
|
+
**options.except(:sandbox)
|
|
1196
|
+
)
|
|
1197
|
+
end
|
|
1198
|
+
@code_execution = options
|
|
1199
|
+
self
|
|
1200
|
+
end
|
|
1201
|
+
|
|
1202
|
+
# Gives the model skills: folders of instructions, scripts, and files
|
|
1203
|
+
# in the open Agent Skills format. Called bare or with +true+, adds
|
|
1204
|
+
# every skill directly under Skill.roots, +app/skills+ by default.
|
|
1205
|
+
# Symbols name folders under the roots, and Strings and Pathnames are
|
|
1206
|
+
# paths to skill folders. Pass +false+ to remove every skill. Passing
|
|
1207
|
+
# +nil+ raises ArgumentError. Returns +self+.
|
|
1208
|
+
#
|
|
1209
|
+
# chat.with_skills
|
|
1210
|
+
# chat.with_skills(:invoices, :reports)
|
|
1211
|
+
# chat.with_skills(:invoices, "vendor/skills/pdf")
|
|
1212
|
+
# chat.with_skills(false)
|
|
1213
|
+
#
|
|
1214
|
+
# Every request lists each skill's name and description, and the model
|
|
1215
|
+
# loads a skill's instructions and files with its +load_skill+ tool.
|
|
1216
|
+
# With #with_code_execution, each skill folder is mounted read-only in
|
|
1217
|
+
# every run at <tt>skills/<name>/</tt>, so the model can run the
|
|
1218
|
+
# skill's scripts.
|
|
1219
|
+
#
|
|
1220
|
+
# Raises SkillNotFoundError for a missing skill, InvalidSkillError for
|
|
1221
|
+
# a +SKILL.md+ that breaks the specification, and ArgumentError when
|
|
1222
|
+
# two skills share a name.
|
|
1223
|
+
def with_skills(*skills)
|
|
1224
|
+
selection = Skill.selection(skills)
|
|
1225
|
+
@skills = selection == false ? [] : Skill.merge(@skills, Skill.resolve(selection)).freeze
|
|
1226
|
+
self
|
|
1227
|
+
end
|
|
1228
|
+
|
|
1229
|
+
# Attaches +store+ to the chat and gives the model tools to work
|
|
1230
|
+
# with it: +list_files+, +read_file+, and +search_files+ to find and
|
|
1231
|
+
# read files, and +write_file+ and +edit_file+ to change them. Files
|
|
1232
|
+
# stop filling the conversation:
|
|
1233
|
+
#
|
|
1234
|
+
# * Every attachment is kept in the store. The model sees the files
|
|
1235
|
+
# attached to the latest question, and those it opens with
|
|
1236
|
+
# +read_file+, in full until the next question; after that, and for
|
|
1237
|
+
# files other tools return, it sees one line naming the file.
|
|
1238
|
+
# * A tool result longer than +inline_limit+ characters is saved under
|
|
1239
|
+
# +results/+, and the model gets its start and the file's path.
|
|
1240
|
+
# * +write_file+ and +edit_file+ change only a file the model read, as
|
|
1241
|
+
# it is now, so the model never writes over a change it hasn't seen.
|
|
1242
|
+
# * With #with_code_execution, code runs in the store's folder when it
|
|
1243
|
+
# has one, such as FileStore::Directory, changing the files in place.
|
|
1244
|
+
# With other stores, each run has read-only copies of the attachments
|
|
1245
|
+
# in +attachments/+, copies in the files the model names to change or
|
|
1246
|
+
# read, and what the code writes is saved back to the store.
|
|
1247
|
+
#
|
|
1248
|
+
# +store+ is a folder path, for a FileStore::Directory, +:memory+, for a
|
|
1249
|
+
# new FileStore::Memory, or a FileStore. Without it, the chat gets a new
|
|
1250
|
+
# FileStore::Memory, or for a persisted chat, its files in Active Storage.
|
|
1251
|
+
#
|
|
1252
|
+
# +inline_limit+ is the characters a tool result may have and still go
|
|
1253
|
+
# to the model whole, or +false+ to send every result whole; tools can
|
|
1254
|
+
# set their own with Tool.inline_limit. Default: 10,000.
|
|
1255
|
+
#
|
|
1256
|
+
# +tools+ names the tools the model gets: +:read+ for +list_files+,
|
|
1257
|
+
# +read_file+, and +search_files+, and +:write+, +:edit+, and
|
|
1258
|
+
# +:delete+ for +write_file+, +edit_file+, and +delete_file+. Default:
|
|
1259
|
+
# <tt>%i[read write edit]</tt>. Raises ArgumentError without +:read+,
|
|
1260
|
+
# since older attachments and long results reach the model through it.
|
|
1261
|
+
#
|
|
1262
|
+
# Pass +nil+ to remove the store and its tools. Returns +self+.
|
|
1263
|
+
#
|
|
1264
|
+
# chat.with_file_store
|
|
1265
|
+
# chat.with_file_store("tmp/chats/42")
|
|
1266
|
+
# chat.with_file_store(:memory)
|
|
1267
|
+
# chat.with_file_store(RubyLLM::FileStore::Directory.new("tmp/chats/42"))
|
|
1268
|
+
# chat.with_file_store(inline_limit: 20_000)
|
|
1269
|
+
# chat.with_file_store(tools: :read)
|
|
1270
|
+
# chat.with_file_store(tools: %i[read write edit delete])
|
|
1271
|
+
# chat.with_file_store(nil)
|
|
1272
|
+
#
|
|
1273
|
+
# Text files are read as text; register converters, such as the OCR
|
|
1274
|
+
# converter for PDFs and images, in Configuration#file_converters to
|
|
1275
|
+
# read more.
|
|
1276
|
+
def with_file_store(store = :memory, inline_limit: FileReferences::INLINE_LIMIT, tools: FileStore::Tools::DEFAULT)
|
|
1277
|
+
FileReferences.validate(store, inline_limit:, tools:) unless store.nil?
|
|
1278
|
+
store = FileReferences.resolve(store)
|
|
1279
|
+
@file_references&.forget(@attachment_replacements)
|
|
1280
|
+
@file_references = if store
|
|
1281
|
+
FileReferences.new(store:, inline_limit:, tools:, config: -> { @config },
|
|
1282
|
+
written: ->(file) { run_callbacks(:after_file_write, file) })
|
|
1283
|
+
end
|
|
1284
|
+
@file_tools = store ? build_file_tools : []
|
|
1285
|
+
self
|
|
1286
|
+
end
|
|
1287
|
+
|
|
1288
|
+
# Returns the FileStore attached with #with_file_store, or +nil+
|
|
1289
|
+
# without one.
|
|
1290
|
+
#
|
|
1291
|
+
# chat.file_store.list
|
|
1292
|
+
# chat.file_store.read("notes/plan.md")
|
|
1293
|
+
def file_store
|
|
1294
|
+
@file_references&.store
|
|
1295
|
+
end
|
|
1296
|
+
|
|
776
1297
|
# Identifies the end user behind the conversation for the provider's
|
|
777
1298
|
# abuse monitoring. Providers without an equivalent field omit it.
|
|
778
1299
|
# Pass +nil+ to remove it.
|
|
@@ -787,13 +1308,33 @@ module RubyLLM
|
|
|
787
1308
|
self
|
|
788
1309
|
end
|
|
789
1310
|
|
|
1311
|
+
# Attributes the usage of every attempt the chat makes to +owner+, such
|
|
1312
|
+
# as a user or an account record: each request, the tools it runs, the
|
|
1313
|
+
# file converters it triggers, and compaction. In Rails, the usage
|
|
1314
|
+
# ledger stores the owner with each row; everywhere, the
|
|
1315
|
+
# +usage.ruby_llm+ event carries it. It wins over RubyLLM.with_owner,
|
|
1316
|
+
# and over the owner a persisted chat's record names. Pass +nil+ to
|
|
1317
|
+
# remove it. Returns +self+.
|
|
1318
|
+
#
|
|
1319
|
+
# chat.with_owner(current_user).ask "Summarize this thread"
|
|
1320
|
+
#
|
|
1321
|
+
# RubyLLM never sends the owner to the provider; see #with_end_user
|
|
1322
|
+
# for the identifier providers receive.
|
|
1323
|
+
def with_owner(owner)
|
|
1324
|
+
@owner = owner
|
|
1325
|
+
self
|
|
1326
|
+
end
|
|
1327
|
+
|
|
790
1328
|
# Rebinds the chat to +context+, a Context built with RubyLLM.context,
|
|
791
1329
|
# so subsequent requests use its configuration. Pass +nil+ to return to
|
|
792
1330
|
# the global RubyLLM.config. Returns +self+.
|
|
793
1331
|
def with_context(context)
|
|
794
1332
|
@context = context
|
|
795
1333
|
@config = context&.config || RubyLLM.config
|
|
1334
|
+
@file_references&.forget(@attachment_replacements)
|
|
796
1335
|
with_model(@model.id, provider: @provider.slug, protocol: @protocol, assume_model_exists: true)
|
|
1336
|
+
apply_tool_concurrency(nil) unless @concurrency_chosen
|
|
1337
|
+
@context_budget = @config.context_budget unless @context_budget_chosen
|
|
797
1338
|
self
|
|
798
1339
|
end
|
|
799
1340
|
|
|
@@ -809,7 +1350,9 @@ module RubyLLM
|
|
|
809
1350
|
end
|
|
810
1351
|
|
|
811
1352
|
# Sets extra HTTP headers sent with completion requests, replacing any
|
|
812
|
-
# previously set headers; +nil+ clears them. Returns +self+.
|
|
1353
|
+
# previously set headers; +nil+ clears them. Returns +self+. The
|
|
1354
|
+
# provider's own headers, such as authentication and API version
|
|
1355
|
+
# headers, win over a header of the same name set here.
|
|
813
1356
|
#
|
|
814
1357
|
# chat.with_headers('anthropic-beta' => 'fine-grained-tool-streaming-2025-05-14')
|
|
815
1358
|
#
|
|
@@ -850,8 +1393,9 @@ module RubyLLM
|
|
|
850
1393
|
add_callback(:before_message, &)
|
|
851
1394
|
end
|
|
852
1395
|
|
|
853
|
-
# Registers a callback that receives each assistant response
|
|
854
|
-
# tool result message
|
|
1396
|
+
# Registers a callback that receives each assistant response, each
|
|
1397
|
+
# tool result message, and each user message a queued message becomes,
|
|
1398
|
+
# once it has been appended. Returns +self+.
|
|
855
1399
|
#
|
|
856
1400
|
# chat.after_message { |message| puts message.content }
|
|
857
1401
|
#
|
|
@@ -859,6 +1403,36 @@ module RubyLLM
|
|
|
859
1403
|
add_callback(:after_message, &)
|
|
860
1404
|
end
|
|
861
1405
|
|
|
1406
|
+
# Registers a callback that wraps the moment each queued message joins
|
|
1407
|
+
# the conversation. It receives the QueuedMessage and +join+, and runs
|
|
1408
|
+
# in the loop's thread. <tt>join.call</tt> adds the user Message and
|
|
1409
|
+
# returns it. Returns +self+.
|
|
1410
|
+
#
|
|
1411
|
+
# chat.around_join do |queued, join|
|
|
1412
|
+
# message = join.call
|
|
1413
|
+
# audit_log << [queued.sender, message.content]
|
|
1414
|
+
# end
|
|
1415
|
+
#
|
|
1416
|
+
# A block that never calls +join+ withdraws the message: it leaves the
|
|
1417
|
+
# queue without joining, and the turn goes on. A block that raises
|
|
1418
|
+
# leaves the message queued and out of the conversation. Several
|
|
1419
|
+
# blocks nest in the order they were registered, the first outermost,
|
|
1420
|
+
# and #after_message runs once they all return.
|
|
1421
|
+
# When an inner block withdraws the message, <tt>join.call</tt> in an
|
|
1422
|
+
# outer block returns +nil+.
|
|
1423
|
+
#
|
|
1424
|
+
# On a persisted chat, the block runs inside the transaction that
|
|
1425
|
+
# creates the message record and deletes the queued one, and
|
|
1426
|
+
# <tt>join.call</tt> takes attributes for the new record, such as
|
|
1427
|
+
# columns of your own. See RubyLLM::ActiveRecord::ChatMethods. A plain
|
|
1428
|
+
# chat has no such columns, so its +join+ raises ArgumentError when
|
|
1429
|
+
# given attributes. Registering the same block again does nothing.
|
|
1430
|
+
def around_join(&block)
|
|
1431
|
+
return self if @callbacks[:around_join].include?(block)
|
|
1432
|
+
|
|
1433
|
+
add_callback(:around_join, &block)
|
|
1434
|
+
end
|
|
1435
|
+
|
|
862
1436
|
# Registers a callback that receives each local ToolCall before the tool
|
|
863
1437
|
# executes. Returns +self+.
|
|
864
1438
|
#
|
|
@@ -868,6 +1442,23 @@ module RubyLLM
|
|
|
868
1442
|
add_callback(:before_tool_call, &)
|
|
869
1443
|
end
|
|
870
1444
|
|
|
1445
|
+
# Registers a callback that wraps each local tool's execution. It
|
|
1446
|
+
# receives the ToolCall and a block, +run+, that runs the tool and
|
|
1447
|
+
# returns its result. Returns +self+.
|
|
1448
|
+
#
|
|
1449
|
+
# chat.around_tool_call { |tool_call, &run| ActsAsTenant.with_tenant(account, &run) }
|
|
1450
|
+
#
|
|
1451
|
+
# The block runs in the thread or fiber that runs the tool, so
|
|
1452
|
+
# fiber-local state, +Current+ attributes, and tenants it sets reach the
|
|
1453
|
+
# tool, also with concurrent tool execution. It runs after
|
|
1454
|
+
# #before_tool_call and before #after_tool_result. Several blocks nest
|
|
1455
|
+
# in the order they were registered, the first outermost. The result is
|
|
1456
|
+
# the tool's, whatever the block returns. A block that never calls
|
|
1457
|
+
# +run+ skips the tool, and the model is told the call did not run.
|
|
1458
|
+
def around_tool_call(&)
|
|
1459
|
+
add_callback(:around_tool_call, &)
|
|
1460
|
+
end
|
|
1461
|
+
|
|
871
1462
|
# Registers a callback that receives each local tool's result after
|
|
872
1463
|
# execution. Returns +self+.
|
|
873
1464
|
def after_tool_result(&)
|
|
@@ -891,9 +1482,16 @@ module RubyLLM
|
|
|
891
1482
|
add_callback(:after_tool_progress, &)
|
|
892
1483
|
end
|
|
893
1484
|
|
|
1485
|
+
# Registers a callback that receives each StoredFile the conversation
|
|
1486
|
+
# writes to the chat's FileStore (see #with_file_store): attachments as they
|
|
1487
|
+
# are kept, long tool results, and the files tools and code write.
|
|
1488
|
+
def after_file_write(&)
|
|
1489
|
+
add_callback(:after_file_write, &)
|
|
1490
|
+
end
|
|
1491
|
+
|
|
894
1492
|
# Registers a callback that receives the Fallback attempt after the
|
|
895
|
-
# current model fails and before the
|
|
896
|
-
# +self+.
|
|
1493
|
+
# current model fails and before the next model is tried, or the same
|
|
1494
|
+
# model again without a parameter it rejected. Returns +self+.
|
|
897
1495
|
def before_fallback(&)
|
|
898
1496
|
add_callback(:before_fallback, &)
|
|
899
1497
|
end
|
|
@@ -930,10 +1528,17 @@ module RubyLLM
|
|
|
930
1528
|
add_callback(:unsupported_attachment, &)
|
|
931
1529
|
end
|
|
932
1530
|
|
|
933
|
-
# Yields each Message in the
|
|
934
|
-
#
|
|
935
|
-
# methods are
|
|
1531
|
+
# Deprecated: iterate #messages instead. Yields each Message in the
|
|
1532
|
+
# conversation, or returns an Enumerator without a block. The
|
|
1533
|
+
# Enumerable methods built on it, such as +map+ and +count+, are
|
|
1534
|
+
# deprecated with it. Warns through RubyLLM.deprecator. RubyLLM 3.0
|
|
1535
|
+
# removes them.
|
|
1536
|
+
#
|
|
1537
|
+
# chat.messages.each { |message| puts message.content }
|
|
1538
|
+
#
|
|
936
1539
|
def each(&)
|
|
1540
|
+
RubyLLM.deprecator.deprecate("Enumerable on #{self.class}", replacement: "#{self.class}#messages",
|
|
1541
|
+
removal: '3.0')
|
|
937
1542
|
messages.each(&)
|
|
938
1543
|
end
|
|
939
1544
|
|
|
@@ -977,7 +1582,7 @@ module RubyLLM
|
|
|
977
1582
|
thinking: resolved_thinking,
|
|
978
1583
|
schema: @schema,
|
|
979
1584
|
citations: @citations,
|
|
980
|
-
caching:
|
|
1585
|
+
caching: request_caching,
|
|
981
1586
|
protocol: @protocol
|
|
982
1587
|
)
|
|
983
1588
|
end
|
|
@@ -1003,10 +1608,13 @@ module RubyLLM
|
|
|
1003
1608
|
RubyLLM.instrument('compaction.ruby_llm', payload, config: @config) do |event|
|
|
1004
1609
|
result = provider_compaction
|
|
1005
1610
|
record_out_of_band_usage(result) if usage_entries.length == usage_start
|
|
1006
|
-
record_generated_message(result, usage_start)
|
|
1611
|
+
record_generated_message(result, usage_start, keep_unfinished: true)
|
|
1007
1612
|
record_completion_event(event, result)
|
|
1008
1613
|
result
|
|
1009
1614
|
end
|
|
1615
|
+
rescue CancelledError
|
|
1616
|
+
@cancelled = false
|
|
1617
|
+
raise
|
|
1010
1618
|
end
|
|
1011
1619
|
|
|
1012
1620
|
# Replaces the conversation with +new_messages+, coercing each element
|
|
@@ -1023,7 +1631,31 @@ module RubyLLM
|
|
|
1023
1631
|
end
|
|
1024
1632
|
|
|
1025
1633
|
# Hooks installed by the Rails integration.
|
|
1026
|
-
attr_writer :
|
|
1634
|
+
attr_writer :run, :message_queue, :tool_call_state # :nodoc:
|
|
1635
|
+
|
|
1636
|
+
# The Agent class that configured the chat, which its instrumentation
|
|
1637
|
+
# events name.
|
|
1638
|
+
attr_accessor :agent_class # :nodoc:
|
|
1639
|
+
|
|
1640
|
+
# Runs the block inside one +agent.ruby_llm+ event when an Agent
|
|
1641
|
+
# configured the chat, unless a run of this chat is already open. Fibers
|
|
1642
|
+
# and threads started during a run inherit its marker, which is emptied
|
|
1643
|
+
# when the run ends, so their later turns open events of their own.
|
|
1644
|
+
def running_agent(&) # :nodoc:
|
|
1645
|
+
return yield if @agent_class.nil? || Fiber[AGENT_RUN_KEY]&.first.equal?(self)
|
|
1646
|
+
|
|
1647
|
+
previous = Fiber[AGENT_RUN_KEY]
|
|
1648
|
+
Fiber[AGENT_RUN_KEY] = run = [self]
|
|
1649
|
+
begin
|
|
1650
|
+
payload = { agent_name: @agent_class.name, chat: self, agent_description: @agent_class.description,
|
|
1651
|
+
chat_id: @run.chat_id }
|
|
1652
|
+
payload.delete_if { |key, value| value.nil? && key != :agent_name }
|
|
1653
|
+
RubyLLM.instrument('agent.ruby_llm', payload, config: @config, &)
|
|
1654
|
+
ensure
|
|
1655
|
+
run.clear
|
|
1656
|
+
Fiber[AGENT_RUN_KEY] = previous
|
|
1657
|
+
end
|
|
1658
|
+
end
|
|
1027
1659
|
|
|
1028
1660
|
# Appends a message to the conversation and returns it as a Message.
|
|
1029
1661
|
# Accepts a Message, an attribute Hash, or a record responding to
|
|
@@ -1032,20 +1664,33 @@ module RubyLLM
|
|
|
1032
1664
|
# chat.add_message(role: :user, content: "What's the capital of France?")
|
|
1033
1665
|
#
|
|
1034
1666
|
def add_message(message_or_attributes)
|
|
1035
|
-
message =
|
|
1667
|
+
message = prepare_message(message_or_attributes)
|
|
1036
1668
|
messages << message
|
|
1037
1669
|
message
|
|
1038
1670
|
end
|
|
1039
1671
|
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1672
|
+
def prepare_message(message_or_attributes, &taken) # :nodoc:
|
|
1673
|
+
message = coerce_message(message_or_attributes)
|
|
1674
|
+
return ToolCallIds.answer(message, messages) if message.tool_result?
|
|
1675
|
+
return message unless message.tool_call?
|
|
1676
|
+
return message if message.tool_calls.none? { |call| reused_tool_call_id?(call.id, &taken) }
|
|
1677
|
+
|
|
1678
|
+
ToolCallIds.new.assign(message)
|
|
1679
|
+
end
|
|
1680
|
+
|
|
1681
|
+
# Deprecated: mark the message itself with Message#cache_until_here, or
|
|
1682
|
+
# pass +cache_until_here:+ to #with_instructions. Marks the latest
|
|
1683
|
+
# message as an explicit prompt cache boundary. Warns through
|
|
1684
|
+
# RubyLLM.deprecator. RubyLLM 3.0 removes it. Returns +self+.
|
|
1044
1685
|
#
|
|
1045
|
-
# chat.with_instructions(policy
|
|
1686
|
+
# chat.with_instructions(policy, cache_until_here: { ttl: "1h" })
|
|
1687
|
+
# chat.add_message(role: :user, content: handbook).cache_until_here
|
|
1046
1688
|
#
|
|
1047
1689
|
# Raises ArgumentError if the chat has no messages.
|
|
1048
1690
|
def cache_until_here(ttl: nil)
|
|
1691
|
+
RubyLLM.deprecator.deprecate("#{self.class}#cache_until_here",
|
|
1692
|
+
replacement: 'Message#cache_until_here or with_instructions(cache_until_here:)',
|
|
1693
|
+
removal: '3.0')
|
|
1049
1694
|
message = messages.last
|
|
1050
1695
|
raise ArgumentError, 'No messages to cache' unless message
|
|
1051
1696
|
|
|
@@ -1062,17 +1707,22 @@ module RubyLLM
|
|
|
1062
1707
|
response.ruby_llm_usage_entries.each { |entry| record_usage_entry(entry) }
|
|
1063
1708
|
end
|
|
1064
1709
|
run_callbacks(:before_message)
|
|
1065
|
-
add_message
|
|
1710
|
+
response = add_message(response)
|
|
1066
1711
|
run_callbacks(:after_message, response)
|
|
1067
1712
|
response
|
|
1068
1713
|
end
|
|
1069
1714
|
|
|
1715
|
+
def add_usage_entry(entry) # :nodoc:
|
|
1716
|
+
record_usage_entry(entry)
|
|
1717
|
+
end
|
|
1718
|
+
|
|
1070
1719
|
# Returns the request payload this chat would send to the provider for
|
|
1071
1720
|
# its next completion, with #before_request hooks applied. Useful for
|
|
1072
1721
|
# inspecting and testing request output.
|
|
1073
1722
|
def render
|
|
1723
|
+
check_requested_tool_choice
|
|
1074
1724
|
@provider.render(
|
|
1075
|
-
preprocessed_messages,
|
|
1725
|
+
with_mcp_outages(preprocessed_messages),
|
|
1076
1726
|
tools: request_tools,
|
|
1077
1727
|
provider_tools: @provider_tools,
|
|
1078
1728
|
tool_prefs: @tool_prefs,
|
|
@@ -1083,7 +1733,7 @@ module RubyLLM
|
|
|
1083
1733
|
schema: @schema,
|
|
1084
1734
|
thinking: resolved_thinking,
|
|
1085
1735
|
citations: @citations,
|
|
1086
|
-
caching:
|
|
1736
|
+
caching: request_caching,
|
|
1087
1737
|
compaction: @compaction,
|
|
1088
1738
|
end_user: @end_user,
|
|
1089
1739
|
protocol: @protocol,
|
|
@@ -1091,6 +1741,14 @@ module RubyLLM
|
|
|
1091
1741
|
)
|
|
1092
1742
|
end
|
|
1093
1743
|
|
|
1744
|
+
# Refuses attachments an MCP::Prompt has no place for. Called by
|
|
1745
|
+
# #ask_later here and in the Rails integration.
|
|
1746
|
+
def raise_if_prompt_attachments!(message, with) # :nodoc:
|
|
1747
|
+
return unless message.is_a?(MCP::Prompt) && with && with != []
|
|
1748
|
+
|
|
1749
|
+
raise ArgumentError, 'An MCP::Prompt carries its own messages, so it takes no attachments'
|
|
1750
|
+
end
|
|
1751
|
+
|
|
1094
1752
|
# Refuses to stage a user message onto an unfinished tool round, which
|
|
1095
1753
|
# providers reject. Called by #ask_later here and in the Rails
|
|
1096
1754
|
# integration before it persists anything.
|
|
@@ -1098,19 +1756,68 @@ module RubyLLM
|
|
|
1098
1756
|
response = pending_tool_response
|
|
1099
1757
|
return unless response
|
|
1100
1758
|
|
|
1101
|
-
names = pending_tool_calls(response).
|
|
1759
|
+
names = pending_tool_calls(response).map(&:name).uniq
|
|
1102
1760
|
raise PendingToolCallsError,
|
|
1103
1761
|
"The last response has unanswered tool calls (#{names.join(', ')}). " \
|
|
1104
|
-
'Run complete,
|
|
1105
|
-
'
|
|
1762
|
+
'Run complete, answering their questions (see pending_questions) and waiting for ' \
|
|
1763
|
+
'their tasks, before asking again.'
|
|
1764
|
+
end
|
|
1765
|
+
|
|
1766
|
+
# Closes the calls of the latest round that a raising tool left without
|
|
1767
|
+
# a result, as unfinished, the way #cancel does, so the next request is
|
|
1768
|
+
# valid and no finished call runs again. Unlike a cancel, the turn goes
|
|
1769
|
+
# on: the next #complete asks the model, without forcing another tool
|
|
1770
|
+
# call. A call that waits on a person or a task, or that another
|
|
1771
|
+
# process runs, stays pending. A call that raised once its questions
|
|
1772
|
+
# were answered is closed too, so the answers don't run it again.
|
|
1773
|
+
def close_unfinished_tool_calls # :nodoc:
|
|
1774
|
+
response = pending_tool_response
|
|
1775
|
+
return unless response
|
|
1776
|
+
|
|
1777
|
+
@tool_prefs[:choice] = nil if forced_tool_choice?
|
|
1778
|
+
pending_tool_calls(response).each do |tool_call|
|
|
1779
|
+
next if running_elsewhere?(tool_call) || paused?(tool_call) || approval_pending?(tool_call)
|
|
1780
|
+
|
|
1781
|
+
record_tool_call_input(tool_call, nil)
|
|
1782
|
+
run_callbacks(:before_message)
|
|
1783
|
+
run_callbacks(:after_message, add_message(unfinished_result(tool_call)))
|
|
1784
|
+
end
|
|
1106
1785
|
end
|
|
1107
1786
|
|
|
1108
1787
|
private
|
|
1109
1788
|
|
|
1789
|
+
def agent_run_chat = self
|
|
1790
|
+
|
|
1791
|
+
def agent_fields
|
|
1792
|
+
name = @agent_class&.name
|
|
1793
|
+
name ? { agent_name: name } : {}
|
|
1794
|
+
end
|
|
1795
|
+
|
|
1796
|
+
def build_skill_loader
|
|
1797
|
+
Skill::Loader.new(skills: -> { @skills }, code_execution: -> { !@code_execution_tool.nil? })
|
|
1798
|
+
end
|
|
1799
|
+
|
|
1800
|
+
def build_file_tools
|
|
1801
|
+
written = ->(file) { run_callbacks(:after_file_write, file) }
|
|
1802
|
+
FileStore::Tools.classes(@file_references.tools)
|
|
1803
|
+
.map { |tool| tool.new(store: -> { file_store }, config: -> { @config }, written:) }
|
|
1804
|
+
end
|
|
1805
|
+
|
|
1110
1806
|
def resolved_thinking
|
|
1111
1807
|
@thinking&.resolve(@model)
|
|
1112
1808
|
end
|
|
1113
1809
|
|
|
1810
|
+
def request_caching
|
|
1811
|
+
return @caching unless @caching.is_a?(Hash)
|
|
1812
|
+
|
|
1813
|
+
caching = @caching
|
|
1814
|
+
caching = @provider.fallback_caching(caching, model: @model, protocol: @protocol) if @answering_fallback
|
|
1815
|
+
key = @run.cache_key
|
|
1816
|
+
return caching if key.nil? || @caching.key?(:key) || !@provider.cache_key?(model: @model, protocol: @protocol)
|
|
1817
|
+
|
|
1818
|
+
caching.merge(key:)
|
|
1819
|
+
end
|
|
1820
|
+
|
|
1114
1821
|
def normalize_compaction(options)
|
|
1115
1822
|
compaction = options.to_h.transform_keys(&:to_sym)
|
|
1116
1823
|
unsupported = compaction.keys - COMPACTION_OPTIONS
|
|
@@ -1191,26 +1898,135 @@ module RubyLLM
|
|
|
1191
1898
|
end
|
|
1192
1899
|
|
|
1193
1900
|
def raise_if_cancelled!
|
|
1194
|
-
|
|
1195
|
-
|
|
1901
|
+
@cancelled = true if @run.cancellation_requested?
|
|
1902
|
+
raise CancelledError if @cancelled
|
|
1903
|
+
end
|
|
1904
|
+
|
|
1905
|
+
# The transport retries through the checkpoint, so a cancelled request
|
|
1906
|
+
# stops at its failure. A chat cancelled while a request failed was going
|
|
1907
|
+
# to stop anyway, so the cancellation is what the caller hears about.
|
|
1908
|
+
def cancellable_request(&)
|
|
1909
|
+
Support::Cancellation.watch(-> { raise_if_cancelled! }, &)
|
|
1910
|
+
rescue Error
|
|
1911
|
+
raise_if_cancelled!
|
|
1912
|
+
raise
|
|
1913
|
+
end
|
|
1914
|
+
|
|
1915
|
+
def build_message_queue(queued = [])
|
|
1916
|
+
MessageQueue.new(queued) do |message|
|
|
1917
|
+
run_around_join(message) do |**attributes|
|
|
1918
|
+
raise ArgumentError, 'join takes attributes only on a persisted chat' if attributes.any?
|
|
1919
|
+
|
|
1920
|
+
add_message(role: :user, content: message.content, attachments: message.attachments)
|
|
1921
|
+
end
|
|
1922
|
+
end
|
|
1923
|
+
end
|
|
1924
|
+
|
|
1925
|
+
def advance(steering_only:, &)
|
|
1926
|
+
return if settled?(steering_only)
|
|
1927
|
+
|
|
1928
|
+
raise_if_cancelled!
|
|
1929
|
+
take_queued_messages(steering_only:) unless pending_tool_response
|
|
1930
|
+
return if answered?
|
|
1931
|
+
return generate(&) unless pending_tool_response
|
|
1196
1932
|
|
|
1933
|
+
before = messages.length
|
|
1934
|
+
run_tools
|
|
1935
|
+
messages.last if messages.length > before
|
|
1936
|
+
rescue CancelledError
|
|
1937
|
+
stop_tool_round
|
|
1938
|
+
raise
|
|
1939
|
+
end
|
|
1940
|
+
|
|
1941
|
+
# A round can stall once while another process lets its claim go, and
|
|
1942
|
+
# goes on the next time, perhaps to pause. A second stall in a row that
|
|
1943
|
+
# leaves nothing to wait on would repeat forever.
|
|
1944
|
+
def stalled_round?(stalled, generated:, move:)
|
|
1945
|
+
return false if generated || move
|
|
1946
|
+
return true unless stalled && !waiting?
|
|
1947
|
+
|
|
1948
|
+
ids = pending_tool_response&.then { |response| pending_tool_calls(response).keys }
|
|
1949
|
+
raise StalledToolRound,
|
|
1950
|
+
"RubyLLM made no progress on tool calls #{Array(ids).join(', ')}: they neither ran nor wait"
|
|
1951
|
+
end
|
|
1952
|
+
|
|
1953
|
+
def turn_result
|
|
1954
|
+
pending_tool_response || halted_result || last_non_system_message || messages.last
|
|
1955
|
+
end
|
|
1956
|
+
|
|
1957
|
+
def raise_if_tool_rounds_spent!(rounds)
|
|
1958
|
+
return unless @tool_rounds && rounds >= @tool_rounds
|
|
1959
|
+
|
|
1960
|
+
raise ToolRoundLimitError,
|
|
1961
|
+
"Reached the tool round limit (#{@tool_rounds}). Every tool call has its result, so call complete " \
|
|
1962
|
+
'to continue, or raise the limit with with_tool_options(rounds:).'
|
|
1963
|
+
end
|
|
1964
|
+
|
|
1965
|
+
def stop_tool_round
|
|
1197
1966
|
@cancelled = false
|
|
1198
|
-
|
|
1967
|
+
cancel_tasks
|
|
1968
|
+
close_unstarted_tool_calls
|
|
1969
|
+
end
|
|
1970
|
+
|
|
1971
|
+
def settled?(steering_only)
|
|
1972
|
+
answered? && @message_queue.none?(steering_only:)
|
|
1973
|
+
end
|
|
1974
|
+
|
|
1975
|
+
def last_conversation_message
|
|
1976
|
+
messages.reverse.find { |message| message.role != :system && !placeholder?(message) }
|
|
1977
|
+
end
|
|
1978
|
+
|
|
1979
|
+
def answered?
|
|
1980
|
+
return false if pending_tool_response
|
|
1981
|
+
|
|
1982
|
+
last = last_conversation_message
|
|
1983
|
+
case last&.role
|
|
1984
|
+
when nil then true
|
|
1985
|
+
when :user then false
|
|
1986
|
+
when :tool then !halted_result.nil? || last.cancelled?
|
|
1987
|
+
else !last.tool_call? && !unfinished?(last)
|
|
1988
|
+
end
|
|
1199
1989
|
end
|
|
1200
1990
|
|
|
1201
|
-
|
|
1991
|
+
# A tool that halted ends the turn once its round has every result.
|
|
1992
|
+
def halted_result
|
|
1993
|
+
messages.reverse_each.take_while(&:tool_result?).find(&:halted?)
|
|
1994
|
+
end
|
|
1995
|
+
|
|
1996
|
+
def generate_once(stream_tracker: nil, usage_start: nil, &)
|
|
1997
|
+
usage_start ||= usage_entries.length
|
|
1998
|
+
resumed = unfinished?(messages.last)
|
|
1999
|
+
streamed = +''
|
|
2000
|
+
tracker = proc do |chunk|
|
|
2001
|
+
streamed << chunk.content if chunk.content.is_a?(String)
|
|
2002
|
+
stream_tracker&.call(chunk)
|
|
2003
|
+
end
|
|
2004
|
+
generate_attempt(stream_tracker: tracker, usage_start:, &)
|
|
2005
|
+
rescue CancelledError
|
|
2006
|
+
keep_cancelled_reply(streamed, usage_start) unless resumed
|
|
2007
|
+
raise
|
|
2008
|
+
end
|
|
2009
|
+
|
|
2010
|
+
def generate_attempt(stream_tracker:, usage_start:, &block)
|
|
1202
2011
|
raise_if_cancelled!
|
|
1203
2012
|
|
|
1204
2013
|
result = nil
|
|
1205
2014
|
entries_before = usage_entries.length
|
|
1206
|
-
usage_start ||= entries_before
|
|
1207
2015
|
payload = instrumentation_payload(streaming: block_given?)
|
|
2016
|
+
announced = block_given?
|
|
2017
|
+
resumed = messages.last if unfinished?(messages.last)
|
|
2018
|
+
progress = proc do |partial|
|
|
2019
|
+
run_callbacks(:before_message) unless announced
|
|
2020
|
+
announced = true
|
|
2021
|
+
record_progress(partial)
|
|
2022
|
+
end
|
|
1208
2023
|
|
|
1209
2024
|
RubyLLM.instrument('chat.ruby_llm', payload, config: @config) do |event|
|
|
1210
|
-
result = provider_completion(usage_recorder: method(:record_usage_entry),
|
|
2025
|
+
result = provider_completion(usage_recorder: method(:record_usage_entry), progress_recorder: progress,
|
|
2026
|
+
stream_tracker:, &block)
|
|
1211
2027
|
event[:response_tokens] = result.tokens
|
|
1212
2028
|
record_out_of_band_usage(result) if usage_entries.length == entries_before
|
|
1213
|
-
record_generated_message(result, usage_start,
|
|
2029
|
+
record_generated_message(result, usage_start, announce: !announced, resumed:)
|
|
1214
2030
|
record_completion_event(event, result)
|
|
1215
2031
|
ensure
|
|
1216
2032
|
event[:response_tokens] ||= Tokens.aggregate(usage_entries[entries_before..].map(&:tokens))
|
|
@@ -1218,14 +2034,49 @@ module RubyLLM
|
|
|
1218
2034
|
result
|
|
1219
2035
|
end
|
|
1220
2036
|
|
|
1221
|
-
|
|
2037
|
+
# Keeps the text a cancelled stream showed, as a reply marked
|
|
2038
|
+
# cancelled. Tool calls it had not finished and its thinking, whose
|
|
2039
|
+
# signature would not verify, are left out.
|
|
2040
|
+
def keep_cancelled_reply(text, usage_start)
|
|
2041
|
+
return if text.nil? || text.strip.empty?
|
|
2042
|
+
|
|
2043
|
+
reply = Message.new(role: :assistant, content: text, model: @model.id, finish_reason: :cancelled)
|
|
2044
|
+
link_completion_usage(reply, usage_start)
|
|
2045
|
+
note_fallback(reply)
|
|
2046
|
+
add_message(reply)
|
|
2047
|
+
run_callbacks(:after_message, reply)
|
|
2048
|
+
end
|
|
2049
|
+
|
|
2050
|
+
def record_generated_message(result, usage_start, announce: true, resumed: nil, keep_unfinished: false)
|
|
1222
2051
|
raise_if_cancelled!
|
|
1223
|
-
link_completion_usage(result, usage_start)
|
|
1224
|
-
|
|
1225
|
-
|
|
2052
|
+
link_completion_usage(result, usage_start, resumed)
|
|
2053
|
+
note_fallback(result)
|
|
2054
|
+
run_callbacks(:before_message) if announce
|
|
2055
|
+
keep_unfinished ? add_message(result) : replace_unfinished(result)
|
|
1226
2056
|
run_callbacks(:after_message, result)
|
|
1227
2057
|
end
|
|
1228
2058
|
|
|
2059
|
+
# An unfinished response stands in the transcript while it continues,
|
|
2060
|
+
# so a later #complete resumes it when the run stops early.
|
|
2061
|
+
def record_progress(partial)
|
|
2062
|
+
replace_unfinished(partial)
|
|
2063
|
+
raise_if_cancelled!
|
|
2064
|
+
@run.record_progress(partial)
|
|
2065
|
+
end
|
|
2066
|
+
|
|
2067
|
+
def note_fallback(message)
|
|
2068
|
+
message.stood_in(model: @model.id, provider: @provider.slug) if @answering_fallback
|
|
2069
|
+
end
|
|
2070
|
+
|
|
2071
|
+
def replace_unfinished(message)
|
|
2072
|
+
messages.pop if unfinished?(messages.last)
|
|
2073
|
+
add_message(message)
|
|
2074
|
+
end
|
|
2075
|
+
|
|
2076
|
+
def unfinished?(message)
|
|
2077
|
+
message&.role == :assistant && !message.continuation.nil?
|
|
2078
|
+
end
|
|
2079
|
+
|
|
1229
2080
|
def instrumentation_payload(streaming:)
|
|
1230
2081
|
empty_tokens = Tokens.new
|
|
1231
2082
|
{
|
|
@@ -1249,7 +2100,8 @@ module RubyLLM
|
|
|
1249
2100
|
caching: @caching,
|
|
1250
2101
|
streaming: streaming,
|
|
1251
2102
|
tokens: empty_tokens,
|
|
1252
|
-
cost: Cost.new(tokens: empty_tokens, model: @model)
|
|
2103
|
+
cost: Cost.new(tokens: empty_tokens, model: @model),
|
|
2104
|
+
**agent_fields
|
|
1253
2105
|
}
|
|
1254
2106
|
end
|
|
1255
2107
|
|
|
@@ -1268,31 +2120,129 @@ module RubyLLM
|
|
|
1268
2120
|
|
|
1269
2121
|
def generate_with_fallbacks(&block)
|
|
1270
2122
|
fallback_queue = fallbacks.dup
|
|
2123
|
+
resume_stand_in(fallback_queue)
|
|
1271
2124
|
attempt = 0
|
|
1272
2125
|
active_fallback = nil
|
|
1273
2126
|
streaming = block_given?
|
|
1274
2127
|
usage_start = usage_entries.length
|
|
2128
|
+
block_failed = false
|
|
2129
|
+
on_chunk = block && proc do |chunk|
|
|
2130
|
+
block.call(chunk)
|
|
2131
|
+
rescue StandardError
|
|
2132
|
+
block_failed = true
|
|
2133
|
+
raise
|
|
2134
|
+
end
|
|
1275
2135
|
|
|
2136
|
+
drops = []
|
|
1276
2137
|
loop do
|
|
1277
2138
|
chunks_yielded = false
|
|
1278
2139
|
|
|
1279
2140
|
begin
|
|
1280
|
-
result =
|
|
2141
|
+
result = with_fallback_ready(fallback_queue) do
|
|
2142
|
+
generate_once(stream_tracker: proc { chunks_yielded = true }, usage_start:, &on_chunk)
|
|
2143
|
+
end
|
|
1281
2144
|
finish_fallback(active_fallback, response: result)
|
|
1282
2145
|
return result
|
|
1283
2146
|
rescue StandardError => e
|
|
1284
2147
|
finish_fallback(active_fallback, fallback_error: e)
|
|
1285
|
-
raise e
|
|
1286
|
-
|
|
1287
|
-
active_fallback, attempt =
|
|
1288
|
-
|
|
1289
|
-
error: e,
|
|
1290
|
-
attempt: attempt,
|
|
1291
|
-
streaming: streaming,
|
|
1292
|
-
chunks_yielded: chunks_yielded
|
|
1293
|
-
)
|
|
2148
|
+
raise e if block_failed || unfinished?(messages.last)
|
|
2149
|
+
|
|
2150
|
+
active_fallback, attempt = next_attempt!(fallback_queue, drops, error: e, attempt:, streaming:,
|
|
2151
|
+
chunks_yielded:)
|
|
1294
2152
|
end
|
|
1295
2153
|
end
|
|
2154
|
+
ensure
|
|
2155
|
+
@answering_fallback = false
|
|
2156
|
+
restore_parameters(drops)
|
|
2157
|
+
end
|
|
2158
|
+
|
|
2159
|
+
# One #complete is a run. While it lasts, @stand_ins holds the
|
|
2160
|
+
# fallback that took over once a model failed with an error in +on:+.
|
|
2161
|
+
# Each later request in the run starts on that fallback, and its
|
|
2162
|
+
# replies are marked as stood in, rather than waiting on the model that
|
|
2163
|
+
# just failed again; the next run starts on the chat's own model.
|
|
2164
|
+
def within_run
|
|
2165
|
+
outer = @stand_ins
|
|
2166
|
+
@stand_ins = []
|
|
2167
|
+
yield
|
|
2168
|
+
ensure
|
|
2169
|
+
@stand_ins = outer
|
|
2170
|
+
end
|
|
2171
|
+
|
|
2172
|
+
def resume_stand_in(fallback_queue)
|
|
2173
|
+
stand_in = @stand_ins&.last
|
|
2174
|
+
index = fallback_queue.index { |fallback| fallback.equal?(stand_in) }
|
|
2175
|
+
return unless index
|
|
2176
|
+
|
|
2177
|
+
switch_to_fallback_model(fallback_queue[index])
|
|
2178
|
+
fallback_queue.shift(index + 1)
|
|
2179
|
+
@answering_fallback = true
|
|
2180
|
+
end
|
|
2181
|
+
|
|
2182
|
+
# While a fallback is left, the transport hands a timeout, a failed
|
|
2183
|
+
# connection, or a long retry wait to it instead of retrying the same
|
|
2184
|
+
# model. Without one, the model is retried as configured.
|
|
2185
|
+
def with_fallback_ready(fallback_queue, &)
|
|
2186
|
+
return yield if fallback_queue.empty?
|
|
2187
|
+
|
|
2188
|
+
Transport::Connection.with_fallback_ready(method(:fallback_error?), &)
|
|
2189
|
+
end
|
|
2190
|
+
|
|
2191
|
+
# Retries the same model without each parameter it rejects, when the
|
|
2192
|
+
# chat opted in, then moves on to the next model with every parameter
|
|
2193
|
+
# back. Each parameter is dropped at most once per model.
|
|
2194
|
+
def next_attempt!(fallback_queue, drops, error:, **details)
|
|
2195
|
+
if (restore = drop_unsupported_parameter(error))
|
|
2196
|
+
drops << restore
|
|
2197
|
+
return retry_without_parameter!(error:, **details)
|
|
2198
|
+
end
|
|
2199
|
+
restore_parameters(drops)
|
|
2200
|
+
raise error unless fallback_error?(error)
|
|
2201
|
+
|
|
2202
|
+
fallback_to_next_model!(fallback_queue, error:, **details)
|
|
2203
|
+
end
|
|
2204
|
+
|
|
2205
|
+
DROPPED_VALUES = { temperature: nil, max_output_tokens: nil, thinking: nil, citations: false }.freeze
|
|
2206
|
+
private_constant :DROPPED_VALUES
|
|
2207
|
+
|
|
2208
|
+
# Clears the setting +error+ names for one retry, and returns how to put
|
|
2209
|
+
# it back, or +nil+ when the chat did not opt in or never set it.
|
|
2210
|
+
def drop_unsupported_parameter(error)
|
|
2211
|
+
return unless @drop_unsupported && error.is_a?(UnsupportedParameterError)
|
|
2212
|
+
|
|
2213
|
+
parameter = error.parameter
|
|
2214
|
+
return drop_provider_option(parameter) unless parameter.is_a?(Symbol)
|
|
2215
|
+
return unless DROPPED_VALUES.key?(parameter)
|
|
2216
|
+
|
|
2217
|
+
name = :"@#{parameter}"
|
|
2218
|
+
original = instance_variable_get(name)
|
|
2219
|
+
return if original.nil? || original == false
|
|
2220
|
+
|
|
2221
|
+
instance_variable_set(name, DROPPED_VALUES[parameter])
|
|
2222
|
+
-> { instance_variable_set(name, original) }
|
|
2223
|
+
end
|
|
2224
|
+
|
|
2225
|
+
def drop_provider_option(parameter)
|
|
2226
|
+
key = @provider_options.keys.find { |candidate| candidate.to_s == parameter.to_s }
|
|
2227
|
+
return unless key
|
|
2228
|
+
|
|
2229
|
+
original = @provider_options
|
|
2230
|
+
@provider_options = original.except(key)
|
|
2231
|
+
-> { @provider_options = original }
|
|
2232
|
+
end
|
|
2233
|
+
|
|
2234
|
+
def restore_parameters(drops)
|
|
2235
|
+
drops.pop.call until drops.nil? || drops.empty?
|
|
2236
|
+
end
|
|
2237
|
+
|
|
2238
|
+
def retry_without_parameter!(error:, attempt:, streaming:, chunks_yielded:)
|
|
2239
|
+
attempt += 1
|
|
2240
|
+
fallback = Fallback.new(model: @model).with_attempt(
|
|
2241
|
+
chat: self, error:, from: @model, to: @model, attempt:, streaming:, chunks_yielded:,
|
|
2242
|
+
dropped_parameter: error.parameter
|
|
2243
|
+
)
|
|
2244
|
+
run_callbacks(:before_fallback, fallback)
|
|
2245
|
+
[fallback, attempt]
|
|
1296
2246
|
end
|
|
1297
2247
|
|
|
1298
2248
|
def with_model_restored
|
|
@@ -1321,20 +2271,20 @@ module RubyLLM
|
|
|
1321
2271
|
end
|
|
1322
2272
|
|
|
1323
2273
|
def with_resolved_model(model)
|
|
1324
|
-
|
|
2274
|
+
@provider = Provider.resolve!(model.provider).new(@config)
|
|
1325
2275
|
@model = model
|
|
1326
|
-
@provider = provider_class.new(@config)
|
|
1327
2276
|
@connection = @provider.connection
|
|
1328
2277
|
self
|
|
1329
2278
|
end
|
|
1330
2279
|
|
|
1331
2280
|
def fallback_to_next_model!(fallback_queue, error:, attempt:, streaming:, chunks_yielded:)
|
|
1332
|
-
|
|
2281
|
+
from_model = @model
|
|
2282
|
+
fallback = switch_to_usable_fallback(fallback_queue)
|
|
1333
2283
|
raise error unless fallback
|
|
1334
2284
|
|
|
2285
|
+
@stand_ins&.replace([fallback])
|
|
2286
|
+
@answering_fallback = true
|
|
1335
2287
|
attempt += 1
|
|
1336
|
-
from_model = @model
|
|
1337
|
-
switch_to_fallback_model(fallback)
|
|
1338
2288
|
fallback = fallback.with_attempt(
|
|
1339
2289
|
chat: self,
|
|
1340
2290
|
error: error,
|
|
@@ -1348,6 +2298,10 @@ module RubyLLM
|
|
|
1348
2298
|
[fallback, attempt]
|
|
1349
2299
|
end
|
|
1350
2300
|
|
|
2301
|
+
def switch_to_usable_fallback(fallback_queue)
|
|
2302
|
+
Fallback.next_usable(fallback_queue) { |fallback| switch_to_fallback_model(fallback) }&.first
|
|
2303
|
+
end
|
|
2304
|
+
|
|
1351
2305
|
def finish_fallback(fallback, response: nil, fallback_error: nil)
|
|
1352
2306
|
return unless fallback
|
|
1353
2307
|
|
|
@@ -1356,7 +2310,7 @@ module RubyLLM
|
|
|
1356
2310
|
end
|
|
1357
2311
|
|
|
1358
2312
|
def fallback_error?(error)
|
|
1359
|
-
|
|
2313
|
+
!@run.interrupted_by?(error) && Fallback.error?(error, fallback_errors)
|
|
1360
2314
|
end
|
|
1361
2315
|
|
|
1362
2316
|
# Preprocessing builds a per-request view of the conversation: the
|
|
@@ -1365,21 +2319,63 @@ module RubyLLM
|
|
|
1365
2319
|
# them. An attachment's store keeps its uploads for later processes.
|
|
1366
2320
|
def preprocessed_messages(list = messages)
|
|
1367
2321
|
list = request_history(list)
|
|
2322
|
+
list = @file_references.view(list) if @file_references
|
|
2323
|
+
list = context_budget_for_model.fit(list) if @context_budget
|
|
2324
|
+
list = CodeExecution.for_model(with_skill_listing(list))
|
|
1368
2325
|
return list unless @provider
|
|
1369
2326
|
|
|
1370
2327
|
@provider.preprocess_messages(list, model: @model, protocol: @protocol,
|
|
1371
2328
|
unsupported_attachment: unsupported_attachment_handler)
|
|
1372
2329
|
end
|
|
1373
2330
|
|
|
2331
|
+
def context_budget_for_model
|
|
2332
|
+
ContextBudget.new(@context_budget, @model&.context_window).tap do |budget|
|
|
2333
|
+
warn_about_unknown_window unless budget.window? || @context_budget_warned
|
|
2334
|
+
end
|
|
2335
|
+
end
|
|
2336
|
+
|
|
2337
|
+
def warn_about_unknown_window
|
|
2338
|
+
@context_budget_warned = true
|
|
2339
|
+
RubyLLM.logger.warn("RubyLLM has no context window for #{@model&.id}, so this chat's context budget does " \
|
|
2340
|
+
'nothing. Pass window: to with_context_budget.')
|
|
2341
|
+
end
|
|
2342
|
+
|
|
2343
|
+
def with_skill_listing(list)
|
|
2344
|
+
return list if skills.empty?
|
|
2345
|
+
|
|
2346
|
+
index = list.index { |message| message.role != :system } || list.size
|
|
2347
|
+
list.dup.insert(index, Message.new(role: :system, content: @skill_loader.listing))
|
|
2348
|
+
end
|
|
2349
|
+
|
|
2350
|
+
def with_mcp_outages(list)
|
|
2351
|
+
unreachable = mcp.unreachable
|
|
2352
|
+
return list if unreachable.empty?
|
|
2353
|
+
|
|
2354
|
+
note = "These MCP servers can't be reached right now, so their tools are unavailable: " \
|
|
2355
|
+
"#{unreachable.join(', ')}. If a request needs them, say so."
|
|
2356
|
+
index = list.index { |message| message.role != :system } || list.size
|
|
2357
|
+
list.dup.insert(index, Message.new(role: :system, content: note))
|
|
2358
|
+
end
|
|
2359
|
+
|
|
1374
2360
|
def unsupported_attachment_handler
|
|
1375
2361
|
callbacks = @callbacks[:unsupported_attachment]
|
|
1376
|
-
|
|
2362
|
+
callbacks += [->(attachment) { @file_references.describe(attachment, config: @config) }] if @file_references
|
|
2363
|
+
return if callbacks.empty? && !@code_execution
|
|
1377
2364
|
|
|
2365
|
+
describe = attachment_describer
|
|
1378
2366
|
lambda do |attachment|
|
|
1379
2367
|
@attachment_replacements[attachment] ||= callbacks.lazy.filter_map { |handler| handler.call(attachment) }.first
|
|
2368
|
+
@attachment_replacements[attachment] || describe.call(attachment)
|
|
1380
2369
|
end
|
|
1381
2370
|
end
|
|
1382
2371
|
|
|
2372
|
+
# A run's names shift as files arrive, so descriptions are not memoized.
|
|
2373
|
+
def attachment_describer
|
|
2374
|
+
return ->(_attachment) {} unless @code_execution
|
|
2375
|
+
|
|
2376
|
+
CodeExecution.describer(messages.flat_map(&:attachments))
|
|
2377
|
+
end
|
|
2378
|
+
|
|
1383
2379
|
# A process that dies mid-round leaves a blank assistant placeholder,
|
|
1384
2380
|
# or tool calls without results, and providers refuse both. A request
|
|
1385
2381
|
# leaves blank messages out and answers the calls of a round the
|
|
@@ -1396,13 +2392,17 @@ module RubyLLM
|
|
|
1396
2392
|
end
|
|
1397
2393
|
|
|
1398
2394
|
def unfinished_results(response, answered)
|
|
1399
|
-
response.tool_calls.
|
|
2395
|
+
response.tool_calls.reject { |tool_call| answered.include?(tool_call.id) }
|
|
1400
2396
|
.map { |tool_call| unfinished_result(tool_call) }
|
|
1401
2397
|
end
|
|
1402
2398
|
|
|
1403
|
-
|
|
2399
|
+
# A call +interrupted+ after it started may have done its work, so the
|
|
2400
|
+
# model hears it may have partly run, as for an MCP call that broke off.
|
|
2401
|
+
def unfinished_result(tool_call, interrupted: false)
|
|
2402
|
+
content = UNFINISHED_TOOL_RESULT
|
|
2403
|
+
content = { error: "The tool call did not finish. #{MCP::Outages::PARTLY_RUN}" }.to_json if interrupted
|
|
1404
2404
|
(remote_refusal(tool_call) if tool_call.remote?) ||
|
|
1405
|
-
Message.new(role: :tool, content:
|
|
2405
|
+
Message.new(role: :tool, content:, tool_call_id: tool_call.id, provider_call_id: tool_call.provider_call_id)
|
|
1406
2406
|
end
|
|
1407
2407
|
|
|
1408
2408
|
# A provider-executed call is closed with the refusal its provider
|
|
@@ -1413,49 +2413,60 @@ module RubyLLM
|
|
|
1413
2413
|
nil
|
|
1414
2414
|
end
|
|
1415
2415
|
|
|
1416
|
-
def provider_completion(usage_recorder:, stream_tracker: nil, &)
|
|
2416
|
+
def provider_completion(usage_recorder:, progress_recorder: nil, stream_tracker: nil, &)
|
|
1417
2417
|
raise_if_cancelled!
|
|
2418
|
+
check_requested_tool_choice
|
|
1418
2419
|
|
|
1419
|
-
request_messages = preprocessed_messages
|
|
2420
|
+
request_messages = with_mcp_outages(preprocessed_messages)
|
|
2421
|
+
tool_call_ids = ToolCallIds.new
|
|
1420
2422
|
streamed = false
|
|
1421
2423
|
tracker = proc do |chunk|
|
|
1422
2424
|
streamed = true
|
|
1423
2425
|
stream_tracker&.call(chunk)
|
|
1424
2426
|
end
|
|
1425
|
-
on_chunk = wrap_streaming_block(stream_tracker: tracker, &)
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
2427
|
+
on_chunk = wrap_streaming_block(tool_call_ids:, stream_tracker: tracker, &)
|
|
2428
|
+
|
|
2429
|
+
sent = request_messages
|
|
2430
|
+
response = replacing_missing_uploads(request_messages, -> { streamed }) do |sent_messages|
|
|
2431
|
+
sent = sent_messages
|
|
2432
|
+
cancellable_request do
|
|
2433
|
+
@provider.complete(
|
|
2434
|
+
sent_messages,
|
|
2435
|
+
tools: request_tools,
|
|
2436
|
+
provider_tools: @provider_tools,
|
|
2437
|
+
tool_prefs: @tool_prefs,
|
|
2438
|
+
temperature: @temperature,
|
|
2439
|
+
max_output_tokens: @max_output_tokens,
|
|
2440
|
+
model: @model,
|
|
2441
|
+
provider_options: Support::Utils.deep_dup(@provider_options),
|
|
2442
|
+
headers: @headers,
|
|
2443
|
+
schema: @schema,
|
|
2444
|
+
thinking: resolved_thinking,
|
|
2445
|
+
citations: @citations,
|
|
2446
|
+
caching: request_caching,
|
|
2447
|
+
compaction: @compaction,
|
|
2448
|
+
end_user: @end_user,
|
|
2449
|
+
protocol: @protocol,
|
|
2450
|
+
before_request: @callbacks[:before_request],
|
|
2451
|
+
usage_recorder: usage_recorder,
|
|
2452
|
+
progress_recorder: progress_recorder,
|
|
2453
|
+
&on_chunk
|
|
2454
|
+
)
|
|
2455
|
+
end
|
|
1449
2456
|
end
|
|
2457
|
+
@file_references&.record_shown(sent)
|
|
2458
|
+
tool_call_ids.assign(response)
|
|
1450
2459
|
end
|
|
1451
2460
|
|
|
1452
2461
|
def provider_compaction
|
|
1453
2462
|
replacing_missing_uploads(preprocessed_messages) do |sent_messages|
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
2463
|
+
cancellable_request do
|
|
2464
|
+
@provider.compact(
|
|
2465
|
+
sent_messages, model: @model, protocol: @protocol,
|
|
2466
|
+
headers: @headers, before_request: @callbacks[:before_request],
|
|
2467
|
+
usage_recorder: method(:record_usage_entry)
|
|
2468
|
+
)
|
|
2469
|
+
end
|
|
1459
2470
|
end
|
|
1460
2471
|
end
|
|
1461
2472
|
|
|
@@ -1480,12 +2491,13 @@ module RubyLLM
|
|
|
1480
2491
|
|
|
1481
2492
|
def record_usage_entry(entry)
|
|
1482
2493
|
usage_entries << entry
|
|
1483
|
-
@
|
|
2494
|
+
@run.record_usage(entry)
|
|
1484
2495
|
entry
|
|
1485
2496
|
end
|
|
1486
2497
|
|
|
1487
|
-
def link_completion_usage(response, usage_start)
|
|
1488
|
-
|
|
2498
|
+
def link_completion_usage(response, usage_start, resumed = nil)
|
|
2499
|
+
earlier = resumed ? resumed.ruby_llm_usage_entries : []
|
|
2500
|
+
response.ruby_llm_usage_entries = earlier + usage_entries.drop(usage_start)
|
|
1489
2501
|
end
|
|
1490
2502
|
|
|
1491
2503
|
def record_out_of_band_usage(response)
|
|
@@ -1497,7 +2509,8 @@ module RubyLLM
|
|
|
1497
2509
|
tokens: response.tokens,
|
|
1498
2510
|
cost: response.cost,
|
|
1499
2511
|
message: response,
|
|
1500
|
-
owner: Accounting::Usage.owner
|
|
2512
|
+
owner: Accounting::Usage.owner,
|
|
2513
|
+
workflow: Accounting::Usage.workflow
|
|
1501
2514
|
)
|
|
1502
2515
|
response.ruby_llm_usage_entries = [entry]
|
|
1503
2516
|
Accounting::Usage.instrument(entry, config: @config)
|
|
@@ -1508,13 +2521,16 @@ module RubyLLM
|
|
|
1508
2521
|
@callbacks[name].each { |callback| callback.call(*args) }
|
|
1509
2522
|
end
|
|
1510
2523
|
|
|
1511
|
-
def wrap_streaming_block(stream_tracker: nil, &block)
|
|
2524
|
+
def wrap_streaming_block(tool_call_ids:, stream_tracker: nil, &block)
|
|
1512
2525
|
return nil unless block
|
|
1513
2526
|
|
|
1514
2527
|
run_callbacks(:before_message)
|
|
2528
|
+
index = -1
|
|
1515
2529
|
|
|
1516
2530
|
proc do |chunk|
|
|
1517
2531
|
raise_if_cancelled!
|
|
2532
|
+
chunk = tool_call_ids.assign(chunk)
|
|
2533
|
+
chunk.index = index += 1
|
|
1518
2534
|
stream_tracker&.call(chunk)
|
|
1519
2535
|
block.call(chunk)
|
|
1520
2536
|
raise_if_cancelled!
|
|
@@ -1524,83 +2540,223 @@ module RubyLLM
|
|
|
1524
2540
|
def execute_pending_tool_calls(response)
|
|
1525
2541
|
raise_if_cancelled!
|
|
1526
2542
|
|
|
1527
|
-
|
|
1528
|
-
|
|
2543
|
+
pending = pending_tool_calls(response).except(*capped_tool_call_ids(response))
|
|
2544
|
+
server_calls, local_calls = pending.to_h.partition { |_, call| call.remote? }.map(&:to_h)
|
|
2545
|
+
decisions = server_calls.transform_values { |tool_call| approval_decision(nil, tool_call) }.compact
|
|
1529
2546
|
executable, denied = partition_pending_tool_calls(local_calls)
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
2547
|
+
executable = executable.reject { |_id, tool_call| exclusive_blocked?(tool_call, executable) }
|
|
2548
|
+
claimed = claim_tool_calls(executable, server_calls.slice(*decisions.keys).merge(denied))
|
|
2549
|
+
answer_claimed_tool_calls(claimed, server_calls, decisions, executable, denied)
|
|
2550
|
+
answer_capped_tool_calls(response)
|
|
2551
|
+
@tool_prefs[:choice] = nil if forced_tool_choice?
|
|
2552
|
+
end
|
|
2553
|
+
|
|
2554
|
+
def answer_capped_tool_calls(response)
|
|
2555
|
+
capped = unanswered_capped_tool_calls(response)
|
|
2556
|
+
capped.each_value do |tool_call|
|
|
2557
|
+
raise_if_cancelled!
|
|
2558
|
+
run_callbacks(:before_message)
|
|
2559
|
+
add_tool_result_message(tool_call, { error: capped_tool_call_error })
|
|
2560
|
+
end
|
|
2561
|
+
ensure
|
|
2562
|
+
instrument_capped_tool_calls(response) if capped&.any? && unanswered_capped_tool_calls(response).empty?
|
|
2563
|
+
end
|
|
2564
|
+
|
|
2565
|
+
def unanswered_capped_tool_calls(response)
|
|
2566
|
+
pending_tool_calls(response).to_h.slice(*capped_tool_call_ids(response))
|
|
2567
|
+
end
|
|
2568
|
+
|
|
2569
|
+
def capped_tool_call_ids(response)
|
|
2570
|
+
return [] unless @tool_call_cap && response
|
|
2571
|
+
|
|
2572
|
+
response.tool_calls.reject(&:remote?).drop(@tool_call_cap).map(&:id)
|
|
2573
|
+
end
|
|
2574
|
+
|
|
2575
|
+
def capped_tool_call?(tool_call)
|
|
2576
|
+
return false unless @tool_call_cap
|
|
2577
|
+
|
|
2578
|
+
response = messages.reverse_each.find { |message| message.tool_calls.key?(tool_call.id) }
|
|
2579
|
+
capped_tool_call_ids(response).include?(tool_call.id)
|
|
2580
|
+
end
|
|
2581
|
+
|
|
2582
|
+
def capped_tool_call_error
|
|
2583
|
+
"This call didn't run: too many tool calls in one answer (#{@tool_call_cap} at most). " \
|
|
2584
|
+
'Continue step by step, a few calls at a time.'
|
|
2585
|
+
end
|
|
2586
|
+
|
|
2587
|
+
def instrument_capped_tool_calls(response)
|
|
2588
|
+
requested = response.tool_calls.count { |tool_call| !tool_call.remote? }
|
|
2589
|
+
payload = { chat: self, provider: response.provider || @provider.slug, model: response.model_id || @model.id,
|
|
2590
|
+
requested:, allowed: @tool_call_cap, capped: requested - @tool_call_cap, chat_id: @run.chat_id,
|
|
2591
|
+
**agent_fields }
|
|
2592
|
+
RubyLLM.instrument('tool_calls_capped.ruby_llm', payload.compact, config: @config)
|
|
2593
|
+
end
|
|
2594
|
+
|
|
2595
|
+
def answer_claimed_tool_calls(claimed, server_calls, decisions, executable, denied)
|
|
2596
|
+
respond_to_tool_approvals(server_calls.slice(*claimed), decisions)
|
|
2597
|
+
deny_tool_calls(denied.slice(*claimed))
|
|
2598
|
+
runnable = answer_interrupted_tool_calls(executable.slice(*claimed))
|
|
2599
|
+
if concurrency && executable.values.none? { |tool_call| ordered?(tool_call) }
|
|
2600
|
+
handle_concurrent_tool_calls(runnable)
|
|
1533
2601
|
else
|
|
1534
|
-
handle_sequential_tool_calls(
|
|
2602
|
+
handle_sequential_tool_calls(runnable)
|
|
1535
2603
|
end
|
|
2604
|
+
finished = true
|
|
2605
|
+
rescue SignalException, SystemExit => e
|
|
2606
|
+
stopped_by = e
|
|
2607
|
+
raise
|
|
2608
|
+
ensure
|
|
2609
|
+
release_tool_calls(claimed, stopped_by, finished:)
|
|
2610
|
+
end
|
|
1536
2611
|
|
|
1537
|
-
|
|
2612
|
+
# A call that had started in a process that stopped before saving its
|
|
2613
|
+
# result may have done its work, so it doesn't run again: the model
|
|
2614
|
+
# reads that it was interrupted and decides what to do. A call that
|
|
2615
|
+
# paused for an answer or a task carries on as usual. Returns the calls
|
|
2616
|
+
# left to run.
|
|
2617
|
+
def answer_interrupted_tool_calls(tool_calls)
|
|
2618
|
+
interrupted, runnable = tool_calls.partition do |_, tool_call|
|
|
2619
|
+
@tool_call_state.interrupted?(tool_call) && !tool_call_input(tool_call)
|
|
2620
|
+
end
|
|
2621
|
+
interrupted.to_h.each_value do |tool_call|
|
|
2622
|
+
run_callbacks(:before_message)
|
|
2623
|
+
run_callbacks(:after_message, add_message(unfinished_result(tool_call, interrupted: true)))
|
|
2624
|
+
end
|
|
2625
|
+
runnable.to_h
|
|
1538
2626
|
end
|
|
1539
2627
|
|
|
1540
|
-
def
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
2628
|
+
def claim_tool_calls(executable, answered)
|
|
2629
|
+
requested = executable.keys + answered.keys
|
|
2630
|
+
@tool_call_state.claim(requested, executing: executable.keys) do
|
|
2631
|
+
leases = executable.values.to_h { |tool_call| [tool_call, max_run_time_for(tool_call)] }
|
|
2632
|
+
answered.each_value { |tool_call| leases[tool_call] = @config.max_run_time }
|
|
2633
|
+
leases
|
|
2634
|
+
end
|
|
2635
|
+
end
|
|
1544
2636
|
|
|
2637
|
+
def release_tool_calls(ids, stopped_by, finished:)
|
|
2638
|
+
answered = messages.filter_map { |message| message.tool_call_id if message.tool_result? }
|
|
2639
|
+
@tool_call_state.release(ids - answered, stopped_by, finished:)
|
|
2640
|
+
end
|
|
2641
|
+
|
|
2642
|
+
def max_run_time_for(tool_call)
|
|
2643
|
+
tool_for(tool_call)&.max_run_time || @config.max_run_time
|
|
2644
|
+
end
|
|
2645
|
+
|
|
2646
|
+
def running_elsewhere?(tool_call)
|
|
2647
|
+
@tool_call_state.running_elsewhere?(tool_call)
|
|
2648
|
+
end
|
|
2649
|
+
|
|
2650
|
+
def respond_to_tool_approvals(tool_calls, decisions)
|
|
2651
|
+
tool_calls.each do |id, tool_call|
|
|
2652
|
+
decision = decisions.fetch(id)
|
|
1545
2653
|
raise_if_cancelled!
|
|
1546
2654
|
run_callbacks(:before_message)
|
|
1547
|
-
|
|
2655
|
+
note = note_text(decline_note(tool_call)) unless decision
|
|
2656
|
+
response = @provider.tool_approval_response(tool_call, approved: decision, model: @model, protocol: @protocol,
|
|
2657
|
+
note:)
|
|
1548
2658
|
message = add_message(response)
|
|
1549
2659
|
run_callbacks(:after_message, message)
|
|
1550
2660
|
end
|
|
1551
2661
|
end
|
|
1552
2662
|
|
|
1553
2663
|
def partition_pending_tool_calls(pending)
|
|
1554
|
-
|
|
1555
|
-
denied = {}
|
|
1556
|
-
pending.reject { |_, tool_call| input_pending?(tool_call) }.each do |id, tool_call|
|
|
1557
|
-
decision = execution_decision(tool_call)
|
|
1558
|
-
(decision ? executable : denied)[id] = tool_call unless decision.nil?
|
|
1559
|
-
end
|
|
1560
|
-
[executable, denied]
|
|
2664
|
+
partition_tool_sequences(pending)
|
|
1561
2665
|
end
|
|
1562
2666
|
|
|
1563
2667
|
def execution_decision(tool_call)
|
|
1564
|
-
|
|
1565
|
-
return tool_call_approval(tool, tool_call) if tool&.requires_approval?
|
|
2668
|
+
return false if tool_call.malformed_arguments?
|
|
1566
2669
|
|
|
1567
|
-
|
|
2670
|
+
tool = tool_for(tool_call)
|
|
2671
|
+
return approval_decision(tool, tool_call) if tool&.requires_approval?(tool_call)
|
|
2672
|
+
|
|
2673
|
+
!@tool_call_state.denied?(tool_call)
|
|
1568
2674
|
end
|
|
1569
2675
|
|
|
1570
2676
|
def deny_tool_calls(tool_calls)
|
|
1571
2677
|
tool_calls.each_value do |tool_call|
|
|
1572
2678
|
raise_if_cancelled!
|
|
1573
2679
|
run_callbacks(:before_message)
|
|
1574
|
-
add_tool_result_message(tool_call,
|
|
2680
|
+
add_tool_result_message(tool_call, refusal(tool_call))
|
|
1575
2681
|
end
|
|
1576
2682
|
end
|
|
1577
2683
|
|
|
2684
|
+
def refusal(tool_call)
|
|
2685
|
+
note = decline_note(tool_call) unless tool_call.malformed_arguments?
|
|
2686
|
+
note.is_a?(Hash) ? note : { error: refusal_error(tool_call, note) }
|
|
2687
|
+
end
|
|
2688
|
+
|
|
2689
|
+
def refusal_error(tool_call, note)
|
|
2690
|
+
name = tool_call.name
|
|
2691
|
+
return note || "The user denied the #{name} tool call." unless tool_call.malformed_arguments?
|
|
2692
|
+
|
|
2693
|
+
"The arguments for #{name} were #{tool_call.malformed_arguments_problem}. Call #{name} again with a JSON object."
|
|
2694
|
+
end
|
|
2695
|
+
|
|
1578
2696
|
def record_tool_call_decision(tool_call, decision)
|
|
1579
2697
|
id = tool_call.respond_to?(:id) ? tool_call.id : tool_call
|
|
1580
|
-
@
|
|
2698
|
+
@tool_call_state.record_decision(id, decision)
|
|
1581
2699
|
self
|
|
1582
2700
|
end
|
|
1583
2701
|
|
|
1584
|
-
def
|
|
1585
|
-
return
|
|
2702
|
+
def approval_decision(tool, tool_call)
|
|
2703
|
+
return false if tool_call.malformed_arguments?
|
|
2704
|
+
|
|
2705
|
+
decision = tool_call_approval(tool, tool_call)
|
|
2706
|
+
return decision unless decision.nil?
|
|
2707
|
+
return if tool.is_a?(CodeExecution)
|
|
2708
|
+
|
|
2709
|
+
true if remembered_tool?(tool_call)
|
|
2710
|
+
end
|
|
2711
|
+
|
|
2712
|
+
def remembered_tool?(call)
|
|
2713
|
+
@tool_call_state.remembered?(call)
|
|
2714
|
+
end
|
|
2715
|
+
|
|
2716
|
+
def remembered_tool_identity(tool_call)
|
|
2717
|
+
id = tool_call.respond_to?(:id) ? tool_call.id : tool_call
|
|
2718
|
+
call = tool_call.respond_to?(:name) ? tool_call : find_tool_call(id)
|
|
2719
|
+
raise ArgumentError, "Unknown tool call: #{id.inspect}" unless call
|
|
2720
|
+
|
|
2721
|
+
ToolCallState.remembered_identity(call)
|
|
2722
|
+
end
|
|
2723
|
+
|
|
2724
|
+
def tool_call_answered?(tool_call)
|
|
2725
|
+
id = tool_call.respond_to?(:id) ? tool_call.id : tool_call
|
|
2726
|
+
messages.any? { |message| message.tool_result? && message.tool_call_id == id }
|
|
2727
|
+
end
|
|
1586
2728
|
|
|
1587
|
-
|
|
1588
|
-
|
|
2729
|
+
def find_tool_call(id)
|
|
2730
|
+
messages.reverse_each do |message|
|
|
2731
|
+
call = message.tool_calls[id]
|
|
2732
|
+
return call if call
|
|
2733
|
+
end
|
|
2734
|
+
nil
|
|
2735
|
+
end
|
|
1589
2736
|
|
|
1590
|
-
|
|
2737
|
+
def reused_tool_call_id?(id)
|
|
2738
|
+
id.nil? || find_tool_call(id) || (block_given? && yield(id))
|
|
2739
|
+
end
|
|
2740
|
+
|
|
2741
|
+
def escalation_approved?(tool_call)
|
|
2742
|
+
return false if tool_call.nil? || @tool_call_state.escalation_spent?(tool_call)
|
|
2743
|
+
|
|
2744
|
+
@tool_call_state.spend_escalation(tool_call)
|
|
2745
|
+
tool_call_approval(nil, tool_call) == true
|
|
1591
2746
|
end
|
|
1592
2747
|
|
|
1593
2748
|
def tool_call_approval(tool, tool_call)
|
|
1594
2749
|
return tool.approval_resolver.call(tool_call) if tool&.approval_resolver
|
|
1595
|
-
return @tool_call_decisions[tool_call.id] if @tool_call_decisions.key?(tool_call.id)
|
|
1596
2750
|
|
|
1597
|
-
@
|
|
2751
|
+
@tool_call_state.decision(tool_call)
|
|
1598
2752
|
end
|
|
1599
2753
|
|
|
1600
2754
|
def handle_sequential_tool_calls(tool_calls)
|
|
1601
2755
|
tool_calls.each_value do |tool_call|
|
|
2756
|
+
next if sequence_blocked?(tool_call) || exclusive_blocked?(tool_call)
|
|
2757
|
+
|
|
1602
2758
|
raise_if_cancelled!
|
|
1603
|
-
result = execute_tool_with_callbacks(tool_call)
|
|
2759
|
+
result = skipped_result(tool_call) || execute_tool_with_callbacks(tool_call)
|
|
1604
2760
|
next if result.equal?(PAUSED)
|
|
1605
2761
|
|
|
1606
2762
|
run_callbacks(:before_message)
|
|
@@ -1612,45 +2768,74 @@ module RubyLLM
|
|
|
1612
2768
|
execute_tools_concurrently(tool_calls) do |tool_call, result|
|
|
1613
2769
|
next if result.equal?(PAUSED)
|
|
1614
2770
|
|
|
1615
|
-
raise_if_cancelled!
|
|
1616
2771
|
run_callbacks(:before_message)
|
|
1617
2772
|
add_tool_result_message(tool_call, result)
|
|
1618
2773
|
end
|
|
1619
2774
|
end
|
|
1620
2775
|
|
|
1621
2776
|
def execute_tools_concurrently(tool_calls, &on_result)
|
|
1622
|
-
|
|
2777
|
+
exclusive = ->(tool_call) { exclusive_call?(tool_call) }
|
|
2778
|
+
paused = ->(result) { result.equal?(PAUSED) }
|
|
2779
|
+
ToolConcurrency.run(concurrency, tool_calls, exclusive:, paused:, on_result:, config: @config) do |tool_call|
|
|
1623
2780
|
execute_tool_with_callbacks(tool_call)
|
|
1624
2781
|
end
|
|
1625
2782
|
end
|
|
1626
2783
|
|
|
1627
2784
|
def execute_tool_with_callbacks(tool_call)
|
|
1628
2785
|
raise_if_cancelled!
|
|
2786
|
+
@tool_call_state.started(tool_call)
|
|
1629
2787
|
run_callbacks(:before_tool_call, tool_call)
|
|
1630
|
-
result = execute_tool tool_call
|
|
2788
|
+
result = run_around_tool_call(tool_call) { execute_tool tool_call }
|
|
1631
2789
|
return result if result.equal?(PAUSED)
|
|
1632
2790
|
|
|
1633
|
-
|
|
1634
|
-
run_callbacks(:after_tool_result, result)
|
|
2791
|
+
run_callbacks(:after_tool_result, result.is_a?(Tool::Halt) ? result.content : result)
|
|
1635
2792
|
result
|
|
1636
2793
|
end
|
|
1637
2794
|
|
|
2795
|
+
def run_around_tool_call(tool_call, &execute)
|
|
2796
|
+
ran = false
|
|
2797
|
+
result = nil
|
|
2798
|
+
innermost = lambda do
|
|
2799
|
+
result = execute.call unless ran
|
|
2800
|
+
ran = true
|
|
2801
|
+
result
|
|
2802
|
+
end
|
|
2803
|
+
outcome = -> { ran ? result : { error: "The #{tool_call.name} call did not run." } }
|
|
2804
|
+
chain = @callbacks[:around_tool_call].reverse.reduce(innermost) do |inner, callback|
|
|
2805
|
+
lambda do
|
|
2806
|
+
callback.call(tool_call) { inner.call }
|
|
2807
|
+
outcome.call
|
|
2808
|
+
end
|
|
2809
|
+
end
|
|
2810
|
+
chain.call
|
|
2811
|
+
outcome.call
|
|
2812
|
+
end
|
|
2813
|
+
|
|
1638
2814
|
def add_tool_result_message(tool_call, result)
|
|
1639
|
-
|
|
2815
|
+
halted = result.is_a?(Tool::Halt)
|
|
2816
|
+
result = result.content if halted
|
|
2817
|
+
content, attachments = split_tool_result(result)
|
|
2818
|
+
content = @file_references.spill(tool_for(tool_call), tool_call, content) if @file_references
|
|
2819
|
+
content = context_budget_for_model.cap(content) if @context_budget
|
|
1640
2820
|
mcp_result = result if result.is_a?(MCP::Result) && result.ui_uri
|
|
1641
|
-
message = add_message(role: :tool, content:, attachments:, tool_call_id: tool_call.id,
|
|
2821
|
+
message = add_message(role: :tool, content:, attachments:, tool_call_id: tool_call.id,
|
|
2822
|
+
provider_call_id: tool_call.provider_call_id, mcp_result:,
|
|
2823
|
+
finish_reason: (:halted if halted))
|
|
1642
2824
|
run_callbacks(:after_message, message)
|
|
1643
2825
|
message
|
|
1644
2826
|
end
|
|
1645
2827
|
|
|
2828
|
+
# The tool has run, so a result that cannot be sent goes back as an
|
|
2829
|
+
# error: raising would leave the call pending and run it again.
|
|
2830
|
+
def split_tool_result(result)
|
|
2831
|
+
Tool.split_result(result)
|
|
2832
|
+
rescue StandardError => e
|
|
2833
|
+
Tool.split_result({ error: e.message })
|
|
2834
|
+
end
|
|
2835
|
+
|
|
1646
2836
|
def execute_tool(tool_call)
|
|
1647
|
-
tool =
|
|
1648
|
-
if tool.nil?
|
|
1649
|
-
return {
|
|
1650
|
-
error: "Model tried to call unavailable tool `#{tool_call.name}`. " \
|
|
1651
|
-
"Available tools: #{tools.keys.to_json}."
|
|
1652
|
-
}
|
|
1653
|
-
end
|
|
2837
|
+
tool = tool_for(tool_call)
|
|
2838
|
+
return { error: unavailable_tool_error(tool_call.qualified_name) } if tool.nil?
|
|
1654
2839
|
|
|
1655
2840
|
args = tool_call.arguments
|
|
1656
2841
|
payload = {
|
|
@@ -1663,7 +2848,8 @@ module RubyLLM
|
|
|
1663
2848
|
tool_call: tool_call,
|
|
1664
2849
|
tool_name: tool.name,
|
|
1665
2850
|
tool_arguments: args,
|
|
1666
|
-
tool_call_id: tool_call.id
|
|
2851
|
+
tool_call_id: tool_call.id,
|
|
2852
|
+
**agent_fields
|
|
1667
2853
|
}
|
|
1668
2854
|
|
|
1669
2855
|
RubyLLM.instrument('tool_call.ruby_llm', payload, config: @config) do |event|
|
|
@@ -1677,6 +2863,16 @@ module RubyLLM
|
|
|
1677
2863
|
end
|
|
1678
2864
|
end
|
|
1679
2865
|
|
|
2866
|
+
# Names a few close tools rather than every tool, which can run to
|
|
2867
|
+
# thousands of characters in a chat with many.
|
|
2868
|
+
def unavailable_tool_error(name)
|
|
2869
|
+
close = DidYouMean::SpellChecker.new(dictionary: tools.keys.map(&:to_s)).correct(name).first(3)
|
|
2870
|
+
message = "There is no tool named `#{name}`."
|
|
2871
|
+
message += " Did you mean #{close.map { |tool| "`#{tool}`" }.join(', ')}?" if close.any?
|
|
2872
|
+
message += " Find tools with `#{Tools::Search.tool_name}`." if tool_search_tool
|
|
2873
|
+
message
|
|
2874
|
+
end
|
|
2875
|
+
|
|
1680
2876
|
def progress_listener(tool_call)
|
|
1681
2877
|
return if @callbacks.fetch(:after_tool_progress, []).empty?
|
|
1682
2878
|
|
|
@@ -1685,15 +2881,55 @@ module RubyLLM
|
|
|
1685
2881
|
|
|
1686
2882
|
def invoke_tool(tool, tool_call, arguments)
|
|
1687
2883
|
input = tool_call_input(tool_call)
|
|
1688
|
-
result =
|
|
1689
|
-
|
|
2884
|
+
result = Tool.asking(tool, input) do
|
|
2885
|
+
rescuing_tool(tool) do
|
|
2886
|
+
input ? tool.resume_call(input, arguments, tool_call:) : tool.call(**arguments, tool_call:)
|
|
2887
|
+
end
|
|
2888
|
+
end
|
|
2889
|
+
return pause_tool_call(tool_call, result.to_h) if result.is_a?(Task)
|
|
1690
2890
|
|
|
1691
2891
|
record_tool_call_input(tool_call, nil) if input
|
|
1692
|
-
result
|
|
1693
|
-
rescue
|
|
2892
|
+
with_decline_notes(result, input)
|
|
2893
|
+
rescue InputRequiredError => e
|
|
1694
2894
|
pause_tool_call(tool_call, e.to_h)
|
|
1695
2895
|
end
|
|
1696
2896
|
|
|
2897
|
+
# The one place a tool's Tool.rescue_from handlers run, so they cover
|
|
2898
|
+
# every call a chat makes, whether the tool overrides Tool#call or
|
|
2899
|
+
# Tool#execute. A question or a cancellation is how a call pauses or
|
|
2900
|
+
# stops, not a failure, so it never reaches a handler; a handler may
|
|
2901
|
+
# end the turn with Tool#halt.
|
|
2902
|
+
def rescuing_tool(tool)
|
|
2903
|
+
catch(Tool::HALT) do
|
|
2904
|
+
yield
|
|
2905
|
+
rescue InputRequiredError, CancelledError
|
|
2906
|
+
raise
|
|
2907
|
+
rescue StandardError => e
|
|
2908
|
+
tool.rescue_with_handler(e)
|
|
2909
|
+
end
|
|
2910
|
+
end
|
|
2911
|
+
|
|
2912
|
+
def with_decline_notes(result, input)
|
|
2913
|
+
notes = Array(input&.[]('requests')).filter_map do |request|
|
|
2914
|
+
note = request.dig('response', 'note')
|
|
2915
|
+
"The user declined: #{note_text(note)}" if note
|
|
2916
|
+
end
|
|
2917
|
+
notes.empty? ? result : noted_result(result, notes)
|
|
2918
|
+
end
|
|
2919
|
+
|
|
2920
|
+
def noted_result(result, notes)
|
|
2921
|
+
case result
|
|
2922
|
+
when Tool::Halt then Tool::Halt.new(noted_result(result.content, notes))
|
|
2923
|
+
when MCP::Result
|
|
2924
|
+
blocks = notes.map { |note| { 'type' => 'text', 'text' => note } }
|
|
2925
|
+
MCP::Result.new(result.to_h.merge('content' => [*result.to_h['content'], *blocks]), result.ui_uri)
|
|
2926
|
+
else
|
|
2927
|
+
content, attachments = split_tool_result(result)
|
|
2928
|
+
text = [content, *notes].reject(&:empty?).join("\n\n")
|
|
2929
|
+
attachments.empty? ? text : [text, *attachments]
|
|
2930
|
+
end
|
|
2931
|
+
end
|
|
2932
|
+
|
|
1697
2933
|
def pause_tool_call(tool_call, state)
|
|
1698
2934
|
record_tool_call_input(tool_call, state)
|
|
1699
2935
|
PAUSED
|
|
@@ -1713,15 +2949,18 @@ module RubyLLM
|
|
|
1713
2949
|
end
|
|
1714
2950
|
|
|
1715
2951
|
def task_for(tool_call, state)
|
|
1716
|
-
tool =
|
|
1717
|
-
|
|
2952
|
+
tool = tool_for(tool_call)
|
|
2953
|
+
return tool.task(state, tool_call:) if tool
|
|
2954
|
+
return MCP::Task.load(nil, state, tool_call:) if state['task'].key?('taskId')
|
|
2955
|
+
|
|
2956
|
+
Task.load(state, tool_call:)
|
|
1718
2957
|
end
|
|
1719
2958
|
|
|
1720
2959
|
def cancel_tasks
|
|
1721
2960
|
response = pending_tool_response
|
|
1722
2961
|
return unless response
|
|
1723
2962
|
|
|
1724
|
-
pending_tool_calls(response).
|
|
2963
|
+
pending_tool_calls(response).each do |tool_call|
|
|
1725
2964
|
state = tool_call_input(tool_call)
|
|
1726
2965
|
next unless state&.key?('task')
|
|
1727
2966
|
|
|
@@ -1730,32 +2969,81 @@ module RubyLLM
|
|
|
1730
2969
|
end
|
|
1731
2970
|
end
|
|
1732
2971
|
|
|
2972
|
+
def close_unstarted_tool_calls
|
|
2973
|
+
response = pending_tool_response
|
|
2974
|
+
return unless response
|
|
2975
|
+
|
|
2976
|
+
pending_tool_calls(response).each do |tool_call|
|
|
2977
|
+
next if running_elsewhere?(tool_call)
|
|
2978
|
+
|
|
2979
|
+
record_tool_call_input(tool_call, nil) if tool_call_input(tool_call)
|
|
2980
|
+
run_callbacks(:before_message)
|
|
2981
|
+
run_callbacks(:after_message, add_message(unfinished_result(tool_call).mark_cancelled))
|
|
2982
|
+
end
|
|
2983
|
+
end
|
|
2984
|
+
|
|
1733
2985
|
def cancel_task(task)
|
|
1734
2986
|
task.cancel
|
|
1735
2987
|
rescue Error, ConfigurationError, Faraday::Error => e
|
|
1736
|
-
RubyLLM.logger.debug { "RubyLLM could not cancel task #{task.id}: #{e.message}" }
|
|
2988
|
+
RubyLLM.logger.debug { "RubyLLM could not cancel the task of tool call #{task.tool_call&.id}: #{e.message}" }
|
|
1737
2989
|
end
|
|
1738
2990
|
|
|
1739
2991
|
def tool_call_input(tool_call)
|
|
1740
|
-
@
|
|
2992
|
+
@tool_call_state.input(tool_call)
|
|
1741
2993
|
end
|
|
1742
2994
|
|
|
1743
2995
|
def record_tool_call_input(tool_call, input)
|
|
1744
|
-
@
|
|
1745
|
-
@input_recorder&.call(tool_call, input)
|
|
2996
|
+
@tool_call_state.record_input(tool_call, input)
|
|
1746
2997
|
end
|
|
1747
2998
|
|
|
1748
|
-
def
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
2999
|
+
def unanswered_questions(tool_call)
|
|
3000
|
+
Array(tool_call_input(tool_call)&.[]('requests')).filter_map do |data|
|
|
3001
|
+
Question.from_h(data, tool_call:, chat: self) unless data['response']
|
|
3002
|
+
end
|
|
3003
|
+
end
|
|
3004
|
+
|
|
3005
|
+
def pending_question(question)
|
|
3006
|
+
id = question.respond_to?(:id) ? question.id : question.to_s
|
|
3007
|
+
pending_questions.find { |pending| pending.id == id } ||
|
|
3008
|
+
(asked_question?(id) ? nil : raise(ArgumentError, "Unknown question: #{id.inspect}"))
|
|
3009
|
+
end
|
|
1752
3010
|
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
3011
|
+
def asked_question?(id)
|
|
3012
|
+
[id, id.rpartition('/').first].any? { |tool_call_id| find_tool_call(tool_call_id) }
|
|
3013
|
+
end
|
|
3014
|
+
|
|
3015
|
+
def record_answer(question, response)
|
|
3016
|
+
@tool_call_state.settle(question.tool_call) { |input| question.answered_input(input, response) }
|
|
3017
|
+
end
|
|
3018
|
+
|
|
3019
|
+
# Records +response+ to +question+ and returns whether it did. An
|
|
3020
|
+
# approval is approved or denied only while no decision came first, so
|
|
3021
|
+
# of two people deciding at once, the first one's decision stands.
|
|
3022
|
+
def settle_question(question, response)
|
|
3023
|
+
unless question.approval?
|
|
3024
|
+
record_answer(question, response)
|
|
3025
|
+
return true
|
|
1756
3026
|
end
|
|
1757
|
-
|
|
1758
|
-
|
|
3027
|
+
|
|
3028
|
+
@tool_call_state.exclusively do
|
|
3029
|
+
next false unless approval_pending?(question.tool_call)
|
|
3030
|
+
|
|
3031
|
+
response == Question::ACCEPTED ? approve(question) : refuse(question.tool_call, response['note'])
|
|
3032
|
+
true
|
|
3033
|
+
end
|
|
3034
|
+
end
|
|
3035
|
+
|
|
3036
|
+
def refuse(tool_call, note)
|
|
3037
|
+
record_tool_call_decision(tool_call, false)
|
|
3038
|
+
@tool_call_state.record_decline_note(tool_call, note) if note
|
|
3039
|
+
end
|
|
3040
|
+
|
|
3041
|
+
def decline_note(tool_call)
|
|
3042
|
+
@tool_call_state.decline_note(tool_call)
|
|
3043
|
+
end
|
|
3044
|
+
|
|
3045
|
+
def note_text(note)
|
|
3046
|
+
note.is_a?(Hash) ? JSON.generate(note) : note
|
|
1759
3047
|
end
|
|
1760
3048
|
|
|
1761
3049
|
def apply_tool_choice(choice)
|
|
@@ -1763,16 +3051,41 @@ module RubyLLM
|
|
|
1763
3051
|
@tool_prefs[:choice] = nil
|
|
1764
3052
|
else
|
|
1765
3053
|
normalized_choice = normalize_tool_choice(choice)
|
|
1766
|
-
|
|
1767
|
-
unless valid_tool_choices.include?(normalized_choice)
|
|
1768
|
-
raise InvalidToolChoiceError,
|
|
1769
|
-
"Invalid tool choice: #{choice}. Valid choices are: #{valid_tool_choices.join(', ')}"
|
|
1770
|
-
end
|
|
1771
|
-
|
|
3054
|
+
check_tool_choice(normalized_choice, choice) if mcp.empty?
|
|
1772
3055
|
@tool_prefs[:choice] = normalized_choice
|
|
1773
3056
|
end
|
|
1774
3057
|
end
|
|
1775
3058
|
|
|
3059
|
+
# A chat with MCP servers checks its choice once it lists their tools,
|
|
3060
|
+
# so building it never contacts them.
|
|
3061
|
+
def check_tool_choice(choice, given = choice)
|
|
3062
|
+
return if choice.nil? || TOOL_CHOICE_MODES.include?(choice) || tools.key?(choice)
|
|
3063
|
+
|
|
3064
|
+
invalid_tool_choice("Invalid tool choice: #{given}. Valid choices are: " \
|
|
3065
|
+
"#{(TOOL_CHOICE_MODES + tools.keys).join(', ')}")
|
|
3066
|
+
end
|
|
3067
|
+
|
|
3068
|
+
# A forced call with no tools to call would reach the provider without
|
|
3069
|
+
# the constraint, since protocols drop a choice when there are no tools.
|
|
3070
|
+
def check_requested_tool_choice
|
|
3071
|
+
return if mcp.empty?
|
|
3072
|
+
|
|
3073
|
+
check_tool_choice(@tool_prefs[:choice])
|
|
3074
|
+
invalid_tool_choice('Tool choice required needs a tool, and the chat has none') if
|
|
3075
|
+
@tool_prefs[:choice] == :required && tools.empty?
|
|
3076
|
+
end
|
|
3077
|
+
|
|
3078
|
+
def invalid_tool_choice(message)
|
|
3079
|
+
unreachable = mcp.unreachable
|
|
3080
|
+
message += ". These MCP servers can't be reached right now: #{unreachable.join(', ')}" if unreachable.any?
|
|
3081
|
+
raise InvalidToolChoiceError, message
|
|
3082
|
+
end
|
|
3083
|
+
|
|
3084
|
+
def apply_tool_concurrency(value)
|
|
3085
|
+
@concurrency_chosen = !value.nil?
|
|
3086
|
+
@concurrency = normalize_tool_concurrency(value.nil? ? @config.tool_concurrency : value)
|
|
3087
|
+
end
|
|
3088
|
+
|
|
1776
3089
|
def normalize_tool_concurrency(concurrency)
|
|
1777
3090
|
return nil if concurrency.nil? || concurrency == false
|
|
1778
3091
|
return :threads if concurrency == true
|
|
@@ -1785,6 +3098,13 @@ module RubyLLM
|
|
|
1785
3098
|
"Available modes: #{ToolConcurrency::MODES.join(', ')}"
|
|
1786
3099
|
end
|
|
1787
3100
|
|
|
3101
|
+
def apply_tool_calls(value)
|
|
3102
|
+
cap = value if value.is_a?(Integer) && value > 1
|
|
3103
|
+
calls = normalize_calls(value) unless value.nil? || cap
|
|
3104
|
+
@tool_call_cap = cap
|
|
3105
|
+
@tool_prefs[:calls] = calls
|
|
3106
|
+
end
|
|
3107
|
+
|
|
1788
3108
|
def normalize_calls(calls)
|
|
1789
3109
|
case calls
|
|
1790
3110
|
when :many, 'many'
|
|
@@ -1792,23 +3112,32 @@ module RubyLLM
|
|
|
1792
3112
|
when :one, 'one', 1
|
|
1793
3113
|
:one
|
|
1794
3114
|
else
|
|
1795
|
-
raise ArgumentError,
|
|
3115
|
+
raise ArgumentError,
|
|
3116
|
+
"Invalid calls value: #{calls.inspect}. Valid values are: :many, :one, or a positive integer"
|
|
1796
3117
|
end
|
|
1797
3118
|
end
|
|
1798
3119
|
|
|
3120
|
+
def normalize_rounds(rounds)
|
|
3121
|
+
return rounds if rounds.nil? || (rounds.is_a?(Integer) && rounds.positive?)
|
|
3122
|
+
|
|
3123
|
+
raise ArgumentError, "Invalid rounds value: #{rounds.inspect}. Valid values are positive integers"
|
|
3124
|
+
end
|
|
3125
|
+
|
|
1799
3126
|
def normalize_tool_choice(choice)
|
|
1800
3127
|
return choice.to_sym if choice.is_a?(String) || choice.is_a?(Symbol)
|
|
1801
3128
|
return tool_name_for_choice_class(choice) if choice.is_a?(Class)
|
|
3129
|
+
return choice.qualified_name.to_sym if choice.is_a?(Tool)
|
|
1802
3130
|
|
|
1803
3131
|
choice.respond_to?(:name) ? choice.name.to_sym : choice.to_sym
|
|
1804
3132
|
end
|
|
1805
3133
|
|
|
1806
3134
|
def tool_name_for_choice_class(tool_class)
|
|
1807
|
-
matched_tool_name = tools.find { |_name, tool| tool.is_a?(tool_class) }&.first
|
|
3135
|
+
matched_tool_name = @tools.find { |_name, tool| tool.is_a?(tool_class) }&.first
|
|
1808
3136
|
return matched_tool_name if matched_tool_name
|
|
1809
|
-
return tool_class.
|
|
3137
|
+
return tool_class.name.to_s.to_sym unless tool_class.respond_to?(:tool_name)
|
|
1810
3138
|
|
|
1811
|
-
tool_class.
|
|
3139
|
+
namespace = tool_class.namespace if tool_class.respond_to?(:namespace)
|
|
3140
|
+
[namespace, tool_class.tool_name].compact.join('_').to_sym
|
|
1812
3141
|
end
|
|
1813
3142
|
|
|
1814
3143
|
def forced_tool_choice?
|
|
@@ -1836,6 +3165,14 @@ module RubyLLM
|
|
|
1836
3165
|
end
|
|
1837
3166
|
end
|
|
1838
3167
|
|
|
3168
|
+
# What a process leaves behind before the provider answers, unlike a
|
|
3169
|
+
# blank answer, which carries its finish reason or usage.
|
|
3170
|
+
def placeholder?(message)
|
|
3171
|
+
return false unless message && blank_response?(message) && !unfinished?(message)
|
|
3172
|
+
|
|
3173
|
+
message.finish_reason.nil? && message.tokens.input.nil?
|
|
3174
|
+
end
|
|
3175
|
+
|
|
1839
3176
|
def blank_response?(message)
|
|
1840
3177
|
message.role == :assistant && !message.tool_call? && message.content.to_s.strip.empty? &&
|
|
1841
3178
|
message.attachments.empty? && message.thinking.nil? && message.server_tool_calls.empty? &&
|
|
@@ -1858,7 +3195,7 @@ module RubyLLM
|
|
|
1858
3195
|
end
|
|
1859
3196
|
|
|
1860
3197
|
def awaiting_approval_names
|
|
1861
|
-
|
|
3198
|
+
pending_questions.select(&:approval?).map { |question| question.tool_call.name }.uniq
|
|
1862
3199
|
end
|
|
1863
3200
|
end
|
|
1864
3201
|
end
|