|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import re |
| 5 | +import time |
| 6 | +from typing import Any, Literal |
| 7 | + |
| 8 | +from sentience.actions import click_async, press_async, type_text_async |
| 9 | +from sentience.integrations.models import AssertionResult, BrowserState, ElementSummary |
| 10 | +from sentience.models import ReadResult, SnapshotOptions, TextRectSearchResult |
| 11 | +from sentience.read import read_async |
| 12 | +from sentience.snapshot import snapshot_async |
| 13 | +from sentience.text_search import find_text_rect_async |
| 14 | + |
| 15 | +from .deps import SentiencePydanticDeps |
| 16 | + |
| 17 | + |
| 18 | +def register_sentience_tools(agent: Any) -> dict[str, Any]: |
| 19 | + """ |
| 20 | + Register Sentience tools on a PydanticAI agent. |
| 21 | +
|
| 22 | + This function is intentionally lightweight and avoids importing `pydantic_ai` |
| 23 | + at module import time. It expects `agent` to provide a `.tool` decorator |
| 24 | + compatible with PydanticAI's `Agent.tool`. |
| 25 | +
|
| 26 | + Returns: |
| 27 | + Mapping of tool name -> underlying coroutine function (useful for tests). |
| 28 | + """ |
| 29 | + |
| 30 | + @agent.tool |
| 31 | + async def snapshot_state( |
| 32 | + ctx: Any, |
| 33 | + limit: int = 50, |
| 34 | + include_screenshot: bool = False, |
| 35 | + ) -> BrowserState: |
| 36 | + """ |
| 37 | + Take a bounded snapshot of the current page and return a small typed summary. |
| 38 | + """ |
| 39 | + deps: SentiencePydanticDeps = ctx.deps |
| 40 | + opts = SnapshotOptions(limit=limit, screenshot=include_screenshot) |
| 41 | + snap = await snapshot_async(deps.browser, opts) |
| 42 | + elements = [ |
| 43 | + ElementSummary( |
| 44 | + id=e.id, |
| 45 | + role=e.role, |
| 46 | + text=e.text, |
| 47 | + importance=e.importance, |
| 48 | + bbox=e.bbox, |
| 49 | + ) |
| 50 | + for e in snap.elements |
| 51 | + ] |
| 52 | + return BrowserState(url=snap.url, elements=elements) |
| 53 | + |
| 54 | + @agent.tool |
| 55 | + async def read_page( |
| 56 | + ctx: Any, |
| 57 | + format: Literal["raw", "text", "markdown"] = "text", |
| 58 | + enhance_markdown: bool = True, |
| 59 | + ) -> ReadResult: |
| 60 | + """ |
| 61 | + Read page content as raw HTML, text, or markdown. |
| 62 | + """ |
| 63 | + deps: SentiencePydanticDeps = ctx.deps |
| 64 | + return await read_async(deps.browser, output_format=format, enhance_markdown=enhance_markdown) |
| 65 | + |
| 66 | + @agent.tool |
| 67 | + async def click( |
| 68 | + ctx: Any, |
| 69 | + element_id: int, |
| 70 | + ): |
| 71 | + """ |
| 72 | + Click an element by Sentience element id (from snapshot). |
| 73 | + """ |
| 74 | + deps: SentiencePydanticDeps = ctx.deps |
| 75 | + return await click_async(deps.browser, element_id) |
| 76 | + |
| 77 | + @agent.tool |
| 78 | + async def type_text( |
| 79 | + ctx: Any, |
| 80 | + element_id: int, |
| 81 | + text: str, |
| 82 | + ): |
| 83 | + """ |
| 84 | + Type text into an element by Sentience element id (from snapshot). |
| 85 | + """ |
| 86 | + deps: SentiencePydanticDeps = ctx.deps |
| 87 | + return await type_text_async(deps.browser, element_id, text) |
| 88 | + |
| 89 | + @agent.tool |
| 90 | + async def press_key( |
| 91 | + ctx: Any, |
| 92 | + key: str, |
| 93 | + ): |
| 94 | + """ |
| 95 | + Press a keyboard key (Enter, Escape, Tab, etc.). |
| 96 | + """ |
| 97 | + deps: SentiencePydanticDeps = ctx.deps |
| 98 | + return await press_async(deps.browser, key) |
| 99 | + |
| 100 | + @agent.tool |
| 101 | + async def find_text_rect( |
| 102 | + ctx: Any, |
| 103 | + text: str, |
| 104 | + case_sensitive: bool = False, |
| 105 | + whole_word: bool = False, |
| 106 | + max_results: int = 10, |
| 107 | + ) -> TextRectSearchResult: |
| 108 | + """ |
| 109 | + Find text occurrences and return pixel coordinates. |
| 110 | + """ |
| 111 | + deps: SentiencePydanticDeps = ctx.deps |
| 112 | + return await find_text_rect_async( |
| 113 | + deps.browser, |
| 114 | + text, |
| 115 | + case_sensitive=case_sensitive, |
| 116 | + whole_word=whole_word, |
| 117 | + max_results=max_results, |
| 118 | + ) |
| 119 | + |
| 120 | + @agent.tool |
| 121 | + async def verify_url_matches( |
| 122 | + ctx: Any, |
| 123 | + pattern: str, |
| 124 | + flags: int = 0, |
| 125 | + ) -> AssertionResult: |
| 126 | + """ |
| 127 | + Verify the current page URL matches a regex pattern. |
| 128 | + """ |
| 129 | + deps: SentiencePydanticDeps = ctx.deps |
| 130 | + if not deps.browser.page: |
| 131 | + return AssertionResult(passed=False, reason="Browser not started (page is None)") |
| 132 | + |
| 133 | + url = deps.browser.page.url |
| 134 | + ok = re.search(pattern, url, flags) is not None |
| 135 | + return AssertionResult( |
| 136 | + passed=ok, |
| 137 | + reason="" if ok else f"URL did not match pattern. url={url!r} pattern={pattern!r}", |
| 138 | + details={"url": url, "pattern": pattern}, |
| 139 | + ) |
| 140 | + |
| 141 | + @agent.tool |
| 142 | + async def verify_text_present( |
| 143 | + ctx: Any, |
| 144 | + text: str, |
| 145 | + *, |
| 146 | + format: Literal["text", "markdown", "raw"] = "text", |
| 147 | + case_sensitive: bool = False, |
| 148 | + ) -> AssertionResult: |
| 149 | + """ |
| 150 | + Verify a text substring is present in `read_page()` output. |
| 151 | + """ |
| 152 | + deps: SentiencePydanticDeps = ctx.deps |
| 153 | + result = await read_async(deps.browser, output_format=format, enhance_markdown=True) |
| 154 | + if result.status != "success": |
| 155 | + return AssertionResult(passed=False, reason=f"read failed: {result.error}", details={}) |
| 156 | + |
| 157 | + haystack = result.content if case_sensitive else result.content.lower() |
| 158 | + needle = text if case_sensitive else text.lower() |
| 159 | + ok = needle in haystack |
| 160 | + return AssertionResult( |
| 161 | + passed=ok, |
| 162 | + reason="" if ok else f"Text not present: {text!r}", |
| 163 | + details={"format": format, "query": text, "length": result.length}, |
| 164 | + ) |
| 165 | + |
| 166 | + @agent.tool |
| 167 | + async def assert_eventually_url_matches( |
| 168 | + ctx: Any, |
| 169 | + pattern: str, |
| 170 | + *, |
| 171 | + timeout_s: float = 10.0, |
| 172 | + poll_s: float = 0.25, |
| 173 | + flags: int = 0, |
| 174 | + ) -> AssertionResult: |
| 175 | + """ |
| 176 | + Retry until the page URL matches `pattern` or timeout is reached. |
| 177 | + """ |
| 178 | + deadline = time.monotonic() + timeout_s |
| 179 | + last = None |
| 180 | + while time.monotonic() <= deadline: |
| 181 | + last = await verify_url_matches(ctx, pattern, flags) |
| 182 | + if last.passed: |
| 183 | + return last |
| 184 | + await asyncio.sleep(poll_s) |
| 185 | + return last or AssertionResult(passed=False, reason="No attempts executed", details={}) |
| 186 | + |
| 187 | + return { |
| 188 | + "snapshot_state": snapshot_state, |
| 189 | + "read_page": read_page, |
| 190 | + "click": click, |
| 191 | + "type_text": type_text, |
| 192 | + "press_key": press_key, |
| 193 | + "find_text_rect": find_text_rect, |
| 194 | + "verify_url_matches": verify_url_matches, |
| 195 | + "verify_text_present": verify_text_present, |
| 196 | + "assert_eventually_url_matches": assert_eventually_url_matches, |
| 197 | + } |
| 198 | + |
0 commit comments