Files
2026-11-27 06:03:56 +00:00

58 lines
2.6 KiB
JavaScript

import assert from 'node:assert/strict';
import test from 'node:test';
import { chat } from '../../module/assistant/agent/javascript/chat.mjs';
const setting = { endpoint: 'https://example.invalid/api/chat', model: 'test-model', timeout_ms: 1000 };
const call = { name: 'Add', arguments: { a: 12, b: 30 } };
test('发送工具历史并转换模型调用,不把供应商 index 传入 Dever', async t => {
let sent;
t.mock.method(globalThis, 'fetch', async (url, request) => {
assert.equal(url, setting.endpoint);
sent = JSON.parse(request.body);
return Response.json({ message: { content: '', tool_calls: [{ function: { index: 0, ...call } }] } });
});
const messages = [
{ role: 'user', content: '计算', calls: [], tool_name: null },
{ role: 'assistant', content: '', calls: [call], tool_name: null },
{ role: 'tool', content: '42', calls: [], tool_name: 'Add' }
];
const output = await chat({ messages }, setting, new AbortController().signal);
assert.deepEqual(output, { turn: { content: '', calls: [call] } });
assert.deepEqual(sent.messages, [
{ role: 'user', content: '计算' },
{ role: 'assistant', content: '', tool_calls: [{ function: call }] },
{ role: 'tool', content: '42', tool_name: 'Add' }
]);
assert.deepEqual(sent.tools.map(tool => tool.function.name), ['Add', 'Multiply']);
assert.equal(sent.stream, false);
assert.equal(sent.model, setting.model);
});
test('普通回答允许省略 tool_calls', async t => {
t.mock.method(globalThis, 'fetch', async () => Response.json({ message: { content: '答案是 84。' } }));
assert.deepEqual(await chat({ messages: [] }, setting, new AbortController().signal), {
turn: { content: '答案是 84。', calls: [] }
});
});
test('HTTP 失败向上传播', async t => {
t.mock.method(globalThis, 'fetch', async () => new Response('', { status: 503 }));
await assert.rejects(chat({ messages: [] }, setting, new AbortController().signal), /Ollama HTTP 503/);
});
test('取消信号到达 fetch,不产生成功结果', async t => {
t.mock.method(globalThis, 'fetch', async (_url, request) => {
request.signal.throwIfAborted();
assert.fail('已取消的请求不应继续');
});
const controller = new AbortController();
controller.abort(new Error('test cancellation'));
await assert.rejects(chat({ messages: [] }, setting, controller.signal), /test cancellation/);
});
test('损坏的 tool_calls 不当成没有工具', async t => {
t.mock.method(globalThis, 'fetch', async () => Response.json({ message: { content: '', tool_calls: null } }));
await assert.rejects(chat({ messages: [] }, setting, new AbortController().signal), TypeError);
});