> ## 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.

# ChatOpenAI 集成

> 使用 LangChain Python 集成 ChatOpenAI 对话模型。

您可以在 [OpenAI 平台](https://platform.openai.com) 文档中找到关于 OpenAI 最新模型、成本、上下文窗口以及支持的输入类型的信息。

> [!TIP]
>
> **API 参考**
>
> 关于所有功能和配置选项的详细文档，请访问 @\[`ChatOpenAI`] API 参考。

> [!WARNING]
>
> **API 范围**
>
> `ChatOpenAI` 仅针对 [官方 OpenAI API 规范](https://github.com/openai/openai-openapi)。来自第三方提供者的非标准响应字段（例如，`reasoning_content`、`reasoning`、`reasoning_details`）**不会被提取或保留**。如果您使用的是扩展了 Chat Completions 或 Responses 格式的提供者，例如 [OpenRouter](https://openrouter.ai/)、[LiteLLM](https://litellm.ai/)、[vLLM](https://docs.vllm.ai/) 或 [DeepSeek](https://api-docs.deepseek.com/)，请使用特定于提供者的包。详情请参阅 [Chat Completions API 兼容性](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/chat.md#chat-completions-api)。

## 概述

### 集成细节

| 类 | 包 | 可序列化 | 支持 JS/TS | 下载量 | 最新版本 |
| :- | :- | :-: | :-: | :-: | :-: |
| @\[`ChatOpenAI`] | @\[`langchain-openai`] | beta | ✅ [(npm)](https://langchain-docs-zh.mintlify.site/langchain/oss/javascript/integrations/chat/openai.md) | [![Downloads per month](https://static.pepy.tech/badge/langchain-openai/month)](https://pypi.org/project/langchain-openai/) | [![PyPI - Latest version](https://img.shields.io/pypi/v/langchain-openai?style=flat-square\&label=%20\&color=orange)](https://pypi.org/project/langchain-openai/) |

### 模型特性

| [工具调用](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/tools.md) | [结构化输出](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/structured-output.md) | 图像输入 | 音频输入 | 视频输入 | Token [级流式输出](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/streaming.md) | 原生异步 | Token [使用量](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/models.md#token-使用) | [Logprobs](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/models.md#对数概率) |
| :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: |
| ✅ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ |

## 设置

要访问 OpenAI 模型，您需要安装 `langchain-openai` 集成包并获取一个 [OpenAI 平台](https://platform.openai.com) API 密钥。

### 安装

```bash pip theme={null}
pip install -U langchain-openai
```

```bash uv theme={null}
uv add langchain-openai
```

### 凭证

前往 [OpenAI 平台](https://platform.openai.com/docs/api-reference/authentication) 注册并生成 API 密钥。完成后，在您的环境中设置 `OPENAI_API_KEY` 环境变量：

```python theme={null}
import getpass
import os

if not os.environ.get("OPENAI_API_KEY"):
    os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter your OpenAI API key: ")
```

如果您通过代理或服务模拟器路由请求，可以通过环境变量设置基础 URL，而不是传递 `base_url`。解析顺序（第一个匹配的优先）：

1. 显式 `base_url`（或 `openai_api_base`）参数。
2. `OPENAI_API_BASE` — 由 LangChain 在初始化时读取。
3. `OPENAI_BASE_URL` — 由底层 `openai` SDK 客户端读取。LangChain 也会检查此值以决定是否默认启用 `stream_usage`；当设置时，默认关闭，因为许多非 OpenAI 端点不支持流式 Token 使用。

如果您想自动跟踪您的模型调用，您还可以设置您的 [LangSmith](https://docs.langchain.com/langsmith/observability) API 密钥：

```python theme={null}
os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
os.environ["LANGSMITH_TRACING"] = "true"
```

## 实例化

现在我们可以实例化我们的模型对象并生成响应：

```python theme={null}
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="gpt-5-nano",
    # stream_usage=True,
    # temperature=None,
    # max_tokens=None,
    # timeout=None,
    # reasoning_effort="low",
    # max_retries=2,
    # api_key="...",  # If you prefer to pass api key in directly
    # base_url="...",
    # organization="...",
    # other params...
)
```

有关可用模型参数的完整集，请参阅 @\[`ChatOpenAI`] API 参考。

> [!NOTE]
>
> **Token 参数弃用**
>
> OpenAI 于 2024 年 9 月弃用 `max_tokens`，改为使用 `max_completion_tokens`。`max_tokens` 仍然支持以向后兼容，但内部会自动转换为 `max_completion_tokens`。

***

## 调用

```python theme={null}
messages = [
    (
        "system",
        "You are a helpful assistant that translates English to French. Translate the user sentence.",
    ),
    ("human", "I love programming."),
]
ai_msg = llm.invoke(messages)
ai_msg
```

```text theme={null}
AIMessage(content="J'adore la programmation.", additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 5, 'prompt_tokens': 31, 'total_tokens': 36}, 'model_name': 'gpt-4o-2024-05-13', 'system_fingerprint': 'fp_3aa7262c27', 'finish_reason': 'stop', 'logprobs': None}, id='run-63219b22-03e3-4561-8cc4-78b7c7c3a3ca-0', usage_metadata={'input_tokens': 31, 'output_tokens': 5, 'total_tokens': 36})
```

```python theme={null}
print(ai_msg.text)
```

```text theme={null}
J'adore la programmation.
```

***

## 流式输出元数据

OpenAI 的 Chat Completions API 默认不流式传输 Token 使用统计信息（请参阅 [OpenAI API 参考中关于流式选项](https://platform.openai.com/docs/api-reference/completions/create#completions-create-stream_options)）。

要在使用 @\[`ChatOpenAI`] 或 `AzureChatOpenAI` 流式传输时恢复 Token 计数，将 `stream_usage=True` 作为初始化参数或在调用时设置：

```python theme={null}
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-5.4-mini", stream_usage=True)  # [!code highlight]
```

***

## 与 Azure OpenAI 一起使用

> [!NOTE]
>
> **Azure OpenAI v1 API 支持**
>
> 自 `langchain-openai>=1.0.1` 起，`ChatOpenAI` 可以直接与 Azure OpenAI 端点使用新的 [v1 API](https://learn.microsoft.com/en-us/azure/ai-foundry/openai/api-version-lifecycle?tabs=python#next-generation-api-1)。这提供了一种统一的方式来使用 OpenAI 模型，无论其是否托管在 OpenAI 或 Azure 上。
>
> 对于传统的 Azure 特定实现，请继续使用 [`AzureChatOpenAI`](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/chat/azure_chat_openai/)。

> [accordion] Using Azure OpenAI v1 API with API Key
>
> 要使用 `ChatOpenAI` 与 Azure OpenAI 一起使用，将 `base_url` 设置为您的 Azure 端点，并附加 `/openai/v1/`：
>
> ```python theme={null}
> from langchain_openai import ChatOpenAI
>
> llm = ChatOpenAI(
>     model="gpt-5-mini",  # Your Azure deployment name
>     base_url="https://{your-resource-name}.openai.azure.com/openai/v1/",
>     api_key="your-azure-api-key"
> )
>
> response = llm.invoke("Hello, how are you?")
> print(response.content)
> ```

> [accordion] Using Azure OpenAI with Microsoft Entra ID
>
> v1 API 添加了对 [Microsoft Entra ID](https://learn.microsoft.com/en-us/azure/ai-foundry/openai/how-to/managed-identity)（以前称为 Azure AD）认证的原生支持，并自动刷新 Token。将一个 Token 提供者可调用对象传递给 `api_key` 参数：
>
> ```python theme={null}
> from azure.identity import DefaultAzureCredential, get_bearer_token_provider
> from langchain_openai import ChatOpenAI
>
> # Create a token provider that handles automatic refresh
> token_provider = get_bearer_token_provider(
>     DefaultAzureCredential(),
>     "https://cognitiveservices.azure.com/.default"
> )
>
> llm = ChatOpenAI(
>     model="gpt-5-mini",  # Your Azure deployment name
>     base_url="https://{your-resource-name}.openai.azure.com/openai/v1/",
>     api_key=token_provider  # Callable that handles token refresh
> )
>
> # Use the model as normal
> messages = [
>     ("system", "You are a helpful assistant."),
>     ("human", "Translate 'I love programming' to French.")
> ]
> response = llm.invoke(messages)
> print(response.content)
> ```
>
> Token 提供者是一个可调用对象，它自动检索和刷新认证 Token，无需手动管理 Token 过期。
>
> > [!TIP]
> >
> > **安装要求**
> >
> > 要使用 Microsoft Entra ID 认证，请安装 Azure Identity 库：
> >
> > ```bash theme={null}
> > pip install azure-identity
> > ```
>
> 在使用异步函数时，您也可以将一个 Token 提供者可调用对象传递给 `api_key` 参数。您必须从 `azure.identity.aio` 导入 DefaultAzureCredential：
>
> ```python theme={null}
> from azure.identity.aio import DefaultAzureCredential
> from langchain_openai import ChatOpenAI
>
> credential = DefaultAzureCredential()
>
> llm_async = ChatOpenAI(
>     model="gpt-5-nano",
>     api_key=credential
> )
>
> # Use async methods when using async callable
> response = await llm_async.ainvoke("Hello!")
> ```
>
> > [!NOTE]
> >
> > 当使用异步可调用对象作为 API 密钥时，您必须使用异步方法（`ainvoke`、`astream` 等）。同步方法将引发错误。

***

## 工具调用

OpenAI 有一个 [工具调用](https://platform.openai.com/docs/guides/function-calling) API，它允许您描述工具及其参数，并让模型返回一个包含要调用的工具及其输入的 JSON 对象。工具调用对于构建使用工具的链和智能体非常有用，并且可以更通用地从模型中获取结构化输出。

### 绑定工具

使用 `ChatOpenAI.bind_tools`，我们可以轻松地将 Pydantic 类、字典模式、LangChain 工具甚至函数作为工具传递给模型。底层这些会被转换为 OpenAI 工具模式，如下所示：

```
{
    "name": "...",
    "description": "...",
    "parameters": {...}  # JSONSchema
}
```

...并且会在每个模型调用中传递。

```python theme={null}
from pydantic import BaseModel, Field


class GetWeather(BaseModel):
    """Get the current weather in a given location"""

    location: str = Field(description="The city and state, e.g. San Francisco, CA")


llm_with_tools = llm.bind_tools([GetWeather])
```

```python theme={null}
ai_msg = llm_with_tools.invoke(
    "what is the weather like in San Francisco",
)
ai_msg
```

```text theme={null}
AIMessage(content='', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 17, 'prompt_tokens': 68, 'total_tokens': 85}, 'model_name': 'gpt-4o-2024-05-13', 'system_fingerprint': 'fp_3aa7262c27', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-1617c9b2-dda5-4120-996b-0333ed5992e2-0', tool_calls=[{'name': 'GetWeather', 'args': {'location': 'San Francisco, CA'}, 'id': 'call_o9udf3EVOWiV4Iupktpbpofk', 'type': 'tool_call'}], usage_metadata={'input_tokens': 68, 'output_tokens': 17, 'total_tokens': 85})
```

### 严格模式

> [!NOTE]
>
> **需要 `langchain-openai>=0.1.21`**

自 2024 年 8 月 6 日起，OpenAI 在调用工具时支持一个 `strict` 参数，这将强制模型遵守工具参数模式。[了解更多](https://platform.openai.com/docs/guides/function-calling)。

> [!NOTE]
>
> 如果 `strict=True`，工具定义也会被验证，并且接受 JSON schema 的子集。关键在于，schema 不能有可选参数（那些带有默认值的）。
>
> 阅读 [完整文档](https://developers.openai.com/api/docs/guides/structured-outputs#supported-schemas) 了解支持哪些类型的 schema。

```python theme={null}
llm_with_tools = llm.bind_tools([GetWeather], strict=True)
ai_msg = llm_with_tools.invoke(
    "what is the weather like in San Francisco",
)
ai_msg
```

```text theme={null}
AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_jUqhd8wzAIzInTJl72Rla8ht', 'function': {'arguments': '{"location":"San Francisco, CA"}', 'name': 'GetWeather'}, 'type': 'function'}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 17, 'prompt_tokens': 68, 'total_tokens': 85}, 'model_name': 'gpt-4o-2024-05-13', 'system_fingerprint': 'fp_3aa7262c27', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-5e3356a9-132d-4623-8e73-dd5a898cf4a6-0', tool_calls=[{'name': 'GetWeather', 'args': {'location': 'San Francisco, CA'}, 'id': 'call_jUqhd8wzAIzInTJl72Rla8ht', 'type': 'tool_call'}], usage_metadata={'input_tokens': 68, 'output_tokens': 17, 'total_tokens': 85})
```

### 工具调用

注意 AIMessage 有一个 `tool_calls` 属性。它以标准化的 ToolCall 格式包含内容，该格式与模型提供者无关。

```python theme={null}
ai_msg.tool_calls
```

```text theme={null}
[{'name': 'GetWeather',
  'args': {'location': 'San Francisco, CA'},
  'id': 'call_jUqhd8wzAIzInTJl72Rla8ht',
  'type': 'tool_call'}]
```

有关绑定工具和工具调用输出的更多信息，请查看 [工具调用](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/tools.md) 文档。

### 异步工具

[异步工具调用](https://developers.openai.com/api/docs/guides/async-tool-calling) 允许模型在发出工具调用后继续工作，而无需等待结果。在使用 Responses API 时，`ChatOpenAI` 通过将 `extras={"async": True}` 传递给 `@tool` 来支持这一点：

```python theme={null}
from langchain.tools import tool

@tool(extras={"async": True})  # [!code highlight]
def lookup_price(sku: str) -> str:
    """Look up the price of a product."""
    return "1200"
```

> [!NOTE]
>
> 异步工具仅通过 Responses API（`use_responses_api=True`）支持。`async` 标志通过消息历史来回传递，以便在回合之间保持提示缓存前缀的完整性。

### 自定义工具

> [!NOTE]
>
> **需要 `langchain-openai>=0.3.29`**

[自定义工具](https://platform.openai.com/docs/guides/function-calling#custom-tools) 支持具有任意字符串输入的工具。当您预期字符串参数会很长或很复杂时，它们特别有用。

```python theme={null}
from langchain_openai import ChatOpenAI, custom_tool
from langchain.agents import create_agent


@custom_tool
def execute_code(code: str) -> str:
    """Execute python code."""
    return "27"


llm = ChatOpenAI(model="gpt-5.5", use_responses_api=True)

agent = create_agent(llm, [execute_code])

input_message = {"role": "user", "content": "Use the tool to calculate 3^3."}
stream = agent.stream_events(
    {"messages": [input_message]},
    version="v3",
)
for snapshot in stream.values:
    snapshot["messages"][-1].pretty_print()
```

```text theme={null}
================================ Human Message =================================

Use the tool to calculate 3^3.
================================== Ai Message ==================================

[{'id': 'rs_68b7336cb72081a080da70bf5e980e4e0d6082d28f91357a', 'summary': [], 'type': 'reasoning'}, {'call_id': 'call_qyKsJ4XlGRudbIJDrXVA2nQa', 'input': 'print(3**3)', 'name': 'execute_code', 'type': 'custom_tool_call', 'id': 'ctc_68b7336f718481a0b39584cd35fbaa5d0d6082d28f91357a', 'status': 'completed'}]
Tool Calls:
  execute_code (call_qyKsJ4XlGRudbIJDrXVA2nQa)
 Call ID: call_qyKsJ4XlGRudbIJDrXVA2nQa
  Args:
    __arg1: print(3**3)
================================= Tool Message =================================
Name: execute_code

[{'type': 'custom_tool_call_output', 'output': '27'}]
================================== Ai Message ==================================

[{'type': 'text', 'text': '27', 'annotations': [], 'id': 'msg_68b73371e9e081a0927f54f88f2cd7a20d6082d28f91357a'}]
```

> [accordion] Context-free grammars
>
> OpenAI 支持在 `lark` 或 `regex` 格式中为自定义工具输入指定一个 [无上下文语法](https://platform.openai.com/docs/guides/function-calling#context-free-grammars)。有关详细信息，请参阅 [OpenAI 文档](https://platform.openai.com/docs/guides/function-calling#context-free-grammars)。`format` 参数可以像下面这样传递给 `@custom_tool`：
>
> ```python theme={null}
> from langchain_openai import ChatOpenAI, custom_tool
> from langchain.agents import create_agent
>
>
> grammar = """
> start: expr
> expr: term (SP ADD SP term)* -> add
> | term
> term: factor (SP MUL SP factor)* -> mul
> | factor
> factor: INT
> SP: " "
> ADD: "+"
> MUL: "*"
> %import common.INT
> """
>
> format_ = {"type": "grammar", "syntax": "lark", "definition": grammar}
>
>
> @custom_tool(format=format_)  # [!code highlight]
> def do_math(input_string: str) -> str:
>     """Do a mathematical operation."""
>     return "27"
>
>
> llm = ChatOpenAI(model="gpt-5.5", use_responses_api=True)
>
> agent = create_agent(llm, [do_math])
>
> input_message = {"role": "user", "content": "Use the tool to calculate 3^3."}
> stream = agent.stream_events(
>     {"messages": [input_message]},
>     version="v3",
> )
> for snapshot in stream.values:
>     snapshot["messages"][-1].pretty_print()
> ```
>
> ```text theme={null}
> ================================ Human Message =================================
>
> Use the tool to calculate 3^3.
> ================================== Ai Message ==================================
>
> [{'id': 'rs_68b733f066a48194a41001c0cc1081760811f11b6f4bae47', 'summary': [], 'type': 'reasoning'}, {'call_id': 'call_7hTYtlTj9NgWyw8AQGqETtV9', 'input': '3 * 3 * 3', 'name': 'do_math', 'type': 'custom_tool_call', 'id': 'ctc_68b733f3a0a08194968b8338d33ad89f0811f11b6f4bae47', 'status': 'completed'}]
> Tool Calls:
>   do_math (call_7hTYtlTj9NgWyw8AQGqETtV9)
>  Call ID: call_7hTYtlTj9NgWyw8AQGqETtV9
>   Args:
>     __arg1: 3 * 3 * 3
> ================================= Tool Message =================================
> Name: do_math
>
> [{'type': 'custom_tool_call_output', 'output': '27'}]
> ================================== Ai Message ==================================
>
> [{'type': 'text', 'text': '27', 'annotations': [], 'id': 'msg_68b733f4bb008194937130796372bd0f0811f11b6f4bae47'}]
> ```

***

## 结构化输出

OpenAI 支持一种原生的 [结构化输出功能](https://platform.openai.com/docs/guides/structured-outputs)，该功能确保其响应符合指定的模式。

您可以在单个模型调用中访问此功能，或通过指定 LangChain [智能体](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/agents.md)的 [响应格式](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/structured-output.md) 来使用此功能。以下为示例。

> [accordion] Individual model calls
>
> 使用 [`with_structured_output`](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/models#结构化输出) 方法生成结构化模型响应。指定 `method="json_schema"` 以启用 OpenAI 的原生结构化输出功能；否则该方法默认使用函数调用。
>
> ```python theme={null}
> from langchain_openai import ChatOpenAI
> from pydantic import BaseModel, Field
>
> llm = ChatOpenAI(model="gpt-5.5")
>
> class Movie(BaseModel):
>     """A movie with details."""
>     title: str = Field(description="The title of the movie")
>     year: int = Field(description="The year the movie was released")
>     director: str = Field(description="The director of the movie")
>     rating: float = Field(description="The movie's rating out of 10")
>
> structured_llm = llm.with_structured_output(Movie, method="json_schema")  # [!code highlight]
> response = structured_llm.invoke("Provide details about the movie Inception")
> response
> ```
>
> ```python theme={null}
> Movie(title='Inception', year=2010, director='Christopher Nolan', rating=8.8)
> ```

> [accordion] Agent response format
>
> 使用 [`ProviderStrategy`](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/structured-output) 指定 `response_format`，在生成最终响应时启用 OpenAI 的结构化输出功能。
>
> ```python theme={null}
> from langchain.agents import create_agent
> from langchain.agents.structured_output import ProviderStrategy
> from pydantic import BaseModel
>
> class Weather(BaseModel):
>     temperature: float
>     condition: str
>
> def weather_tool(location: str) -> str:
>     """Get the weather at a location."""
>     return "Sunny and 75 degrees F."
>
> agent = create_agent(
>     model="openai:gpt-5.5",
>     tools=[weather_tool],
>     response_format=ProviderStrategy(Weather),  # [!code highlight]
> )
>
> result = agent.invoke({
>     "messages": [{"role": "user", "content": "What's the weather in SF?"}]
> })
>
> result["structured_response"]
> ```
>
> ```python theme={null}
> Weather(temperature=75.0, condition='Sunny')
> ```

### 带工具调用的结构化输出

OpenAI 的 [结构化输出](https://platform.openai.com/docs/guides/structured-outputs) 功能可以与工具调用同时使用。模型将生成工具调用或符合预期模式的响应。以下为示例：

```python theme={null}
from langchain_openai import ChatOpenAI
from pydantic import BaseModel


def get_weather(location: str) -> None:
    """Get weather at a location."""
    return "It's sunny."


class OutputSchema(BaseModel):
    """Schema for response."""

    answer: str
    justification: str


llm = ChatOpenAI(model="gpt-5.5")

structured_llm = llm.bind_tools(
    [get_weather],
    response_format=OutputSchema,
    strict=True,
)

# Response contains tool calls:
tool_call_response = structured_llm.invoke("What is the weather in SF?")

# structured_response.additional_kwargs["parsed"] contains parsed output
structured_response = structured_llm.invoke(
    "What weighs more, a pound of feathers or a pound of gold?"
)
```

***

## 响应 API

> [!NOTE]
>
> **需要 `langchain-openai>=0.3.9`**

OpenAI 支持一个面向构建 [智能体](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/agents.md) 应用的 [响应](https://platform.openai.com/docs/guides/responses-vs-chat-completions) API。它包含一套 [内置工具](https://platform.openai.com/docs/guides/tools?api-mode=responses)，包括网络和文件搜索。它还支持 [对话状态](https://platform.openai.com/docs/guides/conversation-state?api-mode=responses) 的管理，允许您在不明确传递先前消息的情况下继续对话线程，以及 [推理过程](https://platform.openai.com/docs/guides/reasoning?api-mode=responses) 的输出。

@\[`ChatOpenAI`] 将路由到响应 API，如果使用这些功能之一。您也可以在实例化 @\[`ChatOpenAI`] 时指定 `use_responses_api=True`。

### 网络搜索

要触发网络搜索，将 `{"type": "web_search"}` 作为其他工具一样传递给模型。

> [!TIP]
>
> **您还可以将内置工具作为调用参数传递：**
>
> ```python theme={null}
> llm.invoke("...", tools=[{"type": "web_search"}])
> ```

```python theme={null}
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-5.4-mini")

tool = {"type": "web_search"}
llm_with_tools = llm.bind_tools([tool])

response = llm_with_tools.invoke("What was a positive news story from today?")
```

请注意，响应包含结构化的 [内容块](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/messages.md#消息内容)，其中既包含响应文本，也包含 OpenAI [注释](https://platform.openai.com/docs/guides/tools-web-search?api-mode=responses#output-and-citations)，引用其来源。输出消息还将包含任何工具调用的信息：

```python theme={null}
response.content_blocks
```

```text theme={null}
[{'type': 'server_tool_call',
  'name': 'web_search',
  'args': {'query': 'positive news stories today', 'type': 'search'},
  'id': 'ws_68cd6f8d72e4819591dab080f4b0c340080067ad5ea8144a'},
 {'type': 'server_tool_result',
  'tool_call_id': 'ws_68cd6f8d72e4819591dab080f4b0c340080067ad5ea8144a',
  'status': 'success'},
 {'type': 'text',
  'text': 'Here are some positive news stories from today...',
  'annotations': [{'end_index': 410,
    'start_index': 337,
    'title': 'Positive News | Real Stories. Real Positive Impact',
    'type': 'citation',
    'url': 'https://www.positivenews.press/?utm_source=openai'},
   {'end_index': 969,
    'start_index': 798,
    'title': "From Green Innovation to Community Triumphs: Uplifting US Stories Lighting Up September 2025 | That's Great News",
    'type': 'citation',
    'url': 'https://info.thatsgreatnews.com/from-green-innovation-to-community-triumphs-uplifting-us-stories-lighting-up-september-2025/?utm_source=openai'},
  'id': 'msg_68cd6f8e8d448195a807b89f483a1277080067ad5ea8144a'}]
```

> [!TIP]
>
> **您可以通过使用 `response.text` 仅恢复响应的文本内容作为字符串。例如，要流式传输响应文本：**
>
> ```python theme={null}
> stream = llm_with_tools.stream_events("...", version="v3")
> for token in stream.text:
>     print(token, end="|")
> ```
>
> 有关更多详细信息，请参阅 [流式传输指南](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/streaming.md)。

### 图像生成

> [!NOTE]
>
> **需要 `langchain-openai>=0.3.19`**

要触发图像生成，将 `{"type": "image_generation"}` 作为其他工具一样传递给模型。

> [!TIP]
>
> 您还可以将内置工具作为调用参数传递：
>
> ```python theme={null}
> llm.invoke("...", tools=[{"type": "image_generation"}])
> ```

```python theme={null}
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-5.4-mini")

tool = {"type": "image_generation", "quality": "low"}

llm_with_tools = llm.bind_tools([tool])

ai_message = llm_with_tools.invoke(
    "Draw a picture of a cute fuzzy cat with an umbrella"
)
```

```python theme={null}
import base64

from IPython.display import Image

image = next(
    item for item in ai_message.content_blocks if item["type"] == "image"
)
Image(base64.b64decode(image["base64"]), width=200)
```

![](https://mintlify.s3.us-west-1.amazonaws.com/langchain-docs-zh/images/cat.png)

### 文件搜索

要触发文件搜索，将 [文件搜索工具](https://platform.openai.com/docs/guides/tools-file-search) 作为其他工具一样传递给模型。您需要填充 OpenAI 管理的向量存储，并在工具定义中包含向量存储 ID。有关更多详细信息，请参阅 [OpenAI 文档](https://platform.openai.com/docs/guides/tools-file-search)。

```python theme={null}
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="gpt-5.4-mini",
    include=["file_search_call.results"],  # optionally include search results
)

openai_vector_store_ids = [
    "vs_...",  # your IDs here
]

tool = {
    "type": "file_search",
    "vector_store_ids": openai_vector_store_ids,
}
llm_with_tools = llm.bind_tools([tool])

response = llm_with_tools.invoke("What is deep research by OpenAI?")
print(response.text)
```

```text theme={null}
Deep Research by OpenAI is...
```

与 [网络搜索](#网络搜索) 类似，响应将包含带有引用的内容块：

```python theme={null}
[block["type"] for block in response.content_blocks]
```

```python theme={null}
['server_tool_call', 'server_tool_result', 'text']
```

```python theme={null}
text_block = next(block for block in response.content_blocks if block["type"] == "text")

text_block["annotations"][:2]
```

```text theme={null}
[{'type': 'citation',
  'title': 'deep_research_blog.pdf',
  'extras': {'file_id': 'file-3UzgX7jcC8Dt9ZAFzywg5k', 'index': 2712}},
 {'type': 'citation',
  'title': 'deep_research_blog.pdf',
  'extras': {'file_id': 'file-3UzgX7jcC8Dt9ZAFzywg5k', 'index': 2712}}]
```

它还将包含内置工具调用的信息：

```python theme={null}
response.content_blocks[0]
```

```text theme={null}
{'type': 'server_tool_call',
 'name': 'file_search',
 'id': 'fs_68cd704c191c81959281b3b2ec6b139908f8f7fb31b1123c',
 'args': {'queries': ['deep research by OpenAI']}}
```

### 工具搜索

> [!NOTE]
>
> 需要 `langchain-openai>=1.1.11`

OpenAI 支持一个 [工具搜索](https://developers.openai.com/api/docs/guides/tools-tool-search/) 功能，允许模型根据需要搜索并加载工具到其上下文中。OpenAI 将检索到的工具定义注入到活动上下文的末尾以保留其 [缓存](#提示缓存)。

要启用工具搜索，请使用 `@tool(extras={"defer_loading": True})` 标记工具，并将 OpenAI 的搜索工具添加到可用工具中。下方提供了示例。

> [accordion] Server-side tool search
>
> OpenAI 可以跨可用工具进行搜索，并在同一响应中返回加载的工具（如果适用，则附带工具调用）：
>
> ```python theme={null}
> @tool(extras={"defer_loading": True})  # [!code highlight]
> def get_weather(location: str) -> str:
>     """Get the current weather for a location."""
>     return f"The weather in {location} is sunny and 72°F"
>
> @tool(extras={"defer_loading": True})  # [!code highlight]
> def get_recipe(query: str) -> None:
>     """Get a recipe for chicken soup."""
>
> model = ChatOpenAI(model="gpt-5.5", use_responses_api=True)
>
> agent = create_agent(
>     model=model,
>     tools=[
>         get_weather,
>         get_recipe,
>         {"type": "tool_search"}  # [!code highlight]
>     ],
> )
> input_message = {"role": "user", "content": "What's the weather in San Francisco?"}
> result = agent.invoke({"messages": [input_message]})
>
> for message in result["messages"]:
>     message.pretty_print()
> ```
>
> ```Result expandable theme={null}
> ================================ Human Message =================================
>
> What's the weather in San Francisco?
> ================================== Ai Message ==================================
>
> [
>   {
>     "id": "tsc_0667642bae2ae6c70069ad6cb31f0c819c838b18b0e1cf1279",
>     "arguments": {
>       "paths": [
>         "get_weather"
>       ]
>     },
>     "execution": "server",
>     "status": "completed",
>     "type": "tool_search_call"
>   },
>   {
>     "id": "tso_0667642bae2ae6c70069ad6cb339dc819c9bbc05cb432f347e",
>     "execution": "server",
>     "status": "completed",
>     "tools": [
>       {
>         "name": "get_weather",
>         "parameters": {
>           "properties": {
>             "location": {
>               "type": "string"
>             }
>           },
>           "required": [
>             "location"
>           ],
>           "type": "object",
>           "additionalProperties": false
>         },
>         "strict": true,
>         "type": "function",
>         "defer_loading": true,
>         "description": "Get the current weather for a location."
>       }
>     ],
>     "type": "tool_search_output"
>   },
>   {
>     "arguments": "{\"location\":\"San Francisco\"}",
>     "call_id": "call_nwy9NDI24fTe8qESIRqZGtYm",
>     "name": "get_weather",
>     "type": "function_call",
>     "id": "fc_0667642bae2ae6c70069ad6cb37adc819cbc55cde85e111e32",
>     "namespace": "get_weather",
>     "status": "completed"
>   }
> ]
> Tool Calls:
>   get_weather (call_nwy9NDI24fTe8qESIRqZGtYm)
>  Call ID: call_nwy9NDI24fTe8qESIRqZGtYm
>   Args:
>     location: San Francisco
> ================================= Tool Message =================================
> Name: get_weather
>
> The weather in San Francisco is sunny and 72°F
> ================================== Ai Message ==================================
>
> [
>   {
>     "type": "text",
>     "text": "It\u2019s currently sunny and 72\u00b0F in San Francisco.",
>     "annotations": [],
>     "id": "msg_0667642bae2ae6c70069ad6cb4829c819c8e26bc7ccc68dcd7"
>   }
> ]
> ```

> [accordion] Client-executed tool search
>
> 要完全控制底层的工具搜索过程，您可以在搜索工具定义中指定 `"execution": "client"`。如果模型选择搜索工具，它将在其响应中包含一个 `tool_search_call` 块。然后，您可以提供一个 `tool_search_output` 块，其中包含工具定义。
>
> 以下示例展示了如何使用 [自定义中间件](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/middleware/custom.md) 来协调此操作。该示例实现了一个定义搜索逻辑的可调用对象。中间件然后包括：
>
> 1. 一个 `after_model` 钩子，用于检查 `tool_search_call` 块并调用我们的可调用对象
> 2. 一个 `wrap_tool_call` 钩子用于 [运行时工具注册](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/tools.md#动态工具选择)
>
> ```python theme={null}
> @tool
> def get_weather(location: str) -> str:
>     """Get the current weather for a location."""
>     return f"The weather in {location} is sunny and 72°F"
>
> # Implement a callable that returns a tool definition
> def search_tools(goal: str) -> list[dict]:
>     """Search for available tools to help answer the question."""
>     # Arbitrary logic here
>     return [
>         {
>             "type": "function",
>             "defer_loading": True,
>             **convert_to_openai_tool(get_weather)["function"],
>         }
>     ]
>
> tool_search_schema = convert_to_openai_tool(search_tools, strict=True)
> tool_search_config: dict = {
>     "type": "tool_search",
>     "execution": "client",
>     "description": tool_search_schema["function"]["description"],
>     "parameters": tool_search_schema["function"]["parameters"],
> }
>
> # Implement middleware to invoke the callable and register the tool.
> class ClientToolSearchMiddleware(AgentMiddleware):
>
>     @hook_config(can_jump_to=["model"])
>     def after_model(self, state: AgentState, runtime: Any) -> dict[str, Any] | None:
>         last_message = state["messages"][-1]
>         if not isinstance(last_message, AIMessage):
>             return None
>         for block in last_message.content:
>             if isinstance(block, dict) and block.get("type") == "tool_search_call":
>                 call_id = block.get("call_id")
>                 args = block.get("arguments", {})
>                 goal = args.get("goal", "") if isinstance(args, dict) else ""
>                 loaded_tools = search_tools(goal)
>                 tool_search_output = {
>                     "type": "tool_search_output",
>                     "execution": "client",
>                     "call_id": call_id,
>                     "status": "completed",
>                     "tools": loaded_tools,
>                 }
>                 return {
>                     "messages": [HumanMessage(content=[tool_search_output])],
>                     "jump_to": "model",
>                 }
>         return None
>
>     def wrap_tool_call(
>         self,
>         request: ToolCallRequest,
>         handler: Any,
>     ) -> Any:
>         if request.tool_call["name"] == "get_weather":
>             return handler(request.override(tool=get_weather))
>         return handler(request)
>
> llm = ChatOpenAI(model="gpt-5.5", use_responses_api=True)
>
> agent = create_agent(
>     model=llm,
>     tools=[tool_search_config],
>     middleware=[ClientToolSearchMiddleware()],
> )
>
> result = agent.invoke(
>     {"messages": [HumanMessage("What's the weather in San Francisco?")]}
> )
>
> for message in result["messages"]:
>     message.pretty_print()
> ```
>
> ```Result expandable theme={null}
> ================================ Human Message =================================
>
> What's the weather in San Francisco?
> ================================== Ai Message ==================================
>
> [
>   {
>     "id": "tsc_0311ca847e392d540069acdd40394c8196a99345e2992eb657",
>     "arguments": {
>       "goal": "Find available tool(s) or weather capability to get current weather for San Francisco."
>     },
>     "call_id": "call_EcvKsh3r9IamaBW4Zz9r7RiK",
>     "execution": "client",
>     "status": "completed",
>     "type": "tool_search_call"
>   }
> ]
> ================================ Human Message =================================
>
> [
>   {
>     "type": "tool_search_output",
>     "execution": "client",
>     "call_id": "call_EcvKsh3r9IamaBW4Zz9r7RiK",
>     "status": "completed",
>     "tools": [
>       {
>         "type": "function",
>         "defer_loading": true,
>         "name": "get_weather",
>         "description": "Get the current weather for a location.",
>         "parameters": {
>           "properties": {
>             "location": {
>               "type": "string"
>             }
>           },
>           "required": [
>             "location"
>           ],
>           "type": "object"
>         }
>       }
>     ]
>   }
> ]
> ================================== Ai Message ==================================
>
> [
>   {
>     "arguments": "{\"location\":\"San Francisco\"}",
>     "call_id": "call_wH09dZpqDoVtpeu7uBdvY91l",
>     "name": "get_weather",
>     "type": "function_call",
>     "id": "fc_0311ca847e392d540069acdd41502881968b29d96840633746",
>     "namespace": "get_weather",
>     "status": "completed"
>   }
> ]
> Tool Calls:
>   get_weather (call_wH09dZpqDoVtpeu7uBdvY91l)
>  Call ID: call_wH09dZpqDoVtpeu7uBdvY91l
>   Args:
>     location: San Francisco
> ================================= Tool Message =================================
> Name: get_weather
>
> The weather in San Francisco is sunny and 72°F
> ================================== Ai Message ==================================
>
> [
>   {
>     "type": "text",
>     "text": "San Francisco is sunny and 72\u00b0F.",
>     "annotations": [],
>     "id": "msg_0311ca847e392d540069acdd420b648196a603306f5546fabd"
>   }
> ]
> ```

要在对话中的特定点添加工具而不使用工具搜索，请参阅 [对话中添加工具](#在对话中途添加工具)。

### 计算机使用

@\[`ChatOpenAI`] 支持 `"computer-use-preview"` 模型，这是一个用于内置计算机使用工具的专用模型。要启用，请将 [计算机使用工具](https://platform.openai.com/docs/guides/tools-computer-use) 作为传递其他工具一样传递给模型。

目前，计算机使用工具的工具输出位于消息 `content` 字段中。要回复计算机使用工具调用，请构造一个 @\[`ToolMessage`]，在其 `additional_kwargs` 中包含 `{"type": "computer_call_output"}`。消息的内容将是一个屏幕截图。下方，我们演示了一个简单的示例。

首先，加载两个屏幕截图：

```python theme={null}
import base64


def load_png_as_base64(file_path):
    with open(file_path, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read())
        return encoded_string.decode("utf-8")


screenshot_1_base64 = load_png_as_base64(
    "/path/to/screenshot_1.png"
)  # perhaps a screenshot of an application
screenshot_2_base64 = load_png_as_base64(
    "/path/to/screenshot_2.png"
)  # perhaps a screenshot of the Desktop
```

```python theme={null}
from langchain_openai import ChatOpenAI

# Initialize model
llm = ChatOpenAI(model="computer-use-preview", truncation="auto")

# Bind computer-use tool
tool = {
    "type": "computer_use_preview",
    "display_width": 1024,
    "display_height": 768,
    "environment": "browser",
}
llm_with_tools = llm.bind_tools([tool])

# Construct input message
input_message = {
    "role": "user",
    "content": [
        {
            "type": "text",
            "text": (
                "Click the red X to close and reveal my Desktop. "
                "Proceed, no confirmation needed."
            ),
        },
        {
            "type": "input_image",
            "image_url": f"data:image/png;base64,{screenshot_1_base64}",
        },
    ],
}

# Invoke model
response = llm_with_tools.invoke(
    [input_message],
    reasoning={
        "generate_summary": "concise",
    },
)
```

响应将在其 `content` 中包含对计算机使用工具的调用：

```python theme={null}
response.content
```

```text theme={null}
[{'id': 'rs_685da051742c81a1bb35ce46a9f3f53406b50b8696b0f590',
  'summary': [{'text': "Clicking red 'X' to show desktop",
    'type': 'summary_text'}],
  'type': 'reasoning'},
 {'id': 'cu_685da054302481a1b2cc43b56e0b381706b50b8696b0f590',
  'action': {'button': 'left', 'type': 'click', 'x': 14, 'y': 38},
  'call_id': 'call_zmQerFBh4PbBE8mQoQHkfkwy',
  'pending_safety_checks': [],
  'status': 'completed',
  'type': 'computer_call'}]
```

我们接下来构建一个具有这些属性的 @\[`ToolMessage`]：

1. 它有一个 `tool_call_id` 匹配计算机调用中的 `call_id`。
2. 它在其 `additional_kwargs` 中有 `{"type": "computer_call_output"}`。
3. 其内容是一个 `image_url` 或一个 `input_image` 输出块（有关格式，请参阅 [OpenAI 文档](https://platform.openai.com/docs/guides/tools-computer-use#5-repeat)）。

```python theme={null}
from langchain.messages import ToolMessage

tool_call_id = next(
    item["call_id"] for item in response.content if item["type"] == "computer_call"
)

tool_message = ToolMessage(
    content=[
        {
            "type": "input_image",
            "image_url": f"data:image/png;base64,{screenshot_2_base64}",
        }
    ],
    # content=f"data:image/png;base64,{screenshot_2_base64}",  # <-- also acceptable
    tool_call_id=tool_call_id,
    additional_kwargs={"type": "computer_call_output"},
)
```

现在我们可以使用消息历史记录再次调用模型：

```python theme={null}
messages = [
    input_message,
    response,
    tool_message,
]

response_2 = llm_with_tools.invoke(
    messages,
    reasoning={
        "generate_summary": "concise",
    },
)
```

```python theme={null}
response_2.text
```

```text theme={null}
'VS Code has been closed, and the desktop is now visible.'
```

除了返回整个序列，我们还可以使用 [`previous_response_id`](#传递-previous_response_id)：

```python theme={null}
previous_response_id = response.response_metadata["id"]

response_2 = llm_with_tools.invoke(
    [tool_message],
    previous_response_id=previous_response_id,
    reasoning={
        "generate_summary": "concise",
    },
)
```

```python theme={null}
response_2.text
```

```text theme={null}
'The VS Code window is closed, and the desktop is now visible. Let me know if you need any further assistance.'
```

### 代码解释器

OpenAI 实现了一个 [代码解释器](https://platform.openai.com/docs/guides/tools-code-interpreter) 工具来支持沙盒化的代码生成和执行。

```python Example use theme={null}
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="gpt-5.4-mini",
    include=["code_interpreter_call.outputs"],  # optionally include outputs
)

llm_with_tools = llm.bind_tools(
    [
        {
            "type": "code_interpreter",
            # Create a new container
            "container": {"type": "auto"},
        }
    ]
)
response = llm_with_tools.invoke(
    "Write and run code to answer the question: what is 3^3?"
)
```

请注意，上述命令创建了一个新容器。我们也可以指定一个现有的容器 ID：

```python theme={null}
code_interpreter_calls = [
    item for item in response.content if item["type"] == "code_interpreter_call"
]
assert len(code_interpreter_calls) == 1
container_id = code_interpreter_calls[0]["extras"]["container_id"]  # [!code highlight]

llm_with_tools = llm.bind_tools(
    [
        {
            "type": "code_interpreter",
            # Use an existing container
            "container": container_id,  # [!code highlight]
        }
    ]
)
```

### 应用补丁

> [!NOTE]
>
> 需要 `langchain-openai>=1.3.0`

OpenAI 实现了一个 [应用补丁](https://developers.openai.com/api/docs/guides/tools-apply-patch) 工具，允许模型使用统一差异创建、更新或删除文件。该工具是客户端执行的：模型提出文件操作，您的应用程序在本地应用它，然后您将结果返回，以便模型可以继续。

要启用它，请将 `{"type": "apply_patch"}` 作为其他工具一样传递给模型。不需要输入模式——模型知道如何构建 `operation` 对象。

```python theme={null}
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-5.5")

llm_with_tools = llm.bind_tools([{"type": "apply_patch"}])

response = llm_with_tools.invoke(
    "Create a new file named hello.txt containing the line: hello world"
)
```

模型返回一个或多个 `apply_patch_call` 内容块，每个块描述一个单个文件操作（`create_file`、`update_file` 或 `delete_file`）：

```python theme={null}
apply_patch_calls = [
    block
    for block in response.content_blocks
    if block["type"] == "apply_patch_call"
]
```

```text theme={null}
[{'type': 'apply_patch_call',
  'id': 'apply_patch_...',
  'call_id': 'call_...',
  'operation': {'type': 'create_file',
   'path': 'hello.txt',
   'diff': '+hello world\n'},
  'status': 'completed'}]
```

将每个操作应用于您的文件系统，然后将结果作为键为相同 `call_id` 的 `apply_patch_call_output` 块发送回去。成功时，将 `status` 设置为 `"completed"`，或使用描述性的 `output` 设置 `"failed"`，以便模型可以调整和重试：

```python theme={null}
from langchain.messages import HumanMessage

call = apply_patch_calls[0]
# ... apply the operation to disk here ...

output_message = HumanMessage(
    content=[
        {
            "type": "apply_patch_call_output",
            "call_id": call["call_id"],
            "status": "completed",
            "output": f"Created {call['operation']['path']}",
        }
    ]
)

follow_up = llm_with_tools.invoke(
    [
        HumanMessage("Create a new file named hello.txt containing: hello world"),
        response,
        output_message,
    ]
)
```

> [!TIP]
>
> 您也可以通过传递 `previous_response_id` 而不是完整消息历史记录来继续与 OpenAI 的状态 API 的对话。请参阅 [管理对话状态](#管理对话状态)。

### 远程 MCP

OpenAI 实现了一个 [远程 MCP](https://platform.openai.com/docs/guides/tools-remote-mcp) 工具，允许模型生成的调用访问 MCP 服务器。

```python Example use theme={null}
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-5.4-mini")

llm_with_tools = llm.bind_tools(
    [
        {
            "type": "mcp",
            "server_label": "deepwiki",
            "server_url": "https://mcp.deepwiki.com/mcp",
            "require_approval": "never",
        }
    ]
)
response = llm_with_tools.invoke(
    "What transport protocols does the 2025-03-26 version of the MCP "
    "spec (modelcontextprotocol/modelcontextprotocol) support?"
)
```

> [accordion] MCP Approvals
>
> OpenAI 有时会请求批准，然后再与远程 MCP 服务器共享数据。
>
> 在上述命令中，我们指示模型永远不需要批准。我们也可以配置模型始终请求批准，或始终为特定工具请求批准：
>
> ```python theme={null}
> llm_with_tools = llm.bind_tools(
>     [
>         {
>             "type": "mcp",
>             "server_label": "deepwiki",
>             "server_url": "https://mcp.deepwiki.com/mcp",
>             "require_approval": {
>                 "always": {
>                     "tool_names": ["read_wiki_structure"]
>                 }
>             }
>         }
>     ]
> )
> response = llm_with_tools.invoke(
>     "What transport protocols does the 2025-03-26 version of the MCP "
>     "spec (modelcontextprotocol/modelcontextprotocol) support?"
> )
> ```
>
> 然后响应可能包括类型为 `"mcp_approval_request"` 的块。
>
> 要提交对批准请求的批准，请在输入消息中将其结构化为一个内容块：
>
> ```python theme={null}
> approval_message = {
>     "role": "user",
>     "content": [
>         {
>             "type": "mcp_approval_response",
>             "approve": True,
>             "approval_request_id": block["id"],
>         }
>         for block in response.content
>         if block["type"] == "mcp_approval_request"
>     ]
> }
>
> next_response = llm_with_tools.invoke(
>     [approval_message],
>     # continue existing thread
>     previous_response_id=response.response_metadata["id"]
> )
> ```

### 管理对话状态

Responses API 支持管理 [对话状态](https://platform.openai.com/docs/guides/conversation-state?api-mode=responses)。

#### 手动管理状态

您可以使用 [LangGraph](https://langchain-docs-zh.mintlify.site/langchain/oss/langgraph/quickstart.md) 手动管理状态，就像其他对话模型一样：

```python theme={null}
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-5.4-mini", use_responses_api=True)

first_query = "Hi, I'm Bob."
messages = [{"role": "user", "content": first_query}]

response = llm.invoke(messages)
print(response.text)
```

```text theme={null}
Hi Bob! Nice to meet you. How can I assist you today?
```

```python theme={null}
second_query = "What is my name?"

messages.extend(
    [
        response,
        {"role": "user", "content": second_query},
    ]
)
second_response = llm.invoke(messages)
print(second_response.text)
```

```text theme={null}
You mentioned that your name is Bob. How can I assist you further, Bob?
```

> [!TIP]
>
> **您可以使用 [LangGraph](https://langchain-docs-zh.mintlify.site/langchain/oss/langgraph/overview.md) 在各种后端（包括内存和 Postgres）为您管理对话线程。请参阅 [这个教程](https://langchain-docs-zh.mintlify.site/langchain/oss/langgraph/quickstart.md) 获取入门指南。**

#### 传递 `previous_response_id`

在使用 Responses API 时，LangChain 消息将在其元数据中包含一个 `"id"` 字段。将此 ID 传递给后续调用将延续对话。请注意，从计费角度来看，这与手动传递消息 [等效](https://platform.openai.com/docs/guides/conversation-state?api-mode=responses#openai-apis-for-conversation-state)。

```python theme={null}
second_response = llm.invoke(
    "What is my name?",
    previous_response_id=response.id,  # [!code highlight]
)
print(second_response.text)
```

```text theme={null}
Your name is Bob. How can I help you today, Bob?
```

ChatOpenAI 还可以使用消息序列中的最后一个响应自动指定 `previous_response_id`：

```python theme={null}
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="gpt-5.4-mini",
    use_previous_response_id=True,  # [!code highlight]
)
```

如果我们设置 `use_previous_response_id=True`，则请求有效负载将丢弃直到最新响应的所有输入消息，并使用最新响应的 ID 设置 `previous_response_id`。

也就是说，

```python theme={null}
llm.invoke(
    [
        HumanMessage("Hello"),
        AIMessage("Hi there!", id="resp_123"),
        HumanMessage("How are you?"),
    ]
)
```

...等效于：

```python theme={null}
llm.invoke([HumanMessage("How are you?")], previous_response_id="resp_123")
```

#### 上下文管理

Responses API 支持自动 [服务器端上下文压缩](https://developers.openai.com/api/docs/guides/compaction)。当对话达到 Token 阈值时，这会减少对话大小，从而支持长时间运行的交互：

```python theme={null}
from langchain_openai import ChatOpenAI

model = ChatOpenAI(
    model="gpt-5.5",
    context_management=[  # [!code highlight]
        {"type": "compaction", "compact_threshold": 100_000}  # [!code highlight]
    ],  # [!code highlight]
)
```

当启用时，`AIMessage` 响应可能包含内容中带有 `"type": "compaction"` 的块。这些应在对话历史记录中保留，并可以按 [通常方式](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/short-term-memory.md) 追加到消息序列中。可以保留最接近的 `compaction` 项之前的消息，或丢弃以提高延迟。

### 推理输出

一些 OpenAI 模型将生成单独的文本内容来说明其推理过程。有关详细信息，请参阅 OpenAI 的 [推理文档](https://platform.openai.com/docs/guides/reasoning?api-mode=responses)。

OpenAI 可以返回模型推理的摘要（尽管它不暴露原始推理 Token）。要配置 @\[`ChatOpenAI`] 返回此摘要，请指定 `reasoning` 参数。@\[`ChatOpenAI`] 将在设置此参数时自动路由到 Responses API。

```python theme={null}
from langchain_openai import ChatOpenAI

reasoning = {
    "effort": "medium",  # 'low', 'medium', or 'high'
    "summary": "auto",  # 'detailed', 'auto', or None
}

llm = ChatOpenAI(model="gpt-5-nano", reasoning=reasoning)
response = llm.invoke("What is 3^3?")

# Output
response.text
```

```text theme={null}
'3³ = 3 × 3 × 3 = 27.'
```

```python theme={null}
# Reasoning
for block in response.content_blocks:
    if block["type"] == "reasoning":
        print(block["reasoning"])
```

```text theme={null}
**Calculating the power of three**

The user is asking about 3 raised to the power of 3. That's a pretty simple calculation! I know that 3^3 equals 27, so I can say, "3 to the power of 3 equals 27." I might also include a quick explanation that it's 3 multiplied by itself three times: 3 × 3 × 3 = 27. So, the answer is definitely 27.
```

对于更简单的等效方案，使用标准 [`reasoning_effort`](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/models#推理) 参数，它翻译为 `reasoning.effort` 并添加 `summary: "auto"`：

```python theme={null}
llm = ChatOpenAI(model="gpt-5-nano", reasoning_effort="medium")
```

> [!NOTE]
>
> 作为标准参数的 `reasoning_effort` 需要 `langchain-openai>=1.4.1`。

### 在对话中途更改推理努力

使用一个 [`configuration_update`](https://developers.openai.com/api/docs/guides/reasoning?api-mode=responses#change-reasoning-mid-conversation) 内容块在回合之间更改推理努力，而无需修改请求级别的 `reasoning_effort` 参数——保持提示词前缀可缓存。将块直接嵌入一个 `HumanMessage`：

```python theme={null}
from langchain_openai import ChatOpenAI
from langchain.messages import HumanMessage

llm = ChatOpenAI(model="gpt-6-astra", use_responses_api=True, reasoning_effort="low")

first = llm.invoke("Hello")

# Raise reasoning effort from this message onward
response = llm.invoke(
    [
        "Hello",
        first,
        HumanMessage(
            [
                {"type": "configuration_update", "reasoning": {"effort": "high"}},  # [!code highlight]
                {"type": "text", "text": "How many distinct 5-card poker hands are a full house?"},
            ]
        ),
    ]
)
```

> [!TIP]
>
> **故障排除：推理模型的空响应**
>
> 如果您从推理模型（如 `gpt-5-nano`）收到空响应，这可能是由于限制性 Token 限制。模型使用 Token 进行内部推理，可能没有足够的 Token 用于最终输出。
>
> 确保 `max_tokens` 设置为 `None` 或增加 Token 限制，以允许足够的 Token 用于推理和输出生成。

### 在对话中途添加工具

> [!NOTE]
>
> `additional_tools` 需要 `langchain-openai>=1.6.5`。

使用一个 [`additional_tools`](https://developers.openai.com/api/docs/guides/tools-tool-search#add-tools-at-a-specific-point-in-the-input) 内容块从对话中的某个点开始提供工具。当您的应用程序在 [工具搜索](#工具搜索) 流程之外加载工具时，这很有用。将块放在一个 @\[`SystemMessage`] 中：

```python theme={null}
from langchain.messages import HumanMessage, SystemMessage
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-6-astra", use_responses_api=True)

response = llm.invoke(
    [
        HumanMessage("What time is it?"),
        SystemMessage(
            [
                {
                    "type": "additional_tools",  # [!code highlight]
                    "role": "developer",  # [!code highlight]
                    "tools": [
                        {
                            "type": "function",
                            "name": "get_time",
                            "description": "Get the current time.",
                            "parameters": {"type": "object", "properties": {}},
                        }
                    ],
                },
            ]
        ),
    ]
)
```

该块需要 Responses API，因此设置 `use_responses_api=True`。在 Chat Completions 或在 `SystemMessage` 之外的消息上，`ChatOpenAI` 会引发 `ValueError`。您也可以将块包装在 `non_standard` 块中，这是 `content_blocks` 返回它的方式。

***

## 微调

您可以通过传递相应的 `modelName` 参数来调用微调的 OpenAI 模型。

这通常采用 `ft:{OPENAI_MODEL_NAME}:{ORG_NAME}::{MODEL_ID}` 的形式。例如：

```python theme={null}
fine_tuned_model = ChatOpenAI(
    temperature=0, model_name="ft:gpt-3.5-turbo-0613:langchain::7qTVM5AR"
)

fine_tuned_model.invoke(messages)
```

```text theme={null}
AIMessage(content="J'adore la programmation.", additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 8, 'prompt_tokens': 31, 'total_tokens': 39}, 'model_name': 'ft:gpt-3.5-turbo-0613:langchain::7qTVM5AR', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}, id='run-0f39b30e-c56e-4f3b-af99-5c948c984146-0', usage_metadata={'input_tokens': 31, 'output_tokens': 8, 'total_tokens': 39})
```

***

## 多模态输入（图像、PDF、音频）

OpenAI 有支持多模态输入的模型。您可以将图像、PDF 或音频传递给这些模型。有关在 LangChain 中如何执行此操作的更多信息，请参阅 [多模态输入](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/messages.md#多模态) 文档。

您可以在 [OpenAI 的文档](https://platform.openai.com/docs/models) 中查看支持不同模态的模型列表。

对于所有模态，LangChain 支持其跨提供商的标准以及 OpenAI 的原生内容块格式。

将多模态数据传入 @\[`ChatOpenAI`]，创建一个包含数据的[内容块](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/messages.md)，并将其整合到消息中，例如如下：

```python theme={null}
message = {
    "role": "user",
    "content": [
        {
            "type": "text",
            # Update prompt as desired
            "text": "Describe the (image / PDF / audio...)",
        },
        content_block,  # [!code highlight]
    ],
}
```

请参考下方的内容块示例。

> [accordion] Images
>
> 参考 [多模态消息指南](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/messages.md#多模态) 中的示例。
>
> ```python URLs theme={null}
> # LangChain format
> content_block = {
>     "type": "image",
>     "url": url_string,
> }
>
> # OpenAI Chat Completions format
> content_block = {
>     "type": "image_url",
>     "image_url": {"url": url_string},
> }
> ```
>
> ```python In-line base64 data theme={null}
> # LangChain format
> content_block = {
>     "type": "image",
>     "base64": base64_string,
>     "mime_type": "image/jpeg",
> }
>
> # OpenAI Chat Completions format
> content_block = {
>     "type": "image_url",
>     "image_url": {
>         "url": f"data:image/jpeg;base64,{base64_string}",
>     },
> }
> ```

> [accordion] PDFs
>
> 注意：OpenAI 要求 PDF 输入时必须指定文件名。在使用 LangChain 的格式时，请包含 `filename` 键。
>
> Read more about [OpenAI file names for multimodal messages](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/messages.md#多模态).
>
> 参考 [PDF 文档如何指南](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/messages.md#多模态)中的示例。
>
> ```python In-line base64 data theme={null}
> # LangChain format
> content_block = {
>     "type": "file",
>     "base64": base64_string,
>     "mime_type": "application/pdf",
>     "filename": "my-file.pdf",  # [!code highlight]
> }
>
> # OpenAI Chat Completions format
> content_block = {
>     "type": "file",
>     "file": {
>         "filename": "my-file.pdf",
>         "file_data": f"data:application/pdf;base64,{base64_string}",
>     }
> }
> ```

> [accordion] Audio
>
> 参见 [支持的模型](https://platform.openai.com/docs/models)，例如 `"gpt-4o-audio-preview"`。
>
> 参考 [音频操作指南](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/messages.md#多模态)中的示例。
>
> ```python In-line base64 data theme={null}
> # LangChain format
> content_block = {
>     "type": "audio",
>     "mime_type": "audio/wav",  # or appropriate mime-type
>     "base64": base64_string,
> }
>
> # OpenAI Chat Completions format
> content_block = {
>     "type": "input_audio",
>     "input_audio": {"data": base64_string, "format": "wav"},
> }
> ```

***

## 预期输出

> [!NOTE]
>
> **Requires `langchain-openai>=0.2.6`**

一些 OpenAI 模型（如 `gpt-4o` 和 `gpt-4o-mini` 系列）支持 [预测输出](https://platform.openai.com/docs/guides/latency-optimization#use-predicted-outputs)，这允许您提前传递 LLM 预期输出的一部分，以减少延迟。这对于编辑文本或代码等场景很有用，在这些场景中，模型输出的只有一小部分会改变。

Here's an example:

```python theme={null}
code = """
/// <summary>
/// Represents a user with a first name, last name, and username.
/// </summary>
public class User
{
    /// <summary>
    /// Gets or sets the user's first name.
    /// </summary>
    public string FirstName { get; set; }

    /// <summary>
    /// Gets or sets the user's last name.
    /// </summary>
    public string LastName { get; set; }

    /// <summary>
    /// Gets or sets the user's username.
    /// </summary>
    public string Username { get; set; }
}
"""

llm = ChatOpenAI(model="gpt-5.5")
query = (
    "Replace the Username property with an Email property. "
    "Respond only with code, and with no markdown formatting."
)
response = llm.invoke(
    [{"role": "user", "content": query}, {"role": "user", "content": code}],
    prediction={"type": "content", "content": code},
)
print(response.content)
print(response.response_metadata)
```

```python theme={null}
/// <summary>
/// Represents a user with a first name, last name, and email.
/// </summary>
public class User
{
    /// <summary>
    /// Gets or sets the user's first name.
    /// </summary>
    public string FirstName { get; set; }

    /// <summary>
    /// Gets or sets the user's last name.
    /// </summary>
    public string LastName { get; set; }

    /// <summary>
    /// Gets or sets the user's email.
    /// </summary>
    public string Email { get; set; }
}
{'token_usage': {'completion_tokens': 226, 'prompt_tokens': 166, 'total_tokens': 392, 'completion_tokens_details': {'accepted_prediction_tokens': 49, 'audio_tokens': None, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 107}, 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_45cf54deae', 'finish_reason': 'stop', 'logprobs': None}
```

> [!NOTE]
>
> 预测会按 Token 额外计费，并可能因这种降低的延迟而增加您的使用量和成本。

## 音频生成（预览）

> [!NOTE]
>
> 需要 `langchain-openai>=0.2.3`

OpenAI 推出了新的[音频生成功能](https://platform.openai.com/docs/guides/audio?audio-generation-quickstart-example=audio-out)，让您可以在 `gpt-4o-audio-preview` 模型上使用音频输入和输出。

```python theme={null}
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="gpt-4o-audio-preview",
    temperature=0,
    model_kwargs={
        "modalities": ["text", "audio"],
        "audio": {"voice": "alloy", "format": "wav"},
    },
)

output_message = llm.invoke(
    [
        ("human", "Are you made by OpenAI? Just answer yes or no"),
    ]
)
```

`output_message.additional_kwargs['audio']` 会包含类似下面这样的字典：

```python theme={null}
{
    'data': '<audio data b64-encoded',
    'expires_at': 1729268602,
    'id': 'audio_67127d6a44348190af62c1530ef0955a',
    'transcript': 'Yes.'
}
```

……其格式就是 `model_kwargs['audio']['format']` 中传入的格式。

我们还可以在 OpenAI 的 `expires_at` 到期之前，把这条带有音频数据的消息作为消息历史的一部分再传回模型。

> [!NOTE]
>
> **输出音频存储在 `AIMessage.additional_kwargs` 的 `audio` 键下，而输入内容块在 `HumanMessage.content` 列表中的类型和键为 `input_audio`。**
>
> 更多信息请参阅 OpenAI 的[音频文档](https://platform.openai.com/docs/guides/audio)。

```python theme={null}
history = [
    ("human", "Are you made by OpenAI? Just answer yes or no"),
    output_message,
    ("human", "And what is your name? Just give your name."),
]
second_output_message = llm.invoke(history)
```

***

## 提示缓存

OpenAI 的[提示缓存](https://platform.openai.com/docs/guides/prompt-caching)功能会自动缓存超过 1024 个 token 的提示词，以降低成本并缩短响应时间。该功能对所有较新的模型（`gpt-4o` 及更新版本）默认启用。

### 手动缓存

您可以使用 `prompt_cache_key` 参数影响 OpenAI 的缓存行为，并优化缓存命中率：

```python theme={null}
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-5.5")

# Use a cache key for repeated prompts
messages = [
    {"role": "system", "content": "You are a helpful assistant that translates English to French."},
    {"role": "user", "content": "I love programming."},
]

response = llm.invoke(
    messages,
    prompt_cache_key="translation-assistant-v1"
)

# Check cache usage
cache_read_tokens = response.usage_metadata.input_token_details.cache_read
print(f"Cached tokens used: {cache_read_tokens}")
```

> [!WARNING]
>
> 缓存命中要求提示词前缀完全匹配

### 缓存键策略

您可以根据应用需求采用不同的缓存键策略：

```python theme={null}
# Static cache keys for consistent prompt templates
customer_response = llm.invoke(
    messages,
    prompt_cache_key="customer-support-v1"
)

support_response = llm.invoke(
    messages,
    prompt_cache_key="internal-support-v1"
)

# Dynamic cache keys based on context
user_type = "premium"
cache_key = f"assistant-{user_type}-v1"
response = llm.invoke(messages, prompt_cache_key=cache_key)
```

### 模型级缓存

您还可以通过 `model_kwargs` 在模型级别设置默认缓存键：

```python theme={null}
llm = ChatOpenAI(
    model="gpt-5.4-mini",
    model_kwargs={"prompt_cache_key": "default-cache-v1"}
)

# Uses default cache key
response1 = llm.invoke(messages)

# Override with specific cache key
response2 = llm.invoke(messages, prompt_cache_key="override-cache-v1")
```

### 使用断点的显式缓存

> [!NOTE]
>
> 需要 `langchain-openai>=1.3.5`。Chat Completions API 与 [Responses API](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/chat/openai.md#响应-api) 均支持。

OpenAI 支持[显式提示缓存断点](https://developers.openai.com/api/docs/guides/prompt-caching#prompt-cache-breakpoints)，允许您将特定的内容块指定为缓存边界。这样您可以细粒度地控制提示词中哪些部分会被缓存，而不必仅依赖自动前缀缓存。

要将某个内容块标记为缓存断点，请为该块添加 `"prompt_cache_breakpoint": {"mode": "explicit"}`。显式断点需要 GPT-5.6 或更新版本的模型系列。

> [tab] Chat Completions
>
> ```python theme={null}
> from langchain_openai import ChatOpenAI
>
> llm = ChatOpenAI(
>     model="gpt-5.6-sol",
>     prompt_cache_options={"mode": "explicit"},
> )
>
> messages = [
>     {
>         "role": "system",
>         "content": [
>             {
>                 "type": "text",
>                 "text": (
>                     "You are a helpful assistant with access to a large knowledge base."
>                 ),
>                 "prompt_cache_breakpoint": {"mode": "explicit"},  # [!code highlight]
>             }
>         ],
>     },
>     {"role": "user", "content": "Summarize the key points."},
> ]
>
> response = llm.invoke(messages, prompt_cache_key="docs-breakpoint-v1")
> ```
>
> > [card] [View example trace](https://smith.langchain.com/public/aade8a0b-e869-4583-b0fe-f91d3bc786ad/r)
> >
> > 为此示例打开一个公开的 LangSmith 运行。

> [tab] Responses API
>
> ```python theme={null}
> from langchain_openai import ChatOpenAI
>
> llm = ChatOpenAI(
>     model="gpt-5.6-sol",
>     use_responses_api=True,
>     prompt_cache_options={"mode": "explicit"},
> )
>
> messages = [
>     {
>         "role": "system",
>         "content": [
>             {
>                 "type": "text",
>                 "text": (
>                     "You are a helpful assistant with access to a large knowledge base."
>                 ),
>                 "prompt_cache_breakpoint": {"mode": "explicit"},  # [!code highlight]
>             }
>         ],
>     },
>     {"role": "user", "content": "Summarize the key points."},
> ]
>
> response = llm.invoke(messages, prompt_cache_key="docs-breakpoint-v1")
> ```
>
> > [card] [View example trace](https://smith.langchain.com/public/a62d33a8-a1bd-4d34-b40b-5bc442aca92c/r)
> >
> > 为此示例打开一个公开的 LangSmith 运行。

断点支持文本、图像和文件内容块。如果您希望保持 LangChain 内容块结构整洁，也可以把 `prompt_cache_breakpoint` 嵌套在 `extras` 字典中：

```python theme={null}
content_block = {
    "type": "text",
    "text": "Long system prompt...",
    "extras": {"prompt_cache_breakpoint": {"mode": "explicit"}},
}
```

> [card] [View example trace](https://smith.langchain.com/public/3cbf13f4-abd1-4ac7-a17d-3f20cb97f920/r)
>
> 为此示例打开一个公开的 LangSmith 运行。

### 请求级缓存选项

> [!NOTE]
>
> 需要 `langchain-openai>=1.3.5`。`prompt_cache_options` 适用于 GPT-5.6 及更新版本的模型系列。

您可以在模型上或每次调用时通过 `prompt_cache_options` 参数传入请求级提示缓存选项：

* **`mode`**：`"implicit"`（默认）或 `"explicit"`。在 `"implicit"` 模式下，OpenAI 会在最新一条消息上放置缓存断点，同时也会使用您提供的显式断点。在 `"explicit"` 模式下，只有您的断点会用于缓存读写。如果请求中没有显式断点，则不会使用提示缓存。
* **`ttl`**：请求写入的断点的最短缓存生存时间。唯一支持的值是 `"30m"`，这也是默认值。

```python theme={null}
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="gpt-5.6-sol",
    prompt_cache_options={"mode": "explicit", "ttl": "30m"},
)

messages = [{"role": "user", "content": "Hello"}]

# Override per request
response = llm.invoke(
    messages,
    prompt_cache_options={"mode": "implicit"},
)
```

> [card] [View example trace](https://smith.langchain.com/public/f89103cb-5a44-4530-8bf9-258c30a76e9c/r)
>
> 为此示例打开一个公开的 LangSmith 运行。

对于 GPT-5.6 系列之前的模型，请改用 `prompt_cache_retention`（`"in_memory"` 或 `"24h"`）。该字段与 `prompt_cache_options` 相互独立，并且在 GPT-5.6 及更新版本的模型系列中已被弃用。

### 缓存写入 token

当 OpenAI 将新内容写入提示缓存时，会在响应中报告 `cache_write_tokens`。`ChatOpenAI` 会以 `input_token_details` 中的 `cache_creation` 呈现该值：

```python theme={null}
response = llm.invoke(messages)

cache_read = response.usage_metadata["input_token_details"].get("cache_read")
cache_creation = response.usage_metadata["input_token_details"].get("cache_creation")
print(f"Cache read tokens:     {cache_read}")
print(f"Cache creation tokens: {cache_creation}")
```

> [card] [View example trace](https://smith.langchain.com/public/53f314e3-ac7b-4980-8ad9-d9e9229d9f1b/r)
>
> 为此示例打开一个公开的 LangSmith 运行。

在 `"priority"` 和 `"flex"` 服务层级中，这些键会加上层级名称前缀——例如 `"priority_cache_read"` 和 `"priority_cache_creation"`。

***

## Flex 处理

OpenAI 提供多种[服务层级](https://platform.openai.com/docs/guides/flex-processing)。`"flex"` 层级为请求提供更低的价格，代价是响应可能更慢，且资源不一定始终可用。这种方式最适合非关键任务，包括模型测试、数据增强或可异步运行的作业。

要使用它，请在初始化模型时设置 `service_tier="flex"`：

```python theme={null}
llm = ChatOpenAI(model="o4-mini", service_tier="flex")
```

请注意，这是一项测试版功能，仅对部分模型可用。更多细节请参阅 OpenAI [文档](https://platform.openai.com/docs/guides/flex-processing)。

***

## API 参考

有关所有功能和配置选项的详细文档，请前往 @\[`ChatOpenAI`] API 参考。

***

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


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