October 15, 2023

LLM. ReAct: Synergizing reasining and acting in language models

🤖 ReAct: Synergizing reasining and acting in language models

🤘 one-liner: LLM можно использовать не только для создания цепочки рассуждений, но и для определения последовательности действий. Эти действия позволяют ей взаимодействовать с внешним миром и собирать дополнительную информацию из разных сторонних источников 📚🔍

Figure 1: (1) Comparison of 4 prompting methods, (a) Standard, (b) Chain-of-thought (CoT, Reason Only), (c) Act-only, and (d) ReAct (Reason+Act), solving a HotpotQA (Yang et al., 2018) question. (2) Comparison of (a) Act-only and (b) ReAct prompting to solve an AlfWorld (Shridhar et al., 2020b) game. In both domains, we omit in-context examples in the prompt, and only show task solving trajectories generated by the model (Act, Thought) and the environment (Obs).

♿️ Ограничения Chain-of-Thought CoT можно сравнить с черным ящиком, так как модель основывается на своих внутренних данных для создания рассуждений и не принимает в расчет информацию из вне. Это делает такой подход менее гибким и приводит к таким проблемам как галюцинации и накоплении ошибки в процессе рассуждений.

💡 Идея ReAct - парадигма, который объединяет `reasoning` и `action` с помощью языковой модели для решения различных задач. ReAct заставляет LLM, одновременно создавать рассуждения и действия для выполнения задачи, таким образом помогает модели динамически размышлять, планировать и корректировать свои действия. Важным фактом ReAct парадигмы является тот факт, что модель может взаимодействовать с внешними источниками

💫 Положительные стороны ReAct:

1️⃣ Интуитивность и простота создания: для ReAct промпта достаточно описать мысли, соответствующие действиям.
2️⃣ Универсальность и гибкость: ReAct подходит для множества задач, требующих разных действий и анализа.
3️⃣ Эффективность и надежность: ReAct хорошо обобщает информацию на новые примеры задач, обучаясь лишь на 1-6 in-context примерах.
4️⃣ Прозрачность и контролируемость: ReAct делает процесс принятия решений понятным и позволяет легко проверять правильность рассуждений. К тому же, вы можете настроить или исправить действия модели в реальном времени, редактируя её рассуждения.

⚔️ In-context learning VS Finetuning

Figure 3: Scaling results for prompting and finetuning on HotPotQA with ReAct (ours) and baselines.

Сравниваются два подхода: prompt и finetune для четырех методов: Standard, CoT, Act, ReAct на датасете HotpotQA. С использованием PaLM-8/62B метод ReAct показывает худший результат среди четырех методов из-за сложности одновременного обучения рассуждениям и действиям, опираясь на in-context примеры
Однако, после дообучения на всего 3000 примерах, ReAct становится лучшим методом среди четырех. При этом PaLM-8B с дообученным ReAct превосходит все prompt методы PaLM-62B, а PaLM-62B с дообученным ReAct превосходит все prompt методы 540B

🥇 Суперпромпт
Промпт позволяющий агенту выбирать между ReAct и CoT+Self-Consistency показывает лучшие результаты на датасетах HotpotQA и Fever

👨‍💻 Code

Сделаем простую среду, к которой будет обращаться агент

import gymnasium

from langchain import Wikipedia
from langchain.agents.react.base import DocstoreExplorer

from environment.utils import (
    parse_action,
    compare_answer
)

