mozex/anthropic-php
Unofficial PHP client for Anthropic’s Claude API. Send messages, build prompts, and work with streaming responses using a simple, framework-friendly interface. Great for adding Claude-powered chat and automation to Laravel or any PHP app.
Begin by installing the package via Composer: composer require mozex/anthropic-php. Then initialize the client in your application—Laravel users typically do this in a service provider or via a factory, while plain PHP apps can instantiate it directly. You’ll need an Anthropic API key (set via environment variable ANTHROPIC_API_KEY or pass explicitly to the constructor). The first use case is straightforward text generation: call Anthropic::messages()->create() with a model name (e.g., claude-3-5-sonnet-latest) and a message payload. The response is returned as a structured object—no manual JSON decoding needed—so you can immediately access ->content, ->usage, or ->id. Check the examples/ directory in the repo for minimal snippets.
Laravel developers commonly bind the client to a singleton in a service provider (e.g., AnthropicClient::class), injecting it into jobs, commands, or services. For chat workflows, accumulate conversation history as an array of ['role' => 'user', 'content' => '...'] messages and pass to messages()->create() with stream: true for real-time token-by-token streaming (handled via Symfony’s Http Client or Guzzle, depending on config). Use the Anthropic::withOptions([...]) helper to dynamically set headers or retry logic per request. Want to send structured output? Leverage response_format => ['type' => 'json_object']—the client automatically validates JSON in responses and throws JsonException on parse failure. Integrate with Laravel queue jobs for async inference: dispatch a job with the full conversation context and log usage metrics afterward via ->usage->input_tokens and ->usage->output_tokens.
claude-3-opus-20240229 → claude-3-5-sonnet-latest). Prefer versioned aliases or use Anthropic::latestModel() (if provided) or a config-driven constant to avoid runtime breaks.stream: true, the response is an iterable of event objects—not raw JSON—so avoid json_encode() on the stream. Use ->events() or ->each(fn ($event) => ...) for chunk processing.Client and override sendRequest().Client::withOptions(['timeout' => 60]). Track X-RateLimit-* headers manually via ->getHeaders() if your app enforces strict QPS control.'debug' => true in options—this logs full requests/responses to php://stdout. In Laravel, pipe to a logger channel with a custom middleware class.How can I help you explore Laravel packages today?