WeightedFragment

Struct WeightedFragment 

Source
pub struct WeightedFragment {
    pub priority: Priority,
    pub context: ContextProfile,
    pub fragment: KnowledgeFragment,
}
Expand description

WeightedFragment: Knowledge entity with metadata

Combines a knowledge fragment with its priority and activation context.

Fields§

§priority: Priority

Priority: Controls enforcement strength and ordering

§context: ContextProfile

Context: Activation conditions

§fragment: KnowledgeFragment

Fragment: The actual knowledge content

Implementations§

Source§

impl WeightedFragment

Source

pub fn new(fragment: KnowledgeFragment) -> Self

Create a new weighted fragment with default priority and always-active context

Examples found in repository?
examples/agent_with_expertise.rs (lines 17-19)
11fn create_code_reviewer() -> Expertise {
12    Expertise::new("rust-code-reviewer", "1.0.0")
13        .with_tag("lang:rust")
14        .with_tag("role:reviewer")
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 unsafe code blocks".to_string(),
28                    "Verify input validation and sanitization".to_string(),
29                    "Review error handling for information leakage".to_string(),
30                ],
31            })
32            .with_priority(Priority::High)
33            .with_context(ContextProfile::Conditional {
34                task_types: vec!["security-review".to_string()],
35                user_states: vec![],
36                task_health: Some(TaskHealth::AtRisk),
37            }),
38        )
39        // Normal: Code quality guidelines
40        .with_fragment(
41            WeightedFragment::new(KnowledgeFragment::Guideline {
42                rule: "Prefer explicit error handling over unwrap/expect".to_string(),
43                anchors: vec![Anchor {
44                    context: "Parsing user input".to_string(),
45                    positive: "let value = parse_input(s).map_err(|e| Error::InvalidInput(e))?;".to_string(),
46                    negative: "let value = parse_input(s).unwrap();".to_string(),
47                    reason: "Unwrap can panic. Use proper error handling for user input.".to_string(),
48                }],
49            })
50            .with_priority(Priority::Normal),
51        )
52}
More examples
Hide additional examples
examples/basic_expertise.rs (lines 17-19)
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}
examples/prompt_generation.rs (lines 17-19)
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_priority(self, priority: Priority) -> Self

Set priority

Examples found in repository?
examples/agent_with_expertise.rs (line 20)
11fn create_code_reviewer() -> Expertise {
12    Expertise::new("rust-code-reviewer", "1.0.0")
13        .with_tag("lang:rust")
14        .with_tag("role:reviewer")
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 unsafe code blocks".to_string(),
28                    "Verify input validation and sanitization".to_string(),
29                    "Review error handling for information leakage".to_string(),
30                ],
31            })
32            .with_priority(Priority::High)
33            .with_context(ContextProfile::Conditional {
34                task_types: vec!["security-review".to_string()],
35                user_states: vec![],
36                task_health: Some(TaskHealth::AtRisk),
37            }),
38        )
39        // Normal: Code quality guidelines
40        .with_fragment(
41            WeightedFragment::new(KnowledgeFragment::Guideline {
42                rule: "Prefer explicit error handling over unwrap/expect".to_string(),
43                anchors: vec![Anchor {
44                    context: "Parsing user input".to_string(),
45                    positive: "let value = parse_input(s).map_err(|e| Error::InvalidInput(e))?;".to_string(),
46                    negative: "let value = parse_input(s).unwrap();".to_string(),
47                    reason: "Unwrap can panic. Use proper error handling for user input.".to_string(),
48                }],
49            })
50            .with_priority(Priority::Normal),
51        )
52}
More examples
Hide additional examples
examples/basic_expertise.rs (line 20)
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}
examples/prompt_generation.rs (line 20)
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_context(self, context: ContextProfile) -> Self

Set context profile

Examples found in repository?
examples/agent_with_expertise.rs (lines 33-37)
11fn create_code_reviewer() -> Expertise {
12    Expertise::new("rust-code-reviewer", "1.0.0")
13        .with_tag("lang:rust")
14        .with_tag("role:reviewer")
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 unsafe code blocks".to_string(),
28                    "Verify input validation and sanitization".to_string(),
29                    "Review error handling for information leakage".to_string(),
30                ],
31            })
32            .with_priority(Priority::High)
33            .with_context(ContextProfile::Conditional {
34                task_types: vec!["security-review".to_string()],
35                user_states: vec![],
36                task_health: Some(TaskHealth::AtRisk),
37            }),
38        )
39        // Normal: Code quality guidelines
40        .with_fragment(
41            WeightedFragment::new(KnowledgeFragment::Guideline {
42                rule: "Prefer explicit error handling over unwrap/expect".to_string(),
43                anchors: vec![Anchor {
44                    context: "Parsing user input".to_string(),
45                    positive: "let value = parse_input(s).map_err(|e| Error::InvalidInput(e))?;".to_string(),
46                    negative: "let value = parse_input(s).unwrap();".to_string(),
47                    reason: "Unwrap can panic. Use proper error handling for user input.".to_string(),
48                }],
49            })
50            .with_priority(Priority::Normal),
51        )
52}
More examples
Hide additional examples
examples/basic_expertise.rs (lines 34-38)
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}
examples/prompt_generation.rs (line 21)
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 WeightedFragment

Source§

fn clone(&self) -> WeightedFragment

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 WeightedFragment

Source§

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

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

impl<'de> Deserialize<'de> for WeightedFragment

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl JsonSchema for WeightedFragment

Source§

fn schema_name() -> String

The name of the generated JSON Schema. Read more
Source§

fn schema_id() -> Cow<'static, str>

Returns a string that uniquely identifies the schema produced by this type. Read more
Source§

fn json_schema(generator: &mut SchemaGenerator) -> Schema

Generates a JSON Schema for this type. Read more
Source§

fn is_referenceable() -> bool

Whether JSON Schemas generated for this type should be re-used where possible using the $ref keyword. Read more
Source§

impl Serialize for WeightedFragment

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

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.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,