> This is a page from the ElevenLabs documentation. For a complete page index, fetch https://elevenlabs.io/docs/llms.txt. For the full documentation in a single file, fetch https://elevenlabs.io/docs/llms-full.txt.

# Python SDK

> **Info**
>
> 另请参阅 [ElevenAgents 概览](/docs/zh/eleven-agents/overview)

## 安装

在项目中安装 `elevenlabs` Python 软件包：

```shell
pip install elevenlabs
# or
poetry add elevenlabs
```

如果要使用默认的音频输入／输出实现，还需要安装 `pyaudio` extra：

```shell
pip install "elevenlabs[pyaudio]"
# or
poetry add "elevenlabs[pyaudio]"
```

> **Info**
>
> 安装 `pyaudio` 软件包可能需要额外的系统依赖项。
>
> 更多信息请参阅 [PyAudio package README](https://pypi.org/project/PyAudio/)。
>
> #### Linux
>
> 在基于 Debian 的系统上，可使用以下命令安装依赖项：
>
> ```shell
> sudo apt-get update
> sudo apt-get install libportaudio2 libportaudiocpp0 portaudio19-dev libasound-dev libsndfile1-dev -y
> ```
>
> #### macOS
>
> 在使用 Homebrew 的 macOS 上，可使用以下命令安装依赖项：
>
> ```shell
> brew install portaudio
> ```

## 使用

本示例将创建一个简单脚本，用于运行与 ElevenLabs Agents 智能体的对话。

首先导入所需依赖项：

```python
import os
import signal

from elevenlabs.client import ElevenLabs
from elevenlabs.conversational_ai.conversation import Conversation
from elevenlabs.conversational_ai.default_audio_interface import DefaultAudioInterface
```

接着从环境变量加载智能体 ID 和 API 密钥：

```python
agent_id = os.getenv("AGENT_ID")
api_key = os.getenv("ELEVENLABS_API_KEY")
```

只有启用了身份验证的非公开智能体才需要 API 密钥。
公开智能体无需设置，代码在未设置 API 密钥时也能正常运行。

然后创建 `ElevenLabs` 客户端实例：

```python
elevenlabs = ElevenLabs(api_key=api_key)
```

现在初始化 `Conversation` 实例：

```python
conversation = Conversation(
    # API client and agent ID.
    elevenlabs,
    agent_id,

    # Assume auth is required when API_KEY is set.
    requires_auth=bool(api_key),

    # Use the default audio interface.
    audio_interface=DefaultAudioInterface(),

    # Simple callbacks that print the conversation to the console.
    callback_agent_response=lambda response: print(f"Agent: {response}"),
    callback_agent_response_correction=lambda original, corrected: print(f"Agent: {original} -> {corrected}"),
    callback_user_transcript=lambda transcript: print(f"User: {transcript}"),

    # Uncomment if you want to see latency measurements.
    # callback_latency_measurement=lambda latency: print(f"Latency: {latency}ms"),

    # Uncomment if you want to receive audio alignment data with character-level timing.
    # callback_audio_alignment=lambda alignment: print(f"Alignment: {alignment.chars}"),
)
```

这里使用 `DefaultAudioInterface`，它会使用系统默认音频输入／输出设备进行对话。
也可通过继承 `elevenlabs.conversational_ai.conversation.AudioInterface` 实现自己的音频接口。

现在可以开始对话。也可以选择传入自己的终端用户 ID，以将对话映射到用户。

```python
conversation.start_session(
    user_id=user_id # optional field
)
```

为在用户按下 `Ctrl+C` 时正常关闭，可添加一个调用 `end_session()` 的信号处理程序：

```python
signal.signal(signal.SIGINT, lambda sig, frame: conversation.end_session())
```

最后，等待对话结束并输出对话 ID（可用于查看对话历史和调试）：

```python
conversation_id = conversation.wait_for_session_end()
print(f"Conversation ID: {conversation_id}")
```

现在只需运行脚本并开始与智能体对话：

```shell
# For public agents:
AGENT_ID=youragentid python demo.py

# For private agents:
AGENT_ID=youragentid ELEVENLABS_API_KEY=yourapikey python demo.py
```