File size: 3,034 Bytes
57645e8
e0ba145
fdefd2f
bd826f0
e0ba145
fdefd2f
e0ba145
 
 
 
fdefd2f
e0ba145
 
 
 
 
fdefd2f
 
e0ba145
 
 
 
 
 
 
 
 
 
 
 
 
884ac0c
e0ba145
 
 
884ac0c
fdefd2f
e0ba145
fdefd2f
5dee7eb
884ac0c
 
e0ba145
884ac0c
 
fdefd2f
e0ba145
5dee7eb
e0ba145
5dee7eb
e0ba145
884ac0c
e0ba145
fdefd2f
 
884ac0c
e0ba145
 
 
fdefd2f
884ac0c
e0ba145
 
 
 
 
 
 
 
 
 
 
5dee7eb
e0ba145
5dee7eb
884ac0c
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
import gradio as gr
from transformers import pipeline, AutoTokenizer
from datasets import load_dataset

# 1. Загрузка датасета с обработкой ошибок
try:
    dataset = load_dataset("sberbank-ai/ru_helpdesk", split="train[:50]")  # Первые 50 примеров
    examples = [d["question"] for d in dataset if "question" in d]
except Exception as e:
    print(f"Ошибка загрузки датасета: {e}")
    examples = [
        "Где мой заказ #12345?",
        "Как вернуть товар?",
        "Не приходит код подтверждения",
        "Ошибка при оплате картой",
        "Как изменить адрес доставки?"
    ]

# 2. Оптимизированная загрузка модели
try:
    tokenizer = AutoTokenizer.from_pretrained("IlyaGusev/saiga_mistral_7b-lora")
    model = pipeline(
        "text-generation",
        model="IlyaGusev/saiga_mistral_7b-lora",
        tokenizer=tokenizer,
        device="cpu",
        torch_dtype="auto",
        model_kwargs={"load_in_4bit": True}  # Критически важно для экономии памяти
    )
except Exception as e:
    raise RuntimeError(f"Ошибка загрузки модели: {str(e)}")

# 3. Генерация ответа с шаблоном
def generate_response(message):
    prompt = f"""Ты - ИИ-ассистент поддержки. Ответь клиенту вежливо и по делу.
    
Клиент: {message}
Ассистент:"""
    
    try:
        response = model(
            prompt,
            max_new_tokens=150,
            temperature=0.3,
            do_sample=True
        )
        return response[0]["generated_text"].split("Ассистент:")[-1].strip()
    except Exception as e:
        return f"⚠️ Ошибка генерации: {str(e)}"

# 4. Интерфейс с примерами
with gr.Blocks(theme=gr.themes.Soft()) as demo:
    gr.Markdown("""<h1><center>🎯 Поддержка клиентов</center></h1>""")
    
    with gr.Row():
        with gr.Column():
            input_text = gr.Textbox(label="Опишите проблему", placeholder="Мой заказ не прибыл...")
            output_text = gr.Textbox(label="Ответ поддержки", lines=5)
            btn = gr.Button("Отправить", variant="primary")
        
        with gr.Column():
            gr.Examples(
                examples=examples,
                inputs=input_text,
                label="Примеры обращений"
            )
            gr.Markdown("""
            **Советы для быстрого решения:**
            1. Указывайте номер заказа
            2. Прикладывайте скриншоты ошибок
            3. Проверяйте спам-папку
            """)

    btn.click(fn=generate_response, inputs=input_text, outputs=output_text)

demo.launch()