feat(ai): integrar Ollama en AiConfig para ia_controller, query_runner y landing

- Agrega provider 'ollama' al panel de AiConfig con badge azul y hint de URL
- ia_controller: reemplaza webhook n8n hardcodeado por llamada directa a Ollama vía AiConfig (módulo 'ia')
- query_runner: agrega soporte explícito de ollama (model fallback gemma3:1b, Basic Auth para URL pública)
- HTML: agrega módulo 'IA / vCard' en el selector de módulos

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Lizandro Guarnizo
2026-07-06 09:33:22 -05:00
co-authored by Claude Sonnet 4.6
parent fa269cabf1
commit 6062f31c70
3 changed files with 90 additions and 60 deletions
+15 -5
View File
@@ -73,9 +73,10 @@
<span class="px-2 py-0.5 rounded-full text-xs font-semibold" <span class="px-2 py-0.5 rounded-full text-xs font-semibold"
:class="{ :class="{
'bg-blue-100 text-blue-700': m.trim() === 'landing', 'bg-blue-100 text-blue-700': m.trim() === 'landing',
'bg-[#e9f0cf] text-[#5a7a1e]': m.trim() === 'query_runner' 'bg-[#e9f0cf] text-[#5a7a1e]': m.trim() === 'query_runner',
'bg-purple-100 text-purple-700': m.trim() === 'ia'
}" }"
x-text="m.trim() === 'landing' ? 'Landing' : m.trim() === 'query_runner' ? 'Query Runner' : m.trim()"> x-text="m.trim() === 'landing' ? 'Landing' : m.trim() === 'query_runner' ? 'Query Runner' : m.trim() === 'ia' ? 'IA / vCard' : m.trim()">
</span> </span>
</template> </template>
</div> </div>
@@ -87,7 +88,8 @@
'bg-purple-100 text-purple-700': item.provider === 'qwen', 'bg-purple-100 text-purple-700': item.provider === 'qwen',
'bg-green-100 text-green-700': item.provider === 'openai', 'bg-green-100 text-green-700': item.provider === 'openai',
'bg-orange-100 text-orange-700': item.provider === 'anthropic', 'bg-orange-100 text-orange-700': item.provider === 'anthropic',
'bg-gray-100 text-gray-700': !['qwen','openai','anthropic'].includes(item.provider) 'bg-blue-100 text-blue-700': item.provider === 'ollama',
'bg-gray-100 text-gray-700': !['qwen','openai','anthropic','ollama'].includes(item.provider)
}" x-text="item.provider"></span> }" x-text="item.provider"></span>
</td> </td>
<td class="py-2 px-3 text-gray-500 font-mono text-xs" x-text="item.model_name || '—'"></td> <td class="py-2 px-3 text-gray-500 font-mono text-xs" x-text="item.model_name || '—'"></td>
@@ -143,6 +145,7 @@
<option value="openai">OpenAI</option> <option value="openai">OpenAI</option>
<option value="anthropic">Anthropic</option> <option value="anthropic">Anthropic</option>
<option value="groq">Groq</option> <option value="groq">Groq</option>
<option value="ollama">Ollama (local)</option>
<option value="otro">Otro</option> <option value="otro">Otro</option>
</select> </select>
</div> </div>
@@ -164,10 +167,16 @@
</div> </div>
<div> <div>
<label class="block text-xs font-medium text-gray-600 mb-1">Base URL <span class="text-gray-400">(opcional — dejar vacío para usar el default del provider)</span></label> <label class="block text-xs font-medium text-gray-600 mb-1">Base URL
<span x-show="form.provider !== 'ollama'" class="text-gray-400">(opcional — dejar vacío para usar el default del provider)</span>
<span x-show="form.provider === 'ollama'" class="text-blue-500">* requerido — incluir /v1 al final</span>
</label>
<input x-model="form.base_url" type="url" <input x-model="form.base_url" type="url"
placeholder="https://dashscope.aliyuncs.com/compatible-mode/v1" :placeholder="form.provider === 'ollama' ? 'http://10.0.1.15:11434/v1' : 'https://dashscope.aliyuncs.com/compatible-mode/v1'"
class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-[#8eb02f]" /> class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-[#8eb02f]" />
<p x-show="form.provider === 'ollama'" x-cloak class="text-[10px] text-blue-500 mt-1">
Interna (red Coolify): <code>http://10.0.1.15:11434/v1</code> — Pública: <code>https://ollama.u-s.app/v1</code>
</p>
</div> </div>
<div> <div>
@@ -258,6 +267,7 @@ function aiConfigApp() {
moduleOptions: [ moduleOptions: [
{ value: 'landing', label: 'Landing Generator' }, { value: 'landing', label: 'Landing Generator' },
{ value: 'query_runner', label: 'Query Runner SQL' }, { value: 'query_runner', label: 'Query Runner SQL' },
{ value: 'ia', label: 'IA / vCard' },
], ],
async init() { await this.load() }, async init() { await this.load() },
+27 -16
View File
@@ -6,8 +6,11 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"net/http" "net/http"
"strings"
"time"
"github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2"
"github.com/sujit-baniya/fiber-boilerplate/pkg/models"
) )
type DataIa struct { type DataIa struct {
@@ -26,54 +29,63 @@ func GeneraTextoStream(c *fiber.Ctx) error {
if err := c.BodyParser(&data); err != nil { if err := c.BodyParser(&data); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "Datos inválidos"}) return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "Datos inválidos"})
} }
// Forzar stream = true
data.Stream = true data.Stream = true
jsonData, err := json.Marshal(data) config, err := models.GetAiConfigForService("ia")
if err != nil { if err != nil {
return err return c.Status(fiber.StatusServiceUnavailable).JSON(fiber.Map{
"error": "No hay configuración de IA activa. Configura una en /app/ai-config",
})
} }
req, err := http.NewRequest("POST", "https://n8n.u-s.app/webhook/c945b974-f534-419b-a6da-4ebd832f8cd9", bytes.NewBuffer(jsonData)) if data.Model == "" {
data.Model = config.ModelName
}
if data.Model == "" {
data.Model = "gemma3:1b"
}
// Usar endpoint nativo de Ollama (/api/generate), no OpenAI compat (/v1/...)
baseURL := strings.TrimSuffix(strings.TrimRight(config.BaseURL, "/"), "/v1")
endpoint := baseURL + "/api/generate"
jsonData, _ := json.Marshal(data)
req, err := http.NewRequest("POST", endpoint, bytes.NewBuffer(jsonData))
if err != nil { if err != nil {
return err return err
} }
req.Header.Set("Content-Type", "application/json") req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer sk-43804e00f5294200ad1e599550fbee4f") // Sin auth para red interna; api_key como token para URL pública
if config.ApiKey != "" && config.ApiKey != "ollama" {
req.SetBasicAuth("ollama", config.ApiKey)
}
client := &http.Client{} client := &http.Client{Timeout: 120 * time.Second}
resp, err := client.Do(req) resp, err := client.Do(req)
if err != nil { if err != nil {
return err return c.Status(fiber.StatusBadGateway).JSON(fiber.Map{"error": err.Error()})
} }
// Configurar headers para streaming
c.Set("Content-Type", "text/plain; charset=utf-8") c.Set("Content-Type", "text/plain; charset=utf-8")
c.Set("Cache-Control", "no-cache") c.Set("Cache-Control", "no-cache")
c.Set("Connection", "keep-alive") c.Set("Connection", "keep-alive")
c.Context().SetBodyStreamWriter(func(w *bufio.Writer) { c.Context().SetBodyStreamWriter(func(w *bufio.Writer) {
defer resp.Body.Close() defer resp.Body.Close()
scanner := bufio.NewScanner(resp.Body) scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() { for scanner.Scan() {
line := scanner.Bytes() line := scanner.Bytes()
if len(line) == 0 { if len(line) == 0 {
continue continue
} }
var msg respuestaOllama var msg respuestaOllama
if err := json.Unmarshal(line, &msg); err != nil { if err := json.Unmarshal(line, &msg); err != nil {
continue continue
} }
if msg.Response != "" { if msg.Response != "" {
fmt.Fprint(w, msg.Response) fmt.Fprint(w, msg.Response)
w.Flush() // <-- envía inmediatamente w.Flush()
} }
if msg.Done { if msg.Done {
break break
} }
@@ -82,4 +94,3 @@ func GeneraTextoStream(c *fiber.Ctx) error {
return nil return nil
} }
+11 -2
View File
@@ -552,6 +552,7 @@ SQL optimizado:`, sql)
case "anthropic": case "anthropic":
baseURL = "https://api.anthropic.com/v1" baseURL = "https://api.anthropic.com/v1"
default: default:
log.Printf("[AI_SQL] Provider '%s' requiere BaseURL configurada", config.Provider)
return nil return nil
} }
} }
@@ -565,6 +566,8 @@ SQL optimizado:`, sql)
modelName = "qwen2.5-72b-instruct" modelName = "qwen2.5-72b-instruct"
case "anthropic": case "anthropic":
modelName = "claude-3-haiku-20240307" modelName = "claude-3-haiku-20240307"
case "ollama":
modelName = "gemma3:1b"
default: default:
modelName = "gpt-4o-mini" modelName = "gpt-4o-mini"
} }
@@ -595,10 +598,16 @@ SQL optimizado:`, sql)
req, _ := http.NewRequest("POST", url, bytes.NewReader(jsonBody)) req, _ := http.NewRequest("POST", url, bytes.NewReader(jsonBody))
req.Header.Set("Content-Type", "application/json") req.Header.Set("Content-Type", "application/json")
if config.Provider == "anthropic" { switch config.Provider {
case "anthropic":
req.Header.Set(authHeader, config.ApiKey) req.Header.Set(authHeader, config.ApiKey)
req.Header.Set("anthropic-version", "2023-06-01") req.Header.Set("anthropic-version", "2023-06-01")
} else { case "ollama":
// Sin auth para red interna; para URL pública el api_key es "usuario:token"
if config.ApiKey != "" && config.ApiKey != "ollama" {
req.SetBasicAuth("ollama", config.ApiKey)
}
default:
req.Header.Set(authHeader, "Bearer "+config.ApiKey) req.Header.Set(authHeader, "Bearer "+config.ApiKey)
} }