Spaces:
Running
Running
File size: 13,490 Bytes
cb994ee 43c192f af1b567 cb994ee 4962f84 cb994ee 43c192f e94650b cfd7ca0 af1b567 cfd7ca0 af1b567 d94d450 af1b567 e94650b cb994ee cfd7ca0 cb994ee 4962f84 cb994ee e94650b cb994ee e94650b 4962f84 e94650b cfd7ca0 52215c5 cfd7ca0 52215c5 cb994ee 52215c5 e94650b 52215c5 4962f84 d94d450 e94650b d94d450 cfd7ca0 d94d450 e94650b d94d450 4962f84 e94650b cb994ee e94650b cb994ee e94650b cb994ee b4fa6b2 cfd7ca0 b4fa6b2 e94650b cb994ee b4fa6b2 e94650b b4fa6b2 cb994ee cfd7ca0 e94650b cb994ee 4962f84 af1b567 cb994ee e94650b b4fa6b2 af1b567 cb994ee cfd7ca0 4962f84 cb994ee cfd7ca0 d94d450 cb994ee 4962f84 d94d450 af1b567 b4fa6b2 af1b567 cb994ee e94650b cfd7ca0 e94650b cb994ee 4962f84 b4fa6b2 af1b567 cb994ee e94650b cb994ee e94650b b4fa6b2 af1b567 cb994ee b4fa6b2 af1b567 cb994ee 4962f84 af1b567 b4fa6b2 cfd7ca0 b4fa6b2 cfd7ca0 af1b567 cfd7ca0 cb994ee e94650b 52215c5 e94650b b4fa6b2 4962f84 af1b567 b4fa6b2 cb994ee e94650b cb994ee 4962f84 e94650b cb994ee cfd7ca0 e94650b cb994ee e94650b cb994ee b4fa6b2 cb994ee e94650b b4fa6b2 cb994ee cfd7ca0 cb994ee cfd7ca0 cb994ee b4fa6b2 2f33702 e94650b cb994ee b4fa6b2 cb994ee b4fa6b2 cb994ee e94650b 4962f84 cb994ee e94650b cb994ee 4962f84 e94650b 52215c5 cfd7ca0 e94650b 52215c5 e94650b cfd7ca0 e94650b cfd7ca0 e94650b 4962f84 e94650b cfd7ca0 e94650b 4962f84 e94650b 2f33702 52215c5 e94650b 52215c5 4962f84 cfd7ca0 4962f84 cb994ee e94650b cb994ee 52215c5 4962f84 e94650b af1b567 cb994ee cfd7ca0 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 |
import os
import gradio as gr
import google.generativeai as genai
import asyncio
###############################################################################
# 1. Настройка окружения и инициализация моделей
###############################################################################
# Подставьте свой ключ или берите из окружения
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
if not GEMINI_API_KEY:
print("Error: GEMINI_API_KEY is not set. Please set the environment variable.")
exit()
genai.configure(api_key=GEMINI_API_KEY)
# Выберите доступные модели (пример)
AVAILABLE_MODELS = [
"gemini-1.5-flash",
# Add other available models if needed
]
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-1.5-flash": (
"You are a helpful assistant (developer role). "
"Provide direct answers."
),
# Add default prompts for other models if needed
}
###############################################################################
# 3. Функция для определения роли ассистента (assistant vs model)
###############################################################################
def _assistant_role(model_name: str) -> str:
"""
Некоторые новые модели не принимают 'assistant', а требуют 'model'.
"""
# Adjust based on model requirements
return "assistant"
###############################################################################
# 4. Преобразование истории из Gradio в формат Generative AI
###############################################################################
def _history_to_genai(history, model_name):
"""
Gradio хранит [(user_msg, bot_msg), ...].
Google GenAI ждёт [{"role": "...", "parts": "..."}].
Дополнительно учитываем developer-сообщения, которые мы вставляем.
"""
genai_history = []
asst_role = _assistant_role(model_name)
for user_text, bot_text in history:
if user_text:
if user_text.startswith("<developer>: "):
genai_history.append({"role": "system", "parts": user_text.replace("<developer>: ", "", 1)})
else:
# Пользовательское сообщение
genai_history.append({"role": "user", "parts": user_text})
if bot_text:
# Ответ ассистента (или model)
genai_history.append({"role": asst_role, "parts": bot_text})
return genai_history
###############################################################################
# 5. Генераторы для стрима обычных моделей и "thinking" моделей
###############################################################################
async def _respond_stream(model_name, user_message, history):
"""
Стриминговый ответ для обычных моделей:
- Кусочек за кусочком (partial_text).
"""
if model_name not in MODELS:
yield "Ошибка: модель не найдена."
return
model = MODELS[model_name]
genai_history = _history_to_genai(history, model_name)
try:
chat = model.start_chat(history=genai_history)
response = chat.send_message(user_message, stream=True)
partial_text = ""
async for chunk in response:
partial_text += (chunk.text or "")
yield partial_text
return
except Exception as e:
yield f"Ошибка при запросе к API: {e}"
return
async def _respond_thinking(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(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:
# Assuming a specific structure for "thinking" models' output
# This part might need adjustments based on actual model output
if isinstance(p, dict) and "output" not in p: # Heuristic for thought
thinking_process_text += p.text or ""
elif isinstance(p, dict) and "output" in p:
final_text += p["output"] # Assuming output is directly in the dict
else:
final_text += p.text or "" # Fallback
# Для 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 (adjust logic based on actual model names)
if "thinking" in model_name.lower():
async for assistant_text, thought_text in _respond_thinking(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(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((
f"<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((
f"<developer>: {default_prompt}",
None
))
return new_history, thinking_text
###############################################################################
# 9. Функция конвертации истории с учётом developer role
###############################################################################
# This part is already implemented in _history_to_genai
###############################################################################
# 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=AVAILABLE_MODELS[0] if AVAILABLE_MODELS else None,
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() |