安装你的 SDK
首先为您的语言安装官方库。我们支持大多数开发人员使用的标准 OpenAI SDK 包。通过终端安装软件包,为下一步做好准备。
配置 base URL 和密钥
将您的客户端指向我们的端点并设置您的凭据。使用 https://api.openrouterlimits.com/v1 作为您的基础 URL。替换 YOUR_API_KEY 使用您在“获取 API 密钥”页面上生成的密钥。通过更改 base_url 和 API 密钥,此设置适用于任何 OpenAI 兼容客户端。
发送您的第一个补全
发出请求以生成文本。使用模型 ID uncensored 访问我们调优后的开源权重模型。该模型不会拒绝合法的成人或争议性话题。向 /v1/chat/completions 附带您的消息。
curl https://api.openrouterlimits.com/v1/chat/completions \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "uncensored",
"messages": [{"role": "user", "content": "Process 5000 records in under 2 seconds"}]
}'
处理流式传输响应
启用流式传输以实时接收令牌。设置 stream 到 true 在请求体中。你将收到包含部分文本的服务器发送事件(SSE)。最后一个数据块包含用于计费的 token 使用情况。
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Tell the story in second person."}],
stream=True,
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
使用工具和 JSON 模式
集成函数调用或严格的 JSON 输出。使用 tools 用于函数调用的参数。设置 response_format 到 {"type": "json_object"} for JSON 模式。支持的参数包括 temperature, top_p, stop, seed, presence_penalty,以及 frequency_penalty.
import OpenAI from "openai";
const client = new OpenAI({ baseURL: "https://api.openrouterlimits.com/v1", apiKey: process.env.API_KEY });
const resp = await client.chat.completions.create({
model: "uncensored",
messages: [{ role: "user", content: "Draft a villain monologue for my game." }],
});
console.log(resp.choices[0].message.content);
监控 token 使用情况
跟踪您的使用情况并优雅地处理错误。您每个密钥每分钟可获得 300 个请求和 8 个并发请求。上下文窗口为 100,000 个 token。处理如 401(无效密钥)、402(无额度)和 429(速率限制)等错误。错误和拒绝免费。额度永不过期。
from openai import OpenAI
client = OpenAI(base_url="https://api.openrouterlimits.com/v1", api_key="YOUR_KEY")
resp = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Summarise this thread without softening it."}],
)
print(resp.choices[0].message.content)