Upload 22 files
Browse files- app/agent.py +53 -3
app/agent.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
"""Agent 主循環:串流呼叫 LLM → 若有工具調用就執行 → 把結果餵回去 → 直到給出最終回答。"""
|
| 2 |
import asyncio
|
| 3 |
import json
|
|
|
|
| 4 |
from datetime import datetime
|
| 5 |
from zoneinfo import ZoneInfo
|
| 6 |
|
|
@@ -132,6 +133,16 @@ def fix_arguments(raw) -> tuple[str, bool]:
|
|
| 132 |
return json.dumps(v, ensure_ascii=False), True
|
| 133 |
except json.JSONDecodeError:
|
| 134 |
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
try:
|
| 136 |
import ast
|
| 137 |
v = ast.literal_eval(t)
|
|
@@ -142,6 +153,40 @@ def fix_arguments(raw) -> tuple[str, bool]:
|
|
| 142 |
return json.dumps({"_invalid_arguments": raw[:2000]}, ensure_ascii=False), False
|
| 143 |
|
| 144 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
def prepare_messages(provider, messages: list[dict]) -> list[dict]:
|
| 146 |
"""依提供商調整工具調用的附加欄位。
|
| 147 |
|
|
@@ -259,8 +304,11 @@ async def run_agent(conv_id: str, user_text: str, model: str | None = None):
|
|
| 259 |
if tc.get("extra_content"): # Gemini 的 thought_signature,下一輪要原樣送回
|
| 260 |
slot["extra_content"] = tc["extra_content"]
|
| 261 |
fn = tc.get("function") or {}
|
| 262 |
-
if fn.get("name")
|
| 263 |
-
slot["function"]["name"]
|
|
|
|
|
|
|
|
|
|
| 264 |
if fn.get("arguments"):
|
| 265 |
slot["function"]["arguments"] += fn["arguments"]
|
| 266 |
n = len(slot["function"]["arguments"].encode())
|
|
@@ -272,7 +320,9 @@ async def run_agent(conv_id: str, user_text: str, model: str | None = None):
|
|
| 272 |
await asyncio.shield(store.add_message(conv_id, "assistant", content + "\n\n(已停止)"))
|
| 273 |
raise
|
| 274 |
|
| 275 |
-
tool_calls = [
|
|
|
|
|
|
|
| 276 |
for n, tc in enumerate(tool_calls):
|
| 277 |
tc["id"] = tc["id"] or f"call_{step}_{n}"
|
| 278 |
|
|
|
|
| 1 |
"""Agent 主循環:串流呼叫 LLM → 若有工具調用就執行 → 把結果餵回去 → 直到給出最終回答。"""
|
| 2 |
import asyncio
|
| 3 |
import json
|
| 4 |
+
import re
|
| 5 |
from datetime import datetime
|
| 6 |
from zoneinfo import ZoneInfo
|
| 7 |
|
|
|
|
| 133 |
return json.dumps(v, ensure_ascii=False), True
|
| 134 |
except json.JSONDecodeError:
|
| 135 |
pass
|
| 136 |
+
if '<|"|>' in t or re.search(r'[{,]\s*[A-Za-z_]\w*\s*:', t):
|
| 137 |
+
# Gemma 4 的原生工具格式:字串用 <|"|> 包、鍵不加引號,例如 {path:<|"|>a.py<|"|>}
|
| 138 |
+
g = t.replace('<|"|>', '"')
|
| 139 |
+
g = re.sub(r'([{,]\s*)([A-Za-z_]\w*)(\s*:)', r'\1"\2"\3', g)
|
| 140 |
+
try:
|
| 141 |
+
v = json.loads(g)
|
| 142 |
+
if isinstance(v, dict):
|
| 143 |
+
return json.dumps(v, ensure_ascii=False), True
|
| 144 |
+
except json.JSONDecodeError:
|
| 145 |
+
pass
|
| 146 |
try:
|
| 147 |
import ast
|
| 148 |
v = ast.literal_eval(t)
|
|
|
|
| 153 |
return json.dumps({"_invalid_arguments": raw[:2000]}, ensure_ascii=False), False
|
| 154 |
|
| 155 |
|
| 156 |
+
def split_merged(tc: dict) -> list[dict]:
|
| 157 |
+
"""把被串在一起的多個工具調用拆開,例如 arguments 是 {"name":"a"}{"name":"b"}。"""
|
| 158 |
+
names = tc.pop("_names", None) or [tc["function"]["name"]]
|
| 159 |
+
raw = (tc["function"]["arguments"] or "").strip()
|
| 160 |
+
try:
|
| 161 |
+
json.loads(raw or "{}")
|
| 162 |
+
return [tc]
|
| 163 |
+
except json.JSONDecodeError:
|
| 164 |
+
pass
|
| 165 |
+
dec, objs, i = json.JSONDecoder(), [], 0
|
| 166 |
+
try:
|
| 167 |
+
while i < len(raw):
|
| 168 |
+
v, j = dec.raw_decode(raw, i)
|
| 169 |
+
if not isinstance(v, dict):
|
| 170 |
+
return [tc]
|
| 171 |
+
objs.append(v)
|
| 172 |
+
i = j
|
| 173 |
+
while i < len(raw) and raw[i] in " \t\r\n,;":
|
| 174 |
+
i += 1
|
| 175 |
+
except json.JSONDecodeError:
|
| 176 |
+
return [tc]
|
| 177 |
+
if len(objs) < 2:
|
| 178 |
+
return [tc]
|
| 179 |
+
out = []
|
| 180 |
+
for n, v in enumerate(objs):
|
| 181 |
+
name = names[n] if len(names) == len(objs) else tc["function"]["name"]
|
| 182 |
+
c = {**tc, "function": {"name": name, "arguments": json.dumps(v, ensure_ascii=False)}}
|
| 183 |
+
c["id"] = tc["id"] if n == 0 else (f"{tc['id']}_{n}" if tc["id"] else "")
|
| 184 |
+
if n:
|
| 185 |
+
c.pop("extra_content", None)
|
| 186 |
+
out.append(c)
|
| 187 |
+
return out
|
| 188 |
+
|
| 189 |
+
|
| 190 |
def prepare_messages(provider, messages: list[dict]) -> list[dict]:
|
| 191 |
"""依提供商調整工具調用的附加欄位。
|
| 192 |
|
|
|
|
| 304 |
if tc.get("extra_content"): # Gemini 的 thought_signature,下一輪要原樣送回
|
| 305 |
slot["extra_content"] = tc["extra_content"]
|
| 306 |
fn = tc.get("function") or {}
|
| 307 |
+
if fn.get("name"):
|
| 308 |
+
if not slot["function"]["name"]:
|
| 309 |
+
slot["function"]["name"] = fn["name"]
|
| 310 |
+
# 有些提供商把同一輪的多個調用都放在同一個 index/id 下:記下每個名字,事後拆開
|
| 311 |
+
slot.setdefault("_names", []).append(fn["name"])
|
| 312 |
if fn.get("arguments"):
|
| 313 |
slot["function"]["arguments"] += fn["arguments"]
|
| 314 |
n = len(slot["function"]["arguments"].encode())
|
|
|
|
| 320 |
await asyncio.shield(store.add_message(conv_id, "assistant", content + "\n\n(已停止)"))
|
| 321 |
raise
|
| 322 |
|
| 323 |
+
tool_calls = []
|
| 324 |
+
for k in sorted(calls):
|
| 325 |
+
tool_calls.extend(split_merged(calls[k]))
|
| 326 |
for n, tc in enumerate(tool_calls):
|
| 327 |
tc["id"] = tc["id"] or f"call_{step}_{n}"
|
| 328 |
|