Use the cloudflare-ai
PHP library to easily integrate Cloudflare AI Models for tasks like text generation, summarization, translation, text embeddings, and text-to-image generation.
Installation
Install the library via Composer:
composer require edgaras/cloudflare-ai
Then include the Composer autoloader:
require __DIR__ . '/vendor/autoload.php';
Obtaining Cloudflare API Credentials
Find your Account ID
Log in to your Cloudflare dashboard.
Select your account and any domain.
Your Account ID is shown on the bottom right on the Overview page.
Generate an API Token
From the Cloudflare dashboard, click on any domain.
Select Manage Account, then click Account API Tokens.
Configure permissions according to your needs and save the token securely.
Usage Examples
Text Generation Example
use Edgaras\CloudFlareAI\AI;
use Edgaras\CloudFlareAI\TextGeneration;
$accountId = "<YOUR-ACCOUNT-ID>";
$apiToken = "<YOUR-API-TOKEN>";
$modelName = "@cf/deepseek-ai/deepseek-math-7b-instruct"; // Define the model name
$config = new AI($accountId, $apiToken);
$textGeneration = new TextGeneration($config, $modelName);
$messages = [
["role" => "system", "content" => "You are a helpful assistant"],
["role" => "user", "content" => "2+2=?"],
];
// Options
$options = [
'temperature' => 0.7,
'max_tokens' => 300,
'top_p' => 0.8,
'frequency_penalty' => 0.2,
'presence_penalty' => 0.3,
];
// Run Model
$response = $textGeneration->run($messages, $options, 60);
Text-to-Image Example
use Edgaras\CloudFlareAI\AI;
use Edgaras\CloudFlareAI\TextToImage;
$accountId = "<YOUR-ACCOUNT-ID>";
$apiToken = "<YOUR-API-TOKEN>";
$modelName = "@cf/black-forest-labs/flux-1-schnell"; // Define the model name
$config = new AI($accountId, $apiToken);
$textToImage = new TextToImage($config, $modelName);
$prompt = "A futuristic cityscape at night with neon lights";
$options = [
'negativePrompt' => "blurry, low resolution",
'height' => 768,
'width' => 1024,
'numSteps' => 20,
'guidance' => 7.5,
'seed' => 12345678,
'timeout' => 20.0,
'maxAttempts' => 3,
];
// Generate the image
try {
$result = $textToImage->generate($prompt, $options);
if (isset($result['error'])) {
echo "Error: " . $result['error'] . PHP_EOL;
if (isset($result['response'])) {
print_r($result['response']);
}
} else {
echo "<img src=\"data:image/jpeg;base64,{$result['result']['image']}\">";
}
} catch (Exception $e) {
echo "Exception: " . $e->getMessage() . PHP_EOL;
}
Top comments (0)