Class: Phronomy::Context::Builder

Inherits:
Object
  • Object
show all
Defined in:
lib/phronomy/context/builder.rb

Overview

Assembles ordered context sections (system prompt, knowledge, conversation history) within a given token budget.

Usage: builder = Phronomy::Context::Builder.new(budget: budget) builder.add_system(instructions_text) builder.add_knowledge(knowledge_text) builder.add_messages(messages) messages_to_send = builder.build

Sections are added in priority order. When the budget is exceeded the lower-priority tail of each section is truncated.

Instance Method Summary collapse

Constructor Details

#initialize(budget:) ⇒ Builder

Returns a new instance of Builder.

Parameters:



19
20
21
22
23
24
# File 'lib/phronomy/context/builder.rb', line 19

def initialize(budget:)
  @budget = budget
  @system = nil
  @knowledge = []
  @messages = []
end

Instance Method Details

#add_knowledge(text) ⇒ Object

Append knowledge/RAG text (medium priority).

Parameters:

  • text (String)


35
36
37
38
# File 'lib/phronomy/context/builder.rb', line 35

def add_knowledge(text)
  @knowledge << text.to_s
  self
end

#add_messages(messages) ⇒ Object

Set conversation messages (lowest priority — oldest are dropped first).

Parameters:

  • messages (Array)

    list of message-like objects with #role and #content



42
43
44
45
# File 'lib/phronomy/context/builder.rb', line 42

def add_messages(messages)
  @messages = Array(messages)
  self
end

#add_system(text) ⇒ Object

Set the system instructions text (highest priority).

Parameters:

  • text (String)


28
29
30
31
# File 'lib/phronomy/context/builder.rb', line 28

def add_system(text)
  @system = text.to_s
  self
end

#buildHash

Assemble the context respecting the token budget.

Returns a hash with: :system [String, nil] system prompt (instructions + knowledge) :messages [Array] conversation messages that fit within the budget

Returns:

  • (Hash)


54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/phronomy/context/builder.rb', line 54

def build
  used = 0

  # System prompt is always included (budget enforcement is informational only).
  system_text = [@system, *@knowledge].compact.join("\n\n")
  used += TokenEstimator.estimate(system_text)

  # Conversation messages — keep as many recent messages as fit.
  remaining = @budget.available(used: used)
  kept = fit_messages_to_budget(@messages, remaining)

  {
    system: system_text.empty? ? nil : system_text,
    messages: kept
  }
end