天天看點

AutoGPT on LangChain PromptGenerator等源碼解析

作者:矽谷ChatGPT和LLM中心

本節閱讀AutoGPT 的prompt_generator.py源代碼,其中定義了一個PromptGenerator類和一個get_prompt函數,用于生成一個提示詞資訊。PromptGenerator類提供了添加限制、指令、資源和性能評估等内容的方法,_generate_numbered_list私有方法用于生成帶序号的清單。get_prompt函數調用PromptGenerator類的方法來生成完整的提示資訊字元串,并将其作為字元串傳回。提示資訊包括了各種限制、指令、資源和性能評估等内容,以及響應的格式。

如圖13-10所示,AutoGPT是一個不斷循環的過程。

AutoGPT on LangChain PromptGenerator等源碼解析

圖13- 10 AutoGPT的運作機制

我們看一下PromptGenerator類的初始化方法,因為AutoGPT要不斷循環,是以定義了一個空的限制清單、指令清單、資源清單和性能評估清單,對實時的狀态進行管理,并且還定義了一個response_format字典,用于描述響應資訊的格式。

prompt_generator.py的PromptGenerator的代碼實作:

  1. class PromptGenerator:
  2. """ 用于生成自定義提示字元串的類。
  3. 基于限制、指令、資源和性能評估來執行此操作。
  4. """
  5. def __init__(self) -> None:
  6. """ 初始化PromptGenerator對象。
  7. 從限制、指令、資源和性能評估的空清單開始。
  8. """
  9. self.constraints: List[str] = []
  10. self.commands: List[BaseTool] = []
  11. self.resources: List[str] = []
  12. self.performance_evaluation: List[str] = []
  13. self.response_format = {
  14. "thoughts": {
  15. "text": "thought",
  16. "reasoning": "reasoning",
  17. "plan": "- short bulleted\n- list that conveys\n- long-term plan",
  18. "criticism": "constructive self-criticism",
  19. "speak": "thoughts summary to say to user",
  20. },
  21. "command": {"name": "command name", "args": {"arg name": "value"}},
  22. }

以上代碼中在響應資訊中定義了:“text(thought)”、“reasoning”、“plan”、“criticism”、“speak”等内容,論文“Auto-GPT for Online Decision Making: Benchmarks and Additional Opinions” 在引言中談到:AutoGPT通過為每一步行動産生“思考”、“原因”、“計劃”和“反思”來進行自我改進,這邊代碼的實作和論文的描述是一樣的。

PromptGenerator類中的add_constraint、add_tool、add_resource和add_performance_evaluation方法分别用于向限制清單、指令清單、資源清單和性能評估清單中添加内容。_generate_command_string方法用于生成一個指令字元串,包括指令名稱、指令描述和指令參數的JSON模式。

_generate_numbered_list方法用于生成一個帶序号的清單,根據不同的item_type參數(預設為清單類型)來生成不同類型的清單。如果item_type為command,則它會使用_generate_command_string方法來生成一個帶參數JSON模式的指令字元串,并且還會添加一個特殊的FINISH_NAME指令,用于表示完成了所有的任務。

prompt_generator.py的_generate_numbered_list方法的代碼實作:

  1. def _generate_numbered_list(self, items: list, item_type: str = "list") -> str:
  2. """
  3. 根據item_type從給定項目生成編号清單
  4. 參數:
  5. items (list): 要編号的項目清單
  6. item_type (str, optional): 清單中項目的類型,預設為“list”。
  7. 傳回:
  8. str: 格式化的編号清單
  9. """
  10. if item_type == "command":
  11. command_strings = [
  12. f"{i + 1}. {self._generate_command_string(item)}"
  13. for i, item in enumerate(items)
  14. ]
  15. finish_description = (
  16. "use this to signal that you have finished all your objectives"
  17. )
  18. finish_args = (
  19. '"response": "final response to let '
  20. 'people know you have finished your objectives"'
  21. )
  22. finish_string = (
  23. f"{len(items) + 1}. {FINISH_NAME}: "
  24. f"{finish_description}, args: {finish_args}"
  25. )
  26. return "\n".join(command_strings + [finish_string])
  27. else:
  28. return "\n".join(f"{i+1}. {item}" for i, item in enumerate(items))
  29. ...

