Open the WaytoAGI knowledge base on Feishu · 100M+ visits, open to everyone →
WaytoAGI

Knowledge Base · Learning paths

LLM-Powered Autonomous Agents: The Brain Behind AI Agents | Lilian Weng

This article by Lilian Weng explores how Large Language Models (LLMs) serve as the core 'brain' for autonomous AI agents. It breaks down the three key components—planning (task decomposition and self-reflection), memory (short-term and long-term), and tool use—while examining powerful techniques like Chain-of-Thought (CoT), Tree of Thoughts (ToT), ReAct, and Reflexion that enable agents to tackle complex real-world tasks.

LLM agentsautonomous agentsLilian WengAI agentsReAct

Translated from Chinese by AI. Spotted an issue? Use the feedback button.

Original source: https://lilianweng.github.io/posts/2023-06-23-agent/

Author: Lilian Weng (Head of Research at OpenAI)

Translation: This version draws on two translations, by Chet, Who Wants to Master Algorithms and AI’s Subconscious, with minor revisions and proofreading.

Using an LLM (large language model) as the core controller of an AI agent is a fascinating concept. Proof-of-concept (PoC) demos such as AutoGPT, GPT-Engineer, and BabyAGI offer exciting examples. But the potential of LLMs goes beyond generating well-written copy, stories, essays, and code: they can also serve as powerful, general-purpose problem solvers.

Overview of an AI Agent System

In an LLM-powered autonomous AI agent system, the LLM acts as the agent’s brain, supported by several key components:

  • Planning

    • Subgoals and decomposition: The AI agent breaks down large tasks into smaller, manageable subgoals, enabling it to handle complex tasks effectively.
    • Reflection and refinement: The AI agent can critique and reflect on its past actions, learn from mistakes, and refine future steps, improving the quality of the final outcome.
  • Memory

    • Short-term memory: I consider all in-context learning (see Prompt Engineering) to be learning that uses the model’s short-term memory.
    • Long-term memory: This gives the AI agent the ability to retain and recall (potentially unlimited) information over extended periods, typically through an external vector store and fast retrieval.
  • Tool Use

    • The AI agent learns to call external APIs to obtain additional information absent from the model’s weights (which are usually difficult to change after pretraining), including up-to-date information, code execution capabilities, access to proprietary information sources, and more.

Figure 1. Overview of an LLM-powered autonomous AI agent system

Part 1: Planning

A complex task typically involves many steps. The AI agent needs to identify these steps and plan ahead.

Task Decomposition

Chain of Thought (CoT; Wei et al. 2022) has become a standard prompting technique for improving model performance on complex tasks. The model is instructed to “think step by step,” using additional test-time computation to break difficult tasks into smaller, simpler steps. CoT transforms large tasks into multiple manageable tasks and provides an explanation of the model’s reasoning process.

Tree of Thoughts (Yao et al. 2023) extends CoT by exploring multiple reasoning possibilities at each step. It first breaks a problem down into several reasoning steps, then generates multiple thoughts at each step, creating a tree structure. The search process can use BFS (breadth-first search) or DFS (depth-first search), with each state evaluated by a classifier (via prompting) or majority voting.

Task decomposition can be achieved in the following ways:

  • (1) Through simple prompts to an LLM, such as "Steps for XYZ.\n1." or "What are the subgoals for achieving XYZ?"

  • (2) Through task-specific instructions, such as "Write a story outline." for writing fiction

  • Or (3) Through human input

A distinctly different approach is LLM+P (Liu et al. 2023), which relies on an external classical planner for long-term planning. This approach uses the Planning Domain Definition Language (PDDL) as an intermediate interface to describe planning problems.

  • In this process, the LLM (1) translates the problem into “Problem PDDL”

  • Then (2) asks a classical planner to generate a PDDL plan based on an existing “Domain PDDL”

  • Finally (3) translates the PDDL plan back into natural language

Essentially, the planning step is outsourced to an external tool, assuming that domain-specific PDDL and a suitable planner are available. This is common in some robotics settings, but not in many other domains.

Self-Reflection

Self-reflection is an important capability that allows autonomous AI agents to improve iteratively by refining past action decisions and correcting previous mistakes. Trial and error is inevitable in real-world tasks, and self-reflection plays a crucial role in this process.

ReAct (Yao et al. 2023) integrates reasoning and action in large language models (LLMs) by expanding the action space to combine task-specific discrete actions with a language space. The former enables the LLM to interact with the environment (for example, using the Wikipedia search API), while the latter (the language space) encourages the LLM to generate reasoning traces in natural language.

The ReAct prompt template includes explicit steps for the LLM's thinking, roughly in the following format:

