"""Agent 主循環:串流呼叫 LLM → 若有工具調用就執行 → 把結果餵回去 → 直到給出最終回答。""" import asyncio import json import re from datetime import datetime from zoneinfo import ZoneInfo import httpx from . import config from . import db as store from . import providers from . import workspace from .tools import execute_tool, tool_schemas class LLMError(Exception): pass async def build_system_prompt(project: dict | None = None) -> str: sp = await store.get_setting("system_prompt") or config.DEFAULT_SYSTEM_PROMPT try: now = datetime.now(ZoneInfo(config.DEFAULT_TZ)).strftime("%Y-%m-%d %H:%M (%A)") except Exception: now = datetime.utcnow().strftime("%Y-%m-%d %H:%M UTC") sp += f"\n\n目前時間:{now},時區 {config.DEFAULT_TZ}。" skills = await store.list_skills(enabled_only=True) if skills: sp += ("\n\n## 已安裝的技能(Skills)\n任務符合下列描述時,先呼叫 load_skill(name) 讀取完整說明再執行:\n" + "\n".join(f"- {s['name']}: {s['description']}" for s in skills)) if project: files = workspace.tree(project["id"], limit=200) sp += (f"\n\n## 目前專案:{project['name']}\n" f"工作目錄(run_python / run_shell 的 cwd,檔案工具的根目錄)就是這個專案的資料夾:{workspace.project_dir(project['id'])}\n" "只有這個資料夾裡的檔案會永久保存並出現在使用者的檔案列表。一律用相對路徑(例如 src/app.py);" "不要寫到 ~、/tmp 或其他絕對路徑,那些地方使用者看不到,重啟就消失。" "node_modules、.git、.venv、各種快取目錄不會保存。\n") if project.get("instructions"): sp += f"\n### 專案說明(使用者寫的,必須遵守)\n{project['instructions']}\n" sp += "\n### 專案檔案\n" + ("\n".join(f"- {f}" for f in files) if files else "(目前是空的)") else: sp += "\n\n(這個對話不屬於任何專案:工作目錄是暫存區,容器重啟後檔案會消失。要保存檔案請使用者建立專案。)" mems = await store.recent_memories(30) if mems: sp += "\n\n## 已知的使用者長期記憶([id] 內容)\n" + "\n".join( f"- [{m['id']}] {m['content']}" for m in reversed(mems)) return sp def rows_to_messages(rows: list[dict]) -> list[dict]: """把資料庫列轉成 OpenAI messages,並清掉不完整的工具調用(例如中途中斷)。""" msgs = [] for r in rows: if r["role"] == "assistant": m = {"role": "assistant", "content": r["content"] or ""} if r["tool_calls"]: m["tool_calls"] = json.loads(r["tool_calls"]) m["content"] = r["content"] or None msgs.append(m) elif r["role"] == "tool": msgs.append({"role": "tool", "tool_call_id": r["tool_call_id"], "content": r["content"] or ""}) else: msgs.append({"role": r["role"], "content": r["content"] or ""}) clean, i = [], 0 while i < len(msgs): m = msgs[i] if m["role"] == "assistant" and m.get("tool_calls"): ids = {tc["id"] for tc in m["tool_calls"]} j, results = i + 1, [] while j < len(msgs) and msgs[j]["role"] == "tool": results.append(msgs[j]) j += 1 if ids <= {t["tool_call_id"] for t in results}: clean.append(m) clean.extend(t for t in results if t["tool_call_id"] in ids) elif m["content"]: clean.append({"role": "assistant", "content": m["content"]}) i = j continue if m["role"] == "tool": # 孤立的工具結果 i += 1 continue clean.append(m) i += 1 return clean def _clean_schema(o): """去掉部分提供商(如 Gemini)不接受的 JSON Schema 欄位。""" if isinstance(o, dict): return {k: _clean_schema(v) for k, v in o.items() if k not in ("$schema", "$id")} if isinstance(o, list): return [_clean_schema(v) for v in o] return o GEMINI_SKIP_SIG = "skip_thought_signature_validator" def is_gemini(provider) -> bool: return "generativelanguage.googleapis.com" in (provider.get("base_url") or "") def fix_arguments(raw) -> tuple[str, bool]: """把模型給的工具參數整理成合法 JSON 物件字串。回傳(參數, 是否原本就合法)。 有些模型(例如部分 Gemma、小模型)會吐出不合法的參數:包在 ```json 裡、前後多文字、單引號、被截斷。 不合法的參數一旦存進歷史,下一輪送回去很多提供商會直接 400(function.arguments must be valid JSON), 整個對話就卡死。所以能修就修,修不了就換成一個合法的佔位物件,讓工具回報錯誤、模型重來。 """ if isinstance(raw, dict): return json.dumps(raw, ensure_ascii=False), True raw = raw or "" if not raw.strip(): return "{}", True try: if isinstance(json.loads(raw), dict): return raw, True except (json.JSONDecodeError, TypeError): pass t = raw.strip() if t.startswith("```"): t = t.split("\n", 1)[1] if "\n" in t else t[3:] t = t.rsplit("```", 1)[0] a, b = t.find("{"), t.rfind("}") if a != -1 and b > a: t = t[a:b + 1] try: v = json.loads(t) if isinstance(v, dict): return json.dumps(v, ensure_ascii=False), True except json.JSONDecodeError: pass if '<|"|>' in t or re.search(r'[{,]\s*[A-Za-z_]\w*\s*:', t): # Gemma 4 的原生工具格式:字串用 <|"|> 包、鍵不加引號,例如 {path:<|"|>a.py<|"|>} g = t.replace('<|"|>', '"') g = re.sub(r'([{,]\s*)([A-Za-z_]\w*)(\s*:)', r'\1"\2"\3', g) try: v = json.loads(g) if isinstance(v, dict): return json.dumps(v, ensure_ascii=False), True except json.JSONDecodeError: pass try: import ast v = ast.literal_eval(t) if isinstance(v, dict): return json.dumps(v, ensure_ascii=False), True except Exception: pass return json.dumps({"_invalid_arguments": raw[:2000]}, ensure_ascii=False), False def split_merged(tc: dict) -> list[dict]: """把被串在一起的多個工具調用拆開,例如 arguments 是 {"name":"a"}{"name":"b"}。""" names = tc.pop("_names", None) or [tc["function"]["name"]] raw = (tc["function"]["arguments"] or "").strip() try: json.loads(raw or "{}") return [tc] except json.JSONDecodeError: pass dec, objs, i = json.JSONDecoder(), [], 0 try: while i < len(raw): v, j = dec.raw_decode(raw, i) if not isinstance(v, dict): return [tc] objs.append(v) i = j while i < len(raw) and raw[i] in " \t\r\n,;": i += 1 except json.JSONDecodeError: return [tc] if len(objs) < 2: return [tc] out = [] for n, v in enumerate(objs): name = names[n] if len(names) == len(objs) else tc["function"]["name"] c = {**tc, "function": {"name": name, "arguments": json.dumps(v, ensure_ascii=False)}} c["id"] = tc["id"] if n == 0 else (f"{tc['id']}_{n}" if tc["id"] else "") if n: c.pop("extra_content", None) out.append(c) return out def prepare_messages(provider, messages: list[dict]) -> list[dict]: """依提供商調整工具調用的附加欄位。 Gemini(OpenAI 相容端點)在工具調用上附 thought_signature(extra_content.google),下一輪必須原樣送回, 否則回 400。舊紀錄或別的模型留下的工具調用沒有簽名,就補官方提供的略過值。 其他提供商不認得 extra_content,送過去可能被拒,所以拿掉。 """ gem = is_gemini(provider) out = [] for m in messages: if m.get("role") != "assistant" or not m.get("tool_calls"): out.append(m) continue tcs = [] for i, tc in enumerate(m["tool_calls"]): tc = {k: v for k, v in tc.items() if k != "extra_content" or gem} fn = dict(tc.get("function") or {}) fn["arguments"] = fix_arguments(fn.get("arguments"))[0] # 舊紀錄裡的壞參數也修掉,否則整個對話送不出去 tc["function"] = fn if gem and i == 0 and not ((tc.get("extra_content") or {}).get("google") or {}).get("thought_signature"): tc["extra_content"] = {"google": {"thought_signature": GEMINI_SKIP_SIG}} tcs.append(tc) out.append({**m, "tool_calls": tcs}) return out async def max_steps() -> int: v = await store.get_setting("max_steps") try: n = int(v) if v else config.MAX_AGENT_STEPS except ValueError: n = config.MAX_AGENT_STEPS return max(1, min(n, 2000)) async def stream_completion(client, provider, model, messages, tools, tool_choice=None): body = {"model": model, "messages": prepare_messages(provider, messages), "stream": True} if tools: body["tools"] = tools if tool_choice: body["tool_choice"] = tool_choice headers = {"Authorization": f"Bearer {providers.key_of(provider)}"} async with client.stream("POST", f"{provider['base_url']}/chat/completions", json=body, headers=headers) as r: if r.status_code >= 400: txt = (await r.aread()).decode(errors="replace") raise LLMError(f"{provider['name']} / {model} 回傳 HTTP {r.status_code}:{txt[:300]}(可在頂欄換模型後重試)") async for line in r.aiter_lines(): line = line.strip() if not line.startswith("data:"): continue data = line[5:].strip() if data == "[DONE]": break try: chunk = json.loads(data) except json.JSONDecodeError: continue if chunk.get("error"): raise LLMError(str(chunk["error"])[:300]) yield chunk async def run_agent(conv_id: str, user_text: str, model: str | None = None): """非同步產生器,逐一 yield 事件:reasoning / token / tool_start / tool_result / done / error。""" await store.add_message(conv_id, "user", user_text) history = await store.get_history(conv_id, config.HISTORY_LIMIT) chosen = await providers.resolve(model) if not chosen: yield {"type": "error", "message": "還沒選模型:請先在「🤖 模型」面板加提供商、拉取並勾選模型,再在頂欄選一個。"} return provider, model_id = chosen conv = await store.get_conversation(conv_id) or {} project = await store.get_project(conv["project_id"]) if conv.get("project_id") else None workspace.current_project.set(project["id"] if project else None) if project: await workspace.restore(project["id"]) messages = [{"role": "system", "content": await build_system_prompt(project)}] + rows_to_messages(history) tools = _clean_schema(tool_schemas()) limit = await max_steps() async with httpx.AsyncClient(timeout=httpx.Timeout(config.LLM_TIMEOUT, connect=config.LLM_CONNECT_TIMEOUT, write=120, pool=60)) as client: for step in range(limit): last_step = step == limit - 1 content, calls, reported, finish, thought = "", {}, {}, None, False try: async for chunk in stream_completion(client, provider, model_id, messages, tools, "none" if last_step else None): choices = chunk.get("choices") or [] if not choices: continue finish = choices[0].get("finish_reason") or finish delta = choices[0].get("delta") or {} reasoning = delta.get("reasoning_content") or delta.get("reasoning") if reasoning: thought = True yield {"type": "reasoning", "text": reasoning} if delta.get("content"): content += delta["content"] yield {"type": "token", "text": delta["content"]} for tc in delta.get("tool_calls") or []: idx = tc.get("index") if idx is None: # 部分提供商(如 Gemini)不給 index:用 id 分辨是不是新的調用 known = {v["id"]: k for k, v in calls.items() if v["id"]} if tc.get("id") in known: idx = known[tc["id"]] elif tc.get("id") or not calls: idx = len(calls) else: idx = max(calls) slot = calls.setdefault(idx, { "id": "", "type": "function", "function": {"name": "", "arguments": ""}}) if tc.get("id"): slot["id"] = tc["id"] if tc.get("extra_content"): # Gemini 的 thought_signature,下一輪要原樣送回 slot["extra_content"] = tc["extra_content"] fn = tc.get("function") or {} if fn.get("name"): if not slot["function"]["name"]: slot["function"]["name"] = fn["name"] # 有些提供商把同一輪的多個調用都放在同一個 index/id 下:記下每個名字,事後拆開 slot.setdefault("_names", []).append(fn["name"]) if fn.get("arguments"): slot["function"]["arguments"] += fn["arguments"] n = len(slot["function"]["arguments"].encode()) if slot["function"]["name"] and n - reported.get(idx, -10**9) >= 1024: reported[idx] = n # 模型正在寫很長的參數(例如整個檔案):讓前端看到進度 yield {"type": "tool_progress", "index": idx, "name": slot["function"]["name"], "bytes": n} except (asyncio.CancelledError, GeneratorExit): if content: # 被停止:保留已經生成的部分 await asyncio.shield(store.add_message(conv_id, "assistant", content + "\n\n(已停止)")) raise tool_calls = [] for k in sorted(calls): tool_calls.extend(split_merged(calls[k])) for n, tc in enumerate(tool_calls): tc["id"] = tc["id"] or f"call_{step}_{n}" if not tool_calls: if not content.strip(): # 只有思考、沒有回答也沒呼叫工具:不要默默結束 why = {"length": "輸出長度到了上限(max tokens)", "content_filter": "被提供商的內容過濾擋下"}.get( finish, f"結束原因:{finish or '未提供'}") yield {"type": "error", "message": ( f"模型{'只輸出了思考過程,' if thought else ''}沒有給出回答也沒有呼叫工具({why})。" "可以按「繼續執行」再試;常發生的話,這個模型可能不支援工具調用,或免費額度的輸出上限太小,建議換模型。")} return await store.add_message(conv_id, "assistant", content) yield {"type": "done"} return for tc in tool_calls: # 參數不是合法 JSON:能修就修,修不了換佔位,避免下一輪被提供商拒絕 fixed, ok = fix_arguments(tc["function"]["arguments"]) if not ok and finish == "length": fixed = json.dumps({"_truncated": True}) tc["function"]["arguments"] = fixed await store.add_message(conv_id, "assistant", content, tool_calls=json.dumps(tool_calls, ensure_ascii=False)) messages.append({"role": "assistant", "content": content or None, "tool_calls": tool_calls}) saved: set[str] = set() try: for tc in tool_calls: name, args = tc["function"]["name"], tc["function"]["arguments"] yield {"type": "tool_start", "id": tc["id"], "name": name, "arguments": args} result = await execute_tool(name, args) await store.add_message(conv_id, "tool", result, tool_call_id=tc["id"], name=name) saved.add(tc["id"]) messages.append({"role": "tool", "tool_call_id": tc["id"], "content": result}) yield {"type": "tool_result", "id": tc["id"], "name": name, "result": result[:4000]} except (asyncio.CancelledError, GeneratorExit): # 被停止:補上工具結果,讓對話歷史保持合法 await asyncio.shield(store.add_messages_tool_stopped( conv_id, [tc for tc in tool_calls if tc["id"] not in saved])) raise yield {"type": "error", "message": f"已跑了 {limit} 輪工具調用,暫停一下。按「繼續執行」接著做(上限可在「設定」調整)"}