![png](_multi_modal_output_agent_files/output_10_1.png)    StableDiffusionâ€‹tools = [SteamshipImageGenerationTool(model_name="stable-diffusion")]mrkl = initialize_agent(    tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)output = mrkl.run("How would you visualize a parot playing soccer?")            > Entering new AgentExecutor chain...     I need to generate an image of a parrot playing soccer.    Action: GenerateImage    Action Input: A parrot wearing a soccer uniform, kicking a soccer ball.    Observation: 25BB588F-85E4-4915-82BE-67ADCF974881    Thought: I now have the UUID of the generated image.    Final Answer: The UUID of the generated image is 25BB588F-85E4-4915-82BE-67ADCF974881.        > Finished chain.show_output(output)    The UUID of the generated image is         ![png](_multi_modal_output_agent_files/output_15_1.png)            PreviousPlug-and-PlaiNextSalesGPT - Your Context-Aware AI Sales Assistant With Knowledge BaseMulti-modal outputs: Image & TextDall-EStableDiffusionCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright Â© 2023 LangChain, Inc.


BabyAGI with Tools | ğŸ¦œï¸�ğŸ”— Langchain


Skip to main contentğŸ¦œï¸�ğŸ”— LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKUse casesQA and Chat over DocumentsAnalyzing structured dataExtractionInteracting with APIsChatbotsSummarizationCode UnderstandingAgent simulationsAgentsBabyAGI User GuideBabyAGI with ToolsCAMEL Role-Playing Autonomous Cooperative AgentsCustom Agent with PlugIn RetrievalPlug-and-Plaimulti_modal_output_agentSalesGPT - Your Context-Aware AI Sales Assistant With Knowledge BaseWikibase AgentAutonomous (long-running) agentsMulti-modalUse casesAgentsBabyAGI with ToolsOn this pageBabyAGI with ToolsThis 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 informationInstall and Import Required Modulesâ€‹import osfrom collections import dequefrom typing import Dict, List, Optional, Anyfrom langchain import LLMChain, OpenAI, PromptTemplatefrom langchain.embeddings import OpenAIEmbeddingsfrom langchain.llms import BaseLLMfrom langchain.vectorstores.base import VectorStorefrom pydantic import BaseModel, Fieldfrom langchain.chains.base import ChainConnect 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({}), {})Define the Chainsâ€‹BabyAGI relies on three LLM chains:Task creation


{})Define the Chainsâ€‹BabyAGI relies on three LLM chains:Task creation chain to select new tasks to add to the listTask prioritization chain to re-prioritize tasksExecution Chain to execute the tasksNOTE: in this notebook, the Execution chain will now be an agent.class TaskCreationChain(LLMChain):    """Chain to generates tasks."""    @classmethod    def from_llm(cls, llm: BaseLLM, verbose: bool = True) -> LLMChain:        """Get the response parser."""        task_creation_template = (            "You are an 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",


"result",                "task_description",                "incomplete_tasks",                "objective",            ],        )        return cls(prompt=prompt, llm=llm, verbose=verbose)class TaskPrioritizationChain(LLMChain):    """Chain to prioritize tasks."""    @classmethod    def from_llm(cls, llm: BaseLLM, verbose: bool = True) -> LLMChain:        """Get the response parser."""        task_prioritization_template = (            "You are an 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,


template=task_prioritization_template,            input_variables=["task_names", "next_task_id", "objective"],        )        return cls(prompt=prompt, llm=llm, verbose=verbose)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",


suffix=suffix,    input_variables=["objective", "task", "context", "agent_scratchpad"],)Define the BabyAGI Controllerâ€‹BabyAGI composes the chains defined above in a (potentially-)infinite loop.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():


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_listdef _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 execute_task(    vectorstore, execution_chain: LLMChain, objective: str, task: str, k: int = 5) -> str:    """Execute a task."""    context = _get_top_tasks(vectorstore, query=objective, k=k)    return execution_chain.run(objective=objective, context=context, task=task)class BabyAGI(Chain, BaseModel):    """Controller model for the BabyAGI agent."""    task_list: deque = Field(default_factory=deque)    task_creation_chain: TaskCreationChain = Field(...)    task_prioritization_chain: TaskPrioritizationChain = Field(...)


task_prioritization_chain: TaskPrioritizationChain = Field(...)    execution_chain: AgentExecutor = Field(...)    task_id_counter: int = Field(1)    vectorstore: VectorStore = Field(init=False)    max_iterations: Optional[int] = None    class Config:        """Configuration for this pydantic object."""        arbitrary_types_allowed = True    def add_task(self, task: Dict):        self.task_list.append(task)    def print_task_list(self):        print("\033[95m\033[1m" + "\n*****TASK LIST*****\n" + "\033[0m\033[0m")        for t in self.task_list:            print(str(t["task_id"]) + ": " + t["task_name"])    def print_next_task(self, task: Dict):        print("\033[92m\033[1m" + "\n*****NEXT TASK*****\n" + "\033[0m\033[0m")        print(str(task["task_id"]) + ": " + task["task_name"])    def print_task_result(self, result: str):        print("\033[93m\033[1m" + "\n*****TASK RESULT*****\n" + "\033[0m\033[0m")        print(result)    @property    def input_keys(self) -> List[str]:        return ["objective"]    @property    def output_keys(self) ->


return ["objective"]    @property    def output_keys(self) -> List[str]:        return []    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)


self.print_task_result(result)                # Step 3: Store the result in Pinecone                result_id = f"result_{task['task_id']}"                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:


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"


+ "\033[0m\033[0m"                )                break        return {}    @classmethod    def from_llm(        cls, llm: BaseLLM, vectorstore: VectorStore, verbose: bool = False, **kwargs    ) -> "BabyAGI":        """Initialize the BabyAGI Controller."""        task_creation_chain = TaskCreationChain.from_llm(llm, verbose=verbose)        task_prioritization_chain = TaskPrioritizationChain.from_llm(            llm, verbose=verbose        )        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        )        return cls(            task_creation_chain=task_creation_chain,            task_prioritization_chain=task_prioritization_chain,            execution_chain=agent_executor,            vectorstore=vectorstore,


vectorstore=vectorstore,            **kwargs,        )Run the BabyAGIâ€‹Now it's time to create the BabyAGI controller and watch it try to accomplish your objective.OBJECTIVE = "Write a weather report for SF 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            > Entering new AgentExecutor chain...    Thought: I need to gather data on the current weather conditions in SF    Action: Search    Action Input: Current weather conditions in SF    Observation: High 67F. Winds WNW at 10 to 15 mph. Clear to partly cloudy.    Thought: I need to make a todo list    Action: TODO    Action Input: Write a weather report for SF today    Observation:         1. Research current weather conditions in San Francisco    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 San


Write a brief introduction to the weather report    5. Describe current weather conditions in San Francisco    6. Discuss any upcoming weather changes    7. Summarize the weather report    8. Proofread and edit the report    9. Submit the report    Thought: I now know the final answer    Final Answer: A weather report for SF today should include research on current weather conditions in San Francisco, gathering data on temperature, humidity, wind speed, and other relevant weather conditions, analyzing data to determine current weather trends, writing a brief introduction to the weather report, describing current weather conditions in San Francisco, discussing any upcoming weather changes, summarizing the weather report, proofreading and editing the report, and submitting the report.        > Finished chain.        *****TASK RESULT*****        A weather report for SF today should include research on current weather conditions in San Francisco, gathering data on temperature, humidity, wind speed, and other relevant weather conditions, analyzing data to determine current weather trends, writing a brief introduction to the weather report, describing current weather conditions in San Francisco, discussing any upcoming weather changes, summarizing the weather report, proofreading and editing the report, and submitting the report.        *****TASK LIST*****        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 San Francisco    6: Discuss any upcoming weather changes    7: Summarize the weather report    8: Proofread and edit the report    9: Submit the report


