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

> Invoca un agente desde PHP con el paquete de Composer fetch-hive/sdk

# Ejecutar con el SDK de PHP

Usa el paquete oficial de Composer `fetch-hive/sdk` cuando quieras enviar un mensaje a un agente desde PHP. El SDK envuelve el endpoint público [`POST /v1/agent/invoke`](../api-reference/agents/invoke), maneja la autenticación, expone respuestas en streaming como un generador y acepta entradas multimodales.

## Instalación

```bash theme={null}
composer require fetch-hive/sdk
```

El SDK requiere PHP 8.1+ y usa Guzzle como cliente HTTP.

## 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_...
```

```php theme={null}
<?php
require_once 'vendor/autoload.php';

use FetchHive\Sdk\FetchHive;

$client = new FetchHive();
```

O pasa la clave explícitamente:

```php theme={null}
$client = new FetchHive(['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:

```php theme={null}
<?php
require_once 'vendor/autoload.php';

use FetchHive\Sdk\FetchHive;

$client = new FetchHive();

$reply = $client->invokeAgent([
    'agent'   => 'AGENT_UUID',
    'message' => 'Summarize the latest AI infrastructure trends',
]);

echo $reply['response'];
```

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

## Referencia del método

| 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`  | 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`  | `array`  | 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

```php theme={null}
$reply = $client->invokeAgent([
    'agent'   => 'AGENT_UUID',
    'message' => 'Hello',
]);

echo $reply['response'];        // final text
echo $reply['model'];           // model identifier
print_r($reply['usage']);       // token usage breakdown
echo $reply['request_id'];      // use this to look up the run in Logs
print_r($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 `Generator`:

```php theme={null}
foreach ($client->invokeAgentStream([
    'agent'     => 'AGENT_UUID',
    'message'   => 'Summarize the latest AI infrastructure trends',
    'thread_id' => 'user-456-support-session',
]) as $chunk) {
    match ($chunk['type']) {
        'response' => print($chunk['response'] ?? ''),
        'tool'     => print("\nCalling tool: " . ($chunk['tool'] ?? '')),
        'usage'    => print("\n\nUsage: " . json_encode($chunk['usage'])),
        default    => null,
    };
}
```

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:

```php theme={null}
$client->invokeAgent([
    'agent'     => 'AGENT_UUID',
    'message'   => 'What are the main AI infrastructure trends right now?',
    'thread_id' => 'user-456-support-session',
]);

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

```php theme={null}
$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`:

```php theme={null}
$result = $client->invokeAgent([
    'agent'      => 'vision-agent',
    'message'    => 'Describe this image',
    'attachments' => ['https://example.com/photo.jpg'],
]);
echo $result['response'];
```

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

## Configuración

| Opción     | Valor predeterminado                     | Descripción                                  |
| ---------- | ---------------------------------------- | -------------------------------------------- |
| `api_key`  | variable de entorno `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 |

```php theme={null}
$client = new FetchHive([
    'api_key'  => 'fhk_...',
    'base_url' => 'https://api.fetchhive.com/v1',
    'timeout'  => 120.0,
]);
```

## Errores

Las respuestas no 2xx lanzan `FetchHive\Sdk\Exception\ApiException` con el código de estado y el cuerpo de la respuesta:

```php theme={null}
use FetchHive\Sdk\Exception\ApiException;

try {
    $reply = $client->invokeAgent([
        'agent'   => 'AGENT_UUID',
        'message' => 'Hello',
    ]);
} catch (ApiException $e) {
    error_log('Fetch Hive error: ' . $e->getMessage());
}
```

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 Packagist](https://packagist.org/packages/fetch-hive/sdk)
* [Código fuente en GitHub](https://github.com/Fetch-Hive/php-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 Ruby](./run-with-ruby-sdk)
* [Invocar Agente](../api-reference/agents/invoke) - Referencia completa del endpoint
