> ## Documentation Index
> Fetch the complete documentation index at: https://docs.fetchhive.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Ejecutar con el SDK de Ruby

> Invoca un deployment de flujo de trabajo desde Ruby con la gema fetch_hive

# Ejecutar con el SDK de Ruby

Usa la gema oficial `fetch_hive` cuando quieras invocar un deployment de flujo de trabajo desde Ruby. El SDK envuelve el endpoint público [`POST /v1/workflow/invoke`](../api-reference/workflows/invoke), maneja la autenticación y admite tanto respuestas directas como entrega por callback.

## Instalación

Agrega a tu `Gemfile`:

```ruby theme={null}
gem "fetch_hive"
```

Luego ejecuta:

```bash theme={null}
bundle install
```

O instálala directamente:

```bash theme={null}
gem install fetch_hive
```

La gema usa `faraday` por debajo y admite Ruby 3.0+.

## Autenticación

Configura la variable de entorno `FETCH_HIVE_API_KEY` con tu clave de API del workspace (el cliente la lee automáticamente):

```bash theme={null}
export FETCH_HIVE_API_KEY=fhk_...
```

```ruby theme={null}
require "fetch_hive"

client = FetchHive::Client.new
```

O pasa la clave explícitamente:

```ruby theme={null}
client = FetchHive::Client.new(api_key: "fhk_...")
```

Consulta [API Keys](../workspace/api-keys) para saber cómo crear y rotar claves.

## Ejemplo básico

Ejecuta un deployment de flujo de trabajo directamente. La llamada se bloquea hasta que el flujo de trabajo termina:

```ruby theme={null}
require "fetch_hive"

client = FetchHive::Client.new

run = client.invoke_workflow(
  deployment: "YOUR_DEPLOYMENT_NAME",
  variant: "YOUR_VARIANT_NAME",
  inputs: { topic: "State of enterprise AI in 2026" }
)

puts run["run_status"]
puts run["output"]
```

Consulta la [forma de respuesta directa](../api-reference/workflows/invoke#response).

## Referencia del método

| Palabra clave  | Tipo      | Requerido | Descripción                                                                                                                                      |
| -------------- | --------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `deployment`   | `String`  | Sí        | El nombre del deployment del flujo de trabajo                                                                                                    |
| `variant`      | `String`  | No        | El nombre de la variante del deployment                                                                                                          |
| `inputs`       | `Hash`    | No        | Pares clave-valor para las variables definidas en el paso **Start**                                                                              |
| `async_mode`   | `Boolean` | No        | Cuando es `true`, devuelve respuesta inmediatamente y entrega el resultado mediante callback firmado                                             |
| `callback_url` | `String`  | No        | Requerido cuando `async_mode: true` - la URL HTTPS de callback a la que llamar cuando la ejecución termine                                       |
| `user`         | `String`  | No        | Identificador opaco de quien llama, expuesto en [User Tracking](../user-tracking/overview)                                                       |
| `metadata`     | `Hash`    | No        | Metadata plana definida por quien llama, para auditoría y filtrado de registros. Consulta [Metadata de invoke](../user-tracking/invoke-metadata) |

`invoke_workflow` construye el cuerpo de la solicitud por ti. Cuando pasas `async_mode: true`, el SDK envía:

```json theme={null}
{
  "async": { "enabled": true, "callback_url": "https://example.com/webhook" }
}
```

## Manejo de la respuesta

```ruby theme={null}
run = client.invoke_workflow(deployment: "my-workflow", variant: "default")

puts run["run_status"]    # "completed" | "failed" | "running" | "queued"
puts run["output"]        # final workflow output
puts run["request_id"]    # use this to look up the run in Logs
```

## Entrega por callback

Pasa `async_mode: true` para devolver respuesta inmediatamente y hacer que Fetch Hive llame a tu URL de callback cuando la ejecución termine:

```ruby theme={null}
run = client.invoke_workflow(
  deployment: "YOUR_DEPLOYMENT_NAME",
  variant: "YOUR_VARIANT_NAME",
  inputs: { topic: "State of enterprise AI in 2026" },
  async_mode: true,
  callback_url: "https://example.com/callback"
)

puts "Queued: #{run['run_status']}"
puts "Webhook secret: #{run['webhook_secret']}"
```

Almacena el `webhook_secret` para que puedas verificar la firma en el callback entrante. Consulta [Entrega por callback y disparadores de webhook](./async-and-webhooks) para el flujo de verificación y la forma del payload firmado.

## Configuración

| Opción     | Predeterminado                 | Descripción                                                                                                    |
| ---------- | ------------------------------ | -------------------------------------------------------------------------------------------------------------- |
| `api_key`  | `ENV["FETCH_HIVE_API_KEY"]`    | Token bearer del dashboard                                                                                     |
| `base_url` | `https://api.fetchhive.com/v1` | Sobrescribe la URL base de la API                                                                              |
| `timeout`  | `120`                          | Timeout de la solicitud en segundos - aumenta para solicitudes directas de flujos de trabajo de larga duración |

```ruby theme={null}
client = FetchHive::Client.new(
  api_key: "fhk_...",
  base_url: "https://api.fetchhive.com/v1",
  timeout: 600
)
```

## Errores

Las respuestas distintas a 2xx lanzan un `RuntimeError` con el código de estado y el cuerpo. Rescátalas si necesitas manejar fallos:

```ruby theme={null}
begin
  run = client.invoke_workflow(deployment: "my-workflow", variant: "default")
rescue => e
  warn "Fetch Hive error: #{e.message}"
end
```

Consulta [Manejo de errores](./error-handling) para los casos de fallo específicos del flujo de trabajo y [Errors and Rate Limits](../api-reference/errors-and-rate-limits) para el significado de los códigos de estado HTTP.

## Enlaces

* [Gem on RubyGems](https://rubygems.org/gems/fetch_hive)
* [Source on GitHub](https://github.com/Fetch-Hive/ruby-sdk)

## Siguientes pasos

* [Entrega por callback y disparadores de webhook](./async-and-webhooks) - Verifica las firmas de callback
* [Ejecutar con API](./run-with-api) - El mismo flujo con cURL
* [Ejecutar con el SDK de Python](./run-with-python-sdk)
* [Ejecutar con el SDK de Node.js](./run-with-nodejs-sdk)
* [Ejecutar con el SDK de PHP](./run-with-php-sdk)
* [Invoke Workflow](../api-reference/workflows/invoke) - Referencia completa del endpoint
