Class: RailsConsoleAi::ConversationEngine
- Inherits:
-
Object
- Object
- RailsConsoleAi::ConversationEngine
- Defined in:
- lib/rails_console_ai/conversation_engine.rb
Constant Summary collapse
- LARGE_OUTPUT_THRESHOLD =
chars — truncate tool results larger than this immediately
20_000- LARGE_OUTPUT_PREVIEW_CHARS =
chars — how much of the output the LLM sees upfront
16_000- LOOP_WARN_THRESHOLD =
same tool+args repeated → inject warning
3- LOOP_BREAK_THRESHOLD =
same tool+args repeated → break loop
5
Instance Attribute Summary collapse
-
#history ⇒ Object
readonly
Returns the value of attribute history.
-
#interactive_session_id ⇒ Object
readonly
Returns the value of attribute interactive_session_id.
-
#session_name ⇒ Object
readonly
Returns the value of attribute session_name.
-
#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.
Instance Method Summary collapse
- #add_user_message(text) ⇒ Object
- #compact_history ⇒ Object
- #context ⇒ Object
- #display_conversation ⇒ Object
- #display_conversation_to(io) ⇒ Object
- #display_cost_summary ⇒ Object
-
#display_session_summary ⇒ Object
— Display helpers (used by Channel::Console slash commands) —.
- #downgrade_from_thinking_model ⇒ Object
- #effective_model ⇒ Object
- #execute_direct(raw_code) ⇒ Object
- #explain(query) ⇒ Object
- #finish_interactive_session ⇒ Object
- #init_guide ⇒ Object
-
#init_interactive ⇒ Object
— Interactive session management —.
-
#initialize(binding_context:, channel:, slack_thread_ts: nil, slack_channel_name: nil) ⇒ ConversationEngine
constructor
A new instance of ConversationEngine.
-
#log_interactive_turn ⇒ Object
— Session logging —.
-
#one_shot(query) ⇒ Object
— Public API for channels —.
- #pop_last_message ⇒ Object
- #process_message(text) ⇒ Object
- #restore_session(session) ⇒ Object
- #retry_last_code ⇒ Object
- #send_and_execute ⇒ Object
- #set_interactive_query(text) ⇒ Object
- #set_session_name(name) ⇒ Object
- #upgrade_to_thinking_model ⇒ Object
- #warn_if_history_large ⇒ Object
Constructor Details
#initialize(binding_context:, channel:, slack_thread_ts: nil, slack_channel_name: nil) ⇒ ConversationEngine
Returns a new instance of ConversationEngine.
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/rails_console_ai/conversation_engine.rb', line 11 def initialize(binding_context:, channel:, slack_thread_ts: nil, slack_channel_name: nil) @binding_context = binding_context @channel = channel @slack_thread_ts = slack_thread_ts @slack_channel_name = slack_channel_name @executor = Executor.new(binding_context, channel: channel) @provider = nil @context_builder = nil @context = nil @history = [] @total_input_tokens = 0 @total_output_tokens = 0 @token_usage = Hash.new { |h, k| h[k] = { input: 0, output: 0 } } @interactive_session_id = nil @session_name = nil @interactive_query = nil @interactive_start = nil @last_interactive_code = nil @last_interactive_output = nil @last_interactive_result = nil @last_interactive_executed = false @compact_warned = false @prior_duration_ms = 0 @expanded_output_ids = Set.new end |
Instance Attribute Details
#history ⇒ Object (readonly)
Returns the value of attribute history.
3 4 5 |
# File 'lib/rails_console_ai/conversation_engine.rb', line 3 def history @history end |
#interactive_session_id ⇒ Object (readonly)
Returns the value of attribute interactive_session_id.
3 4 5 |
# File 'lib/rails_console_ai/conversation_engine.rb', line 3 def interactive_session_id @interactive_session_id end |
#session_name ⇒ Object (readonly)
Returns the value of attribute session_name.
3 4 5 |
# File 'lib/rails_console_ai/conversation_engine.rb', line 3 def session_name @session_name end |
#total_input_tokens ⇒ Object (readonly)
Returns the value of attribute total_input_tokens.
3 4 5 |
# File 'lib/rails_console_ai/conversation_engine.rb', line 3 def total_input_tokens @total_input_tokens end |
#total_output_tokens ⇒ Object (readonly)
Returns the value of attribute total_output_tokens.
3 4 5 |
# File 'lib/rails_console_ai/conversation_engine.rb', line 3 def total_output_tokens @total_output_tokens end |
Instance Method Details
#add_user_message(text) ⇒ Object
213 214 215 |
# File 'lib/rails_console_ai/conversation_engine.rb', line 213 def (text) @history << { role: :user, content: text } end |
#compact_history ⇒ Object
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 |
# File 'lib/rails_console_ai/conversation_engine.rb', line 487 def compact_history if @history.length < 6 $stdout.puts "\e[33m History too short to compact (#{@history.length} messages). Need at least 6.\e[0m" return end before_chars = @history.sum { |m| m[:content].to_s.length } before_count = @history.length executed_code = extract_executed_code(@history) $stdout.puts "\e[2m Compacting #{before_count} messages (~#{format_tokens(before_chars)} chars)...\e[0m" system_prompt = <<~PROMPT You are a conversation summarizer. The user will provide a conversation history from a Rails console AI assistant session. Produce a concise summary that captures: - What the user has been working on and their goals - Key findings and data discovered (include specific values, IDs, record counts) - Current state: what worked, what failed, where things stand - Important variable names, model names, or table names referenced Do NOT include code that was executed — that will be preserved separately. Be concise but preserve all information that would be needed to continue the conversation naturally. Do NOT include any preamble — just output the summary directly. PROMPT history_text = @history.map { |m| "#{m[:role]}: #{m[:content]}" }.join("\n\n") = [{ role: :user, content: "Summarize this conversation history:\n\n#{history_text}" }] begin result = provider.chat(, system_prompt: system_prompt) track_usage(result) summary = result.text.to_s.strip if summary.empty? $stdout.puts "\e[33m Compaction failed: empty summary returned.\e[0m" return end content = "CONVERSATION SUMMARY (compacted):\n#{summary}" unless executed_code.empty? content += "\n\nCODE EXECUTED THIS SESSION (preserved for continuation):\n#{executed_code}" end @history = [{ role: :user, content: content }] @compact_warned = false after_chars = @history.first[:content].length $stdout.puts "\e[36m Compacted: #{before_count} messages -> 1 summary (~#{format_tokens(before_chars)} -> ~#{format_tokens(after_chars)} chars)\e[0m" summary.each_line { |line| $stdout.puts "\e[2m #{line.rstrip}\e[0m" } if !executed_code.empty? $stdout.puts "\e[2m (preserved #{executed_code.scan(/```ruby/).length} executed code block(s))\e[0m" end display_usage(result) rescue => e $stdout.puts "\e[31m Compaction failed: #{e.}\e[0m" end end |
#context ⇒ Object
444 445 446 447 448 449 450 451 |
# File 'lib/rails_console_ai/conversation_engine.rb', line 444 def context base = @context_base ||= context_builder.build parts = [base] parts << safety_context parts << @channel.system_instructions parts << binding_variable_summary parts.compact.join("\n\n") end |
#display_conversation ⇒ Object
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 |
# File 'lib/rails_console_ai/conversation_engine.rb', line 418 def display_conversation stdout = @channel.respond_to?(:real_stdout) ? @channel.real_stdout : $stdout if @history.empty? stdout.puts "\e[2m (no conversation history yet)\e[0m" return end = trim_large_outputs(@history) system_prompt = context require 'rails_console_ai/tools/registry' tools = Tools::Registry.new(executor: @executor, channel: @channel) rescue nil opts = { io: stdout, prefix: " ", d: "\e[2m", r: "\e[0m" } conversation_summary(, system_prompt, tools, **opts) (, **opts) end |
#display_conversation_to(io) ⇒ Object
434 435 436 437 438 439 440 441 442 |
# File 'lib/rails_console_ai/conversation_engine.rb', line 434 def display_conversation_to(io) = trim_large_outputs(@history) system_prompt = context require 'rails_console_ai/tools/registry' tools = Tools::Registry.new(executor: @executor, channel: @channel) rescue nil opts = { io: io, prefix: "", d: "", r: "" } conversation_summary(, system_prompt, tools, **opts) (, **opts) end |
#display_cost_summary ⇒ Object
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 |
# File 'lib/rails_console_ai/conversation_engine.rb', line 381 def display_cost_summary if @token_usage.empty? $stdout.puts "\e[2m No usage yet.\e[0m" return end total_cost = 0.0 $stdout.puts "\e[36m Cost estimate:\e[0m" @token_usage.each do |model, usage| pricing = Configuration::PRICING[model] pricing ||= { input: 0.0, output: 0.0 } if RailsConsoleAi.configuration.provider == :local input_str = "in: #{format_tokens(usage[:input])}" output_str = "out: #{format_tokens(usage[:output])}" if pricing cost = (usage[:input] * pricing[:input]) + (usage[:output] * pricing[:output]) cache_read = usage[:cache_read] || 0 cache_write = usage[:cache_write] || 0 if (cache_read > 0 || cache_write > 0) && pricing[:cache_read] # Subtract cached tokens from full-price input, add at cache rates cost -= cache_read * pricing[:input] cost += cache_read * pricing[:cache_read] cost += cache_write * (pricing[:cache_write] - pricing[:input]) end total_cost += cost cache_str = "" cache_str = " cache r: #{format_tokens(cache_read)} w: #{format_tokens(cache_write)}" if cache_read > 0 || cache_write > 0 $stdout.puts "\e[2m #{model}: #{input_str} #{output_str}#{cache_str} ~$#{'%.2f' % cost}\e[0m" else $stdout.puts "\e[2m #{model}: #{input_str} #{output_str} (pricing unknown)\e[0m" end end $stdout.puts "\e[36m Total: ~$#{'%.2f' % total_cost}\e[0m" end |
#display_session_summary ⇒ Object
— Display helpers (used by Channel::Console slash commands) —
376 377 378 379 |
# File 'lib/rails_console_ai/conversation_engine.rb', line 376 def display_session_summary return if @total_input_tokens == 0 && @total_output_tokens == 0 $stdout.puts "\e[2m[session totals — in: #{@total_input_tokens} | out: #{@total_output_tokens} | total: #{@total_input_tokens + @total_output_tokens}]\e[0m" end |
#downgrade_from_thinking_model ⇒ Object
468 469 470 471 472 473 474 475 476 477 478 479 480 481 |
# File 'lib/rails_console_ai/conversation_engine.rb', line 468 def downgrade_from_thinking_model config = RailsConsoleAi.configuration default = config.resolved_model current = effective_model if current == default && @model_override.nil? $stdout.puts "\e[36m Already using default model (#{current}).\e[0m" else @model_override = nil @provider = nil $stdout.puts "\e[36m Switched back to default model: #{default}\e[0m" end effective_model end |
#effective_model ⇒ Object
483 484 485 |
# File 'lib/rails_console_ai/conversation_engine.rb', line 483 def effective_model @model_override || RailsConsoleAi.configuration.resolved_model end |
#execute_direct(raw_code) ⇒ Object
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 |
# File 'lib/rails_console_ai/conversation_engine.rb', line 239 def execute_direct(raw_code) exec_result = @executor.execute_unsafe(raw_code) output_parts = [] output_parts << "Output:\n#{@executor.last_output.strip}" if @executor.last_output && !@executor.last_output.strip.empty? output_parts << "Return value: #{exec_result.inspect}" if exec_result result_str = output_parts.join("\n\n") context_msg = "User directly executed code: `#{raw_code}`" output_id = @executor.store_output(result_str) if result_str.length > LARGE_OUTPUT_THRESHOLD preview = result_str[0, LARGE_OUTPUT_PREVIEW_CHARS] context_msg += "\n#{preview}\n\n[Output truncated at #{LARGE_OUTPUT_PREVIEW_CHARS} of #{result_str.length} chars — use explore_output with output_id=#{output_id} for focused queries, or recall_output to expand in place]" elsif !output_parts.empty? context_msg += "\n#{result_str}" end @history << { role: :user, content: context_msg, output_id: output_id } @interactive_query ||= "> #{raw_code}" @last_interactive_code = raw_code @last_interactive_output = @executor.last_output @last_interactive_result = exec_result ? exec_result.inspect : nil @last_interactive_executed = true end |
#explain(query) ⇒ Object
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 |
# File 'lib/rails_console_ai/conversation_engine.rb', line 80 def explain(query) start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC) console_capture = StringIO.new with_console_capture(console_capture) do result, _ = send_query(query) track_usage(result) @executor.display_response(result.text) display_usage(result) @_last_log_attrs = { query: query, conversation: [{ role: :user, content: query }, { role: :assistant, content: result.text }], mode: 'explain', executed: false, start_time: start_time } end log_session(@_last_log_attrs.merge(console_output: console_capture.string)) nil rescue Providers::ProviderError => e @channel.display_error("RailsConsoleAi Error: #{e.}") nil rescue => e @channel.display_error("RailsConsoleAi Error: #{e.class}: #{e.}") nil end |
#finish_interactive_session ⇒ Object
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 |
# File 'lib/rails_console_ai/conversation_engine.rb', line 589 def finish_interactive_session @executor.on_prompt = nil require 'rails_console_ai/session_logger' duration_ms = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - @interactive_start) * 1000).round + @prior_duration_ms if @interactive_session_id SessionLogger.update(@interactive_session_id, conversation: @history, input_tokens: @total_input_tokens, output_tokens: @total_output_tokens, code_executed: @last_interactive_code, code_output: @last_interactive_output, code_result: @last_interactive_result, executed: @last_interactive_executed, console_output: @channel.respond_to?(:console_capture_string) ? @channel.console_capture_string : nil, duration_ms: duration_ms ) elsif @interactive_query log_attrs = { query: @interactive_query, conversation: @history, mode: @slack_thread_ts ? 'slack' : 'interactive', code_executed: @last_interactive_code, code_output: @last_interactive_output, code_result: @last_interactive_result, executed: @last_interactive_executed, console_output: @channel.respond_to?(:console_capture_string) ? @channel.console_capture_string : nil, start_time: @interactive_start } log_attrs[:slack_thread_ts] = @slack_thread_ts if @slack_thread_ts log_attrs[:slack_channel_name] = @slack_channel_name if @slack_channel_name if @channel.user_identity log_attrs[:user_name] = @channel.mode == 'slack' ? "slack:#{@channel.user_identity}" : @channel.user_identity end log_session(log_attrs) end end |
#init_guide ⇒ Object
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 |
# File 'lib/rails_console_ai/conversation_engine.rb', line 122 def init_guide storage = RailsConsoleAi.storage existing_guide = begin content = storage.read(RailsConsoleAi::GUIDE_KEY) (content && !content.strip.empty?) ? content.strip : nil rescue nil end if existing_guide @channel.display(" Existing guide found (#{existing_guide.length} chars). Will update.") else @channel.display(" No existing guide. Exploring the app...") end require 'rails_console_ai/tools/registry' init_tools = Tools::Registry.new(mode: :init) sys_prompt = init_system_prompt(existing_guide) = [{ role: :user, content: "Explore this Rails application and generate the application guide." }] original_timeout = RailsConsoleAi.configuration.timeout RailsConsoleAi.configuration.timeout = [original_timeout, 120].max result, _ = send_query_with_tools(, system_prompt: sys_prompt, tools_override: init_tools) guide_text = result.text.to_s.strip guide_text = guide_text.sub(/\A```(?:markdown)?\s*\n?/, '').sub(/\n?```\s*\z/, '') guide_text = guide_text.sub(/\A.*?(?=^#\s)/m, '') if guide_text =~ /^#\s/m if guide_text.empty? @channel.display_warning(" No guide content generated.") return nil end storage.write(RailsConsoleAi::GUIDE_KEY, guide_text) path = storage.respond_to?(:root_path) ? File.join(storage.root_path, RailsConsoleAi::GUIDE_KEY) : RailsConsoleAi::GUIDE_KEY $stdout.puts "\e[32m Guide saved to #{path} (#{guide_text.length} chars)\e[0m" display_usage(result) nil rescue Interrupt $stdout.puts "\n\e[33m Interrupted.\e[0m" nil rescue Providers::ProviderError => e @channel.display_error("RailsConsoleAi Error: #{e.}") nil rescue => e @channel.display_error("RailsConsoleAi Error: #{e.class}: #{e.}") nil ensure RailsConsoleAi.configuration.timeout = original_timeout if original_timeout end |
#init_interactive ⇒ Object
— Interactive session management —
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 |
# File 'lib/rails_console_ai/conversation_engine.rb', line 176 def init_interactive @interactive_start = Process.clock_gettime(Process::CLOCK_MONOTONIC) @executor.on_prompt = -> { log_interactive_turn } @history = [] @total_input_tokens = 0 @total_output_tokens = 0 @token_usage = Hash.new { |h, k| h[k] = { input: 0, output: 0 } } @interactive_query = nil @interactive_session_id = nil @session_name = nil @last_interactive_code = nil @last_interactive_output = nil @last_interactive_result = nil @last_interactive_executed = false @compact_warned = false @prior_duration_ms = 0 end |
#log_interactive_turn ⇒ Object
— Session logging —
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 |
# File 'lib/rails_console_ai/conversation_engine.rb', line 558 def log_interactive_turn require 'rails_console_ai/session_logger' session_attrs = { conversation: @history, input_tokens: @total_input_tokens, output_tokens: @total_output_tokens, code_executed: @last_interactive_code, code_output: @last_interactive_output, code_result: @last_interactive_result, executed: @last_interactive_executed, console_output: @channel.respond_to?(:console_capture_string) ? @channel.console_capture_string : nil } if @interactive_session_id SessionLogger.update(@interactive_session_id, session_attrs) else log_attrs = session_attrs.merge( query: @interactive_query || '(interactive session)', mode: @slack_thread_ts ? 'slack' : 'interactive', name: @session_name ) log_attrs[:slack_thread_ts] = @slack_thread_ts if @slack_thread_ts log_attrs[:slack_channel_name] = @slack_channel_name if @slack_channel_name log_attrs[:model] = effective_model if @channel.user_identity log_attrs[:user_name] = @channel.mode == 'slack' ? "slack:#{@channel.user_identity}" : @channel.user_identity end @interactive_session_id = SessionLogger.log(log_attrs) end end |
#one_shot(query) ⇒ Object
— Public API for channels —
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 |
# File 'lib/rails_console_ai/conversation_engine.rb', line 39 def one_shot(query) start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC) console_capture = StringIO.new exec_result = with_console_capture(console_capture) do conversation = [{ role: :user, content: query }] exec_result, code, executed = one_shot_round(conversation) if executed && @executor.last_error && !@executor.last_safety_error error_msg = "Code execution failed with error: #{@executor.last_error}" error_msg = error_msg[0..1000] + '...' if error_msg.length > 1000 conversation << { role: :assistant, content: @_last_result_text } conversation << { role: :user, content: error_msg } @channel.display_status(" Ran into an issue, trying a different approach...") exec_result, code, executed = one_shot_round(conversation) end @_last_log_attrs = { query: query, conversation: conversation, mode: 'one_shot', code_executed: code, code_output: executed ? @executor.last_output : nil, code_result: executed && exec_result ? exec_result.inspect : nil, executed: executed, start_time: start_time } exec_result end log_session(@_last_log_attrs.merge(console_output: console_capture.string)) exec_result rescue Providers::ProviderError => e @channel.display_error("RailsConsoleAi Error: #{e.}") nil rescue => e @channel.display_error("RailsConsoleAi Error: #{e.class}: #{e.}") nil end |
#pop_last_message ⇒ Object
217 218 219 |
# File 'lib/rails_console_ai/conversation_engine.rb', line 217 def @history.pop end |
#process_message(text) ⇒ Object
108 109 110 111 112 113 114 115 116 117 118 119 120 |
# File 'lib/rails_console_ai/conversation_engine.rb', line 108 def (text) # Initialize interactive state if not already set (first message in session) init_interactive unless @interactive_start @channel.log_input(text) if @channel.respond_to?(:log_input) @interactive_query ||= text @history << { role: :user, content: text } status = send_and_execute if status == :error @channel.display_status(" Ran into an issue, trying a different approach...") send_and_execute end end |
#restore_session(session) ⇒ Object
194 195 196 197 198 199 200 201 202 203 204 205 206 207 |
# File 'lib/rails_console_ai/conversation_engine.rb', line 194 def restore_session(session) @history = JSON.parse(session.conversation, symbolize_names: true) @interactive_session_id = session.id @interactive_query = session.query @session_name = session.name @total_input_tokens = session.input_tokens || 0 @total_output_tokens = session.output_tokens || 0 @prior_duration_ms = session.duration_ms || 0 if session.model && (session.input_tokens.to_i > 0 || session.output_tokens.to_i > 0) @token_usage[session.model][:input] = session.input_tokens.to_i @token_usage[session.model][:output] = session.output_tokens.to_i end end |
#retry_last_code ⇒ Object
229 230 231 232 233 234 235 236 237 |
# File 'lib/rails_console_ai/conversation_engine.rb', line 229 def retry_last_code code = @last_interactive_code unless code @channel.display_warning("No code to retry.") return end @channel.display_status(" Retrying last code...") execute_direct(code) end |
#send_and_execute ⇒ Object
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 |
# File 'lib/rails_console_ai/conversation_engine.rb', line 265 def send_and_execute begin result, , last_llm_stats = send_query(nil, conversation: @history) rescue Providers::ProviderError => e if e..include?("prompt is too long") && @history.length >= 6 @channel.display_warning(" Context limit reached. Run /compact to reduce context size, then try again.") else @channel.display_error("RailsConsoleAi Error: #{e.class}: #{e.}") end return :error rescue Interrupt $stdout.puts "\n\e[33m Aborted.\e[0m" return :interrupted end track_usage(result) return :cancelled if @channel.cancelled? code = @executor.display_response(result.text) display_usage(result, show_session: true) log_interactive_turn @history.concat() if && !.empty? # Only add the final assistant text when the LLM gave a final response (end_turn). # For tool_use results, the assistant message is already in tool_messages via # format_assistant_message, so adding result.text again would duplicate it — # and if the text is empty, Bedrock rejects the empty content array. unless result.tool_use? entry = { role: :assistant, content: result.text } entry[:llm_stats] = last_llm_stats if last_llm_stats @history << entry end return :no_code unless code && !code.strip.empty? return :cancelled if @channel.cancelled? exec_result = if RailsConsoleAi.configuration.auto_execute @executor.execute(code) else @executor.confirm_and_execute(code) end unless @executor.last_cancelled? @last_interactive_code = code @last_interactive_output = @executor.last_output @last_interactive_result = exec_result ? exec_result.inspect : nil @last_interactive_executed = true end if @executor.last_cancelled? :cancelled elsif @executor.last_safety_error exec_result = @executor.offer_danger_retry(code) if exec_result || !@executor.last_error @last_interactive_code = code @last_interactive_output = @executor.last_output @last_interactive_result = exec_result ? exec_result.inspect : nil @last_interactive_executed = true output_parts = [] if @executor.last_output && !@executor.last_output.strip.empty? output_parts << "Output:\n#{@executor.last_output.strip}" end output_parts << "Return value: #{exec_result.inspect}" if exec_result unless output_parts.empty? result_str = output_parts.join("\n\n") output_id = @executor.store_output(result_str) context_msg = "Code was executed (safety override). " if result_str.length > LARGE_OUTPUT_THRESHOLD context_msg += result_str[0, LARGE_OUTPUT_PREVIEW_CHARS] context_msg += "\n\n[Output truncated at #{LARGE_OUTPUT_PREVIEW_CHARS} of #{result_str.length} chars — use explore_output with output_id=#{output_id} for focused queries, or recall_output to expand in place]" else context_msg += result_str end @history << { role: :user, content: context_msg, output_id: output_id } end :success else :cancelled end elsif @executor.last_error error_msg = "Code execution failed with error: #{@executor.last_error}" error_msg = error_msg[0..1000] + '...' if error_msg.length > 1000 @history << { role: :user, content: error_msg } :error else output_parts = [] if @executor.last_output && !@executor.last_output.strip.empty? output_parts << "Output:\n#{@executor.last_output.strip}" end output_parts << "Return value: #{exec_result.inspect}" if exec_result unless output_parts.empty? result_str = output_parts.join("\n\n") output_id = @executor.store_output(result_str) context_msg = "Code was executed. " if result_str.length > LARGE_OUTPUT_THRESHOLD context_msg += result_str[0, LARGE_OUTPUT_PREVIEW_CHARS] context_msg += "\n\n[Output truncated at #{LARGE_OUTPUT_PREVIEW_CHARS} of #{result_str.length} chars — use explore_output with output_id=#{output_id} for focused queries, or recall_output to expand in place]" else context_msg += result_str end @history << { role: :user, content: context_msg, output_id: output_id } end :success end end |
#set_interactive_query(text) ⇒ Object
209 210 211 |
# File 'lib/rails_console_ai/conversation_engine.rb', line 209 def set_interactive_query(text) @interactive_query ||= text end |
#set_session_name(name) ⇒ Object
221 222 223 224 225 226 227 |
# File 'lib/rails_console_ai/conversation_engine.rb', line 221 def set_session_name(name) @session_name = name if @interactive_session_id require 'rails_console_ai/session_logger' SessionLogger.update(@interactive_session_id, name: name) end end |
#upgrade_to_thinking_model ⇒ Object
453 454 455 456 457 458 459 460 461 462 463 464 465 466 |
# File 'lib/rails_console_ai/conversation_engine.rb', line 453 def upgrade_to_thinking_model config = RailsConsoleAi.configuration current = effective_model thinking = config.resolved_thinking_model if current == thinking $stdout.puts "\e[36m Already using thinking model (#{current}).\e[0m" else @model_override = thinking @provider = nil $stdout.puts "\e[36m Switched to thinking model: #{thinking}\e[0m" end effective_model end |
#warn_if_history_large ⇒ Object
547 548 549 550 551 552 553 554 |
# File 'lib/rails_console_ai/conversation_engine.rb', line 547 def warn_if_history_large chars = @history.sum { |m| m[:content].to_s.length } if chars > 50_000 && !@compact_warned @compact_warned = true $stdout.puts "\e[33m Conversation is getting large (~#{format_tokens(chars)} chars). Consider running /compact to reduce context size.\e[0m" end end |