File size: 3,865 Bytes
68300d0
065ca46
fe67270
8cbfc7e
fe67270
78ac0ef
fe67270
68300d0
464f8f9
fe67270
78ac0ef
4c2e13f
78ac0ef
4c2e13f
 
 
 
 
 
 
 
78ac0ef
4c2e13f
78ac0ef
 
065ca46
 
 
4c2e13f
78ac0ef
4c2e13f
78ac0ef
 
 
 
 
464f8f9
fe67270
464f8f9
78ac0ef
fe67270
78ac0ef
fe67270
 
78ac0ef
fe67270
 
 
 
78ac0ef
 
fe67270
464f8f9
fe67270
 
 
 
 
464f8f9
fe67270
78ac0ef
fe67270
 
464f8f9
78ac0ef
 
 
464f8f9
 
fe67270
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78ac0ef
fe67270
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68300d0
fe67270
68300d0
 
464f8f9
68300d0
78ac0ef
 
 
 
 
 
 
 
de3d994
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
import gradio as gr
from ctransformers import AutoModelForCausalLM
import os
from huggingface_hub import hf_hub_download

# Глобальная переменная для модели
model = None

def load_model():
    global model
    try:
        print("Начинаем загрузку модели из Hub...")
        
        # Загружаем файл модели из Hub
        model_path = hf_hub_download(
            repo_id="AugustLight/LLight-3.2-3B-Instruct",
            filename="Llight.Q8_0.gguf",
            repo_type="model"
        )
        
        print(f"Модель загружена в: {model_path}")
        
        # Инициализируем модель
        model = AutoModelForCausalLM.from_pretrained(
            model_path,
            model_type="llama",
            context_length=2048,
            gpu_layers=0,
            threads=4
        )
        print("Модель успешно инициализирована!")
        return model
        
    except Exception as e:
        print(f"Подробная ошибка при загрузке модели: {str(e)}")
        raise e

def respond(message, history, system_message, max_new_tokens, temperature, top_p):
    try:
        global model
        if model is None:
            model = load_model()
            
        # Формируем контекст из истории
        context = f"{system_message}\n\n"
        for user_msg, assistant_msg in history:
            context += f"User: {user_msg}\nAssistant: {assistant_msg}\n"
        context += f"User: {message}\nAssistant: "

        print(f"Генерируем ответ для контекста длиной {len(context)} символов")
        
        # Генерируем ответ
        response = model(
            context,
            max_tokens=max_new_tokens,
            temperature=temperature,
            top_p=top_p,
            stop=["User:", "\n\n", "<|endoftext|>"]
        )
        
        print(f"Ответ сгенерирован успешно, длина: {len(response)}")
        return response.strip()
        
    except Exception as e:
        error_msg = f"Произошла ошибка: {str(e)}"
        print(error_msg)
        return error_msg

# Создаем интерфейс
demo = gr.ChatInterface(
    respond,
    additional_inputs=[
        gr.Textbox(
            value="Ты дружелюбный и полезный ассистент. Ты всегда отвечаешь кратко и по делу.", 
            label="System message"
        ),
        gr.Slider(
            minimum=1, 
            maximum=2048, 
            value=512, 
            step=1, 
            label="Max new tokens"
        ),
        gr.Slider(
            minimum=0.1, 
            maximum=2.0, 
            value=0.7, 
            step=0.1, 
            label="Temperature"
        ),
        gr.Slider(
            minimum=0.1,
            maximum=1.0,
            value=0.95,
            step=0.05,
            label="Top-p (nucleus sampling)"
        ),
    ],
    title="GGUF Chat Model",
    description="Чат с GGUF моделью (Llight.Q8_0.gguf)",
    examples=[
        ["Привет! Как дела?"],
        ["Расскажи мне о себе"],
        ["Что ты умеешь делать?"]
    ],
    cache_examples=False
)

# Запускаем приложение
if __name__ == "__main__":
    # Пробуем загрузить модель при запуске
    try:
        print("Инициализация приложения...")
        model = load_model()
        print("Модель загружена успешно при старте")
    except Exception as e:
        print(f"Ошибка при инициализации: {str(e)}")
    
    demo.launch()