跳至正文

聊天

聊天会话的生命周期、流媒体功能、取消操作以及预热过程等相关指南:可用性说明、相关图片、事件信息、错误处理方法。

聊天生命周期

创建一个属于自己的聊天窗口,然后为其生成文本内容,完成后即可删除该聊天窗口。每个聊天窗口一次只能进行一项生成操作。

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 }, // 适用于所有平台;iOS 会裁剪 Foundation Models 的对话记录
});

const { text } = await LocalLLM.generateText({
  chatId,
  prompt: 'What is the capital of France?',
  // 仅适用于原生平台: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 });

使用 textChunk 流式输出

streamText()会通过textChunk事件逐块推送文本数据,并在处理完所有数据后返回完整的文本内容。

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); // 请替换为更新应用界面的代码
});

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 });
}

取消正在进行的生成

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
} finally {
  await stateListener.remove();
}

调用 generateText() 和 streamText() 都会产生 generationStateChange 事件。插件接受生成请求后、输出首个文本片段前,会立即报告 started。随后只会报告一种最终状态:completed、cancelled 或 failed。使用事件中的 generationId 可以准确取消指定的生成任务。deleteChat() 也会取消该会话中正在进行的生成。

通过预热缩短首次响应时间

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

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

// iOS:预热此聊天。Android:全局预热模型(忽略 chatId)。
// Web:使用此聊天创建并释放一个临时会话(忽略 promptPrefix)。
await LocalLLM.warmup({ chatId, promptPrefix: 'You are a customer support agent for Acme Corp.' });