Home AI SkillsBuild Your First AI Agent with LangChain on Linux

Build Your First AI Agent with LangChain on Linux

by Knowledge Base Linux
Build Your First AI Agent with — Build Your First AI Agent with LangChain on Linux

A LangChain AI agent is a program that pairs a large language model with tools — a calculator, a shell command runner, a web search — and lets the model decide which tool to call, in what order, to complete a task you give it in plain English. Instead of a chatbot that only talks, you get an assistant that acts. This guide shows you how to build your first LangChain AI agent on a Linux server or desktop, starting from a clean Python virtual environment and ending with an agent that can do real sysadmin-flavored work.

Diagram of the LangChain AI agent reasoning loop connecting tools and model

Prerequisites – Build Your First AI Agent with

  • A Linux machine (Ubuntu 22.04/24.04 or Debian 12 used in examples) with sudo access.
  • Python 3.10 or newer (python3 --version to check).
  • An OpenAI API key if you want to use a hosted model (stored in an environment variable — never hardcoded), or a local Ollama install if you prefer running models on your own hardware. If you need the local route first, see Self-Host an LLM with Ollama on Ubuntu.
  • Familiarity with the terminal; if you want AI help directly in your shell first, try ShellGPT: AI in Your Linux Terminal.

What Is a LangChain AI Agent? – Build Your First AI Agent with

Traditional LLM code follows a fixed path: prompt in, answer out. A LangChain AI agent instead runs a reasoning loop — the model thinks, picks a tool, observes the tool's output, thinks again, and repeats until the task is done. LangChain (and its companion library LangGraph, which provides the modern agent runtime) supplies the create_react_agent helper that implements this ReAct (reason + act) loop for you, so your job is reduced to defining tools and giving the agent a goal.

Step 1: Set Up a Python Virtual Environment

Never install AI libraries into the system Python — use a virtual environment to keep dependencies isolated:

sudo apt update && sudo apt install -y python3-venv python3-pip
python3 -m venv ~/ai-agent
source ~/ai-agent/bin/activate
pip install --upgrade pip

Your prompt should now show (ai-agent), confirming the venv is active. Every pip install from here on stays inside ~/ai-agent.

Step 2: Install LangChain and a Model Provider

For a hosted model via the OpenAI API:

pip install langchain langchain-openai langgraph

For a fully local setup with Ollama (no API key, no data leaving your server):

pip install langchain langchain-ollama langgraph

Pin versions in a requirements.txt once things work, so your agent stays reproducible:

pip freeze > requirements.txt

Step 3: Keep Secrets Out of Code

Set your API key as an environment variable before writing any code. Never paste keys into source files, commits, or chat logs:

export OPENAI_API_KEY="sk-your-key-here"

Make it persistent across logins with echo 'export OPENAI_API_KEY="sk-your-key-here"' >> ~/.bashrc, or better, load it from a secrets manager or a .env file that is excluded from version control. The agent script below reads the key only from the environment via os.environ.

Step 4: Build Your First LangChain AI Agent

Create ~/ai-agent/agent.py. It defines two tools — a safe calculator and a restricted shell-command runner — and hands them to create_react_agent, giving your LangChain AI agent real capabilities beyond chat:

import math
import os
import subprocess

from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent


@tool
def calculator(expression: str) -> str:
    """Evaluate a math expression, e.g. '2**10 + 5' or 'round(2380 * 0.15, 2)'."""
    allowed = {k: getattr(math, k) for k in dir(math) if not k.startswith("_")}
    allowed.update({"abs": abs, "round": round, "min": min, "max": max})
    try:
        result = eval(expression, {"__builtins__": {}}, allowed)
    except Exception as exc:
        return f"Error: {exc}"
    return str(result)


ALLOWED_COMMANDS = {"df", "uptime", "whoami", "free", "uname", "ls"}


@tool
def safe_shell(command: str) -> str:
    """Run a whitelisted read-only Linux command, e.g. 'df -h' or 'uptime'."""
    parts = command.strip().split()
    if not parts or parts[0] not in ALLOWED_COMMANDS:
        return "Error: command not allowed. Use one of: " + ", ".join(sorted(ALLOWED_COMMANDS))
    try:
        out = subprocess.run(parts, capture_output=True, text=True, timeout=15)
    except Exception as exc:
        return f"Error: {exc}"
    return out.stdout.strip() or "(no output)"


