Skip to content

高级功能

探索 VPetLLM 的高级功能来创建更复杂和强大的应用。

自定义 LLM 集成

使用 OpenAI

typescript
const pet = new VPetLLM({
  name: 'AI Pet',
  llm: {
    provider: 'openai',
    model: 'gpt-4',
    apiKey: process.env.OPENAI_API_KEY,
    temperature: 0.7,
    maxTokens: 100
  }
});

使用本地 LLM

typescript
const pet = new VPetLLM({
  name: 'Local Pet',
  llm: {
    provider: 'local',
    endpoint: 'http://localhost:8000',
    model: 'llama-2'
  }
});

自定义 LLM 提供商

typescript
class CustomLLMProvider {
  async generate(prompt: string): Promise<string> {
    // 实现你的 LLM 逻辑
    return 'Generated response';
  }
}

const pet = new VPetLLM({
  name: 'Custom Pet',
  llm: new CustomLLMProvider()
});

高级动画

自定义动画

typescript
// 定义自定义动画
pet.defineAnimation('dance', {
  frames: [
    { x: 0, y: 0, duration: 100 },
    { x: 10, y: 0, duration: 100 },
    { x: 0, y: 0, duration: 100 },
    { x: -10, y: 0, duration: 100 }
  ],
  loop: true
});

// 执行自定义动画
pet.playAnimation('dance');

动画序列

typescript
// 创建动画序列
pet.createSequence([
  { action: 'jump', duration: 500 },
  { action: 'spin', duration: 1000 },
  { action: 'sleep', duration: 2000 }
]);

// 执行序列
pet.playSequence();

高级事件系统

自定义事件

typescript
// 监听多个事件
pet.on('speak', handleSpeak);
pet.on('action', handleAction);
pet.on('stateChange', handleStateChange);

// 一次性事件
pet.once('firstSpeak', () => {
  console.log('Pet spoke for the first time!');
});

// 移除事件监听
pet.off('speak', handleSpeak);

// 触发自定义事件
pet.emit('customEvent', { data: 'value' });

多宠物管理

创建宠物群组

typescript
import { PetGroup } from 'vpetllm';

const group = new PetGroup();

// 添加宠物
group.addPet(pet1);
group.addPet(pet2);
group.addPet(pet3);

// 对所有宠物执行操作
group.forEach(pet => {
  pet.speak('Hello!');
});

// 获取宠物
const pet = group.getPet('Buddy');

// 移除宠物
group.removePet('Buddy');

宠物交互

typescript
// 让两个宠物互动
pet1.interact(pet2, 'play');

// 监听交互事件
pet1.on('interact', (otherPet, action) => {
  console.log(`${pet1.name} is ${action} with ${otherPet.name}`);
});

数据持久化

数据库集成

typescript
import { Database } from 'vpetllm';

const db = new Database({
  type: 'mongodb',
  url: 'mongodb://localhost:27017/vpetllm'
});

// 保存宠物到数据库
await db.savePet(pet);

// 从数据库加载宠物
const loadedPet = await db.loadPet('pet-id');

// 查询宠物
const pets = await db.query({ type: 'cat' });

云同步

typescript
// 启用云同步
pet.enableCloudSync({
  provider: 'firebase',
  projectId: 'your-project-id'
});

// 自动同步宠物状态
pet.on('stateChange', async () => {
  await pet.syncToCloud();
});

性能优化

对象池

typescript
import { PetPool } from 'vpetllm';

const pool = new PetPool({
  initialSize: 10,
  maxSize: 50
});

// 从池中获取宠物
const pet = pool.acquire();

// 使用宠物
pet.speak('Hello!');

// 归还宠物到池
pool.release(pet);

内存管理

typescript
// 启用垃圾回收
pet.enableGarbageCollection({
  interval: 60000, // 每分钟检查一次
  threshold: 0.8   // 内存使用超过 80% 时触发
});

// 手动清理
pet.cleanup();

调试和监控

启用调试模式

typescript
// 启用详细日志
pet.setDebugMode(true);

// 获取性能指标
const metrics = pet.getMetrics();
console.log(metrics);
// 输出: { fps: 60, memory: 45.2, renderTime: 16.7 }

// 监控性能
pet.on('performanceWarning', (warning) => {
  console.warn(`Performance issue: ${warning}`);
});

错误处理

typescript
// 设置错误处理器
pet.setErrorHandler((error) => {
  console.error(`Pet error: ${error.message}`);
  // 发送到错误追踪服务
  reportError(error);
});

// 捕获特定错误
pet.on('error', (error) => {
  if (error.type === 'LLM_ERROR') {
    // 处理 LLM 错误
  }
});

最佳实践

  1. 使用对象池 - 减少内存分配
  2. 启用垃圾回收 - 防止内存泄漏
  3. 监控性能 - 定期检查性能指标
  4. 错误处理 - 实现完善的错误处理机制
  5. 数据备份 - 定期备份宠物数据

下一步

Released under the MIT License.