-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathlocal_llm_service.py
123 lines (84 loc) · 2.9 KB
/
local_llm_service.py
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import argparse
import torch
from flask import Flask, json, jsonify, request
from utils import (
LocalLLMCompletion,
LocalLLMEmbedding,
)
app = Flask(__name__)
@app.route("/v1/chat/completions/<model>", methods=["POST"])
def chat_completion_by_local_llm(model):
return local_llm_chat_completion_request(request,model)
@app.route("/v1/embeddings/<model>", methods=["POST"])
def embedding_by_local_llm(model):
return local_llm_embedding_request(request,model)
def local_llm_chat_completion_request(request,model):
# global model,tokenizer
request_data = request.data
json_data = json.loads(request_data)
try:
prompt = json_data["inputs"]
if "context" in json_data:
context = json_data["context"]
else:
context = ""
if "max_tokens" in json_data:
max_tokens = json_data["max_tokens"]
else:
max_tokens = 200
if "temperature" in json_data:
temperature = json_data["temperature"]
else:
temperature = 0.6
localLLMChatCompetetion = LocalLLMCompletion.LocalLLMCompletion(model)
chat_completion_text = localLLMChatCompetetion.call_local_llm_chat(prompt, context, max_tokens,temperature)
data = [{"generated_text": chat_completion_text}]
return jsonify(data)
except Exception as e:
print(e)
return "Sorry, unable to perform sentence completion with model {}".format(
model
)
def local_llm_embedding_request(request,model):
request_data = request.data
json_data = json.loads(request_data)
try:
sentences = json_data["inputs"]
localLLmEmbedding = LocalLLMEmbedding.LocalLLMEmbedding(model)
embeddings, num_prompt_tokens = localLLmEmbedding.call_local_llm_embeddings(sentences)
index = 0
data_entries = []
for embedding in embeddings:
data_entries.append(
{"object": "embedding", "index": index, "embedding": embedding.tolist()}
)
index = index + 1
data = {
"object": "list",
"data": data_entries,
"usage": {
"prompt_tokens": num_prompt_tokens,
"total_tokens": num_prompt_tokens,
},
}
return jsonify(data)
except Exception as e:
print(e)
return "Sorry, unable to generate embeddings with model {}".format(model)
if __name__ == "__main__":
if torch.backends.mps.is_available():
torch.set_default_device("mps")
parser = argparse.ArgumentParser()
parser.add_argument(
"-i", "--ip", default="0.0.0.0"
)
parser.add_argument(
"-p",
"--port",
default=5002,
type=int,
)
args = parser.parse_args()
host_ip = args.ip
port = args.port
app.run(host=host_ip, debug=True, port=port)