ContextMatcher

Struct ContextMatcher 

Source
pub struct ContextMatcher {
    pub task_type: Option<String>,
    pub user_state: Option<String>,
    pub task_health: Option<TaskHealth>,
}
Expand description

ContextMatcher: Runtime context for matching conditional fragments

Used to evaluate whether conditional fragments should be activated.

Fields§

§task_type: Option<String>§user_state: Option<String>§task_health: Option<TaskHealth>

Implementations§

Source§

impl ContextMatcher

Source

pub fn new() -> Self

Create a new context matcher

Examples found in repository?
examples/basic_expertise.rs (line 83)
7fn main() {
8    println!("=== Basic Expertise Example ===\n");
9
10    // Create a code review expertise
11    let expertise = Expertise::new("rust-code-reviewer", "1.0.0")
12        .with_tag("lang:rust")
13        .with_tag("role:reviewer")
14        .with_tag("style:thorough")
15        // Critical: Always verify compilation
16        .with_fragment(
17            WeightedFragment::new(KnowledgeFragment::Text(
18                "ALWAYS run `cargo check` before reviewing code. Never review code that doesn't compile.".to_string(),
19            ))
20            .with_priority(Priority::Critical),
21        )
22        // High: Security checks for at-risk tasks
23        .with_fragment(
24            WeightedFragment::new(KnowledgeFragment::Logic {
25                instruction: "Perform security vulnerability scan".to_string(),
26                steps: vec![
27                    "Check for SQL injection vulnerabilities".to_string(),
28                    "Verify input validation and sanitization".to_string(),
29                    "Review error handling for information leakage".to_string(),
30                    "Check for unsafe code blocks and justify their usage".to_string(),
31                ],
32            })
33            .with_priority(Priority::High)
34            .with_context(ContextProfile::Conditional {
35                task_types: vec!["security-review".to_string()],
36                user_states: vec![],
37                task_health: Some(TaskHealth::AtRisk),
38            }),
39        )
40        // Normal: Code quality guidelines
41        .with_fragment(
42            WeightedFragment::new(KnowledgeFragment::Guideline {
43                rule: "Prefer explicit error handling over unwrap/expect".to_string(),
44                anchors: vec![Anchor {
45                    context: "Parsing user input".to_string(),
46                    positive: "let value = parse_input(s).map_err(|e| Error::InvalidInput(e))?;".to_string(),
47                    negative: "let value = parse_input(s).unwrap();".to_string(),
48                    reason: "Unwrap can panic. Use proper error handling for user input.".to_string(),
49                }],
50            })
51            .with_priority(Priority::Normal),
52        )
53        // Low: Documentation suggestions
54        .with_fragment(
55            WeightedFragment::new(KnowledgeFragment::Text(
56                "Consider adding doc comments for public APIs. Use `cargo doc` to preview.".to_string(),
57            ))
58            .with_priority(Priority::Low),
59        )
60        // Quality standards
61        .with_fragment(
62            WeightedFragment::new(KnowledgeFragment::QualityStandard {
63                criteria: vec![
64                    "Code compiles without warnings".to_string(),
65                    "All tests pass".to_string(),
66                    "No clippy warnings".to_string(),
67                    "Public APIs have documentation".to_string(),
68                ],
69                passing_grade: "All criteria must be met before approval".to_string(),
70            })
71            .with_priority(Priority::High),
72        );
73
74    // Display expertise in various formats
75    println!("--- Tree Visualization ---\n");
76    println!("{}", expertise.to_tree());
77
78    println!("\n--- Generated Prompt (All Contexts) ---\n");
79    println!("{}", expertise.to_prompt());
80
81    println!("\n--- Generated Prompt (Security Review, At Risk) ---\n");
82    use llm_toolkit_expertise::ContextMatcher;
83    let security_context = ContextMatcher::new()
84        .with_task_type("security-review")
85        .with_task_health(TaskHealth::AtRisk);
86    println!("{}", expertise.to_prompt_with_context(&security_context));
87
88    println!("\n--- Mermaid Graph ---\n");
89    println!("{}", expertise.to_mermaid());
90
91    println!("\n--- JSON Serialization ---\n");
92    let json = serde_json::to_string_pretty(&expertise).expect("Failed to serialize");
93    println!("{}", json);
94}
More examples
Hide additional examples
examples/prompt_generation.rs (line 103)
8fn main() {
9    println!("=== Context-Aware Prompt Generation ===\n");
10
11    // Create an expertise with context-conditional fragments
12    let expertise = Expertise::new("adaptive-assistant", "1.0.0")
13        .with_tag("adaptive")
14        .with_tag("context-aware")
15        // Always active: Basic guidelines
16        .with_fragment(
17            WeightedFragment::new(KnowledgeFragment::Text(
18                "Be helpful, concise, and accurate in all responses.".to_string(),
19            ))
20            .with_priority(Priority::Critical)
21            .with_context(ContextProfile::Always),
22        )
23        // On Track: Speed mode
24        .with_fragment(
25            WeightedFragment::new(KnowledgeFragment::Logic {
26                instruction: "Optimize for speed and efficiency".to_string(),
27                steps: vec![
28                    "Provide direct, concise answers".to_string(),
29                    "Skip verbose explanations unless asked".to_string(),
30                    "Use shortcuts and best practices".to_string(),
31                ],
32            })
33            .with_priority(Priority::High)
34            .with_context(ContextProfile::Conditional {
35                task_types: vec![],
36                user_states: vec![],
37                task_health: Some(TaskHealth::OnTrack),
38            }),
39        )
40        // At Risk: Careful mode
41        .with_fragment(
42            WeightedFragment::new(KnowledgeFragment::Logic {
43                instruction: "Proceed with caution and verification".to_string(),
44                steps: vec![
45                    "Double-check all assumptions".to_string(),
46                    "Ask clarifying questions".to_string(),
47                    "Verify requirements before proceeding".to_string(),
48                    "Explain reasoning for each decision".to_string(),
49                ],
50            })
51            .with_priority(Priority::High)
52            .with_context(ContextProfile::Conditional {
53                task_types: vec![],
54                user_states: vec![],
55                task_health: Some(TaskHealth::AtRisk),
56            }),
57        )
58        // Off Track: Stop mode
59        .with_fragment(
60            WeightedFragment::new(KnowledgeFragment::Text(
61                "STOP. The current approach is not working. Reassess the problem, consult with the user, and propose a different strategy before continuing.".to_string(),
62            ))
63            .with_priority(Priority::Critical)
64            .with_context(ContextProfile::Conditional {
65                task_types: vec![],
66                user_states: vec![],
67                task_health: Some(TaskHealth::OffTrack),
68            }),
69        )
70        // Beginner user state
71        .with_fragment(
72            WeightedFragment::new(KnowledgeFragment::Text(
73                "Provide detailed explanations and educational context. Avoid jargon.".to_string(),
74            ))
75            .with_priority(Priority::High)
76            .with_context(ContextProfile::Conditional {
77                task_types: vec![],
78                user_states: vec!["beginner".to_string()],
79                task_health: None,
80            }),
81        )
82        // Debug task type
83        .with_fragment(
84            WeightedFragment::new(KnowledgeFragment::Logic {
85                instruction: "Systematic debugging approach".to_string(),
86                steps: vec![
87                    "Reproduce the issue".to_string(),
88                    "Isolate the root cause".to_string(),
89                    "Propose minimal fix".to_string(),
90                    "Verify fix doesn't break other functionality".to_string(),
91                ],
92            })
93            .with_priority(Priority::High)
94            .with_context(ContextProfile::Conditional {
95                task_types: vec!["debug".to_string()],
96                user_states: vec![],
97                task_health: None,
98            }),
99        );
100
101    // Test different contexts
102    let scenarios = vec![
103        ("Default (no context)", ContextMatcher::new()),
104        (
105            "On Track",
106            ContextMatcher::new().with_task_health(TaskHealth::OnTrack),
107        ),
108        (
109            "At Risk",
110            ContextMatcher::new().with_task_health(TaskHealth::AtRisk),
111        ),
112        (
113            "Off Track",
114            ContextMatcher::new().with_task_health(TaskHealth::OffTrack),
115        ),
116        (
117            "Beginner User",
118            ContextMatcher::new().with_user_state("beginner"),
119        ),
120        ("Debug Task", ContextMatcher::new().with_task_type("debug")),
121        (
122            "Debug + At Risk",
123            ContextMatcher::new()
124                .with_task_type("debug")
125                .with_task_health(TaskHealth::AtRisk),
126        ),
127    ];
128
129    for (name, context) in scenarios {
130        println!("### Scenario: {}\n", name);
131        let prompt = expertise.to_prompt_with_context(&context);
132        println!("{}", prompt);
133        println!("---\n");
134    }
135
136    println!("\n=== Visualization ===\n");
137    println!("{}", expertise.to_tree());
138}
Source

