-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtool_pool.py
More file actions
1128 lines (960 loc) · 47.6 KB
/
tool_pool.py
File metadata and controls
1128 lines (960 loc) · 47.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Singleton Tool Pool
Provides a shared pool of builtin tools that can be used across
multiple agentic frameworks (LangChain, CrewAI, smolagents, LlamaIndex, Semantic Kernel).
Tools in the pool:
- web_search : DuckDuckGo web search (via duckduckgo-search)
- web_browser : Playwright headless browser navigation
- wikipedia : Wikipedia lookup (via wikipedia)
- arxiv : Academic paper search (via arxiv)
- python_repl : Sandboxed Python code execution (via RestrictedPython)
- requests_get : Simple HTTP GET requests (via requests)
- beautifulsoup_scraper : HTML structure extraction (via beautifulsoup4)
- pdf_reader : PDF text extraction (via pypdf)
- datetime : Current date and time (stdlib)
- json_parser : JSON string parsing and querying (stdlib)
- pubmed : Biomedical paper search (via biopython)
- youtube_transcript : YouTube video transcript retrieval (via youtube-transcript-api)
- sympy : Symbolic math and logic evaluation (via sympy)
- web_interaction : Interactive browser tool for multi-step web interactions (via Playwright)
- keyboard_interaction : Keyboard-driven browser interaction optimized for accessibility-style tasks (via Playwright)
- searxng_search : Metasearch tool that queries multiple engines simultaneously (via requests to a SearXNG instance)
Each framework requests a clone of the tool via get_tool(name, framework).
The pool itself is a singleton — only one instance is ever created.
"""
import os
import copy
import time as _time
from typing import Dict, Optional
# ---------------------------------------------------------------------------
# Base tool definition (framework-agnostic)
# ---------------------------------------------------------------------------
class ToolDefinition:
"""
Framework-agnostic tool definition stored in the pool.
Attributes:
name: Canonical tool name.
description: Human-readable description of what the tool does.
func: Underlying callable that executes the tool logic.
"""
def __init__(self, name: str, description: str, func):
self.name = name
self.description = description
self._raw_func = func
self.func = self._make_instrumented(func)
def _make_instrumented(self, func):
"""Wrap func to log every invocation to ToolPool.invocation_log."""
tool_name = self.name
def _instrumented(query):
t0 = _time.perf_counter()
try:
result = func(query)
duration_ms = round((_time.perf_counter() - t0) * 1000, 2)
success = True
error = None
except Exception as e:
duration_ms = round((_time.perf_counter() - t0) * 1000, 2)
result = f"Tool error: {str(e)}"
success = False
error = str(e)
ToolPool.invocation_log.append({
"tool": tool_name,
"input": str(query)[:300],
"output": str(result)[:300],
"duration_ms": duration_ms,
"success": success,
"error": error,
})
if os.getenv("DEBUG_TOOL_CALLS", "false").lower() in ("1", "true", "yes", "on"):
summary = f"🔧 Tool call | {tool_name} | success={success} | duration={duration_ms}ms"
if error:
summary += f" | error={error}"
summary += f" | input={str(query)[:120]!r}"
print(summary)
return result
return _instrumented
def __repr__(self):
return f"ToolDefinition(name={self.name!r})"
# ---------------------------------------------------------------------------
# Adapters — wrap a ToolDefinition into the format expected by each framework
# ---------------------------------------------------------------------------
def _to_langchain(tool_def: ToolDefinition):
"""Return a langchain_community Tool wrapping this definition."""
from langchain_community.tools import Tool as LCTool
return LCTool(
name=tool_def.name,
func=tool_def.func,
description=tool_def.description,
)
def _to_crewai(tool_def: ToolDefinition):
"""Return a crewai BaseTool subclass instance wrapping this definition."""
from crewai.tools import BaseTool as CrewBaseTool
from pydantic import BaseModel, Field
class _Input(BaseModel):
query: str = Field(description="Input query or argument for the tool.")
# Dynamically create a named subclass so CrewAI can identify the tool
def _run(self, query: str) -> str:
return tool_def.func(query)
CrewTool = type(
tool_def.name,
(CrewBaseTool,),
{
"__module__": __name__,
"__annotations__": {
"name": str,
"description": str,
"args_schema": type,
},
"name": tool_def.name,
"description": tool_def.description,
"args_schema": _Input,
"_run": _run,
},
)
return CrewTool()
def _to_smolagents(tool_def: ToolDefinition):
"""Return a smolagents Tool instance wrapping this definition."""
from smolagents import Tool as SmolTool
class _SmolWrapper(SmolTool):
name = tool_def.name
description = tool_def.description
inputs = {"query": {"type": "string", "description": "Input query or argument."}}
output_type = "string"
def forward(self, query: str) -> str:
return tool_def.func(query)
return _SmolWrapper()
def _to_llamaindex(tool_def: ToolDefinition):
"""Return a LlamaIndex FunctionTool wrapping this definition."""
from llama_index.core.tools import FunctionTool
return FunctionTool.from_defaults(
fn=tool_def.func,
name=tool_def.name,
description=tool_def.description
)
def _to_semantic_kernel(tool_def: ToolDefinition):
"""Return a Semantic Kernel KernelFunction wrapping this definition.
The function is registered on a throw-away kernel instance so it can be
retrieved as a standalone KernelFunction and added to any kernel via
kernel.add_plugin() by the caller.
"""
import semantic_kernel as sk
from semantic_kernel.functions.kernel_function_decorator import kernel_function
# Dynamically create a plugin class with a single kernel_function method
@kernel_function(name=tool_def.name, description=tool_def.description)
def _sk_func(query: str) -> str:
return tool_def.func(query)
plugin_class = type(tool_def.name, (), {tool_def.name: staticmethod(_sk_func)})
temp_kernel = sk.Kernel()
plugin = temp_kernel.add_plugin(
plugin=plugin_class(),
plugin_name=tool_def.name
)
return plugin[tool_def.name]
_ADAPTERS = {
"langchain": _to_langchain,
"crewai": _to_crewai,
"smolagents": _to_smolagents,
"llamaindex": _to_llamaindex,
"semantic_kernel": _to_semantic_kernel,
}
# ---------------------------------------------------------------------------
# Tool pool — singleton
# ---------------------------------------------------------------------------
class _ToolPool:
"""
Singleton registry of shared builtin tools.
Usage:
from tool_pool import ToolPool
# Get a LangChain-compatible clone of web_search
tool = ToolPool.get_tool("web_search", framework="langchain")
# Get all tools for CrewAI
tools = ToolPool.get_all_tools(framework="crewai")
"""
_instance: Optional["_ToolPool"] = None
_registry: Dict[str, ToolDefinition] = {}
invocation_log: list = [] # shared across all tool calls
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance._build_pool()
return cls._instance
def reset_log(self):
"""Clear the invocation log. Call before each test run."""
_ToolPool.invocation_log.clear()
def get_log(self) -> list:
"""Return a snapshot of the current invocation log."""
return list(_ToolPool.invocation_log)
def get_log_summary(self) -> Dict:
"""
Return aggregated statistics from the current invocation log.
Returns a dict with:
total_calls : total number of tool invocations
successful_calls : number of successful invocations
failed_calls : number of failed invocations
tools_used : list of distinct tool names called
per_tool : dict of per-tool stats (calls, avg_duration_ms, failures)
"""
log = _ToolPool.invocation_log
if not log:
return {
"total_calls": 0,
"successful_calls": 0,
"failed_calls": 0,
"tools_used": [],
"per_tool": {},
}
per_tool: Dict[str, Dict] = {}
for entry in log:
name = entry["tool"]
if name not in per_tool:
per_tool[name] = {"calls": 0, "duration_ms": [], "failures": 0}
per_tool[name]["calls"] += 1
per_tool[name]["duration_ms"].append(entry["duration_ms"])
if not entry["success"]:
per_tool[name]["failures"] += 1
per_tool_summary = {
name: {
"calls": s["calls"],
"avg_duration_ms": round(sum(s["duration_ms"]) / len(s["duration_ms"]), 2),
"failures": s["failures"],
}
for name, s in per_tool.items()
}
return {
"total_calls": len(log),
"successful_calls": sum(1 for e in log if e["success"]),
"failed_calls": sum(1 for e in log if not e["success"]),
"tools_used": sorted(per_tool.keys()),
"per_tool": per_tool_summary,
}
# ------------------------------------------------------------------
# Pool construction
# ------------------------------------------------------------------
def _build_pool(self):
"""Instantiate and register all builtin tools."""
self._registry = {}
self._register_web_search()
self._register_web_browser()
self._register_wikipedia()
self._register_arxiv()
self._register_python_repl()
self._register_requests_get()
self._register_beautifulsoup_scraper()
self._register_pdf_reader()
self._register_datetime()
self._register_json_parser()
self._register_pubmed()
self._register_youtube_transcript()
self._register_sympy()
self._register_web_interaction()
self._register_keyboard_interaction()
self._register_searxng_search()
def _register_web_search(self):
"""DuckDuckGo web search — works natively with LangChain, CrewAI, smolagents."""
from duckduckgo_search import DDGS
def _search(query: str) -> str:
with DDGS() as ddgs:
results = list(ddgs.text(query, max_results=5))
if not results:
return "No results found."
return "\n\n".join(
f"Title: {r.get('title', '')}\nURL: {r.get('href', '')}\nSnippet: {r.get('body', '')}"
for r in results
)
self._registry["web_search"] = ToolDefinition(
name="web_search",
description=(
"Search the web using DuckDuckGo. "
"Input should be a plain-text search query. "
"Returns titles, URLs, and snippets from the top results."
),
func=_search,
)
def _register_web_browser(self):
"""Playwright headless browser — navigate to a URL and return page text."""
def _browse(url: str) -> str:
try:
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.goto(url, timeout=15000)
text = page.inner_text("body")
browser.close()
return text[:4000] # Truncate to avoid token overflow
except Exception as e:
return f"Browser error: {str(e)}"
self._registry["web_browser"] = ToolDefinition(
name="web_browser",
description=(
"Navigate a headless browser to a URL and return the visible page text. "
"Input should be a valid URL string (including https://). "
"Useful for reading web pages that require JavaScript rendering."
),
func=_browse,
)
def _register_wikipedia(self):
"""Wikipedia lookup — well-supported across all frameworks."""
def _wiki(query: str) -> str:
try:
import wikipedia
summary = wikipedia.summary(query, sentences=5, auto_suggest=False)
return summary
except Exception as e:
return f"Wikipedia error: {str(e)}"
self._registry["wikipedia"] = ToolDefinition(
name="wikipedia",
description=(
"Look up a topic on Wikipedia and return a short summary. "
"Input should be the name of a concept, person, place, or event. "
"Useful for factual background information."
),
func=_wiki,
)
def _register_arxiv(self):
"""Arxiv academic paper search — no API key required."""
def _arxiv(query: str) -> str:
try:
import arxiv
search = arxiv.Search(query=query, max_results=5)
results = list(search.results())
if not results:
return "No papers found."
return "\n\n".join(
f"Title: {r.title}\nAuthors: {', '.join(a.name for a in r.authors[:3])}\n"
f"Published: {r.published.strftime('%Y-%m-%d')}\nSummary: {r.summary[:300]}..."
for r in results
)
except Exception as e:
return f"Arxiv error: {str(e)}"
self._registry["arxiv"] = ToolDefinition(
name="arxiv",
description=(
"Search academic papers on arXiv. "
"Input should be a plain-text search query about a research topic. "
"Returns titles, authors, publication dates, and abstracts of the top results."
),
func=_arxiv,
)
def _register_python_repl(self):
"""Sandboxed Python REPL — executes code via RestrictedPython."""
def _python_repl(code: str) -> str:
try:
from RestrictedPython import compile_restricted, safe_globals
from RestrictedPython.Eval import default_guarded_getiter
from RestrictedPython.Guards import safe_builtins, guarded_iter_unpack_sequence
byte_code = compile_restricted(code, "<string>", "exec")
local_vars = {}
restricted_globals = {
**safe_globals,
"__builtins__": safe_builtins,
"_getiter_": default_guarded_getiter,
"_iter_unpack_sequence_": guarded_iter_unpack_sequence,
}
exec(byte_code, restricted_globals, local_vars) # noqa: S102
output = local_vars.get("result", restricted_globals.get("_print_", None))
return str(output) if output is not None else "Code executed successfully with no output."
except Exception as e:
return f"Python REPL error: {str(e)}"
self._registry["python_repl"] = ToolDefinition(
name="python_repl",
description=(
"Execute a snippet of Python code in a sandboxed environment. "
"Input should be valid Python code as a string. "
"Assign the final result to a variable named 'result' to capture output. "
"Useful for calculations, data transformations, and logic evaluation."
),
func=_python_repl,
)
def _register_requests_get(self):
"""Simple HTTP GET — fetches raw content from a URL via requests."""
def _get(url: str) -> str:
try:
import requests
response = requests.get(url, timeout=10)
response.raise_for_status()
# Return plain text truncated to avoid token overflow
return response.text[:4000]
except Exception as e:
return f"HTTP GET error: {str(e)}"
self._registry["requests_get"] = ToolDefinition(
name="requests_get",
description=(
"Perform an HTTP GET request to a URL and return the raw response text. "
"Input should be a valid URL string (including https://). "
"Useful for fetching JSON APIs, plain-text files, or lightweight web pages."
),
func=_get,
)
def _register_beautifulsoup_scraper(self):
"""HTML structure extraction — parses and returns structured content from a URL."""
def _scrape(url: str) -> str:
try:
import requests
from bs4 import BeautifulSoup
response = requests.get(url, timeout=10)
response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")
# Remove script and style elements
for tag in soup(["script", "style", "noscript"]):
tag.decompose()
headings = [f"{tag.name.upper()}: {tag.get_text(strip=True)}"
for tag in soup.find_all(["h1", "h2", "h3", "h4", "h5", "h6"])]
paragraphs = [p.get_text(strip=True) for p in soup.find_all("p") if p.get_text(strip=True)]
output = ""
if headings:
output += "Headings:\n" + "\n".join(headings[:20]) + "\n\n"
if paragraphs:
output += "Content:\n" + "\n".join(paragraphs[:20])
return output[:4000] if output else "No structured content found."
except Exception as e:
return f"BeautifulSoup scraper error: {str(e)}"
self._registry["beautifulsoup_scraper"] = ToolDefinition(
name="beautifulsoup_scraper",
description=(
"Extract structured HTML content (headings and paragraphs) from a URL. "
"Input should be a valid URL string (including https://). "
"Lighter than web_browser — does not execute JavaScript. "
"Useful for HTML structure analysis and accessibility evaluation."
),
func=_scrape,
)
def _register_pdf_reader(self):
"""PDF text extraction — reads text from a PDF at a URL or local file path."""
def _read_pdf(source: str) -> str:
try:
import io
import pypdf
import requests
if source.startswith("http://") or source.startswith("https://"):
response = requests.get(source, timeout=15)
response.raise_for_status()
file = io.BytesIO(response.content)
else:
file = open(source, "rb")
reader = pypdf.PdfReader(file)
text = "\n\n".join(
page.extract_text() or "" for page in reader.pages
)
if hasattr(file, "close"):
file.close()
return text[:4000] if text.strip() else "No text could be extracted from the PDF."
except Exception as e:
return f"PDF reader error: {str(e)}"
self._registry["pdf_reader"] = ToolDefinition(
name="pdf_reader",
description=(
"Extract text content from a PDF file. "
"Input should be a URL to a PDF (including https://) or a local file path. "
"Useful for reading accessibility standards, technical documents, and reports."
),
func=_read_pdf,
)
def _register_datetime(self):
"""Current date and time — zero dependencies, stdlib only."""
def _datetime(_: str = "") -> str:
from datetime import datetime, timezone
now = datetime.now(timezone.utc)
return (
f"Current UTC date and time: {now.strftime('%Y-%m-%d %H:%M:%S %Z')}\n"
f"ISO 8601: {now.isoformat()}\n"
f"Day of week: {now.strftime('%A')}"
)
self._registry["datetime"] = ToolDefinition(
name="datetime",
description=(
"Return the current UTC date and time. "
"Input is ignored — pass any string or leave empty. "
"Useful for time-aware reasoning, logging, and report generation."
),
func=_datetime,
)
def _register_json_parser(self):
"""JSON parsing and querying — stdlib only, zero dependencies."""
def _parse_json(input_str: str) -> str:
import json
try:
# Support "key::json_string" syntax for targeted key lookup
if "::" in input_str:
key, json_str = input_str.split("::", 1)
data = json.loads(json_str.strip())
result = data.get(key.strip(), f"Key '{key.strip()}' not found.")
return json.dumps(result, indent=2)
else:
data = json.loads(input_str.strip())
return json.dumps(data, indent=2)
except Exception as e:
return f"JSON parser error: {str(e)}"
self._registry["json_parser"] = ToolDefinition(
name="json_parser",
description=(
"Parse and pretty-print a JSON string, or extract a specific key from it. "
"For full parsing, input should be a valid JSON string. "
"For key lookup, use format: 'key::json_string'. "
"Useful for processing API responses and structured data."
),
func=_parse_json,
)
def _register_pubmed(self):
"""PubMed biomedical paper search — via biopython, no API key required."""
def _pubmed(query: str) -> str:
try:
from Bio import Entrez
Entrez.email = "agent@toolpool.local"
handle = Entrez.esearch(db="pubmed", term=query, retmax=5)
record = Entrez.read(handle)
handle.close()
ids = record["IdList"]
if not ids:
return "No PubMed results found."
handle = Entrez.efetch(db="pubmed", id=",".join(ids), rettype="abstract", retmode="text")
abstracts = handle.read()
handle.close()
return abstracts[:4000]
except Exception as e:
return f"PubMed error: {str(e)}"
self._registry["pubmed"] = ToolDefinition(
name="pubmed",
description=(
"Search biomedical and life science literature on PubMed. "
"Input should be a plain-text search query about a medical or biological topic. "
"Returns abstracts of the top matching papers. No API key required."
),
func=_pubmed,
)
def _register_youtube_transcript(self):
"""YouTube transcript retrieval — via youtube-transcript-api, no API key required."""
def _transcript(input_str: str) -> str:
try:
from youtube_transcript_api import YouTubeTranscriptApi
# Accept full URL or bare video ID
if "v=" in input_str:
video_id = input_str.split("v=")[-1].split("&")[0]
elif "youtu.be/" in input_str:
video_id = input_str.split("youtu.be/")[-1].split("?")[0]
else:
video_id = input_str.strip()
transcript = YouTubeTranscriptApi.get_transcript(video_id)
text = " ".join(entry["text"] for entry in transcript)
return text[:4000]
except Exception as e:
return f"YouTube transcript error: {str(e)}"
self._registry["youtube_transcript"] = ToolDefinition(
name="youtube_transcript",
description=(
"Retrieve the transcript of a YouTube video. "
"Input should be a YouTube video URL or bare video ID. "
"Useful for media accessibility evaluation and content analysis."
),
func=_transcript,
)
def _register_sympy(self):
"""Symbolic math and logic evaluation — via sympy, no API key required."""
def _sympy(expression: str) -> str:
try:
import sympy
result = sympy.sympify(expression)
simplified = sympy.simplify(result)
return (
f"Input: {expression}\n"
f"Parsed: {result}\n"
f"Simplified: {simplified}\n"
f"Numeric: {float(simplified.evalf()) if simplified.is_number else 'N/A'}"
)
except Exception as e:
return f"SymPy error: {str(e)}"
self._registry["sympy"] = ToolDefinition(
name="sympy",
description=(
"Evaluate, simplify, or solve a symbolic mathematical expression. "
"Input should be a valid mathematical expression string (e.g. 'x**2 + 2*x + 1'). "
"Useful for calculations, formula verification, and logic evaluation."
),
func=_sympy,
)
def _register_web_interaction(self):
"""Interactive browser tool."""
def _interact(input_str: str) -> str:
"""
Expected input format (JSON string):
{
"url": "https://example.com",
"actions": [
{"type": "navigate"},
{"type": "click", "selector": "button.login"},
{"type": "type", "selector": "input#username", "text": "myuser"},
{"type": "type", "selector": "input#password", "text": "mypassword"},
{"type": "press", "key": "Enter"},
{"type": "wait", "ms": 2000},
{"type": "select", "selector": "select#country", "value": "Brazil"},
{"type": "hover", "selector": ".menu"},
{"type": "scroll", "direction": "down", "amount": 1000},
{"type": "extract", "selector": "body"},
{"type": "extract_all", "selector": ".item"},
{"type": "get_url"},
{"type": "get_title"},
{"type": "screenshot"}
]
}
"""
import json
try:
from playwright.sync_api import sync_playwright
data = json.loads(input_str)
url = data.get("url")
actions = data.get("actions", [])
if not url:
return "Error: 'url' is required."
results = []
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
context = browser.new_context()
page = context.new_page()
page.goto(url, timeout=15000)
for action in actions:
action_type = action.get("type")
try:
if action_type == "navigate":
continue
elif action_type == "click":
page.click(action["selector"], timeout=5000)
elif action_type == "type":
page.fill(action["selector"], action.get("text", ""), timeout=5000)
elif action_type == "press":
page.keyboard.press(action.get("key", "Enter"))
elif action_type == "wait":
page.wait_for_timeout(action.get("ms", 1000))
elif action_type == "wait_for_selector":
page.wait_for_selector(action["selector"], timeout=5000)
elif action_type == "select":
page.select_option(action["selector"], action.get("value"))
elif action_type == "hover":
page.hover(action["selector"])
elif action_type == "scroll":
direction = action.get("direction", "down")
amount = action.get("amount", 1000)
if direction == "down":
page.mouse.wheel(0, amount)
else:
page.mouse.wheel(0, -amount)
elif action_type == "go_back":
page.go_back()
elif action_type == "go_forward":
page.go_forward()
elif action_type == "extract":
selector = action.get("selector", "body")
text = page.inner_text(selector)
results.append(text[:2000])
elif action_type == "extract_all":
selector = action["selector"]
elements = page.query_selector_all(selector)
texts = [el.inner_text() for el in elements[:20]]
results.append("\n".join(texts))
elif action_type == "get_url":
results.append(page.url)
elif action_type == "get_title":
results.append(page.title())
elif action_type == "get_html":
results.append(page.content()[:4000])
elif action_type == "screenshot":
path = action.get("path", "/tmp/screenshot.png")
page.screenshot(path=path)
results.append(f"Screenshot saved to {path}")
else:
results.append(f"Unknown action: {action_type}")
except Exception as step_error:
results.append(f"[{action_type} error]: {str(step_error)}")
browser.close()
return "\n\n".join(results) if results else "No output."
except Exception as e:
return f"Web interaction error: {str(e)}"
self._registry["web_interaction"] = ToolDefinition(
name="web_interaction",
description=(
"Interact with web pages using a headless browser with multi-step actions. "
"Supports navigation, clicking, typing, key presses, dropdown selection, scrolling, "
"waiting, extracting content, and retrieving page metadata. "
"Input must be a JSON string specifying a URL and a sequence of actions."
),
func=_interact,
)
def _register_keyboard_interaction(self):
"""Keyboard-driven browser interaction — optimized for accessibility-style and Mind2Web tasks."""
def _interact(input_str: str) -> str:
"""
Expected input format (JSON string):
{
"url": "https://example.com",
"actions": [
{"type": "navigate"},
{"type": "press", "key": "Tab", "count": 5},
{"type": "press", "key": "Enter"},
{"type": "type", "text": "search query"},
{"type": "press", "key": "Enter"},
{"type": "shortcut", "keys": ["Control", "L"]},
{"type": "wait", "ms": 1000},
{"type": "extract_focused"},
{"type": "extract_active_element"},
{"type": "get_focus_path"},
{"type": "get_url"},
{"type": "get_title"}
]
}
"""
import json
try:
from playwright.sync_api import sync_playwright
data = json.loads(input_str)
url = data.get("url")
actions = data.get("actions", [])
if not url:
return "Error: 'url' is required."
results = []
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
context = browser.new_context()
page = context.new_page()
page.goto(url, timeout=15000)
page.wait_for_load_state("domcontentloaded")
for action in actions:
action_type = action.get("type")
try:
if action_type == "navigate":
continue
elif action_type == "press":
key = action.get("key", "Tab")
count = action.get("count", 1)
for _ in range(count):
page.keyboard.press(key)
elif action_type == "type":
text = action.get("text", "")
page.keyboard.type(text, delay=20)
elif action_type == "shortcut":
keys = action.get("keys", [])
combo = "+".join(keys)
page.keyboard.press(combo)
elif action_type == "wait":
page.wait_for_timeout(action.get("ms", 1000))
elif action_type == "extract_focused":
el = page.evaluate_handle("document.activeElement")
text = el.evaluate("(e) => e ? e.innerText || e.value || '' : ''")
results.append(str(text)[:1000])
elif action_type == "extract_active_element":
html = page.evaluate(
"e => e ? e.outerHTML : ''",
page.evaluate_handle("document.activeElement")
)
results.append(str(html)[:2000])
elif action_type == "get_focus_path":
path = page.evaluate("""
() => {
let el = document.activeElement;
if (!el) return "";
let path = [];
while (el) {
let name = el.tagName.toLowerCase();
if (el.id) name += "#" + el.id;
if (el.className) name += "." + el.className.split(" ").join(".");
path.unshift(name);
el = el.parentElement;
}
return path.join(" > ");
}
""")
results.append(path)
elif action_type == "get_url":
results.append(page.url)
elif action_type == "get_title":
results.append(page.title())
elif action_type == "extract_page_text":
text = page.inner_text("body")
results.append(text[:2000])
else:
results.append(f"Unknown action: {action_type}")
except Exception as step_error:
results.append(f"[{action_type} error]: {str(step_error)}")
browser.close()
return "\n\n".join(results) if results else "No output."
except Exception as e:
return f"Web keyboard interaction error: {str(e)}"
self._registry["web_keyboard_interaction"] = ToolDefinition(
name="web_keyboard_interaction",
description=(
"Interact with web pages using keyboard-only navigation (Tab, Enter, shortcuts). "
"Designed for accessibility-style navigation and Mind2Web tasks where DOM selectors are unknown. "
"Supports key presses, typing, shortcuts, focus inspection, and content extraction from the active element."
),
func=_interact,
)
# TODO: Test hosting SearXNG locally and creating an experiment for common queries performed in Brazil
def _register_searxng_search(self):
"""SearXNG metasearch — aggregates results from 70+ engines."""
import requests
import json
def _searxng_search(query: str) -> str:
# Get the instance URL from environment or a default
base_url = os.getenv("SEARXNG_URL", "http://localhost:8080") # TODO: test hosting locally
try:
# Requesting JSON format is key for your experiments
response = requests.get(
f"{base_url}/search",
params={
"q": query,
"format": "json",
"engines": os.getenv("SEARXNG_ENGINES", "google,bing,duckduckgo,wikipedia"), # TODO: Document how to configure on YAML and retrieve via ConfigExpert
"pageno": 1
},
timeout=15
)
response.raise_for_status()
data = response.json()
results = data.get("results", [])
if not results:
return "No results found via SearXNG."
# For your experiments: Log additional metadata into the invocation_log
# This allows you to track which engines actually responded.
engines_involved = list(set([e for r in results for e in r.get('engines', [])]))
# Enrich the invocation_log entry with experiment-specific data
if _ToolPool.invocation_log:
_ToolPool.invocation_log[-1]["metadata"] = {
"engines_used": engines_involved,
"result_count": len(results),
"raw_traffic_bytes": len(response.content)
}
# Return a structured string for the agent/experimenter to assess
output = []
for i, r in enumerate(results[:10]): # Top 10 results
output.append(
f"[{i+1}] Title: {r.get('title')}\n"
f" URL: {r.get('url')}\n"
f" Engines: {', '.join(r.get('engines', []))}\n"
f" Snippet: {r.get('content', '')[:200]}..."
)
return "\n\n".join(output)
except Exception as e:
return f"SearXNG error: {str(e)}"
self._registry["searxng_search"] = ToolDefinition(
name="searxng_search",
description=(
"Metasearch tool that queries multiple engines simultaneously. "
"Returns results with engine attribution for fan-out analysis."
),
func=_searxng_search,
)
# ------------------------------------------------------------------
# Public API
# ------------------------------------------------------------------
def get_tool(self, name: str, framework: str):
"""