Come integrare modelli di intelligenza artificiale nelle tue applicazioni web.
L'Intelligenza Artificiale non è più un lusso riservato alle grandi aziende tech. Grazie a API accessibili e librerie mature, qualsiasi sviluppatore può oggi integrare funzionalità AI nelle proprie applicazioni web. In questa guida vediamo come farlo in modo pratico e scalabile.
Le opzioni principali per integrare AI nelle applicazioni web:
Uno dei pattern più efficaci per l'UX è lo streaming delle risposte AI:
// routes/api.php
Route::post('/ai/chat', function (Request $request) {
$client = OpenAI::client(config('services.openai.key'));
return response()->stream(function () use ($client, $request) {
$stream = $client->chat()->createStreamed([
'model' => 'gpt-4o-mini',
'messages' => [
['role' => 'system', 'content' => 'Sei un assistente per sviluppatori.'],
['role' => 'user', 'content' => $request->message],
],
]);
foreach ($stream as $response) {
$text = $response->choices[0]->delta->content ?? '';
if ($text) {
echo "data: " . json_encode(['text' => $text]) . "
";
ob_flush();
flush();
}
}
echo "data: [DONE]
";
}, 200, [
'Content-Type' => 'text/event-stream',
'X-Accel-Buffering' => 'no',
]);
});
async function streamChat(message) {
const response = await fetch('/api/ai/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message }),
});
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('
');
buffer = lines.pop();
for (const line of lines) {
if (line.startsWith('data: ') && line !== 'data: [DONE]') {
const data = JSON.parse(line.slice(6));
appendText(data.text); // Aggiorna la UI incrementalmente
}
}
}
}
Gli embedding permettono di cercare contenuti per significato, non solo per parole chiave:
use OpenAILaravelFacadesOpenAI;
class SemanticSearch
{
public function embed(string $text): array
{
$response = OpenAI::embeddings()->create([
'model' => 'text-embedding-3-small',
'input' => $text,
]);
return $response->embeddings[0]->embedding; // array di 1536 float
}
public function search(string $query, int $limit = 5): Collection
{
$queryEmbedding = $this->embed($query);
// Usa pgvector su PostgreSQL per ricerca vettoriale efficiente
return Document::orderByRaw(
'embedding <=> ?',
[json_encode($queryEmbedding)]
)->limit($limit)->get();
}
}
L'AI può essere costosa. Strategie per ridurre i costi:
class AiService
{
public function complete(string $prompt): string
{
// Cache le risposte per prompt identici (es. FAQ, template fissi)
$cacheKey = 'ai:' . md5($prompt);
return Cache::remember($cacheKey, now()->addDay(), function () use ($prompt) {
return OpenAI::chat()->create([
'model' => 'gpt-4o-mini', // Modello economico per task semplici
'messages' => [['role' => 'user', 'content' => $prompt]],
'max_tokens' => 500, // Limita la lunghezza della risposta
])->choices[0]->message->content;
});
}
}
L'integrazione AI nelle applicazioni web è ormai accessibile a tutti gli sviluppatori. Partendo da funzionalità semplici come la generazione di testo o la classificazione, puoi costruire esperienze utente straordinarie. La chiave è iniziare in piccolo, misurare l'impatto e iterare rapidamente.
Il futuro delle applicazioni web è AI-augmented, e il momento migliore per iniziare è adesso.