ahmetmete commited on
Commit
da3cbbe
1 Parent(s): 09e0efb

Create handler.py

Browse files
Files changed (1) hide show
  1. handler.py +26 -0
handler.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Any
2
+ import torch
3
+ from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig
4
+
5
+ class EndpointHandler():
6
+ def __init__(self, path=""):
7
+ self.tokenizer = AutoTokenizer.from_pretrained(path)
8
+ self.model = AutoModelForCausalLM.from_pretrained(path, torch_dtype=torch.bfloat16, device_map="auto")
9
+ self.model.generation_config = GenerationConfig.from_pretrained(path)
10
+ self.model.generation_config.pad_token_id = self.model.generation_config.eos_token_id
11
+
12
+ def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
13
+ inputs = data.pop('inputs', data)
14
+ messages = [{"role": "user", "content": inputs}]
15
+
16
+ # Mesajları modelin anlayacağı formata dönüştürme
17
+ input_texts = [message["content"] for message in messages]
18
+ input_text = self.tokenizer.eos_token.join(input_texts)
19
+ input_ids = self.tokenizer.encode(input_text, return_tensors="pt")
20
+
21
+ # Modelden yanıt üretme
22
+ outputs = self.model.generate(input_ids.to(self.model.device), max_new_tokens=100)
23
+
24
+ # Üretilen yanıtı çözme
25
+ result = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
26
+ return [{"result": result}]