pub fn with_task_type(self, task_type: impl Into<String>) -> Self

Set task type

Examples found in repository?
examples/basic_expertise.rs (line 84)
7fn main() {
8    println!("=== Basic Expertise Example ===\n");
9
10    // Create a code review expertise
11    let expertise = Expertise::new("rust-code-reviewer", "1.0.0")
12        .with_tag("lang:rust")
13        .with_tag("role:reviewer")
14        .with_tag("style:thorough")
15        // Critical: Always verify compilation
16        .with_fragment(
17            WeightedFragment::new(KnowledgeFragment::Text(
18                "ALWAYS run `cargo check` before reviewing code. Never review code that doesn't compile.".to_string(),
19            ))
20            .with_priority(Priority::Critical),
21        )
22        // High: Security checks for at-risk tasks
23        .with_fragment(
24            WeightedFragment::new(KnowledgeFragment::Logic {
25                instruction: "Perform security vulnerability scan".to_string(),
26                steps: vec![
27                    "Check for SQL injection vulnerabilities".to_string(),
28                    "Verify input validation and sanitization".to_string(),
29                    "Review error handling for information leakage".to_string(),
30                    "Check for unsafe code blocks and justify their usage".to_string(),
31                ],
32            })
33            .with_priority(Priority::High)
34            .with_context(ContextProfile::Conditional {
35                task_types: vec!["security-review".to_string()],
36                user_states: vec![],
37                task_health: Some(TaskHealth::AtRisk),
38            }),
39        )
40        // Normal: Code quality guidelines
41        .with_fragment(
42            WeightedFragment::new(KnowledgeFragment::Guideline {
43                rule: "Prefer explicit error handling over unwrap/expect".to_string(),
44                anchors: vec![Anchor {
45                    context: "Parsing user input".to_string(),
46                    positive: "let value = parse_input(s).map_err(|e| Error::InvalidInput(e))?;".to_string(),
47                    negative: "let value = parse_input(s).unwrap();".to_string(),
48                    reason: "Unwrap can panic. Use proper error handling for user input.".to_string(),
49                }],
50            })
51            .with_priority(Priority::Normal),
52        )
53        // Low: Documentation suggestions
54        .with_fragment(
55            WeightedFragment::new(KnowledgeFragment::Text(
56                "Consider adding doc comments for public APIs. Use `cargo doc` to preview.".to_string(),
57            ))
58            .with_priority(Priority::Low),
59        )
60        // Quality standards
61        .with_fragment(
62            WeightedFragment::new(KnowledgeFragment::QualityStandard {
63                criteria: vec![
64                    "Code compiles without warnings".to_string(),
65                    "All tests pass".to_string(),
66                    "No clippy warnings".to_string(),
67                    "Public APIs have documentation".to_string(),
68                ],
69                passing_grade: "All criteria must be met before approval".to_string(),
70            })
71            .with_priority(Priority::High),
72        );
73
74    // Display expertise in various formats
75    println!("--- Tree Visualization ---\n");
76    println!("{}", expertise.to_tree());
77
78    println!("\n--- Generated Prompt (All Contexts) ---\n");
79    println!("{}", expertise.to_prompt());
80
81    println!("\n--- Generated Prompt (Security Review, At Risk) ---\n");
82    use llm_toolkit_expertise::ContextMatcher;
83    let security_context = ContextMatcher::new()
84        .with_task_type("security-review")
85        .with_task_health(TaskHealth::AtRisk);
86    println!("{}", expertise.to_prompt_with_context(&security_context));
87
88    println!("\n--- Mermaid Graph ---\n");
89    println!("{}", expertise.to_mermaid());
90
91    println!("\n--- JSON Serialization ---\n");
92    let json = serde_json::to_string_pretty(&expertise).expect("Failed to serialize");
93    println!("{}", json);
94}
More examples
Hide additional examples
examples/prompt_generation.rs (line 120)
8fn main() {
9    println!("=== Context-Aware Prompt Generation ===\n");
10
11    // Create an expertise with context-conditional fragments
12    let expertise = Expertise::new("adaptive-assistant", "1.0.0")
13        .with_tag("adaptive")
14        .with_tag("context-aware")
15        // Always active: Basic guidelines
16        .with_fragment(
17            WeightedFragment::new(KnowledgeFragment::Text(
18                "Be helpful, concise, and accurate in all responses.".to_string(),
19            ))
20            .with_priority(Priority::Critical)
21            .with_context(ContextProfile::Always),
22        )
23        // On Track: Speed mode
24        .with_fragment(
25            WeightedFragment::new(KnowledgeFragment::Logic {
26                instruction: "Optimize for speed and efficiency".to_string(),
27                steps: vec![
28                    "Provide direct, concise answers".to_string(),
29                    "Skip verbose explanations unless asked".to_string(),
30                    "Use shortcuts and best practices".to_string(),
31                ],
32            })
33            .with_priority(Priority::High)
34            .with_context(ContextProfile::Conditional {
35                task_types: vec![],
36                user_states: vec![],
37                task_health: Some(TaskHealth::OnTrack),
38            }),
39        )
40        // At Risk: Careful mode
41        .with_fragment(
42            WeightedFragment::new(KnowledgeFragment::Logic {
43                instruction: "Proceed with caution and verification".to_string(),
44                steps: vec![
45                    "Double-check all assumptions".to_string(),
46                    "Ask clarifying questions".to_string(),
47                    "Verify requirements before proceeding".to_string(),
48                    "Explain reasoning for each decision".to_string(),
49                ],
50            })
51            .with_priority(Priority::High)
52            .with_context(ContextProfile::Conditional {
53                task_types: vec![],
54                user_states: vec![],
55                task_health: Some(TaskHealth::AtRisk),
56            }),
57        )
58        // Off Track: Stop mode
59        .with_fragment(
60            WeightedFragment::new(KnowledgeFragment::Text(
61                "STOP. The current approach is not working. Reassess the problem, consult with the user, and propose a different strategy before continuing.".to_string(),
62            ))
63            .with_priority(Priority::Critical)
64            .with_context(ContextProfile::Conditional {
65                task_types: vec![],
66                user_states: vec![],
67                task_health: Some(TaskHealth::OffTrack),
68            }),
69        )
70        // Beginner user state
71        .with_fragment(
72            WeightedFragment::new(KnowledgeFragment::Text(
73                "Provide detailed explanations and educational context. Avoid jargon.".to_string(),
74            ))
75            .with_priority(Priority::High)
76            .with_context(ContextProfile::Conditional {
77                task_types: vec![],
78                user_states: vec!["beginner".to_string()],
79                task_health: None,
80            }),
81        )
82        // Debug task type
83        .with_fragment(
84            WeightedFragment::new(KnowledgeFragment::Logic {
85                instruction: "Systematic debugging approach".to_string(),
86                steps: vec![
87                    "Reproduce the issue".to_string(),
88                    "Isolate the root cause".to_string(),
89                    "Propose minimal fix".to_string(),
90                    "Verify fix doesn't break other functionality".to_string(),
91                ],
92            })
93            .with_priority(Priority::High)
94            .with_context(ContextProfile::Conditional {
95                task_types: vec!["debug".to_string()],
96                user_states: vec![],
97                task_health: None,
98            }),
99        );
100
101    // Test different contexts
102    let scenarios = vec![
103        ("Default (no context)", ContextMatcher::new()),
104        (
105            "On Track",
106            ContextMatcher::new().with_task_health(TaskHealth::OnTrack),
107        ),
108        (
109            "At Risk",
110            ContextMatcher::new().with_task_health(TaskHealth::AtRisk),
111        ),
112        (
113            "Off Track",
114            ContextMatcher::new().with_task_health(TaskHealth::OffTrack),
115        ),
116        (
117            "Beginner User",
118            ContextMatcher::new().with_user_state("beginner"),
119        ),
120        ("Debug Task", ContextMatcher::new().with_task_type("debug")),
121        (
122            "Debug + At Risk",
123            ContextMatcher::new()
124                .with_task_type("debug")
125                .with_task_health(TaskHealth::AtRisk),
126        ),
127    ];
128
129    for (name, context) in scenarios {
130        println!("### Scenario: {}\n", name);
131        let prompt = expertise.to_prompt_with_context(&context);
132        println!("{}", prompt);
133        println!("---\n");
134    }
135
136    println!("\n=== Visualization ===\n");
137    println!("{}", expertise.to_tree());
138}
Source

