From cd45ae23f02c5aff3fbd606cffa112cb2a781ee6 Mon Sep 17 00:00:00 2001 From: peptiderepo Date: Tue, 21 Apr 2026 10:04:56 +0700 Subject: [PATCH] feat(images): route Cloudflare Workers AI via AI Gateway by default MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Direct probe on 2026-04-21 confirmed the Cloudflare AI Gateway route to Workers AI (`gateway.ai.cloudflare.com/.../workers-ai/@cf/...`) is no longer 403ing — the upstream regression noted in v0.8.0's ARCHITECTURE.md #16 and in thread image-pipeline seq 6 has been resolved. Routing via the gateway gives us the same benefits we already get for OpenRouter LLM calls: response caching, cost/latency dashboard, rate limiting. Changes: - `Cloudflare_Image_Support::build_endpoint_url()` now prefers the gateway URL derived from the existing `prautoblogger_ai_gateway_base_url` option. Direct API remains the fallback. - New private helper `build_gateway_workers_ai_url()` strips the OpenRouter path suffix from the configured gateway URL and appends `/workers-ai/{model}`. Returns empty string (fallback to direct) when: no gateway URL configured, the new toggle is off, or the URL isn't a valid `https://gateway.ai.cloudflare.com/...` shape. - New admin toggle `prautoblogger_cf_image_via_gateway` (default on) in the Images section. Operators can disable to force direct API without clearing the LLM-path gateway URL. - ARCHITECTURE.md #16 rewritten to reflect the v0.8.2+ gateway routing. - CHANGELOG.md v0.8.2 entry under Changed. Tests (new `CloudflareImageSupportTest`): - Direct URL when gateway not configured. - Gateway URL derived correctly when configured + toggle on. - Toggle off forces direct URL even with gateway configured. - Malformed gateway URL falls back to direct (defensive). - `is_nsfw_error()` only matches error code 3030 (pinned separately so a tolerance regression fails early). Cost impact: near-zero. Gateway adds a few ms of latency and enables response caching — could *reduce* cost on identical prompts within the configurable cache TTL. Uninstall: new option covered by existing prautoblogger_% LIKE sweep. Implements Commit 1b (narrow AI-Gateway-migration scope) per thread image-pipeline seq 7. Co-Authored-By: Claude Opus 4.7 (1M context) --- ARCHITECTURE.md | 4 +- CHANGELOG.md | 13 ++ .../admin/class-settings-fields-extended.php | 8 ++ .../class-cloudflare-image-support.php | 54 +++++++- prautoblogger.php | 4 +- .../Providers/CloudflareImageSupportTest.php | 115 ++++++++++++++++++ 6 files changed, 193 insertions(+), 5 deletions(-) create mode 100644 tests/unit/Providers/CloudflareImageSupportTest.php diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index b04ec15..f95d04a 100755 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -533,8 +533,8 @@ Reddit rejected our OAuth API application (April 2026). We initially switched to The admin model picker (v1) needs to list OpenRouter models with pricing and capabilities. We fetch `https://openrouter.ai/api/v1/models` (free, unauthenticated) once daily and store the normalized payload in a WP option fronted by a 24h transient. On stale-and-fetch-fails, we serve last-good + surface a warning. The registry class (`class-open-router-model-registry.php`) takes all config via constructor (option name, transient name, endpoint URL) — no PRAUTOBLOGGER_* constants inside the class body. Phase 2 lifts it into a shared Composer package with zero internal edits. Phase 3 adds a parallel `Cloudflare_WorkersAI_Model_Registry` behind the same interface. Capability vocabulary: `text→text`, `text+image→text`, `text+audio→text`, `text→image`, `text→audio`, `text→video`, `text→embedding`. Cost: $0/month. -### #16: Image generation via Cloudflare Workers AI (FLUX.1), direct (not via AI Gateway) -The image-generation layer (started 2026-04-15, tracked in `convo/prautoblogger/threads/2026-04-image-pipeline/`) uses FLUX.1 [schnell] on Cloudflare Workers AI as its default model, chosen for its ~$0.0011/MP cost and 2–3 sec latency. FLUX.1 [dev] is a ~4× cost upgrade exposed as a dropdown for specific posts that warrant it. Calls go directly to `https://api.cloudflare.com/client/v4/accounts/{id}/ai/run/@cf/black-forest-labs/...`, *not* through the Cloudflare AI Gateway that we use for OpenRouter — the gateway route to Workers AI currently 403s (pre-existing open issue). The provider lives behind `PRAutoBlogger_Image_Provider_Interface`, so the decision is trivially reversible: switching to a different image API (DALL-E, Replicate, a future AI Gateway route) is a new class implementation plus a one-line swap in the pipeline wiring. Trade-off: we run two different Cloudflare integration paths (gateway for OpenRouter LLMs, direct for Workers AI images) until the gateway route stabilizes — minor cognitive overhead, zero functional downside. +### #16: Image generation via Cloudflare Workers AI (FLUX.1), via AI Gateway (v0.8.2+) +The image-generation layer uses FLUX.1 [schnell] on Cloudflare Workers AI as its default model, chosen for its ~$0.0011/MP cost and 2–3 sec latency. FLUX.1 [dev] is a ~4× cost upgrade exposed as a dropdown for specific posts that warrant it. **v0.8.2+**: calls route through the Cloudflare AI Gateway (same gateway we already use for OpenRouter — `gateway.ai.cloudflare.com/v1/{account}/{gateway}/workers-ai/@cf/black-forest-labs/...`) for response caching, unified cost/latency telemetry, and rate limiting. The 2026-04-15 regression that caused the gateway route to 403 on Workers AI has been resolved upstream; verified by direct probe on 2026-04-21. A `prautoblogger_cf_image_via_gateway` toggle (default on) falls back to the direct `api.cloudflare.com/client/v4/accounts/{id}/ai/run/...` URL if the gateway regresses again. The provider lives behind `PRAutoBlogger_Image_Provider_Interface`, so switching to a different image API (DALL-E, Replicate) is a new class implementation plus a one-line swap in the pipeline wiring. ### #15: Optional Cloudflare AI Gateway in front of OpenRouter We already use Cloudflare for DNS/CDN on peptiderepo.com, so layering AI Gateway in front of OpenRouter is zero marginal infrastructure. It gives us response caching (meaningful for repeated classification/scoring calls), a unified cost/latency dashboard, rate limiting, and provider fallback — all of which we would otherwise have to build ourselves to satisfy the CTO cost-tracking rules. Kept as an opt-in URL setting (`prautoblogger_ai_gateway_base_url`) so the plugin still works unchanged out of the box and can be bypassed instantly if the gateway misbehaves. The gateway is a transparent OpenRouter-compatible proxy; no new provider class is needed, and the response parsing path (`usage`, `choices[0].message.content`) is unchanged. diff --git a/CHANGELOG.md b/CHANGELOG.md index 28afb2c..611f3ce 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,19 @@ All notable changes to PRAutoBlogger will be documented in this file. Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project uses [Semantic Versioning](https://semver.org/). +## [0.8.2] — 2026-04-21 + +### Changed + +- **Cloudflare Workers AI image calls now route through the AI Gateway + by default.** The 2026-04-15 regression that caused the gateway route + to 403 on Workers AI has been resolved upstream. Routing via the + gateway gives us response caching, unified cost/latency dashboard, + and rate limiting for free, mirroring the OpenRouter LLM path. A new + admin toggle `prautoblogger_cf_image_via_gateway` (default on) lets + operators force direct-API if the gateway route regresses again, + without clearing the gateway URL setting the LLM provider depends on. + ## [0.8.1] — 2026-04-21 ### Fixed diff --git a/includes/admin/class-settings-fields-extended.php b/includes/admin/class-settings-fields-extended.php index 673a21b..d0e1266 100644 --- a/includes/admin/class-settings-fields-extended.php +++ b/includes/admin/class-settings-fields-extended.php @@ -260,6 +260,14 @@ class PRAutoBlogger_Settings_Fields_Extended { 'default' => '1', 'description' => __( 'When the provider rejects an image prompt as NSFW (e.g. Cloudflare code 3030), retry once with a generic fallback scene built from the article title. Disable to fail fast if the filter gets trigger-happy.', 'prautoblogger' ), ], + [ + 'id' => 'prautoblogger_cf_image_via_gateway', + 'label' => __( 'Route Cloudflare Images via AI Gateway', 'prautoblogger' ), + 'type' => 'toggle', + 'section' => 'prautoblogger_images', + 'default' => '1', + 'description' => __( 'Route Cloudflare Workers AI image calls through the Cloudflare AI Gateway (requires the AI Gateway URL configured under API Keys). Adds response caching, cost logging, and rate-limiting. Turn off to hit the direct Workers AI API — only needed if the gateway route regresses.', 'prautoblogger' ), + ], ]; } } diff --git a/includes/providers/class-cloudflare-image-support.php b/includes/providers/class-cloudflare-image-support.php index 002f88a..94188f9 100644 --- a/includes/providers/class-cloudflare-image-support.php +++ b/includes/providers/class-cloudflare-image-support.php @@ -55,11 +55,26 @@ class PRAutoBlogger_Cloudflare_Image_Support { /** * Build the Workers AI run URL for a given account + model. * + * By default routes through the Cloudflare AI Gateway we already use for + * OpenRouter — the gateway route to Workers AI was observed 403ing in + * April 2026 (see ARCHITECTURE.md #16), but manual probe on 2026-04-21 + * shows it's now returning 200. Gateway routing gives us response caching, + * cost logging, rate limiting, and provider fallback for free. + * + * Direct-API fallback kicks in automatically when either the + * `prautoblogger_ai_gateway_base_url` option is empty (no gateway + * configured at all) or the new `prautoblogger_cf_image_via_gateway` + * toggle is off (explicit opt-out for if the gateway route regresses). + * * @param string $account_id Cloudflare account UUID. - * @param string $model Fully-qualified Workers AI model id. + * @param string $model Fully-qualified Workers AI model id (e.g. @cf/black-forest-labs/flux-1-schnell). * @return string Fully-formed HTTPS URL. */ public function build_endpoint_url( string $account_id, string $model ): string { + $gateway_url = $this->build_gateway_workers_ai_url( $account_id, $model ); + if ( '' !== $gateway_url ) { + return $gateway_url; + } return sprintf( 'https://api.cloudflare.com/client/v4/accounts/%s/ai/run/%s', rawurlencode( $account_id ), @@ -67,6 +82,43 @@ class PRAutoBlogger_Cloudflare_Image_Support { ); } + /** + * Derive a Workers AI URL rooted at the same AI Gateway we already use + * for OpenRouter. Returns empty string when the gateway isn't configured + * or the admin toggle opts out — the caller falls back to direct API. + * + * The existing `prautoblogger_ai_gateway_base_url` option points at + * `https://gateway.ai.cloudflare.com/v1/{account}/{gateway}/openrouter` + * for the LLM path; we strip the `/openrouter` suffix and append + * `/workers-ai/{model}` for the image path. Defensive: only emits a URL + * that pattern-matches, so a bad option value quietly falls back. + * + * @param string $account_id Cloudflare account UUID (kept for symmetry; not used in URL derivation). + * @param string $model Fully-qualified Workers AI model id. + * @return string Gateway URL, or empty string if unavailable. + */ + private function build_gateway_workers_ai_url( string $account_id, string $model ): string { + unset( $account_id ); + if ( '1' !== (string) get_option( 'prautoblogger_cf_image_via_gateway', '1' ) ) { + return ''; + } + $gateway_base = rtrim( (string) get_option( 'prautoblogger_ai_gateway_base_url', '' ), '/' ); + if ( '' === $gateway_base ) { + return ''; + } + // Must be an https CF AI Gateway URL. + if ( 0 !== stripos( $gateway_base, 'https://gateway.ai.cloudflare.com/' ) ) { + return ''; + } + // Strip the trailing OpenRouter path component (any path component, really); + // everything before the last '/' is the gateway root shared by all provider routes. + $gateway_root = substr( $gateway_base, 0, strrpos( $gateway_base, '/' ) ?: strlen( $gateway_base ) ); + if ( '' === $gateway_root ) { + return ''; + } + return sprintf( '%s/workers-ai/%s', $gateway_root, ltrim( $model, '/' ) ); + } + /** * Emit a WARN line for a retryable failure. * diff --git a/prautoblogger.php b/prautoblogger.php index 7293201..fda4d44 100644 --- a/prautoblogger.php +++ b/prautoblogger.php @@ -8,7 +8,7 @@ declare(strict_types=1); * Plugin Name: PRAutoBlogger * Plugin URI: https://peptiderepo.com/prautoblogger * Description: Monitors social media for trending topics, generates SEO-friendly blog posts using AI, and publishes them on a daily schedule with full cost tracking and self-improvement metrics. - * Version: 0.8.1 + * Version: 0.8.2 * Requires at least: 6.0 * Requires PHP: 7.4 * Author: PeptideRepo @@ -35,7 +35,7 @@ if ( ! defined( 'ABSPATH' ) ) { | and limits without magic strings. */ -define( 'PRAUTOBLOGGER_VERSION', '0.8.1' ); +define( 'PRAUTOBLOGGER_VERSION', '0.8.2' ); define( 'PRAUTOBLOGGER_DB_VERSION', '1.1.0' ); define( 'PRAUTOBLOGGER_PLUGIN_FILE', __FILE__ ); define( 'PRAUTOBLOGGER_PLUGIN_DIR', plugin_dir_path( __FILE__ ) ); diff --git a/tests/unit/Providers/CloudflareImageSupportTest.php b/tests/unit/Providers/CloudflareImageSupportTest.php new file mode 100644 index 0000000..da160e2 --- /dev/null +++ b/tests/unit/Providers/CloudflareImageSupportTest.php @@ -0,0 +1,115 @@ +stub_get_option( [ + 'prautoblogger_ai_gateway_base_url' => '', + 'prautoblogger_cf_image_via_gateway' => '1', + ] ); + + $support = new \PRAutoBlogger_Cloudflare_Image_Support(); + $url = $support->build_endpoint_url( self::ACCOUNT_ID, self::MODEL ); + + $this->assertStringStartsWith( 'https://api.cloudflare.com/client/v4/accounts/', $url ); + $this->assertStringContainsString( self::ACCOUNT_ID, $url ); + $this->assertStringEndsWith( self::MODEL, $url ); + } + + /** + * With the AI Gateway URL configured and the toggle on, image calls + * route through `gateway.ai.cloudflare.com/.../workers-ai/{model}` at + * the same gateway root as the OpenRouter LLM path. + */ + public function test_returns_gateway_url_when_configured_and_toggle_on(): void { + $this->stub_get_option( [ + 'prautoblogger_ai_gateway_base_url' => 'https://gateway.ai.cloudflare.com/v1/' . self::ACCOUNT_ID . '/peptiderepo-prod/openrouter', + 'prautoblogger_cf_image_via_gateway' => '1', + ] ); + + $support = new \PRAutoBlogger_Cloudflare_Image_Support(); + $url = $support->build_endpoint_url( self::ACCOUNT_ID, self::MODEL ); + + $this->assertSame( + 'https://gateway.ai.cloudflare.com/v1/' . self::ACCOUNT_ID . '/peptiderepo-prod/workers-ai/' . self::MODEL, + $url + ); + } + + /** + * The toggle overrides the gateway URL: operators can fall back to the + * direct API if the gateway regresses, without clearing the OpenRouter + * gateway setting that the LLM provider depends on. + */ + public function test_toggle_off_forces_direct_url_even_with_gateway_configured(): void { + $this->stub_get_option( [ + 'prautoblogger_ai_gateway_base_url' => 'https://gateway.ai.cloudflare.com/v1/' . self::ACCOUNT_ID . '/peptiderepo-prod/openrouter', + 'prautoblogger_cf_image_via_gateway' => '0', + ] ); + + $support = new \PRAutoBlogger_Cloudflare_Image_Support(); + $url = $support->build_endpoint_url( self::ACCOUNT_ID, self::MODEL ); + + $this->assertStringStartsWith( 'https://api.cloudflare.com/client/v4/accounts/', $url ); + } + + /** + * A malformed gateway URL (e.g. http, or a totally different host) is + * rejected and the direct-API path is used instead. Defensive — a bad + * option value shouldn't break image generation. + */ + public function test_falls_back_to_direct_when_gateway_url_is_malformed(): void { + $this->stub_get_option( [ + 'prautoblogger_ai_gateway_base_url' => 'http://evil.example.com/openrouter', + 'prautoblogger_cf_image_via_gateway' => '1', + ] ); + + $support = new \PRAutoBlogger_Cloudflare_Image_Support(); + $url = $support->build_endpoint_url( self::ACCOUNT_ID, self::MODEL ); + + $this->assertStringStartsWith( 'https://api.cloudflare.com/client/v4/accounts/', $url ); + } + + /** + * The NSFW detector must match on the documented error code without + * tripping on other 4xx bodies. (Covered at the provider level too, + * but worth pinning at the support class so a tolerance regression + * fails early.) + */ + public function test_is_nsfw_error_matches_code_3030_only(): void { + $support = new \PRAutoBlogger_Cloudflare_Image_Support(); + + $this->assertTrue( + $support->is_nsfw_error( '{"errors":[{"code":3030,"message":"NSFW"}]}' ) + ); + $this->assertFalse( + $support->is_nsfw_error( '{"errors":[{"code":7003,"message":"bad token"}]}' ) + ); + $this->assertFalse( + $support->is_nsfw_error( 'not json at all' ) + ); + $this->assertFalse( + $support->is_nsfw_error( '{}' ) + ); + } +}