DEVSAIO

Call AI models from PHP (cURL, no libraries)

A dependency-free PHP function for chat completions, plus streaming output and error handling.

DEVSAIO team · 2 min read
Share on X

PHP can call any OpenAI-compatible API with the built-in cURL extension. No Composer package needed.

A reusable function

php
<?php
function ai_chat(array $messages, string $model = 'claude-sonnet-4-6', int $maxTokens = 800): string
{
    $ch = curl_init('https://devsaio.lol/v1/chat/completions');
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 120,
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . getenv('DEVSAIO_API_KEY'),
            'Content-Type: application/json',
        ],
        CURLOPT_POSTFIELDS => json_encode(['model' => $model, 'messages' => $messages, 'max_tokens' => $maxTokens]),
    ]);
    $body = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    curl_close($ch);
    $data = json_decode((string)$body, true);
    if ($status !== 200) {
        throw new RuntimeException('AI error ' . $status . ': ' . ($data['error']['message'] ?? 'unknown'));
    }
    return $data['choices'][0]['message']['content'];
}

echo ai_chat([['role' => 'user', 'content' => 'Write a meta description for a bakery website.']]);

Streaming to the browser

php
header('Content-Type: text/plain; charset=utf-8');
header('X-Accel-Buffering: no');
while (ob_get_level()) { ob_end_flush(); }

$ch = curl_init('https://devsaio.lol/v1/chat/completions');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('DEVSAIO_API_KEY'), 'Content-Type: application/json'],
    CURLOPT_POSTFIELDS => json_encode(['model' => 'claude-sonnet-4-6', 'stream' => true, 'messages' => [['role' => 'user', 'content' => 'Tell me a story']]]),
    CURLOPT_WRITEFUNCTION => function ($ch, $chunk) {
        foreach (explode("\n", $chunk) as $line) {
            if (str_starts_with($line, 'data: ') && trim($line) !== 'data: [DONE]') {
                $j = json_decode(substr($line, 6), true);
                echo $j['choices'][0]['delta']['content'] ?? '';
                flush();
            }
        }
        return strlen($chunk);
    },
]);
curl_exec($ch);

Note: Network chunks don't always end on a line break. For production, buffer partial lines between calls; the streaming guide shows how.

Keep the key in an environment variable or a config file outside your web root.

Try it with one API key

Claude, GPT, Gemini, DeepSeek, image and video models through one OpenAI- and Anthropic-compatible endpoint. Prepaid, pay only for what you use.

Keep reading