{"id":8480,"date":"2023-12-16T17:29:57","date_gmt":"2023-12-17T01:29:57","guid":{"rendered":"https:\/\/live-cometml.pantheonsite.io\/?p=8480"},"modified":"2025-04-24T17:03:50","modified_gmt":"2025-04-24T17:03:50","slug":"using-the-react-framework-in-langchain","status":"publish","type":"post","link":"https:\/\/www.comet.com\/site\/blog\/using-the-react-framework-in-langchain\/","title":{"rendered":"Using the ReAct Framework in LangChain"},"content":{"rendered":"\n<h2 class=\"wp-block-heading graf graf--h4\">Both ways: Using off-the-shelf agents and&nbsp;LCEL<\/h2>\n\n\n\n<figure class=\"graf graf--figure\">\n<\/figure>\n\n\n\n<figure class=\"wp-block-image aligncenter graf-image\"><img decoding=\"async\" src=\"https:\/\/cdn-images-1.medium.com\/max\/1600\/0*1vLAWRJypHWHt44b\" alt=\"React prompting technique\"\/><figcaption class=\"wp-element-caption\">Photo by <a href=\"https:\/\/unsplash.com\/@rocinante_11?utm_source=medium&amp;utm_medium=referral\">Mick Haupt <\/a>on\u00a0<a href=\"http:\/\/unsplash.com\">Unsplash<\/a><\/figcaption><\/figure>\n\n\n\n<h3 class=\"wp-block-heading graf graf--h3\">ReAct Framework for Prompting<\/h3>\n\n\n\n<p class=\"graf graf--p\"><a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/colab.research.google.com\/corgiredirector?site=https%3A%2F%2Farxiv.org%2Fabs%2F2210.03629\" target=\"_blank\" rel=\"nofollow noopener\" data-href=\"https:\/\/colab.research.google.com\/corgiredirector?site=https%3A%2F%2Farxiv.org%2Fabs%2F2210.03629\">ReAct<\/a>, which stands for Reasoning + Acting, is a prompting technique developed by professors from Princeton University in collaboration with Google researchers.<\/p>\n\n\n\n<p class=\"graf graf--p\">The method is designed to enhance the reasoning capabilities of LLMs, allowing them to reason and act intelligently within simulated environments.<\/p>\n\n\n\n<p class=\"graf graf--p\">ReAct aims to enable LLMs to mimic human-like operations in the real world, where we reason verbally and take actions to gain information. This advancement holds significant potential for reshaping how we interact with language models.<\/p>\n\n\n\n<p class=\"graf graf--p\">The ReAct framework is flexible and designed to synergize the reasoning abilities of LLMs with actionable outputs.<\/p>\n\n\n\n<p class=\"graf graf--p\">It allows LLMs to interact with external tools, enhancing their decision-making processes. With React, LLMs can understand and generate text, make informed decisions and take actions based on their understanding.<\/p>\n\n\n\n<h4 class=\"wp-block-heading graf graf--h4\">How Does It&nbsp;Work?<\/h4>\n\n\n\n<p class=\"graf graf--p\">ReAct combines reasoning and acting to solve complex language reasoning and decision-making tasks.<\/p>\n\n\n\n<p class=\"graf graf--p\">While <a class=\"markup--anchor markup--p-anchor\" href=\"https:\/\/colab.research.google.com\/corgiredirector?site=https%3A%2F%2Farxiv.org%2Fabs%2F2201.11903\" target=\"_blank\" rel=\"nofollow noopener\" data-href=\"https:\/\/colab.research.google.com\/corgiredirector?site=https%3A%2F%2Farxiv.org%2Fabs%2F2201.11903\">Chain-of-thought<\/a> (CoT) prompting has shown that LLMs can generate reasoning traces for tasks like arithmetic and commonsense reasoning, its lack of access to the external world can lead to issues like fact hallucination. ReAct addresses this by allowing LLMs to generate verbal reasoning traces and actions for a task.<\/p>\n\n\n\n<p class=\"graf graf--p\">Language models can generate responses based on their input, but ReAct enhances this by allowing the model to interact with its environment.<\/p>\n\n\n\n<p class=\"graf graf--p\">This interaction is achieved through text actions that the model can use to ask questions or perform tasks to gain more information and better understand a situation. For instance, when faced with a multi-hop reasoning question, ReAct might initiate multiple search actions, each potentially being a call to an external tool.<\/p>\n\n\n\n<p class=\"graf graf--p\">The results of these actions are then used to generate a final answer.<\/p>\n\n\n\n<p class=\"graf graf--p\">A ReAct prompt might include examples of actions, the observations resulting from those actions, and the transcribed thoughts of a human during the process.<\/p>\n\n\n\n<p class=\"graf graf--p\">By prompting the LLM to alternate between thinking and acting, ReAct transforms it into an active agent in its environment, capable of solving tasks in a human-aligned manner.<\/p>\n\n\n\n<h4 class=\"wp-block-heading graf graf--h4\">When Should This Be&nbsp;Used?<\/h4>\n\n\n\n<p class=\"graf graf--p\">ReAct is ideal when a language model needs to interact with its environment to gather more information or when a task requires multiple reasoning steps.<\/p>\n\n\n\n<p class=\"graf graf--p\">It excels in knowledge-intensive reasoning tasks like multi-hop question answering using Wikipedia passages or fact verification. Additionally, ReAct is beneficial in decision-making tasks where the model navigates simulated environments, such as online shopping websites or text-based games.<\/p>\n\n\n\n<p class=\"graf graf--p\">One of the significant advantages of ReAct is its ability to integrate LLMs with external tools for real-world applications. For instance, Microsoft has integrated OpenAI LLMs with their Office applications in Microsoft 365 Copilot, showcasing its utility.<\/p>\n\n\n\n<p class=\"graf graf--p\">In scenarios like QA systems, where LLMs might not always provide correct answers, the interaction with an external search engine becomes crucial, and ReAct proves invaluable.<\/p>\n\n\n\n<h4 class=\"wp-block-heading graf graf--h4\">How Is It Different from Other Prompting Methods?<\/h4>\n\n\n\n<p class=\"graf graf--p\">Traditional prompting methods predominantly rely on the LLM\u2019s internal knowledge.<\/p>\n\n\n\n<section class=\"section section--body\">\n<div class=\"section-divider\"><\/div>\n<div class=\"section-content\">\n<div class=\"section-inner sectionLayout--insetColumn\">\n<p class=\"graf graf--p\">In contrast, ReAct emphasizes collaboration between the LLM and external tools, ensuring more accurate, context-aware responses. This dynamic approach sets ReAct apart, offering users a more interactive and enriched experience.<\/p>\n<\/div>\n<\/div>\n<\/section>\n\n\n\n<section class=\"section section--body\">\n<div class=\"section-divider\">\n<hr class=\"section-divider\">\n<\/div>\n<div class=\"section-content\">\n<div class=\"section-inner sectionLayout--insetColumn\">\n<blockquote class=\"graf graf--pullquote\"><p>Want to learn how to build modern software with LLMs using the newest tools and techniques in the field? <a class=\"markup--anchor markup--pullquote-anchor\" href=\"https:\/\/www.comet.com\/production\/site\/llm-course\/?utm_source=Heartbeat&amp;utm_medium=referral&amp;utm_content=Medium&amp;utm_campaign=Heartbeat_LangChain_Series_HS\" target=\"_blank\" rel=\"noopener ugc nofollow\" data-href=\"https:\/\/www.comet.com\/production\/site\/llm-course\/?utm_source=Heartbeat&amp;utm_medium=referral&amp;utm_content=Medium&amp;utm_campaign=Heartbeat_LangChain_Series_HS\">Check out this free LLMOps course<\/a> from industry expert Elvis Saravia of&nbsp;DAIR.AI!<\/p><\/blockquote>\n<\/div>\n<\/div>\n<\/section>\n\n\n\n<section class=\"section section--body\">\n<div class=\"section-divider\">\n<hr class=\"section-divider\">\n<\/div>\n<div class=\"section-content\">\n<div class=\"section-inner sectionLayout--insetColumn\">\n<h4 class=\"graf graf--h4\">What Are Its Limitations?<\/h4>\n<\/div>\n<\/div>\n<\/section>\n\n\n\n<p class=\"graf graf--p\">ReAct\u2019s strength is also its potential weakness.<\/p>\n\n\n\n<p class=\"graf graf--p\">Its dynamic approach to prompting heavily relies on integrating external tools. This means that the effectiveness of ReAct is partly dependent on the capabilities and reliability of these external tools.<\/p>\n\n\n\n<p class=\"graf graf--p\">As with any system that relies on external data, there\u2019s always a risk of introducing biases or inaccuracies from those sources.<\/p>\n\n\n\n<h4 class=\"wp-block-heading graf graf--h4\">Preliminaries<\/h4>\n\n\n\n<p class=\"graf graf--p\">Let\u2019s get this out of the way\u2026<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><span class=\"pre--content\">%%capture\n!pip install langchain openai duckduckgo-search youtube_search wikipedia langchainhub\n\nimport os\nimport getpass\n\nos.environ[\"OPENAI_API_KEY\"] = getpass.getpass(\"Enter Your OpenAI API Key:\")\n\nfrom langchain.agents import load_tools\nfrom langchain.agents import initialize_agent\nfrom langchain.agents import AgentType\nfrom langchain.chat_models import ChatOpenAI\n\nfrom langchain import hub\nfrom langchain.agents.format_scratchpad import format_log_to_str\nfrom langchain.agents.output_parsers import ReActSingleInputOutputParser\nfrom langchain.tools.render import render_text_description<\/span><\/pre>\n\n\n\n<h4 class=\"wp-block-heading graf graf--h4\">ReAct Agents in LangChain<\/h4>\n\n\n\n<p class=\"graf graf--p\">The ReAct agent in LangChain is a versatile agent that utilizes the ReAct framework to select the appropriate tool based on its description.<\/p>\n\n\n\n<p class=\"graf graf--p\">This agent is the most general-purpose action agent available in LangChain and can be highly beneficial in situations where multiple tools are available, and selecting the right tool is time-consuming. The ReAct agent allows you to specify a description for each tool and then automatically selects the appropriate tool based on the description.<\/p>\n\n\n\n<p class=\"graf graf--p\">This feature simplifies determining which tool to use in a given situation.<\/p>\n\n\n\n<h4 class=\"wp-block-heading graf graf--h4\">How it&nbsp;works:<\/h4>\n\n\n\n<ol class=\"wp-block-list postList\">\n<li>The system receives input from the user.<\/li>\n\n\n\n<li>Based on the input, the agent decides whether to use a tool and, if so, what the input to that tool should be.<\/li>\n\n\n\n<li>The tool is then called with the appropriate input, and the output of the tool is recorded as an observation.<\/li>\n\n\n\n<li>The history of the tool, tool input, and observation is passed back into the agent, which decides the next step.<\/li>\n\n\n\n<li>The above steps are repeated until the agent determines that no further tools are needed. At this point, it will respond directly to the user.<\/li>\n<\/ol>\n\n\n\n<pre class=\"wp-block-preformatted\"><span class=\"pre--content\">#  load the language model we're using to control the agent\nllm = ChatOpenAI(model = \"gpt-4-1106-preview\",temperature=0)\n\n# load some tools\ntools = load_tools(['wikipedia', 'ddg-search','llm-math'], llm=llm)\n\n# initialize agent with the tools, language model, and the type of agent\nagent = initialize_agent(tools,\n                         llm,\n                         agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,\n                         verbose=True\n                         )<\/span><\/pre>\n\n\n\n<p class=\"graf graf--p\">You can inspect the prompt that the ReAct agent uses. It\u2019s pretty much as described in the paper, but with no examples. That\u2019s why it\u2019s called <code class=\"markup--code markup--p-code\">ZERO_SHOT_REACT_DESCRIPTION<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><span class=\"pre--content\">print(agent.agent.llm_chain.prompt.template)<\/span><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><span class=\"pre--content\">Answer the following questions as best you can. You have access to the following tools:\n\nWikipedia: A wrapper around Wikipedia. Useful for when you need to answer general questions about people, places, companies, facts, historical events, or other subjects. Input should be a search query.\nduckduckgo_search: A wrapper around DuckDuckGo Search. Useful for when you need to answer questions about current events. Input should be a search query.\nCalculator: Useful for when you need to answer questions about math.\n\nUse the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [Wikipedia, duckduckgo_search, Calculator]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought\/Action\/Action Input\/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question\n\nBegin!\n\nQuestion: {input}\nThought:{agent_scratchpad}<\/span><\/pre>\n\n\n\n<p class=\"graf graf--p\">If you wanted to, you could just write your prompt and have a few shot examples. It will improve the performance of your agent for your particular use case.<\/p>\n\n\n\n<p class=\"graf graf--p\">You would just rewrite the prompt and set it as show below:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><span class=\"pre--content\">prompt = \"\"\"\nAnswer the following questions as best you can. You have access to the following tools:\n\nWikipedia: A wrapper around Wikipedia. Useful for when you need to answer general questions about people, places, companies, facts, historical events, or other subjects. Input should be a search query.\nduckduckgo_search: A wrapper around DuckDuckGo Search. Useful for when you need to answer questions about current events. Input should be a search query.\nCalculator: Useful for when you need to answer questions about math.\n\nUse the following format:\n\nQuestion: the input question you must answer\nThought: you should think step by step what actions you need to take\nAction: the action to take, should be one of [Wikipedia, duckduckgo_search, Calculator]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought\/Action\/Action Input\/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question\n\nBegin!\n\nQuestion: {input}\nThought:{agent_scratchpad}\n\n\"\"\"\n\n# set the redefined prompt\nagent.agent.llm_chain.prompt.template = prompt\n\ntools[1].description = \"Useful for when you need to to determine the current date.\"\ntools[2].description = \"Useful for when you need to perfom calculations.\"\n\nagent.run(\"Who is Diljit Dosanjh and what is his age as of today? What is that raised to the 0.43 power?\")<\/span><\/pre>\n\n\n\n<h4 class=\"wp-block-heading graf graf--h4\">And the&nbsp;result:<\/h4>\n\n\n\n<pre class=\"wp-block-preformatted\"><span class=\"pre--content\">&gt; Entering new AgentExecutor chain...\nTo answer the first part of the question, I need to find out who Diljit Dosanjh is and his date of birth to calculate his current age.\nAction: Wikipedia\nAction Input: Diljit Dosanjh\nObservation: Page: Diljit Dosanjh\nSummary: Diljit Dosanjh (born 6 January 1984) is an Indian singer, songwriter, actor, film producer and television personality. He works in Punjabi Music and subsequently in Punjabi and Hindi cinema. Dosanjh entered Social 50 chart by Billboard in 2020. He is featured in various music charts including Canadian Albums Chart, UK Asian chart by Official Charts Company  and New Zealand Hot Singles. His movies, including Jatt &amp; Juliet 2, Punjab 1984, Sajjan Singh Rangroot and Honsla Rakh are among the highest grossing Punjabi films in history.Hailing from Dosanjh Kalan, Jalandhar, Dosanjh started in 2002 and gained recognition in punjabi music with his album \u2018Smile\u2019 (2005) and \u2018Chocolate\u2019 (2008) followed by \u2018The Next Level\u2019 (2009) with Yo Yo Honey Singh. Subsequently he pursued his acting, starring in debut punjabi movie The Lion of Punjab in 2011.He made his Bollywood debut in 2016 with the crime thriller Udta Punjab for which he earned the Filmfare Award for Best Male Debut, in addition for a nomination for the Filmfare Award for Best Supporting Actor. This was followed by Good Newwz (2019), for which he received his second nomination for the Filmfare Award for Best Supporting Actor. As of 2020, he has won the most five PTC Award for Best Actor. He has also appeared as a judge in three seasons of the reality show Rising Star. In 2020, Dosanjh charted on the Social 50 chart by Billboard, with the release of his 11th album G.O.A.T.. The album, along with his next one MoonChild Era were listed in the Billboard Canadian Albums Chart. He became the first Punjabi artist to perform at Coachella Valley Music and Arts Festival in 2023.\n\nPage: Diljit Dosanjh discography\nSummary: Indian singer Diljit Dosanjh has released 13 studio albums, one extended plays, and 41 singles. In 2020, he entered the Social 50 chart by Billboard, following the release of his 11th album G.O.A.T. The album also entered the top 20 in the Canadian Albums Chart. His 12th album MoonChild Era charted at number 32 on the Canadian Albums Chart.\n\nPage: G.O.A.T. (Diljit Dosanjh album)\nSummary: G.O.A.T. is the eleventh studio album by Indian-Punjabi vocalist Diljit Dosanjh, released on July 30, 2020, by Famous Studios. Title track of the album and its music video was released a day prior to album release. Songs were written by Karan Aujla, Raj Ranjodh, Amrit Maan, and other artists. The album was produced by various artists including Desi Crew and The Kidd.\nThought:Diljit Dosanjh is an Indian singer, songwriter, actor, film producer, and television personality born on January 6, 1984. To calculate his current age, I need to subtract his birth year from the current year and then account for whether his birthday has passed this year or not.\n\nAction: Calculator\nAction Input: 2023 - 1984\nObservation: Answer: 39\nThought:Since today is after January 6, 2023, Diljit Dosanjh has already celebrated his birthday this year, so he is 39 years old. Now I need to calculate 39 raised to the power of 0.43.\n\nAction: Calculator\nAction Input: 39^0.43\nObservation: Answer: 4.832343312281572\nThought:I have calculated Diljit Dosanjh's age as 39 years old and raised that to the power of 0.43 to get the result.\nFinal Answer: Diljit Dosanjh is an Indian singer, songwriter, actor, film producer, and television personality, and as of today, he is 39 years old. The value of 39 raised to the 0.43 power is approximately 4.832.\n\n&gt; Finished chain.\nDiljit Dosanjh is an Indian singer, songwriter, actor, film producer, and television personality, and as of today, he is 39 years old. The value of 39 raised to the 0.43 power is approximately 4.832.<\/span><\/pre>\n\n\n\n<h3 class=\"wp-block-heading graf graf--h3\">ReAct Document&nbsp;Store<\/h3>\n\n\n\n<p class=\"graf graf--p\">The <code class=\"markup--code markup--p-code\">DocstoreExplorer<\/code> is a class in LangChain that is used for working with document stores.<\/p>\n\n\n\n<p class=\"graf graf--p\">It&#8217;s specifically designed to implement the ReAct logic for document stores.<\/p>\n\n\n\n<p class=\"graf graf--p\">You can use the <code class=\"markup--code markup--p-code\">DocstoreExplorer<\/code> for tasks such as searching and looking up documents in the document store.<\/p>\n\n\n\n<p class=\"graf graf--p\">It provides two useful tools: \u201cSearch\u201d and \u201cLookup\u201d.<\/p>\n\n\n\n<p class=\"graf graf--p\">The \u201cSearch\u201d tool is used when you need to ask a question with a search, while the \u201cLookup\u201d tool is used when you need to ask a question with a lookup.<\/p>\n\n\n\n<p class=\"graf graf--p\">To use the <code class=\"markup--code markup--p-code\">DocstoreExplorer<\/code>, you need to initialize an agent with the necessary tools and language model.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><span class=\"pre--content\">from langchain import OpenAI, Wikipedia\nfrom langchain.document_loaders import WebBaseLoader\nfrom langchain.agents import initialize_agent, Tool\nfrom langchain.agents import AgentType\nfrom langchain.agents.react.base import DocstoreExplorer\n\ndocstore = DocstoreExplorer(Wikipedia())\n\nsearch_tool = Tool(name=\"Search\",\n                   func=docstore.search,\n                   description=\"Useful for when you need to ask with search\"\n                   )\n\nlookup_tool = Tool(name=\"Lookup\",\n                   func=docstore.lookup,\n                   description=\"Useful for when yuo need to ask with lookup\"\n                   )\n\ntools = [search_tool, lookup_tool]\n\nllm = OpenAI(temperature=0)\n\nreact = initialize_agent(tools,\n                         llm,\n                         agent=AgentType.REACT_DOCSTORE,\n                         verbose=True)\n\nquestion = \"Who did Tupac Shakur have beef with over east vs west coast?\"\nreact.run(question)<\/span><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><span class=\"pre--content\">&gt; Entering new AgentExecutor chain...\nThought: I need to search Tupac Shakur and find who he had beef with over east vs west coast.\nAction: Search[Tupac Shakur]\nObservation: Tupac Amaru Shakur ( TOO-pahk sh\u0259-KOOR; born Lesane Parish Crooks; June 16, 1971 \u2013 September 13, 1996), also known by his stage names 2Pac and Makaveli, was an American rapper. He is widely considered one of the most influential and successful rappers of all time. Shakur is among the best-selling music artists, having sold more than 75 million records worldwide. Much of Shakur's music has been noted for addressing contemporary social issues that plagued inner cities.\nShakur was born in New York City to parents who were both political activists and Black Panther Party members. Raised by his mother, Afeni Shakur, he relocated to Baltimore in 1984 and to the San Francisco Bay Area in 1988. With the release of his debut album 2Pacalypse Now in 1991, he became a central figure in West Coast hip hop for his conscious rap lyrics. Shakur achieved further critical and commercial success with his follow-up albums Strictly 4 My N.I.G.G.A.Z... (1993) and Me Against the World (1995). His Diamond certified album All Eyez on Me (1996), the first double-length album in hip-hop history, abandoned his introspective lyrics for volatile gangsta rap. In addition to his music career, Shakur also found considerable success as an actor, with his starring roles in Juice (1992), Poetic Justice (1993), Above the Rim (1994), Bullet (1996), Gridlock'd (1997), and Gang Related (1997).\nDuring the later part of his career, Shakur was shot five times in the lobby of a New York recording studio and experienced legal troubles, including incarceration. Shakur served eleven months in prison on sexual abuse charges, but was released pending an appeal of his conviction in 1995. Following his release, he signed to Marion \"Suge\" Knight's label Death Row Records and became heavily involved in the growing East Coast\u2013West Coast hip hop rivalry. On September 7, 1996, Shakur was shot four times by an unidentified assailant in a drive-by shooting in Las Vegas; he died six days later. Following his murder, Shakur's friend-turned-rival, the Notorious B.I.G., was at first considered a suspect due to their public feud; he was also murdered in another drive-by shooting six months later in March 1997, while visiting Los Angeles.Shakur's double-length posthumous album Greatest Hits (1998) is one of his two releases\u2014and one of only nine hip hop albums\u2014to have been certified Diamond in the United States. Five more albums have been released since Shakur's death, including his critically acclaimed posthumous album The Don Killuminati: The 7 Day Theory (1996) under his stage name Makaveli, all of which have been certified Platinum in the United States. In 2002, Shakur was inducted into the Hip-Hop Hall of Fame. In 2017, he was inducted into the Rock and Roll Hall of Fame in his first year of eligibility. Rolling Stone ranked Shakur among the 100 Greatest Artists of All Time. In 2023, he was awarded a posthumous star on the Hollywood Walk of Fame.\nThought: Tupac Shakur had beef with Notorious B.I.G. over east vs west coast.\nAction: Finish[Notorious B.I.G.]\n\n&gt; Finished chain.\nNotorious B.I.G.<\/span><\/pre>\n\n\n\n<h3 class=\"wp-block-heading graf graf--h3\">ReAct Agents in&nbsp;LCEL<\/h3>\n\n\n\n<p class=\"graf graf--p\">It\u2019s essentially the same pattern as above, but using the expression language.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><span class=\"pre--content\">prompt = hub.pull(\"hwchase17\/react\")\n\nprompt = prompt.partial(\n    tools=render_text_description(tools),\n    tool_names=\", \".join([t.name for t in tools]),\n)\n\nllm_with_stop = llm.bind(stop=[\"\\nObservation\"])\n\nagent = (\n    {\n        \"input\": lambda x: x[\"input\"],\n        \"agent_scratchpad\": lambda x: format_log_to_str(x[\"intermediate_steps\"]),\n    }\n    | prompt\n    | llm_with_stop\n    | ReActSingleInputOutputParser()\n)<\/span><\/pre>\n\n\n\n<h4 class=\"wp-block-heading graf graf--h4\">Explaining <code class=\"markup--code markup--h4-code\">ReActSingleInputOutputParser<\/code><\/h4>\n\n\n\n<p class=\"graf graf--p\">\ud83d\udee0\ufe0f <strong class=\"markup--strong markup--p-strong\">Instantiation<\/strong>: When you use <code class=\"markup--code markup--p-code\">ReActSingleInputOutputParser()<\/code>, you create an instance of this parser, all set to interpret outputs from a Large Language Model (LLM).<\/p>\n\n\n\n<p class=\"graf graf--p\"><strong class=\"markup--strong markup--p-strong\">Functionality<\/strong>: It\u2019s designed to understand two types of LLM outputs:<\/p>\n\n\n\n<ul class=\"wp-block-list postList\">\n<li>\ud83c\udfaf <strong class=\"markup--strong markup--li-strong\">Action-oriented outputs<\/strong>: Identifies actions and their inputs, creating an <code class=\"markup--code markup--li-code\">AgentAction<\/code> object.<\/li>\n\n\n\n<li>\ud83c\udfc1<strong class=\"markup--strong markup--li-strong\">Final answer outputs<\/strong>: Recognizes conclusive answers, resulting in an <code class=\"markup--code markup--li-code\">AgentFinish<\/code> object\u00a0.<\/li>\n<\/ul>\n\n\n\n<p class=\"graf graf--p\">\ud83d\udd75\ufe0f\u200d\u2642\ufe0f<strong class=\"markup--strong markup--p-strong\">Usage<\/strong>: You\u2019ll typically pass the LLM\u2019s text output to this parser. It then determines if the output is for an action or a final answer, extracting relevant details&nbsp;.<\/p>\n\n\n\n<p class=\"graf graf--p\">\ud83d\udea8<strong class=\"markup--strong markup--p-strong\">Error Handling<\/strong>: If the LLM\u2019s output doesn\u2019t match expected formats or misses key components, the parser raises exceptions to alert you&nbsp;.<\/p>\n\n\n\n<p class=\"graf graf--p\">In essence, <code class=\"markup--code markup--p-code\">ReActSingleInputOutputParser()<\/code> is your go-to tool for smartly parsing and interpreting LLM responses, especially when they&#8217;re formatted for specific actions or definitive answers.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><span class=\"pre--content\">from langchain.agents import AgentExecutor\n\nagent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)\n\nagent_executor.invoke(\n    {\n        \"input\": \"Who is Diljit Dosanjh and what is his age as of today? What is that raised to the 0.43 power?\"\n    }\n)<\/span><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><span class=\"pre--content\">Entering new AgentExecutor chain...\n I need to find out who Diljit Dosanjh is and his age, then calculate the power.\nAction: Search\nAction Input: \"Diljit Dosanjh\"Diljit Dosanjh (born 6 January 1984) is an Indian singer, songwriter, actor, film producer and television personality. He works in Punjabi Music and subsequently in Punjabi and Hindi cinema. Dosanjh entered Social 50 chart by Billboard in 2020. He is featured in various music charts including Canadian Albums Chart, UK Asian chart by Official Charts Company  and New Zealand Hot Singles. His movies, including Jatt &amp; Juliet 2, Punjab 1984, Sajjan Singh Rangroot and Honsla Rakh are among the highest grossing Punjabi films in history.Hailing from Dosanjh Kalan, Jalandhar, Dosanjh started in 2002 and gained recognition in punjabi music with his album \u2018Smile\u2019 (2005) and \u2018Chocolate\u2019 (2008) followed by \u2018The Next Level\u2019 (2009) with Yo Yo Honey Singh. Subsequently he pursued his acting, starring in debut punjabi movie The Lion of Punjab in 2011.He made his Bollywood debut in 2016 with the crime thriller Udta Punjab for which he earned the Filmfare Award for Best Male Debut, in addition for a nomination for the Filmfare Award for Best Supporting Actor. This was followed by Good Newwz (2019), for which he received his second nomination for the Filmfare Award for Best Supporting Actor. As of 2020, he has won the most five PTC Award for Best Actor. He has also appeared as a judge in three seasons of the reality show Rising Star. In 2020, Dosanjh charted on the Social 50 chart by Billboard, with the release of his 11th album G.O.A.T.. The album, along with his next one MoonChild Era were listed in the Billboard Canadian Albums Chart. He became the first Punjabi artist to perform at Coachella Valley Music and Arts Festival in 2023. I now know who Diljit Dosanjh is and his age.\nAction: Lookup\nAction Input: \"Diljit Dosanjh age\"No Results I need to calculate the power.\nAction: Search\nAction Input: \"Raise to the 0.43 power\"Survivor 43 is the forty-third season of the American reality television series Survivor. The show was filmed from May 2 through May 27, 2022, in Fiji, for an eleventh consecutive season; it premiered on September 21, 2022 on CBS in the United States and Global in Canada. The season concluded on December 14, 2022; Mike Gabler was named the winner of the season, defeating Cassidy Clark and Owen Knight in a 7\u20131\u20130 vote. Gabler, aged 51, was the second oldest winner, after Bob Crowley, who was 57 years old at the time of winning Survivor: Gabon. Gabler has stated he intends on donating the one million dollar prize to charity. This is the first season in Survivor history where the oldest contestant of the season was the winner. I now know the final answer.\nFinal Answer: Diljit Dosanjh is an Indian singer, songwriter, actor, film producer and television personality born on 6 January 1984. Raising his age to the 0.43 power results in Survivor 43, the forty-third season of the American reality television series Survivor.\n\n&gt; Finished chain.\n{'input': 'Who is Diljit Dosanjh and what is his age as of today? What is that raised to the 0.43 power?',\n 'output': 'Diljit Dosanjh is an Indian singer, songwriter, actor, film producer and television personality born on 6 January 1984. Raising his age to the 0.43 power results in Survivor 43, the forty-third season of the American reality television series Survivor.'}<\/span><\/pre>\n\n\n\n<h3 class=\"wp-block-heading graf graf--h3\">Conclusion<\/h3>\n\n\n\n<p class=\"graf graf--p\">To wrap up, this blog has explored the ReAct framework\u2019s role in elevating LLMs\u2019 reasoning and action capabilities.<\/p>\n\n\n\n<p class=\"graf graf--p\">We\u2019ve seen how ReAct empowers LLMs to engage with their environment in a more human-like manner, enhancing decision-making and problem-solving. The integration of ReAct agents in LangChain, with their tool-selection intelligence, showcases practical applications in complex scenarios. The insights into the ReAct Document Store and the ReActSingleInputOutputParser highlight the framework\u2019s effectiveness in processing and responding to complex queries.<\/p>\n\n\n\n<p class=\"graf graf--p\">Overall, ReAct represents a significant advancement in the functionality and versatility of language models, opening new possibilities for their application in various fields.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Both ways: Using off-the-shelf agents and&nbsp;LCEL ReAct Framework for Prompting ReAct, which stands for Reasoning + Acting, is a prompting technique developed by professors from Princeton University in collaboration with Google researchers. The method is designed to enhance the reasoning capabilities of LLMs, allowing them to reason and act intelligently within simulated environments. ReAct aims [&hellip;]<\/p>\n","protected":false},"author":68,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"customer_name":"","customer_description":"","customer_industry":"","customer_technologies":"","customer_logo":"","_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[65,7],"tags":[70,71,52,31,34],"coauthors":[166],"class_list":["post-8480","post","type-post","status-publish","format-standard","hentry","category-llmops","category-tutorials","tag-langchain","tag-language-models","tag-llm","tag-llmops","tag-prompt-engineering"],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v25.9 (Yoast SEO v25.9) - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Using the ReAct Framework in LangChain - Comet<\/title>\n<meta name=\"description\" content=\"ReAct is a prompting technique that enables LLMs to mimic humans in the real world where we reason verbally + take action to gain information\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.comet.com\/site\/blog\/using-the-react-framework-in-langchain\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Using the ReAct Framework in LangChain\" \/>\n<meta property=\"og:description\" content=\"ReAct is a prompting technique that enables LLMs to mimic humans in the real world where we reason verbally + take action to gain information\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.comet.com\/site\/blog\/using-the-react-framework-in-langchain\/\" \/>\n<meta property=\"og:site_name\" content=\"Comet\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/cometdotml\" \/>\n<meta property=\"article:published_time\" content=\"2023-12-17T01:29:57+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2025-04-24T17:03:50+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/cdn-images-1.medium.com\/max\/1600\/0*1vLAWRJypHWHt44b\" \/>\n<meta name=\"author\" content=\"Harpreet Sahota\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@Cometml\" \/>\n<meta name=\"twitter:site\" content=\"@Cometml\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Harpreet Sahota\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"16 minutes\" \/>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Using the ReAct Framework in LangChain - Comet","description":"ReAct is a prompting technique that enables LLMs to mimic humans in the real world where we reason verbally + take action to gain information","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.comet.com\/site\/blog\/using-the-react-framework-in-langchain\/","og_locale":"en_US","og_type":"article","og_title":"Using the ReAct Framework in LangChain","og_description":"ReAct is a prompting technique that enables LLMs to mimic humans in the real world where we reason verbally + take action to gain information","og_url":"https:\/\/www.comet.com\/site\/blog\/using-the-react-framework-in-langchain\/","og_site_name":"Comet","article_publisher":"https:\/\/www.facebook.com\/cometdotml","article_published_time":"2023-12-17T01:29:57+00:00","article_modified_time":"2025-04-24T17:03:50+00:00","og_image":[{"url":"https:\/\/cdn-images-1.medium.com\/max\/1600\/0*1vLAWRJypHWHt44b","type":"","width":"","height":""}],"author":"Harpreet Sahota","twitter_card":"summary_large_image","twitter_creator":"@Cometml","twitter_site":"@Cometml","twitter_misc":{"Written by":"Harpreet Sahota","Est. reading time":"16 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.comet.com\/site\/blog\/using-the-react-framework-in-langchain\/#article","isPartOf":{"@id":"https:\/\/www.comet.com\/site\/blog\/using-the-react-framework-in-langchain\/"},"author":{"name":"Harpreet Sahota","@id":"https:\/\/www.comet.com\/site\/#\/schema\/person\/46036ab474aa916e2873daece26a28d6"},"headline":"Using the ReAct Framework in LangChain","datePublished":"2023-12-17T01:29:57+00:00","dateModified":"2025-04-24T17:03:50+00:00","mainEntityOfPage":{"@id":"https:\/\/www.comet.com\/site\/blog\/using-the-react-framework-in-langchain\/"},"wordCount":1262,"publisher":{"@id":"https:\/\/www.comet.com\/site\/#organization"},"image":{"@id":"https:\/\/www.comet.com\/site\/blog\/using-the-react-framework-in-langchain\/#primaryimage"},"thumbnailUrl":"https:\/\/cdn-images-1.medium.com\/max\/1600\/0*1vLAWRJypHWHt44b","keywords":["LangChain","Language Models","LLM","LLMOps","Prompt Engineering"],"articleSection":["LLMOps","Tutorials"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/www.comet.com\/site\/blog\/using-the-react-framework-in-langchain\/","url":"https:\/\/www.comet.com\/site\/blog\/using-the-react-framework-in-langchain\/","name":"Using the ReAct Framework in LangChain - Comet","isPartOf":{"@id":"https:\/\/www.comet.com\/site\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.comet.com\/site\/blog\/using-the-react-framework-in-langchain\/#primaryimage"},"image":{"@id":"https:\/\/www.comet.com\/site\/blog\/using-the-react-framework-in-langchain\/#primaryimage"},"thumbnailUrl":"https:\/\/cdn-images-1.medium.com\/max\/1600\/0*1vLAWRJypHWHt44b","datePublished":"2023-12-17T01:29:57+00:00","dateModified":"2025-04-24T17:03:50+00:00","description":"ReAct is a prompting technique that enables LLMs to mimic humans in the real world where we reason verbally + take action to gain information","breadcrumb":{"@id":"https:\/\/www.comet.com\/site\/blog\/using-the-react-framework-in-langchain\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.comet.com\/site\/blog\/using-the-react-framework-in-langchain\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.comet.com\/site\/blog\/using-the-react-framework-in-langchain\/#primaryimage","url":"https:\/\/cdn-images-1.medium.com\/max\/1600\/0*1vLAWRJypHWHt44b","contentUrl":"https:\/\/cdn-images-1.medium.com\/max\/1600\/0*1vLAWRJypHWHt44b"},{"@type":"BreadcrumbList","@id":"https:\/\/www.comet.com\/site\/blog\/using-the-react-framework-in-langchain\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.comet.com\/site\/"},{"@type":"ListItem","position":2,"name":"Using the ReAct Framework in LangChain"}]},{"@type":"WebSite","@id":"https:\/\/www.comet.com\/site\/#website","url":"https:\/\/www.comet.com\/site\/","name":"Comet","description":"Build Better Models Faster","publisher":{"@id":"https:\/\/www.comet.com\/site\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.comet.com\/site\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.comet.com\/site\/#organization","name":"Comet ML, Inc.","alternateName":"Comet","url":"https:\/\/www.comet.com\/site\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.comet.com\/site\/#\/schema\/logo\/image\/","url":"https:\/\/www.comet.com\/site\/wp-content\/uploads\/2025\/01\/logo_comet_square.png","contentUrl":"https:\/\/www.comet.com\/site\/wp-content\/uploads\/2025\/01\/logo_comet_square.png","width":310,"height":310,"caption":"Comet ML, Inc."},"image":{"@id":"https:\/\/www.comet.com\/site\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/cometdotml","https:\/\/x.com\/Cometml","https:\/\/www.youtube.com\/channel\/UCmN63HKvfXSCS-UwVwmK8Hw"]},{"@type":"Person","@id":"https:\/\/www.comet.com\/site\/#\/schema\/person\/46036ab474aa916e2873daece26a28d6","name":"Harpreet Sahota","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.comet.com\/site\/#\/schema\/person\/image\/2d21512be19ba7e19a71a803309e2a88","url":"https:\/\/secure.gravatar.com\/avatar\/a6ca5a533fc9f143a0a7428037ff652aa0633d66bf27e76ae89b955ae72a0f2d?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/a6ca5a533fc9f143a0a7428037ff652aa0633d66bf27e76ae89b955ae72a0f2d?s=96&d=mm&r=g","caption":"Harpreet Sahota"},"url":"https:\/\/www.comet.com\/site\/blog\/author\/theartistsofdatasciencegmail-com\/"}]}},"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.comet.com\/site\/wp-json\/wp\/v2\/posts\/8480","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.comet.com\/site\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.comet.com\/site\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.comet.com\/site\/wp-json\/wp\/v2\/users\/68"}],"replies":[{"embeddable":true,"href":"https:\/\/www.comet.com\/site\/wp-json\/wp\/v2\/comments?post=8480"}],"version-history":[{"count":1,"href":"https:\/\/www.comet.com\/site\/wp-json\/wp\/v2\/posts\/8480\/revisions"}],"predecessor-version":[{"id":15419,"href":"https:\/\/www.comet.com\/site\/wp-json\/wp\/v2\/posts\/8480\/revisions\/15419"}],"wp:attachment":[{"href":"https:\/\/www.comet.com\/site\/wp-json\/wp\/v2\/media?parent=8480"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.comet.com\/site\/wp-json\/wp\/v2\/categories?post=8480"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.comet.com\/site\/wp-json\/wp\/v2\/tags?post=8480"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.comet.com\/site\/wp-json\/wp\/v2\/coauthors?post=8480"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}