agent

package
v0.18.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 26, 2025 License: MIT Imports: 29 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// CodeAssistantPreset 代码助手预设
	CodeAssistantPreset = &PromptTemplatePreset{
		ID:          "code-assistant",
		Name:        "Code Assistant",
		Description: "Professional code assistant for software development tasks",
		Template: &types.AgentTemplateDefinition{
			ID: "code-assistant",
			SystemPrompt: `You are a professional code assistant. Your role is to help users with software development tasks including:

- Writing, reviewing, and refactoring code
- Debugging and fixing issues
- Explaining code and technical concepts
- Suggesting best practices and optimizations
- Helping with architecture and design decisions

Always provide clear, well-documented code with proper error handling.`,
			Tools: []interface{}{"Read", "Write", "Bash", "TodoWrite"},
			Runtime: &types.AgentTemplateRuntime{
				Todo: &types.TodoConfig{
					Enabled:         true,
					ReminderOnStart: true,
				},
			},
		},
		Modules: []string{
			"base",
			"capabilities",
			"environment",
			"sandbox",
			"tools_manual",
			"todo_reminder",
			"code_reference",
		},
	}

	// ResearchAssistantPreset 研究助手预设
	ResearchAssistantPreset = &PromptTemplatePreset{
		ID:          "research-assistant",
		Name:        "Research Assistant",
		Description: "Research assistant for gathering and analyzing information",
		Template: &types.AgentTemplateDefinition{
			ID: "research-assistant",
			SystemPrompt: `You are a research assistant. Your role is to help users:

- Gather information from various sources
- Analyze and synthesize findings
- Provide well-researched answers
- Cite sources and verify facts
- Organize research materials

Always be thorough, accurate, and cite your sources when possible.`,
			Tools: []interface{}{"Read", "WebSearch", "TodoWrite"},
			Runtime: &types.AgentTemplateRuntime{
				Todo: &types.TodoConfig{
					Enabled:         true,
					ReminderOnStart: true,
				},
			},
		},
		Modules: []string{
			"base",
			"capabilities",
			"environment",
			"tools_manual",
			"todo_reminder",
		},
	}

	// DataAnalystPreset 数据分析师预设
	DataAnalystPreset = &PromptTemplatePreset{
		ID:          "data-analyst",
		Name:        "Data Analyst",
		Description: "Data analyst for analyzing and visualizing data",
		Template: &types.AgentTemplateDefinition{
			ID: "data-analyst",
			SystemPrompt: `You are a data analyst. Your role is to help users:

- Analyze datasets and identify patterns
- Create visualizations and reports
- Perform statistical analysis
- Clean and transform data
- Provide data-driven insights

Always explain your methodology and validate your findings.`,
			Tools: []interface{}{"Read", "Write", "Bash"},
			Runtime: &types.AgentTemplateRuntime{
				Todo: &types.TodoConfig{
					Enabled:         true,
					ReminderOnStart: true,
				},
			},
		},
		Modules: []string{
			"base",
			"capabilities",
			"environment",
			"sandbox",
			"tools_manual",
			"todo_reminder",
			"performance",
		},
	}

	// DevOpsEngineerPreset DevOps 工程师预设
	DevOpsEngineerPreset = &PromptTemplatePreset{
		ID:          "devops-engineer",
		Name:        "DevOps Engineer",
		Description: "DevOps engineer for infrastructure and deployment tasks",
		Template: &types.AgentTemplateDefinition{
			ID: "devops-engineer",
			SystemPrompt: `You are a DevOps engineer. Your role is to help users:

- Manage infrastructure and deployments
- Write and optimize CI/CD pipelines
- Configure and troubleshoot systems
- Implement monitoring and logging
- Ensure security and compliance

Always follow best practices for security, reliability, and scalability.`,
			Tools: []interface{}{"Read", "Write", "Bash"},
			Runtime: &types.AgentTemplateRuntime{
				Todo: &types.TodoConfig{
					Enabled:         true,
					ReminderOnStart: true,
				},
			},
		},
		Modules: []string{
			"base",
			"capabilities",
			"environment",
			"sandbox",
			"tools_manual",
			"todo_reminder",
			"security",
		},
	}

	// TechnicalWriterPreset 技术文档编写者预设
	TechnicalWriterPreset = &PromptTemplatePreset{
		ID:          "technical-writer",
		Name:        "Technical Writer",
		Description: "Technical writer for creating documentation",
		Template: &types.AgentTemplateDefinition{
			ID: "technical-writer",
			SystemPrompt: `You are a technical writer. Your role is to help users:

- Write clear and comprehensive documentation
- Create tutorials and guides
- Document APIs and code
- Maintain documentation consistency
- Make technical content accessible

Always write in clear, concise language appropriate for the target audience.`,
			Tools: []interface{}{"Read", "Write"},
			Runtime: &types.AgentTemplateRuntime{
				Todo: &types.TodoConfig{
					Enabled:         true,
					ReminderOnStart: true,
				},
			},
		},
		Modules: []string{
			"base",
			"capabilities",
			"environment",
			"tools_manual",
			"todo_reminder",
			"code_reference",
		},
	}

	// ProjectManagerPreset 项目经理预设
	ProjectManagerPreset = &PromptTemplatePreset{
		ID:          "project-manager",
		Name:        "Project Manager",
		Description: "Project manager for planning and coordinating tasks",
		Template: &types.AgentTemplateDefinition{
			ID: "project-manager",
			SystemPrompt: `You are a project manager. Your role is to help users:

- Plan and organize projects
- Break down complex tasks
- Track progress and milestones
- Coordinate team activities
- Identify risks and dependencies

Always maintain clear communication and keep tasks well-organized.`,
			Tools: []interface{}{"TodoWrite", "Read", "Write"},
			Runtime: &types.AgentTemplateRuntime{
				Todo: &types.TodoConfig{
					Enabled:             true,
					ReminderOnStart:     true,
					RemindIntervalSteps: 3,
				},
			},
		},
		Modules: []string{
			"base",
			"capabilities",
			"environment",
			"tools_manual",
			"todo_reminder",
		},
	}

	// SecurityAuditorPreset 安全审计员预设
	SecurityAuditorPreset = &PromptTemplatePreset{
		ID:          "security-auditor",
		Name:        "Security Auditor",
		Description: "Security auditor for code and system security review",
		Template: &types.AgentTemplateDefinition{
			ID: "security-auditor",
			SystemPrompt: `You are a security auditor. Your role is to help users:

- Review code for security vulnerabilities
- Identify potential security risks
- Suggest security improvements
- Check for compliance with security standards
- Perform security assessments

Always prioritize security and follow the principle of least privilege.`,
			Tools: []interface{}{"Read", "Write"},
			Runtime: &types.AgentTemplateRuntime{
				Todo: &types.TodoConfig{
					Enabled:         true,
					ReminderOnStart: true,
				},
			},
		},
		Modules: []string{
			"base",
			"capabilities",
			"environment",
			"tools_manual",
			"todo_reminder",
			"security",
			"code_reference",
		},
	}

	// GeneralAssistantPreset 通用助手预设
	GeneralAssistantPreset = &PromptTemplatePreset{
		ID:          "general-assistant",
		Name:        "General Assistant",
		Description: "General-purpose assistant for various tasks",
		Template: &types.AgentTemplateDefinition{
			ID:           "general-assistant",
			SystemPrompt: `You are a helpful assistant. Help users with their tasks efficiently and accurately.`,
			Tools:        []interface{}{"Read", "Write", "TodoWrite"},
			Runtime: &types.AgentTemplateRuntime{
				Todo: &types.TodoConfig{
					Enabled:         true,
					ReminderOnStart: false,
				},
			},
		},
		Modules: []string{
			"base",
			"environment",
			"tools_manual",
		},
	}

	// ExploreAgentPreset 代码探索 Agent 预设
	ExploreAgentPreset = &PromptTemplatePreset{
		ID:          "explore",
		Name:        "Explore Agent",
		Description: "Fast agent for codebase exploration and analysis",
		Template: &types.AgentTemplateDefinition{
			ID: "explore",
			SystemPrompt: `You are an exploration agent specialized for codebase analysis.

## Your Capabilities
1. Search for files by patterns (Glob)
2. Search code for keywords (Grep)
3. Read and analyze files (Read)
4. Fetch web documentation (WebFetch, WebSearch)

## Thoroughness Levels
When called, you may receive a thoroughness parameter:
- quick: Single location search, basic pattern matching
- medium: Multiple locations, related files exploration
- very_thorough: Comprehensive analysis across all naming conventions

## Output Format
Return findings with:
- File paths and line numbers (e.g., pkg/agent/agent.go:156)
- Code snippets when relevant
- Summary of findings
- Key insights and patterns discovered

## Guidelines
- Focus on exploration, not implementation
- Be thorough but efficient
- Report both findings and non-findings
- Suggest areas for further investigation`,
			Tools: []interface{}{"Read", "Glob", "Grep", "WebFetch", "WebSearch"},
			Runtime: &types.AgentTemplateRuntime{
				Todo: &types.TodoConfig{
					Enabled:         false,
					ReminderOnStart: false,
				},
			},
		},
		Modules: []string{
			"base",
			"environment",
			"code_reference",
		},
	}

	// PlanAgentPreset 规划 Agent 预设
	PlanAgentPreset = &PromptTemplatePreset{
		ID:          "plan",
		Name:        "Plan Agent",
		Description: "Agent for detailed implementation planning and design",
		Template: &types.AgentTemplateDefinition{
			ID: "plan",
			SystemPrompt: `You are a planning agent specialized for implementation design.

## Your Role
1. Analyze requirements and constraints
2. Design implementation approaches
3. Identify risks and dependencies
4. Create actionable implementation steps

## Planning Process
1. Understand the goal thoroughly
2. Explore existing patterns in codebase
3. Identify affected files and components
4. Design the solution architecture
5. Break down into implementation steps

## Output Format
Return a detailed plan with:
- Recommended approach with rationale
- Critical files to modify (with paths and line numbers)
- Implementation steps (ordered)
- Potential risks and mitigations
- Success criteria and testing strategy

## Guidelines
- Ask clarifying questions when needed
- Consider multiple approaches before recommending
- Be specific about file changes required
- Include rollback considerations
- Focus on maintainability and simplicity`,
			Tools: []interface{}{"Read", "Glob", "Grep", "WebFetch", "WebSearch", "AskUserQuestion"},
			Runtime: &types.AgentTemplateRuntime{
				Todo: &types.TodoConfig{
					Enabled:         true,
					ReminderOnStart: true,
				},
			},
		},
		Modules: []string{
			"base",
			"environment",
			"tools_manual",
			"todo_reminder",
			"code_reference",
		},
	}
)

