File size: 2,036 Bytes
82c5973
d9df2c4
 
82c5973
21ef4cf
 
 
 
 
 
 
 
 
 
 
 
d9df2c4
21ef4cf
 
 
82c5973
21ef4cf
 
d9df2c4
21ef4cf
 
82c5973
21ef4cf
 
 
d9df2c4
21ef4cf
 
 
 
d9df2c4
 
 
 
21ef4cf
 
 
d9df2c4
21ef4cf
 
 
 
 
 
 
 
 
d9df2c4
21ef4cf
 
 
9b651b2
21ef4cf
 
 
9b651b2
21ef4cf
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
import re
from duckduckgo_search import DDGS
from typing import List, Dict, Any

class BaseTool:
    def __init__(self, name: str, description: str):
        self.name = name
        self.description = description

    def run(self, *args, **kwargs) -> str:
        raise NotImplementedError

class Calculator(BaseTool):
    def __init__(self):
        super().__init__(
            name="Calculator",
            description="Performs basic arithmetic. Input: math expression as string"
        )

    def run(self, expression: str) -> str:
        try:
            expression = expression.replace(' ', '')
            if not re.match(r'^[\d+\-*/.()]+$', expression):
                return "Error: Invalid characters in expression"
            result = eval(expression)
            return str(result)
        except Exception as e:
            return f"Calculation error: {str(e)}"

class DocRetriever(BaseTool):
    def __init__(self):
        super().__init__(
            name="DocRetriever",
            description="Searches provided text. Input: 'query: <search_term>'"
        )
        self.document = ""

    def load_document(self, text: str):
        self.document = text

    def run(self, query: str) -> str:
        if not self.document:
            return "No document loaded"
        
        sentences = [s.strip() for s in self.document.split('.') if s]
        results = [s for s in sentences if query.lower() in s.lower()]
        return '. '.join(results[:3]) + '...' if results else "No matches found"

class WebSearcher(BaseTool):
    def __init__(self):
        super().__init__(
            name="WebSearcher",
            description="Searches the web. Input: search query"
        )

    def run(self, query: str) -> str:
        try:
            with DDGS() as ddgs:
                results = [r for r in ddgs.text(query, max_results=3)]
            return '\n'.join([f"[{r['title']}]({r['href']}): {r['body']}" for r in results])
        except Exception as e:
            return f"Search error: {str(e)}"