feat: LLM syntax check via /console/api/ai/check
- Server-side proxy to LLM API (FISSION_LLM_KEY, FISSION_LLM_URL env vars) - Button in create-modal and edit-modal: check syntax before saving - Result shown inline below code textarea (green=ok, red=errors)
This commit is contained in:
+110
@@ -65,6 +65,9 @@ type server struct {
|
||||
authUser string
|
||||
authPass string
|
||||
|
||||
llmURL string // FISSION_LLM_URL — базовый URL LLM API
|
||||
llmKey string // FISSION_LLM_KEY — Bearer ключ
|
||||
|
||||
tokenMu sync.Mutex
|
||||
cachedJWT string
|
||||
tokenExpAt time.Time
|
||||
@@ -133,6 +136,8 @@ func main() {
|
||||
authUser: authUser,
|
||||
authPass: authPass,
|
||||
testMode: os.Getenv("FISSION_TEST_MODE") == "true",
|
||||
llmURL: envDefault("FISSION_LLM_URL", "https://api.aillm.ru"),
|
||||
llmKey: os.Getenv("FISSION_LLM_KEY"),
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
@@ -204,6 +209,7 @@ func main() {
|
||||
mux.HandleFunc("/console/api/functions/", auth(s.handleFunctionsAction))
|
||||
mux.HandleFunc("/console/api/httptriggers", auth(s.handleList(httpTrigGVR)))
|
||||
mux.HandleFunc("/console/api/timetriggers", auth(s.handleList(timeTrigGVR)))
|
||||
mux.HandleFunc("/console/api/ai/check", auth(s.handleAICheck))
|
||||
|
||||
httpServer := &http.Server{
|
||||
Addr: ":" + port,
|
||||
@@ -1769,3 +1775,107 @@ func readZipFile(file *zip.File) ([]byte, error) {
|
||||
|
||||
return io.ReadAll(rc)
|
||||
}
|
||||
|
||||
// handleAICheck проксирует запрос проверки синтаксиса к LLM API.
|
||||
// POST /console/api/ai/check
|
||||
// Body: {"language":"python","code":"..."}
|
||||
// Response: {"ok":true,"result":"..."}
|
||||
func (s *server) handleAICheck(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, "LLM не настроен (FISSION_LLM_KEY не задан)")
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Language string `json:"language"`
|
||||
Code string `json:"code"`
|
||||
}
|
||||
if err := json.NewDecoder(io.LimitReader(r.Body, 64*1024)).Decode(&req); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "invalid JSON: "+err.Error())
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(req.Code) == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, "code is required")
|
||||
return
|
||||
}
|
||||
|
||||
prompt := fmt.Sprintf(
|
||||
"Проверь синтаксис следующего кода на языке %s для serverless-функции Fission. "+
|
||||
"Найди синтаксические ошибки, неправильные вызовы, проблемы с entrypoint. "+
|
||||
"Если ошибок нет — ответь кратко: \"✅ Синтаксис корректен.\" "+
|
||||
"Если есть — перечисли проблемы по пунктам, кратко, без лишних слов. "+
|
||||
"Код:\n\n```%s\n%s\n```",
|
||||
req.Language, req.Language, req.Code,
|
||||
)
|
||||
|
||||
llmBody, _ := json.Marshal(map[string]any{
|
||||
"model": "gpt-oss-120b",
|
||||
"messages": []map[string]string{
|
||||
{"role": "user", "content": prompt},
|
||||
},
|
||||
"max_tokens": 512,
|
||||
})
|
||||
|
||||
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(llmBody),
|
||||
)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "build llm request: "+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 request failed: "+err.Error())
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
raw, err := io.ReadAll(io.LimitReader(resp.Body, 64*1024))
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusBadGateway, "read llm response: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
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.Unmarshal(raw, &llmResp); err != nil {
|
||||
writeJSONError(w, http.StatusBadGateway, "parse llm response: "+err.Error())
|
||||
return
|
||||
}
|
||||
if llmResp.Error != nil {
|
||||
writeJSONError(w, http.StatusBadGateway, "llm error: "+llmResp.Error.Message)
|
||||
return
|
||||
}
|
||||
if len(llmResp.Choices) == 0 {
|
||||
writeJSONError(w, http.StatusBadGateway, "empty llm response")
|
||||
return
|
||||
}
|
||||
|
||||
result := strings.TrimSpace(llmResp.Choices[0].Message.Content)
|
||||
isOK := strings.Contains(result, "✅") || strings.HasPrefix(strings.ToLower(result), "синтаксис корректен")
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]any{
|
||||
"ok": isOK,
|
||||
"result": result,
|
||||
})
|
||||
}
|
||||
|
||||
+50
-1
@@ -390,6 +390,10 @@
|
||||
<textarea id="c-code">def main(ctx):
|
||||
return {"ok": True, "msg": "hello from fission console"}
|
||||
</textarea>
|
||||
<div style="margin-top:6px;">
|
||||
<button class="btn ghost" id="c-ai-btn" onclick="aiCheck('c-code','c-lang','c-ai-result')">✨ Проверить синтаксис</button>
|
||||
</div>
|
||||
<div id="c-ai-result" style="display:none;margin-top:8px;padding:10px 12px;border-radius:6px;font-size:13px;line-height:1.5;white-space:pre-wrap;font-family:monospace;"></div>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<button class="btn ghost" onclick="closeCreate()">Отмена</button>
|
||||
@@ -401,7 +405,8 @@
|
||||
<div id="edit-modal" class="modal">
|
||||
<div class="panel">
|
||||
<h3 id="e-title">Редактирование кода</h3>
|
||||
<div id="e-tf-warn" style="display:none;background:#553300;color:#ffa;padding:8px 12px;border-radius:6px;margin-bottom:10px;font-size:13px;">\u26a0\ufe0f Эта функция управляется Terraform. Изменения могут быть перезаписаны при следующем <code>terraform apply</code>.</div>
|
||||
<div id="e-tf-warn" style="display:none;background:#553300;color:#ffa;padding:8px 12px;border-radius:6px;margin-bottom:10px;font-size:13px;">⚠️ Эта функция управляется Terraform. Изменения могут быть перезаписаны при следующем <code>terraform apply</code>.</div>
|
||||
<input type="hidden" id="e-lang-hidden" value="">
|
||||
<div class="row">
|
||||
<div class="field">
|
||||
<label>Name</label>
|
||||
@@ -419,6 +424,10 @@
|
||||
<div>
|
||||
<label>Код</label>
|
||||
<textarea id="e-code"></textarea>
|
||||
<div style="margin-top:6px;">
|
||||
<button class="btn ghost" id="e-ai-btn" onclick="aiCheck('e-code','e-lang-hidden','e-ai-result')">✨ Проверить синтаксис</button>
|
||||
</div>
|
||||
<div id="e-ai-result" style="display:none;margin-top:8px;padding:10px 12px;border-radius:6px;font-size:13px;line-height:1.5;white-space:pre-wrap;font-family:monospace;"></div>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<button class="btn ghost" onclick="closeEdit()">Отмена</button>
|
||||
@@ -616,6 +625,18 @@
|
||||
document.getElementById('e-env').value = fn.environment || '';
|
||||
document.getElementById('e-entry').value = fn.entrypoint || '';
|
||||
document.getElementById('e-code').value = fn.code || '';
|
||||
// Определяем язык по имени environment для подсказки AI
|
||||
var envName = (fn.environment || '').toLowerCase();
|
||||
var lang = 'python';
|
||||
if (envName.includes('node')) lang = 'nodejs';
|
||||
else if (envName.includes('go')) lang = 'go';
|
||||
else if (envName.includes('ruby')) lang = 'ruby';
|
||||
else if (envName.includes('php')) lang = 'php';
|
||||
else if (envName.includes('perl')) lang = 'perl';
|
||||
document.getElementById('e-lang-hidden').value = lang;
|
||||
// сбросить предыдущий AI-результат
|
||||
var aiRes = document.getElementById('e-ai-result');
|
||||
if (aiRes) { aiRes.style.display = 'none'; aiRes.textContent = ''; }
|
||||
var warnEl = document.getElementById('e-tf-warn');
|
||||
if (warnEl) {
|
||||
var isTf = /^tf-/.test(name) || /go[-_]env/.test(fn.environment || '');
|
||||
@@ -792,6 +813,34 @@
|
||||
showLoginOverlay();
|
||||
}
|
||||
|
||||
async function aiCheck(codeId, langId, resultId) {
|
||||
var code = document.getElementById(codeId).value.trim();
|
||||
var lang = (document.getElementById(langId) ? document.getElementById(langId).value : '') || 'python';
|
||||
var resEl = document.getElementById(resultId);
|
||||
if (!code) { resEl.style.display = 'block'; resEl.style.background = 'var(--bg-alt)'; resEl.textContent = 'Введите код для проверки.'; return; }
|
||||
var btnId = codeId === 'c-code' ? 'c-ai-btn' : 'e-ai-btn';
|
||||
var btn = document.getElementById(btnId);
|
||||
btn.disabled = true;
|
||||
btn.textContent = '⏳ Проверяю...';
|
||||
resEl.style.display = 'block';
|
||||
resEl.style.background = 'var(--bg-alt)';
|
||||
resEl.style.color = 'var(--fg)';
|
||||
resEl.textContent = 'Отправляю код в LLM...';
|
||||
try {
|
||||
var data = await requestJSON(API_BASE + '/ai/check', 'POST', {language: lang, code: code});
|
||||
resEl.style.background = data.ok ? '#1a3a1a' : '#3a1a1a';
|
||||
resEl.style.color = data.ok ? '#8f8' : '#f88';
|
||||
resEl.textContent = data.result || '(пустой ответ)';
|
||||
} catch(e) {
|
||||
resEl.style.background = '#3a2a00';
|
||||
resEl.style.color = '#ffa';
|
||||
resEl.textContent = 'Ошибка: ' + e.message;
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.textContent = '✨ Проверить синтаксис';
|
||||
}
|
||||
}
|
||||
|
||||
function checkAuth() {
|
||||
if (!localStorage.getItem('auth_token')) {
|
||||
showLoginOverlay();
|
||||
|
||||
Reference in New Issue
Block a user