paladin-ai 0.5.1

Enterprise AI orchestration framework with multi-agent coordination patterns
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
# Output Formatting Guide

This guide covers the Herald system for formatting and controlling Paladin output in various formats and styles.

## Table of Contents

- [Overview]#overview
- [Herald Architecture]#herald-architecture
- [Built-in Formatters]#built-in-formatters
- [Custom Formatters]#custom-formatters
- [Streaming Output]#streaming-output
- [Multi-Format Output]#multi-format-output
- [Post-Processing]#post-processing
- [Best Practices]#best-practices
- [Advanced Patterns]#advanced-patterns
- [Troubleshooting]#troubleshooting

## Overview

The Herald system controls how Paladin output is formatted and presented to users.

**Key Capabilities:**
- **Format Transformation**: Convert LLM output to JSON, Markdown, HTML, etc.
- **Streaming**: Real-time output delivery for better UX
- **Validation**: Ensure output meets schema requirements
- **Post-Processing**: Clean, enhance, or transform responses
- **Multi-Channel**: Different formats for different output destinations

**Key Concepts:**
- **Herald**: Output formatting system
- **Formatter**: Converts raw LLM output to specific format
- **OutputFormat**: Target format specification (JSON, Markdown, Plain, etc.)
- **StreamHandler**: Processes output chunks in real-time

## Herald Architecture

### Core Components

```rust,ignore
// Output format types (paladin_core::platform::container::paladin_config)
pub enum OutputFormat {
    Text,           // Raw text output
    Json,           // Structured JSON
    Structured,     // Structured data output
}

// Herald interface (paladin_core::platform::container::herald)
pub trait Herald: Send + Sync {
    /// Format a complete Paladin execution result
    fn format_paladin_result(&self, result: &PaladinResult) -> Result<String, HeraldError>;

    /// Format a complete Battalion execution result
    fn format_battalion_result(&self, result: &BattalionResult) -> Result<String, HeraldError>;

    /// Format a streaming chunk
    fn format_stream_chunk(&self, chunk: &StreamChunk) -> Result<String, HeraldError>;
}
```

### Integration with Paladin

```rust,ignore
let paladin = PaladinBuilder::new(llm_adapter)
    .name("Assistant")
    .system_prompt("You are a helpful assistant.")
    .output_format(OutputFormat::Text)
    .with_herald(Arc::new(MarkdownHerald::default()))
    .build()?;

let response = paladin.execute("Explain async/await").await?;
// response.content is formatted as Markdown
```

## Built-in Formatters

### Plain Text Herald

No formatting, returns raw LLM output.

```rust,ignore
use paladin_core::platform::container::herald::{Herald, HeraldError};
use paladin::infrastructure::adapters::herald::{JsonHerald, MarkdownHerald, TableHerald};

let herald = Arc::new(MarkdownHerald::new());

let paladin = PaladinBuilder::new(llm_adapter)
    .with_herald(herald)
    .build()?;

let response = paladin.execute("Hello").await?;
println!("{}", response.content);  // Raw output
```

### Markdown Herald

Formats output as Markdown with proper structure.

```rust,ignore
use paladin_core::platform::container::herald::{Herald, HeraldError};
use paladin::infrastructure::adapters::herald::{JsonHerald, MarkdownHerald, TableHerald};

let herald = Arc::new(MarkdownHerald::new()
    .with_code_highlighting(true)
    .with_header_ids(true)
    .with_table_of_contents(true)
);

let paladin = PaladinBuilder::new(llm_adapter)
    .system_prompt("Format all responses as Markdown with proper headers and code blocks.")
    .with_herald(herald)
    .build()?;

let response = paladin.execute("Explain Rust ownership").await?;
println!("{}", response.content);
```

**Output example:**
```markdown
# Rust Ownership

Ownership is a core concept in Rust that ensures memory safety.

## Key Rules

1. Each value has a single owner
2. When the owner goes out of scope, the value is dropped
3. Values can be borrowed immutably or mutably

## Example

```rust,ignore
fn main() {
    let s1 = String::from("hello");
    let s2 = s1;  // s1 is moved
    // println!("{}", s1);  // Error: s1 is no longer valid
}
```

## Benefits

- Memory safety without garbage collection
- No data races at compile time
- Zero-cost abstractions
```

### JSON Herald

