feat: explain-archive LLM endpoint + UI button v1.3.40

This commit is contained in:
“Naeel”
2026-05-03 21:33:18 +04:00
parent 21c11f84d0
commit db3815d03d
5 changed files with 233 additions and 3 deletions
+1 -1
View File
@@ -52,7 +52,7 @@ spec:
serviceAccountName: fission-console
containers:
- name: console
image: naeel/fission-console:v1.3.39
image: naeel/fission-console:v1.3.40
imagePullPolicy: Always
ports:
- containerPort: 8090
+180
View File
@@ -0,0 +1,180 @@
package api
import (
"archive/zip"
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
"context"
)
const (
// maxExplainCodeBytes — суммарный лимит кода из архива для отправки в LLM.
// LLM бесплатный и слабый — не перегружаем контекст.
maxExplainCodeBytes = 20 * 1024
)
// handleExplainArchive — POST /console/api/ai/explain-archive
// Принимает zip-архив, извлекает код, отправляет в LLM с вопросом "что делает?".
func (s *Server) handleExplainArchive(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
writeJSONError(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
if s.llmKey == "" {
writeJSONError(w, http.StatusServiceUnavailable, "AI-ассистент не настроен (FISSION_LLM_KEY не задан)")
return
}
r.Body = http.MaxBytesReader(w, r.Body, 10*1024*1024)
if err := r.ParseMultipartForm(maxArchiveBytes); err != nil {
writeJSONError(w, http.StatusBadRequest, "ошибка разбора multipart: "+err.Error())
return
}
f, _, err := r.FormFile("archive")
if err != nil {
writeJSONError(w, http.StatusBadRequest, "поле 'archive' обязательно")
return
}
defer f.Close()
var buf bytes.Buffer
if _, err := buf.ReadFrom(f); err != nil {
writeJSONError(w, http.StatusBadRequest, "ошибка чтения архива: "+err.Error())
return
}
if buf.Len() > maxArchiveBytes {
writeJSONError(w, http.StatusRequestEntityTooLarge,
fmt.Sprintf("архив слишком большой: максимум %d KB", maxArchiveBytes/1024))
return
}
zr, err := zip.NewReader(bytes.NewReader(buf.Bytes()), int64(buf.Len()))
if err != nil {
writeJSONError(w, http.StatusBadRequest, "не удалось открыть zip: "+err.Error())
return
}
// Поддерживаемые расширения
supported := map[string]bool{".py": true, ".js": true, ".rb": true, ".php": true, ".go": true}
type fileChunk struct {
name string
code string
}
var chunks []fileChunk
var totalBytes int
for _, zf := range zr.File {
if zf.FileInfo().IsDir() {
continue
}
ext := strings.ToLower(archiveFileExt(zf.Name))
if !supported[ext] {
continue
}
if totalBytes >= maxExplainCodeBytes {
break
}
rc, err := zf.Open()
if err != nil {
continue
}
limit := maxExplainCodeBytes - totalBytes
content, err := io.ReadAll(io.LimitReader(rc, int64(limit)))
rc.Close()
if err != nil || len(content) == 0 {
continue
}
chunks = append(chunks, fileChunk{name: zf.Name, code: string(content)})
totalBytes += len(content)
}
if len(chunks) == 0 {
writeJSONError(w, http.StatusBadRequest, "нет поддерживаемых файлов (.py, .js, .rb, .php, .go)")
return
}
// Собираем текст для LLM
var sb strings.Builder
sb.WriteString("Ниже приведены файлы из архива serverless-функции. Опиши КРАТКО (2-5 предложений) что делает эта функция.\n\n")
for _, c := range chunks {
sb.WriteString(fmt.Sprintf("=== %s ===\n%s\n\n", c.name, c.code))
}
prompt := sb.String()
llmReqBody := llmChatRequest{
Model: "gpt-oss-120b",
Messages: []llmMessage{
{Role: "system", Content: "Ты ассистент для анализа serverless-функций. Отвечай кратко, на русском языке."},
{Role: "user", Content: prompt},
},
MaxTokens: 512,
}
body, _ := json.Marshal(llmReqBody)
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
llmReq, err := http.NewRequestWithContext(ctx, http.MethodPost,
strings.TrimRight(s.llmURL, "/")+"/chat/completions",
bytes.NewReader(body),
)
if err != nil {
writeJSONError(w, http.StatusInternalServerError, err.Error())
return
}
llmReq.Header.Set("Content-Type", "application/json")
llmReq.Header.Set("Authorization", "Bearer "+s.llmKey)
resp, err := s.http.Do(llmReq)
if err != nil {
writeJSONError(w, http.StatusBadGateway, "LLM недоступен: "+err.Error())
return
}
defer resp.Body.Close()
var llmResp struct {
Choices []struct {
Message struct {
Content string `json:"content"`
} `json:"message"`
} `json:"choices"`
Error *struct {
Message string `json:"message"`
} `json:"error"`
}
if err := json.NewDecoder(io.LimitReader(resp.Body, 64*1024)).Decode(&llmResp); err != nil {
writeJSONError(w, http.StatusBadGateway, "parse error: "+err.Error())
return
}
if llmResp.Error != nil {
writeJSONError(w, http.StatusBadGateway, llmResp.Error.Message)
return
}
if len(llmResp.Choices) == 0 {
writeJSONError(w, http.StatusBadGateway, "пустой ответ от LLM")
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]any{
"answer": strings.TrimSpace(llmResp.Choices[0].Message.Content),
})
}
// archiveFileExt возвращает расширение файла из пути внутри zip (включая точку).
func archiveFileExt(name string) string {
for i := len(name) - 1; i >= 0 && name[i] != '/'; i-- {
if name[i] == '.' {
return name[i:]
}
}
return ""
}
+1
View File
@@ -157,6 +157,7 @@ func (s *Server) RegisterRoutes(mux *http.ServeMux) {
mux.HandleFunc("/console/api/ns/debug", auth(s.handleNSDebug))
mux.HandleFunc("/console/api/ai/check", auth(s.handleAICheck))
mux.HandleFunc("/console/api/ai/lint-archive", auth(s.handleLintArchive))
mux.HandleFunc("/console/api/ai/explain-archive", auth(s.handleExplainArchive))
// --- ai/ask feature (удалить строку чтобы выкосить роут) ---
mux.HandleFunc("/console/api/ai/ask", auth(s.handleAIAsk))
// --- end ai/ask feature ---
+4 -2
View File
@@ -100,7 +100,7 @@
<div class="nubes">NUBES</div>
<div class="product">FISSION CONSOLE</div>
</div>
<div style="font-size:0.65rem; color:var(--text-secondary); margin-left:10px; align-self:center; opacity:0.7;">v1.3.39</div>
<div style="font-size:0.65rem; color:var(--text-secondary); margin-left:10px; align-self:center; opacity:0.7;">v1.3.40</div>
</div>
<div class="row" style="margin:0;">
<button class="btn ghost" onclick="reloadAll()">Refresh</button>
@@ -229,6 +229,7 @@
<input type="file" id="c-archive-file" accept=".zip" style="display:block; margin-bottom:8px; color:var(--text-primary);">
<div style="display:flex; gap:6px; flex-wrap:wrap;">
<button id="c-lint-btn" class="btn ghost" onclick="lintArchiveFile('c')">&#x1F50D; Проверка архива линтером</button>
<button id="c-explain-archive-btn" class="btn ghost" onclick="explainArchiveFile('c')">&#x1F4D6; LLM: Что делает?</button>
</div>
</div>
<div id="c-gen-prompt" style="display:none; margin-top:8px; display:none; gap:6px; align-items:center;">
@@ -307,6 +308,7 @@
<input type="file" id="e-archive-file" accept=".zip" style="display:block; margin-bottom:8px; color:var(--text-primary);">
<div style="display:flex; gap:6px; flex-wrap:wrap;">
<button id="e-lint-btn" class="btn ghost" onclick="lintArchiveFile('e')">&#x1F50D; Проверка архива линтером</button>
<button id="e-explain-archive-btn" class="btn ghost" onclick="explainArchiveFile('e')">&#x1F4D6; LLM: Что делает?</button>
</div>
</div>
<div id="e-ai-result"
@@ -398,7 +400,7 @@
</div>
<div class="actions" style="justify-content:space-between; align-items:center;">
<span style="font-size:0.75rem; color:var(--text-secondary);">v1.3.39</span>
<span style="font-size:0.75rem; color:var(--text-secondary);">v1.3.40</span>
<button class="btn ghost" onclick="closeHelp()">Закрыть</button>
</div>
</div>
+47
View File
@@ -75,6 +75,53 @@ function lintArchiveFile(prefix) {
});
}
// explainArchiveFile — отправляет zip-архив на /console/api/ai/explain-archive,
// показывает ответ LLM в блоке {prefix}-ai-result.
function explainArchiveFile(prefix) {
var input = document.getElementById(prefix + '-archive-file');
var resEl = document.getElementById(prefix + '-ai-result');
var btn = document.getElementById(prefix + '-explain-archive-btn');
function showRes(text, bg, color) {
if (resEl) {
resEl.style.display = 'block';
resEl.style.background = bg;
resEl.style.color = color;
resEl.textContent = text;
}
}
if (!input || !input.files || !input.files[0]) {
showRes('Выберите .zip файл', '#3a1a1a', '#f88');
return;
}
var file = input.files[0];
if (file.size > 100 * 1024) {
showRes('Архив слишком большой: максимум 100 KB', '#3a1a1a', '#f88');
return;
}
if (btn) { btn.disabled = true; btn.textContent = '⏳ Спрашиваю LLM…'; }
showRes('Запрашиваю у LLM…', 'var(--bg-alt)', 'var(--fg)');
var fd = new FormData();
fd.append('archive', file);
fetch(API_BASE + '/ai/explain-archive', {
method: 'POST',
headers: authHeaders(),
body: fd
})
.then(function(r) { return r.json(); })
.then(function(data) {
if (btn) { btn.disabled = false; btn.textContent = '📖 LLM: Что делает?'; }
if (data.error) {
showRes('Ошибка: ' + data.error, '#3a2a00', '#ffa');
return;
}
showRes(data.answer || '(пустой ответ)', '#1a2a3a', '#8cf');
})
.catch(function(e) {
if (btn) { btn.disabled = false; btn.textContent = '📖 LLM: Что делает?'; }
showRes('Ошибка сети: ' + e.message, '#3a2a00', '#ffa');
});
}
function parseMethods(v) {
const items = String(v || '').split(',').map(s => s.trim().toUpperCase()).filter(Boolean);
return items.length ? Array.from(new Set(items)) : ['GET'];