DEV Community

Edgaras
Edgaras

Posted on

2 1 1

Using Cloudflare AI Models with PHP

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
Enter fullscreen mode Exit fullscreen mode

Then include the Composer autoloader:

require __DIR__ . '/vendor/autoload.php';
Enter fullscreen mode Exit fullscreen mode

Obtaining Cloudflare API Credentials

Find your Account ID

  1. Log in to your Cloudflare dashboard.

  2. Select your account and any domain.

  3. Your Account ID is shown on the bottom right on the Overview page.

Generate an API Token

  1. From the Cloudflare dashboard, click on any domain.

  2. Select Manage Account, then click Account API Tokens.

  3. 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);
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

Useful Links

Top comments (0)

👋 Kindness is contagious

If this post resonated with you, feel free to hit ❤️ or leave a quick comment to share your thoughts!

Okay