kkachi 0.1.8

High-performance, zero-copy library for optimizing language model prompts and programs
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
// Copyright © 2025 lituus-io <spicyzhug@gmail.com>
// All Rights Reserved.
// Licensed under PolyForm Noncommercial 1.0.0

// Allow manual modulo check since `is_multiple_of` is unstable (requires nightly)
#![allow(clippy::manual_is_multiple_of)]

//! # Kkachi - High-Performance LM Optimization Library
//!
//! Zero-copy, embeddable library for optimizing language model prompts and programs.
//! Designed for production use with focus on performance, safety, and ease of integration.
//!
//! ## Architecture
//!
//! Kkachi is built on several key principles:
//!
//! - **TRUE Zero-Copy**: `StrView<'a>` and `BufferView<'a>` for zero-allocation string handling
//! - **String Interning**: 4-byte `Sym` symbols for field names instead of 24-byte Strings
//! - **GATs**: Generic Associated Types for zero-cost async without boxing
//! - **Streaming Pipelines**: Data flows between modules without full materialization
//!
//! ## Quick Start
//!
//! ```ignore
//! use kkachi::recursive::prelude::*;
//!
//! let llm = MockLlm::new(|prompt, _| "fn add(a: i32, b: i32) -> i32 { a + b }".to_string());
//!
//! // Simple refinement with validation
//! let result = refine(&llm, "Write an add function")
//!     .validate(checks().require("fn ").require("->"))
//!     .max_iter(5)
//!     .go()
//!     .unwrap();
//!
//! // CLI validation pipeline
//! let validator = cli("rustfmt").arg("--check")
//!     .then("rustc").args(&["--emit=metadata"]).required()
//!     .ext("rs");
//!
//! let result = refine(&llm, "Write a parser")
//!     .validate(validator)
//!     .go()
//!     .unwrap();
//! ```

#![warn(missing_docs)]
#![cfg_attr(not(feature = "std"), no_std)]
// Allow common patterns that trigger clippy warnings but are intentional
#![allow(clippy::new_ret_no_self)]
#![allow(clippy::should_implement_trait)]
#![allow(clippy::type_complexity)]
#![allow(clippy::too_many_arguments)]
#![allow(clippy::needless_lifetimes)]
#![allow(clippy::int_plus_one)]
#![allow(clippy::unnecessary_map_or)]
#![allow(clippy::while_let_loop)]
#![allow(clippy::implicit_saturating_sub)]
#![allow(clippy::manual_pattern_char_comparison)]

#[cfg(feature = "std")]
extern crate std;

// Phase 0: Zero-copy foundation
pub mod buffer;
pub mod intern;
pub mod str_view;

// Phase 1: Core infrastructure
pub mod bootstrap;
pub mod error;
pub mod example;
pub mod field;
pub mod module;
pub mod optimizer;
pub mod predict;
pub mod prediction;
pub mod signature;
pub mod types;

// v0.4.0: New core modules
pub mod compiled;
pub mod composable;
pub mod evaluate;
pub mod metric;
pub mod typed_adapter;
pub mod typed_sig;

// Phase 4: Advanced optimizers
pub mod optimizers;

// Phase 5: Zero-copy adapters
pub mod adapter;

// Phase 6: Assertions
pub mod assertion;

// Phase 8: Hybrid executor
pub mod executor;

// Phase 10: Recursive Language Prompting (simplified API)
pub mod recursive;

// Phase 11: Diff visualization
pub mod diff;

// Phase 12: Human-in-the-Loop
pub mod hitl;

// Phase 13: Declarative API (thin re-export of recursive)
pub mod declarative;

// Recall/Precision tuning
pub mod recall_precision;

// Re-exports for convenience
pub use bootstrap::{BootstrapFewShot, BootstrapFewShotWithRandomSearch};
pub use error::{Error, OptimizationDetails, Result};
pub use example::Example;
pub use field::{Field, FieldType, InputField, OutputField};
pub use module::Module;
pub use optimizer::{ExampleMeta, ExampleSet, OptimizationResult, Optimizer, OptimizerConfig, Rng};
pub use predict::{
    predict_with_lm, DemoMeta, FieldRange, LMClient, LMOutput, Predict, PredictOutput,
};
pub use prediction::Prediction;
pub use signature::{Signature, SignatureBuilder};

// v0.4.0: Typed signature system
pub use typed_adapter::{ChatTypedAdapter, JsonTypedAdapter, TypedAdapter};
pub use typed_sig::{ParsedOutput, TypedField, TypedSignature, ValueKind};

// v0.4.0: Metric & evaluation
pub use evaluate::{EvalResult, Evaluate, ExampleResult};
pub use metric::{Contains as MetricContains, ExactMatch, F1Token, FnMetric, Metric};

// v0.4.0: Compiled programs
pub use compiled::CompiledProgram;

// v0.4.0: Composable modules
pub use composable::{ComposableModule, ModuleState};

// Advanced optimizers
pub use optimizers::{
    COPROConfig, COPROResult, CombineStrategy, Embedder as OptimizerEmbedder, EmbeddingIndex,
    Ensemble, EnsembleConfig, EnsembleResult, ErasedOptimizer, FailureCase, Improvement,
    ImprovementKind, KNNConfig, KNNFewShot, KNNSelector, LabeledConfig, LabeledFewShot,
    LabeledFewShotBuilder, MIPROConfig, MIPROResult, OptimizeInto, SIMBAConfig, SIMBAResult,
    SelectionStrategy, TPESampler, COPRO, MIPRO, SIMBA,
};

// Recall/Precision mode
pub use recall_precision::RecallPrecisionMode;

// Adapters
pub use adapter::{
    Adapter, ChatAdapter, ChatConfig, DemoData, JSONAdapter, JSONConfig, XMLAdapter, XMLConfig,
};

// Assertions
pub use assertion::{
    Assertion, AssertionLevel, AssertionResult, AssertionRunner, Contains, Custom, EndsWith,
    JsonValid, LengthBounds, NotEmpty, OneOf, RegexMatch, StartsWith,
};

// Executor
pub use executor::{
    BatchRunner, BufferPool, BufferPoolStats, ExecutorConfig, ExecutorStats, HybridExecutor,
    ScopedBuffer,
};

// Recursive Language Prompting (primary API)
pub use recursive::{
    // Agent
    agent,
    all,
    any,
    // Code execution
    bash_executor,
    // Best-of-N
    best_of,
    // Validation
    checks,
    cli,
    cosine_similarity,
    // Ensemble
    ensemble,
    extract_all_code,
    extract_code,
    extract_section,
    // Memory/RAG
    memory,
    mmr_select,
    // Multi-objective / Pareto
    multi_objective,
    node_executor,
    parse_output,
    // Pipeline
    pipeline,
    // Program
    program,
    python_executor,
    // Reason
    reason,
    // Core refinement
    refine,
    refine_pareto,
    refine_pareto_sync,
    // Markdown rewriting
    rewrite,
    ruby_executor,
    // Tool
    tool,
    // Typed/structured output
    typed,
    Agent,
    AgentConfig,
    AgentResult,
    Aggregate,
    All,
    AlwaysFail,
    And,
    Any,
    AsyncFnTool,
    BestOf,
    BestOfConfig,
    BestOfResult,
    BoolValidator,
    BoxedLlm,
    BranchBuilder,
    CacheExt,
    // Caching, retry, and rate limiting
    CachedLlm,
    CandidatePool,
    ChainResult,
    Checks,
    Cli,
    CliCapture,
    CliLlm,
    CliTool,
    CodeExecutor,
    // Results and state
    Compiled,
    Config as RefineConfig,
    ConsensusPool,
    ContextId,
    // Multi-turn conversation
    Conversation,
    Correction,
    DefaultScorer,
    Direction,
    Document,
    Embedder,
    ExecutionResult,
    FailingLlm,
    FanOutBranchResult,
    FeedbackFormatter,
    FnScorer,
    FnTool,
    FnValidator,
    FormatInstruction,
    FormatSpec,
    FormatType,
    HashEmbedder,
    Iteration,
    IterativeMockLlm,
    JsonSchema,
    LinearIndex,
    // LLM trait and implementations
    Llm,
    LlmExt,
    LmOutput,
    Memory,
    MergeStrategy,
    Message,
    MockLlm,
    MockTool,
    MultiObjective,
    MultiObjectiveValidate,
    MultiScore,
    NoValidation,
    Objective,
    OptimizedPrompt,
    Or,
    ParetoCandidate,
    ParetoFront,
    ParetoRefineResult,
    PassthroughFormatter,
    Pipeline,
    PipelineEvent,
    PipelineResult,
    PoolStats,
    ProcessExecutor,
    Program,
    ProgramConfig,
    ProgramResult,
    // Prompt formatting
    PromptFormatter,
    PromptTone,
    RateLimitConfig,
    RateLimitExt,
    RateLimitedLlm,
    Reason,
    ReasonConfig,
    ReasonResult,
    Recall,
    Refine,
    RefineEvent,
    RefineResult,
    RetryConfig,
    RetryLlm,
    Rewrite,
    Role,
    Scalarization,
    Score,
    ScoreValidator,
    ScoredCandidate,
    Scorer,
    Step,
    StepResult,
    StopReason,
    // Template
    Template,
    TemplateExample,
    TemplateOptions,
    ToneModifiers,
    Tool,
    ToolBuilder,
    TypedValidator,
    Validate,
    ValidateExt,
    VectorIndex,
};

// v0.4.0: Critic system
pub use recursive::critic::{Critic, CriticFeedback, FnCritic, LlmCritic, NoCritic};

// v0.4.0: Multimodal input
pub use recursive::input::{ContentType, Input, InputPart, MultimodalLlm};

// v0.4.0: State save/load
pub use recursive::state::{Saveable, SaveableExt, StateMap, StateValue};

// Feature-gated recursive exports
#[cfg(feature = "hnsw")]
pub use recursive::HnswIndex;
#[cfg(feature = "embeddings-onnx")]
pub use recursive::{OnnxEmbedder, OnnxEmbedderError};

// Diff visualization
pub use diff::{
    Change, ChangeKind, DemoSnapshot, DemosDiff, DiffAlgorithm, DiffColors, DiffHunk, DiffRenderer,
    DiffStats, DiffStyle, FieldsDiff, IterationDiffBuilder, ModuleDiff, TextDiff,
};

// Human-in-the-Loop
pub use hitl::{
    AsyncHumanReviewer, AutoAcceptReviewer, CallbackReviewer, HITLConfig, HumanReviewer,
    RecordingReviewer, ReviewContext, ReviewDecision, ReviewTrigger, TerminalReviewer,
    ThresholdReviewer,
};

// Declarative API (thin re-export of recursive + Jinja)
pub use declarative::{JinjaFormatter, JinjaTemplate, JinjaValue};

// Zero-copy types
pub use buffer::{Buffer, BufferView};
pub use intern::{resolve, sym, Sym};
pub use str_view::StrView;
pub use types::{FieldMap, Inputs};

/// Prelude module for convenient imports.
pub mod prelude {
    // New simplified recursive API
    pub use crate::recursive::prelude::*;

    // Error handling
    pub use crate::{Error, OptimizationDetails, Result};

    // Zero-copy types
    pub use crate::{resolve, sym, Buffer, BufferView, StrView, Sym};

    // Core types
    pub use crate::{
        Example, Field, FieldMap, InputField, Inputs, Module, OutputField, Predict, Prediction,
        Signature, SignatureBuilder,
    };

    // v0.4.0: Typed signatures
    pub use crate::{TypedSignature, ValueKind};

    // v0.4.0: Metrics & evaluation
    pub use crate::{ExactMatch, Metric};

    // v0.4.0: Compiled programs
    pub use crate::CompiledProgram;

    // v0.4.0: Composable modules
    pub use crate::{ComposableModule, ModuleState};

    // v0.4.0: Critic
    pub use crate::{Critic, NoCritic};

    // v0.4.0: State
    pub use crate::{Saveable, SaveableExt, StateMap};

    // Optimizer system
    pub use crate::{
        BootstrapFewShot, ExampleSet, Optimizer, OptimizerConfig, COPRO, MIPRO, SIMBA,
    };

    // Adapters
    pub use crate::{Adapter, ChatAdapter, JSONAdapter, XMLAdapter};

    // Assertions
    pub use crate::{Assertion, AssertionLevel, AssertionRunner};

    // Executor
    pub use crate::{BatchRunner, BufferPool, ExecutorConfig, HybridExecutor};

    // Diff
    pub use crate::DiffStyle;

    // HITL
    pub use crate::{HITLConfig, ReviewDecision};

    // Recall/Precision
    pub use crate::RecallPrecisionMode;

    // LM Client
    pub use crate::{predict_with_lm, LMClient};
}

/// Version of the library
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

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

    #[test]
    #[allow(clippy::const_is_empty)]
    fn test_version() {
        assert!(!VERSION.is_empty());
    }
}