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

# ChatXAI 集成

> 使用 LangChain Python 与 ChatXAI 聊天模型集成。

<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/) 提供了与 Grok 模型交互的 API。

<Tip>
  **API 参考**

  有关所有功能和配置选项的详细文档，请查阅 [`ChatXAI`](https://reference.langchain.com/python/langchain-xai/chat_models/ChatXAI) API 参考。
</Tip>

## 概述

### 集成详情

| 类                                                                                     | 包                                                                        | 可序列化 | [JS 支持](https://js.langchain.com/docs/integrations/chat/xai) |                                               下载量                                              |                                              版本                                             |
| :------------------------------------------------------------------------------------ | :----------------------------------------------------------------------- | :--: | :----------------------------------------------------------: | :--------------------------------------------------------------------------------------------: | :-----------------------------------------------------------------------------------------: |
| [`ChatXAI`](https://reference.langchain.com/python/langchain-xai/chat_models/ChatXAI) | [`langchain-xai`](https://reference.langchain.com/python/langchain-xai/) | beta |                               ✅                              | ![PyPI - Downloads](https://img.shields.io/pypi/dm/langchain-xai?style=flat-square\&label=%20) | ![PyPI - Version](https://img.shields.io/pypi/v/langchain-xai?style=flat-square\&label=%20) |

### 模型特性

| [工具调用](/oss/python/langchain/tools) | [结构化输出](/oss/python/langchain/structured-output) | [图像输入](/oss/python/langchain/messages#multimodal) | 音频输入 | 视频输入 | [令牌级流式传输](/oss/python/langchain/streaming#llm-tokens) | 原生异步 | [令牌用量](/oss/python/langchain/models#token-usage) | [对数概率](/oss/python/langchain/models#log-probabilities) |
| :---------------------------------: | :----------------------------------------------: | :-----------------------------------------------: | :--: | :--: | :---------------------------------------------------: | :--: | :----------------------------------------------: | :----------------------------------------------------: |
|                  ✅                  |                         ✅                        |                         ❌                         |   ❌  |   ❌  |                           ✅                           |   ❌  |                         ✅                        |                            ✅                           |

## 设置

要访问 xAI 模型，您需要创建一个 xAI 账户，获取 API 密钥，并安装 `langchain-xai` 集成包。

### 凭证

前往[此页面](https://console.x.ai/)注册 xAI 并生成 API 密钥。完成后，设置 `XAI_API_KEY` 环境变量：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import getpass
import os

if "XAI_API_KEY" not in os.environ:
    os.environ["XAI_API_KEY"] = getpass.getpass("输入您的 xAI API 密钥：")
```

要启用模型调用的自动追踪，请设置您的 [LangSmith](/langsmith/home) API 密钥：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
os.environ["LANGSMITH_API_KEY"] = getpass.getpass("输入您的 LangSmith API 密钥：")
os.environ["LANGSMITH_TRACING"] = "true"
```

### 安装

LangChain xAI 集成位于 `langchain-xai` 包中：

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

## 实例化

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

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_xai import ChatXAI

llm = ChatXAI(
    model="grok-beta",
    temperature=0,
    max_tokens=None,
    timeout=None,
    max_retries=2,
    # 其他参数...
)
```

## 调用

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
messages = [
    (
        "system",
        "您是一个将英语翻译成法语的助手。请翻译用户的句子。",
    ),
    ("human", "I love programming."),
]
ai_msg = llm.invoke(messages)
ai_msg
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
AIMessage(content="J'adore programmer.", additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 6, 'prompt_tokens': 30, 'total_tokens': 36, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'grok-beta', 'system_fingerprint': 'fp_14b89b2dfc', 'finish_reason': 'stop', 'logprobs': None}, id='run-adffb7a3-e48a-4f52-b694-340d85abe5c3-0', usage_metadata={'input_tokens': 30, 'output_tokens': 6, 'total_tokens': 36, 'input_token_details': {}, 'output_token_details': {}})
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
print(ai_msg.content)
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
J'adore programmer.
```

## 工具调用

ChatXAI 具有 [工具调用](https://docs.x.ai/docs#capabilities)（此处我们交替使用“工具调用”和“函数调用”）API，允许您描述工具及其参数，并让模型返回一个 JSON 对象，其中包含要调用的工具及其输入。工具调用对于构建使用工具的链和代理，以及更一般地从模型获取结构化输出非常有用。

### ChatXAI.bind\_tools()

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

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

并在每次模型调用中传递。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from pydantic import BaseModel, Field


class GetWeather(BaseModel):
    """获取指定地点的当前天气"""

    location: str = Field(description="城市和州，例如：San Francisco, CA")


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

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
ai_msg = llm_with_tools.invoke(
    "what is the weather like in San Francisco",
)
ai_msg
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
AIMessage(content='I am retrieving the current weather for San Francisco.', additional_kwargs={'tool_calls': [{'id': '0', 'function': {'arguments': '{"location":"San Francisco, CA"}', 'name': 'GetWeather'}, 'type': 'function'}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 11, 'prompt_tokens': 151, 'total_tokens': 162, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'grok-beta', 'system_fingerprint': 'fp_14b89b2dfc', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-73707da7-afec-4a52-bee1-a176b0ab8585-0', tool_calls=[{'name': 'GetWeather', 'args': {'location': 'San Francisco, CA'}, 'id': '0', 'type': 'tool_call'}], usage_metadata={'input_tokens': 151, 'output_tokens': 11, 'total_tokens': 162, 'input_token_details': {}, 'output_token_details': {}})
```

## 实时搜索

xAI 支持 [实时搜索](https://docs.x.ai/docs/guides/live-search) 功能，使 Grok 能够基于网络搜索结果来支撑其回答：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_xai import ChatXAI

llm = ChatXAI(
    model="grok-3-latest",
    search_parameters={
        "mode": "auto",
        # 以下是可选参数示例：
        "max_search_results": 3,
        "from_date": "2025-05-26",
        "to_date": "2025-05-27",
    },
)

llm.invoke("请提供过去 24 小时内的世界新闻摘要。")
```

完整的网络搜索选项请参阅 [xAI 文档](https://docs.x.ai/docs/guides/live-search)。

***

## API 参考

有关 `ChatXAI` 所有功能和配置的详细文档，请访问 [API 参考](https://reference.langchain.com/python/integrations/langchain_xai/)。

***

<div className="source-links">
  <Callout icon="edit">
    [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/i18n\zh-CN\oss\python\integrations\chat\xai.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).
  </Callout>

  <Callout icon="terminal-2">
    [Connect these docs](/use-these-docs) to Claude, VSCode, and more via MCP for real-time answers.
  </Callout>
</div>
