中文 ▾
获取 API 密钥

Uncensored AI如何使用 AI 图像 API

Python 版 Chat Completions API:流式输出与错误处理

本 Chat Completions API Python 指南带你从安装到构建面向生产的客户端:首次请求、流式输出、工具调用、JSON 模式和错误处理。每个示例都针对 OpenAI 兼容接口,使用模型 ID uncensored。

已更新

传送带上的胶囊进入腔体,化作光流:一次请求和流式回复

01Uncensored AI

要点

  1. 文本 API 独立于图像生成模型,处理提示词构建、脚本编写和元数据提取。

  2. OpenAI 兼容接口允许使用标准 SDK 直接集成,无需自定义协议开发。

  3. 流式输出支持实时 token 交付,这对于交互式提示词优化工作流至关重要。

  4. Token 定价基于使用情况,对上下文窗口和请求速率有具体限制。

安装并进行首次请求

你需要 Python 3.8 或更高版本以及 OpenAI 包。在 API 密钥页面创建密钥;一键试用赠送 $0.50 额度,无需付款。

pip install openai
from openai import OpenAI

client = OpenAI(
    base_url="https://api.uncensoredaiimage.com/v1",
    api_key="YOUR_KEY",
)

response = client.chat.completions.create(
    model="uncensored",
    messages=[
        {"role": "system", "content": "You are a concise assistant."},
        {"role": "user", "content": "What is a mutex?"},
    ],
    temperature=0.7,
)

print(response.choices[0].message.content)
print(response.usage)

此请求发送 POST /v1/chat/completions。messages 是一个字典列表,每个字典包含 role,取值为 system、user、assistant 或 tool。回复内容位于 choices[0].message.content,usage 报告提示词 token 和输出 token 数量,以便你计算成本:输入每 1M token $0.15,输出每 1M token $0.50。

使用环境变量,而非硬编码密钥

将密钥保留在源代码控制之外。如果你不传递它们,SDK 会从环境变量读取 OPENAI_API_KEY 和 OPENAI_BASE_URL,这使得同一个脚本可以针对不同的接口工作。

import os
from openai import OpenAI

client = OpenAI(
    base_url=os.environ.get("LLM_BASE_URL", "https://api.uncensoredaiimage.com/v1"),
    api_key=os.environ["LLM_API_KEY"],
    timeout=120,
    max_retries=0,
)

设置 max_retries=0 关闭 SDK 的自动重试,以便你自行控制重试策略,如下文错误部分所示。对于长补全,设置较长的超时时间是合理的,因为上下文窗口为 100,000 token,回复可能很长。

流式输出

对于聊天界面,在 token 到达时进行流式输出。设置 stream=True 并迭代。请求用量,以便最后一个 chunk 携带 token 计数。

stream = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Explain TCP slow start briefly."}],
    stream=True,
    stream_options={"include_usage": True},
)

parts = []
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        piece = chunk.choices[0].delta.content
        parts.append(piece)
        print(piece, end="", flush=True)
    if chunk.usage:
        usage = chunk.usage

print()
print("tokens:", usage.prompt_tokens, usage.completion_tokens)

传输方式是 server-sent events。要记住的一点是:流式请求会占用一个并发槽位,直到流结束。完整密钥有 8 个槽位,试用密钥有 2 个。如果你放弃流,请关闭它以释放槽位。

对话状态

API 是无状态的。每轮都重新发送历史记录。追加助手回复,然后是下一个用户消息。

history = [{"role": "system", "content": "You are a helpful tutor."}]

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("Define recursion."))
print(chat("Now give a Python example."))

历史记录在每次调用时都作为输入计费,因此长对话每轮成本更高。一旦超过你设定的限制,请截断最旧的消息,并保留系统提示词。

JSON 模式和工具调用

JSON 模式

传递 response_format={"type": "json_object"} 并在提示词中告诉模型你想要哪些键。解析结果并处理失败,因为模型仍可能产生格式错误的输出。

import json

r = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Return JSON with keys city and country for Lyon."}],
    response_format={"type": "json_object"},
)
data = json.loads(r.choices[0].message.content)
print(data)

工具调用

tools = [{
    "type": "function",
    "function": {
        "name": "get_time",
        "description": "Current time in a city",
        "parameters": {
            "type": "object",
            "properties": {"city": {"type": "string"}},
            "required": ["city"],
        },
    },
}]

