File size: 2,480 Bytes
a844653
56205e9
152d4a2
1cc747b
56205e9
6066e39
a844653
152d4a2
a844653
 
 
152d4a2
a844653
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152d4a2
6066e39
56205e9
 
 
a844653
 
 
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
import logging
from fastapi import FastAPI
from llama_cpp import Llama

app = FastAPI()

CHAT_TEMPLATE = '<|system|> {system_prompt}<|end|><|user|> {prompt}<|end|><|assistant|>'.strip()

logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO
)
logger = logging.getLogger(__name__)

logger.info("Запускаемся... 🥳🥳🥳")

# Инициализация модели
try:
    # загрузка модели для локального хранилища
    # llm = Llama(
    #     model_path="./models/phi-3-mini-4k-instruct-q4.gguf",
    #     verbose=False,
    #     n_gpu_layers=-1,
    #     n_ctx=4096
    # )

    logger.info("Загрузка модели...")
    llm = Llama.from_pretrained(
        repo_id='bartowski/Phi-3.5-mini-instruct-GGUF',
        filename='Phi-3.5-mini-instruct-Q6_K_L.gguf',
        n_gpu_layers=-1,
        n_ctx=4096,
    )

except Exception as e:
    logger.error(f"Ошибка загрузки модели: {str(e)}")
    raise


# составление промта для модели
def create_prompt(text: str) -> str | None:
    try:
        user_input = text
        logger.info(f"Получено сообщение: {user_input}")

        system_prompt = 'Ответ должен быть точным и кратким и если возможно шутливым.'

        # Генерация шаблона
        return CHAT_TEMPLATE.format(
            system_prompt=system_prompt,
            prompt=user_input,
        )
    except Exception as e:
        logger.error(e)


def generate_response(prompt: str) -> str:
    try:
        # Обработка текстового сообщения
        output = llm(
            prompt,
            max_tokens=512,
            stop=["<|end|>"],
        )

        logger.info('Output:')
        logger.info(output)

        response: str = output['choices'][0]['text']

        # Отправка ответа
        if response:
            return response

        return 'Произошла ошибка при обработке запроса'
    except Exception as e:
        logger.error(f"Ошибка обработки сообщения: {str(e)}")


@app.post("/predict")
async def predict(text: str):
    # Генерация ответа с помощью модели
    prompt = create_prompt(text)
    response = generate_response(prompt)
    return {"response": response}