要求#
Python 3.11 或更高版本。无需额外包。将 WEIGHTSAPI_API_KEY 设置为您的密钥。AI 访问需要登录、一次至少 100 美元的确认充值、一个已授权的 API 密钥以及足够的可用余额。每次后续充值的最低金额也为 100 美元;较小的剩余余额在足以支付请求时仍可使用。余额需要交易验证。发送流量前请查看服务状态 了解模型可用性。
运行该配方#
import os, json, urllib.request
BASE = os.environ.get("WEIGHTSAPI_BASE_URL", "https://weightsapi.com/v1")
KEY = os.environ["WEIGHTSAPI_API_KEY"]
def chat(messages, model="Qwen/Qwen3-32B", **options):
payload = dict(model=model, messages=messages, max_tokens=512, **options)
req = urllib.request.Request(BASE+"/chat/completions", json.dumps(payload).encode(),
{"Authorization": "Bearer "+KEY, "Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=120) as response:
return json.load(response)
schema = {"type":"object","properties":{"language":{"type":"string"},"summary":{"type":"string"}},
"required":["language","summary"],"additionalProperties":False}
r = chat([{"role":"user","content":"Summarize: Bonjour, je construis une API."}],
response_format={"type":"json_schema","json_schema":{"name":"summary","strict":True,"schema":schema}})
choice = r["choices"][0]
if choice["finish_reason"] != "stop": raise ValueError("Incomplete output")
value = json.loads(choice["message"]["content"])
if set(value) != {"language","summary"} or not all(isinstance(v,str) for v in value.values()):
raise ValueError("Schema validation failed")
print(value)
上线前#
在将工作流暴露给用户之前,请限制并发和重试,验证输出并处理错误。