File size: 6,597 Bytes
b51b727
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16f8a25
b51b727
 
 
 
16f8a25
 
 
b51b727
16f8a25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11c0a44
 
 
 
16f8a25
b51b727
 
 
 
 
 
 
 
 
 
 
 
 
11c0a44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b51b727
11c0a44
 
 
 
 
 
 
 
 
b51b727
16f8a25
 
b51b727
11c0a44
b51b727
 
11c0a44
b51b727
 
 
 
 
 
 
 
11c0a44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b51b727
11c0a44
 
 
 
 
 
 
 
 
b51b727
 
16f8a25
b51b727
 
 
 
 
 
 
 
 
 
 
 
 
 
11c0a44
 
 
 
 
 
 
 
 
 
b51b727
11c0a44
 
 
 
 
 
 
 
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
# The MIT License

# Copyright (c) 2025 Albert Murienne

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

import os
import requests

from smolagents import Tool
from tavily import TavilyClient

class TavilyBaseClient:
    __api_key = os.getenv("TAVILY_API_KEY")
    _tavily_client = TavilyClient(api_key=__api_key)

    @staticmethod
    def get_usage() -> str:
        url = "https://api.tavily.com/usage"
        headers = {
            "Authorization": f"Bearer {TavilyBaseClient.__api_key}",
            "Content-Type": "application/json",
        }
        res = requests.get(url, headers=headers)
        res.raise_for_status()
        
        account = res.json().get("account", {})
        plan_usage = account.get("plan_usage")
        plan_limit = account.get("plan_limit")

        return f"{plan_usage}/{plan_limit}"

# ---------------------------------------------------------------------
# Tavily Tools
# ---------------------------------------------------------------------

class TavilySearchTool(TavilyBaseClient, Tool):
    """
    A tool to perform web searches using the Tavily API.
    """
    name = "tavily_search"
    description = "Search the web using Tavily."
    inputs = {
        "query": {
            "type": "string",
            "description": "The search query string.",
        }
    }
    output_type = "string"

    # Consumes 1 Tavily credit per query
    __basic_params = {
            "search_depth": "basic",
            "max_results": 10,              # fetch up to 10 sources
            "auto_parameters": False,       # keep manual control
            "include_raw_content": False,
        }

    # Consumes 2 Tavily credits per query
    __advanced_params = {
            "search_depth": "advanced",     # 'advanced' yields better relevance
            "max_results": 10,              # fetch up to 10 sources
            "chunks_per_source": 3,         # number of content snippets to return per source
            "auto_parameters": False,       # keep manual control
            "include_raw_content": False,
        }

    def __init__(self):
        """
        Construct the TavilySearchTool.
        """
        # Call superclass constructor
        super().__init__()


        self.params = TavilySearchTool.__basic_params

    def enable_advanced_mode(self, enable: bool = True):
        """
        Enable or disable advanced mode for the search tool.
        Advanced mode uses more credits but yields better results.
        """
        if enable:
            self.params = TavilySearchTool.__advanced_params
        else:
            self.params = TavilySearchTool.__basic_params
        
        print(f"TavilySearchTool advanced mode has been {'enabled' if enable else 'disabled'}.")

    def forward(self, query: str):

        params = self.params
        params["query"] = query

        try:
            response = self._tavily_client.search(**params)
        except Exception as e:
            return f"Error calling Tavily API: {e}"
        
        return response

class TavilyExtractTool(TavilyBaseClient, Tool):
    """
    A tool to extract raw information from web pages using the Tavily API.
    """
    name = "tavily_extract"
    description = "Extract raw information from web pages using Tavily."
    inputs = {
        "url": {
            "type": "string",
            "description": "The URL of the web page to extract information from.",
        }
    }
    output_type = "string"

    def __init__(self):
        """
        Construct the TavilyExtractTool.
        """
        # Call superclass constructor
        super().__init__()

        self.extract_depth = "basic"

    def enable_advanced_mode(self, enable: bool = True):
        """
        Enable or disable advanced mode for the extract tool.
        Advanced mode uses more credits but yields better results (retrieves more data, including tables and embedded content).
        """
        if enable:
            self.extract_depth = "advanced"
        else:
            self.extract_depth = "basic"

        print(f"TavilyExtractTool advanced mode has been {'enabled' if enable else 'disabled'}.")

    def forward(self, url: str):
        try:
            response = self._tavily_client.extract(
                urls=url,
                extract_depth=self.extract_depth)
        except Exception as e:
            return f"Error calling Tavily extract API: {e}"

        # Tavily's Extract API can return raw HTML + text.
        # you may trim or sanitize here if needed.
        return response

class TavilyImageURLSearchTool(TavilyBaseClient, Tool):
    """
    A tool to search for image URLs using the Tavily API.
    """
    name = "tavily_image_search"
    description = "Search for most relevant image URL on the web using Tavily."
    inputs = {
        "query": {
            "type": "string",
            "description": "The search query string.",
        }
    }
    output_type = "string"

    def forward(self, query: str):
        try:
            response = self._tavily_client.search(
                query,
                include_images=True,
                include_image_descriptions=True,
                max_results=5
            )
        except Exception as e:
            return f"Error calling Tavily API: {e}"

        images = response.get("images", [])
        if not images:
            return "none"

        # Return the URL of the first image
        first_image = images[0]
        if isinstance(first_image, dict):
            return first_image.get("url", "none")
        return first_image or "none"