Merge pull request #334 from iaineng/dev

fix: 改进会话粘性机制,支持metadata.user_id并修复cache_control导致的会话切换问题
This commit is contained in:
Wesley Liddick
2025-09-03 21:36:03 +08:00
committed by GitHub

View File

@@ -13,11 +13,22 @@ class SessionHelper {
return null
}
// 1. 优先提取metadata.user_id
if (requestBody.metadata && requestBody.metadata.user_id) {
const hash = crypto
.createHash('sha256')
.update(requestBody.metadata.user_id)
.digest('hex')
.substring(0, 32)
logger.debug(`📋 Session hash generated from metadata.user_id: ${hash}`)
return hash
}
let cacheableContent = ''
const system = requestBody.system || ''
const messages = requestBody.messages || []
// 1. 优先提取带有cache_control: {"type": "ephemeral"}的内容
// 2. 提取带有cache_control: {"type": "ephemeral"}的内容
// 检查system中的cacheable内容
if (Array.isArray(system)) {
for (const part of system) {
@@ -30,13 +41,13 @@ class SessionHelper {
// 检查messages中的cacheable内容
for (const msg of messages) {
const content = msg.content || ''
let hasCacheControl = false
if (Array.isArray(content)) {
for (const part of content) {
if (part && part.cache_control && part.cache_control.type === 'ephemeral') {
if (part.type === 'text') {
cacheableContent += part.text || ''
}
// 其他类型如image不参与hash计算
hasCacheControl = true
break
}
}
} else if (
@@ -44,12 +55,31 @@ class SessionHelper {
msg.cache_control &&
msg.cache_control.type === 'ephemeral'
) {
// 罕见情况,但需要检查
cacheableContent += content
hasCacheControl = true
}
if (hasCacheControl) {
for (const message of messages) {
let messageText = ''
if (typeof message.content === 'string') {
messageText = message.content
} else if (Array.isArray(message.content)) {
messageText = message.content
.filter((part) => part.type === 'text')
.map((part) => part.text || '')
.join('')
}
if (messageText) {
cacheableContent += messageText
break
}
}
break
}
}
// 2. 如果有cacheable内容直接使用
// 3. 如果有cacheable内容直接使用
if (cacheableContent) {
const hash = crypto
.createHash('sha256')
@@ -60,7 +90,7 @@ class SessionHelper {
return hash
}
// 3. Fallback: 使用system内容
// 4. Fallback: 使用system内容
if (system) {
let systemText = ''
if (typeof system === 'string') {
@@ -76,7 +106,7 @@ class SessionHelper {
}
}
// 4. 最后fallback: 使用第一条消息内容
// 5. 最后fallback: 使用第一条消息内容
if (messages.length > 0) {
const firstMessage = messages[0]
let firstMessageText = ''