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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
