File size: 14,556 Bytes
cb994ee
43c192f
af1b567
cb994ee
 
 
4962f84
cb994ee
43c192f
e94650b
fa9ff48
af1b567
fa9ff48
af1b567
d94d450
af1b567
 
e94650b
cb994ee
fa9ff48
 
 
cb994ee
 
 
 
 
 
 
4962f84
 
cb994ee
e94650b
cb994ee
e94650b
4962f84
e94650b
ea307ae
 
 
 
 
 
 
 
 
 
 
 
52215c5
 
cb994ee
52215c5
e94650b
52215c5
4962f84
d94d450
 
e94650b
d94d450
ea307ae
 
 
d94d450
 
 
e94650b
d94d450
4962f84
ea307ae
cb994ee
ea307ae
 
cb994ee
e94650b
ea307ae
e94650b
cb994ee
b4fa6b2
cfd7ca0
ea307ae
 
 
cfd7ca0
ea307ae
cfd7ca0
ea307ae
b4fa6b2
ea307ae
e94650b
ea307ae
cb994ee
 
b4fa6b2
e94650b
b4fa6b2
cb994ee
0852e93
ea307ae
 
 
 
cb994ee
4962f84
af1b567
 
cb994ee
0852e93
b4fa6b2
af1b567
cb994ee
ea307ae
4962f84
cb994ee
0852e93
d94d450
cb994ee
4962f84
d94d450
af1b567
b4fa6b2
 
af1b567
ea307ae
cb994ee
e94650b
cfd7ca0
e94650b
cb994ee
 
4962f84
b4fa6b2
af1b567
cb994ee
ea307ae
cb994ee
e94650b
b4fa6b2
af1b567
 
cb994ee
b4fa6b2
af1b567
cb994ee
 
4962f84
af1b567
b4fa6b2
 
ea307ae
b4fa6b2
af1b567
ea307ae
cb994ee
e94650b
 
52215c5
e94650b
b4fa6b2
4962f84
af1b567
b4fa6b2
 
cb994ee
 
e94650b
cb994ee
4962f84
e94650b
 
 
 
 
 
cb994ee
cfd7ca0
e94650b
cb994ee
e94650b
cb994ee
b4fa6b2
 
cb994ee
e94650b
b4fa6b2
cb994ee
ea307ae
cb994ee
ea307ae
cb994ee
b4fa6b2
 
2f33702
e94650b
cb994ee
ea307ae
b4fa6b2
cb994ee
 
b4fa6b2
cb994ee
e94650b
 
 
 
 
 
 
4962f84
cb994ee
e94650b
cb994ee
4962f84
e94650b
52215c5
cfd7ca0
e94650b
52215c5
e94650b
 
 
 
ea307ae
e94650b
 
 
 
 
cfd7ca0
e94650b
4962f84
e94650b
ea307ae
e94650b
 
4962f84
e94650b
2f33702
52215c5
e94650b
52215c5
4962f84
ea307ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4962f84
cb994ee
e94650b
cb994ee
52215c5
4962f84
e94650b
af1b567
 
cb994ee
 
ea307ae
4962f84
af1b567
cb994ee
af1b567
4962f84
 
 
 
 
e94650b
 
4962f84
e94650b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb994ee
af1b567
e94650b
 
 
3707e31
cfd7ca0
cb994ee
 
b4fa6b2
3707e31
 
cb994ee
 
af1b567
b4fa6b2
3707e31
 
cb994ee
 
 
b4fa6b2
af1b567
e94650b
52215c5
 
 
 
4962f84
52215c5
af1b567
e94650b
 
 
3707e31
cfd7ca0
cb994ee
 
b4fa6b2
3707e31
 
cb994ee
 
 
b4fa6b2
3707e31
 
cb994ee
 
 
b4fa6b2
01c1d14
e94650b
52215c5
 
 
 
4962f84
 
 
e94650b
 
 
3707e31
cb994ee
 
 
 
3707e31
 
cb994ee
 
b4fa6b2
3707e31
 
cb994ee
 
b4fa6b2
e94650b
 
52215c5
 
 
 
97eaf87
e94650b
43c192f
cfd7ca0
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
import os
import gradio as gr
import google.generativeai as genai
import asyncio

###############################################################################
# 1. Настройка окружения и инициализация моделей
###############################################################################

# Подставьте свой ключ или берите из окружения
GEMINI_API_KEY = "AIzaSyBoqoPX-9uzvXyxzse0gRwH8_P9xO6O3Bc"
if not GEMINI_API_KEY:
    print("Error: GEMINI_API_KEY is not set.")
    exit()

genai.configure(api_key=GEMINI_API_KEY)

# Выберите доступные модели (пример)
AVAILABLE_MODELS = [
    "gemini-2.0-flash-exp",
    "gemini-exp-1206",
    "gemini-2.0-flash-thinking-exp-1219",
]

MODELS = {}
for model_name in AVAILABLE_MODELS:
    try:
        MODELS[model_name] = genai.GenerativeModel(model_name=model_name)
    except Exception as e:
        print(f"[Предупреждение] Не удалось инициализировать модель {model_name}: {e}")

