feat(console): add AI assistant panel /api/ai/ask v0.7.9
This commit is contained in:
+105
-1
@@ -68,7 +68,10 @@ type server struct {
|
||||
authUser string
|
||||
authPass string
|
||||
|
||||
|
||||
// --- ai/ask feature (удалить блок целиком чтобы выкосить) ---
|
||||
llmURL string // FISSION_LLM_URL
|
||||
llmKey string // FISSION_LLM_KEY
|
||||
// --- end ai/ask feature ---
|
||||
|
||||
tokenMu sync.Mutex
|
||||
cachedJWT string
|
||||
@@ -138,6 +141,10 @@ func main() {
|
||||
authUser: authUser,
|
||||
authPass: authPass,
|
||||
testMode: os.Getenv("FISSION_TEST_MODE") == "true",
|
||||
// --- ai/ask feature ---
|
||||
llmURL: envDefault("FISSION_LLM_URL", "https://api.aillm.ru"),
|
||||
llmKey: os.Getenv("FISSION_LLM_KEY"),
|
||||
// --- end ai/ask feature ---
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
@@ -210,6 +217,9 @@ func main() {
|
||||
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))
|
||||
// --- ai/ask feature (удалить строку чтобы выкосить роут) ---
|
||||
mux.HandleFunc("/console/api/ai/ask", auth(s.handleAIAsk))
|
||||
// --- end ai/ask feature ---
|
||||
|
||||
httpServer := &http.Server{
|
||||
Addr: ":" + port,
|
||||
@@ -1886,3 +1896,97 @@ func (s *server) handleAICheck(w http.ResponseWriter, r *http.Request) {
|
||||
"result": result,
|
||||
})
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// ai/ask feature — удалить весь блок до "end ai/ask feature" чтобы выкосить
|
||||
// =============================================================================
|
||||
|
||||
// handleAIAsk отвечает на произвольный вопрос пользователя через LLM.
|
||||
// POST /console/api/ai/ask
|
||||
// Body: {"question":"..."}
|
||||
// Response: {"answer":"..."}
|
||||
func (s *server) handleAIAsk(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
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Question string `json:"question"`
|
||||
}
|
||||
if err := json.NewDecoder(io.LimitReader(r.Body, 4*1024)).Decode(&req); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "invalid JSON: "+err.Error())
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(req.Question) == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, "question is required")
|
||||
return
|
||||
}
|
||||
|
||||
body, _ := json.Marshal(map[string]any{
|
||||
"model": "gpt-oss-120b",
|
||||
"messages": []map[string]string{
|
||||
{
|
||||
"role": "system",
|
||||
"content": "Ты помощник по Fission — serverless платформе на Kubernetes. Отвечай кратко и по делу. Если вопрос не про Fission или программирование — вежливо скажи что не знаешь.",
|
||||
},
|
||||
{"role": "user", "content": req.Question},
|
||||
},
|
||||
"max_tokens": 1024,
|
||||
})
|
||||
|
||||
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, "empty response from LLM")
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]any{
|
||||
"answer": strings.TrimSpace(llmResp.Choices[0].Message.Content),
|
||||
})
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// end ai/ask feature
|
||||
// =============================================================================
|
||||
|
||||
@@ -852,5 +852,75 @@
|
||||
|
||||
checkAuth();
|
||||
</script>
|
||||
|
||||
<!-- ================================================================
|
||||
ai/ask feature — удалить весь блок до "end ai/ask feature"
|
||||
================================================================ -->
|
||||
<div id="assistant-panel" style="
|
||||
position:fixed; bottom:0; right:24px;
|
||||
width:360px; background:#1e1e2e; border:1px solid #3a3a5c;
|
||||
border-bottom:none; border-radius:8px 8px 0 0;
|
||||
font-family:inherit; z-index:900; box-shadow:0 -2px 12px rgba(0,0,0,.4);
|
||||
">
|
||||
<div id="assistant-header" onclick="toggleAssistant()" style="
|
||||
display:flex; align-items:center; justify-content:space-between;
|
||||
padding:8px 12px; cursor:pointer; background:#2a2a42; border-radius:8px 8px 0 0;
|
||||
user-select:none;
|
||||
">
|
||||
<span style="font-weight:600; font-size:.85rem;">💬 Ассистент</span>
|
||||
<span id="assistant-toggle-icon" style="font-size:.75rem; opacity:.7;">▲</span>
|
||||
</div>
|
||||
<div id="assistant-body" style="padding:10px; display:flex; flex-direction:column; gap:8px;">
|
||||
<div id="assistant-messages" style="
|
||||
min-height:80px; max-height:260px; overflow-y:auto;
|
||||
font-size:.82rem; line-height:1.5; color:#cdd6f4;
|
||||
background:#13131f; border-radius:4px; padding:8px;
|
||||
white-space:pre-wrap; word-break:break-word;
|
||||
">Привет! Задай любой вопрос про Fission или программирование.</div>
|
||||
<div style="display:flex; gap:6px;">
|
||||
<input id="assistant-input" type="text" placeholder="Введи вопрос..."
|
||||
style="flex:1; background:#2a2a42; border:1px solid #3a3a5c; border-radius:4px;
|
||||
color:#cdd6f4; padding:6px 8px; font-size:.82rem; outline:none;"
|
||||
onkeydown="if(event.key==='Enter')askAssistant()" />
|
||||
<button onclick="askAssistant()" style="
|
||||
background:#7c3aed; color:#fff; border:none; border-radius:4px;
|
||||
padding:6px 12px; cursor:pointer; font-size:.82rem; white-space:nowrap;
|
||||
">→</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
// ai/ask feature
|
||||
var _assistantOpen = true;
|
||||
function toggleAssistant() {
|
||||
_assistantOpen = !_assistantOpen;
|
||||
document.getElementById('assistant-body').style.display = _assistantOpen ? 'flex' : 'none';
|
||||
document.getElementById('assistant-toggle-icon').textContent = _assistantOpen ? '▲' : '▼';
|
||||
}
|
||||
async function askAssistant() {
|
||||
var inp = document.getElementById('assistant-input');
|
||||
var msgs = document.getElementById('assistant-messages');
|
||||
var q = inp.value.trim();
|
||||
if (!q) return;
|
||||
inp.value = '';
|
||||
msgs.textContent += '\n\n👤 ' + q + '\n⏳ ...';
|
||||
msgs.scrollTop = msgs.scrollHeight;
|
||||
try {
|
||||
var r = await fetch('/console/api/ai/ask', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...authHeaders() },
|
||||
body: JSON.stringify({ question: q })
|
||||
});
|
||||
var d = await r.json();
|
||||
msgs.textContent = msgs.textContent.replace('⏳ ...', '🤖 ' + (d.answer || d.error || 'Нет ответа'));
|
||||
} catch(e) {
|
||||
msgs.textContent = msgs.textContent.replace('⏳ ...', '❌ Ошибка: ' + e.message);
|
||||
}
|
||||
msgs.scrollTop = msgs.scrollHeight;
|
||||
}
|
||||
// end ai/ask feature
|
||||
</script>
|
||||
<!-- end ai/ask feature -->
|
||||
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Reference in New Issue
Block a user