class QuestionAnsweringEnvironment(gymnasium.Env):
    def __init__(
        self,
        question: str,
        key: str,
        max_steps: int = 6,
        explorer: DocstoreExplorer = None
    ):

        self.question = question
        self.key = key
        self.max_steps = max_steps
        self.explorer = explorer
        if self.explorer is None:
            self.explorer = DocstoreExplorer(Wikipedia())

        self.reset()

    def reset(self):
        self.curr_step = 0
        self.terminated = False
        self.answer = ""

    def step(self, action: str) -> Tuple[str, bool, bool, bool, bool]:
        action_type, argument = parse_action(action)

        if action_type == "Finish":
            self.answer = argument
            if self.is_correct():
                observation = "Answer is CORRECT"
            else:
                observation = "Answer is INCORRECT"
            self.terminated = True
        elif action_type == "Search":
            try:
                observation = self.explorer.search(argument).strip("\n").strip()
            except Exception as e:
                print(e)
                observation = "Could not find that page, please try again."
        elif action_type == "Lookup":
            try:
                observation = self.explorer.lookup(argument).strip("\n").strip()
            except ValueError:
                observation = "The last page Searched was not found, so you cannot Lookup a keyword in it. Please try one of the similar pages given."

        else:
            observation = "Invalid Action. Valid Actions are Lookup[<topic>] Search[<topic>] and Finish[<answer>]."

        reward = self.is_correct()
        terminated = self.is_terminated()
        truncated = self.is_truncated()

        self.curr_step += 1

        return observation, reward, terminated, truncated, self.curr_step

    def is_correct(self) -> bool:
        return compare_answer(self.answer, self.key)

    def is_terminated(self) -> bool:
        return self.terminated

    def is_truncated(self) -> bool:
        return self.curr_step >= self.max_steps

Дополнительные функции для парсинга текстового запроса из environment.utils

import string
import re


def parse_action(s: str):
    pattern = r"^(\w+)\[(.+)\]quot;
    match = re.match(pattern, s)

    if match:
        action_type = match.group(1)
        argument = match.group(2)
        return action_type, argument

    else:
        return None, None


def normalize_answer(s: str):
    def remove_articles(text):
        return re.sub(r"\b(a|an|the)\b", " ", text)

    def white_space_fix(text):
        return " ".join(text.split())

    def remove_punc(text):
        exclude = set(string.punctuation)
        return "".join(ch for ch in text if ch not in exclude)

    def lower(text):
        return text.lower()

    return white_space_fix(remove_articles(remove_punc(lower(s))))


def compare_answer(answer: str, key: str) -> bool:
    return normalize_answer(answer) == normalize_answer(key)

Теперь напишем агента который будет принимать QuestionAnsweringEnvironment

import os
import tiktoken
import gymnasium

from typing import Optional
from langchain import OpenAI
from langchain.prompts import PromptTemplate


def format_step(step: str) -> str:
    return step.strip('\n').strip().replace('\n', '')

class ReactAgent:
    def __init__(
        self,
        env: gymnasium.Env,
        react_instraction_template: str,
        react_example: str,
        react_llm: Optional[OpenAI] = None
    ) -> None:
        self.question = env.question
        self.agent_prompt = PromptTemplate(
            input_variables=["examples", "question", "scratchpad"],
            template=react_instraction_template,
        )
        self.react_examples = react_example

        self.env = env
        self.env.reset()
        self.reset()
        self.truncated, self.reward, self.terminated = False, False, False

        self.llm = react_llm
        if self.llm is None:
            self.llm = OpenAI(
                temperature=0,
                max_tokens=100,
                model_name="text-davinci-003",
                model_kwargs={"stop": "\n"},
                openai_api_key=os.environ["OPENAI_API_KEY"]
            )

        self.enc = tiktoken.encoding_for_model("text-davinci-003")

    def run(self, reset: bool = True) -> None:
        if reset:
            self.env.reset()
            self.reset()

        while not (self.is_truncated() or self.is_terminated()):
            self.step()

        return self.env.answer

    def step(self) -> None:
        # Think
        self.scratchpad += f"\nThought {self.curr_step}:"
        self.scratchpad += " " + self.prompt_agent()
        print(self.scratchpad.split("\n")[-1])

        # Act
        self.scratchpad += f"\nAction {self.curr_step}:"
        action = self.prompt_agent()
        self.scratchpad += " " + action
        print(self.scratchpad.split("\n")[-1])

        # Observe
        self.scratchpad += f"\nObservation {self.curr_step}: "
        observation, self.reward, self.terminated, self.truncated, self.curr_step = self.env.step(action)
        self.scratchpad += observation
        print(self.scratchpad.split("\n")[-1])

    def prompt_agent(self) -> str:
        return format_step(self.llm(self._build_agent_prompt()))

    def _build_agent_prompt(self) -> str:
        return self.agent_prompt.format(
            examples=self.react_examples,
            question=self.question,
            scratchpad=self.scratchpad
        )

    def is_terminated(self) -> bool:
        return self.env.is_terminated()

    def is_correct(self) -> bool:
        return self.env.is_correct()

    def is_truncated(self) -> bool:
        return (
            self.env.is_truncated() or
            len(self.enc.encode(self._build_agent_prompt())) > 3896
        )

    def reset(self) -> None:
        self.scratchpad = ""
        self.curr_step = 1

