PHP code example of livenetworks / ln-ai-bridge

1. Go to this page and download the library: Download livenetworks/ln-ai-bridge 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/ */

    

livenetworks / ln-ai-bridge example snippets


use LiveNetworks\LnAiBridge\Facades\AiBridge;

$request = AiBridge::prompt('Summarize the key benefits of cloud computing in 3 bullet points.')
    ->system('You are a concise technical writer.')
    ->temperature(0.5)
    ->build();

$response = AiBridge::send($request);

$response->success;   // true
$response->content;   // "• Scalability..."
$response->provider;  // "claude"
$response->model;     // "claude-sonnet-4-20250514"
$response->usage;     // ['input_tokens' => 42, 'output_tokens' => 85]
$response->error;     // null

$request = AiBridge::prompt('Write a greeting for the customer.')
    ->system('You are a helpful assistant.')
    ->context('customer_name', 'John')
    ->context('order_total', '$149.99')
    ->build();

// Use a specific provider instead of the default
$response = AiBridge::send($request, 'openai');

use LiveNetworks\LnAiBridge\Services\ConversationManager;

$cm = app(ConversationManager::class);

// Start a conversation
$conversation = $cm->startConversation(
    tenantId: 1,
    userId: 1,
    systemPrompt: 'Reply concisely and clearly.',
);

// First message
$r1 = $cm->sendMessage($conversation, 'What is ISO 27001?');

// Second message (the AI remembers context from the first)
$r2 = $cm->sendMessage($conversation, 'How many controls does it have?');

$conversation->fresh()->total_tokens;   // cumulative token usage
$conversation->fresh()->message_count;  // 4 (2 user + 2 assistant)

use LiveNetworks\LnAiBridge\DTO\Message;

$request = AiBridge::prompt('What about point 3?')
    ->system('You are a document assistant.')
    ->history([
        Message::user('Generate a security policy'),
        Message::assistant('Here is the policy with 5 key points...'),
    ])
    ->build();

$response = AiBridge::send($request);

$conversation = $cm->startConversation(
    tenantId: $tenant->id,
    userId: auth()->id(),
    systemPrompt: 'You are a document analysis assistant.',
    contextType: 'document',
    contextId: $document->id,
    title: 'Document analysis',
);

$cm = app(ConversationManager::class);

$conv = $cm->startConversation(
    tenantId: 1,
    userId: 1,
    systemPrompt: 'Reply concisely, 1-2 sentences.',
);

// Send 22 messages (11 questions × 2 = 22, exceeds threshold of 20)
$topics = [
    'What is ISO 27001?',
    'What is the difference with ISO 9001?',
    'What is the Statement of Applicability?',
    'How many controls are in Annex A?',
    'What is risk assessment?',
    'What is an ISMS?',
    'Who performs the internal audit?',
    'What is a corrective action?',
    'What is management review?',
    'What is continual improvement?',
    'What is a certification body?',
];

foreach ($topics as $topic) {
    $cm->sendMessage($conv, $topic);
}

$conv->refresh();

// Summary was automatically created
$summary = $conv->summaries()->latest()->first();
$summary->summary;          // condensed text of the conversation
$summary->messages_count;   // number of messages summarized
$summary->tokens_saved;     // tokens saved by summarizing

// Messages after summarization use: summary + last 6 messages as context
$final = $cm->sendMessage($conv, 'Of all the topics we discussed, which is most important?');
$final->content; // AI responds with full context awareness

'conversation' => [
    'summarize_threshold' => 20,  // Trigger after this many unsummarized messages
    'keep_recent'         => 6,   // Keep the last N messages unsummarized
    'summary_max_tokens'  => 500, // Max tokens for the summary response
],

$request = AiBridge::prompt()
    ->system('You are a document assistant.')
    ->prompt('What does document DOC-123 contain?')
    ->tool('get_document_content', 'Retrieves document content by ID', [
        'properties' => [
            'document_id' => ['type' => 'string', 'description' => 'The document ID'],
        ],
        '

use LiveNetworks\LnAiBridge\Contracts\ToolExecutorInterface;
use LiveNetworks\LnAiBridge\DTO\ToolCall;
use LiveNetworks\LnAiBridge\DTO\ToolResult;

class GetDocumentContentExecutor implements ToolExecutorInterface
{
    public function execute(ToolCall $call): ToolResult
    {
        $doc = Document::find($call->arguments['document_id']);

        if (!$doc) {
            return ToolResult::error($call->id, 'Document not found');
        }

        return ToolResult::success($call->id, $doc->content);
    }
}

// In AppServiceProvider::boot()
AiBridge::registerTool('get_document_content', new GetDocumentContentExecutor());

$request = AiBridge::prompt()
    ->system('You are a project assistant.')
    ->prompt('Compare the budgets of projects Alpha and Beta.')
    ->tool('get_project', 'Get project details by name', [
        'properties' => [
            'name' => ['type' => 'string', 'description' => 'Project name'],
        ],
        'e iterations — all handled automatically.
$response = AiBridge::send($request);

use LiveNetworks\LnAiBridge\Services\UsageTracker;

$tracker = app(UsageTracker::class);

$usage = $tracker->getTenantUsage(
    tenantId: 1,
    from: now()->startOfMonth(),
);

// Returns: ['input_tokens' => ..., 'output_tokens' => ..., 'total_tokens' => ..., 'request_count' => ...]

$request = AiBridge::prompt('Analyze this data.')
    ->meta('tenant_id', $tenant->id)
    ->meta('user_id', auth()->id())
    ->build();

$response = AiBridge::send($request);

use LiveNetworks\LnAiBridge\Providers\AbstractProvider;
use LiveNetworks\LnAiBridge\DTO\AiRequest;
use LiveNetworks\LnAiBridge\DTO\AiResponse;

class MistralProvider extends AbstractProvider
{
    public function name(): string { return 'mistral'; }
    public function model(): string { return $this->config['model']; }
    protected function endpoint(): string { return '/v1/chat/completions'; }
    protected function buildHeaders(): array { /* ... */ }
    protected function buildPayload(AiRequest $request): array { /* ... */ }
    protected function parseResponse(array $data): AiResponse { /* ... */ }
}

AiBridge::register('mistral', MistralProvider::class);

'mistral' => [
    'api_key'  => env('AI_BRIDGE_MISTRAL_API_KEY'),
    'model'    => env('AI_BRIDGE_MISTRAL_MODEL', 'mistral-large-latest'),
    'base_url' => 'https://api.mistral.ai',
],

'retry' => [
    'enabled'         => true,
    'max_retries'     => 3,
    'base_delay_ms'   => 1000,
    'multiplier'      => 2,
    'retryable_codes' => [429, 500, 502, 503, 529],
],
bash
php artisan vendor:publish --tag=ai-bridge-config
php artisan vendor:publish --tag=ai-bridge-migrations
php artisan migrate