from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline, TextStreamer import torch from . import util from .inference_result import InferenceResult class LlmEngine: def __init__(self, model_path: str): """ Initialize the LLM Engine with a model path. Args: model_path: Path to the model weights to be used. """ self.set_model_path(model_path) def set_model_path(self, model_path: str): """ Load the model from the specified path. Args: model_path: Path to the model weights to load. """ self.tokenizer = AutoTokenizer.from_pretrained(model_path) model = AutoModelForCausalLM.from_pretrained( model_path, return_dict=True, low_cpu_mem_usage=True, torch_dtype=torch.bfloat16, device_map="auto", trust_remote_code=True, ) if self.tokenizer.pad_token_id is None: self.tokenizer.pad_token_id = self.tokenizer.eos_token_id if model.config.pad_token_id is None: model.config.pad_token_id = model.config.eos_token_id streamer = TextStreamer( self.tokenizer, skip_prompt=True ) self.pipeline = pipeline( "text-generation", model=model, tokenizer=self.tokenizer, torch_dtype=torch.bfloat16, device_map="auto", streamer=streamer, return_full_text=False, ) def infer(self, system_prompt: str, main_context: str, action_schema: str) -> InferenceResult: """ Run inference using the system prompt and main context, while validating actions against the provided XML schema. Args: system_prompt: The system prompt string main_context: The main context string after templating action_schema: XML schema to validate the generated actions Returns: InferenceResult: Tuple containing reasoning and actions that validate against the schema """ valid_elements = util.get_valid_root_elements(action_schema) messages = [ {"role": "system", "content": system_prompt}, {"role": "user", "content": main_context} ] prompt = self.tokenizer.apply_chat_template( messages, tokenize=False, add_generation_prompt=True ) outputs = self.pipeline(prompt, max_new_tokens=120, do_sample=True) generated_text = outputs[0]["generated_text"] #response = generated_text.split("<|start_header_id|>assistant<|end_header_id|>",1)[1].strip() result = util.split_response(generated_text, valid_elements) return result def finetune(self, dataset_paths: list, output_dir: str): """ Fine-tune the model with new datasets and save the updated model weights. Args: dataset_paths: List of paths to datasets for fine-tuning. output_dir: Directory where the updated model weights will be saved. """ pass