本節閱讀AutoGPT 的prompt_generator.py源代碼,其中定義了一個PromptGenerator類和一個get_prompt函數,用于生成一個提示詞資訊。PromptGenerator類提供了添加限制、指令、資源和性能評估等内容的方法,_generate_numbered_list私有方法用于生成帶序号的清單。get_prompt函數調用PromptGenerator類的方法來生成完整的提示資訊字元串,并将其作為字元串傳回。提示資訊包括了各種限制、指令、資源和性能評估等内容,以及響應的格式。
如圖13-10所示,AutoGPT是一個不斷循環的過程。
圖13- 10 AutoGPT的運作機制
我們看一下PromptGenerator類的初始化方法,因為AutoGPT要不斷循環,是以定義了一個空的限制清單、指令清單、資源清單和性能評估清單,對實時的狀态進行管理,并且還定義了一個response_format字典,用于描述響應資訊的格式。
prompt_generator.py的PromptGenerator的代碼實作:
- class PromptGenerator:
- """ 用于生成自定義提示字元串的類。
- 基于限制、指令、資源和性能評估來執行此操作。
- """
- def __init__(self) -> None:
- """ 初始化PromptGenerator對象。
- 從限制、指令、資源和性能評估的空清單開始。
- """
- self.constraints: List[str] = []
- self.commands: List[BaseTool] = []
- self.resources: List[str] = []
- self.performance_evaluation: List[str] = []
- self.response_format = {
- "thoughts": {
- "text": "thought",
- "reasoning": "reasoning",
- "plan": "- short bulleted\n- list that conveys\n- long-term plan",
- "criticism": "constructive self-criticism",
- "speak": "thoughts summary to say to user",
- },
- "command": {"name": "command name", "args": {"arg name": "value"}},
- }
以上代碼中在響應資訊中定義了:“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方法的代碼實作:
- def _generate_numbered_list(self, items: list, item_type: str = "list") -> str:
- """
- 根據item_type從給定項目生成編号清單
- 參數:
- items (list): 要編号的項目清單
- item_type (str, optional): 清單中項目的類型,預設為“list”。
- 傳回:
- str: 格式化的編号清單
- """
- if item_type == "command":
- command_strings = [
- f"{i + 1}. {self._generate_command_string(item)}"
- for i, item in enumerate(items)
- ]
- finish_description = (
- "use this to signal that you have finished all your objectives"
- )
- finish_args = (
- '"response": "final response to let '
- 'people know you have finished your objectives"'
- )
- finish_string = (
- f"{len(items) + 1}. {FINISH_NAME}: "
- f"{finish_description}, args: {finish_args}"
- )
- return "\n".join(command_strings + [finish_string])
- else:
- return "\n".join(f"{i+1}. {item}" for i, item in enumerate(items))
- ...
generate_prompt_string方法用于生成完整的提示資訊字元串。它使用_generate_numbered_list方法生成帶序号的限制、指令、資源和性能評估清單,并且包括了response_format的描述資訊。
prompt_generator.py的generate_prompt_string方法的代碼實作:
- def generate_prompt_string(self) -> str:
- """ 生成提示字元串
- 傳回:
- str: 生成的提示字元串.
- """
- formatted_response_format = json.dumps(self.response_format, indent=4)
- prompt_string = (
- f"Constraints:\n{self._generate_numbered_list(self.constraints)}\n\n"
- f"Commands:\n"
- f"{self._generate_numbered_list(self.commands, item_type='command')}\n\n"
- f"Resources:\n{self._generate_numbered_list(self.resources)}\n\n"
- f"Performance Evaluation:\n"
- f"{self._generate_numbered_list(self.performance_evaluation)}\n\n"
- f"You should only respond in JSON format as described below "
- f"\nResponse Format: \n{formatted_response_format} "
- f"\nEnsure the response can be parsed by Python json.loads"
- )
- return prompt_string
get_prompt函數調用PromptGenerator類的方法來生成完整的提示資訊,并将其作為字元串傳回。get_prompt函數是一個核心函數,因為在循環的過程中會不斷的去産生提示詞。
prompt_generator.py的get_prompt方法的代碼實作:
- def get_prompt(tools: List[BaseTool]) -> str:
- """ 此函數生成一個提示字元串。
- 它包括各種限制、指令、資源和性能評估
- 傳回:
- str: 生成的提示字元串
- """
- # 初始化PromptGenerator對象
- prompt_generator = PromptGenerator()
- # 向PromptGenerator對象添加限制
- prompt_generator.add_constraint(
- "~4000 word limit for short term memory. "
- "Your short term memory is short, "
- "so immediately save important information to files."
- )
- prompt_generator.add_constraint(
- "If you are unsure how you previously did something "
- "or want to recall past events, "
- "thinking about similar events will help you remember."
- )
- prompt_generator.add_constraint("No user assistance")
- prompt_generator.add_constraint(
- 'Exclusively use the commands listed in double quotes e.g. "command name"'
- )
- # 将指令添加到PromptGenerator對象
- for tool in tools:
- prompt_generator.add_tool(tool)
- # 向PromptGenerator對象添加資源
- prompt_generator.add_resource(
- "Internet access for searches and information gathering."
- )
- prompt_generator.add_resource("Long Term memory management.")
- prompt_generator.add_resource(
- "GPT-3.5 powered Agents for delegation of simple tasks."
- )
- prompt_generator.add_resource("File output.")
- # 将性能評估添加到PromptGenerator對象
- prompt_generator.add_performance_evaluation(
- "Continuously review and analyze your actions "
- "to ensure you are performing to the best of your abilities."
- )
- prompt_generator.add_performance_evaluation(
- "Constructively self-criticize your big-picture behavior constantly."
- )
- prompt_generator.add_performance_evaluation(
- "Reflect on past decisions and strategies to refine your approach."
- )
- prompt_generator.add_performance_evaluation(
- "Every command has a cost, so be smart and efficient. "
- "Aim to complete tasks in the least number of steps."
- )
- # Generate the prompt string
- prompt_string = prompt_generator.generate_prompt_string()
- return prompt_string
如果按照前面的描述,你會發現AutoGPT本質上是一個循環及對狀态的管理,基于模型和工具進行操作,這個思路不僅适用于AutoGPT,也适用于一切代理。