# Run with PHP SDK

Use the official `fetch-hive/sdk` Composer package when you want to invoke a prompt deployment from PHP. The SDK wraps the public [`POST /v1/invoke`](/api-reference/invoke-prompt.md) endpoint with an idiomatic facade, handles authentication, and exposes streaming responses as a generator of parsed event arrays.

## Installation

```bash
composer require fetch-hive/sdk
```

The SDK requires PHP 8.1+ and uses Guzzle as its HTTP client.

## Authentication

Set the `FETCH_HIVE_API_KEY` environment variable to your workspace API key (the client reads it automatically):

```bash
export FETCH_HIVE_API_KEY=fhk_...
```

```php
<?php
require_once 'vendor/autoload.php';

use FetchHive\Sdk\FetchHive;

$client = new FetchHive();
```

Or pass the key explicitly:

```php
$client = new FetchHive(['api_key' => 'fhk_...']);
```

See [API Keys](/your-workspace/api-keys.md) for how to create and rotate keys.

## Basic example

Invoke a prompt deployment and read the final response:

```php
<?php
require_once 'vendor/autoload.php';

use FetchHive\Sdk\FetchHive;

$client = new FetchHive();

$result = $client->invokePrompt([
    'deployment' => 'YOUR_DEPLOYMENT_NAME',
    'variant'    => 'YOUR_VARIANT_NAME',
    'inputs'     => ['text' => 'Fetch Hive helps teams ship AI products faster.'],
]);

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

`invokePrompt` blocks until the prompt completes and returns the parsed JSON body as an associative array. See the [non-streaming response shape](/api-reference/invoke-prompt.md#response).

## Method reference

| Key          | Type     | Required | Description                                                                           |
| ------------ | -------- | -------- | ------------------------------------------------------------------------------------- |
| `deployment` | `string` | Yes      | The prompt deployment name                                                            |
| `variant`    | `string` | No       | The deployment variant name                                                           |
| `inputs`     | `array`  | No       | Key-value pairs for the prompt variables                                              |
| `user`       | `string` | No       | Opaque caller identifier surfaced in [User Tracking](/user-tracking/user-tracking.md) |

The SDK injects `streaming: false` for `invokePrompt`. To stream, use `invokePromptStream` (below).

## Handling the response

```php
$result = $client->invokePrompt([
    'deployment' => 'my-prompt',
    'variant'    => 'default',
]);

echo $result['response'];      // final text
echo $result['model'];         // model identifier
print_r($result['usage']);     // token usage breakdown
echo $result['request_id'];    // use this to look up the run in Logs
```

## Streaming

Use `invokePromptStream` to receive Server-Sent Events as they arrive. The method returns a `Generator` you can iterate with `foreach`:

```php
foreach ($client->invokePromptStream([
    'deployment' => 'YOUR_DEPLOYMENT_NAME',
    'variant'    => 'YOUR_VARIANT_NAME',
    'inputs'     => ['text' => 'Fetch Hive helps teams ship AI products faster.'],
]) as $chunk) {
    match ($chunk['type']) {
        'response' => print($chunk['response'] ?? ''),
        'usage'    => print("\n\nUsage: " . json_encode($chunk['usage'])),
        default    => null,
    };
}
```

The stream yields the same event types documented in [Invoke Prompt → Response](/api-reference/invoke-prompt.md#response): `reasoning`, `response`, and a final `usage` event.

## Configuration

| Option     | Default                        | Description                     |
| ---------- | ------------------------------ | ------------------------------- |
| `api_key`  | `FETCH_HIVE_API_KEY` env var   | Bearer token from the dashboard |
| `base_url` | `https://api.fetchhive.com/v1` | Override the API base URL       |
| `timeout`  | `120`                          | Request timeout in seconds      |

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

## Errors

Non-2xx responses throw `FetchHive\Sdk\Exception\ApiException` carrying the status code and response body. Catch it if you need to handle failures:

```php
use FetchHive\Sdk\Exception\ApiException;

try {
    $result = $client->invokePrompt([
        'deployment' => 'my-prompt',
        'variant'    => 'default',
    ]);
} catch (ApiException $e) {
    error_log('Fetch Hive error: ' . $e->getMessage());
}
```

See [Errors and Rate Limits](/api-reference/errors-and-rate-limits.md) for status code meanings.

## Links

* [Package on Packagist](https://packagist.org/packages/fetch-hive/sdk)
* [Source on GitHub](https://github.com/Fetch-Hive/php-sdk)

## Next steps

* [Run with API](/prompts/run-with-api.md) - The same flow with cURL
* [Run with Python SDK](/prompts/run-with-python-sdk.md)
* [Run with Node.js SDK](/prompts/run-with-nodejs-sdk.md)
* [Run with Ruby SDK](/prompts/run-with-ruby-sdk.md)
* [Invoke Prompt](/api-reference/invoke-prompt.md) - Full endpoint reference


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.fetchhive.com/prompts/run-with-php-sdk.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