预定义的 Prompt 模板

AllPresets 所有预设模板

Functions

func FormatStats added in v0.17.0

func FormatStats(stats *PromptStats) string

FormatStats 格式化统计信息

func RegisterAllPresets added in v0.17.0

func RegisterAllPresets(registry *TemplateRegistry)

RegisterAllPresets 注册所有预设到模板注册表

func RegisterPreset added in v0.17.0

func RegisterPreset(registry *TemplateRegistry, preset *PromptTemplatePreset)

RegisterPreset 注册预设到模板注册表

func StreamCollect

func StreamCollect(reader *stream.Reader[*session.Event]) ([]*session.Event, error)

StreamCollect 辅助函数 - 收集所有事件 用于向后兼容,将流式接口转换为批量结果

使用示例:

events, err := StreamCollect(agent.Stream(ctx, "Hello"))
if err != nil {
    return err
}
for _, event := range events {
    fmt.Println(event)
}

func StreamFilter

func StreamFilter(reader *stream.Reader[*session.Event], predicate func(*session.Event) bool) *stream.Reader[*session.Event]

StreamFilter 辅助函数 - 过滤事件

func StreamFirst

func StreamFirst(reader *stream.Reader[*session.Event]) (*session.Event, error)

StreamFirst 辅助函数 - 获取第一个事件

