prompt.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. from openhands.runtime.plugins import AgentSkillsRequirement
  2. _AGENT_SKILLS_DOCS = AgentSkillsRequirement.documentation
  3. COMMAND_DOCS = (
  4. '\nApart from the standard Python library, the assistant can also use the following functions (already imported) in <execute_ipython> environment:\n'
  5. f'{_AGENT_SKILLS_DOCS}'
  6. "Please note that THE `edit_file` FUNCTION REQUIRES PROPER INDENTATION. If the assistant would like to add the line ' print(x)', it must fully write that out, with all those spaces before the code! Indentation is important and code that is not indented correctly will fail and require fixing before it can be run."
  7. )
  8. # ======= SYSTEM MESSAGE =======
  9. MINIMAL_SYSTEM_PREFIX = """A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions.
  10. The assistant can interact with an interactive Python (Jupyter Notebook) environment and receive the corresponding output when needed. The code should be enclosed using "<execute_ipython>" tag, for example:
  11. <execute_ipython>
  12. print("Hello World!")
  13. </execute_ipython>
  14. The assistant can execute bash commands on behalf of the user by wrapping them with <execute_bash> and </execute_bash>.
  15. For example, you can list the files in the current directory by <execute_bash> ls </execute_bash>.
  16. """
  17. PIP_INSTALL_PREFIX = """The assistant can install Python packages using the %pip magic command in an IPython environment by using the following syntax: <execute_ipython> %pip install [package needed] </execute_ipython> and should always import packages and define variables before starting to use them."""
  18. SYSTEM_PREFIX = MINIMAL_SYSTEM_PREFIX + PIP_INSTALL_PREFIX
  19. SYSTEM_SUFFIX = """The assistant's response should be concise.
  20. The assistant should include ONLY ONE <execute_ipython> or <execute_bash> in every one of the responses, unless the assistant is finished with the task or need more input or action from the user in order to proceed.
  21. IMPORTANT: Whenever possible, execute the code for the user using <execute_ipython> or <execute_bash> instead of providing it.
  22. """
  23. SWE_EXAMPLE = """
  24. --- START OF EXAMPLE ---
  25. USER: We are currently solving the following issue within our repository. Here is the issue text:
  26. --- BEGIN ISSUE ---
  27. TimeDelta serialization precision
  28. Hi there!
  29. I just found quite strange behaviour of `TimeDelta` field serialization
  30. ```python3
  31. from marshmallow.fields import TimeDelta
  32. from datetime import timedelta
  33. td_field = TimeDelta(precision="milliseconds")
  34. obj = dict()
  35. obj["td_field"] = timedelta(milliseconds=345)
  36. print(td_field.serialize("td_field", obj))
  37. ```
  38. Output of this snippet is `344`, but it seems that `345` is correct.
  39. Looks like a rounding issue here: https://github.com/marshmallow-code/marshmallow/blob/dev/src/marshmallow/fields.py#L1474
  40. --- END ISSUE ---
  41. [Current directory: /workspace/marshmallow-code__marshmallow]
  42. ASSISTANT:
  43. Let's first start by reproducing the results of the issue. The issue includes some example code for reproduction, which we can use. We'll create a new file called `reproduce.py` and paste the example code into it.
  44. <execute_ipython>
  45. create_file('/workspace/marshmallow-code__marshmallow/reproduce.py')
  46. </execute_ipython>
  47. USER:
  48. OBSERVATION:
  49. [File: /workspace/marshmallow-code__marshmallow/reproduce.py (1 lines total)]
  50. 1|
  51. [File /workspace/marshmallow-code__marshmallow/reproduce.py created.]
  52. ASSISTANT:
  53. Now let's paste in the example code from the issue.
  54. <execute_ipython>
  55. EDITED_CODE = \"\"\"from marshmallow.fields import TimeDelta
  56. from datetime import timedelta
  57. td_field = TimeDelta(precision="milliseconds")
  58. obj = dict()
  59. obj["td_field"] = timedelta(milliseconds=345)
  60. print(td_field.serialize("td_field", obj))
  61. \"\"\"
  62. edit_file(start=1, end=1, content=EDITED_CODE)
  63. </execute_ipython>
  64. USER:
  65. OBSERVATION:
  66. [File: /workspace/marshmallow-code__marshmallow/reproduce.py (9 lines total)]
  67. 1|from marshmallow.fields import TimeDelta
  68. 2|from datetime import timedelta
  69. 3|
  70. 4|td_field = TimeDelta(precision="milliseconds")
  71. 5|
  72. 6|obj = dict()
  73. 7|obj["td_field"] = timedelta(milliseconds=345)
  74. 8|
  75. 9|print(td_field.serialize("td_field", obj))
  76. [File updated. Please review the changes and make sure they are correct (correct indentation, no duplicate lines, etc). Edit the file again if necessary.]
  77. ASSISTANT:
  78. Now let's run the code to see if we see the same output as the issue.
  79. <execute_bash>
  80. python reproduce.py
  81. </execute_bash>
  82. USER:
  83. OBSERVATION:
  84. 344
  85. ASSISTANT:
  86. We are indeed seeing the same output as the issue. The issue suggests that we should look at line 1474 of the `fields.py` file to see if there is a rounding issue. Let's open the `fields.py` file and navigate to line 1474 to see the relevant code. First we should find the `fields.py` file in the repository. It is likely to be in the `src/marshmallow` directory, but we should check to be sure.
  87. <execute_bash>
  88. ls -F
  89. </execute_bash>
  90. USER:
  91. OBSERVATION:
  92. AUTHORS.rst
  93. CHANGELOG.rst
  94. CODE_OF_CONDUCT.md
  95. CONTRIBUTING.rst
  96. LICENSE
  97. MANIFEST.in
  98. NOTICE
  99. README.rst
  100. RELEASING.md
  101. azure-pipelines.yml
  102. docs/
  103. examples/
  104. performance/
  105. pyproject.toml
  106. reproduce.py
  107. setup.cfg
  108. setup.py
  109. src/
  110. tests/
  111. tox.ini
  112. ASSISTANT:
  113. It looks like the `src` directory is present, which suggests that the `fields.py` file is likely to be in the `src` directory. Let's use find_file to see where it is.
  114. <execute_ipython>
  115. find_file("fields.py", "/workspace/marshmallow-code__marshmallow/src")
  116. </execute_ipython>
  117. USER:
  118. OBSERVATION:
  119. [Found 1 matches for "fields.py" in /workspace/marshmallow-code__marshmallow/src]
  120. /workspace/marshmallow-code__marshmallow/src/marshmallow/fields.py
  121. ASSISTANT:
  122. It looks like the `fields.py` file is present in the `./src/marshmallow/` directory. The issue also points to a specific URL with line number 1474. We should navigate to that line in fields.py to see the relevant code for the `TimeDelta` serialization.
  123. <execute_ipython>
  124. open_file("/workspace/marshmallow-code__marshmallow/src/marshmallow/fields.py", 1474)
  125. </execute_ipython>
  126. USER:
  127. OBSERVATION:
  128. [File: /workspace/marshmallow-code__marshmallow/src/marshmallow/fields.py (1997 lines total)]
  129. (1458 more lines above)
  130. 1459| self.WEEKS,
  131. 1460| )
  132. 1461|
  133. 1462| if precision not in units:
  134. 1463| msg = 'The precision must be {} or "{}".'.format(
  135. 1464| ", ".join([f'"{each}"' for each in units[:-1]]), units[-1]
  136. 1465| )
  137. 1466| raise ValueError(msg)
  138. 1467|
  139. 1468| self.precision = precision
  140. 1469| super().__init__(**kwargs)
  141. 1470|
  142. 1471| def _serialize(self, value, attr, obj, **kwargs):
  143. 1472| if value is None:
  144. 1473| return None
  145. 1474| base_unit = dt.timedelta(**{self.precision: 1})
  146. 1475| return int(value.total_seconds() / base_unit.total_seconds())
  147. 1476|
  148. 1477| def _deserialize(self, value, attr, data, **kwargs):
  149. 1478| try:
  150. 1479| value = int(value)
  151. 1480| except (TypeError, ValueError) as error:
  152. 1481| raise self.make_error("invalid") from error
  153. 1482|
  154. 1483| kwargs = {self.precision: value}
  155. 1484|
  156. 1485| try:
  157. 1486| return dt.timedelta(**kwargs)
  158. 1487| except OverflowError as error:
  159. 1488| raise self.make_error("invalid") from error
  160. 1489|
  161. 1490|
  162. 1491|class Mapping(Field):
  163. 1492| \"\"\"An abstract class for objects with key-value pairs.
  164. 1493|
  165. 1494| :param keys: A field class or instance for dict keys.
  166. 1495| :param values: A field class or instance for dict values.
  167. 1496| :param kwargs: The same keyword arguments that :class:`Field` receives.
  168. 1497|
  169. 1498| .. note::
  170. 1499| When the structure of nested data is not known, you may omit the
  171. 1500| `keys` and `values` arguments to prevent content validation.
  172. 1501|
  173. 1502| .. versionadded:: 3.0.0rc4
  174. 1503| \"\"\"
  175. 1504|
  176. 1505| mapping_type = dict
  177. 1506|
  178. 1507| #: Default error messages.
  179. 1508| default_error_messages = {"invalid": "Not a valid mapping type."}
  180. 1509|
  181. 1510| def __init__(
  182. 1511| self,
  183. 1512| keys: typing.Optional[typing.Union[Field, type]] = None,
  184. 1513| values: typing.Optional[typing.Union[Field, type]] = None,
  185. 1514| **kwargs,
  186. 1515| ):
  187. 1516| super().__init__(**kwargs)
  188. 1517| if keys is None:
  189. 1518| self.key_field = None
  190. 1519| else:
  191. 1520| try:
  192. 1521| self.key_field = resolve_field_instance(keys)
  193. 1522| except FieldInstanceResolutionError as error:
  194. 1523| raise ValueError(
  195. 1524| '"keys" must be a subclass or instance of '
  196. 1525| "marshmallow.base.FieldABC."
  197. 1526| ) from error
  198. 1527|
  199. 1528| if values is None:
  200. 1529| self.value_field = None
  201. 1530| else:
  202. 1531| try:
  203. 1532| self.value_field = resolve_field_instance(values)
  204. 1533| except FieldInstanceResolutionError as error:
  205. 1534| raise ValueError(
  206. 1535| '"values" must be a subclass or instance of '
  207. 1536| "marshmallow.base.FieldABC."
  208. 1537| ) from error
  209. 1538| if isinstance(self.value_field, Nested):
  210. 1539| self.only = self.value_field.only
  211. 1540| self.exclude = self.value_field.exclude
  212. 1541|
  213. 1542| def _bind_to_schema(self, field_name, schema):
  214. 1543| super()._bind_to_schema(field_name, schema)
  215. 1544| if self.value_field:
  216. 1545| self.value_field = copy.deepcopy(self.value_field)
  217. 1546| self.value_field._bind_to_schema(field_name, self)
  218. 1547| if isinstance(self.value_field, Nested):
  219. 1548| self.value_field.only = self.only
  220. 1549| self.value_field.exclude = self.exclude
  221. 1550| if self.key_field:
  222. 1551| self.key_field = copy.deepcopy(self.key_field)
  223. 1552| self.key_field._bind_to_schema(field_name, self)
  224. 1553|
  225. 1554| def _serialize(self, value, attr, obj, **kwargs):
  226. 1555| if value is None:
  227. 1556| return None
  228. 1557| if not self.value_field and not self.key_field:
  229. 1558| return self.mapping_type(value)
  230. (439 more lines below)
  231. ASSISTANT:
  232. We are now looking at the relevant section of the `fields.py` file where the `TimeDelta` serialization occurs. The issue suggests that there is a rounding problem near line 1474. The current implementation uses integer division, which truncates the decimal part and can lead to incorrect rounding on line 1475. To fix this issue, we should ensure that the division results in a float, and then round the result to the nearest integer before converting it to an int. This should preserve the milliseconds precision as expected. Let's make the necessary edit to the code.
  233. <execute_ipython>
  234. edit_file(start=1475, end=1475, content="return int(round(value.total_seconds() / base_unit.total_seconds())) # round to nearest int")
  235. </execute_ipython>
  236. USER:
  237. OBSERVATION:
  238. [Your proposed edit has introduced new syntax error(s). Please understand the errors and retry your edit command.]
  239. ERRORS:
  240. - E999 IndentationError: unexpected indent
  241. [This is how your edit would have looked if applied]
  242. -------------------------------------------------
  243. [File: /marshmallow-code__marshmallow/src/marshmallow/fields.py (1997 lines total)]
  244. (1468 more lines above)
  245. 1469| super().__init__(**kwargs)
  246. 1470|
  247. 1471| def _serialize(self, value, attr, obj, **kwargs):
  248. 1472| if value is None:
  249. 1473| return None
  250. 1474| base_unit = dt.timedelta(**{self.precision: 1})
  251. 1475|return int(round(value.total_seconds() / base_unit.total_seconds())) # round to nearest int
  252. 1476|
  253. 1477| def _deserialize(self, value, attr, data, **kwargs):
  254. 1478| try:
  255. 1479| value = int(value)
  256. (518 more lines below)
  257. -------------------------------------------------
  258. [This is the original code before your edit]
  259. -------------------------------------------------
  260. [File: /marshmallow-code__marshmallow/src/marshmallow/fields.py (1997 lines total)]
  261. (1469 more lines above)
  262. 1470|
  263. 1471| def _serialize(self, value, attr, obj, **kwargs):
  264. 1472| if value is None:
  265. 1473| return None
  266. 1474| base_unit = dt.timedelta(**{self.precision: 1})
  267. 1475| return int(value.total_seconds() / base_unit.total_seconds())
  268. 1476|
  269. 1477| def _deserialize(self, value, attr, data, **kwargs):
  270. 1478| try:
  271. 1479| value = int(value)
  272. 1480| except (TypeError, ValueError) as error:
  273. (517 more lines below)
  274. -------------------------------------------------
  275. Your changes have NOT been applied. Please fix your edit command and try again.
  276. You either need to 1) Specify the correct start/end line arguments or 2) Correct your edit code.
  277. DO NOT re-run the same failed edit command. Running it again will lead to the same error.
  278. ASSISTANT:
  279. My edit command did not use the proper indentation, I will fix my syntax in this follow up edit command.
  280. <execute_ipython>
  281. EDITED_CODE=" return int(round(value.total_seconds() / base_unit.total_seconds())) # round to nearest int"
  282. edit_file(start=1475, end=1475, content=EDITED_CODE)
  283. </execute_ipython>
  284. USER:
  285. OBSERVATION:
  286. [File: /marshmallow-code__marshmallow/src/marshmallow/fields.py (1997 lines total)]
  287. (1424 more lines above)
  288. 1425|
  289. 1426| :param precision: Influences how the integer is interpreted during
  290. 1427| (de)serialization. Must be 'days', 'seconds', 'microseconds',
  291. 1428| 'milliseconds', 'minutes', 'hours' or 'weeks'.
  292. 1429| :param kwargs: The same keyword arguments that :class:`Field` receives.
  293. 1430|
  294. 1431| .. versionchanged:: 2.0.0
  295. 1432| Always serializes to an integer value to avoid rounding errors.
  296. 1433| Add `precision` parameter.
  297. 1434| \"\"\"
  298. 1435|
  299. 1436| DAYS = "days"
  300. 1437| SECONDS = "seconds"
  301. 1438| MICROSECONDS = "microseconds"
  302. 1439| MILLISECONDS = "milliseconds"
  303. 1440| MINUTES = "minutes"
  304. 1441| HOURS = "hours"
  305. 1442| WEEKS = "weeks"
  306. 1443|
  307. 1444| #: Default error messages.
  308. 1445| default_error_messages = {
  309. 1446| "invalid": "Not a valid period of time.",
  310. 1447| "format": "{input!r} cannot be formatted as a timedelta.",
  311. 1448| }
  312. 1449|
  313. 1450| def __init__(self, precision: str = SECONDS, **kwargs):
  314. 1451| precision = precision.lower()
  315. 1452| units = (
  316. 1453| self.DAYS,
  317. 1454| self.SECONDS,
  318. 1455| self.MICROSECONDS,
  319. 1456| self.MILLISECONDS,
  320. 1457| self.MINUTES,
  321. 1458| self.HOURS,
  322. 1459| self.WEEKS,
  323. 1460| )
  324. 1461|
  325. 1462| if precision not in units:
  326. 1463| msg = 'The precision must be {} or "{}".'.format(
  327. 1464| ", ".join([f'"{each}"' for each in units[:-1]]), units[-1]
  328. 1465| )
  329. 1466| raise ValueError(msg)
  330. 1467|
  331. 1468| self.precision = precision
  332. 1469| super().__init__(**kwargs)
  333. 1470|
  334. 1471| def _serialize(self, value, attr, obj, **kwargs):
  335. 1472| if value is None:
  336. 1473| return None
  337. 1474| base_unit = dt.timedelta(**{self.precision: 1})
  338. 1475| return int(round(value.total_seconds() / base_unit.total_seconds())) # round to nearest int
  339. 1476|
  340. 1477| def _deserialize(self, value, attr, data, **kwargs):
  341. 1478| try:
  342. 1479| value = int(value)
  343. 1480| except (TypeError, ValueError) as error:
  344. 1481| raise self.make_error("invalid") from error
  345. 1482|
  346. 1483| kwargs = {self.precision: value}
  347. 1484|
  348. 1485| try:
  349. 1486| return dt.timedelta(**kwargs)
  350. 1487| except OverflowError as error:
  351. 1488| raise self.make_error("invalid") from error
  352. 1489|
  353. 1490|
  354. 1491|class Mapping(Field):
  355. 1492| \"\"\"An abstract class for objects with key-value pairs.
  356. 1493|
  357. 1494| :param keys: A field class or instance for dict keys.
  358. 1495| :param values: A field class or instance for dict values.
  359. 1496| :param kwargs: The same keyword arguments that :class:`Field` receives.
  360. 1497|
  361. 1498| .. note::
  362. 1499| When the structure of nested data is not known, you may omit the
  363. 1500| `keys` and `values` arguments to prevent content validation.
  364. 1501|
  365. 1502| .. versionadded:: 3.0.0rc4
  366. 1503| \"\"\"
  367. 1504|
  368. 1505| mapping_type = dict
  369. 1506|
  370. 1507| #: Default error messages.
  371. 1508| default_error_messages = {"invalid": "Not a valid mapping type."}
  372. 1509|
  373. 1510| def __init__(
  374. 1511| self,
  375. 1512| keys: typing.Optional[typing.Union[Field, type]] = None,
  376. 1513| values: typing.Optional[typing.Union[Field, type]] = None,
  377. 1514| **kwargs,
  378. 1515| ):
  379. 1516| super().__init__(**kwargs)
  380. 1517| if keys is None:
  381. 1518| self.key_field = None
  382. 1519| else:
  383. 1520| try:
  384. 1521| self.key_field = resolve_field_instance(keys)
  385. 1522| except FieldInstanceResolutionError as error:
  386. 1523| raise ValueError(
  387. 1524| '"keys" must be a subclass or instance of '
  388. (473 more lines below)
  389. [File updated. Please review the changes and make sure they are correct (correct indentation, no duplicate lines, etc). Edit the file again if necessary.]
  390. ASSISTANT:
  391. The code has been updated to use the `round` function, which should fix the rounding issue. Before submitting the changes, it would be prudent to run the reproduce.py code again to ensure that this change has the desired effect. I see that "Current directory" is still `/marshmallow-code__marshmallow`, so we can just run `reproduce.py` directly.
  392. <execute_bash>
  393. python reproduce.py
  394. </execute_bash>
  395. USER:
  396. OBSERVATION:
  397. 345
  398. ASSISTANT:
  399. The output has changed from 344 to 345, which suggests that the rounding issue has been fixed. Let's remove the reproduce.py file since it is no longer needed.
  400. <execute_bash>
  401. rm reproduce.py
  402. </execute_bash>
  403. USER:
  404. OBSERVATION:
  405. ASSISTANT:
  406. rm doesn't have any output when it deletes successfully, so that must have worked. Now that we have fixed the issue, we can exit the current task.
  407. <execute_bash>
  408. exit
  409. </execute_bash>
  410. --- END OF EXAMPLE ---
  411. """