OpenAI SDK

OpenAI 官方的 TypeScript 和 Python 库,可用于任意模型。

OpenAI SDK 可以用于这里的所有模型,而不只是 OpenAI 的模型。设置 baseURL 和密钥即可。

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://binference.io/api/v1",
  apiKey: process.env.BINF_API_KEY,
});

const stream = await client.chat.completions.create({
  model: "google/gemini-3.8-flash",
  messages: [{ role: "user", content: "Write a haiku about BNB Chain." }],
  max_tokens: 512,
  stream: true,
});

for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}

Responses

client.responses.create 用法相同,并且是无状态的:调用之间不保存任何内容,所以每次都要发送完整对话。

const reply = await client.responses.create({
  model: "openai/gpt-6.1-sol",
  input: "Summarize the last 24 hours of trades in one line.",
  max_output_tokens: 256,
});

console.log(reply.output_text);

重试

SDK 会自动重试返回 429 和 5xx 的请求,默认重试两次,并按 Retry-After-Ms 请求头给出的时间等待。在这里,这正是正确的做法。对于无人值守运行的任务,调高 maxRetries(Python 中为 max_retries)。参见重试。

其他兼容 OpenAI 的工具

任何能设置 OpenAI Base URL 的工具都可以用:LangChain 的 ChatOpenAI、LiteLLM、LlamaIndex,以及大多数 Agent 框架。把 https://binference.io/api/v1 作为 Base URL,把你的 binf_ 密钥作为 API 密钥。

本页目录