中文 ▾

Abliterated LLM

面向开发者的无审查 API

获取 API 密钥

支持函数调用的 LLM:原理与代码

支持函数调用的 LLM 不会运行你的代码。它返回一个结构化请求,指定函数名及其参数,由你的程序决定如何处理。本指南展示了针对 OpenAI 兼容接口的完整循环及可运行代码。

更新于

要点

  • 模型提出调用;你的代码执行它,并以 role: tool 消息的形式将结果发回。
  • 工具定义使用 JSON Schema,因此描述和参数类型决定了调用的效果。
  • 始终验证参数并限制循环迭代次数。
  • 流式响应将 tool_calls 分片发送,你必须将其组装。
模型方块与工具模块在循环中交换信号的等距图

函数调用究竟是什么

函数调用(也称工具调用)是你的程序与语言模型之间的协议。你以 JSON 结构描述函数。模型读取用户消息,然后以纯文本回复,或返回包含函数名称和参数 JSON 字符串的 tool_calls 列表。模型本身不执行函数。你的代码执行该函数,然后将输出发回,以便模型生成最终答案。

这个小循环将聊天模型转变为能查询订单、查询数据库、检查日历或调用内部 API 的工具。它也是大多数 agent 框架的基础。如果你能手动编写下面的循环,就能调试基于它构建的任何框架。

该 API 遵循 OpenAI 聊天补全格式,支持 tools、tool_choice、流式输出的 tool_calls,以及以 role: "tool" 形式返回的结果。Base URL 为 https://api.abliteratedllm.cc/v1,模型 ID 为 uncensored。

请求:描述工具

工具由名称、描述和参数模式组成。描述不是装饰。模型通过阅读描述来选择工具,因此请将其写为一行规范:函数做什么、何时使用、返回什么。

{
  "model": "uncensored",
  "messages": [
    {"role": "user", "content": "Is order 48213 shipped yet?"}
  ],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_order_status",
        "description": "Look up the shipping status of an order by its numeric ID.",
        "parameters": {
          "type": "object",
          "properties": {
            "order_id": {"type": "integer", "description": "The order number"}
          },
          "required": ["order_id"]
        }
      }
    }
  ],
  "tool_choice": "auto"
}

tool_choice 控制行为。使用 auto 时由模型决定。你也可以强制指定特定函数,以便某步骤始终产生结构化输出。如果你只需要干净的 JSON 且无需外部调用,response_format: {"type": "json_object"} 更简单。

Python 中的完整循环

循环包含四个步骤:发送消息和工具、检查 tool_calls、执行每个调用、追加结果并再次调用。当模型回答且无工具调用时停止。

import json, os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.abliteratedllm.cc/v1",
    api_key=os.environ["LLM_API_KEY"],
)

def get_order_status(order_id: int) -> dict:
    # replace with a real lookup
    return {"order_id": order_id, "status": "shipped", "carrier": "post"}

REGISTRY = {"get_order_status": get_order_status}

tools = [{
    "type": "function",
    "function": {
        "name": "get_order_status",
        "description": "Look up the shipping status of an order by its numeric ID.",
        "parameters": {
            "type": "object",
            "properties": {"order_id": {"type": "integer"}},
            "required": ["order_id"],
        },
    },
}]

messages = [{"role": "user", "content": "Is order 48213 shipped yet?"}]

for _ in range(5):  # hard cap on iterations
    resp = client.chat.completions.create(
        model="uncensored", messages=messages, tools=tools, tool_choice="auto"
    )
    msg = resp.choices[0].message
    if not msg.tool_calls:
        print(msg.content)
        break
    messages.append(msg)  # keep the assistant turn that holds tool_calls
    for call in msg.tool_calls:
        try:
            args = json.loads(call.function.arguments)
            result = REGISTRY[call.function.name](**args)
        except Exception as e:
            result = {"error": str(e)}
        messages.append({
            "role": "tool",
            "tool_call_id": call.id,
            "content": json.dumps(result),
        })

三个细节会导致大多数初次错误。包含 tool_calls 的助手消息必须保留在历史记录中。每条工具消息都需要匹配的 tool_call_id。此外,工具消息的 content 是字符串,因此需序列化你的字典。

从命令行尝试

你可以在使用 SDK 之前通过 curl 查看原始结构。发送上一节的请求并查看回复。

curl https://api.abliteratedllm.cc/v1/chat/completions \
  -H "Authorization: Bearer $LLM_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "uncensored",
    "messages": [{"role": "user", "content": "Is order 48213 shipped yet?"}],
    "tools": [{"type": "function", "function": {
      "name": "get_order_status",
      "description": "Look up the shipping status of an order by its numeric ID.",
      "parameters": {"type": "object",
        "properties": {"order_id": {"type": "integer"}},
        "required": ["order_id"]}}}]
  }'

在回复中,你要查找的是 choices[0].message.tool_calls[0].function.arguments。它是一个包含 JSON 的字符串,例如 {"order_id": 48213},而不是对象。这就是 Python 代码调用 json.loads 的原因。

流式工具调用

