PHP Luminova: OpenAI Agent Integration
Use the OpenAI agent for responses, embeddings, image and audio operations, and file handling.
The Luminova OpenAI agent (Luminova\AI\Agents\OpenAI) wraps the OpenAI REST API and provides a clean interface for text generation, embeddings, image generation, text-to-speech, audio transcription, fine-tuning, and file management.
This guide focuses on OpenAI-specific methods and usage within Luminova.For shared AI features and agent implementation, see: Base AI Agent (Luminova\Base\AbstractAiAgent).
To get started with OpenAI, refer to the official API documentation:https://platform.openai.com/docs/api-reference
Usages
Instantiation
use Luminova\AI\Agents\OpenAI;
$agent = new OpenAI(
apiKey: env('OPENAI_KEY'),
organization: 'org-abc123', // Optional
project: 'proj-xyz', // Optional
);Via Application Config
Set handler = 'OpenAI' in App\Config\AI and use the Agent proxy:
use Luminova\AI\Agent;
$reply = Agent::message('Hello from the config-driven agent!');Text Generation
Single Message
$reply = $agent->message('Explain quantum entanglement simply.');
echo $reply[0]['content'][0]['text'] ?? '';Chat Completion (Multi-Turn)
$reply = $agent->chat([
['role' => 'system', 'content' => 'You are a helpful PHP tutor.'],
['role' => 'user', 'content' => 'What is a trait?'],
['role' => 'assistant', 'content' => 'A trait is a reusable set of methods...'],
['role' => 'user', 'content' => 'Can traits have properties?'],
]);
echo $reply[0]['content'][0]['text'] ?? '';Text Generation Options
$reply = $agent->chat('Write a haiku about the ocean.', [
'model' => 'gpt-4.1',
'max_output_tokens' => 64,
'temperature' => 0.8,
]);Text Completion (generate)
generate() delegates to message() for OpenAI:
$response = $agent->generate('List 5 PHP best practices.');
print_r($response);The agent returns the Responses API output items. For a text message item, read the text from its content blocks.
Web Search
Attach the built-in web_search_preview tool to retrieve AI-synthesised answers sourced from the live web.
$results = $agent->webSearch('Latest PHP 8.4 features');
print_r($results);Embeddings
Generate vector embeddings for semantic search, clustering, or RAG pipelines.
Single Embedding
$vector = $agent->embed('The quick brown fox');
// Returns a flat float array: [0.012, -0.034, ...]Batch Embeddings
$vectors = $agent->embed(['Hello world', 'Hi there']);
// Returns an array of float arrays
use Luminova\AI\Agent;
$similarity = Agent::compareCosineVector($vectors[0], $vectors[1]);
echo $similarity; // e.g. ~0.97Embedding Options
$vector = $agent->embed('Some text', [
'model' => 'text-embedding-3-large',
'dimensions' => 512,
]);Image Generation
Basic Generation
$images = $agent->image('A serene mountain lake at sunset, oil painting style.');
echo $images[0]['url'] ?? '';Multiple Images
$images = $agent->image('A futuristic city skyline at night, digital art.', [
'model' => 'dall-e-3',
'size' => '1024x1024',
'response_format' => 'url',
'n' => 2,
]);
foreach ($images as $img) {
echo $img['url'] . PHP_EOL;
}Image Editing (Inpainting)
Set edits to select the editing endpoint and pass the source image and optional mask as top-level options. Transparent areas in the mask will be replaced by the model.
$results = $agent->image('Replace the sky with a dramatic sunset.', [
'size' => '1024x1024',
'edits' => true,
'image' => '/path/to/original.png',
'mask' => '/path/to/mask.png',
]);
echo $results[0]['url'] ?? '';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]['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' => 'gpt-4.1']
);
echo $content[0]['content'][0]['text'] ?? '';Compare Two 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',
]
);With Detail Level
$content = $agent->vision(
'Identify any defects on this product.',
'/tmp/product.jpg',
['detail' => 'high']
);Text-to-Speech (TTS)
Converts text to audio and saves it locally. Returns the public URL of the saved file.
$url = $agent->speech('Welcome to Luminova!', [
'voice' => 'nova', // alloy, echo, fable, onyx, nova, shimmer
'speed' => 1.0,
'model' => 'gpt-4o-mini-tts',
'path' => '/var/www/html/audio', // Optional save directory
]);
echo $url; // https://example.com/audio/6789abc.mp3With Symlink (Public Serving)
$url = $agent->speech('Hello, world!', [
'symlink' => 'public/audio',
]);Audio Transcription
Transcribe audio files to text using Whisper.
$text = $agent->audio(
'Transcribe this meeting recording.',
'/tmp/meeting.mp3',
[
'model' => 'whisper-1',
'language' => 'en',
]
);
echo $text;With SRT Output
$srt = $agent->audio('', '/tmp/interview.mp3', [
'response_format' => 'srt',
]);Fine-Tuning
From a JSONL File
$job = $agent->fineTune('my-assistant', '/path/to/training.jsonl', [
'model' => 'gpt-4.1-mini',
]);
$jobId = $job['id'];
echo 'Job started: ' . $jobId;From a Structured Dataset
fineTuneDataset() handles JSONL conversion automatically.
$job = $agent->fineTuneDataset([
['input' => 'What is your name?', 'output' => 'I am Lumi.'],
['input' => 'Who made you?', 'output' => 'Nanoblock Technology Ltd.'],
], [
'suffix' => 'lumi-v1',
'model' => 'gpt-4.1-mini',
]);Checking Fine-Tune Status
$status = $agent->fineTuneStatus($job['id']);
if ($status['status'] === 'succeeded') {
$modelName = $status['fine_tuned_model'];
echo 'Model ready: ' . $modelName;
}File Management
Upload a File
$fileId = $agent->upload('/path/to/training.jsonl', 'fine-tune');
echo 'Uploaded file ID: ' . $fileId;List Files
$files = $agent->files(['purpose' => 'fine-tune']);
foreach ($files as $file) {
echo $file['id'] . ' — ' . $file['filename'] . PHP_EOL;
}Get File Metadata
$meta = $agent->file('file-abc123');
echo $meta['filename'];Download File Content
// Stream to string
$content = $agent->download('file-abc123');
// Save to disk
$ok = $agent->download('file-abc123', '/tmp/downloaded.jsonl');Delete a File
$deleted = $agent->delete('file-abc123');
var_dump($deleted); // bool(true)Listing Models
$models = $agent->models();
foreach ($models as $model) {
echo $model['id'] . PHP_EOL;
}Get a Specific Model
$info = $agent->model('gpt-4.1-mini');
print_r($info);Error Handling
use Luminova\Exceptions\AIAgentException;
try {
$reply = $agent->message('Hello!');
} catch (AIAgentException $e) {
echo 'OpenAI Error: ' . $e->getMessage();
}Class Definition
- Full namespace:
Luminova\AI\Agents\OpenAI - This class extends Luminova\Base\AbstractAiAgent
- Inherited interfaces include AIAgentInterface and LazyObjectInterface.
Properties
endpoints
OpenAI API endpoints.
/**
* @var array<string, string>
*/
protected array $endpoints = [
'responses' => 'responses',
'models' => 'models',
'images' => 'images',
'speech' => 'audio/speech',
'transcribe' => 'audio/transcriptions',
'embeddings' => 'embeddings',
'fineTune' => 'fine_tuning/jobs',
'files' => 'files',
];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 OpenAI agent instance.
public function __construct(
?string $baseUrl = null,
?string $apiKey = null,
?string $organization = null,
?string $project = 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 | OpenAI secret API key (sk-…). |
$organization | string|null | Optional organization ID (org-…). |
$project | string|null | Optional project ID. |
Example:
use Luminova\AI\Agents\OpenAI;
$agent = new OpenAI(apiKey: env('OPENAI_KEY'), organization: 'org-abc123');
$reply = $agent->message('Hello, OpenAI!');
App\Config\AIFor default application AI configuration.
upload
Upload a local file to OpenAI's file store.
public function upload(string $filename, string $purpose = 'fine-tune', array $options = []): ?stringReturns the file ID string on success, which can be used as the$dataset argument in fineTune().
Parameters:
| Parameter | Type | Description |
|---|---|---|
$filename | string | Absolute path to the local file. |
$purpose | string | Upload purpose. Accepted values: fine-tune, assistants,batch, vision. Default fine-tune. |
$options | array<array-key, mixed> | Additional request parameters. |
Return:
string|null - Uploaded file ID, or null on failure.
Throws:
- Luminova\Exceptions\RuntimeException - If the file does not exist or is empty.
Example:
$fileId = $agent->upload('/path/to/training.jsonl');
$job = $agent->fineTune('my-model', $fileId);files
List all files uploaded to the OpenAI file store.
public function files(array $options = []): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$options | array<array-key, mixed> | Optional query parameters (e.g. ['purpose' => 'fine-tune']). |
Return:
array<array-key, mixed> - Array of file objects.
Example:
$files = $agent->files(['purpose' => 'fine-tune']);
foreach ($files as $file) {
echo $file['id'] . ' — ' . $file['filename'] . PHP_EOL;
}file
Retrieve metadata for a single uploaded file.
public function file(string $fileId, array $options = []): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$fileId | string | File ID returned by upload(). |
$options | array<array-key, mixed> | Optional query parameters. |
Return:
array<array-key, mixed> - File metadata object.
Example:
$meta = $agent->file('file-abc123');
echo $meta['filename']; // training.jsonldownload
Download the raw content of an uploaded file.
public function download(string $fileId, ?string $saveTo = null): string|boolWhen $saveTo is provided, the content is written to that path andtrue is returned on success. When omitted, the raw content stringis returned directly.
Parameters:
| Parameter | Type | Description |
|---|---|---|
$fileId | string | The uploaded file ID. |
$saveTo | string|null | Optional absolute path to save the file content. |
Return:
string|bool - Raw content string, true if saved to disk, or false on failure.
Example:
// Stream to string
$content = $agent->download('file-abc123');
// Save to disk
$ok = $agent->download('file-abc123', '/tmp/downloaded.jsonl');delete
Delete an uploaded file from the OpenAI file store.
public function delete(string $fileId): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$fileId | string | File ID to delete. |
Return:
bool - Returns true if the file was successfully deleted.
Example:
$deleted = $agent->delete('file-abc123');chat
Send a request to the configured Responses endpoint. The prompt or message input becomes the input option.
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 response output items, or an empty array when the response has no output.
webSearch
Attach the web_search_preview tool and send the prompt through chat().
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, organization, and project 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.