Nanbeige API Python 配置
如果你想要一个可以从 Python 调用的托管聊天 API,而无需学习新的客户端库,OpenAI SDK 已经能胜任。你只需更改两个设置,其余代码保持不变。
更新于

要点
- 使用官方的 openai 包,将 base_url 设置为 https://api.nanbeige.cc/v1,并将 model 设置为 uncensored。
- 流式输出、函数调用和 JSON 模式通过标准的 SDK 参数实现。
- 通过读取错误代码来处理 429 响应:rate_limited 和 concurrency 需要不同的修复方法。
- 这不是官方的 Nanbeige 服务,且仅支持文本。
简短版本
要进行与此服务通信的 nanbeige api python 设置,你需要 openai 包、一个 API 密钥和两个值:Base URL https://api.nanbeige.cc/v1 和模型 ID uncensored。以下是完整的代码块。
from openai import OpenAI
client = OpenAI(
base_url="https://api.nanbeige.cc/v1",
api_key="YOUR_API_KEY",
)
resp = client.chat.completions.create(
model="uncensored",
messages=[
{"role": "system", "content": "You are a direct, concise assistant."},
{"role": "user", "content": "Give me three names for a fantasy tavern."},
],
temperature=0.8,
)
print(resp.choices[0].message.content)
print(resp.usage)
在复制代码之前做一个快速说明。该网站不是 Nanbeige 供应商的 API,也不提供 Nanbeige 权重。它是一个独立的、兼容 OpenAI 的接口,运行一个经过调整的开放权重模型,以便在法律允许的成人用途中不进行内容拒绝。上述代码之所以有效,是因为请求和响应的形状符合 OpenAI 格式,而不是因为与特定模型家族有任何关联。
获取密钥并安装 SDK
使用 Google 或电子邮件和密码注册,并打开 API 密钥页面。新用户可以在那里一键领取 $0.50 的免费试用额度。无需信用卡,有效期为 7 天,每人限领一次。获取你的 API 密钥 页面显示了确切的按钮。
使用 pip install openai 安装客户端。任何最新版本的 SDK 都可以,因为聊天补全接口已经稳定了很长时间。虚拟环境可以将依赖项与系统 Python 隔离开来。
不要硬编码密钥。从环境变量中读取它,这样它绝不会进入版本控制:
import os
from openai import OpenAI
client = OpenAI(
base_url=os.environ.get("LLM_BASE_URL", "https://api.nanbeige.cc/v1"),
api_key=os.environ["LLM_API_KEY"],
)
MODEL = os.environ.get("LLM_MODEL", "uncensored")
将 base URL 和 model 保存在变量中会在以后派上用场。如果你将来将同一个脚本指向本地服务器或另一个提供商,你只需更改环境变量,而无需编辑代码。
先检查连接
在调试自己的逻辑之前,通过 models 调用确认密钥和 URL。这将返回可用模型 ID 列表,其中应包含 uncensored。
for m in client.models.list():
print(m.id) # base https://api.nanbeige.cc/v1, expect: uncensored
逐 token 流式输出回复
对于聊天界面和长输出,请流式传输响应,以便用户可以看到生成的文本。当你传入 stream=True 时,服务会发送服务器发送事件,SDK 会将它们转换为迭代器。如果你还请求使用情况,最后一个 chunk 会报告 token 计数,这对于记录成本很有用。
# client created as above, base_url https://api.nanbeige.cc/v1
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Write a short scene set on a night train."}],
stream=True,
stream_options={"include_usage": True},
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
if getattr(chunk, "usage", None):
print("\n", chunk.usage)
生产代码中有一个细节很重要:一个流式请求会占用其并发槽位,直到流结束。如果你的代码提前跳出循环,请关闭流以释放槽位,要么耗尽它,要么将其用作上下文管理器(with stream:)。留下半读流是发送很少请求时达到并发限制的经典方式。
工具调用和 JSON 模式
工具调用遵循 OpenAI 形状。你在 tools 中描述函数,模型可能会用 tool_calls 回答,你运行函数并以 role: "tool" 消息返回结果。这是一个完整的往返示例。
# client created as above, base_url https://api.nanbeige.cc/v1
import json
tools = [{
"type": "function",
"function": {
"name": "get_order_status",
"description": "Look up an order by its numeric ID.",
"parameters": {
"type": "object",
"properties": {"order_id": {"type": "integer"}},
"required": ["order_id"],
},
},
}]
messages = [{"role": "user", "content": "Where is order 4417?"}]
first = client.chat.completions.create(
model="uncensored", messages=messages, tools=tools, tool_choice="auto"
)
msg = first.choices[0].message
if msg.tool_calls:
messages.append(msg)
for call in msg.tool_calls:
args = json.loads(call.function.arguments)
result = {"order_id": args["order_id"], "status": "shipped"} # your real lookup here
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(result),
})
final = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
print(final.choices[0].message.content)
始终防御性地解析 arguments。模型生成一个 JSON 字符串,像任何模型一样,它偶尔会生成格式错误的 JSON,因此将 json.loads 包装在 try 块中,如果解析失败,则发送错误消息作为工具结果。
用于结构化输出的 JSON 模式
当你需要机器可读的输出时,将 response_format 设置为 JSON 对象,并在提示词中说明你需要的形状。JSON 模式要求有效的 JSON;它不强制执行你的模式,因此请验证你依赖的字段。
# client created as above, base_url https://api.nanbeige.cc/v1
resp = client.chat.completions.create(
model="uncensored",
messages=[
{"role": "system", "content": "Reply only with JSON: {\"title\": str, \"tags\": [str]}"},
{"role": "user", "content": "Describe a cozy detective novel set in a lighthouse."},
],
response_format={"type": "json_object"},
)
data = json.loads(resp.choices[0].message.content)
print(data["title"], data["tags"])
采样参数和上下文大小
通常的参数通过以下方式传递:temperature、top_p、stop、seed 以及频率和存在惩罚。对于创意写作,温度在 0.8 到 1.0 之间,配合适度的 top_p 往往能产生多样的散文。对于提取或分类,将温度降低到接近零,并设置 seed 以获得可重复的运行。
上下文窗口为 100,000 个 token,提示词和补全一起计算。max_tokens 是可选的;如果不设置,补全可以使用剩余的任何空间。当你确定答案应该很短时,最好设置它,因为它可以保护你免受响应成本超出预期的情况。请求体限制为 8 MB,这通常不是限制因素,但在粘贴大文档时值得了解。
文档 列出了所有支持的字段。只有 chat completions 和 models listing 存在,因此调用 image、audio 或 embeddings 接口的代码将在此处失败。如果你正在移植更大的项目,请检查这些调用。
处理 429 错误和并发
完整密钥允许 8 个并发请求和每分钟 300 个请求。试用密钥允许 2 个并发和每分钟 60 个。超过任一限制都会导致 HTTP 429,错误代码会告诉你达到了哪个限制:rate_limited 表示每分钟请求过多,concurrency 表示同时请求过多。在临时过载时,API 还会返回带有 Retry-After: 5 头的 429。
OpenAI SDK 默认会重试两次,但对于批处理作业,你应该自己控制行为。此辅助函数使用服务器的提示进行重试,并使用信号量限制并行性,从而首先保持在并发限制之下。
import asyncio
from openai import AsyncOpenAI, RateLimitError
aclient = AsyncOpenAI(base_url="https://api.nanbeige.cc/v1", api_key="YOUR_API_KEY")
gate = asyncio.Semaphore(6) # stay under 8 concurrent
async def ask(prompt, tries=4):
async with gate:
for attempt in range(tries):
try:
r = await aclient.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": prompt}],
)
return r.choices[0].message.content
except RateLimitError as e:
wait = 5 * (attempt + 1)
print("429, waiting", wait, "s:", e)
await asyncio.sleep(wait)
raise RuntimeError("gave up after retries")
async def main():
prompts = [f"Give one fun fact about the number {n}." for n in range(20)]
results = await asyncio.gather(*(ask(p) for p in prompts))
print(len(results), "done")
asyncio.run(main())
将信号量设置为 6 而不是 8 为重试和使用同一密钥的任何其他内容留出余地。响应头也有帮助:X-RateLimit-Limit-Requests 和 X-RateLimit-Limit-Concurrency 显示你密钥的限制,X-Balance-USD 显示剩余额度,X-Request-Id 标识调用,如果你需要联系 支持。
常见误区和快速修复
- 401 或身份验证错误。 密钥缺失、含有杂散空格,或者复制时带有尾随换行符。打印其长度并去除它。
- 未找到模型。 模型 ID 必须完全为
uncensored。其他服务的名称在此处不起作用。 - 在错误主机上的连接错误。 base URL 以
/v1结尾,没有尾随路径。如果你还设置了OPENAI_BASE_URL环境变量,请确保其匹配。 - 空输出或截断输出。 检查
finish_reason。值为length表示你达到了max_tokens或上下文窗口。 - 意外成本。 在开发期间打印
resp.usage。输入 token 每 1M 成本 $0.15,输出 token 每 1M 成本 $0.50,因此长输出是昂贵的部分。定价页面 有详细信息。
失败或拒绝的请求不会收费,因此一个出错的请求不花钱。提示词不用于训练。如果你遇到看起来错误的行为,请保存请求 ID 和确切的有效负载并发送给支持;这比凭记忆描述能更快得到答案。
更多指南
问答
我需要特殊的 Python 库吗?
否。官方 openai 包即可。将 base_url 设为 https://api.nanbeige.cc/v1,传入密钥,并使用模型 ID uncensored。
这是官方的 Nanbeige API 吗?
否。它是一个独立的兼容 OpenAI 的文本 API,运行不同的开放权重模型。它不由 Nanbeige 或任何其他模型供应商运营。
它支持从 Python 进行流式输出和函数调用吗?
支持。传入 stream=True 以获取服务器发送事件,并在末尾获取使用情况;使用 tools 和 tool_choice 参数进行工具调用。JSON 模式可通过 response_format 获得。
达到速率限制时会发生什么?
你会收到 HTTP 429 错误,错误代码为 rate_limited 或 concurrency。请退避,并将并发请求限制为完整密钥 8 个或试用密钥 2 个。
我可以调用 embeddings 或 image 接口吗?
不是。仅存在聊天补全和模型列表。该服务仅支持文本。