Documentation
¶
Index ¶
- Constants
- Variables
- func BuildAskForClarification(question string, options []string, thought, summary string) string
- func BuildBlueprintToolParams(blueprintName string, additionalParams map[string]interface{}) string
- func BuildCallTool(params map[string]interface{}) string
- func BuildCodeToolParams(code, description, language string) string
- func BuildDirectlyAnswer(answer, thought, summary string) string
- func BuildRequestPlanAndExecution(planPayload, thought, summary string) string
- func BuildRequireTool(toolName, thought, summary string) string
- func BuildRiskToolParams(target, title, severity, riskType string) string
- func BuildSearchToolParams(query string, maxResults int) string
- func BuildSleepToolParams(seconds float64) string
- func BuildVerifySatisfaction(satisfied bool, reasoning string) string
- func GetAllTemplates() map[string]*ResponseTemplate
- func GetCommonResponse(name string) (string, bool)
- func GetTemplateResponse(templateName string, args ...interface{}) string
- func ListScenarios() []string
- func PrettyPrintResponse(response string) string
- func ValidateResponse(response string) error
- type AIScenario
- type CallToolBuilder
- type KeywordResponse
- type KeywordScenarios
- func (s *KeywordScenarios) AddResponse(name string, keywords []string, response string, description string)
- func (s *KeywordScenarios) AddResponseWithMatcher(name string, matcher PromptMatcherFunc, response string, description string)
- func (s *KeywordScenarios) GetAICallbackType() aicommon.AICallbackType
- func (s *KeywordScenarios) GetResponse(name string) *KeywordResponse
- func (s *KeywordScenarios) ListResponses() []string
- func (s *KeywordScenarios) PrintAllResponses()
- func (s *KeywordScenarios) RemoveResponse(name string)
- type PromptMatcherFunc
- func MatcherAnd(matchers ...PromptMatcherFunc) PromptMatcherFunc
- func MatcherAny() PromptMatcherFunc
- func MatcherContains(substring string) PromptMatcherFunc
- func MatcherContainsAll(substrings ...string) PromptMatcherFunc
- func MatcherContainsAny(substrings ...string) PromptMatcherFunc
- func MatcherContainsCaseSensitive(substring string) PromptMatcherFunc
- func MatcherEmpty() PromptMatcherFunc
- func MatcherExact(target string) PromptMatcherFunc
- func MatcherFunc(fn func(string) bool) PromptMatcherFunc
- func MatcherLength(min, max int) PromptMatcherFunc
- func MatcherLengthMax(max int) PromptMatcherFunc
- func MatcherLengthMin(min int) PromptMatcherFunc
- func MatcherNone() PromptMatcherFunc
- func MatcherNot(matcher PromptMatcherFunc) PromptMatcherFunc
- func MatcherNotEmpty() PromptMatcherFunc
- func MatcherOr(matchers ...PromptMatcherFunc) PromptMatcherFunc
- func MatcherPrefix(prefix string) PromptMatcherFunc
- func MatcherRegex(pattern string) PromptMatcherFunc
- func MatcherSuffix(suffix string) PromptMatcherFunc
- type ReactResponseBuilder
- func (b *ReactResponseBuilder) Build() string
- func (b *ReactResponseBuilder) WithAskForClarification(question string, options []string) *ReactResponseBuilder
- func (b *ReactResponseBuilder) WithCumulativeSummary(summary string) *ReactResponseBuilder
- func (b *ReactResponseBuilder) WithDirectlyAnswer(answer string) *ReactResponseBuilder
- func (b *ReactResponseBuilder) WithHumanThought(thought string) *ReactResponseBuilder
- func (b *ReactResponseBuilder) WithRequestPlanAndExecution(planPayload string) *ReactResponseBuilder
- func (b *ReactResponseBuilder) WithRequireTool(toolName string) *ReactResponseBuilder
- type ResponseTemplate
- type ScenarioResponse
- type SequentialScenarios
- type TestScenarioDefinition
- type VerifySatisfactionBuilder
Examples ¶
- BuildAskForClarification (Complex)
- BuildBlueprintToolParams
- BuildCodeToolParams
- BuildDirectlyAnswer
- BuildRequireTool
- BuildRequireTool (Comparison)
- BuildRiskToolParams
- BuildSleepToolParams
- CallToolBuilder
- CreateCustomScenarios
- GetCommonResponse
- GetScenario
- KeywordScenarios
- KeywordScenarios (AddCustomResponse)
- KeywordScenarios (AddResponseWithMatcher)
- KeywordScenarios (BuilderWorkflow)
- KeywordScenarios (MixedMatchers)
- KeywordScenarios (MultipleKeywords)
- ListScenarios
- MatcherAnd
- MatcherAnd (Complex)
- MatcherContains
- MatcherContainsAll
- MatcherEmpty
- MatcherFunc
- MatcherLength
- MatcherNot
- MatcherOr
- MatcherPrefix
- MatcherRegex
- PrettyPrintResponse
- ReactResponseBuilder (AskForClarification)
- ReactResponseBuilder (DirectlyAnswer)
- SequentialScenarios
- SequentialScenarios (FromScenario)
- SequentialScenarios (Workflow)
- VerifySatisfactionBuilder
Constants ¶
const ( // DirectlyAnswerTemplate 直接回答模板 DirectlyAnswerTemplate = `` /* 149-byte string literal not displayed */ // RequireToolTemplate 请求工具模板 RequireToolTemplate = `` /* 152-byte string literal not displayed */ // CallToolTemplate 调用工具模板 CallToolTemplate = `{"@action": "call-tool", "params": %s}` // VerifySatisfactionTemplate 验证满意度模板 VerifySatisfactionTemplate = `{"@action": "verify-satisfaction", "user_satisfied": %t, "reasoning": "%s"}` // RequestPlanAndExecutionTemplate 请求计划执行模板 RequestPlanAndExecutionTemplate = `` /* 166-byte string literal not displayed */ // AskForClarificationTemplate 请求澄清模板 AskForClarificationTemplate = `` /* 168-byte string literal not displayed */ )
Variables ¶
var CommonResponses = map[string]string{
"simple_answer": `{"@action": "object", "next_action": {"type": "directly_answer", "answer_payload": "This is a simple answer."}, "human_readable_thought": "Providing straightforward response", "cumulative_summary": "Simple answer provided"}`,
"complex_answer": `{"@action": "object", "next_action": {"type": "directly_answer", "answer_payload": "This is a detailed answer with multiple considerations and nuances."}, "human_readable_thought": "Analyzing multiple factors before answering", "cumulative_summary": "Complex analysis completed and answer provided"}`,
"tool_sleep": `{"@action": "object", "next_action": {"type": "require_tool", "tool_require_payload": "sleep"}, "human_readable_thought": "Need to use sleep functionality", "cumulative_summary": "Requesting sleep tool"}`,
"tool_search": `{"@action": "object", "next_action": {"type": "require_tool", "tool_require_payload": "search"}, "human_readable_thought": "Need to search for information", "cumulative_summary": "Initiating search"}`,
"tool_file_operation": `{"@action": "object", "next_action": {"type": "require_tool", "tool_require_payload": "file_operation"}, "human_readable_thought": "Need to perform file operations", "cumulative_summary": "File operation requested"}`,
"params_sleep": `{"@action": "call-tool", "params": {"seconds": 0.1}}`,
"params_search": `{"@action": "call-tool", "params": {"query": "test query", "max_results": 10}}`,
"satisfaction_yes": `{"@action": "verify-satisfaction", "user_satisfied": true, "reasoning": "Task completed successfully"}`,
"satisfaction_no": `{"@action": "verify-satisfaction", "user_satisfied": false, "reasoning": "Task needs improvement"}`,
"plan_exec_simple": `{"@action": "object", "next_action": {"type": "request_plan_and_execution", "plan_request_payload": "Execute simple task"}, "human_readable_thought": "Creating execution plan", "cumulative_summary": "Plan created"}`,
"clarify_single": `{"@action": "object", "next_action": {"type": "ask_for_clarification", "ask_for_clarification_payload": {"question": "Which option do you prefer?", "options": ["option1", "option2", "option3"]}}, "human_readable_thought": "Need user input", "cumulative_summary": "Requesting clarification"}`,
"clarify_open": `{"@action": "object", "next_action": {"type": "ask_for_clarification", "ask_for_clarification_payload": {"question": "Please provide more details about your requirement.", "options": []}}, "human_readable_thought": "Need more information", "cumulative_summary": "Requesting details"}`,
"error_response": `{"@action": "object", "next_action": {"type": "directly_answer", "answer_payload": "An error occurred during processing."}, "human_readable_thought": "Error detected", "cumulative_summary": "Error handled"}`,
"memory_based_answer": `{"@action": "object", "next_action": {"type": "directly_answer", "answer_payload": "Based on previous context, here is the answer."}, "human_readable_thought": "Retrieving from memory", "cumulative_summary": "Memory-based response provided"}`,
"tool_create_risk": `{"@action": "object", "next_action": {"type": "require_tool", "tool_require_payload": "create_risk"}, "human_readable_thought": "Creating security risk entry", "cumulative_summary": "Risk creation initiated"}`,
"params_risk": `{"@action": "call-tool", "params": {"target": "http://example.com", "title": "Test Risk", "severity": "medium"}}`,
"tool_write_code": `{"@action": "object", "next_action": {"type": "require_tool", "tool_require_payload": "write_yaklang_code"}, "human_readable_thought": "Writing Yaklang code", "cumulative_summary": "Code generation started"}`,
"params_code": `{"@action": "call-tool", "params": {"code": "println(\"Hello World\")", "description": "Simple hello world"}}`,
"tool_query_doc": `{"@action": "object", "next_action": {"type": "require_tool", "tool_require_payload": "query_document"}, "human_readable_thought": "Searching documentation", "cumulative_summary": "Document query initiated"}`,
"tool_blueprint": `{"@action": "object", "next_action": {"type": "require_tool", "tool_require_payload": "blueprint"}, "human_readable_thought": "Selecting blueprint", "cumulative_summary": "Blueprint selection"}`,
"multi_tool_start": `{"@action": "object", "next_action": {"type": "require_tool", "tool_require_payload": "first_tool"}, "human_readable_thought": "Starting tool sequence", "cumulative_summary": "Multi-tool execution initiated"}`,
"task_cancel": `{"@action": "object", "next_action": {"type": "directly_answer", "answer_payload": "Task cancelled as requested."}, "human_readable_thought": "Cancelling task", "cumulative_summary": "Task cancellation processed"}`,
"task_complete": `{"@action": "object", "next_action": {"type": "directly_answer", "answer_payload": "Task completed successfully."}, "human_readable_thought": "Task finished", "cumulative_summary": "Task completion confirmed"}`,
}
CommonResponses 常见的完整响应内容
var HelloWorldScenario = NewKeywordScenarios()
var TestScenarios = map[string]*TestScenarioDefinition{ "simple_qa": &TestScenarioDefinition{ Name: "simple_qa", Description: "Simple question and answer flow", Steps: []string{ `{"@action": "object", "next_action": {"type": "directly_answer", "answer_payload": "Here is the answer to your question."}, "human_readable_thought": "Understanding the question", "cumulative_summary": "Question answered"}`, }, }, "single_tool_call": &TestScenarioDefinition{ Name: "single_tool_call", Description: "Single tool call workflow", Steps: []string{ `{"@action": "object", "next_action": {"type": "require_tool", "tool_require_payload": "sleep"}, "human_readable_thought": "Need to use sleep tool", "cumulative_summary": "Requesting tool"}`, `{"@action": "call-tool", "params": {"seconds": 0.1}}`, `{"@action": "verify-satisfaction", "user_satisfied": true, "reasoning": "Tool executed successfully"}`, }, }, "multi_tool_call": &TestScenarioDefinition{ Name: "multi_tool_call", Description: "Multiple tool call workflow", Steps: []string{ `{"@action": "object", "next_action": {"type": "require_tool", "tool_require_payload": "search"}, "human_readable_thought": "Searching first", "cumulative_summary": "Search initiated"}`, `{"@action": "call-tool", "params": {"query": "test"}}`, `{"@action": "object", "next_action": {"type": "require_tool", "tool_require_payload": "analyze"}, "human_readable_thought": "Analyzing results", "cumulative_summary": "Analysis initiated"}`, `{"@action": "call-tool", "params": {"data": "search_results"}}`, `{"@action": "verify-satisfaction", "user_satisfied": true, "reasoning": "All tools executed"}`, }, }, "plan_and_execute": &TestScenarioDefinition{ Name: "plan_and_execute", Description: "Plan and execute workflow", Steps: []string{ `{"@action": "object", "next_action": {"type": "request_plan_and_execution", "plan_request_payload": "Create and execute plan"}, "human_readable_thought": "Planning task", "cumulative_summary": "Plan requested"}`, `{"@action": "verify-satisfaction", "user_satisfied": true, "reasoning": "Plan executed successfully"}`, }, }, "clarification_flow": &TestScenarioDefinition{ Name: "clarification_flow", Description: "Clarification request workflow", Steps: []string{ `{"@action": "object", "next_action": {"type": "ask_for_clarification", "ask_for_clarification_payload": {"question": "Which option?", "options": ["A", "B", "C"]}}, "human_readable_thought": "Need clarification", "cumulative_summary": "Awaiting user input"}`, `{"@action": "object", "next_action": {"type": "directly_answer", "answer_payload": "Based on your choice, here is the result."}, "human_readable_thought": "Processing user choice", "cumulative_summary": "Choice processed"}`, }, }, "error_and_retry": &TestScenarioDefinition{ Name: "error_and_retry", Description: "Error handling and retry workflow", Steps: []string{ `{"@action": "object", "next_action": {"type": "require_tool", "tool_require_payload": "risky_tool"}, "human_readable_thought": "Trying tool", "cumulative_summary": "First attempt"}`, `{"@action": "call-tool", "params": {"retry": false}}`, `{"@action": "object", "next_action": {"type": "directly_answer", "answer_payload": "Error occurred, will retry."}, "human_readable_thought": "Handling error", "cumulative_summary": "Error detected"}`, `{"@action": "object", "next_action": {"type": "require_tool", "tool_require_payload": "risky_tool"}, "human_readable_thought": "Retrying", "cumulative_summary": "Retry attempt"}`, `{"@action": "call-tool", "params": {"retry": true}}`, `{"@action": "verify-satisfaction", "user_satisfied": true, "reasoning": "Retry successful"}`, }, }, "memory_conversation": &TestScenarioDefinition{ Name: "memory_conversation", Description: "Conversation with memory context", Steps: []string{ `{"@action": "object", "next_action": {"type": "directly_answer", "answer_payload": "First response"}, "human_readable_thought": "Initial answer", "cumulative_summary": "First interaction recorded"}`, `{"@action": "object", "next_action": {"type": "directly_answer", "answer_payload": "Second response based on context"}, "human_readable_thought": "Using previous context", "cumulative_summary": "Context-aware response"}`, `{"@action": "object", "next_action": {"type": "directly_answer", "answer_payload": "Third response with full context"}, "human_readable_thought": "Full context utilization", "cumulative_summary": "Complete conversation context maintained"}`, }, }, "code_generation": &TestScenarioDefinition{ Name: "code_generation", Description: "Code generation and validation workflow", Steps: []string{ `{"@action": "object", "next_action": {"type": "require_tool", "tool_require_payload": "write_yaklang_code"}, "human_readable_thought": "Writing code", "cumulative_summary": "Code generation started"}`, `{"@action": "call-tool", "params": {"code": "println(\"test\")", "language": "yaklang"}}`, `{"@action": "object", "next_action": {"type": "require_tool", "tool_require_payload": "check_syntax"}, "human_readable_thought": "Validating syntax", "cumulative_summary": "Syntax check initiated"}`, `{"@action": "call-tool", "params": {"code": "println(\"test\")"}}`, `{"@action": "verify-satisfaction", "user_satisfied": true, "reasoning": "Code generated and validated"}`, }, }, "risk_creation": &TestScenarioDefinition{ Name: "risk_creation", Description: "Security risk creation workflow", Steps: []string{ `{"@action": "object", "next_action": {"type": "require_tool", "tool_require_payload": "create_risk"}, "human_readable_thought": "Creating risk entry", "cumulative_summary": "Risk creation initiated"}`, `{"@action": "call-tool", "params": {"target": "http://test.com", "title": "SQL Injection", "severity": "high", "type": "sqli"}}`, `{"@action": "verify-satisfaction", "user_satisfied": true, "reasoning": "Risk created successfully"}`, }, }, "knowledge_query": &TestScenarioDefinition{ Name: "knowledge_query", Description: "Knowledge base query and answer workflow", Steps: []string{ `{"@action": "object", "next_action": {"type": "require_tool", "tool_require_payload": "query_knowledge_base"}, "human_readable_thought": "Searching knowledge", "cumulative_summary": "Knowledge query initiated"}`, `{"@action": "call-tool", "params": {"query": "How to use yaklang?"}}`, `{"@action": "object", "next_action": {"type": "directly_answer", "answer_payload": "Based on knowledge base: Yaklang is used for..."}, "human_readable_thought": "Providing knowledge-based answer", "cumulative_summary": "Answer from knowledge base"}`, }, }, "blueprint_execution": &TestScenarioDefinition{ Name: "blueprint_execution", Description: "Blueprint selection and execution workflow", Steps: []string{ `{"@action": "object", "next_action": {"type": "require_tool", "tool_require_payload": "blueprint"}, "human_readable_thought": "Selecting blueprint", "cumulative_summary": "Blueprint selection"}`, `{"@action": "call-tool", "params": {"blueprint_name": "web_scanner"}}`, `{"@action": "object", "next_action": {"type": "require_tool", "tool_require_payload": "modify_blueprint_params"}, "human_readable_thought": "Adjusting parameters", "cumulative_summary": "Parameters modified"}`, `{"@action": "call-tool", "params": {"target": "http://example.com", "depth": 3}}`, `{"@action": "verify-satisfaction", "user_satisfied": true, "reasoning": "Blueprint executed"}`, }, }, "task_queue_management": &TestScenarioDefinition{ Name: "task_queue_management", Description: "Task queue management workflow", Steps: []string{ `{"@action": "object", "next_action": {"type": "directly_answer", "answer_payload": "Task enqueued"}, "human_readable_thought": "Adding to queue", "cumulative_summary": "Task queued"}`, `{"@action": "object", "next_action": {"type": "directly_answer", "answer_payload": "Priority adjusted"}, "human_readable_thought": "Jumping queue", "cumulative_summary": "Priority changed"}`, `{"@action": "object", "next_action": {"type": "directly_answer", "answer_payload": "Task dequeued and executing"}, "human_readable_thought": "Processing task", "cumulative_summary": "Task executing"}`, }, }, "mcp_protocol": &TestScenarioDefinition{ Name: "mcp_protocol", Description: "MCP protocol tool usage workflow", Steps: []string{ `{"@action": "object", "next_action": {"type": "require_tool", "tool_require_payload": "mcp_tool"}, "human_readable_thought": "Using MCP tool", "cumulative_summary": "MCP invoked"}`, `{"@action": "call-tool", "params": {"protocol": "mcp", "action": "fetch_resource"}}`, `{"@action": "verify-satisfaction", "user_satisfied": true, "reasoning": "MCP tool executed successfully"}`, }, }, "self_reflection": &TestScenarioDefinition{ Name: "self_reflection", Description: "Self-reflection and optimization workflow", Steps: []string{ `{"@action": "object", "next_action": {"type": "directly_answer", "answer_payload": "Initial approach"}, "human_readable_thought": "First attempt", "cumulative_summary": "Initial response"}`, `{"@action": "object", "next_action": {"type": "directly_answer", "answer_payload": "After reflection, better approach"}, "human_readable_thought": "Reflecting on approach", "cumulative_summary": "Improved solution"}`, `{"@action": "object", "next_action": {"type": "directly_answer", "answer_payload": "Optimized final solution"}, "human_readable_thought": "Optimization complete", "cumulative_summary": "Best solution provided"}`, }, }, "task_cancellation": &TestScenarioDefinition{ Name: "task_cancellation", Description: "Task cancellation and cleanup workflow", Steps: []string{ `{"@action": "object", "next_action": {"type": "directly_answer", "answer_payload": "Task started"}, "human_readable_thought": "Starting task", "cumulative_summary": "Task initiated"}`, `{"@action": "object", "next_action": {"type": "directly_answer", "answer_payload": "Cancelling task"}, "human_readable_thought": "Processing cancellation", "cumulative_summary": "Cancellation in progress"}`, `{"@action": "object", "next_action": {"type": "directly_answer", "answer_payload": "Task cancelled and cleaned up"}, "human_readable_thought": "Cleanup complete", "cumulative_summary": "Task cancelled"}`, }, }, }
TestScenarios 定义常见测试场景
Functions ¶
func BuildAskForClarification ¶
BuildAskForClarification 构建请求澄清响应
Example (Complex) ¶
ExampleBuildAskForClarification_complex 演示复杂的响应构建
package main
import (
"fmt"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
// 构建一个包含多个选项的澄清请求
response := aidmock.BuildAskForClarification(
"检测到多个漏洞,请选择处理方式:",
[]string{
"生成详细报告",
"自动修复",
"添加到待处理列表",
"忽略",
},
"发现多个安全问题,需要用户决定",
"等待用户选择处理方式",
)
err := aidmock.ValidateResponse(response)
fmt.Printf("Complex response valid: %v\n", err == nil)
}
Output: Complex response valid: true
func BuildBlueprintToolParams ¶
BuildBlueprintToolParams 构建蓝图工具参数
Example ¶
ExampleBuildBlueprintToolParams 演示构建蓝图工具参数
package main
import (
"fmt"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
response := aidmock.BuildBlueprintToolParams(
"web_vulnerability_scanner",
map[string]interface{}{
"target": "http://example.com",
"depth": 3,
"threads": 5,
},
)
err := aidmock.ValidateResponse(response)
fmt.Printf("Blueprint tool params valid: %v\n", err == nil)
}
Output: Blueprint tool params valid: true
func BuildCallTool ¶
BuildCallTool 构建工具调用参数响应
func BuildCodeToolParams ¶
BuildCodeToolParams 构建代码工具参数
Example ¶
ExampleBuildCodeToolParams 演示构建代码工具参数
package main
import (
"fmt"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
response := aidmock.BuildCodeToolParams(
`println("Hello, Yaklang!")`,
"简单的Hello World程序",
"yaklang",
)
err := aidmock.ValidateResponse(response)
fmt.Printf("Code tool params valid: %v\n", err == nil)
}
Output: Code tool params valid: true
func BuildDirectlyAnswer ¶
BuildDirectlyAnswer 构建直接回答响应
Example ¶
ExampleBuildDirectlyAnswer 演示如何构建直接回答响应
package main
import (
"fmt"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
response := aidmock.BuildDirectlyAnswer(
"这是答案内容",
"正在思考如何回答",
"问题已回答",
)
// 验证响应格式
err := aidmock.ValidateResponse(response)
fmt.Printf("Response valid: %v\n", err == nil)
}
Output: Response valid: true
func BuildRequestPlanAndExecution ¶
BuildRequestPlanAndExecution 构建请求计划执行响应
func BuildRequireTool ¶
BuildRequireTool 构建请求工具响应
Example ¶
ExampleBuildRequireTool 演示如何构建工具请求
package main
import (
"fmt"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
// 请求使用sleep工具
response := aidmock.BuildRequireTool(
"sleep",
"需要暂停一下",
"请求sleep工具",
)
err := aidmock.ValidateResponse(response)
fmt.Printf("Response valid: %v\n", err == nil)
}
Output: Response valid: true
Example (Comparison) ¶
ExampleBuildRequireTool_comparison 演示Builder模式 vs 原始JSON
package main
import (
"fmt"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
// 使用Builder(推荐方式)
builderResponse := aidmock.BuildRequireTool(
"nmap",
"需要使用nmap扫描",
"请求nmap工具",
)
// 原始JSON方式(不推荐)
rawJSON := `{"@action":"object","next_action":{"type":"require_tool","tool_require_payload":"nmap"},"human_readable_thought":"需要使用nmap扫描","cumulative_summary":"请求nmap工具"}`
// 两种方式都有效,但Builder更安全、可读、易维护
err1 := aidmock.ValidateResponse(builderResponse)
err2 := aidmock.ValidateResponse(rawJSON)
fmt.Printf("Builder valid: %v\n", err1 == nil)
fmt.Printf("Raw JSON valid: %v\n", err2 == nil)
fmt.Println("Builder is recommended for type safety and maintainability")
}
Output: Builder valid: true Raw JSON valid: true Builder is recommended for type safety and maintainability
func BuildRiskToolParams ¶
BuildRiskToolParams 构建创建风险工具参数
Example ¶
ExampleBuildRiskToolParams 演示如何构建风险创建参数
package main
import (
"fmt"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
response := aidmock.BuildRiskToolParams(
"http://example.com", // target
"SQL注入漏洞", // title
"high", // severity
"sqli", // risk type
)
err := aidmock.ValidateResponse(response)
fmt.Printf("Response valid: %v\n", err == nil)
}
Output: Response valid: true
func BuildSearchToolParams ¶
BuildSearchToolParams 构建搜索工具参数
func BuildSleepToolParams ¶
BuildSleepToolParams 构建sleep工具参数
Example ¶
ExampleBuildSleepToolParams 演示如何构建sleep工具参数
package main
import (
"fmt"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
// 构建sleep 0.5秒的参数
response := aidmock.BuildSleepToolParams(0.5)
err := aidmock.ValidateResponse(response)
fmt.Printf("Response valid: %v\n", err == nil)
}
Output: Response valid: true
func BuildVerifySatisfaction ¶
BuildVerifySatisfaction 构建验证满意度响应
func GetAllTemplates ¶
func GetAllTemplates() map[string]*ResponseTemplate
GetAllTemplates 获取所有预定义的响应模板
func GetCommonResponse ¶
GetCommonResponse 获取常见响应
Example ¶
ExampleGetCommonResponse 演示如何获取常见响应
package main
import (
"fmt"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
// 获取常见响应
resp, ok := aidmock.GetCommonResponse("simple_answer")
if ok {
fmt.Printf("Response found: %v\n", len(resp) > 0)
}
// 获取不存在的响应
_, ok = aidmock.GetCommonResponse("nonexistent")
fmt.Printf("Nonexistent response found: %v\n", ok)
}
Output: Response found: true Nonexistent response found: false
func GetTemplateResponse ¶
GetTemplateResponse 使用模板生成响应
func ListScenarios ¶
func ListScenarios() []string
ListScenarios 列出所有可用的场景名称
Example ¶
ExampleListScenarios 演示如何列出所有场景
package main
import (
"fmt"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
scenarios := aidmock.ListScenarios()
fmt.Printf("Total scenarios: %d\n", len(scenarios))
fmt.Printf("First scenario exists: %v\n", len(scenarios) > 0)
}
Output: Total scenarios: 15 First scenario exists: true
func PrettyPrintResponse ¶
PrettyPrintResponse 格式化打印响应(用于调试)
Example ¶
ExamplePrettyPrintResponse 演示格式化打印响应
package main
import (
"fmt"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
response := aidmock.BuildDirectlyAnswer(
"测试答案",
"测试思考",
"测试总结",
)
// 格式化打印(实际会包含缩进和换行)
pretty := aidmock.PrettyPrintResponse(response)
// 验证格式化后仍是有效JSON
err := aidmock.ValidateResponse(pretty)
fmt.Printf("Pretty printed response valid: %v\n", err == nil)
}
Output: Pretty printed response valid: true
Types ¶
type AIScenario ¶
type AIScenario interface {
// GetAICallbackType 返回一个AI回调函数,该函数会根据请求内容返回模拟的AI响应
GetAICallbackType() aicommon.AICallbackType
}
AIScenario 是用于测试的AI场景接口 实现此接口的类型可以生成模拟的AI回调函数,用于测试AI相关功能
type CallToolBuilder ¶
type CallToolBuilder struct {
// contains filtered or unexported fields
}
CallToolBuilder 工具调用参数构建器
Example ¶
ExampleCallToolBuilder 演示构建工具调用参数
package main
import (
"fmt"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
response := aidmock.NewCallToolBuilder().
WithParam("target", "http://example.com").
WithParam("port", 8080).
WithParam("timeout", 30).
WithParam("verbose", true).
Build()
err := aidmock.ValidateResponse(response)
fmt.Printf("Response valid: %v\n", err == nil)
}
Output: Response valid: true
func (*CallToolBuilder) WithParam ¶
func (b *CallToolBuilder) WithParam(key string, value interface{}) *CallToolBuilder
WithParam 添加单个参数
func (*CallToolBuilder) WithParams ¶
func (b *CallToolBuilder) WithParams(params map[string]interface{}) *CallToolBuilder
WithParams 批量添加参数
type KeywordResponse ¶
type KeywordResponse = ScenarioResponse
KeywordResponse 是 ScenarioResponse 的别名,保持向后兼容
type KeywordScenarios ¶
type KeywordScenarios struct {
// contains filtered or unexported fields
}
KeywordScenarios 是一个基于关键词匹配的AI场景生成器 当请求的prompt中包含特定关键词时,返回预定义的AI响应内容 也支持使用自定义的匹配函数进行更灵活的匹配
Example ¶
ExampleKeywordScenarios 演示如何使用KeywordScenarios
package main
import (
"context"
"fmt"
"github.com/yaklang/yaklang/common/ai/aid/aicommon"
"github.com/yaklang/yaklang/common/ai/aid/aicommon/mock"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
// 创建一个KeywordScenarios,自动加载内置响应
scenarios := aidmock.NewKeywordScenarios()
// 获取AI回调函数
callback := scenarios.GetAICallbackType()
// 创建模拟配置
config := mock.NewMockedAIConfig(context.Background())
// 创建请求(包含关键词 "directly_answer" 和 "next_action")
req := aicommon.NewAIRequest("Please provide a directly_answer with next_action")
// 调用回调函数
resp, err := callback(config, req)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Response received: %v\n", resp != nil)
}
Output: Response received: true
Example (AddCustomResponse) ¶
ExampleKeywordScenarios_addCustomResponse 演示如何添加自定义响应
package main
import (
"fmt"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
scenarios := aidmock.NewKeywordScenarios()
// 添加自定义响应
customResponse := `{"@action": "object", "next_action": {"type": "directly_answer", "answer_payload": "Custom answer"}, "human_readable_thought": "Custom thought", "cumulative_summary": "Custom summary"}`
scenarios.AddResponse(
"my_custom", // 响应名称
[]string{"custom", "keywords"}, // 匹配关键词
customResponse, // 响应内容
"My custom response for testing", // 描述
)
// 列出所有响应
responses := scenarios.ListResponses()
fmt.Printf("Total responses: %d\n", len(responses))
// 获取特定响应
resp := scenarios.GetResponse("my_custom")
fmt.Printf("Custom response exists: %v\n", resp != nil)
}
Output: Total responses: 21 Custom response exists: true
Example (AddResponseWithMatcher) ¶
ExampleKeywordScenarios_addResponseWithMatcher 演示如何使用自定义匹配函数
package main
import (
"fmt"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
scenarios := aidmock.CreateCustomScenarios()
// 使用自定义匹配函数:匹配长度在10-50之间的prompt
customMatcher := func(prompt string) bool {
length := len(prompt)
return length >= 10 && length <= 50
}
response := aidmock.BuildDirectlyAnswer(
"Your prompt length is appropriate",
"Checking prompt length",
"Length validated",
)
scenarios.AddResponseWithMatcher(
"length_validator",
customMatcher,
response,
"Validates prompt length",
)
fmt.Printf("Response added: %v\n", scenarios.GetResponse("length_validator") != nil)
}
Output: Response added: true
Example (BuilderWorkflow) ¶
ExampleKeywordScenarios_builderWorkflow 演示完整的工具调用工作流
package main
import (
"fmt"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
// 创建一个自定义场景生成器
scenarios := aidmock.CreateCustomScenarios()
// 步骤1: 添加请求工具的响应
scenarios.AddResponse(
"request_scan_tool",
[]string{"scan", "vulnerability"},
aidmock.BuildRequireTool(
"vulnerability_scanner",
"需要使用漏洞扫描工具",
"请求扫描工具",
),
"请求漏洞扫描工具",
)
// 步骤2: 添加生成工具参数的响应
scenarios.AddResponse(
"generate_scan_params",
[]string{"parameters", "scan"},
aidmock.NewCallToolBuilder().
WithParam("target", "http://test.com").
WithParam("scan_type", "full").
WithParam("threads", 10).
Build(),
"生成扫描参数",
)
// 步骤3: 添加验证满意度的响应
scenarios.AddResponse(
"verify_scan_result",
[]string{"verify", "result"},
aidmock.BuildVerifySatisfaction(
true,
"扫描完成,发现5个漏洞",
),
"验证扫描结果",
)
fmt.Printf("Registered responses: %d\n", len(scenarios.ListResponses()))
}
Output: Registered responses: 3
Example (MixedMatchers) ¶
ExampleKeywordScenarios_mixedMatchers 演示混合使用关键词和自定义匹配器
package main
import (
"fmt"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
scenarios := aidmock.CreateCustomScenarios()
// 添加使用关键词的响应
scenarios.AddResponse(
"keyword_based",
[]string{"simple", "request"},
aidmock.BuildDirectlyAnswer("Simple response", "Keyword match", "Done"),
"Keyword-based matching",
)
// 添加使用自定义匹配器的响应
scenarios.AddResponseWithMatcher(
"matcher_based",
aidmock.MatcherRegex(`urgent|critical|emergency`),
aidmock.BuildDirectlyAnswer("High priority response", "Urgent match", "Priority"),
"Matcher-based matching",
)
fmt.Printf("Total responses: %d\n", len(scenarios.ListResponses()))
}
Output: Total responses: 2
Example (MultipleKeywords) ¶
ExampleKeywordScenarios_multipleKeywords 演示多关键词匹配
package main
import (
"context"
"fmt"
"github.com/yaklang/yaklang/common/ai/aid/aicommon"
"github.com/yaklang/yaklang/common/ai/aid/aicommon/mock"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
scenarios := aidmock.CreateCustomScenarios()
// 添加需要多个关键词的响应
scenarios.AddResponse(
"multi_keyword",
[]string{"need", "tool", "sleep"}, // 需要同时包含这3个关键词
`{"matched": true}`,
"Multi-keyword response",
)
callback := scenarios.GetAICallbackType()
config := mock.NewMockedAIConfig(context.Background())
// 测试1: 包含所有关键词 - 应该匹配
req1 := aicommon.NewAIRequest("I need to use the sleep tool")
resp1, _ := callback(config, req1)
fmt.Printf("All keywords matched: %v\n", resp1 != nil)
// 测试2: 只包含部分关键词 - 不应该匹配
req2 := aicommon.NewAIRequest("I need a tool")
resp2, _ := callback(config, req2)
fmt.Printf("Partial keywords matched: %v\n", resp2 != nil)
}
Output: All keywords matched: true Partial keywords matched: true
func CreateCustomScenarios ¶
func CreateCustomScenarios() *KeywordScenarios
CreateCustomScenarios 创建一个空的KeywordScenarios,不加载内置响应 适用于需要完全自定义响应的场景
Example ¶
ExampleCreateCustomScenarios 演示如何创建不带内置响应的场景生成器
package main
import (
"fmt"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
// 创建空的场景生成器
scenarios := aidmock.CreateCustomScenarios()
// 检查内置响应数量
fmt.Printf("Built-in responses: %d\n", len(scenarios.ListResponses()))
// 添加自定义响应
scenarios.AddResponse("custom1", []string{"test"}, `{"custom": 1}`, "Custom 1")
scenarios.AddResponse("custom2", []string{"test2"}, `{"custom": 2}`, "Custom 2")
fmt.Printf("After adding: %d\n", len(scenarios.ListResponses()))
}
Output: Built-in responses: 0 After adding: 2
func NewKeywordScenarios ¶
func NewKeywordScenarios() *KeywordScenarios
NewKeywordScenarios 创建一个新的KeywordScenarios实例,并加载内置的响应配置
func (*KeywordScenarios) AddResponse ¶
func (s *KeywordScenarios) AddResponse(name string, keywords []string, response string, description string)
AddResponse 添加自定义的关键词响应配置
func (*KeywordScenarios) AddResponseWithMatcher ¶
func (s *KeywordScenarios) AddResponseWithMatcher(name string, matcher PromptMatcherFunc, response string, description string)
AddResponseWithMatcher 添加使用自定义匹配函数的响应配置 matcher: 自定义的匹配函数,接收prompt返回是否匹配 response: AI响应内容(JSON格式) description: 响应描述
func (*KeywordScenarios) GetAICallbackType ¶
func (s *KeywordScenarios) GetAICallbackType() aicommon.AICallbackType
GetAICallbackType 实现AIScenario接口,返回AI回调函数
func (*KeywordScenarios) GetResponse ¶
func (s *KeywordScenarios) GetResponse(name string) *KeywordResponse
GetResponse 获取指定名称的响应配置
func (*KeywordScenarios) ListResponses ¶
func (s *KeywordScenarios) ListResponses() []string
ListResponses 列出所有已注册的响应名称
func (*KeywordScenarios) PrintAllResponses ¶
func (s *KeywordScenarios) PrintAllResponses()
PrintAllResponses 打印所有已注册的响应信息(用于调试)
func (*KeywordScenarios) RemoveResponse ¶
func (s *KeywordScenarios) RemoveResponse(name string)
RemoveResponse 移除指定名称的响应配置
type PromptMatcherFunc ¶
PromptMatcherFunc 是自定义的prompt匹配函数类型 接收prompt字符串,返回是否匹配
func MatcherAnd ¶
func MatcherAnd(matchers ...PromptMatcherFunc) PromptMatcherFunc
MatcherAnd 创建一个组合多个匹配器的AND匹配器(所有匹配器都要返回true)
Example ¶
ExampleMatcherAnd 演示AND组合匹配器
package main
import (
"fmt"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
scenarios := aidmock.CreateCustomScenarios()
// 组合多个条件:必须同时包含 "scan" 和 "port"
matcher := aidmock.MatcherAnd(
aidmock.MatcherContains("scan"),
aidmock.MatcherContains("port"),
)
response := aidmock.BuildRequireTool(
"port_scanner",
"Initiating port scan",
"Port scan requested",
)
scenarios.AddResponseWithMatcher(
"port_scan",
matcher,
response,
"Port scanning request",
)
fmt.Printf("Combined matcher added: %v\n", scenarios.GetResponse("port_scan") != nil)
}
Output: Combined matcher added: true
Example (Complex) ¶
ExampleMatcherAnd_complex 演示复杂匹配器组合
package main
import (
"fmt"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
scenarios := aidmock.CreateCustomScenarios()
// 复杂条件:
// 1. 必须包含 "scan" 或 "test"
// 2. 必须包含 "target"
// 3. 长度必须大于15个字符
matcher := aidmock.MatcherAnd(
aidmock.MatcherOr(
aidmock.MatcherContains("scan"),
aidmock.MatcherContains("test"),
),
aidmock.MatcherContains("target"),
aidmock.MatcherLengthMin(15),
)
response := aidmock.BuildRequireTool(
"vulnerability_scanner",
"Complex condition matched",
"Scanner activated",
)
scenarios.AddResponseWithMatcher(
"complex_scan",
matcher,
response,
"Complex scanning scenario",
)
fmt.Printf("Complex matcher added: %v\n", scenarios.GetResponse("complex_scan") != nil)
}
Output: Complex matcher added: true
func MatcherContains ¶
func MatcherContains(substring string) PromptMatcherFunc
MatcherContains 创建一个包含指定子字符串的匹配器(不区分大小写)
Example ¶
ExampleMatcherContains 演示包含匹配器
package main
import (
"fmt"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
scenarios := aidmock.CreateCustomScenarios()
// 使用便捷的匹配器函数
matcher := aidmock.MatcherContains("security")
response := aidmock.BuildRequireTool(
"security_scanner",
"Detected security-related request",
"Security scan initiated",
)
scenarios.AddResponseWithMatcher(
"security_match",
matcher,
response,
"Matches security requests",
)
fmt.Printf("Scenarios created: %v\n", len(scenarios.ListResponses()) > 0)
}
Output: Scenarios created: true
func MatcherContainsAll ¶
func MatcherContainsAll(substrings ...string) PromptMatcherFunc
MatcherContainsAll 创建一个匹配包含所有子字符串的匹配器
Example ¶
ExampleMatcherContainsAll 演示包含所有关键词匹配器
package main
import (
"fmt"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
scenarios := aidmock.CreateCustomScenarios()
// 必须同时包含所有关键词
matcher := aidmock.MatcherContainsAll("web", "application", "security", "test")
response := aidmock.BuildRequireTool(
"web_security_scanner",
"Initiating comprehensive web security test",
"Web security scan started",
)
scenarios.AddResponseWithMatcher(
"web_sec_test",
matcher,
response,
"Web application security testing",
)
fmt.Printf("ContainsAll matcher added: %v\n", scenarios.GetResponse("web_sec_test") != nil)
}
Output: ContainsAll matcher added: true
func MatcherContainsAny ¶
func MatcherContainsAny(substrings ...string) PromptMatcherFunc
MatcherContainsAny 创建一个匹配包含任一子字符串的匹配器
func MatcherContainsCaseSensitive ¶
func MatcherContainsCaseSensitive(substring string) PromptMatcherFunc
MatcherContainsCaseSensitive 创建一个包含指定子字符串的匹配器(区分大小写)
func MatcherEmpty ¶
func MatcherEmpty() PromptMatcherFunc
MatcherEmpty 创建一个匹配空prompt的匹配器
Example ¶
ExampleMatcherEmpty 演示空匹配器
package main
import (
"fmt"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
scenarios := aidmock.CreateCustomScenarios()
// 处理空prompt
emptyMatcher := aidmock.MatcherEmpty()
response := aidmock.BuildAskForClarification(
"Your prompt is empty. What would you like to do?",
[]string{"Start scanning", "Get help", "Exit"},
"Empty prompt received",
"Requesting user input",
)
scenarios.AddResponseWithMatcher(
"empty_handler",
emptyMatcher,
response,
"Handles empty prompts",
)
fmt.Printf("Empty matcher added: %v\n", scenarios.GetResponse("empty_handler") != nil)
}
Output: Empty matcher added: true
func MatcherExact ¶
func MatcherExact(target string) PromptMatcherFunc
MatcherExact 创建一个精确匹配的匹配器(不区分大小写)
func MatcherFunc ¶
func MatcherFunc(fn func(string) bool) PromptMatcherFunc
MatcherFunc 创建一个自定义函数匹配器(包装,提供更明确的语义)
Example ¶
ExampleMatcherFunc 演示自定义函数匹配器
package main
import (
"fmt"
"strings"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
scenarios := aidmock.CreateCustomScenarios()
// 使用完全自定义的匹配逻辑
customLogic := aidmock.MatcherFunc(func(prompt string) bool {
// 自定义逻辑:检查是否是问句且包含特定关键词
isQuestion := strings.HasSuffix(strings.TrimSpace(prompt), "?")
hasKeyword := strings.Contains(strings.ToLower(prompt), "vulnerability")
return isQuestion && hasKeyword
})
response := aidmock.BuildDirectlyAnswer(
"Let me help you understand vulnerabilities",
"Question about vulnerabilities detected",
"Educational response provided",
)
scenarios.AddResponseWithMatcher(
"vuln_question",
customLogic,
response,
"Vulnerability-related questions",
)
fmt.Printf("Custom logic matcher added: %v\n", scenarios.GetResponse("vuln_question") != nil)
}
Output: Custom logic matcher added: true
func MatcherLength ¶
func MatcherLength(min, max int) PromptMatcherFunc
MatcherLength 创建一个根据prompt长度匹配的匹配器
Example ¶
ExampleMatcherLength 演示长度匹配器
package main
import (
"fmt"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
scenarios := aidmock.CreateCustomScenarios()
// 匹配短prompt(1-20个字符)
shortMatcher := aidmock.MatcherLength(1, 20)
response := aidmock.BuildAskForClarification(
"Your request is too short. Could you provide more details?",
[]string{"Provide more context", "Cancel"},
"Short prompt detected",
"Requesting clarification",
)
scenarios.AddResponseWithMatcher(
"short_prompt_handler",
shortMatcher,
response,
"Handles short prompts",
)
fmt.Printf("Length matcher added: %v\n", scenarios.GetResponse("short_prompt_handler") != nil)
}
Output: Length matcher added: true
func MatcherLengthMax ¶
func MatcherLengthMax(max int) PromptMatcherFunc
MatcherLengthMax 创建一个匹配最大长度的匹配器
func MatcherLengthMin ¶
func MatcherLengthMin(min int) PromptMatcherFunc
MatcherLengthMin 创建一个匹配最小长度的匹配器
func MatcherNot ¶
func MatcherNot(matcher PromptMatcherFunc) PromptMatcherFunc
MatcherNot 创建一个反转匹配器结果的NOT匹配器
Example ¶
ExampleMatcherNot 演示NOT匹配器
package main
import (
"fmt"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
scenarios := aidmock.CreateCustomScenarios()
// 匹配不包含 "skip" 的prompt
matcher := aidmock.MatcherNot(
aidmock.MatcherContains("skip"),
)
response := aidmock.BuildDirectlyAnswer(
"Processing your request",
"Request accepted",
"Processing",
)
scenarios.AddResponseWithMatcher(
"process_request",
matcher,
response,
"Process non-skip requests",
)
fmt.Printf("NOT matcher added: %v\n", scenarios.GetResponse("process_request") != nil)
}
Output: NOT matcher added: true
func MatcherOr ¶
func MatcherOr(matchers ...PromptMatcherFunc) PromptMatcherFunc
MatcherOr 创建一个组合多个匹配器的OR匹配器(任一匹配器返回true即可)
Example ¶
ExampleMatcherOr 演示OR组合匹配器
package main
import (
"fmt"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
scenarios := aidmock.CreateCustomScenarios()
// 匹配多个可能的关键词之一
matcher := aidmock.MatcherOr(
aidmock.MatcherContains("help"),
aidmock.MatcherContains("assist"),
aidmock.MatcherContains("guide"),
)
response := aidmock.BuildDirectlyAnswer(
"How can I assist you?",
"User requesting help",
"Help offered",
)
scenarios.AddResponseWithMatcher(
"help_request",
matcher,
response,
"Help/assistance requests",
)
fmt.Printf("OR matcher added: %v\n", scenarios.GetResponse("help_request") != nil)
}
Output: OR matcher added: true
func MatcherPrefix ¶
func MatcherPrefix(prefix string) PromptMatcherFunc
MatcherPrefix 创建一个匹配指定前缀的匹配器(不区分大小写)
Example ¶
ExampleMatcherPrefix 演示前缀匹配器
package main
import (
"fmt"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
scenarios := aidmock.CreateCustomScenarios()
// 匹配以特定命令开头的prompt
commandMatcher := aidmock.MatcherPrefix("/scan")
response := aidmock.BuildRequireTool(
"scanner",
"Command detected",
"Executing scan command",
)
scenarios.AddResponseWithMatcher(
"scan_command",
commandMatcher,
response,
"Scan command handler",
)
fmt.Printf("Prefix matcher added: %v\n", scenarios.GetResponse("scan_command") != nil)
}
Output: Prefix matcher added: true
func MatcherRegex ¶
func MatcherRegex(pattern string) PromptMatcherFunc
MatcherRegex 创建一个使用正则表达式匹配的匹配器
Example ¶
ExampleMatcherRegex 演示正则表达式匹配器
package main
import (
"fmt"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
scenarios := aidmock.CreateCustomScenarios()
// 匹配IP地址格式
ipMatcher := aidmock.MatcherRegex(`\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}`)
response := aidmock.BuildDirectlyAnswer(
"IP address detected in your request",
"Parsing IP address",
"IP validated",
)
scenarios.AddResponseWithMatcher(
"ip_detector",
ipMatcher,
response,
"Detects IP addresses",
)
fmt.Printf("IP matcher added: %v\n", scenarios.GetResponse("ip_detector") != nil)
}
Output: IP matcher added: true
func MatcherSuffix ¶
func MatcherSuffix(suffix string) PromptMatcherFunc
MatcherSuffix 创建一个匹配指定后缀的匹配器(不区分大小写)
type ReactResponseBuilder ¶
type ReactResponseBuilder struct {
// contains filtered or unexported fields
}
ReactResponseBuilder 是ReAct响应的基础构建器
Example (AskForClarification) ¶
ExampleReactResponseBuilder_askForClarification 演示构建澄清请求
package main
import (
"fmt"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
response := aidmock.NewReactResponseBuilder().
WithAskForClarification(
"请选择扫描模式",
[]string{"快速扫描", "深度扫描", "自定义扫描"},
).
WithHumanThought("需要用户选择扫描模式").
WithCumulativeSummary("等待用户输入").
Build()
err := aidmock.ValidateResponse(response)
fmt.Printf("Response valid: %v\n", err == nil)
}
Output: Response valid: true
Example (DirectlyAnswer) ¶
ExampleReactResponseBuilder_directlyAnswer 演示使用链式调用构建直接回答
package main
import (
"fmt"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
response := aidmock.NewReactResponseBuilder().
WithDirectlyAnswer("自定义答案").
WithHumanThought("自定义思考过程").
WithCumulativeSummary("自定义总结").
Build()
err := aidmock.ValidateResponse(response)
fmt.Printf("Response valid: %v\n", err == nil)
}
Output: Response valid: true
func NewReactResponseBuilder ¶
func NewReactResponseBuilder() *ReactResponseBuilder
NewReactResponseBuilder 创建一个新的ReAct响应构建器
func (*ReactResponseBuilder) Build ¶
func (b *ReactResponseBuilder) Build() string
Build 构建JSON响应字符串
func (*ReactResponseBuilder) WithAskForClarification ¶
func (b *ReactResponseBuilder) WithAskForClarification(question string, options []string) *ReactResponseBuilder
WithAskForClarification 设置为请求澄清类型
func (*ReactResponseBuilder) WithCumulativeSummary ¶
func (b *ReactResponseBuilder) WithCumulativeSummary(summary string) *ReactResponseBuilder
WithCumulativeSummary 设置累积总结
func (*ReactResponseBuilder) WithDirectlyAnswer ¶
func (b *ReactResponseBuilder) WithDirectlyAnswer(answer string) *ReactResponseBuilder
WithDirectlyAnswer 设置为直接回答类型
func (*ReactResponseBuilder) WithHumanThought ¶
func (b *ReactResponseBuilder) WithHumanThought(thought string) *ReactResponseBuilder
WithHumanThought 设置人类可读的思考过程
func (*ReactResponseBuilder) WithRequestPlanAndExecution ¶
func (b *ReactResponseBuilder) WithRequestPlanAndExecution(planPayload string) *ReactResponseBuilder
WithRequestPlanAndExecution 设置为请求计划和执行类型
func (*ReactResponseBuilder) WithRequireTool ¶
func (b *ReactResponseBuilder) WithRequireTool(toolName string) *ReactResponseBuilder
WithRequireTool 设置为请求工具类型
type ResponseTemplate ¶
ResponseTemplate 响应模板结构
type ScenarioResponse ¶
type ScenarioResponse struct {
Name string // 响应的名称
Keywords []string // 需要匹配的关键词列表(AND关系,所有关键词都要出现)
Matcher PromptMatcherFunc // 自定义匹配函数(如果设置,优先使用此函数)
Response string // AI响应内容(JSON格式)
Description string // 响应描述
}
ScenarioResponse 表示一个场景响应配置
type SequentialScenarios ¶
type SequentialScenarios struct {
// contains filtered or unexported fields
}
SequentialScenarios 顺序响应场景生成器 用于按顺序返回预定义的响应序列,适合测试多步骤流程
Example ¶
ExampleSequentialScenarios 演示如何使用SequentialScenarios
package main
import (
"context"
"fmt"
"github.com/yaklang/yaklang/common/ai/aid/aicommon"
"github.com/yaklang/yaklang/common/ai/aid/aicommon/mock"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
// 定义响应序列
responses := []string{
`{"step": 1, "action": "first"}`,
`{"step": 2, "action": "second"}`,
`{"step": 3, "action": "third"}`,
}
// 创建顺序场景生成器
scenarios := aidmock.NewSequentialScenarios(responses)
// 获取AI回调函数
callback := scenarios.GetAICallbackType()
config := mock.NewMockedAIConfig(context.Background())
// 按顺序调用
for i := 0; i < 3; i++ {
req := aicommon.NewAIRequest("test")
resp, _ := callback(config, req)
fmt.Printf("Response %d: %v\n", i+1, resp != nil)
}
}
Output: Response 1: true Response 2: true Response 3: true
Example (FromScenario) ¶
ExampleSequentialScenarios_fromScenario 演示如何从场景创建SequentialScenarios
package main
import (
"context"
"fmt"
"github.com/yaklang/yaklang/common/ai/aid/aicommon"
"github.com/yaklang/yaklang/common/ai/aid/aicommon/mock"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
// 从预定义场景创建场景生成器
scenarios := aidmock.NewSequentialScenariosFromScenario("simple_qa")
// 获取当前索引
fmt.Printf("Initial index: %d\n", scenarios.GetCurrentIndex())
// 调用一次
callback := scenarios.GetAICallbackType()
config := mock.NewMockedAIConfig(context.Background())
req := aicommon.NewAIRequest("test")
_, _ = callback(config, req)
fmt.Printf("After call index: %d\n", scenarios.GetCurrentIndex())
// 重置
scenarios.Reset()
fmt.Printf("After reset index: %d\n", scenarios.GetCurrentIndex())
}
Output: Initial index: 0 After call index: 1 After reset index: 0
Example (Workflow) ¶
ExampleSequentialScenarios_workflow 演示顺序响应工作流
package main
import (
"fmt"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
// 使用builder创建完整的工作流序列
responses := []string{
// 1. 请求工具
aidmock.BuildRequireTool(
"port_scanner",
"需要扫描端口",
"请求端口扫描工具",
),
// 2. 提供工具参数
aidmock.NewCallToolBuilder().
WithParam("target", "192.168.1.1").
WithParam("port_range", "1-1000").
Build(),
// 3. 验证结果
aidmock.BuildVerifySatisfaction(
true,
"端口扫描完成,发现3个开放端口",
),
}
scenarios := aidmock.NewSequentialScenarios(responses)
fmt.Printf("Workflow steps: %d\n", len(responses))
fmt.Printf("Current index: %d\n", scenarios.GetCurrentIndex())
}
Output: Workflow steps: 3 Current index: 0
func NewSequentialScenarios ¶
func NewSequentialScenarios(responses []string) *SequentialScenarios
NewSequentialScenarios 创建一个顺序响应场景生成器
func NewSequentialScenariosFromScenario ¶
func NewSequentialScenariosFromScenario(scenarioName string) *SequentialScenarios
NewSequentialScenariosFromScenario 从场景创建顺序响应场景生成器
func (*SequentialScenarios) AddResponse ¶
func (s *SequentialScenarios) AddResponse(response string)
AddResponse 添加响应到序列
func (*SequentialScenarios) GetAICallbackType ¶
func (s *SequentialScenarios) GetAICallbackType() aicommon.AICallbackType
GetAICallbackType 实现AIScenario接口
func (*SequentialScenarios) GetCurrentIndex ¶
func (s *SequentialScenarios) GetCurrentIndex() int
GetCurrentIndex 获取当前索引
type TestScenarioDefinition ¶
type TestScenarioDefinition struct {
Name string // 场景名称
Description string // 场景描述
Steps []string // 响应步骤(按顺序)
}
TestScenarioDefinition 测试场景定义 用于描述特定测试场景中的AI响应序列
func GetScenario ¶
func GetScenario(name string) (*TestScenarioDefinition, bool)
GetScenario 获取指定场景的响应序列
Example ¶
ExampleGetScenario 演示如何获取场景信息
package main
import (
"fmt"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
// 获取单个场景
scenario, ok := aidmock.GetScenario("single_tool_call")
if ok {
fmt.Printf("Scenario: %s\n", scenario.Name)
fmt.Printf("Description: %s\n", scenario.Description)
fmt.Printf("Steps: %d\n", len(scenario.Steps))
}
}
Output: Scenario: single_tool_call Description: Single tool call workflow Steps: 3
type VerifySatisfactionBuilder ¶
type VerifySatisfactionBuilder struct {
// contains filtered or unexported fields
}
VerifySatisfactionBuilder 验证满意度构建器
Example ¶
ExampleVerifySatisfactionBuilder 演示构建满意度验证
package main
import (
"fmt"
aidmock "github.com/yaklang/yaklang/common/aiengine/tests/aid_mock"
)
func main() {
// 正面响应
positiveResponse := aidmock.NewVerifySatisfactionBuilder().
WithSatisfied(true).
WithReasoning("扫描已完成,发现3个漏洞").
Build()
// 负面响应
negativeResponse := aidmock.NewVerifySatisfactionBuilder().
WithSatisfied(false).
WithReasoning("需要提供更多目标信息").
Build()
err1 := aidmock.ValidateResponse(positiveResponse)
err2 := aidmock.ValidateResponse(negativeResponse)
fmt.Printf("Positive valid: %v\n", err1 == nil)
fmt.Printf("Negative valid: %v\n", err2 == nil)
}
Output: Positive valid: true Negative valid: true
func NewVerifySatisfactionBuilder ¶
func NewVerifySatisfactionBuilder() *VerifySatisfactionBuilder
NewVerifySatisfactionBuilder 创建验证满意度构建器
func (*VerifySatisfactionBuilder) Build ¶
func (b *VerifySatisfactionBuilder) Build() string
Build 构建JSON响应字符串
func (*VerifySatisfactionBuilder) WithReasoning ¶
func (b *VerifySatisfactionBuilder) WithReasoning(reasoning string) *VerifySatisfactionBuilder
WithReasoning 设置原因
func (*VerifySatisfactionBuilder) WithSatisfied ¶
func (b *VerifySatisfactionBuilder) WithSatisfied(satisfied bool) *VerifySatisfactionBuilder
WithSatisfied 设置是否满意