callanwu commited on
Commit
60058de
·
1 Parent(s): d1fa16d
Files changed (2) hide show
  1. agents.py +293 -0
  2. utils.py +35 -0
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
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/"))