Documentation
¶
Overview ¶
internal/services/Progress_service.go
internal/services/analyzer_service.go
internal/services/character_service.go
internal/services/config_service.go
internal/services/context_service.go
internal/services/export_service.go
internal/services/interaction_aggregate_service.go
internal/services/item_service.go
internal/services/llm_service.go
internal/services/lock_manager.go
internal/services/scene_aggregate_service.go
internal/services/scene_service.go
internal/services/script_service.go
internal/services/stats_service.go
internal/services/story_service.go
internal/services/story_service_metrics.go
internal/services/structs.go
internal/services/user_service.go
Index ¶
- Constants
- Variables
- func CleanLLMJSONResponse(raw string) string
- func SanitizeLLMJSONResponse(raw string) string
- type AggregateOptions
- type AggregateStats
- type AnalysisCache
- type AnalyzerService
- type CacheEntry
- type CachedAggregateData
- type CachedAnalysis
- type CachedExportData
- type CachedInteractionData
- type CachedItemData
- type CachedSceneData
- type CachedSceneList
- type CachedStoryData
- type CachedUserData
- type CharacterInfo
- type CharacterInteraction
- type CharacterMessage
- type CharacterService
- func (s *CharacterService) GenerateCharacterInteraction(sceneID string, characterIDs []string, topic string, contextDescription string) (*models.CharacterInteraction, error)
- func (s *CharacterService) GenerateResponse(sceneID, characterID, userMessage string) (*models.ChatResponse, error)
- func (s *CharacterService) GenerateResponseWithEmotion(sceneID, characterID, message string) (*models.EmotionalResponse, error)
- func (s *CharacterService) GenerateResponseWithEmotionFormat(sceneID, characterID, userMessage string) (*ChatResponseWithEmotion, error)
- func (s *CharacterService) GetCharacter(sceneID, characterID string) (*models.Character, error)
- func (s *CharacterService) GetCharacters(sceneID string, characterIDs []string) ([]*models.Character, error)
- func (s *CharacterService) InvalidateSceneCache(sceneID string)
- func (s *CharacterService) Shutdown()
- func (s *CharacterService) SimulateCharactersConversation(sceneID string, characterIDs []string, initialSituation string, ...) ([]models.InteractionDialogue, error)
- func (s *CharacterService) UpdateCharacterInScene(sceneID, characterID string, character *models.Character) error
- type CharacterState
- type ChatCompletionChoice
- type ChatCompletionMessage
- type ChatCompletionRequest
- type ChatCompletionResponse
- type ChatResponseWithEmotion
- type ConfigAuditEntry
- type ConfigChange
- type ConfigChangeRecord
- type ConfigChangeSubscriber
- type ConfigHealthCheck
- type ConfigService
- func (s *ConfigService) BeginTransaction() *ConfigTransaction
- func (s *ConfigService) ClearSubscribers()
- func (s *ConfigService) EnableAudit(enabled bool)
- func (s *ConfigService) GetAuditLog(limit int) []ConfigAuditEntry
- func (s *ConfigService) GetChangeHistory(limit int) []ConfigChangeRecord
- func (s *ConfigService) GetCurrentConfig() *config.AppConfig
- func (s *ConfigService) GetLLMConfig() map[string]string
- func (s *ConfigService) GetLLMInfo() (string, map[string]string)
- func (s *ConfigService) GetLLMProvider() string
- func (s *ConfigService) GetMetrics() map[string]interface{}
- func (s *ConfigService) GetSubscribersCount() int
- func (s *ConfigService) SaveConfig() error
- func (s *ConfigService) SetDebugMode(enabled bool) error
- func (s *ConfigService) StartCacheRefresher(refreshInterval time.Duration)
- func (s *ConfigService) StopCacheRefresher()
- func (s *ConfigService) SubscribeToChanges(subscriber ConfigChangeSubscriber)
- func (s *ConfigService) UnsubscribeFromChanges(subscriber ConfigChangeSubscriber)
- func (s *ConfigService) UpdateLLMConfig(provider string, configMap map[string]string, changedBy string) error
- func (s *ConfigService) ValidateAPIKey(provider string, apiKey string) (bool, string)
- type ConfigTransaction
- type ContentAnalysis
- type ContextService
- func (s *ContextService) AddConversation(sceneID, speakerID, content string, metadata map[string]interface{}, ...) error
- func (s *ContextService) BuildCharacterMemory(sceneID, characterID string) (string, error)
- func (s *ContextService) GetCharacterInteractions(sceneID string, filter map[string]interface{}, limit int) ([]models.Conversation, error)
- func (s *ContextService) GetCharacterToCharacterInteractions(sceneID string, character1ID string, character2ID string, limit int) ([]models.Conversation, error)
- func (s *ContextService) GetConsoleStoryEntriesByNode(sceneID, nodeID string, limit int) ([]models.Conversation, error)
- func (s *ContextService) GetInteractionsByID(sceneID string, interactionID string) ([]models.Conversation, error)
- func (s *ContextService) GetRecentConsoleStoryEntries(sceneID string, limit int) ([]models.Conversation, error)
- func (s *ContextService) GetRecentConversations(sceneID string, limit int) ([]models.Conversation, error)
- func (s *ContextService) GetSimulationByID(sceneID string, simulationID string) ([]models.Conversation, error)
- func (s *ContextService) GetUserStoryCommandsByNode(sceneID, nodeID string, limit int) ([]models.Conversation, error)
- func (s *ContextService) HasUserStoryCommands(sceneID, nodeID string) bool
- func (s *ContextService) InvalidateSceneCache(sceneID string)
- func (s *ContextService) RemoveConversationsAfterNode(sceneID string, removedNodeIDs []string, cutoff time.Time) error
- type EmotionData
- type ExplorationResult
- type ExportService
- func (s *ExportService) ExportInteractionSummary(ctx context.Context, sceneID string, format string) (*models.ExportResult, error)
- func (s *ExportService) ExportSceneData(ctx context.Context, sceneID string, format string, includeConversations bool) (*models.ExportResult, error)
- func (s *ExportService) ExportStoryAsDocument(ctx context.Context, sceneID string, format string) (*models.ExportResult, error)
- func (s *ExportService) InvalidateSceneCache(sceneID string)
- func (s *ExportService) StartCacheCleanup()
- type GameEvent
- type InteractionAggregateService
- func (s *InteractionAggregateService) ExportInteraction(ctx context.Context, sceneID string, format string) (*models.ExportResult, error)
- func (s *InteractionAggregateService) InvalidateCache(sceneID string)
- func (s *InteractionAggregateService) ProcessInteraction(ctx context.Context, request *InteractionRequest) (*InteractionResult, error)
- func (s *InteractionAggregateService) Start()
- func (s *InteractionAggregateService) StartCacheCleanup()
- type InteractionOptions
- type InteractionRequest
- type InteractionResult
- type InteractionStats
- type ItemService
- func (s *ItemService) AddItem(sceneID string, item *models.Item) error
- func (s *ItemService) DeleteItem(sceneID, itemID string) error
- func (s *ItemService) GetAllItems(sceneID string) ([]*models.Item, error)
- func (s *ItemService) GetItem(sceneID, itemID string) (*models.Item, error)
- func (s *ItemService) UpdateItem(sceneID string, item *models.Item) error
- type KeywordAnalysis
- type LLMCache
- type LLMService
- func (s *LLMService) AddToCache(key string, response *llm.CompletionResponse)
- func (s *LLMService) AnalyzeContent(ctx context.Context, text string) (*ContentAnalysis, error)
- func (s *LLMService) AnalyzeLocationContext(ctx context.Context, sceneName string, locations []LocationInfo) (*LocationAnalysis, error)
- func (s *LLMService) CheckCache(key string) *llm.CompletionResponse
- func (s *LLMService) CreateChatCompletion(ctx context.Context, request ChatCompletionRequest) (ChatCompletionResponse, error)
- func (s *LLMService) CreateStructuredCompletion(ctx context.Context, prompt string, systemPrompt string, ...) error
- func (s *LLMService) ExtractCharacters(ctx context.Context, text, title string) ([]CharacterInfo, error)
- func (s *LLMService) ExtractScenes(ctx context.Context, text, title string) ([]SceneInfo, error)
- func (s *LLMService) GenerateCacheKey(req llm.CompletionRequest) string
- func (s *LLMService) GenerateCharacterInteraction(ctx context.Context, character1 CharacterInfo, character2 CharacterInfo, ...) (*CharacterInteraction, error)
- func (s *LLMService) GenerateExplorationResult(ctx context.Context, ...) (*ExplorationResult, error)
- func (s *LLMService) GenerateScenarioIdeas(ctx context.Context, concept string, genre string, complexity string) (*ScenarioIdeas, error)
- func (s *LLMService) GetDefaultModel() string
- func (s *LLMService) GetProvider() llm.Provider
- func (s *LLMService) GetProviderName() string
- func (s *LLMService) GetProviderStatus() (bool, string)
- func (s *LLMService) GetReadyState() string
- func (s *LLMService) IsReady() bool
- func (s *LLMService) UpdateProvider(providerName string, config map[string]string) error
- type LLMServicer
- type LanguageContext
- type LocationAnalysis
- type LocationInfo
- type LockInfo
- type LockManager
- type Notification
- type NotificationAction
- type ProgressService
- func (s *ProgressService) CleanupAbandonedTrackers(maxAge time.Duration)
- func (s *ProgressService) CleanupCompletedTasks(maxAge time.Duration)
- func (s *ProgressService) CreateTracker(taskID string) *ProgressTracker
- func (s *ProgressService) GetActiveTaskCount() int
- func (s *ProgressService) GetTracker(taskID string) (*ProgressTracker, bool)
- func (s *ProgressService) StartAutoCleanup()
- func (s *ProgressService) Stop()
- type ProgressTracker
- type ProgressUpdate
- type ScenarioIdeas
- type SceneAggregateData
- type SceneAggregateService
- type SceneData
- type SceneInfo
- type SceneProgress
- type SceneService
- func (s *SceneService) AddCharacter(sceneID string, character *models.Character) error
- func (s *SceneService) CreateScene(userID, title, description, content, source string) (*models.Scene, error)
- func (s *SceneService) CreateSceneFromText(userID, text, title string) (*models.Scene, error)
- func (s *SceneService) CreateSceneWithCharacters(scene *models.Scene, characters []models.Character) error
- func (s *SceneService) DeleteCharacter(sceneID, characterID string) error
- func (s *SceneService) DeleteScene(sceneID string) error
- func (s *SceneService) GetAllScenes() ([]models.Scene, error)
- func (s *SceneService) GetCharactersByScene(sceneID string) ([]*models.Character, error)
- func (s *SceneService) LoadScene(sceneID string) (*SceneData, error)
- func (s *SceneService) LoadSceneNoCache(sceneID string) (*SceneData, error)
- func (s *SceneService) UpdateCharacter(sceneID, characterID string, character *models.Character) error
- func (s *SceneService) UpdateContext(sceneID string, context *models.SceneContext) error
- func (s *SceneService) UpdateSettings(sceneID string, settings *models.SceneSettings) error
- type SceneServiceInterface
- type SceneUIState
- type ScriptService
- func (s *ScriptService) Command(ctx context.Context, id string, req models.ScriptCommandRequest) (*models.ScriptCommandResponse, error)
- func (s *ScriptService) CreateProject(ctx context.Context, title, scriptType string, ...) (*models.ScriptProject, error)
- func (s *ScriptService) DeleteProject(ctx context.Context, scriptID string) error
- func (s *ScriptService) Export(ctx context.Context, id string, format string) (*models.ExportResult, error)
- func (s *ScriptService) ExportWithMeta(ctx context.Context, id string, format string, includeMeta bool) (*models.ExportResult, error)
- func (s *ScriptService) GenerateInitial(ctx context.Context, id string, tracker *ProgressTracker) error
- func (s *ScriptService) GetProject(ctx context.Context, id string) (*models.ScriptProject, error)
- func (s *ScriptService) ListDraftMetas(ctx context.Context, scriptID string) ([]models.ScriptDraftMeta, error)
- func (s *ScriptService) ListProjects(ctx context.Context) ([]models.ScriptProject, error)
- func (s *ScriptService) LoadCharacters(ctx context.Context, scriptID string) ([]map[string]interface{}, error)
- func (s *ScriptService) LoadItems(ctx context.Context, scriptID string) ([]map[string]interface{}, error)
- func (s *ScriptService) ManualEditDraft(ctx context.Context, scriptID string, baseDraftID string, ...) (*models.ScriptProject, string, error)
- func (s *ScriptService) Rewind(ctx context.Context, id string, draftID string) (*models.ScriptProject, error)
- func (s *ScriptService) SaveCharacters(ctx context.Context, scriptID string, chars []map[string]interface{}) error
- func (s *ScriptService) SaveItems(ctx context.Context, scriptID string, items []map[string]interface{}) error
- func (s *ScriptService) UpdateChapterUserDraft(ctx context.Context, scriptID string, chapterIndex int, userDraft string) (*models.ScriptChapterDraft, error)
- func (s *ScriptService) UpdateProjectBasics(ctx context.Context, scriptID string, title string, typ string, ...) (*models.ScriptProject, error)
- type StatsService
- type StoryImpact
- type StoryService
- func (s *StoryService) AdvanceStory(sceneID string, preferences *models.UserPreferences) (*models.StoryUpdate, error)
- func (s *StoryService) CompleteObjective(sceneID, taskID, objectiveID string) error
- func (s *StoryService) CreateStoryBranch(sceneID string, triggerType string, triggerID string, ...) (*models.StoryNode, error)
- func (s *StoryService) DeleteStoryData(sceneID string) error
- func (s *StoryService) EvaluateStoryProgress(sceneID string) (*models.StoryProgressStatus, error)
- func (s *StoryService) ExecuteBatchOperation(sceneID string, operation func(*models.StoryData) error) error
- func (s *StoryService) ExploreLocation(sceneID, locationID string, preferences *models.UserPreferences) (*models.ExplorationResult, error)
- func (s *StoryService) GetAvailableChoices(sceneID string) ([]models.StoryChoice, error)
- func (s *StoryService) GetStoryData(sceneID string, preferences *models.UserPreferences) (*models.StoryData, error)
- func (s *StoryService) GetStoryForScene(sceneID string) (*models.StoryData, error)
- func (s *StoryService) GetStoryNode(sceneID, nodeID string) (*models.StoryNode, error)
- func (s *StoryService) InitializeStoryForScene(sceneID string, preferences *models.UserPreferences) (*models.StoryData, error)
- func (s *StoryService) InitializeStoryForSceneFull(sceneID string, preferences *models.UserPreferences) (*models.StoryData, error)
- func (s *StoryService) MakeChoice(sceneID, nodeID, choiceID string, preferences *models.UserPreferences) (*models.StoryNode, error)
- func (s *StoryService) ProcessCharacterInteractionTriggers(sceneID string, nodeID string, preferences *models.UserPreferences) ([]*models.CharacterInteraction, error)
- func (s *StoryService) RewindToNode(sceneID, nodeID string) (*models.StoryData, error)
- func (s *StoryService) SaveStoryData(sceneID string, storyData *models.StoryData) error
- func (s *StoryService) UnlockLocation(sceneID, locationID string) error
- func (s *StoryService) UpdateNodeChoices(sceneID, nodeID string, choices []models.StoryChoice) error
- type StoryServiceMetrics
- type StoryUpdate
- type TabUpdate
- type TaskChange
- type TaskCompletionInfo
- type UIAnimation
- type UINotification
- type UIUpdateCommands
- type Usage
- type UsageStats
- type UserService
- func (s *UserService) AddUserItem(userID string, item models.UserItem) error
- func (s *UserService) AddUserSkill(userID string, skill models.UserSkill) error
- func (s *UserService) CreateUser(username string, email string) (*models.User, error)
- func (s *UserService) DeleteUserItem(userID string, itemID string) error
- func (s *UserService) DeleteUserSkill(userID string, skillID string) error
- func (s *UserService) EnsureUserExists(userID string) error
- func (s *UserService) GetUser(userID string) (*models.User, error)
- func (s *UserService) GetUserItem(userID string, itemID string) (*models.UserItem, error)
- func (s *UserService) GetUserItems(userID string) ([]models.UserItem, error)
- func (s *UserService) GetUserPreferences(userID string) (models.UserPreferences, error)
- func (s *UserService) GetUserSkill(userID string, skillID string) (*models.UserSkill, error)
- func (s *UserService) GetUserSkills(userID string) ([]models.UserSkill, error)
- func (s *UserService) SaveUser(user *models.User) error
- func (s *UserService) UpdateUserItem(userID string, itemID string, updatedItem models.UserItem) error
- func (s *UserService) UpdateUserPreferences(userID string, preferences models.UserPreferences) error
- func (s *UserService) UpdateUserSkill(userID string, skillID string, updatedSkill models.UserSkill) error
Constants ¶
const ( RoleSystem = "system" RoleUser = "user" RoleAssistant = "assistant" )
const (
TriggerTypeCharacterInteraction = "character_interaction"
)
角色互动触发条件常量
Variables ¶
var ErrLLMNotReady = errors.New("llm service not ready")
var (
ErrScriptNotFound = errors.New("script not found")
)
var ErrSkillValidation = errors.New("skill validation failed")
Functions ¶
func CleanLLMJSONResponse ¶ added in v1.3.1
CleanLLMJSONResponse 提供给外部调用的JSON清洗助手
func SanitizeLLMJSONResponse ¶ added in v1.3.1
SanitizeLLMJSONResponse 移除LLM响应中的Markdown代码块或反引号,确保可以解析为JSON
Types ¶
type AggregateOptions ¶
type AggregateOptions struct {
IncludeConversations bool
ConversationLimit int
IncludeStoryData bool
IncludeUIState bool
IncludeProgress bool
UserPreferences *models.UserPreferences
}
AggregateOptions 聚合选项
type AggregateStats ¶
type AggregateStats struct {
TotalCharacters int `json:"total_characters"`
TotalConversations int `json:"total_conversations"`
StoryProgress float64 `json:"story_progress"`
ActiveNodes int `json:"active_nodes"`
AvailableChoices int `json:"available_choices"`
}
AggregateStats 聚合统计信息
type AnalyzerService ¶
type AnalyzerService struct {
LLMService *LLMService
// contains filtered or unexported fields
}
AnalyzerService 分析和提取文本中的各种信息
func NewAnalyzerService ¶
func NewAnalyzerService() (*AnalyzerService, error)
NewAnalyzerService 创建分析服务
func NewAnalyzerServiceWithLLMService ¶ added in v1.3.1
func NewAnalyzerServiceWithLLMService(llmService *LLMService) *AnalyzerService
NewAnalyzerServiceWithLLMService 使用现有的LLM服务创建分析服务
func NewAnalyzerServiceWithProvider ¶
func NewAnalyzerServiceWithProvider(provider llm.Provider) *AnalyzerService
NewAnalyzerServiceWithProvider 使用指定的LLM Provider创建分析服务
func (*AnalyzerService) AnalyzeText ¶
func (s *AnalyzerService) AnalyzeText(text, title string) (*models.AnalysisResult, error)
AnalyzeText 分析文本,提取场景、角色、物品等信息
func (*AnalyzerService) AnalyzeTextWithProgress ¶
func (s *AnalyzerService) AnalyzeTextWithProgress(ctx context.Context, text string, tracker *ProgressTracker) (*models.AnalysisResult, error)
AnalyzeTextWithProgress 带进度反馈和超时控制的文本分析
type CacheEntry ¶
type CachedAggregateData ¶
type CachedAggregateData struct {
Data *SceneAggregateData
Timestamp time.Time
}
CachedAggregateData 缓存的聚合数据
type CachedAnalysis ¶
type CachedAnalysis struct {
Result *models.AnalysisResult
Timestamp time.Time
}
type CachedExportData ¶
type CachedExportData struct {
SceneData *SceneData
Conversations []models.Conversation
StoryData *models.StoryData
Timestamp time.Time
}
CachedExportData 缓存的导出数据
type CachedInteractionData ¶
type CachedInteractionData struct {
SceneData *SceneData
StoryData *models.StoryData
Characters map[string]*models.Character
Timestamp time.Time
}
CachedInteractionData 缓存的交互数据
type CachedItemData ¶
CachedItemData 缓存的物品数据
type CachedSceneData ¶
type CachedSceneList ¶
CachedSceneList 缓存的场景列表
type CachedStoryData ¶
type CachedStoryData struct {
Data *models.StoryData
Timestamp time.Time
Loading *sync.Once // 用于确保只加载一次
}
CachedStoryData 缓存的故事数据
type CachedUserData ¶
CachedUserData 缓存的用户数据
type CharacterInfo ¶
type CharacterInfo struct {
Name string `json:"name"`
Role string `json:"role"`
Description string `json:"description"`
Personality string `json:"personality"`
Background string `json:"background"`
SpeechStyle string `json:"speech_style"`
Relationships map[string]string `json:"relationships"`
Knowledge []string `json:"knowledge"`
}
以下是为各种服务定义的结构化输出类型------------------- CharacterInfo 角色信息
type CharacterInteraction ¶
type CharacterInteraction struct {
Conversation []struct {
Speaker string `json:"speaker"`
Dialogue string `json:"dialogue"`
Emotion string `json:"emotion,omitempty"`
Action string `json:"action,omitempty"`
} `json:"conversation"`
RelationshipDynamics string `json:"relationship_dynamics"`
PotentialOutcomes []struct {
Description string `json:"description"`
Impact string `json:"impact,omitempty"`
} `json:"potential_outcomes,omitempty"`
}
CharacterInteraction 角色互动结果
type CharacterMessage ¶
type CharacterMessage struct {
CharacterID string `json:"character_id"`
CharacterName string `json:"character_name"`
Content string `json:"content"`
EmotionData *EmotionData `json:"emotion_data"`
Timestamp time.Time `json:"timestamp"`
MessageType string `json:"message_type"` // response, action, thought
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
CharacterMessage 角色消息
type CharacterService ¶
type CharacterService struct {
// 依赖服务
LLMService *LLMService
ContextService *ContextService
// contains filtered or unexported fields
}
CharacterService 处理角色相关的业务逻辑
func (*CharacterService) GenerateCharacterInteraction ¶
func (s *CharacterService) GenerateCharacterInteraction( sceneID string, characterIDs []string, topic string, contextDescription string, ) (*models.CharacterInteraction, error)
GenerateCharacterInteraction 生成角色之间的互动对话
func (*CharacterService) GenerateResponse ¶
func (s *CharacterService) GenerateResponse(sceneID, characterID, userMessage string) (*models.ChatResponse, error)
GenerateResponse 生成角色回应
func (*CharacterService) GenerateResponseWithEmotion ¶
func (s *CharacterService) GenerateResponseWithEmotion(sceneID, characterID, message string) (*models.EmotionalResponse, error)
扩展GenerateResponseWithEmotion方法,返回更丰富的情绪数据
func (*CharacterService) GenerateResponseWithEmotionFormat ¶
func (s *CharacterService) GenerateResponseWithEmotionFormat(sceneID, characterID, userMessage string) (*ChatResponseWithEmotion, error)
GenerateResponseWithEmotionFormat 生成带有标准情绪格式的角色回应 使用 [情绪: ...][动作: ...] 格式
func (*CharacterService) GetCharacter ¶
func (s *CharacterService) GetCharacter(sceneID, characterID string) (*models.Character, error)
GetCharacter 根据ID获取指定场景中的角色
func (*CharacterService) GetCharacters ¶
func (s *CharacterService) GetCharacters(sceneID string, characterIDs []string) ([]*models.Character, error)
批量获取角色(避免重复读取)
func (*CharacterService) InvalidateSceneCache ¶
func (s *CharacterService) InvalidateSceneCache(sceneID string)
手动清除指定场景的缓存(当场景数据更新时调用)
func (*CharacterService) SimulateCharactersConversation ¶
func (s *CharacterService) SimulateCharactersConversation( sceneID string, characterIDs []string, initialSituation string, numberOfTurns int, ) ([]models.InteractionDialogue, error)
SimulateCharactersConversation 模拟多轮角色对话
func (*CharacterService) UpdateCharacterInScene ¶
func (s *CharacterService) UpdateCharacterInScene(sceneID, characterID string, character *models.Character) error
更新场景角色
type CharacterState ¶
type CharacterState struct {
CharacterID string `json:"character_id"`
Mood string `json:"mood"`
Energy float64 `json:"energy"`
Relationship map[string]float64 `json:"relationship"` // 与其他角色的关系值
CurrentActivity string `json:"current_activity"`
StatusEffects []string `json:"status_effects"`
LastUpdated time.Time `json:"last_updated"`
Metadata map[string]interface{} `json:"metadata"`
}
CharacterState 角色状态
type ChatCompletionChoice ¶
type ChatCompletionChoice struct {
Message ChatCompletionMessage
FinishReason string
}
ChatCompletionChoice 兼容旧的选择格式
type ChatCompletionMessage ¶
ChatCompletionMessage 兼容旧的消息格式
type ChatCompletionRequest ¶
type ChatCompletionRequest struct {
Model string `json:"model"`
Messages []ChatCompletionMessage `json:"messages"`
Temperature float64 `json:"temperature"`
MaxTokens int `json:"max_tokens"`
ExtraParams map[string]interface{} `json:"extra_params,omitempty"`
}
ChatCompletionRequest 兼容旧的请求格式
type ChatCompletionResponse ¶
type ChatCompletionResponse struct {
ID string
Choices []ChatCompletionChoice
Usage Usage
}
ChatCompletionResponse 兼容旧的响应格式
type ChatResponseWithEmotion ¶
type ChatResponseWithEmotion struct {
CharacterID string `json:"character_id"`
Message string `json:"message"`
Emotion string `json:"emotion"` // 情绪标识
Action string `json:"action"` // 行为描述
Original string `json:"original,omitempty"` // 原始回复(调试用)
}
ChatResponseWithEmotion 包含情绪和动作的聊天响应
type ConfigAuditEntry ¶
type ConfigAuditEntry struct {
Timestamp time.Time
Action string // "read", "write"
Section string
User string // 可用于记录谁访问了配置
}
ConfigAuditEntry 配置访问审计条目
type ConfigChange ¶
type ConfigChange struct {
Type string // "llm_config", "debug_mode", etc.
OldValue interface{}
NewValue interface{}
}
ConfigChange 配置变更
type ConfigChangeRecord ¶
type ConfigChangeRecord struct {
Timestamp time.Time
ChangedBy string
Section string
OldValue interface{}
NewValue interface{}
}
ConfigChangeRecord 配置变更记录
type ConfigChangeSubscriber ¶
ConfigChangeSubscriber 配置变更订阅者接口
type ConfigHealthCheck ¶
type ConfigHealthCheck struct {
// contains filtered or unexported fields
}
ConfigHealthCheck 配置健康检查
func NewConfigHealthCheck ¶
func NewConfigHealthCheck(service *ConfigService) *ConfigHealthCheck
NewConfigHealthCheck 创建配置健康检查
func (*ConfigHealthCheck) CheckHealth ¶
func (c *ConfigHealthCheck) CheckHealth() map[string]interface{}
CheckHealth 检查配置健康状态
type ConfigService ¶
type ConfigService struct {
// contains filtered or unexported fields
}
ConfigService 提供配置管理功能
func NewConfigService ¶
func NewConfigService() *ConfigService
-------------------------------------- NewConfigService 创建配置服务实例
func (*ConfigService) BeginTransaction ¶
func (s *ConfigService) BeginTransaction() *ConfigTransaction
BeginTransaction 开始配置事务
func (*ConfigService) ClearSubscribers ¶
func (s *ConfigService) ClearSubscribers()
ClearSubscribers 清空所有订阅者
func (*ConfigService) EnableAudit ¶
func (s *ConfigService) EnableAudit(enabled bool)
EnableAudit 启用配置访问审计
func (*ConfigService) GetAuditLog ¶
func (s *ConfigService) GetAuditLog(limit int) []ConfigAuditEntry
GetAuditLog 获取配置访问审计日志
func (*ConfigService) GetChangeHistory ¶
func (s *ConfigService) GetChangeHistory(limit int) []ConfigChangeRecord
GetChangeHistory 获取配置变更历史
func (*ConfigService) GetCurrentConfig ¶
func (s *ConfigService) GetCurrentConfig() *config.AppConfig
GetCurrentConfig 获取当前配置
func (*ConfigService) GetLLMConfig ¶
func (s *ConfigService) GetLLMConfig() map[string]string
GetLLMConfig 获取LLM配置
func (*ConfigService) GetLLMInfo ¶
func (s *ConfigService) GetLLMInfo() (string, map[string]string)
批量获取配置信息
func (*ConfigService) GetLLMProvider ¶
func (s *ConfigService) GetLLMProvider() string
GetLLMProvider 获取当前LLM提供商
func (*ConfigService) GetMetrics ¶
func (s *ConfigService) GetMetrics() map[string]interface{}
GetMetrics 获取配置服务指标
func (*ConfigService) GetSubscribersCount ¶
func (s *ConfigService) GetSubscribersCount() int
GetSubscribersCount 获取订阅者数量
func (*ConfigService) SetDebugMode ¶
func (s *ConfigService) SetDebugMode(enabled bool) error
SetDebugMode 设置调试模式
func (*ConfigService) StartCacheRefresher ¶
func (s *ConfigService) StartCacheRefresher(refreshInterval time.Duration)
StartCacheRefresher 启动一个后台goroutine定期刷新配置缓存
func (*ConfigService) SubscribeToChanges ¶
func (s *ConfigService) SubscribeToChanges(subscriber ConfigChangeSubscriber)
SubscribeToChanges 订阅配置变更事件
func (*ConfigService) UnsubscribeFromChanges ¶
func (s *ConfigService) UnsubscribeFromChanges(subscriber ConfigChangeSubscriber)
UnsubscribeFromChanges 取消配置变更订阅
func (*ConfigService) UpdateLLMConfig ¶
func (s *ConfigService) UpdateLLMConfig(provider string, configMap map[string]string, changedBy string) error
UpdateLLMConfig 更新LLM提供商和配置
func (*ConfigService) ValidateAPIKey ¶
func (s *ConfigService) ValidateAPIKey(provider string, apiKey string) (bool, string)
ValidateAPIKey 验证API密钥是否有效 返回验证结果和可能的错误信息
type ConfigTransaction ¶
type ConfigTransaction struct {
// contains filtered or unexported fields
}
ConfigTransaction 配置事务
func (*ConfigTransaction) UpdateLLMConfigInTransaction ¶
func (t *ConfigTransaction) UpdateLLMConfigInTransaction(provider string, configMap map[string]string, changedBy string) error
UpdateLLMConfigInTransaction 在事务中更新LLM配置
type ContentAnalysis ¶
type ContentAnalysis struct {
Characters []struct {
Name string `json:"name"`
Description string `json:"description"`
Traits []string `json:"traits"`
Relations map[string]string `json:"relations,omitempty"`
} `json:"characters"`
Scenes []struct {
Name string `json:"name"`
Description string `json:"description"`
Atmosphere string `json:"atmosphere"`
Items []string `json:"items,omitempty"`
} `json:"scenes"`
Props []struct {
Name string `json:"name"`
Description string `json:"description"`
Function string `json:"function,omitempty"`
Connections []string `json:"connections,omitempty"`
} `json:"props"`
Plotpoints []struct {
Description string `json:"description"`
Importance string `json:"importance"`
Characters []string `json:"characters,omitempty"`
} `json:"plotpoints"`
Themes []string `json:"themes"`
}
ContentAnalysis 内容分析结果
type ContextService ¶
type ContextService struct {
SceneService SceneServiceInterface
// contains filtered or unexported fields
}
ContextService 管理场景上下文和交互历史
func NewContextService ¶
func NewContextService(sceneService SceneServiceInterface) *ContextService
NewContextService 创建上下文服务
func (*ContextService) AddConversation ¶
func (s *ContextService) AddConversation(sceneID, speakerID, content string, metadata map[string]interface{}, nodeID string) error
AddConversation 添加对话到场景上下文,支持角色间对话记录
func (*ContextService) BuildCharacterMemory ¶
func (s *ContextService) BuildCharacterMemory(sceneID, characterID string) (string, error)
BuildCharacterMemory 构建角色记忆
func (*ContextService) GetCharacterInteractions ¶
func (s *ContextService) GetCharacterInteractions(sceneID string, filter map[string]interface{}, limit int) ([]models.Conversation, error)
GetCharacterInteractions 获取场景中的角色间互动历史
func (*ContextService) GetCharacterToCharacterInteractions ¶
func (s *ContextService) GetCharacterToCharacterInteractions(sceneID string, character1ID string, character2ID string, limit int) ([]models.Conversation, error)
GetCharacterToCharacterInteractions 获取特定两个角色之间的互动
func (*ContextService) GetConsoleStoryEntriesByNode ¶ added in v1.3.1
func (s *ContextService) GetConsoleStoryEntriesByNode(sceneID, nodeID string, limit int) ([]models.Conversation, error)
GetConsoleStoryEntriesByNode 获取指定节点的 console_story 内容
func (*ContextService) GetInteractionsByID ¶
func (s *ContextService) GetInteractionsByID(sceneID string, interactionID string) ([]models.Conversation, error)
GetInteractionsByID 根据互动ID获取完整对话
func (*ContextService) GetRecentConsoleStoryEntries ¶ added in v1.3.1
func (s *ContextService) GetRecentConsoleStoryEntries(sceneID string, limit int) ([]models.Conversation, error)
GetRecentConsoleStoryEntries 获取最近的 console_story 内容
func (*ContextService) GetRecentConversations ¶
func (s *ContextService) GetRecentConversations(sceneID string, limit int) ([]models.Conversation, error)
GetRecentConversations 获取最近的对话
func (*ContextService) GetSimulationByID ¶
func (s *ContextService) GetSimulationByID(sceneID string, simulationID string) ([]models.Conversation, error)
GetSimulationByID 根据模拟ID获取完整对话
func (*ContextService) GetUserStoryCommandsByNode ¶ added in v1.3.1
func (s *ContextService) GetUserStoryCommandsByNode(sceneID, nodeID string, limit int) ([]models.Conversation, error)
GetUserStoryCommandsByNode 获取指定节点下最新的玩家指令
func (*ContextService) HasUserStoryCommands ¶ added in v1.3.1
func (s *ContextService) HasUserStoryCommands(sceneID, nodeID string) bool
HasUserStoryCommands 判断指定节点是否存在玩家指令
func (*ContextService) InvalidateSceneCache ¶
func (s *ContextService) InvalidateSceneCache(sceneID string)
手动清除指定场景的缓存(当场景数据更新时调用)
func (*ContextService) RemoveConversationsAfterNode ¶ added in v1.3.1
func (s *ContextService) RemoveConversationsAfterNode(sceneID string, removedNodeIDs []string, cutoff time.Time) error
RemoveConversationsAfterNode 移除指定节点之后的旁白/用户对话,防止回溯后残留上下文
type EmotionData ¶
type EmotionData struct {
Text string `json:"text"`
Emotion string `json:"emotion"`
Action string `json:"action"`
Intensity int `json:"intensity"`
BodyLanguage string `json:"body_language"`
FacialExpression string `json:"facial_expression"`
VoiceTone string `json:"voice_tone"`
SecondaryEmotions []string `json:"secondary_emotions"`
}
EmotionData 提取的情绪数据
type ExplorationResult ¶
type ExplorationResult struct {
DiscoveredItem *struct {
Name string `json:"name"`
Description string `json:"description"`
Type string `json:"type"`
} `json:"discovered_item,omitempty"`
StoryEvent *struct {
Content string `json:"content"`
Type string `json:"type"`
Choices []struct {
Text string `json:"text"`
Consequence string `json:"consequence"`
} `json:"choices,omitempty"`
} `json:"story_event,omitempty"`
NewClue string `json:"new_clue,omitempty"`
}
ExplorationResult 探索结果
type ExportService ¶
type ExportService struct {
ContextService *ContextService
StoryService *StoryService
SceneService *SceneService
// contains filtered or unexported fields
}
func NewExportService ¶
func NewExportService(contextService *ContextService, storyService *StoryService, sceneService *SceneService) *ExportService
NewExportService 创建导出服务
func (*ExportService) ExportInteractionSummary ¶
func (s *ExportService) ExportInteractionSummary(ctx context.Context, sceneID string, format string) (*models.ExportResult, error)
ExportInteractionSummary 导出交互摘要功能
func (*ExportService) ExportSceneData ¶
func (s *ExportService) ExportSceneData(ctx context.Context, sceneID string, format string, includeConversations bool) (*models.ExportResult, error)
--------------------------------------------- ✅ 场景导出方法
func (*ExportService) ExportStoryAsDocument ¶
func (s *ExportService) ExportStoryAsDocument(ctx context.Context, sceneID string, format string) (*models.ExportResult, error)
--------------------------------------------- ✅ 故事导出方法 ExportStoryAsDocument 导出故事文档
func (*ExportService) InvalidateSceneCache ¶
func (s *ExportService) InvalidateSceneCache(sceneID string)
手动清除指定场景的缓存
type GameEvent ¶
type GameEvent struct {
EventType string `json:"event_type"`
EventData map[string]interface{} `json:"event_data"`
Triggers []string `json:"triggers"` // 触发条件
Effects []string `json:"effects"` // 效果
Timestamp time.Time `json:"timestamp"`
}
GameEvent 游戏事件
type InteractionAggregateService ¶
type InteractionAggregateService struct {
CharacterService *CharacterService
ContextService *ContextService
SceneService *SceneService
StatsService *StatsService
StoryService *StoryService
ExportService *ExportService
// contains filtered or unexported fields
}
func NewInteractionAggregateService ¶
func NewInteractionAggregateService( characterService *CharacterService, contextService *ContextService, sceneService *SceneService, statsService *StatsService, storyService *StoryService, exportService *ExportService) *InteractionAggregateService
----------------------------------------------------- NewInteractionAggregateService 创建新的交互聚合服务实例
func (*InteractionAggregateService) ExportInteraction ¶
func (s *InteractionAggregateService) ExportInteraction(ctx context.Context, sceneID string, format string) (*models.ExportResult, error)
委托导出功能
func (*InteractionAggregateService) InvalidateCache ¶
func (s *InteractionAggregateService) InvalidateCache(sceneID string)
清除指定场景的缓存
func (*InteractionAggregateService) ProcessInteraction ¶
func (s *InteractionAggregateService) ProcessInteraction( ctx context.Context, request *InteractionRequest) (*InteractionResult, error)
ProcessInteraction 处理完整的交互流程
func (*InteractionAggregateService) StartCacheCleanup ¶
func (s *InteractionAggregateService) StartCacheCleanup()
启动后台清理
type InteractionOptions ¶
type InteractionOptions struct {
GenerateFollowUps bool `json:"generate_follow_ups"`
UpdateStoryProgress bool `json:"update_story_progress"`
SaveToHistory bool `json:"save_to_history"`
TriggerEvents bool `json:"trigger_events"`
}
InteractionOptions 交互选项
type InteractionRequest ¶
type InteractionRequest struct {
SceneID string `json:"scene_id"`
CharacterIDs []string `json:"character_ids"`
Message string `json:"message"`
NodeID string `json:"node_id,omitempty"`
EmotionData *EmotionData `json:"emotion_data,omitempty"`
Context map[string]interface{} `json:"context,omitempty"`
Options *InteractionOptions `json:"options,omitempty"`
}
InteractionRequest 交互请求
type InteractionResult ¶
type InteractionResult struct {
// 角色响应
Messages []CharacterMessage `json:"messages"`
// 故事更新
StoryUpdates *StoryUpdate `json:"story_updates,omitempty"`
// 角色状态变化
CharacterStates map[string]CharacterState `json:"character_states"`
// 新的选择项
NewChoices []*models.StoryChoice `json:"new_choices,omitempty"`
// UI更新指令
UIUpdates *UIUpdateCommands `json:"ui_updates"`
// 通知消息
Notifications []Notification `json:"notifications"`
// 事件触发
Events []GameEvent `json:"events,omitempty"`
// 统计信息
Stats *InteractionStats `json:"stats"`
}
InteractionResult 交互结果
type InteractionStats ¶
type InteractionStats struct {
TokensUsed int `json:"tokens_used"`
ProcessingTime int64 `json:"processing_time_ms"`
CharactersInvolved int `json:"characters_involved"`
MessagesGenerated int `json:"messages_generated"`
EventsTriggered int `json:"events_triggered"`
TotalInteractions int `json:"total_interactions"`
TotalMessages int `json:"total_messages"`
TotalTokensUsed int `json:"total_tokens_used"`
TotalProcessingTime int64 `json:"total_processing_time"`
TotalTasksCompleted int `json:"total_tasks_completed"`
TotalProgressChange float64 `json:"total_progress_change"`
LastUpdated time.Time `json:"last_updated"`
}
InteractionStats 交互统计
type ItemService ¶
type ItemService struct {
ScenesPath string
// contains filtered or unexported fields
}
ItemService 处理物品相关的业务逻辑
func (*ItemService) AddItem ¶
func (s *ItemService) AddItem(sceneID string, item *models.Item) error
AddItem 添加物品 🔧 线程安全的 AddItem 方法
func (*ItemService) DeleteItem ¶
func (s *ItemService) DeleteItem(sceneID, itemID string) error
DeleteItem 删除物品
func (*ItemService) GetAllItems ¶
func (s *ItemService) GetAllItems(sceneID string) ([]*models.Item, error)
GetAllItems 获取场景中的所有物品
func (*ItemService) GetItem ¶
func (s *ItemService) GetItem(sceneID, itemID string) (*models.Item, error)
GetItem 获取物品
func (*ItemService) UpdateItem ¶
func (s *ItemService) UpdateItem(sceneID string, item *models.Item) error
UpdateItem 更新物品
type KeywordAnalysis ¶
KeywordAnalysis 关键词分析结果
type LLMService ¶
type LLMService struct {
// contains filtered or unexported fields
}
LLMService 提供统一的大语言模型调用接口
func NewEmptyLLMService ¶
func NewEmptyLLMService() *LLMService
NewEmptyLLMService 创建一个空的LLM服务实例作为后备方案
func NewLLMService ¶
func NewLLMService() (*LLMService, error)
----------------------------------------- NewLLMService 创建一个新的LLM服务
func (*LLMService) AddToCache ¶
func (s *LLMService) AddToCache(key string, response *llm.CompletionResponse)
AddToCache 添加响应到缓存
func (*LLMService) AnalyzeContent ¶
func (s *LLMService) AnalyzeContent(ctx context.Context, text string) (*ContentAnalysis, error)
AnalyzeContent 分析文本内容,提取关键信息
func (*LLMService) AnalyzeLocationContext ¶
func (s *LLMService) AnalyzeLocationContext(ctx context.Context, sceneName string, locations []LocationInfo) (*LocationAnalysis, error)
AnalyzeLocationContext 分析场景中的位置关系
func (*LLMService) CheckCache ¶
func (s *LLMService) CheckCache(key string) *llm.CompletionResponse
CheckCache 检查并返回缓存的响应
func (*LLMService) CreateChatCompletion ¶
func (s *LLMService) CreateChatCompletion(ctx context.Context, request ChatCompletionRequest) (ChatCompletionResponse, error)
兼容旧的CreateChatCompletion方法
func (*LLMService) CreateStructuredCompletion ¶
func (s *LLMService) CreateStructuredCompletion(ctx context.Context, prompt string, systemPrompt string, outputSchema interface{}) error
增强版ChatCompletion: 支持结构化输出 🔧 优化后的 CreateStructuredCompletion
func (*LLMService) ExtractCharacters ¶
func (s *LLMService) ExtractCharacters(ctx context.Context, text, title string) ([]CharacterInfo, error)
用于结构化输出时抽取角色信息
func (*LLMService) ExtractScenes ¶
用于提取场景信息
func (*LLMService) GenerateCacheKey ¶
func (s *LLMService) GenerateCacheKey(req llm.CompletionRequest) string
GenerateCacheKey 为请求生成缓存键
func (*LLMService) GenerateCharacterInteraction ¶
func (s *LLMService) GenerateCharacterInteraction(ctx context.Context, character1 CharacterInfo, character2 CharacterInfo, situation string) (*CharacterInteraction, error)
GenerateCharacterInteraction 生成角色互动内容
func (*LLMService) GenerateExplorationResult ¶
func (s *LLMService) GenerateExplorationResult(ctx context.Context, sceneName, locationName, locationDesc, sceneDesc, creativityLevel string, allowPlotTwists bool) (*ExplorationResult, error)
GenerateExplorationResult 用于探索地点时的结果分析
func (*LLMService) GenerateScenarioIdeas ¶
func (s *LLMService) GenerateScenarioIdeas(ctx context.Context, concept string, genre string, complexity string) (*ScenarioIdeas, error)
GenerateScenarioIdeas 根据初始概念生成场景创意
func (*LLMService) GetDefaultModel ¶
func (s *LLMService) GetDefaultModel() string
GetDefaultModel 获取当前配置的默认模型
func (*LLMService) GetProvider ¶
func (s *LLMService) GetProvider() llm.Provider
GetProvider 返回内部的Provider实例
func (*LLMService) GetProviderName ¶
func (s *LLMService) GetProviderName() string
GetProviderName 返回当前LLM提供商名称
func (*LLMService) GetProviderStatus ¶ added in v1.3.1
func (s *LLMService) GetProviderStatus() (bool, string)
GetProviderStatus 返回服务是否就绪以及可读描述
func (*LLMService) GetReadyState ¶
func (s *LLMService) GetReadyState() string
GetReadyState 返回服务就绪状态描述
func (*LLMService) UpdateProvider ¶
func (s *LLMService) UpdateProvider(providerName string, config map[string]string) error
UpdateProvider 更新LLM服务的提供商
type LLMServicer ¶
type LLMServicer interface {
AnalyzeText(text, title string) (*models.AnalysisResult, error)
AnalyzeContent(text string) (*ContentAnalysis, error)
}
LLMServicer 定义LLM服务接口
type LocationAnalysis ¶
type LocationAnalysis struct {
SpatialRelations []struct {
Location1 string `json:"location1"`
Location2 string `json:"location2"`
Relation string `json:"relation"`
PathDetails string `json:"path_details,omitempty"`
} `json:"spatial_relations"`
LocationFunctions map[string]string `json:"location_functions"`
RecommendedPaths []struct {
Path []string `json:"path"`
Description string `json:"description"`
StoryPotential string `json:"story_potential"`
} `json:"recommended_paths"`
StoryFlowSuggestions []string `json:"story_flow_suggestions"`
}
LocationAnalysis 位置分析结果
type LocationInfo ¶
type LocationInfo struct {
Name string `json:"name"`
Description string `json:"description"`
Items []string `json:"items,omitempty"`
Connections []string `json:"connections,omitempty"`
}
LocationInfo 位置信息
type LockInfo ¶ added in v1.3.1
type LockInfo struct {
Mutex *sync.RWMutex
LastUsed time.Time
ReferenceCount int32 // 当前锁被引用的次数,用于防止在使用时被清理
}
LockInfo 包装锁和相关信息
type LockManager ¶
type LockManager struct {
// contains filtered or unexported fields
}
LockManager 统一的锁管理器
func (*LockManager) ExecuteWithSceneLock ¶
func (lm *LockManager) ExecuteWithSceneLock(sceneID string, fn func() error) error
ExecuteWithSceneLock 在场景锁保护下执行操作
func (*LockManager) ExecuteWithSceneReadLock ¶
func (lm *LockManager) ExecuteWithSceneReadLock(sceneID string, fn func() error) error
ExecuteWithSceneReadLock 在场景读锁保护下执行操作
func (*LockManager) GetSceneLock ¶
func (lm *LockManager) GetSceneLock(sceneID string) *sync.RWMutex
GetSceneLock 获取场景锁(线程安全)
type Notification ¶
type Notification struct {
ID string `json:"id"`
Type string `json:"type"` // info, success, warning, error, achievement
Title string `json:"title"`
Message string `json:"message"`
Duration int `json:"duration"` // 显示时间(毫秒)
Actions []NotificationAction `json:"actions,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
Notification 通知
type NotificationAction ¶
type NotificationAction struct {
Label string `json:"label"`
Action string `json:"action"`
Style string `json:"style"` // primary, secondary, danger
Params map[string]interface{} `json:"params,omitempty"`
}
NotificationAction 通知操作
type ProgressService ¶
type ProgressService struct {
// contains filtered or unexported fields
}
ProgressService 管理所有进度跟踪器
func (*ProgressService) CleanupAbandonedTrackers ¶
func (s *ProgressService) CleanupAbandonedTrackers(maxAge time.Duration)
CleanupAbandonedTrackers 清理被遗弃的跟踪器(长时间未更新的运行中任务)
func (*ProgressService) CleanupCompletedTasks ¶
func (s *ProgressService) CleanupCompletedTasks(maxAge time.Duration)
CleanupCompletedTasks 清理已完成的任务
func (*ProgressService) CreateTracker ¶
func (s *ProgressService) CreateTracker(taskID string) *ProgressTracker
CreateTracker 创建新的进度跟踪器
func (*ProgressService) GetActiveTaskCount ¶
func (s *ProgressService) GetActiveTaskCount() int
GetActiveTaskCount 获取当前正在运行的任务数量
func (*ProgressService) GetTracker ¶
func (s *ProgressService) GetTracker(taskID string) (*ProgressTracker, bool)
GetTracker 获取进度跟踪器
type ProgressTracker ¶
type ProgressTracker struct {
TaskID string // 任务唯一标识符
Progress int // 进度百分比 (0-100)
Message string // 当前状态描述
Status string // 状态:running, completed, failed
StartTime time.Time // 开始时间
UpdateTime time.Time // 最后更新时间
Subscribers map[chan ProgressUpdate]bool // 订阅进度更新的通道
Done chan struct{} // 任务完成信号
// contains filtered or unexported fields
}
ProgressTracker 跟踪长时间运行任务的进度
func (*ProgressTracker) Complete ¶
func (t *ProgressTracker) Complete(message string)
Complete 标记任务完成
func (*ProgressTracker) Subscribe ¶
func (t *ProgressTracker) Subscribe() chan ProgressUpdate
Subscribe 订阅进度更新
func (*ProgressTracker) Unsubscribe ¶
func (t *ProgressTracker) Unsubscribe(subscriber chan ProgressUpdate)
Unsubscribe 取消订阅
func (*ProgressTracker) UpdateProgress ¶
func (t *ProgressTracker) UpdateProgress(progress int, message string)
UpdateProgress 更新任务进度
type ProgressUpdate ¶
type ProgressUpdate struct {
Progress int `json:"progress"` // 进度百分比 (0-100)
Message string `json:"message"` // 描述性消息
Status string `json:"status"` // 状态:running, completed, failed
}
ProgressUpdate 表示进度更新
type ScenarioIdeas ¶
type ScenarioIdeas struct {
Ideas []struct {
Title string `json:"title"`
Setting string `json:"setting"`
Premise string `json:"premise"`
Characters []struct {
Role string `json:"role"`
Description string `json:"description"`
Goals []string `json:"goals,omitempty"`
} `json:"characters"`
Conflicts []string `json:"conflicts"`
Branches []struct {
Description string `json:"description"`
Options []string `json:"options,omitempty"`
} `json:"branches,omitempty"`
} `json:"ideas"`
}
ScenarioIdeas 场景创意生成结果
type SceneAggregateData ¶
type SceneAggregateData struct {
// 基础信息
Scene *models.Scene `json:"scene"`
Characters []*models.Character `json:"characters"`
// 故事相关
Story *models.StoryData `json:"story"`
CurrentNode *models.StoryNode `json:"current_node"`
AvailableChoices []*models.StoryChoice `json:"available_choices"`
// 交互历史
RecentConversations []models.Conversation `json:"recent_conversations"`
// UI状态
UIState *SceneUIState `json:"ui_state"`
// 进度和统计
Progress *SceneProgress `json:"progress"`
// 元数据
LastUpdated time.Time `json:"last_updated"`
Version string `json:"version"`
}
SceneAggregateData 聚合的场景数据
type SceneAggregateService ¶
type SceneAggregateService struct {
SceneService *SceneService
CharacterService *CharacterService
ContextService *ContextService
StoryService *StoryService
ProgressService *ProgressService
// contains filtered or unexported fields
}
SceneAggregateService 聚合场景服务
func NewSceneAggregateService ¶
func NewSceneAggregateService( sceneService *SceneService, characterService *CharacterService, contextService *ContextService, storyService *StoryService, progressService *ProgressService) *SceneAggregateService
------------------------------------------------------------ NewSceneAggregateService 创建场景聚合服务
func (*SceneAggregateService) GetSceneAggregate ¶
func (s *SceneAggregateService) GetSceneAggregate(ctx context.Context, sceneID string, options *AggregateOptions) (*SceneAggregateData, error)
GetSceneAggregate 获取完整的场景聚合数据
func (*SceneAggregateService) InvalidateSceneCache ¶
func (s *SceneAggregateService) InvalidateSceneCache(sceneID string)
当相关数据更新时清除缓存
type SceneData ¶
type SceneData struct {
Scene models.Scene `json:"scene"`
Context models.SceneContext `json:"context"`
Settings models.SceneSettings `json:"settings"`
Characters []*models.Character `json:"characters"`
Items []*models.Item `json:"items"`
OriginalText string `json:"original_text,omitempty"`
OriginalSegments []models.OriginalSegment `json:"original_segments,omitempty"`
}
SceneData 包含场景及其相关数据
type SceneInfo ¶
type SceneInfo struct {
Name string `json:"name"`
Description string `json:"description"`
Atmosphere string `json:"atmosphere"`
Era string `json:"era"`
Themes []string `json:"themes"`
Items []string `json:"items"`
Importance string `json:"importance"`
}
SceneInfo 场景信息
type SceneProgress ¶
type SceneProgress struct {
StoryCompletion float64 `json:"story_completion"`
CharacterInteractions int `json:"character_interactions"`
UnlockedContent []string `json:"unlocked_content"`
Achievements []string `json:"achievements"`
}
SceneProgress 场景进度信息
type SceneService ¶
type SceneService struct {
BasePath string
FileCache *storage.FileStorage
ItemService *ItemService
// contains filtered or unexported fields
}
SceneService 处理场景相关的业务逻辑
func NewSceneService ¶
func NewSceneService(basePath string) *SceneService
--------------------------------------------------- NewSceneService 创建场景服务
func (*SceneService) AddCharacter ¶
func (s *SceneService) AddCharacter(sceneID string, character *models.Character) error
AddCharacter 添加新角色到场景
func (*SceneService) CreateScene ¶
func (s *SceneService) CreateScene(userID, title, description, content, source string) (*models.Scene, error)
线程安全的场景创建
func (*SceneService) CreateSceneFromText ¶
func (s *SceneService) CreateSceneFromText(userID, text, title string) (*models.Scene, error)
CreateSceneFromText 从文本创建新场景
func (*SceneService) CreateSceneWithCharacters ¶
func (s *SceneService) CreateSceneWithCharacters(scene *models.Scene, characters []models.Character) error
CreateSceneWithCharacters 创建带有角色的场景
func (*SceneService) DeleteCharacter ¶
func (s *SceneService) DeleteCharacter(sceneID, characterID string) error
DeleteCharacter 删除场景中的角色
func (*SceneService) DeleteScene ¶ added in v1.3.1
func (s *SceneService) DeleteScene(sceneID string) error
DeleteScene 删除场景及其所有相关数据
func (*SceneService) GetAllScenes ¶
func (s *SceneService) GetAllScenes() ([]models.Scene, error)
GetAllScenes 带缓存的获取所有场景列表
func (*SceneService) GetCharactersByScene ¶ added in v1.3.1
func (s *SceneService) GetCharactersByScene(sceneID string) ([]*models.Character, error)
GetCharactersByScene 获取指定场景的所有角色
func (*SceneService) LoadScene ¶
func (s *SceneService) LoadScene(sceneID string) (*SceneData, error)
LoadScene 带缓存的加载场景数据
func (*SceneService) LoadSceneNoCache ¶ added in v1.3.1
func (s *SceneService) LoadSceneNoCache(sceneID string) (*SceneData, error)
LoadSceneNoCache 强制从存储读取最新场景数据并刷新缓存
func (*SceneService) UpdateCharacter ¶
func (s *SceneService) UpdateCharacter(sceneID, characterID string, character *models.Character) error
UpdateCharacter 更新角色
func (*SceneService) UpdateContext ¶
func (s *SceneService) UpdateContext(sceneID string, context *models.SceneContext) error
UpdateContext 更新场景上下文
func (*SceneService) UpdateSettings ¶
func (s *SceneService) UpdateSettings(sceneID string, settings *models.SceneSettings) error
UpdateSettings 更新场景设置
type SceneServiceInterface ¶
type SceneUIState ¶
type SceneUIState struct {
SelectedCharacterIds []string `json:"selected_character_ids"`
CurrentTab string `json:"current_tab"`
StoryTreeExpanded bool `json:"story_tree_expanded"`
ChatViewMode string `json:"chat_view_mode"`
Notifications []UINotification `json:"notifications"`
}
SceneUIState UI状态信息
type ScriptService ¶ added in v1.4.0
type ScriptService struct {
BasePath string
FileStorage *storage.FileStorage
LLM *LLMService
}
func NewScriptService ¶ added in v1.4.0
func NewScriptService(basePath string, llm *LLMService) (*ScriptService, error)
func (*ScriptService) Command ¶ added in v1.4.0
func (s *ScriptService) Command(ctx context.Context, id string, req models.ScriptCommandRequest) (*models.ScriptCommandResponse, error)
func (*ScriptService) CreateProject ¶ added in v1.4.0
func (s *ScriptService) CreateProject(ctx context.Context, title, scriptType string, framework map[string]interface{}) (*models.ScriptProject, error)
func (*ScriptService) DeleteProject ¶ added in v1.4.0
func (s *ScriptService) DeleteProject(ctx context.Context, scriptID string) error
func (*ScriptService) Export ¶ added in v1.4.0
func (s *ScriptService) Export(ctx context.Context, id string, format string) (*models.ExportResult, error)
func (*ScriptService) ExportWithMeta ¶ added in v1.4.0
func (s *ScriptService) ExportWithMeta(ctx context.Context, id string, format string, includeMeta bool) (*models.ExportResult, error)
func (*ScriptService) GenerateInitial ¶ added in v1.4.0
func (s *ScriptService) GenerateInitial(ctx context.Context, id string, tracker *ProgressTracker) error
GenerateInitial 执行“先大纲后正文”的最小生成(用于 /api/scripts/:id/generate)。 说明:该方法设计为可被后台 goroutine 调用,进度通过 tracker 推送。
func (*ScriptService) GetProject ¶ added in v1.4.0
func (s *ScriptService) GetProject(ctx context.Context, id string) (*models.ScriptProject, error)
func (*ScriptService) ListDraftMetas ¶ added in v1.4.0
func (s *ScriptService) ListDraftMetas(ctx context.Context, scriptID string) ([]models.ScriptDraftMeta, error)
func (*ScriptService) ListProjects ¶ added in v1.4.0
func (s *ScriptService) ListProjects(ctx context.Context) ([]models.ScriptProject, error)
func (*ScriptService) LoadCharacters ¶ added in v1.4.0
func (*ScriptService) ManualEditDraft ¶ added in v1.4.0
func (s *ScriptService) ManualEditDraft(ctx context.Context, scriptID string, baseDraftID string, target models.ScriptCommandTarget, text string, userPrompt string) (*models.ScriptProject, string, error)
func (*ScriptService) Rewind ¶ added in v1.4.0
func (s *ScriptService) Rewind(ctx context.Context, id string, draftID string) (*models.ScriptProject, error)
func (*ScriptService) SaveCharacters ¶ added in v1.4.0
func (*ScriptService) UpdateChapterUserDraft ¶ added in v1.4.0
func (s *ScriptService) UpdateChapterUserDraft(ctx context.Context, scriptID string, chapterIndex int, userDraft string) (*models.ScriptChapterDraft, error)
func (*ScriptService) UpdateProjectBasics ¶ added in v1.4.0
func (s *ScriptService) UpdateProjectBasics(ctx context.Context, scriptID string, title string, typ string, framework map[string]interface{}) (*models.ScriptProject, error)
type StatsService ¶
type StatsService struct {
BasePath string // 统计数据存储路径
// contains filtered or unexported fields
}
StatsService 提供API使用统计功能
func NewStatsService ¶
func NewStatsService() *StatsService
------------------------------------ NewStatsService 创建统计服务实例
func (*StatsService) GetUsageStats ¶
func (s *StatsService) GetUsageStats() *UsageStats
GetUsageStats 获取API使用统计
func (*StatsService) RecordAPIRequest ¶
func (s *StatsService) RecordAPIRequest(tokens int) error
RecordAPIRequest 记录API请求
func (*StatsService) ResetStats ¶
func (s *StatsService) ResetStats() error
ResetStats 重置统计数据(仅用于测试或管理目的)
type StoryImpact ¶
type StoryImpact struct {
ProgressChange float64
ShouldCreateNode bool
ShouldUpdateCurrentNode bool
SignificanceLevel int // 1-10,交互的重要程度
EmotionalImpact float64 // 情绪影响强度
RelationshipChanges map[string]float64 // 角色关系变化
KeyEvents []string // 关键事件
UnlockTriggers []string // 解锁触发器
}
StoryImpact 故事影响分析结果
type StoryService ¶
type StoryService struct {
SceneService *SceneService
ContextService *ContextService
LLMService *LLMService
FileStorage *storage.FileStorage
ItemService *ItemService
CharacterService *CharacterService
BasePath string
// contains filtered or unexported fields
}
StoryService 管理故事进展和剧情分支
func NewStoryService ¶
func NewStoryService(llmService *LLMService) *StoryService
NewStoryService 创建故事服务
func (*StoryService) AdvanceStory ¶
func (s *StoryService) AdvanceStory(sceneID string, preferences *models.UserPreferences) (*models.StoryUpdate, error)
AdvanceStory 推进故事情节
func (*StoryService) CompleteObjective ¶
func (s *StoryService) CompleteObjective(sceneID, taskID, objectiveID string) error
CompleteObjective 完成任务目标
func (*StoryService) CreateStoryBranch ¶
func (s *StoryService) CreateStoryBranch(sceneID string, triggerType string, triggerID string, preferences *models.UserPreferences) (*models.StoryNode, error)
CreateStoryBranch 创建故事分支
func (*StoryService) DeleteStoryData ¶ added in v1.3.1
func (s *StoryService) DeleteStoryData(sceneID string) error
DeleteStoryData 删除指定场景的故事数据目录
func (*StoryService) EvaluateStoryProgress ¶
func (s *StoryService) EvaluateStoryProgress(sceneID string) (*models.StoryProgressStatus, error)
EvaluateStoryProgress 评估故事进展状态 🔧 修复后的版本
func (*StoryService) ExecuteBatchOperation ¶
func (s *StoryService) ExecuteBatchOperation(sceneID string, operation func(*models.StoryData) error) error
ExecuteBatchOperation 批量执行故事操作
func (*StoryService) ExploreLocation ¶
func (s *StoryService) ExploreLocation(sceneID, locationID string, preferences *models.UserPreferences) (*models.ExplorationResult, error)
ExploreLocation 探索地点,可能触发新的故事节点或发现物品
func (*StoryService) GetAvailableChoices ¶
func (s *StoryService) GetAvailableChoices(sceneID string) ([]models.StoryChoice, error)
GetAvailableChoices 获取当前可用的剧情选择
func (*StoryService) GetStoryData ¶
func (s *StoryService) GetStoryData(sceneID string, preferences *models.UserPreferences) (*models.StoryData, error)
GetStoryDataSafe 获取场景的故事数据,线程安全
func (*StoryService) GetStoryForScene ¶ added in v1.3.1
func (s *StoryService) GetStoryForScene(sceneID string) (*models.StoryData, error)
GetStoryForScene 获取指定场景的故事数据
func (*StoryService) GetStoryNode ¶ added in v1.3.1
func (s *StoryService) GetStoryNode(sceneID, nodeID string) (*models.StoryNode, error)
GetStoryNode 根据场景和节点ID获取对应的故事节点
func (*StoryService) InitializeStoryForScene ¶
func (s *StoryService) InitializeStoryForScene(sceneID string, preferences *models.UserPreferences) (*models.StoryData, error)
InitializeStoryForScene 初始化场景的故事线
func (*StoryService) InitializeStoryForSceneFull ¶ added in v1.3.1
func (s *StoryService) InitializeStoryForSceneFull(sceneID string, preferences *models.UserPreferences) (*models.StoryData, error)
InitializeStoryForSceneFull 强制使用完整分析流程(保留旧实现)
func (*StoryService) MakeChoice ¶
func (s *StoryService) MakeChoice(sceneID, nodeID, choiceID string, preferences *models.UserPreferences) (*models.StoryNode, error)
MakeChoice 处理玩家做出的故事选择
func (*StoryService) ProcessCharacterInteractionTriggers ¶
func (s *StoryService) ProcessCharacterInteractionTriggers(sceneID string, nodeID string, preferences *models.UserPreferences) ([]*models.CharacterInteraction, error)
ProcessCharacterInteractionTriggers 方法,处理故事节点中的角色互动触发器
func (*StoryService) RewindToNode ¶
func (s *StoryService) RewindToNode(sceneID, nodeID string) (*models.StoryData, error)
RewindToNode 回溯故事到指定节点
func (*StoryService) SaveStoryData ¶
func (s *StoryService) SaveStoryData(sceneID string, storyData *models.StoryData) error
SaveStoryData 保存故事数据到文件(公开方法)
func (*StoryService) UnlockLocation ¶
func (s *StoryService) UnlockLocation(sceneID, locationID string) error
UnlockLocation 解锁场景地点
func (*StoryService) UpdateNodeChoices ¶ added in v1.3.1
func (s *StoryService) UpdateNodeChoices(sceneID, nodeID string, choices []models.StoryChoice) error
UpdateNodeChoices 用新的候选选项覆盖指定节点的可选项
type StoryServiceMetrics ¶
type StoryServiceMetrics struct {
// contains filtered or unexported fields
}
StoryServiceMetrics 故事服务性能指标
func (*StoryServiceMetrics) GetMetrics ¶
func (m *StoryServiceMetrics) GetMetrics() map[string]interface{}
GetMetrics 获取性能指标
func (*StoryServiceMetrics) RecordChoice ¶
func (m *StoryServiceMetrics) RecordChoice(duration time.Duration)
RecordChoice 记录选择操作
func (*StoryServiceMetrics) ResetMetrics ¶
func (m *StoryServiceMetrics) ResetMetrics()
ResetMetrics 重置性能指标
type StoryUpdate ¶
type StoryUpdate struct {
NewNodes []*models.StoryNode `json:"new_nodes,omitempty"`
UpdatedNodes []*models.StoryNode `json:"updated_nodes,omitempty"`
ProgressChange float64 `json:"progress_change"`
UnlockedContent []string `json:"unlocked_content,omitempty"`
UpdatedTasks []*models.Task `json:"updated_tasks,omitempty"` // 添加任务更新
CompletedTasks []*models.Task `json:"completed_tasks,omitempty"` // 添加已完成任务
TaskChanges []TaskChange `json:"task_changes,omitempty"`
}
StoryUpdate 故事更新
type TabUpdate ¶
type TabUpdate struct {
TabID string `json:"tab_id"`
BadgeCount int `json:"badge_count"`
IsActive bool `json:"is_active"`
Title string `json:"title,omitempty"`
}
TabUpdate 标签更新
type TaskChange ¶
type TaskChange struct {
TaskID string `json:"task_id"`
Type string `json:"type"` // "completed", "updated", "new"
OldStatus bool `json:"old_status"` // 原状态
NewStatus bool `json:"new_status"` // 新状态
ChangedAt time.Time `json:"changed_at"`
Reason string `json:"reason"` // 变化原因
}
TaskChange 任务变化记录
type TaskCompletionInfo ¶
TaskCompletionInfo 任务完成信息
type UIAnimation ¶
type UIAnimation struct {
Target string `json:"target"` // CSS选择器或元素ID
Type string `json:"type"` // fade, slide, bounce, etc.
Duration int `json:"duration"` // 毫秒
Params map[string]interface{} `json:"params"`
}
UIAnimation UI动画
type UINotification ¶
type UINotification struct {
ID string `json:"id"`
Type string `json:"type"` // info, warning, error, success
Message string `json:"message"`
Actions []string `json:"actions"`
Timestamp time.Time `json:"timestamp"`
}
UINotification UI通知
type UIUpdateCommands ¶
type UIUpdateCommands struct {
ScrollToBottom bool `json:"scroll_to_bottom"`
HighlightCharacters []string `json:"highlight_characters"`
UpdateChatBadges map[string]int `json:"update_chat_badges"`
TriggerAnimations []UIAnimation `json:"trigger_animations"`
UpdateTabs []TabUpdate `json:"update_tabs"`
}
UIUpdateCommands UI更新指令
type UsageStats ¶
type UsageStats struct {
TodayRequests int `json:"today_requests"`
MonthlyTokens int `json:"monthly_tokens"`
DailyStats map[string]int `json:"daily_stats"`
MonthlyStats map[string]int `json:"monthly_stats"`
LastUpdated time.Time `json:"last_updated"`
}
UsageStats 表示API使用统计
type UserService ¶
type UserService struct {
BasePath string
FileStorage *storage.FileStorage
// contains filtered or unexported fields
}
UserService 处理用户相关的业务逻辑
func NewUserService ¶
func NewUserService() *UserService
--------------------------------- NewUserService 创建用户服务
func (*UserService) AddUserItem ¶
func (s *UserService) AddUserItem(userID string, item models.UserItem) error
AddUserItem 为用户添加自定义道具(线程安全)
func (*UserService) AddUserSkill ¶
func (s *UserService) AddUserSkill(userID string, skill models.UserSkill) error
---技能管理方法--- AddUserSkill 为用户添加自定义技能
func (*UserService) CreateUser ¶
CreateUser 创建新用户
func (*UserService) DeleteUserItem ¶
func (s *UserService) DeleteUserItem(userID string, itemID string) error
DeleteUserItem 删除用户自定义道具
func (*UserService) DeleteUserSkill ¶
func (s *UserService) DeleteUserSkill(userID string, skillID string) error
DeleteUserSkill 删除用户自定义技能
func (*UserService) EnsureUserExists ¶ added in v1.3.1
func (s *UserService) EnsureUserExists(userID string) error
EnsureUserExists 确保给定用户存在,如不存在则创建一个带默认偏好的用户
func (*UserService) GetUser ¶
func (s *UserService) GetUser(userID string) (*models.User, error)
GetUser 获取用户信息(带缓从)
func (*UserService) GetUserItem ¶
GetUserItem 获取用户特定自定义道具
func (*UserService) GetUserItems ¶
func (s *UserService) GetUserItems(userID string) ([]models.UserItem, error)
GetUserItems 获取用户所有自定义道具
func (*UserService) GetUserPreferences ¶
func (s *UserService) GetUserPreferences(userID string) (models.UserPreferences, error)
GetUserPreferences 获取用户偏好设置
func (*UserService) GetUserSkill ¶
GetUserSkill 获取用户特定自定义技能
func (*UserService) GetUserSkills ¶
func (s *UserService) GetUserSkills(userID string) ([]models.UserSkill, error)
GetUserSkills 获取用户所有自定义技能
func (*UserService) SaveUser ¶
func (s *UserService) SaveUser(user *models.User) error
SaveUser 保存用户信息(线程安全)
func (*UserService) UpdateUserItem ¶
func (s *UserService) UpdateUserItem(userID string, itemID string, updatedItem models.UserItem) error
UpdateUserItem 更新用户自定义道具
func (*UserService) UpdateUserPreferences ¶
func (s *UserService) UpdateUserPreferences(userID string, preferences models.UserPreferences) error
UpdateUserPreferences 更新用户偏好设置
func (*UserService) UpdateUserSkill ¶
func (s *UserService) UpdateUserSkill(userID string, skillID string, updatedSkill models.UserSkill) error
UpdateUserSkill 更新用户自定义技能
Source Files
¶
- Progress_service.go
- analyzer_service.go
- character_service.go
- config_service.go
- context_service.go
- export_service.go
- interaction_aggregate_service.go
- item_service.go
- llm_service.go
- lock_manager.go
- scene_aggregate_service.go
- scene_service.go
- script_service.go
- stats_service.go
- story_service.go
- story_service_metrics.go
- structs.go
- user_service.go