Search by

mindtwo / laravel-ai-hetzner

mindtwo

Laravel AI SDK driver for the Hetzner Inference API: GDPR-compliant, EU-hosted open-weight models (GLM 5.3, Kolibri 1, BGE-M3) via Chat Completions, Responses, Anthropic Messages, Embeddings, and Token Counting.

Package info

github.com/mindtwo/laravel-ai-hetzner

pkg:composer/mindtwo/laravel-ai-hetzner

Statistics

Installs: 5

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v2.0.0 2026-12-03 22:09 UTC

This package is auto-updated.

Last update: 2026-12-03 22:10:52 UTC


README

mindtwo GmbH

Laravel AI Hetzner

A hetzner provider driver for the Laravel AI SDK that connects Laravel applications to the Hetzner Inference API. It runs open-weight language, vision, and embedding models (GLM 5.3, GLM 5.3 Flash, Aleph-Alpha Kolibri 1, and BAAI/bge-m3) hosted in GDPR-compliant European data centers with zero data retention. Requests speak OpenAI Chat Completions, OpenAI Responses, Anthropic Messages, or OpenAI Embeddings over Bearer token authentication.

Documentation

Detailed documentation lives in docs/ and covers configuration keys, wire protocol internals, attachment rules, and operational patterns. Start with:

