файл пакета→ .shtukbase/packages/chat/test/fake-llm.ts
test/fake-llm.ts
59 строк, 3.6 КБ.
Файл как есть в пакете: код и комментарии в нём не переводятся.
- // A fake OpenAI-compatible streaming server for testing the chat without a real key.
- // bun apps/standard/packages/chat/test/fake-llm.ts [port] -> base URL http://127.0.0.1:<port>/v1
- // Turn 1 (last message from the user): a streamed tool call records_list {collection: /leads.md}.
- // Turn 2 (last message is the records_list result): a streamed tool call records_write that adds a lead.
- // Turn 3 (last message is the records_write result): a streamed Markdown answer that counts the records.
- const port = Number(process.argv[2] ?? 4399);
- const cors = {
- 'access-control-allow-origin': '*',
- 'access-control-allow-headers': 'authorization, content-type, x-title',
- 'access-control-allow-methods': 'POST, OPTIONS',
- };
- const enc = new TextEncoder();
- function sse(chunks: unknown[]) {
- return new Response(new ReadableStream({
- async start(c) {
- for (const ch of chunks) { c.enqueue(enc.encode(`data: ${JSON.stringify(ch)}\n\n`)); await Bun.sleep(40); }
- c.enqueue(enc.encode('data: [DONE]\n\n'));
- c.close();
- },
- }), { headers: { ...cors, 'content-type': 'text/event-stream' } });
- }
- const delta = (d: unknown) => ({ choices: [{ index: 0, delta: d }] });
- export const requests: any[] = [];
- let listed = 0;
- const toolName = (messages: any[], id: string) =>
- messages.flatMap((m) => m.tool_calls ?? []).find((c: any) => c.id === id)?.function?.name;
- Bun.serve({
- port,
- async fetch(req) {
- if (req.method === 'OPTIONS') return new Response(null, { status: 204, headers: cors });
- if (!new URL(req.url).pathname.endsWith('/chat/completions')) return new Response('nf', { status: 404, headers: cors });
- if (!req.headers.get('authorization')?.startsWith('Bearer ')) return Response.json({ error: { message: 'no key' } }, { status: 401, headers: cors });
- const body = await req.json();
- requests.push(body);
- if (process.env.LOG) console.log('turn', body.messages.length, 'tools', (body.tools ?? []).map((t: any) => t.function.name).join(','));
- const last = body.messages[body.messages.length - 1];
- if (last.role === 'tool' && toolName(body.messages, last.tool_call_id) === 'records_list') {
- let n = 0;
- try { n = JSON.parse(last.content).items.length; } catch {}
- listed = n;
- const args = JSON.stringify({ path: `/leads/fake-${Date.now()}.md`, meta: { title: 'Новая заявка от агента', status: 'new', source: 'telegram', amount: 50000 } });
- return sse([
- delta({ role: 'assistant', content: null, tool_calls: [{ index: 0, id: 'call_2', type: 'function', function: { name: 'records_write', arguments: '' } }] }),
- ...args.match(/.{1,24}/gs)!.map((a) => delta({ tool_calls: [{ index: 0, function: { arguments: a } }] })),
- ]);
- }
- if (last.role === 'tool') {
- const text = `В коллекции **Заявки** было ${listed} записей; добавил одну: «Новая заявка от агента».\n\n- смотрите [документацию](https://example.com)`;
- return sse([delta({ role: 'assistant', content: '' }), ...text.match(/.{1,12}/gs)!.map((t) => delta({ content: t }))]);
- }
- if (!body.tools?.length) return sse([delta({ content: 'Инструменты не подключены, отвечаю без них.' })]);
- return sse([
- delta({ role: 'assistant', content: null, tool_calls: [{ index: 0, id: 'call_1', type: 'function', function: { name: 'records_list', arguments: '' } }] }),
- delta({ tool_calls: [{ index: 0, function: { arguments: '{"collection":' } }] }),
- delta({ tool_calls: [{ index: 0, function: { arguments: '"/leads.md"}' } }] }),
- ]);
- },
- });
- console.log(`fake llm: http://127.0.0.1:${port}/v1`);