# Ejecutar un modelo

`POST https://ai.inovacc.dev/v1/run`

Responde preguntas estructuradas sobre un estado, con un veredicto y una confianza para cada una.

## Parámetros del cuerpo

- `model` (string): Un id de ruta de decisión de `GET /v1/models`. Sin valor, usa la ruta predeterminada de tu organización.
- `input` (object), obligatorio: `{"state", "questions", "images"?}`. Cualquier otro campo se rechaza con `invalid_decision_input`.
- `input.state` (any), obligatorio: Lo que se debe juzgar: cualquier valor JSON excepto `null`.
- `input.questions` (object), obligatorio: De 1 a 64 preguntas identificadas por tus ids. Cada una tiene un `type` (`noul`, `choice` o `score`), `instructions` y `criteria` en la forma estricta de su tipo.
- `input.images` (array): Máximo 16 imágenes para juzgar junto con el estado.
- `escalate` (boolean | object): Vuelve a hacer las preguntas dudosas en el siguiente nivel más fuerte. `true` usa los valores predeterminados; un objeto acepta `min_confidence` y `max_tier`.

## Encabezados

- `Authorization` (string), obligatorio: Bearer <clave de API>
- `X-Operation-Id` (string), obligatorio: un id único que tú eliges, en toda llamada excepto GET
- `Content-Type` (string), obligatorio: application/json, en una llamada con cuerpo

## Solicitud

**cURL**

```sh
curl -X POST "https://ai.inovacc.dev/v1/run" \
  -H "Authorization: Bearer $INOVACC_API_KEY" \
  -H "X-Operation-Id: $(uuidgen)" \
  -H "Content-Type: application/json" \
  -d '{
  "model": "r_eval",
  "input": {
    "state": "The reply resolves the customer'\''s billing question and links the invoice.",
    "questions": {
      "meets_bar": {
        "type": "score",
        "instructions": "Rate the reply against our support bar.",
        "criteria": [
          "Below the bar",
          "At the bar",
          "Above the bar"
        ]
      }
    }
  }
}'
```

**TypeScript**

```ts
import crypto from "node:crypto";

const body: Record<string, unknown> = {
  "model": "r_eval",
  "input": {
    "state": "The reply resolves the customer's billing question and links the invoice.",
    "questions": {
      "meets_bar": {
        "type": "score",
        "instructions": "Rate the reply against our support bar.",
        "criteria": [
          "Below the bar",
          "At the bar",
          "Above the bar"
        ]
      }
    }
  }
};

const url = "https://ai.inovacc.dev/v1/run";

const response = await fetch(url, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.INOVACC_API_KEY}`,
    "X-Operation-Id": crypto.randomUUID(),
    "Content-Type": "application/json",
  },
  body: JSON.stringify(body),
});

console.log(response.status, await response.text());
```

**Python**

```py
import json
import os
import urllib.request
import uuid

body = {
    "model": "r_eval",
    "input": {
        "state": "The reply resolves the customer's billing question and links the invoice.",
        "questions": {
            "meets_bar": {
                "type": "score",
                "instructions": "Rate the reply against our support bar.",
                "criteria": [
                    "Below the bar",
                    "At the bar",
                    "Above the bar",
                ],
            },
        },
    },
}

request = urllib.request.Request(
    "https://ai.inovacc.dev/v1/run",
    data=json.dumps(body).encode(),
    method="POST",
    headers={
        "User-Agent": "inovacc-python-sample",
        "Authorization": "Bearer " + os.environ["INOVACC_API_KEY"],
        "X-Operation-Id": str(uuid.uuid4()),
        "Content-Type": "application/json",
    },
)

with urllib.request.urlopen(request) as response:
    print(response.status, response.read().decode())
```

**Go**

```go
package main

import (
	"crypto/rand"
	"fmt"
	"io"
	"net/http"
	"os"
	"strings"
)

const url = "https://ai.inovacc.dev/v1/run"

const body = `{
  "model": "r_eval",
  "input": {
    "state": "The reply resolves the customer's billing question and links the invoice.",
    "questions": {
      "meets_bar": {
        "type": "score",
        "instructions": "Rate the reply against our support bar.",
        "criteria": [
          "Below the bar",
          "At the bar",
          "Above the bar"
        ]
      }
    }
  }
}`

// newUUID returns a random (version 4) UUID, from the standard library alone.
func newUUID() string {
	b := make([]byte, 16)
	if _, err := rand.Read(b); err != nil {
		panic(err)
	}
	b[6] = b[6]&0x0f | 0x40
	b[8] = b[8]&0x3f | 0x80
	return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
}

