fehmikaya commited on
Commit
21a683d
·
verified ·
1 Parent(s): 3cf4e75

Create llama3.py

Browse files
Files changed (1) hide show
  1. llama3.py +48 -0
llama3.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import requests
3
+
4
+ class llama3chat:
5
+
6
+ def __init__(self, url, bearer_token, max_new_tokens,top_p,temperature):
7
+ self.url = url
8
+ self.bearer_token = bearer_token
9
+ self.headers = {
10
+ 'Content-Type': 'application/json',
11
+ 'Authorization': f'Bearer {bearer_token}'
12
+ }
13
+ self.max_new_tokens=max_new_tokens
14
+ self.top_p=top_p
15
+ self.temperature=temperature
16
+
17
+ def format_llama_messages(self, messages):
18
+
19
+ prompt = []
20
+
21
+ if messages[0]["role"] == "system":
22
+ content = "<|begin_of_text|><|start_header_id|>system<|end_header_id|>\n\n"+messages[0]["content"]+ "<|eot_id|>\n\n"
23
+ prompt.append(content)
24
+ for user, answer in zip(messages[1::2], messages[2::2]):
25
+ prompt.append("<|start_header_id|>user<|end_header_id|>"+ (user["content"]).strip()+ "<|eot_id|><|start_header_id|>assistant<|end_header_id|>"+ (answer["content"]).strip()+ "<|eot_id|>")
26
+
27
+ prompt.append("<|start_header_id|>user<|end_header_id|>"+ (messages[-1]["content"]).strip()+ "<|eot_id|>")
28
+
29
+ return "".join(prompt)
30
+
31
+ def query(self, all_messages):
32
+ formatted_messages=self.format_llama_messages(all_messages)
33
+ json_body = {
34
+ "inputs": formatted_messages,
35
+ "parameters": {"max_new_tokens":self.max_new_tokens, "top_p":self.top_p, "temperature":self.temperature}
36
+ }
37
+ data = json.dumps(json_body)
38
+ response = requests.request("POST", self.url, headers=self.headers, data=data)
39
+ try:
40
+ result=json.loads(response.content.decode("utf-8"))[0]['generated_text']
41
+ target_substring = '|eot_id|>assistant'
42
+ substring_length = len(target_substring)
43
+ last_occurrence_index = result.rfind(target_substring)
44
+ if last_occurrence_index != -1:
45
+ return result[last_occurrence_index + substring_length:].strip()
46
+ except:
47
+ return response
48
+