refactor(tools): x_search filter/tool_def builder helper; single retry loop; inline one-shot config getters

This commit is contained in:
Teknium
2026-09-02 22:15:04 -07:00
parent 8b53adec12
commit dc481dcb37
2 changed files with 88 additions and 162 deletions
+86 -161
View File
@@ -4,16 +4,13 @@
Registers when either xAI credential path is available (``XAI_API_KEY`` or
``hermes auth add xai-oauth``). At call time an explicit ``XAI_API_KEY`` wins
(``prefer_api_key=True``): x_search is API-metered and the subscription OAuth
bearer answers ``/v1/responses`` in a degraded no-citation mode (#88040).
bearer answers ``/v1/responses`` in a degraded no-citation mode.
Defensive output: ``from_date``/``to_date`` are validated client-side (strict
``YYYY-MM-DD``, ``from <= to``, ``from`` not in the future) so malformed windows
fail fast instead of burning a billable call. Successful responses carry
``degraded``/``degraded_reason``: True when a narrowing filter was active AND
xAI returned no citations in either channel, meaning the answer came from the
model's own knowledge rather than the X index.
Salvaged from PR #10786 (originally by @Jaaneek).
``from_date``/``to_date`` are validated client-side (strict ``YYYY-MM-DD``, ``from <= to``,
``from`` not in the future) so malformed windows fail fast instead of burning a billable
call. Successful responses carry ``degraded``/``degraded_reason``: True when a narrowing
filter was active AND xAI returned no citations in either channel (answer came from the
model's own knowledge, not the X index).
"""
from __future__ import annotations
@@ -38,10 +35,6 @@ X_SEARCH_REASONING_EFFORTS = ("low", "medium", "high", "xhigh")
MAX_HANDLES = 10
# ---------------------------------------------------------------------------
# Config
# ---------------------------------------------------------------------------
def _load_x_search_config() -> Dict[str, Any]:
try:
from hermes_cli.config import load_config
@@ -51,29 +44,20 @@ def _load_x_search_config() -> Dict[str, Any]:
return {}
def _get_x_search_model() -> str:
return str(_load_x_search_config().get("model") or "").strip() or DEFAULT_X_SEARCH_MODEL
def _get_x_search_reasoning_effort() -> Optional[str]:
raw_value = _load_x_search_config().get("reasoning_effort")
if raw_value is None or not str(raw_value).strip():
return None
effort = str(raw_value).strip().lower()
if effort not in X_SEARCH_REASONING_EFFORTS:
allowed = ", ".join(X_SEARCH_REASONING_EFFORTS)
raise ValueError(
f"x_search.reasoning_effort must be one of: {allowed} "
f"(got {raw_value!r})"
)
raise ValueError(f"x_search.reasoning_effort must be one of: {allowed} (got {raw_value!r})")
return effort
def _get_x_search_int(key: str, default: int, floor: int) -> int:
raw_value = _load_x_search_config().get(key, default)
try:
return max(floor, int(raw_value))
return max(floor, int(_load_x_search_config().get(key, default)))
except Exception:
return default
@@ -82,20 +66,12 @@ def _get_x_search_timeout_seconds() -> int:
return _get_x_search_int("timeout_seconds", DEFAULT_X_SEARCH_TIMEOUT_SECONDS, 30)
def _get_x_search_retries() -> int:
return _get_x_search_int("retries", DEFAULT_X_SEARCH_RETRIES, 0)
# ---------------------------------------------------------------------------
# Credential resolution
# ---------------------------------------------------------------------------
def _resolve_xai_bearer() -> Tuple[str, str, str]:
"""Return ``(api_key, base_url, source)``; ``source`` is ``"xai-oauth"`` or ``"xai"``.
Raises ``RuntimeError`` when no credential is usable so a credential that
expires between registration and invocation yields a clean tool error, not
a 401. ``prefer_api_key=True``: see module docstring (#88040).
Raises ``RuntimeError`` when no credential is usable so a credential that expires
between registration and invocation yields a clean tool error, not a 401.
``prefer_api_key=True``: see module docstring.
"""
creds = resolve_xai_http_credentials(prefer_api_key=True)
api_key = str(creds.get("api_key") or "").strip()
@@ -105,23 +81,17 @@ def _resolve_xai_bearer() -> Tuple[str, str, str]:
"to sign in with your SuperGrok subscription, or set XAI_API_KEY."
)
base_url = str(creds.get("base_url") or DEFAULT_XAI_BASE_URL).strip().rstrip("/")
source = str(creds.get("provider") or "xai")
return api_key, base_url, source
return api_key, base_url, str(creds.get("provider") or "xai")
def check_x_search_requirements() -> bool:
"""True when xAI credentials resolve to a non-empty bearer (OAuth auto-refreshed)."""
try:
creds = resolve_xai_http_credentials()
return bool(str(creds.get("api_key") or "").strip())
return bool(str(resolve_xai_http_credentials().get("api_key") or "").strip())
except Exception:
return False
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _normalize_handles(handles: Optional[List[str]], field_name: str) -> List[str]:
cleaned = [h for h in (str(handle or "").strip().lstrip("@") for handle in handles or []) if h]
if len(cleaned) > MAX_HANDLES:
@@ -135,9 +105,7 @@ def _parse_iso_date(value: str, field_name: str) -> date:
try:
return datetime.strptime(raw, "%Y-%m-%d").date()
except ValueError as exc:
raise ValueError(
f"{field_name} must be YYYY-MM-DD (got {raw!r})"
) from exc
raise ValueError(f"{field_name} must be YYYY-MM-DD (got {raw!r})") from exc
def _validate_date_range(from_date: str, to_date: str) -> None:
@@ -146,17 +114,14 @@ def _validate_date_range(from_date: str, to_date: str) -> None:
parsed_to = _parse_iso_date(to_date, "to_date") if to_date.strip() else None
if parsed_from and parsed_to and parsed_from > parsed_to:
raise ValueError(
f"from_date ({parsed_from.isoformat()}) must be on or before "
f"to_date ({parsed_to.isoformat()})"
f"from_date ({parsed_from.isoformat()}) must be on or before to_date ({parsed_to.isoformat()})"
)
today_utc = datetime.now(timezone.utc).date()
if parsed_from is not None and parsed_from > today_utc:
raise ValueError(
f"from_date ({parsed_from.isoformat()}) is in the future; "
f"X Search only indexes past posts (today UTC is {today_utc.isoformat()})"
)
if parsed_from is not None:
today_utc = datetime.now(timezone.utc).date()
if parsed_from > today_utc:
raise ValueError(
f"from_date ({parsed_from.isoformat()}) is in the future; "
f"X Search only indexes past posts (today UTC is "
f"{today_utc.isoformat()})"
)
def _message_contents(payload: Dict[str, Any]):
@@ -169,14 +134,12 @@ def _extract_response_text(payload: Dict[str, Any]) -> str:
output_text = str(payload.get("output_text") or "").strip()
if output_text:
return output_text
parts: List[str] = []
for content in _message_contents(payload):
if content.get("type") in {"output_text", "text"}:
text = str(content.get("text") or "").strip()
if text:
parts.append(text)
return "\n\n".join(parts).strip()
parts = [
str(content.get("text") or "").strip()
for content in _message_contents(payload)
if content.get("type") in {"output_text", "text"}
]
return "\n\n".join(p for p in parts if p).strip()
def _extract_inline_citations(payload: Dict[str, Any]) -> List[Dict[str, Any]]:
@@ -197,79 +160,76 @@ def _http_error_message(exc: requests.HTTPError) -> str:
response = getattr(exc, "response", None)
if response is None:
return str(exc)
try:
payload = response.json()
except Exception:
payload = None
if isinstance(payload, dict):
code = str(payload.get("code") or "").strip()
error = str(payload.get("error") or "").strip()
message = error or str(payload)
message = str(payload.get("error") or "").strip() or str(payload)
if code and code not in message:
message = f"{code}: {message}"
return message or str(exc)
text = str(getattr(response, "text", "") or "").strip()
if text:
return text[:500]
return str(exc)
return text[:500] if text else str(exc)
def _error_json(error: str, exc: BaseException) -> str:
return json.dumps(
{
"success": False,
"provider": "xai",
"tool": "x_search",
"error": error,
"error_type": type(exc).__name__,
},
ensure_ascii=False,
)
body = {"success": False, "provider": "xai", "tool": "x_search", "error": error}
return json.dumps({**body, "error_type": type(exc).__name__}, ensure_ascii=False)
def _post_with_retries(url: str, headers: Dict[str, str], payload: Dict[str, Any]) -> requests.Response:
"""POST with retries on 5xx / timeout / connection errors; re-raises the last failure."""
timeout_seconds = _get_x_search_timeout_seconds()
max_retries = _get_x_search_retries()
response: Optional[requests.Response] = None
max_retries = _get_x_search_int("retries", DEFAULT_X_SEARCH_RETRIES, 0)
for attempt in range(max_retries + 1):
try:
response = requests.post(url, headers=headers, json=payload, timeout=timeout_seconds)
response.raise_for_status()
break
return response
except requests.HTTPError as e:
status_code = getattr(getattr(e, "response", None), "status_code", None)
if status_code is None or status_code < 500 or attempt >= max_retries:
raise
logger.warning(
"x_search upstream failure on attempt %s/%s: %s",
attempt + 1,
max_retries + 1,
_http_error_message(e),
)
time.sleep(min(5.0, 1.5 * (attempt + 1)))
kind, detail = "upstream", _http_error_message(e)
except (requests.ReadTimeout, requests.ConnectionError) as e:
if attempt >= max_retries:
raise
logger.warning(
"x_search transient failure on attempt %s/%s: %s",
attempt + 1,
max_retries + 1,
e,
)
time.sleep(min(5.0, 1.5 * (attempt + 1)))
if response is None:
raise RuntimeError("x_search request did not return a response")
return response
kind, detail = "transient", e
logger.warning("x_search %s failure on attempt %s/%s: %s", kind, attempt + 1, max_retries + 1, detail)
time.sleep(min(5.0, 1.5 * (attempt + 1)))
raise RuntimeError("x_search request did not return a response")
# ---------------------------------------------------------------------------
# Tool implementation
# ---------------------------------------------------------------------------
def _build_x_search_tool_def(
allowed_x_handles, excluded_x_handles, from_date: str, to_date: str,
enable_image_understanding: bool, enable_video_understanding: bool,
) -> Tuple[Dict[str, Any], List[str]]:
"""Return ``(tool_def, active_filters)``; raises ValueError on invalid filters."""
allowed = _normalize_handles(allowed_x_handles, "allowed_x_handles")
excluded = _normalize_handles(excluded_x_handles, "excluded_x_handles")
if allowed and excluded:
raise ValueError("allowed_x_handles and excluded_x_handles cannot be used together")
_validate_date_range(from_date, to_date)
tool_def: Dict[str, Any] = {"type": "x_search"}
active_filters: List[str] = []
for key, value in (
("allowed_x_handles", allowed),
("excluded_x_handles", excluded),
("from_date", from_date.strip()),
("to_date", to_date.strip()),
):
if value:
tool_def[key] = value
active_filters.append(key)
if enable_image_understanding:
tool_def["enable_image_understanding"] = True
if enable_video_understanding:
tool_def["enable_video_understanding"] = True
return tool_def, active_filters
def x_search_tool(
query: str,
@@ -282,43 +242,23 @@ def x_search_tool(
) -> str:
if not query or not query.strip():
return tool_error("query is required for x_search")
try:
api_key, base_url, source = _resolve_xai_bearer()
except RuntimeError as exc:
return tool_error(str(exc))
try:
allowed = _normalize_handles(allowed_x_handles, "allowed_x_handles")
excluded = _normalize_handles(excluded_x_handles, "excluded_x_handles")
if allowed and excluded:
return tool_error("allowed_x_handles and excluded_x_handles cannot be used together")
try:
_validate_date_range(from_date, to_date)
tool_def, active_filters = _build_x_search_tool_def(
allowed_x_handles, excluded_x_handles, from_date, to_date,
enable_image_understanding, enable_video_understanding,
)
reasoning_effort = _get_x_search_reasoning_effort()
except ValueError as exc:
return tool_error(str(exc))
from_date, to_date = from_date.strip(), to_date.strip()
tool_def: Dict[str, Any] = {"type": "x_search"}
active_filters: List[str] = []
for key, value in (
("allowed_x_handles", allowed),
("excluded_x_handles", excluded),
("from_date", from_date),
("to_date", to_date),
):
if value:
tool_def[key] = value
active_filters.append(key)
if enable_image_understanding:
tool_def["enable_image_understanding"] = True
if enable_video_understanding:
tool_def["enable_video_understanding"] = True
payload = {
"model": _get_x_search_model(),
"model": str(_load_x_search_config().get("model") or "").strip() or DEFAULT_X_SEARCH_MODEL,
"input": [{"role": "user", "content": query.strip()}],
"tools": [tool_def],
"store": False,
@@ -326,22 +266,17 @@ def x_search_tool(
if reasoning_effort:
payload["reasoning"] = {"effort": reasoning_effort}
response = _post_with_retries(
f"{base_url}/responses",
{
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
"User-Agent": hermes_xai_user_agent(),
},
payload,
)
data = response.json()
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
"User-Agent": hermes_xai_user_agent(),
}
data = _post_with_retries(f"{base_url}/responses", headers, payload).json()
citations = list(data.get("citations") or [])
inline_citations = _extract_inline_citations(data)
# xAI returns 200 with a synthesized answer even when no posts match the
# narrowing filters; with both citation channels empty the answer came
# from training data, so flag it as degraded.
# xAI returns 200 with a synthesized answer even when no posts match the narrowing
# filters; with both citation channels empty the answer came from training data.
degraded = bool(active_filters) and not citations and not inline_citations
return json.dumps(
{
@@ -356,9 +291,7 @@ def x_search_tool(
"inline_citations": inline_citations,
"degraded": degraded,
"degraded_reason": (
f"no citations returned despite filters: {', '.join(active_filters)}"
if degraded
else None
f"no citations returned despite filters: {', '.join(active_filters)}" if degraded else None
),
},
ensure_ascii=False,
@@ -428,23 +361,15 @@ X_SEARCH_SCHEMA = {
def _handle_x_search(args, **kw):
return x_search_tool(
query=args.get("query", ""),
allowed_x_handles=args.get("allowed_x_handles"),
excluded_x_handles=args.get("excluded_x_handles"),
from_date=args.get("from_date", ""),
to_date=args.get("to_date", ""),
enable_image_understanding=bool(args.get("enable_image_understanding", False)),
enable_video_understanding=bool(args.get("enable_video_understanding", False)),
args.get("query", ""), args.get("allowed_x_handles"), args.get("excluded_x_handles"),
args.get("from_date", ""), args.get("to_date", ""),
bool(args.get("enable_image_understanding", False)),
bool(args.get("enable_video_understanding", False)),
)
registry.register(
name="x_search",
toolset="x_search",
schema=X_SEARCH_SCHEMA,
handler=_handle_x_search,
check_fn=check_x_search_requirements,
requires_env=["XAI_API_KEY"],
emoji="🐦",
name="x_search", toolset="x_search", schema=X_SEARCH_SCHEMA, handler=_handle_x_search,
check_fn=check_x_search_requirements, requires_env=["XAI_API_KEY"], emoji="🐦",
max_result_size_chars=100_000,
)
+2 -1
View File
@@ -142,7 +142,8 @@ async def query_group_members(args) -> dict:
action: find (按昵称模糊搜索; 无 name 时等同 list_all) / list_bots / list_all (默认).
"""
group_code, action, name = args.get("group_code", ""), args.get("action", "list_all"), args.get("name", "")
group_code, name = args.get("group_code", ""), args.get("name", "")
action = args.get("action", "list_all")
if not group_code:
return _err("group_code is required")
all_members = [