运行之前
你只需要一个密钥即可。在 API 密钥页面 创建一个;新账户只需点击一次即可领取 $0.50 的免费试用额度,无需信用卡。导出它以便示例读取:
export API_KEY="YOUR_KEY"
pip install openai
npm install openai
API 遵循 OpenAI chat completions 格式。它提供 POST /v1/chat/completions 和 GET /v1/models,接受 Authorization: Bearer,并提供一个 ID 为 uncensored 的单一模型。该模型是一个由独立提供商运行的开放权重模型,经过调整,可在合法成人用途下不拒绝内容。它不是任何模型厂商的官方 API。它仅处理文本:无图像、音频、嵌入或微调。
下面的示例从最简单的调用到函数调用。如果您只需要最短的测试来验证 API 密钥是否有效,第一个 curl 命令就足够了。
使用 curl 发起首次请求,以及关键参数
curl https://api.glmapikey.com/v1/chat/completions \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "uncensored",
"messages": [
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "What is a mutex, in one sentence?"}
],
"temperature": 0.3,
"max_tokens": 80
}'
响应是一个 JSON 对象,choices[0].message.content 包含答案,usage 对象包含 prompt_tokens 和 completion_tokens。响应标头包括 X-Request-Id、X-Balance-USD 和两个 X-RateLimit-Limit 标头。在 curl 中添加 -i 即可查看它们。
temperature、top_p、stop、seed 以及 presence 和 frequency 惩罚参数会透传给模型。max_tokens 是可选的。如果不设置它,完成部分可以使用提示词之后 100,000-token 上下文窗口中剩余的所有空间。
chat completions 请求体有许多可选字段,但其中五个承担了主要工作。它们都会透传给模型。
| 字段 | 作用 | 典型用法 |
|---|---|---|
temperature | 较高的值提供更多样的措辞 | 提取 0.2,小说 0.8 |
top_p | 将采样限制在最可能的 token 上 | 除非进行调优,否则保持默认值 |
stop | 当出现字符串时结束回复 | 在分隔符(如空行)处截断 |
seed | 尽最大努力使采样可重复 | 比较两个提示词版本 |
presence_penalty、frequency_penalty | 避免重复 token | 文本循环时使用 0.3 等小值 |
每次只更改一个值并保持提示词不变,否则你无法判断哪个更改有效。对于任何涉及代码的任务(如分类或提取),使用低 temperature 和固定 seed,以便重新运行测试并看到相同结果。对于创意写作,提高 temperature 并让惩罚参数处理重复。
max_tokens 字段在此处是可选的。如果不设置它,回复可能会使用 100,000-token 上下文窗口中剩余的所有空间,这通常不是你希望的一行答案的情况。当你知道答案长度时,请设置它。
Python:带有记忆力的对话
API 是无状态的,因此你需要自己维护对话并每次发送。此循环维护消息列表并追加双方内容:
from openai import OpenAI
client = OpenAI(
base_url="https://api.glmapikey.com/v1",
api_key="YOUR_KEY",
)
messages = [{"role": "system", "content": "You are a helpful assistant."}]
while True:
user = input("you> ")
if not user:
break
messages.append({"role": "user", "content": user})
resp = client.chat.completions.create(model="uncensored", messages=messages)
reply = resp.choices[0].message.content
messages.append({"role": "assistant", "content": reply})
print("bot>", reply)
因为每次调用都会重新发送完整列表,输入 token 的数量会随着聊天长度而增长。每 1M 输入 token 价格为 $0.15,这很便宜,但在长会话中会累积,因此一旦对话长度超过您愿意付费的大小,就应删除旧消息。价格页面有计算示例。
Python 和 Node 中的流式输出
设置 stream: true,服务器会通过服务器发送的事件发送生成的 token。在 Python 中:
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Write four lines about the sea."}],
stream=True,
)
text = ""
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
piece = chunk.choices[0].delta.content
text += piece
print(piece, end="", flush=True)
if getattr(chunk, "usage", None):
print("\ntokens:", chunk.usage.prompt_tokens, chunk.usage.completion_tokens)
流以使用量信息结束,这就是循环检查它的原因。Node 中的相同操作:
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.glmapikey.com/v1",
apiKey: process.env.API_KEY,
});
const stream = await client.chat.completions.create({
model: "uncensored",
messages: [{ role: "user", content: "Write four lines about the sea." }],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}
关于限制的一个细节:流式请求会保留其并发槽位,直到流结束。如果你启动流但从未读取到结束,该槽位将保持忙碌。务必消费或关闭流。
用于结构化输出的 JSON 模式
当您的代码需要解析答案时,使用 response_format 请求 JSON 对象。同时在提示词中说明您想要的结构,因为格式标志保证有效的 JSON 语法,而不是您特定的模式。
import json
resp = client.chat.completions.create(
model="uncensored",
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": "Reply only with JSON: {\"title\": string, \"tags\": [string]}."},
{"role": "user", "content": "Suggest a title and three tags for a post about home espresso."},
],
temperature=0.2,
)
data = json.loads(resp.choices[0].message.content)
print(data["title"], data["tags"])
在使用之前检查所需的键是否存在,并在提取任务中保持低 temperature。如果解析失败,使用相同输入重试一次通常有效,且失败的请求不会收费。
函数调用:完整往返
函数调用允许模型要求您的代码运行函数。您在 tools 中描述函数,模型回复包含 tool_calls 条目,您运行它并将结果作为 role: "tool" 消息发送回去。
import json
def get_weather(city: str) -> dict:
return {"city": city, "temp_c": 18, "sky": "cloudy"}
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather for a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}]
messages = [{"role": "user", "content": "Is it warm in Lisbon right now?"}]
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)
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(get_weather(**args)),
})
final = client.chat.completions.create(
model="uncensored", messages=messages, tools=tools
)
print(final.choices[0].message.content)
else:
print(msg.content)
此处的函数返回固定数据,因此请替换为真实的查找逻辑。工具参数以 JSON 字符串形式传入,因此在执行操作前,务必解析并验证这些值。启用 stream: true 时,tool_calls 会分片到达,你需要在解析前将它们组装起来。使用 tool_choice 可在需要时强制调用特定工具。
示例的成本,以及导致浪费一小时的操作失误
运行示例的成本非常低,但了解计算过程会有所帮助。每 1M 输入 token 价格为 $0.15,每 1M 输出 token 价格为 $0.50:
- 对话循环,使用 1,200-token 提示词和 300-token 回复:输入费用 $0.00018,输出费用 $0.00015,总计 $0.00033。一千轮对话费用为 $0.33。
- 工具往返 进行两次调用。如果第一次调用输入 400 token,输出 60 token,第二次输入 500 token,输出 150 token,总计输入 900 token,输出 210 token:$0.000135 加上 $0.000105 等于 $0.00024。
- 流式输出 的成本与具有相同 token 计数的普通调用相同。它改变的是看到文本的时机,而不是成本。
$0.50 的免费试用额度足以支付该大小对话循环的 1,500 多轮($0.50 / $0.00033),因此您可以在充值前自由实验。失败和被拒绝的请求不会产生费用,这意味着解析错误导致您重新运行调用时,不会为失败的尝试产生费用。
- 错误的 Base URL。 它必须以
/v1结尾。在 SDK Base URL 中添加/chat/completions会导致 404,因为 SDK 会添加路径。 - 不同的模型名称。 从其他平台复制的名称在此处不存在。ID 为
uncensored。 - 期望 API 有记忆。 API 不会记住之前的调用。每次都要发送历史记录。
- 不加防护地解析模型的 JSON。 将
json.loads包裹在 try 块中,并为错误响应制定计划。 - 不关闭流。 未完成的流会占用一个并发槽位,而试用密钥只有两个。
- 将 API 密钥放在前端代码中。 应将其保留在服务器端。
如果仍有问题,请使用 curl 发送请求,并与你的代码生成的结果进行比较。使用 curl 可以排除 SDK 的干扰,使请求体中的差异一目了然。
读取用量、余额和错误信息
要查看 Python SDK 的响应头,请使用原始响应包装器:
raw = client.chat.completions.with_raw_response.create(
model="uncensored",
messages=[{"role": "user", "content": "Say ok."}],
)
print("request id:", raw.headers.get("x-request-id"))
print("balance usd:", raw.headers.get("x-balance-usd"))
print("rpm limit:", raw.headers.get("x-ratelimit-limit-requests"))
completion = raw.parse()
print(completion.usage.total_tokens)
每次调用都记录请求 ID,以便稍后指向单个请求。使用余额标头在额度耗尽前发出警报。
当达到限制时,API 会返回 HTTP 429 状态码,错误代码会告知你具体是哪一种限制:
| 代码或响应头 | 处理方式 | 处理方式 |
|---|---|---|
rate_limited | 每分钟请求过多(完整密钥为 300,试用密钥为 60) | 退避并分散调用 |
concurrency | 同时请求过多(完整密钥为 8,试用密钥为 2) | 等待正在进行的请求完成 |
Retry-After: 5 | 临时过载 | 五秒后重试 |
失败或被拒绝的请求不会产生费用。请求体最多可达 8 MB。有关完整参考文档以及如何重用现有客户端代码,请参阅 文档。有关如何获取 API 密钥的分步指南,请参阅 GLM API 密钥文章。
