AI AgentsLangChain

How do you install LangChain and build your first agent?

Question 281 of 281 · Updated

On this page

Introduction#

LangChain is an open-source framework for building applications and agents powered by large language models. It provides a consistent interface for chat models, tools, messages, structured output, and agent execution. Its modern agent API centers on create_agent: you provide a model, tools, and instructions, and the framework runs the model/tool cycle until the task is complete.

This lesson builds a small Python agent from a clean environment. The goal is not just to install a package, but to understand the minimum pieces required to run an agent safely and reproducibly.

1. Understand the pieces#

A basic LangChain agent has four parts:

  • Model: interprets the request and decides whether a tool is needed.
  • Tools: Python functions the model may request, such as looking up an order or calculating a value.
  • Instructions: explain the agent's role, boundaries, and expected behavior.
  • Agent runtime: coordinates model calls and tool execution, returning the final response.

A normal model call produces text. An agent can also request a tool call, receive the tool result, and continue reasoning. The model does not execute Python itself; your application executes the registered tool after the model requests it.

LangChain, LangGraph, and Deep Agents are related but distinct layers. LangChain provides a convenient agent framework and integrations. LangGraph provides lower-level orchestration for stateful, durable workflows. Deep Agents provides a more opinionated harness for complex, long-running work. Start with LangChain when a standard model-and-tools loop is sufficient; move to LangGraph when you need custom control flow, durable execution, or explicit state transitions.

2. Create an isolated Python environment#

Use Python 3.10 or newer for a current project, and create a virtual environment so dependencies do not leak into other applications.

BASH
mkdir langchain-first-agent cd langchain-first-agent python -m venv .venv

Activate it:

macOS or Linux

BASH
source .venv/bin/activate

Windows PowerShell

POWERSHELL
.venv\\Scripts\\Activate.ps1

Upgrade the packaging tools:

BASH
python -m pip install --upgrade pip

For a reproducible project, keep the environment isolated and commit a dependency lockfile when you move beyond experimentation.

3. Install LangChain and a model integration#

The core framework is installed separately from provider integrations. For example, to use a chat model through the OpenAI integration:

BASH
pip install -U langchain langchain-openai

Other providers have their own integration packages. Install only the provider package you actually use, and consult that provider's LangChain integration documentation for its supported models and configuration.

Set the provider API key as an environment variable. On macOS or Linux:

BASH
export OPENAI_API_KEY="your-api-key"

On Windows PowerShell:

POWERSHELL
$env:OPENAI_API_KEY="your-api-key"

Do not hard-code API keys in source files, commit them to Git, or print them in logs. For deployed applications, use the hosting platform's secret manager.

4. Create a small tool#

A tool is a callable capability that the agent can use. Its name, description, and argument schema help the model decide when and how to call it.

Create a file named agent.py:

PYTHON
from langchain.tools import tool @tool def multiply(a: int, b: int) -> int: """Multiply two integers and return the product.""" return a * b

The type hints describe the input fields, and the docstring explains the tool's purpose. Keep tool descriptions specific: a vague description makes tool selection less reliable.

This example is deliberately harmless and deterministic. Real tools may read databases, send messages, update records, or call external APIs. Those tools need input validation, authorization checks, bounded permissions, and sometimes human approval before side effects occur.

5. Initialize the model and create the agent#

Add the following to agent.py:

PYTHON
from langchain.agents import create_agent from langchain.chat_models import init_chat_model from langchain.tools import tool @tool def multiply(a: int, b: int) -> int: """Multiply two integers and return the product.""" return a * b model = init_chat_model("openai:gpt-5.5") agent = create_agent( model=model, tools=[multiply], system_prompt=( "You are a helpful assistant. " "Use the multiply tool when a multiplication calculation is needed. " "Do not claim to have used a tool unless it was actually called." ), ) if __name__ == "__main__": result = agent.invoke({ "messages": [ {"role": "user", "content": "What is 17 multiplied by 23?"} ] }) print(result["messages"][-1].content)

The model identifier is an example; select a model that is available to your provider account and supported by the installed integration. The init_chat_model helper gives you a common way to initialize models across supported providers. You can also pass an already initialized chat-model object to create_agent.

The create_agent call wires together the model, tool list, and system prompt. At runtime, the model may respond directly or request the multiply tool. LangChain executes the tool, adds its result to the conversation, and gives the model an opportunity to produce the final answer.

6. Run and inspect the result#

Execute the program from the activated environment:

BASH
python agent.py

The exact wording of the response can vary, but the calculation should be 391. For debugging, inspect the returned message sequence rather than relying only on the final printed text. It can contain the assistant's tool-call request, the tool result, and the final assistant message.

Do not assume that a tool ran simply because the final answer looks plausible. In production, record structured execution events and verify important side effects independently.

7. Common installation and runtime problems#

ImportError or ModuleNotFoundError: Confirm that the virtual environment is active and that the package was installed into that same interpreter. Check with python -m pip show langchain langchain-openai.

Authentication failure: Verify that the environment variable is set in the process that launches Python. Never paste the secret into logs or source control.

Model not found or unsupported: Check the provider integration's current model identifiers and account access. A model name copied from an old tutorial may no longer be available.

Tool is not selected: Improve the tool's name and docstring, make its input schema clear, and test with requests that should and should not trigger it.

Unexpected tool side effects: Keep the first tools read-only or deterministic. Add authorization, validation, idempotency, timeouts, and approval gates before exposing write operations.

Dependency conflicts: Use a fresh virtual environment, pin tested versions for deployment, and update packages deliberately rather than upgrading a production environment blindly.

8. What to learn next#

After the first agent works, progress in this order:

  1. Define multiple tools and improve tool descriptions.
  2. Validate tool arguments and return structured output.
  3. Pass runtime context such as tenant and user identity.
  4. Preserve conversation history and isolate sessions.
  5. Add middleware, guardrails, and human approval.
  6. Stream events and inspect tool execution.
  7. Add tests, tracing, evaluation, and production monitoring.
  8. Use LangGraph when the workflow requires custom state transitions or durable orchestration.

A minimal agent is useful for learning, but it is not automatically production-ready. Production systems must also address identity, permissions, data boundaries, prompt injection, retries, timeouts, observability, cost controls, and safe handling of tool side effects.

Key takeaways#

  • Install langchain and the separate integration package for your model provider.
  • Keep credentials in environment variables or a secret manager.
  • Define tools as narrow, well-described functions with explicit input types.
  • Use create_agent to connect the model, tools, and system instructions.
  • Inspect actual tool-call events; do not infer execution from the final answer.
  • Add security and operational controls before giving an agent access to production systems.

Official references#

  • LangChain overview and agent quickstart: https://docs.langchain.com/oss/python/langchain/overview
  • LangChain API reference: https://reference.langchain.com/
  • LangChain OpenAI integration setup: https://docs.langchain.com/oss/python/integrations/chat/openai
  • LangChain agents and core components: https://docs.langchain.com/oss/python/langchain/agents
  • LangChain OSS stack overview: https://www.langchain.com/oss-overview

References

  1. 1.
  2. 2.
    LangChain API referencereference.langchain.com
  3. 3.
  4. 4.
  5. 5.

Related questions

Explore other topics:Forward Deployed EngineeringLarge Language ModelsRetrieval-Augmented GenerationMLOps