|
| 1 | +from dataclasses import dataclass |
| 2 | +from enum import Enum |
| 3 | +from typing import List, Optional |
| 4 | + |
| 5 | +from pydantic import BaseModel |
| 6 | +from typing_extensions import TypedDict |
| 7 | + |
| 8 | + |
| 9 | +class Document(TypedDict): |
| 10 | + title: str |
| 11 | + text: str |
| 12 | + |
| 13 | + |
| 14 | +class Role(Enum): |
| 15 | + system = "system" |
| 16 | + user = "user" |
| 17 | + assistant = "assistant" |
| 18 | + |
| 19 | + |
| 20 | +@dataclass |
| 21 | +class Message: |
| 22 | + role: Role |
| 23 | + content: str |
| 24 | + |
| 25 | + |
| 26 | +class Chat: |
| 27 | + def __init__( |
| 28 | + self, |
| 29 | + system_msg: Optional[str] = None, |
| 30 | + tools: Optional[List[BaseModel]] = None, |
| 31 | + documents: Optional[List[Document]] = None, |
| 32 | + history: List[Message] = [], |
| 33 | + ): |
| 34 | + self.history = history |
| 35 | + self.system = system_msg |
| 36 | + self.tools = tools |
| 37 | + self.documents = documents |
| 38 | + |
| 39 | + @property |
| 40 | + def trimmed_history(self): |
| 41 | + return self.history |
| 42 | + |
| 43 | + def __add__(self, other: Message): |
| 44 | + history = self.history |
| 45 | + history.append(other) |
| 46 | + return Chat(self.system, self.tools, self.documents, history=history) |
| 47 | + |
| 48 | + def __radd__(self, other: Message): |
| 49 | + history = self.history |
| 50 | + history.append(other) |
| 51 | + return Chat(self.system, self.tools, self.documents, history=history) |
| 52 | + |
| 53 | + def __iadd__(self, other: Message): |
| 54 | + self.history.append(other) |
| 55 | + return self |
| 56 | + |
| 57 | + def __getitem__(self, key): |
| 58 | + if isinstance(key, int): |
| 59 | + return self.history[key] |
| 60 | + else: |
| 61 | + raise KeyError() |
| 62 | + |
| 63 | + def render(self, model_name: str): |
| 64 | + """Render the conversation using the model's chat template. |
| 65 | +
|
| 66 | + TODO: Do this ourselves. |
| 67 | +
|
| 68 | + Parameters |
| 69 | + ---------- |
| 70 | + model_name |
| 71 | + The name of the model whose chat template we need to use. |
| 72 | +
|
| 73 | + """ |
| 74 | + from transformers import AutoTokenizer |
| 75 | + |
| 76 | + conversation = [] |
| 77 | + if self.system is not None: |
| 78 | + conversation.append({"role": "system", "content": self.system}) |
| 79 | + for message in self.trimmed_history: |
| 80 | + conversation.append({"role": message.role, "content": message.content}) |
| 81 | + |
| 82 | + self.tokenizer = AutoTokenizer.from_pretrained(model_name) |
| 83 | + |
| 84 | + return self.tokenizer.apply_chat_template( |
| 85 | + conversation, self.tools, self.documents |
| 86 | + ) |
0 commit comments