插件实用函数#

LLM 提供了一些可能对插件有用的实用函数。

llm.user_dir()#

LLM 在用户机器上的一个目录中存储各种日志和配置数据。

在macOS上,这个目录是~/Library/Application Support/io.datasette.llm,但在其他操作系统上会有所不同。

llm.user_dir() 函数返回该目录的路径作为 pathlib.Path 对象,如果该目录尚不存在,则会先创建该目录。

插件可以使用这个来在这个目录的子目录中存储它们自己的数据。

import llm
user_dir = llm.user_dir()
plugin_dir = data_path = user_dir / "my-plugin"
plugin_dir.mkdir(exist_ok=True)
data_path = plugin_dir / "plugin-data.db"

llm.ModelError#

如果你的模型遇到应该报告给用户的错误,你可以抛出这个异常。例如:

import llm

raise ModelError("MPT model not installed - try running 'llm mpt30b download'")

这将被CLI层捕获并作为错误消息显示给用户。

响应.fake()#

在为模型编写测试时,生成虚假的响应对象可能很有用,例如在llm-mpt30b的这个测试中:

def test_build_prompt_conversation():
    model = llm.get_model("mpt")
    conversation = model.conversation()
    conversation.responses = [
        llm.Response.fake(model, "prompt 1", "system 1", "response 1"),
        llm.Response.fake(model, "prompt 2", None, "response 2"),
        llm.Response.fake(model, "prompt 3", None, "response 3"),
    ]
    lines = model.build_prompt(llm.Prompt("prompt 4", model), conversation)
    assert lines == [
        "<|im_start|>system\system 1<|im_end|>\n",
        "<|im_start|>user\nprompt 1<|im_end|>\n",
        "<|im_start|>assistant\nresponse 1<|im_end|>\n",
        "<|im_start|>user\nprompt 2<|im_end|>\n",
        "<|im_start|>assistant\nresponse 2<|im_end|>\n",
        "<|im_start|>user\nprompt 3<|im_end|>\n",
        "<|im_start|>assistant\nresponse 3<|im_end|>\n",
        "<|im_start|>user\nprompt 4<|im_end|>\n",
        "<|im_start|>assistant\n",
    ]

llm.Response.fake() 的签名是:

def fake(cls, model: Model, prompt: str, system: str, response: str):