Proofread and edit the report    9: Submit the report    1: Research current weather conditions in San Francisco        *****NEXT TASK*****        2: Gather data on temperature, humidity, wind speed, and other relevant weather conditions            > Entering new AgentExecutor chain...    Thought: I need to search for the current weather conditions in SF    Action: Search    Action Input: Current weather conditions in SF    Observation: High 67F. Winds WNW at 10 to 15 mph. Clear to partly cloudy.    Thought: I need to make a todo list    Action: TODO    Action Input: Create a weather report for SF today    Observation:         1. Gather current weather data for SF, including temperature, wind speed, humidity, and precipitation.    2. Research historical weather data for SF to compare current conditions.    3. Analyze current and historical data to determine any trends or patterns.    4. Create a visual representation of the data, such as a graph or chart.    5. Write a summary of the weather report, including key findings and any relevant information.    6. Publish the weather report on a website or other platform.    Thought: I now know the final answer    Final Answer: Today in San Francisco, the temperature is 67F with winds WNW at 10 to 15 mph. The sky is clear to partly cloudy.        > Finished chain.        *****TASK RESULT*****        Today in San Francisco, the temperature is 67F with winds WNW at 10 to


Today in San Francisco, the temperature is 67F with winds WNW at 10 to 15 mph. The sky is clear to partly cloudy.        *****TASK LIST*****        3: Research current weather conditions in San Francisco    4: Compare the current weather conditions in San Francisco to the average for this time of year.    5: Identify any potential weather-related hazards in the area.    6: Research any historical weather patterns in San Francisco.    7: Analyze data to determine current weather trends    8: Include any relevant data from nearby cities in the report.    9: Include any relevant data from the National Weather Service in the report.    10: Include any relevant data from local news sources in the report.    11: Include any relevant data from online weather sources in the report.    12: Include any relevant data from local meteorologists in the report.    13: Include any relevant data from local weather stations in the report.    14: Include any relevant data from satellite images in the report.    15: Describe current weather conditions in San Francisco    16: Discuss any upcoming weather changes    17: Write a brief introduction to the weather report    18: Summarize the weather report    19: Proofread and edit the report    20: Submit the report        *****NEXT TASK*****        3: Research current weather conditions in San Francisco            > Entering new AgentExecutor chain...    Thought: I need to search for current weather conditions in San Francisco    Action: Search    Action Input: Current


for current weather conditions in San Francisco    Action: Search    Action Input: Current weather conditions in San Francisco    Observation: TodaySun 04/09 High 67 Â· 1% Precip. ; TonightSun 04/09 Low 49 Â· 9% Precip. ; TomorrowMon 04/10 High 64 Â· 11% Precip.    Thought: I now know the final answer    Final Answer: Today in San Francisco, the high temperature is 67 degrees with 1% chance of precipitation. The low temperature tonight is 49 degrees with 9% chance of precipitation. Tomorrow's high temperature is 64 degrees with 11% chance of precipitation.        > Finished chain.        *****TASK RESULT*****        Today in San Francisco, the high temperature is 67 degrees with 1% chance of precipitation. The low temperature tonight is 49 degrees with 9% chance of precipitation. Tomorrow's high temperature is 64 degrees with 11% chance of precipitation.        *****TASK ENDING*****        {'objective': 'Write a weather report for SF today'}PreviousBabyAGI User GuideNextCAMEL Role-Playing Autonomous Cooperative AgentsInstall and Import Required ModulesConnect to the Vector StoreDefine the ChainsDefine the BabyAGI ControllerRun the BabyAGICommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright Â© 2023 LangChain, Inc.


Page Not Found | ğŸ¦œï¸�ğŸ”— Langchain

Skip to main contentğŸ¦œï¸�ğŸ”— LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKPage Not FoundWe could not find what you were looking for.Please contact the owner of the site that linked you to the original URL and let them know their link is broken.CommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright Â© 2023 LangChain, Inc.


image_agent | ğŸ¦œï¸�ğŸ”— Langchain


Skip to main contentğŸ¦œï¸�ğŸ”— LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKUse casesQA and Chat over DocumentsAnalyzing structured dataExtractionInteracting with APIsChatbotsSummarizationCode UnderstandingAgent simulationsAgentsAutonomous (long-running) agentsMulti-modalimage_agentUse casesMulti-modalimage_agentOn this pageimage_agentMulti-modal outputs: Image & Textâ€‹This notebook shows how non-text producing tools can be used to create multi-modal agents.This example is limited to text and image outputs and uses UUIDs to transfer content across tools and agents. This example uses Steamship to generate and store generated images. Generated are auth protected by default. You can get your Steamship api key here: https://steamship.com/account/apifrom steamship import Block, Steamshipimport refrom IPython.display import Imagefrom langchain import OpenAIfrom langchain.agents import initialize_agentfrom langchain.agents import AgentTypefrom langchain.tools import SteamshipImageGenerationToolllm = OpenAI(temperature=0)Dall-Eâ€‹tools = [SteamshipImageGenerationTool(model_name="dall-e")]mrkl = initialize_agent(    tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)output = mrkl.run("How would you visualize a parot playing soccer?")            > Entering new AgentExecutor chain...     I need to generate an image of a parrot playing soccer.    Action: GenerateImage    Action Input: A parrot wearing a soccer uniform, kicking a soccer ball.    Observation: E28BE7C7-D105-41E0-8A5B-2CE21424DFEC    Thought: I now have the UUID of the generated


Thought: I now have the UUID of the generated image.    Final Answer: The UUID of the generated image is E28BE7C7-D105-41E0-8A5B-2CE21424DFEC.        > Finished chain.def show_output(output):    """Display the multi-modal output from the agent."""    UUID_PATTERN = re.compile(        r"([0-9A-Za-z]{8}-[0-9A-Za-z]{4}-[0-9A-Za-z]{4}-[0-9A-Za-z]{4}-[0-9A-Za-z]{12})"    )    outputs = UUID_PATTERN.split(output)    outputs = [        re.sub(r"^\W+", "", el) for el in outputs    ]  # Clean trailing and leading non-word characters    for output in outputs:        maybe_block_id = UUID_PATTERN.search(output)        if maybe_block_id:            display(Image(Block.get(Steamship(), _id=maybe_block_id.group()).raw()))        else:            print(output, end="\n\n")show_output(output)    The UUID of the generated image is         ![png](_image_agent_files/output_10_1.png)    StableDiffusionâ€‹tools = [SteamshipImageGenerationTool(model_name="stable-diffusion")]mrkl = initialize_agent(    tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)output = mrkl.run("How would you visualize a parot


verbose=True)output = mrkl.run("How would you visualize a parot playing soccer?")show_output(output)PreviousMeta-PromptMulti-modal outputs: Image & TextDall-EStableDiffusionCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright Â© 2023 LangChain, Inc.


Summarization | ğŸ¦œï¸�ğŸ”— Langchain

Skip to main contentğŸ¦œï¸�ğŸ”— LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKUse casesQA and Chat over DocumentsAnalyzing structured dataExtractionInteracting with APIsChatbotsSummarizationCode UnderstandingAgent simulationsAgentsAutonomous (long-running) agentsMulti-modalUse casesSummarizationSummarizationSummarization involves creating a smaller summary of multiple longer documents.
This can be useful for distilling long documents into the core pieces of information.The recommended way to get started using a summarization chain is:from langchain.chains.summarize import load_summarize_chainchain = load_summarize_chain(llm, chain_type="map_reduce")chain.run(docs)The following resources exist:Summarization notebook: A notebook walking through how to accomplish this task.Additional related resources include:Modules for working with documents: Core components for working with documents.PreviousVoice AssistantNextCode UnderstandingCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright Â© 2023 LangChain, Inc.


