refactor: Remove agent_test command-line tool and associated files to streamline project structure and eliminate unused components

This commit is contained in:
wizardchen
2025-12-01 17:24:57 +08:00
parent 60241a2d29
commit 93af4460d6
40 changed files with 387 additions and 1692 deletions
-75
View File
@@ -1,75 +0,0 @@
.PHONY: build run clean help
# Binary name
BINARY=agent_test
# Build parameters
GOOS?=$(shell go env GOOS)
GOARCH?=$(shell go env GOARCH)
# Default target
all: build
# Build the binary
build:
@echo "Building $(BINARY)..."
@go build -o $(BINARY) .
@echo "Build complete: ./$(BINARY)"
# Build and run with default settings
run: build
@./$(BINARY)
# Run with custom parameters
run-local: build
@./$(BINARY) -url http://localhost:8080 -kb $(KB_ID)
# Run with existing session
run-session: build
@./$(BINARY) -url http://localhost:8080 -session $(SESSION_ID)
# Clean build artifacts
clean:
@echo "Cleaning..."
@rm -f $(BINARY)
@echo "Clean complete"
# Install dependencies
deps:
@echo "Installing dependencies..."
@go mod download
@go mod tidy
@echo "Dependencies installed"
# Run tests
test:
@go test -v ./...
# Build for multiple platforms
build-all:
@echo "Building for multiple platforms..."
@GOOS=linux GOARCH=amd64 go build -o $(BINARY)-linux-amd64 .
@GOOS=darwin GOARCH=amd64 go build -o $(BINARY)-darwin-amd64 .
@GOOS=darwin GOARCH=arm64 go build -o $(BINARY)-darwin-arm64 .
@GOOS=windows GOARCH=amd64 go build -o $(BINARY)-windows-amd64.exe .
@echo "Build complete for all platforms"
# Help
help:
@echo "Available targets:"
@echo " make build - Build the binary"
@echo " make run - Build and run with no parameters"
@echo " make run-local - Build and run with local server (requires KB_ID env var)"
@echo " make run-session - Build and run with existing session (requires SESSION_ID env var)"
@echo " make clean - Remove build artifacts"
@echo " make deps - Install dependencies"
@echo " make test - Run tests"
@echo " make build-all - Build for multiple platforms"
@echo " make help - Show this help message"
@echo ""
@echo "Examples:"
@echo " make build"
@echo " KB_ID=kb_123 make run-local"
@echo " SESSION_ID=sess_456 make run-session"
@echo " ./$(BINARY) -url http://localhost:8080 -kb kb_123 -token mytoken"
-293
View File
@@ -1,293 +0,0 @@
# Quick Start Guide
Get started with the WeKnora Agent Test Tool in 5 minutes!
## Prerequisites
- Go 1.21 or higher
- Access to a running WeKnora instance
- A knowledge base ID (or create one through the tool)
## Quick Start
### Option 1: Using the Build Script (Recommended)
```bash
# 1. Navigate to the tool directory
cd client/cmd/agent_test
# 2. Build and run with your knowledge base
./run.sh -k kb_your_knowledge_base_id
# Or with a remote server
./run.sh -u https://api.weknora.com -k kb_12345 -t your_token
```
### Option 2: Using Make
```bash
# Build the binary
make build
# Run with environment variables
KB_ID=kb_12345 make run-local
# Or run the binary directly
./agent_test -url http://localhost:8080 -kb kb_12345
```
### Option 3: Direct Go Build
```bash
# Build
go build -o agent_test .
# Run
./agent_test -url http://localhost:8080 -kb kb_your_knowledge_base_id
```
## First Steps
Once the tool is running, you'll see an interactive prompt:
```
╔════════════════════════════════════════════════════════════╗
║ WeKnora Agent QA Testing Tool ║
╚════════════════════════════════════════════════════════════╝
[No Session] >
```
### 1. Create a New Session
```
> new
```
The tool will create a new session and show you the session ID.
### 2. Ask Your First Question
```
[Session: abc12345] > ask What is machine learning?
```
You'll see real-time output showing:
- 💭 Agent thinking process
- 🔧 Tool calls (if any)
- 📚 Knowledge references
- 📝 Final answer
- 🤔 Reflections (if any)
### 3. Continue the Conversation
```
[Session: abc12345] > ask Can you give me examples?
[Session: abc12345] > ask How does it work?
```
### 4. View Session Info
```
[Session: abc12345] > info
```
### 5. List All Sessions
```
[Session: abc12345] > sessions
```
### 6. Exit
```
[Session: abc12345] > exit
```
## Command Reference
| Command | Description | Example |
|---------|-------------|---------|
| `new` | Create a new session | `> new` |
| `ask <query>` | Ask the agent a question | `> ask What is AI?` |
| `info` | Show current session details | `> info` |
| `sessions` | List all your sessions | `> sessions` |
| `switch <id>` | Switch to another session | `> switch sess_123` |
| `help` | Show help message | `> help` |
| `exit` or `quit` | Exit the program | `> exit` |
## Example Session
```bash
$ ./run.sh -k kb_ml_docs
[No Session] > new
✓ Session created successfully!
Session ID: sess_a1b2c3d4
Knowledge Base: kb_ml_docs
Created At: 2025-11-03T10:00:00Z
[Session: sess_a1b] > ask What is a neural network?
╔═══ Agent Processing ═══╗
Query: What is a neural network?
💭 Thinking: I need to search the knowledge base for information about neural networks...
🔧 Tool Call: search_knowledge
Arguments: map[query:neural network definition]
✓ Tool Result:
Found 3 relevant knowledge chunks
📚 Knowledge References: Found 3 reference(s)
1. [Score: 0.892] A neural network is a series of algorithms...
Knowledge: Neural Networks 101 (Chunk: 2)
2. [Score: 0.856] Neural networks mimic biological neurons...
Knowledge: Deep Learning Basics (Chunk: 5)
3. [Score: 0.834] The structure consists of layers...
Knowledge: ML Architectures (Chunk: 8)
📝 Final Answer:
A neural network is a computing system inspired by biological neural networks
in animal brains. It consists of interconnected nodes (artificial neurons)
organized in layers that process information using a connectionist approach
to computation. Neural networks learn to perform tasks by considering examples,
generally without being programmed with task-specific rules.
🤔 Reflection: I successfully found relevant information in the knowledge base
and provided a comprehensive answer covering the definition, structure, and
learning mechanism of neural networks.
╔═══ Summary ═══╗
Duration: 2.34s
Tool Calls: 1 (search_knowledge)
References: 3
Reflections: 1
╚═══════════════╝
[Session: sess_a1b] > ask What are the main types?
╔═══ Agent Processing ═══╗
Query: What are the main types?
💭 Thinking: The user is asking about types of neural networks based on the
previous context...
[... continuing the conversation ...]
```
## Testing Scenarios
We provide a test scenarios script for common testing patterns:
```bash
# Run interactive scenario menu
./test_scenarios.sh
# Run a specific scenario
./test_scenarios.sh 1 # Basic Q&A
./test_scenarios.sh 2 # Complex queries
./test_scenarios.sh 3 # Multi-turn conversation
```
## Configuration with Environment Variables
Create a configuration file for repeated use:
```bash
# Create config file
cat > config.env << EOF
export WEKNORA_URL=http://localhost:8080
export WEKNORA_KB_ID=kb_your_knowledge_base_id
export WEKNORA_TOKEN=your_token_if_needed
EOF
# Load and run
source config.env
./run.sh
```
## Troubleshooting
### "Connection refused"
- Make sure WeKnora server is running
- Check the URL is correct
- Verify network connectivity
### "Knowledge base not found"
- Verify your knowledge base ID is correct
- Check you have access to the knowledge base
- Ensure the knowledge base has been initialized
### "Session not found"
- The session may have expired or been deleted
- Create a new session with `new` command
### No tool calls happening
- Check your knowledge base has content
- Verify the agent configuration includes tool definitions
- Look for error messages in the output
## Advanced Usage
### Using with Docker
If WeKnora is running in Docker:
```bash
# Get the container's IP or use host networking
./agent_test -url http://localhost:8080 -kb kb_123
```
### Testing with Production
```bash
# Use production URL with authentication
./agent_test \
-url https://api.weknora.com \
-token $PROD_TOKEN \
-kb kb_prod_123
```
### Continuing an Existing Session
```bash
# Skip session creation and continue existing one
./agent_test -url http://localhost:8080 -session sess_existing_id
```
### Batch Testing
```bash
# Pipe commands for automated testing
echo -e "new\nask What is AI?\ninfo\nexit" | ./agent_test -url http://localhost:8080 -kb kb_123
```
## Next Steps
- Read the full [README.md](README.md) for detailed documentation
- Check [agent_example.go](../../agent_example.go) for code examples
- Explore the [client package documentation](../../README.md)
- Review agent events and response types in the main README
## Getting Help
If you encounter issues:
1. Check the [README.md](README.md) for detailed documentation
2. Review the error messages - they usually indicate the problem
3. Verify your configuration (URL, KB ID, token)
4. Check WeKnora server logs for backend issues
5. Use `info` command to check session state
## Tips
- **Start Simple**: Begin with basic questions to verify connectivity
- **Use Info**: The `info` command shows valuable session configuration
- **Watch Events**: Pay attention to all event types to understand agent behavior
- **Check References**: Knowledge references show if retrieval is working correctly
- **Monitor Performance**: The summary shows timing and tool usage statistics
Happy testing! 🚀
-307
View File
@@ -1,307 +0,0 @@
# WeKnora Agent QA Testing Tool
An interactive command-line tool for testing and debugging WeKnora's Agent QA functionality.
## Features
- 🎯 Interactive terminal interface with colored output
- 📊 Real-time streaming of agent events
- 🔧 Display tool calls and their results
- 💭 Show agent thinking process
- 📚 Display knowledge references with scores
- 🤔 Capture agent reflections
- 📝 Track complete conversation flow
- ⏱️ Performance metrics and timing
- 🔄 Session management (create, switch, list)
## Installation
```bash
cd client/cmd/agent_test
go build -o agent_test
```
## Usage
### Basic Usage
```bash
# Start with a new session
./agent_test -url http://localhost:8080 -kb <knowledge_base_id>
# With authentication token
./agent_test -url http://localhost:8080 -token <your_token> -kb <knowledge_base_id>
# Use existing session
./agent_test -url http://localhost:8080 -session <session_id>
```
### Command Line Flags
- `-url` : WeKnora API base URL (default: http://localhost:8080)
- `-token` : API authentication token (optional)
- `-kb` : Knowledge base ID (required for creating new sessions)
- `-session` : Existing session ID to continue conversation (optional)
### Interactive Commands
Once the tool is running, you can use these commands:
#### Session Management
- `new` - Create a new session
```
> new
```
- `sessions` - List all sessions
```
> sessions
```
- `switch <session_id>` - Switch to another session
```
> switch abc123...
```
- `info` - Show current session information
```
> info
```
#### Agent Interaction
- `ask <query>` - Ask the agent a question
```
> ask What is machine learning?
> ask How can I improve model accuracy?
> ask Explain the difference between supervised and unsupervised learning
```
#### General
- `help` - Show help message
- `exit` or `quit` - Exit the program
## Agent Events
The tool displays various agent events in real-time:
### 💭 Thinking Events
Shows the agent's internal reasoning process
```
💭 Thinking: Let me search for information about machine learning...
```
### 🔧 Tool Call Events
Displays when the agent calls a tool
```
🔧 Tool Call: search_knowledge
Arguments: {"query": "machine learning definition"}
```
### ✓ Tool Result Events
Shows the results from tool execution
```
✓ Tool Result:
Found 5 relevant knowledge chunks
```
### 📚 Knowledge References
Lists retrieved knowledge with relevance scores
```
📚 Knowledge References: Found 3 reference(s)
1. [Score: 0.875] Machine learning is a subset of artificial intelligence...
Knowledge: ML Basics (Chunk: 2)
2. [Score: 0.823] There are three main types of machine learning...
Knowledge: ML Types (Chunk: 5)
```
### 📝 Final Answer
The agent's complete response
```
📝 Final Answer:
Machine learning is an application of artificial intelligence that provides
systems the ability to automatically learn and improve from experience...
```
### 🤔 Reflection Events
Agent's self-reflection on its responses
```
🤔 Reflection: I provided a comprehensive answer covering the main aspects
of machine learning with relevant examples.
```
### Summary
At the end of each query, a summary is displayed:
```
╔═══ Summary ═══╗
Duration: 3.45s
Tool Calls: 2 (search_knowledge, format_response)
References: 3
Reflections: 1
╚═══════════════╝
```
## Example Session
```bash
$ ./agent_test -url http://localhost:8080 -kb kb_12345
╔════════════════════════════════════════════════════════════╗
║ WeKnora Agent QA Testing Tool ║
╚════════════════════════════════════════════════════════════╝
[No Session] > new
✓ Session created successfully!
Session ID: sess_abc123xyz
Knowledge Base: kb_12345
Created At: 2025-11-03T10:30:00Z
[Session: sess_abc] > ask What is neural networks?
╔═══ Agent Processing ═══╗
Query: What is neural networks?
💭 Thinking: I need to search for information about neural networks...
🔧 Tool Call: search_knowledge
Arguments: map[query:neural networks]
✓ Tool Result:
Successfully retrieved 3 relevant chunks
📚 Knowledge References: Found 3 reference(s)
1. [Score: 0.892] A neural network is a series of algorithms...
Knowledge: Deep Learning Fundamentals (Chunk: 1)
2. [Score: 0.856] Neural networks consist of layers of neurons...
Knowledge: Neural Network Architecture (Chunk: 3)
📝 Final Answer:
Neural networks are computing systems inspired by biological neural networks
that constitute animal brains. They consist of interconnected nodes (neurons)
organized in layers...
🤔 Reflection: The answer provides a clear definition with supporting
references from the knowledge base.
╔═══ Summary ═══╗
Duration: 2.87s
Tool Calls: 1 (search_knowledge)
References: 3
Reflections: 1
╚═══════════════╝
[Session: sess_abc] > info
╔═══ Session Information ═══╗
Session ID: sess_abc123xyz
Knowledge Base ID: kb_12345
Max Rounds: 10
Created At: 2025-11-03T10:30:00Z
╚═══════════════════════════╝
[Session: sess_abc] > exit
Goodbye!
```
## Testing Scenarios
### 1. Basic Q&A
Test simple question-answering with knowledge retrieval:
```
> ask What is machine learning?
```
### 2. Multi-Turn Conversation
Test context awareness:
```
> ask What is supervised learning?
> ask Can you give me some examples?
> ask How does it differ from unsupervised learning?
```
### 3. Complex Queries
Test agent's reasoning capabilities:
```
> ask Compare and contrast supervised learning and reinforcement learning, including their use cases
```
### 4. Tool Usage
Test tool calling and reflection:
```
> ask Search for information about deep learning and summarize the key concepts
```
### 5. Edge Cases
Test error handling:
```
> ask [empty query]
> ask [very long query with 1000+ characters]
```
## Debugging
The tool displays detailed information for debugging:
1. **Event Timing**: Track how long each phase takes
2. **Tool Arguments**: See exactly what parameters are passed to tools
3. **Knowledge Scores**: Evaluate retrieval quality
4. **Error Messages**: Clear error reporting for failed operations
5. **Session State**: Monitor session configuration and status
## Troubleshooting
### Connection Issues
```
✗ Request failed: connection refused
```
- Check if WeKnora server is running
- Verify the URL is correct
- Check network connectivity
### Authentication Errors
```
✗ HTTP error 401: Unauthorized
```
- Verify your API token is valid
- Check token hasn't expired
### Session Not Found
```
✗ Failed to get session info: session not found
```
- Session may have been deleted
- Create a new session with `new` command
## Advanced Usage
### Using with Different Environments
Development:
```bash
./agent_test -url http://localhost:8080 -kb kb_dev
```
Staging:
```bash
./agent_test -url https://staging.weknora.com -token $STAGING_TOKEN -kb kb_staging
```
Production:
```bash
./agent_test -url https://api.weknora.com -token $PROD_TOKEN -kb kb_prod
```
### Scripting
You can pipe commands for automated testing:
```bash
echo -e "new\nask What is AI?\nexit" | ./agent_test -url http://localhost:8080 -kb kb_test
```
## License
Copyright (c) 2025 Tencent. All rights reserved.
-7
View File
@@ -1,7 +0,0 @@
module github.com/Tencent/WeKnora/client/cmd/agent_test
go 1.24.2
require github.com/Tencent/WeKnora/client v0.0.0
replace github.com/Tencent/WeKnora/client => ../..
-373
View File
@@ -1,373 +0,0 @@
package main
import (
"bufio"
"context"
"flag"
"fmt"
"os"
"strings"
"time"
"github.com/Tencent/WeKnora/client"
)
// Colors for terminal output
const (
ColorReset = "\033[0m"
ColorRed = "\033[31m"
ColorGreen = "\033[32m"
ColorYellow = "\033[33m"
ColorBlue = "\033[34m"
ColorMagenta = "\033[35m"
ColorCyan = "\033[36m"
ColorWhite = "\033[37m"
ColorBold = "\033[1m"
)
// Config holds the configuration
type Config struct {
BaseURL string
Token string
KnowledgeBaseID string
}
// CLI represents the command line interface
type CLI struct {
client *client.Client
config *Config
currentSessionID string
agentSession *client.AgentSession
}
func main() {
baseURL := flag.String("url", "http://localhost:8080", "WeKnora API base URL")
token := flag.String("token", "", "API authentication token")
kbID := flag.String("kb", "", "Knowledge base ID")
sessionID := flag.String("session", "", "Existing session ID (optional)")
flag.Parse()
config := &Config{
BaseURL: *baseURL,
Token: *token,
KnowledgeBaseID: *kbID,
}
cli := NewCLI(config)
// Use existing session if provided
if *sessionID != "" {
cli.currentSessionID = *sessionID
cli.agentSession = cli.client.NewAgentSession(*sessionID)
fmt.Printf("%s✓ Using existing session: %s%s\n\n", ColorGreen, *sessionID, ColorReset)
}
cli.Run()
}
// NewCLI creates a new CLI instance
func NewCLI(config *Config) *CLI {
clientOptions := []client.ClientOption{
client.WithTimeout(120 * time.Second),
}
if config.Token != "" {
clientOptions = append(clientOptions, client.WithToken(config.Token))
}
return &CLI{
client: client.NewClient(config.BaseURL, clientOptions...),
config: config,
}
}
// Run starts the interactive CLI
func (cli *CLI) Run() {
cli.printWelcome()
reader := bufio.NewReader(os.Stdin)
for {
fmt.Print(cli.getPrompt())
input, err := reader.ReadString('\n')
if err != nil {
fmt.Printf("%sError reading input: %v%s\n", ColorRed, err, ColorReset)
continue
}
input = strings.TrimSpace(input)
if input == "" {
continue
}
if !cli.handleCommand(input) {
break
}
}
fmt.Printf("\n%sGoodbye!%s\n", ColorCyan, ColorReset)
}
func (cli *CLI) getPrompt() string {
if cli.currentSessionID != "" {
return fmt.Sprintf("%s[Session: %s]%s > ", ColorBlue, cli.currentSessionID[:8], ColorReset)
}
return fmt.Sprintf("%s[No Session]%s > ", ColorYellow, ColorReset)
}
func (cli *CLI) printWelcome() {
fmt.Printf("\n%s╔════════════════════════════════════════════════════════════╗%s\n", ColorCyan, ColorReset)
fmt.Printf("%s║ WeKnora Agent QA Testing Tool ║%s\n", ColorCyan, ColorReset)
fmt.Printf("%s╚════════════════════════════════════════════════════════════╝%s\n\n", ColorCyan, ColorReset)
fmt.Printf("%sAvailable commands:%s\n", ColorBold, ColorReset)
fmt.Printf(" %snew%s - Create a new session\n", ColorGreen, ColorReset)
fmt.Printf(" %sask <query>%s - Ask agent a question\n", ColorGreen, ColorReset)
fmt.Printf(" %sinfo%s - Show current session info\n", ColorGreen, ColorReset)
fmt.Printf(" %ssessions%s - List all sessions\n", ColorGreen, ColorReset)
fmt.Printf(" %sswitch <id>%s - Switch to another session\n", ColorGreen, ColorReset)
fmt.Printf(" %shelp%s - Show this help message\n", ColorGreen, ColorReset)
fmt.Printf(" %sexit/quit%s - Exit the program\n\n", ColorGreen, ColorReset)
}
func (cli *CLI) handleCommand(input string) bool {
parts := strings.SplitN(input, " ", 2)
command := strings.ToLower(parts[0])
switch command {
case "help":
cli.printWelcome()
case "new":
cli.createNewSession()
case "ask":
if len(parts) < 2 {
fmt.Printf("%sUsage: ask <your question>%s\n", ColorRed, ColorReset)
return true
}
cli.askQuestion(parts[1])
case "info":
cli.showSessionInfo()
case "sessions":
cli.listSessions()
case "switch":
if len(parts) < 2 {
fmt.Printf("%sUsage: switch <session_id>%s\n", ColorRed, ColorReset)
return true
}
cli.switchSession(parts[1])
case "exit", "quit":
return false
default:
fmt.Printf("%sUnknown command: %s. Type 'help' for available commands.%s\n", ColorRed, command, ColorReset)
}
return true
}
func (cli *CLI) createNewSession() {
if cli.config.KnowledgeBaseID == "" {
fmt.Printf("%sError: Knowledge base ID is required. Use -kb flag.%s\n", ColorRed, ColorReset)
return
}
fmt.Printf("%sCreating new session...%s\n", ColorYellow, ColorReset)
ctx := context.Background()
request := &client.CreateSessionRequest{
KnowledgeBaseID: cli.config.KnowledgeBaseID,
SessionStrategy: &client.SessionStrategy{
MaxRounds: 10,
EnableRewrite: false,
FallbackStrategy: "default",
EmbeddingTopK: 10,
},
}
session, err := cli.client.CreateSession(ctx, request)
if err != nil {
fmt.Printf("%s✗ Failed to create session: %v%s\n", ColorRed, err, ColorReset)
return
}
cli.currentSessionID = session.ID
cli.agentSession = cli.client.NewAgentSession(session.ID)
fmt.Printf("%s✓ Session created successfully!%s\n", ColorGreen, ColorReset)
fmt.Printf(" Session ID: %s%s%s\n", ColorCyan, session.ID, ColorReset)
fmt.Printf(" Knowledge Base: %s%s%s\n", ColorCyan, session.KnowledgeBaseID, ColorReset)
fmt.Printf(" Created At: %s%s%s\n\n", ColorCyan, session.CreatedAt, ColorReset)
}
func (cli *CLI) askQuestion(query string) {
if cli.agentSession == nil {
fmt.Printf("%sError: No active session. Create one with 'new' command.%s\n", ColorRed, ColorReset)
return
}
fmt.Printf("\n%s╔═══ Agent Processing ═══╗%s\n", ColorCyan, ColorReset)
fmt.Printf("%sQuery: %s%s%s\n\n", ColorBold, ColorWhite, query, ColorReset)
ctx := context.Background()
var (
thinkingContent string
finalAnswer string
references []*client.SearchResult
toolCalls []string
reflections []string
)
startTime := time.Now()
err := cli.agentSession.Ask(ctx, query, func(resp *client.AgentStreamResponse) error {
switch resp.ResponseType {
case client.AgentResponseTypeThinking:
thinkingContent += resp.Content
if resp.Done {
fmt.Printf("%s💭 Thinking:%s %s\n\n", ColorYellow, ColorReset, thinkingContent)
thinkingContent = ""
}
case client.AgentResponseTypeToolCall:
toolName := "Unknown"
if resp.Data != nil {
if name, ok := resp.Data["tool_name"].(string); ok {
toolName = name
}
}
toolCalls = append(toolCalls, toolName)
fmt.Printf("%s🔧 Tool Call:%s %s\n", ColorMagenta, ColorReset, toolName)
if resp.Data != nil {
if args, ok := resp.Data["arguments"]; ok {
fmt.Printf(" Arguments: %v\n", args)
}
}
case client.AgentResponseTypeToolResult:
fmt.Printf("%s✓ Tool Result:%s\n", ColorGreen, ColorReset)
fmt.Printf(" %s\n\n", resp.Content)
case client.AgentResponseTypeReferences:
if resp.KnowledgeReferences != nil {
references = append(references, resp.KnowledgeReferences...)
fmt.Printf(
"%s📚 Knowledge References:%s Found %d reference(s)\n",
ColorCyan,
ColorReset,
len(resp.KnowledgeReferences),
)
for i, ref := range resp.KnowledgeReferences {
fmt.Printf(" %d. [Score: %.3f] %s\n", i+1, ref.Score, truncateString(ref.Content, 80))
fmt.Printf(" Knowledge: %s (Chunk: %d)\n", ref.KnowledgeTitle, ref.ChunkIndex)
}
fmt.Println()
}
case client.AgentResponseTypeAnswer:
finalAnswer += resp.Content
if resp.Done {
fmt.Printf("%s📝 Final Answer:%s\n", ColorGreen, ColorReset)
fmt.Printf("%s\n\n", finalAnswer)
}
case client.AgentResponseTypeReflection:
if resp.Done && resp.Content != "" {
reflections = append(reflections, resp.Content)
fmt.Printf("%s🤔 Reflection:%s %s\n\n", ColorBlue, ColorReset, resp.Content)
}
case client.AgentResponseTypeError:
fmt.Printf("%s✗ Error:%s %s\n\n", ColorRed, ColorReset, resp.Content)
}
return nil
})
if err != nil {
fmt.Printf("%s✗ Agent QA failed: %v%s\n", ColorRed, err, ColorReset)
return
}
duration := time.Since(startTime)
// Print summary
fmt.Printf("%s╔═══ Summary ═══╗%s\n", ColorCyan, ColorReset)
fmt.Printf("Duration: %s%.2fs%s\n", ColorCyan, duration.Seconds(), ColorReset)
fmt.Printf("Tool Calls: %s%d%s", ColorCyan, len(toolCalls), ColorReset)
if len(toolCalls) > 0 {
fmt.Printf(" (%s)", strings.Join(toolCalls, ", "))
}
fmt.Println()
fmt.Printf("References: %s%d%s\n", ColorCyan, len(references), ColorReset)
fmt.Printf("Reflections: %s%d%s\n", ColorCyan, len(reflections), ColorReset)
fmt.Printf("%s╚═══════════════╝%s\n\n", ColorCyan, ColorReset)
}
func (cli *CLI) showSessionInfo() {
if cli.currentSessionID == "" {
fmt.Printf("%sNo active session.%s\n", ColorYellow, ColorReset)
return
}
ctx := context.Background()
session, err := cli.client.GetSession(ctx, cli.currentSessionID)
if err != nil {
fmt.Printf("%s✗ Failed to get session info: %v%s\n", ColorRed, err, ColorReset)
return
}
fmt.Printf("\n%s╔═══ Session Information ═══╗%s\n", ColorCyan, ColorReset)
fmt.Printf("Session ID: %s%s%s\n", ColorWhite, session.ID, ColorReset)
fmt.Printf("Title: %s%s%s\n", ColorWhite, session.Title, ColorReset)
fmt.Printf("Knowledge Base ID: %s%s%s\n", ColorWhite, session.KnowledgeBaseID, ColorReset)
fmt.Printf("Max Rounds: %s%d%s\n", ColorWhite, session.MaxRounds, ColorReset)
fmt.Printf("Enable Rewrite: %s%v%s\n", ColorWhite, session.EnableRewrite, ColorReset)
fmt.Printf("Summary Model: %s%s%s\n", ColorWhite, session.SummaryModelID, ColorReset)
fmt.Printf("Created At: %s%s%s\n", ColorWhite, session.CreatedAt, ColorReset)
fmt.Printf("Updated At: %s%s%s\n", ColorWhite, session.UpdatedAt, ColorReset)
fmt.Printf("%s╚═══════════════════════════╝%s\n\n", ColorCyan, ColorReset)
}
func (cli *CLI) listSessions() {
ctx := context.Background()
sessions, total, err := cli.client.GetSessionsByTenant(ctx, 1, 10)
if err != nil {
fmt.Printf("%s✗ Failed to list sessions: %v%s\n", ColorRed, err, ColorReset)
return
}
fmt.Printf("\n%s╔═══ Sessions (Total: %d) ═══╗%s\n", ColorCyan, total, ColorReset)
for i, session := range sessions {
marker := " "
if session.ID == cli.currentSessionID {
marker = "►"
}
fmt.Printf("%s%s %d. %s%s\n", ColorGreen, marker, i+1, session.ID, ColorReset)
fmt.Printf(" Title: %s\n", session.Title)
fmt.Printf(" KB: %s\n", session.KnowledgeBaseID)
fmt.Printf(" Created: %s\n", session.CreatedAt)
fmt.Println()
}
fmt.Printf("%s╚════════════════════════════╝%s\n\n", ColorCyan, ColorReset)
}
func (cli *CLI) switchSession(sessionID string) {
ctx := context.Background()
session, err := cli.client.GetSession(ctx, sessionID)
if err != nil {
fmt.Printf("%s✗ Failed to switch session: %v%s\n", ColorRed, err, ColorReset)
return
}
cli.currentSessionID = session.ID
cli.agentSession = cli.client.NewAgentSession(session.ID)
fmt.Printf("%s✓ Switched to session: %s%s\n", ColorGreen, session.ID, ColorReset)
}
func truncateString(s string, maxLen int) string {
s = strings.ReplaceAll(s, "\n", " ")
if len(s) <= maxLen {
return s
}
return s[:maxLen] + "..."
}
-172
View File
@@ -1,172 +0,0 @@
#!/bin/bash
# WeKnora Agent Test Tool - Quick Start Script
# This script helps you quickly build and run the agent test tool
set -e
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Default values
DEFAULT_URL="http://localhost:8080"
BINARY_NAME="agent_test"
# Function to print colored output
print_info() {
echo -e "${BLUE}ℹ${NC} $1"
}
print_success() {
echo -e "${GREEN}✓${NC} $1"
}
print_warning() {
echo -e "${YELLOW}⚠${NC} $1"
}
print_error() {
echo -e "${RED}✗${NC} $1"
}
# Function to build the binary
build() {
print_info "Building agent test tool..."
if go build -o "$BINARY_NAME" .; then
print_success "Build successful!"
return 0
else
print_error "Build failed!"
return 1
fi
}
# Function to show usage
usage() {
cat << EOF
WeKnora Agent Test Tool - Quick Start Script
Usage:
$0 [OPTIONS]
Options:
-u, --url URL WeKnora API URL (default: $DEFAULT_URL)
-k, --kb KB_ID Knowledge Base ID
-s, --session ID Existing Session ID
-t, --token TOKEN API authentication token
-b, --build-only Only build, don't run
-h, --help Show this help message
Examples:
# Build and run with a knowledge base
$0 -k kb_123456
# Use a different server URL
$0 -u https://api.weknora.com -k kb_123456 -t mytoken
# Continue an existing session
$0 -s sess_123456
# Only build the binary
$0 --build-only
Environment Variables:
WEKNORA_URL Default API URL
WEKNORA_KB_ID Default Knowledge Base ID
WEKNORA_TOKEN Default API Token
WEKNORA_SESSION_ID Default Session ID
EOF
}
# Parse command line arguments
URL="${WEKNORA_URL:-$DEFAULT_URL}"
KB_ID="${WEKNORA_KB_ID:-}"
SESSION_ID="${WEKNORA_SESSION_ID:-}"
TOKEN="${WEKNORA_TOKEN:-}"
BUILD_ONLY=false
while [[ $# -gt 0 ]]; do
case $1 in
-u|--url)
URL="$2"
shift 2
;;
-k|--kb)
KB_ID="$2"
shift 2
;;
-s|--session)
SESSION_ID="$2"
shift 2
;;
-t|--token)
TOKEN="$2"
shift 2
;;
-b|--build-only)
BUILD_ONLY=true
shift
;;
-h|--help)
usage
exit 0
;;
*)
print_error "Unknown option: $1"
usage
exit 1
;;
esac
done
# Build the binary
if ! build; then
exit 1
fi
# Exit if build-only mode
if [ "$BUILD_ONLY" = true ]; then
print_info "Build-only mode. Binary created: ./$BINARY_NAME"
exit 0
fi
# Validate parameters
if [ -z "$SESSION_ID" ] && [ -z "$KB_ID" ]; then
print_warning "Neither session ID nor knowledge base ID provided."
print_info "You can create a new session after starting the tool."
fi
# Build command arguments
ARGS="-url $URL"
if [ -n "$KB_ID" ]; then
ARGS="$ARGS -kb $KB_ID"
fi
if [ -n "$SESSION_ID" ]; then
ARGS="$ARGS -session $SESSION_ID"
fi
if [ -n "$TOKEN" ]; then
ARGS="$ARGS -token $TOKEN"
fi
# Show configuration
echo ""
print_info "Configuration:"
echo " URL: $URL"
[ -n "$KB_ID" ] && echo " Knowledge Base: $KB_ID"
[ -n "$SESSION_ID" ] && echo " Session: $SESSION_ID"
[ -n "$TOKEN" ] && echo " Token: [provided]"
echo ""
# Run the tool
print_info "Starting agent test tool..."
echo ""
./$BINARY_NAME $ARGS
-159
View File
@@ -1,159 +0,0 @@
#!/bin/bash
# Test Scenarios for WeKnora Agent QA
# This script contains various test scenarios you can run
set -e
# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
NC='\033[0m'
print_scenario() {
echo -e "\n${BLUE}═══════════════════════════════════════════════${NC}"
echo -e "${BLUE} $1${NC}"
echo -e "${BLUE}═══════════════════════════════════════════════${NC}\n"
}
# Check if binary exists
if [ ! -f "./agent_test" ]; then
echo "Building agent_test..."
make build
fi
# Load environment variables if .env exists
if [ -f ".env" ]; then
export $(cat .env | grep -v '^#' | xargs)
fi
# Check required variables
if [ -z "$WEKNORA_KB_ID" ]; then
echo "Error: WEKNORA_KB_ID is not set"
echo "Please set it in .env file or export WEKNORA_KB_ID=your_kb_id"
exit 1
fi
URL="${WEKNORA_URL:-http://localhost:8080}"
KB_ID="$WEKNORA_KB_ID"
TOKEN="${WEKNORA_TOKEN:-}"
# Scenario 1: Basic Q&A
scenario_basic() {
print_scenario "Scenario 1: Basic Question & Answer"
echo -e "${YELLOW}This will test basic agent Q&A functionality${NC}\n"
echo "Try asking: What is machine learning?"
echo ""
if [ -n "$TOKEN" ]; then
./agent_test -url "$URL" -kb "$KB_ID" -token "$TOKEN"
else
./agent_test -url "$URL" -kb "$KB_ID"
fi
}
# Scenario 2: Complex query with tool usage
scenario_complex() {
print_scenario "Scenario 2: Complex Query with Tool Usage"
echo -e "${YELLOW}This will test agent's ability to use tools${NC}\n"
echo "Try asking: Search for information about neural networks and explain the key concepts"
echo ""
if [ -n "$TOKEN" ]; then
./agent_test -url "$URL" -kb "$KB_ID" -token "$TOKEN"
else
./agent_test -url "$URL" -kb "$KB_ID"
fi
}
# Scenario 3: Multi-turn conversation
scenario_multiturn() {
print_scenario "Scenario 3: Multi-turn Conversation"
echo -e "${YELLOW}This will test agent's context awareness${NC}\n"
echo "Try this sequence:"
echo " 1. What is supervised learning?"
echo " 2. Can you give me some examples?"
echo " 3. How does it compare to unsupervised learning?"
echo ""
if [ -n "$TOKEN" ]; then
./agent_test -url "$URL" -kb "$KB_ID" -token "$TOKEN"
else
./agent_test -url "$URL" -kb "$KB_ID"
fi
}
# Show menu
show_menu() {
echo -e "\n${GREEN}WeKnora Agent Test Scenarios${NC}\n"
echo "Select a test scenario to run:"
echo " 1) Basic Q&A"
echo " 2) Complex Query with Tool Usage"
echo " 3) Multi-turn Conversation"
echo " 4) Custom (manual testing)"
echo " 5) Exit"
echo ""
read -p "Enter your choice [1-5]: " choice
case $choice in
1) scenario_basic ;;
2) scenario_complex ;;
3) scenario_multiturn ;;
4)
print_scenario "Custom Testing"
if [ -n "$TOKEN" ]; then
./agent_test -url "$URL" -kb "$KB_ID" -token "$TOKEN"
else
./agent_test -url "$URL" -kb "$KB_ID"
fi
;;
5)
echo "Goodbye!"
exit 0
;;
*)
echo "Invalid choice. Please try again."
show_menu
;;
esac
}
# Main
if [ "$1" == "--help" ] || [ "$1" == "-h" ]; then
echo "Usage: $0 [scenario_number]"
echo ""
echo "Available scenarios:"
echo " 1 - Basic Q&A"
echo " 2 - Complex Query with Tool Usage"
echo " 3 - Multi-turn Conversation"
echo " 4 - Custom (manual testing)"
echo ""
echo "If no argument is provided, an interactive menu will be shown."
exit 0
fi
# If scenario number is provided as argument
if [ -n "$1" ]; then
case $1 in
1) scenario_basic ;;
2) scenario_complex ;;
3) scenario_multiturn ;;
4)
if [ -n "$TOKEN" ]; then
./agent_test -url "$URL" -kb "$KB_ID" -token "$TOKEN"
else
./agent_test -url "$URL" -kb "$KB_ID"
fi
;;
*)
echo "Invalid scenario number: $1"
echo "Use --help to see available scenarios"
exit 1
;;
esac
else
# Show interactive menu
show_menu
fi