文档

入门

使用大型语言模型进行预测

文本嵌入

分词

管理模型

模型信息

工具定义

您可以将工具定义为常规的 Python 函数,并在 act() 调用中将其传递给模型。另外,也可以使用 lmstudio.ToolFunctionDef 定义工具,以控制传递给语言模型的名称和描述。

工具的构成

请遵循以下示例之一来定义作为函数的工具(第一种方法通常是最方便的)

# Type hinted functions with clear names and docstrings
# may be used directly as tool definitions
def add(a: int, b: int) → int:
    """Given two numbers a and b, returns the sum of them."""
    # The SDK ensures arguments are coerced to their specified types
    return a + b

# Pass `add` directly to `act()` as a tool definition

重要提示:工具名称、描述和参数定义都将传递给模型!

这意味着您的措辞会影响生成内容的质量。务必始终提供清晰的工具描述,以便模型知道如何使用它。

具有外部效应的工具(例如计算机使用或 API 调用)

工具还可以具有外部效应,例如创建文件、调用程序乃至 API。通过实现具有外部效应的工具,您可以将大型语言模型转变为自主代理,从而在本地机器上执行任务。

示例:create_file_tool

工具定义

from pathlib import Path

def create_file(name: str, content: str):
    """Create a file with the given name and content."""
    dest_path = Path(name)
    if dest_path.exists():
        return "Error: File already exists."
    try:
        dest_path.write_text(content, encoding="utf-8")
    except Exception as exc:
        return "Error: {exc!r}"
    return "File created."

使用 create_file 工具的示例代码:

import lmstudio as lms
from create_file_tool import create_file

model = lms.llm("qwen2.5-7b-instruct")
model.act(
  "Please create a file named output.txt with your understanding of the meaning of life.",
  [create_file],
)

处理工具调用错误

默认情况下,Python SDK 的 1.3.0 及更高版本将自动把工具调用引发的异常转换为文本,并将其报告回语言模型。在许多情况下,当以这种方式通知错误时,语言模型能够调整其请求以避免失败,或者接受失败作为对其请求的有效响应(考虑一个类似 尝试使用提供的工具将 1 除以 0。解释结果。 的提示,其中预期响应是对 Python 解释器在被指示除以零时引发的 ZeroDivisionError 异常的解释)。

此错误处理行为可以使用 handle_invalid_tool_request 回调进行覆盖。例如,以下代码将错误处理恢复为在客户端本地引发异常

import lmstudio as lms

def divide(numerator: float, denominator: float) → float:
    """Divide the given numerator by the given denominator. Return the result."""
    return numerator / denominator

model = lms.llm("qwen2.5-7b-instruct")
chat = Chat()
chat.add_user_message(
    "Attempt to divide 1 by 0 using the tool. Explain the result."
)

def _raise_exc_in_client(
    exc: LMStudioPredictionError, request: ToolCallRequest | None
) → None:
    raise exc

act_result = llm.act(
    chat,
    [divide],
    handle_invalid_tool_request=_raise_exc_in_client,
)

当传递工具请求时,回调结果按如下方式处理:

  • None:原始异常文本未修改地传递给大型语言模型。
  • 一个字符串:返回的字符串将代替原始异常文本传递给大型语言模型。
  • 引发异常(无论是传入的异常还是新异常):引发的异常在客户端本地传播,终止预测过程。

如果没有传入工具请求,则回调调用仅为通知,异常无法转换为文本以传递回大型语言模型(尽管仍可以用不同的异常替换)。这些情况表明与服务器 API 的预期通信失败,这意味着预测过程无法合理地继续,因此如果回调不引发异常,则调用代码将直接引发原始异常。