Autonomous (long-running) agents | ğŸ¦œï¸�ğŸ”— Langchain


Skip to main contentğŸ¦œï¸�ğŸ”— LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKUse casesQA and Chat over DocumentsAnalyzing structured dataExtractionInteracting with APIsChatbotsSummarizationCode UnderstandingAgent simulationsAgentsAutonomous (long-running) agentsAutoGPTBabyAGI User GuideBabyAGI with ToolsHuggingGPTmarathon_timesMeta-PromptMulti-modalUse casesAutonomous (long-running) agentsOn this pageAutonomous (long-running) agentsAutonomous Agents are agents that designed to be more long running.
You give them one or multiple long term goals, and they independently execute towards those goals.
The applications combine tool usage and long term memory.At the moment, Autonomous Agents are fairly experimental and based off of other open-source projects.
By implementing these open source projects in LangChain primitives we can get the benefits of LangChain -
easy switching and experimenting with multiple LLMs, usage of different vectorstores as memory,


easy switching and experimenting with multiple LLMs, usage of different vectorstores as memory,
usage of LangChain's collection of tools.Baby AGI (Original Repo)â€‹Baby AGI: a notebook implementing BabyAGI as LLM ChainsBaby AGI with Tools: building off the above notebook, this example substitutes in an agent with tools as the execution tools, allowing it to actually take actions.AutoGPT (Original Repo)â€‹AutoGPT: a notebook implementing AutoGPT in LangChain primitivesWebSearch Research Assistant: a notebook showing how to use AutoGPT plus specific tools to act as research assistant that can use the web.MetaPrompt (Original Repo)â€‹Meta-Prompt: a notebook implementing Meta-Prompt in LangChain primitivesHuggingGPT (Original Repo)â€‹HuggingGPT: a notebook implementing HuggingGPT in LangChain primitivesPreviousWikibase AgentNextAutoGPTBaby AGI (Original Repo)AutoGPT (Original Repo)MetaPrompt (Original Repo)HuggingGPT (Original Repo)CommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright Â© 2023 LangChain, Inc.


BabyAGI User Guide | ğŸ¦œï¸�ğŸ”— Langchain


Skip to main contentğŸ¦œï¸�ğŸ”— LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKUse casesQA and Chat over DocumentsAnalyzing structured dataExtractionInteracting with APIsChatbotsSummarizationCode UnderstandingAgent simulationsAgentsAutonomous (long-running) agentsAutoGPTBabyAGI User GuideBabyAGI with ToolsHuggingGPTmarathon_timesMeta-PromptMulti-modalUse casesAutonomous (long-running) agentsBabyAGI User GuideOn this pageBabyAGI User GuideThis 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.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).Install and Import Required Modulesâ€‹import osfrom collections import dequefrom typing import Dict, List, Optional, Anyfrom langchain import LLMChain, OpenAI, PromptTemplatefrom langchain.embeddings import OpenAIEmbeddingsfrom langchain.llms import BaseLLMfrom langchain.vectorstores.base import VectorStorefrom pydantic import BaseModel, Fieldfrom langchain.chains.base import Chainfrom langchain.experimental import BabyAGIConnect 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 =


Initialize the vectorstore as emptyimport faissembedding_size = 1536index = faiss.IndexFlatL2(embedding_size)vectorstore = FAISS(embeddings_model.embed_query, index, InMemoryDocstore({}), {})Run the BabyAGIâ€‹Now it's time to create the BabyAGI controller and watch it try to accomplish your objective.OBJECTIVE = "Write a weather report for SF 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 San Francisco today    2. Make note of the temperature, humidity, wind speed, and other relevant weather conditions    3. Write a weather report summarizing the forecast    4. Check for any weather alerts or warnings    5. Share the report with the relevant stakeholders        *****TASK LIST*****        2: Check the current temperature in San Francisco    3: Check the current humidity in San Francisco    4: Check the current wind speed in San Francisco    5: Check for any weather alerts or warnings in San Francisco    6: Check the forecast for


Check for any weather alerts or warnings in San Francisco    6: Check the forecast for the next 24 hours in San Francisco    7: Check the forecast for the next 48 hours in San Francisco    8: Check the forecast for the next 72 hours in San Francisco    9: Check the forecast for the next week in San Francisco    10: Check the forecast for the next month in San Francisco    11: Check the forecast for the next 3 months in San Francisco    1: Write a weather report for SF today        *****NEXT TASK*****        2: Check the current temperature in San Francisco        *****TASK RESULT*****                I will check the current temperature in San Francisco. I will use an online weather service to get the most up-to-date information.        *****TASK LIST*****        3: Check the current UV index in San Francisco.    4: Check the current air quality in San Francisco.    5: Check the current precipitation levels in San Francisco.    6: Check the current cloud cover in San Francisco.    7: Check the current barometric pressure in San Francisco.    8: Check the current dew point in San Francisco.    9: Check the current wind direction in San Francisco.    10: Check the current humidity levels in San Francisco.    1: Check the current temperature in San Francisco to the average temperature for this time of year.    2: Check the current visibility in San Francisco.    11: Write a weather report for SF today.


11: Write a weather report for SF today.        *****NEXT TASK*****        3: Check the current UV index in San Francisco.        *****TASK RESULT*****                The current UV index in San Francisco 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*****        {'objective': 'Write a weather report for SF today'}PreviousAutoGPTNextBabyAGI with ToolsInstall and Import Required ModulesConnect to the Vector StoreRun the BabyAGICommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright Â© 2023 LangChain, Inc.


marathon_times | ğŸ¦œï¸�ğŸ”— Langchain


Skip to main contentğŸ¦œï¸�ğŸ”— LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKUse casesQA and Chat over DocumentsAnalyzing structured dataExtractionInteracting with APIsChatbotsSummarizationCode UnderstandingAgent simulationsAgentsAutonomous (long-running) agentsAutoGPTBabyAGI User GuideBabyAGI with ToolsHuggingGPTmarathon_timesMeta-PromptMulti-modalUse casesAutonomous (long-running) agentsmarathon_timesOn this pagemarathon_timesAutoGPT example finding Winning Marathon Timesâ€‹Implementation of https://github.com/Significant-Gravitas/Auto-GPT With LangChain primitives (LLMs, PromptTemplates, VectorStores, Embeddings, Tools)# !pip install bs4# !pip install nest_asyncio# Generalimport osimport pandas as pdfrom langchain.experimental.autonomous_agents.autogpt.agent import AutoGPTfrom langchain.chat_models import ChatOpenAIfrom langchain.agents.agent_toolkits.pandas.base import create_pandas_dataframe_agentfrom langchain.docstore.document import Documentimport asyncioimport nest_asyncio# Needed synce jupyter runs an async eventloopnest_asyncio.apply()llm = ChatOpenAI(model_name="gpt-4", temperature=1.0)Set up toolsâ€‹We'll set up an AutoGPT with a search tool, and write-file tool, and a read-file tool, a web browsing tool, and a tool to interact with a CSV file via a python REPLDefine any other tools you want to use below:# Toolsimport osfrom contextlib import contextmanagerfrom typing import Optionalfrom langchain.agents import toolfrom langchain.tools.file_management.read import ReadFileToolfrom langchain.tools.file_management.write import WriteFileToolROOT_DIR = "./data/"@contextmanagerdef pushd(new_dir):    """Context manager for changing the current working


