BabyAGI User Guide 宝贝AGI用户指南
This notebook demonstrates how to implement BabyAGI by Yohei Nakajima. BabyAGI is an AI agent that can generate and pretend to execute tasks based on a given objective.
本笔记本演示了如何实现Yohei Nakajima的BabyAGI。BabyAGI是一个AI代理,可以根据给定的目标生成和假装执行任务。
(相关资料图)
This guide will help you understand the components to create your own recursive agents.
本指南将帮助您了解创建自己的递归代理的组件。
Although BabyAGI uses specific vectorstores/model providers (Pinecone, OpenAI), one of the benefits of implementing it with LangChain is that you can easily swap those out for different options. In this implementation we use a FAISS vectorstore (because it runs locally and is free).
尽管BabyAGI使用特定的vectorstore/模型提供程序(Pinecone,OpenAI),但使用LangChain实现它的好处之一是您可以轻松地将它们换成不同的选项。在此实现中,我们使用 FAISS 向量存储(因为它在本地运行并且是免费的)。
Install and Import Required Modules安装和导入所需模块importosfromcollectionsimportdequefromtypingimportDict,List,Optional,AnyfromlangchainimportLLMChain,OpenAI,PromptTemplatefromlangchain.embeddingsimportOpenAIEmbeddingsfromlangchain.llmsimportBaseLLMfromlangchain.vectorstores.baseimportVectorStorefrompydanticimportBaseModel,Fieldfromlangchain.chains.baseimportChainfromlangchain.experimentalimportBabyAGI
Connect to the Vector Store连接到矢量存储
Depending on what vectorstore you use, this step may look different.
根据您使用的向量库,此步骤可能看起来有所不同。
from langchain.vectorstores import FAISSfrom langchain.docstore import InMemoryDocstore
# Define your embedding modelembeddings_model = OpenAIEmbeddings()# Initialize the vectorstore as emptyimport faissembedding_size = 1536index = faiss.IndexFlatL2(embedding_size)vectorstore = FAISS(embeddings_model.embed_query, index, InMemoryDocstore({}), {})
Run the BabyAGI 运行婴儿AGI
Now it’s time to create the BabyAGI controller and watch it try to accomplish your objective.
现在是时候创建BabyAGI控制器并观看它尝试实现您的目标了。
OBJECTIVE = "Write a weather report for efg today"
llm = OpenAI(temperature=0)
# Logging of LLMChainsverbose = False# If None, will keep on going forevermax_iterations: Optional[int] = 3baby_agi = BabyAGI.from_llm( llm=llm, vectorstore=vectorstore, verbose=verbose, max_iterations=max_iterations)
baby_agi({"objective": OBJECTIVE})
*****TASK LIST*****1: Make a todo list*****NEXT TASK*****1: Make a todo list*****TASK RESULT*****1. Check the weather forecast for abc today2. Make note of the temperature, humidity, wind speed, and other relevant weather conditions3. Write a weather report summarizing the forecast4. Check for any weather alerts or warnings5. Share the report with the relevant stakeholders*****TASK LIST*****2: Check the current temperature in abc3: Check the current humidity in abc4: Check the current wind speed in abc5: Check for any weather alerts or warnings in abc6: Check the forecast for the next 24 hours in abc7: Check the forecast for the next 48 hours in abc8: Check the forecast for the next 72 hours in abc9: Check the forecast for the next week in abc10: Check the forecast for the next month in abc11: Check the forecast for the next 3 months in abc1: Write a weather report for efg today*****NEXT TASK*****2: Check the current temperature in abc*****TASK RESULT*****I will check the current temperature in abc. I will use an online weather service to get the most up-to-date information.*****TASK LIST*****3: Check the current UV index in abc.4: Check the current air quality in abc.5: Check the current precipitation levels in abc.6: Check the current cloud cover in abc.7: Check the current barometric pressure in abc.8: Check the current dew point in abc.9: Check the current wind direction in abc.10: Check the current humidity levels in abc.1: Check the current temperature in abc to the average temperature for this time of year.2: Check the current visibility in abc.11: Write a weather report for efg today.*****NEXT TASK*****3: Check the current UV index in abc.*****TASK RESULT*****The current UV index in abc is moderate. The UV index is expected to remain at moderate levels throughout the day. It is recommended to wear sunscreen and protective clothing when outdoors.*****TASK ENDING**********TASK ENDING*****
{"objective": "Write a weather report for efg today"}
BabyAGI with Tools 带工具的婴儿AGI
This notebook builds on top of baby agi, but shows how you can swap out the execution chain. The previous execution chain was just an LLM which made stuff up. By swapping it out with an agent that has access to tools, we can hopefully get real reliable information
此笔记本建立在婴儿 agi 之上,但展示了如何交换执行链。以前的执行链只是一个编造东西的LLM。通过将其替换为可以访问工具的代理,我们有望获得真正可靠的信息
Install and Import Required Modules安装和导入所需模块importosfromcollectionsimportdequefromtypingimportDict,List,Optional,AnyfromlangchainimportLLMChain,OpenAI,PromptTemplatefromlangchain.embeddingsimportOpenAIEmbeddingsfromlangchain.llmsimportBaseLLMfromlangchain.vectorstores.baseimportVectorStorefrompydanticimportBaseModel,Fieldfromlangchain.chains.baseimportChainfromlangchain.experimentalimportBabyAGI
Connect to the Vector Store连接到矢量存储
Depending on what vectorstore you use, this step may look different.
根据您使用的向量库,此步骤可能看起来有所不同。
%pip install faiss-cpu > /dev/null%pip install google-search-results > /dev/nullfrom langchain.vectorstores import FAISSfrom langchain.docstore import InMemoryDocstore
Note: you may need to restart the kernel to use updated packages.Note: you may need to restart the kernel to use updated packages.
# Define your embedding modelembeddings_model = OpenAIEmbeddings()# Initialize the vectorstore as emptyimport faissembedding_size = 1536index = faiss.IndexFlatL2(embedding_size)vectorstore = FAISS(embeddings_model.embed_query, index, InMemoryDocstore({}), {})
Define the Chains 定义链
BabyAGI relies on three LLM chains:
BabyAGI依赖于三个LLM链:
任务创建链,用于选择要添加到列表中的新任务Task prioritization chain to re-prioritize tasks
任务优先级链,用于重新确定任务的优先级Execution Chain to execute the tasks
执行任务的执行链
NOTE: in this notebook, the Execution chain will now be an agent.
注意:在此笔记本中,执行链现在将是一个代理。
from langchain.agents import ZeroShotAgent, Tool, AgentExecutorfrom langchain import OpenAI, SerpAPIWrapper, LLMChaintodo_prompt = PromptTemplate.from_template( "You are a planner who is an expert at coming up with a todo list for a given objective. Come up with a todo list for this objective: {objective}")todo_chain = LLMChain(llm=OpenAI(temperature=0), prompt=todo_prompt)search = SerpAPIWrapper()tools = [ Tool( name="Search", func=search.run, description="useful for when you need to answer questions about current events", ), Tool( name="TODO", func=todo_chain.run, description="useful for when you need to come up with todo lists. Input: an objective to create a todo list for. Output: a todo list for that objective. Please be very clear what the objective is!", ),]prefix = """You are an AI who performs one task based on the following objective: {objective}. Take into account these previously completed tasks: {context}."""suffix = """Question: {task}{agent_scratchpad}"""prompt = ZeroShotAgent.create_prompt( tools, prefix=prefix, suffix=suffix, input_variables=["objective", "task", "context", "agent_scratchpad"],)
llm = OpenAI(temperature=0)llm_chain = LLMChain(llm=llm, prompt=prompt)tool_names = [tool.name for tool in tools]agent = ZeroShotAgent(llm_chain=llm_chain, allowed_tools=tool_names)agent_executor = AgentExecutor.from_agent_and_tools( agent=agent, tools=tools, verbose=True)
Run the BabyAGI 运行婴儿AGI
Now it’s time to create the BabyAGI controller and watch it try to accomplish your objective.
现在是时候创建BabyAGI控制器并观看它尝试实现您的目标了。
OBJECTIVE = "Write a weather report for efg today"
# Logging of LLMChainsverbose = False# If None, will keep on going forevermax_iterations: Optional[int] = 3baby_agi = BabyAGI.from_llm( llm=llm, vectorstore=vectorstore, task_execution_chain=agent_executor, verbose=verbose, max_iterations=max_iterations)
baby_agi({"objective": OBJECTIVE})
*****TASK LIST*****1: Make a todo list*****NEXT TASK*****1: Make a todo list> Entering new AgentExecutor chain...Thought: I need to come up with a todo listAction: TODOAction Input: Write a weather report for efg today1. Research current weather conditions in abc2. Gather data on temperature, humidity, wind speed, and other relevant weather conditions3. Analyze data to determine current weather trends4. Write a brief introduction to the weather report5. Describe current weather conditions in abc6. Discuss any upcoming weather changes7. Summarize the weather report8. Proofread and edit the report9. Submit the report I now know the final answerFinal Answer: The todo list for writing a weather report for efg today is: 1. Research current weather conditions in abc; 2. Gather data on temperature, humidity, wind speed, and other relevant weather conditions; 3. Analyze data to determine current weather trends; 4. Write a brief introduction to the weather report; 5. Describe current weather conditions in abc; 6. Discuss any upcoming weather changes; 7. Summarize the weather report; 8. Proofread and edit the report; 9. Submit the report.> Finished chain.*****TASK RESULT*****The todo list for writing a weather report for efg today is: 1. Research current weather conditions in abc; 2. Gather data on temperature, humidity, wind speed, and other relevant weather conditions; 3. Analyze data to determine current weather trends; 4. Write a brief introduction to the weather report; 5. Describe current weather conditions in abc; 6. Discuss any upcoming weather changes; 7. Summarize the weather report; 8. Proofread and edit the report; 9. Submit the report.*****TASK LIST*****2: Gather data on precipitation, cloud cover, and other relevant weather conditions;3: Analyze data to determine any upcoming weather changes;4: Research current weather forecasts for abc;5: Create a visual representation of the weather report;6: Include relevant images and graphics in the report;7: Format the report for readability;8: Publish the report online;9: Monitor the report for accuracy.*****NEXT TASK*****2: Gather data on precipitation, cloud cover, and other relevant weather conditions;> Entering new AgentExecutor chain...Thought: I need to search for current weather conditions in abcAction: SearchAction Input: Current weather conditions in abcCurrent Weather for Popular Cities ; abc, CA 46 · Partly Cloudy ; Manhattan, NY warning 52 · Cloudy ; Schiller Park, IL (60176) 40 · Sunny ; Boston, MA 54 ... I need to compile the data into a weather reportAction: TODOAction Input: Compile data into a weather report1. Gather data from reliable sources such as the National Weather Service, local weather stations, and other meteorological organizations.2. Analyze the data to identify trends and patterns.3. Create a chart or graph to visualize the data.4. Write a summary of the data and its implications.5. Compile the data into a report format.6. Proofread the report for accuracy and clarity.7. Publish the report to a website or other platform.8. Distribute the report to relevant stakeholders. I now know the final answerFinal Answer: Today in abc, the temperature is 46 degrees Fahrenheit with partly cloudy skies. The forecast for the rest of the day is expected to remain partly cloudy.> Finished chain.*****TASK RESULT*****Today in abc, the temperature is 46 degrees Fahrenheit with partly cloudy skies. The forecast for the rest of the day is expected to remain partly cloudy.*****TASK LIST*****3: Format the report for readability;4: Include relevant images and graphics in the report;5: Compare the current weather conditions in abc to the forecasted conditions;6: Identify any potential weather-related hazards in the area;7: Research historical weather patterns in abc;8: Identify any potential trends in the weather data;9: Include relevant data sources in the report;10: Summarize the weather report in a concise manner;11: Include a summary of the forecasted weather conditions;12: Include a summary of the current weather conditions;13: Include a summary of the historical weather patterns;14: Include a summary of the potential weather-related hazards;15: Include a summary of the potential trends in the weather data;16: Include a summary of the data sources used in the report;17: Analyze data to determine any upcoming weather changes;18: Research current weather forecasts for abc;19: Create a visual representation of the weather report;20: Publish the report online;21: Monitor the report for accuracy*****NEXT TASK*****3: Format the report for readability;> Entering new AgentExecutor chain...Thought: I need to make sure the report is easy to read;Action: TODOAction Input: Make the report easy to read1. Break up the report into sections with clear headings2. Use bullet points and numbered lists to organize information3. Use short, concise sentences4. Use simple language and avoid jargon5. Include visuals such as charts, graphs, and diagrams to illustrate points6. Use bold and italicized text to emphasize key points7. Include a table of contents and page numbers8. Use a consistent font and font size throughout the report9. Include a summary at the end of the report10. Proofread the report for typos and errors I now know the final answerFinal Answer: The report should be formatted for readability by breaking it up into sections with clear headings, using bullet points and numbered lists to organize information, using short, concise sentences, using simple language and avoiding jargon, including visuals such as charts, graphs, and diagrams to illustrate points, using bold and italicized text to emphasize key points, including a table of contents and page numbers, using a consistent font and font size throughout the report, including a summary at the end of the report, and proofreading the report for typos and errors.> Finished chain.*****TASK RESULT*****The report should be formatted for readability by breaking it up into sections with clear headings, using bullet points and numbered lists to organize information, using short, concise sentences, using simple language and avoiding jargon, including visuals such as charts, graphs, and diagrams to illustrate points, using bold and italicized text to emphasize key points, including a table of contents and page numbers, using a consistent font and font size throughout the report, including a summary at the end of the report, and proofreading the report for typos and errors.
{"objective": "Write a weather report for efg today"}