How to write a custom model
mainA model is responsible for the interaction with the LLM. While tasks handle prompt creation and response parsing, the model handles the execution.
Internally, spacy-llm follows this pattern:
prompts = task.generate_prompts(docs)responses = model(prompts)docs = task.parse_responses(docs, responses)
To implement a custom model, register a function using @registry.llm_models. The returned object should be a callable that accepts an iterable of prompts and yields an iterable of responses. While built-in tasks and models typically use str, you can use arbitrary objects if your task and model are designed to be compatible.
from spacy_llm.registry import registry
import random
from typing import Iterable
@registry.llm_models("RandomClassification.v1")
def random_textcat(labels: str):
labels = labels.split(",")
def _classify(prompts: Iterable[str]) -> Iterable[str]:
for _ in prompts:
yield random.choice(labels)
return _classify