pushd(new_dir):    """Context manager for changing the current working directory."""    prev_dir = os.getcwd()    os.chdir(new_dir)    try:        yield    finally:        os.chdir(prev_dir)@tooldef process_csv(    csv_file_path: str, instructions: str, output_path: Optional[str] = None) -> str:    """Process a CSV by with pandas in a limited REPL.\ Only use this after writing data to disk as a csv file.\ Any figures must be saved to disk to be viewed by the human.\ Instructions should be written in natural language, not code. Assume the dataframe is already loaded."""    with pushd(ROOT_DIR):        try:            df = pd.read_csv(csv_file_path)        except Exception as e:            return f"Error: {e}"        agent = create_pandas_dataframe_agent(llm, df, max_iterations=30, verbose=True)        if output_path is not None:            instructions += f" Save output to disk at {output_path}"        try:            result = agent.run(instructions)            return result        except Exception as e:            return f"Error: {e}"Browse a web page with PlayWright# !pip install playwright# !playwright installasync def async_load_playwright(url: str) -> str:    """Load the specified URLs


def async_load_playwright(url: str) -> str:    """Load the specified URLs using Playwright and parse using BeautifulSoup."""    from bs4 import BeautifulSoup    from playwright.async_api import async_playwright    results = ""    async with async_playwright() as p:        browser = await p.chromium.launch(headless=True)        try:            page = await browser.new_page()            await page.goto(url)            page_source = await page.content()            soup = BeautifulSoup(page_source, "html.parser")            for script in soup(["script", "style"]):                script.extract()            text = soup.get_text()            lines = (line.strip() for line in text.splitlines())            chunks = (phrase.strip() for line in lines for phrase in line.split("  "))            results = "\n".join(chunk for chunk in chunks if chunk)        except Exception as e:            results = f"Error: {e}"        await browser.close()    return resultsdef run_async(coro):    event_loop = asyncio.get_event_loop()    return event_loop.run_until_complete(coro)@tooldef browse_web_page(url: str) -> str:    """Verbose way to scrape a whole


browse_web_page(url: str) -> str:    """Verbose way to scrape a whole webpage. Likely to cause issues parsing."""    return run_async(async_load_playwright(url))Q&A Over a webpageHelp the model ask more directed questions of web pages to avoid cluttering its memoryfrom langchain.tools import BaseTool, DuckDuckGoSearchRunfrom langchain.text_splitter import RecursiveCharacterTextSplitterfrom pydantic import Fieldfrom langchain.chains.qa_with_sources.loading import (    load_qa_with_sources_chain,    BaseCombineDocumentsChain,)def _get_text_splitter():    return RecursiveCharacterTextSplitter(        # Set a really small chunk size, just to show.        chunk_size=500,        chunk_overlap=20,        length_function=len,    )class WebpageQATool(BaseTool):    name = "query_webpage"    description = (        "Browse a webpage and retrieve the information relevant to the question."    )    text_splitter: RecursiveCharacterTextSplitter = Field(        default_factory=_get_text_splitter    )    qa_chain: BaseCombineDocumentsChain    def _run(self, url: str, question: str) -> str:        """Useful for browsing websites and scraping the text information."""        result = browse_web_page.run(url)        docs = [Document(page_content=result, metadata={"source": url})]        web_docs = self.text_splitter.split_documents(docs)        results = []


results = []        # TODO: Handle this with a MapReduceChain        for i in range(0, len(web_docs), 4):            input_docs = web_docs[i : i + 4]            window_result = self.qa_chain(                {"input_documents": input_docs, "question": question},                return_only_outputs=True,            )            results.append(f"Response from window {i} - {window_result}")        results_docs = [            Document(page_content="\n".join(results), metadata={"source": url})        ]        return self.qa_chain(            {"input_documents": results_docs, "question": question},            return_only_outputs=True,        )    async def _arun(self, url: str, question: str) -> str:        raise NotImplementedErrorquery_website_tool = WebpageQATool(qa_chain=load_qa_with_sources_chain(llm))Set up memoryâ€‹The memory here is used for the agents intermediate steps# Memoryimport faissfrom langchain.vectorstores import FAISSfrom langchain.docstore import InMemoryDocstorefrom langchain.embeddings import OpenAIEmbeddingsfrom langchain.tools.human.tool import HumanInputRunembeddings_model =


import OpenAIEmbeddingsfrom langchain.tools.human.tool import HumanInputRunembeddings_model = OpenAIEmbeddings()embedding_size = 1536index = faiss.IndexFlatL2(embedding_size)vectorstore = FAISS(embeddings_model.embed_query, index, InMemoryDocstore({}), {})Setup model and AutoGPTâ€‹Model set-up# !pip install duckduckgo_searchweb_search = DuckDuckGoSearchRun()tools = [    web_search,    WriteFileTool(root_dir="./data"),    ReadFileTool(root_dir="./data"),    process_csv,    query_website_tool,    # HumanInputRun(), # Activate if you want the permit asking for help from the human]agent = AutoGPT.from_llm_and_tools(    ai_name="Tom",    ai_role="Assistant",    tools=tools,    llm=llm,    memory=vectorstore.as_retriever(search_kwargs={"k": 8}),    # human_in_the_loop=True, # Set to True if you want to add feedback at each step.)# agent.chain.verbose = TrueAutoGPT for Querying the Webâ€‹I've spent a lot of time over the years crawling data sources and cleaning data. Let's see if AutoGPT can help with this!Here is the prompt for looking up recent boston marathon times and converting them to tabular form.agent.run(    [        "What were the winning boston marathon times for the past 5 years (ending in 2022)? Generate a table of the year, name, country of origin, and times."    ])    {        "thoughts": {            "text": "I


{            "text": "I need to find the winning Boston Marathon times for the past 5 years. I can use the DuckDuckGo Search command to search for this information.",            "reasoning": "Using DuckDuckGo Search will help me gather information on the winning times without complications.",            "plan": "- Use DuckDuckGo Search to find the winning Boston Marathon times\n- Generate a table with the year, name, country of origin, and times\n- Ensure there are no legal complications",            "criticism": "None",            "speak": "I will use the DuckDuckGo Search command to find the winning Boston Marathon times for the past 5 years."        },        "command": {            "name": "DuckDuckGo Search",            "args": {                "query": "winning Boston Marathon times for the past 5 years ending in 2022"            }        }    }    {        "thoughts": {            "text": "The DuckDuckGo Search command did not provide the specific information I need. I must switch my approach and use query_webpage command to browse a webpage containing the Boston Marathon winning times for the past 5 years.",            "reasoning":


past 5 years.",            "reasoning": "The query_webpage command may give me more accurate and comprehensive results compared to the search command.",            "plan": "- Use query_webpage command to find the winning Boston Marathon times\n- Generate a table with the year, name, country of origin, and times\n- Ensure there are no legal complications",            "criticism": "I may face difficulty in finding the right webpage with the desired information.",            "speak": "I will use the query_webpage command to find the winning Boston Marathon times for the past 5 years."        },        "command": {            "name": "DuckDuckGo Search",            "args": {                "query": "site with winning Boston Marathon times for the past 5 years ending in 2022"            }        }    }    {        "thoughts": {            "text": "I need to use the query_webpage command to find the information about the winning Boston Marathon times for the past 5 years.",            "reasoning": "The previous DuckDuckGo Search command did not provide specific enough results. The query_webpage command might give more accurate and comprehensive results.",            "plan": "- Use query_webpage command to


"plan": "- Use query_webpage command to find the winning Boston Marathon times\\n- Generate a table with the year, name, country of origin, and times\\n- Ensure there are no legal complications",            "criticism": "I may face difficulty in finding the right webpage with the desired information.",            "speak": "I will use the query_webpage command to find the winning Boston Marathon times for the past 5 years."        },        "command": {            "name": "query_webpage",            "args": {                "url": "https://en.wikipedia.org/wiki/List_of_winners_of_the_Boston_Marathon",                "question": "What were the winning Boston Marathon times for the past 5 years ending in 2022?"            }        }    }    {        "thoughts": {            "text": "I have already found the winning Boston Marathon times for the past 5 years. Now, I need to generate a table with the information.",            "reasoning": "Using the information I already have, I can create a table containing year, name, country of origin, and times.",            "plan": "- Write the marathon data to a CSV file\n- Process the


"plan": "- Write the marathon data to a CSV file\n- Process the CSV file to display the table",            "criticism": "None",            "speak": "I will generate a table with the year, name, country of origin, and times for the winning Boston Marathon times for the past 5 years."        },        "command": {            "name": "write_file",            "args": {                "file_path": "boston_marathon_winners.csv",                "text": "Year,Name,Country,Time\n2022,Evans Chebet,KEN,2:06:51\n2021,Benson Kipruto,KEN,2:09:51\n2019,Lawrence Cherono,KEN,2:07:57\n2018,Yuki Kawauchi,JPN,2:15:58"            }        }    }    {        "thoughts": {            "text": "I have retrieved the winning Boston Marathon times for the past 5 years. Now, I need to generate a table with the year, name, country of origin, and times.",            "reasoning": "Creating a table will help organize the data in a clear and accessible format.",            "plan": "-


clear and accessible format.",            "plan": "- Write the data to a CSV file\n- Process the CSV file to generate the table\n- Complete the task",            "criticism": "None",            "speak": "I will generate a table with the year, name, country of origin, and winning times using the recently retrieved data."        },        "command": {            "name": "write_file",            "args": {                "file_path": "winning_boston_marathon_data.csv",                "text": "Year,Name,Country,Time\n2022,Evans Chebet,KEN,2:06:51\n2021,Benson Kipruto,KEN,2:09:51\n2019,Lawrence Cherono,KEN,2:07:57\n2018,Yuki Kawauchi,JPN,2:15:58\n"            }        }    }    {        "thoughts": {            "text": "I have found the winning Boston Marathon times for the past five years ending in 2022. Next, I need to create a table with the year, name, country of origin, and times.",            "reasoning": "Generating a table will help organize the information in a structured format.",


"reasoning": "Generating a table will help organize the information in a structured format.",            "plan": "- Create a table with the year, name, country of origin, and times\n- Ensure there are no legal complications",            "criticism": "None",            "speak": "I will generate a table with the winning Boston Marathon times for the past 5 years ending in 2022."        },        "command": {            "name": "write_file",            "args": {                "file_path": "winning_times.csv",                "text": "Year,Name,Country,Time\n2022,Evans Chebet,Kenya,2:06:51\n2021,Benson Kipruto,Kenya,2:09:51\n2020,Canceled due to COVID-19 pandemic,,\n2019,Lawrence Cherono,Kenya,2:07:57\n2018,Yuki Kawauchi,Japan,2:15:58"            }        }    }    {        "thoughts": {            "text": "I need to process the CSV file to generate the table with the year, name, country of origin, and winning times.",            "reasoning": "I have already written


"reasoning": "I have already written the data to a file named 'winning_times.csv'. Now, I need to process this CSV file to properly display the data as a table.",            "plan": "- Use the process_csv command to read the 'winning_times.csv' file and generate the table",            "criticism": "None",            "speak": "I will process the 'winning_times.csv' file to display the table with the winning Boston Marathon times for the past 5 years."        },        "command": {            "name": "process_csv",            "args": {                "csv_file_path": "winning_times.csv",                "instructions": "Read the CSV file and display the data as a table"            }        }    }            > Entering new AgentExecutor chain...    Thought: The CSV file has already been read and saved into a pandas dataframe called `df`. Hence, I can simply display the data by printing the whole dataframe. Since `df.head()` returns the first 5 rows, I can use that to showcase the contents.        Action: python_repl_ast    Action Input: print(df.head())   Year


Year                               Name Country     Time    0  2022                       Evans Chebet   Kenya  2:06:51    1  2021                     Benson Kipruto   Kenya  2:09:51    2  2020  Canceled due to COVID-19 pandemic     NaN      NaN    3  2019                   Lawrence Cherono   Kenya  2:07:57    4  2018                      Yuki Kawauchi   Japan  2:15:58        Observation: None    Thought:I used the wrong tool to perform the action. I should have used the given data and not interacted with the Python shell. I can now provide the displayed data as the answer since the information in the printed dataframe would look like a table when typed as text.        Final Answer:        Year                               Name Country     Time    0  2022                       Evans Chebet   Kenya


Evans Chebet   Kenya  2:06:51    1  2021                     Benson Kipruto   Kenya  2:09:51    2  2020  Canceled due to COVID-19 pandemic     NaN      NaN    3  2019                   Lawrence Cherono   Kenya  2:07:57    4  2018                      Yuki Kawauchi   Japan  2:15:58        > Finished chain.    {        "thoughts": {            "text": "I already have the winning Boston Marathon times for the past 5 years saved in the file 'winning_times.csv'. Now, I need to process the CSV and display the table.",            "reasoning": "I am choosing the process_csv command because I already have the required data saved as a CSV file, and I can use this command to read and display the data as a table.",            "plan": "- Use the process_csv command to read the 'winning_times.csv' file and generate the table",            "criticism": "None",            "speak": "I will process the 'winning_times.csv' file to display the table


"speak": "I will process the 'winning_times.csv' file to display the table with the winning Boston Marathon times for the past 5 years."        },        "command": {            "name": "process_csv",            "args": {                "csv_file_path": "winning_times.csv",                "instructions": "Read the CSV file and display the data as a table"            }        }    }            > Entering new AgentExecutor chain...    Thought: Since the data is already loaded in a pandas dataframe, I just need to display the top rows of the dataframe.    Action: python_repl_ast    Action Input: df.head()    Observation:    Year                               Name Country     Time    0  2022                       Evans Chebet   Kenya  2:06:51    1  2021                     Benson Kipruto   Kenya  2:09:51    2  2020  Canceled due to COVID-19 pandemic     NaN      NaN    3


pandemic     NaN      NaN    3  2019                   Lawrence Cherono   Kenya  2:07:57    4  2018                      Yuki Kawauchi   Japan  2:15:58    Thought:I now know the final answer.    Final Answer:        Year                               Name Country     Time    0  2022                       Evans Chebet   Kenya  2:06:51    1  2021                     Benson Kipruto   Kenya  2:09:51    2  2020  Canceled due to COVID-19 pandemic     NaN      NaN    3  2019                   Lawrence Cherono   Kenya  2:07:57    4  2018                      Yuki Kawauchi   Japan  2:15:58        > Finished chain.    {        "thoughts": {


"thoughts": {            "text": "I have already generated a table with the winning Boston Marathon times for the past 5 years. Now, I can finish the task.",            "reasoning": "I have completed the required actions and obtained the desired data. The task is complete.",            "plan": "- Use the finish command",            "criticism": "None",            "speak": "I have generated the table with the winning Boston Marathon times for the past 5 years. Task complete."        },        "command": {            "name": "finish",            "args": {                "response": "I have generated the table with the winning Boston Marathon times for the past 5 years. Task complete."            }        }    }    'I have generated the table with the winning Boston Marathon times for the past 5 years. Task complete.'PreviousHuggingGPTNextMeta-PromptAutoGPT example finding Winning Marathon TimesSet up toolsSet up memorySetup model and AutoGPTAutoGPT for Querying the WebCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright Â© 2023 LangChain, Inc.


BabyAGI with Tools | ğŸ¦œï¸�ğŸ”— Langchain


Skip to main contentğŸ¦œï¸�ğŸ”— LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKUse casesQA and Chat over DocumentsAnalyzing structured dataExtractionInteracting with APIsChatbotsSummarizationCode UnderstandingAgent simulationsAgentsAutonomous (long-running) agentsAutoGPTBabyAGI User GuideBabyAGI with ToolsHuggingGPTmarathon_timesMeta-PromptMulti-modalUse casesAutonomous (long-running) agentsBabyAGI with ToolsOn this pageBabyAGI with ToolsThis 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 informationInstall and Import Required Modulesâ€‹import osfrom collections import dequefrom typing import Dict, List, Optional, Anyfrom langchain import LLMChain, OpenAI, PromptTemplatefrom langchain.embeddings import OpenAIEmbeddingsfrom langchain.llms import BaseLLMfrom langchain.vectorstores.base import VectorStorefrom pydantic import BaseModel, Fieldfrom langchain.chains.base import Chainfrom langchain.experimental import BabyAGIConnect to the Vector Storeâ€‹Depending on what vectorstore you use, this step may look different.from 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


= FAISS(embeddings_model.embed_query, index, InMemoryDocstore({}), {})Define the Chainsâ€‹BabyAGI relies on three LLM chains:Task creation chain to select new tasks to add to the listTask prioritization chain to re-prioritize tasksExecution Chain to execute the tasksNOTE: 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,


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â€‹Now it's time to create the BabyAGI controller and watch it try to accomplish your objective.OBJECTIVE = "Write a weather report for SF 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 list    Action: TODO    Action Input: Write a weather report for SF today        1. Research current weather conditions in San Francisco    2. Gather data on temperature, humidity, wind speed, and other relevant weather conditions    3. Analyze data to


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 San Francisco    6. Discuss any upcoming weather changes    7. Summarize the weather report    8. Proofread and edit the report    9. Submit the report I now know the final answer    Final Answer: The todo list for writing a weather report for SF today is: 1. Research current weather conditions in San Francisco; 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 San Francisco; 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 SF today is: 1. Research current weather conditions in San Francisco; 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 San Francisco; 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;


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 San Francisco;    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 San Francisco    Action: Search    Action Input: Current weather conditions in San FranciscoCurrent Weather for Popular Cities ; San Francisco, 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 report    Action: TODO    Action Input: Compile data into a weather report        1. 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.


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 answer    Final Answer: Today in San Francisco, 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 San Francisco, 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 San Francisco to the forecasted conditions;    6: Identify any potential weather-related hazards in the area;    7: Research historical weather patterns in San Francisco;    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


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 San Francisco;    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: TODO    Action Input: Make the report easy to read        1. Break up the report into sections with clear headings    2. Use bullet points and numbered lists to organize information    3. Use short, concise sentences    4. Use simple language and avoid jargon    5. Include visuals such as charts, graphs, and diagrams to illustrate points    6. Use bold and italicized text to emphasize key points    7. Include a table of contents and page numbers    8. Use a consistent font and font size throughout the report    9. Include a summary at the end of the report    10. Proofread the report for typos and errors I now know the final answer    Final 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


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.        *****TASK ENDING*****        {'objective': 'Write a weather report for SF today'}PreviousBabyAGI User GuideNextHuggingGPTInstall and Import Required ModulesConnect to the Vector StoreDefine the ChainsRun the BabyAGICommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright Â© 2023 LangChain, Inc.


Page Not Found | ğŸ¦œï¸�ğŸ”— Langchain

Skip to main contentğŸ¦œï¸�ğŸ”— LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKPage Not FoundWe could not find what you were looking for.Please contact the owner of the site that linked you to the original URL and let them know their link is broken.CommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright Â© 2023 LangChain, Inc.


Meta-Prompt | ğŸ¦œï¸�ğŸ”— Langchain


Skip to main contentğŸ¦œï¸�ğŸ”— LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKUse casesQA and Chat over DocumentsAnalyzing structured dataExtractionInteracting with APIsChatbotsSummarizationCode UnderstandingAgent simulationsAgentsAutonomous (long-running) agentsAutoGPTBabyAGI User GuideBabyAGI with ToolsHuggingGPTmarathon_timesMeta-PromptMulti-modalUse casesAutonomous (long-running) agentsMeta-PromptOn this pageMeta-PromptThis is a LangChain implementation of Meta-Prompt, by Noah Goodman, for building self-improving agents.The key idea behind Meta-Prompt is to prompt the agent to reflect on its own performance and modify its own instructions.Here is a description from the original blog post:The agent is a simple loop that starts with no instructions and follows these steps:Engage in conversation with a user, who may provide requests, instructions, or feedback.At the end of the episode, generate self-criticism and a new instruction using the meta-promptAssistant has just had the below interactions with a User. Assistant followed their "system: Instructions" closely. Your job is to critique the Assistant's performance and then revise the Instructions so that Assistant would quickly and correctly respond in the future. ####{hist}#### Please reflect on these interactions.You should first critique Assistant's performance. What could Assistant have done better? What should the Assistant remember about this user? Are there things this user always wants? Indicate this with "Critique: ...".You should next revise the Instructions so that Assistant would quickly and correctly respond in the future. Assistant's goal is to satisfy the user in as few interactions as possible. Assistant will only see the new Instructions, not the interaction history, so anything important must be summarized in the Instructions. Don't forget any important details in the current Instructions! Indicate the new Instructions by "Instructions: ...".Repeat.The


important details in the current Instructions! Indicate the new Instructions by "Instructions: ...".Repeat.The only fixed instructions for this system (which I call Meta-prompt) is the meta-prompt that governs revision of the agentâ€™s instructions. The agent has no memory between episodes except for the instruction it modifies for itself each time. Despite its simplicity, this agent can learn over time and self-improve by incorporating useful details into its instructions.Setupâ€‹We define two chains. One serves as the Assistant, and the other is a "meta-chain" that critiques the Assistant's performance and modifies the instructions to the Assistant.from langchain import OpenAI, LLMChain, PromptTemplatefrom langchain.memory import ConversationBufferWindowMemorydef initialize_chain(instructions, memory=None):    if memory is None:        memory = ConversationBufferWindowMemory()        memory.ai_prefix = "Assistant"    template = f"""    Instructions: {instructions}    {{{memory.memory_key}}}    Human: {{human_input}}    Assistant:"""    prompt = PromptTemplate(        input_variables=["history", "human_input"], template=template    )    chain = LLMChain(        llm=OpenAI(temperature=0),        prompt=prompt,        verbose=True,        memory=ConversationBufferWindowMemory(),    )    return chaindef initialize_meta_chain():    meta_template = """    Assistant has just had the below interactions with a User. Assistant followed their "Instructions" closely. Your job is to critique the Assistant's performance and then revise the Instructions so that Assistant would quickly and correctly respond in the future.    ####


