llm.mock.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. export function createLLMMock(options: LLMMockOptions = {}) {
  2. const { shouldFail = false, delayMs = 0, response } = options;
  3. return {
  4. name: 'mock-llm' as const,
  5. vendor: 'mock' as const,
  6. mode: 'mock' as const,
  7. invoke: vi.fn().mockImplementation(async (input: string) => {
  8. if (delayMs > 0) {
  9. await new Promise((resolve) => setTimeout(resolve, delayMs));
  10. }
  11. if (shouldFail) {
  12. throw new Error('Mock LLM failure');
  13. }
  14. return {
  15. content: response || JSON.stringify({
  16. title: '测试书籍标题',
  17. outline: [
  18. { chapter: 1, title: '第一章', summary: '章节摘要' }
  19. ]
  20. })
  21. };
  22. }),
  23. stream: vi.fn().mockImplementation(async function* (input: string) {
  24. if (delayMs > 0) {
  25. await new Promise((resolve) => setTimeout(resolve, delayMs));
  26. }
  27. if (shouldFail) {
  28. throw new Error('Mock LLM failure');
  29. }
  30. yield { content: '模拟流式输出' };
  31. }),
  32. generate: vi.fn().mockImplementation(async (prompt: string) => {
  33. if (shouldFail) {
  34. throw new Error('Mock LLM failure');
  35. }
  36. return response || 'Mock response';
  37. }),
  38. };
  39. }
  40. export interface LLMMockOptions {
  41. shouldFail?: boolean;
  42. delayMs?: number;
  43. response?: string;
  44. }
  45. export const defaultLLMResponse = {
  46. title: 'AI发展史',
  47. outline: [
  48. { chapter: 1, title: '第一章:起源', summary: '讲述AI的起源' },
  49. { chapter: 2, title: '第二章:发展', summary: '讲述AI的发展' },
  50. ]
  51. };