| import os
|
| import sys
|
| import json
|
| import subprocess
|
| import textwrap
|
| from pathlib import Path
|
|
|
| import requests
|
|
|
|
|
|
|
|
|
|
|
| DEFAULT_MODEL = os.environ.get("OLLAMA_MODEL", "qwen3.5:latest")
|
|
|
| def detect_base_url():
|
|
|
| env_base = os.environ.get("OLLAMA_API_BASE")
|
| if env_base:
|
| return env_base.rstrip("/")
|
|
|
|
|
| return "http://localhost:11434"
|
|
|
| BASE_URL = detect_base_url()
|
|
|
|
|
|
|
|
|
|
|
| def banner():
|
| print()
|
| print(" ▝▜▄ Ollama Dev Agent v1.0 (Gemini Style)")
|
| print(" ▝▜▄")
|
| print(" ▗▟▀ Local / Remote Hybrid AI Dev Agent")
|
| print(f" ▝▀ Model: {DEFAULT_MODEL}")
|
| print()
|
| print("╭──────────────────────────────────────────────────────────────────────────────╮")
|
| print("│ Fala em linguagem natural. │")
|
| print("│ Ex.: 'cria uma app python que mostra WELCOME no meio do ecrã'. │")
|
| print("│ O agente pode: │")
|
| print("│ • ler / escrever ficheiros no diretório atual │")
|
| print("│ • criar projetos │")
|
| print("│ • correr comandos (python, node, etc.) │")
|
| print("│ │")
|
| print("│ Comandos especiais: │")
|
| print("│ /exit sai │")
|
| print("│ /pwd mostra diretório atual │")
|
| print("│ /ls lista ficheiros │")
|
| print("╰──────────────────────────────────────────────────────────────────────────────╯")
|
| print()
|
|
|
| def info(msg):
|
| print(f"[info] {msg}")
|
|
|
| def warn(msg):
|
| print(f"[warn] {msg}")
|
|
|
| def error(msg):
|
| print(f"[erro] {msg}", file=sys.stderr)
|
|
|
|
|
|
|
|
|
|
|
| def call_ollama(prompt: str, model: str = DEFAULT_MODEL) -> str:
|
| url = f"{BASE_URL}/api/generate"
|
| payload = {
|
| "model": model,
|
| "prompt": prompt,
|
| "stream": False,
|
| }
|
| try:
|
| resp = requests.post(url, json=payload, timeout=300)
|
| resp.raise_for_status()
|
| data = resp.json()
|
| return data.get("response", "").strip()
|
| except Exception as e:
|
| error(f"Falha ao chamar o modelo: {e}")
|
| return ""
|
|
|
|
|
|
|
|
|
|
|
| def tool_read_file(path: str) -> str:
|
| p = Path(path)
|
| if not p.exists():
|
| return f"[ERRO] Ficheiro não encontrado: {path}"
|
| try:
|
| return p.read_text(encoding="utf-8", errors="ignore")
|
| except Exception as e:
|
| return f"[ERRO] Ao ler {path}: {e}"
|
|
|
| def tool_write_file(path: str, content: str) -> str:
|
| p = Path(path)
|
| try:
|
| p.parent.mkdir(parents=True, exist_ok=True)
|
| p.write_text(content, encoding="utf-8")
|
| return f"[OK] Escrito: {path}"
|
| except Exception as e:
|
| return f"[ERRO] Ao escrever {path}: {e}"
|
|
|
| def tool_run_command(cmd: str) -> str:
|
| try:
|
| completed = subprocess.run(
|
| cmd,
|
| shell=True,
|
| capture_output=True,
|
| text=True,
|
| )
|
| out = completed.stdout.strip()
|
| err = completed.stderr.strip()
|
| result = []
|
| if out:
|
| result.append("[STDOUT]")
|
| result.append(out)
|
| if err:
|
| result.append("[STDERR]")
|
| result.append(err)
|
| if not result:
|
| result.append("[OK] Comando executado sem output.")
|
| return "\n".join(result)
|
| except Exception as e:
|
| return f"[ERRO] Ao executar comando '{cmd}': {e}"
|
|
|
|
|
|
|
|
|
|
|
| AGENT_SYSTEM_PROMPT = textwrap.dedent("""
|
| És um agente de desenvolvimento local.
|
|
|
| Tens acesso às seguintes ferramentas:
|
|
|
| 1) read_file(path: string) -> string
|
| - Lê o conteúdo de um ficheiro de texto.
|
|
|
| 2) write_file(path: string, content: string) -> string
|
| - Cria ou substitui um ficheiro com o conteúdo dado.
|
|
|
| 3) run_command(command: string) -> string
|
| - Executa um comando no sistema (ex.: "python main.py").
|
|
|
| Regras:
|
| - Trabalhas SEMPRE no diretório atual do utilizador.
|
| - Quando o utilizador pedir para criar uma app, deves:
|
| - planear os ficheiros necessários
|
| - criar os ficheiros com write_file
|
| - se fizer sentido, correr a app com run_command
|
| - Responde SEMPRE num JSON válido, sem texto extra, no formato:
|
|
|
| {
|
| "thoughts": "breve explicação do que vais fazer",
|
| "steps": [
|
| {
|
| "tool": "write_file" | "read_file" | "run_command",
|
| "args": {
|
| "path": "caminho/ficheiro.txt", // para read/write_file
|
| "content": "..." // para write_file
|
| "command": "..." // para run_command
|
| },
|
| "comment": "explicação curta em português"
|
| }
|
| ]
|
| }
|
|
|
| Não uses markdown, não uses comentários fora do JSON.
|
| """).strip()
|
|
|
| def build_agent_prompt(user_message: str) -> str:
|
| return AGENT_SYSTEM_PROMPT + "\n\nUtilizador:\n" + user_message + "\n\nJSON:"
|
|
|
|
|
|
|
|
|
|
|
| def run_agent():
|
| banner()
|
| while True:
|
| try:
|
| user = input("> ").strip()
|
| except (EOFError, KeyboardInterrupt):
|
| print()
|
| break
|
|
|
| if not user:
|
| continue
|
|
|
| if user.lower() in ("/exit", "exit", "quit"):
|
| break
|
|
|
| if user.lower() == "/pwd":
|
| print(os.getcwd())
|
| continue
|
|
|
| if user.lower() == "/ls":
|
| for p in sorted(Path(".").iterdir()):
|
| print(p)
|
| continue
|
|
|
|
|
| prompt = build_agent_prompt(user)
|
| info("A pedir plano ao modelo...")
|
| raw = call_ollama(prompt)
|
| if not raw:
|
| warn("Sem resposta do modelo. A mostrar resposta bruta:")
|
| print(raw)
|
| continue
|
|
|
|
|
| try:
|
| plan = json.loads(raw)
|
| except json.JSONDecodeError:
|
| warn("Modelo não devolveu JSON válido. A mostrar resposta bruta:")
|
| print(raw)
|
| continue
|
|
|
| thoughts = plan.get("thoughts", "")
|
| steps = plan.get("steps", [])
|
|
|
| if thoughts:
|
| print()
|
| print("🧠 Plano:")
|
| print(thoughts)
|
| print()
|
|
|
| if not isinstance(steps, list) or not steps:
|
| warn("Nenhum passo encontrado no plano.")
|
| continue
|
|
|
| for i, step in enumerate(steps, start=1):
|
| tool = step.get("tool")
|
| args = step.get("args", {}) or {}
|
| comment = step.get("comment", "")
|
|
|
| print(f"--- Passo {i}: {tool} ---")
|
| if comment:
|
| print(f"# {comment}")
|
|
|
| result = ""
|
|
|
| if tool == "read_file":
|
| path = args.get("path", "")
|
| result = tool_read_file(path)
|
|
|
| elif tool == "write_file":
|
| path = args.get("path", "")
|
| content = args.get("content", "")
|
| result = tool_write_file(path, content)
|
|
|
| elif tool == "run_command":
|
| cmd = args.get("command", "")
|
| result = tool_run_command(cmd)
|
|
|
| else:
|
| result = f"[ERRO] Ferramenta desconhecida: {tool}"
|
|
|
| print(result)
|
| print()
|
|
|
|
|
|
|
|
|
|
|
| if __name__ == "__main__":
|
| run_agent()
|
|
|