import json, os # cache_dir = ".cache/" # if not os.path.exists(cache_dir): # os.mkdir(cache_dir) import transformers, torch from huggingface_hub import login cache_dir = "." os.environ["TORCH_HOME"] = cache_dir os.environ["TRANSFORMERS_HOME"] = cache_dir os.environ["HF_HOME"] = cache_dir os.environ["TRANSFORMERS_CACHE"] = cache_dir # CONSTANTS MAX_NEW_TOKENS = 1024 SYSTEM_MESSAGE = "You are a hepful, knowledgeable assistant" # # ENV VARS # # To avert Permision error with transformer and hf models # os.environ['SENTENCE_TRANSFORMERS_HOME'] = '.' # token = os.getenv("HF_TOKEN_WRITE") # Must be a write token # # Use the token to authenticate # login(token=token, # write_permission=True # Must be set to True when we pass in our own token # # Otherwise we get Permission Denied. # ) model_id = "microsoft/Phi-3.5-mini-instruct" # model_id = "meta-llama/Llama-3.2-1B-Instruct" def load_model(): print(f"Loading {model_id}") pipeline = transformers.pipeline( "text-generation", model=model_id, model_kwargs={"torch_dtype": torch.bfloat16}, device_map="auto", ) return pipeline def infer(model, message: str, n_output_tokens=256, message_store_path: str = "messages.jsonl"): """ Params: message: Most recent query to the llm. messages: Chat history up to current point properly formatted like {"role": "user", "content": "What is your name?"} """ if os.path.exists(message_store_path): with open(message_store_path, "r", encoding="utf-8") as f: messages = [json.loads(line) for line in f] else: messages = [ {"role": "system", "content": SYSTEM_MESSAGE}, ] messages.append({"role": "user", "content": message}) print(messages) # Perfom inference outputs = model( messages, max_new_tokens=n_output_tokens) output: list = outputs[0]["generated_text"] # Save the newly updated messages object with open(message_store_path, "a", encoding="utf-8") as f: for line in output: json.dump(line, f) f.write("\n") return output[-1]['content'] if __name__ == "__main__": model = load_model() while True: print("Press Ctrl + C to exit.") message = input("Ask a question.") print(infer(model, message)) print("---------------------------------------") print("\n\n") print(messages)