the Instructions so that Assistant would quickly and correctly respond in the future.    ####    {chat_history}    ####    Please reflect on these interactions.    You should first critique Assistant's performance. What could Assistant have done better? What should the Assistant remember about this user? Are there things this user always wants? Indicate this with "Critique: ...".    You should next revise the Instructions so that Assistant would quickly and correctly respond in the future. Assistant's goal is to satisfy the user in as few interactions as possible. Assistant will only see the new Instructions, not the interaction history, so anything important must be summarized in the Instructions. Don't forget any important details in the current Instructions! Indicate the new Instructions by "Instructions: ...".    """    meta_prompt = PromptTemplate(        input_variables=["chat_history"], template=meta_template    )    meta_chain = LLMChain(        llm=OpenAI(temperature=0),        prompt=meta_prompt,        verbose=True,    )    return meta_chaindef get_chat_history(chain_memory):    memory_key = chain_memory.memory_key    chat_history = chain_memory.load_memory_variables(memory_key)[memory_key]    return chat_historydef get_new_instructions(meta_output):    delimiter = "Instructions: "    new_instructions = meta_output[meta_output.find(delimiter) + len(delimiter) :]    return new_instructionsdef main(task, max_iters=3, max_meta_iters=5):    failed_phrase = "task failed"    success_phrase = "task succeeded"    key_phrases = [success_phrase, failed_phrase]    instructions = "None"


