feat(history): establish Telegram SaaS platform foundation
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
function contentText(payload) {
|
||||
return payload?.content?.map((part) => part.text || '').join('') || ''
|
||||
}
|
||||
|
||||
function parseJson(text) {
|
||||
const cleaned = text.replace(/^```(?:json)?/i, '').replace(/```$/, '').trim()
|
||||
return JSON.parse(cleaned)
|
||||
}
|
||||
|
||||
export async function deepseek(system, user, json = false) {
|
||||
const apiKey = process.env.DEEPSEEK_API_KEY
|
||||
if (!apiKey) throw Object.assign(new Error('DEEPSEEK_API_KEY 尚未配置'), { status: 503 })
|
||||
const controller = new AbortController()
|
||||
const timeout = setTimeout(() => controller.abort(), Number(process.env.AI_TIMEOUT_MS || 45000))
|
||||
try {
|
||||
const response = await fetch(`${(process.env.DEEPSEEK_BASE_URL || 'https://api.deepseek.com/anthropic').replace(/\/$/, '')}/v1/messages`, {
|
||||
method: 'POST',
|
||||
signal: controller.signal,
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
'x-api-key': apiKey,
|
||||
'anthropic-version': '2023-06-01',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: process.env.DEEPSEEK_MODEL || 'deepseek-v4-flash',
|
||||
max_tokens: Number(process.env.AI_MAX_TOKENS || 4096),
|
||||
temperature: json ? 0.1 : 0.3,
|
||||
system,
|
||||
messages: [{ role: 'user', content: [{ type: 'text', text: user }] }],
|
||||
}),
|
||||
})
|
||||
const body = await response.json()
|
||||
if (!response.ok) throw Object.assign(new Error(body?.error?.message || `AI 请求失败 (${response.status})`), { status: 502 })
|
||||
const text = contentText(body)
|
||||
return json ? parseJson(text) : text
|
||||
} finally {
|
||||
clearTimeout(timeout)
|
||||
}
|
||||
}
|
||||
|
||||
export function conversationContext(messages) {
|
||||
return messages.slice(-80).map((m) => {
|
||||
const role = m.sender === 'agent' ? '坐席' : m.sender === 'system' ? '系统' : '客户'
|
||||
const content = m.originalText || m.attachmentName || `[${m.type || '消息'}]`
|
||||
const translation = m.translatedText && m.translatedText !== content ? `(译文:${m.translatedText})` : ''
|
||||
return `${m.createdAt || ''} ${role}: ${content}${translation}`
|
||||
}).join('\n')
|
||||
}
|
||||
Reference in New Issue
Block a user