Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Anthropic Php Laravel Package

mozex/anthropic-php

Community-maintained PHP SDK for the Anthropic API. Send messages, stream responses, call tools, use extended thinking, web search, code execution, files, and batches. PSR-18 compatible, works with any HTTP client; Laravel wrapper available.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • PSR-18 Compliance: The package leverages PSR-18 HTTP clients (e.g., Guzzle, Symfony HTTP Client), ensuring seamless integration with Laravel’s built-in HTTP stack (e.g., HttpClient facade). This avoids vendor lock-in and aligns with Laravel’s modern architecture.
  • Laravel-Specific Wrapper: The mozex/anthropic-laravel package provides a Laravel-specific facade, service provider, and config-based setup, reducing boilerplate for Laravel applications.
  • Feature Parity: Supports all Anthropic API endpoints (messages, streaming, tools, files, batches, etc.), including beta features via the betas parameter. This ensures future-proofing as Anthropic introduces new capabilities.
  • Immutable Responses: Typed, immutable response objects (e.g., CreateResponse, FileResponse) improve type safety and IDE support, reducing runtime errors in Laravel’s dependency-injected ecosystem.

Integration Feasibility

  • Laravel Ecosystem: The package integrates natively with Laravel’s:
    • Service Container: Bind the client to the container via the Laravel wrapper or manually.
    • Configuration: Use Laravel’s .env for API keys (e.g., ANTHROPIC_API_KEY) and config files for base URIs/timeouts.
    • Queues/Jobs: Stream responses or batch processing can be offloaded to Laravel queues for async handling.
  • HTTP Middleware: Laravel’s middleware pipeline can intercept requests (e.g., logging, retries) before they reach the Anthropic API.
  • Testing: The built-in ClientFake enables unit testing without external dependencies, aligning with Laravel’s testing tools (e.g., Http facade mocking).

Technical Risk

  • PHP 8.2+ Requirement: Laravel 10+ (PHP 8.1+) or 11+ (PHP 8.2+) are required. Downgrading PHP or using older Laravel versions may necessitate polyfills or custom patches.
  • Beta Features: Features like the Files API or betas parameter may introduce instability if Anthropic’s backend changes. Monitor the changelog for deprecations.
  • Rate Limits: Laravel’s caching layer (e.g., Redis) can store rate limit metadata ($response->meta()) to avoid redundant API calls, but this requires custom logic.
  • Streaming Complexity: Streaming responses (e.g., createStreamed) may conflict with Laravel’s request lifecycle (e.g., middleware, middleware groups). Use Laravel’s SynchronousQueue or custom event listeners to handle streams.

Key Questions

  1. API Key Management:

    • How will API keys be stored/rotated? Use Laravel’s env() or a secrets manager (e.g., AWS Secrets Manager)?
    • Should the key be scoped per environment (e.g., ANTHROPIC_API_KEY_STAGING)?
  2. Error Handling:

    • Will custom exceptions (e.g., Anthropic\Exceptions\RateLimitExceeded) be mapped to Laravel’s Illuminate\Support\Facades\Response for consistent HTTP error responses?
    • Should retries be implemented via Laravel’s Illuminate\Support\Facades\Retry or a custom decorator?
  3. Performance:

    • For high-throughput applications (e.g., batch processing), will the PSR-18 client (e.g., Guzzle) need tuning (e.g., connection pooling, timeouts)?
    • How will token usage ($response->usage) be logged/audited? Integrate with Laravel’s logging or a dedicated observability tool (e.g., Datadog)?
  4. Security:

    • Are there sensitive operations (e.g., tool use with server_tool_use) that require additional validation? Use Laravel’s policy system or middleware.
    • Should API requests be signed (e.g., HMAC) for internal services? Extend the Anthropic\Client with custom middleware.
  5. Monitoring:

    • How will API usage (e.g., tokens, errors) be monitored? Use Laravel’s telemetry package or integrate with Prometheus via laravel-prometheus.
    • Should slow responses (e.g., streaming timeouts) trigger alerts? Use Laravel’s queue:failed events or a dedicated monitoring tool.

Integration Approach