= [success_phrase, failed_phrase]    instructions = "None"    for i in range(max_meta_iters):        print(f"[Episode {i+1}/{max_meta_iters}]")        chain = initialize_chain(instructions, memory=None)        output = chain.predict(human_input=task)        for j in range(max_iters):            print(f"(Step {j+1}/{max_iters})")            print(f"Assistant: {output}")            print(f"Human: ")            human_input = input()            if any(phrase in human_input.lower() for phrase in key_phrases):                break            output = chain.predict(human_input=human_input)        if success_phrase in human_input.lower():            print(f"You succeeded! Thanks for playing!")            return        meta_chain = initialize_meta_chain()        meta_output = meta_chain.predict(chat_history=get_chat_history(chain.memory))        print(f"Feedback: {meta_output}")        instructions = get_new_instructions(meta_output)        print(f"New Instructions: {instructions}")        print("\n" + "#" * 80 + "\n")    print(f"You failed! Thanks for playing!")Specify a


80 + "\n")    print(f"You failed! Thanks for playing!")Specify a task and interact with the agentâ€‹task = "Provide a systematic argument for why we should always eat pasta with olives."main(task)    [Episode 1/5]            > Entering new LLMChain chain...    Prompt after formatting:            Instructions: None                Human: Provide a systematic argument for why we should always eat pasta with olives.        Assistant:        > Finished chain.    (Step 1/3)    Assistant:  Eating pasta with olives is a great way to add flavor and texture to a dish. Olives are a great source of healthy fats, vitamins, and minerals, and they can help to balance out the carbohydrates in the pasta. Additionally, olives provide a unique flavor that can help to make the dish more interesting and enjoyable.    Human:     You response is not in the form of a poem. Try again!            > Entering new LLMChain chain...    Prompt after formatting:            Instructions: None        Human: Provide a systematic argument for why we should always eat pasta with olives.    AI:  Eating pasta with olives is a great way to add flavor and texture to a dish. Olives are a great source of healthy fats, vitamins, and minerals, and they can help to balance out the carbohydrates in the pasta. Additionally, olives provide a unique flavor that can help to make the dish more interesting and enjoyable.