Thought: ...
Action: ...
Observation: ...
... (Repeated many times)

Figure 2. Examples of reasoning traces for knowledge-intensive tasks (such as HotpotQA and FEVER) and decision-making tasks (such as AlfWorld Env and WebShop). (Image source: Yao et al., 2023).

In experiments on both knowledge-intensive and decision-making tasks, ReAct outperformed the Act-only baseline (which omits the Thought: … step).

Reflexion ( Shinn & Labash 2023 ) is a framework that equips AI agents with dynamic memory and self-reflection capabilities to improve their reasoning skills. Reflexion uses a standard reinforcement learning setup in which a reward model provides simple binary rewards (0/1). Its action space follows the ReAct setup, augmenting the task-specific action space with language to enable complex reasoning steps. After each action a_t , the AI agent computes a heuristic h_t and may choose to reset the environment to begin a new trial based on its self-reflection.

Figure 3. Illustration of the Reflexion framework. (Image source: Shinn & Labash, 2023)

The heuristic function determines whether a trajectory is inefficient or contains hallucinations, in which case it should be stopped. Inefficient planning refers to trajectories that take too long without succeeding; hallucination refers to a series of consecutive identical actions that produce the same observations in the environment.

Self-reflection is generated by showing the LLM two examples (two-shot prompting), each consisting of a pair: a failed trajectory and an ideal reflection to guide changes to future plans. These reflections are then added to the AI agent's working memory (short-term memory), with up to three retained as context for querying the LLM.

Figure 4. Experiments on AlfWorld Env and HotpotQA. In AlfWorld, hallucinations are more common than inefficient planning. (Image source: Shinn & Labash, 2023)

Chain of Hindsight (CoH; Liu et al. 2023) encourages a model to improve its outputs by explicitly presenting a sequence of past outputs, each annotated with feedback. The human feedback data is a collection D_h = {(x, y_i , r_i , z_i)}{i=1}^n , where x is the prompt, each y_i is a model completion, r_i is the human rating of y_i , and z_i is the corresponding human-provided hindsight feedback. Assuming the feedback tuples are sorted by reward, r_n \geq r{n-1} \geq \dots \geq r_1 , the process involves supervised fine-tuning on data of the form \tau_h = (x, z_i, y_i, z_j, y_j, \dots, z_n, y_n) , where \leq i \leq j \leq n . The model is fine-tuned to predict only y_n (corresponding to the highest rating), conditioned on the sequence prefix, so that it can reflect on the feedback sequence to produce better outputs.

To avoid overfitting, CoH adds a regularization term when maximizing the log-likelihood of the pretraining dataset. To prevent shortcut learning and copying (since the feedback sequences contain many common words), the authors randomly mask 0%–5% of past tokens during training.

The training dataset used in their experiments combines WebGPT comparisons, summarization from human feedback, and the human preference dataset.

Figure 5. After fine-tuning with CoH, the model can follow instructions to generate a sequence of progressively improved outputs. (Image source: Liu et al. 2023)

The idea behind CoH is to present a history of progressively improved outputs in context and train the model to follow the trend toward better outputs. Algorithm Distillation (AD; Laskin et al., 2023) applies the same idea to cross-episode trajectories in reinforcement learning tasks, encapsulating the algorithm in a policy conditioned on a long history of trajectories (the context). As an AI agent interacts with its environment repeatedly and improves a little with each episode, AD concatenates this learning history and feeds it into the model. We can therefore expect the next predicted action to perform better than previous attempts. The algorithm aims to learn the reinforcement learning process, rather than to train a task-specific policy itself.

Figure 6. An illustration of how Algorithm Distillation (AD) works. (Image source: Laskin et al., 2023).

AD assumes that any algorithm can be distilled into a neural network through behavioral cloning of its historical learning data. This historical data is generated by a set of source policies trained on specific tasks. During training, a task is randomly sampled for each reinforcement learning run, and subsequences of multi-episode histories are used for training, making the learned policy task-agnostic.

In practice, however, the model has a limited context window, so the input episodes must be short enough to construct a multi-episode history. A multi-episode context containing 2–4 episodes is necessary to learn a near-optimal in-context reinforcement learning algorithm. The emergence of in-context reinforcement learning requires a sufficiently long context.

Compared with three baselines—ED (Expert Distillation, which performs behavioral cloning using expert trajectories rather than learning histories), the source policy (used to generate trajectories for UCB distillation), and RL^2 (Duan et al. 2017 ; used as an upper bound because it requires online RL)—AD demonstrates in-context RL despite using only offline RL, achieving performance close to RL^2 and learning much faster than the other baselines. When conditioned on a partial training history from the source policy, AD also improves much faster than the ED baseline.

