OpenAI API Python:使用 OpenAI SDK 调用我们的模型

对于 open ai api python 代码,你不需要特殊的库。一旦你设置了不同的 base URL 和密钥,并且模型 ID 为 uncensored,官方 openai 包即可与此服务配合使用。下面是一个带有复制粘贴示例的完整指南。
要点
- 安装 openai,然后将 base_url 和 api_key 传递给客户端;你的代码中无需其他更改。
- 流式输出、JSON 模式和函数调用均通过相同的 SDK 方法工作。
- 捕获 RateLimitError 并重试;限制为每分钟 300 个请求和 8 个并发请求(完整密钥)。
- 成本为每 1M 输入 token $0.15,每 1M 输出 token $0.50,仅对成功的请求收费。
安装并进行首次调用
你需要 Python 3.9 或更高版本以及官方 SDK。先在 密钥页面创建 API 密钥;新账户可一键领取 $0.50 试用额度,无需信用卡。
pip install openai
export API_KEY="your-key-here"
现在是最小的工作脚本。客户端接受 base URL 和密钥;请求使用模型 ID uncensored。
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.aiapisource.com/v1",
api_key=os.environ["API_KEY"],
)
resp = client.chat.completions.create(
model="uncensored",
messages=[
{"role": "system", "content": "You are a concise writing assistant."},
{"role": "user", "content": "Give me three opening lines for a mystery novel."},
],
temperature=0.8,
)
print(resp.choices[0].message.content)
print(resp.usage.prompt_tokens, resp.usage.completion_tokens)
这就是完整的集成方式。该服务实现了 POST /v1/chat/completions 和 GET /v1/models,涵盖了大多数脚本使用的功能。它是纯文本模型,因此图像、音频和嵌入接口不可用。
这是什么,不是什么
SDK 由 OpenAI 制作,但这里的接口不是 OpenAI 的。这是一个托管的开放权重模型,由独立提供商运行,并针对合法成人用途的无内容拒绝回答进行了调整。没有路由到 GPT 或任何其他供应商的模型。这就是为什么你需要更改 base URL:你正在与接受相同请求格式的不同服务器通信。
如果你正在迁移现有项目,请搜索 OpenAI( 和硬编码的模型名称。这是唯一需要编辑的两个地方。本站点的 GPT API 生产清单 涵盖了适用于任何 OpenAI 格式接口的习惯,例如超时和重试。
流式输出回复
对于聊天界面,你需要在生成时获取 token。设置 stream=True 并迭代。如果你想要账单数字,请在最后询问使用情况:
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Write a four-line poem about 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 chunk.usage:
print("\ntokens:", chunk.usage.prompt_tokens, chunk.usage.completion_tokens)
chunk.choices 的判空检查很重要:最后一个 chunk 可能包含使用情况而没有 choices。此外,流式请求会占用一个并发槽位,直到流结束,因此请务必读取完毕或关闭它。
JSON 模式
当你的代码需要解析答案时,切换到 JSON 模式并在提示词中描述键:
import json
resp = client.chat.completions.create(
model="uncensored",
response_format={"type": "json_object"},
messages=[
{"role": "user", "content": "Return JSON with keys name (string) and traits (list of 3 strings) for a fictional ship captain."}
],
)
character = json.loads(resp.choices[0].message.content)
print(character["name"], character["traits"])
通常能得到有效的 JSON,但不保证符合你想要的确切结构,因此请检查键并在失败时重试一次。
函数调用
在 tools 中描述函数,运行模型要求的任何操作,并使用 role: "tool" 将结果发回:
import json
tools = [{
"type": "function",
"function": {
"name": "roll_dice",
"description": "Roll a die with the given number of sides",
"parameters": {
"type": "object",
"properties": {"sides": {"type": "integer"}},
"required": ["sides"],
},
},
}]
messages = [{"role": "user", "content": "Roll a 20-sided die for my character."}]
first = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
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 = {"value": 14, "sides": args["sides"]} # replace with real logic
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)
else:
print(msg.content)
你可以传递 tool_choice 来强制函数。参数以 JSON 字符串形式提供,因此在使用前务必通过 json.loads 运行并验证它们。
错误、重试和异步
SDK 会自动重试某些失败,你可以使用 max_retries 设置重试次数。对于速率限制,捕获异常并等待。当你超过每分钟限制时,API 返回 HTTP 429 和代码 rate_limited;当同时运行的请求过多时,返回 concurrency;在临时过载时返回 Retry-After: 5 标头。
import time
from openai import RateLimitError
def ask(prompt, tries=4):
for attempt in range(tries):
try:
r = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": prompt}],
)
return r.choices[0].message.content
except RateLimitError:
time.sleep(5 * (attempt + 1))
raise RuntimeError("Still rate limited after retries")
对于批量处理,请使用异步客户端,并将并发请求数控制在限制以下。完整密钥允许 8 个并发请求和每分钟 300 个请求;试用密钥允许 2 个和 60 个。
import asyncio, os
from openai import AsyncOpenAI
aclient = AsyncOpenAI(base_url="https://api.aiapisource.com/v1", api_key=os.environ["API_KEY"])
sem = asyncio.Semaphore(6)
async def one(prompt):
async with sem:
r = await aclient.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": prompt}],
)
return r.choices[0].message.content
async def main():
prompts = [f"Write a tagline for product number {i}." for i in range(20)]
results = await asyncio.gather(*(one(p) for p in prompts))
print(len(results), "done")
asyncio.run(main())
使用 8 个槽位中的 6 个,为同一密钥上的其他流量留出空间。
保持对话
API 是无状态的。它在调用之间不记住任何内容,因此聊天只是你每次发送的消息列表。将回复附加到列表中,然后再次发送整个列表:
history = [{"role": "system", "content": "You are a patient writing coach."}]
def chat(user_text):
history.append({"role": "user", "content": user_text})
r = client.chat.completions.create(model="uncensored", messages=history)
reply = r.choices[0].message.content
history.append({"role": "assistant", "content": reply})
return reply
print(chat("Give me a prompt for a short story."))
print(chat("Make it darker and set it in a harbour town."))
每次调用发送的 token 比上一次多,并且每次调用都会对输入 token 收费。当列表变长时,删除最旧的轮次或将其替换为简短摘要。上下文窗口为 100,000 个 token(提示词加补全),这很多,但长历史会使每个请求更昂贵且启动更慢。
采样参数会原样透传:temperature、top_p、stop、seed 以及频率和存在惩罚。当你想要可重复的测试运行时,设置 seed 和低温度。
大批量运行前估算成本
计费按 token 从预付额度扣除:输入 token 每 100 万 $0.15,输出 token 每 100 万 $0.50。失败或被拒绝的请求不收费,且额度永不过期。假设一批 10,000 个请求,每个请求包含 1,500 个输入 token 和 400 个输出 token。输入 token 总数为 15,000,000,费用为 15 x $0.15 = $2.25。输出 token 总数为 4,000,000,费用为 4 x $0.50 = $2.00。该批次总费用为 $4.25。
响应头包含 X-Balance-USD,因此你可以通过 client.chat.completions.with_raw_response.create(...) 在代码中读取剩余余额。充值金额为 $20 到 $500 之间的任意整数,其中 $50 起额外赠送 5%,$100 起额外赠送 10%,$200 起额外赠送 15%。定价页面列出了支付方式,快速入门列出了所有支持的参数,包括 stop、seed 以及惩罚项。
更多指南
问答
我可以将此 API 与官方 OpenAI Python 包一起使用吗?
是的。安装 openai,将 base_url 设置为服务接口,将 api_key 设置为你的密钥,并使用模型 uncensored 调用 chat.completions.create。
流式输出或工具调用是否需要不同的库?
不需要。流式输出、JSON 模式和函数调用通过相同的 SDK 方法工作,使用常规参数。
这是 OpenAI 的模型吗?
不是。这是一个由独立提供商运行的开放权重模型。请求格式相同,因此 SDK 可以正常工作。
我的提示词会用于训练模型吗?
不会。通过 API 发送的提示词不用于训练。
只差一张表单,即可获得密钥
创建账户,复制密钥,更改 base URL。这就是全部设置。