feat: SodiumPet 小钠桌宠 v0.1.0(Live2D 桌宠 / 经济任务 / 音乐 / 成就 / 编辑器 / MOD)
This commit is contained in:
+123
@@ -0,0 +1,123 @@
|
||||
import {
|
||||
fallbackReply,
|
||||
systemPrompt,
|
||||
type ChatMessage,
|
||||
type LlmConfig
|
||||
} from '../shared/llm'
|
||||
import type { PetSave } from '../shared/petState'
|
||||
|
||||
export class ChatService {
|
||||
private history: ChatMessage[] = []
|
||||
|
||||
constructor(
|
||||
private readonly getConfig: () => LlmConfig,
|
||||
private readonly getSave: () => PetSave
|
||||
) {}
|
||||
|
||||
reset(): void {
|
||||
this.history = []
|
||||
}
|
||||
|
||||
async ask(text: string): Promise<string> {
|
||||
let full = ''
|
||||
await this.askStream(text, (chunk) => {
|
||||
full += chunk
|
||||
})
|
||||
return full
|
||||
}
|
||||
|
||||
/** 流式请求:每收到一段 delta 就回调一次,返回完整回复 */
|
||||
async askStream(
|
||||
text: string,
|
||||
onChunk: (chunk: string) => void,
|
||||
extraContext = "",
|
||||
imageDataUrl = "",
|
||||
flavor = "chemistry"
|
||||
): Promise<string> {
|
||||
const cfg = this.getConfig()
|
||||
if (!cfg.enabled || !cfg.apiKey) {
|
||||
const reply = fallbackReply(text.length + Date.now())
|
||||
onChunk(reply)
|
||||
return reply
|
||||
}
|
||||
|
||||
const sys = systemPrompt(this.getSave(), cfg.personaExtra, flavor)
|
||||
const messages: ChatMessage[] = [
|
||||
{
|
||||
role: 'system',
|
||||
content: extraContext ? `${sys}\n\n【知识库参考,可用可不用】\n${extraContext}` : sys
|
||||
},
|
||||
...this.history.slice(-cfg.maxHistory),
|
||||
{
|
||||
role: 'user',
|
||||
content: imageDataUrl
|
||||
? [
|
||||
{ type: 'text', text },
|
||||
{ type: 'image_url', image_url: { url: imageDataUrl } }
|
||||
]
|
||||
: text
|
||||
}
|
||||
]
|
||||
|
||||
const url = `${cfg.baseUrl.replace(/\/+$/, '')}/chat/completions`
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${cfg.apiKey}`
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: cfg.model,
|
||||
messages,
|
||||
temperature: cfg.temperature,
|
||||
max_tokens: 320,
|
||||
stream: true
|
||||
}),
|
||||
signal: AbortSignal.timeout(45_000)
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
const body = await res.text().catch(() => '')
|
||||
throw new Error(`HTTP ${res.status} ${body.slice(0, 200)}`)
|
||||
}
|
||||
if (!res.body) throw new Error('无响应体')
|
||||
|
||||
const reader = res.body.getReader()
|
||||
const decoder = new TextDecoder('utf-8')
|
||||
let full = ''
|
||||
let buf = ''
|
||||
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
buf += decoder.decode(value, { stream: true })
|
||||
const lines = buf.split('\n')
|
||||
buf = lines.pop() ?? ''
|
||||
for (const raw of lines) {
|
||||
const line = raw.trim()
|
||||
if (!line.startsWith('data:')) continue
|
||||
const data = line.slice(5).trim()
|
||||
if (data === '[DONE]') continue
|
||||
try {
|
||||
const json = JSON.parse(data) as {
|
||||
choices?: Array<{ delta?: { content?: string } }>
|
||||
}
|
||||
const delta = json.choices?.[0]?.delta?.content ?? ''
|
||||
if (delta) {
|
||||
full += delta
|
||||
onChunk(delta)
|
||||
}
|
||||
} catch {
|
||||
// 忽略不完整的 JSON 行
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!full.trim()) throw new Error('空回复')
|
||||
|
||||
this.history.push({ role: 'user', content: text }, { role: 'assistant', content: full })
|
||||
const cap = cfg.maxHistory * 2
|
||||
if (this.history.length > cap) this.history = this.history.slice(-cap)
|
||||
return full
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user