v3
这个提交包含在:
2
.gitignore
vendored
2
.gitignore
vendored
@ -39,3 +39,5 @@ yarn-error.log*
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
|
||||
dev.db
|
||||
|
||||
@ -60,27 +60,33 @@ model VerificationToken {
|
||||
}
|
||||
|
||||
model Provider {
|
||||
id String @id @default(uuid())
|
||||
userId String
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
name String
|
||||
baseUrl String
|
||||
apiKey String
|
||||
modelName String
|
||||
customHeaders String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
id String @id @default(uuid())
|
||||
userId String
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
name String
|
||||
baseUrl String
|
||||
apiKey String
|
||||
modelName String
|
||||
customHeaders String?
|
||||
compressEnabled Boolean @default(true)
|
||||
compressTrigger Int @default(0)
|
||||
contextLimit Int @default(128000)
|
||||
keepRounds Int @default(3)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
}
|
||||
|
||||
model Preset {
|
||||
id String @id @default(uuid())
|
||||
userId String
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
name String
|
||||
isDefault Boolean @default(false)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
fragments Fragment[]
|
||||
id String @id @default(uuid())
|
||||
userId String
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
name String
|
||||
isDefault Boolean @default(false)
|
||||
compressPrompt String?
|
||||
compressRole String @default("system")
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
fragments Fragment[]
|
||||
}
|
||||
|
||||
model Fragment {
|
||||
|
||||
@ -126,22 +126,30 @@ export async function POST(req: NextRequest) {
|
||||
|
||||
messagesToSend.push({ role: "user", content: message })
|
||||
|
||||
// Compression check
|
||||
// Compression check — use provider settings (trigger is absolute token count, 0 = disabled)
|
||||
let compressionApplied = false
|
||||
let compressedContent = ""
|
||||
if (chatSession.compressEnabled && effectivePresetId) {
|
||||
let compressRole = "system"
|
||||
const compressTrigger = provider.compressTrigger ?? 0
|
||||
const compressEnabled = provider.compressEnabled !== false
|
||||
if (compressEnabled && compressTrigger > 0 && effectivePresetId) {
|
||||
const estimatedTokens = estimateTokenCount(messagesToSend)
|
||||
const contextLimit = getContextLimit(provider.modelName)
|
||||
if (estimatedTokens > contextLimit * (1 - chatSession.compressTrigger)) {
|
||||
const keepRounds = chatSession.keepRounds || 3
|
||||
if (estimatedTokens > compressTrigger) {
|
||||
// Load compressPrompt from preset
|
||||
const preset = await prisma.preset.findFirst({
|
||||
where: { id: effectivePresetId, userId: userId },
|
||||
})
|
||||
const keepRounds = provider.keepRounds || 3
|
||||
const toCompress = nonSummaryMessages.slice(0, -keepRounds * 2)
|
||||
if (toCompress.length > 1) {
|
||||
compressedContent = await compressHistory(toCompress, provider)
|
||||
const customPrompt = preset?.compressPrompt || null
|
||||
compressedContent = await compressHistory(toCompress, provider, customPrompt)
|
||||
compressionApplied = true
|
||||
compressRole = preset?.compressRole || "system"
|
||||
|
||||
messagesToSend = []
|
||||
if (systemPrompt) messagesToSend.push({ role: "system", content: systemPrompt })
|
||||
messagesToSend.push({ role: "system", content: `[对话摘要 - 自动压缩] ${compressedContent}` })
|
||||
messagesToSend.push({ role: compressRole, content: `[对话摘要 - 自动压缩] ${compressedContent}` })
|
||||
|
||||
const recentMsgs = nonSummaryMessages.slice(-keepRounds * 2)
|
||||
let hasPendingToolCalls = false
|
||||
@ -572,7 +580,7 @@ export async function POST(req: NextRequest) {
|
||||
await prisma.message.create({
|
||||
data: {
|
||||
sessionId,
|
||||
role: "system",
|
||||
role: compressRole,
|
||||
content: `📝 已压缩前期对话摘要: ${compressedContent}`,
|
||||
isSummary: true,
|
||||
},
|
||||
@ -652,13 +660,16 @@ function getContextLimit(modelName: string): number {
|
||||
|
||||
async function compressHistory(
|
||||
messages: Array<{ role: string; content: string }>,
|
||||
provider: { baseUrl: string; apiKey: string; modelName: string }
|
||||
provider: { baseUrl: string; apiKey: string; modelName: string },
|
||||
customPrompt?: string | null
|
||||
): Promise<string> {
|
||||
const summary = messages
|
||||
.map((m) => `[${m.role}] ${m.content}`)
|
||||
.join("\n")
|
||||
|
||||
const prompt = `请为以下对话历史生成一个简洁的结构化摘要,保留关键信息、决策和动作:
|
||||
const prompt = customPrompt
|
||||
? customPrompt.replace("{{content}}", summary.substring(0, 8000))
|
||||
: `请为以下对话历史生成一个简洁的结构化摘要,保留关键信息、决策和动作:
|
||||
|
||||
${summary.substring(0, 8000)}
|
||||
|
||||
|
||||
@ -0,0 +1,92 @@
|
||||
import { NextRequest, NextResponse } from "next/server"
|
||||
import { auth } from "@/lib/auth"
|
||||
import { prisma } from "@/lib/prisma"
|
||||
import { decryptApiKey } from "@/lib/encryption"
|
||||
|
||||
export async function POST(_req: NextRequest, { params }: { params: Promise<{ sessionId: string }> }) {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||
|
||||
const { sessionId } = await params
|
||||
const chatSession = await prisma.chatSession.findFirst({
|
||||
where: { id: sessionId, userId: session.user.id },
|
||||
include: { messages: { where: { isHidden: false, isSummary: false }, orderBy: { createdAt: "asc" } } },
|
||||
})
|
||||
if (!chatSession) return NextResponse.json({ error: "会话不存在" }, { status: 404 })
|
||||
|
||||
const messages = chatSession.messages
|
||||
if (messages.length === 0) return NextResponse.json({ error: "没有可压缩的消息" }, { status: 400 })
|
||||
|
||||
const providerId = chatSession.providerId
|
||||
if (!providerId) return NextResponse.json({ error: "未选择模型" }, { status: 400 })
|
||||
|
||||
const provider = await prisma.provider.findFirst({
|
||||
where: { id: providerId, userId: session.user.id },
|
||||
})
|
||||
if (!provider) return NextResponse.json({ error: "模型不存在" }, { status: 404 })
|
||||
|
||||
const presetId = chatSession.presetId
|
||||
let compressPrompt = `请为以下对话历史生成一个简洁的结构化摘要,保留关键信息、决策和动作:
|
||||
|
||||
{{content}}
|
||||
|
||||
请用中文输出摘要。`
|
||||
let compressRole = "system"
|
||||
|
||||
if (presetId) {
|
||||
const preset = await prisma.preset.findFirst({
|
||||
where: { id: presetId, userId: session.user.id },
|
||||
})
|
||||
if (preset?.compressPrompt) {
|
||||
compressPrompt = preset.compressPrompt
|
||||
compressRole = preset.compressRole || "system"
|
||||
}
|
||||
}
|
||||
|
||||
const summary = messages
|
||||
.map((m) => `[${m.role}] ${m.content}`)
|
||||
.join("\n")
|
||||
|
||||
const prompt = compressPrompt.replace("{{content}}", summary.substring(0, 8000))
|
||||
|
||||
const apiKey = decryptApiKey(provider.apiKey)
|
||||
const baseUrl = provider.baseUrl.replace(/\/+$/, "")
|
||||
|
||||
let compressedContent = "压缩失败"
|
||||
try {
|
||||
const res = await fetch(baseUrl + "/chat/completions", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: provider.modelName,
|
||||
messages: [{ role: "user", content: prompt }],
|
||||
max_tokens: 2048,
|
||||
}),
|
||||
})
|
||||
|
||||
if (res.ok) {
|
||||
const data = await res.json() as { choices?: Array<{ message?: { content?: string } }> }
|
||||
compressedContent = data.choices?.[0]?.message?.content || "压缩失败"
|
||||
}
|
||||
} catch {/* ignore */}
|
||||
|
||||
const idsToHide = messages.map((m) => m.id)
|
||||
await prisma.message.updateMany({
|
||||
where: { id: { in: idsToHide } },
|
||||
data: { isHidden: true },
|
||||
})
|
||||
|
||||
const summaryMsg = await prisma.message.create({
|
||||
data: {
|
||||
sessionId,
|
||||
role: compressRole,
|
||||
content: `📝 已压缩对话摘要: ${compressedContent}`,
|
||||
isSummary: true,
|
||||
},
|
||||
})
|
||||
|
||||
return NextResponse.json({ success: true, summary: summaryMsg })
|
||||
}
|
||||
@ -0,0 +1,70 @@
|
||||
import { NextRequest, NextResponse } from "next/server"
|
||||
import { auth } from "@/lib/auth"
|
||||
import { prisma } from "@/lib/prisma"
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||
|
||||
const body = await req.json().catch(() => null)
|
||||
if (!body || typeof body !== "object") {
|
||||
return NextResponse.json({ error: "无效的数据格式" }, { status: 400 })
|
||||
}
|
||||
|
||||
if (!body.messages || !Array.isArray(body.messages)) {
|
||||
return NextResponse.json({ error: "数据中缺少 messages 字段" }, { status: 400 })
|
||||
}
|
||||
|
||||
const title = body.title || "导入的会话"
|
||||
const validRoles = ["user", "assistant", "system", "tool"]
|
||||
|
||||
const chatSession = await prisma.chatSession.create({
|
||||
data: {
|
||||
userId: session.user.id,
|
||||
title,
|
||||
totalCost: typeof body.totalCost === "number" ? body.totalCost : 0,
|
||||
thinkingEnabled: body.thinkingEnabled === true,
|
||||
markdownEnabled: body.markdownEnabled !== false,
|
||||
compressEnabled: body.compressEnabled !== false,
|
||||
compressTrigger: typeof body.compressTrigger === "number" ? body.compressTrigger : 0.2,
|
||||
keepRounds: typeof body.keepRounds === "number" ? body.keepRounds : 3,
|
||||
createdAt: body.createdAt ? new Date(body.createdAt) : undefined,
|
||||
messages: {
|
||||
createMany: {
|
||||
data: body.messages
|
||||
.filter((m: { role: string; content?: string }) => m.role && validRoles.includes(m.role) && m.content !== undefined)
|
||||
.map((m: {
|
||||
role: string
|
||||
content: string
|
||||
thinking?: string | null
|
||||
toolCalls?: string | null
|
||||
toolResults?: string | null
|
||||
toolCallId?: string | null
|
||||
tokenUsage?: string | null
|
||||
cost?: number
|
||||
branchParent?: string | null
|
||||
isSummary?: boolean
|
||||
isHidden?: boolean
|
||||
createdAt?: string
|
||||
}) => ({
|
||||
role: m.role,
|
||||
content: m.content,
|
||||
thinking: m.thinking ?? null,
|
||||
toolCalls: m.toolCalls ?? null,
|
||||
toolResults: m.toolResults ?? null,
|
||||
toolCallId: m.toolCallId ?? null,
|
||||
tokenUsage: m.tokenUsage ?? null,
|
||||
cost: typeof m.cost === "number" ? m.cost : 0,
|
||||
branchParent: m.branchParent ?? null,
|
||||
isSummary: m.isSummary === true,
|
||||
isHidden: m.isHidden === true,
|
||||
createdAt: m.createdAt ? new Date(m.createdAt) : undefined,
|
||||
})),
|
||||
},
|
||||
},
|
||||
},
|
||||
include: { messages: { orderBy: { createdAt: "asc" } } },
|
||||
})
|
||||
|
||||
return NextResponse.json(chatSession, { status: 201 })
|
||||
}
|
||||
@ -7,7 +7,7 @@ export async function PUT(req: NextRequest, { params }: { params: Promise<{ id:
|
||||
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||
|
||||
const { id } = await params
|
||||
const { name, isDefault } = await req.json()
|
||||
const { name, isDefault, compressPrompt, compressRole } = await req.json()
|
||||
|
||||
const preset = await prisma.preset.findFirst({ where: { id, userId: session.user.id } })
|
||||
if (!preset) return NextResponse.json({ error: "预设不存在" }, { status: 404 })
|
||||
@ -22,6 +22,8 @@ export async function PUT(req: NextRequest, { params }: { params: Promise<{ id:
|
||||
const data: Record<string, unknown> = {}
|
||||
if (name !== undefined) data.name = name
|
||||
if (isDefault !== undefined) data.isDefault = isDefault
|
||||
if (compressPrompt !== undefined) data.compressPrompt = compressPrompt
|
||||
if (compressRole !== undefined) data.compressRole = compressRole
|
||||
|
||||
const updated = await prisma.preset.update({ where: { id }, data, include: { fragments: { orderBy: { order: "asc" } } } })
|
||||
return NextResponse.json(updated)
|
||||
|
||||
@ -12,14 +12,19 @@ export async function GET(_req: NextRequest) {
|
||||
orderBy: { createdAt: "desc" },
|
||||
})
|
||||
|
||||
return NextResponse.json(presets)
|
||||
return NextResponse.json(
|
||||
presets.map((p) => ({
|
||||
...p,
|
||||
compressRole: p.compressRole || "system",
|
||||
}))
|
||||
)
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||
|
||||
const { name, isDefault } = await req.json()
|
||||
const { name, isDefault, compressPrompt, compressRole } = await req.json()
|
||||
if (!name) return NextResponse.json({ error: "名称不能为空" }, { status: 400 })
|
||||
|
||||
if (isDefault) {
|
||||
@ -30,7 +35,13 @@ export async function POST(req: NextRequest) {
|
||||
}
|
||||
|
||||
const preset = await prisma.preset.create({
|
||||
data: { userId: session.user.id, name, isDefault: isDefault || false },
|
||||
data: {
|
||||
userId: session.user.id,
|
||||
name,
|
||||
isDefault: isDefault || false,
|
||||
compressPrompt: compressPrompt || null,
|
||||
compressRole: compressRole || "system",
|
||||
},
|
||||
include: { fragments: true },
|
||||
})
|
||||
|
||||
|
||||
@ -8,7 +8,7 @@ export async function PUT(req: NextRequest, { params }: { params: Promise<{ id:
|
||||
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||
|
||||
const { id } = await params
|
||||
const { name, baseUrl, apiKey, modelName, customHeaders } = await req.json()
|
||||
const { name, baseUrl, apiKey, modelName, customHeaders, compressEnabled, compressTrigger, contextLimit, keepRounds } = await req.json()
|
||||
|
||||
const data: Record<string, unknown> = {}
|
||||
if (name !== undefined) data.name = name
|
||||
@ -16,6 +16,10 @@ export async function PUT(req: NextRequest, { params }: { params: Promise<{ id:
|
||||
if (apiKey !== undefined) data.apiKey = encryptApiKey(apiKey)
|
||||
if (modelName !== undefined) data.modelName = modelName
|
||||
if (customHeaders !== undefined) data.customHeaders = JSON.stringify(customHeaders)
|
||||
if (compressEnabled !== undefined) data.compressEnabled = compressEnabled
|
||||
if (compressTrigger !== undefined) data.compressTrigger = compressTrigger
|
||||
if (contextLimit !== undefined) data.contextLimit = contextLimit
|
||||
if (keepRounds !== undefined) data.keepRounds = keepRounds
|
||||
|
||||
const provider = await prisma.provider.findFirst({ where: { id, userId: session.user.id } })
|
||||
if (!provider) return NextResponse.json({ error: "Provider 不存在" }, { status: 404 })
|
||||
|
||||
@ -18,6 +18,10 @@ export async function GET(_req: NextRequest) {
|
||||
providers.map((p) => ({
|
||||
...p,
|
||||
apiKey: maskApiKey(decryptApiKey(p.apiKey)),
|
||||
compressEnabled: p.compressEnabled ?? true,
|
||||
compressTrigger: p.compressTrigger ?? 0,
|
||||
contextLimit: p.contextLimit ?? 128000,
|
||||
keepRounds: p.keepRounds ?? 3,
|
||||
}))
|
||||
)
|
||||
}
|
||||
@ -28,7 +32,7 @@ export async function POST(req: NextRequest) {
|
||||
return NextResponse.json({ error: "未登录" }, { status: 401 })
|
||||
}
|
||||
|
||||
const { name, baseUrl, apiKey, modelName, customHeaders } = await req.json()
|
||||
const { name, baseUrl, apiKey, modelName, customHeaders, compressEnabled, compressTrigger, contextLimit, keepRounds } = await req.json()
|
||||
|
||||
if (!name || !baseUrl || !apiKey || !modelName) {
|
||||
return NextResponse.json({ error: "缺少必要参数" }, { status: 400 })
|
||||
@ -44,6 +48,10 @@ export async function POST(req: NextRequest) {
|
||||
apiKey: encryptedKey,
|
||||
modelName,
|
||||
customHeaders: customHeaders ? JSON.stringify(customHeaders) : null,
|
||||
compressEnabled: compressEnabled !== false,
|
||||
compressTrigger: typeof compressTrigger === "number" ? compressTrigger : 0,
|
||||
contextLimit: typeof contextLimit === "number" ? contextLimit : 128000,
|
||||
keepRounds: typeof keepRounds === "number" ? keepRounds : 3,
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
import { useAuth } from "@/components/AuthProvider"
|
||||
import { useState, useCallback, useEffect, useRef } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { Plus, MessageSquare, Search, Settings, LogOut, Pin, Archive, Trash2, MoreVertical, Download, ChevronDown, ChevronRight, Pencil, Check, X, ArrowLeft } from "lucide-react"
|
||||
import { Plus, MessageSquare, Search, Settings, LogOut, Pin, Archive, Trash2, MoreVertical, Download, Upload, ChevronDown, ChevronRight, Pencil, Check, X, ArrowLeft } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
@ -40,6 +40,7 @@ export default function HomePage() {
|
||||
const [editingId, setEditingId] = useState<string | null>(null)
|
||||
const [editTitle, setEditTitle] = useState("")
|
||||
const editInputRef = useRef<HTMLInputElement>(null)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!authLoading && !user) router.push("/login")
|
||||
@ -131,6 +132,38 @@ export default function HomePage() {
|
||||
}
|
||||
}
|
||||
|
||||
const importSession = async (file: File) => {
|
||||
try {
|
||||
const text = await file.text()
|
||||
const data = JSON.parse(text)
|
||||
const res = await fetch("/api/chat/sessions/import", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
if (res.ok) {
|
||||
const s = await res.json()
|
||||
setSessions((prev) => [s, ...prev])
|
||||
setActiveSessionId(s.id)
|
||||
} else {
|
||||
const err = await res.json().catch(() => ({ error: "导入失败" }))
|
||||
alert(err.error || "导入失败")
|
||||
}
|
||||
} catch {
|
||||
alert("文件格式无效,请选择 JSON 格式的导出文件")
|
||||
}
|
||||
}
|
||||
|
||||
const handleImportClick = () => {
|
||||
fileInputRef.current?.click()
|
||||
}
|
||||
|
||||
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0]
|
||||
if (file) importSession(file)
|
||||
if (fileInputRef.current) fileInputRef.current.value = ""
|
||||
}
|
||||
|
||||
if (authLoading || loading) {
|
||||
return <div className="flex items-center justify-center min-h-screen"><p>加载中...</p></div>
|
||||
}
|
||||
@ -146,6 +179,9 @@ export default function HomePage() {
|
||||
<Button variant="ghost" size="icon" onClick={() => setSettingsOpen(true)} title="设置">
|
||||
<Settings className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon" onClick={handleImportClick} title="导入会话">
|
||||
<Upload className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon" onClick={() => logout()} title="退出登录">
|
||||
<LogOut className="h-4 w-4" />
|
||||
</Button>
|
||||
@ -249,6 +285,13 @@ export default function HomePage() {
|
||||
{user?.email}
|
||||
</div>
|
||||
</div>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept=".json"
|
||||
className="hidden"
|
||||
onChange={handleFileChange}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Main Chat Area: desktop always, mobile when session active */}
|
||||
|
||||
@ -433,15 +433,31 @@ export function ChatArea({ sessionId, onSessionUpdated }: { sessionId: string; o
|
||||
const lastUserMsg = [...msgs].reverse().find((m) => m.role === "user")
|
||||
if (!lastUserMsg) return
|
||||
|
||||
const content = lastUserMsg.content
|
||||
await fetch(`/api/chat/sessions/${sessionId}/rollback`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ messageId: lastUserMsg.id }),
|
||||
body: JSON.stringify({ messageId: lastUserMsg.id, includeTarget: true }),
|
||||
})
|
||||
const res = await fetch(`/api/chat/sessions/${sessionId}`)
|
||||
if (res.ok) setChatSession(await res.json())
|
||||
onSessionUpdated()
|
||||
await sendMessage(lastUserMsg.content)
|
||||
await sendMessage(content)
|
||||
}
|
||||
|
||||
const handleCompress = async () => {
|
||||
if (isStreaming) return
|
||||
const res = await fetch(`/api/chat/sessions/${sessionId}/compress`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
})
|
||||
if (res.ok) {
|
||||
fetchSession()
|
||||
onSessionUpdated()
|
||||
} else {
|
||||
const err = await res.json().catch(() => ({ error: "压缩失败" }))
|
||||
alert(err.error || "压缩失败")
|
||||
}
|
||||
}
|
||||
|
||||
const messages = chatSession?.messages || []
|
||||
@ -781,6 +797,12 @@ export function ChatArea({ sessionId, onSessionUpdated }: { sessionId: string; o
|
||||
<SheetTitle>调试信息</SheetTitle>
|
||||
</SheetHeader>
|
||||
<ScrollArea className="h-[calc(100vh-80px)] px-6 py-4">
|
||||
<div className="mb-4">
|
||||
<Button variant="outline" size="sm" onClick={handleCompress} disabled={isStreaming} className="w-full">
|
||||
压缩上下文 (Compress)
|
||||
</Button>
|
||||
<p className="text-[10px] text-muted-foreground mt-1 text-center">压缩当前所有对话消息为摘要,并清空消息列表</p>
|
||||
</div>
|
||||
{debugRounds.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground text-center py-8">发送消息后,此处将显示调试信息</p>
|
||||
) : (
|
||||
|
||||
@ -18,10 +18,12 @@ import {
|
||||
|
||||
interface Provider {
|
||||
id: string; name: string; baseUrl: string; apiKey: string; modelName: string; customHeaders: string | null
|
||||
compressEnabled: boolean; compressTrigger: number; contextLimit: number; keepRounds: number
|
||||
}
|
||||
|
||||
interface Preset {
|
||||
id: string; name: string; isDefault: boolean
|
||||
compressPrompt: string | null; compressRole: string
|
||||
fragments: Array<{ id: string; name: string; content: string; enabled: boolean; order: number }>
|
||||
}
|
||||
|
||||
@ -86,14 +88,51 @@ export function SettingsPanel({ open, onClose, onUpdate }: { open: boolean; onCl
|
||||
}, [refreshAll, onUpdate])
|
||||
|
||||
// --- Provider CRUD ---
|
||||
const [newProvider, setNewProvider] = useState({ name: "", baseUrl: "", apiKey: "", modelName: "" })
|
||||
const defaultProvider = { name: "", baseUrl: "", apiKey: "", modelName: "", compressEnabled: true, compressTrigger: 0, contextLimit: 128000, keepRounds: 3 }
|
||||
const [newProvider, setNewProvider] = useState(defaultProvider)
|
||||
const [editingProviderId, setEditingProviderId] = useState<string | null>(null)
|
||||
|
||||
const addProvider = async () => {
|
||||
await fetch("/api/providers", {
|
||||
method: "POST", headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(newProvider),
|
||||
const startEditProvider = (p: Provider) => {
|
||||
setEditingProviderId(p.id)
|
||||
setNewProvider({
|
||||
name: p.name, baseUrl: p.baseUrl, apiKey: p.apiKey, modelName: p.modelName,
|
||||
compressEnabled: p.compressEnabled ?? true,
|
||||
compressTrigger: p.compressTrigger ?? 0,
|
||||
contextLimit: p.contextLimit ?? 128000,
|
||||
keepRounds: p.keepRounds ?? 3,
|
||||
})
|
||||
setNewProvider({ name: "", baseUrl: "", apiKey: "", modelName: "" })
|
||||
}
|
||||
|
||||
const cancelEditProvider = () => {
|
||||
setEditingProviderId(null)
|
||||
setNewProvider(defaultProvider)
|
||||
}
|
||||
|
||||
const saveProvider = async () => {
|
||||
if (!newProvider.name || !newProvider.baseUrl || !newProvider.modelName) return
|
||||
const body: Record<string, unknown> = {
|
||||
name: newProvider.name, baseUrl: newProvider.baseUrl, modelName: newProvider.modelName,
|
||||
compressEnabled: newProvider.compressEnabled,
|
||||
compressTrigger: Number(newProvider.compressTrigger) || 0,
|
||||
contextLimit: Number(newProvider.contextLimit) || 128000,
|
||||
keepRounds: Number(newProvider.keepRounds) || 3,
|
||||
}
|
||||
if (newProvider.apiKey && newProvider.apiKey !== "****") {
|
||||
body.apiKey = newProvider.apiKey
|
||||
}
|
||||
if (editingProviderId) {
|
||||
await fetch(`/api/providers/${editingProviderId}`, {
|
||||
method: "PUT", headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
} else {
|
||||
if (!newProvider.apiKey) return
|
||||
await fetch("/api/providers", {
|
||||
method: "POST", headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
cancelEditProvider()
|
||||
refresh()
|
||||
}
|
||||
|
||||
@ -395,26 +434,90 @@ export function SettingsPanel({ open, onClose, onUpdate }: { open: boolean; onCl
|
||||
{tab === "providers" && (
|
||||
<div className="space-y-6">
|
||||
<div className="space-y-4 border rounded-lg p-4">
|
||||
<h3 className="font-semibold text-sm">添加新 Provider</h3>
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs">名称</Label>
|
||||
<Input placeholder="我的 DeepSeek" value={newProvider.name} onChange={(e) => setNewProvider({ ...newProvider, name: e.target.value })} />
|
||||
<h3 className="font-semibold text-sm">{editingProviderId ? "编辑 Provider" : "添加新 Provider"}</h3>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs">名称</Label>
|
||||
<Input placeholder="我的 DeepSeek" value={newProvider.name} onChange={(e) => setNewProvider({ ...newProvider, name: e.target.value })} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs">模型名称</Label>
|
||||
<Input placeholder="deepseek-chat" value={newProvider.modelName} onChange={(e) => setNewProvider({ ...newProvider, modelName: e.target.value })} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs">API 地址 (Base URL)</Label>
|
||||
<Input placeholder="https://api.deepseek.com" value={newProvider.baseUrl} onChange={(e) => setNewProvider({ ...newProvider, baseUrl: e.target.value })} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs">API Key</Label>
|
||||
<Label className="text-xs">API Key {editingProviderId ? "(留空则不修改)" : ""}</Label>
|
||||
<Input type="password" placeholder="sk-..." value={newProvider.apiKey} onChange={(e) => setNewProvider({ ...newProvider, apiKey: e.target.value })} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs">模型名称</Label>
|
||||
<Input placeholder="deepseek-chat" value={newProvider.modelName} onChange={(e) => setNewProvider({ ...newProvider, modelName: e.target.value })} />
|
||||
|
||||
<Accordion>
|
||||
<AccordionItem value="compress">
|
||||
<AccordionTrigger className="text-xs font-medium">上下文压缩设置</AccordionTrigger>
|
||||
<AccordionContent className="space-y-3 pt-2">
|
||||
<div className="flex items-center justify-between border rounded-lg p-3">
|
||||
<div className="flex-1 min-w-0 mr-2">
|
||||
<p className="text-sm font-medium">启用自动压缩</p>
|
||||
<p className="text-[11px] text-muted-foreground">关闭后不会自动压缩上下文(1M 上下文模型建议关闭)</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={newProvider.compressEnabled}
|
||||
onCheckedChange={(v) => setNewProvider({ ...newProvider, compressEnabled: v })}
|
||||
/>
|
||||
</div>
|
||||
{newProvider.compressEnabled && (
|
||||
<>
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs">触发压缩的 Token 阈值(0 = 禁用自动压缩)</Label>
|
||||
<Input
|
||||
type="number" min="0" step="1000"
|
||||
placeholder="例如 4000(超过 4000 tokens 时自动压缩)"
|
||||
value={newProvider.compressTrigger || 0}
|
||||
onChange={(e) => setNewProvider({ ...newProvider, compressTrigger: parseInt(e.target.value) || 0 })}
|
||||
/>
|
||||
<p className="text-[10px] text-muted-foreground">当预估输入 tokens 数超过此值时,自动触发压缩。设为 0 则只可手动压缩</p>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs">上下文窗口大小</Label>
|
||||
<Input
|
||||
type="number" min="0" step="1000"
|
||||
placeholder="128000"
|
||||
value={newProvider.contextLimit}
|
||||
onChange={(e) => setNewProvider({ ...newProvider, contextLimit: parseInt(e.target.value) || 128000 })}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs">保留最近对话轮数</Label>
|
||||
<Input
|
||||
type="number" min="1" max="100"
|
||||
placeholder="3"
|
||||
value={newProvider.keepRounds}
|
||||
onChange={(e) => setNewProvider({ ...newProvider, keepRounds: parseInt(e.target.value) || 3 })}
|
||||
/>
|
||||
<p className="text-[10px] text-muted-foreground">压缩后保留的完整对话轮数(用户+AI 各算一轮)</p>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Button size="sm" onClick={saveProvider}>
|
||||
{editingProviderId ? <Check className="h-3 w-3 mr-1" /> : <Plus className="h-3 w-3 mr-1" />}
|
||||
{editingProviderId ? "保存" : "添加"}
|
||||
</Button>
|
||||
{editingProviderId && (
|
||||
<Button size="sm" variant="outline" onClick={cancelEditProvider}>
|
||||
<X className="h-3 w-3 mr-1" />取消
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<Button size="sm" onClick={addProvider}>
|
||||
<Plus className="h-3 w-3 mr-1" />添加
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
@ -427,14 +530,21 @@ export function SettingsPanel({ open, onClose, onUpdate }: { open: boolean; onCl
|
||||
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => testProvider(p.id)}>
|
||||
<Play className="h-3 w-3" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => startEditProvider(p)} title="编辑">
|
||||
<Pencil className="h-3 w-3" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon" className="h-7 w-7 text-destructive" onClick={() => deleteProvider(p.id)}>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">{p.baseUrl} | {p.modelName} | Key: {p.apiKey}</div>
|
||||
<div className="text-xs text-muted-foreground">{p.modelName} @ {p.baseUrl}</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
压缩: {p.compressEnabled && p.compressTrigger > 0 ? `> ${p.compressTrigger} tokens 触发, 保留 ${p.keepRounds} 轮` : "已禁用"}
|
||||
{" | "}上下文: {p.contextLimit}
|
||||
</div>
|
||||
{testResults[p.id] && (
|
||||
<p className={`text-xs ${testResults[p.id].startsWith("成功") ? "text-green-600" : "text-destructive"}`}>
|
||||
<p className={`text-xs ${testResults[p.id].startsWith("成功") || testResults[p.id].startsWith("已连接") ? "text-green-600" : "text-destructive"}`}>
|
||||
{testResults[p.id]}
|
||||
</p>
|
||||
)}
|
||||
@ -494,6 +604,61 @@ export function SettingsPanel({ open, onClose, onUpdate }: { open: boolean; onCl
|
||||
<Plus className="h-3 w-3 mr-1" />添加片段
|
||||
</Button>
|
||||
|
||||
{/* Compression Settings for Preset */}
|
||||
<Accordion>
|
||||
<AccordionItem value="compress">
|
||||
<AccordionTrigger className="text-xs font-medium">压缩提示词设置</AccordionTrigger>
|
||||
<AccordionContent className="space-y-3 pt-2">
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs">压缩提示词(用 {"{{content}}"} 表示待压缩内容)</Label>
|
||||
<Textarea
|
||||
className="text-xs min-h-[60px] font-mono"
|
||||
placeholder={`请为以下对话历史生成一个简洁的结构化摘要,保留关键信息、决策和动作:
|
||||
|
||||
{{content}}
|
||||
|
||||
请用中文输出摘要。`}
|
||||
value={preset.compressPrompt || ""}
|
||||
onChange={(e) => {
|
||||
setPresets(prev => prev.map(p => p.id === preset.id ? { ...p, compressPrompt: e.target.value || null } : p))
|
||||
const key = `preset-compress-${preset.id}`
|
||||
if (debounceTimers.current[key]) clearTimeout(debounceTimers.current[key])
|
||||
debounceTimers.current[key] = setTimeout(async () => {
|
||||
await fetch(`/api/presets/${preset.id}`, {
|
||||
method: "PUT", headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ compressPrompt: e.target.value || null }),
|
||||
})
|
||||
}, 300)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs">压缩内容放置位置</Label>
|
||||
<select
|
||||
className="w-full border rounded-md px-3 py-1.5 text-sm bg-background"
|
||||
value={preset.compressRole || "system"}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value
|
||||
setPresets(prev => prev.map(p => p.id === preset.id ? { ...p, compressRole: val } : p))
|
||||
const key = `preset-compress-role-${preset.id}`
|
||||
if (debounceTimers.current[key]) clearTimeout(debounceTimers.current[key])
|
||||
debounceTimers.current[key] = setTimeout(async () => {
|
||||
await fetch(`/api/presets/${preset.id}`, {
|
||||
method: "PUT", headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ compressRole: val }),
|
||||
})
|
||||
}, 300)
|
||||
}}
|
||||
>
|
||||
<option value="system">作为 System 消息(推荐)</option>
|
||||
<option value="assistant">作为 Assistant 消息</option>
|
||||
</select>
|
||||
<p className="text-[10px] text-muted-foreground">压缩后的摘要将以此角色插入上下文。选择 Assistant 时部分模型可能不会遵守</p>
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
|
||||
{/* System Prompt Preview */}
|
||||
{preset.fragments.filter(f => f.enabled).length > 0 && (
|
||||
<details className="text-xs">
|
||||
|
||||
在新工单中引用
屏蔽一个用户