provide a unique flavor that can help to make the dish more interesting and enjoyable.        Human: You response is not in the form of a poem. Try again!        Assistant:        > Finished chain.    (Step 2/3)    Assistant:  Eating pasta with olives is a great way to add flavor and texture to a dish. Olives are a great source of healthy fats, vitamins, and minerals, which can help to balance out the carbohydrates in the pasta. Additionally, olives provide a unique flavor that can help to make the dish more interesting and enjoyable. For these reasons, it is recommended to always eat pasta with olives for a more balanced and flavorful meal.    Human:     Your response is not piratey enough. Try again!            > Entering new LLMChain chain...    Prompt after formatting:            Instructions: None        Human: Provide a systematic argument for why we should always eat pasta with olives.    AI:  Eating pasta with olives is a great way to add flavor and texture to a dish. Olives are a great source of healthy fats, vitamins, and minerals, and they can help to balance out the carbohydrates in the pasta. Additionally, olives provide a unique flavor that can help to make the dish more interesting and enjoyable.    Human: You response is not in the form of a poem. Try again!    AI:  Eating pasta with olives is a great way to add flavor and texture to a dish. Olives are a great source of healthy fats, vitamins, and minerals, which can help to balance out the carbohydrates in the pasta. Additionally, olives provide a unique flavor that can help


to balance out the carbohydrates in the pasta. Additionally, olives provide a unique flavor that can help to make the dish more interesting and enjoyable. For these reasons, it is recommended to always eat pasta with olives for a more balanced and flavorful meal.        Human: Your response is not piratey enough. Try again!        Assistant:        > Finished chain.    (Step 3/3)    Assistant:  Arrr, me hearties! Eating pasta with olives be a great way to add flavor and texture to a dish. Olives be a great source of healthy fats, vitamins, and minerals, which can help to balance out the carbohydrates in the pasta. Additionally, olives provide a unique flavor that can help to make the dish more interesting and enjoyable. So, it be recommended to always eat pasta with olives for a more balanced and flavorful meal.    Human:     Task failed.            > Entering new LLMChain chain...    Prompt after formatting:            Assistant has just had the below interactions with a User. Assistant followed their "Instructions" closely. Your job is to critique the Assistant's performance and then revise the Instructions so that Assistant would quickly and correctly respond in the future.            ####            Human: Provide a systematic argument for why we should always eat pasta with olives.    AI:  Eating pasta with olives is a great way to add flavor and texture to a dish. Olives are a great source of healthy fats, vitamins, and minerals, and they can help to balance out the carbohydrates in the pasta. Additionally, olives provide a unique flavor that can help to make the


the carbohydrates in the pasta. Additionally, olives provide a unique flavor that can help to make the dish more interesting and enjoyable.    Human: You response is not in the form of a poem. Try again!    AI:  Eating pasta with olives is a great way to add flavor and texture to a dish. Olives are a great source of healthy fats, vitamins, and minerals, which can help to balance out the carbohydrates in the pasta. Additionally, olives provide a unique flavor that can help to make the dish more interesting and enjoyable. For these reasons, it is recommended to always eat pasta with olives for a more balanced and flavorful meal.    Human: Your response is not piratey enough. Try again!    AI:  Arrr, me hearties! Eating pasta with olives be a great way to add flavor and texture to a dish. Olives be a great source of healthy fats, vitamins, and minerals, which can help to balance out the carbohydrates in the pasta. Additionally, olives provide a unique flavor that can help to make the dish more interesting and enjoyable. So, it be recommended to always eat pasta with olives for a more balanced and flavorful meal.            ####            Please reflect on these interactions.            You should first critique Assistant's performance. What could Assistant have done better? What should the Assistant remember about this user? Are there things this user always wants? Indicate this with "Critique: ...".            You should next revise the Instructions so that Assistant would quickly and correctly respond in the future. Assistant's goal is to satisfy the user in as few interactions as possible. Assistant will only see the new Instructions, not the interaction history, so anything important must be summarized in the


will only see the new Instructions, not the interaction history, so anything important must be summarized in the Instructions. Don't forget any important details in the current Instructions! Indicate the new Instructions by "Instructions: ...".                > Finished chain.    Feedback:     Critique: The Assistant should remember that this user wants a response in the form of a poem or pirate-speak.        Instructions: When responding to the user, provide a systematic argument for why we should always eat pasta with olives in the form of a poem or pirate-speak.    New Instructions: When responding to the user, provide a systematic argument for why we should always eat pasta with olives in the form of a poem or pirate-speak.        ################################################################################        [Episode 2/5]            > Entering new LLMChain chain...    Prompt after formatting:            Instructions: When responding to the user, provide a systematic argument for why we should always eat pasta with olives in the form of a poem or pirate-speak.                Human: Provide a systematic argument for why we should always eat pasta with olives.        Assistant:        > Finished chain.    (Step 1/3)    Assistant:          Arrr, me hearty! Let me tell ye why ye should always eat pasta with olives.        First, the olives add a salty flavor that be sure to please.    The briny taste be sure to tantalize yer taste buds


be sure to please.    The briny taste be sure to tantalize yer taste buds with ease.        Second, the olives add a bit of texture to the dish.    The crunchy bites be sure to make yer mouth water with a wish.        Third, the olives add a bit of color to the plate.    The vibrant green be sure to make yer eyes appreciate.        So, me hearties, ye should always eat pasta with olives.    The flavor, texture, and color be sure to make yer meal a success!    Human:     Your response is too long! Try again.            > Entering new LLMChain chain...    Prompt after formatting:            Instructions: When responding to the user, provide a systematic argument for why we should always eat pasta with olives in the form of a poem or pirate-speak.        Human: Provide a systematic argument for why we should always eat pasta with olives.    AI:          Arrr, me hearty! Let me tell ye why ye should always eat pasta with olives.        First, the olives add a salty flavor that be sure to please.    The briny taste be sure to tantalize yer taste buds with ease.        Second, the olives add a bit of texture to the dish.    The crunchy bites be sure to make yer mouth water with a wish.        Third, the olives add a bit of color to the plate.    The vibrant green be sure to make yer eyes appreciate.