pub fn with_user_state(self, user_state: impl Into<String>) -> Self

Set user state

Examples found in repository?
examples/prompt_generation.rs (line 118)
8fn main() {
9    println!("=== Context-Aware Prompt Generation ===\n");
10
11    // Create an expertise with context-conditional fragments
12    let expertise = Expertise::new("adaptive-assistant", "1.0.0")
13        .with_tag("adaptive")
14        .with_tag("context-aware")
15        // Always active: Basic guidelines
16        .with_fragment(
17            WeightedFragment::new(KnowledgeFragment::Text(
18                "Be helpful, concise, and accurate in all responses.".to_string(),
19            ))
20            .with_priority(Priority::Critical)
21            .with_context(ContextProfile::Always),
22        )
23        // On Track: Speed mode
24        .with_fragment(
25            WeightedFragment::new(KnowledgeFragment::Logic {
26                instruction: "Optimize for speed and efficiency".to_string(),
27                steps: vec![
28                    "Provide direct, concise answers".to_string(),
29                    "Skip verbose explanations unless asked".to_string(),
30                    "Use shortcuts and best practices".to_string(),
31                ],
32            })
33            .with_priority(Priority::High)
34            .with_context(ContextProfile::Conditional {
35                task_types: vec![],
36                user_states: vec![],
37                task_health: Some(TaskHealth::OnTrack),
38            }),
39        )
40        // At Risk: Careful mode
41        .with_fragment(
42            WeightedFragment::new(KnowledgeFragment::Logic {
43                instruction: "Proceed with caution and verification".to_string(),
44                steps: vec![
45                    "Double-check all assumptions".to_string(),
46                    "Ask clarifying questions".to_string(),
47                    "Verify requirements before proceeding".to_string(),
48                    "Explain reasoning for each decision".to_string(),
49                ],
50            })
51            .with_priority(Priority::High)
52            .with_context(ContextProfile::Conditional {
53                task_types: vec![],
54                user_states: vec![],
55                task_health: Some(TaskHealth::AtRisk),
56            }),
57        )
58        // Off Track: Stop mode
59        .with_fragment(
60            WeightedFragment::new(KnowledgeFragment::Text(
61                "STOP. The current approach is not working. Reassess the problem, consult with the user, and propose a different strategy before continuing.".to_string(),
62            ))
63            .with_priority(Priority::Critical)
64            .with_context(ContextProfile::Conditional {
65                task_types: vec![],
66                user_states: vec![],
67                task_health: Some(TaskHealth::OffTrack),
68            }),
69        )
70        // Beginner user state
71        .with_fragment(
72            WeightedFragment::new(KnowledgeFragment::Text(
73                "Provide detailed explanations and educational context. Avoid jargon.".to_string(),
74            ))
75            .with_priority(Priority::High)
76            .with_context(ContextProfile::Conditional {
77                task_types: vec![],
78                user_states: vec!["beginner".to_string()],
79                task_health: None,
80            }),
81        )
82        // Debug task type
83        .with_fragment(
84            WeightedFragment::new(KnowledgeFragment::Logic {
85                instruction: "Systematic debugging approach".to_string(),
86                steps: vec![
87                    "Reproduce the issue".to_string(),
88                    "Isolate the root cause".to_string(),
89                    "Propose minimal fix".to_string(),
90                    "Verify fix doesn't break other functionality".to_string(),
91                ],
92            })
93            .with_priority(Priority::High)
94            .with_context(ContextProfile::Conditional {
95                task_types: vec!["debug".to_string()],
96                user_states: vec![],
97                task_health: None,
98            }),
99        );
100
101    // Test different contexts
102    let scenarios = vec![
103        ("Default (no context)", ContextMatcher::new()),
104        (
105            "On Track",
106            ContextMatcher::new().with_task_health(TaskHealth::OnTrack),
107        ),
108        (
109            "At Risk",
110            ContextMatcher::new().with_task_health(TaskHealth::AtRisk),
111        ),
112        (
113            "Off Track",
114            ContextMatcher::new().with_task_health(TaskHealth::OffTrack),
115        ),
116        (
117            "Beginner User",
118            ContextMatcher::new().with_user_state("beginner"),
119        ),
120        ("Debug Task", ContextMatcher::new().with_task_type("debug")),
121        (
122            "Debug + At Risk",
123            ContextMatcher::new()
124                .with_task_type("debug")
125                .with_task_health(TaskHealth::AtRisk),
126        ),
127    ];
128
129    for (name, context) in scenarios {
130        println!("### Scenario: {}\n", name);
131        let prompt = expertise.to_prompt_with_context(&context);
132        println!("{}", prompt);
133        println!("---\n");
134    }
135
136    println!("\n=== Visualization ===\n");
137    println!("{}", expertise.to_tree());
138}
Source

