Class: Ask::Agent::Session
- Inherits:
-
Object
- Object
- Ask::Agent::Session
- Includes:
- Test::SessionOverride
- Defined in:
- lib/ask/agent/session.rb
Instance Attribute Summary collapse
-
#chat ⇒ Object
readonly
Returns the value of attribute chat.
-
#created_at ⇒ Object
readonly
Returns the value of attribute created_at.
-
#id ⇒ Object
readonly
Returns the value of attribute id.
-
#messages ⇒ Object
readonly
Returns the value of attribute messages.
-
#meta_agent_results ⇒ Object
readonly
Returns the value of attribute meta_agent_results.
-
#skills_registry ⇒ Ask::Skills::Registry?
readonly
Auto-discovered skills registry.
-
#tool_calls_made ⇒ Object
readonly
Returns the value of attribute tool_calls_made.
-
#tools ⇒ Object
readonly
Returns the value of attribute tools.
-
#total_cost ⇒ Object
readonly
Returns the value of attribute total_cost.
-
#total_input_tokens ⇒ Object
readonly
Returns the value of attribute total_input_tokens.
-
#total_output_tokens ⇒ Object
readonly
Returns the value of attribute total_output_tokens.
-
#turn_count ⇒ Object
readonly
Returns the value of attribute turn_count.
Class Method Summary collapse
-
.deep_symbolize_keys(obj) ⇒ Object
Recursively convert string keys to symbol keys in hashes.
- .load(id, adapter:) ⇒ Object
Instance Method Summary collapse
- #abort ⇒ Object
- #abort_requested? ⇒ Boolean
-
#complete_pending_tool(tool_call_id:, result:) ⇒ Boolean
Completes a pending (async) tool call from a background thread.
- #delete ⇒ Object
- #deleted? ⇒ Boolean
- #emit(event) ⇒ Object
-
#initialize(model:, tools: [], max_turns: 25, max_tool_retries: 3, compactor: nil, hooks: {}, state: nil, persistence: nil, id: nil, system_prompt: nil, parallel_tools: true, reflector: nil, telemetry: true, meta_agent: nil, agent_dir: nil, evaluator: nil, audit_log: nil, skills_disclosure: true, **chat_options) ⇒ Session
constructor
A new instance of Session.
- #on(type, &block) ⇒ Object
- #on_event(&block) ⇒ Object
-
#pending_tools? ⇒ Boolean
True while at least one async tool is running.
- #reflection_count ⇒ Object
-
#register_pending_tool(tool_call_id, result) ⇒ Object
Registers a pending tool call (called by the loop when a tool returned Ask::Result.pending).
- #reset_messages! ⇒ Object
- #run(message, tools: nil, reset: true) ⇒ Object
-
#run_follow_up ⇒ Object
A follow-up turn driven by an async completion: runs the loop with the tool message already in the conversation, preserving turn state.
- #running? ⇒ Boolean
- #save ⇒ Object
-
#skill(name) ⇒ Object
Load a skill by name or file path.
Methods included from Test::SessionOverride
#called_tool?, #stub_text, #stub_tool_call, #test_mode
Constructor Details
#initialize(model:, tools: [], max_turns: 25, max_tool_retries: 3, compactor: nil, hooks: {}, state: nil, persistence: nil, id: nil, system_prompt: nil, parallel_tools: true, reflector: nil, telemetry: true, meta_agent: nil, agent_dir: nil, evaluator: nil, audit_log: nil, skills_disclosure: true, **chat_options) ⇒ Session
Returns a new instance of Session.
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
# File 'lib/ask/agent/session.rb', line 20 def initialize(model:, tools: [], max_turns: 25, max_tool_retries: 3, compactor: nil, hooks: {}, state: nil, persistence: nil, id: nil, system_prompt: nil, parallel_tools: true, reflector: nil, telemetry: true, meta_agent: nil, agent_dir: nil, evaluator: nil, audit_log: nil, skills_disclosure: true, **) @id = id || SecureRandom.uuid @agent_dir = agent_dir @max_turns = max_turns @max_tool_retries = max_tool_retries @parallel_tools = parallel_tools @skills_disclosure = skills_disclosure @event_handlers = { all: [] } @running = false @deleted = false @abort_requested = false @pending_tools = {} @pending_mutex = Mutex.new @followup_pending = false @turn_count = 0 @created_at = Time.now @_no_tools_instructed = false @total_input_tokens = 0 @total_output_tokens = 0 @total_cost = 0.0 @telemetry = telemetry.is_a?(Telemetry) ? telemetry : Telemetry.new(enabled: !!telemetry) @tools = resolve_tools(tools) @chat = build_chat(model, system_prompt, @tools, **) @loop = Loop.new(max_turns: max_turns) @tool_executor = ToolExecutor.new(max_retries: max_tool_retries, parallel: parallel_tools) @compactor = compactor ? build_compactor(compactor) : nil @hooks = Hooks.new(hooks) @audit_log = build_audit_log(audit_log) @system_context = build_system_context(system_prompt) apply_system_context @state = state || persistence reflector_opts = reflector.is_a?(Hash) ? reflector : {} @reflector = if reflector Reflector.new( model: @chat, max_reflections: reflector_opts[:max_reflections] || 1 ) end @meta_agent_config = @meta_agent_results = nil @compactor&.chat = @chat # Parse evaluator configuration @evaluator = nil @evaluator_config = {} if evaluator eval_model = if evaluator.is_a?(Hash) @evaluator_config = evaluator evaluator[:model] || Ask::Agent.configuration.default_evaluator_model || model_id_from(@chat) else Ask::Agent.configuration.default_evaluator_model || model_id_from(@chat) end @evaluator = Evaluator.new(model: eval_model) end end |
Instance Attribute Details
#chat ⇒ Object (readonly)
Returns the value of attribute chat.
9 10 11 |
# File 'lib/ask/agent/session.rb', line 9 def chat @chat end |
#created_at ⇒ Object (readonly)
Returns the value of attribute created_at.
9 10 11 |
# File 'lib/ask/agent/session.rb', line 9 def created_at @created_at end |
#id ⇒ Object (readonly)
Returns the value of attribute id.
9 10 11 |
# File 'lib/ask/agent/session.rb', line 9 def id @id end |
#messages ⇒ Object (readonly)
Returns the value of attribute messages.
9 10 11 |
# File 'lib/ask/agent/session.rb', line 9 def @messages end |
#meta_agent_results ⇒ Object (readonly)
Returns the value of attribute meta_agent_results.
16 17 18 |
# File 'lib/ask/agent/session.rb', line 16 def @meta_agent_results end |
#skills_registry ⇒ Ask::Skills::Registry? (readonly)
Returns auto-discovered skills registry.
18 19 20 |
# File 'lib/ask/agent/session.rb', line 18 def skills_registry @skills_registry end |
#tool_calls_made ⇒ Object (readonly)
Returns the value of attribute tool_calls_made.
10 11 12 |
# File 'lib/ask/agent/session.rb', line 10 def tool_calls_made @tool_calls_made end |
#tools ⇒ Object (readonly)
Returns the value of attribute tools.
9 10 11 |
# File 'lib/ask/agent/session.rb', line 9 def tools @tools end |
#total_cost ⇒ Object (readonly)
Returns the value of attribute total_cost.
10 11 12 |
# File 'lib/ask/agent/session.rb', line 10 def total_cost @total_cost end |
#total_input_tokens ⇒ Object (readonly)
Returns the value of attribute total_input_tokens.
10 11 12 |
# File 'lib/ask/agent/session.rb', line 10 def total_input_tokens @total_input_tokens end |
#total_output_tokens ⇒ Object (readonly)
Returns the value of attribute total_output_tokens.
10 11 12 |
# File 'lib/ask/agent/session.rb', line 10 def total_output_tokens @total_output_tokens end |
#turn_count ⇒ Object (readonly)
Returns the value of attribute turn_count.
9 10 11 |
# File 'lib/ask/agent/session.rb', line 9 def turn_count @turn_count end |
Class Method Details
.deep_symbolize_keys(obj) ⇒ Object
Recursively convert string keys to symbol keys in hashes. Needed when loading session data that was serialized through JSON.
533 534 535 536 537 538 539 540 541 542 |
# File 'lib/ask/agent/session.rb', line 533 def self.deep_symbolize_keys(obj) case obj when Hash obj.each_with_object({}) { |(k, v), h| h[k.to_sym] = deep_symbolize_keys(v) } when Array obj.map { |e| deep_symbolize_keys(e) } else obj end end |
.load(id, adapter:) ⇒ Object
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 |
# File 'lib/ask/agent/session.rb', line 290 def self.load(id, adapter:) data = adapter.get(id) return nil unless data data = deep_symbolize_keys(data) session = new( id: data[:id], model: data.dig(:metadata, :model), tools: data.dig(:metadata, :tools)&.map(&:constantize) || [], state: adapter ) data[:messages].each do |msg| session.chat.( role: msg[:role].to_sym, content: msg[:content], tool_call_id: msg[:tool_call_id] ) end session.instance_variable_set(:@messages, session.chat..dup) session end |
Instance Method Details
#abort ⇒ Object
320 321 322 |
# File 'lib/ask/agent/session.rb', line 320 def abort @abort_requested = true end |
#abort_requested? ⇒ Boolean
324 |
# File 'lib/ask/agent/session.rb', line 324 def abort_requested? = @abort_requested |
#complete_pending_tool(tool_call_id:, result:) ⇒ Boolean
Completes a pending (async) tool call from a background thread.
Adds the tool result to the conversation and, when the session is idle, runs a follow-up turn so the agent voices the answer. If a turn is running, the follow-up fires as soon as it ends.
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 |
# File 'lib/ask/agent/session.rb', line 353 def complete_pending_tool(tool_call_id:, result:) follow_up = @pending_mutex.synchronize do pending = @pending_tools.delete(tool_call_id) return false unless pending @chat.( role: :tool, content: result[:message].to_s, tool_call_id: tool_call_id ) if @running @followup_pending = true false else true end end emit(Events::ToolCompleted.new(name: result[:tool_name], id: tool_call_id, result: result)) run_follow_up if follow_up true end |
#delete ⇒ Object
315 316 317 318 |
# File 'lib/ask/agent/session.rb', line 315 def delete @deleted = true @state&.delete(@id) end |
#deleted? ⇒ Boolean
284 |
# File 'lib/ask/agent/session.rb', line 284 def deleted? = @deleted |
#emit(event) ⇒ Object
277 278 279 280 281 |
# File 'lib/ask/agent/session.rb', line 277 def emit(event) @event_handlers[:all].each { |h| h.call(event) } handlers = @event_handlers[event.class] handlers&.each { |h| h.call(event) } end |
#on(type, &block) ⇒ Object
271 272 273 274 275 |
# File 'lib/ask/agent/session.rb', line 271 def on(type, &block) @event_handlers[type] ||= [] @event_handlers[type] << block self end |
#on_event(&block) ⇒ Object
266 267 268 269 |
# File 'lib/ask/agent/session.rb', line 266 def on_event(&block) @event_handlers[:all] << block self end |
#pending_tools? ⇒ Boolean
Returns true while at least one async tool is running.
340 341 342 |
# File 'lib/ask/agent/session.rb', line 340 def pending_tools? @pending_mutex.synchronize { !@pending_tools.empty? } end |
#reflection_count ⇒ Object
12 13 14 |
# File 'lib/ask/agent/session.rb', line 12 def reflection_count @reflector&.reflection_count || 0 end |
#register_pending_tool(tool_call_id, result) ⇒ Object
Registers a pending tool call (called by the loop when a tool returned Ask::Result.pending). The background work completes later via #complete_pending_tool.
331 332 333 334 335 336 337 |
# File 'lib/ask/agent/session.rb', line 331 def register_pending_tool(tool_call_id, result) @pending_mutex.synchronize do @pending_tools[tool_call_id] = result end emit(Events::ToolPending.new(name: result[:tool_name], id: tool_call_id)) nil end |
#reset_messages! ⇒ Object
406 407 408 409 |
# File 'lib/ask/agent/session.rb', line 406 def @chat. @messages = [] end |
#run(message, tools: nil, reset: true) ⇒ Object
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 |
# File 'lib/ask/agent/session.rb', line 91 def run(, tools: nil, reset: true) raise "Session deleted" if @deleted raise "Session already running" if @running @running = true @abort_requested = false Ask::Agent.current_session = self if reset @turn_count = 0 @loop.reset! end emit(Events::SessionStart.new) active_tools = @tools if active_tools.empty? && !@_no_tools_instructed @chat.(role: :system, content: "You have no tools available. Do not claim you can look up information or use tools of any kind. Just respond based on your existing knowledge.") @_no_tools_instructed = true end begin @tool_executor.telemetry = @telemetry response = @loop.run_turn( chat: @chat, message: , tools: active_tools, tool_executor: @tool_executor, compactor: @compactor, hooks: @hooks, event_emitter: self, session_id: @id, persist: @state ? method(:persist!) : nil ) @total_input_tokens += @loop.last_input_tokens.to_i @total_output_tokens += @loop.last_output_tokens.to_i @total_cost += @loop.last_cost.to_f rescue MaxTurnsExceeded => e emit(Events::MaxTurnsExceeded.new(max_turns: @max_turns)) @telemetry.log(:max_turns_exceeded, session_id: @id, max_turns: @max_turns) response = last_content rescue LoopDetected => e emit(Events::LoopDetected.new(tool_name: e., repeated_count: 3)) @telemetry.log(:loop_detected, session_id: @id, tool_name: e., repeated_count: 3) response = last_content rescue Ask::ContextLengthExceeded if @compactor && !@compactor.overflow_recovered? @compactor.recover_from_overflow retry end response = "I'm sorry, the conversation has grown too long. Please start a new session." rescue StandardError => e emit(Events::Error.new(error: e., recoverable: true)) raise ensure @running = false Ask::Agent.current_session = nil if Ask::Agent.current_session.equal?(self) persist! if @state # A pending tool completed while this run was busy: voice the # result now that the turn is over (one follow-up per completion). follow_up = @pending_mutex.synchronize do take = @followup_pending @followup_pending = false take end run_follow_up if follow_up end @tool_calls_made = @tool_executor.total_executions # Independent evaluator step (generator/evaluator separation). # Runs BEFORE self-reflection so the evaluator gets a fresh, unbiased look # at the generator's output using a separate model and isolated context. @skip_reflector = false if @evaluator && !@abort_requested goal = @evaluator_config[:goal] || eval_result = @evaluator.evaluate( goal: goal.to_s, response: response, event_emitter: self ) @telemetry.log(:evaluation_end, session_id: @id, decision: eval_result.decision, feedback: eval_result.feedback, scores: eval_result.scores) case eval_result.decision when :revise @chat.( role: :system, content: "An independent evaluator has requested revisions:\n\n#{eval_result.feedback}" ) response = @loop.run_turn( chat: @chat, message: "", tools: active_tools, tool_executor: @tool_executor, compactor: @compactor, hooks: @hooks, event_emitter: self, session_id: @id ) @total_input_tokens += @loop.last_input_tokens.to_i @total_output_tokens += @loop.last_output_tokens.to_i @total_cost += @loop.last_cost.to_f # Skip reflector — we already iterated based on evaluator feedback @skip_reflector = true when :block emit(Events::EvaluationBlocked.new( feedback: eval_result.feedback, scores: eval_result.scores, evidence: eval_result.evidence )) response = "This response was blocked by the evaluator: #{eval_result.feedback}" when :accept # Fall through to reflector for backward compatibility end end if @reflector && !@skip_reflector && @reflector.reflect?(@tool_calls_made) && !@abort_requested eval_result = @reflector.evaluate(response: response, event_emitter: self) @telemetry.log(:reflection_end, session_id: @id, decision: eval_result[:decision], feedback: eval_result[:feedback]) if eval_result[:decision] == :improve && !@abort_requested @chat.( role: :system, content: "Improve your last response: #{eval_result[:feedback]}" ) response = @loop.run_turn( chat: @chat, message: "", tools: active_tools, tool_executor: @tool_executor, compactor: @compactor, hooks: @hooks, event_emitter: self, session_id: @id ) @total_input_tokens += @loop.last_input_tokens.to_i @total_output_tokens += @loop.last_output_tokens.to_i @total_cost += @loop.last_cost.to_f end end if @meta_agent_config @telemetry.increment_session_count! end # Capture messages before emitting SessionEnd so event handlers # can access agent.messages during the callback @messages = @chat..dup emit(Events::SessionEnd.new( result: response, turn_count: @turn_count, tool_calls_made: @tool_calls_made, input_tokens: @total_input_tokens, output_tokens: @total_output_tokens, cost: @total_cost )) response end |
#run_follow_up ⇒ Object
A follow-up turn driven by an async completion: runs the loop with the tool message already in the conversation, preserving turn state.
377 378 379 380 381 382 |
# File 'lib/ask/agent/session.rb', line 377 def run_follow_up run("", reset: false) rescue => e emit(Events::Error.new(error: e., recoverable: false)) raise end |
#running? ⇒ Boolean
283 |
# File 'lib/ask/agent/session.rb', line 283 def running? = @running |
#save ⇒ Object
286 287 288 |
# File 'lib/ask/agent/session.rb', line 286 def save persist! if @state end |
#skill(name) ⇒ Object
Load a skill by name or file path. Injects the skill's full instructions into the conversation as a system message.
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 |
# File 'lib/ask/agent/session.rb', line 389 def skill(name) if @skills_registry && (s = @skills_registry[name]) @chat.( role: :system, content: "## Skill: #{s.name}\n\n#{s.description}\n\n---\n\n#{s.instructions}" ) elsif File.exist?(name.to_s) content = File.read(name.to_s) @chat.( role: :system, content: "## Skill: #{name}\n\n---\n\n#{content}" ) else raise Ask::Skills::Error, "Skill not found: #{name.inspect}" end end |