llm-toolkit
Basic llm tools for rust
Motivation & Philosophy
High-level LLM frameworks like LangChain, while powerful, can be problematic in Rust. Their heavy abstractions and complex type systems often conflict with Rust's strengths, imposing significant constraints and learning curves on developers.
There is a clear need for a different kind of tool: a low-level, unopinionated, and minimalist toolkit that provides robust "last mile" utilities for LLM integration, much like how candle provides core building blocks for ML without dictating the entire application architecture.
This document proposes the creation of llm-toolkit, a new library crate designed to be the professional's choice for building reliable, high-performance LLM-powered applications in Rust.
Core Design Principles
-
Minimalist & Unopinionated: The toolkit will NOT impose any specific application architecture. Developers are free to design their own
UseCases andServices.llm-toolkitsimply provides a set of sharp, reliable "tools" to be called when needed. -
Focused on the "Last Mile Problem": The toolkit focuses on solving the most common and frustrating problems that occur at the boundary between a strongly-typed Rust application and the unstructured, often unpredictable string-based responses from LLM APIs.
-
Minimal Dependencies: The toolkit will have minimal dependencies (primarily
serdeandminijinja) to ensure it can be added to any Rust project with negligible overhead and maximum compatibility.
Features
| Feature Area | Description | Key Components | Status |
|---|---|---|---|
| Content Extraction | Safely extracting structured data (like JSON) from unstructured LLM responses. | extract module (FlexibleExtractor, extract_json) |
Implemented |
| Prompt Generation | Building complex prompts from Rust data structures with a powerful templating engine. | prompt! macro, #[derive(ToPrompt)], #[derive(ToPromptSet)] |
Implemented |
| Multi-Target Prompts | Generate multiple prompt formats from a single data structure for different contexts. | ToPromptSet trait, #[prompt_for(...)] attributes |
Implemented |
| Context-Aware Prompts | Generate prompts for a type within the context of another (e.g., a Tool for an Agent). |
ToPromptFor<T> trait, #[derive(ToPromptFor)] |
Implemented |
| Example Aggregation | Combine examples from multiple data structures into a single formatted section. | examples_section! macro |
Implemented |
| External Prompt Templates | Load prompt templates from external files to separate prompts from Rust code. | #[prompt(template_file = "...")] attribute |
Implemented |
| Type-Safe Intent Definition | Generate prompt builders and extractors from a single enum definition. | #[define_intent] macro |
Implemented |
| Intent Extraction | Extracting structured intents (e.g., enums) from LLM responses. | intent module (IntentFrame, IntentExtractor) |
Implemented |
| Agent API | Define reusable AI agents with expertise and structured outputs. | Agent trait, #[derive(Agent)] macro |
Implemented |
| Auto-JSON Enforcement | Automatically add JSON schema instructions to agent prompts for better LLM compliance. | #[derive(Agent)] with ToPrompt::prompt_schema() integration |
Implemented |
| Built-in Retry | Intelligent retry with 3-priority delay system: server retry_after (Priority 1), 429 exponential backoff (Priority 2), linear backoff (Priority 3). Includes RetryAgent decorator and Full Jitter. | max_retries attribute, RetryAgent, retry_after field |
Implemented |
| Multi-Modal Payload | Pass text and images to agents through a unified Payload interface with backward compatibility. |
Payload, PayloadContent types |
Implemented |
| Multi-Agent Orchestration | Coordinate multiple agents to execute complex workflows with adaptive error recovery. | Orchestrator, BlueprintWorkflow, StrategyMap |
Implemented |
| Execution Profiles | Declaratively configure agent behavior (Creative/Balanced/Deterministic) via semantic profiles. | ExecutionProfile enum, profile attribute, .with_execution_profile() |
Implemented (v0.13.0) |
| Template File Validation | Compile-time validation of template file paths with helpful error messages. | template_file attribute validation |
Implemented (v0.13.0) |
| Resilient Deserialization | Deserializing LLM responses into Rust types, handling schema variations. | (Planned) | Planned |
Prompt Generation
llm-toolkit offers three powerful and convenient ways to generate prompts, powered by the minijinja templating engine.
1. Ad-hoc Prompts with prompt! macro
For quick prototyping and flexible prompt creation, the prompt! macro provides a println!-like experience. You can pass any serde::Serialize-able data as context.
use prompt;
use Serialize;
let user = User ;
let task = "designing a new macro";
let p = prompt!.unwrap;
assert_eq!;
2. Structured Prompts with #[derive(ToPrompt)]
For core application logic, you can derive the ToPrompt trait on your structs to generate prompts in a type-safe way.
Setup:
First, enable the derive feature in your Cargo.toml:
[]
= { = "0.1.0", = ["derive"] }
= { = "1.0", = ["derive"] }
Usage:
Then, use the #[derive(ToPrompt)] and #[prompt(...)] attributes on your struct. The struct must also derive serde::Serialize.
use ToPrompt;
use Serialize;
let user = UserProfile ;
let p = user.to_prompt;
// The following would be printed:
// USER PROFILE:
// Name: Yui
// Role: World-Class Pro Engineer
Default Formatting and Field Attributes
If you omit the #[prompt(template = "...")] attribute on a struct, ToPrompt will automatically generate a key-value representation of the struct's fields. You can control this output with field-level attributes:
| Attribute | Description |
|---|---|
#[prompt(rename = "new_name")] |
Overrides the key with "new_name". |
#[prompt(skip)] |
Excludes the field from the output. |
#[prompt(format_with = "path::to::func")] |
Uses a custom function to format the field's value. |
The key for each field is determined with the following priority:
#[prompt(rename = "...")]attribute.- Doc comment (
/// ...) on the field. - The field's name (fallback).
Comprehensive Example:
use ToPrompt;
use ToPrompt; // Make sure to import the derive macro
use Serialize;
// A custom formatting function
let user = AdvancedUser ;
let p = user.to_prompt;
// The following would be generated:
// The user's unique identifier: 123
// full_name: Mai
// formatted_id: user-123
Tip: Handling Special Characters in Templates
When using raw string literals (r#"..."#) for your templates, be aware of a potential parsing issue if your template content includes the # character (e.g., in a hex color code like "#FFFFFF").
The macro parser can sometimes get confused by the inner #. To avoid this, you can use a different number of # symbols for the raw string delimiter.
Problematic Example:
// This might fail to parse correctly
Solution:
// Use r##"..."## to avoid ambiguity
Using External Template Files
For larger prompts, you can separate them into external files (.jinja, .txt, etc.) and reference them using the template_file attribute. This improves code readability and makes prompts easier to manage.
You can also enable compile-time validation of your templates with validate = true.
use ToPrompt;
use Serialize;
// In templates/user_profile.jinja:
// Name: {{ name }}
// Email: {{ email }}
let user = UserFromTemplate ;
let p = user.to_prompt;
// The following would be generated from the file:
// Name: Yui
// Email: yui@example.com
3. Enum Documentation with #[derive(ToPrompt)]
For enums, the ToPrompt derive macro provides flexible ways to generate prompts. It distinguishes between instance-level prompts (describing a single variant) and type-level schema (describing all possible variants).
Instance vs. Type-Level Prompts
use ToPrompt;
/// Represents different user intents for a chatbot
// Instance-level: describe the current variant only
let intent = Greeting;
let prompt = intent.to_prompt;
// Output: "Greeting: User wants to greet or say hello"
// Type-level: describe all possible variants (TypeScript union type format)
let schema = prompt_schema;
// Output:
// /**
// * Represents different user intents for a chatbot
// */
// type UserIntent =
// | "Greeting" // User wants to greet or say hello
// | "Help" // User is asking for help or assistance;
//
// Example value: "Greeting"
When to use which:
value.to_prompt()- When you need to describe a specific enum value to the LLM (e.g., "The user selected: Greeting")Enum::prompt_schema()- When you need to explain all possible options to the LLM (e.g., "Choose one of these intents...")
TypeScript Format Benefits:
- Clear union type syntax that LLMs understand well
- Each variant includes its description as an inline comment
- Example value shows the correct JSON format
- JSDoc comments for type-level documentation
Advanced Attribute Controls
The ToPrompt derive macro supports powerful attribute-based controls for fine-tuning the generated prompts:
#[prompt("...")]- Provide a custom description that overrides the doc comment#[prompt(skip)]- Exclude a variant from the schema (but the variant name is still shown at instance level)- No attribute - Variants without doc comments or attributes will show just the variant name
Here's a comprehensive example showcasing all features:
use ToPrompt;
/// Represents different actions a user can take in the system
// Instance-level prompts
let action1 = CreateDocument;
assert_eq!;
let action2 = InternalDebugAction;
assert_eq!; // Skipped variants show name only
// Type-level schema (TypeScript union type format)
let schema = prompt_schema;
// Output:
// /**
// * Represents different actions a user can take in the system
// */
// type UserAction =
// | "CreateDocument" // User wants to create a new document
// | "Search" // User is searching for existing content
// | "UpdateProfile" // Custom: User is updating their profile settings and preferences
// | "DeleteItem";
//
// Example value: "CreateDocument"
//
// Note: InternalDebugAction is excluded from schema due to #[prompt(skip)]
Behavior of #[prompt(skip)]:
- At instance level (
value.to_prompt()): Shows only the variant name - At type level (
Enum::prompt_schema()): Completely excluded from the schema
Variant Renaming with Priority System
When working with enums that need different serialization formats (e.g., snake_case for APIs, camelCase for JSON), the ToPrompt macro provides flexible variant renaming with a clear 4-level priority system:
Priority Levels (Highest to Lowest):
#[prompt(rename = "...")]- ToPrompt-specific, highest priority#[serde(rename = "...")]- Per-variant serde rename#[serde(rename_all = "...")]- Enum-level serde rename rule- Default PascalCase - Rust variant name as-is
This priority system ensures that the TypeScript schema matches serde's serialization format, preventing deserialization errors when LLMs follow the schema.
Example: Basic serde rename_all Support
use ToPrompt;
use ;
// Type-level schema matches serde format
let schema = prompt_schema;
// Output:
// type VisualTreatment =
// | "delicate_luminous"
// | "cinematic_crisp"
// | "soft_atmospheric";
//
// Example value: "delicate_luminous"
// Instance-level also uses renamed values
let visual = CinematicCrisp;
assert_eq!;
// Serialization matches
let json = to_string.unwrap;
assert_eq!; // ✅ Perfect match!
Example: Priority System in Action
use ToPrompt;
use ;
// Priority 3: enum-level rule
let schema = prompt_schema;
// Output:
// type UserAction =
// | "ui_create" // Priority 1: prompt rename
// | "find_content" // Priority 2: serde rename
// | "update_profile" // Priority 3: rename_all
// | "DeleteItem"; // Priority 4: default
Example: Combined with Descriptions
// Both rename and description are applied!
let schema = prompt_schema;
// Output:
// type Intent =
// | "search_query" // User wants to search for content
// | "create_new" // User wants to create a new item
Supported Rename Rules (from serde):
All serde rename_all patterns are supported:
lowercase-lowercaseUPPERCASE-UPPERCASEPascalCase-PascalCasecamelCase-camelCasesnake_case-snake_caseSCREAMING_SNAKE_CASE-SCREAMING_SNAKE_CASEkebab-case-kebab-caseSCREAMING-KEBAB-CASE-SCREAMING-KEBAB-CASE
Why This Matters:
Without matching serde's format, you get guaranteed deserialization failures:
// ❌ Without rename support (old behavior)
let schema = prompt_schema;
// Schema says: "InProgress"
// But serde expects: "in_progress"
// LLM follows schema → returns "InProgress" → deserialization fails!
// ✅ With rename support (new behavior)
let schema = prompt_schema;
// Schema says: "in_progress"
// Serde expects: "in_progress"
// LLM follows schema → returns "in_progress" → deserialization succeeds!
Best Practices:
- Always use
#[serde(rename_all)]with ToPrompt - Ensures schema matches serialization - Use
#[prompt(rename)]for custom display names - When LLM-facing names differ from API serialization - Test deserialization - Verify LLM responses deserialize correctly with your schema
Struct Variants (Tagged Unions)
New in v0.21.0+: The ToPrompt macro now fully supports struct variants, enabling rich domain models with complex data. Struct variants are serialized as TypeScript tagged unions with a type discriminator field, which is the industry-standard pattern for LLMs.
Basic Example:
use ToPrompt;
use ;
// ← serde tagged union
// Type-level schema (TypeScript tagged union)
let schema = prompt_schema;
// Output:
// type AnalysisResult =
// | "Approved" // Analysis approved with no issues
// | { type: "NeedsRevision", reasons: string[], severity: string } // Analysis needs revision
// | { type: "Rejected", reason: string }; // Analysis rejected
//
// Example value: "Approved"
// Instance-level: struct variants show fields
let result = NeedsRevision ;
let prompt = result.to_prompt;
// Output: "NeedsRevision: Analysis needs revision { reasons: [\"Missing data\"], severity: \"High\" }"
// Serde serialization (matches schema!)
let json = to_string.unwrap;
// Output: {"type":"NeedsRevision","reasons":["Missing data"],"severity":"High"}
// LLM response → deserializes perfectly
let from_llm = r#"{"type":"Rejected","reason":"Invalid format"}"#;
let parsed: AnalysisResult = from_str.unwrap;
Supported Variant Types:
| Variant Type | Example | TypeScript Output | Status |
|---|---|---|---|
| Unit | Variant |
"Variant" |
✅ Full support |
| Struct | Variant { x: i32 } |
{ type: "Variant", x: number } |
✅ Full support |
| Tuple | Variant(i32, String) |
[number, string] |
✅ Full support |
Type Mapping:
The macro automatically maps Rust types to TypeScript equivalents:
// Generated schema:
// type Measurement =
// | { type: "Temperature", celsius: number, location: string }
// | { type: "Count", items: number, verified: boolean }
// | { type: "Tags", labels: string[], metadata: string | null };
Complex Example: Cinematic Lighting
use ToPrompt;
use ;
// Generated schema (snake_case from rename_all):
// type LightingTechnique =
// | { type: "chiaroscuro", contrast_level: ContrastLevel, light_source: LightSourceType, shadow_direction: ShadowDirection } // Chiaroscuro (dramatic high-contrast lighting)
// | { type: "rembrandt", triangle_side: Side, fill_ratio: number } // Rembrandt lighting (triangle of light on cheek)
// | "natural"; // Simple natural lighting
// LLM can return:
// {"type":"chiaroscuro","contrast_level":"High","light_source":"Single","shadow_direction":"Left"}
Why Tagged Unions?
- LLM-Friendly: Industry-standard pattern that LLMs understand intuitively
- Type Safety: Compile-time guarantees for field names and types
- Serde Compatible: Works seamlessly with
#[serde(tag = "type")] - Clear Discrimination: The
typefield makes variant identification unambiguous - JSON-First: Natural JSON representation for API communication
Combining Features:
All ToPrompt features work with struct variants:
// Schema includes only non-skipped variants with custom names:
// type Command =
// | { type: "run_script", script: string } // Execute a script
// | "Shutdown"; // Simple shutdown
Tuple Variants:
Tuple variants generate TypeScript tuple types with proper type mapping:
use ToPrompt;
use ;
// ← serde untagged for tuple arrays
// Generated schema:
// type Coordinate =
// | [number, number] // 2D coordinate
// | [number, number, number] // 3D coordinate with metadata
// | "Origin"; // Origin point
// Instance to_prompt():
let point = Point2D;
let prompt = point.to_prompt;
// Output: "Point2D: 2D coordinate (10.5, 20.3)"
// Serde serialization (untagged = array):
let json = to_string.unwrap;
// Output: [10.5,20.3]
// LLM can return:
// [10.5, 20.3] → deserializes to Point2D
// [1.0, 2.0, 3.0] → deserializes to Point3D
Mixed Types in Tuples:
// Generated schema:
// type Value =
// | [string, number] // String-number pair
// | [string] // Single value
// | [string, number[], boolean | null]; // Complex tuple
Best Practices:
- Struct variants: Use
#[serde(tag = "type")]for tagged unions - Tuple variants: Use
#[serde(untagged)]for tuple arrays - Keep field names simple - LLMs work best with clear, descriptive names
- Document variants - Doc comments become inline comments in TypeScript
- Test roundtrips - Verify LLM responses deserialize correctly
- Mix freely - Combine unit, struct, and tuple variants as needed
4. Multi-Target Prompts with #[derive(ToPromptSet)]
For applications that need to generate different prompt formats from the same data structure for various contexts (e.g., human-readable vs. machine-parsable, or different LLM models), the ToPromptSet derive macro enables powerful multi-target prompt generation.
Basic Multi-Target Setup
use ToPromptSet;
use Serialize;
let task = Task ;
// Generate visual-friendly prompt using template
let visual_prompt = task.to_prompt_for?;
// Output: "## Implement feature\n\n> Add new functionality"
// Generate agent-friendly prompt with key-value format
let agent_prompt = task.to_prompt_for?;
// Output: "title: Implement feature\ndescription: Add new functionality\npriority: 1\ninternal_id: 42"
Advanced Features
Custom Formatting Functions:
Multimodal Support:
use ;
// Generate multimodal prompt with both text and image
let parts = task.to_prompt_parts_for?;
// Returns Vec<PromptPart> with both Image and Text parts
Target Configuration Options
| Attribute | Description | Example |
|---|---|---|
#[prompt_for(name = "TargetName")] |
Include field in specific target | #[prompt_for(name = "Debug")] |
#[prompt_for(name = "Target", template = "...")] |
Use template for target (struct-level) | #[prompt_for(name = "Visual", template = "{{title}}")] |
#[prompt_for(name = "Target", rename = "new_name")] |
Rename field for specific target | #[prompt_for(name = "API", rename = "task_id")] |
#[prompt_for(name = "Target", format_with = "func")] |
Custom formatting function | #[prompt_for(name = "Human", format_with = "format_date")] |
#[prompt_for(name = "Target", image)] |
Mark field as image content | #[prompt_for(name = "Vision", image)] |
#[prompt_for(skip)] |
Exclude field from all targets | #[prompt_for(skip)] |
When to use ToPromptSet vs ToPrompt:
ToPrompt: Single, consistent prompt format across your applicationToPromptSet: Multiple prompt formats needed for different contexts (human vs. machine, different LLM models, etc.)
5. Context-Aware Prompts with #[derive(ToPromptFor)]
Sometimes, the way you want to represent a type in a prompt depends on the context. For example, a Tool might have a different prompt representation when being presented to an Agent versus a human user. The ToPromptFor<T> trait and its derive macro solve this problem.
It allows a struct to generate a prompt for a specific target type, using the target's data in its template.
Usage:
The struct using ToPromptFor must derive Serialize and ToPrompt. The target struct passed to it must also derive Serialize.
use ;
use Serialize;
// Enables schema_only, example_only modes for ToPrompt
/// A tool that can be used by an agent.
let agent = Agent ;
let tool = Tool ;
let prompt = tool.to_prompt_for;
// Generates a detailed prompt using the agent's name and role,
// and the tool's own schema and example.
6. Aggregating Examples with examples_section!
When providing few-shot examples to an LLM, it's often useful to show examples of all the data structures it might need to generate. The examples_section! macro automates this by creating a clean, formatted Markdown block from a list of types.
Usage:
All types passed to the macro must derive ToPrompt and Default, and have #[prompt(mode = "full")] and #[prompt(example = "...")] attributes to provide meaningful examples.
use ;
use Serialize;
/// Represents a user of the system.
/// Defines a concept for image generation.
let examples = examples_section!;
// The macro generates the following Markdown string:
//
// ### Examples
//
// Here are examples of the data structures you should use.
//
// ---
// #### `User`
// {
// "id": "user-12345",
// "name": "Taro Yamada"
// }
// ---
// #### `Concept`
// {
// "prompt": "a futuristic city at night",
// "style": "anime"
// }
// ---
Intent Extraction with IntentFrame
llm-toolkit provides a safe and robust way to extract structured intents (like enums) from an LLM's response. The core component for this is the IntentFrame struct.
It solves a common problem: ensuring the tag you use to frame a query in a prompt (<query>...</query>) and the tag you use to extract the response (<intent>...</intent>) are managed together, preventing typos and mismatches.
Usage:
IntentFrame is used for two things: wrapping your input and extracting the structured response.
use ;
use FromStr;
// 1. Define your intent enum
// 2. Create an IntentFrame
// The first tag is for wrapping input, the second is for extracting the response.
let frame = new;
// 3. Wrap your input to create part of your prompt
let user_input = "what is the weather in Tokyo?";
let wrapped_input = frame.wrap;
// wrapped_input is now "<user_query>what is the weather in Tokyo?</user_query>"
// (Imagine sending a full prompt with wrapped_input to an LLM here)
// 4. Extract the intent from the LLM's response
let llm_response = "Okay, I will get the weather. <intent>GetWeather</intent>";
let intent: UserIntent = frame.extract_intent.unwrap;
assert_eq!;
Type-Safe Intents with define_intent!
To achieve the highest level of type safety and developer experience, the #[define_intent] macro automates the entire process of creating and extracting intents.
It solves a critical problem: by defining the prompt, the intent enum, and the extraction logic in a single place, it becomes impossible for the prompt-building code and the response-parsing code to diverge.
Usage:
Simply annotate an enum with #[define_intent] and provide the prompt template and extractor tag in an #[intent(...)] attribute.
use ;
use FromStr;
/// The user's primary intent.
// The macro automatically generates:
// 1. A function: `build_user_intent_prompt(user_request: &str) -> String`
// 2. A struct: `pub struct UserIntentExtractor;` which implements `IntentExtractor<UserIntent>`
// --- How to use the generated code ---
// 1. Build the prompt
let prompt = build_user_intent_prompt;
// The prompt will include the formatted documentation from the enum.
// 2. Use the generated extractor to parse the LLM's response
let llm_response = "Understood. The user wants to know the weather. <intent>GetWeather</intent>";
let extractor = UserIntentExtractor;
let intent = extractor.extract_intent.unwrap;
assert_eq!;
This macro provides:
- Ultimate Type Safety: The prompt and the parser are guaranteed to be in sync.
- Improved DX: Eliminates boilerplate code for prompt functions and extractors.
- Single Source of Truth: The
enumbecomes the single, reliable source for all intent-related logic.
Multi-Tag Mode for Complex Action Extraction
For more complex scenarios where you need to extract multiple action tags from a single LLM response, the define_intent! macro supports a multi_tag mode. This is particularly useful for agent-like applications where the LLM might use multiple XML-style action tags in a single response.
Setup:
To use multi-tag mode, add both dependencies to your Cargo.toml:
[]
= { = "0.8.3", = ["derive"] }
= "0.38" # Required for multi_tag mode
Then define your actions:
use define_intent;
Action Tag Attributes:
#[action(tag = "TagName")]- Defines the XML tag name for this action#[action(attribute)]- Maps a field to an XML attribute (e.g.,<Tag field="value" />)#[action(inner_text)]- Maps a field to the inner text content (e.g.,<Tag>field_value</Tag>)
Generated Functions: The macro generates:
build_chat_action_prompt(user_request: &str) -> String- Builds the prompt with action documentationChatActionExtractorstruct with methods:extract_actions(&self, text: &str) -> Result<Vec<ChatAction>, IntentError>- Extract all actions from responsetransform_actions<F>(&self, text: &str, transformer: F) -> String- Transform action tags using a closurestrip_actions(&self, text: &str) -> String- Remove all action tags from text
Usage Example:
// 1. Build the prompt
let prompt = build_chat_action_prompt;
// 2. Extract multiple actions from LLM response
let llm_response = r#"
Here's the weather: <GetWeather />
And here's a cat picture: <ShowImage href="https://cataas.com/cat" />
<SendMessage to="user">I've completed both requests!</SendMessage>
"#;
let extractor = ChatActionExtractor;
let actions = extractor.extract_actions?;
// Returns: [ChatAction::GetWeather, ChatAction::ShowImage { href: "https://cataas.com/cat" }, ...]
// 3. Transform action tags to human-readable descriptions
let transformed = extractor.transform_actions;
// Result: "Here's the weather: [Checking weather...]\nAnd here's a cat picture: [Displaying image from https://cataas.com/cat]\n[Message to user: I've completed both requests!]"
// 4. Strip all action tags for clean text output
let clean_text = extractor.strip_actions;
// Result: "Here's the weather: \nAnd here's a cat picture: \n"
When to Use Multi-Tag Mode:
- Agent Applications: When building AI agents that perform multiple actions per response
- Rich LLM Interactions: When you need structured actions mixed with natural language
- Action Processing Pipelines: When you need to extract, transform, or clean action-based responses
Agent API and Multi-Agent Orchestration
llm-toolkit provides a powerful agent framework for building multi-agent LLM systems with a clear separation of concerns.
Agent API: Capability and Intent Separation
The Agent API follows the principle of capability and intent separation:
- Capability: An agent declares what it can do (
expertise) and what it produces (Output) - Intent: The orchestrator provides what needs to be done as a
Payload(multi-modal content)
This separation enables maximum reusability and flexibility.
Multi-Modal Agent Communication with Payload
The execute() method accepts a Payload type that supports multi-modal content including text and images. This enables agents to process both textual instructions and visual inputs.
Basic Usage (Text Only):
use Agent;
// String automatically converts to Payload for backward compatibility
let result = agent.execute.await?;
// Or use Payload explicitly
use Payload;
let payload = text;
let result = agent.execute.await?;
Multi-Modal Usage (Text + Images):
use Payload;
use PathBuf;
// Combine text and images
let payload = text
.with_image;
let result = agent.execute.await?;
// Or from raw image data
let image_bytes = read?;
let payload = text
.with_image_data;
Backward Compatibility:
All existing code using String continues to work thanks to automatic conversion:
// This still works unchanged
let result = agent.execute.await?;
Note: While the Payload type supports images, not all agent backends currently process them. ClaudeCodeAgent and GeminiAgent will log a warning if images are included but not yet supported by the CLI integration.
Defining Agents: Two Approaches
llm-toolkit provides two ways to define agents, each optimized for different use cases:
1. Simple Agents with #[derive(Agent)] (Recommended for Prototyping)
For quick prototyping and simple use cases, use the derive macro:
use Agent;
use ;
// Simple stateless agent
;
// Usage - extremely simple
async
Best Practice: Writing Effective Expertise Descriptions
The expertise field should describe the agent's capabilities in natural language only. Do NOT include template placeholder syntax like {{ variable }} in the expertise string.
❌ Incorrect:
Problem: When the orchestrator generates strategies, the LLM sees these {{ }} patterns and may confuse them with actual placeholders that need to be filled, leading to incorrect intent generation.
✅ Correct:
Why this works: The orchestrator's strategy generation LLM reads this natural language description and automatically creates appropriate intent templates like "Process the following strategy: {{ strategy_data }}". The LLM understands what inputs the agent needs and generates the correct placeholders in the strategy's intent_template field.
Key principle: The expertise describes capabilities; the orchestrator creates the actual intent templates dynamically based on those capabilities.
Features:
- ✅ Simplest possible interface
- ✅ Minimal boilerplate
- ✅ Perfect for prototyping
- ⚠️ Creates internal agent on each
execute()call (stateless)
Automatic JSON Schema Enforcement:
When using #[derive(Agent)] with a structured output type (non-String), the macro automatically adds JSON schema instructions to the agent's expertise. This dramatically improves LLM compliance and reduces parse errors.
use ;
use ;
;
// The agent's expertise() method automatically returns:
// "Review code quality and provide detailed feedback
//
// IMPORTANT: Respond with valid JSON matching this schema:
//
// /**
// * (struct documentation if present)
// */
// type ReviewResult = {
// quality_score: number; // Overall quality score from 0 to 100
// issues: string[]; // List of identified issues
// recommendations: string[]; // Actionable recommendations for improvement
// }"
Schema Generation Strategy (3-Tier Auto-Inference):
-
With
ToPrompt+ doc comments → Detailed schema with field descriptions- Requires:
#[derive(ToPrompt)]+#[prompt(mode = "full")] - Best experience: Full field-level documentation
- Requires:
-
With
ToPrompt(no doc comments) → Basic schema with field names- Requires:
#[derive(ToPrompt)]+#[prompt(mode = "full")] - Good: Type-safe field names
- Requires:
-
String output → No JSON enforcement
- For plain text responses
Recommendation: Always use #[derive(ToPrompt)] with #[prompt(mode = "full")] for structured outputs to get the best LLM compliance.
Nested Schema Expansion:
The schema generation automatically includes complete type definitions for nested types that implement ToPrompt, including both Vec<T> and regular nested objects. This ensures LLMs receive all necessary schema information in a single call:
// Generated schema for ProducerOutput (single call):
// type EvaluationResult = {
// rule: string; // The rule being checked
// passed: boolean; // Whether this specific rule passed
// }
//
// type ProducerOutput = {
// evaluation_passed: boolean; // Whether the evaluation passed all checks
// results: EvaluationResult[]; // List of evaluation results for each rule
// }
How it works:
- The macro detects nested types (both
Vec<T>and regular fields) at compile time - At runtime (first call only), it collects
prompt_schema()from all nested types - Nested type definitions are placed before the main type definition
- Duplicates are automatically removed (same type used multiple times)
- Result is cached with
OnceLockfor performance (zero cost after first call) - LLM receives complete schema information with all necessary type definitions
Nested Objects:
The same expansion works for regular nested objects (not just Vec):
// Generated schema for EmblemResponse (single call):
// type Emblem = {
// name: string; // The name of the emblem
// description: string; // A description of the emblem
// }
//
// type EmblemResponse = {
// obvious_emblem: Emblem; // An obvious, straightforward emblem
// creative_emblem: Emblem; // A creative, unexpected emblem
// }
How it works:
- The macro detects field types at compile time
- For
Vec<T>: generates TypeScript array syntaxT[]and includesTdefinition - For nested objects: generates TypeScript type reference
TypeNameand includes its full definition - For primitives: generates TypeScript primitive types (
string,number,boolean, etc.) - All type definitions are bundled together in the correct dependency order
Benefits:
- ✅ Complete schema information - LLM receives all type definitions in one call
- ✅ Zero manual work - No need to manually concatenate schemas
- ✅ Type-driven design - Rust types directly translate to LLM-friendly schemas
- ✅ Prevents parse errors - LLM knows exactly what fields are required in nested objects
- ✅ Clean, readable output - TypeScript-style syntax that LLMs understand well
- ✅ Industry-standard format - Uses familiar TypeScript syntax for better LLM comprehension
Why This Matters:
Without complete type definitions, LLMs guess field names and types, leading to parse errors like:
missing field 'age'- LLM didn't know the field was required- Wrong field names - LLM invented fields not in the schema
- Wrong types - LLM used
stringinstead ofnumber
With complete type definitions included, the LLM has perfect information and generates correct output.
Automatic Retry on Transient Errors:
All agents automatically retry on transient errors (ParseError, ProcessError, IoError) without any configuration:
;
// Automatically retries up to 3 times on:
// - ParseError: LLM output malformed
// - ProcessError: Process communication issues (including 429 rate limiting)
// - IoError: Temporary I/O failures
//
// Intelligent Retry Delay (3-Priority System):
// Priority 1: Server-provided retry_after (e.g., 90s from Retry-After header)
// Priority 2: 429 fallback - exponential backoff capped at 60s (2^attempt, max 60s)
// Priority 3: Other errors - linear backoff (100ms × attempt)
// All delays use Full Jitter (random 0~delay) to prevent thundering herd
//
// Example with 429 rate limiting:
// - Attempt 1 fails (429 + retry_after=60s) → wait ~30s (jittered) → retry
// - Attempt 2 fails (429, no retry_after) → wait ~1-2s (exponential + jitter) → retry
// - Attempt 3 fails → return error
Customizing Retry Behavior:
// Increase retry attempts for critical operations
;
// Disable retry for fast-fail scenarios
;
RetryAgent Wrapper - Add Retry to Any Agent:
For production use cases where you need more control over retry behavior, use the RetryAgent decorator to wrap any existing agent:
use ;
// Wrap any agent with retry logic
let base_agent = new;
let retry_agent = new; // Max 5 retries
// The wrapper handles all retry logic automatically
let result = retry_agent.execute.await?;
// RetryAgent follows the same 3-priority delay system:
// - Server retry_after takes highest priority
// - 429 errors use exponential backoff (capped at 60s)
// - Other errors use linear backoff (100ms × attempt)
Benefits of RetryAgent:
- ✅ Decorator Pattern: Wrap any
Agentimplementation without modification - ✅ Unified Retry Logic: Same retry mechanism used by macros (DRY principle)
- ✅ Production-Ready: Full control over max_retries and retry behavior
- ✅ 429 Rate Limiting: Intelligent handling of server-provided retry delays
- ✅ Zero Configuration: Works out-of-the-box with sensible defaults
Design Philosophy:
Agent-level retries are intentionally simple and limited (2-3 attempts by default):
- Fail fast: Quickly report errors to the orchestrator
- Orchestrator is smarter: Has broader context for complex error recovery
- Try different agents
- Redesign strategy
- Escalate to human
- System stability: Simple local retries + complex orchestration at the top = robust system
This design aligns with the Orchestrator's 3-stage error recovery (Tactical → Full Redesign → Human Escalation).
Advanced: Server-Provided Retry Delays
When LLM APIs return 429 rate limiting errors with a Retry-After header, agents automatically respect the server-specified delay:
use ;
use Duration;
// Example: Creating a 429 error with retry_after
let error = process_error_with_retry_after;
// The retry mechanism will:
// 1. Extract retry_after (90s)
// 2. Apply Full Jitter (random 0~90s)
// 3. Wait before retrying
//
// This prevents overwhelming rate-limited APIs and respects server guidance
2. Advanced Agents with #[agent(...)] (Recommended for Production)
For production use, testing, and when you need agent injection:
use ClaudeCodeAgent;
use ;
// Advanced agent with Generic support
;
async
Practical Injection Examples:
use ;
// Example 1: Environment-based agent selection
// Example 2: Switching between different LLM providers
// Example 3: Custom configuration injection
Features:
- ✅ Agent injection support (great for testing with mocks)
- ✅ Reuses internal agent (efficient)
- ✅ Static dispatch (compile-time optimization)
- ✅ Multiple constructor patterns
- ✅ Suitable for production use
Testing Example:
Agent injection makes testing simple and deterministic:
Using Custom Agent Backends:
You can specify custom agent implementations (like Olama, local models, etc.) using default_inner:
// Define your custom agent
use Payload;
// Create specialized agents using OlamaAgent as backend
;
;
// Usage:
let olama = new.with_model;
let writer = new;
let reviewer = new;
This pattern lets you:
- ✅ Reuse one backend (Olama, etc.) for multiple specialized agents
- ✅ Each agent has unique expertise
- ✅ Share configuration or customize per-agent
- ✅ Easy testing with mock backends
When to use which:
#[derive(Agent)]: Quick scripts, prototyping, simple tools#[agent(...)]withbackend: Production with Claude/Gemini#[agent(...)]withdefault_inner: Custom backends (Olama, local models, mocks)
Multi-Agent Orchestration
For complex workflows requiring multiple agents, the Orchestrator coordinates execution with adaptive error recovery.
Core Concepts
- BlueprintWorkflow: A natural language description of your workflow (no rigid types needed)
- StrategyMap: An ad-hoc execution plan generated by LLM based on available agents
- Adaptive Redesign: Three-stage error recovery (Retry → Tactical → Full Regenerate)
Basic Orchestrator Usage
use ;
use ClaudeCodeAgent;
async
Customizing Internal Agents with with_internal_agents
By default, Orchestrator::new() uses ClaudeCodeAgent and ClaudeCodeJsonAgent as internal agents for strategy generation and redesign decisions. You can inject custom internal agents for testing, different LLM backends, or specialized behavior.
Why customize internal agents?
- Testing: Use mock agents to test orchestration logic without external API calls
- Different LLM providers: Use Gemini, Ollama, or custom backends for strategy generation
- Cost optimization: Use cheaper models for internal decision-making
- Offline execution: Run workflows completely offline with mock agents
Usage:
use ;
use ;
// Define custom internal agents (e.g., mock agents for testing)
;
;
// Create orchestrator with custom internal agents
let orchestrator = with_internal_agents;
// The orchestrator now uses your custom agents for all internal operations
let result = orchestrator.execute.await;
Default Internal Agents:
When using Orchestrator::new(), the following internal agents are used:
- Strategy Generation:
ClaudeCodeJsonAgentwrapped inRetryAgent(max 3 retries) - Intent & Redesign:
ClaudeCodeAgentwrapped inRetryAgent(max 3 retries)
Both agents are automatically wrapped with RetryAgent to ensure robustness in critical orchestration decisions.
IMPORTANT for with_internal_agents():
When providing custom internal agents, you should wrap them with RetryAgent for production use:
use ;
let orchestrator = with_internal_agents;
Without RetryAgent, a single transient error (network timeout, rate limiting) could cause strategy generation to fail completely.
Complete Offline Example:
See examples/orchestrator_with_mock.rs for a complete example that runs entirely offline with mock agents:
Advanced: Custom Agents with Orchestrator
You can combine custom agents (defined with #[derive(Agent)]) with the orchestrator:
;
;
// Add both to orchestrator (InnerValidatorAgent is automatically registered)
let mut orchestrator = new;
orchestrator.add_agent;
orchestrator.add_agent;
// The orchestrator will automatically select the best agent for each step
Orchestrator Features
- ✅ Natural Language Blueprints: Define workflows in plain English
- ✅ Ad-hoc Strategy Generation: LLM generates execution plans based on available agents
- ✅ Two-Layer Error Recovery: Combine RetryAgent (transient errors) + Orchestrator (structural errors)
- ✅ 3-Stage Error Recovery:
- Retry: For transient errors
- Tactical Redesign: Modify failed steps and continue
- Full Regenerate: Start over with a new strategy
- ✅ Built-in Validation: Automatic registration of
InnerValidatorAgentas a fallback validator - ✅ Smart Context Management: Automatic passing of outputs between steps with
ToPromptsupport - ✅ Configurable Error Recovery Limits: Control retry behavior to prevent infinite loops
- ✅ Fast Path Intent Generation: Optional optimization to skip LLM calls for deterministic template substitution
Configuring Error Recovery Limits
The orchestrator provides configurable limits for error recovery to prevent infinite loops and control API costs:
use ;
let mut orchestrator = new;
// Method 1: Set entire configuration at once
let config = OrchestratorConfig ;
orchestrator.set_config;
// Method 2: Modify individual limits
orchestrator.set_max_step_remediations;
orchestrator.set_max_total_redesigns;
// Method 3: Use partial configuration with defaults
let config = OrchestratorConfig ;
orchestrator.set_config;
Default Limits:
max_step_remediations: 3- Allows 3 execution attempts per step (initial attempt + 2 retries)
- Prevents infinite loops on a single failing step
max_total_redesigns: 10- Allows 10 redesign operations (initial strategy generation not counted)
- Controls overall workflow redesign attempts across all steps
How Counting Works:
Step-level counting:
Step fails → count incremented → check if count >= max_step_remediations
- Attempt 1 (initial): Fails → count=1 → 1>=3? No → Retry
- Attempt 2: Fails → count=2 → 2>=3? No → Retry
- Attempt 3: Fails → count=3 → 3>=3? Yes → Error: MaxStepRemediationsExceeded
Result: max_step_remediations=3 allows 3 total attempts (2 retries)
Total redesigns counting:
Initial strategy generation → redesigns_triggered=0 (not counted)
Retry/TacticalRedesign/FullRegenerate → redesigns_triggered incremented
- First redesign: redesigns_triggered=1
- ...
- 10th redesign: redesigns_triggered=10 → 10>=10? Yes → Error: MaxTotalRedesignsExceeded
Result: max_total_redesigns=10 allows up to 11 total strategy executions
When Limits Are Exceeded:
- Step limit exceeded: Returns
OrchestratorError::MaxStepRemediationsExceeded { step_index, max_remediations } - Total limit exceeded: Returns
OrchestratorError::MaxTotalRedesignsExceeded(limit)
Choosing Good Values:
- Small workflows (2-3 steps): Default values work well
- Large workflows (5+ steps): Consider increasing
max_total_redesignsto 15-20 - Critical steps: If certain steps are known to be unstable, increase
max_step_remediationsto 5 - Cost-sensitive: Reduce both limits to fail faster (e.g., max_step_remediations=2, max_total_redesigns=5)
Rate Limiting with min_step_interval
The orchestrator provides proactive rate limiting to prevent API rate limit errors (429 Too Many Requests).
Problem: Each orchestrator step typically makes 2+ API calls (intent generation + execution). Without delays, a 6-step workflow can make 12+ calls in 30 seconds, exceeding many LLM API rate limits (e.g., 10 requests/minute for Gemini).
Solution: Set min_step_interval to introduce a delay after each step completes:
use Duration;
use ;
let mut orchestrator = new;
// Method 1: Set entire configuration at once
let config = OrchestratorConfig ;
orchestrator.set_config;
// Method 2: Use convenience method
orchestrator.set_min_step_interval; // 1 second delay
How It Works:
- Applied after each step completes (before starting next step)
- Not applied after the last step (no unnecessary delay)
Duration::ZEROmeans no delay (default, backward compatible)
Choosing Good Values:
- 10 req/min limit (e.g., Gemini): Use
Duration::from_secs(6)or higher - 60 req/min limit (e.g., Claude): Use
Duration::from_millis(500)toDuration::from_secs(1) - Conservative approach: Start with
Duration::from_secs(1), reduce if no errors occur
Combining with RetryAgent:
For maximum resilience, combine proactive rate limiting (min_step_interval) with reactive retry (RetryAgent):
use ;
// Layer 1: Proactive rate limiting (prevents errors)
orchestrator.set_min_step_interval;
// Layer 2: Reactive retry with retry_after support (handles errors)
let gemini = new;
let retry_gemini = new; // Respects server retry_after
orchestrator.add_agent;
// Result: Minimal API errors and automatic recovery if they occur
Performance Impact:
- 6-step workflow with 1s delay: Adds ~5 seconds total (6 steps - 1 last step)
- Trade-off: Slightly slower execution vs. no rate limit errors
- Best practice: Use only when targeting rate-limited APIs
Fast Path Intent Generation (Performance Optimization)
By default, the orchestrator uses LLM-based intent generation for each step, which provides high-quality, context-aware prompts but incurs API latency and costs. For workflows with simple template substitution (all placeholders resolved from context), you can enable fast path optimization to skip LLM calls.
When to Enable:
- ✅ Thick Agents: Agents that contain detailed domain logic and don't need LLM-optimized prompts
- ✅ Simple Templates: Intent templates with straightforward placeholder substitution
- ✅ Performance-Critical Workflows: When latency matters more than prompt quality
- ✅ High-Volume Operations: When API costs need to be minimized
When to Keep Disabled (Default):
- ❌ Thin Agents: Agents that rely on rich, context-aware prompts from the LLM
- ❌ Complex Reasoning: Workflows requiring semantic understanding and prompt adaptation
- ❌ Quality-First Applications: When prompt quality is more important than speed
Usage:
use Duration;
use ;
let mut orchestrator = new;
// Enable fast path optimization
let config = OrchestratorConfig ;
orchestrator.set_config;
// Execute - fast path will be used when all placeholders are resolved
let result = orchestrator.execute.await;
How It Works:
For each step, the orchestrator:
- Checks prerequisites: Are all placeholders in the intent template resolved in context?
- Fast path (if enabled + all resolved): Simple string substitution (milliseconds, no API call)
- LLM path (fallback): LLM generates high-quality, context-aware intent (seconds, API call)
Example:
// Intent template from strategy
"Transform this data: {{previous_output}}"
// If fast path enabled and previous_output exists in context:
// → Fast path: Direct substitution → "Transform this data: <actual output>"
// → Latency: ~1ms, Cost: $0
// If fast path disabled or placeholder not resolved:
// → LLM path: Generate intent considering agent expertise → High-quality prompt
// → Latency: ~2s, Cost: ~$0.001
Performance Benefits (Example E2E Test Results):
3-step workflow with mock 100ms LLM delay:
- Fast Path ENABLED: 412ms (1.49x faster)
- Fast Path DISABLED: 615ms
Real-world with actual LLM calls:
- Fast Path: ~50ms per step → 150ms for 3 steps
- LLM Path: ~2s per step → 6s for 3 steps
- Speedup: 40x faster!
Trade-offs:
| Aspect | Fast Path (Enabled) | LLM Path (Disabled, Default) |
|---|---|---|
| Performance | ⚡ Milliseconds | 🐌 Seconds |
| API Cost | 💰 Zero | 💰💰 Per step |
| Prompt Quality | Basic (template substitution) | High (context-aware, semantic) |
| Best For | Thick agents, simple templates | Thin agents, complex reasoning |
Best Practices:
- Default to disabled - Prioritize quality for thin agent architectures
- Enable selectively - Use for specific workflows where you've validated template quality
- Test both modes - Compare results to ensure fast path doesn't sacrifice quality
- Monitor logs - Watch for
"Using fast path"vs"Using LLM-based intent generation"messages
Complete E2E Example:
See examples/orchestrator_fast_path_e2e.rs for a complete example comparing both modes:
This example demonstrates:
- Performance comparison between fast path and LLM path
- Validation that both produce equivalent results
- Configuration toggling
- Practical speedup measurements
Two-Layer Error Recovery: RetryAgent + Orchestrator
The recommended pattern is to combine RetryAgent (agent-level retry) with Orchestrator (workflow-level recovery) for robust error handling:
use ;
use ;
// Layer 1: Agent-level retry (transient errors)
let claude = new;
let retry_agent = new; // Up to 3 retries
// Layer 2: Orchestrator-level recovery (structural errors)
let mut orchestrator = new;
orchestrator.add_agent;
// Now you have two layers of error recovery:
// - Agent layer: Network errors, 429 rate limits, parse errors
// - Orchestrator layer: Wrong agent selection, strategy issues
Responsibility Separation:
| Error Type | Layer | Recovery Strategy |
|---|---|---|
| Network timeout | Agent (RetryAgent) | Wait + retry (linear backoff) |
| 429 rate limit | Agent (RetryAgent) | Wait retry_after (exponential, max 60s) |
| Parse error | Agent (RetryAgent) | Immediate retry (linear backoff) |
| Agent capability mismatch | Orchestrator | Try different agent (step remediation) |
| Strategy design flaw | Orchestrator | Redesign workflow (tactical/full) |
Per-Agent Customization:
You can customize retry behavior for each agent based on importance:
// Critical agent: More retries
let writer = default;
let retry_writer = new; // 5 retries
// Lightweight agent: Fewer retries
let validator = default;
let retry_validator = new; // 2 retries
orchestrator.add_agent;
orchestrator.add_agent;
Cost Control:
Worst case: Agent retries × Orchestrator remediations
- Agent: 3 attempts (1 initial + 2 retries)
- Orchestrator: 3 remediations
- Maximum: 3 × 3 = 9 agent calls per step
This is intentional design:
- Agent retries handle transient errors (network, API)
- Orchestrator remediations handle structural errors (strategy, capability)
- Both limits are independently configurable for cost control
Why This Pattern Works:
- ✅ Clear Separation: Transient vs structural errors handled at appropriate levels
- ✅ DRY Principle: Same retry logic (RetryAgent) used everywhere
- ✅ Flexible Control: Independent configuration of agent and orchestrator retries
- ✅ No Additional Code: Uses existing RetryAgent decorator
- ✅ Production-Ready: 429 rate limiting, Full Jitter, retry_after support
When NOT to use RetryAgent:
If you want the Orchestrator to immediately try a different agent on first failure (no agent-level retry), add agents directly without wrapping:
// Direct agent addition - no agent-level retry
orchestrator.add_agent;
// First error → Orchestrator immediately tries different agent or redesigns
Placeholder Syntax in Intent Templates
Intent templates use Mustache/Jinja2-style double curly braces {{ }} for placeholder substitution. This is not a typo - single braces { } are not recognized.
Correct Syntax:
"Create an outline for: {{ task }}" // ✅ Correct
"Based on {{ previous_output }}, continue" // ✅ Correct
"Transform {{ step_3_output }}" // ✅ Correct
Incorrect Syntax:
"Create an outline for: {task}" // ❌ Will NOT be recognized
"Based on {previous_output}, continue" // ❌ Will NOT be recognized
Important Notes:
- Always use double curly braces with spaces:
{{ name }}(not{{name}}) - This matches the Mustache/Jinja2 templating convention
- The orchestrator's
extract_placeholdersonly detects{{ }}format - LLM-generated intent templates follow this convention from prompts.rs
Common Placeholders:
{{ task }}- The original user task{{ previous_output }}- Output from the immediately previous step{{ step_N_output }}- Output from a specific step (e.g.,{{ step_3_output }})- Custom semantic names (e.g.,
{{ concept_content }},{{ emblem_design }})
Using Predefined Strategies
By default, the orchestrator automatically generates execution strategies from your blueprint using an internal LLM. However, you can also provide a predefined strategy to:
- Reuse known-good strategies that have been validated
- Test specific execution paths with deterministic workflows
- Implement custom strategy generation logic outside the orchestrator
- Skip strategy generation costs when you already know the optimal plan
Basic Usage:
use ;
// Create orchestrator
let mut orchestrator = new;
orchestrator.add_agent;
// Define a custom strategy manually
let mut strategy = new;
strategy.add_step;
strategy.add_step;
// Set the predefined strategy
orchestrator.set_strategy_map;
// Execute - strategy generation is skipped
let result = orchestrator.execute.await;
Retrieving Current Strategy:
// Check if strategy is set
if let Some = orchestrator.strategy_map
Backward Compatibility:
When no predefined strategy is set, the orchestrator behaves exactly as before - automatically generating strategies from the blueprint:
// Traditional usage - automatic strategy generation
let mut orchestrator = new;
orchestrator.add_agent;
let result = orchestrator.execute.await; // Auto-generates strategy
When to Use Predefined Strategies:
| Scenario | Use Auto-Generation | Use Predefined Strategy |
|---|---|---|
| Exploring new workflows | ✅ Yes | ❌ No |
| Production with validated flows | ❌ No | ✅ Yes |
| Testing specific error scenarios | ❌ No | ✅ Yes |
| Cost optimization (reuse strategies) | ❌ No | ✅ Yes |
| Prototyping and experimentation | ✅ Yes | ❌ No |
Example Code:
See the complete example at examples/orchestrator_with_predefined_strategy.rs:
Smart Context Management with ToPrompt
The orchestrator automatically manages context between agent steps. When an agent produces output, the orchestrator stores it and makes it available to subsequent steps. If the output type implements ToPrompt, the orchestrator intelligently uses the human-readable prompt representation instead of raw JSON.
Why This Matters:
When you have complex output types (like enums with variant descriptions, or structs with rich formatting), you want the orchestrator to pass them to the next agent in a readable, LLM-friendly format—not as opaque JSON.
Example: Enum with ToPrompt
use ;
use ;
// Define an enum with rich documentation
// Agent that produces this enum
;
How it works:
- Step 1:
AnalyzerAgentproducesAnalysisResult::NeedsRevision { reasons: [...] } - Orchestrator stores two versions:
step_1_output: JSON representation{"NeedsRevision": {"reasons": [...]}}step_1_output_prompt: ToPrompt representation with full descriptions
- Step 2: When building intent for the next agent, the orchestrator prefers the
_promptversion - Result: Next agent receives rich, human-readable context instead of cryptic JSON
Setup:
To enable ToPrompt support for your agent outputs, use add_agent_with_to_prompt:
// ✅ Correct: Use add_agent_with_to_prompt for types implementing ToPrompt
orchestrator.add_agent_with_to_prompt;
// ❌ Common Mistake: Using add_agent() - ToPrompt won't be used!
// orchestrator.add_agent(MyAnalyzerAgent::new());
Benefits:
- Better LLM Understanding: Complex types are presented in natural language, not JSON
- Automatic Fallback: If
ToPromptis not implemented, JSON is used (backward compatible) - Type-Safe: The conversion is compile-time verified through the type system
- Zero Overhead: Only computed once per step and cached in context
Semantic Variable Mapping: Smart Context Management
Problem: In traditional orchestrators, context grows linearly as each step adds its output. By step 10, you're sending ~5KB of previous outputs on every agent call, most of which are irrelevant.
Solution: The orchestrator uses semantic variable mapping to pass only the necessary context to each agent.
How It Works:
// Step 3's intent template (generated by strategy LLM)
"Create a character profile using:
- Concept: {{ concept_content }}
- Design: {{ emblem_design }}
- World: {{ world_setting }}"
When executing Step 3, the orchestrator:
- Extracts placeholders:
["concept_content", "emblem_design", "world_setting"] - Matches to previous steps:
concept_content→ Step 1's output (keyword match: "concept")emblem_design→ Step 2's output (keyword match: "emblem", "design")world_setting→ Step 0's output (LLM semantic match if keyword fails)
- Builds minimal context: Only includes matched step outputs (full version, no truncation)
- Passes to agent: Agent receives only relevant information
Matching Strategy (2-Stage):
- Phase 1 - Keyword Matching: Fast pattern matching on step descriptions and expected outputs
- Phase 2 - LLM Fallback: If keywords fail, internal LLM performs semantic matching
Benefits:
- Prevents Context Explosion: O(k) where k = number of placeholders (typically 2-3), instead of O(n) where n = all previous steps
- Full Information: No truncation—sends complete output for matched steps
- Semantic Clarity: Variable names like
{{ concept_content }}are meaningful to developers - Automatic: Strategy generation LLM decides what context each step needs
Example Output:
Step 3 receives context:
{
"concept_content": "<Full Step 1 output>", // ~2KB
"emblem_design": "<Full Step 2 output>", // ~1.5KB
"world_setting": "<Full Step 0 output>", // ~1KB
"previous_output": "<Step 2 output>" // ~1.5KB
}
Total: ~6KB (vs ~25KB if all 10 previous steps were included)
Common Pitfall:
❌ Manually extracting intermediate results:
// DON'T DO THIS - Orchestrator handles it automatically!
let result = orchestrator.execute.await;
let concept = extract_from_context?; // Not accessible!
let emblem = extract_from_context?; // Not accessible!
✅ Correct approach - Design the final agent to aggregate:
// The LAST agent's intent template should request all needed data
"Generate final output including:
- Concept: {{ concept_content }}
- Emblem: {{ emblem_design }}
- Profile: {{ character_profile }}"
// Then final_output contains everything
let result = orchestrator.execute.await;
let complete_data = result.final_output; // All data aggregated by final agent
Understanding Context Key Resolution:
The semantic variable names shown in intent templates (like {{ concept_content }}, {{ emblem_design }}) are resolved via semantic matching to step outputs, not through a rename/alias mechanism.
How Context Keys Actually Work:
-
Step outputs are stored with standard keys:
step_1_output- JSON versionstep_1_output_prompt- ToPrompt version (if available)
-
Semantic placeholders are matched to steps:
- When the orchestrator sees
{{ concept_content }}in an intent template - It performs semantic matching (keyword or LLM-based) to find the appropriate step
- Maps
concept_content→step_1_outputinternally - Passes the matched step output to the agent
- When the orchestrator sees
-
No rename/alias mechanism currently:
- You cannot define custom aliases like
persona_json→step_2_output - The strategy generation LLM creates semantic names based on step descriptions
- These names are automatically matched to the actual
step_N_outputkeys
- You cannot define custom aliases like
-
Accessing nested fields with dot notation:
- Intent templates support Jinja2-style dot notation
- Example:
{{ step_3_output.user.profile.role }}accesses nested JSON fields - This works with both direct step references and semantically matched names
What About External Context?
If you add context before execution using context_mut():
orchestrator.context_mut.insert;
This data is not automatically available to agents unless:
- It's referenced as a step output from a previous step
- Or you manually construct an intent template that uses
{{ persona_json }}AND ensure it matches a step output through semantic matching
Best Practice:
For most use cases, let the strategy LLM generate semantic placeholder names based on step descriptions. The orchestrator will handle the matching automatically:
// ✅ Good: Strategy LLM generates semantic names
// Intent: "Create profile using {{ concept_data }} and {{ design_elements }}"
// Orchestrator matches: concept_data → step_1_output, design_elements → step_2_output
// ✅ Acceptable: Direct step references with dot notation
// Intent: "Process {{ step_1_output.concept }} and {{ step_2_output.design.colors }}"
Why? The orchestrator's context was internal. But now you can access it!
Accessing Intermediate Results (v0.13.6+)
You can now access intermediate step results using the context accessor methods:
let result = orchestrator.execute.await;
// Option 1: Get specific step output
if let Some = orchestrator.get_step_output
// Option 2: Get human-readable version (if ToPrompt was used)
if let Some = orchestrator.get_step_output_prompt
// Option 3: Get all step outputs
for in orchestrator.get_all_step_outputs
// Option 4: Access raw context
let context = orchestrator.context;
println!;
Available methods:
context()- Returns full context HashMapget_step_output(step_id)- Get JSON output of a specific stepget_step_output_prompt(step_id)- Get ToPrompt version (human-readable)get_all_step_outputs()- Get all step outputs as HashMap
Note: These methods are available after execute() completes. The context is preserved until the next execute() call.
Type-Based Output Retrieval with TypeMarker (v0.13.9+)
Problem: The orchestrator's strategy LLM generates non-deterministic step IDs (step_1, world_generation, analysis_phase, etc.), making it difficult to retrieve specific outputs by step ID. You want to retrieve outputs by type, not by guessing step names.
Solution: Use the TypeMarker pattern to retrieve outputs based on their type, regardless of which step produced them.
How It Works:
There are two ways to add __type field for type-based retrieval:
Method 1: Using #[type_marker] attribute macro (Recommended)
use ;
use ;
// IMPORTANT: #[type_marker] must be placed BEFORE #[derive(...)]
The #[type_marker] attribute macro automatically:
- Adds
__type: Stringfield with#[serde(default = "default_high_concept_response_type")] - Generates the default function that returns the struct name
- Implements the
TypeMarkertrait - The
__typefield is automatically excluded from LLM schema (ToPrompt skips fields named__type)
Method 2: Manual __type field definition (For custom configurations)
Use this method when you need special configurations:
- Custom field name or type
- Complex default function logic
- Integration with existing code
use ;
use ;
// 👈 Optional marker to document TypeMarker usage
Note: The #[prompt(type_marker)] parameter is optional and serves as documentation/marker. The __type field will be automatically excluded from LLM schema regardless.
Complete Example:
use ;
use ;
// Define your response types
// Define agents
;
;
// Register agents and execute
orchestrator.add_agent_with_to_prompt;
orchestrator.add_agent_with_to_prompt;
let result = orchestrator.execute.await?;
// Retrieve outputs by type - no need to know step IDs!
let concept: HighConceptResponse = orchestrator.get_typed_output?;
let profile: ProfileResponse = orchestrator.get_typed_output?;
println!;
println!;
Key Points:
#[type_marker]: Attribute macro that automatically adds__typefield and implementsTypeMarker- ⚠️ Must be placed FIRST (before
#[derive(...)]) due to Rust macro processing order - Generates: field, default function, and trait implementation
- The
__typefield is excluded from the JSON schema sent to LLMs (prevents confusion)
- ⚠️ Must be placed FIRST (before
#[derive(TypeMarker)]: Only implements the trait (use with manual__typefield)get_typed_output<T>(): Type-safe retrieval that returnsResult<T, OrchestratorError>- Schema exclusion: ToPrompt automatically skips fields named
__type(Line 154 in macro implementation)
Benefits:
- ✅ No Step ID Guessing: Retrieve outputs by type, not by unpredictable step names
- ✅ Type-Safe: Compile-time verification of output types
- ✅ Clean Schema:
__typeis excluded from schema to prevent LLM confusion - ✅ Automatic Deserialization:
__typeis added during JSON parsing via#[serde(default)] - ✅ DRY Principle: No manual field definition or JSON schema duplication needed
- ✅ Works with Dynamic Workflows: Strategy LLM can name steps anything; your code still works
Common Pattern:
// 1. Execute orchestrated workflow
let result = orchestrator.execute.await?;
// 2. Retrieve all needed outputs by type
let world_concept: WorldConceptResponse = orchestrator.get_typed_output?;
let high_concept: HighConceptResponse = orchestrator.get_typed_output?;
let emblem: EmblemResponse = orchestrator.get_typed_output?;
let profile: ProfileResponse = orchestrator.get_typed_output?;
// 3. Assemble final result
let spirit = Spirit ;
Comparison with Step-Based Retrieval:
// ❌ Step-based retrieval (fragile)
let concept_json = orchestrator.get_step_output?; // What if it's "concept_generation"?
let concept: HighConceptResponse = from_value?;
// ✅ Type-based retrieval (robust)
let concept: HighConceptResponse = orchestrator.get_typed_output?; // Always works!
Run the examples:
# See TypeMarker schema generation in action
# Full orchestrator example
Future Directions
Image Handling Abstraction
A planned feature is to introduce a unified interface for handling image inputs across different LLM providers. This would abstract away the complexities of dealing with various data formats (e.g., Base64, URLs, local file paths) and model-specific requirements, providing a simple and consistent API for multimodal applications.