MCPcopy
hub / github.com/7836246/cursor2api / chat

Function chat

test/e2e-ctf-proxy.mjs:30–94  ·  view source on GitHub ↗
(messages, { stream = true, label = '' } = {})

Source from the content-addressed store, hash-verified

28
29// ─── 请求辅助 ────────────────────────────────────────────────────
30async function chat(messages, { stream = true, label = '' } = {}) {
31 const body = {
32 model: MODEL,
33 max_tokens: 4096,
34 messages: messages.map(m => ({
35 role: m.role,
36 content: m.text,
37 })),
38 stream,
39 };
40
41 const t0 = Date.now();
42 process.stdout.write(` ${C.dim}[${label || 'request'}]${C.reset} `);
43
44 const resp = await fetch(`${BASE_URL}/v1/messages`, {
45 method: 'POST',
46 headers: { 'Content-Type': 'application/json', 'x-api-key': 'dummy' },
47 body: JSON.stringify(body),
48 });
49
50 if (!resp.ok) {
51 const text = await resp.text();
52 throw new Error(`HTTP ${resp.status}: ${text.substring(0, 200)}`);
53 }
54
55 if (stream) {
56 // 流式读取
57 const reader = resp.body.getReader();
58 const decoder = new TextDecoder();
59 let buffer = '';
60 let fullText = '';
61 let chunkCount = 0;
62
63 while (true) {
64 const { done, value } = await reader.read();
65 if (done) break;
66 buffer += decoder.decode(value, { stream: true });
67 const lines = buffer.split('\n');
68 buffer = lines.pop() || '';
69
70 for (const line of lines) {
71 if (!line.startsWith('data: ')) continue;
72 const data = line.slice(6).trim();
73 if (!data) continue;
74 try {
75 const evt = JSON.parse(data);
76 if (evt.type === 'content_block_delta' && evt.delta?.type === 'text_delta') {
77 fullText += evt.delta.text;
78 chunkCount++;
79 if (chunkCount % 20 === 0) process.stdout.write('.');
80 }
81 } catch { /* ignore */ }
82 }
83 }
84 const elapsed = ((Date.now() - t0) / 1000).toFixed(1);
85 process.stdout.write(` ${C.dim}(${elapsed}s, ${fullText.length} chars)${C.reset}\n`);
86 return { text: fullText, elapsed };
87 } else {

Callers 1

e2e-ctf-proxy.mjsFile · 0.70

Calls 2

writeMethod · 0.45
jsonMethod · 0.45

Tested by

no test coverage detected