pref:优化webui界面,增加prompt模板元信息

This commit is contained in:
SengokuCola
2026-05-05 17:57:19 +08:00
parent 0d43d3ec05
commit a5e4ac8531
42 changed files with 826 additions and 410 deletions

View File

@@ -44,6 +44,9 @@
# 关于 A_memorix 修改
如果修改涉及 `src/A_memorix`,请先阅读 `src/A_memorix/MODIFICATION_POLICY.md`
# prompt模板、
涉及对prompt模板的修改要同步修改英文和日文的文件对齐到中文
默认原则:
1. `src/A_memorix` 的实现层改动应优先遵守 `src/A_memorix/MODIFICATION_POLICY.md` 中的归属约束。
2. 不要提交无边界的 `ruff`、格式化、导入整理或大面积实现整理。

View File

@@ -175,6 +175,7 @@ export const DynamicConfigForm: React.FC<DynamicConfigFormProps> = ({
value={values[field.name]}
onChange={(v) => onChange(field.name, v)}
schema={field}
parentValues={values}
/>
)
}
@@ -185,6 +186,7 @@ export const DynamicConfigForm: React.FC<DynamicConfigFormProps> = ({
value={values[field.name]}
onChange={(v) => onChange(field.name, v)}
schema={field}
parentValues={values}
>
<DynamicField
schema={field}
@@ -300,6 +302,7 @@ export const DynamicConfigForm: React.FC<DynamicConfigFormProps> = ({
onChange={(v) => onChange(key, v)}
schema={nestedField ?? nestedSchema}
nestedSchema={nestedSchema}
parentValues={values}
/>
</div>
)
@@ -313,6 +316,7 @@ export const DynamicConfigForm: React.FC<DynamicConfigFormProps> = ({
onChange={(v) => onChange(key, v)}
schema={nestedField ?? nestedSchema}
nestedSchema={nestedSchema}
parentValues={values}
>
<DynamicConfigForm
schema={nestedSchema}

View File

@@ -15,6 +15,7 @@ export interface FieldHookComponentProps {
onChange?: (value: unknown) => void
children?: ReactNode
schema?: ConfigSchema | FieldSchema
parentValues?: Record<string, unknown>
/**
* 如果当前字段是 `List[ConfigBase]` 或嵌套 ConfigBase
* 这里会传入对应子配置类的 ConfigSchema便于自定义编辑器

View File

@@ -8,6 +8,9 @@ export interface PromptFileInfo {
name: string
size: number
modified_at: number
display_name: string
advanced: boolean
description: string
}
export interface PromptCatalog {

View File

@@ -5,7 +5,7 @@
* 修改此处的版本号后,所有展示版本的地方都会自动更新
*/
export const APP_VERSION = '1.0.3'
export const APP_VERSION = '1.0.5'
export const APP_NAME = 'MaiBot Dashboard'
export const APP_FULL_NAME = `${APP_NAME} v${APP_VERSION}`

View File

@@ -48,11 +48,10 @@ const TOAST_DISPLAY_DELAY = 500
/** Tab 标签页的首选排列顺序 (host field name) */
const TAB_ORDER = [
'bot',
'personality',
'chat',
'expression',
'visual',
'a_memorix',
'visual',
'message_receive',
'emoji',
'voice',
@@ -65,10 +64,8 @@ const TAB_ORDER = [
/** 默认展示的主配置栏目 */
const DEFAULT_VISIBLE_TAB_IDS = new Set([
'bot',
'personality',
'chat',
'expression',
'visual',
'a_memorix',
])

View File

@@ -1,4 +1,4 @@
import { useCallback, useMemo, type CSSProperties } from 'react'
import { useCallback, useEffect, useMemo, useState, type CSSProperties } from 'react'
import * as LucideIcons from 'lucide-react'
import { Plus, Trash2 } from 'lucide-react'
@@ -37,6 +37,11 @@ export interface ListItemEditorOptions {
fieldSchemaOverrides?: Record<string, Partial<FieldSchema>>
/** 添加按钮位置 */
addButtonPlacement?: 'top' | 'bottom'
/** 根据同级配置决定是否默认折叠 */
collapseWhen?: (context: { parentValues?: Record<string, unknown> }) => boolean
collapsedText?: string
expandLabel?: string
collapseLabel?: string
}
function resolveLabel(schema?: ConfigSchema | FieldSchema, fieldPath?: string): string {
@@ -159,6 +164,7 @@ export function createListItemEditorHook(
onChange,
schema,
nestedSchema,
parentValues,
value,
}) => {
const items = useMemo<Record<string, unknown>[]>(() => {
@@ -283,6 +289,16 @@ export function createListItemEditorHook(
const description = resolveDescription(schema)
const iconName = resolveIconName(options.iconName, schema, nestedSchema)
const addButtonPlacement = options.addButtonPlacement ?? 'bottom'
const shouldCollapse = options.collapseWhen?.({ parentValues }) ?? false
const [manuallyExpanded, setManuallyExpanded] = useState(false)
const collapsed = shouldCollapse && !manuallyExpanded
useEffect(() => {
if (!shouldCollapse) {
setManuallyExpanded(false)
}
}, [shouldCollapse])
const addButton = (
<Button
type="button"
@@ -310,9 +326,23 @@ export function createListItemEditorHook(
return (
<Card>
<CardHeader className="space-y-2 pb-4">
<div className="flex items-center gap-2">
{renderLucideIcon(iconName, 'h-5 w-5 text-muted-foreground')}
<CardTitle className="text-base">{label}</CardTitle>
<div className="flex items-start justify-between gap-3">
<div className="flex min-w-0 items-center gap-2">
{renderLucideIcon(iconName, 'h-5 w-5 flex-shrink-0 text-muted-foreground')}
<CardTitle className="truncate text-base">{label}</CardTitle>
</div>
{shouldCollapse && (
<Button
type="button"
variant="outline"
size="sm"
onClick={() => setManuallyExpanded((current) => !current)}
>
{collapsed
? (options.expandLabel ?? '展开')
: (options.collapseLabel ?? '折叠')}
</Button>
)}
</div>
{description && (
<CardDescription className="whitespace-pre-line">{description}</CardDescription>
@@ -322,6 +352,12 @@ export function createListItemEditorHook(
)}
</CardHeader>
<CardContent className="space-y-3">
{collapsed ? (
<div className="rounded-md border border-dashed border-muted-foreground/25 bg-muted/10 p-4 text-sm text-muted-foreground">
{options.collapsedText ?? '当前配置已折叠,可手动展开查看或编辑。'}
</div>
) : (
<>
{addButtonPlacement === 'top' && addButton}
{items.length === 0 ? (
<div className="rounded-md border border-dashed border-muted-foreground/25 bg-muted/10 p-6 text-center text-sm text-muted-foreground">
@@ -360,6 +396,8 @@ export function createListItemEditorHook(
})
)}
{addButtonPlacement === 'bottom' && addButton}
</>
)}
</CardContent>
</Card>
)

View File

@@ -1,6 +1,33 @@
import { Plus, Trash2 } from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import type { FieldHookComponent } from '@/lib/field-hooks'
import { createJsonFieldHook } from './JsonFieldHookFactory'
import { createListItemEditorHook } from './ListItemEditorHookFactory'
type ExpressionRuleType = 'group' | 'private'
interface ExpressionGroupTarget {
platform: string
item_id: string
rule_type: ExpressionRuleType
}
interface ExpressionGroupValue {
expression_groups: ExpressionGroupTarget[]
}
const ruleTypeLabel = (rule: unknown) => {
if (rule === 'private') return '私聊'
if (rule === 'group') return '群聊'
@@ -28,9 +55,60 @@ const collectStringList = (value: unknown): string[] => {
.filter((item) => item.length > 0)
}
const normalizeExpressionRuleType = (value: unknown): ExpressionRuleType => {
return value === 'private' ? 'private' : 'group'
}
const normalizeExpressionTarget = (value: unknown): ExpressionGroupTarget => {
const source =
value && typeof value === 'object'
? (value as Record<string, unknown>)
: {}
return {
platform:
typeof source.platform === 'string' ? source.platform.trim() : 'qq',
item_id:
typeof source.item_id === 'string' ? source.item_id.trim() : '',
rule_type: normalizeExpressionRuleType(source.rule_type),
}
}
const normalizeExpressionGroups = (value: unknown): ExpressionGroupValue[] => {
if (!Array.isArray(value)) return []
return value.map((item) => {
const source =
item && typeof item === 'object'
? (item as Record<string, unknown>)
: {}
const members = Array.isArray(source.expression_groups)
? source.expression_groups.map(normalizeExpressionTarget)
: []
return { expression_groups: members }
})
}
const createExpressionTarget = (): ExpressionGroupTarget => ({
platform: 'qq',
item_id: '',
rule_type: 'group',
})
const formatExpressionTarget = (target: ExpressionGroupTarget): string => {
const platform = target.platform.trim()
const itemId = target.item_id.trim()
const rule = ruleTypeLabel(target.rule_type)
if (!platform && !itemId) return `全局 · ${rule}`
if (!itemId) return `${platform} · ${rule}`
return `${platform}:${itemId} · ${rule}`
}
export const ChatTalkValueRulesHook = createListItemEditorHook({
addLabel: '添加发言频率规则',
addButtonPlacement: 'top',
collapseWhen: ({ parentValues }) => parentValues?.enable_talk_value_rules === false,
collapsedText: '动态发言频率规则未启用,规则列表已折叠。展开后仍可查看或编辑已有规则。',
expandLabel: '展开规则',
collapseLabel: '折叠规则',
helperText: '可按平台/聊天流/时段分别配置发言频率,留空表示全局。',
emptyText: '尚未配置任何规则,将使用全局默认频率。',
fieldRows: [
@@ -135,11 +213,219 @@ export const RegexRulesHook = createListItemEditorHook({
},
})
export const ExpressionGroupsHook = createJsonFieldHook({
emptyValue: [],
helperText: '表达互通组使用 JSON 编辑。每一项包含一个 expression_groups 数组。',
placeholder: '[\n {\n "expression_groups": [\n {\n "platform": "qq",\n "item_id": "123456",\n "rule_type": "group"\n }\n ]\n }\n]',
})
export const ExpressionGroupsHook: FieldHookComponent = ({ onChange, value }) => {
const groups = normalizeExpressionGroups(value)
const updateGroups = (nextGroups: ExpressionGroupValue[]) => {
onChange?.(nextGroups)
}
const addGroup = () => {
updateGroups([...groups, { expression_groups: [] }])
}
const removeGroup = (groupIndex: number) => {
updateGroups(groups.filter((_, index) => index !== groupIndex))
}
const addMember = (groupIndex: number) => {
updateGroups(
groups.map((group, index) =>
index === groupIndex
? {
expression_groups: [
...group.expression_groups,
createExpressionTarget(),
],
}
: group
)
)
}
const removeMember = (groupIndex: number, memberIndex: number) => {
updateGroups(
groups.map((group, index) =>
index === groupIndex
? {
expression_groups: group.expression_groups.filter(
(_, currentMemberIndex) => currentMemberIndex !== memberIndex
),
}
: group
)
)
}
const updateMember = (
groupIndex: number,
memberIndex: number,
patch: Partial<ExpressionGroupTarget>
) => {
updateGroups(
groups.map((group, index) =>
index === groupIndex
? {
expression_groups: group.expression_groups.map(
(member, currentMemberIndex) =>
currentMemberIndex === memberIndex
? { ...member, ...patch }
: member
),
}
: group
)
)
}
return (
<div className="space-y-4 rounded-lg border bg-card p-4 sm:p-6">
<div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
<div className="space-y-1">
<h3 className="text-base font-semibold"></h3>
<p className="text-sm text-muted-foreground">
expression_groups
</p>
</div>
<Button type="button" size="sm" variant="outline" onClick={addGroup}>
<Plus className="mr-2 h-4 w-4" />
</Button>
</div>
{groups.length === 0 ? (
<div className="rounded-md border border-dashed bg-muted/30 px-4 py-8 text-center text-sm text-muted-foreground">
</div>
) : (
<div className="space-y-3">
{groups.map((group, groupIndex) => (
<div
key={groupIndex}
className="space-y-3 rounded-md border bg-muted/20 p-3 sm:p-4"
>
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div className="flex flex-wrap items-center gap-2">
<span className="text-sm font-medium">
{groupIndex + 1}
</span>
<Badge variant="secondary">
{group.expression_groups.length}
</Badge>
</div>
<div className="flex gap-2">
<Button
type="button"
size="sm"
variant="outline"
onClick={() => addMember(groupIndex)}
>
<Plus className="mr-2 h-4 w-4" />
</Button>
<Button
type="button"
size="icon"
variant="ghost"
aria-label={`删除互通组 ${groupIndex + 1}`}
onClick={() => removeGroup(groupIndex)}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
{group.expression_groups.length === 0 ? (
<div className="rounded-md bg-background/70 px-3 py-4 text-sm text-muted-foreground">
</div>
) : (
<div className="space-y-2">
{group.expression_groups.map((member, memberIndex) => (
<div
key={`${groupIndex}-${memberIndex}`}
className="grid gap-3 rounded-md bg-background/80 p-3 md:grid-cols-[minmax(7rem,0.75fr)_minmax(10rem,1fr)_minmax(8rem,0.8fr)_auto]"
>
<div className="space-y-1">
<Label className="text-xs"></Label>
<Input
value={member.platform}
placeholder="qq"
onChange={(event) =>
updateMember(groupIndex, memberIndex, {
platform: event.target.value,
})
}
/>
</div>
<div className="space-y-1">
<Label className="text-xs"> / </Label>
<Input
className="font-mono"
value={member.item_id}
placeholder="123456"
onChange={(event) =>
updateMember(groupIndex, memberIndex, {
item_id: event.target.value,
})
}
/>
</div>
<div className="space-y-1">
<Label className="text-xs"></Label>
<Select
value={member.rule_type}
onValueChange={(nextRuleType) =>
updateMember(groupIndex, memberIndex, {
rule_type: normalizeExpressionRuleType(nextRuleType),
})
}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="group"></SelectItem>
<SelectItem value="private"></SelectItem>
</SelectContent>
</Select>
</div>
<div className="flex items-end justify-between gap-2 md:justify-end">
<span className="min-w-0 truncate text-xs text-muted-foreground md:hidden">
{formatExpressionTarget(member)}
</span>
<Button
type="button"
size="icon"
variant="ghost"
aria-label={`删除互通组 ${groupIndex + 1} 的成员 ${memberIndex + 1}`}
onClick={() => removeMember(groupIndex, memberIndex)}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
))}
</div>
)}
{group.expression_groups.length > 0 && (
<div className="flex flex-wrap gap-2">
{group.expression_groups.map((member, memberIndex) => (
<Badge key={memberIndex} variant="outline">
{formatExpressionTarget(member)}
</Badge>
))}
</div>
)}
</div>
))}
</div>
)}
</div>
)
}
export const MCPRootItemsHook = createJsonFieldHook({
emptyValue: [],

View File

@@ -63,27 +63,29 @@ export const BotInfoSection = React.memo(function BotInfoSection({ config, onCha
return (
<div className="rounded-lg border bg-card p-4 sm:p-6 space-y-6">
<div>
<h3 className="text-lg font-semibold mb-4"></h3>
<h3 className="text-lg font-semibold mb-4"></h3>
<div className="grid gap-4">
<div className="grid gap-2">
<Label htmlFor="platform"></Label>
<Input
id="platform"
value={config.platform}
onChange={(e) => onChange({ ...config, platform: e.target.value })}
placeholder="qq"
/>
</div>
<div className="grid gap-4 md:grid-cols-2">
<div className="grid gap-2">
<Label htmlFor="platform"></Label>
<Input
id="platform"
value={config.platform}
onChange={(e) => onChange({ ...config, platform: e.target.value })}
placeholder="qq"
/>
</div>
<div className="grid gap-2">
<Label htmlFor="qq_account">QQ账号</Label>
<Input
id="qq_account"
value={config.qq_account}
onChange={(e) => onChange({ ...config, qq_account: e.target.value })}
placeholder="123456789"
/>
<div className="grid gap-2">
<Label htmlFor="qq_account">QQ账号</Label>
<Input
id="qq_account"
value={config.qq_account}
onChange={(e) => onChange({ ...config, qq_account: e.target.value })}
placeholder="123456789"
/>
</div>
</div>
<div className="grid gap-2">

View File

@@ -311,23 +311,6 @@ export const FeaturesSection = React.memo(function FeaturesSection({
</Label>
</div>
{emojiConfig.content_filtration && (
<div className="grid gap-2 pl-6 border-l-2 border-primary/20">
<Label htmlFor="filtration_prompt"></Label>
<Input
id="filtration_prompt"
value={emojiConfig.filtration_prompt}
onChange={(e) =>
onEmojiChange({ ...emojiConfig, filtration_prompt: e.target.value })
}
placeholder="符合公序良俗"
/>
<p className="text-xs text-muted-foreground">
</p>
</div>
)}
</div>
</div>
</div>

View File

@@ -78,7 +78,6 @@ export interface EmojiConfig {
check_interval: number
steal_emoji: boolean
content_filtration: boolean
filtration_prompt: string
}
export interface MemoryConfig {

View File

@@ -1,5 +1,5 @@
import { useCallback, useEffect, useMemo, useState } from 'react'
import { FileText, Loader2, RefreshCw, Save, Search } from 'lucide-react'
import { FileText, Loader2, RefreshCw, Save, Search, SlidersHorizontal } from 'lucide-react'
import { CodeEditor } from '@/components/CodeEditor'
import { Badge } from '@/components/ui/badge'
@@ -36,6 +36,7 @@ export function PromptManagementPage() {
const [loadingFile, setLoadingFile] = useState(false)
const [saving, setSaving] = useState(false)
const [query, setQuery] = useState('')
const [showAdvancedPrompts, setShowAdvancedPrompts] = useState(false)
const hasUnsavedChanges = content !== savedContent
@@ -44,13 +45,30 @@ export function PromptManagementPage() {
return catalog.files[language] ?? []
}, [catalog, language])
const visiblePromptFiles = useMemo<PromptFileInfo[]>(() => {
return showAdvancedPrompts ? promptFiles : promptFiles.filter((file) => !file.advanced)
}, [promptFiles, showAdvancedPrompts])
const filteredFiles = useMemo(() => {
const normalizedQuery = query.trim().toLowerCase()
if (!normalizedQuery) return promptFiles
return promptFiles.filter((file) => file.name.toLowerCase().includes(normalizedQuery))
}, [promptFiles, query])
if (!normalizedQuery) return visiblePromptFiles
return visiblePromptFiles.filter((file) => {
const searchableText = [
file.name,
file.display_name,
file.description,
].join(' ').toLowerCase()
return searchableText.includes(normalizedQuery)
})
}, [visiblePromptFiles, query])
const selectedFile = promptFiles.find((file) => file.name === filename)
useEffect(() => {
if (!filename || showAdvancedPrompts) return
const currentFile = promptFiles.find((file) => file.name === filename)
if (!currentFile?.advanced) return
setFilename(visiblePromptFiles[0]?.name ?? '')
}, [filename, promptFiles, showAdvancedPrompts, visiblePromptFiles])
const loadCatalog = useCallback(async () => {
try {
@@ -70,7 +88,10 @@ export function PromptManagementPage() {
setLanguage(nextLanguage)
const nextFiles = nextLanguage ? result.data.files[nextLanguage] ?? [] : []
setFilename((current) => nextFiles.some((file) => file.name === current) ? current : nextFiles[0]?.name ?? '')
const nextBasicFiles = nextFiles.filter((file) => !file.advanced)
setFilename((current) =>
nextFiles.some((file) => file.name === current) ? current : nextBasicFiles[0]?.name ?? nextFiles[0]?.name ?? ''
)
} catch (error) {
toast({
title: '加载 Prompt 目录失败',
@@ -130,7 +151,8 @@ export function PromptManagementPage() {
setLanguage(nextLanguage)
setQuery('')
const nextFiles = catalog?.files[nextLanguage] ?? []
setFilename(nextFiles[0]?.name ?? '')
const nextVisibleFiles = showAdvancedPrompts ? nextFiles : nextFiles.filter((file) => !file.advanced)
setFilename(nextVisibleFiles[0]?.name ?? '')
}
const handleSave = async () => {
@@ -181,6 +203,14 @@ export function PromptManagementPage() {
<RefreshCw className={cn('mr-2 h-4 w-4', loadingCatalog && 'animate-spin')} />
</Button>
<Button
variant={showAdvancedPrompts ? 'default' : 'outline'}
size="sm"
onClick={() => setShowAdvancedPrompts((current) => !current)}
>
<SlidersHorizontal className="mr-2 h-4 w-4" />
{showAdvancedPrompts ? '隐藏高级' : '显示高级'}
</Button>
<Button size="sm" onClick={handleSave} disabled={!hasUnsavedChanges || saving || loadingFile || !filename}>
<Save className="mr-2 h-4 w-4" />
{saving ? '保存中' : hasUnsavedChanges ? '保存' : '已保存'}
@@ -194,7 +224,7 @@ export function PromptManagementPage() {
<CardTitle className="flex items-center gap-2 text-sm">
<FileText className="h-4 w-4" />
Prompt
<Badge variant="secondary" className="ml-auto">{promptFiles.length}</Badge>
<Badge variant="secondary" className="ml-auto">{filteredFiles.length}</Badge>
</CardTitle>
<div className="relative">
<Search className="pointer-events-none absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
@@ -226,8 +256,16 @@ export function PromptManagementPage() {
filename === file.name ? 'bg-accent text-accent-foreground' : 'text-muted-foreground',
)}
>
<div className="truncate font-medium" title={file.name}>{file.name}</div>
<div className="mt-0.5 text-xs text-muted-foreground">{formatFileSize(file.size)}</div>
<div className="flex items-center gap-2">
<div className="truncate font-medium" title={file.display_name || file.name}>
{file.display_name || file.name}
</div>
{file.advanced && <Badge variant="outline" className="shrink-0 text-[10px]"></Badge>}
</div>
<div className="mt-0.5 truncate text-xs text-muted-foreground">{file.name} · {formatFileSize(file.size)}</div>
{file.description && (
<div className="mt-1 line-clamp-2 text-xs text-muted-foreground">{file.description}</div>
)}
</button>
))
) : (
@@ -240,12 +278,18 @@ export function PromptManagementPage() {
<Card className="min-h-0 overflow-hidden">
<CardHeader className="flex flex-row items-center justify-between gap-3 space-y-0 pb-3">
<div className="min-w-0">
<CardTitle className="truncate text-sm">{filename || '未选择文件'}</CardTitle>
<CardTitle className="flex items-center gap-2 truncate text-sm">
<span className="truncate">{selectedFile?.display_name || filename || '未选择文件'}</span>
{selectedFile?.advanced && <Badge variant="outline" className="shrink-0"></Badge>}
</CardTitle>
<p className="mt-1 text-xs text-muted-foreground">
{language}
{selectedFile ? ` · ${formatFileSize(selectedFile.size)}` : ''}
{hasUnsavedChanges ? ' · 有未保存修改' : ''}
</p>
{selectedFile?.description && (
<p className="mt-1 line-clamp-2 text-xs text-muted-foreground">{selectedFile.description}</p>
)}
</div>
</CardHeader>
<CardContent className="min-h-0 p-0">

79
prompts/en-US/.meta.toml Normal file
View File

@@ -0,0 +1,79 @@
[maisaka_chat]
display_name = "Planner"
advanced = false
description = "Maisaka 主规划模板,负责整合身份、时间、工具说明和聊天上下文,驱动主循环进行思考、决策与工具调用。"
[maisaka_replyer]
display_name = "Replyer"
advanced = false
description = "Maisaka 回复生成模板,负责根据人格、表达风格、群聊注意事项和待回复上下文生成最终回复。"
[default_expressor]
display_name = "默认表达器"
advanced = true
description = "表达方式生成与整理相关模板,通常只在调试表达系统时需要修改。"
[emoji_content_analysis]
display_name = "表情包内容分析"
advanced = true
description = "用于分析表情包图片内容的模板。"
[emoji_content_filtration]
display_name = "表情包内容过滤"
advanced = true
description = "用于判断表情包内容是否符合过滤要求的模板。"
[emoji_replace]
display_name = "表情包替换"
advanced = true
description = "用于根据文本语境选择或替换表情包的模板。"
[expression_evaluation]
display_name = "表达评价"
advanced = true
description = "用于评价候选表达方式质量的模板。"
[expression_select]
display_name = "表达选择"
advanced = true
description = "用于从表达库中选择合适表达方式的模板。"
[image_description]
display_name = "图片描述"
advanced = true
description = "用于将图片内容转换为文本描述的模板。"
[jargon_compare_inference]
display_name = "术语对比推理"
advanced = true
description = "用于比较和推理群内术语含义的模板。"
[jargon_explainer_summarize]
display_name = "术语解释总结"
advanced = true
description = "用于总结术语解释结果的模板。"
[jargon_inference_content_only]
display_name = "术语推理"
advanced = true
description = "用于仅基于内容推理术语含义的模板。"
[jargon_inference_with_context]
display_name = "术语上下文推理"
advanced = true
description = "用于结合上下文推理术语含义的模板。"
[learn_style]
display_name = "表达风格学习"
advanced = true
description = "用于从聊天内容中学习表达风格的模板。"
[maisaka_timing_gate]
display_name = "Timing Gate"
advanced = false
description = "Maisaka 节奏控制模板,负责在每轮主循环前判断当前应该等待、停止,还是继续进入思考与回复流程。"
[memory_retrieval_react_prompt_head_memory]
display_name = "记忆检索 ReAct 头部"
advanced = true
description = "ReAct 式记忆查询流程使用的高级记忆检索提示词头部。"

View File

@@ -1,5 +1,5 @@
This is a sticker. Please review it according to the following criteria:
1. It must meet the requirement of "{demand}"
1. It must conform to public order and good morals
2. It must not contain pornography, violence, or other illegal or non-compliant content, and it must conform to public order and good morals
3. It must not be any form of screenshot, chat record, or video screenshot
4. It must not contain more than 5 words

View File

@@ -1,27 +0,0 @@
[Historical Topic Title List] (titles only, no specific content):
{history_topics_block}
[End of Historical Topic Title List]
[Current Chat Log] (each message has an index before it for later reference):
{messages_block}
[End of Current Chat Log]
Please complete the following tasks:
**Identify topics**
1. Identify one or more ongoing topics in the [Current Chat Log];
2. Messages in the [Current Chat Log] may be related to historical topics, or they may be completely unrelated;
3. Determine whether the topics in the [Historical Topic Title List] appear in the [Current Chat Log]. If they do, directly use that historical topic title string;
**Select messages**
1. For each topic (whether new or historical), select a list of message indices from the numbered messages above that are strongly related to that topic;
2. For each topic, use one sentence to clearly describe the event that is happening. It must include time (approximate is fine), people, the main event, and the theme, ensuring accuracy and distinction;
Please first output a short piece of reasoning explaining what topics exist, which are not included in the historical topics, which are included in the historical topics, and why;
Then strictly output the topics involved in the [Current Chat Log] in JSON format as follows:
[
{{
"topic": "topic",
"message_indices": [1, 2, 5]
}},
...
]

View File

@@ -1,22 +0,0 @@
Please summarize the following chat record segment based on the topic and extract the following information:
**Topic**: {topic}
**Requirements**:
1. Keywords: extract keywords related to the topic and return them as a list (3-10 keywords)
2. Summary: provide a plain-text summary of this segment (50-200 words). Requirements:
- Carefully retell the event and the chat content;
- Highlight the development process and the result of the event;
- Summarize around the central topic;
- Extract the key information points in the topic, and keep them concise and clear.
Please return in JSON format as follows:
{{
"keywords": ["keyword1", "keyword2", ...],
"summary": "summary content"
}}
Chat record:
{original_text}
Please return JSON directly and do not include any other content.

View File

@@ -1,18 +0,0 @@
You are an expert in analyzing user trait categories. Your task is to analyze the conversation content and determine which personal trait categories are involved.
Please carefully read the following conversation content and determine which personal trait categories are involved.
[Personal Trait Category List]
{categories_summary}
[Task Requirements]
1. Analyze the conversation content and determine which personal trait categories are involved
2. Output only the category numbers involved, separated by spaces
3. If the conversation content does not involve any personal trait category, output "none"
[Output Format Example]
1 3 5
or
none
Please start analyzing:

View File

@@ -1,17 +0,0 @@
You are an expert in extracting user trait information. Your task is to extract personal trait information related to the specified category from the conversation content.
[Target Category]
{category_name}
[Task Requirements]
1. Carefully read the conversation content and find all information related to "{category_name}"
2. The extracted information should be specific and accurate, avoiding vague descriptions
3. If there are multiple relevant pieces of information, merge them into one concise description
4. If there is no information related to this category in the conversation, output "none"
[Output Format Example]
The user is rather introverted and does not like speaking when many people are around, but becomes very lively with close friends.
or
none
Please start extracting:

View File

@@ -1,19 +0,0 @@
You are an expert in retrieving user traits. Your task is to determine which categories of personal trait information need to be retrieved based on the current conversation context.
[Current Conversation Context]
{chat_context}
[Personal Trait Category List]
{categories_summary}
[Task Requirements]
1. Analyze the current conversation context and determine which personal trait information is needed to help understand the user
2. Output only the needed category numbers, separated by spaces
3. If the current conversation does not need any personal trait information, output "none"
[Output Format Example]
2 5 8
or
none
Please start analyzing:

79
prompts/ja-JP/.meta.toml Normal file
View File

@@ -0,0 +1,79 @@
[maisaka_chat]
display_name = "Planner"
advanced = false
description = "Maisaka 主规划模板,负责整合身份、时间、工具说明和聊天上下文,驱动主循环进行思考、决策与工具调用。"
[maisaka_replyer]
display_name = "Replyer"
advanced = false
description = "Maisaka 回复生成模板,负责根据人格、表达风格、群聊注意事项和待回复上下文生成最终回复。"
[default_expressor]
display_name = "默认表达器"
advanced = true
description = "表达方式生成与整理相关模板,通常只在调试表达系统时需要修改。"
[emoji_content_analysis]
display_name = "表情包内容分析"
advanced = true
description = "用于分析表情包图片内容的模板。"
[emoji_content_filtration]
display_name = "表情包内容过滤"
advanced = true
description = "用于判断表情包内容是否符合过滤要求的模板。"
[emoji_replace]
display_name = "表情包替换"
advanced = true
description = "用于根据文本语境选择或替换表情包的模板。"
[expression_evaluation]
display_name = "表达评价"
advanced = true
description = "用于评价候选表达方式质量的模板。"
[expression_select]
display_name = "表达选择"
advanced = true
description = "用于从表达库中选择合适表达方式的模板。"
[image_description]
display_name = "图片描述"
advanced = true
description = "用于将图片内容转换为文本描述的模板。"
[jargon_compare_inference]
display_name = "术语对比推理"
advanced = true
description = "用于比较和推理群内术语含义的模板。"
[jargon_explainer_summarize]
display_name = "术语解释总结"
advanced = true
description = "用于总结术语解释结果的模板。"
[jargon_inference_content_only]
display_name = "术语推理"
advanced = true
description = "用于仅基于内容推理术语含义的模板。"
[jargon_inference_with_context]
display_name = "术语上下文推理"
advanced = true
description = "用于结合上下文推理术语含义的模板。"
[learn_style]
display_name = "表达风格学习"
advanced = true
description = "用于从聊天内容中学习表达风格的模板。"
[maisaka_timing_gate]
display_name = "Timing Gate"
advanced = false
description = "Maisaka 节奏控制模板,负责在每轮主循环前判断当前应该等待、停止,还是继续进入思考与回复流程。"
[memory_retrieval_react_prompt_head_memory]
display_name = "记忆检索 ReAct 头部"
advanced = true
description = "ReAct 式记忆查询流程使用的高级记忆检索提示词头部。"

View File

@@ -1,5 +1,5 @@
これはスタンプです。次の基準に従って審査してください:
1. "{demand}" の要求を満たしていること
1. 公序良俗に反しないこと
2. 色情、暴力などの違法・不適切な内容ではなく、公序良俗に反しないこと
3. いかなる形式のスクリーンショット、チャット履歴、動画のスクリーンショットでもないこと
4. 5文字を超える文字が含まれないこと

View File

@@ -1,27 +0,0 @@
【過去の話題タイトル一覧】(タイトルのみ、具体的な内容は含まない):
{history_topics_block}
【過去の話題タイトル一覧ここまで】
【今回のチャット記録】(各メッセージの前に番号があり、後で参照するために使う):
{messages_block}
【今回のチャット記録ここまで】
以下のタスクを完了してください:
**話題の識別**
1. 【今回のチャット記録】に含まれる進行中の話題を 1 つ以上識別する;
2. 【今回のチャット記録】中のメッセージは、過去の話題に関係している場合もあれば、まったく無関係な場合もある;
3. 【過去の話題タイトル一覧】の話題が【今回のチャット記録】に現れているか判断し、現れている場合はその過去の話題タイトル文字列をそのまま使う;
**メッセージの選択**
1. 各話題(新規話題または過去話題)について、上記の番号付きメッセージからその話題と強く関係するメッセージ番号一覧を選ぶ;
2. 各話題について、何が起きているのかを 1 文で明確に説明すること。時間(おおまかで可)、人物、主な出来事、テーマを必ず含め、正確で区別しやすい内容にする;
まず短い思考を出力し、どんな話題があるか、どれが過去話題に含まれず、どれが過去話題に含まれているか、そしてその理由を説明してください;
その後、【今回のチャット記録】に含まれる話題を次の JSON 形式で厳密に出力してください:
[
{{
"topic": "話題",
"message_indices": [1, 2, 5]
}},
...
]

View File

@@ -1,22 +0,0 @@
以下の話題に基づいて、チャット記録の一部を要約し、次の情報を抽出してください:
**話題**{topic}
**要件**
1. キーワード話題に関連するキーワードを抽出し、リスト形式で返す3〜10 個)
2. 要約この会話部分の平文要約を行う50〜200 文字)。要件:
- 起こった出来事とチャット内容を丁寧に言い換える;
- 出来事の展開過程と結果を重点的に示す;
- この話題という中心を軸に要約する;
- 話題内の重要情報を抽出し、簡潔で明確にする。
JSON 形式で次のように返してください:
{{
"keywords": ["キーワード1", "キーワード2", ...],
"summary": "要約内容"
}}
チャット記録:
{original_text}
JSON のみを直接返し、ほかの内容は含めないでください。

View File

@@ -1,18 +0,0 @@
あなたはユーザー特性カテゴリ分析の専門家です。あなたのタスクは、会話内容を分析し、どの個人特性カテゴリが関係しているかを判断することです。
以下の会話内容を注意深く読み、どの個人特性カテゴリが関係しているかを判断してください。
【個人特性カテゴリ一覧】
{categories_summary}
【タスク要件】
1. 会話内容を分析し、どの個人特性カテゴリが関係しているかを判断する
2. 関係しているカテゴリ番号だけを、スペース区切りで出力する
3. 会話内容がどの個人特性カテゴリにも関係しない場合は「無」と出力する
【出力形式の例】
1 3 5
または
分析を開始してください:

View File

@@ -1,17 +0,0 @@
あなたはユーザー特性情報抽出の専門家です。あなたのタスクは、会話内容から指定カテゴリに関係する個人特性情報を抽出することです。
【対象カテゴリ】
{category_name}
【タスク要件】
1. 会話内容を注意深く読み、「{category_name}」に関係するすべての情報を見つける
2. 抽出する情報は具体的かつ正確で、曖昧な表現を避ける
3. 関連情報が複数ある場合は、簡潔な 1 段落にまとめる
4. 会話内にこのカテゴリに関係する情報がない場合は「無」と出力する
【出力形式の例】
ユーザーはやや内向的で、人が多い場面では話すのが苦手だが、親しい友人とはとても活発になる。
または
抽出を開始してください:

View File

@@ -1,19 +0,0 @@
あなたはユーザー特性検索の専門家です。あなたのタスクは、現在の会話文脈に基づいて、どの個人特性カテゴリ情報を検索する必要があるかを判断することです。
【現在の会話文脈】
{chat_context}
【個人特性カテゴリ一覧】
{categories_summary}
【タスク要件】
1. 現在の会話文脈を分析し、ユーザー理解の助けになる個人特性情報が何かを判断する
2. 必要なカテゴリ番号だけを、スペース区切りで出力する
3. 現在の会話で個人特性情報がまったく不要な場合は「無」と出力する
【出力形式の例】
2 5 8
または
分析を開始してください:

74
prompts/zh-CN/.meta.toml Normal file
View File

@@ -0,0 +1,74 @@
[maisaka_chat]
display_name = "规划器"
advanced = false
description = "Maisaka 主规划模板,负责整合身份、时间、工具说明和聊天上下文,驱动主循环进行思考、决策与工具调用。"
[maisaka_replyer]
display_name = "回复"
advanced = false
description = "Maisaka 回复生成模板,负责根据人格、表达风格、群聊注意事项和待回复上下文生成最终回复。"
[default_expressor]
display_name = "改写器"
advanced = true
description = "表达方式生成与整理相关模板,通常只在调试表达系统时需要修改。"
[emoji_content_analysis]
display_name = "表情包内容分析"
advanced = true
description = "用于分析表情包图片内容的模板。"
[emoji_content_filtration]
display_name = "表情包内容过滤"
advanced = true
description = "用于判断表情包内容是否符合过滤要求的模板。"
[emoji_replace]
display_name = "表情包替换"
advanced = true
description = "用于根据文本语境选择或替换表情包的模板。"
[expression_evaluation]
display_name = "表达评价"
advanced = true
description = "用于评价候选表达方式质量的模板。"
[expression_select]
display_name = "表达选择"
advanced = true
description = "用于从表达库中选择合适表达方式的模板。"
[image_description]
display_name = "图片描述"
advanced = true
description = "用于将图片内容转换为文本描述的模板。"
[jargon_compare_inference]
display_name = "黑话对比推理"
advanced = true
description = "用于比较和推理群内黑话含义的模板。"
[jargon_explainer_summarize]
display_name = "黑话解释总结"
advanced = true
description = "用于总结黑话解释结果的模板。"
[jargon_inference_content_only]
display_name = "黑话推理"
advanced = true
description = "用于仅基于内容推理黑话含义的模板。"
[jargon_inference_with_context]
display_name = "黑话上下文推理"
advanced = true
description = "用于结合上下文推理黑话含义的模板。"
[learn_style]
display_name = "表达风格学习"
advanced = true
description = "用于从聊天内容中学习表达风格的模板。"
[maisaka_timing_gate]
display_name = "时机"
advanced = false
description = "Maisaka 节奏控制模板,负责在每轮主循环前判断当前应该等待、停止,还是继续进入思考与回复流程。"

View File

@@ -1,5 +1,5 @@
这是一个表情包,请对这个表情包进行审核,标准如下:
1. 必须符合"{demand}"的要求
1. 必须符合"符合公序良俗"的要求
2. 不能是色情、暴力、等违法违规内容,必须符合公序良俗
3. 不能是任何形式的截图,聊天记录或视频截图
4. 不要出现5个以上文字

View File

@@ -1,27 +0,0 @@
【历史话题标题列表】(仅标题,不含具体内容):
{history_topics_block}
【历史话题标题列表结束】
【本次聊天记录】(每条消息前有编号,用于后续引用):
{messages_block}
【本次聊天记录结束】
请完成以下任务:
**识别话题**
1. 识别【本次聊天记录】中正在进行的一个或多个话题;
2. 【本次聊天记录】的中的消息可能与历史话题有关,也可能毫无关联。
2. 判断【历史话题标题列表】中的话题是否在【本次聊天记录】中出现,如果出现,则直接使用该历史话题标题字符串;
**选取消息**
1. 对于每个话题(新话题或历史话题),从上述带编号的消息中选出与该话题强相关的消息编号列表;
2. 每个话题用一句话清晰地描述正在发生的事件,必须包含时间(大致即可)、人物、主要事件和主题,保证精准且有区分度;
请先输出一段简短思考,说明有什么话题,哪些是不包含在历史话题中的,哪些是包含在历史话题中的,并说明为什么;
然后严格以 JSON 格式输出【本次聊天记录】中涉及的话题,格式如下:
[
{{
"topic": "话题",
"message_indices": [1, 2, 5]
}},
...
]

View File

@@ -1,22 +0,0 @@
请基于以下话题,对聊天记录片段进行概括,提取以下信息:
**话题**{topic}
**要求**
1. 关键词提取与话题相关的关键词用列表形式返回3-10个关键词
2. 概括对这段话的平文本概括50-200字要求
- 仔细地转述发生的事件和聊天内容;
- 重点突出事件的发展过程和结果;
- 围绕话题这个中心进行概括。
- 提取话题中的关键信息点,关键信息点应该简洁明了。
请以JSON格式返回格式如下
{{
"keywords": ["关键词1", "关键词2", ...],
"summary": "概括内容"
}}
聊天记录:
{original_text}
请直接返回JSON不要包含其他内容。

View File

@@ -1,18 +0,0 @@
你是一个用户特征分类分析专家。你的任务是分析对话内容,判断其中涉及哪些个人特征分类。
请仔细阅读以下对话内容,判断其中涉及了哪些个人特征分类。
【个人特征分类列表】
{categories_summary}
【任务要求】
1. 分析对话内容,判断涉及哪些个人特征分类
2. 只输出涉及到的分类编号,用空格分隔
3. 如果对话内容不涉及任何个人特征分类,输出"无"
【输出格式示例】
1 3 5
请开始分析:

View File

@@ -1,17 +0,0 @@
你是一个用户特征信息提取专家。你的任务是从对话内容中提取与指定分类相关的个人特征信息。
【目标分类】
{category_name}
【任务要求】
1. 仔细阅读对话内容,找出与"{category_name}"相关的所有信息
2. 提取的信息应该具体、准确,避免模糊的描述
3. 如果有多条相关信息,请整合成一段简洁的描述
4. 如果对话中没有与该分类相关的信息,输出"无"
【输出格式示例】
用户性格比较内向,不喜欢在人多的时候说话,但和熟悉的朋友会变得很活跃。
请开始提取:

View File

@@ -1,19 +0,0 @@
你是一个用户特征检索专家。你的任务是根据当前对话上下文,判断需要检索哪些个人特征分类的信息。
【当前对话上下文】
{chat_context}
【个人特征分类列表】
{categories_summary}
【任务要求】
1. 分析当前对话上下文,判断需要哪些个人特征信息来帮助理解用户
2. 只输出需要的分类编号,用空格分隔
3. 如果当前对话不需要任何个人特征信息,输出"无"
【输出格式示例】
2 5 8
请开始分析:

View File

@@ -178,7 +178,6 @@ def _install_stub_modules(monkeypatch):
class _EmojiConfig:
max_reg_num = 20
content_filtration = False
filtration_prompt = ""
steal_emoji = False
do_replace = False
check_interval = 1
@@ -1956,7 +1955,6 @@ async def test_build_emoji_description_content_filtration_reject(monkeypatch):
logger = emoji_manager_new.logger
emoji_manager_new.global_config.emoji.content_filtration = True
emoji_manager_new.global_config.emoji.filtration_prompt = "rule"
def _read_bytes(_path):
return b""
@@ -1994,13 +1992,15 @@ async def test_build_emoji_description_content_filtration_pass(monkeypatch):
logger = emoji_manager_new.logger
emoji_manager_new.global_config.emoji.content_filtration = True
emoji_manager_new.global_config.emoji.filtration_prompt = "rule"
def _read_bytes(_path):
return b""
async def _vlm_response(prompt, *_args, **_kwargs):
if "rule" in str(prompt):
call_count = {"n": 0}
async def _vlm_response(*_args, **_kwargs):
call_count["n"] += 1
if call_count["n"] == 2:
return "", None
return "desc", None

View File

@@ -87,7 +87,46 @@ def test_list_prompt_templates_prefers_locale_specific_files(tmp_path: Path) ->
prompt_templates = list_prompt_templates(prompts_root=prompts_root)
assert prompt_templates["replyer"].read_text(encoding="utf-8") == "English"
assert prompt_templates["replyer"].path.read_text(encoding="utf-8") == "English"
def test_list_prompt_templates_loads_directory_metadata(tmp_path: Path) -> None:
prompts_root = tmp_path / "prompts"
write_prompt(prompts_root, "zh-CN", "replyer", "中文")
metadata_path = prompts_root / "zh-CN" / ".meta.toml"
metadata_path.write_text(
"""
[replyer]
display_name = "回复器"
advanced = true
description = "用于生成回复的主模板"
""".strip(),
encoding="utf-8",
)
prompt_templates = list_prompt_templates(prompts_root=prompts_root)
metadata = prompt_templates["replyer"].metadata
assert metadata.display_name == "回复器"
assert metadata.advanced is True
assert metadata.description == "用于生成回复的主模板"
def test_list_prompt_templates_loads_prompt_specific_metadata(tmp_path: Path) -> None:
prompts_root = tmp_path / "prompts"
write_prompt(prompts_root, "zh-CN", "replyer", "中文")
metadata_path = prompts_root / "zh-CN" / "replyer.meta.json"
metadata_path.write_text(
'{"display_name": "Replyer", "advanced": false, "description": "Prompt specific metadata"}',
encoding="utf-8",
)
prompt_templates = list_prompt_templates(prompts_root=prompts_root)
metadata = prompt_templates["replyer"].metadata
assert metadata.display_name == "Replyer"
assert metadata.advanced is False
assert metadata.description == "Prompt specific metadata"
def test_list_prompt_templates_reports_duplicate_name_with_custom_root(tmp_path: Path) -> None:

View File

@@ -1,8 +1,12 @@
from __future__ import annotations
from dataclasses import dataclass
from functools import lru_cache
from pathlib import Path
from typing import Any
from tomlkit import parse as parse_toml
import json
import logging
import os
import re
@@ -22,6 +26,19 @@ STRICT_ENV_VALUES = {"1", "true", "yes", "on"}
extract_prompt_placeholders = extract_placeholders
@dataclass(frozen=True)
class PromptMetadata:
display_name: str = ""
advanced: bool = False
description: str = ""
@dataclass(frozen=True)
class PromptTemplateInfo:
path: Path
metadata: PromptMetadata
def get_prompts_root(prompts_root: Path | None = None) -> Path:
return (prompts_root or PROMPTS_ROOT).resolve()
@@ -80,24 +97,86 @@ def iter_prompt_files(directory: Path, recursive: bool = True) -> list[Path]:
def _raise_duplicate_prompt_name(name: str, first_path: Path, second_path: Path, prompts_root: Path) -> None:
path_a = first_path.relative_to(prompts_root).as_posix()
path_b = second_path.relative_to(prompts_root).as_posix()
raise ValueError(
t(
"prompt.duplicate_template_name",
name=name,
path_a=first_path.relative_to(prompts_root),
path_b=second_path.relative_to(prompts_root),
path_a=path_a,
path_b=path_b,
)
)
def _scan_prompt_directory(directory: Path, prompts_root: Path) -> dict[str, Path]:
prompt_paths: dict[str, Path] = {}
def _coerce_metadata(raw_metadata: Any) -> PromptMetadata:
if not isinstance(raw_metadata, dict):
return PromptMetadata()
display_name = raw_metadata.get("display_name", "")
advanced = raw_metadata.get("advanced", False)
description = raw_metadata.get("description", "")
return PromptMetadata(
display_name=display_name if isinstance(display_name, str) else "",
advanced=advanced if isinstance(advanced, bool) else False,
description=description if isinstance(description, str) else "",
)
def _read_metadata_file(metadata_path: Path) -> dict[str, Any]:
if not metadata_path.is_file():
return {}
try:
if metadata_path.suffix == ".json":
metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
else:
metadata = parse_toml(metadata_path.read_text(encoding="utf-8"))
except Exception as exc:
logger.warning("读取 Prompt 元信息文件 %s 失败:%s", metadata_path, exc)
return {}
return dict(metadata) if isinstance(metadata, dict) else {}
def _extract_template_metadata(metadata: dict[str, Any], prompt_name: str) -> dict[str, Any]:
templates = metadata.get("templates")
if isinstance(templates, dict) and isinstance(templates.get(prompt_name), dict):
return dict(templates[prompt_name])
prompt_metadata = metadata.get(prompt_name)
if isinstance(prompt_metadata, dict):
return dict(prompt_metadata)
return metadata if any(key in metadata for key in ("display_name", "advanced", "description")) else {}
def _load_prompt_metadata(prompt_path: Path) -> PromptMetadata:
prompt_name = prompt_path.stem
metadata_sources = (
prompt_path.with_name(f"{prompt_name}.meta.toml"),
prompt_path.with_name(f"{prompt_name}.meta.json"),
prompt_path.parent / ".meta.toml",
prompt_path.parent / ".meta.json",
)
merged_metadata: dict[str, Any] = {}
for metadata_path in reversed(metadata_sources):
raw_metadata = _read_metadata_file(metadata_path)
merged_metadata.update(_extract_template_metadata(raw_metadata, prompt_name))
return _coerce_metadata(merged_metadata)
def _scan_prompt_directory(directory: Path, prompts_root: Path) -> dict[str, PromptTemplateInfo]:
prompt_paths: dict[str, PromptTemplateInfo] = {}
for prompt_path in iter_prompt_files(directory):
prompt_name = prompt_path.stem
existing_path = prompt_paths.get(prompt_name)
if existing_path is not None:
_raise_duplicate_prompt_name(prompt_name, existing_path, prompt_path, prompts_root)
prompt_paths[prompt_name] = prompt_path
existing_info = prompt_paths.get(prompt_name)
if existing_info is not None:
_raise_duplicate_prompt_name(prompt_name, existing_info.path, prompt_path, prompts_root)
prompt_paths[prompt_name] = PromptTemplateInfo(path=prompt_path, metadata=_load_prompt_metadata(prompt_path))
return prompt_paths
@@ -115,11 +194,11 @@ def _iter_locale_candidates(requested_locale: str) -> list[str]:
return locale_candidates
def list_prompt_templates(locale: str | None = None, prompts_root: Path | None = None) -> dict[str, Path]:
def list_prompt_templates(locale: str | None = None, prompts_root: Path | None = None) -> dict[str, PromptTemplateInfo]:
resolved_prompts_root = get_prompts_root(prompts_root)
requested_locale = normalize_locale(locale or get_locale())
prompt_paths: dict[str, Path] = {}
prompt_paths: dict[str, PromptTemplateInfo] = {}
for directory in _iter_prompt_template_layers(resolved_prompts_root, requested_locale):
prompt_paths.update(_scan_prompt_directory(directory, resolved_prompts_root))
@@ -149,7 +228,7 @@ def resolve_prompt_path(
else:
prompt_paths = list_prompt_templates(locale=requested_locale, prompts_root=resolved_prompts_root)
if normalized_name in prompt_paths:
return prompt_paths[normalized_name]
return prompt_paths[normalized_name].path
raise FileNotFoundError(t("prompt.template_not_found", locale=requested_locale, name=normalized_name))

View File

@@ -57,7 +57,7 @@ MODEL_CONFIG_PATH: Path = (CONFIG_DIR / "model_config.toml").resolve().absolute(
LEGACY_ENV_PATH: Path = (PROJECT_ROOT / ".env").resolve().absolute()
A_MEMORIX_LEGACY_CONFIG_PATH: Path = (CONFIG_DIR / "a_memorix.toml").resolve().absolute()
MMC_VERSION: str = "1.0.0-pre.11"
CONFIG_VERSION: str = "8.10.6"
CONFIG_VERSION: str = "8.10.7"
MODEL_CONFIG_VERSION: str = "1.15.3"
logger = get_logger("config")

View File

@@ -30,7 +30,7 @@ class ExampleConfig(ConfigBase):
class BotConfig(ConfigBase):
"""机器人配置类"""
__ui_label__ = "本信息"
__ui_label__ = ""
__ui_icon__ = "bot"
platform: str = Field(
@@ -87,6 +87,7 @@ class BotConfig(ConfigBase):
class PersonalityConfig(ConfigBase):
"""人格配置类"""
__ui_parent__ = "bot"
__ui_label__ = "人格"
__ui_icon__ = "user-circle"
@@ -1299,16 +1300,6 @@ class EmojiConfig(ConfigBase):
)
"""是否启用表情包过滤,只有符合该要求的表情包才会被保存"""
filtration_prompt: str = Field(
default="符合公序良俗",
json_schema_extra={
"advanced": True,
"x-widget": "input",
"x-icon": "shield",
},
)
"""表情包过滤要求,只有符合该要求的表情包才会被保存"""
class KeywordRuleConfig(ConfigBase):
"""关键词规则配置类"""

View File

@@ -915,11 +915,10 @@ class EmojiManager:
# 表情包审查
if global_config.emoji.content_filtration:
try:
filtration_prompt_template = prompt_manager.get_prompt("emoji_content_filtration")
filtration_prompt_template.add_context("demand", global_config.emoji.filtration_prompt)
filtration_prompt = await prompt_manager.render_prompt(filtration_prompt_template)
review_prompt_template = prompt_manager.get_prompt("emoji_content_filtration")
review_prompt = await prompt_manager.render_prompt(review_prompt_template)
filtration_result = await emoji_manager_vlm.generate_response_for_image(
filtration_prompt,
review_prompt,
image_base64,
image_format,
)

View File

@@ -13,7 +13,7 @@ from PIL import Image as PILImage
from PIL import ImageDraw, ImageFont
from pydantic import BaseModel, Field as PydanticField
from src.emoji_system.emoji_manager import emoji_manager
from src.emoji_system.emoji_manager import _is_vlm_task_configured, emoji_manager
from src.emoji_system.maisaka_tool import send_emoji_for_maisaka
from src.common.data_models.image_data_model import MaiEmoji
from src.common.data_models.message_component_data_model import ImageComponent, MessageSequence, TextComponent
@@ -38,6 +38,7 @@ _EMOJI_SUB_AGENT_MAX_TOKENS = 240
_EMOJI_MAX_CANDIDATE_COUNT = 64
_EMOJI_CANDIDATE_TILE_SIZE = 256
_EMOJI_SUCCESS_MESSAGE = "表情包发送成功"
_EMOJI_VLM_NOT_CONFIGURED_MESSAGE = "错误,没有配置视觉模型,无法使用表情包功能"
class EmojiSelectionResult(BaseModel):
@@ -298,6 +299,13 @@ def _resolve_emoji_selector_model_task_name() -> str:
return "vlm"
def _is_missing_visual_model_error(exc: Exception) -> bool:
"""判断是否为未配置视觉模型导致的选择失败。"""
error_text = str(exc)
return _EMOJI_VLM_NOT_CONFIGURED_MESSAGE in error_text or "未找到名为 '' 的模型" in error_text
async def _select_emoji_with_sub_agent(
tool_ctx: BuiltinToolRuntimeContext,
reasoning: str,
@@ -351,13 +359,17 @@ async def _select_emoji_with_sub_agent(
request_messages.append(candidate_llm_message)
serialized_request_messages = serialize_prompt_messages(request_messages)
model_task_name = _resolve_emoji_selector_model_task_name()
if model_task_name == "vlm" and not _is_vlm_task_configured():
raise RuntimeError(_EMOJI_VLM_NOT_CONFIGURED_MESSAGE)
selection_started_at = datetime.now()
response = await tool_ctx.runtime.run_sub_agent(
context_message_limit=_EMOJI_SUB_AGENT_CONTEXT_LIMIT,
system_prompt=system_prompt,
extra_messages=[prompt_message, candidate_message],
max_tokens=_EMOJI_SUB_AGENT_MAX_TOKENS,
model_task_name=_resolve_emoji_selector_model_task_name(),
model_task_name=model_task_name,
)
selection_duration_ms = round((datetime.now() - selection_started_at).total_seconds() * 1000, 2)
@@ -448,7 +460,10 @@ async def handle_tool(
)
except Exception as exc:
logger.exception(f"{tool_ctx.runtime.log_prefix} 发送表情包时发生异常: {exc}")
structured_result["message"] = f"发送表情包时发生异常:{exc}"
if _is_missing_visual_model_error(exc):
structured_result["message"] = _EMOJI_VLM_NOT_CONFIGURED_MESSAGE
else:
structured_result["message"] = f"发送表情包时发生异常:{exc}"
return tool_ctx.build_failure_result(
invocation.tool_name,
structured_result["message"],

View File

@@ -274,12 +274,12 @@ class PromptManager:
Exception: 如果在加载过程中出现任何文件操作错误则引发该异常
"""
prompt_templates = list_prompt_templates(prompts_root=PROMPTS_DIR)
for prompt_name, prompt_file in prompt_templates.items():
for prompt_name, prompt_template in prompt_templates.items():
try:
template, need_save = self._load_prompt_template(prompt_name)
self.add_prompt(Prompt(prompt_name=prompt_name, template=template), need_save=need_save)
except Exception as exc:
logger.error(f"加载 Prompt 文件 '{prompt_file}' 时出错,错误信息: {exc}")
logger.error(f"加载 Prompt 文件 '{prompt_template.path}' 时出错,错误信息: {exc}")
raise
for prompt_file in CUSTOM_PROMPTS_DIR.glob(f"*{SUFFIX_PROMPT}"):
if prompt_file.stem in prompt_templates:

View File

@@ -14,6 +14,7 @@ from pydantic import BaseModel, Field
import tomlkit
from src.common.logger import get_logger
from src.common.prompt_i18n import list_prompt_templates
from src.config.config import CONFIG_DIR, PROJECT_ROOT, Config, ModelConfig
from src.config.config_base import AttributeData, ConfigBase
from src.config.model_configs import (
@@ -64,6 +65,9 @@ class PromptFileInfo(BaseModel):
name: str = Field(..., description="Prompt 文件名")
size: int = Field(..., description="文件大小")
modified_at: float = Field(..., description="最后修改时间戳")
display_name: str = Field(default="", description="Prompt 展示名称")
advanced: bool = Field(default=False, description="是否为高级 Prompt")
description: str = Field(default="", description="Prompt 描述")
class PromptCatalogResponse(BaseModel):
@@ -213,14 +217,20 @@ async def list_prompt_files():
continue
language = language_dir.name
prompt_template_infos = list_prompt_templates(locale=language, prompts_root=PROMPTS_DIR)
prompt_files: List[PromptFileInfo] = []
for prompt_file in sorted(language_dir.glob("*.prompt"), key=lambda item: item.name):
stat = prompt_file.stat()
template_info = prompt_template_infos.get(prompt_file.stem)
metadata = template_info.metadata if template_info and template_info.path == prompt_file else None
prompt_files.append(
PromptFileInfo(
name=prompt_file.name,
size=stat.st_size,
modified_at=stat.st_mtime,
display_name=metadata.display_name if metadata else "",
advanced=metadata.advanced if metadata else False,
description=metadata.description if metadata else "",
)
)