forked from poe-platform/server-bot-quick-start
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathbot_PythonAgent.py
436 lines (360 loc) · 13.7 KB
/
bot_PythonAgent.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
"""
BOT_NAME="PythonAgent"; modal deploy --name $BOT_NAME bot_${BOT_NAME}.py; curl -X POST https://api.poe.com/bot/fetch_settings/$BOT_NAME/$POE_ACCESS_KEY
Test message:
download and save wine dataset
list directory
"""
from __future__ import annotations
import re
import textwrap
from typing import AsyncIterable, Optional
import modal
import requests
from fastapi_poe import PoeBot
from fastapi_poe.client import MetaMessage, stream_request
from fastapi_poe.types import (
PartialResponse,
ProtocolMessage,
QueryRequest,
SettingsRequest,
SettingsResponse,
)
from modal import Image, Sandbox
PYTHON_AGENT_SYSTEM_PROMPT = """
You write the Python code for me
When you return Python code
- Encapsulate all Python code within triple backticks (i.e ```python) with newlines.
- The Python code should either print something or plot something
- The Python code should not use input()
I have already installed these Python packages
numpy
scipy
matplotlib
basemap (in mpl_toolkits.basemap)
scikit-learn
pandas (prefer pandas over csv)
ortools
torch
torchvision
tensorflow
transformers
opencv-python-headless
nltk
openai
requests
beautifulsoup4
newspaper3k
feedparser
sympy
yfinance
"""
# probably there is a better method to retain memory than to pickle
CODE_WITH_WRAPPERS = """\
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import savefig
def save_image(filename):
def decorator(func):
def wrapper(*args, **kwargs):
func(*args, **kwargs)
savefig(filename)
return wrapper
return decorator
plt.show = save_image('image.png')(plt.show)
plt.savefig = save_image('image.png')(plt.savefig)
import dill, os, pickle
if os.path.exists("{conversation_id}.dill"):
try:
with open("{conversation_id}.dill", 'rb') as f:
dill.load_session(f)
except:
pass
{code}
try:
with open('{conversation_id}.dill', 'wb') as f:
dill.dump_session(f)
except:
pass
"""
SIMULATED_USER_REPLY_OUTPUT_ONLY = """\
Your code was executed and this is the output.
```output
{output}
```
"""
SIMULATED_USER_REPLY_ERROR_ONLY = """\
Your code was executed and this is the error.
```error
{error}
```
"""
SIMULATED_USER_REPLY_OUTPUT_AND_ERROR = """\
Your code was executed and this is the output and error.
```output
{output}
```
```error
{error}
```
"""
SIMULATED_USER_REPLY_NO_OUTPUT_OR_ERROR = """\
Your code was executed without issues, without any standard output.
"""
SIMULATED_USER_SUFFIX_IMAGE_FOUND = """
Your code was executed and it displayed a plot as attached. Please describe the plot and check if it makes sense.
"""
SIMULATED_USER_SUFFIX_IMAGE_NOT_FOUND = """
Your code was executed but it did not display a plot.
"""
SIMULATED_USER_SUFFIX_PROMPT = """
If there is an issue, you will fix the Python code.
Otherwise, conclude with only text in plaintext. Do NOT produce the final version of the script.
"""
IMAGE_EXEC = (
Image
.debian_slim()
.pip_install(
"ipython",
"scipy",
"matplotlib",
"scikit-learn",
"pandas",
"ortools",
"openai",
"requests",
"beautifulsoup4",
"newspaper3k",
"XlsxWriter",
"docx2txt",
"markdownify",
"pdfminer.six",
"Pillow",
"sortedcontainers",
"intervaltree",
"geopandas",
"basemap",
"tiktoken",
"basemap-data-hires",
"yfinance",
"dill",
"seaborn",
"openpyxl",
"cartopy",
"sympy",
)
.pip_install(
["torch", "torchvision", "torchaudio"],
index_url="https://download.pytorch.org/whl/cpu",
)
.pip_install(
"tensorflow",
"keras",
"nltk",
"spacy",
"opencv-python-headless",
"feedparser",
"wordcloud",
"opencv-python",
)
)
class PythonAgentBot(PoeBot):
prompt_bot = "GPT-4o"
code_iteration_limit = 3
logit_bias = {} # "!["
allow_attachments = True
system_prompt_role: Optional[str] = "system" # Claude-3 does not allow system prompt yet
python_agent_system_prompt: Optional[str] = PYTHON_AGENT_SYSTEM_PROMPT
code_with_wrappers = CODE_WITH_WRAPPERS
simulated_user_suffix_prompt = SIMULATED_USER_SUFFIX_PROMPT
image_exec = IMAGE_EXEC
def extract_code(self, text):
pattern = r"\n```python([\s\S]*?)\n```"
matches = re.findall(pattern, "\n" + text)
if matches:
return "\n\n".join(matches)
pattern = r"```python([\s\S]*?)```"
matches = re.findall(pattern, "\n" + text)
return "\n\n".join(textwrap.dedent(match) for match in matches)
async def get_response(
self, request: QueryRequest
) -> AsyncIterable[PartialResponse]:
last_message = request.query[-1].content
original_message_id = request.message_id
print("user_message")
print(last_message)
assert (self.python_agent_system_prompt is not None) == (self.system_prompt_role is not None)
if self.python_agent_system_prompt is not None:
PYTHON_AGENT_SYSTEM_MESSAGE = ProtocolMessage(
role=self.system_prompt_role, content=self.python_agent_system_prompt
)
request.query = [PYTHON_AGENT_SYSTEM_MESSAGE] + request.query
request.logit_bias = self.logit_bias
request.temperature = 0.1 # does this work?
for query in request.query:
query.message_id = ""
nfs = modal.NetworkFileSystem.from_name(f"vol-{request.user_id[::-1][:32][::-1]}", create_if_missing=True)
for query in request.query:
for attachment in query.attachments:
query.content += f"\n\nThe user has provided {attachment.name} in the current directory."
# upload files in latest user message
for attachment in request.query[-1].attachments:
r = requests.get(attachment.url)
with open(attachment.name, "wb") as f:
f.write(r.content)
nfs.add_local_file(attachment.name, attachment.name)
# for query in request.query:
# bot calling doesn't allow attachments
# query.attachments = []
for code_iteration_count in range(self.code_iteration_limit - 1):
print("code_iteration_count", code_iteration_count)
print(request)
current_bot_reply = ""
async for msg in stream_request(request, self.prompt_bot, request.api_key):
if isinstance(msg, MetaMessage):
continue
elif msg.is_suggested_reply:
yield self.suggested_reply_event(msg.text)
elif msg.is_replace_response:
yield self.replace_response_event(msg.text)
else:
current_bot_reply += msg.text
yield self.text_event(msg.text)
if self.extract_code(current_bot_reply):
# break when a Python code block is detected
break
message = ProtocolMessage(role="bot", content=current_bot_reply)
request.query.append(message)
# if the bot output does not have code, terminate
code = self.extract_code(current_bot_reply)
if not code:
return
# prepare code for execution
print("code")
print(code)
wrapped_code = self.code_with_wrappers.format(code=code, conversation_id=request.conversation_id)
# upload python script
with open(f"{request.conversation_id}.py", "w") as f:
f.write(wrapped_code)
nfs.add_local_file(
f"{request.conversation_id}.py", f"{request.conversation_id[::-1][:32][::-1]}.py"
)
# execute code
sb = Sandbox.create(
"bash",
"-c",
f"cd /cache && python {request.conversation_id[::-1][:32][::-1]}.py",
image=self.image_exec,
network_file_systems={"/cache": nfs},
)
sb.wait()
print("sb.returncode", sb.returncode)
output = sb.stdout.read()
error = sb.stderr.read()
print("len(output)", len(output))
print("len(error)", len(error))
if error: # for monitoring
print("error")
print(error)
current_user_simulated_reply = ""
if output and error:
yield PartialResponse(
text=textwrap.dedent(f"\n\n```output\n{output}```\n\n")
)
yield PartialResponse(
text=textwrap.dedent(f"\n\n```error\n{error}```\n\n")
)
current_user_simulated_reply = (
SIMULATED_USER_REPLY_OUTPUT_AND_ERROR.format(
output=output, error=error
)
)
elif output:
yield PartialResponse(
text=textwrap.dedent(f"\n\n```output\n{output}```\n\n")
)
current_user_simulated_reply = SIMULATED_USER_REPLY_OUTPUT_ONLY.format(
output=output
)
elif error:
yield PartialResponse(
text=textwrap.dedent(f"\n\n```error\n{error}```\n\n")
)
current_user_simulated_reply = SIMULATED_USER_REPLY_ERROR_ONLY.format(
error=error
)
else:
current_user_simulated_reply = SIMULATED_USER_REPLY_NO_OUTPUT_OR_ERROR
# upload image and get image url
image_data = None
if any("image.png" in str(entry) for entry in nfs.listdir("*")):
# some roundabout way to check if image file is in directory
with open("image.png", "wb") as f:
for chunk in nfs.read_file("image.png"):
f.write(chunk)
image_data = None
with open("image.png", "rb") as f:
image_data = f.read()
if image_data:
attachment_upload_response = await self.post_message_attachment(
message_id=original_message_id,
file_data=image_data,
filename="image.png",
is_inline=True,
)
print("inline_ref", attachment_upload_response.inline_ref)
yield PartialResponse(
text=f"\n\n![plot][{attachment_upload_response.inline_ref}]\n\n"
)
nfs.remove_file("image.png")
yield self.text_event("\n")
if image_data is not None:
current_user_simulated_reply += SIMULATED_USER_SUFFIX_IMAGE_FOUND
else:
if "matplotlib" in code:
current_user_simulated_reply += (
SIMULATED_USER_SUFFIX_IMAGE_NOT_FOUND
)
current_user_simulated_reply += self.simulated_user_suffix_prompt
# TODO when feature allows, add image to ProtocolMessage
message = ProtocolMessage(role="user", content=current_user_simulated_reply)
request.query.append(message)
async def get_settings(self, setting: SettingsRequest) -> SettingsResponse:
return SettingsResponse(
server_bot_dependencies={self.prompt_bot: self.code_iteration_limit},
allow_attachments=self.allow_attachments,
introduction_message="",
enable_image_comprehension=True,
)
class PythonAgentExBot(PythonAgentBot):
prompt_bot = "Claude-3.5-Sonnet-200k"
code_iteration_limit = 5
system_prompt_role = "system"
class LeetCodeAgentBot(PythonAgentBot):
prompt_bot = "o1-mini"
code_iteration_limit = 5
system_prompt_role = "user"
python_agent_system_prompt = textwrap.dedent(
"""
You will write the solution and the test cases to a Leetcode problem.
Implement your code as a method in the `class Solution` along with the given test cases. The user will provide the output executed by the code.
When there are issues, following these steps
- Hand-calculate what the intermediate values should be
- Print the intermediate values in the code.
If the intermediate values are already printed
- Hand calculate what the intermediate values should be
- Analyze what is wrong with the intermediate values
- Fix the issue by implementing the full solution along with the given test cases, with the intermediate values printed
If you are repeatedly stuck on the same error, start afresh and try an entirely different method instead.
When a test case is given, hand-calculate the expected output first before writing code.
If the output looks ok, meticulously calculate the complexity of the solution to check whether it is within the time limit. (Note: "105" is likely 10**5).
Fix the code if it is likely to exceed time limit. Do not stop at a solution that will exceed the time limit.
class Solution:
def ...
s = Solution()
print(s.<function>(<inputs>)) # Expected: <expected output>
print(s.<function>(<inputs>)) # Expected: <expected output>
Reminder:
- Write test cases in this format. Do not create new test cases, only use the given test cases.
- Always return the full solution and the test cases in the same Python block
"""
).strip()