class RubyLLM::Message
A Message is a single entry in a chat conversation: a user prompt, an assistant reply, a system instruction, or a tool result. Chat#ask returns the model’s reply as a Message, and Chat#messages holds the transcript as an array of them.
response = chat.ask "What is the capital of France?" response.role # => :assistant response.content # => "The capital of France is Paris." response.finish_reason # => :stop
A Message also carries everything else the provider returned: token usage (tokens), reasoning output (thinking), source citations (citations), and requested tool calls (tool_calls).
Constants
- ROLES
-
The valid message roles:
:system,:user,:assistant, and:tool.
Attributes
The files sent or returned with the message, as an array of Attachment objects.
Returns the cache lifetime given to this message’s boundary, such as "1h", or nil when the chat’s caching policy applies.
The source citations as an array of Citation objects, normalized across providers.
The message text as a String. Empty for assistant messages that only request tool calls.
The ContentFilter verdicts the provider reported on the request and this response, or an empty Array. Read them to see which filter ended a response that is content_filtered?. Only the live response carries them: to_h leaves them out, so a persisted chat never stores them.
Why the model stopped: :stop, :max_tokens, :tool_calls, or :content_filter. Any other reason comes through as the provider named it, as a lowercase Symbol, such as Anthropic’s :pause_turn or Gemini’s :malformed_function_call.
The MCP::Result behind a tool result message, when the MCP tool that returned it has a UI and did not fail, so your app can render the UI again with the result. nil otherwise.
The ID of the model that produced the message, nil on user messages.
The ID of the model that produced the message, nil on user messages.
The raw provider response: a Faraday::Response, or the result body Hash for messages retrieved from a Batch.
The role of the message: :system, :user, :assistant, or :tool.
The provider-executed tool steps in this response, as an array of ServerToolCall objects. Empty unless the chat enabled tools with Chat#with_provider_tools and the model used one.
The model’s reasoning output as a Thinking object, or nil when the provider returned none.
The ID of the tool call this message answers. Set only on tool result messages.
The tool calls the assistant requested, as an Enumerable of ToolCall objects in provider order, also readable by call ID. Empty when there are none.
response.tool_calls.map(&:name) # => ["weather"] response.tool_calls["call_1"] # => #<RubyLLM::ToolCall ...>
Public Instance Methods
Source
# File lib/ruby_llm/message.rb, line 390 def cache_until_here(ttl: nil) @cache_until_here = true @cache_ttl = ttl self end
Marks this message as an explicit prompt cache boundary. Providers with boundary controls use the conversation up to and including this message as the cacheable prefix. Pass ttl:, in any form Chat#with_caching takes, to give this boundary its own cache lifetime instead of the ttl: from Chat#with_caching, on providers that set a lifetime per boundary. Returns self.
chat.add_message(role: :user, content: long_context).cache_until_here chat.add_message(role: :user, content: handbook).cache_until_here(ttl: "1h")
To mark system instructions, pass cache_until_here: to Chat#with_instructions.
Source
# File lib/ruby_llm/message.rb, line 411 def cache_until_here? @cache_until_here end
Returns true if the message carries an explicit prompt cache boundary, false otherwise.
Source
# File lib/ruby_llm/message.rb, line 245 def cancelled? finish_reason == :cancelled end
Returns whether this is the part of a streamed reply the chat kept when it was cancelled (see Chat#cancel), or the result that closed a tool call it left unfinished. Its finish reason is :cancelled.
Source
# File lib/ruby_llm/message.rb, line 352 def content_filtered? finish_reason == :content_filter end
Returns true if a provider safety filter stopped the response, false otherwise.
Source
# File lib/ruby_llm/message.rb, line 371 def cost(model: nil) return ruby_llm_usage_cost if model.nil? && ruby_llm_usage_entries.any? return @supplied_cost if model.nil? && @supplied_cost Cost.new(tokens: model ? tokens.without_reported_cost : tokens, model: model || model_info) end
Returns a Cost pricing this message’s token usage in US dollars. Uses recorded attempt costs, an explicitly supplied cost:, or pricing from model_info. An explicit model: overrides those costs for repricing.
response.cost.total
Source
# File lib/ruby_llm/message.rb, line 238 def halted? finish_reason == :halted end
Returns whether a tool ended the turn with this result, with Tool#halt. Its finish reason is :halted.
Source
# File lib/ruby_llm/message.rb, line 339 def max_tokens? finish_reason == :max_tokens end
Returns true if the response was cut off by a token limit, false otherwise.
Source
# File lib/ruby_llm/message.rb, line 451 def model_info return @model_info if @model_info entry = ruby_llm_usage_entries.reverse.find(&:succeeded?) @model_info = if entry&.model RubyLLM.models.find(entry.model, provider: entry.provider) elsif model RubyLLM.models.find(model) end rescue ModelNotFoundError nil end
Source
# File lib/ruby_llm/message.rb, line 179 def parsed text = answer_text return if text.nil? || text.empty? @parsed ||= JSON.parse(text) end
Returns content parsed as JSON, memoized after the first call. Useful for reading structured output responses. When the provider marks part of the turn as commentary before the final answer, only the final answer is parsed.
response = chat.with_schema(PersonSchema).ask "Generate a person" response.parsed # => {"name" => "Alice", "age" => 30}
Source
# File lib/ruby_llm/message.rb, line 45 def provider @provider || ruby_llm_usage_entries.reverse.find(&:succeeded?)&.provider end
Returns the slug of the provider that produced the message, from its last successful attempt, or nil when none is recorded, as on user messages. A reply from a model given to Chat#with_fallbacks names that model’s provider.
Source
# File lib/ruby_llm/message.rb, line 258 def spilled_path Chat::FileReferences.spilled_path(content) if tool_result? end
Returns the path, in the chat’s files, of the whole of a tool result too long to send whole, or nil when the result went whole. A chat with a file store keeps such a result in a file and sends the model its start and this path (see Chat#with_file_store).
if (path = message.spilled_path) chat.file_store.read(path) end
Source
# File lib/ruby_llm/message.rb, line 328 def stopped? finish_reason == :stop && !tool_call? end
Returns true if finish_reason indicates the model finished normally, false otherwise. A turn that stopped to call tools is reported by tool_call_stop? instead, whatever the provider named it.
Source
# File lib/ruby_llm/message.rb, line 420 def to_h { role: role, content: content, attachments: list_to_h(attachments), model: model, provider: provider, cost: @supplied_cost && cost.to_h, reported_cost: tokens.reported_cost, tool_calls: tool_calls.empty? ? nil : tool_calls.transform_values(&:to_h), tool_call_id: tool_call_id, provider_call_id: @provider_call_id, thinking: thinking&.text, thinking_signature: thinking&.signature, citations: list_to_h(citations), server_tool_calls: list_to_h(server_tool_calls), raw_content: raw_content, raw_reasoning: raw_reasoning, phase: phase, continuation: continuation, mcp_result: mcp_result&.dump, finish_reason: finish_reason, cache_until_here: cache_until_here? || nil, cache_ttl: cache_ttl }.merge(tokens.to_h).compact end
Returns a Hash of the message’s attributes, with token counts merged in as :input_tokens, :output_tokens, and related keys. Omits nil values and empty attachment and citation lists. Includes :cost only when supplied explicitly, preserving unknown costs on round-trip, and :reported_cost when the provider reported its own price.
Source
# File lib/ruby_llm/message.rb, line 359 def tokens return @tokens if ruby_llm_usage_entries.empty? ruby_llm_usage_tokens end
Returns usage aggregated across every provider attempt that produced this message. Messages constructed by hand report the token counts they were built with.
Source
# File lib/ruby_llm/message.rb, line 293 def tool_call? !tool_calls.empty? end
Returns true if the assistant requested one or more tool calls, false otherwise.
Source
# File lib/ruby_llm/message.rb, line 346 def tool_call_stop? finish_reason == :tool_calls || (tool_call? && finish_reason == :stop) end
Returns true if the model stopped to request tool calls, false otherwise.
Source
# File lib/ruby_llm/message.rb, line 333 def tool_error_message tool_result_payload&.[]('error') end
Returns the error text of a failed tool result, or nil.
Source
# File lib/ruby_llm/message.rb, line 299 def tool_result? !tool_call_id.nil? && !tool_call_id.empty? end
Returns true if the message carries the result of a tool call, false otherwise.
Source
# File lib/ruby_llm/message.rb, line 317 def tool_results return [] unless tool_call? && conversation conversation.messages.select do |message| message.tool_result? && tool_calls.key?(message.tool_call_id) end end
Returns the tool result messages answering this message’s tool calls, or an empty array when it made none. Mirrors the tool_results association on acts_as_message records.
Source
# File lib/ruby_llm/message.rb, line 198 def web_sources return [] if server_tool_calls.empty? || provider.nil? Array(Provider.resolve(provider)&.web_sources(self)).uniq(&:url) end
Returns the pages a hosted web search returned for this message, as an array of WebSource objects with each address once. Reads what the message keeps, so a restored message answers the same. Empty when the message ran no search or its provider reports no sources.
response = chat.with_provider_tools(:web_search).ask "What changed in Ruby 4.0?" response.web_sources.map(&:url)
Sources come from the outside world and are not a safe allowlist on their own: a result can be attacker-controlled, and OpenAI can list a page the model chose to open beside what its search found.
Source
# File lib/ruby_llm/message.rb, line 214 def with(**changes) unknown = changes.keys - %i[content attachments] raise ArgumentError, "Message#with cannot change #{unknown.join(', ')}" if unknown.any? changes.reduce(self) do |message, (field, value)| field == :content ? message.with_content(value) : message.with_attachments(value) end end
Returns a copy of the message with the given fields changed, like Data#with. The message itself is left alone. Change content or attachments:
message.with(content: "[left out]")
New content also drops what holds the old text: on an assistant message its thinking, citations, server tool calls, raw response, and native response blocks, and on a tool result its MCP result. Raises ArgumentError for another field.