Justin-lee commited on
Commit
8ebd4a7
·
verified ·
1 Parent(s): 1e8fbb1

Add CodePilot v4: duel toggle, context memory, LeetCode auto-grind

Browse files
Files changed (1) hide show
  1. codepilot_v4.py +713 -0
codepilot_v4.py ADDED
@@ -0,0 +1,713 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ CodePilot v4 — AI 開發助手 + 自動進化
5
+ ======================================
6
+
7
+ v4 新功能:
8
+ 🔄 /duel on|off — 雙模型比較開關,開啟後每個問題自動 DPO 配對
9
+ 🧠 上下文記憶 — CODEPILOT.md 專案記憶 + 對話歷史 + 文件快取
10
+ 🏋️ /grind — LeetCode 自動刷題,無人值守產生訓練數據
11
+
12
+ Usage:
13
+ codepilot # 本地模型
14
+ codepilot --provider openrouter --api-key sk-xxx # 雲端
15
+ codepilot --duel --provider openrouter --api-key sk-xxx --adapter ./my-adapter
16
+ codepilot --grind # 自動刷 LeetCode
17
+ codepilot --grind --provider openrouter --api-key sk-xxx # 用雲端刷題蒸餾
18
+ """
19
+
20
+ import argparse, difflib, json, os, re, shutil, sqlite3, subprocess, sys, torch, time
21
+ from datetime import datetime
22
+ from pathlib import Path
23
+
24
+ try:
25
+ import httpx
26
+ except ImportError:
27
+ httpx = None
28
+
29
+ DEFAULT_LOCAL_MODEL = "Qwen/Qwen2.5-Coder-3B-Instruct"
30
+ CONFIG_DIR = os.path.expanduser("~/.codepilot")
31
+ DB_PATH = os.path.join(CONFIG_DIR, "feedback.db")
32
+
33
+ PROVIDER_CONFIGS = {
34
+ "local": {"name": "Local", "type": "local"},
35
+ "openai": {"name": "OpenAI", "type": "openai", "base_url": "https://api.openai.com/v1", "default_model": "gpt-4o"},
36
+ "anthropic": {"name": "Anthropic", "type": "anthropic", "base_url": "https://api.anthropic.com/v1", "default_model": "claude-sonnet-4-20250514"},
37
+ "openrouter": {"name": "OpenRouter", "type": "openai", "base_url": "https://openrouter.ai/api/v1", "default_model": "anthropic/claude-sonnet-4"},
38
+ "ollama": {"name": "Ollama", "type": "openai", "base_url": "http://localhost:11434/v1", "default_model": "qwen2.5-coder:3b"},
39
+ }
40
+
41
+
42
+ # ============================================================
43
+ # FEEDBACK DB
44
+ # ============================================================
45
+ class FeedbackDB:
46
+ def __init__(self):
47
+ os.makedirs(CONFIG_DIR, exist_ok=True)
48
+ self.conn = sqlite3.connect(DB_PATH)
49
+ self.conn.execute("""CREATE TABLE IF NOT EXISTS feedback (
50
+ id INTEGER PRIMARY KEY, timestamp TEXT, prompt TEXT, completion TEXT,
51
+ label INTEGER, edited_completion TEXT, project TEXT,
52
+ source_model TEXT, provider TEXT)""")
53
+ self.conn.commit()
54
+
55
+ def save(self, prompt, completion, label, edited=None, project=None,
56
+ source_model=None, provider=None):
57
+ self.conn.execute("INSERT INTO feedback VALUES (NULL,?,?,?,?,?,?,?,?)",
58
+ (datetime.now().isoformat(), prompt, completion, int(label),
59
+ edited, project, source_model, provider))
60
+ self.conn.commit()
61
+
62
+ def count(self, provider=None):
63
+ q = "SELECT COUNT(*), COALESCE(SUM(label),0), SUM(CASE WHEN edited_completion IS NOT NULL THEN 1 ELSE 0 END) FROM feedback"
64
+ r = self.conn.execute(q + (" WHERE provider=?" if provider else ""), (provider,) if provider else ()).fetchone()
65
+ return {"total": r[0], "up": int(r[1]), "edits": int(r[2] or 0)}
66
+
67
+ def export_sft(self, only_cloud=False):
68
+ if only_cloud:
69
+ rows = self.conn.execute("SELECT prompt, completion FROM feedback WHERE label=1 AND provider != 'local' AND provider IS NOT NULL").fetchall()
70
+ else:
71
+ rows = self.conn.execute("SELECT prompt, COALESCE(edited_completion, completion) FROM feedback WHERE label=1").fetchall()
72
+ return [{"messages": [{"role": "user", "content": p}, {"role": "assistant", "content": c}]} for p, c in rows]
73
+
74
+ def export_dpo(self):
75
+ rows = self.conn.execute("""SELECT c.prompt, c.completion, l.completion FROM feedback c
76
+ JOIN feedback l ON c.prompt = l.prompt WHERE c.provider != 'local' AND c.label = 1
77
+ AND l.provider = 'local' AND l.label = 0""").fetchall()
78
+ return [{"prompt": [{"role": "user", "content": p}], "chosen": [{"role": "assistant", "content": c}],
79
+ "rejected": [{"role": "assistant", "content": l}]} for p, c, l in rows]
80
+
81
+ def export_kto(self):
82
+ rows = self.conn.execute("SELECT prompt, completion, label FROM feedback").fetchall()
83
+ return [{"prompt": [{"role": "user", "content": p}], "completion": [{"role": "assistant", "content": c}], "label": bool(l)} for p, c, l in rows]
84
+
85
+
86
+ # ============================================================
87
+ # PROJECT CONTEXT — 記憶系統
88
+ # ============================================================
89
+ class ProjectContext:
90
+ """專案上下文記憶"""
91
+
92
+ def __init__(self, project_dir):
93
+ self.project_dir = project_dir
94
+ self.memory_file = os.path.join(project_dir, "CODEPILOT.md")
95
+ self.session_file = os.path.join(CONFIG_DIR, "sessions",
96
+ os.path.basename(project_dir) + ".json")
97
+ os.makedirs(os.path.dirname(self.session_file), exist_ok=True)
98
+
99
+ def load_memory(self):
100
+ """讀取 CODEPILOT.md 專案記憶"""
101
+ if os.path.exists(self.memory_file):
102
+ return Path(self.memory_file).read_text(encoding="utf-8")
103
+ return ""
104
+
105
+ def save_memory(self, content):
106
+ """保存專案記憶"""
107
+ Path(self.memory_file).write_text(content, encoding="utf-8")
108
+
109
+ def load_session(self):
110
+ """載入上次對話"""
111
+ if os.path.exists(self.session_file):
112
+ try:
113
+ data = json.loads(Path(self.session_file).read_text())
114
+ # 只保留最近 20 輪對話(防止 context 爆掉)
115
+ msgs = data.get("messages", [])
116
+ if len(msgs) > 42: # system + 20 rounds * 2 + buffer
117
+ msgs = [msgs[0]] + msgs[-40:]
118
+ return msgs
119
+ except:
120
+ pass
121
+ return None
122
+
123
+ def save_session(self, messages):
124
+ """保存當前對話"""
125
+ # 只保最近 20 輪
126
+ if len(messages) > 42:
127
+ messages = [messages[0]] + messages[-40:]
128
+ Path(self.session_file).write_text(
129
+ json.dumps({"messages": messages, "timestamp": datetime.now().isoformat()},
130
+ ensure_ascii=False))
131
+
132
+
133
+ # ============================================================
134
+ # MODEL BACKENDS
135
+ # ============================================================
136
+ class LocalModel:
137
+ def __init__(self, model_name=DEFAULT_LOCAL_MODEL, adapter_path=None):
138
+ from transformers import AutoTokenizer, AutoModelForCausalLM
139
+ self.name = model_name.split("/")[-1]; self.provider = "local"
140
+ self.tokenizer = AutoTokenizer.from_pretrained(model_name)
141
+ if self.tokenizer.pad_token is None: self.tokenizer.pad_token = self.tokenizer.eos_token
142
+ self.model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.bfloat16, device_map="auto", trust_remote_code=True)
143
+ if adapter_path and os.path.exists(adapter_path):
144
+ from peft import PeftModel; self.model = PeftModel.from_pretrained(self.model, adapter_path)
145
+ self.model.eval()
146
+
147
+ def chat(self, messages, max_tokens=4096):
148
+ text = self.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
149
+ inputs = self.tokenizer(text, return_tensors="pt").to(self.model.device)
150
+ with torch.no_grad():
151
+ out = self.model.generate(**inputs, max_new_tokens=max_tokens, do_sample=True, temperature=0.7, top_p=0.9, repetition_penalty=1.1, pad_token_id=self.tokenizer.pad_token_id)
152
+ return self.tokenizer.decode(out[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True)
153
+
154
+
155
+ class CloudModel:
156
+ def __init__(self, provider_key, api_key, model_name=None):
157
+ config = PROVIDER_CONFIGS[provider_key]
158
+ self.provider = provider_key; self.base_url = config["base_url"]
159
+ self.name = model_name or config["default_model"]; self.api_key = api_key; self.api_type = config["type"]
160
+
161
+ def chat(self, messages, max_tokens=4096):
162
+ if self.api_type == "anthropic": return self._anthropic(messages, max_tokens)
163
+ else: return self._openai(messages, max_tokens)
164
+
165
+ def _openai(self, messages, max_tokens):
166
+ headers = {"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json"}
167
+ if self.provider == "openrouter": headers.update({"HTTP-Referer": "https://codepilot.local", "X-Title": "CodePilot"})
168
+ resp = httpx.post(f"{self.base_url}/chat/completions", headers=headers,
169
+ json={"model": self.name, "messages": messages, "max_tokens": max_tokens, "temperature": 0.7}, timeout=120)
170
+ resp.raise_for_status(); return resp.json()["choices"][0]["message"]["content"]
171
+
172
+ def _anthropic(self, messages, max_tokens):
173
+ system = None; chat_msgs = []
174
+ for m in messages:
175
+ if m["role"] == "system": system = m["content"]
176
+ else: chat_msgs.append(m)
177
+ data = {"model": self.name, "messages": chat_msgs, "max_tokens": max_tokens, "temperature": 0.7}
178
+ if system: data["system"] = system
179
+ resp = httpx.post(f"{self.base_url}/messages", headers={"x-api-key": self.api_key, "Content-Type": "application/json", "anthropic-version": "2023-06-01"}, json=data, timeout=120)
180
+ resp.raise_for_status(); return resp.json()["content"][0]["text"]
181
+
182
+
183
+ # ============================================================
184
+ # PROJECT TOOLS
185
+ # ============================================================
186
+ class ProjectTools:
187
+ def __init__(self, project_dir):
188
+ self.project_dir = os.path.abspath(project_dir); self.cwd = self.project_dir; self.read_cache = {}
189
+
190
+ def _resolve(self, path):
191
+ return path if os.path.isabs(path) else os.path.normpath(os.path.join(self.cwd, path))
192
+
193
+ def read_file(self, path, offset=1, limit=200):
194
+ full = self._resolve(path)
195
+ if not os.path.exists(full): return f"❌ 不存在: {path}"
196
+ try:
197
+ content = Path(full).read_text(encoding="utf-8", errors="replace"); lines = content.splitlines()
198
+ self.read_cache[full] = {"time": os.path.getmtime(full), "content": content}
199
+ result = "\n".join(f"{i+offset:4d} │ {line}" for i, line in enumerate(lines[offset-1:offset-1+limit]))
200
+ if offset + limit < len(lines): result += f"\n... ({len(lines)-offset-limit+1} more)"
201
+ return result
202
+ except Exception as e: return f"❌ {e}"
203
+
204
+ def edit_file(self, path, old_string, new_string):
205
+ full = self._resolve(path)
206
+ if full not in self.read_cache: return "❌ 必須先 read_file"
207
+ content = Path(full).read_text(encoding="utf-8")
208
+ if os.path.getmtime(full) != self.read_cache[full]["time"]: return "❌ 文件已被外部修改"
209
+ count = content.count(old_string)
210
+ if count == 0: return "❌ 找不到要替換的文字"
211
+ if count > 1: return f"❌ 找到 {count} 處,請提供更多上下文"
212
+ new_content = content.replace(old_string, new_string, 1)
213
+ diff = "".join(difflib.unified_diff(content.splitlines(keepends=True), new_content.splitlines(keepends=True), fromfile=f"a/{path}", tofile=f"b/{path}"))
214
+ Path(full).write_text(new_content, encoding="utf-8")
215
+ self.read_cache[full] = {"time": os.path.getmtime(full), "content": new_content}
216
+ return "✅ 已修改:\n" + diff
217
+
218
+ def write_file(self, path, content):
219
+ full = self._resolve(path); os.makedirs(os.path.dirname(full) or ".", exist_ok=True)
220
+ is_new = not os.path.exists(full); Path(full).write_text(content, encoding="utf-8")
221
+ self.read_cache[full] = {"time": os.path.getmtime(full), "content": content}
222
+ return f"✅ {'建立' if is_new else '覆寫'}: {path}"
223
+
224
+ def run_command(self, command, timeout=120):
225
+ for d in {"rm -rf /", "git push --force", "git reset --hard"}:
226
+ if d in command: return f"⛔ 危險: {command}"
227
+ try:
228
+ r = subprocess.run(command, shell=True, cwd=self.cwd, capture_output=True, text=True, timeout=timeout)
229
+ return (r.stdout + (f"\nSTDERR:\n{r.stderr}" if r.stderr else ""))[:10000]
230
+ except subprocess.TimeoutExpired: return "⏰ 超時"
231
+ except Exception as e: return f"❌ {e}"
232
+
233
+ def search_files(self, pattern, glob_pattern=None):
234
+ rg = shutil.which("rg"); cmd = [rg or "grep", "-rn"]
235
+ if rg: cmd += ["--color=never", "--max-count=50"]
236
+ if glob_pattern and rg: cmd += ["--glob", glob_pattern]
237
+ cmd += [pattern, self.cwd]
238
+ try: return subprocess.run(cmd, capture_output=True, text=True, timeout=30).stdout[:5000] or "無匹配"
239
+ except Exception as e: return f"❌ {e}"
240
+
241
+ def list_files(self, pattern="*", max_depth=3):
242
+ files = []
243
+ for root, dirs, fnames in os.walk(self.cwd):
244
+ dirs[:] = [d for d in dirs if d not in {".git","node_modules","__pycache__",".venv","dist","build"}]
245
+ if root.replace(self.cwd, "").count(os.sep) >= max_depth: continue
246
+ files.extend(os.path.relpath(os.path.join(root, f), self.cwd) for f in fnames if Path(f).match(pattern))
247
+ return "\n".join(sorted(files)[:100])
248
+
249
+ def git_context(self):
250
+ try:
251
+ b = subprocess.run(["git","branch","--show-current"], cwd=self.project_dir, capture_output=True, text=True).stdout.strip()
252
+ s = subprocess.run(["git","status","--short"], cwd=self.project_dir, capture_output=True, text=True).stdout.strip()
253
+ l = subprocess.run(["git","log","--oneline","-5"], cwd=self.project_dir, capture_output=True, text=True).stdout.strip()
254
+ return f"Branch: {b}\nStatus:\n{s}\nRecent:\n{l}"
255
+ except: return "(not a git repo)"
256
+
257
+
258
+ TOOL_PATTERN = re.compile(r'<tool>\s*(\w+)\s*\n(.*?)</tool>', re.DOTALL)
259
+
260
+ def parse_tool_calls(text):
261
+ calls = []
262
+ for m in TOOL_PATTERN.finditer(text):
263
+ try: params = json.loads(m.group(2).strip())
264
+ except:
265
+ params = {}
266
+ for line in m.group(2).strip().split("\n"):
267
+ if ":" in line: k, v = line.split(":", 1); params[k.strip()] = v.strip().strip('"')
268
+ calls.append({"tool": m.group(1), "params": params})
269
+ return calls
270
+
271
+ def execute_tool(tools, call):
272
+ n, p = call["tool"], call["params"]
273
+ try:
274
+ if n == "read_file": return tools.read_file(p.get("path",""), int(p.get("offset",1)), int(p.get("limit",200)))
275
+ elif n == "edit_file": return tools.edit_file(p.get("path",""), p.get("old_string",""), p.get("new_string",""))
276
+ elif n == "write_file": return tools.write_file(p.get("path",""), p.get("content",""))
277
+ elif n == "run_command": return tools.run_command(p.get("command",""), int(p.get("timeout",120)))
278
+ elif n == "search_files": return tools.search_files(p.get("pattern",""), p.get("glob"))
279
+ elif n == "list_files": return tools.list_files(p.get("pattern","*"), int(p.get("max_depth",3)))
280
+ elif n == "git_status": return tools.git_context()
281
+ else: return f"❌ 未知: {n}"
282
+ except Exception as e: return f"❌ {e}"
283
+
284
+
285
+ def build_system_prompt(tools, project_memory=""):
286
+ memory_section = f"\n\n## Project Memory (CODEPILOT.md)\n{project_memory}" if project_memory else ""
287
+ return f"""You are CodePilot, an expert AI programming assistant working in the user's project.
288
+
289
+ Working directory: {tools.cwd}
290
+ {tools.git_context()}{memory_section}
291
+
292
+ ## Tools (use <tool>name\n{{json}}</tool>)
293
+ - read_file: {{"path":"...","offset":1,"limit":200}}
294
+ - edit_file: {{"path":"...","old_string":"...","new_string":"..."}} (must read first)
295
+ - write_file: {{"path":"...","content":"..."}}
296
+ - run_command: {{"command":"...","timeout":120}}
297
+ - search_files: {{"pattern":"...","glob":"*.py"}}
298
+ - list_files: {{"pattern":"*","max_depth":3}}
299
+ - git_status: {{}}
300
+
301
+ Rules: read before edit, old_string must be unique, prefer edit over write, verify changes."""
302
+
303
+
304
+ # ============================================================
305
+ # LEETCODE AUTO-GRIND
306
+ # ============================================================
307
+ def run_grind(args, num_problems=100):
308
+ """自動刷 LeetCode 題目,產生訓練數據"""
309
+ from rich.console import Console
310
+ from rich.progress import Progress
311
+ console = Console()
312
+ db = FeedbackDB()
313
+
314
+ console.print(f"""
315
+ ╔════════════════════════════════════════════════════════════╗
316
+ ║ 🏋️ LeetCode Auto-Grind ║
317
+ ║ 自動刷題,無人值守產生訓練數據 ║
318
+ ╚════════════════════════════════════════════════════════════╝
319
+ """)
320
+
321
+ # 載入模型
322
+ provider_key = args.provider or "local"
323
+ if provider_key == "local":
324
+ with console.status("[bold green]載入本地模型..."):
325
+ model = LocalModel(args.model or DEFAULT_LOCAL_MODEL, args.adapter)
326
+ else:
327
+ if not args.api_key:
328
+ console.print("[red]❌ 需要 --api-key[/]"); return
329
+ cloud_model_name = args.cloud_model or PROVIDER_CONFIGS[provider_key]["default_model"]
330
+ model = CloudModel(provider_key, args.api_key, cloud_model_name)
331
+ console.print(f"[green]✅ 模型: {model.name}[/]")
332
+
333
+ # 載入 KodCode 題目
334
+ console.print("📦 載入 KodCode 題庫...")
335
+ from datasets import load_dataset
336
+ dataset = load_dataset("KodCode/KodCode-V1", split="train")
337
+ dataset = dataset.shuffle(seed=int(time.time()) % 10000).select(range(min(num_problems, len(dataset))))
338
+ console.print(f" {len(dataset)} 題已載入\n")
339
+
340
+ passed = 0
341
+ failed = 0
342
+ errors = 0
343
+
344
+ with Progress() as progress:
345
+ task = progress.add_task("[cyan]刷題中...", total=len(dataset))
346
+
347
+ for i, problem in enumerate(dataset):
348
+ question = problem["question"]
349
+ test_code = problem["test"]
350
+ solution_ref = problem["solution"]
351
+
352
+ prompt = f"Write a Python solution. Provide ONLY the code, no explanation.\n\n{question}"
353
+ messages = [
354
+ {"role": "system", "content": "You are an expert Python programmer. Output only clean Python code."},
355
+ {"role": "user", "content": prompt},
356
+ ]
357
+
358
+ # 生成回答
359
+ try:
360
+ response = model.chat(messages, max_tokens=1024)
361
+ except Exception as e:
362
+ errors += 1; progress.update(task, advance=1); continue
363
+
364
+ # 提取 code
365
+ code = response
366
+ if "```python" in code: code = code.split("```python")[1].split("```")[0]
367
+ elif "```" in code: code = code.split("```")[1].split("```")[0]
368
+
369
+ # 執行測試
370
+ reward = 0.0
371
+ try:
372
+ import tempfile
373
+ with tempfile.TemporaryDirectory() as tmpdir:
374
+ Path(os.path.join(tmpdir, "solution.py")).write_text(code)
375
+ Path(os.path.join(tmpdir, "test_solution.py")).write_text(test_code)
376
+ r = subprocess.run(
377
+ [sys.executable, "-m", "pytest", "test_solution.py", "-x", "--tb=no", "-q"],
378
+ cwd=tmpdir, capture_output=True, text=True, timeout=15)
379
+ if r.returncode == 0:
380
+ reward = 1.0; passed += 1
381
+ else:
382
+ reward = 0.0; failed += 1
383
+ except:
384
+ reward = 0.0; failed += 1
385
+
386
+ # 記錄數據
387
+ if reward == 1.0:
388
+ # 通過測試 → 記為好答案 (SFT + KTO positive)
389
+ db.save(prompt, code, 1, source_model=model.name,
390
+ provider=getattr(model, "provider", provider_key))
391
+ else:
392
+ # 失敗 → 記為壞答案,同時記錄正確答案
393
+ db.save(prompt, code, 0, source_model=model.name,
394
+ provider=getattr(model, "provider", provider_key))
395
+ # 正確答案記為 SFT
396
+ if solution_ref:
397
+ db.save(prompt, solution_ref, 1, source_model="ground_truth",
398
+ provider="reference")
399
+
400
+ progress.update(task, advance=1,
401
+ description=f"[cyan]刷題中... ✅{passed} ❌{failed}")
402
+
403
+ # 統計
404
+ total = passed + failed + errors
405
+ console.print(f"\n{'='*50}")
406
+ console.print(f" 🏋️ 刷題完成!")
407
+ console.print(f" ✅ 通過: {passed}/{total} ({100*passed/max(total,1):.0f}%)")
408
+ console.print(f" ❌ 失敗: {failed}/{total}")
409
+ console.print(f" ⚠️ 錯誤: {errors}")
410
+ console.print(f"\n 📊 數據統計:")
411
+ s = db.count()
412
+ console.print(f" 總數據: {s['total']}")
413
+ console.print(f" 👍: {s['up']} / 👎: {s['total']-s['up']}")
414
+ console.print(f"\n 💡 運行 codepilot --train 開始訓練")
415
+
416
+
417
+ # ============================================================
418
+ # MAIN AGENT LOOP
419
+ # ============================================================
420
+ def run_agent_loop(args):
421
+ from rich.console import Console, Group
422
+ from rich.markdown import Markdown
423
+ from rich.panel import Panel
424
+ from rich.prompt import Prompt
425
+ from rich.syntax import Syntax
426
+ from rich.table import Table
427
+
428
+ console = Console(); db = FeedbackDB()
429
+ project_dir = args.project or os.getcwd()
430
+ tools = ProjectTools(project_dir)
431
+ ctx = ProjectContext(project_dir)
432
+ provider_key = args.provider or "local"
433
+
434
+ # 載入模型
435
+ local_model_ref = None; cloud_model_ref = None
436
+ if provider_key == "local":
437
+ with console.status("[bold green]載入本地模型..."):
438
+ model = LocalModel(args.model or DEFAULT_LOCAL_MODEL, args.adapter)
439
+ local_model_ref = model
440
+ else:
441
+ if not args.api_key: console.print(f"[red]❌ 需要 --api-key[/]"); sys.exit(1)
442
+ model = CloudModel(provider_key, args.api_key, args.cloud_model or PROVIDER_CONFIGS[provider_key]["default_model"])
443
+ cloud_model_ref = model
444
+ if args.adapter:
445
+ try:
446
+ with console.status("[dim]載入本地模型 (for duel)..."):
447
+ local_model_ref = LocalModel(args.model or DEFAULT_LOCAL_MODEL, args.adapter)
448
+ console.print("[dim]✅ 本地模型已載入[/]")
449
+ except: pass
450
+
451
+ # Duel 模式開關
452
+ duel_mode = args.duel and local_model_ref and cloud_model_ref
453
+
454
+ # 專案記憶
455
+ project_memory = ctx.load_memory()
456
+
457
+ # Banner
458
+ banner = f"[bold cyan]CodePilot v4[/]"
459
+ if duel_mode: banner += " [bold yellow]⚔️ Duel ON[/]"
460
+ banner += f"\n[dim]Model: {model.name}\nProject: {project_dir}[/]"
461
+ if project_memory: banner += f"\n[dim]📝 CODEPILOT.md loaded ({len(project_memory)} chars)[/]"
462
+ console.print(Panel.fit(banner, border_style="cyan"))
463
+
464
+ git_ctx = tools.git_context()
465
+ if git_ctx != "(not a git repo)": console.print(Panel(git_ctx, title="📂 Project", border_style="dim"))
466
+
467
+ # 嘗試恢復上次對話
468
+ system_prompt = build_system_prompt(tools, project_memory)
469
+ prev_session = ctx.load_session()
470
+ if prev_session and len(prev_session) > 1:
471
+ messages = prev_session
472
+ # 更新 system prompt
473
+ messages[0] = {"role": "system", "content": system_prompt}
474
+ console.print(f"[dim]🔄 已恢復上次對話 ({(len(messages)-1)//2} 輪)[/]")
475
+ else:
476
+ messages = [{"role": "system", "content": system_prompt}]
477
+
478
+ console.print("[dim]/duel on|off /memo /grind /ls /git /clear /status /train /quit[/]\n")
479
+
480
+ while True:
481
+ try: user_input = Prompt.ask("\n[bold green]🧑 You")
482
+ except (EOFError, KeyboardInterrupt): break
483
+ if not user_input.strip(): continue
484
+ cmd = user_input.strip()
485
+
486
+ # ---- 指令 ----
487
+ if cmd in ("/quit", "/exit"): break
488
+
489
+ elif cmd == "/duel on":
490
+ if local_model_ref and cloud_model_ref:
491
+ duel_mode = True; console.print("[yellow]⚔️ Duel 模式已開啟 — 每個問題自動雙模型比較[/]")
492
+ else:
493
+ console.print("[red]需要同時有本地和雲端模型。啟動: codepilot --duel --provider openrouter --api-key xxx --adapter ./adapter[/]")
494
+ continue
495
+
496
+ elif cmd == "/duel off":
497
+ duel_mode = False; console.print("[dim]Duel 模式已關閉[/]"); continue
498
+
499
+ elif cmd == "/memo":
500
+ console.print(f"[bold]📝 CODEPILOT.md[/]")
501
+ console.print("[dim]輸入專案筆記(END 結束),會注入每次對話的 system prompt:[/]")
502
+ lines = []
503
+ if project_memory: console.print(f"[dim]目前內容:\n{project_memory[:500]}[/]\n")
504
+ while True:
505
+ try:
506
+ l = input()
507
+ if l.strip() == "END": break
508
+ lines.append(l)
509
+ except EOFError: break
510
+ if lines:
511
+ project_memory = "\n".join(lines)
512
+ ctx.save_memory(project_memory)
513
+ system_prompt = build_system_prompt(tools, project_memory)
514
+ messages[0] = {"role": "system", "content": system_prompt}
515
+ console.print(f"[green]✅ 已保存 CODEPILOT.md ({len(project_memory)} chars)[/]")
516
+ continue
517
+
518
+ elif cmd == "/grind":
519
+ n = Prompt.ask("刷幾題?", default="50")
520
+ run_grind(args, int(n)); continue
521
+
522
+ elif cmd == "/status":
523
+ s = db.count()
524
+ t = Table(title="📊 統計"); t.add_column("", style="cyan"); t.add_column("", style="green")
525
+ t.add_row("Total", str(s["total"])); t.add_row("👍", str(s["up"]))
526
+ t.add_row("👎", str(s["total"]-s["up"])); t.add_row("✏️", str(s["edits"]))
527
+ t.add_row("DPO 對", str(len(db.export_dpo())))
528
+ t.add_row("Duel", "⚔️ ON" if duel_mode else "OFF")
529
+ t.add_row("記憶", f"{len(project_memory)} chars" if project_memory else "無")
530
+ t.add_row("對話輪數", str((len(messages)-1)//2))
531
+ console.print(t); continue
532
+
533
+ elif cmd == "/train": trigger_training(db, console, args); continue
534
+ elif cmd == "/clear":
535
+ messages = [{"role": "system", "content": system_prompt}]
536
+ ctx.save_session(messages); console.print("[dim]已清除[/]"); continue
537
+ elif cmd == "/git": console.print(Panel(tools.git_context(), title="Git", border_style="dim")); continue
538
+ elif cmd.startswith("/ls"): console.print(tools.list_files(cmd[3:].strip() or "*")); continue
539
+ elif cmd == "/switch":
540
+ new_p = Prompt.ask("切換到", choices=list(PROVIDER_CONFIGS.keys()))
541
+ if new_p == "local":
542
+ with console.status("載入..."): model = LocalModel(args.model or DEFAULT_LOCAL_MODEL, args.adapter)
543
+ local_model_ref = model; provider_key = "local"
544
+ else:
545
+ key = args.api_key or Prompt.ask("API Key")
546
+ cm = Prompt.ask("模型", default=PROVIDER_CONFIGS[new_p]["default_model"])
547
+ model = CloudModel(new_p, key, cm); cloud_model_ref = model; provider_key = new_p
548
+ console.print(f"[green]✅ {provider_key}[/]"); continue
549
+
550
+ # ---- Duel 模式:自動雙模型比較 ----
551
+ if duel_mode and local_model_ref and cloud_model_ref:
552
+ compare_msgs = list(messages) + [{"role": "user", "content": user_input}]
553
+
554
+ with console.status("[bold cyan]🏠 本地模型..."):
555
+ try: local_resp = local_model_ref.chat(compare_msgs)
556
+ except Exception as e: local_resp = f"(錯誤: {e})"
557
+
558
+ with console.status("[bold magenta]☁️ 雲端模型..."):
559
+ try: cloud_resp = cloud_model_ref.chat(compare_msgs)
560
+ except Exception as e: cloud_resp = f"(錯誤: {e})"
561
+
562
+ console.print(Panel(Markdown(local_resp), title=f"🏠 {local_model_ref.name}", border_style="blue"))
563
+ console.print(Panel(Markdown(cloud_resp), title=f"☁️ {cloud_model_ref.name}", border_style="magenta"))
564
+
565
+ console.print(f"[dim][green]1[/]=🏠本地 [magenta]2[/]=☁️雲端 [yellow]b[/]=都好 [red]x[/]=都差 Enter=跳過[/]")
566
+ choice = Prompt.ask(" ", choices=["1","2","b","x",""], default="", show_choices=False)
567
+
568
+ if choice == "2":
569
+ db.save(user_input, cloud_resp, 1, source_model=cloud_model_ref.name, provider=cloud_model_ref.provider)
570
+ db.save(user_input, local_resp, 0, source_model=local_model_ref.name, provider="local")
571
+ console.print(f" [magenta]☁️ 雲端勝 → DPO +1 ({len(db.export_dpo())} 對)[/]")
572
+ messages.append({"role": "user", "content": user_input})
573
+ messages.append({"role": "assistant", "content": cloud_resp})
574
+ elif choice == "1":
575
+ db.save(user_input, local_resp, 1, source_model=local_model_ref.name, provider="local")
576
+ db.save(user_input, cloud_resp, 0, source_model=cloud_model_ref.name, provider=cloud_model_ref.provider)
577
+ console.print(f" [green]🏠 本地勝![/]")
578
+ messages.append({"role": "user", "content": user_input})
579
+ messages.append({"role": "assistant", "content": local_resp})
580
+ elif choice == "b":
581
+ db.save(user_input, local_resp, 1, source_model=local_model_ref.name, provider="local")
582
+ db.save(user_input, cloud_resp, 1, source_model=cloud_model_ref.name, provider=cloud_model_ref.provider)
583
+ console.print(f" [yellow]👍 都好[/]")
584
+ messages.append({"role": "user", "content": user_input})
585
+ messages.append({"role": "assistant", "content": cloud_resp})
586
+ elif choice == "x":
587
+ db.save(user_input, local_resp, 0, source_model=local_model_ref.name, provider="local")
588
+ db.save(user_input, cloud_resp, 0, source_model=cloud_model_ref.name, provider=cloud_model_ref.provider)
589
+ console.print(f" [red]都差[/]")
590
+ else:
591
+ messages.append({"role": "user", "content": user_input})
592
+ messages.append({"role": "assistant", "content": cloud_resp})
593
+
594
+ ctx.save_session(messages)
595
+ continue
596
+
597
+ # ---- 正常模式:單模型 + 工具循環 ----
598
+ messages.append({"role": "user", "content": user_input})
599
+ full_response = ""
600
+
601
+ for rnd in range(10):
602
+ with console.status(f"[bold cyan]{'思考中' if rnd == 0 else f'工具 round {rnd+1}'}..."):
603
+ try: response = model.chat(messages)
604
+ except Exception as e: console.print(f"[red]❌ {e}[/]"); break
605
+
606
+ tool_calls = parse_tool_calls(response)
607
+ text_parts = TOOL_PATTERN.sub("", response).strip()
608
+ if text_parts:
609
+ console.print(f"\n[bold blue]🤖 CodePilot:[/]")
610
+ console.print(Markdown(text_parts))
611
+ full_response += response + "\n"
612
+ if not tool_calls: break
613
+
614
+ messages.append({"role": "assistant", "content": response})
615
+ results = []
616
+ for call in tool_calls:
617
+ console.print(f" [dim]🔧 {call['tool']}[/]")
618
+ result = execute_tool(tools, call)
619
+ if call["tool"] == "edit_file" and "✅" in result:
620
+ d = result.split("\n", 1)[1] if "\n" in result else ""
621
+ if d: console.print(Syntax(d, "diff", theme="monokai"))
622
+ elif call["tool"] == "run_command":
623
+ console.print(Panel(result[:500], title="Terminal", border_style="dim"))
624
+ else: console.print(f" [dim]{result[:200]}[/]")
625
+ results.append(f"[{call['tool']}] {result}")
626
+ messages.append({"role": "user", "content": "Tool results:\n" + "\n\n".join(results)})
627
+
628
+ # 回饋
629
+ console.print(f"\n[dim][green]y[/]=👍 [red]n[/]=👎 [yellow]e[/]=✏️ Enter=跳過[/]")
630
+ fb = Prompt.ask(" ", choices=["y","n","e",""], default="", show_choices=False)
631
+ if fb == "y":
632
+ db.save(user_input, full_response, 1, source_model=getattr(model,"name",""), provider=provider_key)
633
+ console.print(" [green]👍[/]")
634
+ elif fb == "n":
635
+ db.save(user_input, full_response, 0, source_model=getattr(model,"name",""), provider=provider_key)
636
+ console.print(" [red]👎[/]")
637
+ elif fb == "e":
638
+ console.print(" [yellow]貼上修改版(END結束):[/]"); lines = []
639
+ while True:
640
+ try:
641
+ l = input()
642
+ if l.strip() == "END": break
643
+ lines.append(l)
644
+ except EOFError: break
645
+ edited = "\n".join(lines)
646
+ if edited.strip():
647
+ db.save(user_input, full_response, 1, edited=edited, source_model=getattr(model,"name",""), provider=provider_key)
648
+ console.print(" [yellow]✏️[/]")
649
+
650
+ messages.append({"role": "assistant", "content": full_response})
651
+ ctx.save_session(messages)
652
+
653
+ console.print("\n[cyan]👋[/]")
654
+
655
+
656
+ # ============================================================
657
+ # TRAINING
658
+ # ============================================================
659
+ def trigger_training(db, console, args):
660
+ s = db.count()
661
+ if s["total"] == 0: console.print("[yellow]⚠️ 無數據[/]"); return
662
+ cloud_sft = db.export_sft(only_cloud=True); all_sft = db.export_sft(); dpo = db.export_dpo()
663
+ console.print(f"\n[bold]🚀 數據[/] ⚗️蒸餾SFT:{len(cloud_sft)} 📊DPO:{len(dpo)} 📚全SFT:{len(all_sft)}")
664
+
665
+ from datasets import Dataset
666
+ from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
667
+ from peft import LoraConfig, prepare_model_for_kbit_training
668
+
669
+ mn = args.model or DEFAULT_LOCAL_MODEL
670
+ od = os.path.join(CONFIG_DIR, f"adapter_{datetime.now().strftime('%Y%m%d_%H%M')}")
671
+ bnb = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_use_double_quant=True)
672
+ pc = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM",
673
+ target_modules=["q_proj","k_proj","v_proj","o_proj","gate_proj","up_proj","down_proj"])
674
+ td = cloud_sft or all_sft
675
+ if td:
676
+ console.print(f"[bold]📚 {'⚗️蒸餾' if cloud_sft else ''} SFT ({len(td)})...[/]")
677
+ from trl import SFTTrainer, SFTConfig
678
+ m = AutoModelForCausalLM.from_pretrained(mn, quantization_config=bnb, device_map="auto", trust_remote_code=True)
679
+ t = AutoTokenizer.from_pretrained(mn)
680
+ if t.pad_token is None: t.pad_token = t.eos_token
681
+ m = prepare_model_for_kbit_training(m)
682
+ SFTTrainer(model=m, args=SFTConfig(output_dir=od, learning_rate=2e-4, num_train_epochs=3,
683
+ per_device_train_batch_size=1, gradient_accumulation_steps=8, max_seq_length=1024,
684
+ gradient_checkpointing=True, bf16=True, optim="paged_adamw_8bit", logging_steps=5,
685
+ save_total_limit=1, logging_strategy="steps", logging_first_step=True),
686
+ processing_class=t, train_dataset=Dataset.from_list(td), peft_config=pc).train()
687
+ m.save_pretrained(od); del m; torch.cuda.empty_cache()
688
+ console.print(f"\n[bold green]🎉[/] {od}\n codepilot --adapter {od}")
689
+
690
+ def show_stats():
691
+ from rich.console import Console; from rich.table import Table
692
+ c = Console(); db = FeedbackDB(); s = db.count()
693
+ t = Table(title="📊 CodePilot"); t.add_column("",style="cyan"); t.add_column("",style="green")
694
+ t.add_row("Total",str(s["total"])); t.add_row("👍",str(s["up"])); t.add_row("DPO",str(len(db.export_dpo())))
695
+ c.print(t)
696
+
697
+ def main():
698
+ p = argparse.ArgumentParser(description="CodePilot v4")
699
+ p.add_argument("--model", type=str); p.add_argument("--adapter", type=str)
700
+ p.add_argument("--project", type=str); p.add_argument("--provider", type=str, choices=list(PROVIDER_CONFIGS.keys()))
701
+ p.add_argument("--api-key", type=str); p.add_argument("--cloud-model", type=str)
702
+ p.add_argument("--duel", action="store_true", help="啟動時開啟 Duel 模式")
703
+ p.add_argument("--distill", action="store_true")
704
+ p.add_argument("--grind", action="store_true", help="LeetCode 自動刷題")
705
+ p.add_argument("--grind-count", type=int, default=100, help="刷幾題")
706
+ p.add_argument("--stats", action="store_true"); p.add_argument("--train", action="store_true")
707
+ a = p.parse_args()
708
+ if a.stats: show_stats()
709
+ elif a.train: from rich.console import Console; trigger_training(FeedbackDB(), Console(), a)
710
+ elif a.grind: run_grind(a, a.grind_count)
711
+ else: run_agent_loop(a)
712
+
713
+ if __name__ == "__main__": main()