###############################################################################
# 2. Дефолтные промпты (developer role) для каждой модели
###############################################################################
# Когда пользователь переключается на модель, мы добавляем это сообщение в историю.

DEFAULT_DEVELOPER_PROMPTS = {
    "gemini-2.0-flash-exp": (
        "You are a normal model (developer role). "
        "Provide direct answers with no JSON wrapping."
    ),
    "gemini-exp-1206": (
        "You are an experimental normal model (developer role). "
        "Provide direct answers with no JSON wrapping."
    ),
    "gemini-2.0-flash-thinking-exp-1219": (
        "You are a thinking model (developer role). "
        "Please provide your final answer in the format {output: ...}. "
        "You may use internal thoughts but do not show them directly to the user."
    ),
}

###############################################################################
# 3. Функция для определения роли ассистента (assistant vs model)
###############################################################################

def _assistant_role(model_name: str) -> str:
    """
    Некоторые новые модели не принимают 'assistant', а требуют 'model'.
    """
    # Допустим "gemini-exp-1206" и "gemini-2.0-flash-thinking-exp-1219" хотят "model"
    if model_name in ["gemini-exp-1206", "gemini-2.0-flash-thinking-exp-1219"]:
        return "model"
    return "assistant"

###############################################################################
# 4. Преобразование истории из Gradio в формат Generative AI
###############################################################################

def _history_to_genai_enhanced(history, model_name):
    """
    Улучшенная версия, отличающая developer-сообщения
    (префикс "<developer>: ") от user-сообщений.
    """
    asst_role = _assistant_role(model_name)
    genai_history = []

    for user_text, bot_text in history:
        if user_text:
            if user_text.startswith("<developer>: "):
                # Считаем это developer role
                dev_content = user_text.replace("<developer>: ", "", 1)
                genai_history.append({"role": "system", "parts": dev_content})
            else:
                # Обычный пользователь
                genai_history.append({"role": "user", "parts": user_text})

        if bot_text:
            # Ответ ассистента / модель
            genai_history.append({"role": asst_role, "parts": bot_text})

    return genai_history

###############################################################################
# 5. Генераторы для стрима обычных моделей и "thinking" моделей
###############################################################################

async def _respond_stream_enh(model_name, user_message, history):
    """
    Стриминговый ответ для обычных моделей:
    - Кусочек за кусочком (partial_text).
    """
    if model_name not in MODELS:
        yield "Ошибка: модель не найдена."
        return

    model = MODELS[model_name]
    genai_history = _history_to_genai_enhanced(history, model_name)

    try:
        chat = model.start_chat(history=genai_history)
        stream = chat.send_message(user_message, stream=True)

        partial_text = ""
        async for chunk in stream:
            partial_text += (chunk.text or "")
            yield partial_text

        return
    except Exception as e:
        yield f"Ошибка при запросе к API: {e}"
        return

async def _respond_thinking_enh(model_name, user_message, history):
    """
    Для thinking-моделей:
    1) Выводим "Думаю..."
    2) После завершения — финальный ответ в формате {output: ...} + размышления.
    """
    if model_name not in MODELS:
        yield "Ошибка: модель не найдена.", ""
        return

    model = MODELS[model_name]
    genai_history = _history_to_genai_enhanced(history, model_name)

    # Сначала "Думаю..."
    yield "Думаю...", ""

    try:
        chat = model.start_chat(history=genai_history)
        response = chat.send_message(user_message, stream=False)

        thinking_process_text = ""
        final_text = ""

        if response.candidates:
            parts = response.candidates[0].content.parts
            for p in parts:
                if hasattr(p, "thought") and p.thought:
                    thinking_process_text += p.text or ""
                else:
                    final_text += p.text or ""

        # Для thinking-моделей просили итоговый ответ в {output: ...}
        final_text_formatted = f"{{output: {final_text}}}"

        yield final_text_formatted, thinking_process_text
        return

    except Exception as e:
        yield f"Ошибка при запросе к API: {e}", ""
        return

###############################################################################
# 6. Основная функция для ввода пользователя
###############################################################################

async def user_send_message(
    user_message: str,
    history: list[tuple[str, str]],
    model_name: str,
    thinking_text: str
):
    """
    Колбэк, когда пользователь отправляет запрос.
    Добавляем в history новый (user_msg, None), затем генерируем ответ.
    """
    # Пустой ввод
    if not user_message.strip():
        yield history, thinking_text
        return

    # Добавляем (user_message, None)
    history.append((user_message, None))

    # Если модель — thinking
    if "thinking" in model_name.lower():
        async for (assistant_text, thought_text) in _respond_thinking_enh(model_name, user_message, history):
            history[-1] = (user_message, assistant_text)
            yield history, thought_text
        return
    else:
        # Обычная модель
        partial_answer = ""
        async for chunk in _respond_stream_enh(model_name, user_message, history):
            partial_answer = chunk
            history[-1] = (user_message, partial_answer)
            yield history, ""
        return

###############################################################################
# 7. Очистка диалога
###############################################################################