model = ChatOpenAI(model="gpt-4o-mini", api_key=os.environ["OPENAI_API_KEY"])

agent = create_react_agent(
    model,
    [calculator, safe_shell],
    prompt="You are a Linux sysadmin assistant. Use the available tools to answer questions.",
)

if __name__ == "__main__":
    question = "What is 15% of 2380, and how much free disk space is on /?"
    for chunk in agent.stream({"messages": [("user", question)]}):
        print(chunk)

A few design notes worth understanding:

  • The @tool decorator turns a plain Python function into a tool the model can call; the docstring becomes the tool description the model reads, so write it clearly.
  • The shell tool is deliberately whitelisted to read-only commands. Giving an agent unrestricted shell access is a real security risk — always constrain what it can execute, especially on production servers.
  • create_react_agent comes from langgraph.prebuilt, the current home of LangChain's agent runtime. The official LangChain documentation tracks these APIs as they evolve, so check it if an import changes.

To use a local model instead, swap the model line for:

from langchain_ollama import ChatOllama

model = ChatOllama(model="llama3.1", base_url="http://localhost:11434")

Make sure ollama serve is running and the model is pulled (ollama pull llama3.1) first.

Step 5: Run and Iterate on Your LangChain AI Agent

Run the agent from inside the activated venv, then watch your LangChain AI agent reason, call tools, and answer:

cd ~/ai-agent
source bin/activate
python agent.py

You should see the agent call calculator for the percentage and safe_shell with df -h, then combine both results into a final answer. If it instead guesses the numbers without calling tools, improve the system prompt: tell it explicitly to use tools for every fact it does not already know. Iteration is the core skill of agent building:

  • Add tools when the agent says “I can't do that” — a log-search tool, a systemctl status reader, or an HTTP fetcher.
  • Tighten tool descriptions when it picks the wrong tool or formats arguments badly — the docstring is your main lever.
  • Constrain outputs with the system prompt when answers are too verbose or the agent loops instead of finishing.
  • Test edge cases — denied commands, empty outputs, slow commands hitting the timeout — before pointing the agent at anything important.

Troubleshooting Your LangChain AI Agent

  • ModuleNotFoundError: No module named 'langchain': the venv is not activated. Run source ~/ai-agent/bin/activate again — a new terminal session starts outside the venv.
  • KeyError: 'OPENAI_API_KEY': the environment variable is not set in this shell. Export it (Step 3) and re-run; check with env | grep OPENAI.
  • HTTP 429 rate limit errors: you are hitting the API too fast or your quota is exhausted. Add a small delay between runs, reduce the number of tool-calling turns, or switch to a local Ollama model for development.
  • model_not_found / invalid model name: hosted model names change over time — verify the current name in your provider's model list and update the model= argument. For Ollama, confirm the model is pulled with ollama list.
  • Ollama connection refused: ollama serve is not running, or a firewall blocks localhost:11434. Start the service and retest with curl http://localhost:11434/api/tags.
  • Agent loops or never finishes: add a turn limit via create_react_agent(..., debug=False) alternatives like LangGraph's recursion limit config, and sharpen the system prompt with “answer with the tools' results; do not ask follow-up questions.”

Conclusion

You now have a working LangChain AI agent on Linux: an isolated venv, a model wired through LangChain, and two real tools the agent can reason over. The pattern scales — the same create_react_agent loop powers agents that triage logs, draft Ansible playbooks, or watch dashboards, as long as each new tool is carefully described and, where it touches the system, carefully restricted. Turning a LangChain AI agent from a tutorial script into something you trust takes one habit: keep secrets in the environment, keep the shell tool whitelisted, and iterate on prompts and tool descriptions until the agent behaves reliably. That loop — build, run, observe, tighten — is the real skill, and you have already practiced it.

You may also like

KbLinux

Typically replies within a day

Hello, Welcome to the site. Please click below button for chatting me through Telegram.