|
| 1 | +from dataclasses import dataclass |
| 2 | +from typing import Any, Callable, Union |
| 3 | + |
| 4 | +from outlines.generate import Generator |
| 5 | +from outlines.templates import Template |
| 6 | +from outlines.models import Model |
| 7 | + |
| 8 | + |
| 9 | +@dataclass |
| 10 | +class Macro: |
| 11 | + """ |
| 12 | + Macro is a class that encapsulates a model, a prompt template, and an |
| 13 | + output type. It can be called to generate a response. |
| 14 | +
|
| 15 | + Parameters |
| 16 | + ---------- |
| 17 | + model : Model |
| 18 | + The Outlines model to be used for generating responses. |
| 19 | + template : Union[Template, Callable] |
| 20 | + A callable that takes arguments and returns a prompt string. |
| 21 | + output_type : Any |
| 22 | + The expected output type of the generated response. |
| 23 | +
|
| 24 | + Examples |
| 25 | + -------- |
| 26 | + from pydantic import BaseModel |
| 27 | + from transformers import AutoModelForCausalLM, AutoTokenizer |
| 28 | + from outlines import models, Macro |
| 29 | + from outlines.types import JsonType |
| 30 | + from outlines.templates import Template |
| 31 | +
|
| 32 | + class OutputModel(BaseModel): |
| 33 | + result: int |
| 34 | +
|
| 35 | + model = models.from_transformers( |
| 36 | + AutoModelForCausalLM.from_pretrained("microsoft/Phi-3-mini-4k-instruct"), |
| 37 | + AutoTokenizer.from_pretrained("microsoft/Phi-3-mini-4k-instruct") |
| 38 | + ) |
| 39 | +
|
| 40 | + template_string = "What is 2 times {{ num }}?" |
| 41 | + template = Template.from_str(template_string) |
| 42 | +
|
| 43 | + my_macro = Macro(model, template, JsonType(OutputModel)) |
| 44 | +
|
| 45 | + result = my_macro(num=3) |
| 46 | + print(result) # Expected output: { "result" : 6 } |
| 47 | + """ |
| 48 | + model: Model |
| 49 | + template: Union[Template, Callable] |
| 50 | + output_type: Any |
| 51 | + |
| 52 | + def __post_init__(self): |
| 53 | + self.template = self.template |
| 54 | + self.generator = Generator(self.model, self.output_type) |
| 55 | + |
| 56 | + def __call__(self, *args, **kwargs): |
| 57 | + prompt = self.template(*args, **kwargs) |
| 58 | + return self.generator(prompt) |
0 commit comments