113 lines
4 KiB
Ruby
113 lines
4 KiB
Ruby
# lib/orchestrator.rb
|
|
require 'json'
|
|
require_relative 'tools'
|
|
require_relative 'config'
|
|
|
|
class Orchestrator
|
|
RULES_PATH = File.expand_path('../../config/rules/orchestrator.md', __FILE__)
|
|
|
|
def initialize(llm_client)
|
|
@llm_client = llm_client
|
|
debug_log("initialize", "Orchestrator instanciado com sucesso.")
|
|
end
|
|
|
|
def load_rules
|
|
debug_log("load_rules", "Tentando carregar regras de: #{RULES_PATH}")
|
|
if File.exist?(RULES_PATH)
|
|
content = File.read(RULES_PATH)
|
|
debug_log("load_rules", "Regras carregadas com sucesso (#{content.bytesize} bytes).")
|
|
content
|
|
else
|
|
debug_log("load_rules", "Arquivo de regras não encontrado em #{RULES_PATH}. Usando fallback padrão.")
|
|
"Você é o orquestrador de tarefas do agente."
|
|
end
|
|
end
|
|
|
|
def plan(user_message)
|
|
debug_log("plan", "Iniciando planejamento para a mensagem: #{user_message.inspect}")
|
|
|
|
tools_desc = ToolRegistry.definitions_summary
|
|
base_rules = load_rules
|
|
|
|
system_prompt = <<~PROMPT
|
|
#{base_rules}
|
|
|
|
FERRAMENTAS DISPONÍVEIS (Para usar com type: "tool"):
|
|
#{tools_desc}
|
|
PROMPT
|
|
|
|
messages = [
|
|
{ role: 'system', content: system_prompt },
|
|
{ role: 'user', content: user_message }
|
|
]
|
|
|
|
# --- LOG DE DEBUG: ENVIO ---
|
|
if debug_enabled?
|
|
STDERR.puts "\n\e[33m[DEBUG][lib/orchestrator.rb][Orchestrator#plan] === ORCHESTRATOR REQUEST (Enviado ao LLM) ===\e[0m"
|
|
STDERR.puts JSON.pretty_generate(messages)
|
|
STDERR.puts "\n\e[33m[DEBUG][lib/orchestrator.rb][Orchestrator#plan] ================================================\e[0m"
|
|
end
|
|
|
|
debug_log("plan", "Enviando requisição de planejamento ao backend do LLM...")
|
|
response = @llm_client.process(messages: messages)
|
|
raw_content = response.dig('choices', 0, 'message', 'content')&.strip
|
|
|
|
# --- LOG DE DEBUG: RESPOSTA BRUTA ---
|
|
if debug_enabled?
|
|
STDERR.puts "\n\e[35m[DEBUG][lib/orchestrator.rb][Orchestrator#plan] === ORCHESTRATOR RAW RESPONSE (Recebido do LLM) ===\e[0m"
|
|
p raw_content
|
|
STDERR.puts "\n\e[35m[DEBUG][lib/orchestrator.rb][Orchestrator#plan] ===================================================\e[0m"
|
|
end
|
|
|
|
raise "Orquestrador não retornou conteúdo." unless raw_content
|
|
|
|
cleaned_content = raw_content.gsub(/^```json\s*/, '').gsub(/^```\s*/, '').sub(/\s*```$/, '').strip
|
|
|
|
# Tolerância caso o modelo retorne texto puro em vez de JSON estruturado
|
|
if !cleaned_content.start_with?('{')
|
|
debug_log("plan", "AVISO: Resposta do LLM não iniciou com JSON. Convertendo texto puro em tarefa de texto padrão.")
|
|
parsed = {
|
|
"tasks" => [
|
|
{
|
|
"id" => 1,
|
|
"type" => "text",
|
|
"arguments" => { "prompt" => cleaned_content },
|
|
"depends_on" => []
|
|
}
|
|
]
|
|
}
|
|
else
|
|
parsed = JSON.parse(cleaned_content)
|
|
end
|
|
|
|
# --- LOG DE DEBUG: JSON PARSEADO ---
|
|
if debug_enabled?
|
|
STDERR.puts "\n\e[32m[DEBUG][lib/orchestrator.rb][Orchestrator#plan] === ORCHESTRATOR PARSED JSON (Estrutura final) ===\e[0m"
|
|
STDERR.puts JSON.pretty_generate(parsed)
|
|
STDERR.puts "\n\e[32m[DEBUG][lib/orchestrator.rb][Orchestrator#plan] ===================================================\e[0m\n"
|
|
end
|
|
|
|
debug_log("plan", "Plano processado com sucesso contendo #{parsed['tasks']&.size.to_i} tarefa(s).")
|
|
parsed
|
|
rescue => e
|
|
debug_log("plan", "FALHA no Orquestrador: #{e.message}. Acionando fallback de tarefa de texto.")
|
|
STDERR.puts "\e[31m[DEBUG][lib/orchestrator.rb][Orchestrator#plan] Erro no Orquestrador: #{e.message}\e[0m"
|
|
{
|
|
"tasks" => [
|
|
{ "id" => 1, "type" => "text", "arguments" => { "prompt" => user_message }, "depends_on" => [] }
|
|
]
|
|
}
|
|
end
|
|
|
|
private
|
|
|
|
def debug_enabled?
|
|
defined?(AgentConfig) && AgentConfig.respond_to?(:debug?) ? AgentConfig.debug? : true
|
|
end
|
|
|
|
def debug_log(function_name, message)
|
|
if debug_enabled?
|
|
STDERR.puts "\e[36m[DEBUG][lib/orchestrator.rb][Orchestrator##{function_name}] #{message}\e[0m"
|
|
end
|
|
end
|
|
end
|