跳转到正文

开放模型兼容客户端

RightNow AIOpen models开放模型兼容客户端 更新于

本页内容

开放模型 API 兼容 OpenAI。如果你的代码已经在使用聊天 API,只需改三个值,其他都不用变。

三个值
Text
图示聊天 API 客户端要改的三个值。

在你已在用的客户端中改三个值:把基础 URL 改为 https://api.rightnowai.co/v1,把 API 密钥改为你的工作区密钥,把模型改为 GET /v1/models 返回的 ID。 其他都不用变。

TypeScript
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.rightnowai.co/v1",   // <- change
  apiKey: process.env.RIGHTNOW_API_KEY,      // <- change
});

const response = await client.chat.completions.create({
  model: "MODEL_ID",              // <- change
  messages: [{ role: "user", content: "Hello" }],
  max_tokens: 16384,
});

把 MODEL_ID 换成 开放模型 中任意可用的 ID。OpenAI API 使用的模型名称在这里不会映射到模型 ID,所以请传入 GET /v1/models 返回的模型 ID。

response.json
JSON
{
  "id": "chatcmpl-example",
  "object": "chat.completion",
  "model": "MODEL_ID",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "reasoning": "The user said hello. Greet them back.",
        "content": "Hello. How can I help you today?"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": { "prompt_tokens": 9, "completion_tokens": 28, "total_tokens": 37 }
}

reasoning 承载模型的推理,content 承载答案。这个示例中的 ID、文本和令牌数仅作说明。

只要所选模型的页面列出了该能力,流式、工具和结构化输出就使用相同的请求和响应结构。流以 data: [DONE] 结束,工具调用出现在助手消息上,用量出现在响应上。

设置输出预算

这个设置决定推理模型是否还有空间作答。推理令牌计入 max_tokens,在计费的响应上按输出价格计费。无论之后是否有答案,推理都按输出计费。

输出预算
Text
图示两个输出预算中的同一段推理。

推理令牌在答案之前就计入 max_tokens。2,048 个令牌的预算可能被推理用完:响应没有答案,推理按输出计费。16,384 个令牌的预算能容纳同样的推理以及其后的答案。预算是上限,不是花费:没有生成的部分不计费。

把前几个示例的 max_tokens 设为 16,384 与模型实时输出上限中较小的一个。如果公布了推荐的最小值,开放模型 中该模型的页面会写明:对于自己页面推荐至少 4,096 个输出令牌的模型,在实时上限允许时从这个最小值开始。

如果答案返回为空,请检查 finish_reason:"length" 表示需要提高预算,而不是模型什么都没生成。

模型的推理在哪里出现

开放模型 API 在消息上和每个流增量上以 reasoning 发出模型的推理。一些兼容聊天的客户端和提供商改用 reasoning_content 这个名称,所以只读这个名称的客户端能看到答案,却看不到推理。按客户端列出:

客户端可见的答案模型的推理
AI SDK (@ai-sdk/openai-compatible)text / text-deltareasoningText,以及 reasoning-delta 部分
聊天 API 的 SDK,Node 和 Pythonmessage.content / delta.contentmessage.reasoning / delta.reasoning
路由客户端message.contentmessage.reasoning_content
链式客户端(langchain-openai)content不公开,被集成丢弃
直接用 fetchdelta.contentdelta.reasoning

在上面每个客户端中,答案都是正确的。只是获取推理的方式不同,所以如果你想展示推理,请据此选择。

提示缓存与会话亲和性

前缀缓存是服务器在公布了缓存输入价格的模型上的自动行为。你不需要在每个请求中选择缓存的位置、保留或复用。对于多轮对话和智能体会话,请给重复的请求一个一致的会话身份,让这些请求留在其缓存前缀附近。

你发送的会发生什么
prompt_cache_options在 /v1/chat/completions 上以 400 hosted_parameter_not_supported 拒绝。在 /v1/responses 上只接受 null。
prompt_cache_retention在 /v1/chat/completions 上以 400 hosted_parameter_not_supported 拒绝。在 /v1/responses 上接受,但不起作用。
x-session-id一个请求头:显式的会话路由。把你的对话或任务 ID 作为它的值发送。x-parent-session-id 和旧版的 x-session-affinity 也被接受。
prompt_cache_key一个请求体字段:在没有显式会话身份时作为会话身份。
user转发给模型。它本身不是会话身份。

