pub struct Expertise {
pub id: String,
pub version: String,
pub description: Option<String>,
pub tags: Vec<String>,
pub content: Vec<WeightedFragment>,
}Expand description
Expertise: Agent capability package (Graph node)
Represents a complete agent expertise profile composed of weighted knowledge fragments. Uses composition instead of inheritance for flexible capability mixing.
Fields§
§id: StringUnique identifier
version: StringVersion string
description: Option<String>Optional lightweight catalog description for Orchestrator routing
This is a concise (1-2 sentence) summary used by orchestrators to select
the appropriate agent. The full expertise details are rendered via to_prompt()
for LLM consumption.
If not provided, it will be auto-generated from the first fragment content (typically starts with “You are XXX” or “XXX Agent…”).
Tags for search and grouping (e.g., [“lang:rust”, “role:reviewer”, “style:friendly”])
content: Vec<WeightedFragment>Knowledge and capability components (weighted)
Implementations§
Source§impl Expertise
impl Expertise
Sourcepub fn new(id: impl Into<String>, version: impl Into<String>) -> Self
pub fn new(id: impl Into<String>, version: impl Into<String>) -> Self
Create a new expertise profile
§Arguments
id- Unique identifier for this expertiseversion- Version string (e.g., “1.0.0”)
§Description Auto-generation
The description field is optional. If not set via with_description(),
it will be auto-generated from the first fragment’s content when needed.
Typical patterns include:
- “You are a Rust expert…”
- “Senior software engineer specialized in…”
- “Code reviewer with focus on…”
§Example
use llm_toolkit_expertise::Expertise;
let expertise = Expertise::new("rust-expert", "1.0.0");Examples found in repository?
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
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}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}Sourcepub fn with_description(self, description: impl Into<String>) -> Self
pub fn with_description(self, description: impl Into<String>) -> Self
Set an explicit description for catalog/routing purposes
This overrides the auto-generated description. Use this when you want a specific concise summary for orchestrator routing that differs from the first fragment’s content.
§Example
use llm_toolkit_expertise::Expertise;
let expertise = Expertise::new("rust-expert", "1.0.0")
.with_description("Expert Rust developer and code reviewer");Sourcepub fn with_tag(self, tag: impl Into<String>) -> Self
pub fn with_tag(self, tag: impl Into<String>) -> Self
Add a tag
Examples found in repository?
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
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}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}Add tags
Sourcepub fn with_fragment(self, fragment: WeightedFragment) -> Self
pub fn with_fragment(self, fragment: WeightedFragment) -> Self
Add a weighted fragment
Examples found in repository?
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
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}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}Sourcepub fn get_description(&self) -> String
pub fn get_description(&self) -> String
Get the description, auto-generating if not explicitly set
If no explicit description was set via with_description(),
this method generates one from the first fragment’s content. It extracts the first
~100 characters, which typically captures patterns like:
- “You are a Rust expert…”
- “Senior software engineer specialized in…”
Returns an empty string if there are no fragments.
Sourcepub fn extract_tool_names(&self) -> Vec<String>
pub fn extract_tool_names(&self) -> Vec<String>
Extract tool definitions as capability names
This method scans all fragments and extracts tool names from ToolDefinition fragments.
Returns a vector of capability identifiers that can be used for agent registration.
Note: This is a basic implementation that extracts tool names from JSON schemas.
For use with llm-toolkit’s Capability type, enable the “integration” feature.
Sourcepub fn to_prompt(&self) -> String
pub fn to_prompt(&self) -> String
Generate a single prompt string from all fragments
Fragments are ordered by priority (Critical → High → Normal → Low)
Examples found in repository?
54fn main() {
55 println!("=== Expertise-Based Agent Example ===\n");
56
57 // Create expertise
58 let expertise = create_code_reviewer();
59
60 // Display the expertise
61 println!("--- Generated Expertise Prompt ---\n");
62 println!("{}", expertise.to_prompt());
63
64 println!("\n--- Tree Visualization ---\n");
65 println!("{}", expertise.to_tree());
66
67 println!("\n=== Usage with Agent Macro ===\n");
68 println!("With the ToPrompt integration, you can now use:");
69 println!();
70 println!("```rust");
71 println!("const EXPERTISE: Expertise = create_code_reviewer();");
72 println!();
73 println!("#[derive(Agent)]");
74 println!("#[agent(expertise = EXPERTISE, output = \"String\")]");
75 println!("struct CodeReviewerAgent;");
76 println!("```");
77 println!();
78 println!("The expertise() method will automatically call EXPERTISE.to_prompt()");
79 println!("and cache the result for efficiency!");
80}More examples
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}Sourcepub fn to_prompt_with_render_context(&self, context: &RenderContext) -> String
pub fn to_prompt_with_render_context(&self, context: &RenderContext) -> String
Generate a prompt string with render context filtering (Phase 2)
This is the new context-aware rendering API that supports multiple user states and improved context matching.
§Examples
use llm_toolkit_expertise::{Expertise, WeightedFragment, KnowledgeFragment};
use llm_toolkit_expertise::render::RenderContext;
use llm_toolkit_expertise::context::TaskHealth;
let expertise = Expertise::new("test", "1.0")
.with_fragment(WeightedFragment::new(
KnowledgeFragment::Text("Test".to_string())
));
let context = RenderContext::new()
.with_task_type("security-review")
.with_task_health(TaskHealth::AtRisk);
let prompt = expertise.to_prompt_with_render_context(&context);Sourcepub fn to_prompt_with_context(&self, context: &ContextMatcher) -> String
pub fn to_prompt_with_context(&self, context: &ContextMatcher) -> String
Generate a prompt string with context filtering (legacy API)
Only includes fragments that match the given context conditions.
Note: Consider using to_prompt_with_render_context() for the new API
with improved context matching.
Examples found in repository?
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
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}Sourcepub fn to_mermaid(&self) -> String
pub fn to_mermaid(&self) -> String
Generate a Mermaid graph representation
Examples found in repository?
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}Sourcepub fn to_tree(&self) -> String
pub fn to_tree(&self) -> String
Generate a simple tree representation
Examples found in repository?
54fn main() {
55 println!("=== Expertise-Based Agent Example ===\n");
56
57 // Create expertise
58 let expertise = create_code_reviewer();
59
60 // Display the expertise
61 println!("--- Generated Expertise Prompt ---\n");
62 println!("{}", expertise.to_prompt());
63
64 println!("\n--- Tree Visualization ---\n");
65 println!("{}", expertise.to_tree());
66
67 println!("\n=== Usage with Agent Macro ===\n");
68 println!("With the ToPrompt integration, you can now use:");
69 println!();
70 println!("```rust");
71 println!("const EXPERTISE: Expertise = create_code_reviewer();");
72 println!();
73 println!("#[derive(Agent)]");
74 println!("#[agent(expertise = EXPERTISE, output = \"String\")]");
75 println!("struct CodeReviewerAgent;");
76 println!("```");
77 println!();
78 println!("The expertise() method will automatically call EXPERTISE.to_prompt()");
79 println!("and cache the result for efficiency!");
80}More examples
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}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<'de> Deserialize<'de> for Expertise
impl<'de> Deserialize<'de> for Expertise
Source§fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
Source§impl JsonSchema for Expertise
impl JsonSchema for Expertise
Source§fn schema_name() -> String
fn schema_name() -> String
Source§fn schema_id() -> Cow<'static, str>
fn schema_id() -> Cow<'static, str>
Source§fn json_schema(generator: &mut SchemaGenerator) -> Schema
fn json_schema(generator: &mut SchemaGenerator) -> Schema
Source§fn is_referenceable() -> bool
fn is_referenceable() -> bool
$ref keyword. Read more