pythonadvanced

LangChain ReAct Agent Pattern

Implement a ReAct (Reason+Act) agent that thinks step-by-step before calling tools.

python
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
from langchain.agents import AgentExecutor, create_react_agent
from langchain import hub

@tool
def search_docs(query: str) -> str:
    '''Search internal documentation.'''
    return f'Found docs about: {query}. Key detail: always use async/await in FastAPI.'

@tool
def run_python(code: str) -> str:
    '''Execute Python code and return result.'''
    try:
        result = {}
        exec(code, {}, result)  # noqa
        return str(result)
    except Exception as e:
        return f'Error: {e}'

llm = ChatOpenAI(model='gpt-4o-mini', temperature=0)
prompt = hub.pull('hwchase17/react')
agent = create_react_agent(llm, [search_docs, run_python], prompt)
executor = AgentExecutor(agent=agent, tools=[search_docs, run_python], verbose=True, max_iterations=5)
result = executor.invoke({'input': 'What is 15 factorial?'})
print(result['output'])

Use Cases

  • reasoning agents
  • tool-augmented AI
  • step-by-step planning

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.