> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-docs-zh.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# OpenAI 集成

> 使用 LangChain JavaScript 集成 OpenAI 工具。

`@langchain/openai` 包含了适用于 OpenAI 内置工具的 LangChain 兼容封装。这些工具可以通过 `bindTools()` 或 @\[`createAgent`] 绑定到 `ChatOpenAI`。

### 网络搜索工具

网络搜索工具允许 OpenAI 模型在生成回复前搜索网络以获取最新信息。网络搜索支持三种主要类型：

1. **非推理网络搜索**：快速查找，模型直接将查询传递给搜索工具
2. **带推理的智能体搜索**：模型主动管理搜索过程，分析结果并决定是否继续搜索
3. **深度研究**：使用 `o3-deep-research` 或 `gpt-5` 等高推理力模型进行扩展调查

```typescript theme={null}
import { ChatOpenAI, tools } from "@langchain/openai";

const model = new ChatOpenAI({
  model: "gpt-5.5",
});

// Basic usage
const response = await model.invoke(
  "What was a positive news story from today?",
  {
    tools: [tools.webSearch()],
  }
);
```

**领域过滤** - 将搜索结果限制在特定领域（最多100个）：

```typescript theme={null}
const response = await model.invoke("Latest AI research news", {
  tools: [
    tools.webSearch({
      filters: {
        allowedDomains: ["arxiv.org", "nature.com", "science.org"],
      },
    }),
  ],
});
```

**用户位置** - 基于地理位置细化搜索结果：

```typescript theme={null}
const response = await model.invoke("What are the best restaurants near me?", {
  tools: [
    tools.webSearch({
      userLocation: {
        type: "approximate",
        country: "US",
        city: "San Francisco",
        region: "California",
        timezone: "America/Los_Angeles",
      },
    }),
  ],
});
```

**仅缓存模式** - 禁用实时网络访问：

```typescript theme={null}
const response = await model.invoke("Find information about OpenAI", {
  tools: [
    tools.webSearch({
      externalWebAccess: false,
    }),
  ],
});
```

