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

# 自动断线重连

因为并发限制、复杂的网络环境等情况，一些时候我们的连接可能因为一些预期外的状况而中断，通常这种偶发的中断并不会持续很久，我们希望在这种情况下业务依然可以稳定运行，使用简单的代码即可实现断线重连的需求。

<Note>
  本页示例默认使用最新模型 `kimi-k3`。K3 使用请求顶层 `reasoning_effort` 配置推理强度（支持 `"low"` / `"high"` / `"max"`，默认 `"max"`）。换用 `kimi-k2.6`、`kimi-k2.5` 等其他模型时，只需替换 `model` 字段，但各模型的参数配置存在差异，详见[模型参数参考](/docs/api/models-overview)。
</Note>

```python theme={null}
import os

from openai import OpenAI
import time

client = OpenAI(
    api_key=os.environ["MOONSHOT_API_KEY"],
    base_url = "https://api.moonshot.cn/v1",
)

def chat_once(msgs):
    response = client.chat.completions.create(
        model = "kimi-k3",
        messages = msgs
    )
    return response.choices[0].message.content

def chat(input: str, max_attempts: int = 100) -> str | None:
    messages = [
        {"role": "system", "content": "你是 Kimi，由 Moonshot AI 提供的人工智能助手，你更擅长中文和英文的对话。你会为用户提供安全，有帮助，准确的回答。同时，你会拒绝一切涉及恐怖主义，种族歧视，黄色暴力等问题的回答。Moonshot AI 为专有名词，不可翻译成其他语言。"},
    ]

    # 我们将用户最新的问题构造成一个 message（role=user），并添加到 messages 的尾部
    messages.append({
        "role": "user",
        "content": input,
    })
    st_time = time.time()
    for i in range(max_attempts):
        print(f"Attempts: {i+1}/{max_attempts}")
        try:
            response = chat_once(messages)
            ed_time = time.time()
            print("Query Successful!")
            print(f"Query Time: {ed_time-st_time}")
            return response
        except Exception as e:
            print(e)
            time.sleep(1)
            continue

    print("Query Failed.")
    return

print(chat("你好，请给我讲一个童话故事。"))
```

上面的代码实现了一个简单的断线重连功能，最多重复 100 次，每次连接之间等待 1s，你也可以根据具体的需求更改这些数值以及满足重试的条件。
