dsh-qq-affinity 0.0.0-stage → 0.14.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +55 -2
- package/client.js +3550 -0
- package/cordis.patch.yml +6 -0
- package/docs/DETAIL.md +332 -0
- package/icon.svg +12 -0
- package/index.js +128 -0
- package/lib/analyze.js +777 -0
- package/lib/api.js +984 -0
- package/lib/backfill.js +146 -0
- package/lib/bridge-server.js +78 -0
- package/lib/care.js +240 -0
- package/lib/features.js +200 -0
- package/lib/home.js +168 -0
- package/lib/inbound.js +120 -0
- package/lib/llm.js +137 -0
- package/lib/media.js +161 -0
- package/lib/onebot.js +207 -0
- package/lib/parse.js +184 -0
- package/lib/recover.js +46 -0
- package/lib/store.js +705 -0
- package/lib/util.js +186 -0
- package/lib/vision.js +108 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +38 -4
- package/scripts/api-e2e.mjs +538 -0
- package/scripts/backfill-e2e.mjs +142 -0
- package/scripts/backfill-live.mjs +60 -0
- package/scripts/bridge-e2e.mjs +137 -0
- package/scripts/care-e2e.mjs +217 -0
- package/scripts/check-hook-order.mjs +83 -0
- package/scripts/make-napcat-config.mjs +87 -0
- package/scripts/media-e2e.mjs +103 -0
- package/scripts/recover-e2e.mjs +75 -0
- package/scripts/selftest.mjs +159 -0
- package/scripts/strip-bom.mjs +27 -0
package/lib/analyze.js
ADDED
|
@@ -0,0 +1,777 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The two model-driven judgements of this plugin.
|
|
3
|
+
*
|
|
4
|
+
* `scorePerson` derives the three numbers for one QQ number. The "how much I
|
|
5
|
+
* like them" input is built from authentic messages only, so an accepted smart
|
|
6
|
+
* reply — which the other person does receive, and which therefore still counts
|
|
7
|
+
* toward how they feel about me — cannot inflate my own side of the chart.
|
|
8
|
+
*
|
|
9
|
+
* `suggestReplies` produces three candidate answers to the newest inbound
|
|
10
|
+
* message, each with the reasoning the user can judge before sending it.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { score as clampScore, clamp, isAiAuthored, formatTime, styleReply } from './util.js'
|
|
14
|
+
import { lastInbound, measure, renderTranscript, rowsForPerson } from './features.js'
|
|
15
|
+
import { completeText, extractJson, routeFor } from './llm.js'
|
|
16
|
+
import { collectImageBlocks, imagesOf, modelSeesImages } from './vision.js'
|
|
17
|
+
|
|
18
|
+
/** The shared persona instruction for both judgements. */
|
|
19
|
+
const SYSTEM = [
|
|
20
|
+
'你是聊天关系分析助手,只输出 JSON,不输出解释、前言或 Markdown 代码围栏。',
|
|
21
|
+
'评分是给使用者参考的估计值,允许不确定,但不许含糊其辞。',
|
|
22
|
+
'纪律:',
|
|
23
|
+
'1. 只依据给出的记录和统计推断,不编造记录之外的事件、共同经历或身份。',
|
|
24
|
+
'2. 分数范围 0-100,要有区分度,不要都落在 60-80 之间。',
|
|
25
|
+
'3. reasons 必须引用具体证据:谁在什么时候说了什么、回复间隔多久、谁先发起、消息长短对比。',
|
|
26
|
+
'4. 记录里标记为「AI代笔」的消息不是使用者本人的表达,禁止用它们推断使用者对对方的态度。',
|
|
27
|
+
].join('\n')
|
|
28
|
+
|
|
29
|
+
/** Whether the user allows images to leave the machine, and whether the model can read them. */
|
|
30
|
+
function visionAllowed(store) {
|
|
31
|
+
return store.state.settings.visionImages !== false
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Load the newest images of one analysis, when both gates are open.
|
|
36
|
+
*
|
|
37
|
+
* Nothing is downloaded unless the setting allows it AND the model route
|
|
38
|
+
* declares image input; otherwise the prompt keeps its `[图片]` / `[表情包]`
|
|
39
|
+
* markers and the result records why no picture was looked at.
|
|
40
|
+
* @param {object} ctx
|
|
41
|
+
* @param {import('./store.js').Store} store
|
|
42
|
+
* @param {Array<object>} rows
|
|
43
|
+
* @param {{ who?: 'them' | 'me' | 'both', limit?: number, signal?: AbortSignal }} [options]
|
|
44
|
+
*/
|
|
45
|
+
async function gatherVision(ctx, store, rows, options = {}) {
|
|
46
|
+
const info = { allowed: visionAllowed(store), available: false, found: 0, used: 0, reason: '' }
|
|
47
|
+
if (!info.allowed) return { ...info, blocks: [], lines: [], reason: 'disabled' }
|
|
48
|
+
const images = imagesOf(rows, { who: options.who ?? 'both' })
|
|
49
|
+
info.found = images.length
|
|
50
|
+
if (images.length === 0) return { ...info, blocks: [], lines: [], reason: 'no-images' }
|
|
51
|
+
const route = await routeFor(ctx)
|
|
52
|
+
info.available = await modelSeesImages(ctx, route.provider, route.model)
|
|
53
|
+
if (!info.available) return { ...info, blocks: [], lines: [], reason: 'model-without-vision' }
|
|
54
|
+
const collected = await collectImageBlocks(ctx, images, { limit: options.limit ?? 3, signal: options.signal })
|
|
55
|
+
info.used = collected.used
|
|
56
|
+
return { ...info, blocks: collected.blocks, lines: collected.lines, reason: collected.reason }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The prompt paragraph that tells the model what the attached images are. */
|
|
60
|
+
function visionBlock(vision) {
|
|
61
|
+
if (vision.blocks.length === 0) return ''
|
|
62
|
+
return [
|
|
63
|
+
'',
|
|
64
|
+
`【另外附了 ${vision.blocks.length} 张图片/表情包,按时间顺序,可以直接看内容】`,
|
|
65
|
+
...vision.lines.map(line => `- ${line}`),
|
|
66
|
+
'表情包和图片里的文字、梗、情绪都算证据,可以据此判断对方的语气,也可以据此写回复。',
|
|
67
|
+
].join('\n')
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Render the measurement block for the prompt. */
|
|
71
|
+
function measurementBlock(features, extra = {}) { return [
|
|
72
|
+
`总消息数 ${features.totalMessages}(对方 ${features.theirMessages} / 我 ${features.myMessages},其中我的真实表达 ${features.myAuthenticMessages} 条、AI代笔 ${features.aiAdoptedMessages} 条)`,
|
|
73
|
+
`平均字数:对方 ${features.theirAvgChars} / 我 ${features.myAvgChars}`,
|
|
74
|
+
`提问率:对方 ${features.theirQuestionRatio} / 我 ${features.myQuestionRatio}`,
|
|
75
|
+
`每条消息的颜文字或表情标记数:对方 ${features.theirDecorationPerMessage} / 我 ${features.myDecorationPerMessage}`,
|
|
76
|
+
`谁先开口的比例:对方 ${features.theirInitiativeRatio} / 我 ${features.myInitiativeRatio}`,
|
|
77
|
+
`中位回复间隔(秒):对方回我 ${features.theirMedianReplySeconds} / 我回对方 ${features.myMedianReplySeconds}`,
|
|
78
|
+
`对方深夜(23:00-05:00)消息占比 ${features.theirNightRatio},连续追问 ${features.theirDoubleTextCount} 次`,
|
|
79
|
+
`覆盖天数 ${features.spanDays},活跃天数 ${features.activeDays},距最后一条消息 ${features.lastContactDays ?? '—'} 天`,
|
|
80
|
+
...(extra.lines ?? []),
|
|
81
|
+
].join('\n')
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Find one person row, with a readable display name. */
|
|
85
|
+
function nameOf(store, uin) {
|
|
86
|
+
const person = store.person(uin)
|
|
87
|
+
const name = person === undefined || person.names.length === 0 ? '' : person.names[person.names.length - 1]
|
|
88
|
+
return name === '' ? `QQ ${uin}` : name
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Ask for a JSON answer and retry once if the reply is not parseable.
|
|
93
|
+
*
|
|
94
|
+
* Models occasionally wrap the object in prose or stop early; a single stricter
|
|
95
|
+
* retry turns that from a user-visible failure into a slower success.
|
|
96
|
+
* @returns {Promise<any>} the parsed object.
|
|
97
|
+
*/
|
|
98
|
+
async function askForJson(ctx, request) {
|
|
99
|
+
const first = await completeText(ctx, request)
|
|
100
|
+
try {
|
|
101
|
+
return extractJson(first)
|
|
102
|
+
} catch (firstError) {
|
|
103
|
+
const retry = await completeText(ctx, {
|
|
104
|
+
...request,
|
|
105
|
+
prompt: `${request.prompt}\n\n【重要】上一次的回答无法解析。这次只输出那个 JSON 对象本身,不要解释、不要 Markdown 代码围栏、不要任何前后缀。`,
|
|
106
|
+
maxTokens: Math.min(8000, Math.round((request.maxTokens ?? 1600) * 1.5)),
|
|
107
|
+
temperature: 0.1,
|
|
108
|
+
})
|
|
109
|
+
try {
|
|
110
|
+
return extractJson(retry)
|
|
111
|
+
} catch (secondError) {
|
|
112
|
+
throw new Error(
|
|
113
|
+
`模型没有返回可解析的 JSON(试了两次)。`
|
|
114
|
+
+ `第一次:${firstError instanceof Error ? firstError.message : String(firstError)};`
|
|
115
|
+
+ `第二次:${secondError instanceof Error ? secondError.message : String(secondError)}`,
|
|
116
|
+
)
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Judge one person: their favorability, mine, and our intimacy.
|
|
123
|
+
* @param {object} ctx - Cordis context.
|
|
124
|
+
* @param {import('./store.js').Store} store
|
|
125
|
+
* @param {string} uin - the other person's QQ number.
|
|
126
|
+
* @param {{ signal?: AbortSignal }} [options]
|
|
127
|
+
* @returns {Promise<object>} the stored score.
|
|
128
|
+
*/
|
|
129
|
+
export async function scorePerson(ctx, store, uin, options = {}) {
|
|
130
|
+
const rows = rowsForPerson(store, uin)
|
|
131
|
+
if (rows.length < 8) {
|
|
132
|
+
throw new Error(`关于 QQ ${uin} 的记录太少(${rows.length} 条),至少需要 8 条才能给出有意义的判断。`)
|
|
133
|
+
}
|
|
134
|
+
const features = measure(rows, uin)
|
|
135
|
+
const targetName = nameOf(store, uin)
|
|
136
|
+
const maxChars = store.state.settings.maxTranscriptChars
|
|
137
|
+
const all = renderTranscript(rows, { targetUin: uin, targetName, maxChars })
|
|
138
|
+
const authentic = features.aiAdoptedMessages > 0
|
|
139
|
+
? renderTranscript(rows, {
|
|
140
|
+
targetUin: uin,
|
|
141
|
+
targetName,
|
|
142
|
+
excludeAdopted: true,
|
|
143
|
+
maxChars: Math.max(3000, Math.floor(maxChars / 2)),
|
|
144
|
+
})
|
|
145
|
+
: undefined
|
|
146
|
+
|
|
147
|
+
const parts = [
|
|
148
|
+
`请分析「我」与「${targetName}」(QQ ${uin})的关系。`,
|
|
149
|
+
'',
|
|
150
|
+
'【统计】',
|
|
151
|
+
measurementBlock(features),
|
|
152
|
+
'',
|
|
153
|
+
'【完整对话】',
|
|
154
|
+
all.text === '' ? '(无)' : all.text,
|
|
155
|
+
]
|
|
156
|
+
if (authentic !== undefined) {
|
|
157
|
+
parts.push(
|
|
158
|
+
'',
|
|
159
|
+
'【我本人的真实表达(已剔除 AI 代笔消息;判断「我对TA」只能依据这里和统计中我的真实表达)】',
|
|
160
|
+
authentic.text === '' ? '(没有可用的真实表达)' : authentic.text,
|
|
161
|
+
)
|
|
162
|
+
}
|
|
163
|
+
parts.push(
|
|
164
|
+
'',
|
|
165
|
+
'【输出格式】',
|
|
166
|
+
JSON.stringify({
|
|
167
|
+
theirFavor: { score: 0, reasons: ['…', '…'] },
|
|
168
|
+
myFavor: { score: 0, reasons: ['…', '…'] },
|
|
169
|
+
intimacy: { score: 0, reasons: ['…', '…'] },
|
|
170
|
+
signals: ['…', '…'],
|
|
171
|
+
confidence: 0.5,
|
|
172
|
+
}, null, 2),
|
|
173
|
+
'',
|
|
174
|
+
'字段含义:',
|
|
175
|
+
'theirFavor = 对方对我的好感度;myFavor = 我对对方的好感度;intimacy = 我们的亲密度(熟悉、放松、互相接得住的程度)。',
|
|
176
|
+
'My favor 必须只由我的真实表达推出;如果我的真实表达很少,就明确说明证据不足并给较低 confidence。',
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
// Look at the newest pictures only when both the user and the model allow it.
|
|
180
|
+
const vision = await gatherVision(ctx, store, rows, { who: 'both', limit: 3, signal: options.signal })
|
|
181
|
+
parts.push(visionBlock(vision))
|
|
182
|
+
|
|
183
|
+
const parsed = await askForJson(ctx, {
|
|
184
|
+
system: SYSTEM,
|
|
185
|
+
prompt: parts.join('\n'),
|
|
186
|
+
images: vision.blocks,
|
|
187
|
+
maxTokens: 3000,
|
|
188
|
+
temperature: 0.3,
|
|
189
|
+
signal: options.signal,
|
|
190
|
+
purpose: 'qq-affinity-score',
|
|
191
|
+
})
|
|
192
|
+
const readBlock = (value) => {
|
|
193
|
+
if (value !== null && typeof value === 'object') {
|
|
194
|
+
return {
|
|
195
|
+
score: clampScore(value.score),
|
|
196
|
+
reasons: Array.isArray(value.reasons) ? value.reasons.map(item => String(item)).slice(0, 4) : [],
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
return { score: clampScore(value), reasons: [] }
|
|
200
|
+
}
|
|
201
|
+
const result = {
|
|
202
|
+
theirFavor: readBlock(parsed.theirFavor),
|
|
203
|
+
myFavor: readBlock(parsed.myFavor),
|
|
204
|
+
intimacy: readBlock(parsed.intimacy),
|
|
205
|
+
signals: Array.isArray(parsed.signals) ? parsed.signals.map(item => String(item)).slice(0, 6) : [],
|
|
206
|
+
confidence: Math.round(clamp(parsed.confidence ?? 0.5, 0, 1) * 100) / 100,
|
|
207
|
+
basedOn: {
|
|
208
|
+
totalMessages: features.totalMessages,
|
|
209
|
+
myAuthenticMessages: features.myAuthenticMessages,
|
|
210
|
+
aiAdoptedMessages: features.aiAdoptedMessages,
|
|
211
|
+
conversations: store.state.conversations
|
|
212
|
+
.filter(row => row.enabled && ((row.participants ?? []).includes(uin) || row.peerUin === uin))
|
|
213
|
+
.map(row => row.id),
|
|
214
|
+
},
|
|
215
|
+
stale: false,
|
|
216
|
+
vision: { allowed: vision.allowed, available: vision.available, found: vision.found, used: vision.used, reason: vision.reason },
|
|
217
|
+
}
|
|
218
|
+
return store.saveScore(uin, result)
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** The strategies the three suggestions are drawn from. */
|
|
222
|
+
const STRATEGIES = [
|
|
223
|
+
'共情接住:先确认对方的情绪或处境,让 TA 觉得被听懂,不急着给建议。',
|
|
224
|
+
'具体好奇:问一个关于 TA 刚说的事情的细节,把话头递回去,让 TA 愿意多讲。',
|
|
225
|
+
'轻松推进:用具体、轻量的下一步(约、分享、共同话题)把对话往前带,不给压力。',
|
|
226
|
+
]
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Write one reply that can be sent as-is, for the automatic care mode.
|
|
230
|
+
* Unlike {@link suggestReplies} this returns a single line of text, already
|
|
231
|
+
* short enough to look like a chat message and stripped of any framing.
|
|
232
|
+
* @param {object} ctx
|
|
233
|
+
* @param {import('./store.js').Store} store
|
|
234
|
+
* @param {object} request
|
|
235
|
+
* @param {string} request.conversationId
|
|
236
|
+
* @param {string} request.uin - the person being answered.
|
|
237
|
+
* @param {number} [request.maxChars]
|
|
238
|
+
* @param {AbortSignal} [request.signal]
|
|
239
|
+
* @returns {Promise<string>}
|
|
240
|
+
*/
|
|
241
|
+
export async function writeAutoReply(ctx, store, request) {
|
|
242
|
+
const conversation = store.conversation(request.conversationId)
|
|
243
|
+
if (conversation === undefined) throw new Error('找不到这个对话。')
|
|
244
|
+
const uin = request.uin
|
|
245
|
+
const rows = rowsForPerson(store, uin)
|
|
246
|
+
const targetName = nameOf(store, uin)
|
|
247
|
+
const stored = store.score(uin)
|
|
248
|
+
const conversationRows = store.messages(request.conversationId).sort((a, b) => a.ts - b.ts)
|
|
249
|
+
const newest = lastInbound(conversationRows, uin)
|
|
250
|
+
if (newest === undefined) throw new Error('这个对话里没有对方的消息。')
|
|
251
|
+
|
|
252
|
+
const features = rows.length > 0 ? measure(rows, uin) : undefined
|
|
253
|
+
const recent = renderTranscript(conversationRows, { targetUin: uin, targetName, maxChars: 4000 })
|
|
254
|
+
const input = renderTranscript(rows, {
|
|
255
|
+
targetUin: uin,
|
|
256
|
+
targetName,
|
|
257
|
+
excludeAdopted: true,
|
|
258
|
+
maxChars: 2500,
|
|
259
|
+
})
|
|
260
|
+
|
|
261
|
+
const prompt = [
|
|
262
|
+
`「${targetName}」刚给我发了这条消息,请以我的身份回一句。`,
|
|
263
|
+
`[${new Date(newest.ts).toLocaleString('zh-CN')}] ${targetName}:${newest.text}`,
|
|
264
|
+
'',
|
|
265
|
+
'【最近的对话】',
|
|
266
|
+
recent.text === '' ? '(无)' : recent.text,
|
|
267
|
+
'',
|
|
268
|
+
'【我平时说话的样子(只作语气参考,不要复述内容)】',
|
|
269
|
+
input.text === '' ? '(没有足够样本,按普通口语回)' : input.text,
|
|
270
|
+
'',
|
|
271
|
+
'【关系背景】',
|
|
272
|
+
stored === undefined
|
|
273
|
+
? '(还没做过好感度分析)'
|
|
274
|
+
: `对方对我 ${stored.theirFavor.score},我对对方 ${stored.myFavor.score},亲密度 ${stored.intimacy.score}。`,
|
|
275
|
+
features === undefined
|
|
276
|
+
? ''
|
|
277
|
+
: `对方平均每条 ${features.theirAvgChars} 字,我平均 ${features.myAvgChars} 字。`,
|
|
278
|
+
'',
|
|
279
|
+
'【要求】',
|
|
280
|
+
`1. 只输出这一句要发出去的话本身,不要引号、不要「我:」、不要任何解释或换行。`,
|
|
281
|
+
`2. 长度不超过 ${request.maxChars ?? 60} 个字,宁短勿长。`,
|
|
282
|
+
'3. 像真人打字:口语、自然。不要用任何 emoji 或表情符号。',
|
|
283
|
+
'4. 不要用句号、逗号、顿号、分号、冒号,需要断句就空一格;句尾不要加句号。',
|
|
284
|
+
'5. 不要问超过一个问题,不要连着寒暄,不要用「哈哈」「亲」这类套话开头。',
|
|
285
|
+
'5. 如果对方说的是坏消息、求助或情绪问题,先接住情绪,不要急着给建议。',
|
|
286
|
+
'6. 不要承诺时间、地点、金额这类具体事项 —— 这些需要我自己确认。',
|
|
287
|
+
].filter(line => line !== '').join('\n')
|
|
288
|
+
|
|
289
|
+
// The message being answered may itself be a picture or a sticker.
|
|
290
|
+
const vision = await gatherVision(ctx, store, [newest], { who: 'them', limit: 2, signal: request.signal })
|
|
291
|
+
|
|
292
|
+
const answer = await completeText(ctx, {
|
|
293
|
+
system: '你替使用者回一条微信/QQ 消息。只输出要发送的正文,不要任何前后缀。',
|
|
294
|
+
prompt: `${prompt}${visionBlock(vision)}`,
|
|
295
|
+
images: vision.blocks,
|
|
296
|
+
maxTokens: 800,
|
|
297
|
+
temperature: 0.85,
|
|
298
|
+
signal: request.signal,
|
|
299
|
+
purpose: 'qq-affinity-auto',
|
|
300
|
+
})
|
|
301
|
+
|
|
302
|
+
let text = String(answer ?? '')
|
|
303
|
+
.replace(/^```[\s\S]*?\n/, '')
|
|
304
|
+
.replace(/```$/, '')
|
|
305
|
+
.replace(/^(我|回复|回答)\s*[::]\s*/, '')
|
|
306
|
+
.replace(/^["'“”「『]+|["'“”」』]+$/g, '')
|
|
307
|
+
.split('\n')
|
|
308
|
+
.map(line => line.trim())
|
|
309
|
+
.filter(line => line !== '')
|
|
310
|
+
.join(' ')
|
|
311
|
+
// Same chat shape as the suggestions: no emoji, punctuation as a single space.
|
|
312
|
+
text = styleReply(text)
|
|
313
|
+
|
|
314
|
+
const limit = request.maxChars ?? 60
|
|
315
|
+
if (text.length > limit) {
|
|
316
|
+
text = `${styleReply(text.slice(0, limit - 1)).replace(/\s+$/, '')}…`
|
|
317
|
+
}
|
|
318
|
+
if (text === '') throw new Error('模型没有给出可发送的内容。')
|
|
319
|
+
return text
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Produce three candidate replies to the newest inbound message.
|
|
324
|
+
* @param {object} ctx
|
|
325
|
+
* @param {import('./store.js').Store} store
|
|
326
|
+
* @param {string} conversationId
|
|
327
|
+
* @param {{ signal?: AbortSignal }} [options]
|
|
328
|
+
* @returns {Promise<object>} the stored suggestion batch.
|
|
329
|
+
*/
|
|
330
|
+
export async function suggestReplies(ctx, store, conversationId, options = {}) {
|
|
331
|
+
const conversation = store.conversation(conversationId)
|
|
332
|
+
if (conversation === undefined) throw new Error('找不到这个对话。')
|
|
333
|
+
if (conversation.enabled !== true) throw new Error('这个对话还没有开启,开启后才会读取和生成提示。')
|
|
334
|
+
|
|
335
|
+
const rows = store.messages(conversationId).sort((a, b) => a.ts - b.ts)
|
|
336
|
+
if (rows.length === 0) throw new Error('这个对话还没有导入任何消息。')
|
|
337
|
+
const inbound = rows.filter(row => row.direction === 'in')
|
|
338
|
+
const newestInbound = inbound[inbound.length - 1]
|
|
339
|
+
const targetUin = conversation.kind === 'c2c' && conversation.peerUin !== ''
|
|
340
|
+
? conversation.peerUin
|
|
341
|
+
: (newestInbound?.senderUin ?? '')
|
|
342
|
+
const newest = targetUin === '' ? newestInbound : lastInbound(rows, targetUin)
|
|
343
|
+
if (newest === undefined) throw new Error('这个对话里没有对方发来的消息,暂时没有需要回的。')
|
|
344
|
+
|
|
345
|
+
const personRows = targetUin === '' ? rows : rowsForPerson(store, targetUin)
|
|
346
|
+
const features = measure(personRows, targetUin)
|
|
347
|
+
const targetName = targetUin === '' ? '对方' : nameOf(store, targetUin)
|
|
348
|
+
const stored = targetUin === '' ? undefined : store.score(targetUin)
|
|
349
|
+
const maxChars = Math.max(4000, Math.floor(store.state.settings.maxTranscriptChars / 2))
|
|
350
|
+
const transcript = renderTranscript(rows, { targetUin, targetName, maxChars })
|
|
351
|
+
|
|
352
|
+
const scoreLine = stored === undefined
|
|
353
|
+
? '(还没有做过好感度分析)'
|
|
354
|
+
: `对方对我的好感度 ${stored.theirFavor.score};我对对方的好感度 ${stored.myFavor.score};亲密度 ${stored.intimacy.score}。`
|
|
355
|
+
|
|
356
|
+
const prompt = [
|
|
357
|
+
`「${targetName}」刚给我发了这条消息:`,
|
|
358
|
+
`[${new Date(newest.ts).toLocaleString('zh-CN')}] ${targetName}:${newest.text}`,
|
|
359
|
+
'',
|
|
360
|
+
'【当前关系判断】',
|
|
361
|
+
scoreLine,
|
|
362
|
+
'',
|
|
363
|
+
'【统计】',
|
|
364
|
+
measurementBlock(features),
|
|
365
|
+
'',
|
|
366
|
+
'【最近的对话】',
|
|
367
|
+
transcript.text === '' ? '(无)' : transcript.text,
|
|
368
|
+
'',
|
|
369
|
+
'【任务】',
|
|
370
|
+
'给出三条我可以直接发给 TA 的回复候选,目标是让 TA 对我的好感度上升,同时不显得刻意或油腻。',
|
|
371
|
+
'三条必须分别采用下面三种策略,并且互相明显不同(不要换词重说同一句):',
|
|
372
|
+
...STRATEGIES.map((line, index) => `${index + 1}. ${line}`),
|
|
373
|
+
'',
|
|
374
|
+
'每条回复要:像真人打字(可以短、可以有语气词),长度贴近我平时的说话习惯,不复述对方原话,不堆问候语。',
|
|
375
|
+
'不要用任何 emoji 或表情符号;不要用句号、逗号、顿号、分号、冒号,需要断句就空一格;句尾不要加句号。',
|
|
376
|
+
'expectedGain 用一句话说明这条为什么会拉近距离;risk 用一句话说明可能翻车的地方。',
|
|
377
|
+
'',
|
|
378
|
+
'【输出格式】',
|
|
379
|
+
JSON.stringify({
|
|
380
|
+
options: [
|
|
381
|
+
{ strategy: '共情接住', text: '……', why: '……', expectedGain: '……', risk: '……' },
|
|
382
|
+
{ strategy: '具体好奇', text: '……', why: '……', expectedGain: '……', risk: '……' },
|
|
383
|
+
{ strategy: '轻松推进', text: '……', why: '……', expectedGain: '……', risk: '……' },
|
|
384
|
+
],
|
|
385
|
+
}, null, 2),
|
|
386
|
+
].join('\n')
|
|
387
|
+
|
|
388
|
+
// The line being answered may be a picture or a sticker; look at it if allowed.
|
|
389
|
+
const vision = await gatherVision(ctx, store, [newest], { who: 'them', limit: 2, signal: options.signal })
|
|
390
|
+
|
|
391
|
+
const parsed = await askForJson(ctx, {
|
|
392
|
+
system: SYSTEM,
|
|
393
|
+
prompt: `${prompt}${visionBlock(vision)}`,
|
|
394
|
+
images: vision.blocks,
|
|
395
|
+
maxTokens: 1600,
|
|
396
|
+
temperature: 0.8,
|
|
397
|
+
signal: options.signal,
|
|
398
|
+
purpose: 'qq-affinity-suggest',
|
|
399
|
+
})
|
|
400
|
+
const rawOptions = Array.isArray(parsed.options) ? parsed.options : []
|
|
401
|
+
if (rawOptions.length === 0) throw new Error('模型没有返回可用的回复候选,请重试。')
|
|
402
|
+
|
|
403
|
+
const batchId = `b${Date.now().toString(36)}`
|
|
404
|
+
const batch = {
|
|
405
|
+
id: batchId,
|
|
406
|
+
conversationId,
|
|
407
|
+
targetUin,
|
|
408
|
+
targetName,
|
|
409
|
+
basedOnMessageId: newest.id,
|
|
410
|
+
basedOnText: newest.text,
|
|
411
|
+
createdAt: new Date().toISOString(),
|
|
412
|
+
options: rawOptions.slice(0, 3).map((option, index) => ({
|
|
413
|
+
id: `${batchId}-${index + 1}`,
|
|
414
|
+
strategy: String(option.strategy ?? STRATEGIES[index] ?? '备选'),
|
|
415
|
+
text: styleReply(option.text),
|
|
416
|
+
why: String(option.why ?? '').trim(),
|
|
417
|
+
expectedGain: String(option.expectedGain ?? '').trim(),
|
|
418
|
+
risk: String(option.risk ?? '').trim(),
|
|
419
|
+
adopted: false,
|
|
420
|
+
adoptedAt: null,
|
|
421
|
+
})).filter(option => option.text !== ''),
|
|
422
|
+
}
|
|
423
|
+
if (batch.options.length === 0) throw new Error('模型返回的候选都是空的,请重试。')
|
|
424
|
+
return store.pushSuggestions(conversationId, batch)
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/** One MBTI axis, left-to-right: the two poles it chooses between. */
|
|
428
|
+
const MBTI_AXES = [
|
|
429
|
+
{ axis: 'EI', poles: ['E', 'I'], labels: ['外向', '内向'] },
|
|
430
|
+
{ axis: 'NS', poles: ['N', 'S'], labels: ['直觉', '实感'] },
|
|
431
|
+
{ axis: 'TF', poles: ['T', 'F'], labels: ['思考', '情感'] },
|
|
432
|
+
{ axis: 'JP', poles: ['J', 'P'], labels: ['判断', '知觉'] },
|
|
433
|
+
]
|
|
434
|
+
|
|
435
|
+
/**
|
|
436
|
+
* Validate one MBTI block from the model.
|
|
437
|
+
*
|
|
438
|
+
* The four letters are rebuilt from the axis letters when all four are present,
|
|
439
|
+
* so a model that contradicts itself cannot produce a type like `INFP` with a
|
|
440
|
+
* `J` axis. Anything unparseable yields `null` and the panel simply omits the
|
|
441
|
+
* card, rather than showing an invented type.
|
|
442
|
+
* @param {unknown} value
|
|
443
|
+
* @returns {{ type: string, nickname: string, confidence: number, caveat: string,
|
|
444
|
+
* axes: Array<{ axis: string, letter: string, strength: number, reason: string, labels: string[] }> } | null}
|
|
445
|
+
*/
|
|
446
|
+
function parseMbti(value) {
|
|
447
|
+
if (value === null || typeof value !== 'object') return null
|
|
448
|
+
const rawAxes = Array.isArray(value.axes) ? value.axes : []
|
|
449
|
+
const axes = []
|
|
450
|
+
for (const definition of MBTI_AXES) {
|
|
451
|
+
const found = rawAxes.find(item => item !== null && typeof item === 'object'
|
|
452
|
+
&& String(item.axis ?? '').toUpperCase() === definition.axis)
|
|
453
|
+
const letter = String(found?.letter ?? '').toUpperCase()
|
|
454
|
+
if (!definition.poles.includes(letter)) continue
|
|
455
|
+
axes.push({
|
|
456
|
+
axis: definition.axis,
|
|
457
|
+
letter,
|
|
458
|
+
labels: definition.labels,
|
|
459
|
+
strength: Math.round(clamp(Number(found?.strength ?? 50), 0, 100)),
|
|
460
|
+
reason: String(found?.reason ?? '').trim(),
|
|
461
|
+
})
|
|
462
|
+
}
|
|
463
|
+
if (axes.length === 0) return null
|
|
464
|
+
const rebuilt = axes.length === 4 ? axes.map(item => item.letter).join('') : ''
|
|
465
|
+
const declared = String(value.type ?? '').toUpperCase()
|
|
466
|
+
const type = /^[EI][NS][TF][JP]$/.test(rebuilt) ? rebuilt : (/^[EI][NS][TF][JP]$/.test(declared) ? declared : '')
|
|
467
|
+
if (type === '') return null
|
|
468
|
+
return {
|
|
469
|
+
type,
|
|
470
|
+
nickname: String(value.nickname ?? '').trim(),
|
|
471
|
+
confidence: Math.round(clamp(Number(value.confidence ?? 0.5), 0, 1) * 100) / 100,
|
|
472
|
+
caveat: String(value.caveat ?? '').trim(),
|
|
473
|
+
axes,
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
/**
|
|
478
|
+
* Analyse the user themself, across every enabled conversation.
|
|
479
|
+
*
|
|
480
|
+
* Only messages the user actually typed are read: suggestions the AI wrote and
|
|
481
|
+
* auto-replies the host sent are excluded by the same rule that keeps them out
|
|
482
|
+
* of "my favour" — otherwise the profile would describe the model, not the user.
|
|
483
|
+
* @param {object} ctx
|
|
484
|
+
* @param {import('./store.js').Store} store
|
|
485
|
+
* @param {{ signal?: AbortSignal }} [options]
|
|
486
|
+
* @returns {Promise<object>} the stored profile.
|
|
487
|
+
*/
|
|
488
|
+
export async function analyzeSelf(ctx, store, options = {}) {
|
|
489
|
+
const selfUin = store.state.settings.selfUin
|
|
490
|
+
if (selfUin === '') throw new Error('请先在设置里填写你的 QQ 号:自我分析需要它认出哪些话是你说的。')
|
|
491
|
+
|
|
492
|
+
const enabled = store.state.conversations.filter(row => row.enabled === true)
|
|
493
|
+
if (enabled.length === 0) throw new Error('还没有开启任何对话,没有可分析的内容。')
|
|
494
|
+
|
|
495
|
+
const mine = []
|
|
496
|
+
const perConversation = []
|
|
497
|
+
let excluded = 0
|
|
498
|
+
for (const conversation of enabled) {
|
|
499
|
+
const rows = store.messages(conversation.id)
|
|
500
|
+
const outgoing = rows.filter(row => row.direction === 'out')
|
|
501
|
+
const authentic = outgoing.filter(row => !isAiAuthored(row))
|
|
502
|
+
excluded += outgoing.length - authentic.length
|
|
503
|
+
for (const row of authentic) mine.push(row)
|
|
504
|
+
if (authentic.length > 0) {
|
|
505
|
+
perConversation.push({
|
|
506
|
+
id: conversation.id,
|
|
507
|
+
title: conversation.title,
|
|
508
|
+
kind: conversation.kind,
|
|
509
|
+
count: authentic.length,
|
|
510
|
+
avgChars: Math.round(authentic.reduce((total, row) => total + row.text.length, 0) / authentic.length),
|
|
511
|
+
})
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
if (mine.length < 20) {
|
|
515
|
+
throw new Error(`你真实发出的消息只有 ${mine.length} 条,至少需要 20 条才能看出说话风格。`)
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
mine.sort((left, right) => left.ts - right.ts)
|
|
519
|
+
const picked = mine.length > 220 ? mine.slice(-220) : mine
|
|
520
|
+
const transcript = picked
|
|
521
|
+
.map(row => {
|
|
522
|
+
const text = row.text.replace(/\s+/g, ' ').slice(0, 160)
|
|
523
|
+
return `[${formatTime(row.ts).slice(5, 16)}] 我:${text}`
|
|
524
|
+
})
|
|
525
|
+
.join('\n')
|
|
526
|
+
.slice(-12000)
|
|
527
|
+
|
|
528
|
+
const avgChars = Math.round(mine.reduce((total, row) => total + row.text.length, 0) / mine.length)
|
|
529
|
+
const questionShare = Math.round(mine.filter(row => /[??]/.test(row.text)).length / mine.length * 100)
|
|
530
|
+
const decorated = Math.round(mine.filter(row => /\[图片\]|\[表情\]|\[语音\]/.test(row.text)).length / mine.length * 100)
|
|
531
|
+
|
|
532
|
+
const prompt = [
|
|
533
|
+
'下面这些消息都是「我」本人打出来的(已经排除了 AI 代笔和自动回复)。请分析我是一个什么样的聊天对象。',
|
|
534
|
+
'',
|
|
535
|
+
'【我说的原话(按时间)】',
|
|
536
|
+
transcript,
|
|
537
|
+
'',
|
|
538
|
+
'【统计】',
|
|
539
|
+
`真实发出 ${mine.length} 条(另有 ${excluded} 条 AI 代笔已排除);平均每条 ${avgChars} 字;带问号 ${questionShare}%;带图片/表情 ${decorated}%。`,
|
|
540
|
+
'各对话分布:',
|
|
541
|
+
perConversation.map(row => `- ${row.title === '' ? row.id : row.title}(${row.kind === 'group' ? '群' : '私聊'}):${row.count} 条,平均 ${row.avgChars} 字`).join('\n'),
|
|
542
|
+
'',
|
|
543
|
+
'【纪律】',
|
|
544
|
+
'1. 只根据这些原话判断。不要猜我的职业、年龄、所在地、外貌。',
|
|
545
|
+
'2. 每条特点都要给证据:引用我的原话片段,或引用上面的统计。',
|
|
546
|
+
'3. blindSpots(我的问题)要具体、可操作,别写「要注意沟通」这种空话;能指到某类对话更好。',
|
|
547
|
+
'4. patternsByPerson 只在记录里确实有差异时写,没有就给空数组。',
|
|
548
|
+
'5. MBTI 只从我的文字倾向推,四轴给强度(0-100),caveat 一句话说明不是正式测评。',
|
|
549
|
+
'',
|
|
550
|
+
'【输出格式】',
|
|
551
|
+
JSON.stringify({
|
|
552
|
+
mbti: {
|
|
553
|
+
type: 'ENFJ',
|
|
554
|
+
nickname: '主人公',
|
|
555
|
+
confidence: 0.5,
|
|
556
|
+
axes: [
|
|
557
|
+
{ axis: 'EI', letter: 'E', strength: 60, reason: '主动起话题多' },
|
|
558
|
+
{ axis: 'NS', letter: 'N', strength: 58, reason: '常聊感受和可能性' },
|
|
559
|
+
{ axis: 'TF', letter: 'F', strength: 66, reason: '先接情绪' },
|
|
560
|
+
{ axis: 'JP', letter: 'J', strength: 55, reason: '爱约具体时间' },
|
|
561
|
+
],
|
|
562
|
+
caveat: '从文字推断的倾向,不是正式测评。',
|
|
563
|
+
},
|
|
564
|
+
summary: '一句话说我是什么样的人,30 字以内',
|
|
565
|
+
tags: ['主动', '爱接梗'],
|
|
566
|
+
traits: [{ label: '主动找话题', strength: 0.8, evidence: '在 5 个对话里都由我先开口' }],
|
|
567
|
+
speakingStyle: '句子长短、语气词、标点、用不用表情',
|
|
568
|
+
strengths: ['我聊得好在哪,2-4 条,要带证据'],
|
|
569
|
+
blindSpots: ['我容易踩的坑,2-4 条,具体可改'],
|
|
570
|
+
patternsByPerson: [{ name: '某人', note: '对他我明显更爱用表情、回复更快' }],
|
|
571
|
+
advise: ['具体建议,2-4 条'],
|
|
572
|
+
confidence: 0.6,
|
|
573
|
+
}, null, 2),
|
|
574
|
+
'',
|
|
575
|
+
'traits 给 4-6 条。',
|
|
576
|
+
].filter(line => line !== '').join('\n')
|
|
577
|
+
|
|
578
|
+
// My own pictures count too: how I use stickers is part of my style.
|
|
579
|
+
const vision = await gatherVision(ctx, store, mine, { who: 'me', limit: 3, signal: options.signal })
|
|
580
|
+
|
|
581
|
+
const parsed = await askForJson(ctx, {
|
|
582
|
+
system: SYSTEM,
|
|
583
|
+
prompt: `${prompt}${visionBlock(vision)}`,
|
|
584
|
+
images: vision.blocks,
|
|
585
|
+
maxTokens: 2600,
|
|
586
|
+
temperature: 0.4,
|
|
587
|
+
signal: options.signal,
|
|
588
|
+
purpose: 'qq-affinity-self',
|
|
589
|
+
})
|
|
590
|
+
|
|
591
|
+
const text = (value) => String(value ?? '').trim()
|
|
592
|
+
const list = (value, limit) => (Array.isArray(value) ? value.map(item => text(item)).filter(item => item !== '').slice(0, limit) : [])
|
|
593
|
+
const traits = Array.isArray(parsed.traits)
|
|
594
|
+
? parsed.traits
|
|
595
|
+
.filter(item => item !== null && typeof item === 'object')
|
|
596
|
+
.map(item => ({
|
|
597
|
+
label: text(item.label),
|
|
598
|
+
evidence: text(item.evidence),
|
|
599
|
+
strength: Math.round(clamp(Number(item.strength ?? 0.6), 0, 1) * 100) / 100,
|
|
600
|
+
}))
|
|
601
|
+
.filter(item => item.label !== '')
|
|
602
|
+
.slice(0, 6)
|
|
603
|
+
: []
|
|
604
|
+
const patterns = Array.isArray(parsed.patternsByPerson)
|
|
605
|
+
? parsed.patternsByPerson
|
|
606
|
+
.filter(item => item !== null && typeof item === 'object')
|
|
607
|
+
.map(item => ({ name: text(item.name), note: text(item.note) }))
|
|
608
|
+
.filter(item => item.name !== '' && item.note !== '')
|
|
609
|
+
.slice(0, 5)
|
|
610
|
+
: []
|
|
611
|
+
|
|
612
|
+
const result = {
|
|
613
|
+
mbti: parseMbti(parsed.mbti),
|
|
614
|
+
summary: text(parsed.summary),
|
|
615
|
+
tags: list(parsed.tags, 6),
|
|
616
|
+
traits,
|
|
617
|
+
speakingStyle: text(parsed.speakingStyle),
|
|
618
|
+
strengths: list(parsed.strengths, 4),
|
|
619
|
+
blindSpots: list(parsed.blindSpots, 4),
|
|
620
|
+
patternsByPerson: patterns,
|
|
621
|
+
advise: list(parsed.advise, 4),
|
|
622
|
+
confidence: Math.round(clamp(parsed.confidence ?? 0.5, 0, 1) * 100) / 100,
|
|
623
|
+
vision: { allowed: vision.allowed, available: vision.available, found: vision.found, used: vision.used, reason: vision.reason },
|
|
624
|
+
basedOn: {
|
|
625
|
+
myMessages: mine.length,
|
|
626
|
+
excludedAiMessages: excluded,
|
|
627
|
+
conversations: perConversation.map(row => row.id),
|
|
628
|
+
avgChars,
|
|
629
|
+
},
|
|
630
|
+
}
|
|
631
|
+
if (result.summary === '' && result.traits.length === 0) {
|
|
632
|
+
throw new Error('模型没有给出可用的自我分析内容,请重试。')
|
|
633
|
+
}
|
|
634
|
+
return store.saveSelfProfile(result)
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/**
|
|
638
|
+
* Sketch who the other person is, from how they write.
|
|
639
|
+
*
|
|
640
|
+
* The judgement is deliberately restricted to observable writing behaviour and
|
|
641
|
+
* stated content: no guessing at job, age, or identity. Every trait has to cite
|
|
642
|
+
* something in the record, so the user can disagree with the evidence rather
|
|
643
|
+
* than with an opinion.
|
|
644
|
+
* @param {object} ctx
|
|
645
|
+
* @param {import('./store.js').Store} store
|
|
646
|
+
* @param {string} uin
|
|
647
|
+
* @param {{ signal?: AbortSignal }} [options]
|
|
648
|
+
* @returns {Promise<object>} the stored sketch.
|
|
649
|
+
*/
|
|
650
|
+
export async function analyzePersona(ctx, store, uin, options = {}) {
|
|
651
|
+
const rows = rowsForPerson(store, uin)
|
|
652
|
+
if (rows.length < 8) {
|
|
653
|
+
throw new Error(`关于 QQ ${uin} 的记录太少(${rows.length} 条),至少需要 8 条才能看出说话方式。`)
|
|
654
|
+
}
|
|
655
|
+
const targetName = nameOf(store, uin)
|
|
656
|
+
const features = measure(rows, uin)
|
|
657
|
+
const theirs = rows.filter(row => row.senderUin === uin)
|
|
658
|
+
const monologue = renderTranscript(theirs, { targetUin: uin, targetName, maxChars: 6000 })
|
|
659
|
+
const dialogue = renderTranscript(rows, { targetUin: uin, targetName, maxChars: 2500 })
|
|
660
|
+
const stored = store.score(uin)
|
|
661
|
+
|
|
662
|
+
const prompt = [
|
|
663
|
+
`请根据聊天记录,判断「${targetName}」(QQ ${uin})大概是个什么样的人,并给出一个 MBTI 类型倾向。`,
|
|
664
|
+
'',
|
|
665
|
+
'【TA 自己说的话(判断的主要依据)】',
|
|
666
|
+
monologue.text === '' ? '(无)' : monologue.text,
|
|
667
|
+
'',
|
|
668
|
+
'【完整的对话(作为语境,看 TA 对什么有反应)】',
|
|
669
|
+
dialogue.text === '' ? '(无)' : dialogue.text,
|
|
670
|
+
'',
|
|
671
|
+
'【可量化的说话习惯】',
|
|
672
|
+
measurementBlock(features),
|
|
673
|
+
stored === undefined ? '' : `关系参考:TA 对我 ${stored.theirFavor.score} 分,亲密度 ${stored.intimacy.score} 分。`,
|
|
674
|
+
'',
|
|
675
|
+
'【MBTI 怎么判】',
|
|
676
|
+
'只从文字证据推倾向,四个轴分别判断,并给出强度(0-100,50 表示看不出来):',
|
|
677
|
+
'- E/I:主动起话题的密度、话多话少、需要互动还是自述、回复的即时性。',
|
|
678
|
+
'- N/S:聊具体事实/细节/流程,还是聊可能性/意义/联想/假设。',
|
|
679
|
+
'- T/F:讲道理给方案,还是先接情绪、在意感受和关系。',
|
|
680
|
+
'- J/P:计划明确、约好时间地点、讨厌变动,还是随性、临时起意、话题跳。',
|
|
681
|
+
'MBTI 只是从文字推断的倾向,不是正式测评。caveat 要写清楚这点(一句话)。',
|
|
682
|
+
'',
|
|
683
|
+
'【纪律】',
|
|
684
|
+
'1. 只写记录里能观察到的东西。不要猜职业、年龄、学校、所在地、外貌、身份。',
|
|
685
|
+
'2. 每条性格判断都必须给证据:引用 TA 的原话片段,或引用上面的统计数字。',
|
|
686
|
+
'3. tags(关键词)要短,2-6 个字,4-6 个,像别人给 TA 贴的标签。',
|
|
687
|
+
'4. interests(兴趣)只写 TA **明确提到过**的东西;没提到就给空数组,不要凑。',
|
|
688
|
+
'5. avoid(雷区)要基于观察:比如某类话题之后 TA 明显变短、变慢、转移话题。',
|
|
689
|
+
'6. strength 表示这个特点有多突出(0-1)。看不出来就给低分,不要为了好看拉满。',
|
|
690
|
+
'7. 不确定就降低 confidence,不要为了显得聪明而编。',
|
|
691
|
+
'',
|
|
692
|
+
'【输出格式】',
|
|
693
|
+
JSON.stringify({
|
|
694
|
+
mbti: {
|
|
695
|
+
type: 'INFP',
|
|
696
|
+
nickname: '调停者',
|
|
697
|
+
confidence: 0.55,
|
|
698
|
+
axes: [
|
|
699
|
+
{ axis: 'EI', letter: 'I', strength: 68, reason: '几乎不主动起话题,回复偏短' },
|
|
700
|
+
{ axis: 'NS', letter: 'N', strength: 55, reason: '常聊「如果…」「感觉」' },
|
|
701
|
+
{ axis: 'TF', letter: 'F', strength: 62, reason: '先接情绪再谈事' },
|
|
702
|
+
{ axis: 'JP', letter: 'P', strength: 70, reason: '约时间总说「看情况」' },
|
|
703
|
+
],
|
|
704
|
+
caveat: '从文字推断的倾向,不是正式测评。',
|
|
705
|
+
},
|
|
706
|
+
summary: '一句话画像,30 字以内',
|
|
707
|
+
tags: ['慢热', '细节控'],
|
|
708
|
+
traits: [
|
|
709
|
+
{ label: '慢热', strength: 0.8, evidence: '第一次直接聊了三天才开始主动找我,原话「…」' },
|
|
710
|
+
{ label: '爱分享细节', strength: 0.6, evidence: '平均每条 xx 字,会主动描述过程' },
|
|
711
|
+
],
|
|
712
|
+
speakingStyle: 'TA 的文字风格:句长、语气词、标点习惯、用不用表情',
|
|
713
|
+
relationshipStyle: 'TA 在关系里的模式:怎么靠近、怎么退开、在意什么',
|
|
714
|
+
interests: ['只在记录里出现过的兴趣'],
|
|
715
|
+
howToTalk: ['怎么跟 TA 聊更顺,2-4 条'],
|
|
716
|
+
avoid: ['会让 TA 冷下来的做法,0-3 条'],
|
|
717
|
+
confidence: 0.6,
|
|
718
|
+
}, null, 2),
|
|
719
|
+
'',
|
|
720
|
+
'traits 给 4-6 条。',
|
|
721
|
+
].filter(line => line !== '').join('\n')
|
|
722
|
+
|
|
723
|
+
// Their pictures and stickers are evidence about them.
|
|
724
|
+
const vision = await gatherVision(ctx, store, rows, { who: 'them', limit: 3, signal: options.signal })
|
|
725
|
+
|
|
726
|
+
const parsed = await askForJson(ctx, {
|
|
727
|
+
system: SYSTEM,
|
|
728
|
+
prompt: `${prompt}${visionBlock(vision)}`,
|
|
729
|
+
images: vision.blocks,
|
|
730
|
+
maxTokens: 2600,
|
|
731
|
+
temperature: 0.4,
|
|
732
|
+
signal: options.signal,
|
|
733
|
+
purpose: 'qq-affinity-persona',
|
|
734
|
+
})
|
|
735
|
+
|
|
736
|
+
const text = (value) => String(value ?? '').trim()
|
|
737
|
+
const list = (value, limit) => (Array.isArray(value) ? value.map(item => text(item)).filter(item => item !== '').slice(0, limit) : [])
|
|
738
|
+
const traits = Array.isArray(parsed.traits)
|
|
739
|
+
? parsed.traits
|
|
740
|
+
.filter(item => item !== null && typeof item === 'object')
|
|
741
|
+
.map(item => ({
|
|
742
|
+
label: text(item.label),
|
|
743
|
+
evidence: text(item.evidence),
|
|
744
|
+
strength: Math.round(clamp(Number(item.strength ?? 0.6), 0, 1) * 100) / 100,
|
|
745
|
+
}))
|
|
746
|
+
.filter(item => item.label !== '')
|
|
747
|
+
.slice(0, 6)
|
|
748
|
+
: []
|
|
749
|
+
|
|
750
|
+
const mbti = parseMbti(parsed.mbti)
|
|
751
|
+
|
|
752
|
+
const result = {
|
|
753
|
+
mbti,
|
|
754
|
+
summary: text(parsed.summary),
|
|
755
|
+
tags: list(parsed.tags, 6),
|
|
756
|
+
traits,
|
|
757
|
+
speakingStyle: text(parsed.speakingStyle),
|
|
758
|
+
relationshipStyle: text(parsed.relationshipStyle),
|
|
759
|
+
interests: list(parsed.interests, 8),
|
|
760
|
+
howToTalk: list(parsed.howToTalk, 5),
|
|
761
|
+
avoid: list(parsed.avoid, 4),
|
|
762
|
+
confidence: Math.round(clamp(parsed.confidence ?? 0.5, 0, 1) * 100) / 100,
|
|
763
|
+
vision: { allowed: vision.allowed, available: vision.available, found: vision.found, used: vision.used, reason: vision.reason },
|
|
764
|
+
basedOn: {
|
|
765
|
+
totalMessages: features.totalMessages,
|
|
766
|
+
theirMessages: features.theirMessages,
|
|
767
|
+
conversations: store.state.conversations
|
|
768
|
+
.filter(row => row.enabled && ((row.participants ?? []).includes(uin) || row.peerUin === uin))
|
|
769
|
+
.map(row => row.id),
|
|
770
|
+
},
|
|
771
|
+
}
|
|
772
|
+
if (result.summary === '' && result.traits.length === 0) {
|
|
773
|
+
throw new Error('模型没有给出可用的画像内容,请重试。')
|
|
774
|
+
}
|
|
775
|
+
return store.savePersona(uin, result)
|
|
776
|
+
}
|
|
777
|
+
|