要求#
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)
documents = [
{"id":"S1","text":"A KV cache reuses attention keys and values from previous tokens."},
{"id":"S2","text":"Prefill processes the prompt; decode generates new output tokens."},
{"id":"S3","text":"Longer contexts increase KV cache memory usage."}]
question = "How does caching affect generation?"
terms = set(question.lower().split())
ranked = sorted(documents, key=lambda d: len(terms & set(d["text"].lower().split())), reverse=True)[:2]
context = "\n".join("["+d["id"]+"] "+d["text"] for d in ranked)
r = chat([{"role":"system","content":"Answer only from the sources. Cite [S1], [S2], etc. Say when evidence is missing."},
{"role":"user","content":context+"\nQuestion: "+question}])
print(r["choices"][0]["message"]["content"])
print("Retrieved sources:", [d["id"] for d in ranked])
上线前#
此小型示例使用词法排序和嵌入式样本来独立运行。请用您自己的检索器替换语料库和排序方式,并验证引用确实支持每项陈述。