Workers AI Provider

August 17, 2026 ยท View on GitHub

Module: bernstein.core.routing.cloudflare_ai Class: WorkersAIProvider

Cloudflare Workers AI provides free-tier LLM models that Bernstein can use for task decomposition, planning, manager decisions, and structured output generation. This lets you run the orchestrator's internal LLM calls at zero cost.


Available models

All models listed below are free on Workers AI:

ModelContextSpeedBest for
@cf/meta/llama-3.1-70b-instruct131,072MediumPlanning, decomposition (default)
@cf/meta/llama-3.1-8b-instruct131,072FastSimple classification, routing
@cf/mistral/mistral-7b-instruct-v0.232,768FastQuick completions
@cf/google/gemma-7b-it8,192FastShort prompts, simple tasks
@cf/qwen/qwen1.5-14b-chat32,768MediumMultilingual tasks

!!! tip "Zero-cost planning" Use Workers AI as your internal_llm_provider in bernstein.yaml to eliminate LLM costs for orchestrator-internal calls (task decomposition, priority assignment, plan optimization). Agent execution still uses your configured CLI adapter.


Configuration

WorkersAIConfig dataclass fields:

FieldTypeDefaultDescription
account_idstr(required)Cloudflare account ID
api_tokenstr(required)API token with Workers AI: Run permission
modelstr"@cf/meta/llama-3.1-70b-instruct"Model identifier
max_tokensint4096Maximum output tokens
temperaturefloat0.3Sampling temperature
timeout_secondsint60HTTP request timeout

Usage

Text completion

from bernstein.core.routing.cloudflare_ai import WorkersAIConfig, WorkersAIProvider

provider = WorkersAIProvider(
    WorkersAIConfig(
        account_id="abc123",
        api_token="cf_token_...",
    )
)

response = await provider.complete(
    "Decompose this task into 3 subtasks: Add authentication to the API",
    system="You are a senior engineering manager planning work for a team.",
)

print(response.text)
print(response.model)  # "@cf/meta/llama-3.1-70b-instruct"
print(response.input_tokens)  # token count from API
print(response.output_tokens)
print(response.is_free)  # True for free-tier models

Structured JSON output

schema = {
    "type": "object",
    "properties": {
        "subtasks": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "title": {"type": "string"},
                    "role": {"type": "string"},
                    "priority": {"type": "integer"},
                },
            },
        },
    },
}

result = await provider.structured(
    "Decompose: Add OAuth2 login to the web app",
    schema=schema,
    system="Return a task decomposition as JSON.",
)
# result is a parsed dict matching the schema
print(result["subtasks"])

!!! note "JSON parsing" The structured() method automatically strips markdown code fences from model output before parsing. If the model returns invalid JSON, a json.JSONDecodeError is raised.

Cost estimation

cost = provider.estimate_cost(input_tokens=1000, output_tokens=500)
print(f"${cost:.6f}")  # \$0.000000 for free models

# List all available models with metadata
models = WorkersAIProvider.available_models()
for name, info in models.items():
    print(f"{name}: free={info['free']}, context={info['context']}")

Response type

WorkersAIResponse fields:

FieldTypeDescription
textstrGenerated text
modelstrModel identifier used
input_tokensintInput token count (from API usage)
output_tokensintOutput token count
is_freeboolWhether this model is on the free tier

Integration with bernstein.yaml

To use Workers AI as the internal scheduler LLM:

# bernstein.yaml
internal_llm_provider: cloudflare_ai
internal_llm_model: "@cf/meta/llama-3.1-70b-instruct"

This routes all orchestrator-internal LLM calls (task decomposition, priority assignment) through Workers AI while agents still use your configured CLI adapter (Claude, Codex, Gemini, etc.).


Cost comparison

ProviderModelInput cost/1M tokensOutput cost/1M tokensPlanning cost for 50-task run
Workers AILlama 3.1 70B$0.00$0.00$0.00
Workers AILlama 3.1 8B$0.00$0.00$0.00
AnthropicClaude Haiku~$0.25~$1.25~$0.50
AnthropicClaude Sonnet~$3.00~$15.00~$6.00
OpenAIGPT-4o-mini~$0.15~$0.60~$0.30

!!! tip "Hybrid approach" Use Workers AI for planning/decomposition (free) and Claude/Codex/Gemini for actual code generation (paid but high quality). This eliminates orchestrator overhead costs entirely.