function_calling.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. """This file contains the function calling implementation for different actions.
  2. This is similar to the functionality of `CodeActResponseParser`.
  3. """
  4. import json
  5. from browsergym.core.action.highlevel import HighLevelActionSet
  6. from litellm import (
  7. ChatCompletionToolParam,
  8. ChatCompletionToolParamFunctionChunk,
  9. ModelResponse,
  10. )
  11. from openhands.core.logger import openhands_logger as logger
  12. from openhands.events.action import (
  13. Action,
  14. AgentDelegateAction,
  15. AgentFinishAction,
  16. BrowseInteractiveAction,
  17. CmdRunAction,
  18. FileEditAction,
  19. IPythonRunCellAction,
  20. MessageAction,
  21. )
  22. from openhands.events.tool import ToolCallMetadata
  23. SYSTEM_PROMPT = """You are a helpful assistant that can interact with a computer to solve tasks.
  24. <IMPORTANT>
  25. * If user provides a path, you should NOT assume it's relative to the current working directory. Instead, you should explore the file system to find the file before working on it.
  26. </IMPORTANT>
  27. """
  28. _BASH_DESCRIPTION = """Execute a bash command in the terminal.
  29. * Long running commands: For commands that may run indefinitely, it should be run in the background and the output should be redirected to a file, e.g. command = `python3 app.py > server.log 2>&1 &`.
  30. * Interactive: If a bash command returns exit code `-1`, this means the process is not yet finished. The assistant must then send a second call to terminal with an empty `command` (which will retrieve any additional logs), or it can send additional text (set `command` to the text) to STDIN of the running process, or it can send command=`ctrl+c` to interrupt the process.
  31. * Timeout: If a command execution result says "Command timed out. Sending SIGINT to the process", the assistant should retry running the command in the background.
  32. """
  33. CmdRunTool = ChatCompletionToolParam(
  34. type='function',
  35. function=ChatCompletionToolParamFunctionChunk(
  36. name='execute_bash',
  37. description=_BASH_DESCRIPTION,
  38. parameters={
  39. 'type': 'object',
  40. 'properties': {
  41. 'command': {
  42. 'type': 'string',
  43. 'description': 'The bash command to execute. Can be empty to view additional logs when previous exit code is `-1`. Can be `ctrl+c` to interrupt the currently running process.',
  44. },
  45. },
  46. 'required': ['command'],
  47. },
  48. ),
  49. )
  50. _IPYTHON_DESCRIPTION = """Run a cell of Python code in an IPython environment.
  51. * The assistant should define variables and import packages before using them.
  52. * The variable defined in the IPython environment will not be available outside the IPython environment (e.g., in terminal).
  53. """
  54. # We are not using agentskills's file_ops for viewing files now because StrReplaceEditorTool already supports viewing files
  55. # """* Apart from the standard Python library, the assistant can also use the following functions (already imported):
  56. # {AgentSkillsRequirement.documentation}"""
  57. IPythonTool = ChatCompletionToolParam(
  58. type='function',
  59. function=ChatCompletionToolParamFunctionChunk(
  60. name='execute_ipython_cell',
  61. description=_IPYTHON_DESCRIPTION,
  62. parameters={
  63. 'type': 'object',
  64. 'properties': {
  65. 'code': {
  66. 'type': 'string',
  67. 'description': 'The Python code to execute. Supports magic commands like %pip.',
  68. },
  69. },
  70. 'required': ['code'],
  71. },
  72. ),
  73. )
  74. _FILE_EDIT_DESCRIPTION = """Edit a file.
  75. * The assistant can edit files by specifying the file path and providing a draft of the new file content.
  76. * The draft content doesn't need to be exactly the same as the existing file; the assistant may skip unchanged lines using comments like `# unchanged` to indicate unchanged sections.
  77. * IMPORTANT: For large files (e.g., > 300 lines), specify the range of lines to edit using `start` and `end` (1-indexed, inclusive). The range should be smaller than 300 lines.
  78. * To append to a file, set both `start` and `end` to `-1`.
  79. * If the file doesn't exist, a new file will be created with the provided content.
  80. **Example 1: general edit for short files**
  81. For example, given an existing file `/path/to/file.py` that looks like this:
  82. (this is the end of the file)
  83. 1|class MyClass:
  84. 2| def __init__(self):
  85. 3| self.x = 1
  86. 4| self.y = 2
  87. 5| self.z = 3
  88. 6|
  89. 7|print(MyClass().z)
  90. 8|print(MyClass().x)
  91. (this is the end of the file)
  92. The assistant wants to edit the file to look like this:
  93. (this is the end of the file)
  94. 1|class MyClass:
  95. 2| def __init__(self):
  96. 3| self.x = 1
  97. 4| self.y = 2
  98. 5|
  99. 6|print(MyClass().y)
  100. (this is the end of the file)
  101. The assistant may produce an edit action like this:
  102. path="/path/to/file.txt" start=1 end=-1
  103. content=```
  104. class MyClass:
  105. def __init__(self):
  106. # no changes before
  107. self.y = 2
  108. # self.z is removed
  109. # MyClass().z is removed
  110. print(MyClass().y)
  111. ```
  112. **Example 2: append to file for short files**
  113. For example, given an existing file `/path/to/file.py` that looks like this:
  114. (this is the end of the file)
  115. 1|class MyClass:
  116. 2| def __init__(self):
  117. 3| self.x = 1
  118. 4| self.y = 2
  119. 5| self.z = 3
  120. 6|
  121. 7|print(MyClass().z)
  122. 8|print(MyClass().x)
  123. (this is the end of the file)
  124. To append the following lines to the file:
  125. ```python
  126. print(MyClass().y)
  127. ```
  128. The assistant may produce an edit action like this:
  129. path="/path/to/file.txt" start=-1 end=-1
  130. content=```
  131. print(MyClass().y)
  132. ```
  133. **Example 3: edit for long files**
  134. Given an existing file `/path/to/file.py` that looks like this:
  135. (1000 more lines above)
  136. 1001|class MyClass:
  137. 1002| def __init__(self):
  138. 1003| self.x = 1
  139. 1004| self.y = 2
  140. 1005| self.z = 3
  141. 1006|
  142. 1007|print(MyClass().z)
  143. 1008|print(MyClass().x)
  144. (2000 more lines below)
  145. The assistant wants to edit the file to look like this:
  146. (1000 more lines above)
  147. 1001|class MyClass:
  148. 1002| def __init__(self):
  149. 1003| self.x = 1
  150. 1004| self.y = 2
  151. 1005|
  152. 1006|print(MyClass().y)
  153. (2000 more lines below)
  154. The assistant may produce an edit action like this:
  155. path="/path/to/file.txt" start=1001 end=1008
  156. content=```
  157. class MyClass:
  158. def __init__(self):
  159. # no changes before
  160. self.y = 2
  161. # self.z is removed
  162. # MyClass().z is removed
  163. print(MyClass().y)
  164. ```
  165. """
  166. LLMBasedFileEditTool = ChatCompletionToolParam(
  167. type='function',
  168. function=ChatCompletionToolParamFunctionChunk(
  169. name='edit_file',
  170. description=_FILE_EDIT_DESCRIPTION,
  171. parameters={
  172. 'type': 'object',
  173. 'properties': {
  174. 'path': {
  175. 'type': 'string',
  176. 'description': 'The absolute path to the file to be edited.',
  177. },
  178. 'new_content_draft': {
  179. 'type': 'string',
  180. 'description': 'A draft of the new content for the file being edited. Note that the assistant may skip unchanged lines.',
  181. },
  182. 'start': {
  183. 'type': 'integer',
  184. 'description': 'The starting line number for the edit (1-indexed, inclusive). Default is 1.',
  185. },
  186. 'end': {
  187. 'type': 'integer',
  188. 'description': 'The ending line number for the edit (1-indexed, inclusive). Default is -1 (end of file).',
  189. },
  190. },
  191. 'required': ['path', 'content'],
  192. },
  193. ),
  194. )
  195. _STR_REPLACE_EDITOR_DESCRIPTION = """Custom editing tool for viewing, creating and editing files
  196. * State is persistent across command calls and discussions with the user
  197. * If `path` is a file, `view` displays the result of applying `cat -n`. If `path` is a directory, `view` lists non-hidden files and directories up to 2 levels deep
  198. * The `create` command cannot be used if the specified `path` already exists as a file
  199. * If a `command` generates a long output, it will be truncated and marked with `<response clipped>`
  200. * The `undo_edit` command will revert the last edit made to the file at `path`
  201. Notes for using the `str_replace` command:
  202. * The `old_str` parameter should match EXACTLY one or more consecutive lines from the original file. Be mindful of whitespaces!
  203. * If the `old_str` parameter is not unique in the file, the replacement will not be performed. Make sure to include enough context in `old_str` to make it unique
  204. * The `new_str` parameter should contain the edited lines that should replace the `old_str`
  205. """
  206. StrReplaceEditorTool = ChatCompletionToolParam(
  207. type='function',
  208. function=ChatCompletionToolParamFunctionChunk(
  209. name='str_replace_editor',
  210. description=_STR_REPLACE_EDITOR_DESCRIPTION,
  211. parameters={
  212. 'type': 'object',
  213. 'properties': {
  214. 'command': {
  215. 'description': 'The commands to run. Allowed options are: `view`, `create`, `str_replace`, `insert`, `undo_edit`.',
  216. 'enum': ['view', 'create', 'str_replace', 'insert', 'undo_edit'],
  217. 'type': 'string',
  218. },
  219. 'path': {
  220. 'description': 'Absolute path to file or directory, e.g. `/repo/file.py` or `/repo`.',
  221. 'type': 'string',
  222. },
  223. 'file_text': {
  224. 'description': 'Required parameter of `create` command, with the content of the file to be created.',
  225. 'type': 'string',
  226. },
  227. 'old_str': {
  228. 'description': 'Required parameter of `str_replace` command containing the string in `path` to replace.',
  229. 'type': 'string',
  230. },
  231. 'new_str': {
  232. 'description': 'Optional parameter of `str_replace` command containing the new string (if not given, no string will be added). Required parameter of `insert` command containing the string to insert.',
  233. 'type': 'string',
  234. },
  235. 'insert_line': {
  236. 'description': 'Required parameter of `insert` command. The `new_str` will be inserted AFTER the line `insert_line` of `path`.',
  237. 'type': 'integer',
  238. },
  239. 'view_range': {
  240. 'description': 'Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.',
  241. 'items': {'type': 'integer'},
  242. 'type': 'array',
  243. },
  244. },
  245. 'required': ['command', 'path'],
  246. },
  247. ),
  248. )
  249. # from browsergym/core/action/highlevel.py
  250. _browser_action_space = HighLevelActionSet(
  251. subsets=['bid', 'nav'],
  252. strict=False, # less strict on the parsing of the actions
  253. multiaction=True, # enable to agent to take multiple actions at once
  254. )
  255. _BROWSER_DESCRIPTION = """Interact with the browser using Python code.
  256. The following 15 functions are available. Nothing else is supported.
  257. goto(url: str)
  258. Description: Navigate to a url.
  259. Examples:
  260. goto('http://www.example.com')
  261. go_back()
  262. Description: Navigate to the previous page in history.
  263. Examples:
  264. go_back()
  265. go_forward()
  266. Description: Navigate to the next page in history.
  267. Examples:
  268. go_forward()
  269. noop(wait_ms: float = 1000)
  270. Description: Do nothing, and optionally wait for the given time (in milliseconds).
  271. You can use this to get the current page content and/or wait for the page to load.
  272. Examples:
  273. noop()
  274. noop(500)
  275. scroll(delta_x: float, delta_y: float)
  276. Description: Scroll horizontally and vertically. Amounts in pixels, positive for right or down scrolling, negative for left or up scrolling. Dispatches a wheel event.
  277. Examples:
  278. scroll(0, 200)
  279. scroll(-50.2, -100.5)
  280. fill(bid: str, value: str)
  281. Description: Fill out a form field. It focuses the element and triggers an input event with the entered text. It works for <input>, <textarea> and [contenteditable] elements.
  282. Examples:
  283. fill('237', 'example value')
  284. fill('45', 'multi-line\nexample')
  285. fill('a12', 'example with "quotes"')
  286. select_option(bid: str, options: str | list[str])
  287. Description: Select one or multiple options in a <select> element. You can specify option value or label to select. Multiple options can be selected.
  288. Examples:
  289. select_option('a48', 'blue')
  290. select_option('c48', ['red', 'green', 'blue'])
  291. click(bid: str, button: Literal['left', 'middle', 'right'] = 'left', modifiers: list[typing.Literal['Alt', 'Control', 'ControlOrMeta', 'Meta', 'Shift']] = [])
  292. Description: Click an element.
  293. Examples:
  294. click('a51')
  295. click('b22', button='right')
  296. click('48', button='middle', modifiers=['Shift'])
  297. dblclick(bid: str, button: Literal['left', 'middle', 'right'] = 'left', modifiers: list[typing.Literal['Alt', 'Control', 'ControlOrMeta', 'Meta', 'Shift']] = [])
  298. Description: Double click an element.
  299. Examples:
  300. dblclick('12')
  301. dblclick('ca42', button='right')
  302. dblclick('178', button='middle', modifiers=['Shift'])
  303. hover(bid: str)
  304. Description: Hover over an element.
  305. Examples:
  306. hover('b8')
  307. press(bid: str, key_comb: str)
  308. Description: Focus the matching element and press a combination of keys. It accepts the logical key names that are emitted in the keyboardEvent.key property of the keyboard events: Backquote, Minus, Equal, Backslash, Backspace, Tab, Delete, Escape, ArrowDown, End, Enter, Home, Insert, PageDown, PageUp, ArrowRight, ArrowUp, F1 - F12, Digit0 - Digit9, KeyA - KeyZ, etc. You can alternatively specify a single character you'd like to produce such as "a" or "#". Following modification shortcuts are also supported: Shift, Control, Alt, Meta, ShiftLeft, ControlOrMeta. ControlOrMeta resolves to Control on Windows and Linux and to Meta on macOS.
  309. Examples:
  310. press('88', 'Backspace')
  311. press('a26', 'ControlOrMeta+a')
  312. press('a61', 'Meta+Shift+t')
  313. focus(bid: str)
  314. Description: Focus the matching element.
  315. Examples:
  316. focus('b455')
  317. clear(bid: str)
  318. Description: Clear the input field.
  319. Examples:
  320. clear('996')
  321. drag_and_drop(from_bid: str, to_bid: str)
  322. Description: Perform a drag & drop. Hover the element that will be dragged. Press left mouse button. Move mouse to the element that will receive the drop. Release left mouse button.
  323. Examples:
  324. drag_and_drop('56', '498')
  325. upload_file(bid: str, file: str | list[str])
  326. Description: Click an element and wait for a "filechooser" event, then select one or multiple input files for upload. Relative file paths are resolved relative to the current working directory. An empty list clears the selected files.
  327. Examples:
  328. upload_file('572', '/home/user/my_receipt.pdf')
  329. upload_file('63', ['/home/bob/Documents/image.jpg', '/home/bob/Documents/file.zip'])
  330. Multiple actions can be provided at once, but will be executed sequentially without any feedback from the page.
  331. More than 2-3 actions usually leads to failure or unexpected behavior. Example:
  332. fill('a12', 'example with "quotes"')
  333. click('a51')
  334. click('48', button='middle', modifiers=['Shift'])
  335. """
  336. for _, action in _browser_action_space.action_set.items():
  337. assert (
  338. action.signature in _BROWSER_DESCRIPTION
  339. ), f'Browser description mismatch. Please double check if the BrowserGym updated their action space.\n\nAction: {action.signature}'
  340. assert (
  341. action.description in _BROWSER_DESCRIPTION
  342. ), f'Browser description mismatch. Please double check if the BrowserGym updated their action space.\n\nAction: {action.description}'
  343. BrowserTool = ChatCompletionToolParam(
  344. type='function',
  345. function=ChatCompletionToolParamFunctionChunk(
  346. name='browser',
  347. description=_BROWSER_DESCRIPTION,
  348. parameters={
  349. 'type': 'object',
  350. 'properties': {
  351. 'code': {
  352. 'type': 'string',
  353. 'description': 'The Python code that interacts with the browser.',
  354. }
  355. },
  356. 'required': ['code'],
  357. },
  358. ),
  359. )
  360. _FINISH_DESCRIPTION = """Finish the interaction when the task is complete OR if the assistant cannot proceed further with the task."""
  361. FinishTool = ChatCompletionToolParam(
  362. type='function',
  363. function=ChatCompletionToolParamFunctionChunk(
  364. name='finish',
  365. description=_FINISH_DESCRIPTION,
  366. ),
  367. )
  368. def combine_thought(action: Action, thought: str) -> Action:
  369. if not hasattr(action, 'thought'):
  370. return action
  371. if thought:
  372. action.thought = thought
  373. return action
  374. def response_to_actions(response: ModelResponse) -> list[Action]:
  375. actions: list[Action] = []
  376. assert len(response.choices) == 1, 'Only one choice is supported for now'
  377. assistant_msg = response.choices[0].message
  378. if assistant_msg.tool_calls:
  379. # Check if there's assistant_msg.content. If so, add it to the thought
  380. thought = ''
  381. if isinstance(assistant_msg.content, str):
  382. thought = assistant_msg.content
  383. elif isinstance(assistant_msg.content, list):
  384. for msg in assistant_msg.content:
  385. if msg['type'] == 'text':
  386. thought += msg['text']
  387. # Process each tool call to OpenHands action
  388. for i, tool_call in enumerate(assistant_msg.tool_calls):
  389. action: Action
  390. try:
  391. arguments = json.loads(tool_call.function.arguments)
  392. except json.decoder.JSONDecodeError as e:
  393. raise RuntimeError(
  394. f'Failed to parse tool call arguments: {tool_call.function.arguments}'
  395. ) from e
  396. if tool_call.function.name == 'execute_bash':
  397. action = CmdRunAction(**arguments)
  398. elif tool_call.function.name == 'execute_ipython_cell':
  399. action = IPythonRunCellAction(**arguments)
  400. elif tool_call.function.name == 'delegate_to_browsing_agent':
  401. action = AgentDelegateAction(
  402. agent='BrowsingAgent',
  403. inputs=arguments,
  404. )
  405. elif tool_call.function.name == 'finish':
  406. action = AgentFinishAction()
  407. elif tool_call.function.name == 'edit_file':
  408. action = FileEditAction(**arguments)
  409. elif tool_call.function.name == 'str_replace_editor':
  410. # We implement this in agent_skills, which can be used via Jupyter
  411. # convert tool_call.function.arguments to kwargs that can be passed to file_editor
  412. code = f'print(file_editor(**{arguments}))'
  413. logger.debug(
  414. f'TOOL CALL: str_replace_editor -> file_editor with code: {code}'
  415. )
  416. action = IPythonRunCellAction(code=code, include_extra=False)
  417. elif tool_call.function.name == 'browser':
  418. action = BrowseInteractiveAction(browser_actions=arguments['code'])
  419. else:
  420. raise RuntimeError(f'Unknown tool call: {tool_call.function.name}')
  421. # We only add thought to the first action
  422. if i == 0:
  423. action = combine_thought(action, thought)
  424. # Add metadata for tool calling
  425. action.tool_call_metadata = ToolCallMetadata(
  426. tool_call_id=tool_call.id,
  427. function_name=tool_call.function.name,
  428. model_response=response,
  429. total_calls_in_response=len(assistant_msg.tool_calls),
  430. )
  431. actions.append(action)
  432. else:
  433. actions.append(
  434. MessageAction(content=assistant_msg.content, wait_for_response=True)
  435. )
  436. assert len(actions) >= 1
  437. return actions
  438. def get_tools(
  439. codeact_enable_browsing: bool = False,
  440. codeact_enable_llm_editor: bool = False,
  441. codeact_enable_jupyter: bool = False,
  442. ) -> list[ChatCompletionToolParam]:
  443. tools = [CmdRunTool, FinishTool]
  444. if codeact_enable_browsing:
  445. tools.append(BrowserTool)
  446. if codeact_enable_jupyter:
  447. tools.append(IPythonTool)
  448. if codeact_enable_llm_editor:
  449. tools.append(LLMBasedFileEditTool)
  450. else:
  451. tools.append(StrReplaceEditorTool)
  452. return tools