Adicionando arquivos
This commit is contained in:
parent
9f26bd4e05
commit
6509536d12
9 changed files with 409 additions and 0 deletions
14
agent_rules.yml
Normal file
14
agent_rules.yml
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
rules:
|
||||
- "NUNCA execute comandos contendo 'git merge' ou 'git pull' sem autorização explícita e manual."
|
||||
- "Ao criar arquivos em C ou C++, utilize padrões modernos e mantenha o código limpo e documentado."
|
||||
|
||||
templates:
|
||||
c_header: |
|
||||
/*
|
||||
* =====================================================================================
|
||||
* Projeto: Sistemas Embarcados / Automação
|
||||
* Arquivo: {filename}
|
||||
* Autor: Agente Local Ruby (llama.cpp)
|
||||
* =====================================================================================
|
||||
*/
|
||||
|
||||
92
bin/agent
Normal file
92
bin/agent
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
#!/usr/bin/env ruby
|
||||
require 'fileutils'
|
||||
require 'json'
|
||||
require_relative '../lib/config'
|
||||
require_relative '../lib/registry'
|
||||
require_relative '../lib/backends/llama'
|
||||
require_relative '../lib/orchestrator'
|
||||
require_relative '../lib/tools'
|
||||
|
||||
# Carrega as configurações do projeto
|
||||
config = AgentConfig.load
|
||||
|
||||
# Configuração e Registro do Backend de Texto
|
||||
text_section = config.dig('backends', 'text') || {}
|
||||
default_provider = text_section['default']&.to_sym || :llama
|
||||
providers = text_section['providers'] || {}
|
||||
|
||||
BackendRegistry.register(:text, :llama, LlamaBackend)
|
||||
provider_config = providers[default_provider.to_s] || {}
|
||||
|
||||
begin
|
||||
llm_client = BackendRegistry.create(:text, default_provider, provider_config)
|
||||
rescue => e
|
||||
puts "\e[31m[!] Erro ao carregar backend #{default_provider}: #{e.message}\e[0m"
|
||||
exit 1
|
||||
end
|
||||
|
||||
# Inicializa o Orquestrador
|
||||
orchestrator = Orchestrator.new(llm_client)
|
||||
|
||||
puts "\e[32m=== Ruby Local AI Code Agent (Modular & Orchestrated) ===\e[0m"
|
||||
puts "\e[32m[✓] Pronto usando [text:#{default_provider}] com suporte a ferramentas e shell.\e[0m"
|
||||
puts "Digite 'sair' ou 'exit' para encerrar.\n\n"
|
||||
|
||||
# Loop principal do chat
|
||||
loop do
|
||||
print "\e[36mvocê > \e[0m"
|
||||
input = $stdin.gets&.strip
|
||||
break if input.nil? || %w[sair exit].include?(input.downcase)
|
||||
next if input.empty?
|
||||
|
||||
print "\e[33m[orquestrador] Analisando plano...\e[0m\r"
|
||||
|
||||
begin
|
||||
plan = orchestrator.plan(input)
|
||||
tasks = plan['tasks'] || []
|
||||
|
||||
print "\e[33m[orquestrador] Plano gerado com #{tasks.size} tarefa(s). Executando...\e[0m\n"
|
||||
|
||||
execution_context = []
|
||||
|
||||
# 1. Executa todas as tarefas (ferramentas ou prompts)
|
||||
tasks.each_with_index do |task, index|
|
||||
type = task['type']
|
||||
name = task['name'] || 'direto'
|
||||
puts "\e[34m -> [Tarefa #{index + 1}] Tipo: #{type} (#{name})\e[0m"
|
||||
|
||||
case type
|
||||
when 'tool'
|
||||
args = task['arguments'] || {}
|
||||
result = ToolRegistry.execute(name, args)
|
||||
execution_context << "Resultado da ferramenta #{name} com args #{args.to_json}:\n#{result}"
|
||||
|
||||
# Mostra o resultado detalhado da ferramenta no terminal
|
||||
puts "\e[90m Saída:\n#{result}\e[0m"
|
||||
|
||||
when 'text'
|
||||
prompt = task['prompt'] || input
|
||||
execution_context << prompt
|
||||
end
|
||||
end
|
||||
|
||||
# 2. SE houver contexto de ferramentas ou se o plano foi apenas de ferramentas,
|
||||
# faz uma chamada final ao modelo para ele interpretar e responder ao usuário.
|
||||
unless execution_context.empty?
|
||||
messages = [
|
||||
{ role: 'system', content: "Você é um assistente técnico em desenvolvimento de software. Resuma ou responda ao usuário com base nos resultados das ferramentas executadas no sistema." },
|
||||
{ role: 'user', content: "Solicitação original: #{input}\n\nContexto e resultados obtidos:\n#{execution_context.join("\n\n")}" }
|
||||
]
|
||||
|
||||
print "\e[35magente > \e[0m"
|
||||
response = llm_client.process(messages: messages)
|
||||
reply = response.dig('choices', 0, 'message', 'content')&.strip || "Concluído sem resposta textual."
|
||||
puts reply
|
||||
end
|
||||
|
||||
rescue => e
|
||||
puts "\e[31m[!] Erro durante o processamento do fluxo: #{e.message}\e[0m"
|
||||
end
|
||||
|
||||
puts "\n"
|
||||
end
|
||||
24
config/agent.yml
Normal file
24
config/agent.yml
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
# config/agent.yml
|
||||
backends:
|
||||
text:
|
||||
default: llama
|
||||
providers:
|
||||
llama:
|
||||
endpoint: "http://127.0.0.1:8080/v1/chat/completions"
|
||||
model: "local-model"
|
||||
timeout: 120
|
||||
|
||||
# Preparado para futuras expansões
|
||||
image:
|
||||
default: stable_diffusion
|
||||
providers:
|
||||
stable_diffusion:
|
||||
endpoint: "http://127.0.0.1:8081/v1/generation"
|
||||
timeout: 180
|
||||
|
||||
audio:
|
||||
default: local_tts
|
||||
providers:
|
||||
local_tts:
|
||||
endpoint: "http://127.0.0.1:8082/v1/audio"
|
||||
timeout: 60
|
||||
18
lib/backends/base.rb
Normal file
18
lib/backends/base.rb
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
# lib/backends/base.rb
|
||||
# Classe abstrata que define o contrato padrão para todos os backends do sistema.
|
||||
class BaseBackend
|
||||
# Retorna o identificador simbólico curto do backend (ex: :llama)
|
||||
def name
|
||||
raise NotImplementedError, "#{self.class} deve implementar o método #name"
|
||||
end
|
||||
|
||||
# Retorna uma descrição amigável da modalidade e do provedor
|
||||
def description
|
||||
raise NotImplementedError, "#{self.class} deve implementar o método #description"
|
||||
end
|
||||
|
||||
# Processa o payload específico da modalidade (mensagens, prompts ou parâmetros)
|
||||
def process(payload)
|
||||
raise NotImplementedError, "#{self.class} deve implementar o método #process"
|
||||
end
|
||||
end
|
||||
58
lib/backends/llama.rb
Normal file
58
lib/backends/llama.rb
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
# lib/backends/llama.rb
|
||||
require_relative 'base'
|
||||
require 'net/http'
|
||||
require 'json'
|
||||
require 'uri'
|
||||
|
||||
# Backend de texto e raciocínio baseado no llama.cpp (compatível com API OpenAI)
|
||||
class LlamaBackend < BaseBackend
|
||||
def initialize(config = {})
|
||||
@endpoint = config['endpoint'] || 'http://127.0.0.1:8080/v1/chat/completions'
|
||||
@model = config['model'] || 'local-model'
|
||||
@timeout = config['timeout'] || 120
|
||||
@uri = URI(@endpoint)
|
||||
end
|
||||
|
||||
# Identificador curto do backend
|
||||
def name
|
||||
:llama
|
||||
end
|
||||
|
||||
# Descrição amigável para exibição no CLI
|
||||
def description
|
||||
'Backend local de linguagem natural via llama.cpp (OpenAI-compatible)'
|
||||
end
|
||||
|
||||
# Processa mensagens de texto e ferramentas opcionais enviadas ao modelo
|
||||
def process(messages:, tools: nil)
|
||||
http = Net::HTTP.new(@uri.host, @uri.port)
|
||||
http.use_ssl = (@uri.scheme == 'https')
|
||||
http.open_timeout = 10
|
||||
http.read_timeout = @timeout
|
||||
|
||||
request = Net::HTTP::Post.new(@uri, {
|
||||
'Content-Type' => 'application/json',
|
||||
'Connection' => 'keep-alive'
|
||||
})
|
||||
|
||||
payload = {
|
||||
model: @model,
|
||||
messages: messages,
|
||||
temperature: 0.2
|
||||
}
|
||||
payload[:tools] = tools if tools && !tools.empty?
|
||||
|
||||
request.body = payload.to_json
|
||||
response = http.request(request)
|
||||
|
||||
unless response.is_a?(Net::HTTPSuccess)
|
||||
raise "Erro no llama.cpp: #{response.code} #{response.body}"
|
||||
end
|
||||
|
||||
JSON.parse(response.body)
|
||||
rescue Net::OpenTimeout, Net::ReadTimeout
|
||||
raise "Erro: Timeout na conexão com o llama.cpp."
|
||||
rescue Errno::ECONNRESET => e
|
||||
raise "Erro: Conexão resetada pelo servidor llama.cpp (ECONNRESET)."
|
||||
end
|
||||
end
|
||||
28
lib/config.rb
Normal file
28
lib/config.rb
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
# lib/config.rb
|
||||
require 'yaml'
|
||||
require 'fileutils'
|
||||
|
||||
class AgentConfig
|
||||
DEFAULT_PATH = 'config/agent.yml'
|
||||
|
||||
# Carrega o arquivo de configuração ou usa um fallback padrão se não existir
|
||||
def self.load(path = DEFAULT_PATH)
|
||||
if File.exist?(path)
|
||||
YAML.load_file(path) rescue {}
|
||||
else
|
||||
{
|
||||
'backends' => {
|
||||
'text' => {
|
||||
'default' => 'llama',
|
||||
'providers' => {
|
||||
'llama' => {
|
||||
'endpoint' => ENV.fetch('LLAMA_CPP_ENDPOINT', 'http://127.0.0.1:8080/v1/chat/completions'),
|
||||
'model' => 'local-model'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
end
|
||||
end
|
||||
end
|
||||
70
lib/orchestrator.rb
Normal file
70
lib/orchestrator.rb
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
# lib/orchestrator.rb
|
||||
require 'json'
|
||||
|
||||
class Orchestrator
|
||||
SYSTEM_PROMPT = <<~PROMPT.freeze
|
||||
Você é um planejador e orquestrador estrito de tarefas. Sua ÚNICA função é analisar a mensagem do usuário e retornar um objeto JSON contendo o plano de execução.
|
||||
NÃO responda à pergunta do usuário e NÃO crie textos de conversação no plano. Apenas categorize o pedido em tarefas.
|
||||
|
||||
REGRA CRÍTICA PARA O CAMPO "arguments":
|
||||
O campo "arguments" DEVE SER SEMPRE UM OBJETO (hash com chaves e valores). NUNCA envie uma string solta ou um array simples.
|
||||
|
||||
EXEMPLOS DE PLANOS CORRETOS:
|
||||
- Para saudação ou conversa geral:
|
||||
{"tasks": [{"type": "text", "prompt": "bom dia"}]} <-- (Repasse exatamente o que o usuário disse)
|
||||
|
||||
- Para listar diretório:
|
||||
{"tasks": [{"type": "tool", "name": "list_directory", "arguments": {"path": "."}}]}
|
||||
|
||||
- Para comandos bash:
|
||||
{"tasks": [{"type": "tool", "name": "bash", "arguments": {"command": "git status"}}]}
|
||||
|
||||
Retorne APENAS o JSON válido, sem blocos de markdown e sem texto adicional.
|
||||
PROMPT
|
||||
|
||||
def initialize(llm_client)
|
||||
@llm_client = llm_client
|
||||
end
|
||||
|
||||
def plan(user_message)
|
||||
messages = [
|
||||
{ role: 'system', content: SYSTEM_PROMPT },
|
||||
{ role: 'user', content: user_message }
|
||||
]
|
||||
|
||||
# --- LOG DE ENVIO ---
|
||||
puts "\n\e[33m[DEBUG] === ORCHESTRATOR REQUEST (Enviado ao LLM) ===\e[0m"
|
||||
puts JSON.pretty_generate(messages)
|
||||
puts "\e[33m[DEBUG] ================================================\e[0m"
|
||||
|
||||
response = @llm_client.process(messages: messages)
|
||||
raw_content = response.dig('choices', 0, 'message', 'content')&.strip
|
||||
|
||||
# --- LOG DE RESPOSTA BRUTA ---
|
||||
puts "\n\e[35m[DEBUG] === ORCHESTRATOR RAW RESPONSE (Recebido do LLM) ===\e[0m"
|
||||
p raw_content
|
||||
puts "\e[35m[DEBUG] ===================================================\e[0m"
|
||||
|
||||
raise "Orquestrador não retornou conteúdo." unless raw_content
|
||||
|
||||
cleaned_content = raw_content.gsub(/^```json\s*/, '').gsub(/^```\s*/, '').sub(/\s*```$/, '').strip
|
||||
|
||||
parsed = JSON.parse(cleaned_content)
|
||||
|
||||
# --- LOG DO JSON PARSEADO ---
|
||||
puts "\n\e[32m[DEBUG] === ORCHESTRATOR PARSED JSON (Estrutura final) ===\e[0m"
|
||||
puts JSON.pretty_generate(parsed)
|
||||
puts "\e[32m[DEBUG] ===================================================\e[0m\n"
|
||||
|
||||
parsed
|
||||
rescue JSON::ParserError => e
|
||||
puts "\e[31m[DEBUG] Erro de Parse JSON: #{e.message}\e[0m"
|
||||
{
|
||||
"tasks" => [
|
||||
{ "type" => "text", "prompt" => user_message }
|
||||
]
|
||||
}
|
||||
rescue => e
|
||||
raise "Erro na pré-análise do orquestrador: #{e.message}"
|
||||
end
|
||||
end
|
||||
23
lib/registry.rb
Normal file
23
lib/registry.rb
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
# lib/registry.rb
|
||||
# Gerencia o registro centralizado e a instanciação de backends por modalidade (tipo).
|
||||
class BackendRegistry
|
||||
@@backends = {}
|
||||
|
||||
# Registra um backend associado a um tipo (ex: :text => { llama: LlamaBackend })
|
||||
def self.register(type, key, klass)
|
||||
@@backends[type.to_sym] ||= {}
|
||||
@@backends[type.to_sym][key.to_sym] = klass
|
||||
end
|
||||
|
||||
# Retorna todos os backends disponíveis agrupados por tipo
|
||||
def self.available
|
||||
@@backends
|
||||
end
|
||||
|
||||
# Instancia e retorna um backend específico pelo tipo e chave com opções de configuração
|
||||
def self.create(type, key, config = {})
|
||||
klass = @@backends.dig(type.to_sym, key.to_sym)
|
||||
raise "Backend '#{key}' para o tipo '#{type}' não encontrado no registro." unless klass
|
||||
klass.new(config)
|
||||
end
|
||||
end
|
||||
82
lib/tools.rb
Normal file
82
lib/tools.rb
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
# lib/tools.rb
|
||||
require 'json'
|
||||
require 'fileutils'
|
||||
require 'open3'
|
||||
|
||||
class ToolRegistry
|
||||
@@tools = {}
|
||||
|
||||
def self.register(name, &block)
|
||||
@@tools[name.to_s] = block
|
||||
end
|
||||
|
||||
def self.execute(name, arguments)
|
||||
tool = @@tools[name.to_s]
|
||||
raise "Ferramenta '#{name}' não encontrada no registro." unless tool
|
||||
|
||||
# Exige estritamente um Hash com chaves simbolizadas
|
||||
normalized_args = arguments.is_a?(Hash) ? arguments.transform_keys(&:to_sym) : arguments
|
||||
tool.call(normalized_args)
|
||||
rescue => e
|
||||
"Erro ao executar a ferramenta #{name}: #{e.message}"
|
||||
end
|
||||
end
|
||||
|
||||
# --- Ferramentas ---
|
||||
|
||||
ToolRegistry.register('read_file') do |args|
|
||||
path = args[:path]
|
||||
raise "Argumento 'path' ausente ou inválido." unless path
|
||||
File.exist?(path) ? File.read(path) : "Erro: Arquivo não encontrado em '#{path}'."
|
||||
end
|
||||
|
||||
ToolRegistry.register('write_file') do |args|
|
||||
path = args[:path]
|
||||
content = args[:content] || ''
|
||||
raise "Argumento 'path' ausente." unless path
|
||||
|
||||
FileUtils.mkdir_p(File.dirname(path)) unless File.dirname(path) == '.'
|
||||
File.write(path, content)
|
||||
"Sucesso: Arquivo gravado em '#{path}' (#{content.bytesize} bytes)."
|
||||
end
|
||||
|
||||
ToolRegistry.register('delete_file') do |args|
|
||||
path = args[:path]
|
||||
raise "Argumento 'path' ausente." unless path
|
||||
|
||||
if File.exist?(path)
|
||||
File.delete(path)
|
||||
"Sucesso: Arquivo '#{path}' removido."
|
||||
else
|
||||
"Erro: Arquivo não encontrado em '#{path}'."
|
||||
end
|
||||
end
|
||||
|
||||
ToolRegistry.register('create_directory') do |args|
|
||||
path = args[:path]
|
||||
raise "Argumento 'path' ausente." unless path
|
||||
|
||||
FileUtils.mkdir_p(path)
|
||||
"Sucesso: Diretório criado em '#{path}'."
|
||||
end
|
||||
|
||||
ToolRegistry.register('list_directory') do |args|
|
||||
dir = args[:path] || '.'
|
||||
if Dir.exist?(dir)
|
||||
Dir.entries(dir).reject { |f| f == '.' || f == '..' }.to_json
|
||||
else
|
||||
"Erro: Diretório não encontrado em '#{dir}'."
|
||||
end
|
||||
end
|
||||
|
||||
ToolRegistry.register('bash') do |args|
|
||||
command = args[:command]
|
||||
raise "Argumento 'command' ausente." unless command
|
||||
|
||||
stdout, stderr, status = Open3.capture3(command)
|
||||
{
|
||||
exit_status: status.exitstatus,
|
||||
stdout: stdout.strip,
|
||||
stderr: stderr.strip
|
||||
}.to_json
|
||||
end
|
||||
Loading…
Add table
Reference in a new issue