From b495dde6810882efc8481ebebd22ff26a6afb902 Mon Sep 17 00:00:00 2001 From: tanaka takashi Date: Wed, 26 Aug 2026 19:23:40 +0900 Subject: fix(tools): PDFの会話間継続をトークン単独で再開可能にする MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 長いPDFを複数会話に分けて取得する際、モデルがurl_or_pathを省略したり、過去の添付IDや古い継続トークンを組み合わせたりして、先頭または以前のページへ戻る問題を改善する。PDFカーソル自体は正しく進んでいたため、汎用LLM層やセッション形式を変更せず、pdf_to_textの入出力契約だけを明確化する。 - continue_fromを自己完結した再開情報として扱い、PDFソース、ページ番号、ページ内文字位置をトークンから復元 - 継続時はurl_or_pathを省略可能にし、競合する値が渡されてもトークン内のソースを優先 - Ollama生成スキーマでもurl_or_pathを任意にして、continue_from単独のツール呼び出しを許可 - 未完了結果へ最新トークン、旧トークンの置換、単独再開、上限時の保持を表すPDF専用メタデータを追加 - 継続メタデータを固定キーと真偽値で表現し、会話言語に依存しない形式へ統一 - 無効トークン時は先頭再試行を禁止し、直前の最新トークンを再利用する機械可読情報を返却 - メタデータをpage-info側へ配置して本文連結を汚さず、結果全体を6000文字以内に再調整 - llm.py、チャット処理、セッションJSON、scrape_url、search_and_fetch、MCPツールは変更しない 検証: - pytest: 132 passed - ruff check: passed - mypy src: passed - 1463891.1463912.pdf: 12ページ、52577文字をcontinue_from単独の10回で完全再構成 - 指定PDFの最大ツール結果長はメタデータ込み5992文字 --- src/ollama_web/tools/pdf.py | 80 ++++++++++++++++++++++++++++++++++----------- 1 file changed, 61 insertions(+), 19 deletions(-) (limited to 'src/ollama_web') diff --git a/src/ollama_web/tools/pdf.py b/src/ollama_web/tools/pdf.py index 4faf8ac..657edf9 100644 --- a/src/ollama_web/tools/pdf.py +++ b/src/ollama_web/tools/pdf.py @@ -12,6 +12,7 @@ from .helper.pagination import ( PageSizeError, format_page_to_limit, make_token, + parse_paged_result, parse_token, ) from .helper.pdf import extract_pdf_page @@ -23,6 +24,16 @@ logger = logging.getLogger("ollama_web.tools.pdf") AttachmentLoader = Callable[[str], bytes | None] +_RESUME_RULE = ( + "\nresume_tool: pdf_to_text" + "\nresume_page_index: {page_index}" + "\nresume_page_char_offset: {page_char_offset}" + "\nnext_token_is_latest: true" + "\nsupersedes_previous_tokens: true" + "\nresume_with_continue_from_only: true" + "\npreserve_next_token_on_tool_limit: true" +) + def _cursor_value(payload: dict[str, Any], key: str, fallback: int = 0) -> int: raw = payload.get(key, fallback) @@ -38,26 +49,32 @@ def _cursor_value(payload: dict[str, Any], key: str, fallback: int = 0) -> int: def _pdf_to_text( - url_or_path: str, + url_or_path: str | None, max_chars: int | None, continue_from: str | None, attachment_loader: AttachmentLoader | None, ) -> str: - if not url_or_path or not url_or_path.strip(): - return "Invalid PDF source." - - src = url_or_path.strip() + src = (url_or_path or "").strip() page_index = 0 page_char_offset = 0 if continue_from: try: payload = parse_token(continue_from, _TOOL_NAME) - src = str(payload.get("url") or src) + # A continuation token is self-contained. Its source is + # authoritative so a later conversation cannot accidentally pair + # the cursor with a stale attachment ID or URL. + src = str(payload["url"]) # Version 1 used offset as the PDF page index. page_index = _cursor_value(payload, "page_index", int(payload["offset"])) page_char_offset = _cursor_value(payload, "page_char_offset") except ValueError as exc: - return f"Invalid continuation token: {exc}" + return ( + f"Invalid continuation token: {exc}\n" + "restart_from_beginning: false\n" + "required_action: reuse_latest_next_token" + ) + elif not src: + return "Invalid PDF source." if src.startswith(_ATTACHMENT_PREFIX): file_id = src.removeprefix(_ATTACHMENT_PREFIX) @@ -98,12 +115,33 @@ def _pdf_to_text( ) try: - result = format_page_to_limit( - page_factory, - token_factory, - requested_chars=requested, - result_limit=settings.max_tool_result_chars, - ) + result_limit = settings.max_tool_result_chars + render_limit = result_limit + result = "" + for _ in range(4): + result = format_page_to_limit( + page_factory, + token_factory, + requested_chars=requested, + result_limit=render_limit, + ) + _, has_more, next_token = parse_paged_result(result) + if not has_more or next_token is None: + break + next_payload = parse_token(next_token, _TOOL_NAME) + resume_metadata = _RESUME_RULE.format( + page_index=_cursor_value(next_payload, "page_index", next_payload["offset"]), + page_char_offset=_cursor_value(next_payload, "page_char_offset"), + ) + overflow = len(result) + len(resume_metadata) - result_limit + if overflow <= 0: + result += resume_metadata + break + render_limit -= overflow + 8 + if render_limit <= 0: + raise PageSizeError("PDF continuation metadata exceeds the result limit.") + else: + raise PageSizeError("PDF continuation metadata could not fit the result limit.") except PageSizeError as exc: return f"PDF pagination failed: {exc}" @@ -119,17 +157,21 @@ def _pdf_to_text( def pdf_to_text( - url_or_path: str, max_chars: int | None = None, continue_from: str | None = None + url_or_path: str | None = None, + max_chars: int | None = None, + continue_from: str | None = None, ) -> str: """Extract a losslessly paged PDF from an HTTP(S) URL. Args: - url_or_path: HTTP(S) PDF URL. In chat, a session attachment URI may also - be supplied by the attachment context. Arbitrary filesystem paths are - never accepted. + url_or_path: HTTP(S) PDF URL for the first call. In chat, a session + attachment URI may also be supplied by the attachment context. + Omit this argument when continue_from is supplied. Arbitrary + filesystem paths are never accepted. max_chars: Requested maximum source characters for this page. The tool may return fewer characters so metadata and its token remain intact. - continue_from: Opaque continuation token from the preceding result. + continue_from: Opaque, self-contained continuation token from the most + recent result for this PDF. It restores both the source and cursor. """ return _pdf_to_text(url_or_path, max_chars, continue_from, None) @@ -138,7 +180,7 @@ def make_session_pdf_tool(attachment_loader: AttachmentLoader) -> Callable[..., """Create a session-scoped ``pdf_to_text`` supporting attachment IDs.""" def session_pdf_to_text( - url_or_path: str, + url_or_path: str | None = None, max_chars: int | None = None, continue_from: str | None = None, ) -> str: -- cgit v1.2.3