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

# LangChain（OpenAI）

> 使用 LangChain 的 ChatOpenAI 接入 PipeLLM 的 OpenAI 兼容路由

认证和模型列表请参考 [OpenAI 概述](/api-reference/openai/overview.zh)。

<Note>
  这页是框架集成文档。原始 HTTP 端点说明请看
  [Chat Completions](/api-reference/openai/chat-completions.zh) 或
  [Responses](/api-reference/openai/responses.zh)。
</Note>

## 安装

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

## 代码示例

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    import os
    from langchain_openai import ChatOpenAI

    llm = ChatOpenAI(
      model='gpt-4.1',
      api_key=os.getenv('PIPELLM_API_KEY'),
      base_url='https://api.pipellm.ai/v1'
    )

    response = llm.invoke([
      ('user', 'Why is the sky blue?')
    ])

    print(response.content)
    ```
  </Tab>

  <Tab title="Node.js">
    ```javascript theme={null}
    import { ChatOpenAI } from '@langchain/openai';

    const llm = new ChatOpenAI({
      model: 'gpt-4.1',
      apiKey: process.env.PIPELLM_API_KEY,
      configuration: {
        baseURL: 'https://api.pipellm.ai/v1'
      }
    });

    const response = await llm.invoke([
      { role: 'user', content: 'Why is the sky blue?' }
    ]);

    console.log(response.content);
    ```
  </Tab>
</Tabs>

## 流式响应

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

llm = ChatOpenAI(
  model='gpt-4.1',
  api_key=os.getenv('PIPELLM_API_KEY'),
  base_url='https://api.pipellm.ai/v1',
  streaming=True
)

for chunk in llm.stream('Tell me a story'):
  print(chunk.content, end='', flush=True)
```

## 函数调用

```python theme={null}
import os
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool

@tool
def get_weather(location: str) -> str:
  """获取指定地点的天气"""
  return f"{location} 的天气：22°C，晴天"

llm = ChatOpenAI(
  model='gpt-4.1',
  api_key=os.getenv('PIPELLM_API_KEY'),
  base_url='https://api.pipellm.ai/v1'
)

llm_with_tools = llm.bind_tools([get_weather])
response = llm_with_tools.invoke("东京现在天气怎么样？")

print(response.tool_calls)
```

## 相关文档

<Columns cols={3}>
  <Card title="OpenAI 概述" icon="bolt" href="/api-reference/openai/overview.zh">
    查看 Header、模型和原生路由
  </Card>

  <Card title="Chat Completions" icon="comments" href="/api-reference/openai/chat-completions.zh">
    查看 `POST /v1/chat/completions` 的端点说明
  </Card>

  <Card title="开发工具总览" icon="terminal" href="/integrations/overview.zh">
    查看 PipeLLM 上的更多工具与框架集成
  </Card>
</Columns>
