Luminova Framework

PHP Luminova: Build Custom AI Agents

Last updated: 2026-11-28 20:57:12

Extend the shared AI agent class to integrate a custom provider with Luminova’s request options, HTTP helpers, and agent registry.

The AI's Agent Abstract Class is a base for implementing an agent for an AI provider. Your subclass defines the provider-specific behavior and can reuse the base class’s helpers for managing options, building requests, parsing responses, and resolving models.


Configuration

Configure default AI agents and behavior via AI Agent Configuration.


Available Agents

Luminova ships with ready-to-use AI agent classes that extend the base:

  • OpenAI Agent – Text generation, embeddings, images, TTS, audio, and fine-tuning via the OpenAI API.
  • Ollama Agent – Local or remote open-source model support via the Ollama API.
  • Anthropic Agent – Claude model family including batch processing via the Anthropic API.

Integrations

This guide explains how to create a custom AI agent that integrates natively with the Luminova AI system. By extending Luminova\Base\AbstractAiAgent and providing the required chat() and vision() implementations, your agent becomes usable anywhere the built-in OpenAI, Ollama, or Anthropic agents are used, including the Agent proxy and registry.


Architecture Overview

The Luminova AI stack has three layers:

AIAgentInterface          ← Contract: defines every public method
       ↑
Luminova\Base\AbstractAiAgent           ← Abstract base: shared HTTP, options, parsing utilities
       ↑
App\AI\Agent\ExampleAgent     ← Concrete: provider-specific request/response logic

Your agent only needs to handle what the provider's API actually does differently. Everything else like option merging, model resolution, user injection, error normalization, endpoint URL building, fluent chaining is already implemented in the base class and inherited for free.


Create the Agent Class

Extend Luminova\Base\AbstractAiAgent, set $baseUrl, and map the endpoints your agent calls in $endpoints. The abstract example shows the setup. The complete example below implements the two required methods.

// /app/AI/Agent/ExampleAgent.php

namespace App\AI\Agent;

use Luminova\Base\AbstractAiAgent;

abstract class ExampleAgent extends AbstractAiAgent
{
    /**
     * Base API URL for ExampleAgent.
     * Must end with a trailing slash.
     */
    protected string $baseUrl = 'https://api.example.com/v1/';

    /**
     * Named endpoint map.
     * Keys are logical names used when calling $this->endpoint().
     * Values are the URL path segments relative to $baseUrl.
     */
    /**
     * @var array<string, string>
     */
    protected array $endpoints = [
        'chat'       => 'chat/completions',
        'models'     => 'models',
        'embeddings' => 'embeddings',
    ];

    public function __construct(string $apiKey)
    {
        parent::__construct(apiKey: $apiKey);
    }
}

The endpoint() helper appends the named path to $baseUrl, followed by a slash and the optional suffix.

$endpoints is an associative map of logical names to URL path segments.Add an entry for every endpoint your agent calls.Endpoint names are arbitrary, just be consistent with what you pass to $this->endpoint().


Understand What the Base Provides

Before overriding anything, be aware of what Luminova\Base\AbstractAiAgent already does for you. You only need to override what the base default behavior does not cover.

MethodBase behaviorOverride when
generate()Delegates to message()Your API has a dedicated completion endpoint
message()Calls chat(['role'=>'user','content'=>$prompt])Rarely needed
chat()Required by the interfaceImplement for every concrete agent
vision()Required by the interfaceImplement the provider’s vision request or report that it is unavailable
embed()Returns []Provider supports embeddings
image()Returns falseProvider supports image generation
speech()Returns falseProvider supports TTS
audio()Returns falseProvider supports audio transcription
webSearch()Returns []Provider supports web search
models()Calls fetchModel()Only if your models endpoint differs
model()Calls fetchModel($name)Only if your model detail endpoint differs
fineTune()Returns []Provider supports fine-tuning
fineTuneDataset()Returns []Provider supports fine-tuning
fineTuneStatus()Returns []Provider supports fine-tuning
setBaseUrl()Updates $this->baseUrlUse the inherited implementation
setModel()Updates $this->modelUse the inherited implementation
user()Updates $this->user + optionsUse the inherited implementation