func StreamLast

func StreamLast(reader *stream.Reader[*session.Event]) (*session.Event, error)

StreamLast 辅助函数 - 获取最后一个事件

Types

type Agent

type Agent struct {
	// contains filtered or unexported fields
}

Agent AI代理

func Create

func Create(ctx context.Context, config *types.AgentConfig, deps *Dependencies) (*Agent, error)

Create 创建新Agent

func (*Agent) Chat

func (a *Agent) Chat(ctx context.Context, text string) (*types.CompleteResult, error)

Chat 同步对话(阻塞式)

func (*Agent) Close

func (a *Agent) Close() error

Close 关闭Agent

func (*Agent) ControlTool added in v0.16.0

func (a *Agent) ControlTool(callID, action, note string) error

ControlTool 执行对运行中工具的控制

func (*Agent) ExecuteToolDirect added in v0.17.0

func (a *Agent) ExecuteToolDirect(ctx context.Context, toolName string, input map[string]interface{}) (interface{}, error)

ExecuteToolDirect 直接执行工具(程序化工具调用) 这个方法允许 Agent 或外部代码直接调用工具,绕过 LLM 决策 主要用于程序化工具编排场景

func (*Agent) ExecuteToolsDirect added in v0.17.0

func (a *Agent) ExecuteToolsDirect(ctx context.Context, calls []ToolCall) []ToolCallResult

ExecuteToolsDirect 批量直接执行工具(顺序执行)

func (*Agent) GetSystemPrompt added in v0.16.0

func (a *Agent) GetSystemPrompt() string

GetSystemPrompt 获取当前的 System Prompt

func (*Agent) GetToolSnapshot added in v0.16.0

func (a *Agent) GetToolSnapshot(callID string) types.ToolCallSnapshot

GetToolSnapshot 获取指定调用的实时快照

func (*Agent) ID

func (a *Agent) ID() string

ID 返回AgentID

func (*Agent) ListRunningToolSnapshots added in v0.16.0

func (a *Agent) ListRunningToolSnapshots() []types.ToolCallSnapshot

ListRunningToolSnapshots 列出运行中的工具调用

func (*Agent) Send

func (a *Agent) Send(ctx context.Context, text string) error

Send 发送消息

func (*Agent) Status

func (a *Agent) Status() *types.AgentStatus

Status 获取状态

func (*Agent) Stream

func (a *Agent) Stream(ctx context.Context, message string, opts ...Option) *stream.Reader[*session.Event]

Stream 实现流式执行接口 返回 stream.Reader,支持: - 流式生成事件 - 客户端控制的取消 - 与 LLM 流式 API 无缝集成 - 多消费者支持(Copy, Merge, Transform)

func (*Agent) Subscribe

func (a *Agent) Subscribe(channels []types.AgentChannel, opts *types.SubscribeOptions) <-chan types.AgentEventEnvelope

Subscribe 订阅事件

func (*Agent) Unsubscribe

func (a *Agent) Unsubscribe(ch <-chan types.AgentEventEnvelope)

Unsubscribe 取消事件订阅

type AvoidOverEngineeringModule added in v0.18.0

type AvoidOverEngineeringModule struct{}

AvoidOverEngineeringModule 避免过度工程化模块

func (*AvoidOverEngineeringModule) Build added in v0.18.0

func (*AvoidOverEngineeringModule) Condition added in v0.18.0

func (m *AvoidOverEngineeringModule) Condition(ctx *PromptContext) bool

func (*AvoidOverEngineeringModule) Name added in v0.18.0

func (*AvoidOverEngineeringModule) Priority added in v0.18.0

func (m *AvoidOverEngineeringModule) Priority() int

type BasePromptModule added in v0.17.0

type BasePromptModule struct{}

BasePromptModule 基础 Prompt(来自模板)

func (*BasePromptModule) Build added in v0.17.0

func (m *BasePromptModule) Build(ctx *PromptContext) (string, error)

