中文 ▾
获取 API 密钥

Python 版 NSFW Grok API:使用 OpenAI SDK 配置

等轴测终端通过管道向 API 服务器立方体发送数据流

最快的 NSFW Grok API Python 配置方式是使用指向独立无审查接口的官方 OpenAI SDK。你只需更改两个值,其余代码保持不变。

更新于

要点

Mistral 模型包含内置内容过滤器,可能会拦截合法的成人内容,需要变通方法。

Mistral 长上下文使用的 token 成本可能超过固定费率的无审查替代方案。

单个 API 密钥适用于所有 Mistral 接口,驳斥了需要单独 NSFW 密钥的说法。

对于无拒绝的纯文本生成,专用无审查 API 通常提供更高的价值和可靠性。

本页内容

你连接到的内容

这是一个面向单一开放权重模型的独立 API,经过调整可在合法成人用途中无内容拒绝地回答问题。它不是 xAI 的 Grok,也不是任何供应商的官方 API。人们搜索的名称 nsfw grok 描述的是他们想要的行为,而非背后的产品。如果需要官方 Grok 模型,请使用 xAI 的 API。

该接口遵循 OpenAI chat completions 协议。存在两种方法:POST /v1/chat/completions 和 GET /v1/models。认证使用 Authorization 标头中的 Bearer token。模型 ID 为 uncensored,上下文窗口为 100,000 token(提示词和补全合计),服务仅支持文本。由于遵循 OpenAI 格式,任何允许设置 Base URL 的客户端均可使用,Python 的 openai 包是常用选择。

你需要先获取密钥。使用 Google 或邮箱密码注册,然后打开 API 密钥页面。那里提供一键领取 $0.50 试用额度,有效期 7 天,每人限领一次,无需填写支付信息。这对于本文介绍的所有功能来说已经足够了。

安装并发送第一个请求

创建虚拟环境并安装 SDK。

python -m venv .venv
source .venv/bin/activate
pip install openai
export NSFWGROK_KEY="paste-your-key-here"
curl -s https://api.nsfwgrok.top/v1/models -H "Authorization: Bearer $NSFWGROK_KEY"

上一条命令调用 GET /v1/models 并应列出 uncensored。如果返回 401,说明密钥错误或缺失。现在进行 Python 调用:

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.nsfwgrok.top/v1",
    api_key=os.environ["NSFWGROK_KEY"],
)

resp = client.chat.completions.create(
    model="uncensored",
    messages=[
        {"role": "system", "content": "You are a blunt, concise writing assistant."},
        {"role": "user", "content": "Give me three opening lines for a noir short story."},
    ],
    temperature=0.9,
    max_tokens=300,
)
print(resp.choices[0].message.content)

将密钥保存在环境变量中,不要放在仓库里。max_tokens 是可选的;不设置它,补全将使用 100,000 token 窗口中剩余的所有空间。设置它仍是一个好习惯,因为它可以限制失控回复时的最大账单。

流式输出回复

对于交互内容,请启用流式输出。设置 stream=True 并遍历 chunk;服务器通过服务器发送事件 (SSE) 推送数据。用量数据在流结束时返回。

import os
from openai import OpenAI

client = OpenAI(base_url="https://api.nsfwgrok.top/v1", api_key=os.environ["NSFWGROK_KEY"])

stream = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Write a 120-word scene set in a rain-soaked port town."}],
    stream=True,
)

usage = None
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):
        usage = chunk.usage
print()
if usage:
    print("tokens in/out:", usage.prompt_tokens, usage.completion_tokens)

一个细节常让人措手不及。流式请求会占用并发槽位,直到流结束。如果你的代码打开流但未读取到末尾或关闭它,该槽位将保持忙碌,后续调用可能会因 concurrency 错误而失败。务必消耗流或在 finally 块中关闭它。

函数调用

函数调用使用标准的 tools 和 tool_choice 参数。当模型需要调用工具时,回复将包含 tool_calls;你执行函数并将结果作为 role: "tool" 消息返回。

import json, os
from openai import OpenAI

client = OpenAI(base_url="https://api.nsfwgrok.top/v1", api_key=os.environ["NSFWGROK_KEY"])

tools = [{
    "type": "function",
    "function": {
        "name": "roll_dice",
        "description": "Roll n dice with the given number of sides.",
        "parameters": {
            "type": "object",
            "properties": {"n": {"type": "integer"}, "sides": {"type": "integer"}},
            "required": ["n", "sides"],
        },
    },
}]

