forked from Marktechpost/AI-Agents-Projects-Tutorials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsmartwebagent_tavily_gemini_webintelligence_marktechpost2.py
More file actions
237 lines (195 loc) Β· 9.39 KB
/
smartwebagent_tavily_gemini_webintelligence_marktechpost2.py
File metadata and controls
237 lines (195 loc) Β· 9.39 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
# -*- coding: utf-8 -*-
"""SmartWebAgent_Tavily_Gemini_WebIntelligence_Marktechpost2.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1CrcBSqFMStW8yTr27dcKjOhK1eypqOL_
"""
import os
import json
import asyncio
from typing import List, Dict, Any
from dataclasses import dataclass
from rich.console import Console
from rich.progress import track
from rich.panel import Panel
from rich.markdown import Markdown
from langchain_tavily import TavilyExtract
from langchain.chat_models import init_chat_model
from langgraph.prebuilt import create_react_agent
@dataclass
class WebIntelligence:
"""Web Intelligence Configuration"""
tavily_key: str = os.getenv("TAVILY_API_KEY", "")
google_key: str = os.getenv("GOOGLE_API_KEY", "")
extract_depth: str = "advanced"
max_urls: int = 10
class SmartWebAgent:
"""Intelligent Web Content Extraction & Analysis Agent"""
def __init__(self, config: WebIntelligence):
self.config = config
self.console = Console()
self._setup_environment()
self._initialize_tools()
def _setup_environment(self):
"""Setup API keys with interactive prompts"""
if not self.config.tavily_key:
self.config.tavily_key = input("π Enter Tavily API Key: ")
os.environ["TAVILY_API_KEY"] = self.config.tavily_key
if not self.config.google_key:
self.config.google_key = input("π Enter Google Gemini API Key: ")
os.environ["GOOGLE_API_KEY"] = self.config.google_key
def _initialize_tools(self):
"""Initialize AI tools and agents"""
self.console.print("π οΈ Initializing AI Tools...", style="bold blue")
try:
self.extractor = TavilyExtract(
extract_depth=self.config.extract_depth,
include_images=False,
include_raw_content=False,
max_results=3
)
self.llm = init_chat_model(
"gemini-2.0-flash",
model_provider="google_genai",
temperature=0.3,
max_tokens=1024
)
test_response = self.llm.invoke("Say 'AI tools initialized successfully!'")
self.console.print(f"β
LLM Test: {test_response.content}", style="green")
self.agent = create_react_agent(self.llm, [self.extractor])
self.console.print("β
AI Agent Ready!", style="bold green")
except Exception as e:
self.console.print(f"β Initialization Error: {e}", style="bold red")
self.console.print("π‘ Check your API keys and internet connection", style="yellow")
raise
def extract_content(self, urls: List[str]) -> Dict[str, Any]:
"""Extract and structure content from URLs"""
results = {}
for url in track(urls, description="π Extracting content..."):
try:
response = self.extractor.invoke({"urls": [url]})
content = json.loads(response.content) if isinstance(response.content, str) else response.content
results[url] = {
"status": "success",
"data": content,
"summary": content.get("summary", "No summary available")[:200] + "..."
}
except Exception as e:
results[url] = {"status": "error", "error": str(e)}
return results
def analyze_with_ai(self, query: str, urls: List[str] = None) -> str:
"""Intelligent analysis using AI agent"""
try:
if urls:
message = f"Use the tavily_extract tool to analyze these URLs and answer: {query}\nURLs: {urls}"
else:
message = query
self.console.print(f"π€ AI Analysis: {query}", style="bold magenta")
messages = [{"role": "user", "content": message}]
all_content = []
with self.console.status("π AI thinking..."):
try:
for step in self.agent.stream({"messages": messages}, stream_mode="values"):
if "messages" in step and step["messages"]:
for msg in step["messages"]:
if hasattr(msg, 'content') and msg.content and msg.content not in all_content:
all_content.append(str(msg.content))
except Exception as stream_error:
self.console.print(f"β οΈ Stream error: {stream_error}", style="yellow")
if not all_content:
self.console.print("π Trying direct AI invocation...", style="yellow")
try:
response = self.llm.invoke(message)
return str(response.content) if hasattr(response, 'content') else str(response)
except Exception as direct_error:
self.console.print(f"β οΈ Direct error: {direct_error}", style="yellow")
if urls:
self.console.print("π Extracting content first...", style="blue")
extracted = self.extract_content(urls)
content_summary = "\n".join([
f"URL: {url}\nContent: {result.get('summary', 'No content')}\n"
for url, result in extracted.items() if result.get('status') == 'success'
])
fallback_query = f"Based on this content, {query}:\n\n{content_summary}"
response = self.llm.invoke(fallback_query)
return str(response.content) if hasattr(response, 'content') else str(response)
return "\n".join(all_content) if all_content else "β Unable to generate response. Please check your API keys and try again."
except Exception as e:
return f"β Analysis failed: {str(e)}\n\nTip: Make sure your API keys are valid and you have internet connectivity."
def display_results(self, results: Dict[str, Any]):
"""Beautiful result display"""
for url, result in results.items():
if result["status"] == "success":
panel = Panel(
f"π [bold blue]{url}[/bold blue]\n\n{result['summary']}",
title="β
Extracted Content",
border_style="green"
)
else:
panel = Panel(
f"π [bold red]{url}[/bold red]\n\nβ Error: {result['error']}",
title="β Extraction Failed",
border_style="red"
)
self.console.print(panel)
def run_async_safely(coro):
"""Run async function safely in any environment"""
try:
loop = asyncio.get_running_loop()
import nest_asyncio
nest_asyncio.apply()
return asyncio.run(coro)
except RuntimeError:
return asyncio.run(coro)
except ImportError:
print("β οΈ Running in sync mode. Install nest_asyncio for better performance.")
return None
def main():
"""Interactive Web Intelligence Demo"""
console = Console()
console.print(Panel("π Web Intelligence Agent", style="bold cyan", subtitle="Powered by Tavily & Gemini"))
config = WebIntelligence()
agent = SmartWebAgent(config)
demo_urls = [
"https://en.wikipedia.org/wiki/Artificial_intelligence",
"https://en.wikipedia.org/wiki/Machine_learning",
"https://en.wikipedia.org/wiki/Quantum_computing"
]
while True:
console.print("\n" + "="*60)
console.print("π― Choose an option:", style="bold yellow")
console.print("1. Extract content from URLs")
console.print("2. AI-powered analysis")
console.print("3. Demo with sample URLs")
console.print("4. Exit")
choice = input("\nEnter choice (1-4): ").strip()
if choice == "1":
urls_input = input("Enter URLs (comma-separated): ")
urls = [url.strip() for url in urls_input.split(",")]
results = agent.extract_content(urls)
agent.display_results(results)
elif choice == "2":
query = input("Enter your analysis query: ")
urls_input = input("Enter URLs to analyze (optional, comma-separated): ")
urls = [url.strip() for url in urls_input.split(",") if url.strip()] if urls_input.strip() else None
try:
response = agent.analyze_with_ai(query, urls)
console.print(Panel(Markdown(response), title="π€ AI Analysis", border_style="blue"))
except Exception as e:
console.print(f"β Analysis failed: {e}", style="bold red")
elif choice == "3":
console.print("π¬ Running demo with AI & Quantum Computing URLs...")
results = agent.extract_content(demo_urls)
agent.display_results(results)
response = agent.analyze_with_ai(
"Compare AI, ML, and Quantum Computing. What are the key relationships?",
demo_urls
)
console.print(Panel(Markdown(response), title="π§ Comparative Analysis", border_style="magenta"))
elif choice == "4":
console.print("π Goodbye!", style="bold green")
break
else:
console.print("β Invalid choice!", style="bold red")
if __name__ == "__main__":
main()