func (*BasePromptModule) Condition added in v0.17.0

func (m *BasePromptModule) Condition(ctx *PromptContext) bool

func (*BasePromptModule) Name added in v0.17.0

func (m *BasePromptModule) Name() string

func (*BasePromptModule) Priority added in v0.17.0

func (m *BasePromptModule) Priority() int

type CapabilitiesModule added in v0.17.0

type CapabilitiesModule struct{}

CapabilitiesModule Agent 能力说明模块

func (*CapabilitiesModule) Build added in v0.17.0

func (m *CapabilitiesModule) Build(ctx *PromptContext) (string, error)

func (*CapabilitiesModule) Condition added in v0.17.0

func (m *CapabilitiesModule) Condition(ctx *PromptContext) bool

func (*CapabilitiesModule) Name added in v0.17.0

func (m *CapabilitiesModule) Name() string

func (*CapabilitiesModule) Priority added in v0.17.0

func (m *CapabilitiesModule) Priority() int

type CodeReferenceModule added in v0.17.0

type CodeReferenceModule struct{}

CodeReferenceModule 代码引用规范模块

func (*CodeReferenceModule) Build added in v0.17.0

func (m *CodeReferenceModule) Build(ctx *PromptContext) (string, error)

func (*CodeReferenceModule) Condition added in v0.17.0

func (m *CodeReferenceModule) Condition(ctx *PromptContext) bool

func (*CodeReferenceModule) Name added in v0.17.0

func (m *CodeReferenceModule) Name() string

func (*CodeReferenceModule) Priority added in v0.17.0

func (m *CodeReferenceModule) Priority() int

type CollaborationModule added in v0.17.0

type CollaborationModule struct {
	RoomInfo *RoomCollaborationInfo
}

CollaborationModule 多 Agent 协作模块

func (*CollaborationModule) Build added in v0.17.0

func (m *CollaborationModule) Build(ctx *PromptContext) (string, error)

func (*CollaborationModule) Condition added in v0.17.0

func (m *CollaborationModule) Condition(ctx *PromptContext) bool

func (*CollaborationModule) Name added in v0.17.0

func (m *CollaborationModule) Name() string

func (*CollaborationModule) Priority added in v0.17.0

func (m *CollaborationModule) Priority() int

type CompressOptions added in v0.17.0

type CompressOptions struct {
	TargetLength     int              // 目标长度(字符数)
	TargetTokens     int              // 目标 Token 数
	Mode             CompressionMode  // 压缩模式
	Level            CompressionLevel // 压缩级别
	PreserveSections []string         // 必须保留的段落标题
}

CompressOptions 压缩选项

type CompressResult added in v0.17.0

type CompressResult struct {
	Compressed       string  // 压缩后的内容
	OriginalLength   int     // 原始长度
	CompressedLength int     // 压缩后长度
	OriginalTokens   int     // 原始 Token 数
	CompressedTokens int     // 压缩后 Token 数
	CompressionRatio float64 // 压缩率
	TokensSaved      int     // 节省的 Token 数
	Mode             string  // 使用的模式
}

CompressResult 压缩结果

type CompressionLevel added in v0.17.0

type CompressionLevel int

CompressionLevel 压缩级别

const (
	CompressionLevelLight      CompressionLevel = 1 // 轻度压缩(保留 60-70%)
	CompressionLevelModerate   CompressionLevel = 2 // 中度压缩(保留 40-50%)
	CompressionLevelAggressive CompressionLevel = 3 // 激进压缩(保留 20-30%)
)

type CompressionMode added in v0.17.0

type CompressionMode string

CompressionMode 压缩模式

const (
	CompressionModeSimple CompressionMode = "simple" // 基于规则的快速压缩
	CompressionModeLLM    CompressionMode = "llm"    // LLM 驱动的智能压缩
	CompressionModeHybrid CompressionMode = "hybrid" // 混合模式(先规则后 LLM)
)

type ConcisenessModule added in v0.18.0

type ConcisenessModule struct{}

ConcisenessModule 简洁性模块 强调简洁、高效的沟通风格

func (*ConcisenessModule) Build added in v0.18.0

func (m *ConcisenessModule) Build(ctx *PromptContext) (string, error)

func (*ConcisenessModule) Condition added in v0.18.0

func (m *ConcisenessModule) Condition(ctx *PromptContext) bool

func (*ConcisenessModule) Name added in v0.18.0

func (m *ConcisenessModule) Name() string

func (*ConcisenessModule) Priority added in v0.18.0

func (m *ConcisenessModule) Priority() int

type ContextWindowModule added in v0.17.0

type ContextWindowModule struct {
	MaxTokens int
	Strategy  string
}

ContextWindowModule 上下文窗口管理模块

func (*ContextWindowModule) Build added in v0.17.0

func (m *ContextWindowModule) Build(ctx *PromptContext) (string, error)

func (*ContextWindowModule) Condition added in v0.17.0

func (m *ContextWindowModule) Condition(ctx *PromptContext) bool

func (*ContextWindowModule) Name added in v0.17.0

func (m *ContextWindowModule) Name() string

func (*ContextWindowModule) Priority added in v0.17.0

func (m *ContextWindowModule) Priority() int

type CustomInstructionsModule added in v0.17.0

type CustomInstructionsModule struct {
	Instructions string
}

CustomInstructionsModule 用户自定义指令模块

func (*CustomInstructionsModule) Build added in v0.17.0