messages = [{"role": "user", "content": "Roll 3 six-sided dice 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 = {"rolls": [4, 2, 6][: args["n"]]}  # 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)

务必检查 msg.tool_calls 是否存在,因为模型可能会直接回答。在使用参数前进行验证,因为它们是模型输出,可能格式错误。函数调用也支持流式输出,此时调用以片段形式到达,你需要将其组装。

用于结构化输出的 JSON 模式

当需要机器可读的输出时,传入 response_format={"type": "json_object"}。同时在提示词中告知模型你需要 JSON 并描述键,因为该模式限制格式但不限制你的 schema。

import json, os
from openai import OpenAI

client = OpenAI(base_url="https://api.nsfwgrok.top/v1", api_key=os.environ["NSFWGROK_KEY"])

resp = client.chat.completions.create(
    model="uncensored",
    response_format={"type": "json_object"},
    messages=[
        {"role": "system", "content": "Reply only with JSON: {\"name\": str, \"traits\": [str], \"hook\": str}"},
        {"role": "user", "content": "Invent a tavern keeper for a fantasy campaign."},
    ],
    temperature=0.7,
)
data = json.loads(resp.choices[0].message.content)
print(data["name"], data["traits"])

无论如何都要用 try 块包裹 json.loads。如果输出被 max_tokens 截断,JSON 将不完整,因此请为结构化回复留出足够空间。在调试时为了获得可重复的输出,请传递 seed 并设置较低的 temperature 值;采样参数如 temperature、top_p、stop、seed 以及惩罚项将传递给模型。

速率限制、429 错误和重试

完整密钥允许 8 个并发请求和每分钟 300 个请求。试用密钥允许 2 个和 60 个。超过任一限制,API 将返回 HTTP 429。错误代码告诉你触发了哪个限制:rate_limited 表示每分钟请求过多,concurrency 表示同时请求过多。在临时过载时,你还会收到 429,并带有 Retry-After: 5 标头。每个响应都包含 X-Request-Id、X-Balance-USD、X-RateLimit-Limit-Requests 和 X-RateLimit-Limit-Concurrency;联系支持时请引用请求 ID。

import asyncio, os
from openai import AsyncOpenAI, RateLimitError

client = AsyncOpenAI(base_url="https://api.nsfwgrok.top/v1", api_key=os.environ["NSFWGROK_KEY"], max_retries=0)
gate = asyncio.Semaphore(8)  # use 2 on a trial key

async def ask(prompt, tries=4):
    async with gate:
        for attempt in range(tries):
            try:
                r = await client.chat.completions.create(
                    model="uncensored",
                    messages=[{"role": "user", "content": prompt}],
                )
                return r.choices[0].message.content
            except RateLimitError as e:
                wait = float(e.response.headers.get("retry-after", 5))
                await asyncio.sleep(wait * (attempt + 1))
    raise RuntimeError("gave up after retries")

async def main():
    out = await asyncio.gather(*(ask(f"Give me idea number {i} for a short story.") for i in range(20)))
    print(len(out), "done")

asyncio.run(main())

信号量确保你不超过并发上限,重试机制尊重 Retry-After。失败或被拒绝的请求不会收费,因此重试不会让你支付两次。定价为每 1M 输入 token $0.15,每 1M 输出 token $0.50;定价页面 有实际成本示例,API 文档 涵盖了所有参数。

提示词不用于训练。唯一的硬性内容规则是:涉及未成年人的性内容永远不允许,此类请求将不被服务。

常见错误及修复方法

大多数首日问题源于简短的原因列表。在假设服务宕机之前,请按顺序排查。

记录调试所需的信息

在日志中保留每个响应的 X-Request-Id。SDK 通过 with_raw_response 暴露标头,该函数在解析对象旁边返回 HTTP 响应。这也是在每次调用后读取 X-Balance-USD 并在额度耗尽前警告自己的最简单方法。

import os
from openai import OpenAI

client = OpenAI(base_url="https://api.nsfwgrok.top/v1", api_key=os.environ["NSFWGROK_KEY"])

raw = client.chat.completions.with_raw_response.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Say hello in five words."}],
)
print("request id:", raw.headers.get("x-request-id"))
print("balance usd:", raw.headers.get("x-balance-usd"))
print(raw.parse().choices[0].message.content)

通过每条调用一行日志包含请求 ID、余额和使用情况,你可以几乎无需猜测地回答关于失败或昂贵请求的任何问题。

问答

这是官方的 Grok API 吗?

不是。这是一个面向开放权重模型的独立 OpenAI 兼容 API,并非 xAI 或任何其他供应商的官方 API。请使用模型 ID uncensored。

我应该使用哪个 Python 包?

官方的 openai 包即可使用。将 base_url 设置为 https://api.nsfwgrok.top/v1 并将密钥作为 api_key 传入。

是否支持流式输出和函数调用?

可以。流式输出通过 SSE 实现(设置 stream=True),工具调用遵循 OpenAI 工具格式,结果以 role: tool 消息形式返回。

为什么我会收到 429 错误?

你触发了限制。错误代码 rate_limited 表示每分钟请求过多,concurrency 表示同时请求过多,Retry-After 标头为 5 表示临时过载。

测试需要付费吗?

不需要。新用户注册后可一键领取 $0.50 试用额度。有效期 7 天,试用密钥允许 2 个并发请求和每分钟 60 个请求。

只需填写一个表单即可获得密钥

创建账户,复制密钥,更改基础 URL。这就是全部设置。