Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,64 +1,120 @@
|
|
1 |
import gradio as gr
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
|
6 |
-
"""
|
7 |
-
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
8 |
-
|
9 |
-
|
10 |
-
def respond(
|
11 |
-
message,
|
12 |
-
history: list[tuple[str, str]],
|
13 |
-
system_message,
|
14 |
-
max_tokens,
|
15 |
-
temperature,
|
16 |
-
top_p,
|
17 |
-
):
|
18 |
-
messages = [{"role": "system", "content": system_message}]
|
19 |
-
|
20 |
-
for val in history:
|
21 |
-
if val[0]:
|
22 |
-
messages.append({"role": "user", "content": val[0]})
|
23 |
-
if val[1]:
|
24 |
-
messages.append({"role": "assistant", "content": val[1]})
|
25 |
-
|
26 |
-
messages.append({"role": "user", "content": message})
|
27 |
-
|
28 |
-
response = ""
|
29 |
-
|
30 |
-
for message in client.chat_completion(
|
31 |
-
messages,
|
32 |
-
max_tokens=max_tokens,
|
33 |
-
stream=True,
|
34 |
-
temperature=temperature,
|
35 |
-
top_p=top_p,
|
36 |
-
):
|
37 |
-
token = message.choices[0].delta.content
|
38 |
-
|
39 |
-
response += token
|
40 |
-
yield response
|
41 |
-
|
42 |
-
|
43 |
-
"""
|
44 |
-
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
|
45 |
-
"""
|
46 |
-
demo = gr.ChatInterface(
|
47 |
-
respond,
|
48 |
-
additional_inputs=[
|
49 |
-
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
|
50 |
-
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
51 |
-
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
52 |
-
gr.Slider(
|
53 |
-
minimum=0.1,
|
54 |
-
maximum=1.0,
|
55 |
-
value=0.95,
|
56 |
-
step=0.05,
|
57 |
-
label="Top-p (nucleus sampling)",
|
58 |
-
),
|
59 |
-
],
|
60 |
-
)
|
61 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
|
63 |
if __name__ == "__main__":
|
64 |
-
demo.launch()
|
|
|
1 |
import gradio as gr
|
2 |
+
import google.generativeai as genai
|
3 |
+
import os
|
4 |
+
import asyncio # Import для асинхронности
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
|
6 |
+
# Безопасное получение API ключа
|
7 |
+
GEMINI_API_KEY = "AIzaSyBoqoPX-9uzvXyxzse0gRwH8_P9xO6O3Bc"
|
8 |
+
if not GEMINI_API_KEY:
|
9 |
+
print("Error: GEMINI_API_KEY environment variable not set.")
|
10 |
+
exit()
|
11 |
+
|
12 |
+
genai.configure(api_key=GEMINI_API_KEY)
|
13 |
+
|
14 |
+
AVAILABLE_MODELS = ["gemini-1.5-flash", "gemini-1.5-pro", "gemini-2.0-flash-thinking-exp"]
|
15 |
+
|
16 |
+
# Инициализация моделей один раз при запуске приложения
|
17 |
+
MODELS = {model_name: genai.GenerativeModel(model_name=model_name) for model_name in AVAILABLE_MODELS}
|
18 |
+
|
19 |
+
async def respond(message, history, selected_model):
|
20 |
+
model = MODELS.get(selected_model)
|
21 |
+
if not model:
|
22 |
+
yield "Error: Selected model not available.", ""
|
23 |
+
return
|
24 |
+
|
25 |
+
try:
|
26 |
+
chat = model.start_chat(history=history)
|
27 |
+
response_stream = chat.send_message(message, stream=True)
|
28 |
+
full_response = ""
|
29 |
+
for chunk in response_stream:
|
30 |
+
full_response += (chunk.text or "")
|
31 |
+
yield full_response, "" # Пустая строка для thinking output
|
32 |
+
except Exception as e:
|
33 |
+
yield f"Error during API call: {e}", ""
|
34 |
+
|
35 |
+
async def respond_thinking(message, history, selected_model):
|
36 |
+
if "thinking" not in selected_model:
|
37 |
+
yield "Thinking model не выбрана.", ""
|
38 |
+
return
|
39 |
+
|
40 |
+
model = MODELS.get(selected_model)
|
41 |
+
if not model:
|
42 |
+
yield "Error: Selected model not available.", ""
|
43 |
+
return
|
44 |
+
|
45 |
+
yield "", "Думаю..." # Сообщение о начале размышлений
|
46 |
+
|
47 |
+
try:
|
48 |
+
response = model.generate_content(message)
|
49 |
+
thinking_process_text = ""
|
50 |
+
model_response_text = ""
|
51 |
+
|
52 |
+
if response.candidates:
|
53 |
+
for part in response.candidates[0].content.parts:
|
54 |
+
if hasattr(part, 'thought') and part.thought == True:
|
55 |
+
thinking_process_text += f"Model Thought:\n{part.text}\n\n"
|
56 |
+
else:
|
57 |
+
model_response_text += (part.text or "")
|
58 |
+
|
59 |
+
yield model_response_text, thinking_process_text
|
60 |
+
except Exception as e:
|
61 |
+
yield f"Error during API call: {e}", f"Error during API call: {e}"
|
62 |
+
|
63 |
+
def update_chatbot_function(model_name):
|
64 |
+
if "thinking" in model_name:
|
65 |
+
return respond_thinking
|
66 |
+
else:
|
67 |
+
return respond
|
68 |
+
|
69 |
+
with gr.Blocks() as demo:
|
70 |
+
gr.Markdown("# Gemini Chatbot с режимом размышления")
|
71 |
+
|
72 |
+
with gr.Row():
|
73 |
+
model_selection = gr.Dropdown(
|
74 |
+
AVAILABLE_MODELS, value="gemini-1.5-flash", label="Выберите модель Gemini"
|
75 |
+
)
|
76 |
+
|
77 |
+
chatbot = gr.ChatInterface(
|
78 |
+
respond, # Изначально используем асинхронную функцию respond
|
79 |
+
additional_inputs=[model_selection],
|
80 |
+
title="Gemini Chat",
|
81 |
+
description="Общайтесь с моделями Gemini от Google.",
|
82 |
+
)
|
83 |
+
|
84 |
+
thinking_output = gr.Code(label="Процесс размышления (для моделей с размышлением)")
|
85 |
+
|
86 |
+
def change_function(model_name):
|
87 |
+
return update_chatbot_function(model_name)
|
88 |
+
|
89 |
+
model_selection.change(
|
90 |
+
change_function,
|
91 |
+
inputs=[model_selection],
|
92 |
+
outputs=[chatbot],
|
93 |
+
)
|
94 |
+
|
95 |
+
async def process_message(message, history, model_name):
|
96 |
+
if "thinking" in model_name:
|
97 |
+
generator = respond_thinking(message, history, model_name)
|
98 |
+
response, thinking = await generator.__anext__() # Получаем первое значение (пустое сообщение и "Думаю...")
|
99 |
+
yield response, thinking
|
100 |
+
final_response, final_thinking = await generator.__anext__() # Получаем окончательный ответ и размышления
|
101 |
+
yield final_response, final_thinking
|
102 |
+
else:
|
103 |
+
async for response, _ in respond(message, history, model_name):
|
104 |
+
yield response, ""
|
105 |
+
|
106 |
+
chatbot.input_messages[-1].submit(
|
107 |
+
process_message,
|
108 |
+
inputs=[chatbot.input_messages[-1], chatbot.chat_memory, model_selection],
|
109 |
+
outputs=[chatbot.output_messages[-1], thinking_output],
|
110 |
+
scroll_to_output=True,
|
111 |
+
)
|
112 |
+
|
113 |
+
chatbot.input_messages[-1].change(
|
114 |
+
lambda: "",
|
115 |
+
inputs=[],
|
116 |
+
outputs=[thinking_output]
|
117 |
+
)
|
118 |
|
119 |
if __name__ == "__main__":
|
120 |
+
demo.launch()
|