DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(knowledge): add Zotero BibTeX search
XZH785f13cca74c
diff --git a/deeptutor/i18n/metadata_i18n.py b/deeptutor/i18n/metadata_i18n.pyindex 6d53fdf95..dae452920 100644--- a/deeptutor/i18n/metadata_i18n.py+++ b/deeptutor/i18n/metadata_i18n.py@@ -54,6 +54,10 @@ _TOOL_DESCRIPTIONS: dict[str, dict[str, str]] = {"en": "Search arXiv preprints and return paper metadata.","zh": "搜索 arXiv 预印本并返回论文元数据。",},+ "zotero_search": {+ "en": "Search a user-supplied Zotero library for references.",+ "zh": "搜索用户提供的 Zotero 文献库。",+ },"reason": {"en": "Use a dedicated reasoning model call for hard reasoning tasks.","zh": "调用专门的推理模型处理高难度推理任务。",diff --git a/deeptutor/runtime/worker_tasks.py b/deeptutor/runtime/worker_tasks.pyindex 5a7b87e32..078d6d176 100644--- a/deeptutor/runtime/worker_tasks.py+++ b/deeptutor/runtime/worker_tasks.py@@ -29,11 +29,16 @@ def extract_document_to_markdown(max_bytes: int | None,max_chars: int | None,) -> None:+ source = Path(source_path)text = extract_document_text(source_path,max_bytes=max_bytes,max_chars=max_chars,)+ if source.suffix.lower() == ".bib":+ from deeptutor.utils.bibtex_converter import bibtex_to_markdown++ text = bibtex_to_markdown(text, source.stem)Path(output_path).write_text(text, encoding="utf-8")diff --git a/deeptutor/tools/builtin/__init__.py b/deeptutor/tools/builtin/__init__.pyindex e0b9b6afd..1b879d991 100644--- a/deeptutor/tools/builtin/__init__.py+++ b/deeptutor/tools/builtin/__init__.py@@ -379,6 +379,129 @@ class PaperSearchToolWrapper(_PromptHintsMixin, BaseTool):)+class ZoteroSearchToolWrapper(_PromptHintsMixin, BaseTool):+ """Search the user-supplied Zotero library through the public Web API."""++ _ERROR_MESSAGES = {+ "invalid_api_key": "The Zotero API key is invalid or cannot access this private library.",+ "library_not_found": "No Zotero library was found for that user ID.",+ "rate_limited": "Zotero rate-limited the search. Please try again later.",+ "network_unavailable": "Zotero is temporarily unavailable. Check the network and try again.",+ "invalid_response": "Zotero returned an unexpected response.",+ }++ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="zotero_search",+ description=(+ "Search a Zotero user library by title, creator, or year. Requires the "+ "numeric Zotero user ID; an API key is needed only for private libraries."+ ),+ parameters=[+ ToolParameter(name="query", type="string", description="Search query."),+ ToolParameter(+ name="user_id",+ type="string",+ description="Numeric Zotero user ID from the Zotero account settings page.",+ ),+ ToolParameter(+ name="api_key",+ type="string",+ description="Zotero API key, required only for a private library.",+ required=False,+ default="",+ sensitive=True,+ ),+ ToolParameter(+ name="max_results",+ type="integer",+ description="Maximum references to return (1-25).",+ required=False,+ default=5,+ ),+ ],+ )++ async def execute(self, **kwargs: Any) -> ToolResult:+ from deeptutor.tools.zotero_search import ZoteroSearchClient, ZoteroSearchError++ query = str(kwargs.get("query") or "").strip()+ user_id = str(kwargs.get("user_id") or "").strip()+ if not query:+ return ToolResult(content="Error: query is required.", success=False)+ if not user_id:+ return ToolResult(+ content="Error: user_id is required. It is available in Zotero account settings.",+ success=False,+ )++ try:+ items = await ZoteroSearchClient().search(+ query=query,+ user_id=user_id,+ api_key=str(kwargs.get("api_key") or ""),+ max_results=kwargs.get("max_results", 5),+ )+ except ZoteroSearchError as exc:+ message = self._ERROR_MESSAGES.get(+ exc.code, "Zotero search failed. Check the user ID and try again."+ )+ return ToolResult(+ content=message,+ sources=[],+ metadata={+ "provider": "zotero",+ "items": [],+ "error": exc.code,+ "status_code": exc.status_code,+ },+ success=False,+ )+ except ValueError:+ return ToolResult(+ content="Error: Zotero user_id and max_results are invalid.",+ success=False,+ metadata={"provider": "zotero", "items": []},+ )++ if not items:+ return ToolResult(+ content="No Zotero references matched this query.",+ sources=[],+ metadata={"provider": "zotero", "items": []},+ )++ lines: list[str] = []+ for item in items:+ year = item.get("year") or "undated"+ lines.append(f"**{item['title']}** ({year})")+ if item.get("authors"):+ lines.append(f"Authors: {', '.join(item['authors'])}")+ if item.get("doi"):+ lines.append(f"DOI: {item['doi']}")+ if item.get("url"):+ lines.append(f"URL: {item['url']}")+ if item.get("abstract"):+ lines.append(f"Abstract: {item['abstract'][:400]}")+ lines.append("")++ return ToolResult(+ content="\n".join(lines),+ sources=[+ {+ "type": "reference",+ "provider": "zotero",+ "title": item.get("title", ""),+ "url": item.get("zotero_url") or item.get("url", ""),+ "doi": item.get("doi", ""),+ "zotero_key": item.get("zotero_key", ""),+ }+ for item in items+ ],+ metadata={"provider": "zotero", "items": items},+ )++class GeoGebraAnalysisTool(_PromptHintsMixin, BaseTool):"""Analyze a math-problem image and generate GeoGebra visualization commands."""@@ -1549,6 +1672,7 @@ USER_TOGGLEABLE_TOOL_NAMES: tuple[str, ...] = ("brainstorm","web_search","paper_search",+ "zotero_search","reason","geogebra_analysis","imagegen",@@ -1634,6 +1758,7 @@ __all__ = ["ListNotebookTool","PaperSearchToolWrapper","QuestionBankTool",+ "ZoteroSearchToolWrapper","PartnerMemorizeTool","PartnerReadTool","PartnerSearchTool",diff --git a/deeptutor/tools/builtin_specs.py b/deeptutor/tools/builtin_specs.pyindex cd458504f..bb40be451 100644--- a/deeptutor/tools/builtin_specs.py+++ b/deeptutor/tools/builtin_specs.py@@ -53,6 +53,7 @@ BUILTIN_TOOL_SPECS: tuple[BuiltinToolSpec, ...] = (("web_search", "WebSearchTool"),("reason", "ReasonTool"),("paper_search", "PaperSearchToolWrapper"),+ ("zotero_search", "ZoteroSearchToolWrapper"),("read_source", "ReadSourceTool"),("read_memory", "ReadMemoryTool"),("write_memory", "WriteMemoryTool"),diff --git a/deeptutor/tools/prompting/hints/en/zotero_search.yaml b/deeptutor/tools/prompting/hints/en/zotero_search.yamlnew file mode 100644index 000000000..b748ef7c9--- /dev/null+++ b/deeptutor/tools/prompting/hints/en/zotero_search.yaml@@ -0,0 +1,6 @@+short_description: "Search a Zotero library for references already saved by the user."+when_to_use: "Use when the user asks for an item from their Zotero library or asks whether a saved reference exists. Skip for public web or arXiv searches."+input_format: "`query` plus the numeric Zotero `user_id`. Include `api_key` only when the user supplies one for a private library."+guideline: "Do not invent a user_id or API key. If either is missing, ask for the user_id first; mention that the ID is in Zotero account settings."+note: "Read-only Zotero Web API v3 lookup; returns at most 25 references."+phase: "expansion"diff --git a/deeptutor/tools/prompting/hints/zh/zotero_search.yaml b/deeptutor/tools/prompting/hints/zh/zotero_search.yamlnew file mode 100644index 000000000..4f859ac8a--- /dev/null+++ b/deeptutor/tools/prompting/hints/zh/zotero_search.yaml@@ -0,0 +1,6 @@+short_description: "搜索用户 Zotero 文献库中已保存的文献。"+when_to_use: "用户要查找自己 Zotero 库中的文献或确认某条文献是否已保存时使用;公共网页搜索或 arXiv 检索不要用。"+input_format: "提供 `query` 和数字 Zotero `user_id`;仅当用户为私有库提供 `api_key` 时才传入。"+guideline: "不要编造 user_id 或 API key。缺少 user_id 时先询问;可提示该 ID 位于 Zotero 账户设置页。"+note: "只读调用 Zotero Web API v3,最多返回 25 条文献。"+phase: "expansion"diff --git a/deeptutor/tools/zotero_search.py b/deeptutor/tools/zotero_search.pynew file mode 100644index 000000000..6b1b61539--- /dev/null+++ b/deeptutor/tools/zotero_search.py@@ -0,0 +1,136 @@+"""Zotero Web API v3 lookup for a user's public or authorized library."""++from __future__ import annotations++from collections.abc import Callable+from contextlib import AbstractAsyncContextManager+import logging+import re+from typing import Any++import httpx++logger = logging.getLogger(__name__)++ZOTERO_API_BASE = "https://api.zotero.org"+DEFAULT_LIMIT = 5+MAX_LIMIT = 25+REQUEST_TIMEOUT_S = httpx.Timeout(15.0, connect=5.0)+_LIBRARY_ID_RE = re.compile(r"^[A-Za-z0-9_-]+$")++ClientFactory = Callable[[], AbstractAsyncContextManager[httpx.AsyncClient]]+++class ZoteroSearchError(Exception):+ """A normalized failure that can be presented without exposing secrets."""++ def __init__(self, code: str, status_code: int | None = None) -> None:+ super().__init__(code)+ self.code = code+ self.status_code = status_code+++class ZoteroSearchClient:+ """Query top-level Zotero items and return normalized reference metadata."""++ def __init__(self, client_factory: ClientFactory | None = None) -> None:+ self._client_factory = client_factory or (+ lambda: httpx.AsyncClient(+ timeout=REQUEST_TIMEOUT_S,+ follow_redirects=True,+ )+ )++ async def search(+ self,+ *,+ query: str,+ user_id: str,+ api_key: str = "",+ max_results: int = DEFAULT_LIMIT,+ ) -> list[dict[str, Any]]:+ query = str(query or "").strip()+ user_id = str(user_id or "").strip()+ if not query:+ raise ValueError("Zotero query must be a non-empty string.")+ if not _LIBRARY_ID_RE.fullmatch(user_id):+ raise ValueError("Zotero user ID must be a non-empty URL-safe identifier.")++ try:+ limit = min(max(int(max_results), 1), MAX_LIMIT)+ except (TypeError, ValueError) as exc:+ raise ValueError("Zotero max_results must be an integer.") from exc++ headers = {"Zotero-API-Version": "3"}+ if api_key:+ headers["Authorization"] = f"Bearer {api_key}"+ params = {+ "format": "json",+ "itemType": "-attachment",+ "limit": limit,+ "q": query,+ "qmode": "titleCreatorYear",+ }+ url = f"{ZOTERO_API_BASE}/users/{user_id}/items/top"++ try:+ async with self._client_factory() as client:+ response = await client.get(url, headers=headers, params=params)+ response.raise_for_status()+ payload = response.json()+ except httpx.HTTPStatusError as exc:+ status = exc.response.status_code+ if status in {401, 403}:+ raise ZoteroSearchError("invalid_api_key", status) from exc+ if status == 404:+ raise ZoteroSearchError("library_not_found", status) from exc+ if status == 429:+ raise ZoteroSearchError("rate_limited", status) from exc+ raise ZoteroSearchError("request_failed", status) from exc+ except (httpx.TimeoutException, httpx.HTTPError) as exc:+ logger.info("Zotero search request failed: %s", exc.__class__.__name__)+ raise ZoteroSearchError("network_unavailable") from exc+ except ValueError as exc:+ raise ZoteroSearchError("invalid_response") from exc++ if not isinstance(payload, list):+ raise ZoteroSearchError("invalid_response")+ return [+ self._normalize(item)+ for item in payload+ if isinstance(item, dict) and isinstance(item.get("data"), dict)+ ]++ @staticmethod+ def _normalize(item: dict[str, Any]) -> dict[str, Any]:+ data = item["data"]+ authors: list[str] = []+ for creator in data.get("creators") or []:+ if not isinstance(creator, dict):+ continue+ name = str(creator.get("name") or "").strip()+ if not name:+ first = str(creator.get("firstName") or "").strip()+ last = str(creator.get("lastName") or "").strip()+ name = f"{first} {last}".strip()+ if name:+ authors.append(name)++ date = str(data.get("date") or "").strip()+ year_match = re.match(r"\d{4}", date)+ links = item.get("links") if isinstance(item.get("links"), dict) else {}+ alternate = links.get("alternate") if isinstance(links.get("alternate"), dict) else {}+ return {+ "title": str(data.get("title") or "Untitled").strip() or "Untitled",+ "item_type": str(data.get("itemType") or "").strip(),+ "authors": authors,+ "year": year_match.group(0) if year_match else date,+ "doi": str(data.get("DOI") or "").strip(),+ "url": str(data.get("url") or "").strip(),+ "abstract": str(data.get("abstractNote") or "").strip(),+ "zotero_key": str(data.get("key") or "").strip(),+ "zotero_url": str(alternate.get("href") or "").strip(),+ }+++__all__ = ["ClientFactory", "ZoteroSearchClient", "ZoteroSearchError"]diff --git a/deeptutor/utils/bibtex_converter.py b/deeptutor/utils/bibtex_converter.pynew file mode 100644index 000000000..12cf69d9f--- /dev/null+++ b/deeptutor/utils/bibtex_converter.py@@ -0,0 +1,284 @@+"""Convert BibTeX source into readable Markdown for retrieval."""++from __future__ import annotations++from dataclasses import dataclass+import re++_ENTRY_START_RE = re.compile(r"@([A-Za-z][A-Za-z0-9_+.-]*)\s*([({])")+_IDENTIFIER_RE = re.compile(r"[A-Za-z][A-Za-z0-9_.+:-]*")+_WHITESPACE_RE = re.compile(r"\s+")++_DELIMITERS = {"{": "}", "(": ")"}+_METADATA_ENTRY_TYPES = {"comment", "string", "preamble"}+_DISPLAY_FIELDS = (+ "author",+ "year",+ "journal",+ "booktitle",+ "publisher",+ "doi",+ "url",+ "abstract",+ "keywords",+ "note",+)+_TYPE_LABELS = {+ "article": "Journal Article",+ "book": "Book",+ "booklet": "Booklet",+ "conference": "Conference Paper",+ "inbook": "Book Chapter",+ "incollection": "Book Chapter",+ "inproceedings": "Conference Paper",+ "manual": "Manual",+ "mastersthesis": "Master's Thesis",+ "misc": "Other",+ "phdthesis": "PhD Thesis",+ "proceedings": "Proceedings",+ "techreport": "Technical Report",+ "unpublished": "Unpublished",+}+++@dataclass(frozen=True, slots=True)+class _Entry:+ entry_type: str+ key: str+ fields: dict[str, str]+++def _clean_value(value: str) -> str:+ cleaned = value.replace("{", "").replace("}", "")+ return _WHITESPACE_RE.sub(" ", cleaned).strip()+++def _format_authors(value: str) -> str:+ names: list[str] = []+ for raw_name in _clean_value(value).split(" and "):+ name = raw_name.strip()+ if "," in name:+ last, first = (part.strip() for part in name.split(",", 1))+ name = f"{first} {last}".strip()+ if name:+ names.append(name)+ return ", ".join(names)+++def _field_label(field: str) -> str:+ labels = {+ "booktitle": "Book Title",+ "doi": "DOI",+ "author": "Authors",+ "url": "URL",+ }+ return labels.get(field, field.capitalize())+++def _format_entry(entry: _Entry, index: int) -> str:+ entry_type = _TYPE_LABELS.get(+ entry.entry_type, entry.entry_type.replace("_", " ").title() or "Reference"+ )+ title = entry.fields.get("title") or "Untitled"+ lines = [f"## {index}. {title}", "", f"**Type:** {entry_type}"]+ citation_key = entry.key.replace("`", "'") or "unknown"+ lines.append(f"**Citation key:** `{citation_key}`")++ for field in _DISPLAY_FIELDS:+ value = entry.fields.get(field, "")+ if not value:+ continue+ if field == "author":+ value = _format_authors(value)+ lines.append(f"**{_field_label(field)}:** {value}")+ lines.append("")+ return "\n".join(lines)+++def _skip_whitespace(text: str, index: int) -> int:+ while index < len(text) and text[index].isspace():+ index += 1+ return index+++def _read_braced(text: str, index: int) -> tuple[str, int]:+ depth = 1+ start = index + 1+ index += 1+ escaped = False+ while index < len(text):+ char = text[index]+ if escaped:+ escaped = False+ elif char == "\\":+ escaped = True+ elif char == "{":+ depth += 1+ elif char == "}":+ depth -= 1+ if depth == 0:+ return text[start:index], index + 1+ index += 1+ raise ValueError("unterminated braced BibTeX value")+++def _read_quoted(text: str, index: int) -> tuple[str, int]:+ start = index + 1+ index += 1+ escaped = False+ while index < len(text):+ char = text[index]+ if escaped:+ escaped = False+ elif char == "\\":+ escaped = True+ elif char == '"':+ return text[start:index], index + 1+ index += 1+ raise ValueError("unterminated quoted BibTeX value")+++def _read_fields(body: str) -> dict[str, str]:+ fields: dict[str, str] = {}+ index = 0+ while index < len(body):+ index = _skip_whitespace(body, index)+ if index >= len(body):+ break+ match = _IDENTIFIER_RE.match(body, index)+ if match is None:+ break+ name = match.group(0).lower()+ index = _skip_whitespace(body, match.end())+ if index >= len(body) or body[index] != "=":+ break+ index = _skip_whitespace(body, index + 1)++ parts: list[str] = []+ while index < len(body):+ char = body[index]+ if char == "{":+ value, index = _read_braced(body, index)+ elif char == '"':+ value, index = _read_quoted(body, index)+ else:+ end = index+ while end < len(body) and body[end] not in {"#", ",", "}", ")"}:+ if body[end].isspace():+ break+ end += 1+ if end == index:+ raise ValueError("empty BibTeX value")+ value = body[index:end]+ index = end+ parts.append(value.strip())+ index = _skip_whitespace(body, index)+ if index < len(body) and body[index] == "#":+ index = _skip_whitespace(body, index + 1)+ continue+ break++ fields[name] = _clean_value("".join(parts))+ index = _skip_whitespace(body, index)+ if index < len(body) and body[index] == ",":+ index += 1+ elif index < len(body):+ break+ return fields+++def _scan_entry(text: str, match: re.Match[str]) -> tuple[_Entry | None, int] | None:+ entry_type = match.group(1).lower()+ opener = match.group(2)+ closer = _DELIMITERS[opener]+ index = match.end()+ brace_depth = 1 if opener == "{" else 0+ paren_depth = 1 if opener == "(" else 0+ quoted = False+ escaped = False++ while index < len(text):+ char = text[index]+ if quoted:+ if escaped:+ escaped = False+ elif char == "\\":+ escaped = True+ elif char == '"':+ quoted = False+ index += 1+ continue+ if char == '"':+ quoted = True+ elif char == "{":+ brace_depth += 1+ elif char == "}":+ brace_depth -= 1+ elif char == "(":+ paren_depth += 1+ elif char == ")":+ paren_depth -= 1++ if opener == "{" and brace_depth == 0:+ body_end = index+ return _make_entry(entry_type, text, match.end(), body_end), index + 1+ if opener == "(" and paren_depth == 0 and brace_depth <= 0:+ body_end = index+ return _make_entry(entry_type, text, match.end(), body_end), index + 1+ if brace_depth < 0 or paren_depth < 0:+ return None+ index += 1+ return None+++def _make_entry(entry_type: str, text: str, start: int, end: int) -> _Entry | None:+ body = text[start:end]+ separator = body.find(",")+ if separator < 0:+ return None+ key = body[:separator].strip()+ try:+ fields = _read_fields(body[separator + 1 :])+ except ValueError:+ return None+ return _Entry(entry_type=entry_type, key=key, fields=fields)+++def _parse_entries(text: str) -> list[_Entry]:+ entries: list[_Entry] = []+ index = 0+ while index < len(text):+ match = _ENTRY_START_RE.search(text, index)+ if match is None:+ break+ if match.group(1).lower() in _METADATA_ENTRY_TYPES:+ scanned = _scan_entry(text, match)+ index = scanned[1] if scanned is not None else match.start() + 1+ continue+ scanned = _scan_entry(text, match)+ if scanned is None:+ index = match.start() + 1+ continue+ entry, index = scanned+ if entry is not None:+ entries.append(entry)+ return entries+++def bibtex_to_markdown(text: str, source_name: str = "bibliography") -> str:+ """Return structured Markdown, or the input when no BibTeX entry exists."""+ entries = _parse_entries(text or "")+ if not entries:+ return text or ""++ parts = [+ f"# Bibliography: {source_name}",+ "",+ f"Total entries: {len(entries)}",+ "",+ ]+ parts.extend(_format_entry(entry, index) for index, entry in enumerate(entries, 1))+ return "\n".join(parts)+++__all__ = ["bibtex_to_markdown"]diff --git a/tests/api/test_tools_router.py b/tests/api/test_tools_router.pyindex 33111b44c..581dca6cc 100644--- a/tests/api/test_tools_router.py+++ b/tests/api/test_tools_router.py@@ -46,6 +46,7 @@ async def test_list_builtin_tools_marks_toggleable_set("brainstorm","web_search","paper_search",+ "zotero_search","reason","geogebra_analysis","imagegen",diff --git a/tests/services/parsing/test_engines.py b/tests/services/parsing/test_engines.pyindex 56578d7df..0f45a9a3a 100644--- a/tests/services/parsing/test_engines.py+++ b/tests/services/parsing/test_engines.py@@ -78,6 +78,30 @@ def test_text_only_parser_extracts_docx_text(tmp_path) -> None:assert (workdir / "lesson.md").read_text(encoding="utf-8") == "Hello DeepTutor"+def test_text_only_parser_converts_bibtex_to_structured_markdown(tmp_path) -> None:+ parser = factory.get_parser("text_only")+ source = tmp_path / "references.bib"+ source.write_text(+ "@article{sample2020,\n"+ " author = {Doe, Jane},\n"+ " title = {Readable References},\n"+ " year = {2020},\n"+ " abstract = {A clean summary.}\n"+ "}\n",+ encoding="utf-8",+ )+ workdir = tmp_path / "parsed"+ workdir.mkdir()++ parser.parse(source, workdir, config={})++ markdown = (workdir / "references.md").read_text(encoding="utf-8")+ assert "## 1. Readable References" in markdown+ assert "**Authors:** Jane Doe" in markdown+ assert "A clean summary." in markdown+ assert "@article" not in markdown++def test_mineru_signature_distinguishes_local_and_cloud() -> None:parser = factory.get_parser("mineru")from deeptutor.services.parsing.engines.mineru.config import MinerUConfigdiff --git a/tests/services/rag/test_file_routing.py b/tests/services/rag/test_file_routing.pyindex 79653e9ca..c9a75dfb8 100644--- a/tests/services/rag/test_file_routing.py+++ b/tests/services/rag/test_file_routing.py@@ -22,6 +22,8 @@ class TestExtensionClassification:("notes.md", DocumentType.TEXT),("readme.MARKDOWN", DocumentType.TEXT),("data.json", DocumentType.TEXT),+ ("references.bib", DocumentType.TEXT),+ ("REFERENCES.BIB", DocumentType.TEXT),("script.py", DocumentType.TEXT),("config.yaml", DocumentType.TEXT),("paper.docx", DocumentType.DOCX),diff --git a/tests/tools/test_zotero_search.py b/tests/tools/test_zotero_search.pynew file mode 100644index 000000000..f0b4cb34d--- /dev/null+++ b/tests/tools/test_zotero_search.py@@ -0,0 +1,195 @@+from __future__ import annotations++from typing import Any++import httpx+import pytest++from deeptutor.tools import zotero_search as zotero_module+from deeptutor.tools.builtin import (+ BUILTIN_TOOL_NAMES,+ USER_TOGGLEABLE_TOOL_NAMES,+ ZoteroSearchToolWrapper,+)+from deeptutor.tools.zotero_search import ZoteroSearchClient, ZoteroSearchError+++class FakeResponse:+ def __init__(self, payload: Any, status_code: int = 200) -> None:+ self.payload = payload+ self.status_code = status_code++ def raise_for_status(self) -> None:+ if self.status_code >= 400:+ raise httpx.HTTPStatusError(+ f"HTTP {self.status_code}",+ request=httpx.Request("GET", "https://api.zotero.org"),+ response=httpx.Response(self.status_code),+ )++ def json(self) -> Any:+ return self.payload+++class FakeClient:+ def __init__(self, response: FakeResponse) -> None:+ self.response = response++ async def __aenter__(self) -> "FakeClient":+ return self++ async def __aexit__(self, *args: object) -> None:+ return None++ async def get(self, url: str, *, headers: dict, params: dict) -> FakeResponse:+ self.url = url+ self.headers = headers+ self.params = params+ return self.response+++def _item(title: str = "Attention Is All You Need") -> dict[str, Any]:+ return {+ "key": "OUTER1",+ "links": {"alternate": {"href": "https://www.zotero.org/users/123/items/OUTER1"}},+ "data": {+ "key": "ABCD1234",+ "itemType": "journalArticle",+ "title": title,+ "creators": [{"firstName": "Ashish", "lastName": "Vaswani"}],+ "date": "2017-06-12",+ "DOI": "10.5555/example",+ "url": "https://example.com/paper",+ "abstractNote": "A compact abstract.",+ },+ }+++async def test_zotero_client_requests_public_user_library() -> None:+ client = FakeClient(FakeResponse([_item()]))++ items = await ZoteroSearchClient(lambda: client).search(+ query="attention",+ user_id="12345",+ )++ assert client.url == "https://api.zotero.org/users/12345/items/top"+ assert "Authorization" not in client.headers+ assert client.headers["Zotero-API-Version"] == "3"+ assert client.params["q"] == "attention"+ assert client.params["qmode"] == "titleCreatorYear"+ assert items[0]["title"] == "Attention Is All You Need"+ assert items[0]["authors"] == ["Ashish Vaswani"]+ assert items[0]["year"] == "2017"+ assert items[0]["zotero_key"] == "ABCD1234"+++async def test_zotero_client_maps_private_library_auth_error() -> None:+ client = FakeClient(FakeResponse([], status_code=403))+ search = ZoteroSearchClient(lambda: client)++ with pytest.raises(ZoteroSearchError, match="invalid_api_key") as exc_info:+ await search.search(query="attention", user_id="12345", api_key="secret")++ assert exc_info.value.status_code == 403+ assert client.headers["Authorization"] == "Bearer secret"+++async def test_zotero_tool_formats_items_and_sources(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ captured: dict[str, Any] = {}++ class FakeSearchClient:+ async def search(self, **kwargs: Any) -> list[dict[str, Any]]:+ captured.update(kwargs)+ return [+ {+ "title": "Saved Reference",+ "item_type": "journalArticle",+ "authors": ["Ada Lovelace"],+ "year": "1843",+ "doi": "10.1234/saved",+ "url": "https://example.com",+ "abstract": "Saved abstract.",+ "zotero_key": "ZOT1",+ "zotero_url": "https://www.zotero.org/users/1/items/ZOT1",+ }+ ]++ monkeypatch.setattr(zotero_module, "ZoteroSearchClient", FakeSearchClient)++ result = await ZoteroSearchToolWrapper().execute(+ query="reference",+ user_id="12345",+ api_key="secret",+ )++ expected = {+ "query": "reference",+ "user_id": "12345",+ "api_key": "secret",+ "max_results": 5,+ }+ assert captured == expected+ assert "**Saved Reference** (1843)" in result.content+ assert result.sources[0]["provider"] == "zotero"+ assert result.sources[0]["zotero_key"] == "ZOT1"+++async def test_zotero_tool_reports_missing_and_no_result_paths(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ missing = await ZoteroSearchToolWrapper().execute(query="reference", user_id="")+ assert missing.success is False+ assert "user_id is required" in missing.content++ class FakeSearchClient:+ async def search(self, **kwargs: Any) -> list[dict[str, Any]]:+ return []++ monkeypatch.setattr(zotero_module, "ZoteroSearchClient", FakeSearchClient)+ empty = await ZoteroSearchToolWrapper().execute(query="reference", user_id="12345")+ assert empty.success is True+ assert empty.content == "No Zotero references matched this query."+++async def test_zotero_tool_maps_request_error(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ class FailingSearchClient:+ async def search(self, **kwargs: Any) -> list[dict[str, Any]]:+ raise ZoteroSearchError("request_failed", 500)++ monkeypatch.setattr(zotero_module, "ZoteroSearchClient", FailingSearchClient)++ result = await ZoteroSearchToolWrapper().execute(query="reference", user_id="12345")++ assert result.success is False+ assert result.metadata["error"] == "request_failed"+ assert result.metadata["status_code"] == 500+++def test_zotero_tool_is_registered_and_user_toggleable() -> None:+ definition = ZoteroSearchToolWrapper().get_definition()+ parameters = {parameter.name: parameter for parameter in definition.parameters}++ assert definition.name == "zotero_search"+ assert definition.name in BUILTIN_TOOL_NAMES+ assert parameters["api_key"].sensitive is True+ assert parameters["max_results"].default == 5+ assert "zotero_search" in USER_TOGGLEABLE_TOOL_NAMES++[email protected]("language", ["en", "zh"])+def test_zotero_prompt_hints_are_bilingual(language: str) -> None:+ hints = ZoteroSearchToolWrapper().get_prompt_hints(language=language)++ assert "Zotero" in hints.short_description+ assert hints.guideline+ assert hints.input_formatdiff --git a/tests/utils/test_bibtex_converter.py b/tests/utils/test_bibtex_converter.pynew file mode 100644index 000000000..1068e6a0d--- /dev/null+++ b/tests/utils/test_bibtex_converter.py@@ -0,0 +1,72 @@+from __future__ import annotations++from deeptutor.utils.bibtex_converter import bibtex_to_markdown++SAMPLE_BIBTEX = r"""+@string{venue = {Advances}}++@article{vaswani2017attention,+ author = {Vaswani, Ashish and Shazeer, Noam},+ title = {Attention {Is} All You Need},+ journal = {Advances in Neural Information Processing Systems},+ year = {2017},+ doi = {10.5555/3295222},+ abstract = {The dominant models use recurrent networks.}+}++@inproceedings{devlin2019bert,+ author = {Devlin, Jacob and Chang, Ming-Wei},+ title = {"BERT": Pre-training of Deep Bidirectional Transformers},+ booktitle = {NAACL},+ year = 2019+}+"""+++def test_bibtex_to_markdown_extracts_structured_entries() -> None:+ result = bibtex_to_markdown(SAMPLE_BIBTEX, "references")++ assert "Total entries: 2" in result+ assert "## 1. Attention Is All You Need" in result+ assert "**Authors:** Ashish Vaswani, Noam Shazeer" in result+ assert "**Type:** Journal Article" in result+ assert "10.5555/3295222" in result+ assert "The dominant models use recurrent networks." in result+ assert "@string" not in result+ assert '## 2. "BERT": Pre-training' in result+ assert "**Type:** Conference Paper" in result+++def test_bibtex_to_markdown_keeps_value_with_nested_braces_intact() -> None:+ text = r"""+ @article{nested,+ title = {A {Nested {Title}} Here},+ year = {2020}+ }+ """++ result = bibtex_to_markdown(text)++ assert "A Nested Title Here" in result+ assert "2020" in result+++def test_bibtex_to_markdown_skips_entry_with_unterminated_value() -> None:+ text = """+ @article{valid,+ title = {Valid Entry},+ year = {2020}+ }++ @article{broken,+ title = {Unterminated+ """++ result = bibtex_to_markdown(text)++ assert "Valid Entry" in result+ assert "broken" not in result+++def test_bibtex_to_markdown_passes_non_bibtex_through() -> None:+ assert bibtex_to_markdown("not a bibliography") == "not a bibliography"