feat: Implement manual knowledge editing and enhance knowledge base features
- Added functionality for manual knowledge entry, allowing users to create and edit Markdown content directly in the browser. - Introduced new API endpoints for creating and updating manual knowledge entries. - Enhanced UI components to support the new manual knowledge editor, including integration with existing knowledge base features. - Updated knowledge retrieval logic to accommodate manual entries, ensuring seamless user experience across knowledge types. - Improved agent configuration to support custom system prompts, enhancing flexibility in agent responses.
This commit is contained in:
@@ -11,8 +11,8 @@ type AvailableTool struct {
|
||||
// Keep this in sync with registered tools in this package.
|
||||
func AvailableToolDefinitions() []AvailableTool {
|
||||
return []AvailableTool{
|
||||
{Name: "thinking", Label: "思考", Description: "AI 进行深度思考和推理"},
|
||||
{Name: "todo_write", Label: "制定计划", Description: "为复杂任务制定执行计划"},
|
||||
{Name: "thinking", Label: "思考", Description: "动态和反思性的问题解决思考工具"},
|
||||
{Name: "todo_write", Label: "制定计划", Description: "创建结构化的研究计划"},
|
||||
{Name: "knowledge_search", Label: "知识搜索", Description: "在知识库中搜索相关信息"},
|
||||
{Name: "get_related_chunks", Label: "获取相关片段", Description: "查找相关的知识片段"},
|
||||
{Name: "query_knowledge_graph", Label: "查询知识图谱", Description: "从知识图谱中查询关系"},
|
||||
|
||||
@@ -52,16 +52,6 @@ func NewKnowledgeSearchTool(
|
||||
- Need semantic (vector) or exact keyword searches
|
||||
- Want to search only specific documents within KBs
|
||||
|
||||
**Parameters**:
|
||||
- knowledge_base_ids (optional): Array of KB IDs to search (1-10). If omitted, searches all allowed KBs.
|
||||
- query (optional): Single search query (for simple hybrid search)
|
||||
- vector_queries (optional): Array of semantic queries for vector search (1-5 queries)
|
||||
- keyword_queries (optional): Array of keyword queries for keyword search (1-5 queries)
|
||||
- top_k (optional): Results per KB per query (default: 5, max: 20)
|
||||
- vector_threshold (optional): Minimum score for vector results (default: 0.6, 0.0-1.0)
|
||||
- keyword_threshold (optional): Minimum score for keyword results (default: 0.5, 0.0-1.0)
|
||||
- knowledge_ids (optional): Array of document IDs to filter results (only return results from these documents)
|
||||
- min_score (optional): Absolute minimum score to include results (default: 0.3, filters very low quality chunks)
|
||||
|
||||
**Search Modes**:
|
||||
- Simple: Provide single query parameter (hybrid search)
|
||||
@@ -110,11 +100,7 @@ func NewKnowledgeSearchTool(
|
||||
- Reranked scores are in 0-1 range and directly comparable
|
||||
- Results are merged, deduplicated and sorted by relevance
|
||||
- Use vector_queries for semantic/conceptual searches
|
||||
- Use keyword_queries for exact term matching
|
||||
- Results below threshold are automatically filtered
|
||||
- High relevance (>=0.8): directly usable
|
||||
- Medium relevance (0.6-0.8): reference only
|
||||
- Low relevance (<0.6): use with caution`
|
||||
- Use keyword_queries for exact term matching`
|
||||
|
||||
return &KnowledgeSearchTool{
|
||||
BaseTool: NewBaseTool("knowledge_search", description),
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// SequentialThinkingTool implements a dynamic and reflective problem-solving tool
|
||||
// This tool helps analyze problems through a flexible thinking process that can adapt and evolve
|
||||
type SequentialThinkingTool struct {
|
||||
BaseTool
|
||||
thoughtHistory []ThoughtData
|
||||
branches map[string][]ThoughtData
|
||||
}
|
||||
|
||||
// ThoughtData represents a single thought in the sequential thinking process
|
||||
type ThoughtData struct {
|
||||
Thought string `json:"thought"`
|
||||
ThoughtNumber int `json:"thought_number"`
|
||||
TotalThoughts int `json:"total_thoughts"`
|
||||
IsRevision bool `json:"is_revision,omitempty"`
|
||||
RevisesThought *int `json:"revises_thought,omitempty"`
|
||||
BranchFromThought *int `json:"branch_from_thought,omitempty"`
|
||||
BranchID string `json:"branch_id,omitempty"`
|
||||
NeedsMoreThoughts bool `json:"needs_more_thoughts,omitempty"`
|
||||
NextThoughtNeeded bool `json:"next_thought_needed"`
|
||||
}
|
||||
|
||||
// NewSequentialThinkingTool creates a new sequential thinking tool instance
|
||||
func NewSequentialThinkingTool() *SequentialThinkingTool {
|
||||
description := `A detailed tool for dynamic and reflective problem-solving through thoughts.
|
||||
|
||||
This tool helps analyze problems through a flexible thinking process that can adapt and evolve.
|
||||
|
||||
Each thought can build on, question, or revise previous insights as understanding deepens.
|
||||
|
||||
## When to Use This Tool
|
||||
|
||||
- Breaking down complex problems into steps
|
||||
- Planning and design with room for revision
|
||||
- Analysis that might need course correction
|
||||
- Problems where the full scope might not be clear initially
|
||||
- Problems that require a multi-step solution
|
||||
- Tasks that need to maintain context over multiple steps
|
||||
- Situations where irrelevant information needs to be filtered out
|
||||
|
||||
## Key Features
|
||||
|
||||
- You can adjust total_thoughts up or down as you progress
|
||||
- You can question or revise previous thoughts
|
||||
- You can add more thoughts even after reaching what seemed like the end
|
||||
- You can express uncertainty and explore alternative approaches
|
||||
- Not every thought needs to build linearly - you can branch or backtrack
|
||||
- Generates a solution hypothesis
|
||||
- Verifies the hypothesis based on the Chain of Thought steps
|
||||
- Repeats the process until satisfied
|
||||
- Provides a correct answer
|
||||
|
||||
## Parameters Explained
|
||||
|
||||
- **thought**: Your current thinking step, which can include:
|
||||
* Regular analytical steps
|
||||
* Revisions of previous thoughts
|
||||
* Questions about previous decisions
|
||||
* Realizations about needing more analysis
|
||||
* Changes in approach
|
||||
* Hypothesis generation
|
||||
* Hypothesis verification
|
||||
|
||||
- **next_thought_needed**: True if you need more thinking, even if at what seemed like the end
|
||||
- **thought_number**: Current number in sequence (can go beyond initial total if needed)
|
||||
- **total_thoughts**: Current estimate of thoughts needed (can be adjusted up/down)
|
||||
- **is_revision**: A boolean indicating if this thought revises previous thinking
|
||||
- **revises_thought**: If is_revision is true, which thought number is being reconsidered
|
||||
- **branch_from_thought**: If branching, which thought number is the branching point
|
||||
- **branch_id**: Identifier for the current branch (if any)
|
||||
- **needs_more_thoughts**: If reaching end but realizing more thoughts needed
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. Start with an initial estimate of needed thoughts, but be ready to adjust
|
||||
2. Feel free to question or revise previous thoughts
|
||||
3. Don't hesitate to add more thoughts if needed, even at the "end"
|
||||
4. Express uncertainty when present
|
||||
5. Mark thoughts that revise previous thinking or branch into new paths
|
||||
6. Ignore information that is irrelevant to the current step
|
||||
7. Generate a solution hypothesis when appropriate
|
||||
8. Verify the hypothesis based on the Chain of Thought steps
|
||||
9. Repeat the process until satisfied with the solution
|
||||
10. Provide a single, ideally correct answer as the final output
|
||||
11. Only set next_thought_needed to false when truly done and a satisfactory answer is reached`
|
||||
|
||||
return &SequentialThinkingTool{
|
||||
BaseTool: NewBaseTool("thinking", description),
|
||||
thoughtHistory: make([]ThoughtData, 0),
|
||||
branches: make(map[string][]ThoughtData),
|
||||
}
|
||||
}
|
||||
|
||||
// Parameters returns the JSON schema for the tool's parameters
|
||||
func (t *SequentialThinkingTool) Parameters() map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"type": "object",
|
||||
"properties": map[string]interface{}{
|
||||
"thought": map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "Your current thinking step",
|
||||
},
|
||||
"nextThoughtNeeded": map[string]interface{}{
|
||||
"type": "boolean",
|
||||
"description": "Whether another thought step is needed",
|
||||
},
|
||||
"thoughtNumber": map[string]interface{}{
|
||||
"type": "integer",
|
||||
"description": "Current thought number (numeric value, e.g., 1, 2, 3)",
|
||||
"minimum": 1,
|
||||
},
|
||||
"totalThoughts": map[string]interface{}{
|
||||
"type": "integer",
|
||||
"description": "Estimated total thoughts needed (numeric value, e.g., 5, 10)",
|
||||
"minimum": 1,
|
||||
},
|
||||
"isRevision": map[string]interface{}{
|
||||
"type": "boolean",
|
||||
"description": "Whether this revises previous thinking",
|
||||
},
|
||||
"revisesThought": map[string]interface{}{
|
||||
"type": "integer",
|
||||
"description": "Which thought is being reconsidered",
|
||||
"minimum": 1,
|
||||
},
|
||||
"branchFromThought": map[string]interface{}{
|
||||
"type": "integer",
|
||||
"description": "Branching point thought number",
|
||||
"minimum": 1,
|
||||
},
|
||||
"branchId": map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "Branch identifier",
|
||||
},
|
||||
"needsMoreThoughts": map[string]interface{}{
|
||||
"type": "boolean",
|
||||
"description": "If more thoughts are needed",
|
||||
},
|
||||
},
|
||||
"required": []string{"thought", "nextThoughtNeeded", "thoughtNumber", "totalThoughts"},
|
||||
}
|
||||
}
|
||||
|
||||
// Execute executes the sequential thinking tool
|
||||
func (t *SequentialThinkingTool) Execute(ctx context.Context, args map[string]interface{}) (*types.ToolResult, error) {
|
||||
logger.Infof(ctx, "[Tool][SequentialThinking] Execute started")
|
||||
|
||||
// Validate and parse input
|
||||
thoughtData, err := t.validateThoughtData(args)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "[Tool][SequentialThinking] Validation failed: %v", err)
|
||||
return &types.ToolResult{
|
||||
Success: false,
|
||||
Error: fmt.Sprintf("Validation failed: %v", err),
|
||||
}, err
|
||||
}
|
||||
|
||||
// Adjust totalThoughts if thoughtNumber exceeds it
|
||||
if thoughtData.ThoughtNumber > thoughtData.TotalThoughts {
|
||||
thoughtData.TotalThoughts = thoughtData.ThoughtNumber
|
||||
}
|
||||
|
||||
// Add to thought history
|
||||
t.thoughtHistory = append(t.thoughtHistory, thoughtData)
|
||||
|
||||
// Handle branching
|
||||
if thoughtData.BranchFromThought != nil && thoughtData.BranchID != "" {
|
||||
if t.branches[thoughtData.BranchID] == nil {
|
||||
t.branches[thoughtData.BranchID] = make([]ThoughtData, 0)
|
||||
}
|
||||
t.branches[thoughtData.BranchID] = append(t.branches[thoughtData.BranchID], thoughtData)
|
||||
}
|
||||
|
||||
logger.Debugf(ctx, "[Tool][SequentialThinking] %s", thoughtData.Thought)
|
||||
|
||||
// Prepare response data
|
||||
branchKeys := make([]string, 0, len(t.branches))
|
||||
for k := range t.branches {
|
||||
branchKeys = append(branchKeys, k)
|
||||
}
|
||||
|
||||
responseData := map[string]interface{}{
|
||||
"thought_number": thoughtData.ThoughtNumber,
|
||||
"total_thoughts": thoughtData.TotalThoughts,
|
||||
"next_thought_needed": thoughtData.NextThoughtNeeded,
|
||||
"branches": branchKeys,
|
||||
"thought_history_length": len(t.thoughtHistory),
|
||||
"display_type": "thinking",
|
||||
"thought": thoughtData.Thought,
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[Tool][SequentialThinking] Execute completed - Thought %d/%d", thoughtData.ThoughtNumber, thoughtData.TotalThoughts)
|
||||
|
||||
return &types.ToolResult{
|
||||
Success: true,
|
||||
Output: "Thought process recorded",
|
||||
Data: responseData,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// validateThoughtData validates and parses the input arguments
|
||||
func (t *SequentialThinkingTool) validateThoughtData(input map[string]interface{}) (ThoughtData, error) {
|
||||
var data ThoughtData
|
||||
|
||||
// Validate thought (required)
|
||||
thought, ok := input["thought"].(string)
|
||||
if !ok || thought == "" {
|
||||
return data, fmt.Errorf("invalid thought: must be a non-empty string")
|
||||
}
|
||||
data.Thought = thought
|
||||
|
||||
// Validate thoughtNumber (required)
|
||||
thoughtNumber, ok := input["thoughtNumber"].(float64)
|
||||
if !ok {
|
||||
// Try int type
|
||||
if num, ok := input["thoughtNumber"].(int); ok {
|
||||
data.ThoughtNumber = num
|
||||
} else {
|
||||
return data, fmt.Errorf("invalid thoughtNumber: must be a number")
|
||||
}
|
||||
} else {
|
||||
data.ThoughtNumber = int(thoughtNumber)
|
||||
}
|
||||
if data.ThoughtNumber < 1 {
|
||||
return data, fmt.Errorf("invalid thoughtNumber: must be >= 1")
|
||||
}
|
||||
|
||||
// Validate totalThoughts (required)
|
||||
totalThoughts, ok := input["totalThoughts"].(float64)
|
||||
if !ok {
|
||||
// Try int type
|
||||
if num, ok := input["totalThoughts"].(int); ok {
|
||||
data.TotalThoughts = num
|
||||
} else {
|
||||
return data, fmt.Errorf("invalid totalThoughts: must be a number")
|
||||
}
|
||||
} else {
|
||||
data.TotalThoughts = int(totalThoughts)
|
||||
}
|
||||
if data.TotalThoughts < 1 {
|
||||
return data, fmt.Errorf("invalid totalThoughts: must be >= 1")
|
||||
}
|
||||
|
||||
// Validate nextThoughtNeeded (required)
|
||||
nextThoughtNeeded, ok := input["nextThoughtNeeded"].(bool)
|
||||
if !ok {
|
||||
return data, fmt.Errorf("invalid nextThoughtNeeded: must be a boolean")
|
||||
}
|
||||
data.NextThoughtNeeded = nextThoughtNeeded
|
||||
|
||||
// Optional fields
|
||||
if isRevision, ok := input["isRevision"].(bool); ok {
|
||||
data.IsRevision = isRevision
|
||||
}
|
||||
|
||||
if revisesThought, ok := input["revisesThought"].(float64); ok {
|
||||
num := int(revisesThought)
|
||||
data.RevisesThought = &num
|
||||
} else if revisesThought, ok := input["revisesThought"].(int); ok {
|
||||
data.RevisesThought = &revisesThought
|
||||
}
|
||||
|
||||
if branchFromThought, ok := input["branchFromThought"].(float64); ok {
|
||||
num := int(branchFromThought)
|
||||
data.BranchFromThought = &num
|
||||
} else if branchFromThought, ok := input["branchFromThought"].(int); ok {
|
||||
data.BranchFromThought = &branchFromThought
|
||||
}
|
||||
|
||||
if branchID, ok := input["branchId"].(string); ok {
|
||||
data.BranchID = branchID
|
||||
}
|
||||
|
||||
if needsMoreThoughts, ok := input["needsMoreThoughts"].(bool); ok {
|
||||
data.NeedsMoreThoughts = needsMoreThoughts
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// ThinkingTool implements the thinking tool functionality
|
||||
// This is a no-op tool inspired by code-agent and tau-bench
|
||||
// It logs thoughts for transparency and better decision-making
|
||||
type ThinkingTool struct {
|
||||
BaseTool
|
||||
}
|
||||
|
||||
// NewThinkingTool creates a new thinking tool instance
|
||||
func NewThinkingTool() *ThinkingTool {
|
||||
description := `Deep reasoning tool for systematic thinking. Use this frequently to analyze, plan, and reflect.
|
||||
|
||||
## Purpose
|
||||
|
||||
This tool helps you:
|
||||
- **Analyze problems** before acting
|
||||
- **Plan your approach** for complex tasks
|
||||
- **Evaluate results** after tool calls
|
||||
- **Reflect** on strategy and adjust
|
||||
|
||||
This is a no-op tool - it doesn't fetch data, but helps organize your reasoning transparently.
|
||||
|
||||
## When to Use
|
||||
|
||||
**Use frequently at key moments**:
|
||||
- **Start**: Analyze the question, understand what's needed
|
||||
- **Before major decisions**: Which tool to use? What query to run?
|
||||
- **After tool calls**: Evaluate results, decide next step
|
||||
- **Before answering**: Organize information, check completeness
|
||||
|
||||
## What to Think About
|
||||
|
||||
### At Start
|
||||
- What is the user really asking?
|
||||
- What information do I need?
|
||||
- What's my search strategy?
|
||||
|
||||
### After Search Results
|
||||
- Are results relevant? Complete?
|
||||
- Do I need more context (get_related_chunks)?
|
||||
- Should I search more or answer now?
|
||||
|
||||
### Before Answering
|
||||
- Do I have enough information?
|
||||
- Are all sources cited?
|
||||
- Is the structure clear?
|
||||
|
||||
|
||||
## Tips
|
||||
|
||||
- Use before important decisions
|
||||
- Keep thoughts focused and actionable
|
||||
- End with clear next step
|
||||
- Don't overthink simple queries`
|
||||
|
||||
return &ThinkingTool{
|
||||
BaseTool: NewBaseTool(
|
||||
"thinking",
|
||||
description,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
// Parameters returns the JSON schema for the tool's parameters
|
||||
func (t *ThinkingTool) Parameters() map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"type": "object",
|
||||
"properties": map[string]interface{}{
|
||||
"thought": map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "Your thinking process and reasoning content",
|
||||
},
|
||||
},
|
||||
"required": []string{"thought"},
|
||||
}
|
||||
}
|
||||
|
||||
// Execute executes the thinking tool
|
||||
func (t *ThinkingTool) Execute(ctx context.Context, args map[string]interface{}) (*types.ToolResult, error) {
|
||||
logger.Infof(ctx, "[Tool][Thinking] Execute started")
|
||||
|
||||
thought, ok := args["thought"].(string)
|
||||
if !ok {
|
||||
thought = "Thought content not provided"
|
||||
logger.Warnf(ctx, "[Tool][Thinking] No thought content provided")
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[Tool][Thinking] Thought length: %d characters", len(thought))
|
||||
logger.Debugf(ctx, "[Tool][Thinking] Thought content:\n%s", thought)
|
||||
|
||||
// This is a no-op tool - it just logs the thought
|
||||
// The thought itself is valuable for transparency and decision-making
|
||||
|
||||
// Format output for better display
|
||||
output := "Thought process recorded:\n\n"
|
||||
output += thought
|
||||
|
||||
logger.Infof(ctx, "[Tool][Thinking] Execute completed")
|
||||
return &types.ToolResult{
|
||||
Success: true,
|
||||
Output: output,
|
||||
Data: map[string]interface{}{
|
||||
"thought": thought,
|
||||
"display_type": "thinking",
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
@@ -25,172 +25,121 @@ type PlanStep struct {
|
||||
|
||||
// NewTodoWriteTool creates a new todo_write tool instance
|
||||
func NewTodoWriteTool() *TodoWriteTool {
|
||||
description := `Use this tool to create a structured, actionable plan for complex research tasks. This helps you organize multi-step investigations, track progress, and ensure comprehensive coverage.
|
||||
|
||||
## Critical Thinking Integration
|
||||
**IMPORTANT**: When working with complex research questions, you should typically use the **think tool** for deep analysis BEFORE creating your plan. This ensures:
|
||||
|
||||
- **Problem Analysis**: Use think tool to analyze the research question, identify key dimensions, and explore different angles
|
||||
- **Strategic Planning**: Use think tool to consider what information is needed, which knowledge bases to search, and potential challenges
|
||||
- **Scope Definition**: Use think tool to determine the depth and breadth of research required
|
||||
|
||||
The think tool helps ensure your plan is comprehensive, well-structured, and addresses all aspects of the research question effectively.
|
||||
description := `Use this tool to create and manage a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
|
||||
It also helps the user understand the progress of the task and overall progress of their requests.
|
||||
|
||||
## When to Use This Tool
|
||||
|
||||
Use this tool proactively in these scenarios:
|
||||
|
||||
1. **Complex multi-dimensional questions** - Questions requiring investigation of multiple aspects or dimensions
|
||||
2. **Comparison tasks** - When you need to compare multiple systems, approaches, or solutions systematically
|
||||
3. **Deep research tasks** - Questions requiring exploration of multiple knowledge areas or documents
|
||||
4. **Architecture analysis** - Tasks involving system design, architecture review, or technical deep-dives
|
||||
5. **User requests explicit planning** - When users ask for structured analysis or step-by-step investigation
|
||||
1. Complex multi-step tasks - When a task requires 3 or more distinct steps or actions
|
||||
2. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations
|
||||
3. User explicitly requests todo list - When the user directly asks you to use the todo list
|
||||
4. User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)
|
||||
5. After receiving new instructions - Immediately capture user requirements as todos
|
||||
6. When you start working on a task - Mark it as in_progress BEFORE beginning work. Ideally you should only have one todo as in_progress at a time
|
||||
7. After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation
|
||||
|
||||
## When NOT to Use This Tool
|
||||
|
||||
Skip using this tool when:
|
||||
1. There is only a single, straightforward task
|
||||
2. The task is trivial and tracking it provides no organizational benefit
|
||||
3. The task is purely conversational or informational
|
||||
|
||||
1. **Simple, direct queries** - Questions with straightforward answers (e.g., "What is a vector database?")
|
||||
2. **Single-step searches** - When you already know exactly what to search for
|
||||
3. **Mid-execution** - Don't create plans after you've already started searching
|
||||
4. **Trivial lookups** - Simple fact-finding that requires one tool call
|
||||
NOTE that you should not use this tool if there is only one trivial task to do. In this case you are better off just doing the task directly.
|
||||
|
||||
NOTE: If the question can be answered with 1-2 simple searches, skip planning and search directly.
|
||||
|
||||
## Examples of When to Use
|
||||
## Examples of When to Use the Todo List
|
||||
|
||||
<example>
|
||||
User: "如何设计一个高可用的微服务架构?需要考虑哪些方面?"
|
||||
Assistant: This is a complex, multi-dimensional question. Let me first think through the key aspects and then create a structured research plan.
|
||||
*Uses think tool to analyze: architecture patterns, reliability concerns, deployment strategies, monitoring needs*
|
||||
Assistant: Based on my analysis, let me create a research plan covering the main dimensions.
|
||||
*Creates plan with steps for:*
|
||||
1. Search microservices architecture patterns and best practices
|
||||
2. Investigate high availability strategies (load balancing, failover, redundancy)
|
||||
3. Research service mesh and communication patterns
|
||||
4. Explore monitoring and observability solutions
|
||||
5. Investigate deployment and scaling strategies
|
||||
*Begins executing the plan*
|
||||
User: I need to implement these features for my e-commerce site: user registration, product catalog, shopping cart, and checkout flow.
|
||||
Assistant: I'll help implement these features for your e-commerce site. Let me first think through the architecture and dependencies between these features to create an optimal implementation plan.
|
||||
*Uses think tool to analyze the e-commerce architecture, identify dependencies between features (user auth needed for cart, catalog needed for checkout), consider database design, security requirements, and implementation order*
|
||||
Assistant: After analyzing the system architecture and feature dependencies, let me create a strategic todo list that accounts for the interconnected nature of these features.
|
||||
*Creates a todo list breaking down each feature into specific tasks based on the project architecture and dependencies*
|
||||
Assistant: Let's start with user registration since it's foundational for the shopping cart and checkout features. This will involve creating database models, API endpoints, and frontend forms that integrate with your existing authentication system.
|
||||
|
||||
<reasoning>
|
||||
The assistant used both think and todo_write tools because:
|
||||
1. First used think tool to analyze the multi-dimensional nature of the question
|
||||
2. Identified key areas: architecture, availability, communication, monitoring, deployment
|
||||
3. Created a structured plan to ensure systematic coverage
|
||||
4. The plan helps avoid missing critical aspects of high availability
|
||||
1. First used think tool to analyze the complex e-commerce architecture and feature dependencies
|
||||
2. Considered the interconnected nature of features (user auth → cart → checkout)
|
||||
3. Analyzed security requirements, database design, and optimal implementation order
|
||||
4. Then created a strategic todo list that accounts for these dependencies
|
||||
5. This approach ensures features are implemented in the correct order with proper foundations
|
||||
</reasoning>
|
||||
</example>
|
||||
|
||||
<example>
|
||||
User: "对比Redis、Memcached和Hazelcast这三种缓存系统的性能、成本和适用场景"
|
||||
Assistant: This is a structured comparison task. Let me think through the comparison dimensions and create a systematic research plan.
|
||||
*Uses think tool to identify: performance metrics, cost factors, use case categories, comparison criteria*
|
||||
Assistant: I'll create a research plan to ensure fair, comprehensive comparison across all three systems.
|
||||
*Creates plan with steps:*
|
||||
1. Search Redis characteristics (performance, features, use cases)
|
||||
2. Search Memcached characteristics (performance, features, use cases)
|
||||
3. Search Hazelcast characteristics (performance, features, use cases)
|
||||
4. Search direct performance comparisons between these systems
|
||||
5. Investigate cost considerations and deployment complexity
|
||||
*Executes searches systematically*
|
||||
User: Can you help optimize my React application? It's rendering slowly and has performance issues.</user>
|
||||
Assistant: I'll help optimize your React application. First, let me examine your codebase to identify potential performance bottlenecks.
|
||||
*Reviews component structure, render patterns, state management, and data fetching*
|
||||
Assistant: After analyzing your codebase, I've identified several performance issues. Let me create a todo list to track our optimization efforts.
|
||||
*Creates todo list with items like: 1) Implement memoization for expensive calculations in ProductList, 2) Add virtualization for long lists in Dashboard, 3) Optimize image loading in Gallery component, 4) Fix state update loops in ShoppingCart, 5) Review bundle size and implement code splitting*
|
||||
Let's start by implementing memoization for the expensive calculations in your ProductList component.</assistant>
|
||||
|
||||
<reasoning>
|
||||
The assistant used todo_write because:
|
||||
1. Comparison tasks benefit from structured, parallel research
|
||||
2. The plan ensures each system is investigated equally
|
||||
3. Structured approach prevents bias toward any particular system
|
||||
4. Makes it easier to synthesize structured comparison at the end
|
||||
The assistant used the todo list because:
|
||||
1. First, the assistant examined the codebase to identify specific performance issues
|
||||
2. Based on this analysis, it identified multiple optimization opportunities
|
||||
3. Performance optimization is a non-trivial task requiring multiple steps
|
||||
4. The todo list helps methodically track improvements across different components
|
||||
5. This systematic approach ensures all performance bottlenecks are addressed
|
||||
</reasoning>
|
||||
</example>
|
||||
|
||||
## Examples of When NOT to Use
|
||||
## Examples of When NOT to Use the Todo List
|
||||
|
||||
<example>
|
||||
User: "向量数据库的主要用途是什么?"
|
||||
Assistant: Let me search for information about vector database use cases.
|
||||
*Uses knowledge_search directly without planning*
|
||||
User: How do I print 'Hello World' in Python?
|
||||
Assistant: In Python, you can print "Hello World" with this simple code:
|
||||
|
||||
print("Hello World")
|
||||
|
||||
This will output the text "Hello World" to the console when executed.</assistant>
|
||||
|
||||
<reasoning>
|
||||
The assistant skipped todo_write because:
|
||||
1. This is a simple, direct question
|
||||
2. One well-crafted search will likely provide the answer
|
||||
3. No need to organize multiple research steps
|
||||
4. Planning would add unnecessary overhead
|
||||
The assistant did not use the todo list because this is a single, trivial task that can be completed in one step. There's no need to track multiple tasks or steps for such a straightforward request.
|
||||
</reasoning>
|
||||
</example>
|
||||
|
||||
<example>
|
||||
User: "Kubernetes是什么?"
|
||||
Assistant: Let me search for information about Kubernetes.
|
||||
*Uses knowledge_search directly*
|
||||
User: What does the git status command do?
|
||||
Assistant: The git status command shows the current state of your working directory and staging area. It displays which changes have been staged, which haven't, and which files aren't being tracked by Git. This is a fundamental command for understanding the current state of your repository before making commits.
|
||||
|
||||
<reasoning>
|
||||
Simple definitional question - just search directly without planning.
|
||||
The assistant did not use the todo list because this is an informational request with no actual coding task to complete. The user is simply asking for an explanation, not for the assistant to perform multiple steps or tasks.
|
||||
</reasoning>
|
||||
</example>
|
||||
|
||||
## Standard Workflow
|
||||
## Task States and Management
|
||||
|
||||
The recommended workflow when using this tool:
|
||||
1. **Task States**: Use these states to track progress:
|
||||
- pending: Task not yet started
|
||||
- in_progress: Currently working on (limit to ONE task at a time)
|
||||
- completed: Task finished successfully
|
||||
|
||||
` + "```" + `
|
||||
Step 1: User asks complex question
|
||||
↓
|
||||
Step 2: Use think tool (analyze problem, identify dimensions, consider approaches)
|
||||
↓
|
||||
Step 3: Use todo_write tool (create structured plan with steps, tools, priorities) [OPTIONAL]
|
||||
↓
|
||||
Step 4: Execute plan steps (use search tools, mark progress)
|
||||
↓
|
||||
Step 5: Use think tool (evaluate results, identify gaps)
|
||||
↓
|
||||
Step 6: Adjust plan or execute remaining steps
|
||||
↓
|
||||
Step 7: Synthesize comprehensive answer with citations
|
||||
` + "```" + `
|
||||
2. **Task Management**:
|
||||
- Update task status in real-time as you work
|
||||
- Mark tasks complete IMMEDIATELY after finishing (don't batch completions)
|
||||
- Only have ONE task in_progress at any time
|
||||
- Complete current tasks before starting new ones
|
||||
- Remove tasks that are no longer relevant from the list entirely
|
||||
|
||||
## Plan Structure
|
||||
3. **Task Completion Requirements**:
|
||||
- ONLY mark a task as completed when you have FULLY accomplished it
|
||||
- If you encounter errors, blockers, or cannot finish, keep the task as in_progress
|
||||
- When blocked, create a new task describing what needs to be resolved
|
||||
- Never mark a task as completed if:
|
||||
- Tests are failing
|
||||
- Implementation is partial
|
||||
- You encountered unresolved errors
|
||||
- You couldn't find necessary files or dependencies
|
||||
|
||||
Your plan should include steps with:
|
||||
- **ID**: Unique identifier for each step (e.g., "step1", "step2")
|
||||
- **Description**: Clear description of what to investigate
|
||||
- **Tools to Use**: Which tools to use (e.g., "knowledge_search", "get_related_chunks")
|
||||
- **Status**: Current status (pending, in_progress, completed, skipped)
|
||||
4. **Task Breakdown**:
|
||||
- Create specific, actionable items
|
||||
- Break complex tasks into smaller, manageable steps
|
||||
- Use clear, descriptive task names
|
||||
|
||||
## Step Status Management
|
||||
|
||||
1. **Status Values**:
|
||||
- **pending**: Step not yet started (default for new steps)
|
||||
- **in_progress**: Currently executing this step
|
||||
- **completed**: Step finished successfully with results
|
||||
- **skipped**: Step determined to be unnecessary based on findings
|
||||
|
||||
2. **Status Management Best Practices**:
|
||||
- Start with all steps as "pending"
|
||||
- Mark one step as "in_progress" before executing it
|
||||
- Update to "completed" immediately after finishing
|
||||
- Mark as "skipped" if findings make a step unnecessary
|
||||
|
||||
## Parameters
|
||||
|
||||
- **task** (required): The complex task or question you need to create a plan for
|
||||
- Be specific about what needs to be accomplished
|
||||
- Include the user's actual question or research goal
|
||||
|
||||
- **steps** (required): Array of plan steps, each containing:
|
||||
- **id**: Unique identifier (e.g., "step1", "step2")
|
||||
- **description**: What to investigate or accomplish
|
||||
- **tools_to_use**: Suggested tools for this step
|
||||
- **status**: Current status (pending, in_progress, completed, skipped)
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Think First**: Always use think tool before creating a plan to ensure thorough analysis
|
||||
2. **Be Specific**: Each step should have a clear, actionable objective
|
||||
3. **Stay Flexible**: Adjust the plan based on findings - some steps may become unnecessary
|
||||
4. **Track Progress**: Update step status as you work through the plan
|
||||
5. **Don't Over-plan**: 3-7 steps is usually sufficient; more suggests over-complexity
|
||||
`
|
||||
When in doubt, use this tool. Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully.`
|
||||
|
||||
return &TodoWriteTool{
|
||||
BaseTool: NewBaseTool("todo_write", description),
|
||||
@@ -229,8 +178,8 @@ func (t *TodoWriteTool) Parameters() map[string]interface{} {
|
||||
},
|
||||
"status": map[string]interface{}{
|
||||
"type": "string",
|
||||
"enum": []string{"pending", "in_progress", "completed", "skipped"},
|
||||
"description": "Current status: pending (not started), in_progress (executing), completed (finished), skipped (unnecessary)",
|
||||
"enum": []string{"pending", "in_progress", "completed"},
|
||||
"description": "Current status: pending (not started), in_progress (executing), completed (finished)",
|
||||
},
|
||||
},
|
||||
"required": []string{"id", "description", "status"},
|
||||
|
||||
@@ -0,0 +1,564 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/PuerkitoBio/goquery"
|
||||
"github.com/chromedp/chromedp"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
const (
|
||||
webFetchTimeout = 60 * time.Second
|
||||
webFetchMaxChars = 100000
|
||||
)
|
||||
|
||||
type webFetchParams struct {
|
||||
URL string
|
||||
Prompt string
|
||||
}
|
||||
|
||||
type webFetchItemResult struct {
|
||||
output string
|
||||
data map[string]interface{}
|
||||
err error
|
||||
}
|
||||
|
||||
// WebFetchTool 拉取网页内容并根据提示执行总结
|
||||
type WebFetchTool struct {
|
||||
BaseTool
|
||||
client *http.Client
|
||||
chatModel chat.Chat
|
||||
}
|
||||
|
||||
// NewWebFetchTool 创建 web_fetch 工具实例
|
||||
func NewWebFetchTool(chatModel chat.Chat) *WebFetchTool {
|
||||
description := `Fetch web content from previously discovered URLs and analyze it with an LLM.
|
||||
|
||||
## 流程
|
||||
- 接收一个或多个 {url, prompt} 组合
|
||||
- 抓取网页内容并转换为 Markdown 文本
|
||||
- 使用提示词调用小模型进行分析与总结(若模型可用)
|
||||
- 返回总结结果与原始内容片段
|
||||
|
||||
## 使用场景
|
||||
- 对 web_search 返回的链接做进一步深入阅读
|
||||
- 从网页中提取结构化信息或关键信息
|
||||
|
||||
## 参数
|
||||
- items (必填): 数组,元素为 { "url": "...", "prompt": "..." }
|
||||
`
|
||||
|
||||
return &WebFetchTool{
|
||||
BaseTool: NewBaseTool("web_fetch", description),
|
||||
client: &http.Client{
|
||||
Timeout: webFetchTimeout,
|
||||
},
|
||||
chatModel: chatModel,
|
||||
}
|
||||
}
|
||||
|
||||
// Parameters 返回工具参数的 JSON Schema
|
||||
func (t *WebFetchTool) Parameters() map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"type": "object",
|
||||
"properties": map[string]interface{}{
|
||||
"items": map[string]interface{}{
|
||||
"type": "array",
|
||||
"description": "批量抓取任务,每项包含 url 与 prompt",
|
||||
"items": map[string]interface{}{
|
||||
"type": "object",
|
||||
"properties": map[string]interface{}{
|
||||
"url": map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "待抓取的网页 URL,需来自 web_search 结果",
|
||||
},
|
||||
"prompt": map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "分析该网页内容时使用的提示词",
|
||||
},
|
||||
},
|
||||
"required": []string{"url", "prompt"},
|
||||
},
|
||||
"minItems": 1,
|
||||
},
|
||||
},
|
||||
"required": []string{"items"},
|
||||
}
|
||||
}
|
||||
|
||||
// Execute 执行 web_fetch 工具
|
||||
func (t *WebFetchTool) Execute(ctx context.Context, args map[string]interface{}) (*types.ToolResult, error) {
|
||||
logger.Infof(ctx, "[Tool][WebFetch] Execute started")
|
||||
|
||||
rawItems, ok := args["items"]
|
||||
if !ok {
|
||||
logger.Errorf(ctx, "[Tool][WebFetch] 参数缺失: items")
|
||||
return &types.ToolResult{
|
||||
Success: false,
|
||||
Error: "missing required parameter: items",
|
||||
}, nil
|
||||
}
|
||||
|
||||
itemsSlice, ok := rawItems.([]interface{})
|
||||
if !ok || len(itemsSlice) == 0 {
|
||||
logger.Errorf(ctx, "[Tool][WebFetch] items 解析失败或为空: %#v", rawItems)
|
||||
return &types.ToolResult{
|
||||
Success: false,
|
||||
Error: "'items' must be a non-empty array",
|
||||
}, nil
|
||||
}
|
||||
|
||||
results := make([]*webFetchItemResult, len(itemsSlice))
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(len(itemsSlice))
|
||||
|
||||
for idx := range itemsSlice {
|
||||
i := idx
|
||||
itemAny := itemsSlice[i]
|
||||
|
||||
params := t.parseParams(itemAny)
|
||||
|
||||
go func(index int, p webFetchParams) {
|
||||
defer wg.Done()
|
||||
|
||||
if err := t.validateParams(p); err != nil {
|
||||
results[index] = &webFetchItemResult{
|
||||
err: err,
|
||||
data: map[string]interface{}{
|
||||
"url": p.URL,
|
||||
"prompt": p.Prompt,
|
||||
"error": err.Error(),
|
||||
},
|
||||
output: fmt.Sprintf("URL: %s\n错误: %v\n\n", p.URL, err),
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
output, data, err := t.executeFetch(ctx, p)
|
||||
results[index] = &webFetchItemResult{
|
||||
output: output,
|
||||
data: data,
|
||||
err: err,
|
||||
}
|
||||
}(i, params)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
var builder strings.Builder
|
||||
builder.WriteString("=== Web Fetch Results ===\n\n")
|
||||
|
||||
aggregated := make([]map[string]interface{}, 0, len(results))
|
||||
success := true
|
||||
var firstErr error
|
||||
|
||||
for idx, res := range results {
|
||||
if res == nil {
|
||||
success = false
|
||||
if firstErr == nil {
|
||||
firstErr = fmt.Errorf("fetch item %d returned nil", idx)
|
||||
}
|
||||
builder.WriteString(fmt.Sprintf("#%d: 无结果(内部错误)\n\n", idx+1))
|
||||
continue
|
||||
}
|
||||
|
||||
builder.WriteString(fmt.Sprintf("#%d:\n%s", idx+1, res.output))
|
||||
if !strings.HasSuffix(res.output, "\n") {
|
||||
builder.WriteString("\n")
|
||||
}
|
||||
builder.WriteString("\n")
|
||||
|
||||
if res.data != nil {
|
||||
aggregated = append(aggregated, res.data)
|
||||
}
|
||||
|
||||
if res.err != nil {
|
||||
success = false
|
||||
if firstErr == nil {
|
||||
firstErr = res.err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data := map[string]interface{}{
|
||||
"results": aggregated,
|
||||
"count": len(aggregated),
|
||||
"display_type": "web_fetch_results",
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[Tool][WebFetch] Completed with success=%v, items=%d", success, len(aggregated))
|
||||
|
||||
return &types.ToolResult{
|
||||
Success: success,
|
||||
Output: builder.String(),
|
||||
Data: data,
|
||||
Error: func() string {
|
||||
if firstErr != nil {
|
||||
return firstErr.Error()
|
||||
}
|
||||
return ""
|
||||
}(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (t *WebFetchTool) parseParams(item interface{}) webFetchParams {
|
||||
params := webFetchParams{}
|
||||
if m, ok := item.(map[string]interface{}); ok {
|
||||
if v, ok := m["url"].(string); ok {
|
||||
params.URL = strings.TrimSpace(v)
|
||||
}
|
||||
if v, ok := m["prompt"].(string); ok {
|
||||
params.Prompt = strings.TrimSpace(v)
|
||||
}
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func (t *WebFetchTool) validateParams(p webFetchParams) error {
|
||||
if p.URL == "" {
|
||||
return fmt.Errorf("url is required")
|
||||
}
|
||||
if p.Prompt == "" {
|
||||
return fmt.Errorf("prompt is required")
|
||||
}
|
||||
if !strings.HasPrefix(p.URL, "http://") && !strings.HasPrefix(p.URL, "https://") {
|
||||
return fmt.Errorf("invalid URL format")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *WebFetchTool) executeFetch(ctx context.Context, params webFetchParams) (string, map[string]interface{}, error) {
|
||||
logger.Infof(ctx, "[Tool][WebFetch] Fetching URL: %s", params.URL)
|
||||
|
||||
finalURL := t.normalizeGitHubURL(params.URL)
|
||||
|
||||
htmlContent, method, err := t.fetchHTMLContent(ctx, finalURL)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "[Tool][WebFetch] 获取页面失败 url=%s err=%v", finalURL, err)
|
||||
return fmt.Sprintf("URL: %s\n错误: %v\n", params.URL, err),
|
||||
map[string]interface{}{
|
||||
"url": params.URL,
|
||||
"prompt": params.Prompt,
|
||||
"error": err.Error(),
|
||||
}, err
|
||||
}
|
||||
|
||||
textContent := t.convertHTMLToText(htmlContent)
|
||||
|
||||
resultData := map[string]interface{}{
|
||||
"url": params.URL,
|
||||
"prompt": params.Prompt,
|
||||
"raw_content": textContent,
|
||||
"content_length": len(textContent),
|
||||
"method": method,
|
||||
}
|
||||
var summary string
|
||||
var summaryErr error
|
||||
summary, summaryErr = t.processWithLLM(ctx, params, textContent)
|
||||
if summaryErr != nil {
|
||||
logger.Warnf(ctx, "[Tool][WebFetch] LLM 处理失败 url=%s err=%v", params.URL, summaryErr)
|
||||
} else if summary != "" {
|
||||
resultData["summary"] = summary
|
||||
}
|
||||
|
||||
output := t.buildOutputText(params, textContent, summary, summaryErr)
|
||||
|
||||
return output, resultData, summaryErr
|
||||
}
|
||||
|
||||
func (t *WebFetchTool) normalizeGitHubURL(source string) string {
|
||||
if strings.Contains(source, "github.com") && strings.Contains(source, "/blob/") {
|
||||
source = strings.Replace(source, "github.com", "raw.githubusercontent.com", 1)
|
||||
source = strings.Replace(source, "/blob/", "/", 1)
|
||||
}
|
||||
return source
|
||||
}
|
||||
|
||||
func (t *WebFetchTool) processWithLLM(ctx context.Context, params webFetchParams, content string) (string, error) {
|
||||
if t.chatModel == nil {
|
||||
return "", fmt.Errorf("chat model not available for web_fetch")
|
||||
}
|
||||
|
||||
systemMessage := "你是一名擅长阅读网页内容的智能助手,请根据提供的网页文本回答用户需求,严禁编造未在文本中出现的信息。"
|
||||
userTemplate := `用户请求:
|
||||
%s
|
||||
|
||||
网页内容:
|
||||
%s`
|
||||
|
||||
messages := []chat.Message{
|
||||
{
|
||||
Role: "system",
|
||||
Content: systemMessage,
|
||||
},
|
||||
{
|
||||
Role: "user",
|
||||
Content: fmt.Sprintf(userTemplate, params.Prompt, content),
|
||||
},
|
||||
}
|
||||
|
||||
response, err := t.chatModel.Chat(ctx, messages, &chat.ChatOptions{
|
||||
Temperature: 0.3,
|
||||
MaxTokens: 1024,
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return strings.TrimSpace(response.Content), nil
|
||||
}
|
||||
|
||||
func (t *WebFetchTool) buildOutputText(params webFetchParams, content string, summary string, summaryErr error) string {
|
||||
var builder strings.Builder
|
||||
builder.WriteString(fmt.Sprintf("URL: %s\n", params.URL))
|
||||
builder.WriteString(fmt.Sprintf("Prompt: %s\n", params.Prompt))
|
||||
|
||||
if summaryErr == nil && summary != "" {
|
||||
builder.WriteString("Summary:\n")
|
||||
builder.WriteString(summary)
|
||||
builder.WriteString("\n")
|
||||
} else {
|
||||
builder.WriteString("Content Preview:\n")
|
||||
builder.WriteString(content)
|
||||
builder.WriteString("\n")
|
||||
}
|
||||
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
func (t *WebFetchTool) fetchHTMLContent(ctx context.Context, targetURL string) (string, string, error) {
|
||||
html, err := t.fetchWithChromedp(ctx, targetURL)
|
||||
if err == nil && strings.TrimSpace(html) != "" {
|
||||
return html, "chromedp", nil
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
logger.Debugf(ctx, "[Tool][WebFetch] Chromedp 抓取失败 url=%s err=%v,尝试直接请求", targetURL, err)
|
||||
}
|
||||
|
||||
html, httpErr := t.fetchWithHTTP(ctx, targetURL)
|
||||
if httpErr != nil {
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("chromedp error: %v; http error: %w", err, httpErr)
|
||||
}
|
||||
return "", "", httpErr
|
||||
}
|
||||
|
||||
return html, "http", nil
|
||||
}
|
||||
|
||||
func (t *WebFetchTool) fetchWithChromedp(ctx context.Context, targetURL string) (string, error) {
|
||||
logger.Debugf(ctx, "[Tool][WebFetch] Chromedp 抓取开始 url=%s", targetURL)
|
||||
|
||||
opts := append(chromedp.DefaultExecAllocatorOptions[:],
|
||||
chromedp.Flag("headless", true),
|
||||
chromedp.Flag("disable-setuid-sandbox", true),
|
||||
chromedp.Flag("disable-dev-shm-usage", true),
|
||||
chromedp.Flag("disable-gpu", true),
|
||||
chromedp.Flag("disable-blink-features", "AutomationControlled"),
|
||||
chromedp.Flag("disable-features", "VizDisplayCompositor"),
|
||||
chromedp.UserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"),
|
||||
)
|
||||
|
||||
allocCtx, cancel := chromedp.NewExecAllocator(ctx, opts...)
|
||||
defer cancel()
|
||||
|
||||
ctx, cancel = chromedp.NewContext(allocCtx)
|
||||
defer cancel()
|
||||
|
||||
ctx, cancel = context.WithTimeout(ctx, webFetchTimeout)
|
||||
defer cancel()
|
||||
|
||||
var html string
|
||||
err := chromedp.Run(ctx,
|
||||
chromedp.Navigate(targetURL),
|
||||
chromedp.WaitReady("body", chromedp.ByQuery),
|
||||
chromedp.OuterHTML("html", &html),
|
||||
)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("chromedp run failed: %w", err)
|
||||
}
|
||||
|
||||
logger.Debugf(ctx, "[Tool][WebFetch] Chromedp 抓取成功 url=%s", targetURL)
|
||||
return html, nil
|
||||
}
|
||||
|
||||
func (t *WebFetchTool) fetchWithHTTP(ctx context.Context, targetURL string) (string, error) {
|
||||
resp, err := t.fetchWithTimeout(ctx, targetURL)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("request failed with status %d %s", resp.StatusCode, resp.Status)
|
||||
}
|
||||
|
||||
limitedReader := io.LimitReader(resp.Body, webFetchMaxChars*2)
|
||||
htmlBytes, err := io.ReadAll(limitedReader)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read response body: %w", err)
|
||||
}
|
||||
|
||||
return string(htmlBytes), nil
|
||||
}
|
||||
|
||||
func (t *WebFetchTool) fetchWithTimeout(ctx context.Context, targetURL string) (*http.Response, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, targetURL, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
|
||||
req.Header.Set("User-Agent", "Mozilla/5.0 (compatible; WebFetchTool/1.0)")
|
||||
req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8")
|
||||
req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
|
||||
req.Header.Set("Cache-Control", "no-cache")
|
||||
|
||||
return t.client.Do(req)
|
||||
}
|
||||
|
||||
func (t *WebFetchTool) convertHTMLToText(html string) string {
|
||||
doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
|
||||
if err != nil {
|
||||
return t.basicTextExtraction(html)
|
||||
}
|
||||
|
||||
doc.Find("script, style, nav, footer, header").Remove()
|
||||
|
||||
var markdown strings.Builder
|
||||
doc.Find("body").Each(func(i int, body *goquery.Selection) {
|
||||
t.processNode(body, &markdown)
|
||||
})
|
||||
|
||||
result := markdown.String()
|
||||
result = regexp.MustCompile(`\n{3,}`).ReplaceAllString(result, "\n\n")
|
||||
return strings.TrimSpace(result)
|
||||
}
|
||||
|
||||
func (t *WebFetchTool) processNode(s *goquery.Selection, markdown *strings.Builder) {
|
||||
s.Contents().Each(func(i int, node *goquery.Selection) {
|
||||
nodeName := goquery.NodeName(node)
|
||||
|
||||
switch nodeName {
|
||||
case "h1", "h2", "h3", "h4", "h5", "h6":
|
||||
headerLevel := int(nodeName[1] - '0')
|
||||
markdown.WriteString("\n")
|
||||
markdown.WriteString(strings.Repeat("#", headerLevel))
|
||||
markdown.WriteString(" ")
|
||||
markdown.WriteString(strings.TrimSpace(node.Text()))
|
||||
markdown.WriteString("\n\n")
|
||||
case "p":
|
||||
t.processNode(node, markdown)
|
||||
markdown.WriteString("\n\n")
|
||||
case "a":
|
||||
href, exists := node.Attr("href")
|
||||
text := strings.TrimSpace(node.Text())
|
||||
if exists && text != "" {
|
||||
markdown.WriteString("[")
|
||||
markdown.WriteString(text)
|
||||
markdown.WriteString("](")
|
||||
markdown.WriteString(href)
|
||||
markdown.WriteString(")")
|
||||
} else if text != "" {
|
||||
markdown.WriteString(text)
|
||||
}
|
||||
case "img":
|
||||
src, _ := node.Attr("src")
|
||||
alt, _ := node.Attr("alt")
|
||||
if src != "" {
|
||||
markdown.WriteString("
|
||||
markdown.WriteString(src)
|
||||
markdown.WriteString(")\n\n")
|
||||
}
|
||||
case "ul", "ol":
|
||||
markdown.WriteString("\n")
|
||||
isOrdered := nodeName == "ol"
|
||||
node.Find("li").Each(func(idx int, li *goquery.Selection) {
|
||||
if isOrdered {
|
||||
markdown.WriteString(fmt.Sprintf("%d. ", idx+1))
|
||||
} else {
|
||||
markdown.WriteString("- ")
|
||||
}
|
||||
markdown.WriteString(strings.TrimSpace(li.Text()))
|
||||
markdown.WriteString("\n")
|
||||
})
|
||||
markdown.WriteString("\n")
|
||||
case "br":
|
||||
markdown.WriteString("\n")
|
||||
case "code":
|
||||
parent := node.Parent()
|
||||
if goquery.NodeName(parent) == "pre" {
|
||||
markdown.WriteString("\n```\n")
|
||||
markdown.WriteString(node.Text())
|
||||
markdown.WriteString("\n```\n\n")
|
||||
} else {
|
||||
markdown.WriteString("`")
|
||||
markdown.WriteString(node.Text())
|
||||
markdown.WriteString("`")
|
||||
}
|
||||
case "blockquote":
|
||||
lines := strings.Split(strings.TrimSpace(node.Text()), "\n")
|
||||
for _, line := range lines {
|
||||
markdown.WriteString("> ")
|
||||
markdown.WriteString(strings.TrimSpace(line))
|
||||
markdown.WriteString("\n")
|
||||
}
|
||||
markdown.WriteString("\n")
|
||||
case "strong", "b":
|
||||
markdown.WriteString("**")
|
||||
markdown.WriteString(strings.TrimSpace(node.Text()))
|
||||
markdown.WriteString("**")
|
||||
case "em", "i":
|
||||
markdown.WriteString("*")
|
||||
markdown.WriteString(strings.TrimSpace(node.Text()))
|
||||
markdown.WriteString("*")
|
||||
case "hr":
|
||||
markdown.WriteString("\n---\n\n")
|
||||
case "table":
|
||||
markdown.WriteString("\n")
|
||||
node.Find("tr").Each(func(idx int, tr *goquery.Selection) {
|
||||
tr.Find("th, td").Each(func(i int, cell *goquery.Selection) {
|
||||
markdown.WriteString("| ")
|
||||
markdown.WriteString(strings.TrimSpace(cell.Text()))
|
||||
markdown.WriteString(" ")
|
||||
})
|
||||
markdown.WriteString("|\n")
|
||||
if idx == 0 {
|
||||
tr.Find("th").Each(func(i int, _ *goquery.Selection) {
|
||||
markdown.WriteString("|---")
|
||||
})
|
||||
markdown.WriteString("|\n")
|
||||
}
|
||||
})
|
||||
markdown.WriteString("\n")
|
||||
case "#text":
|
||||
text := node.Text()
|
||||
if strings.TrimSpace(text) != "" {
|
||||
markdown.WriteString(text)
|
||||
}
|
||||
default:
|
||||
t.processNode(node, markdown)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (t *WebFetchTool) basicTextExtraction(html string) string {
|
||||
re := regexp.MustCompile(`<[^>]*>`)
|
||||
text := re.ReplaceAllString(html, " ")
|
||||
text = regexp.MustCompile(`\s+`).ReplaceAllString(text, " ")
|
||||
return strings.TrimSpace(text)
|
||||
}
|
||||
Reference in New Issue
Block a user