2024-07-08 07:17:28 +00:00
|
|
|
from pydantic import Field
|
|
|
|
from transformers import AutoModel, AutoTokenizer
|
|
|
|
from typing import Iterator
|
|
|
|
import torch
|
|
|
|
|
2024-07-09 03:37:30 +00:00
|
|
|
|
|
|
|
class CodegeexChatModel:
|
2024-07-08 07:17:28 +00:00
|
|
|
device: str = Field(description="device to load the model")
|
|
|
|
tokenizer = Field(description="model's tokenizer")
|
|
|
|
model = Field(description="Codegeex model")
|
|
|
|
temperature: float = Field(description="temperature to use for the model.")
|
|
|
|
|
2024-07-09 03:37:30 +00:00
|
|
|
def __init__(self, model_name_or_path):
|
2024-07-08 07:17:28 +00:00
|
|
|
super().__init__()
|
|
|
|
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
2024-07-09 03:37:30 +00:00
|
|
|
self.tokenizer = AutoTokenizer.from_pretrained(
|
|
|
|
model_name_or_path, trust_remote_code=True
|
|
|
|
)
|
|
|
|
self.model = (
|
|
|
|
AutoModel.from_pretrained(model_name_or_path, trust_remote_code=True)
|
|
|
|
.to(self.device)
|
|
|
|
.eval()
|
|
|
|
)
|
2024-07-08 07:17:28 +00:00
|
|
|
print("Model has been initialized.")
|
|
|
|
|
2024-07-09 03:37:30 +00:00
|
|
|
def chat(self, prompt, temperature=0.2, top_p=0.95):
|
2024-07-08 07:17:28 +00:00
|
|
|
try:
|
|
|
|
response, _ = self.model.chat(
|
|
|
|
self.tokenizer,
|
|
|
|
query=prompt,
|
2024-07-08 08:00:04 +00:00
|
|
|
max_length=120000,
|
2024-07-08 07:17:28 +00:00
|
|
|
temperature=temperature,
|
2024-07-09 03:37:30 +00:00
|
|
|
top_p=top_p,
|
2024-07-08 07:17:28 +00:00
|
|
|
)
|
|
|
|
return response
|
|
|
|
except Exception as e:
|
|
|
|
return f"error:{e}"
|
|
|
|
|
2024-07-09 03:37:30 +00:00
|
|
|
def stream_chat(self, prompt, temperature=0.2, top_p=0.95):
|
2024-07-08 07:17:28 +00:00
|
|
|
|
|
|
|
try:
|
|
|
|
for response, _ in self.model.stream_chat(
|
2024-07-09 03:37:30 +00:00
|
|
|
self.tokenizer,
|
|
|
|
query=prompt,
|
|
|
|
max_length=120000,
|
|
|
|
temperature=temperature,
|
|
|
|
top_p=top_p,
|
2024-07-08 07:17:28 +00:00
|
|
|
):
|
2024-07-08 08:00:04 +00:00
|
|
|
yield response
|
2024-07-08 07:17:28 +00:00
|
|
|
except Exception as e:
|
2024-07-09 03:37:30 +00:00
|
|
|
yield f"error: {e}"
|