Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -11,62 +11,85 @@ from autogen_agentchat.teams import SelectorGroupChat
|
|
11 |
from autogen_ext.models.openai import OpenAIChatCompletionClient
|
12 |
from autogen_ext.agents.web_surfer import MultimodalWebSurfer
|
13 |
|
14 |
-
# Enable nested event loops
|
15 |
nest_asyncio.apply()
|
16 |
|
17 |
class AIShoppingAnalyzer:
|
18 |
def __init__(self, api_key: str):
|
19 |
self.api_key = api_key
|
20 |
-
# Set the API key in environment
|
21 |
os.environ["OPENAI_API_KEY"] = api_key
|
22 |
self.model_client = OpenAIChatCompletionClient(model="gpt-4o")
|
23 |
self.termination = MaxMessageTermination(max_messages=20) | TextMentionTermination("TERMINATE")
|
24 |
|
25 |
def create_websurfer(self) -> MultimodalWebSurfer:
|
26 |
"""Initialize the web surfer agent for e-commerce research"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
return MultimodalWebSurfer(
|
28 |
name="websurfer_agent",
|
29 |
-
description=
|
30 |
-
1. Searches multiple retailers for product options
|
31 |
-
2. Compares prices and reviews
|
32 |
-
3. Checks product specifications and availability
|
33 |
-
4. Analyzes website structure and findability
|
34 |
-
5. Detects and analyzes structured data (Schema.org, JSON-LD, Microdata)
|
35 |
-
6. Evaluates product markup and rich snippets
|
36 |
-
7. Checks for proper semantic HTML and data organization""",
|
37 |
model_client=self.model_client,
|
38 |
-
headless=True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
)
|
40 |
|
41 |
def create_assistant(self) -> AssistantAgent:
|
42 |
"""Initialize the shopping assistant agent"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
43 |
return AssistantAgent(
|
44 |
name="assistant_agent",
|
45 |
description="E-commerce shopping advisor and website analyzer",
|
46 |
-
system_message=
|
47 |
-
1. Help find products based on user needs
|
48 |
-
2. Compare prices and features across different sites
|
49 |
-
3. Analyze website usability and product findability
|
50 |
-
4. Evaluate product presentation and information quality
|
51 |
-
5. Assess the overall e-commerce experience
|
52 |
-
6. Analyze structured data implementation:
|
53 |
-
- Check for Schema.org markup
|
54 |
-
- Validate JSON-LD implementation
|
55 |
-
- Evaluate microdata usage
|
56 |
-
- Assess rich snippet potential
|
57 |
-
7. Report on data structure quality:
|
58 |
-
- Product markup completeness
|
59 |
-
- Price and availability markup
|
60 |
-
- Review and rating markup
|
61 |
-
- Inventory status markup
|
62 |
-
|
63 |
-
When working with the websurfer_agent:
|
64 |
-
- Guide their research effectively
|
65 |
-
- Verify the information they find
|
66 |
-
- Analyze how easy it was to find products
|
67 |
-
- Evaluate product page quality
|
68 |
-
- Say 'keep going' if more research is needed
|
69 |
-
- Say 'TERMINATE' only when you have a complete analysis""",
|
70 |
model_client=self.model_client
|
71 |
)
|
72 |
|
@@ -77,17 +100,17 @@ class AIShoppingAnalyzer:
|
|
77 |
description="An e-commerce site owner looking for AI shopping analysis"
|
78 |
)
|
79 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
80 |
return SelectorGroupChat(
|
81 |
participants=[websurfer_agent, assistant_agent, user_proxy],
|
82 |
-
selector_prompt=
|
83 |
-
{roles}
|
84 |
-
|
85 |
-
Given the conversation history {history}, select the next role from {participants}.
|
86 |
-
- The websurfer_agent searches products and analyzes website structure
|
87 |
-
- The assistant_agent evaluates findings and makes recommendations
|
88 |
-
- The user_proxy provides input when needed
|
89 |
-
|
90 |
-
Return only the role name.""",
|
91 |
model_client=self.model_client,
|
92 |
termination_condition=self.termination
|
93 |
)
|
@@ -99,24 +122,21 @@ class AIShoppingAnalyzer:
|
|
99 |
"""Run the analysis with proper cleanup"""
|
100 |
websurfer = None
|
101 |
try:
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
|
|
108 |
|
109 |
if specific_product:
|
110 |
query += f"\n5. Detailed analysis of this specific product: {specific_product}"
|
111 |
|
112 |
-
# Initialize agents with automatic browser management
|
113 |
websurfer = self.create_websurfer()
|
114 |
assistant = self.create_assistant()
|
115 |
-
|
116 |
-
# Create team
|
117 |
team = self.create_team(websurfer, assistant)
|
118 |
|
119 |
-
# Modified execution to handle EOF errors
|
120 |
try:
|
121 |
result = []
|
122 |
async for message in team.run_stream(task=query):
|
@@ -136,9 +156,8 @@ class AIShoppingAnalyzer:
|
|
136 |
await websurfer.close()
|
137 |
except Exception as e:
|
138 |
print(f"Cleanup error: {str(e)}")
|
139 |
-
# Continue even if cleanup fails
|
140 |
|
141 |
-
def create_gradio_interface() -> gr.
|
142 |
"""Create the Gradio interface for the AI Shopping Analyzer"""
|
143 |
|
144 |
css = """
|
@@ -175,7 +194,6 @@ def create_gradio_interface() -> gr.Interface:
|
|
175 |
background-color: #e5e7eb;
|
176 |
}
|
177 |
|
178 |
-
/* Custom styling for form elements */
|
179 |
.gr-form {
|
180 |
background: transparent !important;
|
181 |
border: none !important;
|
@@ -209,18 +227,63 @@ def create_gradio_interface() -> gr.Interface:
|
|
209 |
.gr-button:hover {
|
210 |
background-color: #3a3ab8 !important;
|
211 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
212 |
"""
|
213 |
-
|
214 |
-
def validate_api_key(api_key: str) -> bool:
|
215 |
-
"""Validate the OpenAI API key format"""
|
216 |
-
return api_key.startswith("sk-") and len(api_key) > 20
|
217 |
|
218 |
async def run_analysis(api_key: str,
|
219 |
website_url: str,
|
220 |
product_category: str,
|
221 |
specific_product: str) -> str:
|
222 |
"""Handle the analysis submission"""
|
223 |
-
if not
|
224 |
return "Please enter a valid OpenAI API key (should start with 'sk-')"
|
225 |
|
226 |
if not website_url:
|
@@ -240,34 +303,72 @@ def create_gradio_interface() -> gr.Interface:
|
|
240 |
except Exception as e:
|
241 |
return f"Error during analysis: {str(e)}"
|
242 |
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
259 |
|
260 |
if __name__ == "__main__":
|
261 |
-
|
262 |
-
import subprocess
|
263 |
try:
|
264 |
-
subprocess
|
265 |
-
subprocess.run(
|
266 |
-
|
267 |
-
|
|
|
|
|
|
|
268 |
except Exception as e:
|
269 |
-
print(f"
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
|
|
|
11 |
from autogen_ext.models.openai import OpenAIChatCompletionClient
|
12 |
from autogen_ext.agents.web_surfer import MultimodalWebSurfer
|
13 |
|
14 |
+
# Enable nested event loops
|
15 |
nest_asyncio.apply()
|
16 |
|
17 |
class AIShoppingAnalyzer:
|
18 |
def __init__(self, api_key: str):
|
19 |
self.api_key = api_key
|
|
|
20 |
os.environ["OPENAI_API_KEY"] = api_key
|
21 |
self.model_client = OpenAIChatCompletionClient(model="gpt-4o")
|
22 |
self.termination = MaxMessageTermination(max_messages=20) | TextMentionTermination("TERMINATE")
|
23 |
|
24 |
def create_websurfer(self) -> MultimodalWebSurfer:
|
25 |
"""Initialize the web surfer agent for e-commerce research"""
|
26 |
+
description = (
|
27 |
+
"E-commerce research specialist that:\n"
|
28 |
+
"1. Searches multiple retailers for product options\n"
|
29 |
+
"2. Compares prices and reviews\n"
|
30 |
+
"3. Checks product specifications and availability\n"
|
31 |
+
"4. Analyzes website structure and findability\n"
|
32 |
+
"5. Detects and analyzes structured data (Schema.org, JSON-LD, Microdata)\n"
|
33 |
+
"6. Evaluates product markup and rich snippets\n"
|
34 |
+
"7. Checks for proper semantic HTML and data organization"
|
35 |
+
)
|
36 |
+
|
37 |
return MultimodalWebSurfer(
|
38 |
name="websurfer_agent",
|
39 |
+
description=description,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
40 |
model_client=self.model_client,
|
41 |
+
headless=True,
|
42 |
+
browser_kwargs={
|
43 |
+
"args": [
|
44 |
+
"--disable-dev-shm-usage",
|
45 |
+
"--no-sandbox",
|
46 |
+
"--disable-setuid-sandbox"
|
47 |
+
]
|
48 |
+
}
|
49 |
)
|
50 |
|
51 |
def create_assistant(self) -> AssistantAgent:
|
52 |
"""Initialize the shopping assistant agent"""
|
53 |
+
system_message = (
|
54 |
+
"You are an expert shopping assistant and e-commerce analyst. "
|
55 |
+
"Analyze websites and provide reports in this format:\n\n"
|
56 |
+
"📊 E-COMMERCE ANALYSIS REPORT\n"
|
57 |
+
"============================\n"
|
58 |
+
"Site: {url}\n"
|
59 |
+
"Date: {date}\n\n"
|
60 |
+
"🔍 FINDABILITY SCORE: [★★★★☆]\n"
|
61 |
+
"-----------------------------\n"
|
62 |
+
"• Category Organization\n"
|
63 |
+
"• Navigation Structure\n"
|
64 |
+
"• Filter Systems\n\n"
|
65 |
+
"📝 INFORMATION QUALITY: [★★★★☆]\n"
|
66 |
+
"------------------------------\n"
|
67 |
+
"• Product Details\n"
|
68 |
+
"• Image Quality\n"
|
69 |
+
"• Technical Specs\n"
|
70 |
+
"• Structured Data\n\n"
|
71 |
+
"🔄 NAVIGATION & SEARCH: [★★★★☆]\n"
|
72 |
+
"------------------------------\n"
|
73 |
+
"• Search Features\n"
|
74 |
+
"• User Experience\n"
|
75 |
+
"• Mobile Design\n\n"
|
76 |
+
"💰 PRICING TRANSPARENCY: [★★★★☆]\n"
|
77 |
+
"------------------------------\n"
|
78 |
+
"• Price Display\n"
|
79 |
+
"• Special Offers\n"
|
80 |
+
"• Comparison Tools\n\n"
|
81 |
+
"📈 OVERALL ASSESSMENT\n"
|
82 |
+
"-------------------\n"
|
83 |
+
"[Summary]\n\n"
|
84 |
+
"🔧 TECHNICAL INSIGHTS\n"
|
85 |
+
"-------------------\n"
|
86 |
+
"[Technical Details]"
|
87 |
+
)
|
88 |
+
|
89 |
return AssistantAgent(
|
90 |
name="assistant_agent",
|
91 |
description="E-commerce shopping advisor and website analyzer",
|
92 |
+
system_message=system_message,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
93 |
model_client=self.model_client
|
94 |
)
|
95 |
|
|
|
100 |
description="An e-commerce site owner looking for AI shopping analysis"
|
101 |
)
|
102 |
|
103 |
+
selector_prompt = (
|
104 |
+
"You are coordinating an e-commerce analysis system. Select the next role from these participants:\n"
|
105 |
+
"- The websurfer_agent searches products and analyzes website structure\n"
|
106 |
+
"- The assistant_agent evaluates findings and makes recommendations\n"
|
107 |
+
"- The user_proxy provides input when needed\n\n"
|
108 |
+
"Return only the role name."
|
109 |
+
)
|
110 |
+
|
111 |
return SelectorGroupChat(
|
112 |
participants=[websurfer_agent, assistant_agent, user_proxy],
|
113 |
+
selector_prompt=selector_prompt,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
114 |
model_client=self.model_client,
|
115 |
termination_condition=self.termination
|
116 |
)
|
|
|
122 |
"""Run the analysis with proper cleanup"""
|
123 |
websurfer = None
|
124 |
try:
|
125 |
+
query = (
|
126 |
+
f"Analyze the e-commerce experience for {website_url} focusing on:\n"
|
127 |
+
f"1. Product findability in the {product_category} category\n"
|
128 |
+
"2. Product information quality\n"
|
129 |
+
"3. Navigation and search functionality\n"
|
130 |
+
"4. Price visibility and comparison features"
|
131 |
+
)
|
132 |
|
133 |
if specific_product:
|
134 |
query += f"\n5. Detailed analysis of this specific product: {specific_product}"
|
135 |
|
|
|
136 |
websurfer = self.create_websurfer()
|
137 |
assistant = self.create_assistant()
|
|
|
|
|
138 |
team = self.create_team(websurfer, assistant)
|
139 |
|
|
|
140 |
try:
|
141 |
result = []
|
142 |
async for message in team.run_stream(task=query):
|
|
|
156 |
await websurfer.close()
|
157 |
except Exception as e:
|
158 |
print(f"Cleanup error: {str(e)}")
|
|
|
159 |
|
160 |
+
def create_gradio_interface() -> gr.Blocks:
|
161 |
"""Create the Gradio interface for the AI Shopping Analyzer"""
|
162 |
|
163 |
css = """
|
|
|
194 |
background-color: #e5e7eb;
|
195 |
}
|
196 |
|
|
|
197 |
.gr-form {
|
198 |
background: transparent !important;
|
199 |
border: none !important;
|
|
|
227 |
.gr-button:hover {
|
228 |
background-color: #3a3ab8 !important;
|
229 |
}
|
230 |
+
|
231 |
+
.analysis-output {
|
232 |
+
background: white;
|
233 |
+
padding: 20px;
|
234 |
+
border-radius: 8px;
|
235 |
+
border: 1px solid #e0e5ff;
|
236 |
+
margin-top: 20px;
|
237 |
+
}
|
238 |
+
|
239 |
+
.analysis-output h1 {
|
240 |
+
font-size: 1.5em;
|
241 |
+
font-weight: bold;
|
242 |
+
margin-bottom: 1em;
|
243 |
+
}
|
244 |
+
|
245 |
+
.analysis-output h2 {
|
246 |
+
font-size: 1.25em;
|
247 |
+
font-weight: 600;
|
248 |
+
margin-top: 1.5em;
|
249 |
+
margin-bottom: 0.5em;
|
250 |
+
}
|
251 |
+
|
252 |
+
.analysis-output h3 {
|
253 |
+
font-size: 1.1em;
|
254 |
+
font-weight: 600;
|
255 |
+
margin-top: 1em;
|
256 |
+
margin-bottom: 0.5em;
|
257 |
+
}
|
258 |
+
|
259 |
+
.analysis-output ul {
|
260 |
+
margin-left: 1.5em;
|
261 |
+
margin-bottom: 1em;
|
262 |
+
}
|
263 |
+
|
264 |
+
.analysis-output li {
|
265 |
+
margin-bottom: 0.5em;
|
266 |
+
}
|
267 |
+
|
268 |
+
.analysis-output p {
|
269 |
+
margin-bottom: 1em;
|
270 |
+
line-height: 1.6;
|
271 |
+
}
|
272 |
+
|
273 |
+
.analysis-output code {
|
274 |
+
background: #f3f4f6;
|
275 |
+
padding: 0.2em 0.4em;
|
276 |
+
border-radius: 4px;
|
277 |
+
font-size: 0.9em;
|
278 |
+
}
|
279 |
"""
|
|
|
|
|
|
|
|
|
280 |
|
281 |
async def run_analysis(api_key: str,
|
282 |
website_url: str,
|
283 |
product_category: str,
|
284 |
specific_product: str) -> str:
|
285 |
"""Handle the analysis submission"""
|
286 |
+
if not api_key.startswith("sk-"):
|
287 |
return "Please enter a valid OpenAI API key (should start with 'sk-')"
|
288 |
|
289 |
if not website_url:
|
|
|
303 |
except Exception as e:
|
304 |
return f"Error during analysis: {str(e)}"
|
305 |
|
306 |
+
with gr.Blocks(css=css) as demo:
|
307 |
+
gr.HTML("""
|
308 |
+
<div class="dashboard-container p-6">
|
309 |
+
<h1 class="text-2xl font-bold mb-2">AI Shopping Agent Analyzer</h1>
|
310 |
+
<p class="text-gray-600 mb-6">Analyze how your e-commerce site performs with AI shoppers</p>
|
311 |
+
</div>
|
312 |
+
""")
|
313 |
+
|
314 |
+
with gr.Group():
|
315 |
+
api_key = gr.Textbox(
|
316 |
+
label="OpenAI API Key",
|
317 |
+
placeholder="sk-...",
|
318 |
+
type="password",
|
319 |
+
container=True
|
320 |
+
)
|
321 |
+
|
322 |
+
website_url = gr.Textbox(
|
323 |
+
label="Website URL",
|
324 |
+
placeholder="https://your-store.com",
|
325 |
+
container=True
|
326 |
+
)
|
327 |
+
|
328 |
+
product_category = gr.Textbox(
|
329 |
+
label="Product Category",
|
330 |
+
placeholder="e.g., Electronics, Clothing, etc.",
|
331 |
+
container=True
|
332 |
+
)
|
333 |
+
|
334 |
+
specific_product = gr.Textbox(
|
335 |
+
label="Specific Product (Optional)",
|
336 |
+
placeholder="e.g., Blue Widget Model X",
|
337 |
+
container=True
|
338 |
+
)
|
339 |
+
|
340 |
+
analyze_button = gr.Button(
|
341 |
+
"Analyze Site",
|
342 |
+
variant="primary"
|
343 |
+
)
|
344 |
+
|
345 |
+
analysis_output = gr.Markdown(
|
346 |
+
label="Analysis Results",
|
347 |
+
value="Results will appear here...",
|
348 |
+
elem_classes="analysis-output"
|
349 |
+
)
|
350 |
+
|
351 |
+
analyze_button.click(
|
352 |
+
fn=run_analysis,
|
353 |
+
inputs=[api_key, website_url, product_category, specific_product],
|
354 |
+
outputs=analysis_output
|
355 |
+
)
|
356 |
+
|
357 |
+
return demo
|
358 |
|
359 |
if __name__ == "__main__":
|
360 |
+
print("Setting up Playwright...")
|
|
|
361 |
try:
|
362 |
+
import subprocess
|
363 |
+
subprocess.run(
|
364 |
+
["playwright", "install", "chromium"],
|
365 |
+
check=True,
|
366 |
+
capture_output=True,
|
367 |
+
text=True
|
368 |
+
)
|
369 |
except Exception as e:
|
370 |
+
print(f"Warning: Playwright setup encountered an issue: {str(e)}")
|
371 |
+
|
372 |
+
print("Starting Gradio interface...")
|
373 |
+
demo = create_gradio_interface()
|
374 |
+
demo.launch()
|