Figure 7. A comparison of AD, ED, the source policy, and RL^2 in environments that require memory and exploration. Only binary rewards are assigned. The source policies are trained using A3C for the “dark” environments and DQN for the water maze. (Image source: Laskin et al., 2023)

Part 2: Memory

(Many thanks to ChatGPT for helping me draft this section. Through my conversation with ChatGPT, I learned a great deal about the human brain and data structures for fast MIPS.)

Types of Memory

Memory can be defined as the processes used to acquire, store, retain, and subsequently retrieve information. There are several types of memory in the human brain.

  1. Sensory memory: This is the earliest stage of memory, enabling us to retain impressions of sensory information (visual, auditory, etc.) after the original stimulus has ended. Sensory memory typically lasts only a few seconds. Subcategories include iconic memory (vision), echoic memory (hearing), and haptic memory (touch).

  2. Short-term memory (STM) or working memory: This stores information we are currently aware of and need to perform complex cognitive tasks such as learning and reasoning. Short-term memory is thought to have a capacity of approximately 7 items (Miller 1956) and to last 20–30 seconds.

  3. Long-term memory (LTM): Long-term memory can store information for extended periods, ranging from days to decades, with essentially unlimited storage capacity. LTM has two subtypes:

  • Explicit/declarative memory: This is memory for facts and events that can be consciously recalled, including episodic memory (events and experiences) and semantic memory (facts and concepts).
  • Implicit/procedural memory: This type of memory is unconscious and involves skills and habits performed automatically, such as riding a bicycle or typing on a keyboard.

Figure 8. Categories of human memory.

We can draw the following rough parallels:

  • Sensory memory corresponds to learned embedding representations of raw inputs, including text, images, or other modalities;

  • Short-term memory is akin to in-context learning. It is brief and limited because it is constrained by the finite context window of a Transformer.

  • Long-term memory corresponds to an external vector store that AI agents can access through fast retrieval and use at query time.

Maximum Inner Product Search (MIPS)

External memory can help overcome the limitations of a finite attention span. The standard approach is to save embedding representations of information in a vector database that supports fast maximum inner product search (MIPS). To optimize retrieval speed, a common choice is to use approximate nearest neighbor (ANN) algorithms, which return an approximation of the top k nearest neighbors, trading a little accuracy for a substantial speedup.

Some common ANN algorithms for fast MIPS include:

  • LSH (Locality-Sensitive Hashing): This introduces a hash function that maps similar input items to the same bucket with high probability, with far fewer buckets than input items.

  • ANNOY (Approximate Nearest Neighbors Oh Yeah): Its core data structure is a collection of random projection trees—binary trees in which each non-leaf node represents a hyperplane that divides the input space in half, and each leaf node stores a data point. The trees are built independently and randomly, so they mimic hash functions to some extent. ANNOY searches across all trees, iteratively exploring the half closest to the query and aggregating the results. This idea is closely related to KD-trees but offers greater scalability.

  • HNSW (Hierarchical Navigable Small World): This is inspired by the concept of small-world networks, in which most nodes can reach any other node in just a few steps—for example, the “six degrees of separation” property of social networks. HNSW builds a hierarchy of these small-world graphs, with the bottom layer containing the actual data points. Intermediate layers create shortcuts to accelerate searches. During a search, HNSW starts at a random node in the top layer and navigates toward the target node. When it can no longer get closer, it descends to the next layer, continuing until it reaches the bottom layer. Each move in the upper layers can cover a large distance in the data space, while moves in the lower layers improve search quality.

  • FAISS (Facebook AI Similarity Search): This operates on the assumption that distances between nodes in high-dimensional spaces follow a Gaussian distribution, so clusters of data points should exist. FAISS applies vector quantization by partitioning the vector space into clusters and quantizing within those clusters. A search first uses coarse quantization to identify candidate clusters, then uses finer quantization to search the data within each cluster.

  • ScaNN (Scalable Nearest Neighbors): ScaNN’s main innovation is anisotropic vector quantization. It quantizes a data point x_i into \tilde{x}_i so that the inner products \langle q, x_i \rangle and \langle q, \tilde{x}_i \rangle are as similar as possible, rather than selecting the nearest quantization centroid.

Figure 9. Categories of human memory. (Image source: Google Blog, 2020)

See more MIPS algorithms and performance comparisons at ann-benchmarks.com.

Part 3: Tool Use

Tool use is a remarkable and distinctive human trait. We create, modify, and use external objects to accomplish things beyond our physical and cognitive abilities. Equipping large language models (LLMs) with external tools can significantly extend their capabilities.