更多信息，请参阅 [OpenAI 的网络搜索文档](https://platform.openai.com/docs/guides/tools-web-search)。

### MCP 工具（模型上下文协议）

MCP 工具允许 OpenAI 模型连接到远程 MCP 服务器和 OpenAI 维护的服务连接器，从而让模型访问外部工具和服务。

使用 MCP 工具有两种方法：

1. **远程 MCP 服务器**：通过 URL 连接到任何公共 MCP 服务器
2. **连接器**：使用 OpenAI 维护的流行服务（如 Google Workspace 或 Dropbox）的封装

**远程 MCP 服务器** - 连接到任何 MCP 兼容服务器：

```typescript theme={null}
import { ChatOpenAI, tools } from "@langchain/openai";

const model = new ChatOpenAI({ model: "gpt-5.5" });

const response = await model.invoke("Roll 2d4+1", {
  tools: [
    tools.mcp({
      serverLabel: "dmcp",
      serverDescription: "A D&D MCP server for dice rolling",
      serverUrl: "https://dmcp-server.deno.dev/sse",
      requireApproval: "never",
    }),
  ],
});
```

**服务连接器** - 使用 OpenAI 维护的流行服务封装：

```typescript theme={null}
const response = await model.invoke("What's on my calendar today?", {
  tools: [
    tools.mcp({
      serverLabel: "google_calendar",
      connectorId: "connector_googlecalendar",
      authorization: "<oauth-access-token>",
      requireApproval: "never",
    }),
  ],
});
```

更多信息，请参阅 [OpenAI 的 MCP 文档](https://platform.openai.com/docs/guides/tools-remote-mcp)。

### 代码解释器工具

代码解释器工具允许模型在一个沙盒环境中编写和运行 Python 代码以解决复杂问题。

使用代码解释器进行：

* **数据分析**：处理具有多样数据和格式的文件
* **文件生成**：创建包含数据和图像图表的文件
* **迭代编码**：编写和运行代码以迭代解决问题
* **视觉智能**：裁剪、缩放、旋转和转换图像

```typescript theme={null}
import { ChatOpenAI, tools } from "@langchain/openai";

const model = new ChatOpenAI({ model: "gpt-5.5" });

// Basic usage with auto container (default 1GB memory)
const response = await model.invoke("Solve the equation 3x + 11 = 14", {
  tools: [tools.codeInterpreter()],
});
```

**内存配置** - 选择 1GB（默认）、4GB、16GB 或 64GB：

```typescript theme={null}
const response = await model.invoke(
  "Analyze this large dataset and create visualizations",
  {
    tools: [
      tools.codeInterpreter({
        container: { memoryLimit: "4g" },
      }),
    ],
  }
);
```

**带文件** - 将上传的文件提供给代码：

```typescript theme={null}
const response = await model.invoke("Process the uploaded CSV file", {
  tools: [
    tools.codeInterpreter({
      container: {
        memoryLimit: "4g",
        fileIds: ["file-abc123", "file-def456"],
      },
    }),
  ],
});
```

**显式容器** - 使用预创建的容器 ID：

```typescript theme={null}
const response = await model.invoke("Continue working with the data", {
  tools: [
    tools.codeInterpreter({
      container: "cntr_abc123",
    }),
  ],
});
```

> **注意**：容器在 20 分钟不活动后过期。虽然称为 "代码解释器"，但模型将其称为 "python 工具" - 对于明确提示，请在提示词中请求 "the python tool"。

更多信息，请参阅 [OpenAI 的代码解释器文档](https://platform.openai.com/docs/guides/tools-code-interpreter)。

### 文件搜索工具

文件搜索工具允许模型使用语义和关键词搜索在您的文件中搜索相关信息。它支持从向量存储中存储的先前上传文件的知识库中检索。

**前提条件**：在使用文件搜索前，您必须：

1. 使用 `purpose: "assistants"` 将文件上传到文件 API
2. 创建向量存储
3. 将文件添加到向量存储

```typescript theme={null}
import { ChatOpenAI, tools } from "@langchain/openai";

const model = new ChatOpenAI({ model: "gpt-5.5" });

const response = await model.invoke("What is deep research by OpenAI?", {
  tools: [
    tools.fileSearch({
      vectorStoreIds: ["vs_abc123"],
      // maxNumResults: 5, // Limit results for lower latency
      // filters: { type: "eq", key: "category", value: "blog" }, // Metadata filtering
      // filters: { type: "and", filters: [                       // Compound filters (AND/OR)
      //   { type: "eq", key: "category", value: "technical" },
      //   { type: "gte", key: "year", value: 2024 },
      // ]},
      // rankingOptions: { scoreThreshold: 0.8, ranker: "auto" }, // Customize scoring
    }),
  ],
});
```

过滤运算符：`eq`（等于）、`ne`（不等于）、`gt`（大于）、`gte`（大于或等于）、`lt`（小于）、`lte`（小于或等于）。

更多信息，请参阅 [OpenAI 的文件搜索文档](https://platform.openai.com/docs/guides/tools-file-search)。

### 图像生成工具

图像生成工具允许模型使用文本提示和可选的图像输入生成或编辑图像。它利用 GPT 图像模型并自动优化文本输入以提升性能。

使用图像生成进行：

* **从文本创建图像**：根据详细的文本描述生成图像
* **编辑现有图像**：根据文本指令修改图像
* **多轮图像编辑**：跨对话轮次迭代优化图像
* **多种输出格式**：支持 PNG、JPEG 和 WebP 格式

```typescript theme={null}
import { ChatOpenAI, tools } from "@langchain/openai";

const model = new ChatOpenAI({ model: "gpt-5.5" });

// Basic usage - generate an image
const response = await model.invoke(
  "Generate an image of a gray tabby cat hugging an otter with an orange scarf",
  { tools: [tools.imageGeneration()] }
);

// Access the generated image (base64-encoded)
const imageOutput = response.additional_kwargs.tool_outputs?.find(
  (output) => output.type === "image_generation_call"
);
if (imageOutput?.result) {
  const fs = await import("fs");
  fs.writeFileSync("output.png", Buffer.from(imageOutput.result, "base64"));
}
```

**自定义尺寸和质量** - 配置输出尺寸和质量：

```typescript theme={null}
const response = await model.invoke("Draw a beautiful sunset over mountains", {
  tools: [
    tools.imageGeneration({
      size: "1536x1024", // Landscape format (also: "1024x1024", "1024x1536", "auto")
      quality: "high", // Quality level (also: "low", "medium", "auto")
    }),
  ],
});
```

**输出格式和压缩** - 选择格式和压缩级别：

```typescript theme={null}
const response = await model.invoke("Create a product photo", {
  tools: [
    tools.imageGeneration({
      outputFormat: "jpeg", // Format (also: "png", "webp")
      outputCompression: 90, // Compression 0-100 (for JPEG/WebP)
    }),
  ],
});
```

**透明背景** - 生成带透明背景的图像：

```typescript theme={null}
const response = await model.invoke(
  "Create a logo with transparent background",
  {
    tools: [
      tools.imageGeneration({
        background: "transparent", // Background type (also: "opaque", "auto")
        outputFormat: "png",
      }),
    ],
  }
);
```

**流式输出部分图像** - 在生成过程中获取视觉反馈：

```typescript theme={null}
const response = await model.invoke("Draw a detailed fantasy castle", {
  tools: [
    tools.imageGeneration({
      partialImages: 2, // Number of partial images (0-3)
    }),
  ],
});
```

**强制图像生成** - 确保模型使用图像生成工具：

```typescript theme={null}
const response = await model.invoke("A serene lake at dawn", {
  tools: [tools.imageGeneration()],
  tool_choice: { type: "image_generation" },
});
```

**多轮编辑** - 跨对话轮次优化图像：

```typescript theme={null}
import { HumanMessage } from "@langchain/core/messages";

// First turn: generate initial image
const response1 = await model.invoke("Draw a red car", {
  tools: [tools.imageGeneration()],
});

// Second turn: edit the image
const response2 = await model.invoke(
  [response1, new HumanMessage("Now change the car color to blue")],
  { tools: [tools.imageGeneration()] }
);
```

> **提示词技巧**：使用 "draw" 或 "edit" 获得最佳效果。对于组合图像，说 "edit the first image by adding this element" 而不是 "combine" 或 "merge"。

支持模型：`gpt-4o`、`gpt-4o-mini`、`gpt-5.5`、`gpt-5.4-mini`、`gpt-5.4-nano`、`o3`

更多信息，请参阅 [OpenAI 的图像生成文档](https://platform.openai.com/docs/guides/tools-image-generation)。

### 计算机使用工具

计算机使用工具允许模型通过模拟鼠标点击、键盘输入、滚动等操作来控制计算机界面。它使用 OpenAI 的计算机使用智能体（CUA）模型来理解截图并建议操作。

> **测试版**：计算机使用处于测试版。仅在沙盒环境中使用，不要用于高风险或认证任务。对于重要决策，始终实施人机交互。

**工作原理**：该工具在持续循环中运行：

1. 模型发送计算机操作（点击、输入、滚动等）
2. 您的代码在受控环境中执行这些操作
3. 您捕获结果截图
4. 将截图发送回模型
5. 重复直到任务完成

```typescript theme={null}
import { ChatOpenAI, tools } from "@langchain/openai";

const model = new ChatOpenAI({ model: "computer-use-preview" });

// With execute callback for automatic action handling
const computer = tools.computerUse({
  displayWidth: 1024,
  displayHeight: 768,
  environment: "browser",
  execute: async (action) => {
    if (action.type === "screenshot") {
      return captureScreenshot();
    }
    if (action.type === "click") {
      await page.mouse.click(action.x, action.y, { button: action.button });
      return captureScreenshot();
    }
    if (action.type === "type") {
      await page.keyboard.type(action.text);
      return captureScreenshot();
    }
    if (action.type === "scroll") {
      await page.mouse.move(action.x, action.y);
      await page.evaluate(
        `window.scrollBy(${action.scroll_x}, ${action.scroll_y})`
      );
      return captureScreenshot();
    }
    // Handle other actions...
    return captureScreenshot();
  },
});

const llmWithComputer = model.bindTools([computer]);
const response = await llmWithComputer.invoke(
  "Check the latest news on bing.com"
);
```

更多信息，请参阅 [OpenAI 的计算机使用文档](https://platform.openai.com/docs/guides/tools-computer-use)。

### 本地 Shell 工具

本地 Shell 工具允许模型在您提供的机器上本地运行 Shell 命令。命令在您的运行时环境中执行——API 仅返回指令。

> **安全警告**：运行任意 Shell 命令可能很危险。始终在转发命令到系统 Shell 前进行沙盒执行或添加严格的允许/禁止列表。
> **注意**：此工具设计用于与 [Codex CLI](https://github.com/openai/codex) 和 `codex-mini-latest` 模型配合使用。

```typescript theme={null}
import { ChatOpenAI, tools } from "@langchain/openai";
import { exec } from "child_process";
import { promisify } from "util";

const execAsync = promisify(exec);
const model = new ChatOpenAI({ model: "codex-mini-latest" });

// With execute callback for automatic command handling
const shell = tools.localShell({
  execute: async (action) => {
    const { command, env, working_directory, timeout_ms } = action;
    const result = await execAsync(command.join(" "), {
      cwd: working_directory ?? process.cwd(),
      env: { ...process.env, ...env },
      timeout: timeout_ms ?? undefined,
    });
    return result.stdout + result.stderr;
  },
});

const llmWithShell = model.bindTools([shell]);
const response = await llmWithShell.invoke(
  "List files in the current directory"
);
```

**操作属性**：模型返回的操作具有这些属性：

* `command` - 要执行的 argv 令牌数组
* `env` - 要设置的環境变量
* `working_directory` - 要在其中运行命令的目录
* `timeout_ms` - 建议的超时时间（请自行强制执行限制）
* `user` - 可选的用户，以该用户身份运行命令

更多信息，请参阅 [OpenAI 的本地 Shell 文档](https://platform.openai.com/docs/guides/tools-local-shell)。

### Shell 工具

Shell 工具允许模型通过您的集成运行 Shell 命令。与 Local Shell 不同，此工具支持并发执行多个命令，并专为 `gpt-5.1` 设计。

> **安全警告**：运行任意 Shell 命令可能很危险。在将命令转发到系统 Shell 之前，请始终进行沙盒执行或添加严格的允许/拒绝列表。

**用例**：

* **自动化文件系统或进程诊断** – 例如，“在 \~/Documents 下找到最大的 PDF 文件”
* **扩展模型功能** – 使用内置的 UNIX 工具、Python 运行时和其他 CLI
* **运行多步骤构建和测试流程** – 链接命令如 `pip install` 和 `pytest`
* **复杂的智能体编码工作流** – 使用 `apply_patch` 进行文件操作

```typescript theme={null}
import { ChatOpenAI, tools } from "@langchain/openai";
import { exec } from "node:child_process/promises";

const model = new ChatOpenAI({ model: "gpt-5.1" });

// With execute callback for automatic command handling
const shellTool = tools.shell({
  execute: async (action) => {
    const outputs = await Promise.all(
      action.commands.map(async (cmd) => {
        try {
          const { stdout, stderr } = await exec(cmd, {
            timeout: action.timeout_ms ?? undefined,
          });
          return {
            stdout,
            stderr,
            outcome: { type: "exit" as const, exit_code: 0 },
          };
        } catch (error) {
          const timedOut = error.killed && error.signal === "SIGTERM";
          return {
            stdout: error.stdout ?? "",
            stderr: error.stderr ?? String(error),
            outcome: timedOut
              ? { type: "timeout" as const }
              : { type: "exit" as const, exit_code: error.code ?? 1 },
          };
        }
      })
    );
    return {
      output: outputs,
      maxOutputLength: action.max_output_length,
    };
  },
});

const llmWithShell = model.bindTools([shellTool]);
const response = await llmWithShell.invoke(
  "Find the largest PDF file in ~/Documents"
);
```

**操作属性**：模型返回具有这些属性的操作：

* `commands` - 要执行的 Shell 命令数组（可以并发执行）
* `timeout_ms` - 可选的超时时间（毫秒）（请自行强制执行限制）
* `max_output_length` - 可选的每个命令返回的最大字符数

**返回格式**：您的执行函数应返回一个 `ShellResult`：

```typescript theme={null}
interface ShellResult {
  output: Array<{
    stdout: string;
    stderr: string;
    outcome: { type: "exit"; exit_code: number } | { type: "timeout" };
  }>;
  maxOutputLength?: number | null; // Pass back from action if provided
}
```

> **注意**：仅通过 Responses API 使用 `gpt-5.1` 时可用。模型返回的 `timeout_ms` 仅是提示——请始终自行强制执行限制。

更多信息，请参阅 [OpenAI 的 Shell 文档](https://platform.openai.com/docs/guides/tools-shell)。

### 应用补丁工具

应用补丁工具允许模型提出结构化的差异，您的集成会应用这些差异。这支持迭代的多步骤代码编辑工作流，其中模型可以创建、更新和删除您的代码库中的文件。

**何时使用**：

* **多文件重构** – 重命名符号、提取辅助函数或重新组织模块
* **修复错误** – 让模型同时诊断问题并发出精确的补丁
* **测试和文档生成** – 创建新的测试文件、固定装置和文档
* **迁移和机械编辑** – 应用重复的、结构化的更新

> **安全警告**：应用补丁可能会修改您的代码库中的文件。请始终验证路径、实施备份并考虑沙盒执行。
> **注意**：此工具专为 `gpt-5.1` 模型设计。

```typescript theme={null}
import { ChatOpenAI, tools } from "@langchain/openai";
import { applyDiff } from "@openai/agents";
import * as fs from "fs/promises";

const model = new ChatOpenAI({ model: "gpt-5.1" });

// With execute callback for automatic patch handling
const patchTool = tools.applyPatch({
  execute: async (operation) => {
    if (operation.type === "create_file") {
      const content = applyDiff("", operation.diff, "create");
      await fs.writeFile(operation.path, content);
      return `Created ${operation.path}`;
    }
    if (operation.type === "update_file") {
      const current = await fs.readFile(operation.path, "utf-8");
      const newContent = applyDiff(current, operation.diff);
      await fs.writeFile(operation.path, newContent);
      return `Updated ${operation.path}`;
    }
    if (operation.type === "delete_file") {
      await fs.unlink(operation.path);
      return `Deleted ${operation.path}`;
    }
    return "Unknown operation type";
  },
});

const llmWithPatch = model.bindTools([patchTool]);
const response = await llmWithPatch.invoke(
  "Rename the fib() function to fibonacci() in lib/fib.py"
);
```

**操作类型**：模型返回具有这些属性的操作：

* `create_file` – 在 `path` 创建一个包含 `diff` 内容的新文件
* `update_file` – 使用 `diff` 中的 V4A 差异格式修改 `path` 中的现有文件
* `delete_file` – 删除 `path` 中的文件

**最佳实践**：

* **路径验证**：防止目录遍历并限制编辑到允许的目录
* **备份**：在应用补丁之前考虑备份文件
* **错误处理**：返回描述性错误消息，以便模型可以恢复
* **原子性**：决定您是否希望“全或无”语义（如果任何补丁失败则回滚）

更多信息，请参阅 [OpenAI 的应用补丁文档](https://platform.openai.com/docs/guides/tools-apply-patch)。

***

> 官方原文：[src/oss/javascript/integrations/tools/openai.mdx](https://github.com/langchain-ai/docs/blob/main/src/oss/javascript/integrations/tools/openai.mdx) · 非官方翻译，译文由 AI 生成，以英文原文为准。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.