Implement Agent Method Logic

Agent methods should follow a consistent structure by using the helpers provided in the base class. This ensures predictable behavior across all AI agents.

public function chat(array|string $messages, array $options = []): array
{
    // Build full endpoint URL
    $url = $this->endpoint(
        'chat',
        suffix: '' // Optional URI suffix
    );

    // Normalize string input as required via provider
    if (is_string($messages)) {
        $messages = [['role' => 'user', 'content' => $messages]];
    } elseif (isset($messages['role'])) {
        $messages = [$messages];
    }

    // Attach messages payload as needed
    $options['messages'] = $messages;

    // Merge caller options with instance defaults ($this->model, $this->user, etc.)
    // Keep options() and clearOptions() consistent with the request payload.
    $this->parseOptions($options);

    $finalOption = ['body' => $this->options];

    // Attach custom headers if defined
    if ($this->headers) {
        $finalOption['headers'] = $this->headers;
    }

    // Send API HTTP request
    $res = $this->send(
        'POST',         // HTTP method
        $url,           // Full API URL
        $finalOption    // Full HTTP client options
    );

    // Normalize the response for the provider if needed.
    return $res;
}

Key helpers available inside any method

HelperPurpose
$this->endpoint('chat')Builds the full URL using $this->baseUrl, endpoint mapping, and optional suffix
$this->parseOptions()Merges input options with defaults and injects model/user if missing
$this->send()Sends the HTTP request and returns a decoded response
$this->toResponse()Decodes JSON and NDJSON and normalizes API error payloads
$this->errorHandler()Normalizes exceptions into AIAgentException (keeps LuminovaException unchanged)
$this->headersPer-request headers
$this->optionsAccumulated request options (populated by parseOptions())
$this->modelDefault model set via setModel()
$this->httpThe underlying HTTP client instance

Full Example Agent

Below is a complete, realistic custom agent for a fictional provider called ExampleAgent.

// /app/AI/Agent/ExampleAgent.php

namespace App\AI\Agent;

use Luminova\Base\AbstractAiAgent;

class ExampleAgent extends AbstractAiAgent
{
    protected string $baseUrl = 'https://api.example.com/v1/';

    /**
     * @var array<string, string>
     */
    protected array $endpoints = [
        'chat'       => 'chat/completions'
    ];

    public function __construct(
        string $apiKey,
        ?string $organization = null
    ) {
        $headers = [];

        if ($organization !== null) {
            $headers['X-Organization'] = $organization;
        }

        parent::__construct(apiKey: $apiKey, headers: $headers);
    }

    public function chat(array|string $messages, array $options = []): array
    {
        $url = $this->endpoint('chat');

        if (is_string($messages)) {
            $messages = [['role' => 'user', 'content' => $messages]];
        } elseif (isset($messages['role'])) {
            $messages = [$messages];
        }

        $options['messages'] = $messages;
        $options['model']  ??= $this->model ?? 'my-chat-model';

        $this->parseOptions($options);
        $finalOption = ['body' => $this->options];

        if ($this->headers) {
            $finalOption['headers'] = $this->headers;
        }

        $res = $this->send('POST', $url, $finalOption);

        if (isset($res['error'])) {
            throw new \Luminova\Exceptions\AIAgentException($res['message'], $res['error']);
        }

        return $res['choices'][0]['message'] ?? [];
    }

    public function vision(string $prompt, string|array $images, array $options = []): array
    {
        throw new \Luminova\Exceptions\RuntimeException('ExampleAgent only supports text chat.');
    }
}

Use the Agent Directly

use App\AI\Agent\ExampleAgent;

$agent = new ExampleAgent((string) env('MY_AI_AGENT_KEY'));
$reply  = $agent->message('Hello from ExampleAgent!');

Register a Named Agent

use Luminova\AI\Agent;
use App\AI\Agent\ExampleAgent;

