File size: 8,830 Bytes
7fd1a0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
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
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
90
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
265
266
267
268
import os
import sys
import json
import subprocess
import textwrap
from pathlib import Path

import requests

# ==========================
# Configuração do modelo
# ==========================

DEFAULT_MODEL = os.environ.get("OLLAMA_MODEL", "qwen3.5:latest")

def detect_base_url():
    # Se o utilizador definir um endpoint (ex: HuggingFace), usamos esse
    env_base = os.environ.get("OLLAMA_API_BASE")
    if env_base:
        return env_base.rstrip("/")

    # Caso contrário, assumimos Ollama local
    return "http://localhost:11434"

BASE_URL = detect_base_url()

# ==========================
# Utilitários de terminal
# ==========================

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)

# ==========================
# Chamada ao modelo
# ==========================

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 ""

# ==========================
# Ferramentas do agente
# ==========================

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}"

# ==========================
# Prompt de agente
# ==========================

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:"

# ==========================
# Loop de agente
# ==========================

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

        # Construir prompt de agente
        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

        # Tentar interpretar JSON
        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()

# ==========================
# Entry point
# ==========================

if __name__ == "__main__":
    run_agent()