droid / src /routes /utils /converter.js
devme's picture
Upload 15 files
50852f0 verified
/**
* 将 /v1/responses API 结果转换为 /v1/chat/completions 兼容格式
* 适用于非流式响应
* @param {Object} resp - 原始响应对象
* @returns {Object} OpenAI 兼容的聊天补全格式
*/
export function convertResponseToChatCompletion(resp) {
if (!resp || typeof resp !== 'object') {
throw new Error('Invalid response object')
}
const outputMsg = (resp.output || []).find(o => o.type === 'message')
const textBlocks = outputMsg?.content?.filter(c => c.type === 'output_text') || []
const content = textBlocks.map(c => c.text).join('')
const chatCompletion = {
id: resp.id ? resp.id.replace(/^resp_/, 'chatcmpl-') : `chatcmpl-${Date.now()}`,
object: 'chat.completion',
created: resp.created_at || Math.floor(Date.now() / 1000),
model: resp.model || 'unknown-model',
choices: [
{
index: 0,
message: {
role: outputMsg?.role || 'assistant',
content: content || ''
},
finish_reason: resp.status === 'completed' ? 'stop' : 'unknown'
}
],
usage: {
prompt_tokens: resp.usage?.input_tokens ?? 0,
completion_tokens: resp.usage?.output_tokens ?? 0,
total_tokens: resp.usage?.total_tokens ?? 0
}
}
return chatCompletion
}