Formats output as structured JSON.

```rust,ignore
use paladin_core::platform::container::herald::{Herald, HeraldError};
use paladin::infrastructure::adapters::herald::{JsonHerald, MarkdownHerald, TableHerald};
use serde_json::json;

let herald = Arc::new(JsonHerald::new()
    .with_schema(json!({
        "type": "object",
        "properties": {
            "summary": {"type": "string"},
            "key_points": {
                "type": "array",
                "items": {"type": "string"}
            },
            "confidence": {"type": "number"}
        },
        "required": ["summary", "key_points"]
    }))
    .validate_output(true)
);

let paladin = PaladinBuilder::new(llm_adapter)
    .system_prompt("Always respond in JSON format matching this schema: \
                    {summary: string, key_points: string[], confidence: number}")
    .with_herald(herald)
    .build()?;

let response = paladin.execute("Analyze sentiment of: 'This product is amazing!'").await?;

// Parse structured output
let json: serde_json::Value = serde_json::from_str(&response.content)?;
println!("Summary: {}", json["summary"]);
println!("Key points: {:?}", json["key_points"]);
```

**Output example:**
```json
{
  "summary": "Highly positive sentiment expressing enthusiasm",
  "key_points": [
    "Strong positive emotion indicated by 'amazing'",
    "Exclamation mark reinforces enthusiasm",
    "No negative indicators present"
  ],
  "confidence": 0.95
}
```

### HTML Herald

Formats output as styled HTML.

```rust,ignore
use paladin_core::platform::container::herald::{Herald, HeraldError};
use paladin::infrastructure::adapters::herald::{JsonHerald, MarkdownHerald, TableHerald};

let herald = Arc::new(JsonHerald::new()
    .with_css_framework(CssFramework::Tailwind)
    .with_syntax_highlighting(true)
    .with_responsive_design(true)
);

let paladin = PaladinBuilder::new(llm_adapter)
    .with_herald(herald)
    .build()?;

let response = paladin.execute("Create a todo list").await?;

// Serve as web page
let html = format!(r#"
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Paladin Response</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2/dist/tailwind.min.css" rel="stylesheet">
</head>
<body class="bg-gray-100 p-8">
    {}
</body>
</html>
"#, response.content);
```

### Code Herald

Specialized for code generation with syntax validation.

```rust,ignore
use paladin_core::platform::container::herald::{Herald, HeraldError};
use paladin::infrastructure::adapters::herald::{JsonHerald, MarkdownHerald, TableHerald};

let herald = Arc::new(CodeHerald::new()
    .language("rust")
    .with_syntax_check(true)
    .with_formatting(true)
    .with_linting(true)
);

let paladin = PaladinBuilder::new(llm_adapter)
    .system_prompt("You are a Rust code generator. Return ONLY valid Rust code.")
    .with_herald(herald)
    .build()?;

let response = paladin.execute("Write a function to reverse a string").await?;

// Output is validated, formatted Rust code
println!("{}", response.content);
```

**Output:**
```rust,ignore
pub fn reverse_string(s: &str) -> String {
    s.chars().rev().collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_reverse_string() {
        assert_eq!(reverse_string("hello"), "olleh");
        assert_eq!(reverse_string(""), "");
    }
}
```

## Custom Formatters

Create custom heralds for specialized output formats.

### Simple Custom Herald

```rust,ignore
use paladin_core::platform::container::herald::{Herald, HeraldError};
use paladin::infrastructure::adapters::herald::{JsonHerald, MarkdownHerald, TableHerald};
use async_trait::async_trait;

pub struct UppercaseHerald;

impl Herald for UppercaseHerald {
    fn format_paladin_result(&self, result: &PaladinResult) -> Result<String, HeraldError> {
        Ok(content.to_uppercase())
    }

    fn format_stream_chunk(&self, chunk: &StreamChunk) -> Result<String, HeraldError> {
        Ok(chunk.to_uppercase())
    }
}

// Usage
let herald = Arc::new(UppercaseHerald);
let paladin = PaladinBuilder::new(llm_adapter)
    .with_herald(herald)
    .build()?;
```

### XML Herald