В качестве in-context примеров будет использовать следующий набор

Question: What is the elevation range for the area that the eastern sector of the Colorado orogeny extends into?
Thought 1: I need to search Colorado orogeny, find the area that the eastern sector of the Colorado orogeny extends into, then find the elevation range of the area.
Action 1: Search[Colorado orogeny]
Observation 1: The Colorado orogeny was an episode of mountain building (an orogeny) in Colorado and surrounding areas.
Thought 2: It does not mention the eastern sector. So I need to look up eastern sector.
Action 2: Lookup[eastern sector]
Observation 2: (Result 1 / 1) The eastern sector extends into the High Plains and is called the Central Plains orogeny.
Thought 3: The eastern sector of Colorado orogeny extends into the High Plains. So I need to search High Plains and find its elevation range.
Action 3: Search[High Plains]
Observation 3: High Plains refers to one of two distinct land regions:
Thought 4: I need to instead search High Plains (United States).
Action 4: Search[High Plains (United States)]
Observation 4: The High Plains are a subregion of the Great Plains. From east to west, the High Plains rise in elevation from around 1,800 to 7,000 ft (550 to 2,130 m).[3]
Thought 5: High Plains rise in elevation from around 1,800 to 7,000 ft, so the answer is 1,800 to 7,000 ft.
Action 5: Finish[1,800 to 7,000 ft]

Question: Musician and satirist Allie Goertz wrote a song about the "The Simpsons" character Milhouse, who Matt Groening named after who?
Thought 1: The question simplifies to "The Simpsons" character Milhouse is named after who. I only need to search Milhouse and find who it is named after.
Action 1: Search[Milhouse]
Observation 1: Milhouse Mussolini Van Houten is a recurring character in the Fox animated television series The Simpsons voiced by Pamela Hayden and created by Matt Groening.
Thought 2: The paragraph does not tell who Milhouse is named after, maybe I can look up "named after".
Action 2: Lookup[named after]
Observation 2: (Result 1 / 1) Milhouse was named after U.S. president Richard Nixon, whose middle name was Milhous.
Thought 3: Milhouse was named after U.S. president Richard Nixon, so the answer is Richard Nixon.
Action 3: Finish[Richard Nixon]

Question: Which documentary is about Finnish rock groups, Adam Clayton Powell or The Saimaa Gesture?
Thought 1: I need to search Adam Clayton Powell and The Saimaa Gesture, and find which documentary is about Finnish rock groups.
Action 1: Search[Adam Clayton Powell]
Observation 1: Could not find [Adam Clayton Powell]. Similar: ['Adam Clayton Powell III', 'Seventh Avenue (Manhattan)', 'Adam Clayton Powell Jr. State Office Building', 'Isabel Washington Powell', 'Adam Powell', 'Adam Clayton Powell (film)', 'Giancarlo Esposito'].
Thought 2: To find the documentary, I can search Adam Clayton Powell (film).
Action 2: Search[Adam Clayton Powell (film)]
Observation 2: Adam Clayton Powell is a 1989 American documentary film directed by Richard Kilberg.
The film is about the rise and fall of influential African-American politician Adam Clayton Powell Jr.[3][4] It was later aired as part of the PBS series The American Experience.
Thought 3: Adam Clayton Powell (film) is a documentary about an African-American politician, not Finnish rock groups. So the documentary about Finnish rock groups must instead be The Saimaa Gesture.
Action 3: Finish[The Saimaa Gesture]

