mirror of
https://github.com/NousResearch/hermes-agent.git
synced 2026-05-24 05:41:40 +00:00
chore: ruff auto-fix C401, C416, C408, PLR1722 (#23940)
C401: set(x for x in y) -> {x for x in y} (set comprehension)
C416: [(k,v) for k,v in d] -> list(d.items()) (unnecessary listcomp)
C408: tuple()/dict() -> ()/{} (unnecessary collection call)
PLR1722: exit() -> sys.exit() (adds import sys where needed)
21 instances fixed, 0 remaining. 19 files, +40/-36.
This commit is contained in:
parent
7b76366552
commit
ce0f529cde
19 changed files with 40 additions and 36 deletions
|
|
@ -919,7 +919,7 @@ class TerminalBench2EvalEnv(HermesAgentBaseEnv):
|
||||||
eval_metrics[f"eval/pass_rate_{cat_key}"] = cat_pass_rate
|
eval_metrics[f"eval/pass_rate_{cat_key}"] = cat_pass_rate
|
||||||
|
|
||||||
# Store metrics for wandb_log
|
# Store metrics for wandb_log
|
||||||
self.eval_metrics = [(k, v) for k, v in eval_metrics.items()]
|
self.eval_metrics = list(eval_metrics.items())
|
||||||
|
|
||||||
# ---- Print summary ----
|
# ---- Print summary ----
|
||||||
print(f"\n{'='*60}")
|
print(f"\n{'='*60}")
|
||||||
|
|
|
||||||
|
|
@ -759,7 +759,7 @@ class YCBenchEvalEnv(HermesAgentBaseEnv):
|
||||||
eval_metrics[f"eval/survival_rate_{key}"] = ps / pt if pt else 0
|
eval_metrics[f"eval/survival_rate_{key}"] = ps / pt if pt else 0
|
||||||
eval_metrics[f"eval/avg_score_{key}"] = pa
|
eval_metrics[f"eval/avg_score_{key}"] = pa
|
||||||
|
|
||||||
self.eval_metrics = [(k, v) for k, v in eval_metrics.items()]
|
self.eval_metrics = list(eval_metrics.items())
|
||||||
|
|
||||||
# --- Print summary ---
|
# --- Print summary ---
|
||||||
print(f"\n{'='*60}")
|
print(f"\n{'='*60}")
|
||||||
|
|
|
||||||
|
|
@ -3724,7 +3724,7 @@ class DiscordAdapter(BasePlatformAdapter):
|
||||||
return None
|
return None
|
||||||
|
|
||||||
# DMs, voice channels, and existing threads can't host child threads.
|
# DMs, voice channels, and existing threads can't host child threads.
|
||||||
if isinstance(parent, getattr(discord, "DMChannel", tuple())):
|
if isinstance(parent, getattr(discord, "DMChannel", ())):
|
||||||
logger.info(
|
logger.info(
|
||||||
"[%s] Handoff thread: parent %s is a DM; threads not supported here",
|
"[%s] Handoff thread: parent %s is a DM; threads not supported here",
|
||||||
self.name, parent_chat_id,
|
self.name, parent_chat_id,
|
||||||
|
|
|
||||||
|
|
@ -1428,8 +1428,8 @@ class FeishuAdapter(BasePlatformAdapter):
|
||||||
per_chat_require_mention = _to_boolean(rule_cfg.get("require_mention"))
|
per_chat_require_mention = _to_boolean(rule_cfg.get("require_mention"))
|
||||||
group_rules[str(chat_id)] = FeishuGroupRule(
|
group_rules[str(chat_id)] = FeishuGroupRule(
|
||||||
policy=str(rule_cfg.get("policy", "open")).strip().lower(),
|
policy=str(rule_cfg.get("policy", "open")).strip().lower(),
|
||||||
allowlist=set(str(u).strip() for u in rule_cfg.get("allowlist", []) if str(u).strip()),
|
allowlist={str(u).strip() for u in rule_cfg.get("allowlist", []) if str(u).strip()},
|
||||||
blacklist=set(str(u).strip() for u in rule_cfg.get("blacklist", []) if str(u).strip()),
|
blacklist={str(u).strip() for u in rule_cfg.get("blacklist", []) if str(u).strip()},
|
||||||
require_mention=per_chat_require_mention,
|
require_mention=per_chat_require_mention,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -228,7 +228,7 @@ def _load_pairing_approved() -> set:
|
||||||
if isinstance(approved, dict):
|
if isinstance(approved, dict):
|
||||||
return set(approved.keys())
|
return set(approved.keys())
|
||||||
if isinstance(approved, list):
|
if isinstance(approved, list):
|
||||||
return set(str(u) for u in approved if u)
|
return {str(u) for u in approved if u}
|
||||||
return set()
|
return set()
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -59,7 +59,7 @@ class TelegramFallbackTransport(httpx.AsyncBaseTransport):
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, fallback_ips: Iterable[str], **transport_kwargs):
|
def __init__(self, fallback_ips: Iterable[str], **transport_kwargs):
|
||||||
self._fallback_ips = [ip for ip in dict.fromkeys(_normalize_fallback_ips(fallback_ips))]
|
self._fallback_ips = list(dict.fromkeys(_normalize_fallback_ips(fallback_ips)))
|
||||||
proxy_url = _resolve_proxy_url(target_hosts=[_TELEGRAM_API_HOST, *self._fallback_ips])
|
proxy_url = _resolve_proxy_url(target_hosts=[_TELEGRAM_API_HOST, *self._fallback_ips])
|
||||||
if proxy_url and "proxy" not in transport_kwargs:
|
if proxy_url and "proxy" not in transport_kwargs:
|
||||||
transport_kwargs["proxy"] = proxy_url
|
transport_kwargs["proxy"] = proxy_url
|
||||||
|
|
|
||||||
|
|
@ -2337,7 +2337,7 @@ class SessionDB:
|
||||||
"SELECT id FROM sessions WHERE started_at < ? AND ended_at IS NOT NULL",
|
"SELECT id FROM sessions WHERE started_at < ? AND ended_at IS NOT NULL",
|
||||||
(cutoff,),
|
(cutoff,),
|
||||||
)
|
)
|
||||||
session_ids = set(row["id"] for row in cursor.fetchall())
|
session_ids = {row["id"] for row in cursor.fetchall()}
|
||||||
|
|
||||||
if not session_ids:
|
if not session_ids:
|
||||||
return 0
|
return 0
|
||||||
|
|
|
||||||
|
|
@ -343,7 +343,7 @@ def key_metrics(data: dict[str, Any]) -> dict[str, float]:
|
||||||
metrics["backpressure_frames"] = bp
|
metrics["backpressure_frames"] = bp
|
||||||
|
|
||||||
if react:
|
if react:
|
||||||
for pid in set(e["id"] for e in react):
|
for pid in {e["id"] for e in react}:
|
||||||
ms = [e["actualMs"] for e in react if e["id"] == pid]
|
ms = [e["actualMs"] for e in react if e["id"] == pid]
|
||||||
metrics[f"react_{pid}_p99"] = pct(ms, 0.99)
|
metrics[f"react_{pid}_p99"] = pct(ms, 0.99)
|
||||||
metrics[f"react_{pid}_max"] = max(ms)
|
metrics[f"react_{pid}_max"] = max(ms)
|
||||||
|
|
|
||||||
|
|
@ -1426,7 +1426,7 @@ def main():
|
||||||
print(f" SemVer: v{current_version} → v{new_version}")
|
print(f" SemVer: v{current_version} → v{new_version}")
|
||||||
print(f" Previous tag: {prev_tag or '(none — first release)'}")
|
print(f" Previous tag: {prev_tag or '(none — first release)'}")
|
||||||
print(f" Commits: {len(commits)}")
|
print(f" Commits: {len(commits)}")
|
||||||
print(f" Unique authors: {len(set(c['github_author'] for c in commits))}")
|
print(f" Unique authors: {len({c['github_author'] for c in commits})}")
|
||||||
print(f" Mode: {'PUBLISH' if args.publish else 'DRY RUN'}")
|
print(f" Mode: {'PUBLISH' if args.publish else 'DRY RUN'}")
|
||||||
print(f"{'='*60}")
|
print(f"{'='*60}")
|
||||||
print()
|
print()
|
||||||
|
|
|
||||||
|
|
@ -291,7 +291,7 @@ class MemoryStore:
|
||||||
|
|
||||||
if len(matches) > 1:
|
if len(matches) > 1:
|
||||||
# If all matches are identical (exact duplicates), operate on the first one
|
# If all matches are identical (exact duplicates), operate on the first one
|
||||||
unique_texts = set(e for _, e in matches)
|
unique_texts = {e for _, e in matches}
|
||||||
if len(unique_texts) > 1:
|
if len(unique_texts) > 1:
|
||||||
previews = [e[:80] + ("..." if len(e) > 80 else "") for _, e in matches]
|
previews = [e[:80] + ("..." if len(e) > 80 else "") for _, e in matches]
|
||||||
return {
|
return {
|
||||||
|
|
@ -341,7 +341,7 @@ class MemoryStore:
|
||||||
|
|
||||||
if len(matches) > 1:
|
if len(matches) > 1:
|
||||||
# If all matches are identical (exact duplicates), remove the first one
|
# If all matches are identical (exact duplicates), remove the first one
|
||||||
unique_texts = set(e for _, e in matches)
|
unique_texts = {e for _, e in matches}
|
||||||
if len(unique_texts) > 1:
|
if len(unique_texts) > 1:
|
||||||
previews = [e[:80] + ("..." if len(e) > 80 else "") for _, e in matches]
|
previews = [e[:80] + ("..." if len(e) > 80 else "") for _, e in matches]
|
||||||
return {
|
return {
|
||||||
|
|
|
||||||
|
|
@ -54,6 +54,7 @@ from typing import Dict, Any, List, Optional
|
||||||
from tools.openrouter_client import get_async_client as _get_openrouter_client, check_api_key as check_openrouter_api_key
|
from tools.openrouter_client import get_async_client as _get_openrouter_client, check_api_key as check_openrouter_api_key
|
||||||
from agent.auxiliary_client import extract_content_or_reasoning
|
from agent.auxiliary_client import extract_content_or_reasoning
|
||||||
from tools.debug_helpers import DebugSession
|
from tools.debug_helpers import DebugSession
|
||||||
|
import sys
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
@ -451,7 +452,7 @@ if __name__ == "__main__":
|
||||||
print("❌ OPENROUTER_API_KEY environment variable not set")
|
print("❌ OPENROUTER_API_KEY environment variable not set")
|
||||||
print("Please set your API key: export OPENROUTER_API_KEY='your-key-here'")
|
print("Please set your API key: export OPENROUTER_API_KEY='your-key-here'")
|
||||||
print("Get API key at: https://openrouter.ai/")
|
print("Get API key at: https://openrouter.ai/")
|
||||||
exit(1)
|
sys.exit(1)
|
||||||
else:
|
else:
|
||||||
print("✅ OpenRouter API key found")
|
print("✅ OpenRouter API key found")
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -928,5 +928,5 @@ def _build_summary(name: str, source: str, trust: str, verdict: str, findings: L
|
||||||
if not findings:
|
if not findings:
|
||||||
return f"{name}: clean scan, no threats detected"
|
return f"{name}: clean scan, no threats detected"
|
||||||
|
|
||||||
categories = set(f.category for f in findings)
|
categories = {f.category for f in findings}
|
||||||
return f"{name}: {verdict} — {len(findings)} finding(s) in {', '.join(sorted(categories))}"
|
return f"{name}: {verdict} — {len(findings)} finding(s) in {', '.join(sorted(categories))}"
|
||||||
|
|
|
||||||
|
|
@ -345,7 +345,7 @@ def reset_bundled_skill(name: str, restore: bool = False) -> dict:
|
||||||
manifest = _read_manifest()
|
manifest = _read_manifest()
|
||||||
bundled_dir = _get_bundled_dir()
|
bundled_dir = _get_bundled_dir()
|
||||||
bundled_skills = _discover_bundled_skills(bundled_dir)
|
bundled_skills = _discover_bundled_skills(bundled_dir)
|
||||||
bundled_by_name = {skill_name: skill_dir for skill_name, skill_dir in bundled_skills}
|
bundled_by_name = dict(bundled_skills)
|
||||||
|
|
||||||
in_manifest = name in manifest
|
in_manifest = name in manifest
|
||||||
is_bundled = name in bundled_by_name
|
is_bundled = name in bundled_by_name
|
||||||
|
|
|
||||||
|
|
@ -721,7 +721,7 @@ def skills_list(category: str = None, task_id: str = None) -> str:
|
||||||
|
|
||||||
# Extract unique categories
|
# Extract unique categories
|
||||||
categories = sorted(
|
categories = sorted(
|
||||||
set(s.get("category") for s in all_skills if s.get("category"))
|
{s.get("category") for s in all_skills if s.get("category")}
|
||||||
)
|
)
|
||||||
|
|
||||||
return json.dumps(
|
return json.dumps(
|
||||||
|
|
|
||||||
|
|
@ -888,6 +888,7 @@ from tools.environments.docker import DockerEnvironment as _DockerEnvironment
|
||||||
from tools.environments.modal import ModalEnvironment as _ModalEnvironment
|
from tools.environments.modal import ModalEnvironment as _ModalEnvironment
|
||||||
from tools.environments.managed_modal import ManagedModalEnvironment as _ManagedModalEnvironment
|
from tools.environments.managed_modal import ManagedModalEnvironment as _ManagedModalEnvironment
|
||||||
from tools.managed_tool_gateway import is_managed_tool_gateway_ready
|
from tools.managed_tool_gateway import is_managed_tool_gateway_ready
|
||||||
|
import sys
|
||||||
|
|
||||||
|
|
||||||
# Tool description for LLM
|
# Tool description for LLM
|
||||||
|
|
@ -2243,7 +2244,7 @@ if __name__ == "__main__":
|
||||||
|
|
||||||
if not check_terminal_requirements():
|
if not check_terminal_requirements():
|
||||||
print("\n❌ Requirements not met. Please check the messages above.")
|
print("\n❌ Requirements not met. Please check the messages above.")
|
||||||
exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
print("\n✅ All requirements met!")
|
print("\n✅ All requirements met!")
|
||||||
print("\nAvailable Tool:")
|
print("\nAvailable Tool:")
|
||||||
|
|
|
||||||
|
|
@ -848,13 +848,13 @@ def _generate_openai_tts(text: str, output_path: str, tts_config: Dict[str, Any]
|
||||||
OpenAIClient = _import_openai_client()
|
OpenAIClient = _import_openai_client()
|
||||||
client = OpenAIClient(api_key=api_key, base_url=base_url)
|
client = OpenAIClient(api_key=api_key, base_url=base_url)
|
||||||
try:
|
try:
|
||||||
create_kwargs = dict(
|
create_kwargs = {
|
||||||
model=model,
|
"model": model,
|
||||||
voice=voice,
|
"voice": voice,
|
||||||
input=text,
|
"input": text,
|
||||||
response_format=response_format,
|
"response_format": response_format,
|
||||||
extra_headers={"x-idempotency-key": str(uuid.uuid4())},
|
"extra_headers": {"x-idempotency-key": str(uuid.uuid4())},
|
||||||
)
|
}
|
||||||
if speed != 1.0:
|
if speed != 1.0:
|
||||||
create_kwargs["speed"] = max(0.25, min(4.0, speed))
|
create_kwargs["speed"] = max(0.25, min(4.0, speed))
|
||||||
response = client.audio.speech.create(**create_kwargs)
|
response = client.audio.speech.create(**create_kwargs)
|
||||||
|
|
|
||||||
|
|
@ -41,6 +41,7 @@ from agent.auxiliary_client import async_call_llm, extract_content_or_reasoning
|
||||||
from hermes_constants import get_hermes_dir
|
from hermes_constants import get_hermes_dir
|
||||||
from tools.debug_helpers import DebugSession
|
from tools.debug_helpers import DebugSession
|
||||||
from tools.website_policy import check_website_access
|
from tools.website_policy import check_website_access
|
||||||
|
import sys
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
@ -937,7 +938,7 @@ if __name__ == "__main__":
|
||||||
if not api_available:
|
if not api_available:
|
||||||
print("❌ No auxiliary vision model available")
|
print("❌ No auxiliary vision model available")
|
||||||
print("Configure a supported multimodal backend (OpenRouter, Nous, Codex, Anthropic, or a custom OpenAI-compatible endpoint).")
|
print("Configure a supported multimodal backend (OpenRouter, Nous, Codex, Anthropic, or a custom OpenAI-compatible endpoint).")
|
||||||
exit(1)
|
sys.exit(1)
|
||||||
else:
|
else:
|
||||||
print("✅ Vision model available")
|
print("✅ Vision model available")
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -100,6 +100,7 @@ from tools.managed_tool_gateway import (
|
||||||
from tools.tool_backend_helpers import managed_nous_tools_enabled, prefers_gateway
|
from tools.tool_backend_helpers import managed_nous_tools_enabled, prefers_gateway
|
||||||
from tools.url_safety import is_safe_url
|
from tools.url_safety import is_safe_url
|
||||||
from tools.website_policy import check_website_access
|
from tools.website_policy import check_website_access
|
||||||
|
import sys
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
@ -2153,7 +2154,7 @@ if __name__ == "__main__":
|
||||||
print(f"✅ Auxiliary model available: {default_summarizer_model}")
|
print(f"✅ Auxiliary model available: {default_summarizer_model}")
|
||||||
|
|
||||||
if not web_available:
|
if not web_available:
|
||||||
exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
print("🛠️ Web tools ready for use!")
|
print("🛠️ Web tools ready for use!")
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1624,27 +1624,27 @@ def _on_tool_progress(
|
||||||
|
|
||||||
|
|
||||||
def _agent_cbs(sid: str) -> dict:
|
def _agent_cbs(sid: str) -> dict:
|
||||||
return dict(
|
return {
|
||||||
tool_start_callback=lambda tc_id, name, args: _on_tool_start(
|
"tool_start_callback": lambda tc_id, name, args: _on_tool_start(
|
||||||
sid, tc_id, name, args
|
sid, tc_id, name, args
|
||||||
),
|
),
|
||||||
tool_complete_callback=lambda tc_id, name, args, result: _on_tool_complete(
|
"tool_complete_callback": lambda tc_id, name, args, result: _on_tool_complete(
|
||||||
sid, tc_id, name, args, result
|
sid, tc_id, name, args, result
|
||||||
),
|
),
|
||||||
tool_progress_callback=lambda event_type, name=None, preview=None, args=None, **kwargs: _on_tool_progress(
|
"tool_progress_callback": lambda event_type, name=None, preview=None, args=None, **kwargs: _on_tool_progress(
|
||||||
sid, event_type, name, preview, args, **kwargs
|
sid, event_type, name, preview, args, **kwargs
|
||||||
),
|
),
|
||||||
tool_gen_callback=lambda name: _tool_progress_enabled(sid)
|
"tool_gen_callback": lambda name: _tool_progress_enabled(sid)
|
||||||
and _emit("tool.generating", sid, {"name": name}),
|
and _emit("tool.generating", sid, {"name": name}),
|
||||||
thinking_callback=lambda text: _emit("thinking.delta", sid, {"text": text}),
|
"thinking_callback": lambda text: _emit("thinking.delta", sid, {"text": text}),
|
||||||
reasoning_callback=lambda text: _emit("reasoning.delta", sid, {"text": text}),
|
"reasoning_callback": lambda text: _emit("reasoning.delta", sid, {"text": text}),
|
||||||
status_callback=lambda kind, text=None: _status_update(
|
"status_callback": lambda kind, text=None: _status_update(
|
||||||
sid, str(kind), None if text is None else str(text)
|
sid, str(kind), None if text is None else str(text)
|
||||||
),
|
),
|
||||||
clarify_callback=lambda q, c: _block(
|
"clarify_callback": lambda q, c: _block(
|
||||||
"clarify.request", sid, {"question": q, "choices": c}
|
"clarify.request", sid, {"question": q, "choices": c}
|
||||||
),
|
),
|
||||||
)
|
}
|
||||||
|
|
||||||
|
|
||||||
def _wire_callbacks(sid: str):
|
def _wire_callbacks(sid: str):
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue