← Blog

Claude API LangChain Agent: Example & Tutorial

2026-11-17 · 5 min read · SubToAPI Team

Building an agent that calls the Claude API through LangChain means connecting LangChain's agent framework (tool selection, reasoning loops, memory) to Anthropic's chat model. This guide walks through a working example in JavaScript/TypeScript: setting up the model, defining tools, wiring an agent executor, and running it end to end.

If you've tried this before and hit confusing errors about tool schemas or message formatting, that's usually because Claude's tool-calling format differs slightly from OpenAI's, and LangChain's integration package handles the translation — but only if you set it up correctly. We'll cover that here.

What You Need Before Starting

Install the dependencies:

npm install @langchain/anthropic @langchain/core langchain zod

zod is used to define tool input schemas — LangChain converts these into the JSON schema Claude expects for tool use.

Setting Up the Claude Chat Model

The core building block is ChatAnthropic, which wraps the Claude API in a LangChain-compatible chat model interface.

import { ChatAnthropic } from "@langchain/anthropic";

const model = new ChatAnthropic({
  model: "claude-3-5-sonnet-latest",
  temperature: 0,
  apiKey: process.env.ANTHROPIC_API_KEY,
});

This model object is what the agent will call internally each time it needs to think or decide which tool to invoke. Temperature 0 keeps tool selection deterministic, which matters for agents more than for freeform chat.

Defining Tools for the Agent

An agent is only as useful as its tools. Each tool needs a name, a description (Claude uses this to decide when to call it), and an input schema.

import { z } from "zod";
import { tool } from "@langchain/core/tools";

const getWeather = tool(
  async ({ city }) => {
    // Replace with a real API call
    return `The weather in ${city} is 18°C and clear.`;
  },
  {
    name: "get_weather",
    description: "Get the current weather for a given city.",
    schema: z.object({
      city: z.string().describe("The city to check weather for"),
    }),
  }
);

const calculate = tool(
  async ({ expression }) => {
    // eslint-disable-next-line no-eval
    return String(eval(expression));
  },
  {
    name: "calculate",
    description: "Evaluate a basic arithmetic expression.",
    schema: z.object({
      expression: z.string().describe("A math expression like '12 * 4'"),
    }),
  }
);

const tools = [getWeather, calculate];

Keep descriptions specific. Claude's tool selection accuracy drops when multiple tools have vague, overlapping descriptions — it either calls the wrong one or calls nothing and guesses.

Building the Agent Executor

LangChain's createToolCallingAgent handles the loop of: send messages → check if Claude wants to call a tool → execute the tool → feed the result back → repeat until Claude returns a final answer.

import { createToolCallingAgent, AgentExecutor } from "langchain/agents";
import { ChatPromptTemplate } from "@langchain/core/prompts";

const prompt = ChatPromptTemplate.fromMessages([
  ["system", "You are a helpful assistant. Use tools when needed."],
  ["human", "{input}"],
  ["placeholder", "{agent_scratchpad}"],
]);

const agent = await createToolCallingAgent({ llm: model, tools, prompt });

const executor = new AgentExecutor({
  agent,
  tools,
  verbose: true,
});

The agent_scratchpad placeholder is where LangChain injects intermediate tool calls and results — without it, the agent loses track of what it already tried.

Running the Agent

const result = await executor.invoke({
  input: "What's the weather in Lisbon, and what's 340 divided by 17?",
});

console.log(result.output);

Claude will typically call get_weather and calculate in sequence (or in parallel, depending on the model version), then compose a final answer using both results. Set verbose: true while developing so you can see each tool call and response in the console — it's the fastest way to debug a misfiring agent.

Adding Memory for Multi-Turn Agents

For a conversational agent rather than a one-shot task runner, wrap the executor with message history:

import { RunnableWithMessageHistory } from "@langchain/core/runnables";
import { InMemoryChatMessageHistory } from "@langchain/core/chat_history";

const sessions = new Map();

const agentWithHistory = new RunnableWithMessageHistory({
  runnable: executor,
  getMessageHistory: (sessionId) => {
    if (!sessions.has(sessionId)) {
      sessions.set(sessionId, new InMemoryChatMessageHistory());
    }
    return sessions.get(sessionId);
  },
  inputMessagesKey: "input",
  historyMessagesKey: "chat_history",
});

For production use, swap InMemoryChatMessageHistory for a persisted store (Redis, Postgres) so sessions survive restarts.

Pointing LangChain at a Different Claude Endpoint

ChatAnthropic accepts a clientOptions.baseURL parameter, which is useful if you're routing Claude traffic through a gateway for key management, usage tracking, or team billing instead of using a raw Anthropic key directly in every service.

const model = new ChatAnthropic({
  model: "claude-3-5-sonnet-latest",
  apiKey: process.env.SUBTOAPI_KEY,
  clientOptions: {
    baseURL: "https://api.subtoapi.app/v1",
  },
});

This is how teams building multiple agents on the same Claude access handle it with SubToAPI: issue a sub_live_... key per app or environment, get streaming and tool-use support identical to the native API, and see token usage per key in one dashboard instead of digging through Anthropic's console for each project. Check the quickstart and tool use docs for the exact request shapes supported.

Common Pitfalls

questions

Does LangChain support Claude's native tool-use format, or does it convert from OpenAI's? LangChain's @langchain/anthropic package handles the translation internally — you define tools with the standard LangChain tool() helper and Zod schemas, and it converts them to Claude's tool-use JSON schema automatically.

Can I use LangChain agents with a Claude API proxy instead of a direct Anthropic key? Yes. ChatAnthropic accepts a custom baseURL via clientOptions, so any proxy that implements the same Messages API shape — including SubToAPI — works as a drop-in replacement. See /docs for request format details.

Why does my Claude agent call tools in the wrong order or skip a step? Usually it's ambiguous tool descriptions or a missing agent_scratchpad placeholder in the prompt. Enable verbose: true on the AgentExecutor to inspect each step and confirm the agent is receiving prior tool results before its next decision.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →