首页/指南
Llama API Python 配置:兼容 OpenAI 的接口
llama api python 环境配置很简单,因为大多数托管的 Llama 风格服务都支持 OpenAI 格式。安装 openai 包,设置基础 URL 和密钥,然后调用聊天完成。以下代码对任何兼容的提供商都适用,并且已在该接口上使用模型 <code>uncensored</code> 进行了测试。
更新于


- 使用 openai 包,设置 base_url=https://api.llamaapis.com/v1 和模型 uncensored。
- 流式输出、工具调用和 JSON 模式使用标准的 OpenAI 参数。
- 在 HTTP 429 时重试并读取 Retry-After 头。
- 通过更改三个设置,相同的脚本可在其他兼容提供商上运行。
安装并进行首次调用
Python 3.9 或更高版本可用。安装 SDK 并将密钥存储在环境变量中,以免其进入源代码控制。
pip install openai
export LLM_API_KEY="YOUR_KEY"
# base URL: https://api.llamaapis.com/v1 model: uncensored
然后是第一个请求:
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.llamaapis.com/v1",
api_key=os.environ["LLM_API_KEY"],
)
resp = client.chat.completions.create(
model="uncensored",
messages=[
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "Explain what a token is in two sentences."},
],
)
print(resp.choices[0].message.content)
print(resp.usage)
从 API 密钥页面获取密钥。新用户只需一键即可领取 $0.50 的试用额度,有效期 7 天且无需信用卡。该服务是一个仅支持文本的 OpenAI 兼容接口,用于一个开放权重模型。它不是 Meta 或其他任何模型供应商的官方 API,因此模型名称为 uncensored 而不是一个 Llama 版本字符串。
保持对话:角色和历史
API 是无状态的。要保持对话,每次发送完整的消息列表,并在其中追加每次回复。
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.llamaapis.com/v1", api_key=os.environ["LLM_API_KEY"])
history = [{"role": "system", "content": "You are a patient writing coach."}]
def chat(user_text):
history.append({"role": "user", "content": user_text})
r = client.chat.completions.create(model="uncensored", messages=history, temperature=0.7)
reply = r.choices[0].message.content
history.append({"role": "assistant", "content": reply})
return reply
print(chat("Give me a prompt for a ghost story."))
print(chat("Make it set on a ferry."))
上下文窗口为 100,000 个 token,包含提示词和补全,允许较长的历史记录。你仍需为每轮的每个输入 token 付费,因此当列表变长时,请修剪或总结旧消息。成本计算很简单:输入成本为每 1M 个 token $0.15,输出为每 1M 个 token $0.50。
Python 中的流式输出
传入 stream=True 并进行遍历。添加 stream_options 以便在最后一个数据块中获取 token 使用情况。
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.llamaapis.com/v1", api_key=os.environ["LLM_API_KEY"])
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Write a short scene at a night market."}],
stream=True,
stream_options={"include_usage": True},
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
if chunk.usage:
print("\n", chunk.usage)
最后一个数据块的 choices 列表为空,这就是循环首先检查它的原因。请记住,流式请求会一直占用其并发槽位,直到结束,因此如果用户离开,请关闭流。
工具与 JSON 模式
对于函数调用,在 tools 中描述你的函数,检查 message.tool_calls,运行函数,并使用 role: "tool" 返回输出:
import json, os
from openai import OpenAI
client = OpenAI(base_url="https://api.llamaapis.com/v1", api_key=os.environ["LLM_API_KEY"])
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the weather for a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}]
messages = [{"role": "user", "content": "What is the weather in Lisbon?"}]
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 = {"city": args["city"], "temp_c": 21} # your real lookup here
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)
对于纯结构化输出,设置 response_format={"type": "json_object"} 并在提示词中说明需要 JSON。在 try 块中使用 json.loads 解析结果,因为模型有时会返回损坏的 JSON。
重试和速率限制
完整密钥允许 8 个并发请求和每分钟 300 个请求;试用密钥允许 2 个并发请求和每分钟 60 个请求。如果超出限制,API 将返回 HTTP 429,代码为 rate_limited 或 concurrency。在临时过载情况下,它还会返回带有 Retry-After: 5 的 429。SDK 会抛出 RateLimitError,因此请这样包装调用:
import os, time
from openai import OpenAI, RateLimitError
client = OpenAI(base_url="https://api.llamaapis.com/v1", api_key=os.environ["LLM_API_KEY"], max_retries=0)
def call_with_retry(messages, tries=4):
for attempt in range(tries):
try:
return client.chat.completions.create(model="uncensored", messages=messages)
except RateLimitError as e:
if attempt == tries - 1:
raise
wait = int(e.response.headers.get("retry-after", 2 ** attempt))
time.sleep(wait)
设置 max_retries=0 将关闭 SDK 自身的重试,以便只有你的重试生效。使用限制文章 有更多模式,包括用于限制并发调用的信号量。
用于大量请求的异步调用
对于批处理工作,请使用异步客户端,并将并发限制在你的并发限制内,这样就不会收到 429 错误:
import asyncio, os
from openai import AsyncOpenAI
client = AsyncOpenAI(base_url="https://api.llamaapis.com/v1", api_key=os.environ["LLM_API_KEY"])
sem = asyncio.Semaphore(8) # use 2 on a trial key
async def one(prompt):
async with sem:
r = await client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": prompt}],
)
return r.choices[0].message.content
async def main():
prompts = [f"Give a name for fantasy town number {i}." for i in range(20)]
for text in await asyncio.gather(*(one(p) for p in prompts)):
print(text)
asyncio.run(main())常见错误及修复方法
- 基础 URL 缺少
/v1。 SDK 会追加/chat/completions,因此没有/v1的基础 URL 通常会因未找到而失败。 - 使用供应商模型名称。 诸如 Llama 版本之类的字符串在此处无效。发送
uncensored。 - 在最后一个流式 chunk 读取
choices[0]。 该 chunk 可能没有 choices,因此请先检查列表。 - 忘记历史记录。 如果模型似乎忘记了最后一条消息,你可能没有将其追加到列表中。
- 盲目解析工具参数。 将
json.loads包装在 try 块中,如果失败则发送错误消息作为工具结果,这通常能让模型自我纠正。 - 空白回复。 很小的
max_tokens或过早触发的停止序列会立即结束输出。调试时请移除两者。
当出现异常时,记录 X-Request-Id 响应头。使用 SDK 的原始响应,client.chat.completions.with_raw_response.create(...) 可访问 X-Balance-USD 和速率限制头等标头。
从代码检查余额
接口 GET /v1/balance 返回你的剩余额度,OpenAI 风格的 /v1/dashboard/billing/credit_grants 路由也存在。在大批量处理前进行小检查,可避免因余额耗尽而中途停止任务。
相同的代码、其他提供商和成本
由于格式共享,此代码可与任何兼容服务运行。更改 base_url、密钥和模型名称,然后测试不同提供商之间变化的参数。OpenAI 兼容 API 服务器 文章解释了兼容性的边界。
在此接口上,1,500 输入 token 和 400 输出 token 的调用成本为 1,500 x $0.15 / 1M + 400 x $0.50 / 1M = $0.000225 + $0.0002 = $0.000425。$0.50 的试用额度可覆盖约 1,176 次。之后,从 $20 充值至 $500;定价页面 列出了奖金。提示词不用于训练,失败或被拒的请求不收费。文档 涵盖其余内容。
更多指南
问答
需要哪个 Python 包?
官方 openai 包。将 base_url 设置为 https://api.llamaapis.com/v1 并传入你的密钥创建客户端,使用模型 ID uncensored。
相同的代码能与其他 Llama 风格的主机兼容吗?
通常可以,只要主机兼容 OpenAI。更改基础 URL、密钥和模型名称,并检查它支持哪些可选参数。
如何在 Python 中流式输出 token?
设置 stream=True 并遍历数据块。添加 stream_options 并设置 include_usage 以便在末尾获取 token 计数。
遇到 429 错误该怎么办?
如果提供了 Retry-After 秒数,请等待该秒数后再重试;否则请退避并重试。如果是并发限制导致的,请降低并行请求的数量。
只差一张表单,即可获得密钥
创建账户,复制密钥,更改基础 URL。这就是全部设置。