Stack Fit

  • Laravel Core:

    • Service Container: Register the client via the Laravel wrapper’s service provider or manually:
      $this->app->singleton(AnthropicClient::class, function ($app) {
          return Anthropic::client(config('services.anthropic.api_key'));
      });
      
    • Configuration: Define settings in config/services.php:
      'anthropic' => [
          'api_key' => env('ANTHROPIC_API_KEY'),
          'base_uri' => env('ANTHROPIC_BASE_URI', 'https://api.anthropic.com/v1'),
          'timeout' => env('ANTHROPIC_TIMEOUT', 30),
      ],
      
    • Facades: Use the Laravel wrapper’s facade (Anthropic::client()) or create a custom facade for brevity.
  • HTTP Client:

    • Laravel’s HttpClient (PSR-18 compliant) is auto-discovered by mozex/anthropic-php. No additional setup is needed unless using a custom client (e.g., Symfony’s HttpClient).
    • For advanced use cases (e.g., retries, logging), wrap the client in a Laravel middleware:
      $client = new \Anthropic\Client(
          config('services.anthropic.api_key'),
          new \GuzzleHttp\Client(['timeout' => config('services.anthropic.timeout')])
      );
      
  • Queues:

    • Offload non-blocking operations (e.g., batch processing, file uploads) to Laravel queues:
      dispatch(new UploadFileJob($filePath))->onQueue('anthropic');
      

Migration Path

  1. Evaluation Phase:

    • Install the package in a staging environment:
      composer require mozex/anthropic-php mozex/anthropic-laravel
      
    • Test basic functionality (e.g., messages()->create()) with the ClientFake for unit tests.
    • Benchmark performance (e.g., response times, token usage) against direct API calls.
  2. Incremental Rollout:

    • Start with read-only operations (e.g., model listings, file metadata) to validate integration.
    • Gradually introduce write operations (e.g., message creation, file uploads) with feature flags.
    • Use Laravel’s config('app.debug') to toggle Anthropic features during development.
  3. Deprecation Strategy:

    • If replacing an existing AI service (e.g., OpenAI), use Laravel’s config('services.anthropic.enabled') to toggle between old/new implementations.
    • Maintain backward compatibility for custom logic (e.g., tool use handlers) via interfaces or abstract classes.

Compatibility

  • Laravel Versions:
    • Tested with Laravel 10+ (PHP 8.1+) and 11+ (PHP 8.2+). For Laravel 9, use PHP 8.1 with a patched version of the package.
  • Dependencies:
    • Conflicts: None critical. Resolve minor version mismatches (e.g., Guzzle) via Composer’s conflict-resolution or platform-check.
    • Overrides: If using a custom HTTP client (e.g., Symfony’s), ensure it’s PSR-18 compliant.
  • Database:
    • Store Anthropic-specific data (e.g., file IDs, tool use results) in Laravel migrations. Example:
      Schema::create('anthropic_files', function (Blueprint $table) {
          $table->id();
          $table->string('file_id')->unique();
          $table->string('purpose')->comment('e.g., "document", "code_output"');
          $table->timestamps();
      });
      

Sequencing

  1. Core Setup:

    • Install packages and configure Laravel bindings.
    • Set up API key management (e.g., .env, secrets manager).
  2. Basic Functionality:

    • Implement message creation/streaming in a controller or command.
    • Add error handling (e.g., try-catch blocks for AnthropicException).
  3. Advanced Features:

    • Integrate tool use with Laravel’s job system (e.g., HandleToolUseJob).
    • Implement file uploads/downloads with Laravel’s filesystem (e.g., Storage::disk('anthropic')->put()).
  4. Observability:

    • Add logging for API calls (e.g., Monolog channel).
    • Instrument with metrics (e.g., tokens used, latency) via Laravel’s telemetry.
  5. Security:

    • Restrict API key exposure (e.g., environment variables, IAM roles).
    • Validate tool use inputs/outputs with Laravel’s validation rules.

Operational Impact

Maintenance

  • Dependency Updates:
    • Monitor mozex/anthropic-php for breaking changes via GitHub releases or
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor