Saltar al contenido principal

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, maneja la autenticación, expone el streaming como un AsyncIterable y admite entradas multimodales.

Instalación

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:
export FETCH_HIVE_API_KEY=fhk_...
import { FetchHive } from '@fetch-hive/sdk';

const client = new FetchHive();
O pasa la clave explícitamente:
const client = new FetchHive({ apiKey: 'fhk_...' });
Consulta Claves de API para saber cómo crear y rotar claves.

Ejemplo básico

Envía un mensaje a un agente y lee la respuesta final:
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.

Referencia del método

CampoTipoRequeridoDescripción
agentstringEl ID del agente
messagestringEl mensaje que quieres enviar
thread_idstringNoUna cadena arbitraria que identifica un hilo de conversación persistente
messagesArray<{ role, content, image_urls? }>NoHistorial de conversación administrado por quien llama
image_urlsstring[]NoURLs HTTPS de imágenes adjuntas al message actual para entradas multimodales
userstringNoIdentificador opaco del llamador expuesto en Seguimiento de usuarios
metadataRecord<string, string | number | boolean | null>NoMetadatos planos definidos por el llamador para auditoría y filtrado de registros. Consulta Metadatos de invocación
El SDK inyecta streaming: false para invokeAgent. Para hacer streaming, usa invokeAgentStream (abajo).

Manejo de la respuesta

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:
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: 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:
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:
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 image_urls:
const result = await client.invokeAgent({
  agent: 'vision-agent',
  message: 'Describe this image',
  image_urls: ['https://example.com/photo.jpg'],
});
console.log(result.response);
Las URLs deben comenzar con https://.

Configuración

OpciónValor predeterminadoDescripción
apiKeyprocess.env.FETCH_HIVE_API_KEYToken Bearer del panel
baseURLhttps://api.fetchhive.com/v1Sobrescribe la URL base de la API
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:
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 para conocer el significado de los códigos de estado.

Enlaces

Próximos pasos