Question: What profession does Nicholas Ray and Elia Kazan have in common?
Thought 1: I need to search Nicholas Ray and Elia Kazan, find their professions, then find the profession they have in common.
Action 1: Search[Nicholas Ray]
Observation 1: Nicholas Ray (born Raymond Nicholas Kienzle Jr., August 7, 1911 – June 16, 1979) was an American film director, screenwriter, and actor best known for the 1955 film Rebel Without a Cause.
Thought 2: Professions of Nicholas Ray are director, screenwriter, and actor. I need to search Elia Kazan next and find his professions.
Action 2: Search[Elia Kazan]
Observation 2: Elia Kazan was an American film and theatre director, producer, screenwriter and actor.
Thought 3: Professions of Elia Kazan are director, producer, screenwriter, and actor. So profession Nicholas Ray and Elia Kazan have in common is director, screenwriter, and actor.
Action 3: Finish[director, screenwriter, actor]

Question: Which magazine was started first Arthur's Magazine or First for Women?
Thought 1: I need to search Arthur's Magazine and First for Women, and find which was started first.
Action 1: Search[Arthur's Magazine]
Observation 1: Arthur's Magazine (1844-€“1846) was an American literary periodical published in Philadelphia in the 19th century.
Thought 2: Arthur's Magazine was started in 1844. I need to search First for Women next.
Action 2: Search[First for Women]
Observation 2: First for Women is a woman's magazine published by Bauer Media Group in the USA.[1] The magazine was started in 1989.
Thought 3: First for Women was started in 1989. 1844 (Arthur's Magazine) < 1989 (First for Women), so Arthur's Magazine was started first.
Action 3: Finish[Arthur's Magazine]

Question: Were Pavel Urysohn and Leonid Levin known for the same type of work?
Thought 1: I need to search Pavel Urysohn and Leonid Levin, find their types of work, then find if they are the same.
Action 1: Search[Pavel Urysohn]
Observation 1: Pavel Samuilovich Urysohn (February 3, 1898 – August 17, 1924) was a Soviet mathematician who is best known for his contributions in dimension theory.
Thought 2: Pavel Urysohn is a mathematician. I need to search Leonid Levin next and find its type of work.
Action 2: Search[Leonid Levin]
Observation 2: Leonid Anatolievich Levin is a Soviet-American mathematician and computer scientist. 
Thought 3: Leonid Levin is a mathematician and computer scientist. So Pavel Urysohn and Leonid Levin have the same type of work.
Action 3: Finish[yes]

Промпт который будет объединять все для ReAct

Solve a question answering task with interleaving Thought, Action, Observation steps. Thought can reason about the current situation, and Action can be three types: 
(1) Search[entity], which searches the exact entity on Wikipedia and returns the first paragraph if it exists. If not, it will return some similar entities to search.
(2) Lookup[keyword], which returns the next sentence containing keyword in the last passage successfully found by Search.
(3) Finish[answer], which returns the answer and finishes the task.
You may take as many steps as necessary.
Here are some examples:
{examples}
(END OF EXAMPLES)
Question: {question}
{scratchpad}

Итоговый скрипт

question = "What is the elevation range for the area that the eastern sector of the Colorado orogeny extends into?"
answer = "1,800 to 7,000 ft"

env = QAEnv(question, answer)
agent = ReactAgent(
    env,
    react_inst_template,
    react_example
)
prediction = agent.run()
assert prediction == answer