LangChain Agents and Tool Execution
Use an agent when the next action depends on observations. For a fixed sequence such as classify, extract and format, an ordinary chain is often easier to test and operate.
#A read-only example
This example uses the create_agent API. It requires compatible langchain and langchain-openai packages, an authorized key and OPENAI_MODEL. Invoking it makes provider calls. The lookup data is fictional and local.
pythonimport os from langchain.agents import create_agent from langchain_core.tools import tool from langchain_openai import ChatOpenAI @tool def lookup_demo_order(order_id: str) -> str: """Read a fictional order's shipping status. Does not modify orders.""" if order_id != "DEMO-104": return "No matching fictional order." return "DEMO-104 is packed. This is demo data." agent = create_agent( model=ChatOpenAI(model=os.environ["OPENAI_MODEL"]), tools=[lookup_demo_order], system_prompt="Use only the demo lookup for order facts. Never invent an order status.", ) result = agent.invoke( {"messages": [{"role": "user", "content": "Check demo order DEMO-104."}]}, config={"recursion_limit": 10}, ) print(result["messages"][-1].content)
The recursion limit is a safety boundary for graph execution, not a precise count of billable calls. Add request timeouts, cancellation and a usage budget at the application layer.
#Define useful tools
State when a tool should be used, its accepted argument formats and what it returns. Validate inputs even when a schema exists. Avoid arbitrary eval, unrestricted shell commands and success messages that do not reflect a real operation.
Legacy tutorials may use AgentExecutor and create_tool_calling_agent; follow the migration guide for your installed version instead of combining the two API styles.
For a research assistant, separate source collection from writing and keep source URLs with claims. For writes or messages, enforce authorization and idempotency outside the prompt. Stream tool status summaries and final output; do not require hidden reasoning to be exposed.