PHP code example of digitaldreams / local-batch-api
1. Go to this page and download the library: Download digitaldreams/local-batch-api library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
digitaldreams / local-batch-api example snippets
use BatchApi\Events\SubmitAnthropicBatchEvent;
use BatchApi\Data\Input\AnthropicBatchItemDto;
$items = [
new AnthropicBatchItemDto(
customId: 'req-1',
maxTokens: 512,
messages: [
['role' => 'user', 'content' => 'Summarise this article in one paragraph.'],
],
),
new AnthropicBatchItemDto(
customId: 'req-2',
maxTokens: 256,
messages: [
['role' => 'user', 'content' => 'What is the capital of France?'],
],
system: 'You are a geography expert.',
),
];
event(new SubmitAnthropicBatchEvent($items));
use BatchApi\BatchService;
use BatchApi\Events\SubmitOpenAiBatchEvent;
use BatchApi\Data\Input\OpenAiBatchItemDto;
$service = app(BatchService::class);
// Build items from raw JSONL or manually
$items = [
new OpenAiBatchItemDto(
customId: 'req-1',
messages: [['role' => 'user', 'content' => 'Hello']],
maxTokens: 512,
),
];
// Create a file record (mirrors OpenAI's file upload step)
$file = $service->uploadFile(
collect($items)->map(fn ($item) => json_encode([
'custom_id' => $item->customId,
'method' => 'POST',
'url' => '/v1/chat/completions',
'body' => ['messages' => $item->messages, 'max_tokens' => $item->maxTokens],
]))->implode("\n")
);
event(new SubmitOpenAiBatchEvent($file->id, $items));
// app/Listeners/HandleBatchCompletedListener.php
use BatchApi\Events\BatchCompletedEvent;
use BatchApi\Data\BatchResultDto;
class HandleBatchCompletedListener
{
public function handle(BatchCompletedEvent $event): void
{
$batch = $event->batch;
foreach ($event->results as $result) {
/** @var BatchResultDto $result */
if ($result->succeeded) {
// $result->customId — matches your request's custom_id
// $result->content — the model's response text
// $result->model — model used
// $result->inputTokens / $result->outputTokens
} else {
// $result->error — failure message
}
}
}
}
// app/Providers/AppServiceProvider.php
use BatchApi\Events\BatchCompletedEvent;
use App\Listeners\HandleBatchCompletedListener;
use Illuminate\Support\Facades\Event;
public function boot(): void
{
Event::listen(BatchCompletedEvent::class, HandleBatchCompletedListener::class);
}
use BatchApi\Facades\BatchApi;
Route::middleware('auth:sanctum')->group(function () {
BatchApi::routes();
});
// In a controller or seeder
$token = $user->createToken('batch-api-client')->plainTextToken;
// Pass this token to the HTTP client
bash
php artisan migrate
bash
php artisan queue:work
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.