Module: LLM::Context::Deserializer Private

Included in:
LLM::Context
Defined in:
lib/llm/context/deserializer.rb

This module is part of a private API. You should avoid using this module if possible, as it may be removed or be changed in the future.

Instance Method Summary collapse

Instance Method Details

#deserialize(path: nil, string: nil, data: nil) ⇒ LLM::Context Also known as: restore

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.

Restore a saved context state.

The context_used and context_window keys carried by a payload are projections for queryability. They are deliberately ignored here: the runtime derives both from the messages and the registry, so a payload can never seed them.

The payload has to have been written by this version, which LLM::Context.validate_schema! asserts: the payload is not backwards compatible, so a payload from any other version - older, newer, or carrying no version at all - is refused rather than read on a best-effort basis.

Parameters:

  • path (String, nil) (defaults to: nil) —

    The path to a JSON file

  • string (String, nil) (defaults to: nil) —

    A raw JSON string

  • data (Hash, nil) (defaults to: nil) —

    A parsed context payload

Returns:

Raises:

  • (LLM::Error) —

    When the payload was written by another version

  • (SystemCallError) —

    Might raise a number of SystemCallError subclasses



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/llm/context/deserializer.rb', line 31

def deserialize(path: nil, string: nil, data: nil)
  ctx = if data
    data
  elsif path.nil? and string.nil?
    raise ArgumentError, "a path, string, or data payload is required"
  elsif path
    LLM.json.load(::File.binread(path))
  else
    LLM.json.load(string)
  end
  LLM::Context.validate_schema!(version: ctx["schema_version"])
  @id = ctx["id"] || @id
  @created_at = nil
  @messages.concat [*ctx["messages"]].map { deserialize_message(_1) }
  @compacted = !!ctx["compacted"]
  self
end