477 lines
13 KiB
Go
477 lines
13 KiB
Go
package propuesta
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"os"
|
|
"regexp"
|
|
"strings"
|
|
"time"
|
|
|
|
"cotizador/internal/config"
|
|
)
|
|
|
|
const (
|
|
DefaultMinimaxBaseURL = "https://api.minimax.io/anthropic"
|
|
DefaultMinimaxModel = "MiniMax-M3"
|
|
anthropicVersion = "2023-06-01"
|
|
maxTransitoriosDef = 3
|
|
)
|
|
|
|
// UsoTokens acumula el consumo de tokens reportado por el endpoint de mensajes.
|
|
type UsoTokens struct {
|
|
Entrada int `json:"entrada"`
|
|
Salida int `json:"salida"`
|
|
CacheLectura int `json:"cacheLectura"`
|
|
CacheEscritura int `json:"cacheEscritura"`
|
|
}
|
|
|
|
// BloqueSystem representa un bloque del prompt de sistema con cache opcional.
|
|
type BloqueSystem struct {
|
|
Texto string
|
|
Cachear bool
|
|
}
|
|
|
|
// Herramienta define la herramienta de salida estructurada para tool-calling.
|
|
type Herramienta struct {
|
|
Nombre string
|
|
Descripcion string
|
|
InputSchema map[string]any
|
|
Validar func(datos map[string]any) []string
|
|
}
|
|
|
|
// OpcionesLlamada configura una invocacion con tool-calling y bucle de validacion.
|
|
type OpcionesLlamada struct {
|
|
System []BloqueSystem
|
|
MensajeUsuario string
|
|
Herramienta Herramienta
|
|
MaxIntentos int
|
|
MaxTokens int
|
|
}
|
|
|
|
// ResultadoLlamada contiene la salida validada, el uso acumulado y los intentos.
|
|
type ResultadoLlamada struct {
|
|
Datos map[string]any
|
|
Uso UsoTokens
|
|
Intentos int
|
|
}
|
|
|
|
// ClienteIA habla con el endpoint compatible con Anthropic Messages de MiniMax
|
|
// usando net/http puro (sin SDK externo).
|
|
type ClienteIA struct {
|
|
APIKey string
|
|
BaseURL string
|
|
Model string
|
|
HTTPClient *http.Client
|
|
Sleep func(ctx context.Context, d time.Duration) error
|
|
}
|
|
|
|
// NuevoClienteIA construye el cliente de MiniMax leyendo MINIMAX_API_KEY,
|
|
// MINIMAX_BASE_URL y MINIMAX_MODEL (desde cfg si se pasa, o desde el entorno).
|
|
// Rechaza explicitamente una clave vacia y advierte cuando solo ANTHROPIC_API_KEY
|
|
// esta presente para evitar enviar credenciales al proveedor equivocado.
|
|
func NuevoClienteIA(cfg *config.Config) (*ClienteIA, error) {
|
|
var apiKey, baseURL, model string
|
|
if cfg != nil {
|
|
apiKey = strings.TrimSpace(cfg.MinimaxAPIKey)
|
|
baseURL = strings.TrimSpace(cfg.MinimaxBaseURL)
|
|
model = strings.TrimSpace(cfg.MinimaxModel)
|
|
} else {
|
|
apiKey = strings.TrimSpace(os.Getenv("MINIMAX_API_KEY"))
|
|
baseURL = strings.TrimSpace(os.Getenv("MINIMAX_BASE_URL"))
|
|
model = strings.TrimSpace(os.Getenv("MINIMAX_MODEL"))
|
|
}
|
|
|
|
if apiKey == "" {
|
|
if strings.TrimSpace(os.Getenv("ANTHROPIC_API_KEY")) != "" {
|
|
return nil, errors.New(
|
|
"Falta MINIMAX_API_KEY (se detecto ANTHROPIC_API_KEY en el entorno, pero NO se usa para evitar mandar credenciales al proveedor equivocado). Define MINIMAX_API_KEY en .env.",
|
|
)
|
|
}
|
|
return nil, errors.New(
|
|
"Falta MINIMAX_API_KEY. Definela en .env. No uses ANTHROPIC_API_KEY: la clave de MiniMax nunca debe enviarse a api.anthropic.com.",
|
|
)
|
|
}
|
|
|
|
if baseURL == "" {
|
|
baseURL = DefaultMinimaxBaseURL
|
|
}
|
|
baseURL = strings.TrimRight(baseURL, "/")
|
|
|
|
if model == "" {
|
|
model = DefaultMinimaxModel
|
|
}
|
|
|
|
return &ClienteIA{
|
|
APIKey: apiKey,
|
|
BaseURL: baseURL,
|
|
Model: model,
|
|
HTTPClient: &http.Client{
|
|
Timeout: 120 * time.Second,
|
|
},
|
|
Sleep: sleepContext,
|
|
}, nil
|
|
}
|
|
|
|
// NormalizarRespuesta corrige rarezas observadas en las respuestas de MiniMax
|
|
// antes de validar: a veces envuelve elementos de arrays en `{item: {...}}`.
|
|
// Solo desenvuelve cuando "item" es la UNICA clave del objeto.
|
|
func NormalizarRespuesta(v any) any {
|
|
switch val := v.(type) {
|
|
case []any:
|
|
out := make([]any, len(val))
|
|
for i, elem := range val {
|
|
out[i] = NormalizarRespuesta(elem)
|
|
}
|
|
return out
|
|
case map[string]any:
|
|
if len(val) == 1 {
|
|
if inner, ok := val["item"]; ok {
|
|
return NormalizarRespuesta(inner)
|
|
}
|
|
}
|
|
out := make(map[string]any, len(val))
|
|
for k, elem := range val {
|
|
out[k] = NormalizarRespuesta(elem)
|
|
}
|
|
return out
|
|
default:
|
|
return v
|
|
}
|
|
}
|
|
|
|
type apiCacheControl struct {
|
|
Type string `json:"type"`
|
|
}
|
|
|
|
type apiSystemBlock struct {
|
|
Type string `json:"type"`
|
|
Text string `json:"text"`
|
|
CacheControl *apiCacheControl `json:"cache_control,omitempty"`
|
|
}
|
|
|
|
type apiTool struct {
|
|
Name string `json:"name"`
|
|
Description string `json:"description"`
|
|
InputSchema map[string]any `json:"input_schema"`
|
|
}
|
|
|
|
type apiToolChoice struct {
|
|
Type string `json:"type"`
|
|
Name string `json:"name,omitempty"`
|
|
}
|
|
|
|
type apiMessage struct {
|
|
Role string `json:"role"`
|
|
Content any `json:"content"`
|
|
}
|
|
|
|
type apiRequest struct {
|
|
Model string `json:"model"`
|
|
MaxTokens int `json:"max_tokens"`
|
|
System []apiSystemBlock `json:"system,omitempty"`
|
|
Tools []apiTool `json:"tools,omitempty"`
|
|
ToolChoice *apiToolChoice `json:"tool_choice,omitempty"`
|
|
Messages []apiMessage `json:"messages"`
|
|
}
|
|
|
|
type apiContentBlock struct {
|
|
Type string `json:"type"`
|
|
Text string `json:"text,omitempty"`
|
|
ID string `json:"id,omitempty"`
|
|
Name string `json:"name,omitempty"`
|
|
Input any `json:"input,omitempty"`
|
|
}
|
|
|
|
type apiUsage struct {
|
|
InputTokens int `json:"input_tokens"`
|
|
OutputTokens int `json:"output_tokens"`
|
|
CacheReadInputTokens int `json:"cache_read_input_tokens"`
|
|
CacheCreationInputTokens int `json:"cache_creation_input_tokens"`
|
|
}
|
|
|
|
type apiResponse struct {
|
|
ID string `json:"id"`
|
|
Type string `json:"type"`
|
|
Role string `json:"role"`
|
|
Content []apiContentBlock `json:"content"`
|
|
StopReason string `json:"stop_reason"`
|
|
Usage apiUsage `json:"usage"`
|
|
}
|
|
|
|
type apiHTTPError struct {
|
|
Status int
|
|
Body string
|
|
}
|
|
|
|
func (e *apiHTTPError) Error() string {
|
|
return fmt.Sprintf("error HTTP %d del proveedor IA: %s", e.Status, e.Body)
|
|
}
|
|
|
|
var (
|
|
reTransitorio400 = regexp.MustCompile(`(?i)unexpected|internal|parse|unknown`)
|
|
reTransitorioRed = regexp.MustCompile(`(?i)ECONN|ETIMEDOUT|socket|network|connection reset|EOF|timeout`)
|
|
)
|
|
|
|
func esTransitorio(err error) bool {
|
|
if err == nil {
|
|
return false
|
|
}
|
|
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
|
return false
|
|
}
|
|
var httpErr *apiHTTPError
|
|
if errors.As(err, &httpErr) {
|
|
switch httpErr.Status {
|
|
case http.StatusRequestTimeout, http.StatusConflict, http.StatusTooManyRequests:
|
|
return true
|
|
}
|
|
if httpErr.Status >= 500 {
|
|
return true
|
|
}
|
|
if httpErr.Status == http.StatusBadRequest && reTransitorio400.MatchString(httpErr.Body) {
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
var netErr net.Error
|
|
if errors.As(err, &netErr) {
|
|
return true
|
|
}
|
|
return reTransitorioRed.MatchString(err.Error())
|
|
}
|
|
|
|
func sleepContext(ctx context.Context, d time.Duration) error {
|
|
t := time.NewTimer(d)
|
|
defer t.Stop()
|
|
select {
|
|
case <-ctx.Done():
|
|
return ctx.Err()
|
|
case <-t.C:
|
|
return nil
|
|
}
|
|
}
|
|
|
|
func (c *ClienteIA) crearMensaje(ctx context.Context, reqBody apiRequest) (*apiResponse, error) {
|
|
payload, err := json.Marshal(reqBody)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("error serializando solicitud IA: %w", err)
|
|
}
|
|
|
|
endpoint := strings.TrimRight(c.BaseURL, "/") + "/v1/messages"
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(payload))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("error creando solicitud HTTP: %w", err)
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("x-api-key", c.APIKey)
|
|
req.Header.Set("anthropic-version", anthropicVersion)
|
|
|
|
httpClient := c.HTTPClient
|
|
if httpClient == nil {
|
|
httpClient = &http.Client{Timeout: 120 * time.Second}
|
|
}
|
|
|
|
resp, err := httpClient.Do(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
raw, err := io.ReadAll(io.LimitReader(resp.Body, 10<<20))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
|
bodyStr := strings.TrimSpace(string(raw))
|
|
if len(bodyStr) > 1000 {
|
|
bodyStr = bodyStr[:1000]
|
|
}
|
|
return nil, &apiHTTPError{Status: resp.StatusCode, Body: bodyStr}
|
|
}
|
|
|
|
var parsed apiResponse
|
|
if err := json.Unmarshal(raw, &parsed); err != nil {
|
|
return nil, fmt.Errorf("error decodificando respuesta IA: %w", err)
|
|
}
|
|
return &parsed, nil
|
|
}
|
|
|
|
func (c *ClienteIA) crearMensajeConReintentos(ctx context.Context, reqBody apiRequest, maxTransitorios int) (*apiResponse, error) {
|
|
if maxTransitorios <= 0 {
|
|
maxTransitorios = maxTransitoriosDef
|
|
}
|
|
sleepFn := c.Sleep
|
|
if sleepFn == nil {
|
|
sleepFn = sleepContext
|
|
}
|
|
|
|
var ultimo error
|
|
for i := 1; i <= maxTransitorios; i++ {
|
|
res, err := c.crearMensaje(ctx, reqBody)
|
|
if err == nil {
|
|
return res, nil
|
|
}
|
|
ultimo = err
|
|
if !esTransitorio(err) || i == maxTransitorios {
|
|
return nil, err
|
|
}
|
|
backoff := time.Duration(1<<(i-1)) * time.Second // 1s, 2s
|
|
if sleepErr := sleepFn(ctx, backoff); sleepErr != nil {
|
|
return nil, sleepErr
|
|
}
|
|
}
|
|
return nil, ultimo
|
|
}
|
|
|
|
// LlamarConHerramienta invoca al modelo exigiendo una llamada a opts.Herramienta,
|
|
// normaliza rarezas de MiniMax, valida contra el contrato y reintenta devolviendo
|
|
// los errores exactos de validacion hasta opts.MaxIntentos.
|
|
func (c *ClienteIA) LlamarConHerramienta(ctx context.Context, opts OpcionesLlamada) (*ResultadoLlamada, error) {
|
|
maxIntentos := opts.MaxIntentos
|
|
if maxIntentos <= 0 {
|
|
maxIntentos = 3
|
|
}
|
|
maxTokens := opts.MaxTokens
|
|
if maxTokens <= 0 {
|
|
maxTokens = 8000
|
|
}
|
|
|
|
systemBlocks := make([]apiSystemBlock, 0, len(opts.System))
|
|
for _, b := range opts.System {
|
|
blk := apiSystemBlock{
|
|
Type: "text",
|
|
Text: b.Texto,
|
|
}
|
|
if b.Cachear {
|
|
blk.CacheControl = &apiCacheControl{Type: "ephemeral"}
|
|
}
|
|
systemBlocks = append(systemBlocks, blk)
|
|
}
|
|
|
|
tools := []apiTool{
|
|
{
|
|
Name: opts.Herramienta.Nombre,
|
|
Description: opts.Herramienta.Descripcion,
|
|
InputSchema: opts.Herramienta.InputSchema,
|
|
},
|
|
}
|
|
|
|
toolChoice := &apiToolChoice{
|
|
Type: "tool",
|
|
Name: opts.Herramienta.Nombre,
|
|
}
|
|
|
|
mensajes := []apiMessage{
|
|
{Role: "user", Content: opts.MensajeUsuario},
|
|
}
|
|
|
|
var uso UsoTokens
|
|
var ultimoError string
|
|
|
|
for intento := 1; intento <= maxIntentos; intento++ {
|
|
res, err := c.crearMensajeConReintentos(ctx, apiRequest{
|
|
Model: c.Model,
|
|
MaxTokens: maxTokens,
|
|
System: systemBlocks,
|
|
Tools: tools,
|
|
ToolChoice: toolChoice,
|
|
Messages: mensajes,
|
|
}, maxTransitoriosDef)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
uso.Entrada += res.Usage.InputTokens
|
|
uso.Salida += res.Usage.OutputTokens
|
|
uso.CacheLectura += res.Usage.CacheReadInputTokens
|
|
uso.CacheEscritura += res.Usage.CacheCreationInputTokens
|
|
|
|
var bloquesTool []apiContentBlock
|
|
var candidatos []apiContentBlock
|
|
for _, blk := range res.Content {
|
|
if blk.Type == "tool_use" {
|
|
bloquesTool = append(bloquesTool, blk)
|
|
if blk.Name == opts.Herramienta.Nombre {
|
|
candidatos = append(candidatos, blk)
|
|
}
|
|
}
|
|
}
|
|
|
|
var primerFallo *apiContentBlock
|
|
for i := range candidatos {
|
|
cand := candidatos[i]
|
|
norm := NormalizarRespuesta(cand.Input)
|
|
datos, ok := norm.(map[string]any)
|
|
var errs []string
|
|
if !ok {
|
|
errs = []string{"La entrada de la herramienta debe ser un objeto JSON."}
|
|
} else if opts.Herramienta.Validar != nil {
|
|
errs = opts.Herramienta.Validar(datos)
|
|
}
|
|
if len(errs) == 0 {
|
|
return &ResultadoLlamada{
|
|
Datos: datos,
|
|
Uso: uso,
|
|
Intentos: intento,
|
|
}, nil
|
|
}
|
|
if primerFallo == nil {
|
|
cp := cand
|
|
primerFallo = &cp
|
|
ultimoError = strings.Join(errs, "\n")
|
|
}
|
|
}
|
|
|
|
if len(bloquesTool) > 0 {
|
|
if primerFallo == nil {
|
|
ultimoError = fmt.Sprintf("El modelo llamo a una herramienta inesperada. Usa %s.", opts.Herramienta.Nombre)
|
|
}
|
|
userBlocks := make([]any, 0, len(bloquesTool)+1)
|
|
for _, b := range bloquesTool {
|
|
content := fmt.Sprintf("Herramienta inesperada. Usa %s.", opts.Herramienta.Nombre)
|
|
if primerFallo != nil && b.ID == primerFallo.ID {
|
|
content = ultimoError
|
|
}
|
|
userBlocks = append(userBlocks, map[string]any{
|
|
"type": "tool_result",
|
|
"tool_use_id": b.ID,
|
|
"is_error": true,
|
|
"content": content,
|
|
})
|
|
}
|
|
userBlocks = append(userBlocks, map[string]any{
|
|
"type": "text",
|
|
"text": fmt.Sprintf(
|
|
"La llamada no cumple el schema. Corrige EXACTAMENTE estos errores y vuelve a llamar a %s:\n\n%s\n\nRevisa que cada objeto este en el array que le corresponde y que no falte ningun campo obligatorio. No agregues campos que el schema no declara.",
|
|
opts.Herramienta.Nombre,
|
|
ultimoError,
|
|
),
|
|
})
|
|
mensajes = append(mensajes,
|
|
apiMessage{Role: "assistant", Content: res.Content},
|
|
apiMessage{Role: "user", Content: userBlocks},
|
|
)
|
|
continue
|
|
}
|
|
|
|
ultimoError = "El modelo respondio con prosa en vez de llamar a la herramienta."
|
|
mensajes = append(mensajes,
|
|
apiMessage{Role: "assistant", Content: res.Content},
|
|
apiMessage{
|
|
Role: "user",
|
|
Content: fmt.Sprintf("Debes responder llamando a la herramienta %s. No escribas prosa suelta.", opts.Herramienta.Nombre),
|
|
},
|
|
)
|
|
}
|
|
|
|
return nil, fmt.Errorf("El paso %q agoto %d intentos.\nUltimo error:\n%s", opts.Herramienta.Nombre, maxIntentos, ultimoError)
|
|
}
|