这些会话路由提示在 /v1/chat/completions 和 /v1/responses 上有效。会话请求头留在网关内,prompt_cache_key 在转发前被消耗,所以两种路由提示都不会到达模型。显式的身份能让你的对话或任务分组准确无误。

没有显式身份时,请求可能按开头的消息分组;没有消息文本的请求保持工作区级别的分组。放置的优先顺序以及 user 的单独作用,请参阅 会话。缓存令牌数和命中率请在 提示缓存 中查看,公布的命中率数据见所选模型的页面和价格页面。

框架配置

这些框架集成可以与 https://api.rightnowai.co/v1 配合使用。所用版本:ai 7.0.65,@ai-sdk/openai-compatible 3.0.30,openai 7.4.0(Node)和 2.54.0(Python),langchain-openai,litellm。

链式客户端

Python
import os
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="MODEL_ID",
    base_url="https://api.rightnowai.co/v1",
    api_key=os.environ["RIGHTNOW_API_KEY"],
    max_tokens=4096,
)

print(llm.invoke("Write a TypeScript retry helper.").content)

for chunk in llm.stream("Write a TypeScript retry helper."):
    print(chunk.content, end="", flush=True)

路由客户端

路由客户端通过它的提供商前缀 openai/ 访问开放模型 API,并把推理公开为 reasoning_content。

Python
import os
import litellm

response = litellm.completion(
    model="openai/MODEL_ID",
    api_base="https://api.rightnowai.co/v1",
    api_key=os.environ["RIGHTNOW_API_KEY"],
    messages=[{
        "role": "user",
        "content": "Write a TypeScript retry helper.",
    }],
    max_tokens=16384,
)
print(response.choices[0].message.content)

加上 stream=True 获取增量,读取 chunk.choices[0].delta.content,并跳过没有 choices 的用量帧。

索引客户端

使用 llama-index-llms-openai-like 中的 OpenAILike,并设置 is_chat_model=True。OpenAI 类对它未列出的任何 ID 都会抛出 Unknown model。

Python
import os
from llama_index.llms.openai_like import OpenAILike

llm = OpenAILike(
    model="MODEL_ID",
    api_base="https://api.rightnowai.co/v1",
    api_key=os.environ["RIGHTNOW_API_KEY"],
    is_chat_model=True,
)

print(llm.complete("Write a TypeScript retry helper.").text)

AI SDK

@ai-sdk/openai-compatible 读取 reasoning_content,没有时回退到 reasoning,也就是我们发出的名称,所以答案和推理都能拿到。

TypeScript
// Server-side only: never expose RIGHTNOW_API_KEY
// in browser code.
import {
  createOpenAICompatible,
} from "@ai-sdk/openai-compatible";
import { streamText } from "ai";

const apiKey = process.env.RIGHTNOW_API_KEY;
if (!apiKey) throw new Error("Set RIGHTNOW_API_KEY first.");

const gateway = createOpenAICompatible({
  name: "gateway",
  baseURL: "https://api.rightnowai.co/v1",
  apiKey,
});

const result = streamText({
  model: gateway.chatModel("MODEL_ID"),
  maxOutputTokens: 4096,
  prompt: "Write a TypeScript retry helper.",
});

for await (const part of result.fullStream) {
  if (part.type === "reasoning-delta") {
    process.stdout.write(part.text);
  }
  if (part.type === "text-delta") {
    process.stdout.write(part.text);
  }
}
generateText
用法相同,推理在 reasoningText 上。
maxOutputTokens
AI SDK 对上面所说输出预算的叫法。

即使模型做了推理,usage.outputTokenDetails.reasoningTokens 也报告 0,因为这个端点还没有把推理从 completion_tokens 中拆分出来。outputTokens 的总数是正确的,也是你被计费的数量。

直接用 fetch,不用 SDK

