agentskills.py 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  1. """agentskills.py
  2. This module provides various file manipulation skills for the OpenDevin agent.
  3. Functions:
  4. - open_file(path: str, line_number: int | None = 1, context_lines: int = 100): Opens a file and optionally moves to a specific line.
  5. - goto_line(line_number): Moves the window to show the specified line number.
  6. - scroll_down(): Moves the window down by the number of lines specified in WINDOW.
  7. - scroll_up(): Moves the window up by the number of lines specified in WINDOW.
  8. - create_file(filename): Creates and opens a new file with the given name.
  9. - search_dir(search_term, dir_path='./'): Searches for a term in all files in the specified directory.
  10. - search_file(search_term, file_path=None): Searches for a term in the specified file or the currently open file.
  11. - find_file(file_name, dir_path='./'): Finds all files with the given name in the specified directory.
  12. - edit_file_by_replace(file_name: str, to_replace: str, new_content: str): Replaces lines in a file with the given content.
  13. - insert_content_at_line(file_name: str, line_number: int, content: str): Inserts given content at the specified line number in a file.
  14. - append_file(file_name: str, content: str): Appends the given content to the end of the specified file.
  15. """
  16. import base64
  17. import os
  18. import re
  19. import shutil
  20. import tempfile
  21. from inspect import signature
  22. from typing import Optional
  23. import docx
  24. import PyPDF2
  25. from openai import OpenAI
  26. from pptx import Presentation
  27. from pylatexenc.latex2text import LatexNodes2Text
  28. if __package__ is None or __package__ == '':
  29. from aider import Linter
  30. else:
  31. from .aider import Linter
  32. CURRENT_FILE: str | None = None
  33. CURRENT_LINE = 1
  34. WINDOW = 100
  35. # This is also used in unit tests!
  36. MSG_FILE_UPDATED = '[File updated (edited at line {line_number}). Please review the changes and make sure they are correct (correct indentation, no duplicate lines, etc). Edit the file again if necessary.]'
  37. # ==================================================================================================
  38. # OPENAI
  39. # TODO: Move this to EventStream Actions when EventStreamRuntime is fully implemented
  40. # NOTE: we need to get env vars inside functions because they will be set in IPython
  41. # AFTER the agentskills is imported (the case for EventStreamRuntime)
  42. # ==================================================================================================
  43. def _get_openai_api_key():
  44. return os.getenv('OPENAI_API_KEY', os.getenv('SANDBOX_ENV_OPENAI_API_KEY', ''))
  45. def _get_openai_base_url():
  46. return os.getenv('OPENAI_BASE_URL', 'https://api.openai.com/v1')
  47. def _get_openai_model():
  48. return os.getenv('OPENAI_MODEL', 'gpt-4o-2024-05-13')
  49. def _get_max_token():
  50. return os.getenv('MAX_TOKEN', 500)
  51. def _get_openai_client():
  52. client = OpenAI(api_key=_get_openai_api_key(), base_url=_get_openai_base_url())
  53. return client
  54. # ==================================================================================================
  55. def _is_valid_filename(file_name) -> bool:
  56. if not file_name or not isinstance(file_name, str) or not file_name.strip():
  57. return False
  58. invalid_chars = '<>:"/\\|?*'
  59. if os.name == 'nt': # Windows
  60. invalid_chars = '<>:"/\\|?*'
  61. elif os.name == 'posix': # Unix-like systems
  62. invalid_chars = '\0'
  63. for char in invalid_chars:
  64. if char in file_name:
  65. return False
  66. return True
  67. def _is_valid_path(path) -> bool:
  68. if not path or not isinstance(path, str):
  69. return False
  70. try:
  71. return os.path.exists(os.path.normpath(path))
  72. except PermissionError:
  73. return False
  74. def _create_paths(file_name) -> bool:
  75. try:
  76. dirname = os.path.dirname(file_name)
  77. if dirname:
  78. os.makedirs(dirname, exist_ok=True)
  79. return True
  80. except PermissionError:
  81. return False
  82. def _check_current_file(file_path: str | None = None) -> bool:
  83. global CURRENT_FILE
  84. if not file_path:
  85. file_path = CURRENT_FILE
  86. if not file_path or not os.path.isfile(file_path):
  87. raise ValueError('No file open. Use the open_file function first.')
  88. return True
  89. def _clamp(value, min_value, max_value):
  90. return max(min_value, min(value, max_value))
  91. def _lint_file(file_path: str) -> tuple[Optional[str], Optional[int]]:
  92. """Lint the file at the given path and return a tuple with a boolean indicating if there are errors,
  93. and the line number of the first error, if any.
  94. Returns:
  95. tuple[str, Optional[int]]: (lint_error, first_error_line_number)
  96. """
  97. linter = Linter(root=os.getcwd())
  98. lint_error = linter.lint(file_path)
  99. if not lint_error:
  100. # Linting successful. No issues found.
  101. return None, None
  102. return 'ERRORS:\n' + lint_error.text, lint_error.lines[0]
  103. def _print_window(file_path, targeted_line, window, return_str=False):
  104. global CURRENT_LINE
  105. _check_current_file(file_path)
  106. with open(file_path) as file:
  107. content = file.read()
  108. # Ensure the content ends with a newline character
  109. if not content.endswith('\n'):
  110. content += '\n'
  111. lines = content.splitlines(True) # Keep all line ending characters
  112. total_lines = len(lines)
  113. # cover edge cases
  114. CURRENT_LINE = _clamp(targeted_line, 1, total_lines)
  115. half_window = max(1, window // 2)
  116. # Ensure at least one line above and below the targeted line
  117. start = max(1, CURRENT_LINE - half_window)
  118. end = min(total_lines, CURRENT_LINE + half_window)
  119. # Adjust start and end to ensure at least one line above and below
  120. if start == 1:
  121. end = min(total_lines, start + window - 1)
  122. if end == total_lines:
  123. start = max(1, end - window + 1)
  124. output = ''
  125. # only display this when there's at least one line above
  126. if start > 1:
  127. output += f'({start - 1} more lines above)\n'
  128. else:
  129. output += '(this is the beginning of the file)\n'
  130. for i in range(start, end + 1):
  131. _new_line = f'{i}|{lines[i-1]}'
  132. if not _new_line.endswith('\n'):
  133. _new_line += '\n'
  134. output += _new_line
  135. if end < total_lines:
  136. output += f'({total_lines - end} more lines below)\n'
  137. else:
  138. output += '(this is the end of the file)\n'
  139. output = output.rstrip()
  140. if return_str:
  141. return output
  142. else:
  143. print(output)
  144. def _cur_file_header(current_file, total_lines) -> str:
  145. if not current_file:
  146. return ''
  147. return f'[File: {os.path.abspath(current_file)} ({total_lines} lines total)]\n'
  148. def open_file(
  149. path: str, line_number: int | None = 1, context_lines: int | None = WINDOW
  150. ) -> None:
  151. """Opens the file at the given path in the editor. If line_number is provided, the window will be moved to include that line.
  152. It only shows the first 100 lines by default! Max `context_lines` supported is 2000, use `scroll up/down`
  153. to view the file if you want to see more.
  154. Args:
  155. path: str: The path to the file to open, preferred absolute path.
  156. line_number: int | None = 1: The line number to move to. Defaults to 1.
  157. context_lines: int | None = 100: Only shows this number of lines in the context window (usually from line 1), with line_number as the center (if possible). Defaults to 100.
  158. """
  159. global CURRENT_FILE, CURRENT_LINE, WINDOW
  160. if not os.path.isfile(path):
  161. raise FileNotFoundError(f'File {path} not found')
  162. CURRENT_FILE = os.path.abspath(path)
  163. with open(CURRENT_FILE) as file:
  164. total_lines = max(1, sum(1 for _ in file))
  165. if not isinstance(line_number, int) or line_number < 1 or line_number > total_lines:
  166. raise ValueError(f'Line number must be between 1 and {total_lines}')
  167. CURRENT_LINE = line_number
  168. # Override WINDOW with context_lines
  169. if context_lines is None or context_lines < 1:
  170. context_lines = WINDOW
  171. output = _cur_file_header(CURRENT_FILE, total_lines)
  172. output += _print_window(
  173. CURRENT_FILE, CURRENT_LINE, _clamp(context_lines, 1, 2000), return_str=True
  174. )
  175. print(output)
  176. def goto_line(line_number: int) -> None:
  177. """Moves the window to show the specified line number.
  178. Args:
  179. line_number: int: The line number to move to.
  180. """
  181. global CURRENT_FILE, CURRENT_LINE, WINDOW
  182. _check_current_file()
  183. with open(str(CURRENT_FILE)) as file:
  184. total_lines = max(1, sum(1 for _ in file))
  185. if not isinstance(line_number, int) or line_number < 1 or line_number > total_lines:
  186. raise ValueError(f'Line number must be between 1 and {total_lines}')
  187. CURRENT_LINE = _clamp(line_number, 1, total_lines)
  188. output = _cur_file_header(CURRENT_FILE, total_lines)
  189. output += _print_window(CURRENT_FILE, CURRENT_LINE, WINDOW, return_str=True)
  190. print(output)
  191. def scroll_down() -> None:
  192. """Moves the window down by 100 lines.
  193. Args:
  194. None
  195. """
  196. global CURRENT_FILE, CURRENT_LINE, WINDOW
  197. _check_current_file()
  198. with open(str(CURRENT_FILE)) as file:
  199. total_lines = max(1, sum(1 for _ in file))
  200. CURRENT_LINE = _clamp(CURRENT_LINE + WINDOW, 1, total_lines)
  201. output = _cur_file_header(CURRENT_FILE, total_lines)
  202. output += _print_window(CURRENT_FILE, CURRENT_LINE, WINDOW, return_str=True)
  203. print(output)
  204. def scroll_up() -> None:
  205. """Moves the window up by 100 lines.
  206. Args:
  207. None
  208. """
  209. global CURRENT_FILE, CURRENT_LINE, WINDOW
  210. _check_current_file()
  211. with open(str(CURRENT_FILE)) as file:
  212. total_lines = max(1, sum(1 for _ in file))
  213. CURRENT_LINE = _clamp(CURRENT_LINE - WINDOW, 1, total_lines)
  214. output = _cur_file_header(CURRENT_FILE, total_lines)
  215. output += _print_window(CURRENT_FILE, CURRENT_LINE, WINDOW, return_str=True)
  216. print(output)
  217. def create_file(filename: str) -> None:
  218. """Creates and opens a new file with the given name.
  219. Args:
  220. filename: str: The name of the file to create.
  221. """
  222. if os.path.exists(filename):
  223. raise FileExistsError(f"File '{filename}' already exists.")
  224. with open(filename, 'w') as file:
  225. file.write('\n')
  226. open_file(filename)
  227. print(f'[File {filename} created.]')
  228. LINTER_ERROR_MSG = '[Your proposed edit has introduced new syntax error(s). Please understand the errors and retry your edit command.]\n'
  229. class LineNumberError(Exception):
  230. pass
  231. def _append_impl(lines, content):
  232. """Internal method to handle appending to a file.
  233. Args:
  234. lines: list[str]: The lines in the original file.
  235. content: str: The content to append to the file.
  236. Returns:
  237. content: str: The new content of the file.
  238. n_added_lines: int: The number of lines added to the file.
  239. """
  240. content_lines = content.splitlines(keepends=True)
  241. n_added_lines = len(content_lines)
  242. if lines and not (len(lines) == 1 and lines[0].strip() == ''):
  243. # file is not empty
  244. if not lines[-1].endswith('\n'):
  245. lines[-1] += '\n'
  246. new_lines = lines + content_lines
  247. content = ''.join(new_lines)
  248. else:
  249. # file is empty
  250. content = ''.join(content_lines)
  251. return content, n_added_lines
  252. def _insert_impl(lines, start, content):
  253. """Internal method to handle inserting to a file.
  254. Args:
  255. lines: list[str]: The lines in the original file.
  256. start: int: The start line number for inserting.
  257. content: str: The content to insert to the file.
  258. Returns:
  259. content: str: The new content of the file.
  260. n_added_lines: int: The number of lines added to the file.
  261. Raises:
  262. LineNumberError: If the start line number is invalid.
  263. """
  264. inserted_lines = [content + '\n' if not content.endswith('\n') else content]
  265. if len(lines) == 0:
  266. new_lines = inserted_lines
  267. elif start is not None:
  268. if len(lines) == 1 and lines[0].strip() == '':
  269. # if the file with only 1 line and that line is empty
  270. lines = []
  271. if len(lines) == 0:
  272. new_lines = inserted_lines
  273. else:
  274. new_lines = lines[: start - 1] + inserted_lines + lines[start - 1 :]
  275. else:
  276. raise LineNumberError(
  277. f'Invalid line number: {start}. Line numbers must be between 1 and {len(lines)} (inclusive).'
  278. )
  279. content = ''.join(new_lines)
  280. n_added_lines = len(inserted_lines)
  281. return content, n_added_lines
  282. def _edit_impl(lines, start, end, content):
  283. """Internal method to handle editing a file.
  284. REQUIRES (should be checked by caller):
  285. start <= end
  286. start and end are between 1 and len(lines) (inclusive)
  287. content ends with a newline
  288. Args:
  289. lines: list[str]: The lines in the original file.
  290. start: int: The start line number for editing.
  291. end: int: The end line number for editing.
  292. content: str: The content to replace the lines with.
  293. Returns:
  294. content: str: The new content of the file.
  295. n_added_lines: int: The number of lines added to the file.
  296. """
  297. # Handle cases where start or end are None
  298. if start is None:
  299. start = 1 # Default to the beginning
  300. if end is None:
  301. end = len(lines) # Default to the end
  302. # Check arguments
  303. if not (1 <= start <= len(lines)):
  304. raise LineNumberError(
  305. f'Invalid start line number: {start}. Line numbers must be between 1 and {len(lines)} (inclusive).'
  306. )
  307. if not (1 <= end <= len(lines)):
  308. raise LineNumberError(
  309. f'Invalid end line number: {end}. Line numbers must be between 1 and {len(lines)} (inclusive).'
  310. )
  311. if start > end:
  312. raise LineNumberError(
  313. f'Invalid line range: {start}-{end}. Start must be less than or equal to end.'
  314. )
  315. if not content.endswith('\n'):
  316. content += '\n'
  317. content_lines = content.splitlines(True)
  318. n_added_lines = len(content_lines)
  319. new_lines = lines[: start - 1] + content_lines + lines[end:]
  320. content = ''.join(new_lines)
  321. return content, n_added_lines
  322. def _edit_file_impl(
  323. file_name: str,
  324. start: int | None = None,
  325. end: int | None = None,
  326. content: str = '',
  327. is_insert: bool = False,
  328. is_append: bool = False,
  329. ) -> str:
  330. """Internal method to handle common logic for edit_/append_file methods.
  331. Args:
  332. file_name: str: The name of the file to edit or append to.
  333. start: int | None = None: The start line number for editing. Ignored if is_append is True.
  334. end: int | None = None: The end line number for editing. Ignored if is_append is True.
  335. content: str: The content to replace the lines with or to append.
  336. is_insert: bool = False: Whether to insert content at the given line number instead of editing.
  337. is_append: bool = False: Whether to append content to the file instead of editing.
  338. """
  339. ret_str = ''
  340. global CURRENT_FILE, CURRENT_LINE, WINDOW
  341. ERROR_MSG = f'[Error editing file {file_name}. Please confirm the file is correct.]'
  342. ERROR_MSG_SUFFIX = (
  343. 'Your changes have NOT been applied. Please fix your edit command and try again.\n'
  344. 'You either need to 1) Open the correct file and try again or 2) Specify the correct line number arguments.\n'
  345. 'DO NOT re-run the same failed edit command. Running it again will lead to the same error.'
  346. )
  347. if not _is_valid_filename(file_name):
  348. raise FileNotFoundError('Invalid file name.')
  349. if not _is_valid_path(file_name):
  350. raise FileNotFoundError('Invalid path or file name.')
  351. if not _create_paths(file_name):
  352. raise PermissionError('Could not access or create directories.')
  353. if not os.path.isfile(file_name):
  354. raise FileNotFoundError(f'File {file_name} not found.')
  355. if is_insert and is_append:
  356. raise ValueError('Cannot insert and append at the same time.')
  357. # Use a temporary file to write changes
  358. content = str(content or '')
  359. temp_file_path = ''
  360. src_abs_path = os.path.abspath(file_name)
  361. first_error_line = None
  362. try:
  363. n_added_lines = None
  364. # Create a temporary file
  365. with tempfile.NamedTemporaryFile('w', delete=False) as temp_file:
  366. temp_file_path = temp_file.name
  367. # Read the original file and check if empty and for a trailing newline
  368. with open(file_name) as original_file:
  369. lines = original_file.readlines()
  370. if is_append:
  371. content, n_added_lines = _append_impl(lines, content)
  372. elif is_insert:
  373. try:
  374. content, n_added_lines = _insert_impl(lines, start, content)
  375. except LineNumberError as e:
  376. ret_str += (f'{ERROR_MSG}\n' f'{e}\n' f'{ERROR_MSG_SUFFIX}') + '\n'
  377. return ret_str
  378. else:
  379. try:
  380. content, n_added_lines = _edit_impl(lines, start, end, content)
  381. except LineNumberError as e:
  382. ret_str += (f'{ERROR_MSG}\n' f'{e}\n' f'{ERROR_MSG_SUFFIX}') + '\n'
  383. return ret_str
  384. if not content.endswith('\n'):
  385. content += '\n'
  386. # Write the new content to the temporary file
  387. temp_file.write(content)
  388. # Replace the original file with the temporary file atomically
  389. shutil.move(temp_file_path, src_abs_path)
  390. # Handle linting
  391. # NOTE: we need to get env var inside this function
  392. # because the env var will be set AFTER the agentskills is imported
  393. enable_auto_lint = os.getenv('ENABLE_AUTO_LINT', 'false').lower() == 'true'
  394. if enable_auto_lint:
  395. # BACKUP the original file
  396. original_file_backup_path = os.path.join(
  397. os.path.dirname(file_name),
  398. f'.backup.{os.path.basename(file_name)}',
  399. )
  400. with open(original_file_backup_path, 'w') as f:
  401. f.writelines(lines)
  402. lint_error, first_error_line = _lint_file(file_name)
  403. if lint_error is not None:
  404. if first_error_line is not None:
  405. show_line = int(first_error_line)
  406. elif is_append:
  407. # original end-of-file
  408. show_line = len(lines)
  409. # insert OR edit WILL provide meaningful line numbers
  410. elif start is not None and end is not None:
  411. show_line = int((start + end) / 2)
  412. else:
  413. raise ValueError('Invalid state. This should never happen.')
  414. ret_str += LINTER_ERROR_MSG
  415. ret_str += lint_error + '\n'
  416. editor_lines = n_added_lines + 20
  417. ret_str += '[This is how your edit would have looked if applied]\n'
  418. ret_str += '-------------------------------------------------\n'
  419. ret_str += (
  420. _print_window(file_name, show_line, editor_lines, return_str=True)
  421. + '\n'
  422. )
  423. ret_str += '-------------------------------------------------\n\n'
  424. ret_str += '[This is the original code before your edit]\n'
  425. ret_str += '-------------------------------------------------\n'
  426. ret_str += (
  427. _print_window(
  428. original_file_backup_path,
  429. show_line,
  430. editor_lines,
  431. return_str=True,
  432. )
  433. + '\n'
  434. )
  435. ret_str += '-------------------------------------------------\n'
  436. ret_str += (
  437. 'Your changes have NOT been applied. Please fix your edit command and try again.\n'
  438. 'You either need to 1) Specify the correct start/end line arguments or 2) Correct your edit code.\n'
  439. 'DO NOT re-run the same failed edit command. Running it again will lead to the same error.'
  440. )
  441. # recover the original file
  442. with open(original_file_backup_path) as fin, open(
  443. file_name, 'w'
  444. ) as fout:
  445. fout.write(fin.read())
  446. os.remove(original_file_backup_path)
  447. return ret_str
  448. except FileNotFoundError as e:
  449. ret_str += f'File not found: {e}\n'
  450. except IOError as e:
  451. ret_str += f'An error occurred while handling the file: {e}\n'
  452. except ValueError as e:
  453. ret_str += f'Invalid input: {e}\n'
  454. except Exception as e:
  455. # Clean up the temporary file if an error occurs
  456. if temp_file_path and os.path.exists(temp_file_path):
  457. os.remove(temp_file_path)
  458. print(f'An unexpected error occurred: {e}')
  459. raise e
  460. # Update the file information and print the updated content
  461. with open(file_name, 'r', encoding='utf-8') as file:
  462. n_total_lines = max(1, len(file.readlines()))
  463. if first_error_line is not None and int(first_error_line) > 0:
  464. CURRENT_LINE = first_error_line
  465. else:
  466. if is_append:
  467. CURRENT_LINE = max(1, len(lines)) # end of original file
  468. else:
  469. CURRENT_LINE = start or n_total_lines or 1
  470. ret_str += f'[File: {os.path.abspath(file_name)} ({n_total_lines} lines total after edit)]\n'
  471. CURRENT_FILE = file_name
  472. ret_str += _print_window(CURRENT_FILE, CURRENT_LINE, WINDOW, return_str=True) + '\n'
  473. ret_str += MSG_FILE_UPDATED.format(line_number=CURRENT_LINE)
  474. return ret_str
  475. def edit_file_by_replace(file_name: str, to_replace: str, new_content: str) -> None:
  476. """Edit a file. This will search for `to_replace` in the given file and replace it with `new_content`.
  477. Every *to_replace* must *EXACTLY MATCH* the existing source code, character for character, including all comments, docstrings, etc.
  478. Include enough lines to make code in `to_replace` unique. `to_replace` should NOT be empty.
  479. For example, given a file "/workspace/example.txt" with the following content:
  480. ```
  481. line 1
  482. line 2
  483. line 2
  484. line 3
  485. ```
  486. EDITING: If you want to replace the second occurrence of "line 2", you can make `to_replace` unique:
  487. edit_file_by_replace(
  488. '/workspace/example.txt',
  489. to_replace='line 2\nline 3',
  490. new_content='new line\nline 3',
  491. )
  492. This will replace only the second "line 2" with "new line". The first "line 2" will remain unchanged.
  493. The resulting file will be:
  494. ```
  495. line 1
  496. line 2
  497. new line
  498. line 3
  499. ```
  500. REMOVAL: If you want to remove "line 2" and "line 3", you can set `new_content` to an empty string:
  501. edit_file_by_replace(
  502. '/workspace/example.txt',
  503. to_replace='line 2\nline 3',
  504. new_content='',
  505. )
  506. Args:
  507. file_name: str: The name of the file to edit.
  508. to_replace: str: The content to search for and replace.
  509. new_content: str: The new content to replace the old content with.
  510. """
  511. # FIXME: support replacing *all* occurrences
  512. if to_replace.strip() == '':
  513. raise ValueError('`to_replace` must not be empty.')
  514. if to_replace == new_content:
  515. raise ValueError('`to_replace` and `new_content` must be different.')
  516. # search for `to_replace` in the file
  517. # if found, replace it with `new_content`
  518. # if not found, perform a fuzzy search to find the closest match and replace it with `new_content`
  519. with open(file_name, 'r') as file:
  520. file_content = file.read()
  521. if file_content.count(to_replace) > 1:
  522. raise ValueError(
  523. '`to_replace` appears more than once, please include enough lines to make code in `to_replace` unique.'
  524. )
  525. start = file_content.find(to_replace)
  526. if start != -1:
  527. # Convert start from index to line number
  528. start_line_number = file_content[:start].count('\n') + 1
  529. end_line_number = start_line_number + len(to_replace.splitlines()) - 1
  530. else:
  531. def _fuzzy_transform(s: str) -> str:
  532. # remove all space except newline
  533. return re.sub(r'[^\S\n]+', '', s)
  534. # perform a fuzzy search (remove all spaces except newlines)
  535. to_replace_fuzzy = _fuzzy_transform(to_replace)
  536. file_content_fuzzy = _fuzzy_transform(file_content)
  537. # find the closest match
  538. start = file_content_fuzzy.find(to_replace_fuzzy)
  539. if start == -1:
  540. print(
  541. f'[No exact match found in {file_name} for\n```\n{to_replace}\n```\n]'
  542. )
  543. return
  544. # Convert start from index to line number for fuzzy match
  545. start_line_number = file_content_fuzzy[:start].count('\n') + 1
  546. end_line_number = start_line_number + len(to_replace.splitlines()) - 1
  547. ret_str = _edit_file_impl(
  548. file_name,
  549. start=start_line_number,
  550. end=end_line_number,
  551. content=new_content,
  552. is_insert=False,
  553. )
  554. # lint_error = bool(LINTER_ERROR_MSG in ret_str)
  555. # TODO: automatically tries to fix linter error (maybe involve some static analysis tools on the location near the edit to figure out indentation)
  556. print(ret_str)
  557. def insert_content_at_line(file_name: str, line_number: int, content: str) -> None:
  558. """Insert content at the given line number in a file.
  559. This will NOT modify the content of the lines before OR after the given line number.
  560. For example, if the file has the following content:
  561. ```
  562. line 1
  563. line 2
  564. line 3
  565. ```
  566. and you call `insert_content_at_line('file.txt', 2, 'new line')`, the file will be updated to:
  567. ```
  568. line 1
  569. new line
  570. line 2
  571. line 3
  572. ```
  573. Args:
  574. file_name: str: The name of the file to edit.
  575. line_number: int: The line number (starting from 1) to insert the content after.
  576. content: str: The content to insert.
  577. """
  578. ret_str = _edit_file_impl(
  579. file_name,
  580. start=line_number,
  581. end=line_number,
  582. content=content,
  583. is_insert=True,
  584. is_append=False,
  585. )
  586. print(ret_str)
  587. def append_file(file_name: str, content: str) -> None:
  588. """Append content to the given file.
  589. It appends text `content` to the end of the specified file.
  590. Args:
  591. file_name: str: The name of the file to edit.
  592. line_number: int: The line number (starting from 1) to insert the content after.
  593. content: str: The content to insert.
  594. """
  595. ret_str = _edit_file_impl(
  596. file_name,
  597. start=None,
  598. end=None,
  599. content=content,
  600. is_insert=False,
  601. is_append=True,
  602. )
  603. print(ret_str)
  604. def search_dir(search_term: str, dir_path: str = './') -> None:
  605. """Searches for search_term in all files in dir. If dir is not provided, searches in the current directory.
  606. Args:
  607. search_term: str: The term to search for.
  608. dir_path: Optional[str]: The path to the directory to search.
  609. """
  610. if not os.path.isdir(dir_path):
  611. raise FileNotFoundError(f'Directory {dir_path} not found')
  612. matches = []
  613. for root, _, files in os.walk(dir_path):
  614. for file in files:
  615. if file.startswith('.'):
  616. continue
  617. file_path = os.path.join(root, file)
  618. with open(file_path, 'r', errors='ignore') as f:
  619. for line_num, line in enumerate(f, 1):
  620. if search_term in line:
  621. matches.append((file_path, line_num, line.strip()))
  622. if not matches:
  623. print(f'No matches found for "{search_term}" in {dir_path}')
  624. return
  625. num_matches = len(matches)
  626. num_files = len(set(match[0] for match in matches))
  627. if num_files > 100:
  628. print(
  629. f'More than {num_files} files matched for "{search_term}" in {dir_path}. Please narrow your search.'
  630. )
  631. return
  632. print(f'[Found {num_matches} matches for "{search_term}" in {dir_path}]')
  633. for file_path, line_num, line in matches:
  634. print(f'{file_path} (Line {line_num}): {line}')
  635. print(f'[End of matches for "{search_term}" in {dir_path}]')
  636. def search_file(search_term: str, file_path: Optional[str] = None) -> None:
  637. """Searches for search_term in file. If file is not provided, searches in the current open file.
  638. Args:
  639. search_term: str: The term to search for.
  640. file_path: Optional[str]: The path to the file to search.
  641. """
  642. global CURRENT_FILE
  643. if file_path is None:
  644. file_path = CURRENT_FILE
  645. if file_path is None:
  646. raise FileNotFoundError(
  647. 'No file specified or open. Use the open_file function first.'
  648. )
  649. if not os.path.isfile(file_path):
  650. raise FileNotFoundError(f'File {file_path} not found')
  651. matches = []
  652. with open(file_path) as file:
  653. for i, line in enumerate(file, 1):
  654. if search_term in line:
  655. matches.append((i, line.strip()))
  656. if matches:
  657. print(f'[Found {len(matches)} matches for "{search_term}" in {file_path}]')
  658. for match in matches:
  659. print(f'Line {match[0]}: {match[1]}')
  660. print(f'[End of matches for "{search_term}" in {file_path}]')
  661. else:
  662. print(f'[No matches found for "{search_term}" in {file_path}]')
  663. def find_file(file_name: str, dir_path: str = './') -> None:
  664. """Finds all files with the given name in the specified directory.
  665. Args:
  666. file_name: str: The name of the file to find.
  667. dir_path: Optional[str]: The path to the directory to search.
  668. """
  669. if not os.path.isdir(dir_path):
  670. raise FileNotFoundError(f'Directory {dir_path} not found')
  671. matches = []
  672. for root, _, files in os.walk(dir_path):
  673. for file in files:
  674. if file_name in file:
  675. matches.append(os.path.join(root, file))
  676. if matches:
  677. print(f'[Found {len(matches)} matches for "{file_name}" in {dir_path}]')
  678. for match in matches:
  679. print(f'{match}')
  680. print(f'[End of matches for "{file_name}" in {dir_path}]')
  681. else:
  682. print(f'[No matches found for "{file_name}" in {dir_path}]')
  683. def parse_pdf(file_path: str) -> None:
  684. """Parses the content of a PDF file and prints it.
  685. Args:
  686. file_path: str: The path to the file to open.
  687. """
  688. print(f'[Reading PDF file from {file_path}]')
  689. content = PyPDF2.PdfReader(file_path)
  690. text = ''
  691. for page_idx in range(len(content.pages)):
  692. text += (
  693. f'@@ Page {page_idx + 1} @@\n'
  694. + content.pages[page_idx].extract_text()
  695. + '\n\n'
  696. )
  697. print(text.strip())
  698. def parse_docx(file_path: str) -> None:
  699. """Parses the content of a DOCX file and prints it.
  700. Args:
  701. file_path: str: The path to the file to open.
  702. """
  703. print(f'[Reading DOCX file from {file_path}]')
  704. content = docx.Document(file_path)
  705. text = ''
  706. for i, para in enumerate(content.paragraphs):
  707. text += f'@@ Page {i + 1} @@\n' + para.text + '\n\n'
  708. print(text)
  709. def parse_latex(file_path: str) -> None:
  710. """Parses the content of a LaTex file and prints it.
  711. Args:
  712. file_path: str: The path to the file to open.
  713. """
  714. print(f'[Reading LaTex file from {file_path}]')
  715. with open(file_path) as f:
  716. data = f.read()
  717. text = LatexNodes2Text().latex_to_text(data)
  718. print(text.strip())
  719. def _base64_img(file_path: str) -> str:
  720. with open(file_path, 'rb') as image_file:
  721. encoded_image = base64.b64encode(image_file.read()).decode('utf-8')
  722. return encoded_image
  723. def _base64_video(file_path: str, frame_interval: int = 10) -> list[str]:
  724. import cv2
  725. video = cv2.VideoCapture(file_path)
  726. base64_frames = []
  727. frame_count = 0
  728. while video.isOpened():
  729. success, frame = video.read()
  730. if not success:
  731. break
  732. if frame_count % frame_interval == 0:
  733. _, buffer = cv2.imencode('.jpg', frame)
  734. base64_frames.append(base64.b64encode(buffer).decode('utf-8'))
  735. frame_count += 1
  736. video.release()
  737. return base64_frames
  738. def _prepare_image_messages(task: str, base64_image: str):
  739. return [
  740. {
  741. 'role': 'user',
  742. 'content': [
  743. {'type': 'text', 'text': task},
  744. {
  745. 'type': 'image_url',
  746. 'image_url': {'url': f'data:image/jpeg;base64,{base64_image}'},
  747. },
  748. ],
  749. }
  750. ]
  751. def parse_audio(file_path: str, model: str = 'whisper-1') -> None:
  752. """Parses the content of an audio file and prints it.
  753. Args:
  754. file_path: str: The path to the audio file to transcribe.
  755. model: Optional[str]: The audio model to use for transcription. Defaults to 'whisper-1'.
  756. """
  757. print(f'[Transcribing audio file from {file_path}]')
  758. try:
  759. # TODO: record the COST of the API call
  760. with open(file_path, 'rb') as audio_file:
  761. transcript = _get_openai_client().audio.translations.create(
  762. model=model, file=audio_file
  763. )
  764. print(transcript.text)
  765. except Exception as e:
  766. print(f'Error transcribing audio file: {e}')
  767. def parse_image(
  768. file_path: str, task: str = 'Describe this image as detail as possible.'
  769. ) -> None:
  770. """Parses the content of an image file and prints the description.
  771. Args:
  772. file_path: str: The path to the file to open.
  773. task: Optional[str]: The task description for the API call. Defaults to 'Describe this image as detail as possible.'.
  774. """
  775. print(f'[Reading image file from {file_path}]')
  776. # TODO: record the COST of the API call
  777. try:
  778. base64_image = _base64_img(file_path)
  779. response = _get_openai_client().chat.completions.create(
  780. model=_get_openai_model(),
  781. messages=_prepare_image_messages(task, base64_image),
  782. max_tokens=_get_max_token(),
  783. )
  784. content = response.choices[0].message.content
  785. print(content)
  786. except Exception as error:
  787. print(f'Error with the request: {error}')
  788. def parse_video(
  789. file_path: str,
  790. task: str = 'Describe this image as detail as possible.',
  791. frame_interval: int = 30,
  792. ) -> None:
  793. """Parses the content of an image file and prints the description.
  794. Args:
  795. file_path: str: The path to the video file to open.
  796. task: Optional[str]: The task description for the API call. Defaults to 'Describe this image as detail as possible.'.
  797. frame_interval: Optional[int]: The interval between frames to analyze. Defaults to 30.
  798. """
  799. print(
  800. f'[Processing video file from {file_path} with frame interval {frame_interval}]'
  801. )
  802. task = task or 'This is one frame from a video, please summarize this frame.'
  803. base64_frames = _base64_video(file_path)
  804. selected_frames = base64_frames[::frame_interval]
  805. if len(selected_frames) > 30:
  806. new_interval = len(base64_frames) // 30
  807. selected_frames = base64_frames[::new_interval]
  808. print(f'Totally {len(selected_frames)} would be analyze...\n')
  809. idx = 0
  810. for base64_frame in selected_frames:
  811. idx += 1
  812. print(f'Process the {file_path}, current No. {idx * frame_interval} frame...')
  813. # TODO: record the COST of the API call
  814. try:
  815. response = _get_openai_client().chat.completions.create(
  816. model=_get_openai_model(),
  817. messages=_prepare_image_messages(task, base64_frame),
  818. max_tokens=_get_max_token(),
  819. )
  820. content = response.choices[0].message.content
  821. current_frame_content = f"Frame {idx}'s content: {content}\n"
  822. print(current_frame_content)
  823. except Exception as error:
  824. print(f'Error with the request: {error}')
  825. def parse_pptx(file_path: str) -> None:
  826. """Parses the content of a pptx file and prints it.
  827. Args:
  828. file_path: str: The path to the file to open.
  829. """
  830. print(f'[Reading PowerPoint file from {file_path}]')
  831. try:
  832. pres = Presentation(str(file_path))
  833. text = []
  834. for slide_idx, slide in enumerate(pres.slides):
  835. text.append(f'@@ Slide {slide_idx + 1} @@')
  836. for shape in slide.shapes:
  837. if hasattr(shape, 'text'):
  838. text.append(shape.text)
  839. print('\n'.join(text))
  840. except Exception as e:
  841. print(f'Error reading PowerPoint file: {e}')
  842. __all__ = [
  843. # file operation
  844. 'open_file',
  845. 'goto_line',
  846. 'scroll_down',
  847. 'scroll_up',
  848. 'create_file',
  849. 'edit_file_by_replace',
  850. 'insert_content_at_line',
  851. 'append_file',
  852. 'search_dir',
  853. 'search_file',
  854. 'find_file',
  855. # readers
  856. 'parse_pdf',
  857. 'parse_docx',
  858. 'parse_latex',
  859. 'parse_pptx',
  860. ]
  861. # This is called from OpenDevin's side
  862. # If SANDBOX_ENV_OPENAI_API_KEY is set, we will be able to use these tools in the sandbox environment
  863. if _get_openai_api_key() and _get_openai_base_url():
  864. __all__ += ['parse_audio', 'parse_video', 'parse_image']
  865. DOCUMENTATION = ''
  866. for func_name in __all__:
  867. func = globals()[func_name]
  868. cur_doc = func.__doc__
  869. # remove indentation from docstring and extra empty lines
  870. cur_doc = '\n'.join(filter(None, map(lambda x: x.strip(), cur_doc.split('\n'))))
  871. # now add a consistent 4 indentation
  872. cur_doc = '\n'.join(map(lambda x: ' ' * 4 + x, cur_doc.split('\n')))
  873. fn_signature = f'{func.__name__}' + str(signature(func))
  874. DOCUMENTATION += f'{fn_signature}:\n{cur_doc}\n\n'