func (*CustomInstructionsModule) Condition added in v0.17.0

func (m *CustomInstructionsModule) Condition(ctx *PromptContext) bool

func (*CustomInstructionsModule) Name added in v0.17.0

func (m *CustomInstructionsModule) Name() string

func (*CustomInstructionsModule) Priority added in v0.17.0

func (m *CustomInstructionsModule) Priority() int

type Dependencies

type Dependencies struct {
	Store           store.Store
	SandboxFactory  *sandbox.Factory
	ToolRegistry    *tools.Registry
	ProviderFactory provider.Factory
	// Router 为可选依赖,如果为 nil,则沿用旧的静态 ModelConfig 行为。
	Router           router.Router
	TemplateRegistry *TemplateRegistry

	// PromptCompressor 可选的 Prompt 压缩器
	// 如果配置了且模板启用了压缩,将用于压缩 System Prompt
	PromptCompressor *EnhancedPromptCompressor
}

Dependencies Agent依赖

type EnhancedPromptCompressor added in v0.17.0

type EnhancedPromptCompressor struct {
	// contains filtered or unexported fields
}

EnhancedPromptCompressor 增强的 Prompt 压缩器 集成 Token 计数、段落分析和多模式压缩

func NewEnhancedPromptCompressor added in v0.17.0

func NewEnhancedPromptCompressor(prov provider.Provider, language string) *EnhancedPromptCompressor

NewEnhancedPromptCompressor 创建增强压缩器

func (*EnhancedPromptCompressor) Compress added in v0.17.0

Compress 压缩 Prompt

func (*EnhancedPromptCompressor) EstimateTokens added in v0.17.0

func (c *EnhancedPromptCompressor) EstimateTokens(ctx context.Context, text string) (int, error)

EstimateTokens 估算 Token 数

type EnvironmentInfo added in v0.17.0

type EnvironmentInfo struct {
	WorkingDir string
	Platform   string
	OSVersion  string
	Date       time.Time
	GitRepo    *GitRepoInfo
}

EnvironmentInfo 环境信息

type EnvironmentModule added in v0.17.0

type EnvironmentModule struct{}

EnvironmentModule 环境信息模块

func (*EnvironmentModule) Build added in v0.17.0

func (m *EnvironmentModule) Build(ctx *PromptContext) (string, error)

func (*EnvironmentModule) Condition added in v0.17.0

func (m *EnvironmentModule) Condition(ctx *PromptContext) bool

func (*EnvironmentModule) Name added in v0.17.0

func (m *EnvironmentModule) Name() string

func (*EnvironmentModule) Priority added in v0.17.0

func (m *EnvironmentModule) Priority() int

type FallbackStats added in v0.13.0

type FallbackStats struct {
	TotalRequests    int64
	SuccessRequests  int64
	FailedRequests   int64
	FallbackCount    int64
	ModelUsageCount  map[string]int64
	LastFallbackTime time.Time
}

FallbackStats 降级统计信息

type GitRepoInfo added in v0.17.0

type GitRepoInfo struct {
	IsRepo        bool
	CurrentBranch string
	MainBranch    string
	Status        string
	RecentCommits []string
}

GitRepoInfo Git 仓库信息

type GitSafetyModule added in v0.18.0

type GitSafetyModule struct{}

GitSafetyModule Git 安全协议模块

func (*GitSafetyModule) Build added in v0.18.0

func (m *GitSafetyModule) Build(ctx *PromptContext) (string, error)

func (*GitSafetyModule) Condition added in v0.18.0

func (m *GitSafetyModule) Condition(ctx *PromptContext) bool

func (*GitSafetyModule) Name added in v0.18.0

func (m *GitSafetyModule) Name() string

func (*GitSafetyModule) Priority added in v0.18.0

func (m *GitSafetyModule) Priority() int

type LLMPromptCompressor added in v0.17.0

type LLMPromptCompressor struct {
	// contains filtered or unexported fields
}

LLMPromptCompressor LLM 驱动的 Prompt 压缩器

func NewLLMPromptCompressor added in v0.17.0

func NewLLMPromptCompressor(prov provider.Provider, model string, language string) *LLMPromptCompressor

NewLLMPromptCompressor 创建 LLM Prompt 压缩器

func (*LLMPromptCompressor) Compress added in v0.17.0

func (c *LLMPromptCompressor) Compress(ctx context.Context, prompt string, targetLength int, preserveSections []string, level int) (string, error)

Compress 压缩 Prompt

func (*LLMPromptCompressor) CompressSection added in v0.17.0

func (c *LLMPromptCompressor) CompressSection(ctx context.Context, section string, targetLength int) (string, error)

CompressSection 压缩单个段落

func (*LLMPromptCompressor) EstimateCompressionRatio added in v0.17.0

func (c *LLMPromptCompressor) EstimateCompressionRatio(level int) float64

EstimateCompressionRatio 估算压缩率

type LimitationsModule added in v0.17.0

type LimitationsModule struct{}

LimitationsModule 限制说明模块

func (*LimitationsModule) Build added in v0.17.0

func (m *LimitationsModule) Build(ctx *PromptContext) (string, error)

func (*LimitationsModule) Condition added in v0.17.0

func (m *LimitationsModule) Condition(ctx *PromptContext) bool

func (*LimitationsModule) Name added in v0.17.0

func (m *LimitationsModule) Name() string