pub fn with_task_health(self, task_health: TaskHealth) -> Self

Set task health

Examples found in repository?
examples/basic_expertise.rs (line 85)
7fn main() {
8    println!("=== Basic Expertise Example ===\n");
9
10    // Create a code review expertise
11    let expertise = Expertise::new("rust-code-reviewer", "1.0.0")
12        .with_tag("lang:rust")
13        .with_tag("role:reviewer")
14        .with_tag("style:thorough")
15        // Critical: Always verify compilation
16        .with_fragment(
17            WeightedFragment::new(KnowledgeFragment::Text(
18                "ALWAYS run `cargo check` before reviewing code. Never review code that doesn't compile.".to_string(),
19            ))
20            .with_priority(Priority::Critical),
21        )
22        // High: Security checks for at-risk tasks
23        .with_fragment(
24            WeightedFragment::new(KnowledgeFragment::Logic {
25                instruction: "Perform security vulnerability scan".to_string(),
26                steps: vec![
27                    "Check for SQL injection vulnerabilities".to_string(),
28                    "Verify input validation and sanitization".to_string(),
29                    "Review error handling for information leakage".to_string(),
30                    "Check for unsafe code blocks and justify their usage".to_string(),
31                ],
32            })
33            .with_priority(Priority::High)
34            .with_context(ContextProfile::Conditional {
35                task_types: vec!["security-review".to_string()],
36                user_states: vec![],
37                task_health: Some(TaskHealth::AtRisk),
38            }),
39        )
40        // Normal: Code quality guidelines
41        .with_fragment(
42            WeightedFragment::new(KnowledgeFragment::Guideline {
43                rule: "Prefer explicit error handling over unwrap/expect".to_string(),
44                anchors: vec![Anchor {
45                    context: "Parsing user input".to_string(),
46                    positive: "let value = parse_input(s).map_err(|e| Error::InvalidInput(e))?;".to_string(),
47                    negative: "let value = parse_input(s).unwrap();".to_string(),
48                    reason: "Unwrap can panic. Use proper error handling for user input.".to_string(),
49                }],
50            })
51            .with_priority(Priority::Normal),
52        )
53        // Low: Documentation suggestions
54        .with_fragment(
55            WeightedFragment::new(KnowledgeFragment::Text(
56                "Consider adding doc comments for public APIs. Use `cargo doc` to preview.".to_string(),
57            ))
58            .with_priority(Priority::Low),
59        )
60        // Quality standards
61        .with_fragment(
62            WeightedFragment::new(KnowledgeFragment::QualityStandard {
63                criteria: vec![
64                    "Code compiles without warnings".to_string(),
65                    "All tests pass".to_string(),
66                    "No clippy warnings".to_string(),
67                    "Public APIs have documentation".to_string(),
68                ],
69                passing_grade: "All criteria must be met before approval".to_string(),
70            })
71            .with_priority(Priority::High),
72        );
73
74    // Display expertise in various formats
75    println!("--- Tree Visualization ---\n");
76    println!("{}", expertise.to_tree());
77
78    println!("\n--- Generated Prompt (All Contexts) ---\n");
79    println!("{}", expertise.to_prompt());
80
81    println!("\n--- Generated Prompt (Security Review, At Risk) ---\n");
82    use llm_toolkit_expertise::ContextMatcher;
83    let security_context = ContextMatcher::new()
84        .with_task_type("security-review")
85        .with_task_health(TaskHealth::AtRisk);
86    println!("{}", expertise.to_prompt_with_context(&security_context));
87
88    println!("\n--- Mermaid Graph ---\n");
89    println!("{}", expertise.to_mermaid());
90
91    println!("\n--- JSON Serialization ---\n");
92    let json = serde_json::to_string_pretty(&expertise).expect("Failed to serialize");
93    println!("{}", json);
94}
More examples
Hide additional examples
examples/prompt_generation.rs (line 106)
8fn main() {
9    println!("=== Context-Aware Prompt Generation ===\n");
10
11    // Create an expertise with context-conditional fragments
12    let expertise = Expertise::new("adaptive-assistant", "1.0.0")
13        .with_tag("adaptive")
14        .with_tag("context-aware")
15        // Always active: Basic guidelines
16        .with_fragment(
17            WeightedFragment::new(KnowledgeFragment::Text(
18                "Be helpful, concise, and accurate in all responses.".to_string(),
19            ))
20            .with_priority(Priority::Critical)
21            .with_context(ContextProfile::Always),
22        )
23        // On Track: Speed mode
24        .with_fragment(
25            WeightedFragment::new(KnowledgeFragment::Logic {
26                instruction: "Optimize for speed and efficiency".to_string(),
27                steps: vec![
28                    "Provide direct, concise answers".to_string(),
29                    "Skip verbose explanations unless asked".to_string(),
30                    "Use shortcuts and best practices".to_string(),
31                ],
32            })
33            .with_priority(Priority::High)
34            .with_context(ContextProfile::Conditional {
35                task_types: vec![],
36                user_states: vec![],
37                task_health: Some(TaskHealth::OnTrack),
38            }),
39        )
40        // At Risk: Careful mode
41        .with_fragment(
42            WeightedFragment::new(KnowledgeFragment::Logic {
43                instruction: "Proceed with caution and verification".to_string(),
44                steps: vec![
45                    "Double-check all assumptions".to_string(),
46                    "Ask clarifying questions".to_string(),
47                    "Verify requirements before proceeding".to_string(),
48                    "Explain reasoning for each decision".to_string(),
49                ],
50            })
51            .with_priority(Priority::High)
52            .with_context(ContextProfile::Conditional {
53                task_types: vec![],
54                user_states: vec![],
55                task_health: Some(TaskHealth::AtRisk),
56            }),
57        )
58        // Off Track: Stop mode
59        .with_fragment(
60            WeightedFragment::new(KnowledgeFragment::Text(
61                "STOP. The current approach is not working. Reassess the problem, consult with the user, and propose a different strategy before continuing.".to_string(),
62            ))
63            .with_priority(Priority::Critical)
64            .with_context(ContextProfile::Conditional {
65                task_types: vec![],
66                user_states: vec![],
67                task_health: Some(TaskHealth::OffTrack),
68            }),
69        )
70        // Beginner user state
71        .with_fragment(
72            WeightedFragment::new(KnowledgeFragment::Text(
73                "Provide detailed explanations and educational context. Avoid jargon.".to_string(),
74            ))
75            .with_priority(Priority::High)
76            .with_context(ContextProfile::Conditional {
77                task_types: vec![],
78                user_states: vec!["beginner".to_string()],
79                task_health: None,
80            }),
81        )
82        // Debug task type
83        .with_fragment(
84            WeightedFragment::new(KnowledgeFragment::Logic {
85                instruction: "Systematic debugging approach".to_string(),
86                steps: vec![
87                    "Reproduce the issue".to_string(),
88                    "Isolate the root cause".to_string(),
89                    "Propose minimal fix".to_string(),
90                    "Verify fix doesn't break other functionality".to_string(),
91                ],
92            })
93            .with_priority(Priority::High)
94            .with_context(ContextProfile::Conditional {
95                task_types: vec!["debug".to_string()],
96                user_states: vec![],
97                task_health: None,
98            }),
99        );
100
101    // Test different contexts
102    let scenarios = vec![
103        ("Default (no context)", ContextMatcher::new()),
104        (
105            "On Track",
106            ContextMatcher::new().with_task_health(TaskHealth::OnTrack),
107        ),
108        (
109            "At Risk",
110            ContextMatcher::new().with_task_health(TaskHealth::AtRisk),
111        ),
112        (
113            "Off Track",
114            ContextMatcher::new().with_task_health(TaskHealth::OffTrack),
115        ),
116        (
117            "Beginner User",
118            ContextMatcher::new().with_user_state("beginner"),
119        ),
120        ("Debug Task", ContextMatcher::new().with_task_type("debug")),
121        (
122            "Debug + At Risk",
123            ContextMatcher::new()
124                .with_task_type("debug")
125                .with_task_health(TaskHealth::AtRisk),
126        ),
127    ];
128
129    for (name, context) in scenarios {
130        println!("### Scenario: {}\n", name);
131        let prompt = expertise.to_prompt_with_context(&context);
132        println!("{}", prompt);
133        println!("---\n");
134    }
135
136    println!("\n=== Visualization ===\n");
137    println!("{}", expertise.to_tree());
138}

Trait Implementations§

Source§

impl Clone for ContextMatcher

Source§

fn clone(&self) -> ContextMatcher

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ContextMatcher

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for ContextMatcher

Source§

fn default() -> ContextMatcher

Returns the “default value” for a type. Read more
Source§

impl From<ContextMatcher> for RenderContext

Convert from legacy ContextMatcher

Source§

fn from(matcher: ContextMatcher) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.