def clear_all():
    """Сброс истории и размышлений."""
    return [], ""

###############################################################################
# 8. Когда меняем модель в Dropdown
###############################################################################

def on_model_change(selected_model, history, thinking_text):
    """
    При переключении модели добавляем в историю developer-сообщение,
    + добавляем дефолтный промпт этой модели (тоже developer).
    """
    new_history = history.copy()

    # Cообщаем модели, что переключились (developer role)
    new_history.append((
        "<developer>: Switched to model: " + selected_model,
        None
    ))

    # Добавляем дефолтный промпт (developer role)
    default_prompt = DEFAULT_DEVELOPER_PROMPTS.get(
        selected_model,
        "No default prompt for this model."
    )
    new_history.append((
        "<developer>: " + default_prompt,
        None
    ))

    return new_history, thinking_text

###############################################################################
# 9. Функция конвертации истории с учётом developer role
###############################################################################

def _history_to_genai_enhanced(history, model_name):
    """
    Улучшенная версия, отличающая developer-сообщения
    (префикс "<developer>: ") от user-сообщений.
    """
    asst_role = _assistant_role(model_name)
    genai_history = []

    for user_text, bot_text in history:
        if user_text:
            if user_text.startswith("<developer>: "):
                # Считаем это developer role
                dev_content = user_text.replace("<developer>: ", "", 1)
                genai_history.append({"role": "system", "parts": dev_content})
            else:
                # Обычный пользователь
                genai_history.append({"role": "user", "parts": user_text})

        if bot_text:
            # Ответ ассистента / модель
            genai_history.append({"role": asst_role, "parts": bot_text})

    return genai_history

###############################################################################
# 10. Построение интерфейса Gradio
###############################################################################

with gr.Blocks() as demo:
    gr.Markdown("## Chat с Gemini. Поддержка developer role, переключения моделей, JSON-ответа для thinking")

    with gr.Row():
        model_dropdown = gr.Dropdown(
            choices=AVAILABLE_MODELS,
            value="gemini-2.0-flash-exp",
            label="Выберите модель"
        )
        clear_button = gr.Button("Очистить чат")

    history_state = gr.State([])
    thinking_store = gr.State("")

    chatbot = gr.Chatbot(label="Диалог с Gemini")
    user_input = gr.Textbox(label="Ваш вопрос", placeholder="Введите текст...")
    thinking_output = gr.Textbox(label="Размышления", interactive=False)
    send_btn = gr.Button("Отправить")

    ################################################
    # (A) Обработка переключения модели
    ################################################
    def handle_model_change(selected_model, history, thinking):
        new_history, new_thinking = on_model_change(selected_model, history, thinking)
        return new_history, new_thinking

    # Когда пользователь меняет модель:
    model_change = model_dropdown.change(
        fn=handle_model_change,
        inputs=[model_dropdown, history_state, thinking_store],
        outputs=[history_state, thinking_store],
        queue=False
    ).then(
        # После добавления developer-сообщений в историю → обновляем чат
        fn=lambda h: h,
        inputs=[history_state],
        outputs=[chatbot],
        queue=False
    )

    ################################################
    # (B) При нажатии «Отправить»
    ################################################
    send_chain = send_btn.click(
        fn=user_send_message,
        inputs=[user_input, history_state, model_dropdown, thinking_store],
        outputs=[history_state, thinking_store],
        queue=True
    )
    send_chain.then(
        fn=lambda h: h,
        inputs=[history_state],
        outputs=[chatbot],
        queue=True
    )
    send_chain.then(
        fn=lambda t: t,
        inputs=[thinking_store],
        outputs=[thinking_output],
        queue=True
    )
    # Очистка поля ввода
    send_chain.then(
        fn=lambda: "",
        inputs=[],
        outputs=[user_input],
        queue=False
    )

    ################################################
    # (C) При нажатии Enter в textbox
    ################################################
    submit_chain = user_input.submit(
        fn=user_send_message,
        inputs=[user_input, history_state, model_dropdown, thinking_store],
        outputs=[history_state, thinking_store],
        queue=True
    )
    submit_chain.then(
        fn=lambda h: h,
        inputs=[history_state],
        outputs=[chatbot],
        queue=True
    )
    submit_chain.then(
        fn=lambda t: t,
        inputs=[thinking_store],
        outputs=[thinking_output],
        queue=True
    )
    # Очистка поля ввода
    submit_chain.then(
        fn=lambda: "",
        inputs=[],
        outputs=[user_input],
        queue=False
    )

    ################################################
    # (D) Кнопка «Очистить»
    ################################################
    clear_chain = clear_button.click(
        fn=clear_all,
        inputs=[],
        outputs=[history_state, thinking_store],
        queue=False
    )
    clear_chain.then(
        fn=lambda h: h,
        inputs=[history_state],
        outputs=[chatbot]
    )
    clear_chain.then(
        fn=lambda _: "",
        inputs=[],
        outputs=[thinking_output]
    )
    clear_chain.then(
        fn=lambda: "",
        inputs=[],
        outputs=[user_input]
    )

# Запуск
if __name__ == "__main__":
    demo.launch()