Python / Python Modern Generative AI and Agents Interview Questions
What is the ReAct agent pattern and how does LangChain implement it?
ReAct (Reasoning + Acting) is an agent pattern where the LLM alternates between producing a Thought (internal reasoning about what to do next), an Action (calling a tool), and an Observation (the tool's result). This loop continues until the LLM produces a Final Answer. The key insight is that interleaving reasoning and acting makes the agent more reliable — the explicit thought step helps the model plan before acting and reflect on results before taking the next step.
from langchain_openai import ChatOpenAI from langchain.agents import create_react_agent, AgentExecutor from langchain_core.tools import tool from langchain import hub # Define tools with @tool decorator @tool def calculator(expression: str) -> str: '''Evaluate a mathematical expression. Input must be a valid Python expression.''' try: return str(eval(expression, {'__builtins__': {}})) except Exception as e: return f'Error: {e}' @tool def get_word_length(word: str) -> int: '''Returns the number of characters in a word.''' return len(word) tools = [calculator, get_word_length] llm = ChatOpenAI(model='gpt-4o', temperature=0) # Pull the standard ReAct prompt from LangChain hub react_prompt = hub.pull('hwchase17/react') agent = create_react_agent(llm, tools, react_prompt) agent_executor = AgentExecutor( agent=agent, tools=tools, verbose=True, # prints Thought / Action / Observation max_iterations=10, handle_parsing_errors=True, ) result = agent_executor.invoke({ 'input': 'What is 25 * 4 + 10? Then tell me the length of the word "transformer".' }) print(result['output']) # Agent trace (verbose=True): # Thought: I need to calculate 25*4+10 first. # Action: calculator # Action Input: 25 * 4 + 10 # Observation: 110 # Thought: Now I need the length of 'transformer'. # Action: get_word_length # Action Input: transformer # Observation: 11 # Final Answer: 25*4+10 = 110. 'transformer' has 11 characters.
More Related questions...