Figure 10: A sea otter using a rock to crack open a shell while floating in the water. Although some other animals can also use tools, the complexity of their tool use cannot compare to that of humans. (Image source: Animals That Use Tools)

MRKL (Karpas et al. 2022), short for “Modular Reasoning, Knowledge and Language,” is a neuro-symbolic architecture for autonomous AI agents. A proposed MRKL system consists of a collection of “expert” modules, with a general-purpose LLM acting as a router that directs queries to the most suitable expert module. These modules can be neural networks (such as deep learning models) or symbolic components (such as a calculator, currency converter, or weather API).

The researchers conducted an experiment using arithmetic as a test case, fine-tuning an LLM to call a calculator. The results showed that solving math word problems was more difficult than solving explicitly stated mathematical problems, because the LLM (the 7B Jurassic1-large model) could not reliably extract the correct arguments for basic arithmetic. These results highlight that even when external symbolic tools work reliably, knowing when and how to use them is crucial—and depends on the LLM’s capabilities.

TALM (Tool Augmented Language Models; Parisi et al., 2022) and Toolformer (Schick et al., 2023) both fine-tune language models to learn to use external tool APIs. They expand their datasets based on whether newly added API call annotations improve the quality of the model’s output. See the “External APIs” section of Prompt Engineering for more details.

ChatGPT plugins and OpenAI API function calling are good examples of LLM tool use in practice. The collection of tool APIs can be provided by other developers (as with plugins) or custom-defined (as with function calling).

HuggingGPT (Shen et al. 2023) is a framework that uses ChatGPT as a task planner, selects models available on the HuggingFace platform based on their descriptions, and summarizes the execution results into a response.

Figure 11. An illustration of how HuggingGPT works. (Image source: Shen et al. 2023)

The system consists of four stages:

(1) Task planning: The LLM acts as the brain, parsing a user request into multiple tasks. Each task has four attributes: task type, ID, dependencies, and arguments. Few-shot examples guide the LLM in task parsing and planning.

Instruction:

markdown
The AI assistant can parse user input to several tasks: [{"task": task, "id", task_id, "dep": dependency_task_ids, "args": {"text": text, "image": URL, "audio": URL, "video": URL}}]. The "dep" field denotes the id of the previous task which generates a new resource that the current task relies on. A special tag "-task_id" refers to the generated text image, audio and video in the dependency task with id as task_id. The task MUST be selected from the following options: {{ Available Task List }}. There is a logical relationship between tasks, please note their order. If the user input can't be parsed, you need to reply empty JSON. Here are several cases for your reference: {{ Demonstrations }}. The chat history is recorded as {{ Chat History }}. From this chat history, you can find the path of the user-mentioned resources for your task planning.

(2) Model Selection: The LLM assigns tasks to expert models, framing the request as a multiple-choice question. The LLM is given a list of models to choose from. Due to the limited context length, the list needs to be filtered by task type.

Instructions:

markdown
Given the user request and the call command, the AI assistant helps the user to select a suitable model from a list of models to process the user request. The AI assistant merely outputs the model id of the most appropriate model. The output must be in a strict JSON format: "id": "id", "reason": "your detail reason for the choice". We have a list of models for you to choose from {{ Candidate Models }}. Please select one model from the list.

(3) Task Execution: Expert models execute specific tasks and record the results.

Instructions:

markdown
With the input and the inference results, the AI assistant needs to describe the process and results. The previous stages can be formed as - User Input: {{ User Input }}, Task Planning: {{ Tasks }}, Model Selection: {{ Model Assignment }}, Task Execution: {{ Predictions }}. You must first answer the user's request in a straightforward manner. Then describe the task process and show your analysis and model inference results to the user in the first person. If inference results contain a file path, must tell the user the complete file path.

(4) Response Generation: The LLM receives the execution results and provides the user with a summary.

Several challenges still need to be addressed before HuggingGPT can be applied in the real world: (1) efficiency needs to improve, as repeated LLM inference rounds and interactions with other models slow down the process; (2) it relies on a long context window to handle complex tasks; and (3) the reliability of LLM outputs and external model services needs to improve.

API-Bank (Li et al. 2023) is a benchmark for evaluating the performance of tool-augmented LLMs. It includes 53 commonly used API tools, a complete workflow for tool-augmented LLMs, and 264 annotated conversations containing 568 API calls. The selected APIs cover a wide range of functions, including search engines, calculators, calendar queries, smart home control, schedule management, health data management, account authentication workflows, and more. Given the large number of APIs, the LLM first uses an API search engine to find the appropriate API, then calls it using the corresponding documentation.