TypeScript
const url = "https://api.rightnowai.co/v1/chat/completions";
const response = await fetch(url, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.RIGHTNOW_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: "MODEL_ID",
    messages: [{
      role: "user",
      content: "Write a TypeScript retry helper.",
    }],
    max_tokens: 4096,
    stream: true,
    stream_options: { include_usage: true },
  }),
});

if (!response.ok) {
  const { error } = await response.json();
  throw new Error(
    `${response.status} ${error.code}: ${error.message}`,
  );
}

const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
let complete = false;

while (true) {
  const { done, value } = await reader.read();
  if (done) break;

  const text = decoder.decode(value, { stream: true });
  const lines = `${buffer}${text}`.split("\n");
  buffer = lines.pop() ?? "";

  for (const line of lines) {
    if (!line.startsWith("data: ")) continue;
    const payload = line.slice(6).trim();
    if (payload === "[DONE]") {
      complete = true;
      continue;
    }

    const chunk = JSON.parse(payload);
    if (chunk.error) {
      throw new Error(
        `${chunk.error.code}: ${chunk.error.message}`,
      );
    }
    const delta = chunk.choices?.[0]?.delta;
    // The model's thinking arrives as `reasoning`,
    // the answer as `content`.
    if (delta?.reasoning) process.stdout.write(delta.reasoning);
    if (delta?.content) process.stdout.write(delta.content);
  }
}

if (!complete) {
  throw new Error("The stream ended before [DONE]");
}

一行 data: 可能被拆在两次网络读取中,所以末尾不完整的那一行要留在 buffer 里,而不是拿去解析。丢掉这部分剩余内容,是在测试中正常的流上 JSON.parse 偶尔失败的常见原因。

兼容行为

有哪些端点

端点这里
POST /v1/chat/completions已提供,采用兼容聊天的约定。
POST /v1/responses已提供,采用兼容聊天的约定。它是 chat completions 的兼容适配层,不实现状态、网页搜索和文件搜索等托管工具、对话存储或后台任务。
POST /v1/messagesPOST /v1/messages/count_tokens已提供,采用兼容 Messages 的约定。
GET /v1/modelsGET /v1/models/{model}已提供。
GET /v1/creditsGET /v1/usageGET /v1/usage/daily已提供。
/v1/batches已提供。请参阅 Batch。
/v1/completions/v1/files/v1/assistants/v1/threads任何地方都不支持。/v1/completions 是旧版的非聊天路由。

Responses 客户端在 /v1/responses 上会遇到:

状态
store 会被接受,但始终按 false 处理;之后什么也取不回。previous_response_id、conversation 和 prompt 只接受 null,background 只接受 false 或 null。
工具
在页面列出了工具调用的模型上,函数工具可以完整运行。由于端点不保存状态,请在 input 中重新发送之前的输出项。
流
携带回复的流以 response.completed 结束,绝不会以 response.incomplete 结束。过长的提示会以 response.failed 结束流。
推理
output_text 只承载最终答案。模型的推理作为单独的 reasoning 输出项,在消息之前到达。
被截断的回复
status 为 "incomplete",incomplete_details.reason 为 max_output_tokens 或 content_filter。在把答案当作完整之前,请先检查 status。

端点的完整约定请参阅 Responses 参考。

你发送的字段会怎样

转发允许列表中的字段会原样到达模型。不在列表中的字段会在请求离开网关之前被丢弃,是静默丢弃而不是报错,所以今天能用的请求结构以后也能用。Chat completions 逐个列出允许列表中的字段,并点名少数带有网关行为的字段。

错误与重试

这些兼容聊天的路由使用聊天 API 的错误格式 { error: { message, type, code } },error.type 有六个值:invalid_request_error、authentication_error、permission_error、not_found_error、rate_limit_error 和 api_error。没有 server_error 类型;5xx 响应携带 api_error。Messages 路由使用 Messages 协议的格式。所有状态和代码见 错误,排查方法见 故障排查。

重试行为取决于你的客户端配置。在部分流可能已经到达你的应用之后,不要盲目重试会产生费用的请求;请改用 幂等键。在任何支持工单中都请附上响应头 X-Request-Id 的值。

把客户端和代理的超时设置为:流的第一个令牌最多等待 180 秒,整个响应最多 740 秒,无论是否流式。