Spaces:
Sleeping

File size: 2,526 Bytes
ec455f6
 
8790464
 
 
 
4f37c86
 
 
 
8790464
c437eef
e78e0f3
c437eef
4f37c86
 
67138c2
ec455f6
1ad978f
ec455f6
 
1ad978f
 
 
 
ec455f6
1ad978f
 
 
 
 
ec455f6
1ad978f
 
ec455f6
 
1ad978f
ec455f6
 
 
 
 
 
1ad978f
ec455f6
 
71c54ff
ec455f6
 
 
71c54ff
 
ec455f6
71c54ff
 
 
 
 
 
 
ec455f6
71c54ff
ec455f6
 
71c54ff
ec455f6
71c54ff
 
 
ec455f6
71c54ff
ec455f6
 
 
71c54ff
 
1ad978f
 
71c54ff
1ad978f
 
 
71c54ff
1ad978f
 
 
ec455f6
1ad978f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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)