Integrate Anthropic's Claude models into LangChain.js applications with support for chat, streaming, tools, memory, web search, file operations, and computer control.
Integrate Anthropic's Claude models into your LangChain.js applications. This skill provides comprehensive support for chat models, streaming, tool use, memory management, web search, file operations, and computer control using the `@langchain/anthropic` package.
This skill helps you integrate Anthropic's Claude models into LangChain.js applications with support for:
Install the required packages:
```bash
npm install @langchain/anthropic @langchain/core
```
Ensure package version consistency by adding to `package.json`:
```json
{
"dependencies": {
"@langchain/anthropic": "^0.0.9",
"@langchain/core": "^0.3.0"
},
"resolutions": {
"@langchain/core": "^0.3.0"
},
"overrides": {
"@langchain/core": "^0.3.0"
},
"pnpm": {
"overrides": {
"@langchain/core": "^0.3.0"
}
}
}
```
Configure environment variable:
```bash
export ANTHROPIC_API_KEY=your-api-key
```
Initialize and use the chat model:
```typescript
import { ChatAnthropic } from "@langchain/anthropic";
const model = new ChatAnthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
model: "claude-sonnet-4-5-20250929"
});
const response = await model.invoke({
role: "user",
content: "Hello world!"
});
```
For streaming responses:
```typescript
const stream = await model.stream({
role: "user",
content: "Tell me a story"
});
for await (const chunk of stream) {
console.log(chunk);
}
```
Enable Claude to store and retrieve information across conversations:
```typescript
import { ChatAnthropic, tools } from "@langchain/anthropic";
const files = new Map<string, string>();
const memory = tools.memory_20250818({
execute: async (command) => {
switch (command.command) {
case "view":
if (!command.path || command.path === "/") {
return Array.from(files.keys()).join("\n") || "Directory is empty.";
}
return files.get(command.path) ?? `Error: File not found: ${command.path}`;
case "create":
files.set(command.path!, command.file_text ?? "");
return `Successfully created file: ${command.path}`;
case "str_replace":
const content = files.get(command.path!);
if (content && command.old_str) {
files.set(command.path!, content.replace(command.old_str, command.new_str ?? ""));
}
return `Successfully replaced text in: ${command.path}`;
case "delete":
files.delete(command.path!);
return `Successfully deleted: ${command.path}`;
default:
return "Unknown command";
}
}
});
const llm = new ChatAnthropic({ model: "claude-sonnet-4-5-20250929" });
const llmWithMemory = llm.bindTools([memory]);
const response = await llmWithMemory.invoke(
"Remember that my favorite programming language is TypeScript"
);
```
Give Claude access to real-time web content with automatic source citations:
```typescript
import { tools } from "@langchain/anthropic";
const response = await llm.invoke("What is the weather in NYC?", {
tools: [tools.webSearch_20250305()]
});
// With configuration
const configuredResponse = await llm.invoke("Latest AI news?", {
tools: [tools.webSearch_20250305({
maxUses: 5,
allowedDomains: ["reuters.com", "bbc.com"],
userLocation: {
type: "approximate",
city: "San Francisco",
region: "California",
country: "US",
timezone: "America/Los_Angeles"
}
})]
});
```
Retrieve full content from specified web pages and PDFs:
```typescript
import { tools } from "@langchain/anthropic";
const response = await llm.invoke(
"Please analyze the content at https://example.com/article",
{
tools: [tools.webFetch_20250910({
maxUses: 5,
allowedDomains: ["example.com"],
citations: { enabled: true },
maxContentTokens: 50000
})]
}
);
// Combine with web search
const combined = await llm.invoke(
"Find recent articles about quantum computing and analyze the most relevant one",
{
tools: [
tools.webSearch_20250305({ maxUses: 3 }),
tools.webFetch_20250910({ maxUses: 5, citations: { enabled: true } })
]
}
);
```
Enable dynamic tool discovery when working with hundreds or thousands of tools:
```typescript
import { ChatAnthropic, tools } from "@langchain/anthropic";
import { tool } from "langchain";
import { z } from "zod";
const getWeather = tool(
async (input: { location: string }) => {
return `Weather in ${input.location}: Sunny, 72°F`;
},
{
name: "get_weather",
description: "Get the weather at a specific location",
schema: z.object({ location: z.string() }),
extras: { defer_loading: true }
}
);
// Regex-based search
const response = await llm.invoke("What is the weather in San Francisco?", {
tools: [tools.toolSearchRegex_20251119(), getWeather]
});
// BM25 natural language search
const bm25Response = await llm.invoke("What is the weather in San Francisco?", {
tools: [tools.toolSearchBM25_20251119(), getWeather]
});
```
Enable Claude to view and modify text files:
```typescript
import fs from "node:fs";
import { tools } from "@langchain/anthropic";
const textEditor = tools.textEditor_20250728({
async execute(args) {
switch (args.command) {
case "view":
const content = fs.readFileSync(args.path, "utf-8");
return content.split("\n").map((line, i) => `${i + 1}: ${line}`).join("\n");
case "str_replace":
let fileContent = fs.readFileSync(args.path, "utf-8");
fileContent = fileContent.replace(args.old_str, args.new_str);
fs.writeFileSync(args.path, fileContent);
return "Successfully replaced text.";
case "create":
fs.writeFileSync(args.path, args.file_text);
return `Successfully created file: ${args.path}`;
case "insert":
const lines = fs.readFileSync(args.path, "utf-8").split("\n");
lines.splice(args.insert_line, 0, args.new_str);
fs.writeFileSync(args.path, lines.join("\n"));
return `Successfully inserted text at line ${args.insert_line}`;
default:
return "Unknown command";
}
},
maxCharacters: 10000
});
const llmWithEditor = llm.bindTools([textEditor]);
const response = await llmWithEditor.invoke(
"There's a syntax error in my primes.py file. Can you help me fix it?"
);
```
Enable Claude to interact with desktop environments through screenshots and input control:
```typescript
import { ChatAnthropic, tools, type Computer20250124Action } from "@langchain/anthropic";
const computer = tools.computer_20250124({
displayWidthPx: 1024,
displayHeightPx: 768,
displayNumber: 1,
execute: async (action: Computer20250124Action) => {
switch (action.action) {
case "screenshot":
// Capture and return base64-encoded screenshot
break;
case "left_click":
// Click at specified coordinates
break;
// Handle other actions...
}
}
});
const llmWithComputer = llm.bindTools([computer]);
const response = await llmWithComputer.invoke(
"Save a picture of a cat to my desktop."
);
// For Claude Opus 4.5 with zoom support
const advancedComputer = tools.computer_20251124({
displayWidthPx: 1920,
displayHeightPx: 1080,
enableZoom: true,
execute: async (action) => {
// Handle actions including "zoom"
}
});
```
**Basic chat with streaming:**
```typescript
const model = new ChatAnthropic({ model: "claude-sonnet-4-5-20250929" });
const stream = await model.stream({ role: "user", content: "Explain quantum computing" });
```
**Multi-tool agent:**
```typescript
const response = await llm.invoke("Research quantum computing and save findings to memory", {
tools: [
tools.webSearch_20250305({ maxUses: 3 }),
tools.webFetch_20250910({ maxUses: 5 }),
tools.memory_20250818({ execute: memoryHandler })
]
});
```
**Code assistance:**
```typescript
const llmWithEditor = llm.bindTools([tools.textEditor_20250728({ execute: fileHandler })]);
const response = await llmWithEditor.invoke("Fix the bug in src/app.ts");
```
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/langchain-anthropic-integration/raw