Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import os
|
3 |
+
import asyncio
|
4 |
+
import nest_asyncio
|
5 |
+
from datetime import datetime
|
6 |
+
from typing import Optional, Dict, Any
|
7 |
+
|
8 |
+
from autogen_agentchat.agents import AssistantAgent, UserProxyAgent
|
9 |
+
from autogen_agentchat.conditions import MaxMessageTermination, TextMentionTermination
|
10 |
+
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 for Jupyter compatibility
|
15 |
+
nest_asyncio.apply()
|
16 |
+
|
17 |
+
class AIShoppingAnalyzer:
|
18 |
+
def __init__(self, api_key: str):
|
19 |
+
self.api_key = api_key
|
20 |
+
self.model_client = OpenAIChatCompletionClient(model="gpt-4o")
|
21 |
+
self.termination = MaxMessageTermination(max_messages=20) | TextMentionTermination("TERMINATE")
|
22 |
+
|
23 |
+
def create_websurfer(self) -> MultimodalWebSurfer:
|
24 |
+
"""Initialize the web surfer agent for e-commerce research"""
|
25 |
+
return MultimodalWebSurfer(
|
26 |
+
name="websurfer_agent",
|
27 |
+
description="""E-commerce research specialist that:
|
28 |
+
1. Searches multiple retailers for product options
|
29 |
+
2. Compares prices and reviews
|
30 |
+
3. Checks product specifications and availability
|
31 |
+
4. Analyzes website structure and findability""",
|
32 |
+
model_client=self.model_client,
|
33 |
+
headless=True
|
34 |
+
)
|
35 |
+
|
36 |
+
def create_assistant(self) -> AssistantAgent:
|
37 |
+
"""Initialize the shopping assistant agent"""
|
38 |
+
return AssistantAgent(
|
39 |
+
name="assistant_agent",
|
40 |
+
description="E-commerce shopping advisor and website analyzer",
|
41 |
+
system_message="""You are an expert shopping assistant and e-commerce analyst. Your role is to:
|
42 |
+
1. Help find products based on user needs
|
43 |
+
2. Compare prices and features across different sites
|
44 |
+
3. Analyze website usability and product findability
|
45 |
+
4. Evaluate product presentation and information quality
|
46 |
+
5. Assess the overall e-commerce experience
|
47 |
+
|
48 |
+
When working with the websurfer_agent:
|
49 |
+
- Guide their research effectively
|
50 |
+
- Verify the information they find
|
51 |
+
- Analyze how easy it was to find products
|
52 |
+
- Evaluate product page quality
|
53 |
+
- Say 'keep going' if more research is needed
|
54 |
+
- Say 'TERMINATE' only when you have a complete analysis""",
|
55 |
+
model_client=self.model_client
|
56 |
+
)
|
57 |
+
|
58 |
+
def create_team(self, websurfer_agent: MultimodalWebSurfer, assistant_agent: AssistantAgent) -> SelectorGroupChat:
|
59 |
+
"""Set up the team of agents"""
|
60 |
+
user_proxy = UserProxyAgent(
|
61 |
+
name="user_proxy",
|
62 |
+
description="An e-commerce site owner looking for AI shopping analysis"
|
63 |
+
)
|
64 |
+
|
65 |
+
return SelectorGroupChat(
|
66 |
+
participants=[websurfer_agent, assistant_agent, user_proxy],
|
67 |
+
selector_prompt="""You are coordinating an e-commerce analysis system. The following roles are available:
|
68 |
+
{roles}
|
69 |
+
|
70 |
+
Given the conversation history {history}, select the next role from {participants}.
|
71 |
+
- The websurfer_agent searches products and analyzes website structure
|
72 |
+
- The assistant_agent evaluates findings and makes recommendations
|
73 |
+
- The user_proxy provides input when needed
|
74 |
+
|
75 |
+
Return only the role name.""",
|
76 |
+
model_client=self.model_client,
|
77 |
+
termination_condition=self.termination
|
78 |
+
)
|
79 |
+
|
80 |
+
async def analyze_site(self,
|
81 |
+
website_url: str,
|
82 |
+
product_category: str,
|
83 |
+
specific_product: Optional[str] = None) -> str:
|
84 |
+
"""Run the analysis with proper cleanup"""
|
85 |
+
websurfer = None
|
86 |
+
try:
|
87 |
+
# Set up the analysis query
|
88 |
+
query = f"""Analyze the e-commerce experience for {website_url} focusing on:
|
89 |
+
1. Product findability in the {product_category} category
|
90 |
+
2. Product information quality
|
91 |
+
3. Navigation and search functionality
|
92 |
+
4. Price visibility and comparison features"""
|
93 |
+
|
94 |
+
if specific_product:
|
95 |
+
query += f"\n5. Detailed analysis of this specific product: {specific_product}"
|
96 |
+
|
97 |
+
# Initialize agents
|
98 |
+
websurfer = self.create_websurfer()
|
99 |
+
assistant = self.create_assistant()
|
100 |
+
|
101 |
+
# Create team
|
102 |
+
team = self.create_team(websurfer, assistant)
|
103 |
+
|
104 |
+
# Run the analysis
|
105 |
+
result = []
|
106 |
+
async for message in team.run_stream(task=query):
|
107 |
+
result.append(message)
|
108 |
+
|
109 |
+
return "\n".join(result)
|
110 |
+
|
111 |
+
except Exception as e:
|
112 |
+
return f"Analysis error: {str(e)}"
|
113 |
+
finally:
|
114 |
+
if websurfer:
|
115 |
+
try:
|
116 |
+
await websurfer.close()
|
117 |
+
except Exception as e:
|
118 |
+
return f"Cleanup error: {str(e)}"
|
119 |
+
|
120 |
+
def create_gradio_interface() -> gr.Interface:
|
121 |
+
"""Create the Gradio interface for the AI Shopping Analyzer"""
|
122 |
+
|
123 |
+
def validate_api_key(api_key: str) -> bool:
|
124 |
+
"""Validate the OpenAI API key format"""
|
125 |
+
return api_key.startswith("sk-") and len(api_key) > 20
|
126 |
+
|
127 |
+
async def run_analysis(api_key: str,
|
128 |
+
website_url: str,
|
129 |
+
product_category: str,
|
130 |
+
specific_product: str) -> str:
|
131 |
+
"""Handle the analysis submission"""
|
132 |
+
if not validate_api_key(api_key):
|
133 |
+
return "Please enter a valid OpenAI API key (should start with 'sk-')"
|
134 |
+
|
135 |
+
if not website_url:
|
136 |
+
return "Please enter a website URL"
|
137 |
+
|
138 |
+
if not product_category:
|
139 |
+
return "Please specify a product category"
|
140 |
+
|
141 |
+
try:
|
142 |
+
analyzer = AIShoppingAnalyzer(api_key)
|
143 |
+
result = await analyzer.analyze_site(
|
144 |
+
website_url=website_url,
|
145 |
+
product_category=product_category,
|
146 |
+
specific_product=specific_product if specific_product else None
|
147 |
+
)
|
148 |
+
return result
|
149 |
+
except Exception as e:
|
150 |
+
return f"Error during analysis: {str(e)}"
|
151 |
+
|
152 |
+
# Create the interface
|
153 |
+
return gr.Interface(
|
154 |
+
fn=run_analysis,
|
155 |
+
inputs=[
|
156 |
+
gr.Textbox(label="OpenAI API Key", placeholder="sk-...", type="password"),
|
157 |
+
gr.Textbox(label="Website URL", placeholder="https://your-store.com"),
|
158 |
+
gr.Textbox(label="Product Category", placeholder="e.g., Electronics, Clothing, etc."),
|
159 |
+
gr.Textbox(label="Specific Product (Optional)", placeholder="e.g., Blue Widget Model X")
|
160 |
+
],
|
161 |
+
outputs=gr.Textbox(label="Analysis Results", lines=20),
|
162 |
+
title="AI Shopping Agent Analyzer",
|
163 |
+
description="""Analyze how your e-commerce site performs when the shopper is an AI agent.
|
164 |
+
This tool helps you understand your site's effectiveness for AI-powered shopping assistants.""",
|
165 |
+
theme="default",
|
166 |
+
allow_flagging="never"
|
167 |
+
)
|
168 |
+
|
169 |
+
if __name__ == "__main__":
|
170 |
+
# Create and launch the interface
|
171 |
+
iface = create_gradio_interface()
|
172 |
+
iface.launch(share=True)
|