PHP Luminova: Anthropic AI Agent Integration
Use the Anthropic agent for Claude messages, vision, web search, and batch operations.
The Luminova Anthropic agent (Luminova\AI\Agents\Anthropic) provides access to the Anthropic Messages API, supporting single and multi-turn conversations, vision, web search, and large-scale asynchronous batch processing with the Claude model family. It does not support custom model creation or fine-tuning.
This guide covers Anthropic-specific methods and usage within Luminova.
For shared AI features and agent implementation, see: Base AI Agent (Luminova\Base\AbstractAiAgent)
To get started, create an API key and review the docs:https://docs.anthropic.com/en/api
Usages
Instantiation
use Luminova\AI\Agents\Anthropic;
$agent = new Anthropic(apiKey: (string) env('ANTHROPIC_API_KEY'));
$agent->setModel('claude-sonnet-4-6');With a Specific API Version
$agent = new Anthropic(
apiKey: env('ANTHROPIC_API_KEY'),
version: '2023-06-01', // Optional, defaults to 2023-06-01
);With Beta Features Enabled
$agent = new Anthropic(
apiKey: env('ANTHROPIC_API_KEY'),
betaFeatures: 'interleaved-thinking-2025-05-14',
);Via Application Config
Set handler = 'Anthropic' in App\Config\AI and use the Agent proxy:
use Luminova\AI\Agent;
$reply = Agent::message('Hello from Claude!');Beta Features
Enable or disable Anthropic beta feature flags at runtime. Multiple flags are comma-separated.
$agent->setBetaFeatures('interleaved-thinking-2025-05-14');
$reply = $agent->message('Reason step by step: what is 17 × 43?');Clear Beta Features
$agent->setBetaFeatures(null);Text Generation
Single Message
$reply = $agent->message('Summarize the Stoic philosophy in two sentences.');
echo $reply[0]['text'] ?? '';Chat Completion (Multi-Turn)
$reply = $agent->chat([
['role' => 'system', 'content' => 'You are a concise Python tutor.'],
['role' => 'user', 'content' => 'What is a list comprehension?'],
['role' => 'assistant', 'content' => 'A compact way to create lists using a single line...'],
['role' => 'user', 'content' => 'Show me a practical example.'],
]);
echo $reply[0]['text'] ?? '';With Explicit Options
$reply = $agent->chat('Write a limerick about APIs.', [
'model' => 'claude-sonnet-4-6',
'max_tokens' => 256,
'temperature' => 0.9,
]);With a System Prompt via Options
$reply = $agent->chat(
[['role' => 'user', 'content' => 'Who are you?']],
['system' => 'You are Lumi, a helpful Luminova assistant.']
);Note:
Anthropic does not accept
systemas part of the messages array.The agent extracts it automatically from the messages and moves it to the request body.
Web Search
Anthropic's web search tool lets Claude retrieve live information from the web before answering.
$results = $agent->webSearch('Latest Claude model releases');
print_r($results);With Domain Filtering and Location Context
$results = $agent->webSearch('Current ringgit exchange rate', [
'allowed_domains' => ['bnm.gov.my', 'xe.com'],
'user_location' => [
'type' => 'approximate',
'city' => 'Kuala Lumpur',
'country' => 'MY',
'timezone' => 'Asia/Kuala_Lumpur',
],
'max_uses' => 3,
]);Restrict with Blocked Domains
$results = $agent->webSearch('PHP security best practices', [
'blocked_domains' => ['w3schools.com'],
]);Use the Older ZDR-Eligible Tool Version
$results = $agent->webSearch('Open source licenses compared', [
'search_tool' => 'web_search_20250305',
]);Vision (Image Understanding)
Analyze an Image by URL
$content = $agent->vision(
'Describe what you see in this image.',
'https://upload.wikimedia.org/wikipedia/commons/a/a7/Camponotus_flavomarginatus_ant.jpg'
);
echo $content[0]['text'] ?? '';Analyze a Local File
$content = $agent->vision(
'Is there any text in this screenshot? If so, transcribe it.',
'/tmp/screenshot.png',
['model' => 'claude-sonnet-4-6']
);
echo $content[0]['text'] ?? '';Compare Multiple Images
$content = $agent->vision(
'Which of these two logos is more recognizable and why?',
[
'https://example.com/logo-a.png',
'https://example.com/logo-b.png',
]
);Supported image formats:
jpeg,png,gif,webp. Local files are base64-encoded automatically.
Batch Processing
The Message Batches API processes large volumes of requests asynchronously at 50% of the standard per-token cost. Each item in the request array must have a custom_id and a params object matching the standard Messages API body.
Submitting a Batch
$batch = $agent->batch([
[
'custom_id' => 'req-001',
'params' => [
'model' => 'claude-haiku-4-5-20251001',
'max_tokens' => 128,
'messages' => [['role' => 'user', 'content' => 'Translate "hello" to French.']],
],
],
[
'custom_id' => 'req-002',
'params' => [
'model' => 'claude-haiku-4-5-20251001',
'max_tokens' => 128,
'messages' => [['role' => 'user', 'content' => 'Translate "hello" to Spanish.']],
],
],
]);
$batchId = $batch['id'];
echo 'Batch submitted: ' . $batchId;Polling Batch Status
Poll until processing_status is 'ended':
do {
$status = $agent->batchStatus($batchId);
echo 'Status: ' . $status['processing_status'] . PHP_EOL;
sleep(5);
} while ($status['processing_status'] === 'in_progress');
echo 'Results available at: ' . $status['results_url'];Cancelling a Batch
$result = $agent->cancelBatch('msgbatch_abc123');
echo 'Cancellation requested. Status: ' . $result['processing_status'];Listing Models
$models = $agent->models();
foreach ($models as $model) {
echo $model['id'] . PHP_EOL;
}Get a Specific Model
$info = $agent->model('claude-sonnet-4-6');
print_r($info);Error Handling
use Luminova\Exceptions\AIAgentException;
try {
$reply = $agent->message('Hello!');
} catch (AIAgentException $e) {
echo 'Anthropic Error: ' . $e->getMessage();
}Class Definition
- Full namespace:
Luminova\AI\Agents\Anthropic - This class extends Luminova\Base\AbstractAiAgent
- Inherited interfaces include AIAgentInterface and LazyObjectInterface.
Properties
endpoints
Anthropic API endpoints.
/**
* @var array<string, string>
*/
protected array $endpoints = [
'messages' => 'messages',
'models' => 'models',
'batches' => 'messages/batches',
];Methods
The Base AI Agent reference documents the shared constructor hook, request options, and provider method contracts. The sections below describe the behavior specific to this agent.
__construct
Create a new Anthropic AI agent instance.
public function __construct(
?string $baseUrl = null,
?string $apiKey = null,
?string $headerVersion = null,
?string $betaFeatures = null
)Parameters:
| Parameter | Type | Description |
|---|---|---|
$baseUrl | string|null | Override the provider base URL. Defaults to null, which uses the provider URL and configured version. |
$apiKey | string|null | Anthropic secret API key (sk-ant-…). |
$version | string | API version header value (default: 2023-06-01 current stable). |
$betaFeatures | string|null | Optional comma-separated beta feature flags sent via anthropic-beta header.(e.g, 'interleaved-thinking-2025-05-14'). |
Example:
Basic usage:
$agent = new Anthropic(apiKey: (string) env('ANTHROPIC_API_KEY'));
$agent->setModel('claude-sonnet-4-6');
$reply = $agent->message('Hello, Anthropic!');With beta features enabled:
$agent = new Anthropic(
apiKey: env('ANTHROPIC_API_KEY'),
betaFeatures: 'interleaved-thinking-2025-05-14',
);
$reply = $agent->message('Reason carefully: what is 17 × 43?');
App\Config\AI- For default application AI configuration.
setBetaFeatures
Enable one or more Anthropic beta features for all subsequent requests.
Sets the anthropic-beta request header. Multiple flags can be passed as a comma-separated string. Passing null clears any active flags.
public function setBetaFeatures(?string $features = null): staticParameters:
| Parameter | Type | Description |
|---|---|---|
$features | string|null | Comma-separated beta feature flag(s), ornull to disable beta headers. |
batch
Submit a batch of message requests for asynchronous processing.
The Message Batches API processes large volumes of requests at 50% of the standard per-token cost.Each item in $requests must be a ['custom_id' => string, 'params' => array] entry where params follows the standard Messages API body shape.
public function batch(array $requests, array $options = []): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$requests | array<int, array<string, mixed>> | Batch items. |
$options | array<array-key, mixed> | Optional additional request parameters. |
Return:
array<array-key, mixed> - Batch creation response containing id, processing_status,request_counts, created_at, expires_at, and more.
Throws:
- Luminova\Exceptions\RuntimeException - On network or provider request errors.
- Luminova\Exceptions\JsonException - On malformed JSON in the response.
batchStatus
Poll the processing status of a message batch.
public function batchStatus(string $batchId): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$batchId | string | Batch ID returned by batch(). |
Return:
array<array-key, mixed> - Batch status object. Key processing_status is either 'in_progress' or 'ended'. When 'ended', retrieve results via the results_url field or the Anthropic console.
Throws:
- Luminova\Exceptions\RuntimeException - On network or provider request errors.
cancelBatch
Cancel an in-progress message batch.
public function cancelBatch(string $batchId): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$batchId | string | Batch ID to cancel. |
Return:
array<array-key, mixed> - Updated batch object (processing_status will become 'ended' once cancellation is complete).
Throws:
- Luminova\Exceptions\RuntimeException - On network or provider request errors.
chat
Send a chat request. If the options do not already define system, the first system message is moved into that option. A supplied user identifier becomes metadata.user_id.
public function chat(array|string $messages, array $options = []): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$messages | string\|array<string,mixed>\|array<int,array<string,mixed>> | Prompt, single message, or conversation history. |
$options | array<string,mixed> | Provider request options. |
Return:
array<int,array<string,mixed>> - Returns the response content blocks, or an empty array when the response has no content.
webSearch
Attach the web search tool and send a chat request. The tool supports a maximum-use limit, allowed or blocked domains, and a user location.
public function webSearch(string $query, array $options = []): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$query | string | Search prompt. |
$options | array<string,mixed> | Provider request options. |
Return:
array<array-key,mixed> - Returns the provider’s search response data.
resolveConstructorArgs
Read the base URL, API key, API version header, and beta feature flags from the application AI configuration.
public static function resolveConstructorArgs(AI $config): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$config | App\Config\AI | Application AI configuration. |
Return:
array<int,mixed> - Returns the values in the order expected by the agent constructor.