generate_prompt_string方法用于生成完整的提示資訊字元串。它使用_generate_numbered_list方法生成帶序号的限制、指令、資源和性能評估清單,并且包括了response_format的描述資訊。

prompt_generator.py的generate_prompt_string方法的代碼實作:

  1. def generate_prompt_string(self) -> str:
  2. """ 生成提示字元串
  3. 傳回:
  4. str: 生成的提示字元串.
  5. """
  6. formatted_response_format = json.dumps(self.response_format, indent=4)
  7. prompt_string = (
  8. f"Constraints:\n{self._generate_numbered_list(self.constraints)}\n\n"
  9. f"Commands:\n"
  10. f"{self._generate_numbered_list(self.commands, item_type='command')}\n\n"
  11. f"Resources:\n{self._generate_numbered_list(self.resources)}\n\n"
  12. f"Performance Evaluation:\n"
  13. f"{self._generate_numbered_list(self.performance_evaluation)}\n\n"
  14. f"You should only respond in JSON format as described below "
  15. f"\nResponse Format: \n{formatted_response_format} "
  16. f"\nEnsure the response can be parsed by Python json.loads"
  17. )
  18. return prompt_string

get_prompt函數調用PromptGenerator類的方法來生成完整的提示資訊,并将其作為字元串傳回。get_prompt函數是一個核心函數,因為在循環的過程中會不斷的去産生提示詞。

prompt_generator.py的get_prompt方法的代碼實作:

  1. def get_prompt(tools: List[BaseTool]) -> str:
  2. """ 此函數生成一個提示字元串。
  3. 它包括各種限制、指令、資源和性能評估
  4. 傳回:
  5. str: 生成的提示字元串
  6. """
  7. # 初始化PromptGenerator對象
  8. prompt_generator = PromptGenerator()
  9. # 向PromptGenerator對象添加限制
  10. prompt_generator.add_constraint(
  11. "~4000 word limit for short term memory. "
  12. "Your short term memory is short, "
  13. "so immediately save important information to files."
  14. )
  15. prompt_generator.add_constraint(
  16. "If you are unsure how you previously did something "
  17. "or want to recall past events, "
  18. "thinking about similar events will help you remember."
  19. )
  20. prompt_generator.add_constraint("No user assistance")
  21. prompt_generator.add_constraint(
  22. 'Exclusively use the commands listed in double quotes e.g. "command name"'
  23. )
  24. # 将指令添加到PromptGenerator對象
  25. for tool in tools:
  26. prompt_generator.add_tool(tool)
  27. # 向PromptGenerator對象添加資源
  28. prompt_generator.add_resource(
  29. "Internet access for searches and information gathering."
  30. )
  31. prompt_generator.add_resource("Long Term memory management.")
  32. prompt_generator.add_resource(
  33. "GPT-3.5 powered Agents for delegation of simple tasks."
  34. )
  35. prompt_generator.add_resource("File output.")
  36. # 将性能評估添加到PromptGenerator對象
  37. prompt_generator.add_performance_evaluation(
  38. "Continuously review and analyze your actions "
  39. "to ensure you are performing to the best of your abilities."
  40. )
  41. prompt_generator.add_performance_evaluation(
  42. "Constructively self-criticize your big-picture behavior constantly."
  43. )
  44. prompt_generator.add_performance_evaluation(
  45. "Reflect on past decisions and strategies to refine your approach."
  46. )
  47. prompt_generator.add_performance_evaluation(
  48. "Every command has a cost, so be smart and efficient. "
  49. "Aim to complete tasks in the least number of steps."
  50. )
  51. # Generate the prompt string
  52. prompt_string = prompt_generator.generate_prompt_string()
  53. return prompt_string

如果按照前面的描述,你會發現AutoGPT本質上是一個循環及對狀态的管理,基于模型和工具進行操作,這個思路不僅适用于AutoGPT,也适用于一切代理。

繼續閱讀