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
## Getting Started

### Minimal Setup in Laravel
1. **Install the package** (preferably with the Laravel wrapper for easier integration):
   ```bash
   composer require mozex/anthropic-php mozex/anthropic-laravel
  1. Publish the config (if using the Laravel wrapper):
    php artisan vendor:publish --provider="Mozex\Anthropic\AnthropicServiceProvider"
    
  2. Configure .env:
    ANTHROPIC_API_KEY=your_api_key_here
    ANTHROPIC_MODEL=claude-sonnet-4-6
    
  3. First use case: Send a simple message in a controller or service:
    use Mozex\Anthropic\Facades\Anthropic;
    
    $response = Anthropic::messages()->create([
        'model' => config('anthropic.model'),
        'messages' => [
            ['role' => 'user', 'content' => 'Hello, how are you?'],
        ],
    ]);
    
    return $response->content[0]->text;
    

Key First Steps

  • Check the Laravel wrapper docs for service container integration and config options.
  • Use the facade (Anthropic::) for quick access in controllers/views.
  • Test locally with ClientFake (see Testing for examples).

Implementation Patterns

Core Workflows

1. Chatbot Integration

  • Pattern: Use messages()->create() for synchronous responses or createStreamed() for real-time UX.
  • Example:
    $stream = Anthropic::messages()->createStreamed([
        'model' => config('anthropic.model'),
        'messages' => $conversationHistory,
        'stream' => true,
    ]);
    
    foreach ($stream as $chunk) {
        if ($chunk->type === 'content_block_delta' && $chunk->delta->type === 'text_delta') {
            echo $chunk->delta->text; // Stream output to UI
        }
    }
    
  • Laravel Tip: Store conversation history in a database (e.g., conversations table) and hydrate it before each request.

2. Tool Use for Dynamic Actions

  • Pattern: Define tools in the request, handle tool calls in middleware, and return results.
  • Example:
    $response = Anthropic::messages()->create([
        'tools' => [
            ['name' => 'fetch_user_data', 'description' => 'Fetch user data by ID', 'input_schema' => [...]],
        ],
        'messages' => [['role' => 'user', 'content' => 'Get user #123 details']],
    ]);
    
    // Handle tool calls in a Laravel middleware or service
    if ($response->content[0]->type === 'tool_use') {
        $userData = User::find($response->content[0]->input['user_id']);
        return Anthropic::messages()->create([
            'messages' => [
                ['role' => 'assistant', 'content' => 'User data: ' . json_encode($userData)],
            ],
        ]);
    }
    

3. Batch Processing

  • Pattern: Use batches()->create() for parallelized requests (e.g., processing multiple user queries).
  • Example:
    $batch = Anthropic::batches()->create([
        'model' => config('anthropic.model'),
        'messages' => [
            ['role' => 'user', 'content' => 'Query 1'],
            ['role' => 'user', 'content' => 'Query 2'],
        ],
    ]);
    

4. File Handling (Beta)

  • Pattern: Upload files once and reference them in messages (e.g., for PDF analysis).
  • Example:
    // Upload
    $file = Anthropic::files()->upload(['file' => fopen('contract.pdf', 'r')]);
    
    // Reference in message
    $response = Anthropic::messages()->create([
        'betas' => ['files-api-2025-04-14'],
        'messages' => [
            ['role' => 'user', 'content' => [
                ['type' => 'text', 'text' => 'Summarize this document.'],
                ['type' => 'document', 'source' => ['type' => 'file', 'file_id' => $file->id]],
            ]],
        ],
    ]);
    

Integration Tips

  • Rate Limits: Always check $response->meta()->rateLimits to avoid throttling.
  • Error Handling: Use try-catch with Anthropic\Exceptions\AnthropicException for API errors.
  • Token Management: Use Anthropic::tokenizer() to count tokens before sending requests.
  • Caching: Cache responses for identical inputs (e.g., FAQs) using Laravel’s cache system.
  • Queue Jobs: Offload long-running requests (e.g., batch processing) to Laravel queues:
    dispatch(new ProcessAnthropicBatch($requestData));
    

Gotchas and Tips

Pitfalls

  1. Beta Features:

    • Issue: Forgetting to include betas in requests (e.g., ['files-api-2025-04-14']).
    • Fix: Use the Laravel wrapper’s config('anthropic.betas') or hardcode the latest beta from the Anthropic docs.
    • Tip: The SDK auto-injects beta headers for files() calls, but messages require manual inclusion.
  2. Streaming Quirks:

    • Issue: Missing chunks or incomplete responses in streams.
    • Fix: Always check $chunk->type and $chunk->delta->type before processing:
      if ($chunk->type === 'content_block_delta' && $chunk->delta->type === 'text_delta') {
          // Safe to process
      }
      
    • Debug: Log raw chunks to identify malformed responses:
      \Log::debug('Stream chunk:', ['chunk' => $chunk->toArray()]);
      
  3. Tool Use Loops:

    • Issue: Infinite loops when tools call other tools without proper termination.
    • Fix: Add a max_turns parameter or validate tool responses in middleware:
      if ($response->stop_reason === 'tool_use') {
          $turnCount++;
          if ($turnCount > 3) throw new \Exception('Max turns exceeded');
      }
      
  4. File API Limitations:

    • Issue: Downloaded files (via files()->download()) are only available for files generated by code execution or Skills, not user-uploaded files.
    • Fix: Store user-uploaded files in Laravel storage (storage/app/public) and reference them locally.
  5. Token Counting:

    • Issue: Unexpected token limits causing truncated responses.
    • Fix: Use Anthropic::tokenizer()->countTokens($message) to validate inputs:
      $tokenCount = Anthropic::tokenizer()->countTokens($request['messages']);
      if ($tokenCount > config('anthropic.max_input_tokens')) {
          throw new \Exception('Message too long');
      }
      

Debugging

  • Enable Debug Mode: Set ANTHROPIC_DEBUG=true in .env to log raw API requests/responses.
  • Test Client: Use ClientFake for unit tests:
    $fakeClient = new \Anthropic\Testing\ClientFake([
        \Anthropic\Responses\Messages\CreateResponse::fake([
            'content' => [['type' => 'text', 'text' => 'Test response']],
        ]),
    ]);
    $fakeClient->assertSent(\Anthropic\Resources\Messages::class, fn($method, $params) => ...);
    
  • Rate Limit Headers: Check $response->meta()->customHeaders for anthropic-rate-limit-* to debug throttling.

Extension Points

  1. Custom HTTP Clients:

    • Override the default client in the Laravel wrapper’s config:
      'http_client' => \GuzzleHttp\Client::class,
      'http_client_config' => ['timeout' => 30],
      
    • Or use the factory:
      $client = \Anthropic\Anthropic::factory()
          ->withHttpClient(new \Symfony\Contracts\HttpClient\HttpClient())
          ->make();
      
  2. Middleware for Tool Handling:

    • Create a Laravel middleware to intercept tool calls:
      public function handle($request, Closure $next) {
          $response = $next($request);
          if ($response->content[0]->type === 'tool_use') {
              $result = $this->executeTool($response->content[0]->input);
              return $this->resumeConversation($result);
          }
          return $response;
      }
      
  3. Event Listeners:

    • Dispatch events for key actions (e.g., message sent, tool used):
      event(new \Anthropic\Events\MessageSent($
      
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
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
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