forked from KonstFed/RAGCore
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
392 lines (323 loc) · 13.1 KB
/
app.py
File metadata and controls
392 lines (323 loc) · 13.1 KB
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
from uuid import uuid4
import gradio as gr
from src.assistant import Assistant
assistant = Assistant(service_cfg_path="configs/deployment_config.yaml")
def _build_delete_request(repo_url: str) -> dict:
return {
"meta": {"request_id": str(uuid4())},
"repo_url": repo_url,
}
def _build_index_request(repo_url: str) -> tuple[dict, dict]:
request = {
"meta": {"request_id": str(uuid4())},
"repo_url": repo_url,
"branch": "main",
}
config = {
"ast_chunker_config": {
"max_chunk_size": 1000,
"chunk_overlap": 50,
"extensions": [
".py",
".ipynb",
".cpp",
".h",
".java",
".ts",
".tsx",
".cs",
],
"chunk_expansion": True,
"metadata_template": "default",
},
"text_splitter_config": {"chunk_size": 500, "chunk_overlap": 50},
"exclude_patterns": ["*.lock", "__pycache__", ".venv", "build"],
}
return request, config
def _build_search_config() -> dict:
return {
"query_preprocessor": {
"enabled": True,
"normalize_whitespace": True,
"sanitization": {
"enabled": True,
"regex_patterns": ["jailbreak", "hallucinations"],
"replacement_token": "",
},
},
"query_rewriter": {"enabled": False},
"retriever": {"enabled": True},
"filtering": {"enabled": True},
"reranker": {"enabled": False},
"context_expansion": {"enabled": True},
"qa": {"enabled": True},
"query_postprocessor": {
"enabled": True,
"format_markdown": True,
"sanitization": {
"enabled": True,
"regex_patterns": ["can't", "wtf"],
"replacement_token": "",
},
},
}
async def index_repo(repo_url: str) -> str:
if not repo_url:
return "❌ **Ошибка:** Введите GitHub URL."
request, config = _build_index_request(repo_url)
try:
response = await assistant.index(request, config)
# Calculate duration
duration = (
response.meta.end_datetime - response.meta.start_datetime
).total_seconds()
# Build verbose response
result = []
result.append("## 📊 Результат индексации\n")
result.append(f"**Request ID:** `{response.meta.request_id}`\n")
result.append(f"**Repository URL:** {response.repo_url}\n")
result.append(f"**Время выполнения:** {duration:.2f} секунд\n")
result.append(f"**Статус:** {response.meta.status}\n")
# Check if repo was already indexed
is_already_indexed = (
response.job_status.description_error
and "already indexed" in response.job_status.description_error.lower()
)
if is_already_indexed:
result.append("\n⚠️ **Репозиторий уже проиндексирован**\n")
result.append(
"Индексация была пропущена, так как репозиторий "
"уже существует в базе данных.\n"
)
else:
# Show job status details
if response.job_status.status:
status_emoji = {
"failed": "❌",
"loaded": "📥",
"parsed": "🔍",
"vectorized": "🧮",
"saved_to_qdrant": "✅",
}
emoji = status_emoji.get(response.job_status.status, "ℹ️")
result.append(
f"\n**Статус задачи:** {emoji} {response.job_status.status}\n"
)
# Show chunks processed
if response.job_status.chunks_processed is not None:
result.append(
f"**Обработано чанков:** {response.job_status.chunks_processed}\n"
)
# Show errors if any
if response.meta.status == "error":
result.append("\n### ❌ Ошибка при индексации\n")
if response.job_status.description_error:
result.append(
f"**Описание ошибки:**\n```\n"
f"{response.job_status.description_error}\n```\n"
)
else:
result.append("Произошла ошибка во время индексации.\n")
elif response.job_status.status == "saved_to_qdrant":
result.append("\n### ✅ Индексация завершена успешно\n")
result.append(
"Репозиторий успешно проиндексирован и сохранен "
"в векторную базу данных.\n"
)
return "".join(result)
except Exception as e:
return f"❌ **Критическая ошибка:** {type(e).__name__}: {str(e)}"
async def delete_index(repo_url: str) -> str:
if not repo_url:
return "❌ **Ошибка:** Введите GitHub URL."
request = _build_delete_request(repo_url)
try:
response = await assistant.delete_index(request)
# Calculate duration
duration = (
response.meta.end_datetime - response.meta.start_datetime
).total_seconds()
# Build verbose response
result = []
result.append("## 🗑️ Результат удаления индекса\n")
result.append(f"**Request ID:** `{response.meta.request_id}`\n")
result.append(f"**Repository URL:** {response.repo_url}\n")
result.append(f"**Время выполнения:** {duration:.2f} секунд\n")
result.append(f"**Статус:** {response.meta.status}\n")
if response.success:
result.append("\n### ✅ Удаление завершено успешно\n")
result.append(
"Индекс репозитория успешно удален из векторной базы данных.\n"
)
if response.message:
result.append(f"\n**Сообщение:** {response.message}\n")
else:
result.append("\n### ❌ Ошибка при удалении\n")
if response.message:
result.append(f"**Описание ошибки:**\n```\n{response.message}\n```\n")
else:
result.append("Произошла ошибка во время удаления индекса.\n")
return "".join(result)
except Exception as e:
return f"❌ **Критическая ошибка:** {type(e).__name__}: {str(e)}"
def _collect_sources(response) -> list[dict]:
sources = []
if getattr(response, "sources", None):
for source in response.sources:
sources.append(
{
"filepath": source.metadata.filepath,
"language": source.metadata.language or "",
"content": source.content,
}
)
return sources
def _render_sources(sources: list[dict], show_sources: bool) -> str:
if not sources:
return "Источники:\n- не найдено\n"
sources_md = "Источники:\n"
for source in sources:
sources_md += f"- {source['filepath']}\n"
if show_sources:
sources_md += f"\n```{source['language']}\n"
sources_md += f"{source['content']}\n"
sources_md += "```\n"
return sources_md
def _content_to_text(content) -> str:
if content is None:
return ""
if isinstance(content, str):
return content
if isinstance(content, dict):
return str(content.get("text") or content.get("content") or "")
if isinstance(content, list):
parts = []
for item in content:
if isinstance(item, str):
parts.append(item)
elif isinstance(item, dict):
if item.get("type") == "text":
parts.append(str(item.get("text", "")))
elif "text" in item:
parts.append(str(item.get("text", "")))
return "".join(parts)
return str(content)
def _normalize_history(history: list[dict] | None) -> list[dict]:
"""Ensure history is list of {'role': str, 'content': str}."""
if not history:
return []
out = []
for m in history:
if isinstance(m, dict) and "role" in m:
out.append(
{
"role": str(m.get("role", "")),
"content": _content_to_text(m.get("content")),
}
)
return out
def _last_pairs(history: list[dict], pairs: int = 3) -> list[dict]:
"""Keep last N user+assistant pairs = 2*N messages."""
max_msgs = 2 * pairs
return history if len(history) <= max_msgs else history[-max_msgs:]
async def chat(
repo_url: str,
message: str,
show_sources: bool,
history_state: list[dict],
chatbot_history: list[dict],
):
history_state = _normalize_history(history_state)
chatbot_history = _normalize_history(chatbot_history)
if not repo_url:
return (
"Введите URL репозитория.",
"Источники:\n- не найдено\n",
[],
history_state,
chatbot_history,
)
if not message:
return (
"Введите вопрос.",
"Источники:\n- не найдено\n",
[],
history_state,
chatbot_history,
)
# Backend context: last 3 Q/A pairs (6 msgs) + new question
context_messages = _last_pairs(history_state, pairs=3)
request_messages = context_messages + [{"role": "user", "content": message}]
request = {
"meta": {"request_id": str(uuid4())},
"query": {"messages": request_messages},
"repo_url": repo_url,
}
config = _build_search_config()
try:
response = await assistant.query(request, config)
answer_text = (getattr(response, "answer", "") or "").strip()
except Exception as e:
return (
f"Ошибка: {type(e).__name__}: {e}",
"Источники:\n- не найдено\n",
[],
history_state,
chatbot_history,
)
final_answer = answer_text or "Ответ пуст."
sources = _collect_sources(response)
sources_md = _render_sources(sources, show_sources)
chatbot_history = chatbot_history + [
{"role": "user", "content": message},
{"role": "assistant", "content": final_answer},
]
new_history_state = request_messages + [
{"role": "assistant", "content": final_answer}
]
new_history_state = _last_pairs(new_history_state, pairs=3)
return sources_md, sources, new_history_state, chatbot_history
def update_sources(show_sources: bool, sources: list[dict]):
return _render_sources(sources or [], show_sources)
with gr.Blocks(title="RAGCode") as demo:
gr.Markdown("# RAGCode")
with gr.Tabs():
with gr.Tab("Индексировать репозиторий"):
repo_url_input = gr.Textbox(label="GitHub URL")
with gr.Row():
index_button = gr.Button("Индексировать", variant="primary")
delete_button = gr.Button("Удалить индекс", variant="stop")
index_status = gr.Markdown()
index_button.click(index_repo, inputs=repo_url_input, outputs=index_status)
delete_button.click(
delete_index, inputs=repo_url_input, outputs=index_status
)
with gr.Tab("Чат по коду"):
chat_repo_url = gr.Textbox(label="URL репозитория")
chatbot = gr.Chatbot(label="История", height=420)
sources = gr.Markdown("Источники:\n- не найдено\n")
message_input = gr.Textbox(label="Ваш вопрос")
show_sources = gr.Checkbox(
label="Показывать содержимое источников", value=False
)
sources_state = gr.State([])
history_state = gr.State([])
send_button = gr.Button("Спросить")
send_button.click(
chat,
inputs=[
chat_repo_url,
message_input,
show_sources,
history_state,
chatbot,
],
outputs=[sources, sources_state, history_state, chatbot],
)
show_sources.change(
update_sources,
inputs=[show_sources, sources_state],
outputs=[sources],
)
if __name__ == "__main__":
demo.launch(server_name="0.0.0.0", server_port=8501)