PHP code example of cynchro / modux-ia

1. Go to this page and download the library: Download cynchro/modux-ia 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/ */

    

cynchro / modux-ia example snippets


use PhpAI\DriverFactory;
use PhpAI\RAG\RAGEngine;

class SoporteService
{
    public function __construct(
        private readonly DriverFactory $ai,
        private readonly RAGEngine     $rag,
    ) {}

    public function responder(string $pregunta): string
    {
        return $this->rag->ask($pregunta);
    }
}

use PhpAI\DriverFactory;
use PhpAI\RAG\RAGEngine;

class SupportController extends Controller
{
    public function __construct(
        private readonly DriverFactory $ai,
        private readonly RAGEngine     $rag,
    ) {}

    public function ask(Request $request): JsonResponse
    {
        $answer = $this->rag->ask($request->input('question'));
        return response()->json(['answer' => $answer]);
    }
}

use DI\ContainerBuilder;
use PhpAI\Psr11\AIDefinitions;

$builder = new ContainerBuilder();
$builder->addDefinitions(AIDefinitions::get());
$container = $builder->build();



use PhpAI\Bootstrap;

// Zero config — lee todo desde variables de entorno
$ai = Bootstrap::fromEnv();

// O configuración explícita
$ai = Bootstrap::create([
    'driver' => 'cloud',
    'drivers' => [
        'cloud' => [
            'provider' => 'openai',
            'api_key'  => 'sk-...',
            'model'    => 'gpt-4o-mini',
        ],
    ],
    'rag' => ['sqlite_path' => __DIR__ . '/storage/vectors.db'],
]);

use PhpAI\Contracts\CompletionRequest;

$response = $factory->llm()->complete(new CompletionRequest(
    messages: [
        ['role' => 'system', 'content' => 'Sos un experto en PHP.'],
        ['role' => 'user',   'content' => '¿Qué es un trait?'],
    ],
    temperature: 0.7,
    maxTokens: 512,
));

echo $response->content;

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

foreach ($factory->llm()->stream($request) as $token) {
    echo "data: " . json_encode(['token' => $token]) . "\n\n";
    ob_flush(); flush();
}
echo "data: [DONE]\n\n";

$rag = $factory->rag();

$rag->ingest(
    document: file_get_contents('manual.txt'),
    id:       'manual-v1',
    metadata: ['tipo' => 'manual'],
);

// Respuesta directa
$answer = $rag->ask("¿Cuál es el proceso de devolución?");

// Con filtro de metadata
$answer = $rag->ask(
    question: "¿Cómo configuro el sistema?",
    filter:   ['tipo' => 'manual'],
);

// Con system prompt personalizado
$answer = $rag->ask(
    question:     "¿Qué garantías tiene el producto?",
    systemPrompt: "Respondé de forma empática en no más de 3 oraciones.",
);

$chunks = $rag->retrieve("política de envíos internacionales");

foreach ($chunks as $chunk) {
    echo "[{$chunk['score']}] {$chunk['metadata']['content']}\n";
}

$vector  = $factory->embeddings()->embed("texto de ejemplo");
$vectors = $factory->embeddings()->embedBatch(["texto 1", "texto 2"]);
bash
php artisan vendor:publish --tag=modux-ia