Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions agentmain.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,14 +59,14 @@ def load_llm_sessions(self):
mykeys, changed = reload_mykeys()
if not changed and hasattr(self, 'llmclients'): return
try: oldhistory = self.llmclient.backend.history
except: oldhistory = None
except Exception: oldhistory = None
llm_sessions = []
for k, cfg in mykeys.items():
if not any(x in k for x in ['api', 'config', 'cookie']): continue
try:
if 'mixin' in k: llm_sessions += [{'mixin_cfg': cfg}]
elif c := resolve_client(k): llm_sessions += [c]
except: pass
except Exception: pass
for i, s in enumerate(llm_sessions):
if isinstance(s, dict) and 'mixin_cfg' in s:
try:
Expand All @@ -84,7 +84,7 @@ def next_llm(self, n=-1):
lastc = self.llmclient
self.llmclient = self.llmclients[self.llm_no]
try: self.llmclient.backend.history = lastc.backend.history
except: raise Exception('[ERROR] BAD Mixin config: Check your mykey.py')
except Exception: raise Exception('[ERROR] BAD Mixin config: Check your mykey.py')
self.llmclient.last_tools = ''
name = self.get_llm_name(model=True)
if 'glm' in name or 'minimax' in name or 'kimi' in name: load_tool_schema('_cn')
Expand Down
2 changes: 1 addition & 1 deletion assets/code_run_header.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ def _d(b):
if not b: return ''
if isinstance(b, str): return b
try: return b.decode()
except: return b.decode('gbk', 'replace')
except Exception: return b.decode('gbk', 'replace')
def _run(*a, **k):
t = k.pop('text', 0) | k.pop('universal_newlines', 0)
enc = k.pop('encoding', None)
Expand Down
4 changes: 2 additions & 2 deletions frontends/qtapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -707,7 +707,7 @@ def __init__(self, text: str, role: str, parent=None, on_resend=None, on_delete=
time_lbl = QLabel(dt.strftime("%Y-%m-%d %H:%M"))
time_lbl.setStyleSheet("color: #a1a1aa; font-size: 11px; background: transparent;")
alayout.addWidget(time_lbl)
except:
except Exception:
pass

self._action_row.hide()
Expand Down Expand Up @@ -791,7 +791,7 @@ def __init__(self, text: str, role: str, parent=None, on_resend=None, on_delete=
time_lbl = QLabel(dt.strftime("%Y-%m-%d %H:%M"))
time_lbl.setStyleSheet("color: #a1a1aa; font-size: 11px; background: transparent;")
alayout.addWidget(time_lbl)
except:
except Exception:
pass

self._action_row.hide()
Expand Down
4 changes: 2 additions & 2 deletions frontends/stapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
if sys.stdout is None: sys.stdout = open(os.devnull, "w")
if sys.stderr is None: sys.stderr = open(os.devnull, "w")
try: sys.stdout.reconfigure(errors='replace')
except: pass
except Exception: pass
try: sys.stderr.reconfigure(errors='replace')
except: pass
except Exception: pass
script_dir = os.path.dirname(__file__)
sys.path.append(os.path.abspath(os.path.join(script_dir, '..')))
sys.path.append(os.path.abspath(script_dir))
Expand Down
4 changes: 2 additions & 2 deletions frontends/stapp2.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
if sys.stdout is None: sys.stdout = open(os.devnull, "w")
if sys.stderr is None: sys.stderr = open(os.devnull, "w")
try: sys.stdout.reconfigure(errors='replace')
except: pass
except Exception: pass
try: sys.stderr.reconfigure(errors='replace')
except: pass
except Exception: pass
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

import streamlit as st
Expand Down
2 changes: 1 addition & 1 deletion frontends/tgapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from telegram.ext import ApplicationBuilder, CallbackQueryHandler, MessageHandler, filters, ContextTypes
from telegram.helpers import escape_markdown
from telegram.request import HTTPXRequest
except:
except Exception:
print("Please ask the agent install python-telegram-bot to use telegram module.")
sys.exit(1)
from chatapp_common import (
Expand Down
2 changes: 1 addition & 1 deletion frontends/wechatapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -348,7 +348,7 @@ def _keep_typing():
if not ticket: return
while not _typing_stop.is_set():
try: bot.send_typing(uid, ticket)
except: pass
except Exception: pass
_typing_stop.wait(2.0)
threading.Thread(target=_keep_typing, daemon=True).start()
result = ''; sent = 0; mi = 0; last_send = 0; item = {}
Expand Down
16 changes: 8 additions & 8 deletions ga.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ def stream_reader(proc, logs):
except UnicodeDecodeError: line = line_bytes.decode('gbk', errors='ignore')
logs.append(line)
try: print(line, end="")
except: pass
except: pass
except Exception: pass
except Exception: pass

try:
process = subprocess.Popen(
Expand Down Expand Up @@ -156,7 +156,7 @@ def log_memory_access(path):
stats_file = os.path.join(script_dir, 'memory/file_access_stats.json')
try:
with open(stats_file, 'r', encoding='utf-8') as f: stats = json.load(f)
except: stats = {}
except Exception: stats = {}
fname = os.path.basename(path)
stats[fname] = {'count': stats.get(fname, {}).get('count', 0) + 1, 'last': datetime.now().strftime('%Y-%m-%d')}
with open(stats_file, 'w', encoding='utf-8') as f: json.dump(stats, f, indent=2, ensure_ascii=False)
Expand Down Expand Up @@ -286,7 +286,7 @@ def do_code_run(self, args, response):
code = self._extract_code_block(response, code_type)
if not code: return StepOutcome("[Error] Code missing. Must use reply code block or 'script' arg.", next_prompt="\n")
try: timeout = int(args.get("timeout", 60))
except: timeout = 60
except Exception: timeout = 60
raw_path = os.path.join(self.cwd, args.get("cwd", './'))
cwd = os.path.normpath(os.path.abspath(raw_path))
code_cwd = os.path.normpath(self.cwd)
Expand Down Expand Up @@ -345,10 +345,10 @@ def do_web_execute_js(self, args, response):
try:
with open(abs_path, 'w', encoding='utf-8') as f: f.write(str(content))
result["js_return"] += f"\n\n[已保存完整内容到 {abs_path}]"
except: result['js_return'] += f"\n\n[保存失败,无法写入文件 {abs_path}]"
except Exception: result['js_return'] += f"\n\n[保存失败,无法写入文件 {abs_path}]"
show = smart_format(json.dumps(result, ensure_ascii=False, indent=2, default=json_default), max_str_len=300)
try: print("Web Execute JS Result:", show)
except: pass
except Exception: pass
yield f"JS 执行结果:\n{show}\n"
next_prompt = self._get_anchor_prompt(skip=args.get('_index', 0) > 0)
result = json.dumps(result, ensure_ascii=False, default=json_default)
Expand Down Expand Up @@ -430,7 +430,7 @@ def enter_plan_mode(self, plan_path):
def _check_plan_completion(self):
if not os.path.isfile(p:=self._in_plan_mode() or ''): return None
try: return len(re.findall(r'\[ \]', open(p, encoding='utf-8', errors='replace').read()))
except: return None
except Exception: return None

def do_update_working_checkpoint(self, args, response):
'''为整个任务设定后续需要临时记忆的重点。'''
Expand Down Expand Up @@ -541,7 +541,7 @@ def _get_anchor_prompt(self, skip=False):
if self.working.get('related_sop'): prompt += f"\n有不清晰的地方请再次读取{self.working.get('related_sop')}"
if getattr(self.parent, 'verbose', False):
try: print(prompt)
except: pass
except Exception: pass
return prompt

def turn_end_callback(self, response, tool_calls, tool_results, turn, next_prompt, exit_reason):
Expand Down
32 changes: 16 additions & 16 deletions llmcore.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ def _parse_claude_sse(resp_lines):
if current_block:
if current_block["type"] == "tool_use":
try: current_block["input"] = json.loads(tool_json_buf) if tool_json_buf else {}
except: current_block["input"] = {"_raw": tool_json_buf}
except Exception: current_block["input"] = {"_raw": tool_json_buf}
content_blocks.append(current_block)
current_block = None
elif evt_type == "message_delta":
Expand All @@ -180,7 +180,7 @@ def _parse_claude_sse(resp_lines):
if current_block:
if current_block["type"] == "tool_use":
try: current_block["input"] = json.loads(tool_json_buf) if tool_json_buf else {}
except: current_block["input"] = {"_raw": tool_json_buf}
except Exception: current_block["input"] = {"_raw": tool_json_buf}
content_blocks.append(current_block); current_block = None
if warn:
print(f"[WARN] {warn.strip()}")
Expand All @@ -192,13 +192,13 @@ def _try_parse_tool_args(raw):
Returns list of parsed dicts."""
if not raw: return [{}]
try: return [json.loads(raw)]
except: pass
except Exception: pass
parts = re.split(r'(?<=\})(?=\{)', raw)
if len(parts) > 1:
parsed = []
for p in parts:
try: parsed.append(json.loads(p))
except: return [{"_raw": raw}]
except Exception: return [{"_raw": raw}]
return parsed
return [{"_raw": raw}]

Expand All @@ -217,7 +217,7 @@ def _parse_openai_sse(resp_lines, api_mode="chat_completions"):
data_str = line[5:].lstrip()
if data_str == "[DONE]": break
try: evt = json.loads(data_str)
except: continue
except Exception: continue
etype = evt.get("type", "")
if etype == "response.output_text.delta":
delta = evt.get("delta", "")
Expand Down Expand Up @@ -266,7 +266,7 @@ def _parse_openai_sse(resp_lines, api_mode="chat_completions"):
data_str = line[5:].lstrip()
if data_str == "[DONE]": break
try: evt = json.loads(data_str)
except: continue
except Exception: continue
ch = (evt.get("choices") or [{}])[0]
delta = ch.get("delta") or {}
if delta.get("reasoning_content"):
Expand Down Expand Up @@ -323,7 +323,7 @@ def _parse_openai_json(data, api_mode="chat_completions"):
blocks.append({"type": "text", "text": p["text"]}); yield p["text"]
elif item.get("type") == "function_call":
try: args = json.loads(item.get("arguments", "")) if item.get("arguments") else {}
except: args = {"_raw": item.get("arguments", "")}
except Exception: args = {"_raw": item.get("arguments", "")}
blocks.append({"type": "tool_use", "id": item.get("call_id", item.get("id", "")),
"name": item.get("name", ""), "input": args})
else:
Expand All @@ -338,7 +338,7 @@ def _parse_openai_json(data, api_mode="chat_completions"):
for tc in (msg.get("tool_calls") or []):
fn = tc.get("function", {})
try: args = json.loads(fn.get("arguments", "")) if fn.get("arguments") else {}
except: args = {"_raw": fn.get("arguments", "")}
except Exception: args = {"_raw": fn.get("arguments", "")}
blocks.append({"type": "tool_use", "id": tc.get("id", ""), "name": fn.get("name", ""), "input": args})
return blocks

Expand All @@ -359,7 +359,7 @@ def _stream_with_retry(sess, url, headers, payload, parse_fn):
_RETRYABLE = {408, 409, 425, 429, 500, 502, 503, 504, 529}
def _delay(resp, attempt):
try: ra = float((resp.headers or {}).get("retry-after"))
except: ra = None
except Exception: ra = None
return max(0.5, ra if ra is not None else min(30.0, 1.5 * (2 ** attempt)))
for attempt in range(sess.max_retries + 1):
streamed = False
Expand All @@ -372,7 +372,7 @@ def _delay(resp, attempt):
print(f"[LLM Retry] HTTP {r.status_code}, retry in {d:.1f}s ({attempt+1}/{sess.max_retries+1})")
time.sleep(d); continue
try: body = r.text.strip()[:500]
except: body = ""
except Exception: body = ""
err = f"!!!Error: HTTP {r.status_code}" + (f": {body}" if body else "")
yield err; return [{"type": "text", "text": err}]
gen = parse_fn(r)
Expand Down Expand Up @@ -843,7 +843,7 @@ def _parse_mixed_response(self, text):
except json.JSONDecodeError:
errors.append(f'Failed to parse tool_use JSON: {json_str[:200]}')
self.last_tools = ''
except: pass
except Exception: pass
if not tool_calls:
for e in errors:
print(f"[Warn] {e}"); tool_calls.append(MockToolCall('bad_json', {'msg': e}))
Expand All @@ -859,15 +859,15 @@ def _parse_text_tool_calls(content):
idx = content.index(_jp); raw = json.loads(content[idx:])
tcs = [MockToolCall(b["name"], b.get("input", {}), id=b.get("id", "")) for b in raw if b.get("type") == "tool_use"]
return tcs, content[:idx].strip()
except: pass
except Exception: pass
# try XML tags: <tool_call>{"name":..., "arguments":...}</tool_call>
_xp = r"<(?:tool_use|tool_call)>((?:(?!<(?:tool_use|tool_call)>).){15,}?)</(?:tool_use|tool_call)>"
for s in re.findall(_xp, content, re.DOTALL):
try:
d = tryparse(s.strip()); name = d.get('name')
args = d.get('arguments') or d.get('args') or d.get('input') or {}
if name: tcs.append(MockToolCall(name, args))
except: pass
except Exception: pass
if tcs: content = re.sub(_xp, "", content, flags=re.DOTALL).strip()
return tcs, content

Expand All @@ -891,12 +891,12 @@ def _write_llm_log(label, content, log_path=None):

def tryparse(json_str):
try: return json.loads(json_str)
except: pass
except Exception: pass
json_str = json_str.strip().strip('`').replace('json\n', '', 1).strip()
try: return json.loads(json_str)
except: pass
except Exception: pass
try: return json.loads(json_str[:-1])
except: pass
except Exception: pass
if '}' in json_str: json_str = json_str[:json_str.rfind('}') + 1]
return json.loads(json_str)

Expand Down
2 changes: 1 addition & 1 deletion memory/autonomous_operation_sop/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ def complete_task(taskname: str, historyline: str, report_path: str) -> str:
# 回滚:把报告移回去
try:
shutil.move(str(dest_path), str(report))
except:
except Exception:
pass
return f"[ERROR] 写入 history 失败: {e}(报告已回滚)"

Expand Down
2 changes: 1 addition & 1 deletion memory/ljqCtrl.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
try:
from PIL import ImageGrab, Image, ImageEnhance, ImageFilter, ImageDraw
import cv2
except: pass
except Exception: pass

_hdc = ctypes.windll.user32.GetDC(0)
swidth = ctypes.windll.gdi32.GetDeviceCaps(_hdc, 118) # DESKTOPHORZRES (物理)
Expand Down
2 changes: 1 addition & 1 deletion plugins/langfuse_tracing.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ def _extract_usage(buf):
ds = s[5:].lstrip()
if ds == '[DONE]': continue
try: evt = _j.loads(ds)
except: continue
except Exception: continue
if evt.get('type') == 'message_start':
us = evt.get('message', {}).get('usage', {}) or {}
u['input'] = us.get('input_tokens', u.get('input', 0))
Expand Down
2 changes: 1 addition & 1 deletion reflect/scheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def _last_run(tid, done_files):
try:
t = datetime.strptime(df[:15], '%Y-%m-%d_%H%M')
if latest is None or t > latest: latest = t
except: continue
except Exception: continue
return latest

def check():
Expand Down
8 changes: 4 additions & 4 deletions simphtml.py
Original file line number Diff line number Diff line change
Expand Up @@ -635,7 +635,7 @@ def optimize_html_for_tokens(html):
"""
def start_temp_monitor(driver):
try: driver.execute_js(temp_monitor_js)
except: pass
except Exception: pass

def get_temp_texts(driver):
js = """function stopStrMonitor() {
Expand Down Expand Up @@ -821,7 +821,7 @@ def execute_js_rich(script, driver, no_monitor=False):
last_html = None
if not no_monitor:
try: last_html = get_html(driver, cutlist=False, extra_js=temp_monitor_js, maxchars=9999999)
except: pass
except Exception: pass
result = None; error_msg = None; reloaded = False; newTabs = []
before_sids = set(driver.get_session_dict().keys()); response = {}
try:
Expand Down Expand Up @@ -853,7 +853,7 @@ def execute_js_rich(script, driver, no_monitor=False):
if no_monitor: return rr
if not reloaded:
try: rr['transients'] = get_temp_texts(driver)
except: rr['transients'] = []
except Exception: rr['transients'] = []
if not reloaded and len(newTabs) == 0:
try:
current_html = get_html(driver, cutlist=False, maxchars=9999999)
Expand All @@ -867,7 +867,7 @@ def execute_js_rich(script, driver, no_monitor=False):
if change_count == 0 and not transients and len(newTabs) == 0:
diff_summary += " (页面无变化)"
rr['suggestion'] = "页面无明显变化"
except:
except Exception:
diff_summary = "页面变化监控不可用"
rr['diff'] = diff_summary
return rr