Figure 12. Pseudocode showing how an LLM makes API calls in API-Bank. (Image source: Li et al. 2023)

In the API-Bank workflow, the LLM needs to make several decisions, and the accuracy of each decision can be evaluated at every step. These decisions include:

  1. Whether an API call is needed.

  2. Identifying the correct API to call: if the result is unsatisfactory, the LLM needs to iteratively refine the API inputs (for example, choosing search keywords for a search engine API).

  3. Based on feedback from the API results, whether to refine the inputs and make another call if the model is not satisfied with the results.

The benchmark evaluates AI agents' tool-use capabilities at three levels:

  • Level-1: Evaluates the ability to call APIs. Based on an API's description, the model needs to determine whether to call the given API, call it correctly, and respond appropriately to its output.

  • Level-2: Examines the ability to retrieve APIs. The model needs to search for APIs that could meet the user's needs and learn how to use them by reading the documentation.

  • Level-3: Evaluates the ability to plan API use beyond retrieval and invocation. Given an underspecified user request (such as scheduling a team meeting or booking flights, hotels, and restaurants for a trip), the model may need to make multiple API calls to solve the problem.

Case Studies

Scientific Discovery Agents

ChemCrow (Bran et al., 2023) is a domain-specific example in which a large language model (LLM) is augmented with 13 expert-designed tools to perform tasks such as organic synthesis, drug discovery, and materials design. The workflow, implemented in LangChain, mirrors the approaches previously described in ReAct and MRKL, combining chain-of-thought (CoT) reasoning with task-specific tools:

  • The LLM is provided with a list of tool names, descriptions of their functions, and details about their expected inputs and outputs.

  • The system then instructs it to use the provided tools as needed to answer the user's prompt. The instruction recommends following the ReAct format: Thought, Action, Action Input, Observation.

One interesting observation is that, although LLM-based evaluations concluded that GPT-4 and ChemCrow performed almost equally well, human evaluations by experts, focusing on solution completeness and chemical correctness, showed that ChemCrow substantially outperformed GPT-4. This suggests potential problems with using LLMs to evaluate their own performance in domains that require deep expertise. A lack of domain knowledge may prevent an LLM from recognizing its shortcomings, leaving it unable to reliably judge whether a task's outcome is correct.

Boiko et al. (2023) also investigated LLM-powered scientific discovery AI agents for the autonomous design, planning, and execution of complex scientific experiments. These AI agents can use tools to browse the internet, read documentation, execute code, call robotic experiment APIs, and leverage other LLMs.

For example, when asked to "develop a novel anticancer drug", the model proposed the following reasoning steps:

  1. Ask about current trends in anticancer drug discovery;

  2. Select a target;

  3. Request scaffolds for these compounds;

  4. Once the compounds have been identified, attempt to synthesize them.

The authors also discussed risks, particularly those involving illicit drugs and biological weapons. They developed a test set containing a range of known chemical warfare agents and asked the AI agent to synthesize them. Of the 11 requests, 4 (36%) were accepted for developing synthesis solutions, and the AI agent attempted to consult documentation to carry out the procedures. The remaining 7 requests were rejected: 5 after a web search and 2 based solely on the prompt.

Generative Agent Simulation

Generative Agents (Park et al., 2023) is a fascinating experiment in which 25 virtual characters, each controlled by an LLM-powered AI agent, live and interact in a sandbox environment inspired by The Sims. Generative agents create believable simulations of human behavior for interactive applications.

The design of generative agents combines LLMs with memory, planning, and reflection mechanisms, enabling agents to act based on past experiences and interact with other agents.

  • Memory stream: A long-term memory module (an external database) that records a comprehensive list of the AI agent's experiences in natural language.

    • Each entry is an observation—an event directly perceived by the agent. Communication between agents can generate new natural-language statements.
  • Retrieval model: Surfaces context to inform agents' behavior based on relevance, recency, and importance.

    • Recency: More recent events receive higher scores.
    • Importance: Distinguishes mundane memories from core memories. Ask the LM directly.
    • Relevance: Based on how closely a memory relates to the current situation or query.
  • Reflection mechanism: Synthesizes memories into higher-level inferences over time and guides the AI agent's future behavior. These are higher-level summaries of past events (<- Note that this is somewhat different from the self-reflection discussed above).

    • Prompt the LM with the 100 most recent observations and ask it to generate the three most important high-level questions based on these observations or statements. Then have the LM answer those questions.
  • Planning and reacting: Translates reflections and environmental information into actions.

    • Planning essentially aims to make behavior believable both in the moment and over time.
    • Prompt template: {Intro of an agent X}. Here is X's plan today in broad strokes: 1)
    • Both planning and reacting take into account relationships between agents and one agent's observations of another.
    • Environmental information is presented in a tree structure.

