插件钩子#

插件使用插件钩子来自定义LLM的行为。这些钩子由Pluggy插件系统提供支持。

每个插件可以使用@hookimpl装饰器实现一个或多个钩子,针对本页描述的钩子函数名称之一。

LLM 模仿了 Datasette 插件系统。Datasette 插件文档 描述了插件的工作原理。

注册命令(cli)#

这个钩子向llm CLI工具添加了新命令 - 例如llm extra-command

这个示例插件添加了一个新的 hello-world 命令,用于打印“Hello world!”:

from llm import hookimpl
import click

@hookimpl
def register_commands(cli):
    @cli.command(name="hello-world")
    def hello_world():
        "Print hello world"
        click.echo("Hello world!")

这个新命令将被添加到llm --help中,并且可以使用llm hello-world来运行。

注册模型(register)#

此钩子可用于注册一个或多个额外的模型。

import llm

@llm.hookimpl
def register_models(register):
    register(HelloWorld())

class HelloWorld(llm.Model):
    model_id = "helloworld"

    def execute(self, prompt, stream, response):
        return ["hello world"]

如果你的模型包含一个异步版本,你也可以注册它:

class AsyncHelloWorld(llm.AsyncModel):
    model_id = "helloworld"

    async def execute(self, prompt, stream, response):
        return ["hello world"]

@llm.hookimpl
def register_models(register):
    register(HelloWorld(), AsyncHelloWorld(), aliases=("hw",))

这演示了如何注册一个包含同步和异步版本的模型,以及如何为该模型指定别名。

模型插件教程详细描述了如何使用这个钩子。异步模型在这里描述