msgs = [{"role": "user", "content": "What time is it in Tokyo?"}]
r = client.chat.completions.create(model="uncensored", messages=msgs, tools=tools)
call = r.choices[0].message.tool_calls[0]
msgs.append(r.choices[0].message)
msgs.append({"role": "tool", "tool_call_id": call.id, "content": "14:05"})
final = client.chat.completions.create(model="uncensored", messages=msgs, tools=tools)
print(final.choices[0].message.content)

在实际代码中,在索引之前检查 tool_calls 是否不为空,因为模型可能会直接回答。结果以 role: "tool" 消息返回。

透传的采样参数

这些参数原样传递给模型:temperature、top_p、stop、seed、frequency_penalty 和 presence_penalty。一些实用设置:

  • 提取和代码: temperature 0 到 0.3,使答案在多次运行之间保持稳定。
  • 创意写作和角色扮演: temperature 0.8 到 1.0,如果文本循环则使用轻微的 presence penalty。
  • 可重复测试: 固定 seed 并保持其他设置相同。将可重复性视为尽力而为,而非保证。
  • 停止输出: 使用 stop 和一个标记字符串,例如格式结束的行。

一次更改一个设置,并在固定的提示词集上进行比较。同时更改 temperature 和 penalties 很难判断是什么起了作用。

错误、限制和重试

请分别处理三种情况。状态码为 rate_limited 的 429 错误 表示你超过了每分钟请求数限制(完整密钥为 300,试用密钥为 60)。状态码为 concurrency 的 429 错误 表示同时进行的请求过多(完整密钥为 8,试用密钥为 2)。带有 Retry-After: 5 标头的 429 错误 表示临时过载,请等待后重试。失败或被拒绝的请求不会收费。

import time, random
from openai import APIStatusError, APIConnectionError, RateLimitError

def complete(messages, tries=5):
    for attempt in range(tries):
        try:
            return client.chat.completions.create(model="uncensored", messages=messages)
        except RateLimitError as e:
            wait = float(e.response.headers.get("Retry-After", 5))
            time.sleep(wait + random.random())
        except APIConnectionError:
            time.sleep(2 ** attempt)
        except APIStatusError as e:
            if e.status_code >= 500:
                time.sleep(2 ** attempt)
            else:
                raise
    raise RuntimeError("gave up after retries")

对于并行工作,在代码中限制并发,而不是依赖重试。ThreadPoolExecutor(max_workers=8) 或 asyncio.Semaphore(8) 对应完整密钥的限制。超过 8 MB 的请求会被拒绝,这仅在你将大型文档嵌入提示词时才有意义。

跟踪成本和余额

每个响应都包含 X-Request-Id、X-Balance-USD、X-RateLimit-Limit-Requests 和 X-RateLimit-Limit-Concurrency。要使用 SDK 读取标头,请使用原始响应:

raw = client.chat.completions.with_raw_response.create(
    model="uncensored",
    messages=[{"role": "user", "content": "ping"}],
)
print(raw.headers.get("X-Balance-USD"), raw.headers.get("X-Request-Id"))
response = raw.parse()
print(response.choices[0].message.content)

你还可以调用 GET /v1/balance。记录每次错误的请求 ID;这是从 支持页面获得帮助的最快方法。充值从 $20 到 $500,附带 $50 起的奖金,通过加密货币支付(TRC20 上的 USDT 或 Base 上的 USDC);详见 定价。

如果你更喜欢先使用原始 HTTP 进行测试,curl 指南 显示了相同的调用,文档 列出了所有接口。对于代码导向的提示词,参见 用于编码的 uncensored AI。记住这是一个纯文本 API:它不生成图像,尽管网站名称可能暗示这一点。

02Uncensored AI

问答

我需要特殊的库吗?

不需要。设置 base_url 和 api_key 后,官方 openai Python 包即可使用。使用模型 uncensored。

最大上下文窗口是多少?

上下文窗口为 100,000 token,包括提示词和补全。max_tokens 是可选的,因此补全可以使用剩余空间。

如何区分这两种 429 错误?

读取错误代码。rate_limited 表示每分钟请求过多,concurrency 表示同时请求过多。Retry-After: 5 标头标记临时过载。

max_tokens 是必需的吗?

不需要。它是可选的。当你希望限制回复长度和成本时设置它。

Uncensored AIuncensoredaiimage.com

只差一张表单,即可获得密钥

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

获取 API 密钥