BUILD · 5 MIN READ

Build an agent with LangChain

Use the agent abstraction to connect a model and a small tool inventory.

Download example files Code + setup + checks in a ZIP
Jump to a section 9 sections

EXAMPLE USE CASE

Create a model-and-tools support agent with less orchestration code

You need a standard agent loop before deciding whether custom graph transitions are necessary.

Input
An order question, the lookup_order function, a provider model and a system instruction.
Expected output
Messages containing the tool interaction and an answer grounded in the returned order status.
  • Success check: A104 and A999 produce distinct evidence-backed outcomes.
  • Try a failure: A model that answers without calling the required tool should fail the regression test even if its wording looks correct.

Example scope: A real LangChain create_agent example using a small local tool fixture.

LangChain exampleLangGraph exampleLangSmith example
SEE HOW THE SYSTEM FITS TOGETHERSELECT A COMPONENT
taskinvokedecisionvalidatedobservationstatecompleteApplication requestIdentity + goalLangChainAgent or graph runtimeConfigured modelAvailable provider modelAllowed toolsTyped application functionsState + limitsMessages and stopping rulesVerified answerCompare with the result
  1. Resolve the real user and pass a bounded task to the SDK.

  2. The runtime manages the loop or explicit state transitions; it does not replace resource authorization.

  3. Keep provider credentials on the server and select a model supported by the API account.

  4. The example exposes a local fixture. A real tool must check the authenticated user and resource.

  5. Track the current conversation and stop when the turn or recursion budget is reached.

    Result or stopping point
  6. For A104, confirm that the answer reflects the lookup observation and contains no invented dates.

    Result or stopping point
LangChain

The runtime manages the loop or explicit state transitions; it does not replace resource authorization.

Follow the arrows, then select a component to inspect its responsibility. On mobile, downward arrows connect the next step; bent arrows identify branches and return paths. Select a destination to jump to that component.

Where it fits

  • LangChain’s agent API supplies a higher-level starting point for a model-and-tools loop.
  • Model integrations and tool interfaces help connect the application to different services.

Prepare the example

  • Install langchain and langchain-openai.
  • Set OPENAI_API_KEY and OPENAI_MODEL.
  • Save the example as agent.py, then run python agent.py.
Shell · install in a virtual environment
python3 -m venv .venv
source .venv/bin/activate
python -m pip install langchain langchain-openai
export OPENAI_API_KEY="your-api-key"
export OPENAI_MODEL="your-enabled-model-id"
Python · agent.py
import os
from langchain.agents import create_agent

def lookup_order(order_id: str) -> str:
    """Read an order status from a local demonstration fixture."""
    orders = {"A104": "Packed; awaiting courier pickup"}
    return orders.get(order_id, "Order not found")

agent = create_agent(
    model="openai:" + os.environ["OPENAI_MODEL"],
    tools=[lookup_order],
    system_prompt=(
        "Use lookup_order for status questions. "
        "Ground your answer in its returned data."
    ),
)

result = agent.invoke(
    {"messages": [
        {"role": "user", "content": "What is the status of A104?"}
    ]},
    config={"recursion_limit": 8},
)
print(result["messages"][-1].content)

Educational example. Uses your configured environment and credentials; no paid model call is made by this website.

Read the result

  • The tool uses a local demonstration fixture.
  • The returned messages contain the tool interaction and the final answer.
  • Test the known order and an unknown identifier before replacing the fixture with a real service.

When to reach for LangGraph

  • Choose explicit graph construction when your application needs custom transitions, unusual state, or a workflow whose control structure you want to own directly.
  • Keep that choice separate from selecting a model provider.

Run and verify

Shell
python agent.py
  • The last message contains the order status from lookup_order.
  • The missing-order test should produce a grounded not-found response.

Troubleshooting and failure tests

  • Install the provider integration package as well as langchain.
  • Keep the tool docstring and parameter types: the agent uses them to construct its tool interface.

Before production

  • Replace the local fixture with a service that enforces authenticated tenant and resource permissions.
  • Add timeouts, bounded retries, tracing redaction, and a regression case for each observed failure.
  • Model calls consume provider API usage when you run this example; this website only displays the code.

Keep exploring

Build an explicit agent loop with LangGraphAI agent evaluation: frameworks, tools and an example