Features

  • EU model tiers and aliases – maps default, cheapest (#[UseCheapestModel]), smartest (#[UseSmartestModel]), and embeddings to Hetzner's catalog (zai-org/GLM-5.3-Flash, Aleph-Alpha/Kolibri-1, zai-org/GLM-5.3, BAAI/bge-m3), with a manual visionTextModel() helper, short aliases, and full overrides for future Hugging Face models
  • Three wire protocols – routes generation calls through /v1/chat/completions (chat), /v1/responses (responses), or /v1/messages (messages, authenticated via Authorization: Bearer instead of x-api-key) per connection or per agent
  • Typed HetznerOptions builder – configures reasoning_effort (none, low, medium, high), extended thinking, deterministic seed, stop, logprobs, wire protocol selection, and PDF modes, normalizing reasoning parameters across protocols
  • Prompt caching and reasoning usage – surfaces Hetzner's automatic prompt cache hits (cacheReadInputTokens) and reasoning token counts (reasoningTokens) in both synchronous and streaming responses
  • Multilingual embeddings – generates 1,024-dimensional vectors via BAAI/bge-m3 on /v1/embeddings while omitting unsupported Matryoshka dimensions parameters on fixed-size models
  • Vision and document conversion – downloads and base64-inlines remote Image::fromUrl() links required by Hetzner, wraps text documents in <document> blocks, converts PDFs (text, images, or both), and enforces Hetzner's 32 MiB payload limit pre-flight
  • Failover-aware error mapping – parses JSON and plain-text errors, separating HTTP 429 RPM limits (RateLimitedException) from monthly EUR consumption caps (InsufficientCreditsException) and HTTP 504 300-second timeouts (ProviderOverloadedException)
  • Catalog and token utilities – inspects served models (GET /v1/models), counts input tokens server-side (POST /v1/messages/count_tokens), checks context-window fit via the Hetzner facade, and validates readiness via hetzner:status

Tech Stack

Layer Technology Docs
Runtime PHP 8.3+ PHP
Framework Laravel 12 and 13 Laravel
AI Laravel AI SDK ^1.4, Prism 0.99 Laravel AI SDK, Prism
Inference API Hetzner Inference API Hetzner Docs
Testing Pest 4, Orchestra Testbench Pest, Testbench
Code quality Pint, Larastan (level 8) Pint, Larastan

Requirements

  • PHP 8.3 or newer
  • Composer 2
  • Laravel 12 or 13 with laravel/ai ^1.4 installed
  • A Hetzner Inference Token generated in the Hetzner Console under Inference
  • Optional, for PDF text extraction: smalot/pdfparser 2.12+
  • Optional, for PDF page rendering: poppler's pdftoppm (brew install poppler or apt install poppler-utils), or ext-imagick with Ghostscript

Installation

composer require mindtwo/laravel-ai-hetzner

The service provider and Hetzner facade alias are auto-discovered and register ai.providers.hetzner unless config/ai.php already defines one. Add your Inference Token to .env:

HETZNER_AI_API_KEY=
HETZNER_AI_MODEL="zai-org/GLM-5.3-Flash"
HETZNER_AI_API="chat"
Variable Purpose
HETZNER_AI_API_KEY Bearer Inference Token (falls back to HETZNER_INFERENCE_TOKEN)
HETZNER_AI_URL Base URL including /v1; defaults to https://inference.hetzner.com/v1
HETZNER_AI_API Wire protocol: chat (default), responses, or messages
HETZNER_AI_MODEL Default text model; defaults to zai-org/GLM-5.3-Flash
HETZNER_AI_CHEAPEST_MODEL Tier for #[UseCheapestModel]; defaults to Aleph-Alpha/Kolibri-1
HETZNER_AI_SMARTEST_MODEL Tier for #[UseSmartestModel]; defaults to zai-org/GLM-5.3
HETZNER_AI_EMBEDDINGS_MODEL Default embedding model; defaults to BAAI/bge-m3 (1024 dimensions)
HETZNER_AI_REASONING_EFFORT Optional global reasoning effort (none, low, medium, high)
HETZNER_AI_SEED Optional deterministic sampling seed
HETZNER_AI_TIMEOUT Client utilities / standalone Prism timeout (120 default). SDK agents use timeout: / #[Timeout] (default 60); embeddings use generate(timeout: ...) (default 30)
HETZNER_AI_INLINE_REMOTE_IMAGES Base64-inline external Image::fromUrl() attachments (true default)
HETZNER_AI_PDF_MODE PDF handling mode: text (default), images, or both

To customize model aliases, headers, or attachment thresholds in code, publish the configuration file:

php artisan vendor:publish --tag="ai-hetzner-config"

All 23 environment variables and multi-connection patterns are documented in Configuration and Models.

Development

Application commands

Command Description
php artisan hetzner:status Verify token presence, /v1/models reachability, served models, and PDF renderers for the default hetzner connection
php artisan hetzner:status hetzner-overflow Inspect a named ai.providers.* connection configured with 'driver' => 'hetzner'

Testing

composer test
composer test -- --filter=ApiModesTest
composer test:live

Unit tests mock all HTTP traffic with Http::fake() and Http::preventStrayRequests(). composer test:live runs the opt-in integration suite (tests/Integration/) against https://inference.hetzner.com/v1 when HETZNER_AI_API_KEY is set in .env.

Code quality

composer format     # Pint
composer analyse    # Larastan (level 8)

Usage

Select hetzner via #[Provider('hetzner')] or per call, and combine model tier attributes with HetznerOptions when customizing reasoning, wire protocols, or PDF attachments:

use Laravel\Ai\Attributes\Provider;
use Laravel\Ai\Attributes\UseSmartestModel;
use Laravel\Ai\Contracts\Agent;
use Laravel\Ai\Contracts\HasProviderOptions;
use Laravel\Ai\Embeddings;
use Laravel\Ai\Enums\Lab;
use Laravel\Ai\Promptable;
use Mindtwo\LaravelAiHetzner\Attachments\PdfMode;
use Mindtwo\LaravelAiHetzner\Enums\ReasoningEffort;
use Mindtwo\LaravelAiHetzner\Facades\Hetzner;
use Mindtwo\LaravelAiHetzner\HetznerOptions;

use function Laravel\Ai\agent;

#[Provider('hetzner')]
#[UseSmartestModel] // Resolves to zai-org/GLM-5.3
class ComplianceReviewAgent implements Agent, HasProviderOptions
{
    use Promptable;

    public function instructions(): string
    {
        return 'Review contracts for GDPR compliance in German or English.';
    }

    public function providerOptions(Lab|string $provider): array
    {
        return $provider === 'hetzner'
            ? HetznerOptions::make()
                ->reasoningEffort(ReasoningEffort::High)
                ->seed(42)
                ->pdfMode(PdfMode::Both, maxPages: 25)
                ->toArray()
            : [];
    }
}

$review = (new ComplianceReviewAgent)->prompt($contractText);
$cachedTokens = $review->usage->cacheReadInputTokens;

// Ad-hoc call using short aliases ("kolibri", "glm-flash", "glm") and multi-token failover:
$reply = agent(instructions: 'Antworte kurz.')
    ->prompt('Was bedeutet Zero Data Retention?', provider: ['hetzner', 'hetzner-overflow'], model: 'kolibri');

// Multilingual EU embeddings (1,024 dimensions via BAAI/bge-m3):
$vectors = Embeddings::for(['Datenschutz nach DSGVO'])->generate(provider: 'hetzner')->embeddings;

// Server-side input token counting via POST /v1/messages/count_tokens:
$tokens = Hetzner::countTokens($contractText, instructions: 'Summarize.', model: 'kolibri');

Streaming, multi-step tool calling, JSON Schema structured outputs, Anthropic /v1/messages and OpenAI /v1/responses modes, and PDF attachment workflows are covered in docs/.

Architecture

Path Purpose
src/HetznerServiceProvider.php Registers the hetzner driver on Laravel AI and Prism, merges config, and binds HetznerManager
src/HetznerProvider.php Resolves model tiers and aliases; exposes visionTextModel() for explicit model selection
src/HetznerGateway.php Bridges Laravel AI requests to Prism and guards fixed vs. Matryoshka embedding dimensions
src/HetznerOptions.php Fluent builder for reasoning, wire protocol selection, sampling, and attachment options
src/Enums/ Typed HetznerModel, ApiMode, and ReasoningEffort backed enums
src/Prism/Hetzner.php Prism provider handling Bearer auth, cross-protocol option normalization, and HTTP error mapping
src/Prism/Handlers/ Protocol handlers for Chat Completions (Chat*), OpenAI Responses (Responses*), Anthropic Messages (Messages*), and Embeddings
src/Attachments/ Remote Image::fromUrl() base64 inliner, <document> text wrapper, PDF renderers, and 32 MiB guard
src/Client/ HetznerClient and HetznerManager backing the Hetzner facade (/v1/models and /v1/messages/count_tokens)
src/Console/HetznerStatusCommand.php hetzner:status health and model readiness check

Prism\Hetzner selects the handler family per request (chat, responses, or messages) while reusing a single Bearer-authenticated HTTP client, since Hetzner's /v1/messages endpoint rejects x-api-key. Protocol differences and error semantics are detailed in Wire Protocols and Options.

Releasing

  1. Add the changes to CHANGELOG.md under a new version heading.
  2. Tag and push the release: git tag vX.Y.Z && git push --tags.
  3. Before widening the laravel/ai or prism-php/prism version constraints in composer.json, run the full test and static analysis suite against the target versions.

Packagist updates automatically from GitHub tags once the repository webhook is connected.

Conventions

  • Semantic Versioning; breaking changes ship only in major releases
  • Code style is enforced by Laravel Pint and static types by Larastan at level 8
  • Every protocol behavior, attachment mode, and error mapping requires a Pest test asserting the outgoing HTTP payload
  • Language of code, comments, and documentation is English

License

MIT, see LICENSE.md.

Support

Maintained by the development team at mindtwo GmbH.

Back to the top