func (*LimitationsModule) Priority added in v0.17.0

func (m *LimitationsModule) Priority() int

type ModelFallback added in v0.13.0

type ModelFallback struct {
	// Config 模型配置
	Config *types.ModelConfig

	// MaxRetries 最大重试次数
	MaxRetries int

	// Enabled 是否启用此模型
	Enabled bool

	// Priority 优先级(数字越小优先级越高)
	Priority int
	// contains filtered or unexported fields
}

ModelFallback 模型降级配置

type ModelFallbackManager added in v0.13.0

type ModelFallbackManager struct {
	// contains filtered or unexported fields
}

ModelFallbackManager 模型降级管理器

func NewModelFallbackManager added in v0.13.0

func NewModelFallbackManager(fallbacks []*ModelFallback, deps *Dependencies) (*ModelFallbackManager, error)

NewModelFallbackManager 创建模型降级管理器

func (*ModelFallbackManager) Complete added in v0.13.0

Complete 执行非流式请求,支持自动降级

func (*ModelFallbackManager) DisableModel added in v0.13.0

func (m *ModelFallbackManager) DisableModel(provider, model string) error

DisableModel 禁用指定模型

func (*ModelFallbackManager) EnableModel added in v0.13.0

func (m *ModelFallbackManager) EnableModel(provider, model string) error

EnableModel 启用指定模型

func (*ModelFallbackManager) GetCurrentProvider added in v0.13.0

func (m *ModelFallbackManager) GetCurrentProvider() provider.Provider

GetCurrentProvider 获取当前使用的 Provider

func (*ModelFallbackManager) GetStats added in v0.13.0

func (m *ModelFallbackManager) GetStats() *FallbackStats

GetStats 获取统计信息

func (*ModelFallbackManager) ListModels added in v0.13.0

func (m *ModelFallbackManager) ListModels() []map[string]interface{}

ListModels 列出所有模型及其状态

func (*ModelFallbackManager) ResetStats added in v0.13.0

func (m *ModelFallbackManager) ResetStats()

ResetStats 重置统计信息

func (*ModelFallbackManager) Stream added in v0.13.0

func (m *ModelFallbackManager) Stream(
	ctx context.Context,
	messages []types.Message,
	opts *provider.StreamOptions,
) (<-chan provider.StreamChunk, error)

Stream 执行流式请求,支持自动降级

type Option

type Option func(*streamConfig)

Option 流式执行选项

type PerformanceModule added in v0.17.0

type PerformanceModule struct{}

PerformanceModule 性能优化模块

func (*PerformanceModule) Build added in v0.17.0

func (m *PerformanceModule) Build(ctx *PromptContext) (string, error)

func (*PerformanceModule) Condition added in v0.17.0

func (m *PerformanceModule) Condition(ctx *PromptContext) bool

func (*PerformanceModule) Name added in v0.17.0

func (m *PerformanceModule) Name() string

func (*PerformanceModule) Priority added in v0.17.0

func (m *PerformanceModule) Priority() int

type PlanningWithoutTimelinesModule added in v0.18.0

type PlanningWithoutTimelinesModule struct{}

PlanningWithoutTimelinesModule 无时间线规划模块

func (*PlanningWithoutTimelinesModule) Build added in v0.18.0

func (*PlanningWithoutTimelinesModule) Condition added in v0.18.0

func (*PlanningWithoutTimelinesModule) Name added in v0.18.0

func (*PlanningWithoutTimelinesModule) Priority added in v0.18.0

func (m *PlanningWithoutTimelinesModule) Priority() int

type ProfessionalObjectivityModule added in v0.18.0

type ProfessionalObjectivityModule struct{}

ProfessionalObjectivityModule 专业客观性模块 借鉴 Claude Code 的设计原则,强调技术准确性和真实性

func (*ProfessionalObjectivityModule) Build added in v0.18.0

func (*ProfessionalObjectivityModule) Condition added in v0.18.0

func (*ProfessionalObjectivityModule) Name added in v0.18.0

func (*ProfessionalObjectivityModule) Priority added in v0.18.0

func (m *ProfessionalObjectivityModule) Priority() int

type PromptBuilder added in v0.17.0

type PromptBuilder struct {
	// contains filtered or unexported fields
}

PromptBuilder System Prompt 构建器

func NewPromptBuilder added in v0.17.0

func NewPromptBuilder() *PromptBuilder

NewPromptBuilder 创建构建器

func NewPromptBuilderWithCompression added in v0.17.0

func NewPromptBuilderWithCompression(compressor *EnhancedPromptCompressor) *PromptBuilder

NewPromptBuilderWithCompression 创建带压缩功能的构建器

func (*PromptBuilder) AddModule added in v0.17.0

func (pb *PromptBuilder) AddModule(module PromptModule)

AddModule 添加模块

func (*PromptBuilder) Build added in v0.17.0

func (pb *PromptBuilder) Build(ctx *PromptContext) (string, error)

Build 构建完整的 System Prompt

func (*PromptBuilder) SetCompressor added in v0.17.0

func (pb *PromptBuilder) SetCompressor(compressor *EnhancedPromptCompressor)

SetCompressor 设置压缩器

type PromptCompressor added in v0.17.0

type PromptCompressor struct {
	TargetLength     int
	PreserveSections []string // 需要保留的段落标题
}

PromptCompressor Prompt 压缩器(使用 LLM 进行智能压缩)

