Class: LLM::Context
- Inherits:
-
Object
- Object
- LLM::Context
- Includes:
- Deserializer, Serializer
- Defined in:
- lib/llm/context.rb,
lib/llm/context/serializer.rb,
lib/llm/context/deserializer.rb
Overview
LLM::Context is the low-level stateful execution boundary in llm.rb. Most users should start with Agent, which wraps Context and manages tool loops automatically. Use Context directly when you need manual control over tool execution.
It holds the evolving runtime state for an LLM workflow: conversation history, tool calls and returns, schema and streaming configuration, accumulated usage, and request ownership for interruption.
This is broader than prompt context alone. A context is the object that lets one-off prompts, streaming turns, tool execution, persistence, retries, and serialized long-lived workflows all run through the same model.
A context can drive the chat completions API that all providers support or the Responses API on providers that expose it.
Defined Under Namespace
Modules: Deserializer, Serializer
Instance Attribute Summary collapse
-
#compacted ⇒ Boolean
(also: #compacted?)
private
Returns whether the context has been compacted and no later model response has cleared that state.
-
#llm ⇒ LLM::Provider
readonly
Returns a provider.
-
#messages ⇒ LLM::Buffer<LLM::Message>
readonly
Returns the accumulated message history for this context.
-
#mode ⇒ Symbol
readonly
Returns the context mode.
Instance Method Summary collapse
-
#ask(prompt, options = {}) {|String| ... } ⇒ LLM::Response
Ask a question and return the content string directly.
-
#compactor ⇒ LLM::Compactor
Returns a context compactor.
-
#context_window ⇒ Integer
Returns the model's context window.
-
#cost ⇒ LLM::Cost
Returns an approximate cost for a given context based on both the provider, and model.
-
#guard ⇒ Class<LLM::Guard>
Returns the configured guard class.
-
#image_url(url) ⇒ LLM::Object
Recongize an object as a URL to an image.
-
#initialize(llm, params = {}) ⇒ Context
constructor
A new instance of Context.
- #inspect ⇒ String
-
#interrupt! ⇒ nil
(also: #cancel!)
Interrupt the active request, if any.
-
#local_file(path) ⇒ LLM::Object
Recongize an object as a local file.
-
#model ⇒ String
Returns the model a Context is actively using.
-
#params ⇒ Hash
Returns the default params for this context.
-
#pending_functions ⇒ Array<LLM::Function>
Returns an array of functions that can be called.
-
#pending_functions? ⇒ Boolean
Returns whether there is pending tool work in this context.
-
#prompt(&b) ⇒ LLM::Prompt
(also: #build_prompt)
Build a role-aware prompt for a single request.
-
#remote_file(res) ⇒ LLM::Object
Reconginize an object as a remote file.
-
#returns ⇒ Array<LLM::Function::Return>
Returns tool returns accumulated in this context.
-
#serialize(path:) ⇒ void
(also: #save)
Save the current context state.
-
#spawn(function, strategy) ⇒ LLM::Function::Task
Spawns a function through the context.
-
#stream ⇒ LLM::Stream, ...
Returns a stream object, or nil.
-
#talk(prompt, params = {}) ⇒ LLM::Response
Interact with the context via the chat completions API.
- #to_h ⇒ Hash
- #to_json ⇒ String
-
#tracer ⇒ LLM::Tracer
Returns an LLM tracer.
- #tracer=(other) ⇒ void
-
#transformer ⇒ Class<LLM::Transformer>
Returns the configured transformer class.
-
#usage ⇒ LLM::Object
Returns token usage accumulated in this context.
-
#wait(strategy, except: []) ⇒ Array<LLM::Function::Return>
Waits for queued tool work to finish.
Methods included from Deserializer
Constructor Details
#initialize(llm, params = {}) ⇒ Context
Returns a new instance of Context.
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 |
# File 'lib/llm/context.rb', line 98 def initialize(llm, params = {}) params = {}.merge!(params) @llm = llm @mode = params.delete(:mode) || (llm.name == :openai ? :responses : :completions) tools = [*params.delete(:tools), *load_skills(params.delete(:skills))] @params = {model: llm.default_model, schema: nil}.compact.merge!(params) @params[:tools] = tools unless tools.empty? @params[:store] ||= false if @mode == :responses @messages = LLM::Buffer.new(llm) extra = @params.slice(:model, :tools).merge!(ctx: self, tracer:) @params[:stream] = LLM::Stream.try(@params[:stream], extra:) @compactor = { klass: params.delete(:compactor) || LLM::Compactor::Null, options: params.delete(:compactor_options) || {} } @transformer = { klass: params.delete(:transformer) || LLM::Transformer::Null, options: params.delete(:transformer_options) || {} } @guard = { klass: params.delete(:guard) || LLM::Guard::Null, options: params.delete(:guard_options) || {} } end |
Instance Attribute Details
#compacted ⇒ Boolean Also known as: compacted?
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Returns whether the context has been compacted and no later model response has cleared that state.
142 143 144 |
# File 'lib/llm/context.rb', line 142 def compacted @compacted end |
#llm ⇒ LLM::Provider (readonly)
Returns a provider
63 64 65 |
# File 'lib/llm/context.rb', line 63 def llm @llm end |
#messages ⇒ LLM::Buffer<LLM::Message> (readonly)
Returns the accumulated message history for this context
58 59 60 |
# File 'lib/llm/context.rb', line 58 def @messages end |
#mode ⇒ Symbol (readonly)
Returns the context mode
68 69 70 |
# File 'lib/llm/context.rb', line 68 def mode @mode end |
Instance Method Details
#ask(prompt, options = {}) {|String| ... } ⇒ LLM::Response
Ask a question and return the content string directly.
Accepts with: for file attachments and a block for streaming.
This interface is compatible with RubyLLM's ask method.
217 218 219 220 221 222 223 224 225 226 227 228 229 |
# File 'lib/llm/context.rb', line 217 def ask(prompt, = {}, &block) = {with: nil, stream: nil}.merge!( || {}) with, stream = .values_at(:with, :stream) prompt = with ? [prompt, [*with].map { local_file(_1) }] : prompt target = if block blk = block.dup blk.singleton_class.alias_method(:<<, :call) blk else stream end target ? talk(prompt, stream: target) : talk(prompt) end |
#compactor ⇒ LLM::Compactor
Returns a context compactor
133 134 135 |
# File 'lib/llm/context.rb', line 133 def compactor @compactor[:klass] end |
#context_window ⇒ Integer
This method returns 0 when the provider or model can't be found within Registry.
Returns the model's context window. The context window is the maximum amount of input and output tokens a model can consider in a single request.
487 488 489 490 491 492 493 494 |
# File 'lib/llm/context.rb', line 487 def context_window LLM .registry_for(llm) .limit(model:) .context rescue LLM::NoSuchModelError, LLM::NoSuchRegistryError 0 end |
#cost ⇒ LLM::Cost
Returns an approximate cost for a given context based on both the provider, and model
475 476 477 |
# File 'lib/llm/context.rb', line 475 def cost LLM::Cost.from(self) end |
#guard ⇒ Class<LLM::Guard>
Returns the configured guard class.
Guards are context-level supervisors for agentic execution. A guard can inspect the runtime state and decide whether pending tool work should be blocked before the context keeps looping.
The guard is stamped onto the functions the context binds, so it runs
whenever a task is spawned — including tool calls queued from a stream
via Stream#on_tool_call. A blocked call yields its in-band
guard_error return without executing.
The built-in implementation is LLM::Guard::Loop, which
detects repeated tool-call patterns and turns them into in-band
guard_error tool returns.
162 163 164 |
# File 'lib/llm/context.rb', line 162 def guard @guard[:klass] end |
#image_url(url) ⇒ LLM::Object
Recongize an object as a URL to an image
386 387 388 |
# File 'lib/llm/context.rb', line 386 def image_url(url) LLM::Object.from(value: url, kind: :image_url) end |
#inspect ⇒ String
233 234 235 236 237 |
# File 'lib/llm/context.rb', line 233 def inspect "#<#{LLM::Utils.object_id(self)} " \ "@llm=#{@llm.class}, @mode=#{@mode.inspect}, @params=#{@params.inspect}, " \ "@messages=#{@messages.inspect}>" end |
#interrupt! ⇒ nil Also known as: cancel!
Interrupt the active request, if any. This is inspired by Go's context cancellation model.
329 330 331 332 333 334 335 336 |
# File 'lib/llm/context.rb', line 329 def interrupt! llm.interrupt!(@owner) queue&.interrupt! pending_functions.each(&:interrupt!) @queue = nil @owner = nil nil end |
#local_file(path) ⇒ LLM::Object
Recongize an object as a local file
396 397 398 |
# File 'lib/llm/context.rb', line 396 def local_file(path) LLM::Object.from(value: LLM.File(path), kind: :local_file) end |
#model ⇒ String
Returns the model a Context is actively using
435 436 437 |
# File 'lib/llm/context.rb', line 435 def model .find(&:assistant?)&.model || @params[:model] end |
#params ⇒ Hash
Returns the default params for this context
126 127 128 |
# File 'lib/llm/context.rb', line 126 def params @params.dup end |
#pending_functions ⇒ Array<LLM::Function>
Returns an array of functions that can be called
242 243 244 245 246 247 248 249 250 251 252 253 254 255 |
# File 'lib/llm/context.rb', line 242 def pending_functions return_ids = returns.map(&:id) guard = @guard[:klass].new(self) @messages .select(&:assistant?) .flat_map do |msg| fns = msg.functions.select { _1.pending? && !return_ids.include?(_1.id) } fns.each do |fn| fn.tracer = tracer fn.model = msg.model fn.guard = guard end end.extend(LLM::Function::Array) end |
#pending_functions? ⇒ Boolean
Returns whether there is pending tool work in this context. This prefers queued streamed tool work when present, and otherwise falls back to unresolved functions derived from the message history.
262 263 264 265 |
# File 'lib/llm/context.rb', line 262 def pending_functions? pending = queue (pending && !pending.empty?) || pending_functions.any? end |
#prompt(&b) ⇒ LLM::Prompt Also known as: build_prompt
Build a role-aware prompt for a single request.
Prefer this method over #build_prompt. The older method name is kept for backward compatibility.
375 376 377 |
# File 'lib/llm/context.rb', line 375 def prompt(&b) LLM::Prompt.new(@llm, &b) end |
#remote_file(res) ⇒ LLM::Object
Reconginize an object as a remote file
406 407 408 |
# File 'lib/llm/context.rb', line 406 def remote_file(res) LLM::Object.from(value: res, kind: :remote_file) end |
#returns ⇒ Array<LLM::Function::Return>
Returns tool returns accumulated in this context
280 281 282 283 284 285 286 287 288 |
# File 'lib/llm/context.rb', line 280 def returns @messages .select(&:tool_return?) .flat_map do |msg| LLM::Function::Return === msg.content ? [msg.content] : [*msg.content].grep(LLM::Function::Return) end end |
#serialize(path:) ⇒ void Also known as: save
This method returns an undefined value.
Save the current context state
466 467 468 |
# File 'lib/llm/context.rb', line 466 def serialize(path:) ::File.binwrite path, LLM.json.dump(to_h) end |
#spawn(function, strategy) ⇒ LLM::Function::Task
Spawns a function through the context.
273 274 275 |
# File 'lib/llm/context.rb', line 273 def spawn(function, strategy) function.task(strategy) end |
#stream ⇒ LLM::Stream, ...
Returns a stream object, or nil
428 429 430 |
# File 'lib/llm/context.rb', line 428 def stream @stream || @params[:stream] end |
#talk(prompt, params = {}) ⇒ LLM::Response
Interact with the context via the chat completions API. This method immediately sends a request to the LLM and returns the response.
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 |
# File 'lib/llm/context.rb', line 188 def talk(prompt, params = {}) @owner = @llm.request_owner @compactor[:klass].new(self).call(**@compactor[:options]) repair!(@messages, prompt) prompt, params, res = mode == :responses ? respond(prompt, params) : complete(prompt, params) self.compacted = false if prompt.all?(&:tool_return?) @messages.concat prompt.map { LLM::Message.new(@llm.tool_role, _1.content, _1.extra) } else @messages.concat(prompt) end @messages.concat([res.choices[-1]].compact) res ensure @owner = nil end |
#to_h ⇒ Hash
441 442 443 444 445 446 447 448 |
# File 'lib/llm/context.rb', line 441 def to_h { schema_version: 1, model:, compacted:, messages: @messages.map { (_1) } } end |
#to_json ⇒ String
452 453 454 |
# File 'lib/llm/context.rb', line 452 def to_json(...) LLM.json.dump(to_h, ...) end |
#tracer ⇒ LLM::Tracer
Returns an LLM tracer
413 414 415 |
# File 'lib/llm/context.rb', line 413 def tracer @llm.tracer end |
#tracer=(other) ⇒ void
This method returns an undefined value.
421 422 423 |
# File 'lib/llm/context.rb', line 421 def tracer=(other) @llm.tracer = other || LLM::Tracer::Null.new(@llm) end |
#transformer ⇒ Class<LLM::Transformer>
Returns the configured transformer class.
Transformers rewrite the most recent message before it is sent to the provider.
173 174 175 |
# File 'lib/llm/context.rb', line 173 def transformer @transformer[:klass] end |
#usage ⇒ LLM::Object
Returns token usage accumulated in this context
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 |
# File 'lib/llm/context.rb', line 342 def usage if usage = @messages.find(&:assistant?)&.usage LLM::Object.from( input_tokens: usage.input_tokens || 0, output_tokens: usage.output_tokens || 0, reasoning_tokens: usage.reasoning_tokens || 0, input_audio_tokens: usage.input_audio_tokens || 0, output_audio_tokens: usage.output_audio_tokens || 0, input_image_tokens: usage.input_image_tokens || 0, cache_read_tokens: usage.cache_read_tokens || 0, cache_write_tokens: usage.cache_write_tokens || 0, total_tokens: usage.total_tokens || 0 ) else ZERO_USAGE end end |
#wait(strategy, except: []) ⇒ Array<LLM::Function::Return>
Waits for queued tool work to finish.
This prefers queued streamed tool work when the configured stream exposes a non-empty queue. Otherwise it falls back to waiting on the context's pending functions directly.
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 |
# File 'lib/llm/context.rb', line 305 def wait(strategy, except: []) if stream.queue.empty? ## # Every pending function is spawned as a task that checks its own # guard (stamped on the function) before running. Blocked tasks # yield their guard's return, so all pending calls still close. tools = except.empty? ? pending_functions : pending_functions - except @queue = tools.task(strategy) returns = @queue.wait emit_tool_returns(tools, returns) returns else @queue = stream.queue @queue.wait end ensure @queue = nil @stream = nil end |