Search by

idpromogroup / laravel-anthropic

iljainc

Laravel package for Anthropic Claude Messages API with the same public contract as laravel-openai-responses

Package info

github.com/iljainc/laravel-anthropic

pkg:composer/idpromogroup/laravel-anthropic

Statistics

Installs: 0

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

dev-main 2026-09-09 14:31 UTC

This package is auto-updated.

Last update: 2026-09-09 14:35:55 UTC


README

Laravel-пакет для Claude Messages API. Публичные классы: LaService, Result, фасад La. Методы те же, что у LOR.

Installation

composer require idpromogroup/laravel-anthropic
php artisan vendor:publish --provider="Idpromogroup\LaravelAnthropic\LaravelAnthropicServiceProvider"

В .env:

ANTHROPIC_API_KEY=sk-ant-...

Usage

use Idpromogroup\LaravelAnthropic\Services\LaService;

$service = new LaService($externalKey, 'Your message here');
$result = $service->setModel('claude-haiku-4-5')
    ->setInstructions('You are a helpful assistant')
    ->execute();

if ($result->success) {
    echo $result->getMsg();
}

Files

JPG, PNG, WEBP и PDF. Файл уходит в Messages API как base64 (image / document).

$service = new LaService($externalKey, 'Analyze this document')
    ->setModel('claude-sonnet-5')
    ->attachLocalFile(storage_path('app/documents/report.pdf'));

$result = $service->execute();

Templates

$service = new LaService($externalKey, 'Your message')
    ->useTemplate('analysis_template')
    ->execute();

Conversation

История хранится локально (у Anthropic нет Conversations API) и подставляется в messages.

$service = new LaService($externalKey, 'Hello')
    ->setConversation('user123')
    ->execute();

$service = new LaService($externalKey, 'Follow up question')
    ->setConversation('user123')
    ->execute();

Function calls

setTools() принимает тот же OpenAI-shape, пакет конвертирует его в Anthropic input_schema.

'function_handler' => App\Services\MyFunctionHandler::class,
class MyFunctionHandler
{
    public function execute(string $functionName, array $args)
    {
        switch ($functionName) {
            case 'get_weather':
                return $this->getWeather($args['location']);
            default:
                return ['error' => 'Unknown function'];
        }
    }
}

Advanced

$service = new LaService($externalKey, 'Your message')
    ->setModel('claude-sonnet-5')
    ->setInstructions('Custom instructions')
    ->setTemperature(0.7)
    ->setTools([
        ['type' => 'function', 'function' => [...]]
    ])
    ->setJSONSchema([
        'type' => 'object',
        'properties' => [...]
    ])
    ->execute();

У моделей Claude 4.7+ / Sonnet 5 / Opus 5 параметр temperature часто отвергается API (кроме 1.0). Если не вызывать setTemperature(), поле не отправляется.

Models and pricing

Цены Claude API, USD за 1M токенов. Источник: Pricing, Models overview (сентябрь 2026).

Model ID Input Cache read Output
claude-fable-5-1 $10 $0.25 $50
claude-mythos-5-1 $10 $0.25 $50
claude-opus-5 $5 $0.50 $25
claude-sonnet-5 $2 $0.20 $10
claude-haiku-4-5 $1 $0.10 $5
claude-fable-5 $10 $1.00 $50
claude-mythos-5 $10 $1.00 $50
claude-opus-4-8 $5 $0.50 $25
claude-opus-4-7 $5 $0.50 $25
claude-opus-4-6 $5 $0.50 $25
claude-opus-4-5 $5 $0.50 $25
claude-sonnet-4-6 $3 $0.30 $15
claude-sonnet-4-5 $3 $0.30 $15

Алиас Haiku: claude-haiku-4-5claude-haiku-4-5-20251001. По умолчанию используется claude-haiku-4-5.

Полная таблица (включая 5m cache writes) — в config/laravel-anthropic.php.

Usage and cost tracking

После каждого успешного вызова /v1/messages токены и оценка USD пишутся в la_request_logs. Cache read → cached_input_*, cache write 5m учитывается в input_cost.

  • Выключить: LARAVEL_ANTHROPIC_BILLING=false
  • Если модель не найдена в prices, токены сохраняются, cost остаётся null
$service->setBillingContext(billingSourceCode: 0, billingUser: 42)
    ->setApiKey($userAnthropicKey)
    ->execute();
use Idpromogroup\LaravelAnthropic\Facades\La;

$sum = La::usage()
    ->forExternalKey($externalKey)
    ->betweenDates(now()->startOfMonth(), now())
    ->whereNotNull('total_cost')
    ->sum('total_cost');

License

MIT License