react.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import os
  2. tools_text = """code_interpreter: Call this tool to interact with the Code Interpreter API.
  3. What is the Code Interpreter API useful for?
  4. Code Interpreter is used to execute Python code to deal with the following tasks:
  5. 1. Solving mathematical problems, both quantitative and qualitative
  6. 2. Doing data analysis and visualization
  7. 3. Converting files between formats
  8. Parameters:
  9. ```py
  10. code
  11. ```
  12. Enclose the code within triple backticks (```) at the beginning and end of the code.
  13. """
  14. REACT_PROMPT = """Answer the following questions as best you can. You have access to the following tools:
  15. {tools_text}
  16. Use the following format:
  17. Question: the input question you must answer
  18. Thought: you should always think about what to do
  19. Action: the action to take, should be one of [{tools_name_text}]
  20. Action Input: the input to the action
  21. Observation: the result of the action
  22. ... (this Thought/Action/Action Input/Observation can be repeated zero or more times)
  23. Thought: I now know the final answer
  24. Final Answer: the final answer to the original input question
  25. Begin!
  26. Question: {query}"""
  27. fname_template = {
  28. 'zh': '文件{fname_str},',
  29. 'en_multi': 'Files {fname_str}. ',
  30. 'en': 'File {fname_str}. ',
  31. }
  32. class ReAct(object):
  33. def __init__(self, query, lang='en', upload_file_paths=[]):
  34. self.query = query
  35. self.lang = lang
  36. self.upload_file_paths = [f'`{os.path.basename(fname)}`' for fname in upload_file_paths]
  37. self.fname_template = fname_template
  38. self.react_template = REACT_PROMPT
  39. self.prompt = ''
  40. def build_prompt(self):
  41. query = self._format_upload_fname() + self.query
  42. tools_text = self._build_tools_text()
  43. tools_name_text = self._build_tools_name_text()
  44. planning_prompt = self.react_template.format(query=query, tools_text=tools_text, tools_name_text=tools_name_text)
  45. self.prompt = planning_prompt
  46. return planning_prompt
  47. def _format_upload_fname(self):
  48. prefix = ''
  49. if self.upload_file_paths:
  50. fname_str = ', '.join(self.upload_file_paths)
  51. lang_key = 'en_multi' if self.lang == 'en' and len(self.upload_file_paths) > 1 else self.lang
  52. fname_template = self.fname_template[lang_key]
  53. prefix = fname_template.format(fname_str=fname_str)
  54. return prefix
  55. def _build_tools_text(self):
  56. return tools_text
  57. def _build_tools_name_text(self):
  58. return 'code_interpreter'
  59. def build_observation(self, observation):
  60. return f'\nObservation: {observation}\nThought:'
  61. def get_stop_words_list(self):
  62. return ['Observation:', 'Observation:\n']