func main() {
	req, err := http.NewRequest("POST", url, strings.NewReader(body))
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("INOVACC_API_KEY"))
	req.Header.Set("X-Operation-Id", newUUID())
	req.Header.Set("Content-Type", "application/json")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	out, err := io.ReadAll(res.Body)
	if err != nil {
		panic(err)
	}
	fmt.Println(res.Status, string(out))
}
```

**Rust**

```rs
// Cargo.toml: reqwest = { version = "0.12", features = ["blocking", "json"] }
// Cargo.toml: serde_json = "1"
// Cargo.toml: uuid = { version = "1", features = ["v4"] }

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let api_key = std::env::var("INOVACC_API_KEY")?;
    let body = serde_json::json!({
        "model": "r_eval",
        "input": {
            "state": "The reply resolves the customer's billing question and links the invoice.",
            "questions": {
                "meets_bar": {
                    "type": "score",
                    "instructions": "Rate the reply against our support bar.",
                    "criteria": [
                        "Below the bar",
                        "At the bar",
                        "Above the bar"
                    ]
                }
            }
        }
    });
    let response = reqwest::blocking::Client::new()
        .post("https://ai.inovacc.dev/v1/run")
        .bearer_auth(api_key)
        .header("X-Operation-Id", uuid::Uuid::new_v4().to_string())
        .json(&body)
        .send()?;
    println!("{} {}", response.status(), response.text()?);
    Ok(())
}
```

**JavaScript**

```mjs
import crypto from "node:crypto";

const body = {
  "model": "r_eval",
  "input": {
    "state": "The reply resolves the customer's billing question and links the invoice.",
    "questions": {
      "meets_bar": {
        "type": "score",
        "instructions": "Rate the reply against our support bar.",
        "criteria": [
          "Below the bar",
          "At the bar",
          "Above the bar"
        ]
      }
    }
  }
};

const url = "https://ai.inovacc.dev/v1/run";

const response = await fetch(url, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.INOVACC_API_KEY}`,
    "X-Operation-Id": crypto.randomUUID(),
    "Content-Type": "application/json",
  },
  body: JSON.stringify(body),
});

console.log(response.status, await response.text());
```

**PHP**

```php
<?php

$body = <<<'JSON'
{
  "model": "r_eval",
  "input": {
    "state": "The reply resolves the customer's billing question and links the invoice.",
    "questions": {
      "meets_bar": {
        "type": "score",
        "instructions": "Rate the reply against our support bar.",
        "criteria": [
          "Below the bar",
          "At the bar",
          "Above the bar"
        ]
      }
    }
  }
}
JSON;

function uuid4(): string
{
    $bytes = random_bytes(16);
    $bytes[6] = chr(ord($bytes[6]) & 0x0f | 0x40);
    $bytes[8] = chr(ord($bytes[8]) & 0x3f | 0x80);
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($bytes), 4));
}

$curl = curl_init('https://ai.inovacc.dev/v1/run');
curl_setopt_array($curl, [
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('INOVACC_API_KEY'),
        'X-Operation-Id: ' . uuid4(),
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => $body,
]);

$response = curl_exec($curl);
echo curl_getinfo($curl, CURLINFO_HTTP_CODE), ' ', $response, "\n";
curl_close($curl);
```

**Ruby**

```rb
require "net/http"
require "securerandom"
require "uri"

uri = URI('https://ai.inovacc.dev/v1/run')
body = <<~'JSON'
{
  "model": "r_eval",
  "input": {
    "state": "The reply resolves the customer's billing question and links the invoice.",
    "questions": {
      "meets_bar": {
        "type": "score",
        "instructions": "Rate the reply against our support bar.",
        "criteria": [
          "Below the bar",
          "At the bar",
          "Above the bar"
        ]
      }
    }
  }
}
JSON

request = Net::HTTP::Post.new(uri)
request["Authorization"] = "Bearer #{ENV.fetch('INOVACC_API_KEY')}"
request["X-Operation-Id"] = SecureRandom.uuid
request["Content-Type"] = "application/json"
request.body = body

response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") do |http|
  http.request(request)
end

puts "#{response.code} #{response.body}"
```

**Java**

```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.UUID;

public class Main {
    public static void main(String[] args) throws Exception {
        String apiKey = System.getenv("INOVACC_API_KEY");
        String body = "{" +
                "\"model\": \"r_eval\"," +
                "\"input\": {" +
                "\"state\": \"The reply resolves the customer's billing question and links the invoice.\"," +
                "\"questions\": {" +
                "\"meets_bar\": {" +
                "\"type\": \"score\"," +
                "\"instructions\": \"Rate the reply against our support bar.\"," +
                "\"criteria\": [" +
                "\"Below the bar\"," +
                "\"At the bar\"," +
                "\"Above the bar\"" +
                "]" +
                "}" +
                "}" +
                "}" +
                "}";

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://ai.inovacc.dev/v1/run"))
                .header("Authorization", "Bearer " + apiKey)
                .header("X-Operation-Id", UUID.randomUUID().toString())
                .header("Content-Type", "application/json")
                .method("POST", HttpRequest.BodyPublishers.ofString(body))
                .build();

        HttpResponse<String> response = HttpClient.newHttpClient()
                .send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.statusCode() + " " + response.body());
    }
}
```

