DR-256-backup / tools /common.py
Shangy's picture
Publish DeepResearch-9K local-search frontier v1
a06d854 verified
Raw History Blame Contribute Delete
6.52 kB
"""Shared, dependency-light helpers for the DeepResearch-9K pipeline."""
from __future__ import annotations
import ast
import hashlib
import json
import re
import unicodedata
from collections.abc import Iterable, Iterator
from pathlib import Path
from typing import Any
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
TOOL_CALL_RE = re.compile(r"<tool_call>\s*(.*?)\s*</tool_call>", re.DOTALL | re.IGNORECASE)
TRACKING_QUERY_KEYS = {
"fbclid",
"gclid",
"mc_cid",
"mc_eid",
}
def normalize_question(text: str) -> str:
"""Normalize a question for duplicate detection without rewriting content."""
return re.sub(r"\s+", " ", unicodedata.normalize("NFKC", text or "")).strip()
def question_key(text: str) -> str:
return normalize_question(text).casefold()
def stable_qid(question: str) -> str:
digest = hashlib.sha256(question_key(question).encode("utf-8")).hexdigest()[:16]
return f"dr9k-{digest}"
def to_plain(value: Any) -> Any:
"""Recursively convert numpy/Arrow containers to JSON-compatible values."""
if hasattr(value, "tolist"):
return to_plain(value.tolist())
if isinstance(value, dict):
return {str(key): to_plain(item) for key, item in value.items()}
if isinstance(value, (list, tuple)):
return [to_plain(item) for item in value]
if hasattr(value, "item"):
try:
return value.item()
except (TypeError, ValueError):
pass
return value
def trajectory_fingerprint(row: dict[str, Any]) -> str:
"""Fingerprint the complete public row so DeepResearch-Hard matches exactly."""
payload = {
"question": normalize_question(str(row["question"])),
"difficulty": int(row["difficulty"]),
"search trajectory": to_plain(row["search trajectory"]),
"final answer": str(row["final answer"]).strip(),
}
encoded = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(encoded.encode("utf-8")).hexdigest()
def parse_tool_call_block(block: str) -> dict[str, Any]:
"""Parse one JSON-ish tool-call block.
The public data contains a small number of Python-literal or fenced blocks,
so JSON is attempted first and ``literal_eval`` is a conservative fallback.
"""
value = block.strip()
if value.startswith("```") and value.endswith("```"):
value = re.sub(r"^```(?:json)?\s*|\s*```$", "", value, flags=re.DOTALL | re.IGNORECASE).strip()
errors: list[str] = []
for parser in (json.loads, ast.literal_eval):
try:
result = parser(value)
if not isinstance(result, dict):
raise ValueError(f"tool call is {type(result).__name__}, not an object")
name = result.get("name")
arguments = result.get("arguments", {})
if not isinstance(name, str) or not name.strip():
raise ValueError("tool call has no string name")
if not isinstance(arguments, dict):
raise ValueError("tool-call arguments are not an object")
return {"name": name.strip(), "arguments": arguments}
except (SyntaxError, ValueError, TypeError, json.JSONDecodeError) as exc:
errors.append(str(exc))
raise ValueError("; ".join(errors))
def iter_tool_calls(trajectory: Iterable[dict[str, Any]]) -> Iterator[tuple[int, int, dict[str, Any], str]]:
"""Yield ``(message_index, block_index, call, raw_block)`` from a trajectory."""
for message_index, message in enumerate(trajectory):
if message.get("role") != "assistant":
continue
content = str(message.get("content") or "")
for block_index, match in enumerate(TOOL_CALL_RE.finditer(content)):
raw = match.group(1)
yield message_index, block_index, parse_tool_call_block(raw), raw
def as_string_list(value: Any) -> list[str]:
if isinstance(value, str):
return [value.strip()] if value.strip() else []
if isinstance(value, (list, tuple)):
return [str(item).strip() for item in value if str(item).strip()]
return []
def unwrap_jina_url(url: str) -> tuple[str, bool]:
"""Return the underlying URL for an observed r.jina.ai reader URL."""
value = url.strip()
match = re.match(r"^https?://r\.jina\.ai/(https?://.+)$", value, flags=re.IGNORECASE)
return (match.group(1), True) if match else (value, False)
def canonicalize_url(url: str) -> str:
"""Canonicalize an HTTP(S) URL for corpus deduplication."""
value, _ = unwrap_jina_url(url)
parsed = urlsplit(value.strip())
scheme = parsed.scheme.lower()
if scheme not in {"http", "https"} or not parsed.hostname:
raise ValueError("only absolute HTTP(S) URLs are supported")
hostname = parsed.hostname.encode("idna").decode("ascii").lower()
port = parsed.port
netloc = hostname
if port and not ((scheme == "http" and port == 80) or (scheme == "https" and port == 443)):
netloc = f"{hostname}:{port}"
if parsed.username or parsed.password:
raise ValueError("credential-bearing URLs are not supported")
path = re.sub(r"/{2,}", "/", parsed.path or "/")
if path != "/":
path = path.rstrip("/")
query_items = []
for key, item in parse_qsl(parsed.query, keep_blank_values=True):
lowered = key.casefold()
if lowered.startswith("utm_") or lowered in TRACKING_QUERY_KEYS:
continue
query_items.append((key, item))
query = urlencode(sorted(query_items))
return urlunsplit((scheme, netloc, path, query, ""))
def url_id(canonical_url: str) -> str:
return "url-" + hashlib.sha256(canonical_url.encode("utf-8")).hexdigest()[:24]
def write_jsonl(path: Path, records: Iterable[dict[str, Any]]) -> int:
path.parent.mkdir(parents=True, exist_ok=True)
count = 0
with path.open("w", encoding="utf-8") as handle:
for record in records:
handle.write(json.dumps(record, ensure_ascii=False, sort_keys=True) + "\n")
count += 1
return count
def read_jsonl(path: Path) -> Iterator[dict[str, Any]]:
with path.open(encoding="utf-8") as handle:
for line_number, line in enumerate(handle, start=1):
if not line.strip():
continue
try:
yield json.loads(line)
except json.JSONDecodeError as exc:
raise ValueError(f"invalid JSON in {path}:{line_number}: {exc}") from exc