Figure 13. Generative agent architecture. (Image source: Park et al., 2023)

This fascinating simulation produces emergent social behaviors, such as information diffusion, relationship memory (for example, two agents continuing a discussion), and the coordination of social activities (for example, hosting a party and inviting many others).

Proof-of-Concept Example

AutoGPT sparked widespread interest in the possibility of building autonomous AI agents with a large language model (LLM) as their primary controller. Its natural-language interface introduces many reliability issues, but it is still a cool proof-of-concept demo. Much of the code in AutoGPT deals with parsing formats.

Here is the system message used by AutoGPT, where {{...}} represents user input:

markdown
You are {{ai-name}}, {{user-provided AI bot description}}.
Your decisions must always be made independently without seeking user assistance. Play to your strengths as an LLM and pursue simple strategies with no legal complications.

GOALS:

1. {{user-provided goal 1}}
2. {{user-provided goal 2}}
3. ...
4. ...
5. ...

Constraints:
1. ~4000 word limit for short term memory. Your short term memory is short, so immediately save important information to files.
2. If you are unsure how you previously did something or want to recall past events, thinking about similar events will help you remember.
3. No user assistance
4. Exclusively use the commands listed in double quotes e.g. "command name"
5. Use subprocesses for commands that will not terminate within a few minutes

Commands:
1. Google Search: "google", args: "input": "<search>"
2. Browse Website: "browse_website", args: "url": "<url>", "question": "<what_you_want_to_find_on_website>"
3. Start GPT Agent: "start_agent", args: "name": "<name>", "task": "<short_task_desc>", "prompt": "<prompt>"
4. Message GPT Agent: "message_agent", args: "key": "<key>", "message": "<message>"
5. List GPT Agents: "list_agents", args:
6. Delete GPT Agent: "delete_agent", args: "key": "<key>"
7. Clone Repository: "clone_repository", args: "repository_url": "<url>", "clone_path": "<directory>"
8. Write to file: "write_to_file", args: "file": "<file>", "text": "<text>"
9. Read file: "read_file", args: "file": "<file>"
10. Append to file: "append_to_file", args: "file": "<file>", "text": "<text>"
11. Delete file: "delete_file", args: "file": "<file>"
12. Search Files: "search_files", args: "directory": "<directory>"
13. Analyze Code: "analyze_code", args: "code": "<full_code_string>"
14. Get Improved Code: "improve_code", args: "suggestions": "<list_of_suggestions>", "code": "<full_code_string>"
15. Write Tests: "write_tests", args: "code": "<full_code_string>", "focus": "<list_of_focus_areas>"
16. Execute Python File: "execute_python_file", args: "file": "<file>"
17. Generate Image: "generate_image", args: "prompt": "<prompt>"
18. Send Tweet: "send_tweet", args: "text": "<text>"
19. Do Nothing: "do_nothing", args:
20. Task Complete (Shutdown): "task_complete", args: "reason": "<reason>"

Resources:
1. Internet access for searches and information gathering.
2. Long Term memory management.
3. GPT-3.5 powered Agents for delegation of simple tasks.
4. File output.

Performance Evaluation:
1. Continuously review and analyze your actions to ensure you are performing to the best of your abilities.
2. Constructively self-criticize your big-picture behavior constantly.
3. Reflect on past decisions and strategies to refine your approach.
4. Every command has a cost, so be smart and efficient. Aim to complete tasks in the least number of steps.

You should only respond in JSON format as described below
Response Format:
{
    "thoughts": {
        "text": "thought",
        "reasoning": "reasoning",
        "plan": "- short bulleted\n- list that conveys\n- long-term plan",
        "criticism": "constructive self-criticism",
        "speak": "thoughts summary to say to user"
    },
    "command": {
        "name": "command name",
        "args": {
            "arg name": "value"
        }
    }
}
Ensure the response can be parsed by Python json.loads

GPT-Engineer is another project that creates entire code repositories based on tasks specified in natural language. GPT-Engineer is instructed to think through a series of smaller components to build and ask the user for input to clarify issues as needed.

Below is an example conversation sent to the OpenAI ChatCompletion endpoint used by GPT-Engineer to describe a task. The user input is represented by {{user input text}}.