// Register a live instance
Agent::register('exampleAgent', new ExampleAgent(env('MY_AI_AGENT_KEY')));

// Access via static magic call
$reply = Agent::ExampleAgent()->message('Hello!');

// Or via Agent::with()
$reply = Agent::with('exampleAgent')->message('Hello!');

Use the Shared Agent Proxy

use Luminova\AI\Agent;
use App\AI\Agent\ExampleAgent;

Agent::create(new ExampleAgent(env('MY_AI_AGENT_KEY')))
    ->message('Using ExampleAgent on the singleton.');

As the App Default (Config)

To make your agent the application-wide default register it during application setup before the first call to the agent proxy.

use Luminova\AI\Agent;
use App\AI\Agent\ExampleAgent;

Agent::register(
    'exampleAgent', 
    new ExampleAgent(env('MY_AI_AGENT_KEY'))
);

Then in App\Config\AI:

// /app/Config/AI.php

public string $handler = 'exampleAgent';

Common Mistakes

Not calling parseOptions() before send()

Without this call, $this->model, $this->user, and previously set options will not be merged into the request body.

// Wrong — skips model/user injection
$this->options = $options;
$res = $this->send('POST', $url, ['body' => $this->options]);

// Correct
$this->parseOptions($options);
$res = $this->send('POST', $url, ['body' => $this->options]);

Not normalizing string input in chat()

The interface contract allows chat() to receive a plain string, a single message array, or a full messages array. All three must be handled.

if (is_string($messages)) {
    $messages = [['role' => 'user', 'content' => $messages]];
} elseif (isset($messages['role'])) {
    $messages = [$messages];
}

Returning raw agent response instead of a content array

For a custom chat() implementation, extract the reply from the agent response so callers can work directly with the message.

// Wrong — exposes agent-specific structure
return $res;

// Correct — extract and return the content
return $res['choices'][0]['message'] ?? [];

Class Definition

Properties

Options Property

Request options keyed by option name. parseOptions() merges the options for each request into this map.

/**
 * @var array<string, mixed>
 */
protected array $options = [];

Headers Property

HTTP request headers keyed by header name. The constructor initializes this map, and header() or headers() can update it.

/**
 * @var array<string, mixed>
 */
protected array $headers = [];

http

HTTP client instance typed as Psr\Http\Client\ClientInterface. A replacement HTTP client needs to provide request() and getConfig() for the base request and header helpers.

protected ?ClientInterface $http = null;

baseUrl

Base URL for the AI agent provider API.

protected string $baseUrl = '';

apiKey

API key provided to the constructor.

protected ?string $apiKey = null;

endpoints

Maps endpoint names to paths relative to $baseUrl. For example, endpoint('chat') looks up the path under the chat key.

/**
 * @var array<string, string>
 */
protected array $endpoints = [];

Model Property

Default model used when none is specified per-request.

protected ?string $model = null;

User Property

Default user ID used when none is specified per-request.

protected string|int $user = '';

Methods

__construct

Create an agent and initialize the configured HTTP client.

The constructor sets Content-Type: application/json and adds a Bearer authorization header for a nonempty API key. Custom headers can replace either default.

public function __construct(
    ?string $baseUrl = null,
    ?string $apiKey = null,
    array $headers = [],
    bool $initHttpClient = true
)

Parameters:

ParameterTypeDescription
$baseUrlstring\|nullAPI base URL (default null, which retains the subclass URL).
$apiKeystring\|nullAPI key (default null).
$headersarray<string, string>Additional or replacement headers (default []).
$initHttpClientboolInitialize the HTTP client immediately (default true).

__call

Dynamically set a request option using a fluent method call.

Any undefined method invoked on the instance will be treated as anoption name and stored in the default request options.

public function __call(string $name, array $arguments): self

Parameters:

ParameterTypeDescription
$namestringThe option name being set.
$argumentsarray<array-key, mixed>The first argument supplies the option value.

Return:

self - Returns the current instance.


fetchModel

Retrieve available models or details for a specific model.

This method adapts the request based on the AI agent implementation.Standard providers (such as OpenAI or compatible APIs) use a GETrequest to list models or retrieve a specific model by name.

