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

# 使用 PHP SDK 运行

> 使用 fetch-hive/sdk Composer 包从 PHP 调用提示词部署

# 使用 PHP SDK 运行

当你想从 PHP 调用提示词部署时，请使用官方的 `fetch-hive/sdk` Composer 包。SDK 使用符合 PHP 风格的外观包装了公共的 [`POST /v1/prompt/invoke`](../api-reference/prompts/invoke) 端点，处理身份验证，并将流式响应作为已解析事件数组的生成器公开。

## 安装

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

该 SDK 需要 PHP 8.1+，并使用 Guzzle 作为其 HTTP 客户端。

## 身份验证

将 `FETCH_HIVE_API_KEY` 环境变量设置为你的工作区 API 密钥（客户端会自动读取它）：

```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();
```

或显式传入密钥：

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

有关如何创建和轮换密钥，请参阅 [API 密钥](../workspace/api-keys)。

## 基本示例

调用提示词部署并读取最终响应：

```php theme={null}
<?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` 会阻塞直到提示词完成，并将已解析的 JSON 主体作为关联数组返回。请参阅 [非流式响应结构](../api-reference/prompts/invoke#response)。

## 方法参考

| 键            | 类型       | 必填 | 描述                                                                  |
| ------------ | -------- | -- | ------------------------------------------------------------------- |
| `deployment` | `string` | 是  | 提示词部署名称                                                             |
| `variant`    | `string` | 否  | 部署变体名称                                                              |
| `inputs`     | `array`  | 否  | 提示词变量的键值对                                                           |
| `user`       | `string` | 否  | 在 [用户跟踪](../user-tracking/overview) 中显示的不透明调用方标识符                   |
| `metadata`   | `array`  | 否  | 调用方定义的扁平元数据，用于审计和日志过滤。请参阅 [调用元数据](../user-tracking/invoke-metadata) |

SDK 会为 `invokePrompt` 注入 `streaming: false`。要使用流式，请使用下面的 `invokePromptStream`。

## 处理响应

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

## 流式响应

使用 `invokePromptStream` 在到达时接收 Server-Sent Events。该方法返回一个可使用 `foreach` 迭代的 `Generator`：

```php theme={null}
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,
    };
}
```

该流会产生 [调用提示词 → 响应](../api-reference/prompts/invoke#response) 中记录的相同事件类型：`reasoning`、`response`、最终的 `usage` 事件，或在提供商在流中失败时产生的 `error` 事件。

## 配置

| 选项         | 默认值                            | 描述               |
| ---------- | ------------------------------ | ---------------- |
| `api_key`  | `FETCH_HIVE_API_KEY` 环境变量      | 来自仪表板的 Bearer 令牌 |
| `base_url` | `https://api.fetchhive.com/v1` | 覆盖 API 基础 URL    |
| `timeout`  | `120`                          | 请求超时（秒）          |

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

## 错误

非 2xx 响应会抛出 `FetchHive\Sdk\Exception\ApiException`，其中包含状态码和响应体。如需处理失败，请捕获该异常：

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

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

有关状态码含义，请参阅 [错误与速率限制](../api-reference/errors-and-rate-limits)。

## 链接

* [Packagist 上的软件包](https://packagist.org/packages/fetch-hive/sdk)
* [GitHub 上的源码](https://github.com/Fetch-Hive/php-sdk)

## 后续步骤

* [使用 API 运行](./run-with-api) - 使用 cURL 的相同流程
* [使用 Python SDK 运行](./run-with-python-sdk)
* [使用 Node.js SDK 运行](./run-with-nodejs-sdk)
* [使用 Ruby SDK 运行](./run-with-ruby-sdk)
* [调用提示词](../api-reference/prompts/invoke) - 完整端点参考
