grok-project / core /utils.js
kevin
优化
7324743
raw
history blame contribute delete
939 Bytes
// utils.js
export function getRandomIDPro(size) {
const customDict = '0123456789';
return Array.from({ length: size }, () =>
customDict[Math.floor(Math.random() * customDict.length)]
).join('');
}
export function validateRequest(req) {
const { messages, model, stream } = req;
if (!Array.isArray(messages) || messages.length === 0) {
throw new ValidationError('Messages array is required and cannot be empty');
}
if (!messages.every(msg =>
msg.role && msg.content &&
['system', 'user', 'assistant'].includes(msg.role)
)) {
throw new ValidationError('Invalid message format');
}
return { messages, model, stream: Boolean(stream) };
}
export async function withTimeout(promise, ms) {
const timeout = new Promise((_, reject) => {
setTimeout(() => reject(new Error('Request timeout')), ms);
});
return Promise.race([promise, timeout]);
}