When $name is null, a list of available models is returned.When $name is provided, details for the specified model are returned.

protected function fetchModel(?string $name = null): array

Parameters:

ParameterTypeDescription
$namestring|nullModel name (default null, which lists available models).

Return:

array<array-key,mixed> - Returns an array of models when $name is null,otherwise returns the model details.

Throws:

See Also:


getHeaders

Retrieve the configured headers after the HTTP client has been initialized. If that configuration is empty, the method returns the agent’s current header map.

public function getHeaders(): array

Return:

array<string,mixed> - Return an associative array of HTTP headers.


header

Set an API request header for the agent.

public function header(string $name, mixed $value): self

Parameters:

ParameterTypeDescription
$namestringThe header name.
$valuemixedThe header value.

Return:

self - Returns the current instance.


headers

Set multiple API request headers for the agent at once.

public function headers(array $headers): self

Parameters:

ParameterTypeDescription
$headersarray<string, mixed>The array headers key-value.

Return:

self - Returns the current instance.

Note:Matching header names are replaced. Other headers are retained.


option

Explicitly set a request option.

This method provides a direct and IDE-friendly way to definerequest parameters when the option name is dynamic or whenavoiding the magic method.

public function option(string $name, mixed $value): self

Parameters:

ParameterTypeDescription
$namestringThe option name.
$valuemixedThe request option value. Pass a string when setting options through this method.

Return:

self - Returns the current instance.


options

Retrieve all AI request options.

public function options(): array

Return:

array<string,mixed> - Returns the current AI agent options.


clearOptions

Clear all AI agent options.

Use this before reusing the agent to reset accumulated options to an empty user value and the configured model or luminova. A later request can restore the user previously set by user().

public function clearOptions(): self

Return:

self - Returns the current instance.


clearHeaders

Clear all custom API request headers.

This ensures headers are cleared before reusing same object.

public function clearHeaders(): self

Return:

self - Returns the current instance.

See Also:


setBaseUrl

Set the agent's API base URL.

Use this to target a self-hosted or proxied endpoint. The method normalizes the URL to a single trailing slash.

public function setBaseUrl(string $url): static

Parameters:

