> ## 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 Python 集成 OpenAI LLM。

> [!WARNING]
>
> **您当前位于 OpenAI 文本补全模型的文档页面。OpenAI 最新且最流行的模型是 [对话生成模型](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/models.md)。**
>
> 除非您明确使用 `gpt-3.5-turbo-instruct`，否则您可能需要访问 [此页面](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/chat/openai.md)。

[OpenAI](https://platform.openai.com/docs/introduction) 提供了不同能力层级的多款模型，适用于各类任务。

本示例演示如何使用 LangChain 与 OpenAI [模型](https://platform.openai.com/docs/models) 进行交互

## 概览

### 集成细节

| 类别 | 包名 | 本地 | 可序列化 | [JS 支持](https://langchain-docs-zh.mintlify.site/langchain/oss/javascript/integrations/chat/openai.md) | 下载量 | 版本 |
| :- | :- | :-: | :-: | :-: | :-: | :-: |
| [`ChatOpenAI`](https://reference.langchain.com/python/langchain-openai/chat_models/base/ChatOpenAI) | [`langchain-openai`](https://reference.langchain.com/python/langchain-openai) | ❌ | beta | ✅ | ![PyPI - 下载量](https://img.shields.io/pypi/dm/langchain-openai?style=flat-square\&label=%20) | ![PyPI - 版本](https://img.shields.io/pypi/v/langchain-openai?style=flat-square\&label=%20) |

## 安装配置

访问 OpenAI 模型需创建账户、获取 API 密钥并安装 `langchain-openai` 集成包。

### 凭据管理

前往 [platform.openai.com](https://platform.openai.com) 注册 OpenAI 账户并生成 API 密钥。完成设置后需配置 OPENAI\_API\_KEY 环境变量：

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

if "OPENAI_API_KEY" not in os.environ:
    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 客户端读取

为启用模型调用自动追踪，设置 [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"
```

### 安装

LangChain OpenAI 集成位于 `langchain-openai` 包中：

```python theme={null}
pip install -qU langchain-openai
```

若需指定组织 ID，可通过以下代码实现（仅当您属于多组织或需使用默认组织时必要）。您可在 [OpenAI API 密钥页面](https://platform.openai.com/account/api-keys) 查看默认组织：

```python theme={null}
OPENAI_ORGANIZATION = getpass()

os.environ["OPENAI_ORGANIZATION"] = OPENAI_ORGANIZATION
```

## 实例化

现在可实例化模型对象并生成对话补全：

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

llm = OpenAI()
```

## 调用

```python theme={null}
llm.invoke("Hello how are you?")
```

```text theme={null}
'\n\nI am an AI and do not have emotions like humans do, so I am always functioning at my optimal level. Thank you for asking! How can I assist you today?'
```

## 链式调用

```python theme={null}
from langchain_core.prompts import PromptTemplate

prompt = PromptTemplate.from_template("How to say {input} in {output_language}:\n")

chain = prompt | llm
chain.invoke(
    {
        "output_language": "German",
        "input": "I love programming.",
    }
)
```

```text theme={null}
'\nIch liebe Programmieren.'
```

## 使用代理

若您处于显式代理环境，可通过指定 http\_client 实现代理穿透：

```python theme={null}
pip install httpx

import httpx

openai = OpenAI(
    model_name="gpt-3.5-turbo-instruct",
    http_client=httpx.Client(proxies="http://proxy.yourcompany.com:8080"),
)
```

***

## API 参考文档

获取所有 @\[`OpenAI`] LLM 功能及配置的详细文档，请访问 API 参考文档：[reference.langchain.com/python/langchain-openai/llms/base/OpenAI](https://reference.langchain.com/python/langchain-openai/llms/base/OpenAI)

***

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


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