LangChain.js 7 大核心组件详解
基于 LangChain.js v1.2.x 官方文档
目录
- Agents 代理
- Models 模型
- Messages 消息
- Tools 工具
- Short-term Memory 短期记忆
- Streaming 流式输出
- Structured Output 结构化输出
1. Agents 代理
Agent 是 LangChain 的核心,它能够循环调用工具来完成目标。
核心 API
import { createAgent } from "langchain";
const agent = createAgent({
model: "gpt-4o", // 模型
tools: [tool1, tool2], // 工具列表
systemPrompt: "你是助手", // 系统提示词
checkpointer: memSaver, // 记忆管理
responseFormat: schema, // 结构化输出
stateSchema: customState, // 自定义状态
contextSchema: contextSchema, // 上下文 schema
});
调用方式
// invoke - 一次性返回
const result = await agent.invoke({
messages: [{ role: "user", content: "你好" }],
});
// stream - 流式返回
const stream = await agent.stream(
{ messages: [...] },
{ streamMode: "values" }
);
Middleware 中间件
import { createMiddleware } from "langchain";
const middleware = createMiddleware({
name: "CustomMiddleware",
beforeModel: (state) => { /* 模型调用前 */ },
afterModel: (state) => { /* 模型调用后 */ },
wrapToolCall: async (toolCall, toolFn) => { /* 工具调用包装 */ },
});
const agent = createAgent({
model: "gpt-4o",
middleware: [middleware],
});
项目应用
routes/chat.ts: 使用createAgent创建对话 agentroutes/extract.ts: 使用createAgent+responseFormat结构化提取
2. Models 模型
模型是 LangChain 与 LLM 交互的核心接口。
初始化模型
// 方式1: initChatModel (自动识别)
import { initChatModel } from "langchain";
const model = await initChatModel("gpt-4o");
// 方式2: 直接实例化
import { ChatOpenAI } from "@langchain/openai";
const model = new ChatOpenAI({
model: "gpt-4o",
apiKey: process.env.OPENAI_API_KEY,
configuration: {
baseURL: "https://api.openai.com/v1",
},
});
核心方法
| 方法 | 说明 | 返回类型 |
|---|---|---|
invoke(input) | 同步调用 | AIMessage |
stream(input) | 流式调用 | AsyncIterable<AIMessageChunk> |
batch(inputs) | 批量调用 | AIMessage[] |
bindTools(tools) | 绑定工具 | Model |
withStructuredOutput(schema) | 结构化输出 | Model |
invoke 示例
// 简单文本
const response = await model.invoke("你好");
// 消息数组
const response = await model.invoke([
{ role: "system", content: "你是翻译助手" },
{ role: "user", content: "Hello" },
]);
stream 示例
const stream = await model.stream("讲个故事");
for await (const chunk of stream) {
process.stdout.write(chunk.text);
}
batch 批量调用
const responses = await model.batch(
["问题1", "问题2", "问题3"],
{ maxConcurrency: 5 } // 限制并发
);