Auto-GPT 是由Toran Bruce Richards创建的一个开源的自主AI代理,基于OpenAI的GPT-4语言模型。它的主要功能是自动链接多个任务,以实现用户设定的大目标。与传统的聊天机器人(如ChatGPT)不同,用户只需提供一个提示或一组自然语言指令,Auto-GPT 就会通过自动化多步提示过程,将目标分解为子任务,以达到其目标。
在BabyAGI中,你向系统提出一个目标之后,它将不断优先考虑需要实现或完成的任务,以实现该目标。具体来说,系统将形成任务列表,从任务列表中拉出优先级最高的第一个任务,使用 OpenAI API 根据上下文将任务发送到执行代理并完成任务,一旦这些任务完成,它们就会被存储在内存(或者Pinecone这类向量数据库)中,然后,根据目标和上一个任务的结果创建新任务并确定优先级。
执行代理,是系统的核心,利用OpenAI的API来处理任务。这个代理的实现函数有两个参数,目标和任务,用于向 OpenAI 的 API 发送提示,并以字符串形式返回任务结果。
任务创建代理,通过OpenAI的API根据当前对象和先前任务的结果创建新任务。这个代理的实现函数有四个参数,目标、上一个任务的结果、任务描述和当前任务列表。这个代理会向 OpenAI 的 API 发送一条提示,该 API 将以字符串形式返回新任务列表。然后,该函数将以字典列表的形式返回这些新任务,其中每个字典都包含任务的名称。
优先级设置代理,负责任务列表的排序和优先级,仍然是通过调用OpenAI 的 API 来重新确定任务列表的优先级。这个代理的实现函数有一个参数,即当前任务的 ID。这个代理会向 OpenAI 的 API 发送提示,并返回已重新优先排序为编号列表的新任务列表。
# 设置API Key import os os.environ["OPENAI_API_KEY"] = 'Your OpenAI API Key
# 导入所需的库和模块 from collections import deque from typing import Dict, List, Optional, Any from langchain.chains import LLMChain from langchain.prompts import PromptTemplate from langchain.embeddings import OpenAIEmbeddings from langchain.llms import BaseLLM, OpenAI from langchain.vectorstores.base import VectorStore from pydantic import BaseModel, Field from langchain.chains.base import Chain from langchain.vectorstores import FAISS import faiss from langchain.docstore import InMemoryDocstore
# 任务生成链 class TaskCreationChain(LLMChain): """负责生成任务的链""" @classmethod def from_llm(cls, llm: BaseLLM, verbose: bool = True) -> LLMChain: """从LLM获取响应解析器""" task_creation_template = ( "You are a task creation AI that uses the result of an execution agent" " to create new tasks with the following objective: {objective}," " The last completed task has the result: {result}." " This result was based on this task description: {task_description}." " These are incomplete tasks: {incomplete_tasks}." " Based on the result, create new tasks to be completed" " by the AI system that do not overlap with incomplete tasks." " Return the tasks as an array." ) prompt = PromptTemplate( template=task_creation_template, input_variables=[ "result", "task_description", "incomplete_tasks", "objective", ], ) return cls(prompt=prompt, llm=llm, verbose=verbose)
# 任务优先级链 class TaskPrioritizationChain(LLMChain): """负责任务优先级排序的链""" @classmethod def from_llm(cls, llm: BaseLLM, verbose: bool = True) -> LLMChain: """从LLM获取响应解析器""" task_prioritization_template = ( "You are a task prioritization AI tasked with cleaning the formatting of and reprioritizing" " the following tasks: {task_names}." " Consider the ultimate objective of your team: {objective}." " Do not remove any tasks. Return the result as a numbered list, like:" " #. First task" " #. Second task" " Start the task list with number {next_task_id}." ) prompt = PromptTemplate( template=task_prioritization_template, input_variables=["task_names", "next_task_id", "objective"], ) return cls(prompt=prompt, llm=llm, verbose=verbose)
下面是定义任务执行链,这个链负责执行具体的任务,并返回结果。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# 任务执行链 class ExecutionChain(LLMChain): """负责执行任务的链"""
@classmethod def from_llm(cls, llm: BaseLLM, verbose: bool = True) -> LLMChain: """从LLM获取响应解析器""" execution_template = ( "You are an AI who performs one task based on the following objective: {objective}." " Take into account these previously completed tasks: {context}." " Your task: {task}." " Response:" ) prompt = PromptTemplate( template=execution_template, input_variables=["objective", "context", "task"], ) return cls(prompt=prompt, llm=llm, verbose=verbose)
def get_next_task( task_creation_chain: LLMChain, result: Dict, task_description: str, task_list: List[str], objective: str, ) -> List[Dict]: """Get the next task.""" incomplete_tasks = ", ".join(task_list) response = task_creation_chain.run( result=result, task_description=task_description, incomplete_tasks=incomplete_tasks, objective=objective, ) new_tasks = response.split("\n") return [{"task_name": task_name} for task_name in new_tasks if task_name.strip()]
def prioritize_tasks( task_prioritization_chain: LLMChain, this_task_id: int, task_list: List[Dict], objective: str, ) -> List[Dict]: """Prioritize tasks.""" task_names = [t["task_name"] for t in task_list] next_task_id = int(this_task_id) + 1 response = task_prioritization_chain.run( task_names=task_names, next_task_id=next_task_id, objective=objective ) new_tasks = response.split("\n") prioritized_task_list = [] for task_string in new_tasks: if not task_string.strip(): continue task_parts = task_string.strip().split(".", 1) if len(task_parts) == 2: task_id = task_parts[0].strip() task_name = task_parts[1].strip() prioritized_task_list.append({"task_id": task_id, "task_name": task_name}) return prioritized_task_list
def _get_top_tasks(vectorstore, query: str, k: int) -> List[str]: """Get the top k tasks based on the query.""" results = vectorstore.similarity_search_with_score(query, k=k) if not results: return [] sorted_results, _ = zip(*sorted(results, key=lambda x: x[1], reverse=True)) return [str(item.metadata["task"]) for item in sorted_results]
def _call(self, inputs: Dict[str, Any]) -> Dict[str, Any]: """Run the agent.""" objective = inputs["objective"] first_task = inputs.get("first_task", "Make a todo list") self.add_task({"task_id": 1, "task_name": first_task}) num_iters = 0 while True: if self.task_list: self.print_task_list()
# Step 1: Pull the first task task = self.task_list.popleft() self.print_next_task(task)
# Step 2: Execute the task result = execute_task( self.vectorstore, self.execution_chain, objective, task["task_name"] ) this_task_id = int(task["task_id"]) self.print_task_result(result)
# Step 3: Store the result in Pinecone result_id = f"result_{task['task_id']}_{num_iters}" self.vectorstore.add_texts( texts=[result], metadatas=[{"task": task["task_name"]}], ids=[result_id], )
# Step 4: Create new tasks and reprioritize task list new_tasks = get_next_task( self.task_creation_chain, result, task["task_name"], [t["task_name"] for t in self.task_list], objective, ) for new_task in new_tasks: self.task_id_counter += 1 new_task.update({"task_id": self.task_id_counter}) self.add_task(new_task) self.task_list = deque( prioritize_tasks( self.task_prioritization_chain, this_task_id, list(self.task_list), objective, ) ) num_iters += 1 if self.max_iterations is not None and num_iters == self.max_iterations: print( "\033[91m\033[1m" + "\n*****TASK ENDING*****\n" + "\033[0m\033[0m" ) break return {}
1. Gather data on current weather conditions in Beijing, including temperature, humidity, wind speed, and precipitation.
2. Analyze the data to determine the best storage strategy for flowers.
3. Research the optimal temperature, humidity, and other environmental conditions for flower storage.
4. Develop a plan for storing flowers in Beijing based on the data and research.
5. Implement the plan and monitor the flowers for any changes in condition.
6. Make adjustments to the plan as needed.
*****TASK LIST*****
2: Identify the most suitable materials for flower storage in Beijing. 3: Investigate the effects of temperature, humidity, and other environmental factors on flower storage. 4: Research the best methods for preserving flowers in Beijing. 5: Develop a plan for storing flowers in Beijing that takes into account the data and research. 6: Monitor the flowers for any changes in condition and make adjustments to the plan as needed. 7: Analyze the current climate conditions in Beijing and write out a strategy for flower storage. 8: Create a report summarizing the findings and recommendations for flower storage in Beijing.
*****NEXT TASK*****
2: Identify the most suitable materials for flower storage in Beijing.
*****TASK RESULT*****
In order to store flowers in Beijing, it is important to consider the current weather conditions. Today, the temperature in Beijing is around 18°C with a humidity of around 70%. This means that the air is relatively dry and cool, making it suitable for storing flowers.
The best materials for flower storage in Beijing would be materials that are breathable and moisture-resistant. Examples of suitable materials include paper, cardboard, and fabric. These materials will help to keep the flowers fresh and prevent them from wilting. Additionally, it is important to keep the flowers away from direct sunlight and heat sources, as this can cause them to dry out quickly.
*****TASK LIST*****
3: Analyze the current climate conditions in Beijing and write out a strategy for flower storage. 4: Investigate the effects of temperature, humidity, and other environmental factors on flower storage in Beijing. 5: Research the best methods for preserving flowers in Beijing. 6: Develop a plan for storing flowers in Beijing that takes into account the data and research. 7: Monitor the flowers for any changes in condition and make adjustments to the plan as needed. 8: Create a report summarizing the findings and recommendations for flower storage in Beijing, and provide suggestions for improvement.
*****NEXT TASK*****
3: Analyze the current climate conditions in Beijing and write out a strategy for flower storage.
*****TASK RESULT*****
Based on the current climate conditions in Beijing, the best strategy for flower storage is to keep the flowers in a cool, dry place. This means avoiding direct sunlight and keeping the flowers away from any sources of heat. Additionally, it is important to keep the flowers away from any sources of moisture, such as humidifiers or air conditioners. The flowers should also be kept away from any sources of strong odors, such as perfumes or cleaning products. Finally, it is important to keep the flowers away from any sources of pests, such as insects or rodents. To ensure the flowers remain in optimal condition, it is important to regularly check the temperature and humidity levels in the storage area.
*****TASK LIST*****
4: Monitor the flowers for any changes in condition and make adjustments to the plan as needed. 1: Analyze the impact of different types of flowers on flower storage in Beijing. 2: Compare the effectiveness of different flower storage strategies in Beijing. 3: Investigate the effects of temperature, humidity, and other environmental factors on flower storage in Beijing. 5: Research the best methods for preserving flowers in Beijing. 6: Develop a plan for storing flowers in Beijing that takes into account the data and research. 7: Investigate the effects of different storage materials on flower preservation in Beijing. 8: Develop a system for monitoring the condition of flowers in storage in Beijing. 9: Create a checklist for flower storage in Beijing that can be used to ensure optimal conditions. 10: Identify potential risks associated with flower storage in Beijing and develop strategies to mitigate them. 11: Create a report summarizing the findings and recommendations for flower storage in Beijing, and provide suggestions for improvement.
*****NEXT TASK*****
4: Monitor the flowers for any changes in condition and make adjustments to the plan as needed.
*****TASK RESULT*****
I will monitor the flowers for any changes in condition and make adjustments to the plan as needed. This includes checking for signs of wilting, discoloration, or other signs of deterioration. I will also monitor the temperature and humidity levels in the storage area to ensure that the flowers are kept in optimal conditions. If necessary, I will adjust the storage plan to ensure that the flowers remain in good condition. Additionally, I will keep track of the expiration date of the flowers and adjust the storage plan accordingly.
*****TASK LIST*****
5: Analyze the current climate conditions in Beijing and how they affect flower storage. 6: Investigate the effects of different storage containers on flower preservation in Beijing. 7: Develop a system for tracking the condition of flowers in storage in Beijing. 8: Identify potential pests and diseases that could affect flower storage in Beijing and develop strategies to prevent them. 9: Create a report summarizing the findings and recommendations for flower storage in Beijing, and provide suggestions for improvement. 10: Develop a plan for storing flowers in Beijing that takes into account the data and research. 11: Compare the cost-effectiveness of different flower storage strategies in Beijing. 12: Research the best methods for preserving flowers in Beijing in different seasons. 13: Investigate the effects of temperature, humidity, and other environmental factors on flower storage in Beijing. 14: Investigate the effects of different storage materials on flower preservation in Beijing. 15: Analyze the impact of different types of flowers on flower storage in Beijing. 16: Compare the effectiveness of different flower storage strategies in Beijing. 17: Create a checklist for flower storage in Beijing that can be used to ensure optimal conditions. 18: Identify potential risks associated with flower storage in
*****NEXT TASK*****
5: Analyze the current climate conditions in Beijing and how they affect flower storage.
*****TASK RESULT*****
Based on the current climate conditions in Beijing, the most suitable materials for flower storage would be materials that are breathable and moisture-resistant. This would include materials such as burlap, cotton, and linen. Additionally, it is important to ensure that the flowers are stored in a cool, dry place, away from direct sunlight. Furthermore, it is important to monitor the flowers for any changes in condition and make adjustments to the plan as needed. Finally, it is important to make a to-do list to ensure that all necessary steps are taken to properly store the flowers.
*****TASK LIST*****
6: Develop a plan for storing flowers in Beijing that takes into account the local climate conditions. 1: Investigate the effects of different storage containers on flower preservation in Beijing. 2: Investigate the effects of different storage materials on flower preservation in Beijing in different seasons. 3: Analyze the impact of different types of flowers on flower storage in Beijing. 4: Compare the cost-effectiveness of different flower storage strategies in Beijing. 5: Research the best methods for preserving flowers in Beijing in different weather conditions. 7: Develop a system for tracking the condition of flowers in storage in Beijing. 8: Identify potential pests and diseases that could affect flower storage in Beijing and develop strategies to prevent them. 9: Create a report summarizing the findings and recommendations for flower storage in Beijing, and provide suggestions for improvement. 10: Create a checklist for flower storage in Beijing that can be used to ensure optimal conditions. 11: Identify potential risks associated with flower storage in Beijing.
*****NEXT TASK*****
6: Develop a plan for storing flowers in Beijing that takes into account the local climate conditions.
*****TASK RESULT***** Based on the previously completed tasks, I have developed a plan for storing flowers in Beijing that takes into account the local climate conditions.
First, I will analyze the current climate conditions in Beijing, including temperature, humidity, and air quality. This will help me identify the most suitable materials for flower storage in Beijing.
Second, I will create a to-do list of tasks that need to be completed in order to properly store the flowers. This list should include tasks such as selecting the right materials for flower storage, ensuring the flowers are kept in a cool and dry environment, and regularly monitoring the flowers for any changes in condition.
Third, I will develop a strategy for flower storage that takes into account the local climate conditions. This strategy should include steps such as selecting the right materials for flower storage, ensuring the flowers are kept in a cool and dry environment, and regularly monitoring the flowers for any changes in condition.
Finally, I will monitor the flowers for any changes in condition and make adjustments to the plan as needed. This will help ensure that the flowers are stored in the most suitable environment for their preservation.
*****TASK ENDING*****'''
从结构上看,内容以循环方式进行组织,首先是 TASK LIST(任务列表),接着是 NEXT TASK(下一个任务),然后是 TASK RESULT(任务结果)。