PHP Client How-To

OpenAI-compatible gateway client for Klintero.

OpenAI: /v1/* PHP

Base URL: http://dev-ai.klintero.com

OpenAiGatewayClient How-To

This document covers **common scenarios** for `OpenAiGatewayClient` in `developers/client-php/ai_gateway_client.php`.

Quick Start

<?php
require_once __DIR__ . '/ai_gateway_client.php';

$client = new OpenAiGatewayClient([
  'base_url' => 'http://dev-ai-klintero-com', // or https://dev-ai.klintero.com
  'api_key' => 'sk_live_...',
  'connect_timeout' => 10,
  'timeout' => 60,
]);

1) Chat Completions (sync)

$res = $client->chatCompletions([
  'model' => 'gpt-4.1-mini',
  'messages' => [
    ['role' => 'user', 'content' => 'Hello!'],
  ],
]);

2) Responses (sync)

$res = $client->responses([
  'model' => 'gpt-4.1-mini',
  'input' => 'Say hello!',
]);

3) Embeddings (sync)

$res = $client->embeddings([
  'model' => 'text-embedding-3-small',
  'input' => 'Embeddings test',
]);

4) Models (list)

$res = $client->models();

5) Async (queue + poll)

// 1) Send async
$res = $client->responses([
  'model' => 'gpt-4.1-mini',
  'input' => 'Async test',
  'mode' => 'async',
]);

$jobId = $res['data']['job_id'] ?? null;
if (!$jobId) {
  // Handle error
}

// 2) Poll job
$job = $client->jobsGet($jobId);

6) Stream (SSE) – Chat

OpenAI-compatible SSE stream. The callback receives **raw SSE** (data/event lines).

$client->chatCompletions([
  'model' => 'gpt-4.1-mini',
  'messages' => [
    ['role' => 'user', 'content' => 'Stream test'],
  ],
  'stream' => true,
], function (string $chunk): void {
  echo $chunk;
  if (function_exists('flush')) { @flush(); }
});

7) Stream (SSE) – Responses

$client->responses([
  'model' => 'gpt-4.1-mini',
  'input' => 'Stream test',
  'stream' => true,
], function (string $chunk): void {
  echo $chunk;
  if (function_exists('flush')) { @flush(); }
});

8) Cancel async job

$res = $client->jobsCancel($jobId);

9) Generic request (optional)

If you need a new endpoint before the client adds a wrapper:

$res = $client->request('POST', '/v1/chat/completions', [
  'model' => 'gpt-4.1-mini',
  'messages' => [['role' => 'user', 'content' => 'Hej!']],
]);

Streaming via generic:

$client->request('POST', '/v1/responses', [
  'model' => 'gpt-4.1-mini',
  'input' => 'Hej!',
  'stream' => true,
], function (string $chunk): void {
  echo $chunk;
});

10) Error handling (all responses)

All methods return an array:

[
  'endpoint' => '/v1/...',
  'status' => 200,
  'data' => [ ... ],      // JSON-decoded body
  'raw' => '...',         // raw body (sync)
  'headers' => [ ... ],
  'request_id' => '...',
  'error' => null         // string om cURL/transportfel
]

Always check `status` and `error`.

11) Tips

- `base_url` must **not** include `/v1`. Example: `http://dev-ai-klintero-com` - Auth is sent as `Authorization: Bearer <api_key>` - Streaming uses **raw SSE**; parse in client code (OpenAI SDK-compatible)