```rust,ignore
use paladin_core::platform::container::herald::{Herald, HeraldError};
use paladin::infrastructure::adapters::herald::{JsonHerald, MarkdownHerald, TableHerald};
use quick_xml::Writer;
use std::io::Cursor;

pub struct XmlHerald {
    root_element: String,
}

impl XmlHerald {
    pub fn new(root_element: &str) -> Self {
        Self {
            root_element: root_element.to_string(),
        }
    }
}

impl Herald for XmlHerald {
    fn format_paladin_result(&self, result: &PaladinResult) -> Result<String, HeraldError> {
        let mut writer = Writer::new(Cursor::new(Vec::new()));

        // Write XML declaration
        writer.write_event(quick_xml::events::Event::Decl(
            quick_xml::events::BytesDecl::new("1.0", Some("UTF-8"), None)
        ))?;

        // Parse content as structured data
        let data: serde_json::Value = serde_json::from_str(content)
            .map_err(|e| HeraldError::FormatError(e.to_string()))?;

        // Convert to XML
        self.json_to_xml(&mut writer, &self.root_element, &data)?;

        let xml_bytes = writer.into_inner().into_inner();
        Ok(String::from_utf8(xml_bytes)?)
    }
}

// Usage
let herald = Arc::new(XmlHerald::new("response"));

let paladin = PaladinBuilder::new(llm_adapter)
    .system_prompt("Return JSON that will be converted to XML")
    .with_herald(herald)
    .build()?;
```

### CSV Herald

```rust,ignore
use paladin_core::platform::container::herald::{Herald, HeraldError};
use paladin::infrastructure::adapters::herald::{JsonHerald, MarkdownHerald, TableHerald};
use csv::Writer;

pub struct CsvHerald {
    headers: Vec<String>,
    delimiter: u8,
}

impl CsvHerald {
    pub fn new(headers: Vec<String>) -> Self {
        Self {
            headers,
            delimiter: b',',
        }
    }

    pub fn with_delimiter(mut self, delimiter: u8) -> Self {
        self.delimiter = delimiter;
        self
    }
}

impl Herald for CsvHerald {
    fn format_paladin_result(&self, result: &PaladinResult) -> Result<String, HeraldError> {
        // Parse JSON array
        let rows: Vec<serde_json::Value> = serde_json::from_str(content)
            .map_err(|e| HeraldError::FormatError(e.to_string()))?;

        let mut wtr = Writer::from_writer(vec![]);

        // Write headers
        wtr.write_record(&self.headers)?;

        // Write data rows
        for row in rows {
            let record: Vec<String> = self.headers.iter()
                .map(|h| {
                    row.get(h)
                        .map(|v| v.to_string())
                        .unwrap_or_default()
                })
                .collect();

            wtr.write_record(&record)?;
        }

        wtr.flush()?;
        let csv_bytes = wtr.into_inner()?;
        Ok(String::from_utf8(csv_bytes)?)
    }
}

// Usage
let herald = Arc::new(CsvHerald::new(vec![
    "name".to_string(),
    "age".to_string(),
    "city".to_string(),
]));

let paladin = PaladinBuilder::new(llm_adapter)
    .system_prompt("Return data as JSON array of objects with name, age, city fields")
    .with_herald(herald)
    .build()?;

let response = paladin.execute("Generate 5 sample user records").await?;
// Output is formatted CSV
```

## Streaming Output

Process and format output in real-time for better user experience.

### Basic Streaming

```rust,ignore
use paladin_core::platform::container::herald::{Herald, HeraldError};
use paladin::infrastructure::adapters::herald::{JsonHerald, MarkdownHerald, TableHerald};
use futures::StreamExt;

let herald = Arc::new(MarkdownHerald::default());

let paladin = PaladinBuilder::new(llm_adapter)
    .with_herald(herald.clone())
    .build()?;

// Execute with streaming
let mut stream = paladin.execute_stream("Write a story").await?;

while let Some(chunk) = stream.next().await {
    let chunk = chunk?;

    // Format chunk
    let formatted = herald.format_chunk(&chunk.content).await?;

    // Print in real-time
    print!("{}", formatted);
    std::io::stdout().flush()?;
}
println!();
```

### Streaming with Accumulation

