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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import streamlit as st
|
2 |
+
import os
|
3 |
+
import json5
|
4 |
+
from agents import Seeker
|
5 |
+
from qwen_agent.tools.base import BaseTool, register_tool
|
6 |
+
import os
|
7 |
+
import re
|
8 |
+
import json
|
9 |
+
import asyncio
|
10 |
+
from utils import *
|
11 |
+
import base64
|
12 |
+
from PIL import Image
|
13 |
+
import subprocess
|
14 |
+
def run_command(command):
|
15 |
+
try:
|
16 |
+
# Run the shell command
|
17 |
+
result = subprocess.run(command, shell=True, text=True, capture_output=True)
|
18 |
+
# Print the output of the command
|
19 |
+
print("Command Output:")
|
20 |
+
print(result.stdout)
|
21 |
+
# Print the error if there is any
|
22 |
+
if result.stderr:
|
23 |
+
print("Command Error:")
|
24 |
+
print(result.stderr)
|
25 |
+
except Exception as e:
|
26 |
+
print(f"An error occurred: {e}")
|
27 |
+
|
28 |
+
# Run crawl4ai-setup
|
29 |
+
def init_crawl4ai():
|
30 |
+
try:
|
31 |
+
# 使用 subprocess 执行命令
|
32 |
+
result = subprocess.run(
|
33 |
+
["python", "-m", "playwright", "install", "--with-deps", "chromium"],
|
34 |
+
check=True, # 如果命令失败,抛出 CalledProcessError
|
35 |
+
text=True, # 输出以文本形式返回
|
36 |
+
capture_output=True # 捕获输出
|
37 |
+
)
|
38 |
+
print("Success!")
|
39 |
+
print(result.stdout)
|
40 |
+
except subprocess.CalledProcessError as e:
|
41 |
+
print("Error!")
|
42 |
+
print(e.stderr)
|
43 |
+
|
44 |
+
model = "qwen-max"
|
45 |
+
llm_cfg = {
|
46 |
+
'model': model,
|
47 |
+
'api_key': os.getenv('API_KEY'),
|
48 |
+
'model_server': "https://dashscope.aliyuncs.com/compatible-mode/v1" ,
|
49 |
+
'generate_cfg': {
|
50 |
+
'top_p': 0.8,
|
51 |
+
'max_input_tokens': 120000,
|
52 |
+
'max_retries': 20
|
53 |
+
},
|
54 |
+
}
|
55 |
+
|
56 |
+
def extract_links_with_text(html):
|
57 |
+
with open("ROOT_URL.txt", "r") as f:
|
58 |
+
ROOT_URL = f.read()
|
59 |
+
soup = BeautifulSoup(html, 'html.parser')
|
60 |
+
links = []
|
61 |
+
|
62 |
+
# 常规的<a>标签
|
63 |
+
for a_tag in soup.find_all('a', href=True):
|
64 |
+
url = a_tag['href']
|
65 |
+
text = ''.join(a_tag.stripped_strings)
|
66 |
+
|
67 |
+
# 过滤掉图片链接和javascript链接
|
68 |
+
if text and "javascript" not in url and not url.endswith(('.jpg', '.png', '.gif', '.jpeg', '.pdf')):
|
69 |
+
if process_url(ROOT_URL, url).startswith(ROOT_URL):
|
70 |
+
links.append({'url': process_url(ROOT_URL, url), 'text': text})
|
71 |
+
|
72 |
+
# 特殊情况1: 使用onclick事件的链接
|
73 |
+
for a_tag in soup.find_all('a', onclick=True):
|
74 |
+
onclick_text = a_tag['onclick']
|
75 |
+
text = ''.join(a_tag.stripped_strings)
|
76 |
+
|
77 |
+
# 使用正则表达式提取url
|
78 |
+
match = re.search(r"window\.location\.href='([^']*)'", onclick_text)
|
79 |
+
if match:
|
80 |
+
url = match.group(1)
|
81 |
+
if url and text and not url.endswith(('.jpg', '.png', '.gif', '.jpeg', '.pdf')):
|
82 |
+
if process_url(ROOT_URL, url).startswith(ROOT_URL):
|
83 |
+
links.append({'url': process_url(ROOT_URL, url), 'text': text})
|
84 |
+
|
85 |
+
# 特殊情况2: data-url属性的链接
|
86 |
+
for a_tag in soup.find_all('a', attrs={'data-url': True}):
|
87 |
+
url = a_tag['data-url']
|
88 |
+
text = ''.join(a_tag.stripped_strings)
|
89 |
+
if url and text and not url.endswith(('.jpg', '.png', '.gif', '.jpeg', '.pdf')):
|
90 |
+
if process_url(ROOT_URL, url).startswith(ROOT_URL):
|
91 |
+
links.append({'url': process_url(ROOT_URL, url), 'text': text})
|
92 |
+
|
93 |
+
# 特殊情况3: class为"herf-mask"的链接
|
94 |
+
for a_tag in soup.find_all('a', class_='herf-mask'):
|
95 |
+
url = a_tag.get('href')
|
96 |
+
text = a_tag.get('title') or ''.join(a_tag.stripped_strings)
|
97 |
+
if url and text and not url.endswith(('.jpg', '.png', '.gif', '.jpeg', '.pdf')):
|
98 |
+
if process_url(ROOT_URL, url).startswith(ROOT_URL):
|
99 |
+
links.append({'url': process_url(ROOT_URL, url), 'text': text})
|
100 |
+
# 特殊情况4: <button>标签作为链接
|
101 |
+
for button in soup.find_all('button', onclick=True):
|
102 |
+
onclick_text = button['onclick']
|
103 |
+
text = button.get('title') or button.get('aria-label') or ''.join(button.stripped_strings)
|
104 |
+
match = re.search(r"window\.location\.href='([^']*)'", onclick_text)
|
105 |
+
if match:
|
106 |
+
url = match.group(1)
|
107 |
+
if url and text:
|
108 |
+
if process_url(ROOT_URL, url).startswith(ROOT_URL):
|
109 |
+
links.append({'url': process_url(ROOT_URL, url), 'text': text})
|
110 |
+
|
111 |
+
# 过滤重复链接
|
112 |
+
if "Welcome!" in html:
|
113 |
+
print(links)
|
114 |
+
links.remove({'url': 'https://2025.aclweb.org/calls/industry_track/', 'text': 'Call for Industry Track'})
|
115 |
+
unique_links = {f"{item['url']}_{item['text']}": item for item in links} # 去重
|
116 |
+
|
117 |
+
if not os.path.exists("BUTTON_URL_ADIC.json"):
|
118 |
+
with open("BUTTON_URL_ADIC.json", "w") as f:
|
119 |
+
json.dump({}, f)
|
120 |
+
with open("BUTTON_URL_ADIC.json", "r") as f:
|
121 |
+
BUTTON_URL_ADIC = json.load(f)
|
122 |
+
for temp in list(unique_links.values()):
|
123 |
+
BUTTON_URL_ADIC[temp["text"]] = temp["url"]
|
124 |
+
|
125 |
+
with open("BUTTON_URL_ADIC.json", "w") as f:
|
126 |
+
json.dump(BUTTON_URL_ADIC, f)
|
127 |
+
info = ""
|
128 |
+
for i in list(unique_links.values()):
|
129 |
+
info += "<button>" + i["text"] + "<button>" + "\n"
|
130 |
+
return info
|
131 |
+
|
132 |
+
|
133 |
+
flag = 0
|
134 |
+
if __name__ == "__main__":
|
135 |
+
st.title('🤝WebWalker')
|
136 |
+
st.markdown("### 📚Introduction")
|
137 |
+
st.markdown("👋Welcome to WebWalker! WebWalker is a web-based conversational agent that can help you navigate websites and find information.")
|
138 |
+
st.markdown("📑The paper of WebWalker is available at [arXiv]().")
|
139 |
+
st.markdown("✨You can bulid your own WebWalker by following the [instruction](https://github.com/Alibaba-NLP/WebWalker).")
|
140 |
+
st.markdown("🙋If you have any questions, please feel free to contact us via the [Github issue](https://github.com/Alibaba-NLP/WebWalker/issue).")
|
141 |
+
st.markdown("### 🚀Let's start exploring the website!")
|
142 |
+
st.text("⌛️When you first use this app, you need to wait for a while to initialize the environment. Please be patient.")
|
143 |
+
if flag == 0:
|
144 |
+
init_crawl4ai()
|
145 |
+
st.text("✅Initialization is complete. You can start using the app now.")
|
146 |
+
flag = 1
|
147 |
+
else:
|
148 |
+
st.text("✅Initialization is complete. You can start using the app now.")
|
149 |
+
if 'form_1_text' not in st.session_state:
|
150 |
+
st.session_state.form_1_text = ""
|
151 |
+
if 'form_2_text' not in st.session_state:
|
152 |
+
st.session_state.form_2_text = ""
|
153 |
+
|
154 |
+
with st.sidebar:
|
155 |
+
MAX_ROUNDS = st.number_input('Max Count Count:', min_value=1, max_value=15, value=10, step=1)
|
156 |
+
website_example = st.sidebar.selectbox('Example Website:', ['https://2025.aclweb.org/'])
|
157 |
+
question_example = st.sidebar.selectbox('Example Query:', ["When is the paper submission deadline for ACL 2025 Industry Track, and what is the venue specific address?", "Who is the general chair of ACL 2025?", "What is the spcial theme of ACL 2025?"])
|
158 |
+
|
159 |
+
col1, col2 = st.columns([3, 1])
|
160 |
+
with col1:
|
161 |
+
with st.form(key='my_form'):
|
162 |
+
form_1_text = st.text_area("**🤯Memory**", value="No Memory", height=68)
|
163 |
+
website = st.text_area('👉Website', value=website_example, placeholder='Input the website you want to walk through.')
|
164 |
+
query = st.text_area('🤔Query', value=question_example, placeholder='Input the query you want to ask.')
|
165 |
+
submit_button = st.form_submit_button('Start!!!!')
|
166 |
+
|
167 |
+
if submit_button:
|
168 |
+
if website and query:
|
169 |
+
tools = ["visit_page"]
|
170 |
+
K = 15
|
171 |
+
llm_cfg["query"] = query
|
172 |
+
bot = Seeker(llm=llm_cfg,
|
173 |
+
function_list=tools,
|
174 |
+
)
|
175 |
+
BUTTON_URL_ADIC = {}
|
176 |
+
ROOT_URL = website
|
177 |
+
with open("ROOT_URL.txt", "w") as f:
|
178 |
+
f.write("https://2025.aclweb.org/")
|
179 |
+
messages = [] # This stores the chat history.
|
180 |
+
visited_links = []
|
181 |
+
start_prompt = "query:\n{query} \nofficial website:\n{website}".format(query=query, website=website)
|
182 |
+
# print(website_adic[query])
|
183 |
+
st.markdown('**🌐Now visit**')
|
184 |
+
st.write(website)
|
185 |
+
html, markdown, screenshot = asyncio.run(get_info(website))
|
186 |
+
with col2:
|
187 |
+
st.markdown('**📸Observation**')
|
188 |
+
if screenshot:
|
189 |
+
st.session_state.image_index = 0
|
190 |
+
print("get screenshot!")
|
191 |
+
image_folder = "images/"
|
192 |
+
with open(image_folder+str(st.session_state.image_index)+".png", "wb") as f:
|
193 |
+
f.write(base64.b64decode(screenshot))
|
194 |
+
image_files = os.listdir(image_folder)
|
195 |
+
image_files = [f for f in image_files if f.endswith(('.png', '.jpg', '.jpeg'))]
|
196 |
+
image_path = os.path.join(image_folder, image_files[st.session_state.image_index])
|
197 |
+
image = Image.open(image_folder+str(st.session_state.image_index)+".png")
|
198 |
+
st.image(image, caption='Start Obervation', width=400)
|
199 |
+
|
200 |
+
buttons = extract_links_with_text(html)
|
201 |
+
response = "website information:\n\n" + markdown + "\n\n"
|
202 |
+
response += "clickable button:\n\n" + buttons + "\n\nEach button is wrapped in a <button> tag"
|
203 |
+
start_prompt += "\nObservation:" + response + "\n\n"
|
204 |
+
messages.append({'role': 'user', 'content':start_prompt})
|
205 |
+
cnt = 0
|
206 |
+
response = []
|
207 |
+
response = bot.run(messages=messages, lang = "zh")
|
208 |
+
for i in response:
|
209 |
+
if "\"}" in i[0]["content"] and "Memory" not in i[0]["content"]:
|
210 |
+
st.markdown('**💭Thoughts**')
|
211 |
+
st.markdown(i[0]["content"].split("Action")[0])
|
212 |
+
elif "\"}" in i[0]["content"] and "Memory" in i[0]["content"]:
|
213 |
+
st.text_area('**🤯Memory Update**', i[0]["content"][:-2])
|
214 |
+
if "Final Answer" in i[0]["content"]:
|
215 |
+
st.session_state.answer = i[0]["content"]
|
216 |
+
st.markdown('**🙋Anwser**')
|
217 |
+
st.write(st.session_state.answer)
|
218 |
+
else:
|
219 |
+
st.error('Please input the website and query.')
|
220 |
+
|
221 |
+
def get_content_between_a_b(start_tag, end_tag, text):
|
222 |
+
"""
|
223 |
+
|
224 |
+
Args:
|
225 |
+
start_tag (str): start_tag
|
226 |
+
end_tag (str): end_tag
|
227 |
+
text (str): complete sentence
|
228 |
+
|
229 |
+
Returns:
|
230 |
+
str: the content between start_tag and end_tag
|
231 |
+
"""
|
232 |
+
extracted_text = ""
|
233 |
+
start_index = text.find(start_tag)
|
234 |
+
while start_index != -1:
|
235 |
+
end_index = text.find(end_tag, start_index + len(start_tag))
|
236 |
+
if end_index != -1:
|
237 |
+
extracted_text += text[start_index + len(start_tag) : end_index] + " "
|
238 |
+
start_index = text.find(start_tag, end_index + len(end_tag))
|
239 |
+
else:
|
240 |
+
break
|
241 |
+
|
242 |
+
return extracted_text.strip()
|
243 |
+
|
244 |
+
|
245 |
+
|
246 |
+
@register_tool('visit_page',allow_overwrite=True)
|
247 |
+
class VisitPage(BaseTool):
|
248 |
+
description = 'A tool analyzes the content of a webpage and extracts buttons associated with sublinks. Simply input the button which you want to explore, and the tool will return both the markdown-formatted content of the corresponding page of button and a list of new clickable buttons found on the new page.'
|
249 |
+
parameters = [{
|
250 |
+
'name': 'button',
|
251 |
+
'type': 'string',
|
252 |
+
'description': 'the button you want to click',
|
253 |
+
'required': True
|
254 |
+
}]
|
255 |
+
|
256 |
+
|
257 |
+
def call(self, params: str, **kwargs) -> str:
|
258 |
+
if not params.strip().endswith("}"):
|
259 |
+
if "}" in params.strip():
|
260 |
+
params = "{" + get_content_between_a_b("{","}",params) + "}"
|
261 |
+
else:
|
262 |
+
if not params.strip().endswith("\""):
|
263 |
+
params = params.strip() + "\"}"
|
264 |
+
else:
|
265 |
+
params = params.strip() + "}"
|
266 |
+
params = "{" + get_content_between_a_b("{","}",params) + "}"
|
267 |
+
if 'button' in json5.loads(params):
|
268 |
+
# `params` are the arguments generated by the LLM agent.
|
269 |
+
with open("BUTTON_URL_ADIC.json", "r") as f:
|
270 |
+
BUTTON_URL_ADIC = json.load(f)
|
271 |
+
if json5.loads(params)['button'].replace("<button>","") in BUTTON_URL_ADIC:
|
272 |
+
st.markdown('**👆Click Button**')
|
273 |
+
st.write(json5.loads(params)['button'].replace("<button>",""))
|
274 |
+
url = BUTTON_URL_ADIC[json5.loads(params)['button'].replace("<button>","")]
|
275 |
+
html, markdown, screenshot = asyncio.run(get_info(url))
|
276 |
+
st.markdown('**🌐Now Visit**')
|
277 |
+
st.write(url)
|
278 |
+
with col2:
|
279 |
+
st.write("")
|
280 |
+
st.markdown('**📸Observation**')
|
281 |
+
if screenshot:
|
282 |
+
print("get screenshot!")
|
283 |
+
image_folder = "images/"
|
284 |
+
with open(image_folder+str(st.session_state.image_index+1)+".png", "wb") as f:
|
285 |
+
f.write(base64.b64decode(screenshot))
|
286 |
+
st.session_state.image_index += 1
|
287 |
+
# st.write(st.session_state.image_index)
|
288 |
+
image = Image.open(image_folder+str(st.session_state.image_index)+".png")
|
289 |
+
st.image(image, caption='Step ' + str(st.session_state.image_index) + ' Obervation', width=400)
|
290 |
+
response_bottons = extract_links_with_text(html)
|
291 |
+
response_content = markdown
|
292 |
+
if response_content:
|
293 |
+
response = "当前页面的信息是:\n\n" + response_content + "\n\n"
|
294 |
+
else:
|
295 |
+
response = "当前页面的信息不可访问\n\n"
|
296 |
+
response += "可以点击的按钮有\n\n" + response_bottons + "\n\n每个按钮由<button>..<button>包裹\n"
|
297 |
+
return response
|
298 |
+
else:
|
299 |
+
return "the button can not be clicked, please retry a new botton!"
|
300 |
+
else:
|
301 |
+
return "your input is invalid, plase output the action input correctly!"
|
requirements.txt
CHANGED
@@ -1,3 +1,6 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
|
|
|
|
|
|
|
1 |
+
crawl4ai
|
2 |
+
requests
|
3 |
+
json5
|
4 |
+
pillow
|
5 |
+
beautifulsoup4
|
6 |
+
qwen-agent
|