AnatoliiG commited on
Commit ·
af83b4e
1
Parent(s): dd4c32e
update gradio
Browse files- app.py +49 -107
- requirements.txt +2 -3
app.py
CHANGED
|
@@ -28,7 +28,7 @@ try:
|
|
| 28 |
)
|
| 29 |
except Exception as e:
|
| 30 |
print(f"Critical Error: {e}")
|
| 31 |
-
|
| 32 |
|
| 33 |
# --- API (FastAPI) ---
|
| 34 |
app = FastAPI()
|
|
@@ -43,6 +43,9 @@ app.add_middleware(
|
|
| 43 |
|
| 44 |
@app.post("/v1/chat/completions")
|
| 45 |
async def chat_completions(request: Request):
|
|
|
|
|
|
|
|
|
|
| 46 |
try:
|
| 47 |
data = await request.json()
|
| 48 |
messages = data.get("messages", [])
|
|
@@ -72,16 +75,33 @@ async def chat_completions(request: Request):
|
|
| 72 |
|
| 73 |
|
| 74 |
# --- ЛОГИКА ГЕНЕРАЦИИ ДЛЯ GRADIO ---
|
| 75 |
-
|
| 76 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
messages = [{"role": "system", "content": system_prompt}]
|
| 78 |
|
| 79 |
-
# Берем последние 10
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
-
|
|
|
|
|
|
|
| 85 |
|
| 86 |
partial_text = ""
|
| 87 |
try:
|
|
@@ -96,16 +116,18 @@ def generate_response(message, history, system_prompt, temperature, max_tokens):
|
|
| 96 |
delta = chunk["choices"][0]["delta"]
|
| 97 |
if "content" in delta:
|
| 98 |
partial_text += delta["content"]
|
| 99 |
-
|
|
|
|
|
|
|
| 100 |
|
| 101 |
except Exception as e:
|
| 102 |
traceback.print_exc()
|
| 103 |
-
|
|
|
|
| 104 |
|
| 105 |
|
| 106 |
# --- ИНТЕРФЕЙС (Gradio Blocks) ---
|
| 107 |
|
| 108 |
-
# CSS для увеличения высоты окна чата и улучшения шрифтов кода
|
| 109 |
custom_css = """
|
| 110 |
#chatbot {
|
| 111 |
height: 70vh !important;
|
|
@@ -113,127 +135,47 @@ custom_css = """
|
|
| 113 |
}
|
| 114 |
"""
|
| 115 |
|
| 116 |
-
|
| 117 |
-
theme = gr.themes.Soft(
|
| 118 |
-
primary_hue="blue", secondary_hue="slate", neutral_hue="slate", text_size="lg"
|
| 119 |
-
)
|
| 120 |
|
| 121 |
with gr.Blocks(theme=theme, css=custom_css, title="Qwen Coder Pro") as demo:
|
| 122 |
gr.Markdown("# 💻 Qwen 2.5 Coder Assistant")
|
| 123 |
|
| 124 |
with gr.Row():
|
| 125 |
-
#
|
| 126 |
with gr.Column(scale=1, min_width=250):
|
| 127 |
gr.Markdown("### ⚙️ Settings")
|
| 128 |
-
|
| 129 |
system_prompt = gr.Textbox(
|
| 130 |
label="System Prompt",
|
| 131 |
-
value="You are an expert coding assistant. Write clean
|
| 132 |
-
lines=
|
| 133 |
-
interactive=True,
|
| 134 |
-
)
|
| 135 |
-
|
| 136 |
-
temperature = gr.Slider(
|
| 137 |
-
minimum=0.0,
|
| 138 |
-
maximum=1.0,
|
| 139 |
-
value=0.4,
|
| 140 |
-
step=0.1,
|
| 141 |
-
label="Creativity (Temperature)",
|
| 142 |
-
info="Lower = more precise code. Higher = more creative.",
|
| 143 |
)
|
|
|
|
|
|
|
|
|
|
| 144 |
|
| 145 |
-
|
| 146 |
-
minimum=512,
|
| 147 |
-
maximum=8192,
|
| 148 |
-
value=4096,
|
| 149 |
-
step=256,
|
| 150 |
-
label="Max Response Length",
|
| 151 |
-
info="Limit the length of the answer.",
|
| 152 |
-
)
|
| 153 |
-
|
| 154 |
-
gr.Markdown("---")
|
| 155 |
-
clear_btn = gr.Button("🗑️ Clear Chat", variant="secondary")
|
| 156 |
-
|
| 157 |
-
# Правая колонка - Чат (80% ширины)
|
| 158 |
with gr.Column(scale=4):
|
|
|
|
| 159 |
chatbot = gr.Chatbot(
|
| 160 |
label="Conversation",
|
| 161 |
elem_id="chatbot",
|
| 162 |
-
show_copy_button=True, #
|
| 163 |
-
avatar_images=(
|
| 164 |
-
None,
|
| 165 |
-
"https://api.iconify.design/noto:robot.svg",
|
| 166 |
-
), # Иконка бота
|
| 167 |
-
type="messages", # Новый формат сообщений Gradio
|
| 168 |
)
|
| 169 |
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
show_label=False,
|
| 173 |
-
placeholder="Type your code question here...",
|
| 174 |
-
scale=8,
|
| 175 |
-
container=False,
|
| 176 |
-
lines=2,
|
| 177 |
-
)
|
| 178 |
-
submit_btn = gr.Button("Run ➤", variant="primary", scale=1)
|
| 179 |
-
|
| 180 |
-
# --- СВЯЗКА СОБЫТИЙ ---
|
| 181 |
-
|
| 182 |
-
# Функция обертка для обработки истории в новом формате Gradio
|
| 183 |
-
def user_input(user_message, history):
|
| 184 |
-
return "", history + [{"role": "user", "content": user_message}]
|
| 185 |
-
|
| 186 |
-
def bot_response(history, sys_p, temp, m_tok):
|
| 187 |
-
# Преобразуем формат истории Gradio (список словарей) в формат для модели (список кортежей для старой логики или обработка словарей напрямую)
|
| 188 |
-
# Здесь мы адаптируем логику под список словарей
|
| 189 |
-
|
| 190 |
-
messages = [{"role": "system", "content": sys_p}]
|
| 191 |
-
# Добавляем историю (исключая последнее сообщение, которое мы добавим сейчас для генерации,
|
| 192 |
-
# но в новом формате Gradio история уже содержит последнее сообщение пользователя)
|
| 193 |
-
|
| 194 |
-
# Конвертация для LlamaCPP
|
| 195 |
-
llama_messages = [{"role": "system", "content": sys_p}]
|
| 196 |
-
|
| 197 |
-
# Берем последние 20 сообщений
|
| 198 |
-
relevant_history = history[-20:]
|
| 199 |
-
|
| 200 |
-
for msg in relevant_history:
|
| 201 |
-
llama_messages.append({"role": msg["role"], "content": msg["content"]})
|
| 202 |
-
|
| 203 |
-
partial_text = ""
|
| 204 |
-
history.append({"role": "assistant", "content": ""})
|
| 205 |
-
|
| 206 |
-
try:
|
| 207 |
-
stream = llm.create_chat_completion(
|
| 208 |
-
messages=llama_messages,
|
| 209 |
-
max_tokens=int(m_tok),
|
| 210 |
-
temperature=float(temp),
|
| 211 |
-
stream=True,
|
| 212 |
)
|
|
|
|
| 213 |
|
| 214 |
-
|
| 215 |
-
delta = chunk["choices"][0]["delta"]
|
| 216 |
-
if "content" in delta:
|
| 217 |
-
partial_text += delta["content"]
|
| 218 |
-
# Обновляем последнее сообщение ассистента в истории
|
| 219 |
-
history[-1]["content"] = partial_text
|
| 220 |
-
yield history
|
| 221 |
-
|
| 222 |
-
except Exception as e:
|
| 223 |
-
history[-1]["content"] = f"Error: {str(e)}"
|
| 224 |
-
yield history
|
| 225 |
-
|
| 226 |
-
# Отправка по Enter или кнопке
|
| 227 |
msg.submit(user_input, [msg, chatbot], [msg, chatbot], queue=False).then(
|
| 228 |
bot_response, [chatbot, system_prompt, temperature, max_tokens], chatbot
|
| 229 |
)
|
| 230 |
-
|
| 231 |
submit_btn.click(user_input, [msg, chatbot], [msg, chatbot], queue=False).then(
|
| 232 |
bot_response, [chatbot, system_prompt, temperature, max_tokens], chatbot
|
| 233 |
)
|
| 234 |
-
|
| 235 |
-
# Очистка
|
| 236 |
-
clear_btn.click(lambda: [], None, chatbot, queue=False)
|
| 237 |
|
| 238 |
app = mount_gradio_app(app, demo, path="/")
|
| 239 |
|
|
|
|
| 28 |
)
|
| 29 |
except Exception as e:
|
| 30 |
print(f"Critical Error: {e}")
|
| 31 |
+
llm = None
|
| 32 |
|
| 33 |
# --- API (FastAPI) ---
|
| 34 |
app = FastAPI()
|
|
|
|
| 43 |
|
| 44 |
@app.post("/v1/chat/completions")
|
| 45 |
async def chat_completions(request: Request):
|
| 46 |
+
if not llm:
|
| 47 |
+
return JSONResponse(content={"error": "Model not loaded"}, status_code=500)
|
| 48 |
+
|
| 49 |
try:
|
| 50 |
data = await request.json()
|
| 51 |
messages = data.get("messages", [])
|
|
|
|
| 75 |
|
| 76 |
|
| 77 |
# --- ЛОГИКА ГЕНЕРАЦИИ ДЛЯ GRADIO ---
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def user_input(user_message, history):
|
| 81 |
+
return "", history + [[user_message, None]]
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def bot_response(history, system_prompt, temperature, max_tokens):
|
| 85 |
+
if not llm:
|
| 86 |
+
history[-1][1] = "Error: Model failed to load. Check logs."
|
| 87 |
+
yield history
|
| 88 |
+
return
|
| 89 |
+
|
| 90 |
+
# Конвертируем историю Gradio (списки) в формат Llama (словари)
|
| 91 |
messages = [{"role": "system", "content": system_prompt}]
|
| 92 |
|
| 93 |
+
# Берем последние 10 диалогов для контекста
|
| 94 |
+
relevant_history = history[-11:-1] if len(history) > 1 else []
|
| 95 |
+
|
| 96 |
+
for user_msg, assistant_msg in relevant_history:
|
| 97 |
+
if user_msg:
|
| 98 |
+
messages.append({"role": "user", "content": user_msg})
|
| 99 |
+
if assistant_msg:
|
| 100 |
+
messages.append({"role": "assistant", "content": assistant_msg})
|
| 101 |
|
| 102 |
+
# Добавляем последнее сообщение пользователя
|
| 103 |
+
last_user_msg = history[-1][0]
|
| 104 |
+
messages.append({"role": "user", "content": last_user_msg})
|
| 105 |
|
| 106 |
partial_text = ""
|
| 107 |
try:
|
|
|
|
| 116 |
delta = chunk["choices"][0]["delta"]
|
| 117 |
if "content" in delta:
|
| 118 |
partial_text += delta["content"]
|
| 119 |
+
# Обновляем последнее сообщение ассистента в истории (классический формат)
|
| 120 |
+
history[-1][1] = partial_text
|
| 121 |
+
yield history
|
| 122 |
|
| 123 |
except Exception as e:
|
| 124 |
traceback.print_exc()
|
| 125 |
+
history[-1][1] = partial_text + f"\n\n❌ **Error:** {str(e)}"
|
| 126 |
+
yield history
|
| 127 |
|
| 128 |
|
| 129 |
# --- ИНТЕРФЕЙС (Gradio Blocks) ---
|
| 130 |
|
|
|
|
| 131 |
custom_css = """
|
| 132 |
#chatbot {
|
| 133 |
height: 70vh !important;
|
|
|
|
| 135 |
}
|
| 136 |
"""
|
| 137 |
|
| 138 |
+
theme = gr.themes.Soft(primary_hue="blue", text_size="lg")
|
|
|
|
|
|
|
|
|
|
| 139 |
|
| 140 |
with gr.Blocks(theme=theme, css=custom_css, title="Qwen Coder Pro") as demo:
|
| 141 |
gr.Markdown("# 💻 Qwen 2.5 Coder Assistant")
|
| 142 |
|
| 143 |
with gr.Row():
|
| 144 |
+
# Настройки
|
| 145 |
with gr.Column(scale=1, min_width=250):
|
| 146 |
gr.Markdown("### ⚙️ Settings")
|
|
|
|
| 147 |
system_prompt = gr.Textbox(
|
| 148 |
label="System Prompt",
|
| 149 |
+
value="You are an expert coding assistant. Write clean code.",
|
| 150 |
+
lines=3,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
)
|
| 152 |
+
temperature = gr.Slider(0.0, 1.0, value=0.4, label="Temperature")
|
| 153 |
+
max_tokens = gr.Slider(512, 8192, value=4096, label="Max Tokens")
|
| 154 |
+
clear_btn = gr.Button("🗑️ Clear Chat")
|
| 155 |
|
| 156 |
+
# Чат
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
with gr.Column(scale=4):
|
| 158 |
+
# ВАЖНО: Убрали type="messages", используем стандартный формат
|
| 159 |
chatbot = gr.Chatbot(
|
| 160 |
label="Conversation",
|
| 161 |
elem_id="chatbot",
|
| 162 |
+
show_copy_button=True, # Требует gradio>=3.37 (см. requirements.txt)
|
| 163 |
+
avatar_images=(None, "https://api.iconify.design/noto:robot.svg"),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
)
|
| 165 |
|
| 166 |
+
msg = gr.Textbox(
|
| 167 |
+
show_label=False, placeholder="Type your code question here...", lines=2
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
)
|
| 169 |
+
submit_btn = gr.Button("Run ➤", variant="primary")
|
| 170 |
|
| 171 |
+
# Связка событий
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
msg.submit(user_input, [msg, chatbot], [msg, chatbot], queue=False).then(
|
| 173 |
bot_response, [chatbot, system_prompt, temperature, max_tokens], chatbot
|
| 174 |
)
|
|
|
|
| 175 |
submit_btn.click(user_input, [msg, chatbot], [msg, chatbot], queue=False).then(
|
| 176 |
bot_response, [chatbot, system_prompt, temperature, max_tokens], chatbot
|
| 177 |
)
|
| 178 |
+
clear_btn.click(lambda: None, None, chatbot, queue=False)
|
|
|
|
|
|
|
| 179 |
|
| 180 |
app = mount_gradio_app(app, demo, path="/")
|
| 181 |
|
requirements.txt
CHANGED
|
@@ -1,6 +1,5 @@
|
|
| 1 |
fastapi
|
| 2 |
uvicorn
|
| 3 |
-
|
| 4 |
huggingface_hub
|
| 5 |
-
|
| 6 |
-
pydantic
|
|
|
|
| 1 |
fastapi
|
| 2 |
uvicorn
|
| 3 |
+
scipy
|
| 4 |
huggingface_hub
|
| 5 |
+
gradio>=4.19.0
|
|
|