```rust,ignore
pub struct StreamAccumulator {
    herald: Arc<dyn Herald>,
    buffer: String,
}

impl StreamAccumulator {
    pub fn new(herald: Arc<dyn Herald>) -> Self {
        Self {
            herald,
            buffer: String::new(),
        }
    }

    pub async fn process_chunk(&mut self, chunk: &str) -> Result<String, HeraldError> {
        self.buffer.push_str(chunk);

        // Format accumulated content
        self.herald.format(&self.buffer).await
    }

    pub fn buffer(&self) -> &str {
        &self.buffer
    }
}

// Usage
let mut accumulator = StreamAccumulator::new(herald);
let mut stream = paladin.execute_stream("Explain quantum computing").await?;

while let Some(chunk) = stream.next().await {
    let chunk = chunk?;
    let formatted_so_far = accumulator.process_chunk(&chunk.content).await?;

    // Update UI with fully formatted content
    update_ui(&formatted_so_far);
}
```

### Progress Indicators

```rust,ignore
pub struct ProgressHerald {
    inner: Arc<dyn Herald>,
    show_progress: bool,
}

impl Herald for ProgressHerald {
    fn format_stream_chunk(&self, chunk: &StreamChunk) -> Result<String, HeraldError> {
        let formatted = self.inner.format_chunk(chunk).await?;

        if self.show_progress {
            // Add visual progress indicator
            Ok(format!("{} .", formatted))
        } else {
            Ok(formatted)
        }
    }

    fn format_paladin_result(&self, result: &PaladinResult) -> Result<String, HeraldError> {
        self.inner.format_paladin_result(result)
    }
}
```

## Multi-Format Output

Generate output in multiple formats simultaneously.

### Multi-Format Herald

```rust,ignore
pub struct MultiFormatHerald {
    heralds: HashMap<String, Arc<dyn Herald>>,
}

impl MultiFormatHerald {
    pub fn new() -> Self {
        Self {
            heralds: HashMap::new(),
        }
    }

    pub fn add_format(mut self, name: &str, herald: Arc<dyn Herald>) -> Self {
        self.heralds.insert(name.to_string(), herald);
        self
    }

    pub async fn format_all(&self, content: &str) -> Result<HashMap<String, String>, HeraldError> {
        let mut results = HashMap::new();

        for (name, herald) in &self.heralds {
            let formatted = herald.format(content).await?;
            results.insert(name.clone(), formatted);
        }

        Ok(results)
    }
}

// Usage
let multi_herald = MultiFormatHerald::new()
    .add_format("json", Arc::new(JsonHerald::default()))
    .add_format("markdown", Arc::new(MarkdownHerald::default()))
    .add_format("html", Arc::new(JsonHerald::new()));

let paladin = PaladinBuilder::new(llm_adapter).build()?;
let response = paladin.execute("Summarize Rust features").await?;

// Generate all formats
let all_formats = multi_herald.format_all(&response.content).await?;

// Save or serve each format
std::fs::write("output.json", &all_formats["json"])?;
std::fs::write("output.md", &all_formats["markdown"])?;
std::fs::write("output.html", &all_formats["html"])?;
```

### Adaptive Format Selection

```rust,ignore
pub struct AdaptiveHerald {
    formats: HashMap<String, Arc<dyn Herald>>,
    default: Arc<dyn Herald>,
}

impl AdaptiveHerald {
    pub async fn format_for_context(
        &self,
        content: &str,
        context: &OutputContext,
    ) -> Result<String, HeraldError> {
        let herald = self.select_herald(context);
        herald.format(content).await
    }

    fn select_herald(&self, context: &OutputContext) -> &Arc<dyn Herald> {
        match context.channel {
            OutputChannel::Web => self.formats.get("html").unwrap_or(&self.default),
            OutputChannel::Api => self.formats.get("json").unwrap_or(&self.default),
            OutputChannel::Terminal => self.formats.get("markdown").unwrap_or(&self.default),
            OutputChannel::File(ref ext) => {
                self.formats.get(ext.as_str()).unwrap_or(&self.default)
            }
        }
    }
}

pub struct OutputContext {
    pub channel: OutputChannel,
    pub user_preferences: HashMap<String, String>,
}

pub enum OutputChannel {
    Web,
    Api,
    Terminal,
    File(String),
}

// Usage
let adaptive = AdaptiveHerald::new()
    .with_format("html", Arc::new(JsonHerald::new()))
    .with_format("json", Arc::new(JsonHerald::default()))
    .with_format("markdown", Arc::new(MarkdownHerald::default()))
    .with_default(Arc::new(MarkdownHerald::new()));

// Format based on context
let web_output = adaptive.format_for_context(
    &content,
    &OutputContext {
        channel: OutputChannel::Web,
        user_preferences: HashMap::new(),
    }
).await?;

let api_output = adaptive.format_for_context(
    &content,
    &OutputContext {
        channel: OutputChannel::Api,
        user_preferences: HashMap::new(),
    }
).await?;
```