ParameterTypeDescription
$urlstringFully-qualified base URL (e.g. http://localhost:11434/api/).

Return:

static - Returns the current agent.


setModel

Set the default model for all subsequent AI requests.

When set, this model will be used unless overridden via $options['model']in individual method calls.

public function setModel(object|string $model): static

Parameters:

ParameterTypeDescription
$modelobject&#124;stringModel identifier, such as gpt-4.1-mini.

Return:

static - Returns the current agent.

Throws:


user

Set the default user ID for all subsequent AI requests.

When set, this user will be used unless overridden via $options['user']in individual method calls.

public function user(string|int $user): self

Parameters:

ParameterTypeDescription
$userstring|intThe user identifier for requests. Pass the identifier as a string.

Return:

self - Returns the current agent.


generate

Generate a text completion for a given prompt.

Sends a single prompt string and returns the generated response.The base implementation delegates to message(). A provider can override it to use a dedicated completion endpoint.

public function generate(string $prompt, array $options = []): array

Parameters:

ParameterTypeDescription
$promptstringThe input prompt to complete.
$optionsarray<string, mixed>Optional request parameters (default []).
@type string model Model identifier. Default varies by agent.
@type float temperature Sampling temperature (0–2). Default 0.7.
@type int max_tokens Maximum tokens to generate. Default 1024.
@type float top_p Nucleus sampling probability (0–1). Default 1.0.

Return:

array<array-key,mixed> - Generated completion output.

Throws:


chat

Send a chat conversation and receive a reply.

Accepts either a pre-built messages array (multi-turn) or a rawstring (treated as a single user message). All agents normalizethe input into the format their API expects.

public function chat(array|string $messages, array $options = []): array

Parameters:

ParameterTypeDescription
$messagesstring&#124;array{role:string, content:mixed, ...}&#124;list<array<string, mixed>>Single user message string, a single message
associative array (['role' => 'user', 'content' => '...']),
or a full conversation array of message objects.
$optionsarray<string, mixed>Optional request parameters (default []).
@type string model Model identifier.
@type float temperature Sampling temperature.
@type int max_tokens Maximum tokens in the reply.
@type string user End-user identifier for abuse monitoring.

Return:

array<array-key,mixed> - The assistant's reply message(s).

Throws:


message

Send a single user message and receive a reply.

Convenience wrapper around chat() for simple single-turn interactions.

public function message(string $prompt, array $options = []): array

Parameters:

ParameterTypeDescription
$promptstringThe user message to send.
$optionsarray<string, mixed>Optional request parameters (default [], see chat()).

Return:

array<array-key,mixed> - The assistant's reply message(s).

Throws:


image

The base implementation returns false. An agent can override this method to expose the provider capability described below.

Generate images or edit image from a text prompt.

Returns an array of image URLs or base64-encoded image data dependingon the response_format option, or false if the agent does notsupport image generation (e.g. Ollama).

Sends a source image (and an optional mask) together with a prompt sothe model can modify only the designated area.

public function image(string $prompt, array $options = []): array|bool

Parameters:

ParameterTypeDescription
$promptstringDescriptive text prompt for the image.
$optionsarray<string, mixed>Optional request parameters (default []).
@type string model Image model (e.g. gpt-image-1, dall-e-3).
@type string size Image dimensions (e.g. 1024x1024). Default 1024x1024.
@type string response_format Output format: url or b64_json. Default url.
@type int n Number of images to generate. Default 1.
@type array{image:string, mask?:string} edits
@type string image Absolute path to the source image (PNG, max 4 MB).
@type string mask Absolute path to the mask image (PNG, max 4 MB, transparent areas are edited).

Return:

list<array<string,mixed>>|bool - Array of image result objects, or false if unsupported.


vision

Send one or more images with a text prompt for visual analysis. Each concrete agent supplies its own implementation. The content block formats below describe Anthropic’s implementation.

It builds a multimodal user message containing image content blocks followedby the text prompt.

Each entry in $images accepts one of:

  • A URL string (https://…) — sent as {"type":"url","url":"…"}
  • An absolute local file path — base64-encoded and sent as{"type":"base64","media_type":"…","data":"…"}
  • A pre-built content block array (passed through unchanged)
public function vision(string $prompt, string|array $images, array $options = []): array

Parameters:

ParameterTypeDescription
$promptstringText instruction for the model.
$imagesstring&#124;list<string&#124;array<string, mixed>>Image URL(s), file path(s), or pre-built blocks.
$optionsarray<string, mixed>Optional request parameters (default [], see chat()).

@type string model Model identifier. Default claude-opus-4-6.
@type int max_tokens Max tokens. Default 1024.

Return:

array<array-key,mixed> - The provider-specific reply, such as Anthropic’s content array.

Throws:


embed

The base implementation returns []. An agent can override this method to expose the provider capability described below.

Generate a vector embedding for the given text input.

Embeddings are dense numeric vector representations of text, usefulfor semantic search, clustering, RAG (retrieval-augmented generation),and recommendation systems. Pass a string for a single embedding or anarray of strings for batch embeddings.

public function embed(string|array $input, array $options = []): array

Parameters:

ParameterTypeDescription
$inputstring&#124;string[]A single text string or an array of text strings.
$optionsarray<string, mixed>Optional request parameters (default []).

Return:

list<float>|list<list<float>> - Flat float array for single input, or array of float arrays for batch input.


speech

The base implementation returns false. An agent can override this method to expose the provider capability described below.

Convert text to speech and save to a local file.

Returns the public URL of the saved audio file on success.Returns false if the agent does not support TTS (e.g. Ollama).

public function speech(string $text, array $options = []): string|bool

Parameters:

ParameterTypeDescription
$textstringThe text to convert to audio.
$optionsarray<string, mixed>Optional request parameters (default []).
@type string voice Voice identifier: alloy, echo, fable, onyx, nova, shimmer. Default alloy.
@type float speed Playback speed (0.25–4.0). Default 1.0.
@type string response_format Audio format: mp3, opus, aac, flac, wav, pcm. Default mp3.
@type string path Directory path to save the audio file. Default writeable/ai/speech.
@type string symlink Optional public directory path for a symbolic link to the saved file.

Return:

string|bool - Absolute URL to the saved file, or false on failure/unsupported.


audio

The base implementation returns false. An agent can override this method to expose the provider capability described below.

Transcribe or translate audio to text.

Sends an audio file to the agent's transcription endpoint andreturns the recognized text. Returns false if the agent doesnot support audio transcription (e.g. Ollama).

public function audio(string $prompt, string $filename, array $options = []): string|bool

Parameters:

ParameterTypeDescription
$promptstringOptional context hint to guide transcription accuracy.
$filenamestringAbsolute path to the local audio file.
$optionsarray<string, mixed>Optional request parameters (default []).

@type string model Transcription model (e.g. whisper-1). Default whisper-1.
@type string language BCP-47 language code for the audio (e.g. en). Default auto-detect.
@type string response_format Output format: json, text, srt, vtt. Default json.
@type float temperature Sampling temperature. Default 0.

Return:

string|bool - Transcribed text on success, false on failure/unsupported.


models

Retrieve a list of available models.

public function models(): array

Return:

array<array-key,mixed> - Provider model list or response details.

Throws:


model

Retrieve detailed information about a specific model.

public function model(string $name): array

Parameters:

ParameterTypeDescription
$namestringModel identifier.

Return:

array<string,mixed> - Model details.

Throws:


webSearch

The base implementation returns []. An agent can override this method to expose the provider capability described below.

Perform a web search and return AI-augmented results.

The agent queries the web and returns a structured response thatmay include cited sources, snippets, or a synthesized answer.

public function webSearch(string $query, array $options = []): array

Parameters:

ParameterTypeDescription
$querystringThe search query string.
$optionsarray<string, mixed>Optional provider-specific parameters (default []).
@type string model Model identifier (OpenAI: uses built-in web_search_preview tool).
@type int limit Maximum number of results to return (Ollama-specific).

Return:

array<array-key,mixed> - Search results or AI-synthesized answer array.


fineTune

The base implementation returns []. An agent can override this method to expose the provider capability described below.

Fine-tune a model with a custom dataset.

Submits a training job to the agent using either an uploadedfile ID (OpenAI) or a raw modelfile/dataset path (Ollama). Thereturned array contains the job details, which can be polled viafineTuneStatus().

public function fineTune(string $model, string $dataset, array $options = []): array

Parameters:

ParameterTypeDescription
$modelstringSuffix or display name for the resulting fine-tuned model.
$datasetstringTraining file path, raw modelfile content, or uploaded file ID.
$optionsarray<string, mixed>Optional training parameters (default []).
@type string model Base model to fine-tune (e.g. gpt-4.1-mini, llama3).
@type int n_epochs Training epochs. Default auto.
@type string suffix Custom suffix appended to the fine-tuned model name.
@type bool auto_delete_file Automatically delete the training file after upload (default false).
@type string system System prompt to embed in the modelfile (Ollama only).

Return:

array<array-key,mixed> - Fine-tuning job response or model creation result.


fineTuneDataset

The base implementation returns []. An agent can override this method to expose the provider capability described below.

Prepare and submit a structured dataset array for fine-tuning.

Converts a high-level [input => ..., output => ...] array into theagent's native training format (JSONL for OpenAI, Modelfile for Ollama),writes it to a temporary file, and calls fineTune() automatically.

public function fineTuneDataset(array $dataset, array $options = []): array

Parameters:

ParameterTypeDescription
$datasetarray<int, array{input: string, output: string}>Training examples.
$optionsarray<string, mixed>Optional training parameters (default [], see fineTune()).

@type string suffix Suffix for the fine-tuned model name. Default fine-tuned.
@type string model Base model identifier.
@type string system System prompt (Ollama only).

Return:

array<array-key,mixed> - Fine-tuning job response (see fineTune()).


fineTuneStatus

The base implementation returns []. An agent can override this method to expose the provider capability described below.

Poll the status of a fine-tuning job.

public function fineTuneStatus(string $jobId): array

Parameters:

ParameterTypeDescription
$jobIdstringThe fine-tuning job ID returned by fineTune() or
the model name to check (Ollama).

Return:

array<array-key,mixed> - Status response. Contains at minimum a status key(queued, running, succeeded, failed for OpenAI;building or ready for Ollama).


send

Send an HTTP request to the provider API.

protected function send(string $method, string $url, array $finalOptions): array

Parameters:

ParameterTypeDescription
$methodstringThe HTTP request method.
$urlstringThe full API request URL.
$finalOptionsarray<string, mixed>HTTP client options for the provider request.

Return:

array<array-key,mixed> - Decoded provider response.

Throws:

  • Luminova\Exceptions\LuminovaException if the HTTP client throws a Luminova exception. Other failures are wrapped in AIAgentException.

resolveConstructorArgs

Define the constructor arguments used when the framework creates a shared instance of the agent. Override this public static method in a subclass that needs values from the application AI configuration.

public static function resolveConstructorArgs(AIConfig $config): array

Parameters:

ParameterTypeDescription
$configApp\Config\AIShared application AI configuration.

Return:

array<int,mixed> - Returns the positional arguments in constructor order. The base implementation returns an empty array.


endpoint

Build the full URL for a named endpoint.

protected function endpoint(string $name, string $suffix = ''): string

Parameters:

ParameterTypeDescription
$namestringThe endpoint URI name from $this->endpoints.
$suffixstringPath suffix appended after the endpoint segment (default ''), such as foo/bar.

Return:

string - Fully-qualified endpoint URL.

Throws:


toResponse

Decode the HTTP response body into an associative array.

Supports both standard JSON and newline-delimited JSON (NDJSON) streams.Automatically strips SSE-style data: prefixes and ignores empty lines.Invalid JSON lines are skipped, or optionally collected as raw entries.

protected function toResponse(ResponseInterface $res, bool $parseRaw = true): array

Parameters:

ParameterTypeDescription
$resPsr\Http\Message\ResponseInterfaceRaw HTTP response.
$parseRawboolCapture non-JSON lines under the __raw key (default true).

Return:

array{error:int, message:string, details:array<array-key,mixed>}|array<array-key,mixed> - A decoded response or list of decoded stream entries. If the response contains an API error, the method returns the following fields.

KeyTypeDescription
errorintHTTP response status code.
messagestringProvider error message or a fallback message.
detailsarray<array-key,mixed>Decoded provider response.

Throws:

  • \JsonException if JSON decoding fails.

toModelFile

Convert a structured dataset array into Modelfile directive lines.

public static function toModelFile(array $dataset): string

Recognizes three top-level keys:

  • parameters → PARAMETER name value lines
  • templates → TEMPLATE value lines
  • messages → MESSAGE role content lines

Other scalar keys are written as key value. Other array entries are written as name: value. When no template lines are supplied, the method inserts a default template.

Parameters:

ParameterTypeDescription
$datasetarray<string, mixed>Structured dataset to serialize.

Return:

string - Modelfile content string (no leading/trailing whitespace).

Throws:


parseOptions

Parse the base parameter array for an AI request.

protected function parseOptions(array $options = []): void

Merges caller options into $this->options, replacing matching keys. If the caller omits the model, the method uses $this->model or luminova. If the caller omits the user, the method inserts the instance user when it is truthy.

Parameters:

ParameterTypeDescription
$optionsarray<string, mixed>Caller-supplied options (default []).

errorHandler

Normalize and re-throw exceptions from API calls.

protected function errorHandler(Throwable $e): never

Rethrows Luminova exceptions unchanged and wraps other exceptions in AIAgentException.

Parameters:

ParameterTypeDescription
$eThrowableThe caught exception.

Return:

never - Always throws an exception.

Throws: