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

# 旧版文本补全

> 使用 prompt 完成旧版同步与流式文本补全。

`POST /v1/completions` 面向 `prompt` 文本补全，不是 `messages` 对话。先由部署方确认模型和渠道支持该接口；新应用通常从 [Chat](/zh/api-reference/chat-completions) 或 [Responses](/zh/api-reference/responses) 开始。不要因 SDK 中存在 `completions` 方法就假定对话模型可用。

本例限定单条文本、单个输出，读取 `choices[0].text`，要求 `finish_reason=stop`。流式增量同样读取 `text`，不是 Chat 的 `delta.content`；`length`、`content_filter`、断流或空文本均作为未完成处理。示例缓冲文本，完成后才打印；不会把半成品当最终结果。SDK 解析 SSE，本例以完成字段验证生成结果，不实现断线恢复。

按 [Python SDK](/zh/guides/python)安装依赖并设置 `API_BASE_URL`（含 `/v1`）、`API_KEY`、`API_MODEL`。

```bash theme={null}
.venv/bin/python examples/legacy-completions.py sync
.venv/bin/python examples/legacy-completions.py stream
```

参数和格式见 [API 参考](/zh/api-reference/completions)。不承诺所有渠道保留 `suffix`、`echo`、`logprobs` 或 `best_of` 等旧字段；先按实际转换器验证。协议参照 [OpenAI Completions](https://developers.openai.com/api/reference/resources/completions/methods/create)，网关范围以本项目实现为准。

```python theme={null}
import os
import sys
from openai import OpenAI, APIConnectionError, APIStatusError

mode = sys.argv[1] if len(sys.argv) == 2 else "sync"
if mode not in ("sync", "stream"):
    raise SystemExit("Usage: python legacy-completions.py [sync|stream]")
with OpenAI(base_url=os.environ["API_BASE_URL"].rstrip("/"),
            api_key=os.environ["API_KEY"], timeout=60.0, max_retries=0) as client:
    try:
        result = client.completions.create(model=os.environ["API_MODEL"],
            prompt="Complete this sentence: A good API guide should", stream=mode == "stream")
        text, finished = "", False
        if mode == "sync":
            if len(result.choices) != 1 or result.choices[0].index != 0:
                raise ValueError("Expected one completion.")
            choice = result.choices[0]
            if choice.finish_reason != "stop" or not isinstance(choice.text, str):
                raise ValueError("Incomplete completion.")
            text, finished = choice.text, True
        else:
            with result:
                for chunk in result:
                    if not chunk.choices:
                        continue  # Usage-only chunk, not a completion marker.
                    if finished or len(chunk.choices) != 1 or chunk.choices[0].index != 0:
                        raise ValueError("Unexpected completion chunk.")
                    choice = chunk.choices[0]
                    if not isinstance(choice.text, str) or choice.finish_reason not in (None, "stop"):
                        raise ValueError("Incomplete completion.")
                    text += choice.text
                    if len(text) > 1_000_000:
                        raise ValueError("Example output limit exceeded.")
                    finished = choice.finish_reason == "stop"
        if not finished or not text.strip():
            raise ValueError("Missing completed text.")
        print(text)
    except APIStatusError as error:
        raise SystemExit(f"Request failed (HTTP {error.status_code}). No automatic retry.")
    except APIConnectionError:
        raise SystemExit("Connection failed. No automatic retry.")
    except Exception:
        raise SystemExit("Completion did not produce valid complete text.")
```

[Read in English](/en/guides/legacy-completions)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.