## Post-Processing

Transform or enhance output after formatting.

### Sanitization Herald

```rust,ignore
pub struct SanitizingHerald {
    inner: Arc<dyn Herald>,
    remove_patterns: Vec<regex::Regex>,
}

impl SanitizingHerald {
    pub fn new(inner: Arc<dyn Herald>) -> Self {
        Self {
            inner,
            remove_patterns: vec![
                // Remove potential PII
                regex::Regex::new(r"\b\d{3}-\d{2}-\d{4}\b").unwrap(),  // SSN
                regex::Regex::new(r"\b[\w\.-]+@[\w\.-]+\.\w+\b").unwrap(),  // Email
                regex::Regex::new(r"\b\d{3}-\d{3}-\d{4}\b").unwrap(),  // Phone
            ],
        }
    }
}

impl Herald for SanitizingHerald {
    fn format_paladin_result(&self, result: &PaladinResult) -> Result<String, HeraldError> {
        let formatted = self.inner.format(content).await?;

        // Remove sensitive patterns
        let mut sanitized = formatted;
        for pattern in &self.remove_patterns {
            sanitized = pattern.replace_all(&sanitized, "[REDACTED]").to_string();
        }

        Ok(sanitized)
    }

    // Implement other methods...
}
```

### Enhancement Herald

```rust,ignore
pub struct EnhancingHerald {
    inner: Arc<dyn Herald>,
}

impl Herald for EnhancingHerald {
    fn format_paladin_result(&self, result: &PaladinResult) -> Result<String, HeraldError> {
        let formatted = self.inner.format(content).await?;

        // Add enhancements
        let enhanced = self.add_table_of_contents(&formatted);
        let enhanced = self.add_footnotes(&enhanced);
        let enhanced = self.add_timestamps(&enhanced);

        Ok(enhanced)
    }

    fn add_table_of_contents(&self, content: &str) -> String {
        // Extract headers and generate TOC
        let headers = self.extract_headers(content);

        if headers.is_empty() {
            return content.to_string();
        }

        let toc = headers.iter()
            .map(|(level, text, id)| {
                let indent = "  ".repeat(*level - 1);
                format!("{}* [{}](#{})", indent, text, id)
            })
            .collect::<Vec<_>>()
            .join("\n");

        format!("## Table of Contents\n\n{}\n\n{}", toc, content)
    }

    fn add_footnotes(&self, content: &str) -> String {
        // Process [^1] style footnote references
        // Implementation...
        content.to_string()
    }

    fn add_timestamps(&self, content: &str) -> String {
        format!("Generated at: {}\n\n{}", chrono::Utc::now().to_rfc3339(), content)
    }
}
```

### Caching Herald

```rust,ignore
use std::collections::HashMap;
use std::sync::RwLock;

pub struct CachingHerald {
    inner: Arc<dyn Herald>,
    cache: RwLock<HashMap<String, String>>,
    max_cache_size: usize,
}

impl Herald for CachingHerald {
    fn format_paladin_result(&self, result: &PaladinResult) -> Result<String, HeraldError> {
        // Check cache
        {
            let cache = self.cache.read().unwrap();
            if let Some(cached) = cache.get(content) {
                return Ok(cached.clone());
            }
        }

        // Format
        let formatted = self.inner.format(content).await?;

        // Store in cache
        {
            let mut cache = self.cache.write().unwrap();

            // Evict oldest if at capacity
            if cache.len() >= self.max_cache_size {
                if let Some(key) = cache.keys().next().cloned() {
                    cache.remove(&key);
                }
            }

            cache.insert(content.to_string(), formatted.clone());
        }

        Ok(formatted)
    }

    // Implement other methods...
}
```

## Best Practices

### 1. Match Format to Use Case