使用 stream: true 时,工具调用以片段形式到达。调用的第一个块携带其 id 和函数名,后续块追加参数字符串的片段。你必须按 index 拼接片段,并仅在流结束后解析。

calls = {}
stream = client.chat.completions.create(
    model="uncensored", messages=messages, tools=tools, stream=True
)
for chunk in stream:
    if not chunk.choices:
        continue
    for tc in chunk.choices[0].delta.tool_calls or []:
        slot = calls.setdefault(tc.index, {"id": "", "name": "", "args": ""})
        if tc.id:
            slot["id"] = tc.id
        if tc.function and tc.function.name:
            slot["name"] = tc.function.name
        if tc.function and tc.function.arguments:
            slot["args"] += tc.function.arguments
# after the loop: json.loads(slot["args"]) for each entry

一个操作要点:流式请求会占用并发槽位直到流结束。完整密钥允许同时 8 个,试用密钥允许 2 个。如果你的 agent 并行发起多个使用工具的对话,请计算流的数量,否则你会看到代码为 concurrency 的 429 响应。

Node 中的相同调用

JavaScript 中的结构相同。以下是第一轮,从回复中读取工具调用并解析参数字符串。

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.abliteratedllm.cc/v1",
  apiKey: process.env.LLM_API_KEY,
});

const tools = [{
  type: "function",
  function: {
    name: "get_order_status",
    description: "Look up the shipping status of an order by its numeric ID.",
    parameters: {
      type: "object",
      properties: { order_id: { type: "integer" } },
      required: ["order_id"],
    },
  },
}];

const messages = [{ role: "user", content: "Is order 48213 shipped yet?" }];
const resp = await client.chat.completions.create({
  model: "uncensored", messages, tools, tool_choice: "auto",
});

const msg = resp.choices[0].message;
if (msg.tool_calls) {
  const args = JSON.parse(msg.tool_calls[0].function.arguments);
  console.log("model wants order", args.order_id);
}

何时 JSON 模式是更好的选择

并非所有结构化任务都需要工具。如果你希望模型从文本中提取字段(例如从电子邮件中提取姓名、日期和金额),则无需调用。请求 JSON 对象,并将 response_format 设置为 json_object,在提示词中描述键并解析回复。当模型必须在动作之间做出选择,或你的代码必须根据结果采取行动并发送内容时,使用函数调用。

提高调用的可靠性

  • 保持工具列表简短。 五个清晰的工具胜过二十个重叠的工具。合并仅在一个参数上不同的函数。
  • 使用枚举。 如果参数有一组固定值,请在模式中列出它们,而不是用文字描述。
  • 执行前验证。 参数是模型输出。检查类型和范围,切勿直接将其传入 shell 命令或 SQL 字符串。
  • 将错误作为数据返回。 当函数失败时,将 {"error": "..."} 作为工具结果发回。模型通常会在下一轮自行纠正。
  • 限制迭代次数。 上述循环在五轮后停止。如果没有上限,困惑的模型可能会无限消耗 token。
  • 降低 temperature。 对于工具选择,0 到 0.3 比默认的创意范围提供更稳定的选择。

当回复出乎意料时,记录 X-Request-Id 响应头以及你自己的追踪信息。这将使支持问题的解答变得容易得多。

使用工具的 agent 成本

每次循环都会重新发送对话,包括工具定义,因此输入 token 会增加。以支持机器人为例,每轮有 2,500 个输入 token(历史记录加工具模式)和 150 个输出 token,典型问题需要 2 轮。输入:5,000 token x $0.15 / 1,000,000 = $0.00075。输出:300 token x $0.50 / 1,000,000 = $0.00015。总计每问题 $0.0009,因此 1,000 个问题成本为 $0.90。

计费按量付费,输入 token 为每 100 万 $0.15,输出 token 为每 100 万 $0.50,失败的请求不收费。查看 定价页面 了解充值和奖励,查看 文档 获取完整参数列表,并访问 密钥页面 领取 $0.50 试用额度。如果你正在为此类工作比较模型,无审查 AI 模型对比 解释了它们之间的差异。

该服务仅支持文本,模型是来自独立提供商的单一开放权重模型,针对合法成人使用进行了调校,不会因内容而拒绝回答。在发布前,始终在自己的提示词上测试自己的模式。

问答

模型会执行我的函数吗?

不会。它仅返回函数名和参数。你的代码执行函数,并通过 role 为 tool 的消息将结果发回。

我可以强制模型调用特定函数吗?

可以,通过 tool_choice 字段。当某步骤必须产生结构化参数时使用。

为什么 function.arguments 是字符串?

它遵循 OpenAI 格式,其中参数是 JSON 编码的字符串。使用 json.loads 或 JSON.parse 解析,并处理格式错误的情况。

流式输出支持与工具配合使用吗?

是的。工具调用以片段形式流式输出,你需按索引拼接后再进行解析。

工具定义是否计入 token?

是的。它们属于提示词的一部分,因此每次请求都会作为输入 token 计费,且工具列表过长会在多轮交互中累积消耗。

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

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

从试用额度开始

邮箱和密码,密钥立即显示在屏幕上。