File size: 15,487 Bytes
ef04721 17037b0 654165a 494c9e4 ca74a9e 494c9e4 654165a 494c9e4 ef04721 494c9e4 ca74a9e 494c9e4 654165a 494c9e4 654165a 494c9e4 654165a 494c9e4 ef04721 654165a 494c9e4 654165a 494c9e4 654165a 494c9e4 28147a1 494c9e4 ca74a9e 494c9e4 654165a ef04721 654165a 494c9e4 2764e14 494c9e4 2764e14 654165a 2764e14 494c9e4 2764e14 494c9e4 654165a 2764e14 654165a 2764e14 494c9e4 2764e14 494c9e4 2764e14 494c9e4 2764e14 494c9e4 2764e14 494c9e4 2764e14 494c9e4 654165a 494c9e4 654165a 494c9e4 654165a 494c9e4 ef04721 494c9e4 ca74a9e 494c9e4 2764e14 494c9e4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 | import { AdminManager } from '../cross/adminManager';
import { apiUrl } from './resolveApiBase';
import * as completionResultCache from '../../features/chat/completionResultCache';
import type { ChatDisplaySegment } from '../../features/chat/chatSegments';
import type { TokenWithOffset } from './generatedSchemas';
function completionsRequestHeaders(): Record<string, string> {
const headers: Record<string, string> = {
'Content-Type': 'application/json; charset=UTF-8',
};
const admin = AdminManager.getInstance();
const token = admin.isInAdminMode() ? admin.getAdminToken() : null;
if (token) {
headers['X-Admin-Token'] = token;
}
return headers;
}
/** 与 server.yaml basePath `/api` + `/v1/completions` 一致 */
const COMPLETIONS_PATH = '/api/v1/completions';
const COMPLETIONS_PROMPT_PATH = '/api/v1/completions/prompt';
const COMPLETIONS_PROMPT_INCREMENTAL_PATH = '/api/v1/completions/prompt-incremental';
const COMPLETIONS_STOP_PATH = '/api/v1/completions/stop';
/** 与 server_openai_definitions.yaml OpenAICompletionsRequest 对齐的最小类型 */
export type OpenAICompletionsRequest = {
model: string;
prompt: string;
max_tokens?: number;
temperature?: number;
top_p?: number;
stop?: string | string[];
[key: string]: unknown;
};
export type OpenAICompletionChoice = {
text?: string;
index?: number;
finish_reason?: string | null;
};
/** 与 server_openai_definitions InfoRadarCompletionPayload 对齐 */
export type InfoRadarCompletionPayload = {
bpe_strings: TokenWithOffset[];
};
/** 与 OpenAICompletionsResponse 对齐(SSE 末条 result 的 data 与此同形) */
export type OpenAICompletionsResponse = {
id: string;
object: 'text_completion';
created: number;
model: string;
choices: OpenAICompletionChoice[];
usage?: {
prompt_tokens?: number;
completion_tokens?: number;
total_tokens?: number;
};
/** 续写 token 级 real_topk / pred_topk,与主站信息密度分析字段一致 */
info_radar?: InfoRadarCompletionPayload;
};
/**
* 单用户串行:通知后端全局停止续写(不 await,避免阻塞 UI)。
* Chat 页 Stop 仅调用此函数而不断开 fetch,以便仍收到末条 SSE result(含 info_radar)。
*/
export function postCompletionsStop(): void {
const url = apiUrl(COMPLETIONS_STOP_PATH);
void fetch(url, {
method: 'POST',
headers: completionsRequestHeaders(),
body: '{}'
}).catch(() => {
/* 忽略:Stop 与 SSE 并行,失败时生成仍可能靠墙钟或其它路径结束 */
});
}
export type PostCompletionsPromptOptions = {
signal?: AbortSignal;
};
export type CompletionsChatMessage = {
role: 'system' | 'user' | 'assistant' | 'tool';
content: string;
name?: string;
};
/**
* POST /v1/completions/prompt:将 messages 套用 chat template,返回完整 prompt_used。
*/
export async function postCompletionsPrompt(
body: {
model: string;
messages: CompletionsChatMessage[];
tools?: Record<string, unknown>[];
enable_thinking?: boolean;
},
options: PostCompletionsPromptOptions = {}
): Promise<{ prompt_used: string }> {
const { signal } = options;
const url = apiUrl(COMPLETIONS_PROMPT_PATH);
const payload: Record<string, unknown> = {
model: body.model,
messages: body.messages,
};
if (body.tools !== undefined && body.tools.length > 0) {
payload.tools = body.tools;
}
if (body.enable_thinking === true) {
payload.enable_thinking = true;
}
const res = await fetch(url, {
method: 'POST',
headers: completionsRequestHeaders(),
body: JSON.stringify(payload),
signal
});
const text = await res.text();
let parsed: { success?: boolean; message?: string; prompt_used?: string };
try {
parsed = JSON.parse(text) as typeof parsed;
} catch {
throw new Error(`POST ${COMPLETIONS_PROMPT_PATH} failed: ${res.status} ${text.slice(0, 500)}`);
}
if (!res.ok) {
const msg =
typeof parsed.message === 'string' ? parsed.message : text.slice(0, 500);
throw new Error(msg || `POST ${COMPLETIONS_PROMPT_PATH} failed: ${res.status}`);
}
if (typeof parsed.prompt_used !== 'string' || !parsed.prompt_used.length) {
throw new Error('completions/prompt response missing prompt_used');
}
return { prompt_used: parsed.prompt_used };
}
/**
* POST /v1/completions/prompt-incremental:计算多轮 wire 模式下 tool response 的 incremental_suffix。
*/
export async function postCompletionsPromptIncremental(
body: {
model: string;
tool_content: string;
tool_name?: string;
enable_thinking?: boolean;
},
options: PostCompletionsPromptOptions = {}
): Promise<{ incremental_suffix: string }> {
const { signal } = options;
const url = apiUrl(COMPLETIONS_PROMPT_INCREMENTAL_PATH);
const payload: Record<string, unknown> = {
model: body.model,
tool_content: body.tool_content,
};
if (body.tool_name !== undefined) {
payload.tool_name = body.tool_name;
}
if (body.enable_thinking === true) {
payload.enable_thinking = true;
}
const res = await fetch(url, {
method: 'POST',
headers: completionsRequestHeaders(),
body: JSON.stringify(payload),
signal
});
const text = await res.text();
let parsed: { success?: boolean; message?: string; incremental_suffix?: string };
try {
parsed = JSON.parse(text) as typeof parsed;
} catch {
throw new Error(`POST ${COMPLETIONS_PROMPT_INCREMENTAL_PATH} failed: ${res.status} ${text.slice(0, 500)}`);
}
if (!res.ok) {
const msg =
typeof parsed.message === 'string' ? parsed.message : text.slice(0, 500);
throw new Error(msg || `POST ${COMPLETIONS_PROMPT_INCREMENTAL_PATH} failed: ${res.status}`);
}
if (typeof parsed.incremental_suffix !== 'string') {
throw new Error('completions/prompt-incremental response missing incremental_suffix');
}
return { incremental_suffix: parsed.incremental_suffix };
}
export type PostCompletionsOptions = {
signal?: AbortSignal;
/** 续写增量文本 */
onDelta?: (text: string, streamEnd: boolean) => void;
/** 与请求体 `prompt` 一致(prompt_used);仅 Chat 等需缓存时传入 */
cacheKey?: completionResultCache.CompletionResultCacheKey;
/** 与 cacheKey 一并写入 IndexedDB,加载时还原左侧面板 */
cacheDraft?: completionResultCache.ChatCompletionDraft;
/** 为 true 时跳过命中本地缓存,与 Chat 页「Force retry」一致 */
forceRefresh?: boolean;
};
/** postCompletions 返回值;传入 cacheKey 时 contentKey 与 IndexedDB / `?content=` 一致 */
export type PostCompletionsResult = {
response: OpenAICompletionsResponse;
contentKey?: string;
/** 缓存命中时携带已存 segments(多轮或单轮) */
cachedSegments?: ChatDisplaySegment[];
};
/**
* POST /v1/completions:响应恒为 SSE(delta… → result)。
* 末条 result 的 data 为 OpenAICompletionsResponse;可与拼接的 delta 对照校验。
*/
export async function postCompletions(
body: OpenAICompletionsRequest,
options: PostCompletionsOptions = {}
): Promise<PostCompletionsResult> {
const { signal, onDelta, cacheKey, cacheDraft, forceRefresh } = options;
const modelName = body.model;
return new Promise((resolve, reject) => {
let settled = false;
let streamedText = '';
const safeReject = (e: unknown) => {
if (!settled) {
settled = true;
reject(e);
}
};
const finishResolve = (
response: OpenAICompletionsResponse,
contentKey?: string,
cachedSegments?: ChatDisplaySegment[]
) => {
settled = true;
resolve({ response, contentKey, cachedSegments });
};
const safeResolve = async (v: OpenAICompletionsResponse) => {
if (settled) return;
if (signal?.aborted) {
safeReject(new DOMException('Aborted', 'AbortError'));
return;
}
let contentKey: string | undefined;
if (typeof v.choices?.[0]?.text === 'string' && cacheKey) {
try {
({ contentKey } = await completionResultCache.save(
cacheKey,
v,
'complete',
cacheDraft
));
} catch (e) {
safeReject(e);
return;
}
}
if (settled) return;
if (signal?.aborted) {
safeReject(new DOMException('Aborted', 'AbortError'));
return;
}
finishResolve(v, contentKey);
};
const rejectIfAborted = (): boolean => {
if (!signal?.aborted) return false;
if (cacheKey && streamedText.length > 0) {
void completionResultCache.save(
cacheKey,
{
id: `partial-${Date.now()}`,
object: 'text_completion',
created: Math.floor(Date.now() / 1000),
model: modelName,
choices: [{ text: streamedText, index: 0, finish_reason: 'abort' }],
},
'partial',
cacheDraft
);
}
safeReject(new DOMException('Aborted', 'AbortError'));
return true;
};
if (cacheKey) {
void (async () => {
try {
if (forceRefresh) {
await completionResultCache.removeForCacheKey(cacheKey);
}
const cachedEntry = forceRefresh
? undefined
: await completionResultCache.getEntry(cacheKey);
if (cachedEntry) {
await completionResultCache.touch(cacheKey);
queueMicrotask(() => {
if (settled) return;
if (rejectIfAborted()) return;
const cached = cachedEntry.response;
const text = cached.choices?.[0]?.text;
if (typeof text !== 'string') {
safeReject(new Error('completions cache: invalid choices[0].text'));
return;
}
onDelta?.(text, true);
if (settled) return;
if (signal?.aborted) {
safeReject(new DOMException('Aborted', 'AbortError'));
return;
}
finishResolve(cached, cachedEntry.contentKey, cachedEntry.segments);
});
return;
}
} catch (e) {
console.warn('[completions] read cache failed:', e);
}
fetchRemote();
})();
return;
}
fetchRemote();
function fetchRemote(): void {
fetch(apiUrl(COMPLETIONS_PATH), {
method: 'POST',
headers: completionsRequestHeaders(),
body: JSON.stringify(body),
signal
})
.then((response) => {
if (!response.ok) {
return response.text().then((t) => {
throw new Error(`POST ${COMPLETIONS_PATH} failed: ${response.status} ${t.slice(0, 500)}`);
});
}
const reader = response.body!.getReader();
signal?.addEventListener('abort', () => reader.cancel(), { once: true });
const decoder = new TextDecoder();
let buffer = '';
const processDataLine = (jsonStr: string) => {
if (settled) return;
if (rejectIfAborted()) return;
let parsed: {
type?: string;
text?: string;
stream_end?: boolean;
data?: OpenAICompletionsResponse;
message?: string;
};
try {
parsed = JSON.parse(jsonStr) as typeof parsed;
} catch (e) {
safeReject(
new Error(
`SSE event JSON parse failed: ${
e instanceof SyntaxError ? e.message : String(e)
}`
)
);
return;
}
if (parsed.type === 'delta') {
const delta = parsed.text ?? '';
streamedText += delta;
onDelta?.(delta, Boolean(parsed.stream_end));
} else if (parsed.type === 'result') {
const data = parsed.data;
if (data && typeof data === 'object' && 'choices' in data) {
void safeResolve(data as OpenAICompletionsResponse);
} else {
safeReject(new Error('completions stream: invalid result payload'));
}
} else if (parsed.type === 'error') {
safeReject(new Error(parsed.message || 'completions stream failed'));
}
};
const readChunk = (): Promise<void> => {
return reader.read().then(({ done, value }) => {
if (settled) return;
if (rejectIfAborted()) return;
if (done) {
if (buffer.trim()) {
const line = buffer;
if (line.startsWith('data: ')) processDataLine(line.slice(6));
}
if (!settled) {
safeReject(new Error('completions stream ended without result'));
}
return;
}
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (line.startsWith('data: ')) processDataLine(line.slice(6));
}
return readChunk();
});
};
return readChunk();
})
.catch((e) => {
if (!settled) safeReject(e);
});
}
});
}
|