```rust,ignore
// ✅ API endpoints - use JSON
let api_herald = Arc::new(JsonHerald::new()
    .with_schema(api_schema)
    .validate_output(true)
);

// ✅ Documentation - use Markdown
let docs_herald = Arc::new(MarkdownHerald::new()
    .with_table_of_contents(true)
    .with_code_highlighting(true)
);

// ✅ Web display - use HTML
let web_herald = Arc::new(JsonHerald::new()
    .with_css_framework(CssFramework::Bootstrap)
    .with_responsive_design(true)
);

// ✅ Data export - use CSV
let export_herald = Arc::new(CsvHerald::new(headers));
```

### 2. Validate Structured Output

```rust,ignore
let herald = Arc::new(JsonHerald::new()
    .with_schema(schema)
    .validate_output(true)  // Validate against schema
);

// Paladin will retry if output doesn't match schema
let paladin = PaladinBuilder::new(llm_adapter)
    .system_prompt("CRITICAL: Output MUST be valid JSON matching the schema")
    .with_herald(herald)
    .max_retries(3)  // Retry on validation failures
    .build()?;
```

### 3. Use Streaming for Long Responses

```rust,ignore
// ❌ Bad: Wait for complete response
let response = paladin.execute(long_prompt).await?;
println!("{}", response.content);  // User waits 30 seconds

// ✅ Good: Stream for immediate feedback
let mut stream = paladin.execute_stream(long_prompt).await?;
while let Some(chunk) = stream.next().await {
    let chunk = chunk?;
    print!("{}", chunk.content);  // Immediate output
    std::io::stdout().flush()?;
}
```

### 4. Layer Heralds for Composability

```rust,ignore
// Layer: Base -> Enhancement -> Sanitization -> Caching
let herald = Arc::new(
    CachingHerald::new(
        Arc::new(SanitizingHerald::new(
            Arc::new(EnhancingHerald::new(
                Arc::new(MarkdownHerald::default())
            ))
        )),
        100,  // cache size
    )
);
```

### 5. Provide Format Guidance in System Prompt

```rust,ignore
// ✅ Explicit format instructions
let paladin = PaladinBuilder::new(llm_adapter)
    .system_prompt(
        "You MUST respond in valid JSON format:\n\
         {\n\
           \"answer\": \"your response\",\n\
           \"confidence\": 0.0 to 1.0,\n\
           \"sources\": [\"source1\", \"source2\"]\n\
         }\n\
         Do NOT include any text outside this JSON structure."
    )
    .with_herald(Arc::new(JsonHerald::default()))
    .build()?;
```

## Advanced Patterns

### Template-Based Herald

```rust,ignore
use handlebars::Handlebars;

pub struct TemplateHerald {
    handlebars: Handlebars<'static>,
    template_name: String,
}

impl TemplateHerald {
    pub fn new(template: &str, template_name: &str) -> Result<Self, HeraldError> {
        let mut handlebars = Handlebars::new();
        handlebars.register_template_string(template_name, template)?;

        Ok(Self {
            handlebars,
            template_name: template_name.to_string(),
        })
    }
}

impl Herald for TemplateHerald {
    fn format_paladin_result(&self, result: &PaladinResult) -> Result<String, HeraldError> {
        // Parse content as JSON
        let data: serde_json::Value = serde_json::from_str(content)?;

        // Render template
        let rendered = self.handlebars.render(&self.template_name, &data)?;

        Ok(rendered)
    }

    // Implement other methods...
}

// Usage
let template = r#"
# {{title}}

**Summary:** {{summary}}

## Details

{{#each items}}
- {{this}}
{{/each}}

*Generated: {{timestamp}}*
"#;

let herald = Arc::new(TemplateHerald::new(template, "report")?);

let paladin = PaladinBuilder::new(llm_adapter)
    .system_prompt("Return JSON: {title, summary, items: [], timestamp}")
    .with_herald(herald)
    .build()?;
```

### Diff Herald

```rust,ignore
pub struct DiffHerald {
    previous_content: RwLock<Option<String>>,
}

impl Herald for DiffHerald {
    fn format_paladin_result(&self, result: &PaladinResult) -> Result<String, HeraldError> {
        let previous = self.previous_content.read().unwrap().clone();

        let formatted = if let Some(prev) = previous {
            // Generate diff
            self.generate_diff(&prev, content)
        } else {
            // First time, show all
            content.to_string()
        };

        // Update previous content
        *self.previous_content.write().unwrap() = Some(content.to_string());

        Ok(formatted)
    }

    fn generate_diff(&self, old: &str, new: &str) -> String {
        // Use diff algorithm
        // Implementation...
        format!("--- Old\n+++ New\n{}", new)
    }
}
```