the plate.    The vibrant green be sure to make yer eyes appreciate.        So, me hearties, ye should always eat pasta with olives.    The flavor, texture, and color be sure to make yer meal a success!        Human: Your response is too long! Try again.        Assistant:        > Finished chain.    (Step 2/3)    Assistant:         Aye, me hearties! Ye should always eat pasta with olives.    The flavor, texture, and color be sure to make yer meal a success!    Human:     Your response should be in the form of a poem. Try again!            > Entering new LLMChain chain...    Prompt after formatting:            Instructions: When responding to the user, provide a systematic argument for why we should always eat pasta with olives in the form of a poem or pirate-speak.        Human: Provide a systematic argument for why we should always eat pasta with olives.    AI:          Arrr, me hearty! Let me tell ye why ye should always eat pasta with olives.        First, the olives add a salty flavor that be sure to please.    The briny taste be sure to tantalize yer taste buds with ease.        Second, the olives add a bit of texture to the dish.    The crunchy bites be sure to make yer mouth water with a wish.        Third, the olives add a bit of


with a wish.        Third, the olives add a bit of color to the plate.    The vibrant green be sure to make yer eyes appreciate.        So, me hearties, ye should always eat pasta with olives.    The flavor, texture, and color be sure to make yer meal a success!    Human: Your response is too long! Try again.    AI:         Aye, me hearties! Ye should always eat pasta with olives.    The flavor, texture, and color be sure to make yer meal a success!        Human: Your response should be in the form of a poem. Try again!        Assistant:        > Finished chain.    (Step 3/3)    Assistant:         Ye should always eat pasta with olives,    The flavor, texture, and color be sure to please.    The salty taste and crunchy bites,    Will make yer meal a delight.    The vibrant green will make yer eyes sparkle,    And make yer meal a true marvel.    Human:     Task succeeded    You succeeded! Thanks for playing!Previousmarathon_timesNextimage_agentSetupSpecify a task and interact with the agentCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright Â© 2023 LangChain, Inc.


HuggingGPT | ğŸ¦œï¸�ğŸ”— Langchain


Skip to main contentğŸ¦œï¸�ğŸ”— LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKUse casesQA and Chat over DocumentsAnalyzing structured dataExtractionInteracting with APIsChatbotsSummarizationCode UnderstandingAgent simulationsAgentsAutonomous (long-running) agentsAutoGPTBabyAGI User GuideBabyAGI with ToolsHuggingGPTmarathon_timesMeta-PromptMulti-modalUse casesAutonomous (long-running) agentsHuggingGPTOn this pageHuggingGPTImplementation of HuggingGPT. HuggingGPT is a system to connect LLMs (ChatGPT) with ML community (Hugging Face).ğŸ”¥ Paper: https://arxiv.org/abs/2303.17580ğŸš€ Project: https://github.com/microsoft/JARVISğŸ¤— Space: https://huggingface.co/spaces/microsoft/HuggingGPTSet up toolsâ€‹We set up the tools available from Transformers Agent. It includes a library of tools supported by Transformers and some customized tools such as image generator, video generator, text downloader and other tools.from transformers import load_toolhf_tools = [    load_tool(tool_name)    for tool_name in [        "document-question-answering",        "image-captioning",        "image-question-answering",        "image-segmentation",        "speech-to-text",        "summarization",        "text-classification",        "text-question-answering",        "translation",


"translation",        "huggingface-tools/text-to-image",        "huggingface-tools/text-to-video",        "text-to-speech",        "huggingface-tools/text-download",        "huggingface-tools/image-transformation",    ]]Setup model and HuggingGPTâ€‹We create an instance of HuggingGPT and use ChatGPT as the controller to rule the above tools.from langchain.llms import OpenAIfrom langchain_experimental.autonomous_agents import HuggingGPT# %env OPENAI_API_BASE=http://localhost:8000/v1llm = OpenAI(model_name="gpt-3.5-turbo")agent = HuggingGPT(llm, hf_tools)Run an exampleâ€‹Given a text, show a related image and video.agent.run("please show me a video and an image of 'a boy is running'")PreviousBabyAGI with ToolsNextmarathon_timesSet up toolsSetup model and HuggingGPTRun an exampleCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright Â© 2023 LangChain, Inc.


AutoGPT | ğŸ¦œï¸�ğŸ”— Langchain


Skip to main contentğŸ¦œï¸�ğŸ”— LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKUse casesQA and Chat over DocumentsAnalyzing structured dataExtractionInteracting with APIsChatbotsSummarizationCode UnderstandingAgent simulationsAgentsAutonomous (long-running) agentsAutoGPTBabyAGI User GuideBabyAGI with ToolsHuggingGPTmarathon_timesMeta-PromptMulti-modalUse casesAutonomous (long-running) agentsAutoGPTOn this pageAutoGPTImplementation of https://github.com/Significant-Gravitas/Auto-GPT but with LangChain primitives (LLMs, PromptTemplates, VectorStores, Embeddings, Tools)Set up toolsâ€‹We'll set up an AutoGPT with a search tool, and write-file tool, and a read-file toolfrom langchain.utilities import SerpAPIWrapperfrom langchain.agents import Toolfrom langchain.tools.file_management.write import WriteFileToolfrom langchain.tools.file_management.read import ReadFileToolsearch = SerpAPIWrapper()tools = [    Tool(        name="search",        func=search.run,        description="useful for when you need to answer questions about current events. You should ask targeted questions",    ),    WriteFileTool(),    ReadFileTool(),]Set up memoryâ€‹The memory here is used for the agents intermediate stepsfrom langchain.vectorstores import FAISSfrom langchain.docstore import InMemoryDocstorefrom langchain.embeddings import OpenAIEmbeddings# Define your embedding modelembeddings_model = OpenAIEmbeddings()# Initialize the vectorstore as emptyimport faissembedding_size = 1536index = faiss.IndexFlatL2(embedding_size)vectorstore =


= 1536index = faiss.IndexFlatL2(embedding_size)vectorstore = FAISS(embeddings_model.embed_query, index, InMemoryDocstore({}), {})Setup model and AutoGPTâ€‹Initialize everything! We will use ChatOpenAI modelfrom langchain.experimental import AutoGPTfrom langchain.chat_models import ChatOpenAIagent = AutoGPT.from_llm_and_tools(    ai_name="Tom",    ai_role="Assistant",    tools=tools,    llm=ChatOpenAI(temperature=0),    memory=vectorstore.as_retriever(),)# Set verbose to be trueagent.chain.verbose = TrueRun an exampleâ€‹Here we will make it write a weather report for SFagent.run(["write a weather report for SF today"])Chat History Memoryâ€‹In addition to the memory that holds the agent immediate steps, we also have a chat history memory. By default, the agent will use 'ChatMessageHistory' and it can be changed. This is useful when you want to use a different type of memory for example 'FileChatHistoryMemory'from langchain.memory.chat_message_histories import FileChatMessageHistoryagent = AutoGPT.from_llm_and_tools(    ai_name="Tom",    ai_role="Assistant",    tools=tools,    llm=ChatOpenAI(temperature=0),    memory=vectorstore.as_retriever(),    chat_history_memory=FileChatMessageHistory("chat_history.txt"),)PreviousAutonomous (long-running) agentsNextBabyAGI User GuideSet up toolsSet up memorySetup model and AutoGPTRun an exampleChat History MemoryCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright Â© 2023 LangChain, Inc.