feat: Add agent configuration and cleanup scripts for database migrations
This commit is contained in:
+120
-3
@@ -11,9 +11,10 @@
|
||||
3. **知识管理**:添加、获取和删除知识内容
|
||||
4. **租户管理**:租户的CRUD操作
|
||||
5. **知识问答**:支持普通问答和流式问答
|
||||
6. **分块管理**:查询、更新和删除知识分块
|
||||
7. **消息管理**:获取和删除会话消息
|
||||
8. **模型管理**:创建、获取、更新和删除模型
|
||||
6. **Agent问答**:支持基于Agent的智能问答,包含思考过程、工具调用和反思
|
||||
7. **分块管理**:查询、更新和删除知识分块
|
||||
8. **消息管理**:获取和删除会话消息
|
||||
9. **模型管理**:创建、获取、更新和删除模型
|
||||
|
||||
## 使用方法
|
||||
|
||||
@@ -114,6 +115,122 @@ if err != nil {
|
||||
}
|
||||
```
|
||||
|
||||
### 示例:Agent智能问答
|
||||
|
||||
Agent问答提供更强大的智能对话能力,支持工具调用、思考过程展示和自我反思。
|
||||
|
||||
```go
|
||||
// 创建Agent会话
|
||||
agentSession := apiClient.NewAgentSession(session.ID)
|
||||
|
||||
// 进行Agent问答,带完整事件处理
|
||||
err := agentSession.Ask(context.Background(), "搜索机器学习相关知识并总结要点",
|
||||
func(resp *client.AgentStreamResponse) error {
|
||||
switch resp.ResponseType {
|
||||
case client.AgentResponseTypeThinking:
|
||||
// Agent正在思考
|
||||
if resp.Done {
|
||||
fmt.Printf("💭 思考: %s\n", resp.Content)
|
||||
}
|
||||
|
||||
case client.AgentResponseTypeToolCall:
|
||||
// Agent调用工具
|
||||
if resp.Data != nil {
|
||||
toolName := resp.Data["tool_name"]
|
||||
fmt.Printf("🔧 调用工具: %v\n", toolName)
|
||||
}
|
||||
|
||||
case client.AgentResponseTypeToolResult:
|
||||
// 工具执行结果
|
||||
fmt.Printf("✓ 工具结果: %s\n", resp.Content)
|
||||
|
||||
case client.AgentResponseTypeReferences:
|
||||
// 知识引用
|
||||
if resp.KnowledgeReferences != nil {
|
||||
fmt.Printf("📚 找到 %d 条相关知识\n", len(resp.KnowledgeReferences))
|
||||
for _, ref := range resp.KnowledgeReferences {
|
||||
fmt.Printf(" - [%.3f] %s\n", ref.Score, ref.KnowledgeTitle)
|
||||
}
|
||||
}
|
||||
|
||||
case client.AgentResponseTypeAnswer:
|
||||
// 最终答案(流式输出)
|
||||
fmt.Print(resp.Content)
|
||||
if resp.Done {
|
||||
fmt.Println() // 结束后换行
|
||||
}
|
||||
|
||||
case client.AgentResponseTypeReflection:
|
||||
// Agent的自我反思
|
||||
if resp.Done {
|
||||
fmt.Printf("🤔 反思: %s\n", resp.Content)
|
||||
}
|
||||
|
||||
case client.AgentResponseTypeError:
|
||||
// 错误信息
|
||||
fmt.Printf("❌ 错误: %s\n", resp.Content)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
// 处理错误
|
||||
}
|
||||
|
||||
// 简化版:只关心最终答案
|
||||
var finalAnswer string
|
||||
err = agentSession.Ask(context.Background(), "什么是深度学习?",
|
||||
func(resp *client.AgentStreamResponse) error {
|
||||
if resp.ResponseType == client.AgentResponseTypeAnswer {
|
||||
finalAnswer += resp.Content
|
||||
}
|
||||
return nil
|
||||
})
|
||||
```
|
||||
|
||||
### Agent事件类型说明
|
||||
|
||||
| 事件类型 | 说明 | 何时触发 |
|
||||
|---------|------|---------|
|
||||
| `AgentResponseTypeThinking` | Agent思考过程 | Agent分析问题和制定计划时 |
|
||||
| `AgentResponseTypeToolCall` | 工具调用 | Agent决定使用某个工具时 |
|
||||
| `AgentResponseTypeToolResult` | 工具执行结果 | 工具执行完成后 |
|
||||
| `AgentResponseTypeReferences` | 知识引用 | 检索到相关知识时 |
|
||||
| `AgentResponseTypeAnswer` | 最终答案 | Agent生成回答时(流式) |
|
||||
| `AgentResponseTypeReflection` | 自我反思 | Agent评估自己的回答时 |
|
||||
| `AgentResponseTypeError` | 错误 | 发生错误时 |
|
||||
|
||||
### Agent问答测试工具
|
||||
|
||||
我们提供了一个交互式命令行工具用于测试Agent功能:
|
||||
|
||||
```bash
|
||||
cd client/cmd/agent_test
|
||||
go build -o agent_test
|
||||
./agent_test -url http://localhost:8080 -kb <knowledge_base_id>
|
||||
```
|
||||
|
||||
该工具支持:
|
||||
- 创建和管理会话
|
||||
- 交互式Agent问答
|
||||
- 实时显示所有Agent事件
|
||||
- 性能统计和调试信息
|
||||
|
||||
详细使用说明请参考 `client/cmd/agent_test/README.md`。
|
||||
|
||||
### Agent问答的高级用法
|
||||
|
||||
更多高级用法示例,请参考 `agent_example.go` 文件,包括:
|
||||
- 基础Agent问答
|
||||
- 工具调用跟踪
|
||||
- 知识引用捕获
|
||||
- 完整事件跟踪
|
||||
- 自定义错误处理
|
||||
- 流取消控制
|
||||
- 多会话管理
|
||||
|
||||
```
|
||||
|
||||
### 示例:管理模型
|
||||
|
||||
```go
|
||||
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
// Package client provides the implementation for interacting with the WeKnora API
|
||||
// The Agent related interfaces are used to manage agent-based question-answering
|
||||
package client
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// AgentQARequest agent Q&A request
|
||||
type AgentQARequest struct {
|
||||
Query string `json:"query"`
|
||||
}
|
||||
|
||||
// AgentResponseType defines the type of agent response
|
||||
type AgentResponseType string
|
||||
|
||||
const (
|
||||
AgentResponseTypeThinking AgentResponseType = "thinking"
|
||||
AgentResponseTypeToolCall AgentResponseType = "tool_call"
|
||||
AgentResponseTypeToolResult AgentResponseType = "tool_result"
|
||||
AgentResponseTypeReferences AgentResponseType = "references"
|
||||
AgentResponseTypeAnswer AgentResponseType = "answer"
|
||||
AgentResponseTypeReflection AgentResponseType = "reflection"
|
||||
AgentResponseTypeError AgentResponseType = "error"
|
||||
)
|
||||
|
||||
// AgentStreamResponse agent streaming response
|
||||
type AgentStreamResponse struct {
|
||||
ID string `json:"id"` // Unique identifier
|
||||
ResponseType AgentResponseType `json:"response_type"` // Response type
|
||||
Content string `json:"content,omitempty"` // Current content fragment
|
||||
Done bool `json:"done"` // Whether completed
|
||||
KnowledgeReferences []*SearchResult `json:"knowledge_references"` // Knowledge references
|
||||
Data map[string]interface{} `json:"data,omitempty"` // Additional event data
|
||||
}
|
||||
|
||||
// AgentEventCallback is called for each streaming event
|
||||
// Return error to stop processing the stream
|
||||
type AgentEventCallback func(*AgentStreamResponse) error
|
||||
|
||||
// AgentQAStream performs agent-based Q&A with SSE streaming
|
||||
// The callback will be invoked for each event received from the server
|
||||
func (c *Client) AgentQAStream(ctx context.Context, sessionID string, query string, callback AgentEventCallback) error {
|
||||
path := fmt.Sprintf("/api/v1/agent-chat/%s", sessionID)
|
||||
|
||||
request := &AgentQARequest{
|
||||
Query: query,
|
||||
}
|
||||
|
||||
resp, err := c.doRequest(ctx, http.MethodPost, path, request, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("request failed: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
return fmt.Errorf("HTTP error %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
// Process SSE stream
|
||||
return c.processAgentSSEStream(resp.Body, callback)
|
||||
}
|
||||
|
||||
// processAgentSSEStream processes the SSE stream and invokes callback for each event
|
||||
func (c *Client) processAgentSSEStream(reader io.Reader, callback AgentEventCallback) error {
|
||||
scanner := bufio.NewScanner(reader)
|
||||
var dataBuffer string
|
||||
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
|
||||
// Empty line indicates the end of an event
|
||||
if line == "" {
|
||||
if dataBuffer != "" {
|
||||
var streamResponse AgentStreamResponse
|
||||
if err := json.Unmarshal([]byte(dataBuffer), &streamResponse); err != nil {
|
||||
return fmt.Errorf("failed to parse SSE data: %w", err)
|
||||
}
|
||||
|
||||
if err := callback(&streamResponse); err != nil {
|
||||
return err
|
||||
}
|
||||
dataBuffer = ""
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// Process lines with event: prefix (for future use)
|
||||
if strings.HasPrefix(line, "event:") {
|
||||
// Event type is available but not currently used
|
||||
// eventType := strings.TrimSpace(line[6:])
|
||||
continue
|
||||
}
|
||||
|
||||
// Process lines with data: prefix
|
||||
if strings.HasPrefix(line, "data:") {
|
||||
dataBuffer = strings.TrimSpace(line[5:]) // Remove "data:" prefix
|
||||
}
|
||||
}
|
||||
|
||||
if err := scanner.Err(); err != nil {
|
||||
return fmt.Errorf("failed to read SSE stream: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// AgentSession is a wrapper for agent-based interactions
|
||||
type AgentSession struct {
|
||||
client *Client
|
||||
sessionID string
|
||||
}
|
||||
|
||||
// NewAgentSession creates a new agent session wrapper
|
||||
func (c *Client) NewAgentSession(sessionID string) *AgentSession {
|
||||
return &AgentSession{
|
||||
client: c,
|
||||
sessionID: sessionID,
|
||||
}
|
||||
}
|
||||
|
||||
// Ask sends a query to the agent and processes the streaming response
|
||||
func (as *AgentSession) Ask(ctx context.Context, query string, callback AgentEventCallback) error {
|
||||
return as.client.AgentQAStream(ctx, as.sessionID, query, callback)
|
||||
}
|
||||
|
||||
// GetSessionID returns the session ID
|
||||
func (as *AgentSession) GetSessionID() string {
|
||||
return as.sessionID
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ExampleAgentQABasic demonstrates basic agent QA usage
|
||||
func ExampleAgentQABasic() {
|
||||
// Create client
|
||||
client := NewClient("http://localhost:8080", WithTimeout(60*time.Second))
|
||||
|
||||
// Create a session
|
||||
ctx := context.Background()
|
||||
session, err := client.CreateSession(ctx, &CreateSessionRequest{
|
||||
KnowledgeBaseID: "your_kb_id",
|
||||
SessionStrategy: &SessionStrategy{
|
||||
MaxRounds: 10,
|
||||
EnableRewrite: false,
|
||||
FallbackStrategy: "default",
|
||||
EmbeddingTopK: 10,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to create session: %v", err)
|
||||
}
|
||||
|
||||
fmt.Printf("Session created: %s\n", session.ID)
|
||||
|
||||
// Create agent session wrapper
|
||||
agentSession := client.NewAgentSession(session.ID)
|
||||
|
||||
// Ask a question
|
||||
err = agentSession.Ask(ctx, "What is machine learning?", func(resp *AgentStreamResponse) error {
|
||||
switch resp.ResponseType {
|
||||
case AgentResponseTypeThinking:
|
||||
if resp.Done {
|
||||
fmt.Printf("Thinking: %s\n", resp.Content)
|
||||
}
|
||||
case AgentResponseTypeAnswer:
|
||||
fmt.Print(resp.Content) // Print answer incrementally
|
||||
if resp.Done {
|
||||
fmt.Println() // New line at the end
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
log.Fatalf("Agent QA failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// ExampleAgentQAWithToolTracking demonstrates tracking tool calls
|
||||
func ExampleAgentQAWithToolTracking() {
|
||||
client := NewClient("http://localhost:8080")
|
||||
agentSession := client.NewAgentSession("existing_session_id")
|
||||
|
||||
ctx := context.Background()
|
||||
toolCalls := make([]string, 0)
|
||||
|
||||
err := agentSession.Ask(ctx, "Search for information about neural networks", func(resp *AgentStreamResponse) error {
|
||||
switch resp.ResponseType {
|
||||
case AgentResponseTypeToolCall:
|
||||
if resp.Data != nil {
|
||||
if toolName, ok := resp.Data["tool_name"].(string); ok {
|
||||
toolCalls = append(toolCalls, toolName)
|
||||
fmt.Printf("Tool called: %s\n", toolName)
|
||||
}
|
||||
}
|
||||
case AgentResponseTypeToolResult:
|
||||
fmt.Printf("Tool result: %s\n", resp.Content)
|
||||
case AgentResponseTypeAnswer:
|
||||
if resp.Done {
|
||||
fmt.Printf("Final answer: %s\n", resp.Content)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
log.Fatalf("Error: %v", err)
|
||||
}
|
||||
|
||||
fmt.Printf("Total tool calls: %d\n", len(toolCalls))
|
||||
}
|
||||
|
||||
// ExampleAgentQAWithReferences demonstrates capturing knowledge references
|
||||
func ExampleAgentQAWithReferences() {
|
||||
client := NewClient("http://localhost:8080")
|
||||
agentSession := client.NewAgentSession("existing_session_id")
|
||||
|
||||
ctx := context.Background()
|
||||
var references []*SearchResult
|
||||
var finalAnswer string
|
||||
|
||||
err := agentSession.Ask(ctx, "Explain deep learning", func(resp *AgentStreamResponse) error {
|
||||
switch resp.ResponseType {
|
||||
case AgentResponseTypeReferences:
|
||||
if resp.KnowledgeReferences != nil {
|
||||
references = append(references, resp.KnowledgeReferences...)
|
||||
fmt.Printf("Found %d references\n", len(resp.KnowledgeReferences))
|
||||
}
|
||||
case AgentResponseTypeAnswer:
|
||||
finalAnswer += resp.Content
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
log.Fatalf("Error: %v", err)
|
||||
}
|
||||
|
||||
// Process results
|
||||
fmt.Println("Final Answer:", finalAnswer)
|
||||
fmt.Printf("\nBased on %d knowledge references:\n", len(references))
|
||||
for i, ref := range references {
|
||||
fmt.Printf("%d. [Score: %.3f] %s\n", i+1, ref.Score, ref.KnowledgeTitle)
|
||||
}
|
||||
}
|
||||
|
||||
// ExampleAgentQAWithFullEventTracking demonstrates comprehensive event tracking
|
||||
func ExampleAgentQAWithFullEventTracking() {
|
||||
client := NewClient("http://localhost:8080")
|
||||
agentSession := client.NewAgentSession("existing_session_id")
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// Tracking state
|
||||
state := struct {
|
||||
thinking string
|
||||
toolCalls []map[string]interface{}
|
||||
toolResults []string
|
||||
references []*SearchResult
|
||||
answer string
|
||||
reflections []string
|
||||
errors []string
|
||||
}{}
|
||||
|
||||
err := agentSession.Ask(ctx, "Your question here", func(resp *AgentStreamResponse) error {
|
||||
switch resp.ResponseType {
|
||||
case AgentResponseTypeThinking:
|
||||
state.thinking += resp.Content
|
||||
if resp.Done {
|
||||
fmt.Printf("💭 Thinking: %s\n", state.thinking)
|
||||
}
|
||||
|
||||
case AgentResponseTypeToolCall:
|
||||
toolCall := map[string]interface{}{
|
||||
"name": resp.Data["tool_name"],
|
||||
"arguments": resp.Data["arguments"],
|
||||
}
|
||||
state.toolCalls = append(state.toolCalls, toolCall)
|
||||
fmt.Printf("🔧 Tool Call: %v\n", resp.Data["tool_name"])
|
||||
|
||||
case AgentResponseTypeToolResult:
|
||||
state.toolResults = append(state.toolResults, resp.Content)
|
||||
success := "✓"
|
||||
if resp.Data != nil {
|
||||
if s, ok := resp.Data["success"].(bool); ok && !s {
|
||||
success = "✗"
|
||||
}
|
||||
}
|
||||
fmt.Printf("%s Tool Result: %s\n", success, resp.Content)
|
||||
|
||||
case AgentResponseTypeReferences:
|
||||
if resp.KnowledgeReferences != nil {
|
||||
state.references = append(state.references, resp.KnowledgeReferences...)
|
||||
fmt.Printf("📚 References: %d\n", len(resp.KnowledgeReferences))
|
||||
}
|
||||
|
||||
case AgentResponseTypeAnswer:
|
||||
state.answer += resp.Content
|
||||
if resp.Done {
|
||||
fmt.Printf("📝 Answer: %s\n", state.answer)
|
||||
}
|
||||
|
||||
case AgentResponseTypeReflection:
|
||||
if resp.Done {
|
||||
state.reflections = append(state.reflections, resp.Content)
|
||||
fmt.Printf("🤔 Reflection: %s\n", resp.Content)
|
||||
}
|
||||
|
||||
case AgentResponseTypeError:
|
||||
state.errors = append(state.errors, resp.Content)
|
||||
fmt.Printf("❌ Error: %s\n", resp.Content)
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
log.Fatalf("Error: %v", err)
|
||||
}
|
||||
|
||||
// Print summary
|
||||
fmt.Println("\n=== Summary ===")
|
||||
fmt.Printf("Tool Calls: %d\n", len(state.toolCalls))
|
||||
fmt.Printf("References: %d\n", len(state.references))
|
||||
fmt.Printf("Reflections: %d\n", len(state.reflections))
|
||||
fmt.Printf("Errors: %d\n", len(state.errors))
|
||||
}
|
||||
|
||||
// ExampleAgentQAWithCustomErrorHandling demonstrates custom error handling
|
||||
func ExampleAgentQAWithCustomErrorHandling() {
|
||||
client := NewClient("http://localhost:8080")
|
||||
agentSession := client.NewAgentSession("existing_session_id")
|
||||
|
||||
ctx := context.Background()
|
||||
hasError := false
|
||||
|
||||
err := agentSession.Ask(ctx, "Your question", func(resp *AgentStreamResponse) error {
|
||||
if resp.ResponseType == AgentResponseTypeError {
|
||||
hasError = true
|
||||
// Log error to your monitoring system
|
||||
fmt.Printf("Agent error occurred: %s\n", resp.Content)
|
||||
// You can return an error here to stop processing
|
||||
// return fmt.Errorf("stopping due to error: %s", resp.Content)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
log.Printf("Stream error: %v", err)
|
||||
}
|
||||
|
||||
if hasError {
|
||||
log.Println("Agent encountered errors during processing")
|
||||
}
|
||||
}
|
||||
|
||||
// ExampleAgentQAStreamCancellation demonstrates canceling a stream
|
||||
func ExampleAgentQAStreamCancellation() {
|
||||
client := NewClient("http://localhost:8080")
|
||||
agentSession := client.NewAgentSession("existing_session_id")
|
||||
|
||||
// Create a context with timeout
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Or cancel based on a condition
|
||||
maxToolCalls := 5
|
||||
toolCallCount := 0
|
||||
|
||||
err := agentSession.Ask(ctx, "Complex query that might take long", func(resp *AgentStreamResponse) error {
|
||||
if resp.ResponseType == AgentResponseTypeToolCall {
|
||||
toolCallCount++
|
||||
if toolCallCount > maxToolCalls {
|
||||
// Stop processing if too many tool calls
|
||||
return fmt.Errorf("too many tool calls: %d", toolCallCount)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
log.Printf("Stream stopped: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// ExampleMultipleAgentSessions demonstrates managing multiple agent sessions
|
||||
func ExampleMultipleAgentSessions() {
|
||||
client := NewClient("http://localhost:8080")
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// Create multiple sessions for different purposes
|
||||
sessions := map[string]*AgentSession{
|
||||
"technical": client.NewAgentSession("session_id_1"),
|
||||
"general": client.NewAgentSession("session_id_2"),
|
||||
"customer": client.NewAgentSession("session_id_3"),
|
||||
}
|
||||
|
||||
// Use appropriate session based on query type
|
||||
queryType := "technical"
|
||||
query := "How does gradient descent work?"
|
||||
|
||||
if session, ok := sessions[queryType]; ok {
|
||||
err := session.Ask(ctx, query, func(resp *AgentStreamResponse) error {
|
||||
if resp.ResponseType == AgentResponseTypeAnswer && resp.Done {
|
||||
fmt.Printf("[%s] Answer: %s\n", queryType, resp.Content)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
log.Printf("Error in %s session: %v", queryType, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
.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"
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
# 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! 🚀
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
# 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.
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
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 => ../..
|
||||
@@ -0,0 +1,369 @@
|
||||
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] + "..."
|
||||
}
|
||||
Executable
+172
@@ -0,0 +1,172 @@
|
||||
#!/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
|
||||
|
||||
Executable
+159
@@ -0,0 +1,159 @@
|
||||
#!/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
|
||||
|
||||
+15
-1
@@ -49,10 +49,23 @@ type SummaryConfig struct {
|
||||
MaxCompletionTokens int `json:"max_completion_tokens"`
|
||||
}
|
||||
|
||||
// AgentConfig defines agent configuration for agent mode
|
||||
type AgentConfig struct {
|
||||
Enabled bool `json:"enabled"` // Whether agent mode is enabled
|
||||
EnablePlanning bool `json:"enable_planning"` // Whether to plan before executing
|
||||
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
|
||||
KnowledgeBases []string `json:"knowledge_bases"` // Accessible knowledge base IDs
|
||||
}
|
||||
|
||||
// CreateSessionRequest session creation request
|
||||
type CreateSessionRequest struct {
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"` // Associated knowledge base ID
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"` // Associated knowledge base ID (optional in agent mode)
|
||||
SessionStrategy *SessionStrategy `json:"session_strategy"` // Session strategy
|
||||
AgentConfig *AgentConfig `json:"agent_config"` // Agent configuration (optional, for agent mode)
|
||||
}
|
||||
|
||||
// Session session information
|
||||
@@ -73,6 +86,7 @@ type Session struct {
|
||||
RerankThreshold float64 `json:"reranking_threshold"` // Reranking threshold
|
||||
SummaryModelID string `json:"summary_model_id"`
|
||||
SummaryParameters *SummaryConfig `json:"summary_parameters"`
|
||||
AgentConfig *AgentConfig `json:"agent_config"` // Agent configuration (optional)
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user