json
[
  {"role": "system",
    "content": "You will read instructions and not carry them out, only seek to clarify them.\nSpecifically you will first summarise a list of super short bullets of areas that need clarification.\nThen you will pick one clarifying question, and wait for an answer from the user.\n"
  },
  {"role": "user",
    "content": "We are writing {{a Super Mario game in python. MVC components split in separate files. Keyboard control.}}\n"
  },
  {"role": "assistant",
    "content": "Summary of areas that need clarification:\n1. Specifics of the Super Mario game (e.g. level design, characters, gameplay mechanics)\n2. Details about the MVC components (e.g. which components are in each file)\n3. Keyboard control implementation (e.g. which keys to use, how to handle input)\n\nClarifying question:\nCan you provide more details about the Super Mario game, such as level design, characters, and gameplay mechanics?"
  },
  {"role": "user",
    "content": "{{There are 10 levels in total. The main character is a plumber named Mario, who can walk and jump. It is a classical platform game just like Super Mario. The main character moves from left to right, trying to get to the destination, where there are many obstacles and attacks from enemies in the process.}}\n\nIs anything else unclear? If yes, only answer in the form:\n{remaining unclear areas} remaining questions.\n{Next question}\nIf everything is sufficiently clear, only answer \"Nothing more to clarify.\"."
  },
  {"role": "assistant",
    "content": "Remaining unclear areas: 2 remaining questions.\nCan you provide more information about how the MVC components are split into separate files?"
  },
  {"role": "user",
    "content": "{{Make your own assumptions and state them explicitly before starting}}"
  }
]

Then, after these clarifications, the AI agents enter coding mode and display different system messages. System message:

You will get instructions for code to write. You will write a very long answer. Make sure that every detail of the architecture is, in the end, implemented as code. Make sure that every detail of the architecture is, in the end, implemented as code.

Think step by step and reason yourself to the right decisions to make sure we get it right. You will first lay out the names of the core classes, functions, methods that will be necessary, as well as a quick comment on their purpose.

Then you will output the content of each file including ALL code. Each file must strictly follow a markdown code block format, where the following tokens must be replaced such that FILENAME is the lowercase file name including the file extension, LANG is the markup code block language for the code’s language, and CODE is the code:

FILENAME

Code

You will start with the “entrypoint” file, then go to the ones that are imported by that file, and so on. Please note that the code should be fully functional. No placeholders.

Follow a language and framework appropriate best practice file naming convention. Make sure that files contain all imports, types etc. Make sure that code in different files are compatible with each other. Ensure to implement all code, if you are unsure, write a plausible implementation. Include module dependency or package manager dependency definition file. Before you finish, double check that all parts of the architecture is present in the files.

Useful to know: You almost always put different classes in different files. For Python, you always create an appropriate requirements.txt file. For NodeJS, you always create an appropriate package.json file. You always add a comment briefly describing the purpose of the function definition. You try to add comments explaining very complex bits of logic. You always follow the best practices for the requested languages in terms of describing the code written as a defined package/project.

Python toolbelt preferences:
- pytest
- dataclasses

Sample conversation:

json
[
  {"role": "system",
    "content": "You will get instructions for code to write.\nYou will write a very long answer. Make sure that every detail of the architecture is, in the end, implemented as code.\nMake sure that every detail of the architecture is, in the end, implemented as code.\n\nThink step by step and reason yourself to the right decisions to make sure we get it right.\nYou will first lay out the names of the core classes, functions, methods that will be necessary, as well as a quick comment on their purpose.\n\nThen you will output the content of each file including ALL code.\nEach file must strictly follow a markdown code block format, where the following tokens must be replaced such that\nFILENAME is the lowercase file name including the file extension,\nLANG is the markup code block language for the code's language, and CODE is the code:\n\nFILENAME\n'''LANG\nCODE\n'''\n\nYou will start with the \"entrypoint\" file, then go to the ones that are imported by that file, and so on.\nPlease note that the code should be fully functional. No placeholders.\n\nFollow a language and framework appropriate best practice file naming convention.\nMake sure that files contain all imports, types etc. Make sure that code in different files are compatible with each other.\nEnsure to implement all code, if you are unsure, write a plausible implementation.\nInclude module dependency or package manager dependency definition file.\nBefore you finish, double check that all parts of the architecture is present in the files.\n\nUseful to know:\nYou almost always put different classes in different files.\nFor Python, you always create an appropriate requirements.txt file.\nFor NodeJS, you always create an appropriate package.json file.\nYou always add a comment briefly describing the purpose of the function definition.\nYou try to add comments explaining very complex bits of logic.\nYou always follow the best practices for the requested languages in terms of describing the code written as a defined\npackage/project.\n\n\nPython toolbelt preferences:\n- pytest\n- dataclasses\n"
  },
 #  … same conversation as earlier, ended with "Make your own assumptions and state them explicitly before starting".
  {"role": "assistant",
    "content": "Assumptions:\n1. Model: The model will contain the game's data, such as level information, character states, and enemy positions.\n2. View: The view will handle the game's visuals, including rendering the game objects, backgrounds, and updating the display.\n3. Controller: The controller will manage user input, such as keyboard controls, and update the model accordingly.\n\nWith these assumptions in mind, is there any specific aspect of the keyboard control implementation you would like me to clarify?"
  },
  {"role": "user",
    "content": "Please now remember the steps:\n\nThink step by step and reason yourself to the right decisions to make sure we get it right.\nFirst lay out the names of the core classes, functions, methods that will be necessary, As well as a quick comment on their purpose.\n\nThen you will output the content of each file including ALL code.\nEach file must strictly follow a markdown code block format, where the following tokens must be replaced such that\nFILENAME is the lowercase file name including the file extension,\nLANG is the markup code block language for the code's language, and CODE is the code:\n\nFILENAME\n'''LANG\nCODE\n'''\n\nPlease note that the code should be fully functional. No placeholders.\n\nYou will start with the \"entrypoint\" file, then go to the ones that are imported by that file, and so on.\nFollow a language and framework appropriate best practice file naming convention.\nMake sure that files contain all imports, types etc. The code should be fully functional. Make sure that code in different files are compatible with each other.\nBefore you finish, double check that all parts of the architecture is present in the files.\n"
  }
]

