> ## 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 agente desde Ruby con la gema fetch_hive

# Ejecutar con el SDK de Ruby

Usa la gema oficial `fetch_hive` cuando quieras enviar un mensaje a un agente desde Ruby. El SDK envuelve el endpoint público [`POST /v1/agent/invoke`](../api-reference/agents/invoke), maneja la autenticación, admite streaming mediante un bloque y acepta entradas multimodales.

## Instalación

Agrega a tu `Gemfile`:

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

Luego ejecuta:

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

O instala directamente:

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

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

## Autenticación

Establece la variable de entorno `FETCH_HIVE_API_KEY` con la clave de API de tu espacio de trabajo (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 [Claves de API](../workspace/api-keys) para saber cómo crear y rotar claves.

## Ejemplo básico

Envía un mensaje a un agente y lee la respuesta final:

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

client = FetchHive::Client.new

reply = client.invoke_agent(
  agent: "AGENT_UUID",
  message: "Summarize the latest AI infrastructure trends"
)

puts reply["response"]
```

Consulta el [formato de respuesta sin streaming](../api-reference/agents/invoke#response).

## Referencia del método

| Palabra clave | Tipo          | Requerido | Descripción                                                                                                                                             |
| ------------- | ------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `agent`       | `String`      | Sí        | El ID del agente                                                                                                                                        |
| `message`     | `String`      | Sí        | El mensaje que quieres enviar                                                                                                                           |
| `thread_id`   | `String`      | No        | Una cadena arbitraria que identifica un hilo de conversación persistente                                                                                |
| `messages`    | `Array<Hash>` | No        | Historial de conversación administrado por el llamador. Cada elemento: `{ role: "user" \| "assistant" \| "system", content: String }`.                  |
| `user`        | `String`      | No        | Identificador opaco del llamador expuesto en [Seguimiento de usuarios](../user-tracking/overview)                                                       |
| `metadata`    | `Hash`        | No        | Metadatos planos definidos por el llamador para auditoría y filtrado de registros. Consulta [Metadatos de invocación](../user-tracking/invoke-metadata) |

El SDK inyecta `streaming: false` para `invoke_agent`. Para hacer streaming, usa `invoke_agent_stream` (abajo).

## Manejo de la respuesta

```ruby theme={null}
reply = client.invoke_agent(agent: "AGENT_UUID", message: "Hello")

puts reply["response"]      # final text
puts reply["model"]         # model identifier
puts reply["usage"]         # token usage breakdown
puts reply["request_id"]    # use this to look up the run in Logs
puts reply["tool_calls"]    # tool invocations made during the run
```

## Streaming

Usa `invoke_agent_stream` para recibir Server-Sent Events a medida que llegan. El método entrega cada hash de evento analizado al bloque:

```ruby theme={null}
client.invoke_agent_stream(
  agent: "AGENT_UUID",
  message: "Summarize the latest AI infrastructure trends",
  thread_id: "user-456-support-session"
) do |chunk|
  case chunk["type"]
  when "response"
    print chunk["response"]
    $stdout.flush
  when "tool"
    puts "\nCalling tool: #{chunk['tool']}"
  when "usage"
    puts "\n\nUsage: #{chunk['usage']}"
  end
end
```

El stream genera los mismos tipos de eventos documentados en [Invocar Agente → Respuesta](../api-reference/agents/invoke#response): `summary` (cuando se dispara el resumen automático), `reasoning`, `response`, `tool`, un evento final `usage`, o un evento `error` si el proveedor falla a mitad del stream.

Si omites el bloque, el método devuelve un `Enumerator` que puedes pasar por ahí:

```ruby theme={null}
enum = client.invoke_agent_stream(agent: "AGENT_UUID", message: "Hello")
enum.each { |chunk| handle(chunk) }
```

## Conversaciones de múltiples turnos

### Hilos persistentes

Pasa cualquier cadena como `thread_id` y Fetch Hive creará el hilo en la primera llamada y lo reanudará en llamadas posteriores con el mismo valor:

```ruby theme={null}
client.invoke_agent(
  agent: "AGENT_UUID",
  message: "What are the main AI infrastructure trends right now?",
  thread_id: "user-456-support-session"
)

client.invoke_agent(
  agent: "AGENT_UUID",
  message: "Which of those trends have the most enterprise adoption?",
  thread_id: "user-456-support-session"
)
```

### Historial sin estado

Administra el estado tú mismo pasando los turnos previos en `messages`. Fetch Hive usa el historial proporcionado como contexto pero no lo persiste:

```ruby theme={null}
client.invoke_agent(
  agent: "AGENT_UUID",
  message: "Which of those trends have the most enterprise adoption?",
  messages: [
    { role: "user", content: "What are the main AI infrastructure trends right now?" },
    { role: "assistant", content: "Teams are focusing on evals, tool routing, and observability." }
  ]
)
```

## Entradas multimodales

Adjunta imágenes al mensaje actual con `attachments`:

```ruby theme={null}
result = client.invoke_agent(
  agent: "vision-agent",
  message: "Describe this image",
  attachments: ["https://example.com/photo.jpg"]
)
puts result["response"]
```

Las URLs deben comenzar con `https://`.

## Configuración

| Opción     | Valor predeterminado           | Descripción                                  |
| ---------- | ------------------------------ | -------------------------------------------- |
| `api_key`  | `ENV["FETCH_HIVE_API_KEY"]`    | Token Bearer del panel                       |
| `base_url` | `https://api.fetchhive.com/v1` | Sobrescribe la URL base de la API            |
| `timeout`  | `120`                          | Tiempo de espera de la solicitud en segundos |

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

## Errores

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

```ruby theme={null}
begin
  reply = client.invoke_agent(agent: "AGENT_UUID", message: "Hello")
rescue => e
  warn "Fetch Hive error: #{e.message}"
end
```

Consulta [Errores y límites de tasa](../api-reference/errors-and-rate-limits) para conocer el significado de los códigos de estado.

## Enlaces

* [Gema en RubyGems](https://rubygems.org/gems/fetch_hive)
* [Código fuente en GitHub](https://github.com/Fetch-Hive/ruby-sdk)

## Próximos pasos

* [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)
* [Invocar Agente](../api-reference/agents/invoke) - Referencia completa del endpoint
