模型 (Models)

大语言模型 (LLM) 是强大的 AI 工具,能够像人类一样理解和生成文本。它们足够灵活,可以撰写内容、翻译语言、总结文本和回答问题,而无需针对每个任务进行专门训练。

除了文本生成,许多模型还支持:

模型是智能体的推理引擎。它们驱动智能体的决策过程,决定调用哪些工具、如何解释结果以及何时提供最终答案。

你选择的模型的质量和能力直接影响智能体的基线可靠性和性能。不同的模型擅长不同的任务——有些更擅长遵循复杂指令,有些更擅长结构化推理,有些支持更大的上下文窗口以处理更多信息。

基本用法

模型可以通过两种方式使用:

  1. 与智能体一起使用 - 在创建智能体时可以动态指定模型
  2. 独立使用 - 可以直接调用模型(在智能体循环之外)进行文本生成、分类或提取等任务,无需智能体框架

相同的模型接口在两种场景下都适用,这让你可以灵活地从简单开始,然后根据需要扩展到更复杂的基于智能体的工作流。

初始化模型

在 LangChain 中开始使用独立模型的最简单方法是使用 initChatModel 从你选择的聊天模型提供商初始化一个模型:

OpenAI

# 安装
npm install @langchain/openai
import { initChatModel } from "langchain";

process.env.OPENAI_API_KEY = "your-api-key";

const model = await initChatModel("gpt-4.1");

Anthropic

# 安装
npm install @langchain/anthropic
import { initChatModel } from "langchain";

process.env.ANTHROPIC_API_KEY = "your-api-key";

const model = await initChatModel("claude-sonnet-4-5-20250929");

Google Gemini

# 安装
npm install @langchain/google-genai
import { initChatModel } from "langchain";

process.env.GOOGLE_API_KEY = "your-api-key";

const model = await initChatModel("gemini-2.0-flash");

调用

关键方法

所有聊天模型都实现了 Runnable 接口,该接口带有调用、批处理和流式传输的默认实现方法:

invoke

调用模型并返回完整响应:

import { initChatModel } from "langchain";

const model = await initChatModel("gpt-4.1");

const response = await model.invoke([
  { role: "user", content: "你好,世界!" }
]);

console.log(response.content);
// 你好!有什么我可以帮助你的吗?

batch

并行处理多个输入:

const responses = await model.batch([
  [{ role: "user", content: "什么是 AI?" }],
  [{ role: "user", content: "什么是机器学习?" }],
]);

console.log(responses.map(r => r.content));

stream

流式传输响应令牌:

const stream = await model.stream([
  { role: "user", content: "写一首关于编程的诗" }
]);

for await (const chunk of stream) {
  process.stdout.write(chunk.content);
}

工具调用

工具调用允许模型请求执行外部函数。这是构建能够与外部系统交互的智能体的关键功能。

import { initChatModel } from "langchain";
import { tool } from "langchain";
import * as z from "zod";

const getWeather = tool(
  ({ city }) => `${city}的天气是晴天,温度 25°C`,
  {
    name: "get_weather",
    description: "获取指定城市的天气",
    schema: z.object({
      city: z.string().describe("城市名称"),
    }),
  }
);

const model = await initChatModel("gpt-4.1");
const modelWithTools = model.bindTools([getWeather]);

const response = await modelWithTools.invoke([
  { role: "user", content: "北京的天气怎么样?" }
]);

console.log(response.tool_calls);
// [{ name: "get_weather", args: { city: "北京" } }]

结构化输出

结构化输出允许你约束模型的响应以遵循特定的模式:

import { initChatModel } from "langchain";
import * as z from "zod";

const model = await initChatModel("gpt-4.1");

const responseSchema = z.object({
  answer: z.string().describe("问题的答案"),
  confidence: z.number().describe("置信度 0-1"),
  sources: z.array(z.string()).describe("信息来源"),
});

const structuredModel = model.withStructuredOutput(responseSchema);

const result = await structuredModel.invoke([
  { role: "user", content: "谁发明了电话?" }
]);

console.log(result);
// { answer: "亚历山大·格雷厄姆·贝尔", confidence: 0.95, sources: ["维基百科"] }

多模态

许多现代模型支持多模态输入,如图像:

import { initChatModel } from "langchain";

const model = await initChatModel("gpt-4.1");

const response = await model.invoke([
  {
    role: "user",
    content: [
      { type: "text", text: "这张图片里有什么?" },
      {
        type: "image_url",
        image_url: { url: "https://example.com/image.jpg" }
      }
    ]
  }
]);

console.log(response.content);

参数配置

模型支持多种配置参数:

import { initChatModel } from "langchain";

const model = await initChatModel("gpt-4.1", {
  temperature: 0.7,
  maxTokens: 1000,
  timeout: 30,
  maxRetries: 3,
});

支持的模型

LangChain 支持多种模型提供商:

本地模型

你也可以使用本地运行的模型:

import { ChatOllama } from "@langchain/ollama";

const model = new ChatOllama({
  model: "llama3.2",
  baseUrl: "http://localhost:11434",
});

const response = await model.invoke([
  { role: "user", content: "你好!" }
]);

下一步