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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import requests
|
3 |
+
import json
|
4 |
+
from typing import Optional, List
|
5 |
+
|
6 |
+
def tavily_search(
|
7 |
+
api_key: str,
|
8 |
+
query: str,
|
9 |
+
topic: str = "general",
|
10 |
+
search_depth: str = "basic",
|
11 |
+
chunks_per_source: int = 3,
|
12 |
+
max_results: int = 5,
|
13 |
+
time_range: Optional[str] = None,
|
14 |
+
days: int = 7,
|
15 |
+
include_answer: bool = True,
|
16 |
+
include_raw_content: str = "false",
|
17 |
+
include_images: bool = False,
|
18 |
+
include_image_descriptions: bool = False,
|
19 |
+
include_domains: str = "",
|
20 |
+
exclude_domains: str = "",
|
21 |
+
country: Optional[str] = None
|
22 |
+
):
|
23 |
+
"""
|
24 |
+
Perform a Tavily search with the given parameters.
|
25 |
+
"""
|
26 |
+
if not api_key.strip():
|
27 |
+
return "β Error: Please provide a valid Tavily API key."
|
28 |
+
|
29 |
+
if not query.strip():
|
30 |
+
return "β Error: Please provide a search query."
|
31 |
+
|
32 |
+
url = "https://api.tavily.com/search"
|
33 |
+
|
34 |
+
# Prepare the payload
|
35 |
+
payload = {
|
36 |
+
"query": query,
|
37 |
+
"topic": topic,
|
38 |
+
"search_depth": search_depth,
|
39 |
+
"max_results": max_results,
|
40 |
+
"include_answer": include_answer,
|
41 |
+
"include_images": include_images,
|
42 |
+
"include_image_descriptions": include_image_descriptions,
|
43 |
+
}
|
44 |
+
|
45 |
+
# Add optional parameters
|
46 |
+
if search_depth == "advanced":
|
47 |
+
payload["chunks_per_source"] = chunks_per_source
|
48 |
+
|
49 |
+
if time_range and time_range != "None":
|
50 |
+
payload["time_range"] = time_range
|
51 |
+
|
52 |
+
if topic == "news" and days > 0:
|
53 |
+
payload["days"] = days
|
54 |
+
|
55 |
+
if include_raw_content != "false":
|
56 |
+
payload["include_raw_content"] = include_raw_content if include_raw_content != "true" else True
|
57 |
+
|
58 |
+
if include_domains.strip():
|
59 |
+
payload["include_domains"] = [domain.strip() for domain in include_domains.split(",")]
|
60 |
+
|
61 |
+
if exclude_domains.strip():
|
62 |
+
payload["exclude_domains"] = [domain.strip() for domain in exclude_domains.split(",")]
|
63 |
+
|
64 |
+
if country and country != "None":
|
65 |
+
payload["country"] = country
|
66 |
+
|
67 |
+
headers = {
|
68 |
+
"Authorization": f"Bearer {api_key}",
|
69 |
+
"Content-Type": "application/json"
|
70 |
+
}
|
71 |
+
|
72 |
+
try:
|
73 |
+
response = requests.post(url, json=payload, headers=headers, timeout=30)
|
74 |
+
|
75 |
+
if response.status_code == 200:
|
76 |
+
result = response.json()
|
77 |
+
|
78 |
+
# Format the response for better readability
|
79 |
+
formatted_result = "π **Tavily Search Results**\n\n"
|
80 |
+
|
81 |
+
if "answer" in result and result["answer"]:
|
82 |
+
formatted_result += f"π **Answer:**\n{result['answer']}\n\n"
|
83 |
+
|
84 |
+
if "results" in result:
|
85 |
+
formatted_result += f"π **Found {len(result['results'])} results:**\n\n"
|
86 |
+
|
87 |
+
for i, item in enumerate(result["results"], 1):
|
88 |
+
formatted_result += f"**{i}. {item.get('title', 'No Title')}**\n"
|
89 |
+
formatted_result += f"π URL: {item.get('url', 'No URL')}\n"
|
90 |
+
formatted_result += f"π Content: {item.get('content', 'No content available')[:500]}...\n"
|
91 |
+
if item.get('score'):
|
92 |
+
formatted_result += f"β Score: {item['score']}\n"
|
93 |
+
formatted_result += "\n" + "β" * 50 + "\n\n"
|
94 |
+
|
95 |
+
# Add raw JSON for debugging
|
96 |
+
formatted_result += "\n\nπ§ **Raw JSON Response:**\n```json\n" + json.dumps(result, indent=2) + "\n```"
|
97 |
+
|
98 |
+
return formatted_result
|
99 |
+
|
100 |
+
else:
|
101 |
+
return f"β Error: HTTP {response.status_code}\n{response.text}"
|
102 |
+
|
103 |
+
except requests.exceptions.Timeout:
|
104 |
+
return "β Error: Request timed out. Please try again."
|
105 |
+
except requests.exceptions.RequestException as e:
|
106 |
+
return f"β Error: {str(e)}"
|
107 |
+
except Exception as e:
|
108 |
+
return f"β Unexpected error: {str(e)}"
|
109 |
+
|
110 |
+
# Define the country options
|
111 |
+
country_options = [
|
112 |
+
"None", "afghanistan", "albania", "algeria", "andorra", "angola", "argentina",
|
113 |
+
"armenia", "australia", "austria", "azerbaijan", "bahamas", "bahrain", "bangladesh",
|
114 |
+
"barbados", "belarus", "belgium", "belize", "benin", "bhutan", "bolivia",
|
115 |
+
"bosnia and herzegovina", "botswana", "brazil", "brunei", "bulgaria", "burkina faso",
|
116 |
+
"burundi", "cambodia", "cameroon", "canada", "cape verde", "central african republic",
|
117 |
+
"chad", "chile", "china", "colombia", "comoros", "congo", "costa rica", "croatia",
|
118 |
+
"cuba", "cyprus", "czech republic", "denmark", "djibouti", "dominican republic",
|
119 |
+
"ecuador", "egypt", "el salvador", "equatorial guinea", "eritrea", "estonia",
|
120 |
+
"ethiopia", "fiji", "finland", "france", "gabon", "gambia", "georgia", "germany",
|
121 |
+
"ghana", "greece", "guatemala", "guinea", "haiti", "honduras", "hungary", "iceland",
|
122 |
+
"india", "indonesia", "iran", "iraq", "ireland", "israel", "italy", "jamaica",
|
123 |
+
"japan", "jordan", "kazakhstan", "kenya", "kuwait", "kyrgyzstan", "latvia", "lebanon",
|
124 |
+
"lesotho", "liberia", "libya", "liechtenstein", "lithuania", "luxembourg", "madagascar",
|
125 |
+
"malawi", "malaysia", "maldives", "mali", "malta", "mauritania", "mauritius", "mexico",
|
126 |
+
"moldova", "monaco", "mongolia", "montenegro", "morocco", "mozambique", "myanmar",
|
127 |
+
"namibia", "nepal", "netherlands", "new zealand", "nicaragua", "niger", "nigeria",
|
128 |
+
"north korea", "north macedonia", "norway", "oman", "pakistan", "panama",
|
129 |
+
"papua new guinea", "paraguay", "peru", "philippines", "poland", "portugal", "qatar",
|
130 |
+
"romania", "russia", "rwanda", "saudi arabia", "senegal", "serbia", "singapore",
|
131 |
+
"slovakia", "slovenia", "somalia", "south africa", "south korea", "south sudan",
|
132 |
+
"spain", "sri lanka", "sudan", "sweden", "switzerland", "syria", "taiwan",
|
133 |
+
"tajikistan", "tanzania", "thailand", "togo", "trinidad and tobago", "tunisia",
|
134 |
+
"turkey", "turkmenistan", "uganda", "ukraine", "united arab emirates",
|
135 |
+
"united kingdom", "united states", "uruguay", "uzbekistan", "venezuela", "vietnam",
|
136 |
+
"yemen", "zambia", "zimbabwe"
|
137 |
+
]
|
138 |
+
|
139 |
+
# Create the Gradio interface
|
140 |
+
with gr.Blocks(title="Tavily Search API", theme=gr.themes.Soft()) as app:
|
141 |
+
gr.Markdown("# π Tavily Search API Interface")
|
142 |
+
gr.Markdown("Search the web using Tavily's powerful search API with customizable parameters.")
|
143 |
+
|
144 |
+
with gr.Row():
|
145 |
+
with gr.Column(scale=1):
|
146 |
+
# API Configuration
|
147 |
+
gr.Markdown("## π API Configuration")
|
148 |
+
api_key = gr.Textbox(
|
149 |
+
label="Tavily API Key",
|
150 |
+
placeholder="Enter your Tavily API key here...",
|
151 |
+
type="password",
|
152 |
+
info="Your API key will be used to authenticate requests to Tavily."
|
153 |
+
)
|
154 |
+
|
155 |
+
# Search Parameters
|
156 |
+
gr.Markdown("## π― Search Parameters")
|
157 |
+
query = gr.Textbox(
|
158 |
+
label="Search Query",
|
159 |
+
placeholder="e.g., 'who is Leo Messi?'",
|
160 |
+
info="The search query you want to execute."
|
161 |
+
)
|
162 |
+
|
163 |
+
with gr.Row():
|
164 |
+
topic = gr.Dropdown(
|
165 |
+
choices=["general", "news"],
|
166 |
+
value="general",
|
167 |
+
label="Topic",
|
168 |
+
info="general: broad searches, news: real-time updates"
|
169 |
+
)
|
170 |
+
|
171 |
+
search_depth = gr.Dropdown(
|
172 |
+
choices=["basic", "advanced"],
|
173 |
+
value="basic",
|
174 |
+
label="Search Depth",
|
175 |
+
info="basic: 1 credit, advanced: 2 credits"
|
176 |
+
)
|
177 |
+
|
178 |
+
with gr.Row():
|
179 |
+
max_results = gr.Slider(
|
180 |
+
minimum=1,
|
181 |
+
maximum=20,
|
182 |
+
value=5,
|
183 |
+
step=1,
|
184 |
+
label="Max Results",
|
185 |
+
info="Maximum number of search results to return"
|
186 |
+
)
|
187 |
+
|
188 |
+
chunks_per_source = gr.Slider(
|
189 |
+
minimum=1,
|
190 |
+
maximum=3,
|
191 |
+
value=3,
|
192 |
+
step=1,
|
193 |
+
label="Chunks per Source",
|
194 |
+
info="Only applies to advanced search"
|
195 |
+
)
|
196 |
+
|
197 |
+
# Advanced Options
|
198 |
+
gr.Markdown("## βοΈ Advanced Options")
|
199 |
+
|
200 |
+
with gr.Row():
|
201 |
+
time_range = gr.Dropdown(
|
202 |
+
choices=["None", "day", "week", "month", "year"],
|
203 |
+
value="None",
|
204 |
+
label="Time Range",
|
205 |
+
info="Filter results by time period"
|
206 |
+
)
|
207 |
+
|
208 |
+
days = gr.Number(
|
209 |
+
value=7,
|
210 |
+
minimum=1,
|
211 |
+
label="Days (News only)",
|
212 |
+
info="Number of days back for news searches"
|
213 |
+
)
|
214 |
+
|
215 |
+
with gr.Row():
|
216 |
+
include_answer = gr.Checkbox(
|
217 |
+
value=True,
|
218 |
+
label="Include Answer",
|
219 |
+
info="Include LLM-generated answer"
|
220 |
+
)
|
221 |
+
|
222 |
+
include_images = gr.Checkbox(
|
223 |
+
value=False,
|
224 |
+
label="Include Images",
|
225 |
+
info="Perform image search"
|
226 |
+
)
|
227 |
+
|
228 |
+
include_image_descriptions = gr.Checkbox(
|
229 |
+
value=False,
|
230 |
+
label="Include Image Descriptions",
|
231 |
+
info="Add descriptions for images"
|
232 |
+
)
|
233 |
+
|
234 |
+
include_raw_content = gr.Dropdown(
|
235 |
+
choices=["false", "true", "markdown", "text"],
|
236 |
+
value="false",
|
237 |
+
label="Include Raw Content",
|
238 |
+
info="Include cleaned HTML content"
|
239 |
+
)
|
240 |
+
|
241 |
+
with gr.Row():
|
242 |
+
include_domains = gr.Textbox(
|
243 |
+
label="Include Domains",
|
244 |
+
placeholder="example.com, another.com",
|
245 |
+
info="Comma-separated list of domains to include"
|
246 |
+
)
|
247 |
+
|
248 |
+
exclude_domains = gr.Textbox(
|
249 |
+
label="Exclude Domains",
|
250 |
+
placeholder="example.com, another.com",
|
251 |
+
info="Comma-separated list of domains to exclude"
|
252 |
+
)
|
253 |
+
|
254 |
+
country = gr.Dropdown(
|
255 |
+
choices=country_options,
|
256 |
+
value="None",
|
257 |
+
label="Country",
|
258 |
+
info="Boost results from specific country (general topic only)"
|
259 |
+
)
|
260 |
+
|
261 |
+
# Search Button
|
262 |
+
search_btn = gr.Button("π Search", variant="primary", size="lg")
|
263 |
+
|
264 |
+
with gr.Column(scale=2):
|
265 |
+
# Results
|
266 |
+
gr.Markdown("## π Search Results")
|
267 |
+
results = gr.Textbox(
|
268 |
+
label="Results",
|
269 |
+
lines=25,
|
270 |
+
max_lines=50,
|
271 |
+
show_copy_button=True,
|
272 |
+
placeholder="Results will appear here after searching..."
|
273 |
+
)
|
274 |
+
|
275 |
+
# Examples
|
276 |
+
gr.Markdown("## π‘ Examples")
|
277 |
+
gr.Examples(
|
278 |
+
[
|
279 |
+
["Who is Leo Messi?", "general", "basic", 5, True],
|
280 |
+
["Latest news about artificial intelligence", "news", "advanced", 3, True],
|
281 |
+
["Python programming tutorials", "general", "basic", 10, True],
|
282 |
+
["Climate change recent developments", "news", "basic", 5, True],
|
283 |
+
],
|
284 |
+
inputs=[query, topic, search_depth, max_results, include_answer],
|
285 |
+
label="Click on an example to load it"
|
286 |
+
)
|
287 |
+
|
288 |
+
# Connect the search button
|
289 |
+
search_btn.click(
|
290 |
+
fn=tavily_search,
|
291 |
+
inputs=[
|
292 |
+
api_key, query, topic, search_depth, chunks_per_source, max_results,
|
293 |
+
time_range, days, include_answer, include_raw_content, include_images,
|
294 |
+
include_image_descriptions, include_domains, exclude_domains, country
|
295 |
+
],
|
296 |
+
outputs=results
|
297 |
+
)
|
298 |
+
|
299 |
+
# Footer
|
300 |
+
gr.Markdown("---")
|
301 |
+
gr.Markdown("π **Get your Tavily API key at:** [tavily.com](https://tavily.com)")
|
302 |
+
|
303 |
+
# Launch the app
|
304 |
+
if __name__ == "__main__":
|
305 |
+
app.launch(
|
306 |
+
share=False,
|
307 |
+
server_name="127.0.0.1",
|
308 |
+
server_port=7860,
|
309 |
+
show_error=True
|
310 |
+
)
|