**C#**

```cs
using System.Text;

var body = "{" +
    "\"model\": \"r_eval\"," +
    "\"input\": {" +
    "\"state\": \"The reply resolves the customer's billing question and links the invoice.\"," +
    "\"questions\": {" +
    "\"meets_bar\": {" +
    "\"type\": \"score\"," +
    "\"instructions\": \"Rate the reply against our support bar.\"," +
    "\"criteria\": [" +
    "\"Below the bar\"," +
    "\"At the bar\"," +
    "\"Above the bar\"" +
    "]" +
    "}" +
    "}" +
    "}" +
    "}";

var url = "https://ai.inovacc.dev/v1/run";
var apiKey = Environment.GetEnvironmentVariable("INOVACC_API_KEY");

using var client = new HttpClient();
using var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Headers.Add("Authorization", $"Bearer {apiKey}");
request.Headers.Add("X-Operation-Id", Guid.NewGuid().ToString());
request.Content = new StringContent(body, Encoding.UTF8, "application/json");

using var response = await client.SendAsync(request);
Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}");
```

**Kotlin**

```kt
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.util.UUID

fun main() {
    val apiKey = System.getenv("INOVACC_API_KEY")
    val body = "{" +
        "\"model\": \"r_eval\"," +
        "\"input\": {" +
        "\"state\": \"The reply resolves the customer's billing question and links the invoice.\"," +
        "\"questions\": {" +
        "\"meets_bar\": {" +
        "\"type\": \"score\"," +
        "\"instructions\": \"Rate the reply against our support bar.\"," +
        "\"criteria\": [" +
        "\"Below the bar\"," +
        "\"At the bar\"," +
        "\"Above the bar\"" +
        "]" +
        "}" +
        "}" +
        "}" +
        "}"

    val request = HttpRequest.newBuilder()
        .uri(URI.create("https://ai.inovacc.dev/v1/run"))
        .header("Authorization", "Bearer " + apiKey)
        .header("X-Operation-Id", UUID.randomUUID().toString())
        .header("Content-Type", "application/json")
        .method("POST", HttpRequest.BodyPublishers.ofString(body))
        .build()

    val response = HttpClient.newHttpClient()
        .send(request, HttpResponse.BodyHandlers.ofString())
    println("${response.statusCode()} ${response.body()}")
}
```

**Swift**

```swift
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif

let body = #"""
{
  "model": "r_eval",
  "input": {
    "state": "The reply resolves the customer's billing question and links the invoice.",
    "questions": {
      "meets_bar": {
        "type": "score",
        "instructions": "Rate the reply against our support bar.",
        "criteria": [
          "Below the bar",
          "At the bar",
          "Above the bar"
        ]
      }
    }
  }
}
"""#

let apiKey = ProcessInfo.processInfo.environment["INOVACC_API_KEY"] ?? ""

let url = URL(string: "https://ai.inovacc.dev/v1/run")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
request.setValue(UUID().uuidString, forHTTPHeaderField: "X-Operation-Id")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = Data(body.utf8)

let (data, response) = try await URLSession.shared.data(for: request)
let status = (response as? HTTPURLResponse)?.statusCode ?? 0
print(status, String(decoding: data, as: UTF8.self))
```

## Respuesta

**200**

```json
{
  "model": "r_eval",
  "result": {
    "answers": {
      "meets_bar": {
        "type": "score",
        "score": 1.6,
        "confidence": 0.7,
        "legend": {
          "0": "Below the bar",
          "1": "At the bar",
          "2": "Above the bar"
        },
        "probabilities": {
          "0": 0.05,
          "1": 0.3,
          "2": 0.65
        }
      }
    },
    "usage": {
      "input_tokens": 80,
      "output_tokens": 12
    }
  },
  "state": "Completed",
  "engine": {
    "tier": "standard",
    "latency_ms": 840
  }
}
```

**400**: missing_operation_id, invalid_operation_id, invalid_body, invalid_input, invalid_decision_input, invalid_escalate, unsupported_field, model_not_allowed, input_too_large

**401**: missing_credentials, invalid_credentials

**403**: route_forbidden

**409**: operation_in_progress

**413**: request_too_large

**429**: rate_limited, quota_exceeded, concurrency_limited, budget_exhausted

**502**: upstream_error

**503**: service_unavailable, route_unavailable

## Ver también

- [Autenticación](https://developer.inovacc.dev/es/guides/authentication/)
- [Errores](https://developer.inovacc.dev/es/guides/errors/)
- [Límites](https://developer.inovacc.dev/es/guides/limits/)
