Skip to main content
OpenAI 是一个人工智能 (AI) 研究实验室。 本指南将帮助你开始使用 OpenAI chat models。有关所有 ChatOpenAI 功能和配置的详细文档,请前往 API 参考
Chat Completions API 兼容性ChatOpenAI is fully compatible with OpenAI’s (legacy) Chat Completions API. If you are looking to connect to other model providers that support the Chat Completions API, you can do so – see instructions.
托管在 Azure 上的 OpenAI 模型Note that certain OpenAI models can also be accessed via the Microsoft Azure platform.

概述

集成详情

模型功能

请参阅下表标题中的链接,了解如何使用特定功能。

设置

要访问 OpenAI 聊天模型,你需要创建一个 OpenAI 账户、获取 API 密钥并安装 @langchain/openai 集成包。

凭证

前往 OpenAI’s website 注册 OpenAI 并生成 API 密钥。完成后设置 OPENAI_API_KEY 环境变量:
如果你想要自动追踪模型调用,还可以设置你的 LangSmith API 密钥,取消注释以下内容:

安装

LangChain 的 ChatOpenAI 集成位于 @langchain/openai 包中:

实例化

现在我们可以实例化模型对象并生成聊天补全:

调用

自定义 URL

You can customize the base URL the SDK sends requests to by passing a configuration parameter like this:
The configuration field also accepts other ClientOptions parameters accepted by the official SDK. If you are hosting on Azure OpenAI, see the dedicated page instead.

自定义请求头

You can specify custom headers in the same configuration field:

禁用流式使用元数据

Some proxies or third-party providers present largely the same API interface as OpenAI, but don’t support the more recently added stream_options parameter to return streaming usage. You can use ChatOpenAI to access these providers by disabling streaming usage like this:

调用微调模型

You can call fine-tuned OpenAI models by passing in your corresponding modelName parameter. This generally takes the form of ft:{OPENAI_MODEL_NAME}:{ORG_NAME}::{MODEL_ID}. For example:

生成元数据

If you need additional information like logprobs or token usage, these will be returned directly in the invoke response within the response_metadata field on the message.
需要 @langchain/core 版本 >=0.1.48。

自定义工具

Custom tools support tools with arbitrary string inputs. They can be particularly useful when you expect your string arguments to be long or complex. If you use a model that supports custom tools, you can use the ChatOpenAI class and the customTool function to create a custom tool.

strict: true

As of Aug 6, 2024, OpenAI supports a strict argument when calling tools that will enforce that the tool argument schema is respected by the model. See more.
Requires @langchain/openai >= 0.2.6
If strict: true the tool definition will also be validated, and a subset of JSON schema are accepted. Crucially, schema cannot have optional args (those with default values). Read the full docs on what types of schema are supported.
Here’s an example with tool calling. Passing an extra strict: true argument to .bindTools will pass the param through to all tool definitions:
If you only want to apply this parameter to a select number of tools, you can also pass OpenAI formatted tool schemas directly:

结构化输出

We can also pass strict: true to the .withStructuredOutput(). Here’s an example:

Responses API

兼容性The below points apply to @langchain/openai>=0.4.5-rc.0.
OpenAI supports a Responses API that is oriented toward building agentic applications. It includes a suite of built-in tools, including web and file search. It also supports management of conversation state, allowing you to continue a conversational thread without explicitly passing in previous messages. ChatOpenAI will route to the Responses API if one of these features is used. You can also specify useResponsesApi: true when instantiating ChatOpenAI.

内置工具

Equipping ChatOpenAI with built-in tools will ground its responses with outside information, such as via context in files or the web. The AIMessage generated from the model will include information about the built-in tool invocation.

网络搜索

To trigger a web search, pass {"type": "web_search_preview"} to the model as you would another tool.
You can also pass built-in tools as invocation params:
Note that the response includes structured content blocks that include both the text of the response and OpenAI annotations citing its sources. The output message will also contain information from any tool invocations.

文件搜索

To trigger a file search, pass a file search tool to the model as you would another tool. You will need to populate an OpenAI-managed vector store and include the vector store ID in the tool definition. See OpenAI documentation for more details.
As with web search, the response will include content blocks with citations. It will also include information from the built-in tool invocations.

计算机使用

ChatOpenAI supports the computer-use-preview model, which is a specialized model for the built-in computer use tool. To enable, pass a computer use tool as you would pass another tool. Currently tool outputs for computer use are present in AIMessage.additional_kwargs.tool_outputs. To reply to the computer use tool call, you need to set additional_kwargs.type: "computer_call_output" while creating a corresponding ToolMessage. See OpenAI documentation for more details.

代码解释器

ChatOpenAI allows you to use the built-in code interpreter tool to support the sandboxed generation and execution of code.
Note that the above command creates a new container. We can reuse containers across calls by specifying an existing container ID.

远程 MCP

ChatOpenAI supports the built-in remote MCP tool that allows for model-generated calls to MCP servers to happen on OpenAI servers.
MCP ApprovalsWhen instructed, OpenAI will request approval before making calls to a remote MCP server.In the above command, we instructed the model to never require approval. We can also configure the model to always request approval, or to always request approval for specific tools:
With this configuration, responses can contain tool outputs typed as mcp_approval_request. To submit approvals for an approval request, you can structure it into a content block in a followup message:

图像生成

ChatOpenAI allows you to bring the built-in image generation tool to create images as apart of multi-turn conversations through the responses API.

推理模型

Compatibility: The below points apply to @langchain/openai>=0.4.0.
When using reasoning models like o1, the default method for withStructuredOutput is OpenAI’s built-in method for structured output (equivalent to passing method: "jsonSchema" as an option into withStructuredOutput). JSON schema mostly works the same as other models, but with one important caveat: when defining schema, z.optional() is not respected, and you should instead use z.nullable(). 以下是一个示例:
And here’s an example with z.nullable():

提示词缓存

Newer OpenAI models will automatically cache parts of your prompt if your inputs are above a certain size (1024 tokens at the time of writing) in order to reduce costs for use-cases that require long context. Note: The number of tokens cached for a given query is not yet standardized in AIMessage.usage_metadata, and is instead contained in the AIMessage.response_metadata field. Here’s an example

预测输出

Some OpenAI models (such as their gpt-4o and gpt-4o-mini series) support Predicted Outputs, which allow you to pass in a known portion of the LLM’s expected output ahead of time to reduce latency. This is useful for cases such as editing text or code, where only a small part of the model’s output will change. 以下是一个示例:
Note that currently predictions are billed as additional tokens and will increase your usage and costs in exchange for this reduced latency.

音频输出

Some OpenAI models (such as gpt-4o-audio-preview) support generating audio output. This example shows how to use that feature:
We see that the audio data is returned inside the data field. We are also provided an expires_at date field. This field represents the date the audio response will no longer be accessible on the server for use in multi-turn conversations.

流式音频输出

OpenAI also supports streaming audio output. Here’s an example:

音频输入

These models also support passing audio as input. For this, you must specify input_audio fields as seen below:

API 参考

有关所有 ChatOpenAI 功能和配置的详细文档,请前往 API 参考