> ## Documentation Index
> Fetch the complete documentation index at: https://cndoc-langchain.site/llms.txt
> Use this file to discover all available pages before exploring further.

# xAI 集成

> 使用 LangChain Python 与 xAI 集成。

<Warning>
  本页指的是由 [xAI](https://docs.x.ai/docs/overview) 提供的 Grok 模型——请勿与另一家独立的 AI 硬件和软件公司 [Groq](https://console.groq.com/docs/overview) 混淆。请参阅 [Groq 提供者页面](/oss/python/integrations/providers/groq)。
</Warning>

[xAI](https://console.x.ai) 提供了一个 API 来与 Grok 模型交互。本示例将介绍如何使用 LangChain 与 xAI 模型进行交互。

## 安装

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
pip install -U langchain-xai
```

## 环境

要使用 xAI，您需要[创建一个 API 密钥](https://console.x.ai/)。该 API 密钥可以作为初始化参数 `xai_api_key` 传入，也可以设置为环境变量 `XAI_API_KEY`。

## 示例

详情和支持的功能请参阅 [ChatXAI 文档](/oss/python/integrations/chat/xai)。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
# 使用 xAI 查询聊天模型

from langchain_xai import ChatXAI

chat = ChatXAI(
    # xai_api_key="YOUR_API_KEY",
    model="grok-4",
)

# 流式接收模型的响应
for m in chat.stream("Tell me fun things to do in NYC"):
    print(m.content, end="", flush=True)

# 如果您不想使用流式传输，可以使用 invoke 方法
# chat.invoke("Tell me fun things to do in NYC")
```

***

<div className="source-links">
  <Callout icon="terminal-2">
    [将这些文档](/use-these-docs)通过 MCP 连接到 Claude、VSCode 等，以获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/oss/python/integrations/providers/xai.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
