> ## 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 通过 @langchain/openai 包与 OpenAI 和 Azure OpenAI 进行集成。

LangChain 通过 `@langchain/openai` 包与 OpenAI 和 Azure OpenAI 进行集成。

> [OpenAI](https://en.wikipedia.org/wiki/OpenAI) 是一家美国人工智能（AI）研究实验室，由非营利组织 `OpenAI Incorporated` 及其营利性子公司 `OpenAI Limited Partnership` 组成。OpenAI 以促进和发展友好型 AI 为宗旨进行 AI 研究。OpenAI 系统运行在 `Azure` 基于的超级计算平台上，由 `Microsoft` 提供。

> [OpenAI API](https://platform.openai.com/docs/models) 由一系列具有不同能力和价格点的模型驱动。

> [ChatGPT](https://chat.openai.com) 是由 `OpenAI` 开发的一个人工智能（AI）聊天机器人。

## 安装和设置

* 获取 OpenAI API 密钥并将其设置为环境变量（`OPENAI_API_KEY`）

## 对话模型

查看 [使用示例](https://langchain-docs-zh.mintlify.site/langchain/oss/javascript/integrations/chat/openai.md)。

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

## 大语言模型

查看 [使用示例](https://langchain-docs-zh.mintlify.site/langchain/oss/javascript/integrations/llms/openai.md)。

> [!TIP]
>
> 查看 [安装 LangChain 包的一般说明](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/install.md)。

```bash npm theme={null}
npm install @langchain/openai @langchain/core
```

```typescript theme={null}
import { OpenAI } from "@langchain/openai";
```

## 文本嵌入模型

查看 [使用示例](https://langchain-docs-zh.mintlify.site/langchain/oss/javascript/integrations/embeddings/openai.md)

```typescript theme={null}
import { OpenAIEmbeddings } from "@langchain/openai";
```

## 决策模型

为路由、分类和智能体中间件提供类型化答案和校准概率。查看 [使用示例](https://langchain-docs-zh.mintlify.site/langchain/oss/javascript/integrations/decision_models/openai.md)。

```typescript theme={null}
import { OpenAIDecisions } from "@langchain/openai";
```

## 链

```typescript theme={null}
import { OpenAIModerationChain } from "@langchain/classic/chains";
```

## 中间件

专为 OpenAI 模型设计的中间件。了解更多关于 [中间件](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/middleware/overview.md) 的信息。

| 中间件 | 描述 |
| - | - |
| [内容审核](#内容审核) | 使用 OpenAI 的审核端点审核智能体流量 |
| [模型路由](https://langchain-docs-zh.mintlify.site/langchain/oss/javascript/integrations/decision_models/openai.md#模型路由) | 使用 OpenAI 决策 API（预览版）将每个智能体运行路由到模型 |
| [工具风险网关](https://langchain-docs-zh.mintlify.site/langchain/oss/javascript/integrations/decision_models/openai.md#工具风险门控) | 使用 OpenAI 决策 API（预览版）阻止有风险的工具调用 |

### 内容审核

使用 OpenAI 的审核端点审核智能体流量（用户输入、模型输出和工具结果），以检测和处理不安全内容。内容审核适用于以下场景：

* 需要内容安全和合规的应用
* 过滤有害、仇恨或不适当的内容
* 需要安全护栏的客户面智能体
* 满足平台审核要求

> [!NOTE]
>
> 了解更多关于 [OpenAI 的审核模型](https://platform.openai.com/docs/guides/moderation) 和类别。

**API 参考:** @\[`openAIModerationMiddleware`]

```typescript theme={null}
import { createAgent, openAIModerationMiddleware } from "langchain";

const agent = createAgent({
  model: "openai:gpt-5.5",
  tools: [searchTool, databaseTool],
  middleware: [
    openAIModerationMiddleware({
      model: "openai:gpt-5.5",
      moderationModel: "omni-moderation-latest",
      checkInput: true,
      checkOutput: true,
      exitBehavior: "end",
    }),
  ],
});
```

> [accordion] Configuration options
>
> **model** `string | BaseChatModel` *required*
>
> 用于审核的 OpenAI 模型。可以是模型名称字符串（例如，`"openai:gpt-5.5"`）或 `BaseChatModel` 实例。中间件将使用此模型的客户端访问审核端点。
>
> **moderationModel** `ModerationModel` (default: omni-moderation-latest)
>
> 要使用的 OpenAI 审核模型。选项：`'omni-moderation-latest'`, `'omni-moderation-2024-09-26'`, `'text-moderation-latest'`, `'text-moderation-stable'`
>
> **checkInput** `boolean` (default: true)
>
> 在调用模型之前是否检查用户输入消息
>
> **checkOutput** `boolean` (default: true)
>
> 在调用模型后是否检查模型输出消息
>
> **checkToolResults** `boolean` (default: false)
>
> 在调用模型之前是否检查工具结果消息
>
> **exitBehavior** `'error' | 'end' | 'replace'` (default: 'end')
>
> 当内容被标记为违规时如何处理。选项：
>
> * `'end'` - 立即结束智能体执行并显示违规消息
> * `'error'` - 抛出 `OpenAIModerationError` 异常
> * `'replace'` - 用违规消息替换被标记的内容并继续
>
> **violationMessage** `string | undefined`
>
> 违规消息的自定义模板。支持模板变量：
>
> * `{categories}` - 被标记类别的逗号分隔列表
> * `{category_scores}` - 类别分数的 JSON 字符串
> * `{original_content}` - 原始被标记的内容
>
> 默认：`"I'm sorry, but I can't comply with that request. It was flagged for {categories}."`

> [accordion] Full example
>
> 该中间件集成了 OpenAI 的审核端点，在不同阶段检查内容：
>
> **审核阶段：**
>
> * `checkInput` - 调用模型前的用户消息
> * `checkOutput` - 调用模型后的 AI 消息
> * `checkToolResults` - 调用模型前的工具输出
>
> **退出行为：**
>
> * `'end'`（默认） - 带违规消息停止执行
> * `'error'` - 抛出异常供应用程序处理
> * `'replace'` - 替换被标记的内容并继续
>
> ```typescript theme={null}
> import { createAgent, openAIModerationMiddleware } from "langchain";
>
> // Basic moderation
> const agent = createAgent({
>   model: "openai:gpt-5.5",
>   tools: [searchTool, customerDataTool],
>   middleware: [
>     openAIModerationMiddleware({
>       model: "openai:gpt-5.5",
>       moderationModel: "omni-moderation-latest",
>       checkInput: true,
>       checkOutput: true,
>     }),
>   ],
> });
>
> // Strict moderation with custom message
> const agentStrict = createAgent({
>   model: "openai:gpt-5.5",
>   tools: [searchTool, customerDataTool],
>   middleware: [
>     openAIModerationMiddleware({
>       model: "openai:gpt-5.5",
>       moderationModel: "omni-moderation-latest",
>       checkInput: true,
>       checkOutput: true,
>       checkToolResults: true,
>       exitBehavior: "error",
>       violationMessage:
>         "Content policy violation detected: {categories}. " +
>         "Please rephrase your request.",
>     }),
>   ],
> });
>
> // Moderation with replacement behavior
> const agentReplace = createAgent({
>   model: "openai:gpt-5.5",
>   tools: [searchTool],
>   middleware: [
>     openAIModerationMiddleware({
>       model: "openai:gpt-5.5",
>       checkInput: true,
>       exitBehavior: "replace",
>       violationMessage: "[Content removed due to safety policies]",
>     }),
>   ],
> });
> ```

***

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


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