Saltar al contenido

Chat

Ciclo de vida del chat, transmisión de datos, cancelación y proceso de preparación antes de la transmisión. Guías relacionadas: Disponibilidad, Imágenes, Eventos, Manejo de errores.

Ciclo de vida del chat

Se puede crear un chat propio, generar texto relacionado con él, y luego eliminarlo una vez que se haya terminado. Cada chat permite la generación de texto durante un solo proceso a la vez.

import { LocalLLM } from '@rdlabo/capacitor-local-llm';

const { status } = await LocalLLM.getAvailability();
if (status !== 'available') {
  throw new Error(`Model not ready: ${status}`);
}

const { id: chatId } = await LocalLLM.createChat({
  instructions: 'You are a helpful assistant.',
  history: { maxMessages: 20, maxCharacters: 12000 }, // en todas las plataformas; iOS recorta el historial de Foundation Models
});

const { text } = await LocalLLM.generateText({
  chatId,
  prompt: 'What is the capital of France?',
  // Solo en plataformas nativas: options: { temperature: 0.2, maxOutputTokens: 256 },
});

const followUp = await LocalLLM.generateText({
  chatId,
  prompt: 'What is the population of that city?',
});

console.log(text, followUp.text);

await LocalLLM.deleteChat({ id: chatId });

Transmisión por fragmentos con textChunk

La función streamText() emite fragmentos de texto de forma incremental, a través del evento textChunk. Cuando todo el proceso está completo, devuelve el texto completo.

import { LocalLLM } from '@rdlabo/capacitor-local-llm';

const { id: chatId } = await LocalLLM.createChat();

let streamedText = '';
const chunkListener = await LocalLLM.addListener('textChunk', (event) => {
  if (event.chatId !== chatId) return;
  streamedText += event.text;
  console.log(streamedText); // sustituye esta línea por una actualización de la interfaz de tu aplicación
});

try {
  const { text, generationId } = await LocalLLM.streamText({
    chatId,
    prompt: 'Summarize the theory of relativity in one paragraph.',
  });
  console.log('\ncomplete:', text, generationId);
} finally {
  await chunkListener.remove();
  await LocalLLM.deleteChat({ id: chatId });
}

Cancela una generación en curso

import { LocalLLM } from '@rdlabo/capacitor-local-llm';

const stateListener = await LocalLLM.addListener('generationStateChange', (event) => {
  if (event.chatId === chatId && event.state === 'started') {
    void LocalLLM.cancelGeneration({ chatId, generationId: event.generationId });
  }
});

const streamPromise = LocalLLM.streamText({ chatId, prompt: 'Write a long essay.' });

try {
  await streamPromise;
} catch (err) {
  // LOCAL_LLM_GENERATION_CANCELLED en todas las plataformas cuando se detecta la cancelación
} finally {
  await stateListener.remove();
}

Tanto generateText() como streamText() emiten generationStateChange. En cuanto el plugin acepta una solicitud de generación y antes del primer fragmento de texto, comunica started. Después emite un único estado final: completed, cancelled o failed. Usa su generationId para cancelar exactamente esa generación. deleteChat() también cancela cualquier generación activa de ese chat.

Reduce la latencia de la primera respuesta con el precalentamiento

import { LocalLLM } from '@rdlabo/capacitor-local-llm';

const { id: chatId } = await LocalLLM.createChat({
  instructions: 'You are a customer support agent for Acme Corp.',
});

// iOS: precarga este chat. Android: precarga el modelo de forma global (se ignora chatId).
// Web: crea y libera una sesión temporal con este chat (se ignora promptPrefix).
await LocalLLM.warmup({ chatId, promptPrefix: 'You are a customer support agent for Acme Corp.' });