feat: Add agent configuration and cleanup scripts for database migrations

This commit is contained in:
wizardchen
2025-11-05 23:18:44 +08:00
parent ae9d0778e9
commit 4fa3adbf3b
126 changed files with 22506 additions and 629 deletions
+110
View File
@@ -0,0 +1,110 @@
package types
import (
"context"
"database/sql/driver"
"encoding/json"
"time"
)
// AgentConfig represents the configuration for an agent session
type AgentConfig struct {
Enabled bool `json:"enabled"` // Whether agent mode is enabled
MaxIterations int `json:"max_iterations"` // Maximum number of ReAct iterations
ReflectionEnabled bool `json:"reflection_enabled"` // Whether to enable reflection
AllowedTools []string `json:"allowed_tools"` // List of allowed tool names
Temperature float64 `json:"temperature"` // LLM temperature for agent
ThinkingModelID string `json:"thinking_model_id"` // Model ID for reasoning
RerankModelID string `json:"rerank_model_id"` // Model ID for reranking search results
KnowledgeBases []string `json:"knowledge_bases"` // Accessible knowledge base IDs
}
// Value implements driver.Valuer interface for AgentConfig
func (c AgentConfig) Value() (driver.Value, error) {
return json.Marshal(c)
}
// Scan implements sql.Scanner interface for AgentConfig
func (c *AgentConfig) Scan(value interface{}) error {
if value == nil {
return nil
}
b, ok := value.([]byte)
if !ok {
return nil
}
return json.Unmarshal(b, c)
}
// Tool defines the interface that all agent tools must implement
type Tool interface {
// Name returns the unique identifier for this tool
Name() string
// Description returns a human-readable description of what the tool does
Description() string
// Parameters returns the JSON Schema for the tool's parameters
Parameters() map[string]interface{}
// Execute runs the tool with the given arguments
Execute(ctx context.Context, args map[string]interface{}) (*ToolResult, error)
}
// ToolResult represents the result of a tool execution
type ToolResult struct {
Success bool `json:"success"` // Whether the tool executed successfully
Output string `json:"output"` // Human-readable output
Data map[string]interface{} `json:"data,omitempty"` // Structured data for programmatic use
Error string `json:"error,omitempty"` // Error message if execution failed
}
// ToolCall represents a single tool invocation within an agent step
type ToolCall struct {
ID string `json:"id"` // Function call ID from LLM
Name string `json:"name"` // Tool name
Args map[string]interface{} `json:"args"` // Tool arguments
Result *ToolResult `json:"result"` // Execution result (contains Output)
Reflection string `json:"reflection,omitempty"` // Agent's reflection on this tool call result (if enabled)
Duration int64 `json:"duration"` // Execution time in milliseconds
}
// AgentStep represents one iteration of the ReAct loop
type AgentStep struct {
Iteration int `json:"iteration"` // Iteration number (0-indexed)
Thought string `json:"thought"` // LLM's reasoning/thinking (Think phase)
ToolCalls []ToolCall `json:"tool_calls"` // Tools called in this step (Act phase)
Timestamp time.Time `json:"timestamp"` // When this step occurred
}
// GetObservations returns observations from all tool calls in this step
// This is a convenience method to maintain backward compatibility
func (s *AgentStep) GetObservations() []string {
observations := make([]string, 0, len(s.ToolCalls))
for _, tc := range s.ToolCalls {
if tc.Result != nil && tc.Result.Output != "" {
observations = append(observations, tc.Result.Output)
}
if tc.Reflection != "" {
observations = append(observations, "Reflection: "+tc.Reflection)
}
}
return observations
}
// AgentState tracks the execution state of an agent across iterations
type AgentState struct {
CurrentRound int `json:"current_round"` // Current round number
RoundSteps []AgentStep `json:"round_steps"` // All steps taken so far in the current round
Plan []string `json:"plan,omitempty"` // Execution plan (if planning enabled)
IsComplete bool `json:"is_complete"` // Whether agent has finished
FinalAnswer string `json:"final_answer"` // The final answer to the query
KnowledgeRefs []*SearchResult `json:"knowledge_refs"` // Collected knowledge references
}
// FunctionDefinition represents a function definition for LLM function calling
type FunctionDefinition struct {
Name string `json:"name"`
Description string `json:"description"`
Parameters map[string]interface{} `json:"parameters"`
}
+32 -1
View File
@@ -5,9 +5,26 @@ import (
"encoding/json"
)
// LLMToolCall represents a function/tool call from the LLM
type LLMToolCall struct {
ID string `json:"id"`
Type string `json:"type"` // "function"
Function FunctionCall `json:"function"`
}
// FunctionCall represents the function details
type FunctionCall struct {
Name string `json:"name"`
Arguments string `json:"arguments"` // JSON string
}
// ChatResponse chat response
type ChatResponse struct {
Content string `json:"content"`
// Tool calls requested by the model
ToolCalls []LLMToolCall `json:"tool_calls,omitempty"`
// Finish reason
FinishReason string `json:"finish_reason,omitempty"` // "stop", "tool_calls", "length", etc.
// Usage information
Usage struct {
// Prompt tokens
@@ -27,6 +44,16 @@ const (
ResponseTypeAnswer ResponseType = "answer"
// References response type
ResponseTypeReferences ResponseType = "references"
// Thinking response type (for agent thought process)
ResponseTypeThinking ResponseType = "thinking"
// Tool call response type (for agent tool invocations)
ResponseTypeToolCall ResponseType = "tool_call"
// Tool result response type (for agent tool results)
ResponseTypeToolResult ResponseType = "tool_result"
// Error response type
ResponseTypeError ResponseType = "error"
// Reflection response type (for agent reflection)
ResponseTypeReflection ResponseType = "reflection"
)
// StreamResponse stream response
@@ -40,7 +67,11 @@ type StreamResponse struct {
// Whether the response is complete
Done bool `json:"done"`
// Knowledge references
KnowledgeReferences References `json:"knowledge_references"`
KnowledgeReferences References `json:"knowledge_references,omitempty"`
// Tool calls for streaming (partial)
ToolCalls []LLMToolCall `json:"tool_calls,omitempty"`
// Additional metadata for enhanced display
Data map[string]interface{} `json:"data,omitempty"`
}
// References references
+33
View File
@@ -0,0 +1,33 @@
package interfaces
import (
"context"
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/types"
)
// AgentStreamEvent represents a streaming event from the agent
type AgentStreamEvent struct {
Type string `json:"type"` // "thought", "tool_call", "tool_result", "final_answer", "error", "references"
Content string `json:"content"` // Incremental content
Data map[string]interface{} `json:"data"` // Additional structured data
Done bool `json:"done"` // Whether this is the last event
Iteration int `json:"iteration"` // Current iteration number
}
// AgentEngine defines the interface for agent execution engine
type AgentEngine interface {
// ExecuteStreamWithHistory executes the agent with conversation history and returns a stream of events
Execute(ctx context.Context, sessionID, query string, llmContext []chat.Message) (*types.AgentState, error)
}
// AgentService defines the interface for agent-related operations
type AgentService interface {
// CreateAgentEngine creates an agent engine with the given configuration and EventBus
CreateAgentEngine(ctx context.Context, config *types.AgentConfig, eventBus *event.EventBus) (AgentEngine, error)
// ValidateConfig validates an agent configuration
ValidateConfig(config *types.AgentConfig) error
}
+1 -1
View File
@@ -40,7 +40,7 @@ type ChunkService interface {
// CreateChunks creates chunks
CreateChunks(ctx context.Context, chunks []*types.Chunk) error
// GetChunkByID gets a chunk by id
GetChunkByID(ctx context.Context, knowledgeID string, id string) (*types.Chunk, error)
GetChunkByID(ctx context.Context, id string) (*types.Chunk, error)
// ListChunksByKnowledgeID lists chunks by knowledge id
ListChunksByKnowledgeID(ctx context.Context, knowledgeID string) ([]*types.Chunk, error)
// ListPagedChunksByKnowledgeID lists paged chunks by knowledge id
@@ -0,0 +1,49 @@
package interfaces
import (
"context"
"github.com/Tencent/WeKnora/internal/models/chat"
)
// ContextManager manages LLM context for sessions
// It maintains conversation context separately from message storage
// and provides context compression when context window is exceeded
type ContextManager interface {
// AddMessage adds a message to the session context
// The message will be added to the context window for LLM
AddMessage(ctx context.Context, sessionID string, message chat.Message) error
// GetContext retrieves the current context for a session
// Returns messages that fit within the context window
// May apply compression if context is too large
GetContext(ctx context.Context, sessionID string) ([]chat.Message, error)
// ClearContext clears all context for a session
ClearContext(ctx context.Context, sessionID string) error
// GetContextStats returns statistics about the context
GetContextStats(ctx context.Context, sessionID string) (*ContextStats, error)
}
// ContextStats contains statistics about session context
type ContextStats struct {
// Total number of messages in context
MessageCount int `json:"message_count"`
// Estimated token count
TokenCount int `json:"token_count"`
// Whether context was compressed
IsCompressed bool `json:"is_compressed"`
// Number of original messages before compression
OriginalMessageCount int `json:"original_message_count"`
}
// CompressionStrategy defines how context should be compressed
type CompressionStrategy interface {
// Compress compresses messages when context exceeds limits
// Returns compressed messages that fit within the limit
Compress(ctx context.Context, messages []chat.Message, maxTokens int) ([]chat.Message, error)
// EstimateTokens estimates token count for messages
EstimateTokens(messages []chat.Message) int
}
+2
View File
@@ -46,4 +46,6 @@ type ModelRepository interface {
Update(ctx context.Context, model *types.Model) error
// Delete deletes a model
Delete(ctx context.Context, tenantID uint, id string) error
// ClearDefaultByType clears the default flag for all models of a specific type, optionally excluding a specific model ID
ClearDefaultByType(ctx context.Context, tenantID uint, modelType types.ModelType, excludeID string) error
}
+4
View File
@@ -3,6 +3,7 @@ package interfaces
import (
"context"
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/types"
)
@@ -30,6 +31,9 @@ type SessionService interface {
KnowledgeQAByEvent(ctx context.Context, chatManage *types.ChatManage, eventList []types.EventType) error
// SearchKnowledge performs knowledge-based search, without summarization
SearchKnowledge(ctx context.Context, knowledgeBaseID, query string) ([]*types.SearchResult, error)
// AgentQA performs agent-based question answering with conversation history and streaming support
// eventBus is optional - if nil, uses service's default EventBus
AgentQA(ctx context.Context, session *types.Session, query string, assistantMessageID string, eventBus *event.EventBus) ([]*types.SearchResult, error)
}
// SessionRepository defines the session repository interface
+21 -4
View File
@@ -7,12 +7,22 @@ import (
"github.com/Tencent/WeKnora/internal/types"
)
// StreamEvent represents a single event in the stream
type StreamEvent struct {
ID string `json:"id"` // Unique event ID for precise replacement
Type types.ResponseType `json:"type"` // Event type (thinking, tool_call, tool_result, etc.)
Content string `json:"content"` // Event content
Done bool `json:"done"` // Whether this event is done
Timestamp time.Time `json:"timestamp"` // When this event occurred
Data map[string]interface{} `json:"data,omitempty"` // Additional event data
}
// StreamInfo stream information
type StreamInfo struct {
SessionID string // session ID
RequestID string // request ID
Query string // query content
Content string // current content
Events []StreamEvent // all events in order (for replay on refresh)
KnowledgeReferences types.References // knowledge references
LastUpdated time.Time // last updated time
IsCompleted bool // whether completed
@@ -23,12 +33,19 @@ type StreamManager interface {
// RegisterStream registers a new stream
RegisterStream(ctx context.Context, sessionID, requestID, query string) error
// UpdateStream updates the stream content
UpdateStream(ctx context.Context, sessionID, requestID string, content string, references types.References) error
// PushEvent pushes an event to the stream (append mode)
PushEvent(ctx context.Context, sessionID, requestID string, event StreamEvent) error
// ReplaceEvent replaces an event by ID (for streaming progress updates)
// If no matching event exists, it will append the event
ReplaceEvent(ctx context.Context, sessionID, requestID string, event StreamEvent) error
// UpdateReferences updates knowledge references
UpdateReferences(ctx context.Context, sessionID, requestID string, references types.References) error
// CompleteStream completes the stream
CompleteStream(ctx context.Context, sessionID, requestID string) error
// GetStream gets a specific stream
// GetStream gets a specific stream (for replay on refresh)
GetStream(ctx context.Context, sessionID, requestID string) (*StreamInfo, error)
}
+35
View File
@@ -2,6 +2,8 @@
package types
import (
"database/sql/driver"
"encoding/json"
"time"
"github.com/google/uuid"
@@ -34,6 +36,10 @@ type Message struct {
Role string `json:"role"`
// References to knowledge chunks used in the response
KnowledgeReferences References `json:"knowledge_references" gorm:"type:json,column:knowledge_references"`
// Agent execution steps (only for assistant messages generated by agent)
// This contains the detailed reasoning process and tool calls made by the agent
// Stored for user history display, but NOT included in LLM context to avoid redundancy
AgentSteps AgentSteps `json:"agent_steps,omitempty" gorm:"type:json,column:agent_steps"`
// Whether message generation is complete
IsCompleted bool `json:"is_completed"`
// Message creation timestamp
@@ -44,6 +50,32 @@ type Message struct {
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
}
// AgentSteps represents a collection of agent execution steps
// Used for storing agent reasoning process in database
type AgentSteps []AgentStep
// Value implements the driver.Valuer interface for database serialization
func (a AgentSteps) Value() (driver.Value, error) {
if a == nil {
return json.Marshal([]AgentStep{})
}
return json.Marshal(a)
}
// Scan implements the sql.Scanner interface for database deserialization
func (a *AgentSteps) Scan(value interface{}) error {
if value == nil {
*a = make(AgentSteps, 0)
return nil
}
b, ok := value.([]byte)
if !ok {
*a = make(AgentSteps, 0)
return nil
}
return json.Unmarshal(b, a)
}
// BeforeCreate is a GORM hook that runs before creating a new message record
// Automatically generates a UUID for new messages and initializes knowledge references
// Parameters:
@@ -56,5 +88,8 @@ func (m *Message) BeforeCreate(tx *gorm.DB) (err error) {
if m.KnowledgeReferences == nil {
m.KnowledgeReferences = make(References, 0)
}
if m.AgentSteps == nil {
m.AgentSteps = make(AgentSteps, 0)
}
return nil
}
+43
View File
@@ -44,6 +44,30 @@ type SummaryConfig struct {
MaxCompletionTokens int `json:"max_completion_tokens"`
}
// ContextCompressionStrategy represents the strategy for context compression
type ContextCompressionStrategy string
const (
// ContextCompressionSlidingWindow keeps the most recent N messages
ContextCompressionSlidingWindow ContextCompressionStrategy = "sliding_window"
// ContextCompressionSmart uses LLM to summarize old messages
ContextCompressionSmart ContextCompressionStrategy = "smart"
)
// ContextConfig configures LLM context management
// This is separate from message storage and manages token limits
type ContextConfig struct {
// Maximum tokens allowed in LLM context
MaxTokens int `json:"max_tokens"`
// Compression strategy: "sliding_window" or "smart"
CompressionStrategy ContextCompressionStrategy `json:"compression_strategy"`
// For sliding_window: number of messages to keep
// For smart: number of recent messages to keep uncompressed
RecentMessageCount int `json:"recent_message_count"`
// Enable context management (default: true)
Enabled bool `json:"enabled"`
}
// Session represents the session
type Session struct {
// ID
@@ -69,6 +93,8 @@ type Session struct {
RerankThreshold float64 `json:"rerank_threshold"` // 排序阈值
SummaryModelID string `json:"summary_model_id"` // 总结模型ID
SummaryParameters *SummaryConfig `json:"summary_parameters" gorm:"type:json"` // 总结模型参数
AgentConfig *AgentConfig `json:"agent_config" gorm:"type:json"` // Agent 配置(可选)
ContextConfig *ContextConfig `json:"context_config" gorm:"type:json"` // 上下文管理配置(可选)
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
@@ -118,3 +144,20 @@ func (c *SummaryConfig) Scan(value interface{}) error {
}
return json.Unmarshal(b, c)
}
// Value implements the driver.Valuer interface, used to convert ContextConfig to database value
func (c *ContextConfig) Value() (driver.Value, error) {
return json.Marshal(c)
}
// Scan implements the sql.Scanner interface, used to convert database value to ContextConfig
func (c *ContextConfig) Scan(value interface{}) error {
if value == nil {
return nil
}
b, ok := value.([]byte)
if !ok {
return nil
}
return json.Unmarshal(b, c)
}
+2 -4
View File
@@ -8,10 +8,6 @@ import (
"gorm.io/gorm"
)
const (
InitDefaultTenantID uint = 1
)
// Tenant represents the tenant
type Tenant struct {
// ID
@@ -32,6 +28,8 @@ type Tenant struct {
StorageQuota int64 `yaml:"storage_quota" json:"storage_quota" gorm:"default:10737418240"`
// Storage used (Bytes)
StorageUsed int64 `yaml:"storage_used" json:"storage_used" gorm:"default:0"`
// Global Agent configuration for this tenant (default for all sessions)
AgentConfig *AgentConfig `yaml:"agent_config" json:"agent_config" gorm:"type:json"`
// Creation time
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
// Last updated time