Cloudflare Clef Driver
v1.0.0Comprehensive configuration and operational guide for the obelaw/systemone-clef driver using Cloudflare Workers AI.
Cloudflare Clef Driver
The obelaw/systemone-clef package is the official production driver adapter for the Obelaw SystemOne Decision Engine. It routes decision requests directly to Cloudflare Workers AI, leveraging Cloudflare’s serverless edge infrastructure and specialized decision models.
Architectural Overview
Traditional LLM integrations require communicating with centralized API gateways in a single geographic region. In contrast, Cloudflare Workers AI evaluates decision requests across Cloudflare’s global network spanning 300+ cities worldwide.
flowchart LR
subgraph AppHost["Laravel Application Server"]
App["Business Application"]
Driver["ClefDriver<br/><code>obelaw/systemone-clef</code>"]
Config["config/clef.php<br/>Account ID & Token"]
end
subgraph Edge["Cloudflare Global Anycast Edge (300+ Cities)"]
Gateway["Cloudflare Workers AI Gateway<br/><code>api.cloudflare.com/client/v4</code>"]
ModelClef["Model: <code>@cf/cloudflare/clef</code>"]
ModelFlash["Model: <code>@cf/cloudflare/clef-flash</code>"]
end
App --> Driver
Config -.-> Driver
Driver -->|"HTTPS POST (Bearer Token, <100ms)"| Gateway
Gateway --> ModelClef
Gateway --> ModelFlash
ModelClef -->|"Answers JSON { urgent: 0.94 }"| Driver
ModelFlash -->|"Answers JSON { urgent: 0.94 }"| Driver
Driver --> App
Key Advantages
- Sub-100ms Latency: Inference executes closest to your servers or edge nodes.
- Zero Infrastructure Maintenance: No self-hosted GPUs, Ollama daemons, or cluster scaling.
- Calibrated Probabilities: Tailored to emit well-calibrated decision distributions rather than loose discursive prose.
- Cost Efficiency: Fractional cent pricing per decision evaluation.
Installation
Install the driver adapter into your Laravel project:
composer require obelaw/systemone-clef
The package includes Laravel package discovery and will automatically register Obelaw\SystemOne\Clef\ClefServiceProvider.
Configuration
Publish the clef.php configuration file to your application’s config/ directory:
php artisan vendor:publish --tag="systemone-clef-config"
This creates config/clef.php:
return [
/*
|--------------------------------------------------------------------------
| Cloudflare Workers AI Account ID
|--------------------------------------------------------------------------
*/
'account_id' => env('CLOUDFLARE_ACCOUNT_ID', ''),
/*
|--------------------------------------------------------------------------
| Cloudflare API Token
|--------------------------------------------------------------------------
*/
'api_token' => env('CLOUDFLARE_API_TOKEN', ''),
/*
|--------------------------------------------------------------------------
| Default AI Decision Model
|--------------------------------------------------------------------------
*/
'model' => env('CLOUDFLARE_AI_MODEL', '@cf/cloudflare/clef'),
/*
|--------------------------------------------------------------------------
| Cloudflare API Base URL
|--------------------------------------------------------------------------
*/
'base_url' => env('CLOUDFLARE_API_BASE_URL', 'https://api.cloudflare.com/client/v4'),
/*
|--------------------------------------------------------------------------
| Request Timeout (seconds)
|--------------------------------------------------------------------------
*/
'timeout' => (int) env('CLOUDFLARE_AI_TIMEOUT', 30),
];
Environment Variables
Add the credentials from your Cloudflare dashboard to your .env file:
CLOUDFLARE_ACCOUNT_ID=d84f892bc091234abcd5678ef9012345
CLOUDFLARE_API_TOKEN=Vv-SecretTokenCreatedWithWorkersAIPermissions
CLOUDFLARE_AI_MODEL=@cf/cloudflare/clef
CLOUDFLARE_AI_TIMEOUT=15
Tip: Generate your API Token from Cloudflare Dashboard > My Profile > API Tokens > Create Token, selecting the Workers AI (Read/Edit) template.
Supported Models & Aliases
The Clef driver includes built-in alias resolution for Cloudflare Workers AI models:
| Model Tag | Alias | Description |
|---|---|---|
@cf/cloudflare/clef | clef | Standard Decision Model: Maximum accuracy, optimal for fraud, complex categorization, and multi-criteria rubrics. |
@cf/cloudflare/clef-flash | clef-flash | Ultra-Fast Model: Optimized for high-throughput, low-latency triage (pings, anomaly filters, rate-limiting). |
Overriding the Model Dynamically
You can target a specific model dynamically on any DecisionRequest:
use Obelaw\SystemOne\Facades\SystemOne;
use Obelaw\SystemOne\Primitives\Noul;
// Uses @cf/cloudflare/clef-flash for fast triage
$response = SystemOne::state($serverTelemetry)
->model('clef-flash')
->ask('anomaly', Noul::make('Is this CPU surge unexpected?'))
->run();
How the Driver Works Internally
When ->run() is invoked:
- The driver checks that
account_idandapi_tokenare configured. - The endpoint model and payload body are resolved (e.g. mapping
clef-flashto@cf/cloudflare/clef-flash). - Sends a
POSTrequest to:https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/run/{model} - Verifies HTTP status and checks for Cloudflare API-level errors (
success: false). - Extracts answers from
result.answersand instantiates a typedDecisionResponse.
flowchart TD
Start["Call SystemOne::run()"] --> Step1["1. Validate Configuration<br/>Ensure account_id and api_token exist"]
Step1 --> Step2["2. Resolve Model & Payload<br/>Map 'clef' / 'clef-flash' to Cloudflare model tags"]
Step2 --> Step3["3. Send HTTPS POST<br/>To api.cloudflare.com/.../ai/run/{model}"]
Step3 --> Check{"4. Check HTTP Status<br/>and success == true?"}
Check -- Yes --> Step5["5. Extract result.answers<br/>Hydrate DecisionResponse instance"]
Check -- No --> Step6["6. Throw DriverException<br/>Capture status, error response, and driver context"]
Step5 --> ReturnResp["Return DecisionResponse to Application"]
Error Handling & Exceptions
The package provides dedicated exception classes for troubleshooting:
use Obelaw\SystemOne\Clef\Exceptions\DriverException;
use Obelaw\SystemOne\Facades\SystemOne;
try {
$response = SystemOne::state($data)
->ask('check', Noul::make('Is this input valid?'))
->run();
} catch (DriverException $e) {
// Inspect failure details
Log::error('SystemOne Decision Error', [
'driver' => $e->getDriver(),
'status_code' => $e->getStatusCode(),
'api_response' => $e->getResponse(),
'message' => $e->getMessage(),
]);
// Graceful fallback logic
}
Common Exception Causes
- Missing Credentials:
account_idorapi_tokenare blank inconfig/clef.php. - 401 Unauthorized: Invalid API token or token does not have
Workers AIpermission. - 429 Rate Limit: Cloudflare rate limits exceeded on your account tier.
- Network / Timeout Error: Request exceeded the configured
timeoutlimit.
Next Steps
- Want to create an alternative driver? See Custom Drivers.
- Write automated tests with zero network calls in Testing & Mocking.