|
| 1 | +from typing import Union, List, Dict, Callable |
| 2 | +from dataclasses import asdict |
| 3 | +from .base_textgen import TextGenerator |
| 4 | +from ...datamodel import TextGenerationConfig, TextGenerationResponse, Message |
| 5 | +from ...utils import cache_request, num_tokens_from_messages |
| 6 | + |
| 7 | + |
| 8 | +class CustomTextGenerator(TextGenerator): |
| 9 | + def __init__( |
| 10 | + self, |
| 11 | + text_generation_function: Callable[[str], str], |
| 12 | + provider: str = "custom", |
| 13 | + **kwargs |
| 14 | + ): |
| 15 | + super().__init__(provider=provider, **kwargs) |
| 16 | + self.text_generation_function = text_generation_function |
| 17 | + |
| 18 | + def generate( |
| 19 | + self, |
| 20 | + messages: Union[List[Dict], str], |
| 21 | + config: TextGenerationConfig = TextGenerationConfig(), |
| 22 | + **kwargs |
| 23 | + ) -> TextGenerationResponse: |
| 24 | + use_cache = config.use_cache |
| 25 | + messages = self.format_messages(messages) |
| 26 | + cache_key = {"messages": messages, "config": asdict(config)} |
| 27 | + if use_cache: |
| 28 | + response = cache_request(cache=self.cache, params=cache_key) |
| 29 | + if response: |
| 30 | + return TextGenerationResponse(**response) |
| 31 | + |
| 32 | + generation_response = self.text_generation_function(messages) |
| 33 | + response = TextGenerationResponse( |
| 34 | + text=[Message(role="system", content=generation_response)], |
| 35 | + logprobs=[], # You may need to extract log probabilities from the response if needed |
| 36 | + usage={}, |
| 37 | + config={}, |
| 38 | + ) |
| 39 | + |
| 40 | + if use_cache: |
| 41 | + cache_request( |
| 42 | + cache=self.cache, params=cache_key, values=asdict(response) |
| 43 | + ) |
| 44 | + |
| 45 | + return response |
| 46 | + |
| 47 | + def format_messages(self, messages) -> str: |
| 48 | + prompt = "" |
| 49 | + for message in messages: |
| 50 | + if message["role"] == "system": |
| 51 | + prompt += message["content"] + "\n" |
| 52 | + else: |
| 53 | + prompt += message["role"] + ": " + message["content"] + "\n" |
| 54 | + |
| 55 | + return prompt |
| 56 | + |
| 57 | + def count_tokens(self, text) -> int: |
| 58 | + return num_tokens_from_messages(text) |
0 commit comments