Challenges

After exploring the key ideas and demos for building LLM-centered AI agents, I began to notice some common limitations:

  • Limited context length: Limited context capacity restricts how much historical information, detailed instructions, API call context, and response content can be included. Systems must be designed to operate within this limited communication bandwidth, while mechanisms such as self-reflection could benefit greatly from long or unlimited context windows. Although vector storage and retrieval can provide access to larger knowledge bases, their representational capabilities are less powerful than full attention.

  • Challenges in long-term planning and task decomposition: Long-term planning and effective exploration of the solution space remain challenging. LLMs struggle to adjust their plans when unexpected errors arise, making them less robust than humans who learn through trial and error.

  • Reliability of natural language interfaces: Current AI agent systems rely on natural language as the interface between LLMs and external components such as memory and tools. However, the reliability of model outputs is questionable: LLMs can produce formatting errors and occasionally exhibit defiant behavior, such as refusing to follow instructions. As a result, much of the code in AI agent demos focuses on parsing model outputs.

References

[1] Wei et al. “Chain of thought prompting elicits reasoning in large language models." NeurIPS 2022

[2] Yao et al. “Tree of Thoughts: Dliberate Problem Solving with Large Language Models." arXiv preprint arXiv:2305.10601 (2023).

[3] Liu et al. “Chain of Hindsight Aligns Language Models with Feedback “ arXiv preprint arXiv:2302.02676 (2023).

[4] Liu et al. “LLM+P: Empowering Large Language Models with Optimal Planning Proficiency” arXiv preprint arXiv:2304.11477 (2023).

[5] Yao et al. “ReAct: Synergizing reasoning and acting in language models." ICLR 2023.

[6] Google Blog. “Announcing ScaNN: Efficient Vector Similarity Search” July 28, 2020.

[7] https://chat.openai.com/share/46ff149e-a4c7-4dd7-a800-fc4a642ea389

[8] Shinn & Labash. “Reflexion: an autonomous agent with dynamic memory and self-reflection” arXiv preprint arXiv:2303.11366 (2023).

[9] Laskin et al. “In-context Reinforcement Learning with Algorithm Distillation” ICLR 2023.

[10] Karpas et al. “MRKL Systems A modular, neuro-symbolic architecture that combines large language models, external knowledge sources and discrete reasoning." arXiv preprint arXiv:2205.00445 (2022).

[11] Weaviate Blog. Why is Vector Search so fast? Sep 13, 2022.

[12] Li et al. “API-Bank: A Benchmark for Tool-Augmented LLMs” arXiv preprint arXiv:2304.08244 (2023).

[13] Shen et al. “HuggingGPT: Solving AI Tasks with ChatGPT and its Friends in HuggingFace” arXiv preprint arXiv:2303.17580 (2023).

[14] Bran et al. “ChemCrow: Augmenting large-language models with chemistry tools." arXiv preprint arXiv:2304.05376 (2023).

[15] Boiko et al. “Emergent autonomous scientific research capabilities of large language models." arXiv preprint arXiv:2304.05332 (2023).

[16] Joon Sung Park, et al. “Generative Agents: Interactive Simulacra of Human Behavior." arXiv preprint arXiv:2304.03442 (2023).

[17] AutoGPT. https://github.com/Significant-Gravitas/Auto-GPT

[18] GPT-Engineer. https://github.com/AntonOsika/gpt-engineer