feat: adapt preloaded skills to smart-reasoning agent

This commit is contained in:
nullkey
2026-02-04 03:40:09 +08:00
committed by lyingbug
parent 33f7e7da66
commit 3f21345546
32 changed files with 2194 additions and 719 deletions
+17 -6
View File
@@ -202,16 +202,27 @@ func formatSkillsMetadata(skillsMetadata []*skills.SkillMetadata) string {
}
var builder strings.Builder
builder.WriteString("\n### Available Skills\n\n")
builder.WriteString("The following skills are available. When a user request matches a skill's description, ")
builder.WriteString("use the `read_skill` tool to load its full instructions before proceeding.\n\n")
builder.WriteString("\n### Available Skills (IMPORTANT - READ CAREFULLY)\n\n")
builder.WriteString("**You MUST actively consider using these skills for EVERY user request.**\n\n")
builder.WriteString("#### Skill Matching Protocol (MANDATORY)\n\n")
builder.WriteString("Before responding to ANY user query, follow this checklist:\n\n")
builder.WriteString("1. **SCAN**: Read each skill's description and trigger conditions below\n")
builder.WriteString("2. **MATCH**: Check if the user's intent matches ANY skill's triggers (keywords, scenarios, or task types)\n")
builder.WriteString("3. **LOAD**: If a match is found, call `read_skill(skill_name=\"...\")` BEFORE generating your response\n")
builder.WriteString("4. **APPLY**: Follow the skill's instructions to provide a higher-quality, structured response\n\n")
builder.WriteString("**⚠️ CRITICAL**: Skill usage is MANDATORY when applicable. Do NOT skip skills to save time or tokens.\n\n")
builder.WriteString("#### Available Skills\n\n")
for i, skill := range skillsMetadata {
builder.WriteString(fmt.Sprintf("%d. **%s**: %s\n", i+1, skill.Name, skill.Description))
builder.WriteString(fmt.Sprintf("%d. **%s**\n", i+1, skill.Name))
builder.WriteString(fmt.Sprintf(" %s\n\n", skill.Description))
}
builder.WriteString("\nUse `read_skill` with the skill name to load detailed instructions when needed.\n")
builder.WriteString("Use `execute_skill_script` to run utility scripts bundled with a skill.\n")
builder.WriteString("#### Tool Reference\n\n")
builder.WriteString("- `read_skill(skill_name)`: Load full skill instructions (MUST call before using a skill)\n")
builder.WriteString("- `execute_skill_script(skill_name, script_path, args, input)`: Run utility scripts bundled with a skill\n")
return builder.String()
}
+4 -3
View File
@@ -236,7 +236,7 @@ func (l *Loader) LoadSkillFile(skillName, relativePath string) (*SkillFile, erro
return &SkillFile{
Name: relativePath,
Path: fullPath,
Path: absFilePath, // Use absolute path for sandbox execution
Content: string(content),
IsScript: IsScript(relativePath),
}, nil
@@ -287,7 +287,7 @@ func (l *Loader) GetSkillByName(name string) (*Skill, bool) {
return skill, ok
}
// GetSkillBasePath returns the base path for a skill
// GetSkillBasePath returns the base path for a skill (always absolute)
func (l *Loader) GetSkillBasePath(skillName string) (string, error) {
skill, ok := l.discoveredSkills[skillName]
if !ok {
@@ -297,7 +297,8 @@ func (l *Loader) GetSkillBasePath(skillName string) (string, error) {
return "", fmt.Errorf("skill not found: %s", skillName)
}
}
return skill.BasePath, nil
// Return absolute path for consistent sandbox execution
return filepath.Abs(skill.BasePath)
}
// Reload clears the cache and rediscovers all skills
+2 -1
View File
@@ -172,7 +172,7 @@ func (m *Manager) ListSkillFiles(ctx context.Context, skillName string) ([]strin
}
// ExecuteScript executes a script from a skill in the sandbox
func (m *Manager) ExecuteScript(ctx context.Context, skillName, scriptPath string, args []string) (*sandbox.ExecuteResult, error) {
func (m *Manager) ExecuteScript(ctx context.Context, skillName, scriptPath string, args []string, stdin string) (*sandbox.ExecuteResult, error) {
if !m.enabled {
return nil, fmt.Errorf("skills are not enabled")
}
@@ -207,6 +207,7 @@ func (m *Manager) ExecuteScript(ctx context.Context, skillName, scriptPath strin
Script: file.Path,
Args: args,
WorkDir: basePath,
Stdin: stdin,
}
// Execute in sandbox
+2 -2
View File
@@ -23,8 +23,8 @@ const (
// Reserved words that cannot be used in skill names
var reservedWords = []string{"anthropic", "claude"}
// namePattern validates skill names: lowercase letters, numbers, and hyphens only
var namePattern = regexp.MustCompile(`^[a-z0-9-]+$`)
// namePattern validates skill names: unicode letters, numbers only
var namePattern = regexp.MustCompile(`^[\p{L}\p{N}-]+$`)
// xmlTagPattern detects XML tags in content
var xmlTagPattern = regexp.MustCompile(`<[^>]+>`)
+4 -3
View File
@@ -44,6 +44,7 @@ type ExecuteSkillScriptInput struct {
SkillName string `json:"skill_name" jsonschema:"Name of the skill containing the script"`
ScriptPath string `json:"script_path" jsonschema:"Relative path to the script within the skill directory (e.g. scripts/analyze.py)"`
Args []string `json:"args,omitempty" jsonschema:"Optional command-line arguments to pass to the script"`
Input string `json:"input,omitempty" jsonschema:"Optional input data to pass to the script via stdin"`
}
// ExecuteSkillScriptTool allows the agent to execute skill scripts in a sandbox
@@ -98,10 +99,10 @@ func (t *ExecuteSkillScriptTool) Execute(ctx context.Context, args json.RawMessa
}
// Execute the script in sandbox
logger.Infof(ctx, "[Tool][ExecuteSkillScript] Executing script: %s/%s with args: %v",
input.SkillName, input.ScriptPath, input.Args)
logger.Infof(ctx, "[Tool][ExecuteSkillScript] Executing script: %s/%s with args: %v, input length: %d",
input.SkillName, input.ScriptPath, input.Args, len(input.Input))
result, err := t.skillManager.ExecuteScript(ctx, input.SkillName, input.ScriptPath, input.Args)
result, err := t.skillManager.ExecuteScript(ctx, input.SkillName, input.ScriptPath, input.Args, input.Input)
if err != nil {
logger.Errorf(ctx, "[Tool][ExecuteSkillScript] Script execution failed: %v", err)
return &types.ToolResult{
+63
View File
@@ -843,6 +843,66 @@ func (s *sessionService) resolveKnowledgeBasesFromAgent(
}
}
// configureSkillsFromAgent configures skills settings in AgentConfig based on CustomAgentConfig
// Returns the skill directories and allowed skills based on the selection mode:
// - "all": uses all preloaded skills
// - "selected": uses the explicitly selected skills
// - "none" or "": skills are disabled
func (s *sessionService) configureSkillsFromAgent(
ctx context.Context,
agentConfig *types.AgentConfig,
customAgent *types.CustomAgent,
) {
if customAgent == nil {
return
}
switch customAgent.Config.SkillsSelectionMode {
case "all":
// Enable all preloaded skills
agentConfig.SkillsEnabled = true
agentConfig.SkillDirs = []string{DefaultPreloadedSkillsDir}
agentConfig.AllowedSkills = nil // Empty means all skills allowed
logger.Infof(ctx, "SkillsSelectionMode=all: enabled all preloaded skills")
case "selected":
// Enable only selected skills
if len(customAgent.Config.SelectedSkills) > 0 {
agentConfig.SkillsEnabled = true
agentConfig.SkillDirs = []string{DefaultPreloadedSkillsDir}
agentConfig.AllowedSkills = customAgent.Config.SelectedSkills
logger.Infof(ctx, "SkillsSelectionMode=selected: enabled %d selected skills: %v",
len(customAgent.Config.SelectedSkills), customAgent.Config.SelectedSkills)
} else {
agentConfig.SkillsEnabled = false
logger.Infof(ctx, "SkillsSelectionMode=selected but no skills selected: skills disabled")
}
case "none", "":
// Skills disabled
agentConfig.SkillsEnabled = false
logger.Infof(ctx, "SkillsSelectionMode=%s: skills disabled", customAgent.Config.SkillsSelectionMode)
default:
// Unknown mode, disable skills
agentConfig.SkillsEnabled = false
logger.Warnf(ctx, "Unknown SkillsSelectionMode=%s: skills disabled", customAgent.Config.SkillsSelectionMode)
}
// Configure sandbox mode for skill script execution
if agentConfig.SkillsEnabled {
// Set sandbox mode (default to "docker" when skills are enabled)
agentConfig.SandboxMode = customAgent.Config.SandboxMode
if agentConfig.SandboxMode == "" {
agentConfig.SandboxMode = "docker" // Default to docker for security
}
// Set sandbox timeout (default to 60 seconds)
agentConfig.SandboxTimeout = customAgent.Config.SandboxTimeout
if agentConfig.SandboxTimeout == 0 {
agentConfig.SandboxTimeout = 60
}
logger.Infof(ctx, "Sandbox configured: mode=%s, timeout=%ds",
agentConfig.SandboxMode, agentConfig.SandboxTimeout)
}
}
// buildSearchTargets computes the unified search targets from knowledgeBaseIDs and knowledgeIDs
// This is called once at the request entry point to avoid repeated queries later in the pipeline
// Logic:
@@ -1130,6 +1190,9 @@ func (s *sessionService) AgentQA(
RetrieveKBOnlyWhenMentioned: customAgent.Config.RetrieveKBOnlyWhenMentioned,
}
// Configure skills based on CustomAgentConfig
s.configureSkillsFromAgent(ctx, agentConfig, customAgent)
// Resolve knowledge bases: request-level @ mentions take priority over agent config
// If RetrieveKBOnlyWhenMentioned is enabled and no @ mentions, don't use KB at all
hasExplicitMention := len(knowledgeBaseIDs) > 0 || len(knowledgeIDs) > 0
@@ -0,0 +1,135 @@
package service
import (
"context"
"fmt"
"os"
"path/filepath"
"sync"
"github.com/Tencent/WeKnora/internal/agent/skills"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// DefaultPreloadedSkillsDir is the default directory for preloaded skills
const DefaultPreloadedSkillsDir = "skills/preloaded"
// skillService implements SkillService interface
type skillService struct {
loader *skills.Loader
preloadedDir string
mu sync.RWMutex
initialized bool
}
// NewSkillService creates a new skill service
func NewSkillService() interfaces.SkillService {
// Determine the preloaded skills directory
preloadedDir := getPreloadedSkillsDir()
return &skillService{
preloadedDir: preloadedDir,
initialized: false,
}
}
// getPreloadedSkillsDir returns the path to the preloaded skills directory
func getPreloadedSkillsDir() string {
// Check if SKILLS_DIR environment variable is set
if dir := os.Getenv("WEKNORA_SKILLS_DIR"); dir != "" {
return dir
}
// Try to find the skills directory relative to the executable
execPath, err := os.Executable()
if err == nil {
execDir := filepath.Dir(execPath)
skillsDir := filepath.Join(execDir, DefaultPreloadedSkillsDir)
if _, err := os.Stat(skillsDir); err == nil {
return skillsDir
}
}
// Try current working directory
cwd, err := os.Getwd()
if err == nil {
skillsDir := filepath.Join(cwd, DefaultPreloadedSkillsDir)
if _, err := os.Stat(skillsDir); err == nil {
return skillsDir
}
}
// Default to relative path (will be created if needed)
return DefaultPreloadedSkillsDir
}
// ensureInitialized initializes the loader if not already done
func (s *skillService) ensureInitialized(ctx context.Context) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.initialized {
return nil
}
// Check if preloaded directory exists
if _, err := os.Stat(s.preloadedDir); os.IsNotExist(err) {
logger.Warnf(ctx, "Preloaded skills directory does not exist: %s", s.preloadedDir)
// Create the directory to avoid repeated warnings
if err := os.MkdirAll(s.preloadedDir, 0755); err != nil {
logger.Warnf(ctx, "Failed to create preloaded skills directory: %v", err)
}
}
// Create loader with preloaded directory
s.loader = skills.NewLoader([]string{s.preloadedDir})
s.initialized = true
logger.Infof(ctx, "Skill service initialized with preloaded directory: %s", s.preloadedDir)
return nil
}
// ListPreloadedSkills returns metadata for all preloaded skills
func (s *skillService) ListPreloadedSkills(ctx context.Context) ([]*skills.SkillMetadata, error) {
if err := s.ensureInitialized(ctx); err != nil {
return nil, fmt.Errorf("failed to initialize skill service: %w", err)
}
s.mu.RLock()
defer s.mu.RUnlock()
metadata, err := s.loader.DiscoverSkills()
if err != nil {
logger.Errorf(ctx, "Failed to discover preloaded skills: %v", err)
return nil, fmt.Errorf("failed to discover skills: %w", err)
}
logger.Infof(ctx, "Discovered %d preloaded skills", len(metadata))
return metadata, nil
}
// GetSkillByName retrieves a skill by its name
func (s *skillService) GetSkillByName(ctx context.Context, name string) (*skills.Skill, error) {
if err := s.ensureInitialized(ctx); err != nil {
return nil, fmt.Errorf("failed to initialize skill service: %w", err)
}
s.mu.RLock()
defer s.mu.RUnlock()
skill, err := s.loader.LoadSkillInstructions(name)
if err != nil {
logger.Errorf(ctx, "Failed to load skill %s: %v", name, err)
return nil, fmt.Errorf("failed to load skill: %w", err)
}
return skill, nil
}
// GetPreloadedDir returns the configured preloaded skills directory
func (s *skillService) GetPreloadedDir() string {
return s.preloadedDir
}
+2
View File
@@ -197,6 +197,8 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(handler.NewMCPServiceHandler))
must(container.Provide(handler.NewWebSearchHandler))
must(container.Provide(handler.NewCustomAgentHandler))
must(container.Provide(service.NewSkillService))
must(container.Provide(handler.NewSkillHandler))
logger.Debugf(ctx, "[Container] HTTP handlers registered")
// Router configuration
+64
View File
@@ -0,0 +1,64 @@
package handler
import (
"net/http"
"github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/gin-gonic/gin"
)
// SkillHandler handles skill-related HTTP requests
type SkillHandler struct {
skillService interfaces.SkillService
}
// NewSkillHandler creates a new skill handler
func NewSkillHandler(skillService interfaces.SkillService) *SkillHandler {
return &SkillHandler{
skillService: skillService,
}
}
// SkillInfoResponse represents the skill info returned to frontend
type SkillInfoResponse struct {
Name string `json:"name"`
Description string `json:"description"`
}
// ListSkills godoc
// @Summary 获取预装Skills列表
// @Description 获取所有预装的Agent Skills元数据
// @Tags Skills
// @Accept json
// @Produce json
// @Success 200 {object} map[string]interface{} "Skills列表"
// @Failure 500 {object} errors.AppError "服务器错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /skills [get]
func (h *SkillHandler) ListSkills(c *gin.Context) {
ctx := c.Request.Context()
skillsMetadata, err := h.skillService.ListPreloadedSkills(ctx)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError("Failed to list skills: " + err.Error()))
return
}
// Convert to response format
var response []SkillInfoResponse
for _, meta := range skillsMetadata {
response = append(response, SkillInfoResponse{
Name: meta.Name,
Description: meta.Description,
})
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": response,
})
}
+11
View File
@@ -48,6 +48,7 @@ type RouterParams struct {
FAQHandler *handler.FAQHandler
TagHandler *handler.TagHandler
CustomAgentHandler *handler.CustomAgentHandler
SkillHandler *handler.SkillHandler
}
// NewRouter 创建新的路由
@@ -112,6 +113,7 @@ func NewRouter(params RouterParams) *gin.Engine {
RegisterMCPServiceRoutes(v1, params.MCPServiceHandler)
RegisterWebSearchRoutes(v1, params.WebSearchHandler)
RegisterCustomAgentRoutes(v1, params.CustomAgentHandler)
RegisterSkillRoutes(v1, params.SkillHandler)
}
return r
@@ -439,3 +441,12 @@ func RegisterCustomAgentRoutes(r *gin.RouterGroup, agentHandler *handler.CustomA
agents.POST("/:id/copy", agentHandler.CopyAgent)
}
}
// RegisterSkillRoutes registers skill routes
func RegisterSkillRoutes(r *gin.RouterGroup, skillHandler *handler.SkillHandler) {
skills := r.Group("/skills")
{
// List all preloaded skills
skills.GET("", skillHandler.ListSkills)
}
}
+11 -1
View File
@@ -94,6 +94,16 @@ type CustomAgentConfig struct {
// Selected MCP service IDs (only used when MCPSelectionMode is "selected")
MCPServices []string `yaml:"mcp_services" json:"mcp_services"`
// ===== Skills Settings (only for smart-reasoning mode) =====
// Skills selection mode: "all" = all preloaded skills, "selected" = specific skills, "none" = no skills
SkillsSelectionMode string `yaml:"skills_selection_mode" json:"skills_selection_mode"`
// Selected skill names (only used when SkillsSelectionMode is "selected")
SelectedSkills []string `yaml:"selected_skills" json:"selected_skills"`
// Sandbox mode for skill script execution: "docker", "local", "disabled" (default: "docker" when skills enabled)
SandboxMode string `yaml:"sandbox_mode" json:"sandbox_mode"`
// Script execution timeout in seconds (default: 60)
SandboxTimeout int `yaml:"sandbox_timeout" json:"sandbox_timeout"`
// ===== Knowledge Base Settings =====
// Knowledge base selection mode: "all" = all KBs, "selected" = specific KBs, "none" = no KB
KBSelectionMode string `yaml:"kb_selection_mode" json:"kb_selection_mode"`
@@ -322,7 +332,7 @@ func GetBuiltinDataAnalystAgent(tenantID uint64) *CustomAgent {
IsBuiltin: true,
TenantID: tenantID,
Config: CustomAgentConfig{
AgentMode: AgentModeSmartReasoning,
AgentMode: AgentModeSmartReasoning,
SystemPrompt: `### Role
You are WeKnora Data Analyst, an intelligent data analysis assistant powered by DuckDB. You specialize in analyzing structured data from CSV and Excel files using SQL queries.
+16
View File
@@ -0,0 +1,16 @@
package interfaces
import (
"context"
"github.com/Tencent/WeKnora/internal/agent/skills"
)
// SkillService defines the interface for skill business logic
type SkillService interface {
// ListPreloadedSkills returns metadata for all preloaded skills
ListPreloadedSkills(ctx context.Context) ([]*skills.SkillMetadata, error)
// GetSkillByName retrieves a skill by its name
GetSkillByName(ctx context.Context, name string) (*skills.Skill, error)
}