> ## 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 Node.js

> Invoca un agente desde Node.js o TypeScript con el paquete @fetch-hive/sdk

# Ejecutar con el SDK de Node.js

Usa el paquete oficial `@fetch-hive/sdk` cuando quieras enviar un mensaje a un agente desde Node.js o TypeScript. El SDK envuelve el endpoint público [`POST /v1/agent/invoke`](../api-reference/agents/invoke), maneja la autenticación, expone el streaming como un `AsyncIterable` y admite entradas multimodales.

## Instalación

```bash theme={null}
npm install @fetch-hive/sdk
# or
yarn add @fetch-hive/sdk
# or
pnpm add @fetch-hive/sdk
```

El SDK está dirigido a Node.js 18+ (usa el `fetch` global) y se distribuye con tipos de TypeScript.

## Autenticación

Establece la variable de entorno `FETCH_HIVE_API_KEY` con la clave de API de tu espacio de trabajo:

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

```typescript theme={null}
import { FetchHive } from '@fetch-hive/sdk';

const client = new FetchHive();
```

O pasa la clave explícitamente:

```typescript theme={null}
const client = new FetchHive({ apiKey: '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:

```typescript theme={null}
import { FetchHive } from '@fetch-hive/sdk';

const client = new FetchHive();

const reply = await client.invokeAgent({
  agent: 'AGENT_UUID',
  message: 'Summarize the latest AI infrastructure trends',
});

console.log(reply.response);
```

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

## Referencia del método

| Campo       | 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<{ role, content, attachments? }>`              | No        | Historial de conversación administrado por quien llama                                                                                                  |
| `user`      | `string`                                              | No        | Identificador opaco del llamador expuesto en [Seguimiento de usuarios](../user-tracking/overview)                                                       |
| `metadata`  | `Record<string, string \| number \| boolean \| null>` | 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 `invokeAgent`. Para hacer streaming, usa `invokeAgentStream` (abajo).

## Manejo de la respuesta

```typescript theme={null}
const reply = await client.invokeAgent({
  agent: 'AGENT_UUID',
  message: 'Hello',
});

console.log(reply.response);     // final text
console.log(reply.model);        // model identifier
console.log(reply.usage);        // token usage breakdown
console.log(reply.request_id);   // use this to look up the run in Logs
console.log(reply.tool_calls);   // tool invocations made during the run
```

## Streaming

Usa `invokeAgentStream` para recibir Server-Sent Events a medida que llegan. El método devuelve un `AsyncIterable`:

```typescript theme={null}
for await (const chunk of client.invokeAgentStream({
  agent: 'AGENT_UUID',
  message: 'Summarize the latest AI infrastructure trends',
  thread_id: 'user-456-support-session',
})) {
  if (chunk.type === 'response') {
    process.stdout.write(chunk.response ?? '');
  } else if (chunk.type === 'tool') {
    console.log(`\n[Calling tool: ${chunk.tool}]`);
  } else if (chunk.type === 'usage') {
    console.log('\n\nUsage:', chunk.usage);
  }
}
```

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.

## 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:

```typescript theme={null}
await client.invokeAgent({
  agent: 'AGENT_UUID',
  message: 'What are the main AI infrastructure trends right now?',
  thread_id: 'user-456-support-session',
});

await client.invokeAgent({
  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:

```typescript theme={null}
await client.invokeAgent({
  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`:

```typescript theme={null}
const result = await client.invokeAgent({
  agent: 'vision-agent',
  message: 'Describe this image',
  attachments: ['https://example.com/photo.jpg'],
});
console.log(result.response);
```

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

## Configuración

| Opción    | Valor predeterminado             | Descripción                       |
| --------- | -------------------------------- | --------------------------------- |
| `apiKey`  | `process.env.FETCH_HIVE_API_KEY` | Token Bearer del panel            |
| `baseURL` | `https://api.fetchhive.com/v1`   | Sobrescribe la URL base de la API |

```typescript theme={null}
const client = new FetchHive({
  apiKey: 'fhk_...',
  baseURL: 'https://api.fetchhive.com/v1',
});
```

## Errores

Las respuestas no 2xx lanzan un `Error` cuyo mensaje incluye el código de estado y el cuerpo de la respuesta:

```typescript theme={null}
try {
   const reply = await client.invokeAgent({
    agent: 'AGENT_UUID',
    message: 'Hello',
  });
} catch (err) {
  console.error('Fetch Hive error:', err);
}
```

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

## Enlaces

* [Paquete en npm](https://www.npmjs.com/package/@fetch-hive/sdk)
* [Código fuente en GitHub](https://github.com/Fetch-Hive/nodejs-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 Ruby](./run-with-ruby-sdk)
* [Ejecutar con el SDK de PHP](./run-with-php-sdk)
* [Invocar Agente](../api-reference/agents/invoke) - Referencia completa del endpoint
