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

# Python SDK

> 使用官方 OpenAI Python SDK 调用 Yelu 的聊天、Responses、流式输出与错误处理。

官方 OpenAI Python SDK 只需修改 API Key 与 Base URL 即可使用 Yelu。

## 安装

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
python -m pip install --upgrade openai
```

## 配置客户端

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["YELU_API_KEY"],
    base_url="https://api.yelu.ai/v1",
    timeout=60.0,
    max_retries=2,
)
```

## Chat Completions

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
completion = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[
        {"role": "system", "content": "回答简洁。"},
        {"role": "user", "content": "解释向量搜索。"},
    ],
    max_completion_tokens=200,
)
print(completion.choices[0].message.content)
print(completion.usage)
```

## Responses

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
response = client.responses.create(
    model="gpt-4o-mini",
    instructions="面向软件工程师回答。",
    input="什么是背压？",
    max_output_tokens=200,
)
print(response.output_text)
```

## 流式输出

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
stream = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "写一段简短发布说明。"}],
    stream=True,
)
for chunk in stream:
    print(chunk.choices[0].delta.content or "", end="", flush=True)
```

## 错误处理

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import openai

try:
    client.models.list()
except openai.AuthenticationError as exc:
    print("检查 YELU_API_KEY", exc.status_code)
except openai.RateLimitError as exc:
    print("退避后再重试", exc.status_code)
except openai.APIConnectionError as exc:
    print("网络或 TLS 失败", exc.__cause__)
except openai.APIStatusError as exc:
    print("Yelu 返回", exc.status_code, exc.response.text)
```

<Tip>当应用同时调用其他 OpenAI-compatible 服务时，应显式设置 Yelu Base URL，避免环境变量变化导致请求发往错误服务。</Tip>

异步应用可使用 `AsyncOpenAI`，参数与同步客户端一致。更多协议细节参见[聊天示例](/zh/examples/chat)、[流式指南](/zh/guides/streaming)与[错误处理](/zh/errors)。