func (*PromptCompressor) Compress added in v0.17.0

func (pc *PromptCompressor) Compress(prompt string) string

Compress 压缩 Prompt(简化版,实际可以使用 LLM)

type PromptContext added in v0.17.0

type PromptContext struct {
	Agent       *Agent
	Template    *types.AgentTemplateDefinition
	Environment *EnvironmentInfo
	Sandbox     *SandboxInfo
	Tools       map[string]tools.Tool
	Metadata    map[string]interface{}
}

PromptContext 构建上下文

type PromptModule added in v0.17.0

type PromptModule interface {
	Name() string
	Build(ctx *PromptContext) (string, error)
	Priority() int                     // 模块优先级,决定注入顺序
	Condition(ctx *PromptContext) bool // 是否应该注入此模块
}

PromptModule 表示一个可组合的 prompt 模块

type PromptOptimizer added in v0.17.0

type PromptOptimizer struct {
	MaxLength        int  // 最大长度(字符数)
	RemoveDuplicates bool // 移除重复内容
	CompactFormat    bool // 紧凑格式
}

PromptOptimizer Prompt 优化器

func (*PromptOptimizer) Optimize added in v0.17.0

func (po *PromptOptimizer) Optimize(prompt string) string

Optimize 优化 System Prompt

type PromptStats added in v0.17.0

type PromptStats struct {
	TotalLength     int
	LineCount       int
	SectionCount    int
	ModuleCount     int
	EstimatedTokens int
}

PromptStats Prompt 统计信息

func AnalyzePrompt added in v0.17.0

func AnalyzePrompt(prompt string) *PromptStats

AnalyzePrompt 分析 Prompt 统计信息

type PromptTemplatePreset added in v0.17.0

type PromptTemplatePreset struct {
	ID          string
	Name        string
	Description string
	Template    *types.AgentTemplateDefinition
	Modules     []string // 推荐的模块列表
}

PromptTemplatePreset Prompt 模板预设

func GetPreset added in v0.17.0

func GetPreset(id string) *PromptTemplatePreset

GetPreset 根据 ID 获取预设

type RoomCollaborationInfo added in v0.17.0

type RoomCollaborationInfo struct {
	RoomID      string
	MemberCount int
	Members     []string
}

type SandboxInfo added in v0.17.0

type SandboxInfo struct {
	Kind       types.SandboxKind
	WorkDir    string
	AllowPaths []string
}

SandboxInfo 沙箱信息

type SandboxModule added in v0.17.0

type SandboxModule struct{}

SandboxModule 沙箱信息模块

func (*SandboxModule) Build added in v0.17.0

func (m *SandboxModule) Build(ctx *PromptContext) (string, error)

func (*SandboxModule) Condition added in v0.17.0

func (m *SandboxModule) Condition(ctx *PromptContext) bool

func (*SandboxModule) Name added in v0.17.0

func (m *SandboxModule) Name() string

func (*SandboxModule) Priority added in v0.17.0

func (m *SandboxModule) Priority() int

type ScoredSection added in v0.17.0

type ScoredSection struct {
	Content  string
	Title    string
	Score    float64
	MustKeep bool
}

ScoredSection 带评分的段落

type SecurityModule added in v0.17.0

type SecurityModule struct{}

SecurityModule 安全策略模块

func (*SecurityModule) Build added in v0.17.0

func (m *SecurityModule) Build(ctx *PromptContext) (string, error)

func (*SecurityModule) Condition added in v0.17.0

func (m *SecurityModule) Condition(ctx *PromptContext) bool

func (*SecurityModule) Name added in v0.17.0

func (m *SecurityModule) Name() string

func (*SecurityModule) Priority added in v0.17.0

func (m *SecurityModule) Priority() int

type StreamingAgent

type StreamingAgent interface {
	// Stream 流式执行,返回事件流
	// 相比 Chat 方法的优势:
	// 1. 内存高效 - 按需生成事件,无需完整加载到内存
	// 2. 背压控制 - 客户端可控制消费速度
	// 3. 实时响应 - 可以立即处理每个事件,而不是等待所有事件
	// 4. 多消费者 - 支持 Copy 复制流给多个消费者
	Stream(ctx context.Context, message string, opts ...Option) *stream.Reader[*session.Event]
}

StreamingAgent 扩展接口 - 支持流式执行 参考 Google ADK-Go 的 Agent.Run() 设计,使用 stream.Reader

使用示例:

reader := agent.Stream(ctx, "Hello")
for {
    event, err := reader.Recv()
    if err == io.EOF { break }
    if err != nil {
        log.Printf("Error: %v", err)
        break
    }
    fmt.Printf("Event: %+v\n", event)
}

type TemplateNotFoundError

type TemplateNotFoundError struct {
	ID string
}

TemplateNotFoundError 模板未找到错误

func (*TemplateNotFoundError) Error

func (e *TemplateNotFoundError) Error() string

type TemplateRegistry

type TemplateRegistry struct {
	// contains filtered or unexported fields
}

TemplateRegistry 模板注册表

func NewTemplateRegistry

func NewTemplateRegistry() *TemplateRegistry

NewTemplateRegistry 创建模板注册表

func (*TemplateRegistry) Get

Get 获取模板

func (*TemplateRegistry) List

List 列出所有模板

func (*TemplateRegistry) Register