## Troubleshooting

### Invalid JSON Output

**Problem**: JSON Herald fails to parse LLM output.

**Solutions**:
1. Strengthen system prompt with explicit JSON instructions
2. Add JSON schema to prompt
3. Enable output validation with retries
4. Use JSON mode in LLM if supported

```rust,ignore
let paladin = PaladinBuilder::new(llm_adapter)
    .system_prompt(
        "CRITICAL INSTRUCTION: You MUST respond with ONLY valid JSON. \
         No additional text before or after. No markdown code blocks. \
         Just pure JSON.\n\n\
         Schema: {\"result\": string, \"confidence\": number}"
    )
    .output_format(OutputFormat::Json)  // Some LLMs support JSON mode
    .max_retries(3)
    .build()?;
```

### Streaming Format Inconsistency

**Problem**: Streamed chunks don't format correctly.

**Solutions**:
1. Use accumulation pattern
2. Implement chunk boundary detection
3. Buffer until complete format units

```rust,ignore
pub struct BufferedStreamHerald {
    buffer: RwLock<String>,
    delimiter: String,
}

impl BufferedStreamHerald {
    fn format_stream_chunk(&self, chunk: &StreamChunk) -> Result<String, HeraldError> {
        let mut buffer = self.buffer.write().unwrap();
        buffer.push_str(chunk);

        // Check for complete units (e.g., sentences, paragraphs)
        if buffer.ends_with(&self.delimiter) {
            let complete = buffer.clone();
            buffer.clear();
            Ok(complete)
        } else {
            Ok(String::new())  // Not ready yet
        }
    }
}
```

### Performance Issues with Complex Formatting

**Problem**: Formatting is slow for large outputs.

**Solutions**:
1. Implement caching
2. Use lazy formatting (format on demand)
3. Optimize regex patterns
4. Consider parallel processing

```rust,ignore
// Lazy formatting
pub struct LazyHerald {
    inner: Arc<dyn Herald>,
    cached_result: RwLock<Option<String>>,
}

impl LazyHerald {
    pub async fn get_formatted(&self, content: &str) -> Result<String, HeraldError> {
        // Check cache
        if let Some(cached) = self.cached_result.read().unwrap().as_ref() {
            return Ok(cached.clone());
        }

        // Format and cache
        let formatted = self.inner.format(content).await?;
        *self.cached_result.write().unwrap() = Some(formatted.clone());

        Ok(formatted)
    }
}
```

## Testing

### Unit Testing Heralds

```rust,ignore
#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_json_herald_formats_correctly() {
        let herald = JsonHerald::default();

        let input = r#"{"name": "Alice", "age": 30}"#;
        let formatted = herald.format(input).await.unwrap();

        // Verify valid JSON
        let parsed: serde_json::Value = serde_json::from_str(&formatted).unwrap();
        assert_eq!(parsed["name"], "Alice");
        assert_eq!(parsed["age"], 30);
    }

    #[tokio::test]
    async fn test_json_herald_validates_schema() {
        let schema = json!({
            "type": "object",
            "properties": {
                "name": {"type": "string"}
            },
            "required": ["name"]
        });

        let herald = JsonHerald::new().with_schema(schema);

        // Valid
        assert!(herald.validate(r#"{"name": "Bob"}"#).is_ok());

        // Invalid - missing required field
        assert!(herald.validate(r#"{"age": 25}"#).is_err());
    }
}
```

## Examples

See working examples:
- `examples/herald_markdown_output.rs` - Markdown formatting
- `examples/herald_json_output.rs` - Structured JSON output
- `examples/herald_streaming.rs` - Real-time streaming
- `examples/herald_custom_formatter.rs` - Custom herald implementation

## Next Steps

- **[Tool Integration]tool-integration.md** - Format tool results
- **[Battalion Patterns]battalion-patterns.md** - Format multi-agent outputs
- **[API Reference]https://docs.rs/paladin** - Herald API documentation

## Related Resources

- [Handlebars Templates]https://handlebarsjs.com/
- [JSON Schema]https://json-schema.org/
- [Markdown Specification]https://commonmark.org/