callanwu commited on
Commit
c33c43d
·
1 Parent(s): e1876a2
Files changed (5) hide show
  1. Dockerfile +33 -0
  2. agents.py +293 -0
  3. app.py +294 -0
  4. requirements.txt +6 -0
  5. utils.py +35 -0
Dockerfile ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.8.9
2
+
3
+ WORKDIR /app
4
+
5
+ COPY ./requirements.txt /app/requirements.txt
6
+ COPY ./packages.txt /app/packages.txt
7
+
8
+ RUN apt-get update && xargs -r -a /app/packages.txt apt-get install -y && rm -rf /var/lib/apt/lists/*
9
+ RUN pip3 install --no-cache-dir -r /app/requirements.txt
10
+ RUN pip install -U crawl4ai
11
+
12
+ # Run post-installation setup
13
+ RUN crawl4ai-setup
14
+
15
+ # Verify your installation
16
+ RUN crawl4ai-doctor
17
+ # User
18
+ RUN useradd -m -u 1000 user
19
+ USER user
20
+ ENV HOME /home/user
21
+ ENV PATH $HOME/.local/bin:$PATH
22
+
23
+ WORKDIR $HOME
24
+ RUN mkdir app
25
+ WORKDIR $HOME/app
26
+ COPY . $HOME/app
27
+
28
+ EXPOSE 8501
29
+ CMD streamlit run app.py \
30
+ --server.headless true \
31
+ --server.enableCORS false \
32
+ --server.enableXsrfProtection false \
33
+ --server.fileWatcherType none
agents.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from typing import Dict, Iterator, List, Literal, Optional, Tuple, Union
3
+
4
+ from qwen_agent.agents.fncall_agent import FnCallAgent
5
+ from qwen_agent.llm import BaseChatModel
6
+ from qwen_agent.llm.schema import ASSISTANT, DEFAULT_SYSTEM_MESSAGE, Message
7
+ from qwen_agent.settings import MAX_LLM_CALL_PER_RUN
8
+ from qwen_agent.tools import BaseTool
9
+ from qwen_agent.utils.utils import format_as_text_message, merge_generate_cfgs
10
+ from openai import OpenAI
11
+ import time
12
+
13
+
14
+ TOOL_DESC = (
15
+ '{name_for_model}: Call this tool to interact with the {name_for_human} API. '
16
+ 'What is the {name_for_human} API useful for? {description_for_model} Parameters: {parameters} {args_format}')
17
+
18
+ PROMPT_REACT = """Digging through the buttons to find quailty sources and the right information. You have access to the following tools:
19
+
20
+ {tool_descs}
21
+
22
+ Use the following format:
23
+
24
+ Question: the input question you must answer
25
+ Thought: you should always think about what to do
26
+ Action: the action to take, should be one of [{tool_names}]
27
+ Action Input: the input to the action
28
+ Observation: the result of the action
29
+ Action: the action to take, should be one of [{tool_names}]
30
+ Action Input: the input to the action
31
+ Observation: the result of the action
32
+ ... (this Thought/Action/Action Input/Observation can be repeated zero or more 20 times)
33
+
34
+ Notice:
35
+ - You must take action at every step. When you take action, you must use the tool with the correct format and output the action input.
36
+ - When you can not find the information you need, you should visit page of previous page recursively until you find the information you need.
37
+ - You can not say "I'm sorry, but I cannot assist with this request."!!! You must explore.
38
+ - You do not need to provide the final answer, but you must explore.
39
+ - Action Input should be valid JSON.
40
+
41
+ Begin!
42
+
43
+ {query}
44
+ """
45
+ # def call_(self, **kwargs):
46
+ # user_prompt = self.template.format(
47
+ # query = kwargs["query"],
48
+ # document = kwargs["document"]
49
+ # )
50
+ # messages = []
51
+ # messages.append({"role": "system", "content": self.system})
52
+ # messages.append({"role": "user", "content": user_prompt})
53
+ # response = litellm.completion(
54
+ # model = "gpt-4o",
55
+ # response_format={"type": "json_object"},
56
+ # messages=messages
57
+ # )
58
+ # try:
59
+ # return eval(response.choices[0].message.content)
60
+
61
+ class Seeker(FnCallAgent):
62
+ """This agent use ReAct format to call tools"""
63
+
64
+ def __init__(self,
65
+ function_list: Optional[List[Union[str, Dict, BaseTool]]] = None,
66
+ llm: Optional[Union[Dict, BaseChatModel]] = None,
67
+ system_message: Optional[str] = DEFAULT_SYSTEM_MESSAGE,
68
+ name: Optional[str] = None,
69
+ description: Optional[str] = None,
70
+ files: Optional[List[str]] = None,
71
+ **kwargs):
72
+ super().__init__(function_list=function_list,
73
+ llm=llm,
74
+ system_message=system_message,
75
+ name=name,
76
+ description=description,
77
+ files=files,
78
+ **kwargs)
79
+ self.extra_generate_cfg = merge_generate_cfgs(
80
+ base_generate_cfg=self.extra_generate_cfg,
81
+ new_generate_cfg={'stop': ['Observation:', 'Observation:\n']},
82
+ )
83
+ self.client = OpenAI(
84
+ api_key=llm['api_key'],
85
+ base_url=llm['model_server'],
86
+ )
87
+ self.llm_cfg = llm
88
+ self.momery = []
89
+
90
+ def observation_information_extraction(self, query, observation):
91
+ SYSTEM_PROMPT = """You are an information extraction agent. Your task is to analyze the given observation and extract information relevant to the current query. You need to decide if the observation contains useful information for the query. If it does, return a JSON object with a "usefulness" value of true and an "information" field with the relevant details. If not, return a JSON object with a "usefulness" value of false.
92
+
93
+ **Input:**
94
+ - Query: "<Query>"
95
+ - Observation: "<Current Observation>"
96
+
97
+ **Output (JSON):**
98
+ {
99
+ "usefulness": true,
100
+ "information": "<Extracted Useful Information> using string format"
101
+ }
102
+ Or, if the observation does not contain useful information:
103
+ {
104
+ "usefulness": false
105
+ }
106
+ Only respond with valid JSON.
107
+
108
+ """
109
+ user_prompt = "- Query: {query}\n- Observation: {observation}".format(query=query, observation=observation)
110
+ # print(user_prompt)
111
+ messages = [
112
+ {'role': 'system', 'content': SYSTEM_PROMPT},
113
+ {'role': 'user', 'content': user_prompt}]
114
+ max_retries = 10
115
+ for attempt in range(max_retries):
116
+ try:
117
+ response = self.client.chat.completions.create(
118
+ model=self.llm_cfg['model'],
119
+ response_format={"type": "json_object"},
120
+ messages=messages
121
+ )
122
+ print(response.choices[0].message.content)
123
+ # response_content = json.loads(response.choices[0].message.content)
124
+ if "true" in response.choices[0].message.content:
125
+ try:
126
+ return json.loads(response.choices[0].message.content)["information"]
127
+ except:
128
+ return response.choices[0].message.content
129
+ else:
130
+ return None
131
+ except Exception as e:
132
+ print(e)
133
+ if attempt < max_retries - 1:
134
+ time.sleep(1 * (2 ** attempt)) # Exponential backoff
135
+ else:
136
+ raise e # Raise the exception if the last retry fails
137
+
138
+ def critic_information(self, query, memory):
139
+ SYSTEM_PROMPT = """You are a query answering agent. Your task is to evaluate whether the accumulated useful information is sufficient to answer the current query. If it is sufficient, return a JSON object with a "judge" value of true and an "answer" field with the answer. If the information is insufficient, return a JSON object with a "judge" value of false.
140
+
141
+ **Input:**
142
+ - Query: "<Query>"
143
+ - Accumulated Information: "<Accumulated Useful Information>"
144
+
145
+
146
+ **Output (JSON):**
147
+ {
148
+ "judge": true,
149
+ "answer": "<Generated Answer> using string format"
150
+ }
151
+ Or, if the information is insufficient to answer the query:
152
+ {
153
+ "judge": false
154
+ }
155
+ Only respond with valid JSON.
156
+ """
157
+ memory = "-".join(memory)
158
+ user_prompt = "- Query: {query}\n- Accumulated Information: {memory}".format(query = query, memory=memory)
159
+ messages = [
160
+ {'role': 'system', 'content': SYSTEM_PROMPT},
161
+ {'role': 'user', 'content': user_prompt}]
162
+ response = self.client.chat.completions.create(
163
+ model=self.llm_cfg['model'],
164
+ response_format={"type": "json_object"},
165
+ messages=messages
166
+ )
167
+ max_retries = 10
168
+ for attempt in range(max_retries):
169
+ try:
170
+ response = self.client.chat.completions.create(
171
+ model=self.llm_cfg['model'],
172
+ response_format={"type": "json_object"},
173
+ messages=messages
174
+ )
175
+ print(response.choices[0].message.content)
176
+ if "true" in response.choices[0].message.content:
177
+ try:
178
+ return json.loads(response.choices[0].message.content)["answer"]
179
+ except:
180
+ return response.choices[0].message.content
181
+ else:
182
+ return None
183
+
184
+ except Exception as e:
185
+ print(e)
186
+ if attempt < max_retries - 1:
187
+ time.sleep(1 * (2 ** attempt)) # Exponential backoff
188
+ else:
189
+ raise e # Raise the exception if the last retry fails
190
+
191
+ def _run(self, messages: List[Message], lang: Literal['en', 'zh'] = 'en', **kwargs) -> Iterator[List[Message]]:
192
+ text_messages = self._prepend_react_prompt(messages, lang=lang)
193
+ # print("==========================")
194
+ # print(text_messages)
195
+ # print("==========================")
196
+ num_llm_calls_available = MAX_LLM_CALL_PER_RUN
197
+ response: str = 'Thought: '
198
+ query = self.llm_cfg["query"]
199
+ action_count = self.llm_cfg.get("action_count", MAX_LLM_CALL_PER_RUN)
200
+ num_llm_calls_available = action_count
201
+ while num_llm_calls_available > 0:
202
+ num_llm_calls_available -= 1
203
+ # print(num_llm_calls_available)
204
+ # Display the streaming response
205
+ output = []
206
+ for output in self._call_llm(messages=text_messages):
207
+ if output:
208
+ yield [Message(role=ASSISTANT, content=output[-1].content)]
209
+ # print(output)
210
+ # Accumulate the current response
211
+ if output:
212
+ response += output[-1].content
213
+
214
+ has_action, action, action_input, thought = self._detect_tool("\n"+output[-1].content)
215
+ if not has_action:
216
+ if "Final Answer: " in output[-1].content:
217
+ break
218
+ else:
219
+ continue
220
+
221
+ # Add the tool result
222
+ query = self.llm_cfg["query"]
223
+ observation = self._call_tool(action, action_input, messages=messages, **kwargs)
224
+ stage1 = self.observation_information_extraction(query, observation)
225
+ if stage1:
226
+ self.momery.append(stage1+"\n")
227
+ if len(self.momery) > 1:
228
+ yield [Message(role=ASSISTANT, content= "Memory:\n" + "-".join(self.momery)+"\"}")]
229
+ else:
230
+ yield [Message(role=ASSISTANT, content= "Memory:\n" + "-" + self.momery[0]+"\"}")]
231
+ stage2 = self.critic_information(query, self.momery)
232
+ if stage2:
233
+ response = f'Final Answer: {stage2}'
234
+ yield [Message(role=ASSISTANT, content=response)]
235
+ break
236
+
237
+
238
+ observation = f'\nObservation: {observation}\nThought: '
239
+ response += observation
240
+ # yield [Message(role=ASSISTANT, content=response)]
241
+
242
+ if (not text_messages[-1].content.endswith('\nThought: ')) and (not thought.startswith('\n')):
243
+ # Add the '\n' between '\nQuestion:' and the first 'Thought:'
244
+ text_messages[-1].content += '\n'
245
+ if action_input.startswith('```'):
246
+ # Add a newline for proper markdown rendering of code
247
+ action_input = '\n' + action_input
248
+ text_messages[-1].content += thought + f'\nAction: {action}\nAction Input: {action_input}' + observation
249
+ # print(text_messages[-1].content)
250
+
251
+ def _prepend_react_prompt(self, messages: List[Message], lang: Literal['en', 'zh']) -> List[Message]:
252
+ tool_descs = []
253
+ for f in self.function_map.values():
254
+ function = f.function
255
+ name = function.get('name', None)
256
+ name_for_human = function.get('name_for_human', name)
257
+ name_for_model = function.get('name_for_model', name)
258
+ assert name_for_human and name_for_model
259
+ args_format = function.get('args_format', '')
260
+ tool_descs.append(
261
+ TOOL_DESC.format(name_for_human=name_for_human,
262
+ name_for_model=name_for_model,
263
+ description_for_model=function['description'],
264
+ parameters=json.dumps(function['parameters'], ensure_ascii=False),
265
+ args_format=args_format).rstrip())
266
+ tool_descs = '\n\n'.join(tool_descs)
267
+ tool_names = ','.join(tool.name for tool in self.function_map.values())
268
+ text_messages = [format_as_text_message(m, add_upload_info=True, lang=lang) for m in messages]
269
+ text_messages[-1].content = PROMPT_REACT.format(
270
+ tool_descs=tool_descs,
271
+ tool_names=tool_names,
272
+ query=text_messages[-1].content,
273
+ )
274
+ return text_messages
275
+
276
+ def _detect_tool(self, text: str) -> Tuple[bool, str, str, str]:
277
+ special_func_token = '\nAction:'
278
+ special_args_token = '\nAction Input:'
279
+ special_obs_token = '\nObservation:'
280
+ func_name, func_args = None, None
281
+ i = text.rfind(special_func_token)
282
+ j = text.rfind(special_args_token)
283
+ k = text.rfind(special_obs_token)
284
+ if 0 <= i < j: # If the text has `Action` and `Action input`,
285
+ if k < j: # but does not contain `Observation`,
286
+ # then it is likely that `Observation` is ommited by the LLM,
287
+ # because the output text may have discarded the stop word.
288
+ text = text.rstrip() + special_obs_token # Add it back.
289
+ k = text.rfind(special_obs_token)
290
+ func_name = text[i + len(special_func_token):j].strip()
291
+ func_args = text[j + len(special_args_token):k].strip()
292
+ text = text[:i] # Return the response before tool call, i.e., `Thought`
293
+ return (func_name is not None), func_name, func_args, text
app.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ if 'form_1_text' not in st.session_state:
143
+ st.session_state.form_1_text = ""
144
+ if 'form_2_text' not in st.session_state:
145
+ st.session_state.form_2_text = ""
146
+
147
+ with st.sidebar:
148
+ MAX_ROUNDS = st.number_input('Max Count Count:', min_value=1, max_value=15, value=10, step=1)
149
+ website_example = st.sidebar.selectbox('Example Website:', ['https://2025.aclweb.org/'])
150
+ 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?"])
151
+
152
+ col1, col2 = st.columns([3, 1])
153
+ with col1:
154
+ with st.form(key='my_form'):
155
+ form_1_text = st.text_area("**🤯Memory**", value="No Memory", height=68)
156
+ website = st.text_area('👉Website', value=website_example, placeholder='Input the website you want to walk through.')
157
+ query = st.text_area('🤔Query', value=question_example, placeholder='Input the query you want to ask.')
158
+ submit_button = st.form_submit_button('Start!!!!')
159
+
160
+ if submit_button:
161
+ if website and query:
162
+ tools = ["visit_page"]
163
+ K = 15
164
+ llm_cfg["query"] = query
165
+ bot = Seeker(llm=llm_cfg,
166
+ function_list=tools,
167
+ )
168
+ BUTTON_URL_ADIC = {}
169
+ ROOT_URL = website
170
+ with open("ROOT_URL.txt", "w") as f:
171
+ f.write("https://2025.aclweb.org/")
172
+ messages = [] # This stores the chat history.
173
+ visited_links = []
174
+ start_prompt = "query:\n{query} \nofficial website:\n{website}".format(query=query, website=website)
175
+ # print(website_adic[query])
176
+ st.markdown('**🌐Now visit**')
177
+ st.write(website)
178
+ html, markdown, screenshot = asyncio.run(get_info(website))
179
+ with col2:
180
+ st.markdown('**📸Observation**')
181
+ if screenshot:
182
+ st.session_state.image_index = 0
183
+ print("get screenshot!")
184
+ image_folder = "images/"
185
+ with open(image_folder+str(st.session_state.image_index)+".png", "wb") as f:
186
+ f.write(base64.b64decode(screenshot))
187
+ image_files = os.listdir(image_folder)
188
+ image_files = [f for f in image_files if f.endswith(('.png', '.jpg', '.jpeg'))]
189
+ image_path = os.path.join(image_folder, image_files[st.session_state.image_index])
190
+ image = Image.open(image_folder+str(st.session_state.image_index)+".png")
191
+ st.image(image, caption='Start Obervation', width=400)
192
+
193
+ buttons = extract_links_with_text(html)
194
+ response = "website information:\n\n" + markdown + "\n\n"
195
+ response += "clickable button:\n\n" + buttons + "\n\nEach button is wrapped in a <button> tag"
196
+ start_prompt += "\nObservation:" + response + "\n\n"
197
+ messages.append({'role': 'user', 'content':start_prompt})
198
+ cnt = 0
199
+ response = []
200
+ response = bot.run(messages=messages, lang = "zh")
201
+ for i in response:
202
+ if "\"}" in i[0]["content"] and "Memory" not in i[0]["content"]:
203
+ st.markdown('**💭Thoughts**')
204
+ st.markdown(i[0]["content"].split("Action")[0])
205
+ elif "\"}" in i[0]["content"] and "Memory" in i[0]["content"]:
206
+ st.text_area('**🤯Memory Update**', i[0]["content"][:-2])
207
+ if "Final Answer" in i[0]["content"]:
208
+ st.session_state.answer = i[0]["content"]
209
+ st.markdown('**🙋Anwser**')
210
+ st.write(st.session_state.answer)
211
+ else:
212
+ st.error('Please input the website and query.')
213
+
214
+ def get_content_between_a_b(start_tag, end_tag, text):
215
+ """
216
+
217
+ Args:
218
+ start_tag (str): start_tag
219
+ end_tag (str): end_tag
220
+ text (str): complete sentence
221
+
222
+ Returns:
223
+ str: the content between start_tag and end_tag
224
+ """
225
+ extracted_text = ""
226
+ start_index = text.find(start_tag)
227
+ while start_index != -1:
228
+ end_index = text.find(end_tag, start_index + len(start_tag))
229
+ if end_index != -1:
230
+ extracted_text += text[start_index + len(start_tag) : end_index] + " "
231
+ start_index = text.find(start_tag, end_index + len(end_tag))
232
+ else:
233
+ break
234
+
235
+ return extracted_text.strip()
236
+
237
+
238
+
239
+ @register_tool('visit_page',allow_overwrite=True)
240
+ class VisitPage(BaseTool):
241
+ 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.'
242
+ parameters = [{
243
+ 'name': 'button',
244
+ 'type': 'string',
245
+ 'description': 'the button you want to click',
246
+ 'required': True
247
+ }]
248
+
249
+
250
+ def call(self, params: str, **kwargs) -> str:
251
+ if not params.strip().endswith("}"):
252
+ if "}" in params.strip():
253
+ params = "{" + get_content_between_a_b("{","}",params) + "}"
254
+ else:
255
+ if not params.strip().endswith("\""):
256
+ params = params.strip() + "\"}"
257
+ else:
258
+ params = params.strip() + "}"
259
+ params = "{" + get_content_between_a_b("{","}",params) + "}"
260
+ if 'button' in json5.loads(params):
261
+ # `params` are the arguments generated by the LLM agent.
262
+ with open("BUTTON_URL_ADIC.json", "r") as f:
263
+ BUTTON_URL_ADIC = json.load(f)
264
+ if json5.loads(params)['button'].replace("<button>","") in BUTTON_URL_ADIC:
265
+ st.markdown('**👆Click Button**')
266
+ st.write(json5.loads(params)['button'].replace("<button>",""))
267
+ url = BUTTON_URL_ADIC[json5.loads(params)['button'].replace("<button>","")]
268
+ html, markdown, screenshot = asyncio.run(get_info(url))
269
+ st.markdown('**🌐Now Visit**')
270
+ st.write(url)
271
+ with col2:
272
+ st.write("")
273
+ st.markdown('**📸Observation**')
274
+ if screenshot:
275
+ print("get screenshot!")
276
+ image_folder = "images/"
277
+ with open(image_folder+str(st.session_state.image_index+1)+".png", "wb") as f:
278
+ f.write(base64.b64decode(screenshot))
279
+ st.session_state.image_index += 1
280
+ # st.write(st.session_state.image_index)
281
+ image = Image.open(image_folder+str(st.session_state.image_index)+".png")
282
+ st.image(image, caption='Step ' + str(st.session_state.image_index) + ' Obervation', width=400)
283
+ response_bottons = extract_links_with_text(html)
284
+ response_content = markdown
285
+ if response_content:
286
+ response = "当前页面的信息是:\n\n" + response_content + "\n\n"
287
+ else:
288
+ response = "当前页面的信息不可访问\n\n"
289
+ response += "可以点击的按钮有\n\n" + response_bottons + "\n\n每个按钮由<button>..<button>包裹\n"
290
+ return response
291
+ else:
292
+ return "the button can not be clicked, please retry a new botton!"
293
+ else:
294
+ return "your input is invalid, plase output the action input correctly!"
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ crawl4ai
2
+ requests
3
+ json5
4
+ pillow
5
+ beautifulsoup4
6
+ qwen-agent
utils.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import urllib.parse
2
+ from bs4 import BeautifulSoup
3
+ from crawl4ai import AsyncWebCrawler
4
+ import re
5
+ import asyncio
6
+
7
+ def process_url(url, sub_url):
8
+ return urllib.parse.urljoin(url, sub_url)
9
+
10
+
11
+ def clean_markdown(res):
12
+ pattern = r'\[.*?\]\(.*?\)'
13
+ try:
14
+ # 使用 re.sub() 将匹配的内容替换为空字符
15
+ result = re.sub(pattern, '', res)
16
+ url_pattern = pattern = r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
17
+ result = re.sub(url_pattern, '', result)
18
+ result = result.replace("* \n","")
19
+ result = re.sub(r"\n\n+", "\n", result)
20
+ return result
21
+ except Exception:
22
+ return res
23
+
24
+ async def get_info(url, screentshot = True) -> str:
25
+ async with AsyncWebCrawler() as crawler:
26
+ if screentshot:
27
+ result = await crawler.arun(url, screenshot=screentshot)
28
+ # print(result)
29
+ return result.html, clean_markdown(result.markdown), result.screenshot
30
+ else:
31
+ result = await crawler.arun(url, screenshot=screentshot)
32
+ return result.html, clean_markdown(result.markdown)
33
+
34
+ if __name__ == "__main__":
35
+ asyncio.run(get_info("https://2024.aclweb.org/"))