func (tr *TemplateRegistry) Register(template *types.AgentTemplateDefinition)

Register 注册模板

type TodoReminderModule added in v0.17.0

type TodoReminderModule struct {
	Config *types.TodoConfig
}

TodoReminderModule Todo 提醒模块

func (*TodoReminderModule) Build added in v0.17.0

func (m *TodoReminderModule) Build(ctx *PromptContext) (string, error)

func (*TodoReminderModule) Condition added in v0.17.0

func (m *TodoReminderModule) Condition(ctx *PromptContext) bool

func (*TodoReminderModule) Name added in v0.17.0

func (m *TodoReminderModule) Name() string

func (*TodoReminderModule) Priority added in v0.17.0

func (m *TodoReminderModule) Priority() int

type ToolCall added in v0.17.0

type ToolCall struct {
	Name  string                 `json:"name"`
	Input map[string]interface{} `json:"input"`
}

ToolCall 工具调用参数

type ToolCallResult added in v0.17.0

type ToolCallResult struct {
	Name    string      `json:"name"`
	Success bool        `json:"success"`
	Result  interface{} `json:"result,omitempty"`
	Error   string      `json:"error,omitempty"`
}

ToolCallResult 工具调用结果

type ToolManager added in v0.17.0

type ToolManager struct {
	// contains filtered or unexported fields
}

ToolManager 工具管理器 支持动态工具激活和工具搜索

func NewToolManager added in v0.17.0

func NewToolManager(registry *tools.Registry) *ToolManager

NewToolManager 创建工具管理器

func (*ToolManager) ActivateTool added in v0.17.0

func (tm *ToolManager) ActivateTool(name string) error

ActivateTool 激活延迟工具

func (*ToolManager) ActivateTools added in v0.17.0

func (tm *ToolManager) ActivateTools(names []string) (activated []string, failed map[string]error)

ActivateTools 批量激活工具

func (*ToolManager) AddTool added in v0.17.0

func (tm *ToolManager) AddTool(tool tools.Tool, source string, deferred bool) error

AddTool 添加新工具

func (*ToolManager) AddToolEntry added in v0.17.0

func (tm *ToolManager) AddToolEntry(entry search.ToolIndexEntry) error

AddToolEntry 添加工具条目(用于 MCP 延迟加载)

func (*ToolManager) DeactivateTool added in v0.17.0

func (tm *ToolManager) DeactivateTool(name string) error

DeactivateTool 停用工具(移回延迟状态)

func (*ToolManager) GetActiveTool added in v0.17.0

func (tm *ToolManager) GetActiveTool(name string) (tools.Tool, bool)

GetActiveTool 获取单个活跃工具

func (*ToolManager) GetActiveTools added in v0.17.0

func (tm *ToolManager) GetActiveTools() map[string]tools.Tool

GetActiveTools 获取所有活跃工具

func (*ToolManager) GetIndex added in v0.17.0

func (tm *ToolManager) GetIndex() *search.ToolIndex

GetIndex 获取工具索引

func (*ToolManager) Initialize added in v0.17.0

func (tm *ToolManager) Initialize(toolNames []string, activeByDefault bool) error

Initialize 初始化工具管理器 将所有工具添加到索引,并根据配置决定哪些工具活跃

func (*ToolManager) IsCoreTool added in v0.17.0

func (tm *ToolManager) IsCoreTool(name string) bool

IsCoreTools 检查是否是核心工具

func (*ToolManager) RemoveTool added in v0.17.0

func (tm *ToolManager) RemoveTool(name string) error

RemoveTool 移除工具

func (*ToolManager) SearchTools added in v0.17.0

func (tm *ToolManager) SearchTools(query string, topK int) []search.ToolSearchResult

SearchTools 搜索工具

func (*ToolManager) Stats added in v0.17.0

func (tm *ToolManager) Stats() map[string]interface{}

Stats 返回统计信息

type ToolsManualModule added in v0.17.0

type ToolsManualModule struct {
	Config *types.ToolsManualConfig
}

ToolsManualModule 工具手册模块

func (*ToolsManualModule) Build added in v0.17.0

func (m *ToolsManualModule) Build(ctx *PromptContext) (string, error)

func (*ToolsManualModule) Condition added in v0.17.0

func (m *ToolsManualModule) Condition(ctx *PromptContext) bool

func (*ToolsManualModule) Name added in v0.17.0

func (m *ToolsManualModule) Name() string

func (*ToolsManualModule) Priority added in v0.17.0

func (m *ToolsManualModule) Priority() int

type WorkflowContextInfo added in v0.17.0

type WorkflowContextInfo struct {
	WorkflowID   string
	CurrentStep  string
	TotalSteps   int
	StepIndex    int
	PreviousStep string
	NextStep     string
}

type WorkflowModule added in v0.17.0

type WorkflowModule struct {
	WorkflowInfo *WorkflowContextInfo
}

WorkflowModule 工作流上下文模块

func (*WorkflowModule) Build added in v0.17.0

func (m *WorkflowModule) Build(ctx *PromptContext) (string, error)

func (*WorkflowModule) Condition added in v0.17.0

func (m *WorkflowModule) Condition(ctx *PromptContext) bool

func (*WorkflowModule) Name added in v0.17.0

func (m *WorkflowModule) Name() string

func (*WorkflowModule) Priority added in v0.17.0

func (m *WorkflowModule) Priority() int

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL