中文 ▾
获取 API 密钥

nsfwllms.com指南

LLM 函数调用:可运行代码示例

函数调用让模型请求你的代码运行函数,然后将结果用于回答。此 API 支持标准 OpenAI 字段,因此更改 Base URL 后现有客户端代码即可运行。

更新于

要点

  1. 发送 tools 数组,从回复中读取 tool_calls,自行运行函数,发送 role: tool 消息。
  2. 使用 uncensored 模型和 Base URL https://api.nsfwllms.com/v1 即可配合任何 OpenAI SDK 使用。
  3. 支持 tool_choice、流式输出的 tool_calls 和 JSON 模式。
  4. 模型不会运行你的代码。你验证参数并决定执行内容。
模型节点与一组工具之间发光的箭头循环,展示函数调用

四步循环

LLM 的函数调用是代码与模型之间的简短对话。模型无法执行任何操作,只能返回结构化请求,说明它想要哪个函数以及使用什么参数。

  1. 你发送消息以及一个 tools 数组,该数组使用 JSON Schema 描述每个函数。
  2. 模型回复普通文本或包含 tool_calls 列表。每条记录包含 id、函数名和参数字符串。
  3. 你的代码解析参数,运行函数,并以附带匹配的 tool_call_id 将结果作为角色为 role: "tool" 的消息追加。
  4. 你再次调用 API。模型读取结果并生成最终答案。

此处均使用 POST /v1/chat/completions。不涉及额外接口或 beta 标志。

首次 curl 请求

从原始 HTTP 开始以便观察结构。将密钥替换为你自己的。下面的函数掷骰子,这是桌面或文字冒险应用所需的小型工具。

curl https://api.nsfwllms.com/v1/chat/completions \
  -H "Authorization: Bearer YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "uncensored",
    "messages": [
      {"role": "user", "content": "Roll a twenty-sided die for my attack."}
    ],
    "tools": [{
      "type": "function",
      "function": {
        "name": "roll_dice",
        "description": "Roll one die with the given number of sides.",
        "parameters": {
          "type": "object",
          "properties": {"sides": {"type": "integer", "minimum": 2}},
          "required": ["sides"]
        }
      }
    }],
    "tool_choice": "auto"
  }'

如果模型决定使用工具,choices[0].message.content 为空或 null,且 choices[0].message.tool_calls 包含请求。你的代码从此时接管。

Python 完整往返流程

使用 openai SDK 时,整个交互过程仅需约二十行代码。使用 pip install openai 安装。

import json
import random
from openai import OpenAI

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

def roll_dice(sides: int) -> int:
    return random.randint(1, sides)

tools = [{
    "type": "function",
    "function": {
        "name": "roll_dice",
        "description": "Roll one die with the given number of sides.",
        "parameters": {
            "type": "object",
            "properties": {"sides": {"type": "integer", "minimum": 2}},
            "required": ["sides"],
        },
    },
}]

messages = [{"role": "user", "content": "Roll a twenty-sided die for my attack."}]

first = client.chat.completions.create(
    model="uncensored", messages=messages, tools=tools, tool_choice="auto"
)
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 = roll_dice(**args)
        messages.append({
            "role": "tool",
            "tool_call_id": call.id,
            "content": json.dumps({"result": result}),
        })
    final = client.chat.completions.create(
        model="uncensored", messages=messages, tools=tools
    )
    print(final.choices[0].message.content)
else:
    print(msg.content)

有两个细节很重要。包含 tool_calls 的助手消息必须排在工具结果之前,且每条结果都需要其对应调用的 tool_call_id。跳过任一环节,第二次请求将格式错误。

控制工具使用方式

tool_choice 决定模型拥有多少自由度。

  • "auto" 允许模型在回答和调用工具之间进行选择。当存在 tools 时,这是默认值。
  • "none" 禁止本次请求使用工具调用。若希望获得纯文本答案,请在最后一轮使用。
  • {"type": "function", "function": {"name": "roll_dice"}} 强制使用特定函数。

像为新同事写文档一样编写描述。说明函数功能、使用场景及每个参数的含义。模糊的名称如 do_action 会导致模糊调用。为固定选项使用枚举,为必填字段使用 required,以减少错误的参数。

如果你只需要结构化输出且无需运行函数,JSON 模式更简单:将 response_format 设置为 {"type": "json_object"} 并在提示词中要求 JSON。

流式工具调用

使用 stream: true 时,参数通过 SSE 分块到达。每个块携带带有 index 的片段,你将相同索引的片段拼接,直到流结束。

calls = {}
stream = client.chat.completions.create(
    model="uncensored",
    messages=messages,
    tools=tools,
    stream=True,
)
for chunk in stream:
    if not chunk.choices:
        continue  # a final chunk may carry usage only
    delta = chunk.choices[0].delta
    for tc in delta.tool_calls or []:
        slot = calls.setdefault(tc.index, {"id": "", "name": "", "arguments": ""})
        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["arguments"] += tc.function.arguments

for slot in calls.values():
    args = json.loads(slot["arguments"])  # parse only when the stream is done
    print(slot["name"], args)

不要在流结束前解析参数。未接收完整的字符串不是有效的 JSON。使用情况在流结束时报告,因此你仍可以记录 token 计数。

需规避的设计错误

  • 信任参数。模型会生成这些参数,因此请将其视为用户输入。验证类型和范围,并将json.loads包裹在 try 块中。如果解析失败,将错误作为工具结果返回,并让模型重试一次。
  • 缺少确认环节的副作用。 对于任何涉及花钱、删除数据或向人发消息的操作,在你的代码中要求确认。不要将工具直接映射到 shell 命令。
  • 无限循环。 限制轮数,例如五轮。如果不限制,困惑的模型可能会持续调用工具。
  • 臃肿的结果。 仅返回模型需要的字段。庞大的工具输出会在后续每一轮消耗输入 token。
  • 速率限制。全功能密钥允许 8 个并发请求和每分钟 300 次请求。工具循环会在每个用户轮次中进行多次顺序调用,因此请计算这些调用。

成本保持很小。一次往返发送 1,500 个输入 token 并返回 150 个输出 token,成本为 1,500 x $0.15 / 1M + 150 x $0.50 / 1M = $0.000225 + $0.000075 = $0.0003。费率列在 定价页面。

下一步操作

成人小说、角色扮演和陪伴类应用的首选工具是小巧且本地运行的:如掷骰器、角色表查询、保存用户所述事实的记忆存储,或让角色知晓时间的时钟。模型决定何时读取或写入这些工具,而你的数据库保持为唯一事实来源。

快速入门文档 涵盖认证和基本请求。你可以在 API 密钥页面 获取密钥,新账户可领取 $0.50 的免费试用额度。这足以支持超过一千次上述往返。

问答

此 API 支持函数调用吗?

可以。向 POST /v1/chat/completions 发送 tools 和 tool_choice,从回复中读取 tool_calls,并以 role: tool 消息返回结果。流式输出的 tool_calls 同样有效。

我应该使用哪个模型 ID?

在模型字段中使用 uncensored。Base URL 为 https://api.nsfwllms.com/v1

模型会运行我的函数吗?

不会。它仅返回函数名和参数。你的代码运行函数并将结果返回。

我可以将函数调用与 JSON 模式结合使用吗?

它们是独立的功能。当你希望代码执行操作时使用函数调用,当你只希望最终答案以 JSON 对象形式返回时使用 JSON 模式。

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

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

获取 API 密钥