工具定义
定义要由 LLM 调用的工具,并在 act() 调用中将它们传递给模型。
您可以将工具定义为普通的 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。通过实现具有外部影响的工具,您本质上可以将 LLM 转化为自主智能体,在本地计算机上执行任务。
示例: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 及更高版本会自动将工具调用引发的异常转换为文本,并将其报告回语言模型。在许多情况下,当以这种方式收到错误通知时,语言模型能够调整其请求以避免失败,或者接受该失败作为其请求的有效响应(例如提示词 Attempt to divide 1 by 0 using the provided tool. Explain the result.,其中预期的响应是解释 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:原始异常文本将不加修改地传递给 LLM- 字符串:返回的字符串将代替原始异常文本传递给 LLM
- 引发异常(无论是传入的异常还是新异常):引发的异常将在客户端本地传播,从而终止预测过程
如果未传入工具请求,则回调调用仅为通知,且无法将异常转换为文本以传回 LLM(尽管仍可以将其替换为其他异常)。这些情况表明与服务器 API 的预期通信失败,这意味着预测过程无法合理地继续进行,因此如果回调没有引发异常,调用代码将直接引发原始异常。