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

# SDK 和 API 使用

> 使用您现有的 OpenAI SDK。更改基础 URL，并添加 `start_within` 字段。

FlexInference 接受与 OpenAI 兼容的请求。保留官方 OpenAI SDK 或 `curl`，将基础 URL 设置为 FlexInference，使用您的 `flex_live_` 密钥进行身份验证，并在每个请求中发送必需的 `start_within` 字段。如果省略该字段，您将收到 `400 missing_start_within` 错误。

```
Base URL   https://api.flexinference.com/v1
Auth       Authorization: Bearer flex_live_...
```

FlexInference 支持四个 POST 端点，并将每个调用者请求结构转换为规划器选择的提供商接口：

* `POST /v1/responses`：Responses API
* `POST /v1/chat/completions`：Chat Completions API
* `POST /v1/interactions`：Interactions API（适用于 OpenAI、Gemini 和 Anthropic 模型）
* `POST /v1/messages`：Anthropic Messages API（适用于**任何**模型）

每个端点还接受可选的有序 `provider` 数组来固定路由；请参阅下面的[固定路由](#pinning-the-route)。

OpenAI SDK 支持 `/v1/responses` 和 `/v1/chat/completions`。它不暴露 `/v1/interactions` 或 `/v1/messages`，因此请使用 `curl` 或 FlexInference 原生 SDK（[Python](https://pypi.org/project/flexinference/)、[TypeScript](https://www.npmjs.com/package/flexinference/)）访问这些端点。

## 配置客户端

<CodeGroup>
  ```python Python theme={null}
  from openai import OpenAI

  client = OpenAI(
      base_url="https://api.flexinference.com/v1",
      api_key="flex_live_...",
  )
  ```

  ```typescript Node theme={null}
  import OpenAI from "openai";

  const client = new OpenAI({
    baseURL: "https://api.flexinference.com/v1",
    apiKey: "flex_live_...",
  });
  ```

  ```bash curl theme={null}
  export FLEX_API_KEY="flex_live_..."
  export FLEX_BASE_URL="https://api.flexinference.com/v1"
  ```
</CodeGroup>

## 传递 `start_within`

`start_within` 告诉 FlexInference 请求开始返回数据前可以等待多长时间。使用 `00h-01m-00s` 这样的持续时间表示一分钟。持续时间会启动 flex 竞速：规划器会在该预算内尝试更经济的 flex 层级，如果 flex 无法及时启动，则会升级到 standard 层级。

OpenAI SDK 不对 `start_within` 进行类型检查，因此在 Python 中通过 `extra_body` 传递，在 Node 中通过无类型请求对象传递。

<CodeGroup>
  ```python Python theme={null}
  resp = client.responses.create(
      model="gpt-5.5",
      input="Summarize this contract.",
      extra_body={"start_within": "00h-01m-00s"},
  )
  ```

  ```typescript Node theme={null}
  const resp = await client.responses.create({
    model: "gpt-5.5",
    input: "Summarize this contract.",
    start_within: "00h-01m-00s",
  } as any);
  ```

  ```bash curl theme={null}
  curl "$FLEX_BASE_URL/responses" \
    -H "Authorization: Bearer $FLEX_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "gpt-5.5",
      "input": "Summarize this contract.",
      "start_within": "00h-01m-00s"
    }'
  ```
</CodeGroup>

有关所有可用值，请参阅[截止时间路由](/zh/deadline-routing)。

## 读取 flex 结果

读取响应体中的 `service_tier` 以及 `x-flexinference-flex-*` 响应头。`x-flexinference-flex-applied` 指示响应是否由 flex 提供。`x-flexinference-flex-reason` 提供机器可读的结果，包括 `flex_committed` 和 `flex_lost_race`。无法运行 flex 竞速的持续时间会返回 `400 flex_unsupported_for_anthropic` 或 `400 flex_model_not_capable`。有关如何读取这些头信息，请参阅[截止时间路由](/zh/deadline-routing)，有关完整列表，请参阅[错误](/zh/errors)。

## 流式传输

设置 `stream: true` 并像使用 OpenAI 一样消费事件。流式传输不会改变路由。FlexInference 首先确定一个层级，然后在该层级开始响应后流式传输 token。

<CodeGroup>
  ```python Python theme={null}
  stream = client.responses.create(
      model="gpt-5-nano",
      input="Count to ten.",
      stream=True,
      extra_body={"start_within": "00h-00m-20s"},
  )
  for event in stream:
      if event.type == "response.output_text.delta":
          print(event.delta, end="")
  ```

  ```typescript Node theme={null}
  const stream = await client.responses.create({
    model: "gpt-5-nano",
    input: "Count to ten.",
    stream: true,
    start_within: "00h-00m-20s",
  } as any);

  for await (const event of stream) {
    if (event.type === "response.output_text.delta")
      process.stdout.write(event.delta);
  }
  ```

  ```bash curl theme={null}
  curl "$FLEX_BASE_URL/responses" \
    -H "Authorization: Bearer $FLEX_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "gpt-5-nano",
      "input": "Count to ten.",
      "stream": true,
      "start_within": "00h-00m-20s"
    }'
  ```
</CodeGroup>

## 超时

`start_within` 限制的是请求开始的时间，而不是总生成时间。FlexInference 会一直持有 HTTP 响应，直到某个层级确定。一旦 flex 确定，它将运行至完成；FlexInference 不会因为生成速度慢而将已确定的请求切换到 standard 层级。请将您的客户端超时时间设置为覆盖等待窗口以及模型响应所需的时间。

OpenAI SDK 默认超时时间为 10 分钟，这与允许的最长 `start_within` 时间相匹配。如果生成可能在较长窗口的末尾开始，请将超时时间提高到默认值以上。较短的超时时间可能会在 FlexInference 返回结果之前取消请求。请参阅 [`client_closed_request`](/zh/errors#client_closed_request)。

<CodeGroup>
  ```python Python theme={null}
  client = OpenAI(
      base_url="https://api.flexinference.com/v1",
      api_key="flex_live_...",
      timeout=600,  # seconds; keep it at least as long as your start_within
  )
  ```

  ```typescript Node theme={null}
  const client = new OpenAI({
    baseURL: "https://api.flexinference.com/v1",
    apiKey: "flex_live_...",
    timeout: 600_000, // ms; keep it at least as long as your start_within
  });
  ```
</CodeGroup>

FlexInference 原生 SDK（[Python](https://pypi.org/project/flexinference/)、[TypeScript](https://www.npmjs.com/package/flexinference/)）会自动处理此问题。它们根据 `start_within` 调整首次响应的等待时间，使用空闲超时限制停滞的流，并对流不设总限制，以便长时间的响应可以完成。非流式调用会保留一个总预算。每个超时都可以在客户端和每个请求中配置。

## 重试瞬时上游故障

当您的请求因瞬时 `429` 或 `5xx` 错误而未能启动时，添加一个可选的 `retry` 对象以重新尝试服务您请求的层级。传递方式与传递 `start_within` 相同。

<CodeGroup>
  ```python Python theme={null}
  resp = client.responses.create(
      model="gpt-5.5",
      input="Summarize this contract.",
      extra_body={"start_within": "00h-01m-00s", "retry": {"count": 2}},
  )
  ```

  ```typescript Node theme={null}
  const resp = await client.responses.create({
    model: "gpt-5.5",
    input: "Summarize this contract.",
    start_within: "00h-01m-00s",
    retry: { count: 2 },
  } as any);
  ```

  ```bash curl theme={null}
  curl "$FLEX_BASE_URL/responses" \
    -H "Authorization: Bearer $FLEX_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "gpt-5.5",
      "input": "Summarize this contract.",
      "start_within": "00h-01m-00s",
      "retry": { "count": 2 }
    }'
  ```
</CodeGroup>

`count` 的范围是 `1` 到 `5`，`backoff` 是 `"exponential"`（默认）或 `"linear"`，`jitter` 默认为 `true`。重试仅在响应确定之前进行，会遵守提供商的 `Retry-After` 头，并与您的客户端 SDK 自身的重试机制叠加。有关完整行为和 `x-flexinference-retries` 响应头，请参阅[截止时间路由](/zh/deadline-routing)。

## 固定路由

可选的有序 `provider` 数组用于固定哪个提供商路由服务您的请求。它适用于所有端点：`/v1/responses`、`/v1/chat/completions`、`/v1/interactions` 和 `/v1/messages`。元素 0 是主路由和唯一的 flex 门控；元素 1 到 n 是相同模型的备用链，当某个路由瞬时失败时按顺序尝试。如果省略，FlexInference 将使用模型的原生路由。传递方式与传递 `start_within` 相同。

您命名的每个路由都需要先配置其密钥。如果缺少密钥，该路由将返回 `400` 错误，并且不会回退到下一个路由，因此在命名每个路由之前，请在仪表板中添加其密钥。请参阅[提供商路由](/zh/models)。

<CodeGroup>
  ```python Python theme={null}
  resp = client.responses.create(
      model="gpt-5.5",
      input="Summarize this contract.",
      extra_body={"start_within": "default", "provider": ["openai"]},
  )
  ```

  ```typescript Node theme={null}
  const resp = await client.responses.create({
    model: "gpt-5.5",
    input: "Summarize this contract.",
    start_within: "default",
    provider: ["openai"],
  } as any);
  ```

  ```bash curl theme={null}
  curl "$FLEX_BASE_URL/responses" \
    -H "Authorization: Bearer $FLEX_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "gpt-5.5",
      "input": "Summarize this contract.",
      "start_within": "default",
      "provider": ["openai"]
    }'
  ```
</CodeGroup>

`google`、`openai` 和 `anthropic` 是直接路由。`vertex` (Gemini) 和 `bedrock` (Claude) 是云路由，它们在 Google Vertex AI 和 Amazon Bedrock 上提供相同的模型；每个都需要该云服务自己的 BYOK 密钥。无效数组会返回 `400 invalid_provider_chain`，无法服务模型的路由会返回 `400 provider_model_mismatch`，而以云路由开头的持续时间 `start_within` 会返回 `400 flex_unsupported_on_cloud`。FlexInference 原生 SDK 会对 `provider` 进行类型检查并在请求离开您的进程之前本地检查其形状；OpenAI SDK 不对其进行类型检查，因此请通过 `extra_body` 或无类型对象传递。有关有效链矩阵，请参阅[提供商路由](/zh/models)。

## 聊天补全

Chat Completions 使用相同的 `start_within` 规则。当请求可以通过规范 Responses 路由时，持续时间会启动 flex 竞速。OpenAI Chat 请求会通过规范 Responses 路由，除非原生 Chat 参数需要 OpenAI Chat 直通；仅限原生的 Chat 参数不能与持续时间 `start_within` 结合使用。

<CodeGroup>
  ```python Python theme={null}
  resp = client.chat.completions.create(
      model="gpt-5.5",
      messages=[{"role": "user", "content": "Hello!"}],
      extra_body={"start_within": "default"},
  )
  print(resp.choices[0].message.content)
  ```

  ```typescript Node theme={null}
  const resp = await client.chat.completions.create({
    model: "gpt-5.5",
    messages: [{ role: "user", content: "Hello!" }],
    start_within: "default",
  } as any);

  console.log(resp.choices[0].message.content);
  ```
</CodeGroup>

## 交互

Interactions 端点是 OpenAI、Gemini 和 Anthropic 模型的另一种调用者格式。`start_within` 的应用方式相同。将 `input` 作为字符串、内容部分数组或多轮步骤列表发送。`system_instruction`、`tools` 和 `response_format` 映射到相同的上游功能。

<CodeGroup>
  ```python Python theme={null}
  from flexinference import FlexInference, interaction_output_text

  client = FlexInference(api_key="flex_live_...")

  resp = client.interactions.create({
      "model": "gemini-3.5-flash",
      "input": "Summarize this contract.",
      "start_within": "00h-01m-00s",
  })
  print(interaction_output_text(resp))
  ```

  ```typescript Node theme={null}
  import { FlexInference, interactionText } from "flexinference";

  const client = new FlexInference({ apiKey: "flex_live_..." });

  const resp = await client.interactions.create({
    model: "gemini-3.5-flash",
    input: "Summarize this contract.",
    start_within: "00h-01m-00s",
  });

  console.log(interactionText(resp));
  ```

  ```bash curl theme={null}
  curl "$FLEX_BASE_URL/interactions" \
    -H "Authorization: Bearer $FLEX_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "gemini-3.5-flash",
      "input": "Summarize this contract.",
      "start_within": "00h-01m-00s"
    }'
  ```
</CodeGroup>

响应是一个 `interaction` 对象。输出位于 `steps` 中。`usage` 将 token 计数分为输入、输出、思考、缓存、工具使用和总计。

```json theme={null}
{
  "id": "interaction_...",
  "object": "interaction",
  "status": "completed",
  "model": "gemini-3.5-flash",
  "created": 1750000000,
  "updated": 1750000000,
  "service_tier": "flex",
  "usage": {
    "total_input_tokens": 1200,
    "total_output_tokens": 180,
    "total_thought_tokens": 64,
    "total_cached_tokens": 0,
    "total_tokens": 1444,
    "total_tool_use_tokens": 0
  },
  "steps": [
    { "type": "model_output", "content": [{ "type": "text", "text": "..." }] }
  ]
}
```

当步骤为 `function_call` 时，`status` 为 `requires_action`；当输出被截断时为 `incomplete`；出错时为 `failed`；否则为 `completed`。`generation_config.thinking_level` 映射到 `reasoning.effort`。额外的 `generation_config.*` 键在 Gemini 模型上会直通。在非 Gemini 模型上，任何未映射的 `generation_config.*` 键都会因 `unsupported_generation_config` 而失败。调用者提供的 `service_tier` 会因 `service_tier_not_allowed` 而被拒绝；请参阅[错误](/zh/errors)。

FlexInference 从 `start_within` 派生层级选择。如果您发送 `service_tier`，请求将因 `service_tier_not_allowed` 而失败。请移除该字段并通过 `start_within` 来表达层级。有关完整列表和示例响应体，请参阅[错误](/zh/errors)。

## 消息

Messages 端点使用 **Anthropic Messages** 请求和响应结构。它适用于**任何**模型，因为 FlexInference 通过规范形式进行转换。`start_within` 是必需的。Anthropic 要求 `max_tokens`；当您设置它时，FlexInference 会转发它，而当您省略它时，FlexInference 不会合成默认值。将 `messages` 作为 `{role, content}` 轮次发送，其中 `content` 是字符串或内容块数组。`system`、`tools`、`tool_choice` 和 `thinking` 映射到相同的上游功能。

<CodeGroup>
  ```python Python theme={null}
  from flexinference import FlexInference, message_output_text

  client = FlexInference(api_key="flex_live_...")

  resp = client.messages.create({
      "model": "claude-opus-4-8",
      "max_tokens": 1024,
      "messages": [{"role": "user", "content": "Summarize this contract."}],
      "start_within": "default",
  })
  print(message_output_text(resp))
  ```

  ```typescript Node theme={null}
  import { FlexInference, messageText } from "flexinference";

  const client = new FlexInference({ apiKey: "flex_live_..." });

  const resp = await client.messages.create({
    model: "claude-opus-4-8",
    max_tokens: 1024,
    messages: [{ role: "user", content: "Summarize this contract." }],
    start_within: "default",
  });

  console.log(messageText(resp));
  ```

  ```bash curl theme={null}
  curl "$FLEX_BASE_URL/messages" \
    -H "Authorization: Bearer $FLEX_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "claude-opus-4-8",
      "max_tokens": 1024,
      "messages": [{ "role": "user", "content": "Summarize this contract." }],
      "start_within": "default"
    }'
  ```
</CodeGroup>

响应是一个 Anthropic `message` 对象。输出位于 `content` 中，作为 `text`、`thinking` 和 `tool_use` 块。`usage.service_tier` 是服务的层级，可以是 flex 或 standard。

```json theme={null}
{
  "id": "msg_...",
  "type": "message",
  "role": "assistant",
  "model": "claude-opus-4-8",
  "content": [{ "type": "text", "text": "..." }],
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 1200,
    "cache_read_input_tokens": 0,
    "cache_creation_input_tokens": 0,
    "output_tokens": 180,
    "output_tokens_details": { "thinking_tokens": 64 },
    "service_tier": "standard"
  }
}
```

`stop_reason` 在正常完成时为 `end_turn`，截断时为 `max_tokens`，模型调用工具时为 `tool_use`，拒绝时为 `refusal`。`thinking` 映射到每个模型的 `reasoning.effort`。在 Claude 模型上，原生 Anthropic 字段，例如 `top_k`、`stop_sequences`、`cache_control` 块、引用以及 `document` 或 `file` 内容块会直通。在 OpenAI 或 Gemini 模型上，带有 base64 源的 `document` 和 `file` 内容块会转换为规范的 `input_file` 并且不会被拒绝。远程 URL 文档仍然取决于目标提供商自身的支持。其他 Anthropic 原生字段，包括 `top_k`、`stop_sequences`、`cache_control` 块和引用，在跨提供商时会因 `unsupported_parameter` 而失败。调用者提供的 `service_tier` 总是会因 `service_tier_not_allowed` 而失败；请参阅[错误](/zh/errors)。

## 其他一切保持不变

工具调用、结构化输出 (`response_format`)、视觉和推理会直通到所选的提供商。请使用提供商的常规字段来实现这些功能。

<Warning>
  当需要原生 Chat 直通时，Chat 原生参数会在 OpenAI 模型上直通：`presence_penalty`、`frequency_penalty`、`logit_bias`、`logprobs`、`top_logprobs`、`seed`、`stop`、`prediction`、`audio`、非文本 `modalities` 和 `web_search_options`。在 Gemini 或 Claude 模型上，将这些字段中的任何一个设置为实际值都会因 `unsupported_parameter` 而失败。Chat Completions `n > 1` 总是会因 `unsupported_value` 而失败。对于规范路径上的网络搜索，请使用 Responses `web_search` 工具。
</Warning>
