feat(ai-config): agregar botón Probar para verificar conectividad del provider

- Endpoint GET /ai-config/:id/test que llama /api/tags (Ollama) o /v1/models (OpenAI-compat/Anthropic)
- Botón "Probar" en cada fila de la tabla con modal de resultado JSON

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Lizandro Guarnizo
2026-07-06 09:33:29 -05:00
co-authored by Claude Sonnet 4.6
parent 6062f31c70
commit 569d8b0f28
4 changed files with 109 additions and 1 deletions
+4
View File
@@ -57,6 +57,10 @@ func DeleteAiConfig(id uint) error {
return app.Http.Database.DB.Delete(&AiConfig{}, id).Error
}
func GetAiConfigByID(id uint, out *AiConfig) error {
return app.Http.Database.DB.First(out, id).Error
}
// GetActiveAiConfig retorna la primera configuración activa del provider indicado.
// Si provider está vacío, retorna cualquier config activa.
func GetActiveAiConfig(provider string) (*AiConfig, error) {
+26 -1
View File
@@ -101,6 +101,8 @@
</td>
<td class="py-2 px-3 text-right">
<div class="flex justify-end gap-2">
<button @click="testConfig(item.ID)"
class="text-xs text-green-600 hover:text-green-800 font-medium transition">Probar</button>
<button @click="openEdit(item)"
class="text-xs text-blue-600 hover:text-blue-800 font-medium transition">Editar</button>
<button @click="confirmDelete(item.ID)"
@@ -235,6 +237,22 @@
</div>
</div>
<!-- Modal resultado test -->
<div x-show="testResult" x-cloak class="fixed inset-0 bg-black/50 flex items-center justify-center z-40 p-4">
<div @click.outside="testResult = null" class="bg-white rounded-xl shadow-xl w-full max-w-md p-6">
<div class="flex items-center gap-3 mb-3">
<span x-show="testResult && testResult.ok" class="text-2xl"></span>
<span x-show="testResult && !testResult.ok" class="text-2xl"></span>
<h2 class="text-lg font-bold" x-text="testResult && testResult.ok ? 'Conexión exitosa' : 'Error de conexión'"></h2>
</div>
<pre x-show="testResult" class="text-xs bg-gray-50 border border-gray-200 rounded-lg p-3 overflow-x-auto max-h-60"
x-text="JSON.stringify(testResult, null, 2)"></pre>
<div class="flex justify-end mt-4">
<button @click="testResult = null" class="px-4 py-2 text-sm border border-gray-300 rounded-lg hover:bg-gray-50">Cerrar</button>
</div>
</div>
</div>
<!-- Modal confirmar eliminación -->
<div x-show="deleteId" x-cloak class="fixed inset-0 bg-black/50 flex items-center justify-center z-40 p-4">
<div class="bg-white rounded-xl shadow-xl w-full max-w-sm p-6 text-center">
@@ -260,7 +278,7 @@ function aiConfigApp() {
loading: false, saving: false,
items: [], total: 0, totalPages: 1, page: 1,
search: '',
showModal: false, editItem: null, deleteId: null,
showModal: false, editItem: null, deleteId: null, testResult: null,
errorMsg: '', successMsg: '', formError: '',
form: { nombre: '', provider: '', api_key: '', base_url: '', model_name: '', is_active: true, notes: '', modulos: [] },
@@ -341,6 +359,13 @@ function aiConfigApp() {
await this.load()
},
async testConfig(id) {
this.loading = true
const res = await fetch(`/app/ai-config/${id}/test`)
this.loading = false
this.testResult = await res.json()
},
showSuccess(msg) {
this.successMsg = msg
setTimeout(() => { this.successMsg = '' }, 3000)
+78
View File
@@ -1,9 +1,12 @@
package controllers
import (
"encoding/json"
"math"
"net/http"
"strconv"
"strings"
"time"
"github.com/gofiber/fiber/v2"
"github.com/sujit-baniya/fiber-boilerplate/pkg/models"
@@ -164,6 +167,81 @@ func GetAiConfigSelect(c *fiber.Ctx) error {
return c.JSON(fiber.Map{"registros": items})
}
// TestAiConfigHandler verifica conectividad con el provider de la config.
func TestAiConfigHandler(c *fiber.Ctx) error {
id, err := strconv.ParseUint(c.Params("id"), 10, 64)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "id inválido"})
}
var item models.AiConfig
if err := models.GetAiConfigByID(uint(id), &item); err != nil {
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"error": "config no encontrada"})
}
client := &http.Client{Timeout: 10 * time.Second}
var testURL string
var req *http.Request
switch item.Provider {
case "ollama":
base := strings.TrimSuffix(strings.TrimRight(item.BaseURL, "/"), "/v1")
testURL = base + "/api/tags"
req, _ = http.NewRequest("GET", testURL, nil)
if item.ApiKey != "" && item.ApiKey != "ollama" {
req.SetBasicAuth("ollama", item.ApiKey)
}
case "anthropic":
// Anthropic no tiene /models; usamos /v1/models igual (devuelve 200 con lista)
base := item.BaseURL
if base == "" {
base = "https://api.anthropic.com/v1"
}
testURL = base + "/models"
req, _ = http.NewRequest("GET", testURL, nil)
req.Header.Set("x-api-key", item.ApiKey)
req.Header.Set("anthropic-version", "2023-06-01")
default:
base := item.BaseURL
if base == "" {
switch item.Provider {
case "openai":
base = "https://api.openai.com/v1"
case "qwen":
base = "https://dashscope.aliyuncs.com/compatible-mode/v1"
case "groq":
base = "https://api.groq.com/openai/v1"
default:
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "BaseURL requerida para este provider"})
}
}
testURL = base + "/models"
req, _ = http.NewRequest("GET", testURL, nil)
req.Header.Set("Authorization", "Bearer "+item.ApiKey)
}
resp, err := client.Do(req)
if err != nil {
return c.JSON(fiber.Map{"ok": false, "error": err.Error()})
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
var body map[string]interface{}
json.NewDecoder(resp.Body).Decode(&body)
return c.JSON(fiber.Map{"ok": false, "status": resp.StatusCode, "error": body})
}
// Para Ollama devolvemos la lista de modelos disponibles
if item.Provider == "ollama" {
var body map[string]interface{}
json.NewDecoder(resp.Body).Decode(&body)
return c.JSON(fiber.Map{"ok": true, "status": resp.StatusCode, "data": body})
}
return c.JSON(fiber.Map{"ok": true, "status": resp.StatusCode})
}
// DeleteAiConfigHandler elimina una configuración de IA.
func DeleteAiConfigHandler(c *fiber.Ctx) error {
id, err := strconv.ParseUint(c.Params("id"), 10, 64)
+1
View File
@@ -290,6 +290,7 @@ func UserRoutes(app fiber.Router) {
protected.Post("/ai-config", controllers.CreateAiConfigHandler)
protected.Put("/ai-config/:id", controllers.UpdateAiConfigHandler)
protected.Delete("/ai-config/:id", controllers.DeleteAiConfigHandler)
protected.Get("/ai-config/:id/test", controllers.TestAiConfigHandler)
// ─── OSS API (Alibaba Cloud + S3/MinIO) ────────────────────────────────────
protected.Get("/oss-api", middlewares.MenuMiddleware, controllers.OssApiIndex)