Class: Ask::Agent::SystemContext

Inherits:
Object
  • Object
show all
Defined in:
lib/ask/agent/system_context.rb

Overview

Composes typed context sources into a coherent system prompt.

At initialization, each source renders its baseline text. Sources are ordered by their key for deterministic output.

At any point, changes returns a list of update texts for sources whose values have changed since the last snapshot. This enables mid-conversation updates without rebuilding the entire prompt.

Examples:

ctx = SystemContext.new([
  InstructionsSource.new("You are a helper."),
  SkillsListSource.new(registry),
  DateSource.new,
])

prompt = ctx.render     # full system prompt
updates = ctx.changes   # nil if nothing changed

Defined Under Namespace

Classes: Snapshot

Instance Method Summary collapse

Constructor Details

#initialize(sources) ⇒ SystemContext

Returns a new instance of SystemContext.



26
27
28
29
30
# File 'lib/ask/agent/system_context.rb', line 26

def initialize(sources)
  @sources = sources
  @snapshots = {}
  take_snapshot
end

Instance Method Details

#[](key) ⇒ ContextSource?

Access a source by key.

Parameters:

  • key (String)

Returns:



63
64
65
# File 'lib/ask/agent/system_context.rb', line 63

def [](key)
  @sources.find { |s| s.key == key }
end

#changesArray<String>?

Detect changes since the last snapshot. Returns update texts for sources whose value changed, or nil.

Returns:

  • (Array<String>, nil)


46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/ask/agent/system_context.rb', line 46

def changes
  updates = []
  @sources.each do |source|
    prev_value = @snapshots[source.key]&.value
    current_value = source.load
    next if prev_value == current_value

    update_text = source.update(prev_value, current_value)
    updates << update_text if update_text
    @snapshots[source.key] = Snapshot.new(key: source.key, value: current_value)
  end
  updates.any? ? updates : nil
end

#renderString

Render the full baseline system prompt.

Returns:

  • (String)


34
35
36
37
38
39
40
41
# File 'lib/ask/agent/system_context.rb', line 34

def render
  parts = @sources.map do |source|
    value = @snapshots[source.key]&.value
    text = source.baseline(value) rescue nil
    text
  end
  parts.compact.join("\n\n")
end