ShtukbaseStandard
package file→ .shtukbase/packages/chat/test/fake-llm.ts

test/fake-llm.ts

59 lines, 3.6 KB.

The file as it is in the package. Some comments in it may not be in English yet.

  1. // A fake OpenAI-compatible streaming server for testing the chat without a real key.
  2. // bun apps/standard/packages/chat/test/fake-llm.ts [port] -> base URL http://127.0.0.1:<port>/v1
  3. // Turn 1 (last message from the user): a streamed tool call records_list {collection: /leads.md}.
  4. // Turn 2 (last message is the records_list result): a streamed tool call records_write that adds a lead.
  5. // Turn 3 (last message is the records_write result): a streamed Markdown answer that counts the records.
  6. const port = Number(process.argv[2] ?? 4399);
  7. const cors = {
  8. 'access-control-allow-origin': '*',
  9. 'access-control-allow-headers': 'authorization, content-type, x-title',
  10. 'access-control-allow-methods': 'POST, OPTIONS',
  11. };
  12. const enc = new TextEncoder();
  13. function sse(chunks: unknown[]) {
  14. return new Response(new ReadableStream({
  15. async start(c) {
  16. for (const ch of chunks) { c.enqueue(enc.encode(`data: ${JSON.stringify(ch)}\n\n`)); await Bun.sleep(40); }
  17. c.enqueue(enc.encode('data: [DONE]\n\n'));
  18. c.close();
  19. },
  20. }), { headers: { ...cors, 'content-type': 'text/event-stream' } });
  21. }
  22. const delta = (d: unknown) => ({ choices: [{ index: 0, delta: d }] });
  23. export const requests: any[] = [];
  24. let listed = 0;
  25. const toolName = (messages: any[], id: string) =>
  26. messages.flatMap((m) => m.tool_calls ?? []).find((c: any) => c.id === id)?.function?.name;
  27. Bun.serve({
  28. port,
  29. async fetch(req) {
  30. if (req.method === 'OPTIONS') return new Response(null, { status: 204, headers: cors });
  31. if (!new URL(req.url).pathname.endsWith('/chat/completions')) return new Response('nf', { status: 404, headers: cors });
  32. if (!req.headers.get('authorization')?.startsWith('Bearer ')) return Response.json({ error: { message: 'no key' } }, { status: 401, headers: cors });
  33. const body = await req.json();
  34. requests.push(body);
  35. if (process.env.LOG) console.log('turn', body.messages.length, 'tools', (body.tools ?? []).map((t: any) => t.function.name).join(','));
  36. const last = body.messages[body.messages.length - 1];
  37. if (last.role === 'tool' && toolName(body.messages, last.tool_call_id) === 'records_list') {
  38. let n = 0;
  39. try { n = JSON.parse(last.content).items.length; } catch {}
  40. listed = n;
  41. const args = JSON.stringify({ path: `/leads/fake-${Date.now()}.md`, meta: { title: 'Новая заявка от агента', status: 'new', source: 'telegram', amount: 50000 } });
  42. return sse([
  43. delta({ role: 'assistant', content: null, tool_calls: [{ index: 0, id: 'call_2', type: 'function', function: { name: 'records_write', arguments: '' } }] }),
  44. ...args.match(/.{1,24}/gs)!.map((a) => delta({ tool_calls: [{ index: 0, function: { arguments: a } }] })),
  45. ]);
  46. }
  47. if (last.role === 'tool') {
  48. const text = `В коллекции **Заявки** было ${listed} записей; добавил одну: «Новая заявка от агента».\n\n- смотрите [документацию](https://example.com)`;
  49. return sse([delta({ role: 'assistant', content: '' }), ...text.match(/.{1,12}/gs)!.map((t) => delta({ content: t }))]);
  50. }
  51. if (!body.tools?.length) return sse([delta({ content: 'Инструменты не подключены, отвечаю без них.' })]);
  52. return sse([
  53. delta({ role: 'assistant', content: null, tool_calls: [{ index: 0, id: 'call_1', type: 'function', function: { name: 'records_list', arguments: '' } }] }),
  54. delta({ tool_calls: [{ index: 0, function: { arguments: '{"collection":' } }] }),
  55. delta({ tool_calls: [{ index: 0, function: { arguments: '"/leads.md"}' } }] }),
  56. ]);
  57. },
  58. });
  59. console.log(`fake llm: http://127.0.0.1:${port}/v1`);