Expand description
Pluggable model adapters for KOPITIAM’s Semantic Runtime.
This crate defines the ModelAdapter trait — the sole boundary through
which a model (local Qwen, Claude, GPT, Gemini, …) is invoked anywhere
in the platform. Per the Semantic Runtime’s dependency rule, only
kopitiam-workflow depends on this crate; everything else in the
platform (kopitiam-knowledge, kopitiam-index, kopitiam-search,
kopitiam-workspace, kopitiam-translation) stays model-agnostic.
What lives here is the shape of a request/response
(CompletionRequest, CompletionResponse, Message), one
deterministic stub adapter (EchoAdapter, always available) so
kopitiam-workflow has something real to compile and test against with
no weights and no network, and — behind the default-on local Cargo
feature — LocalAdapter, a real, offline, on-CPU adapter backed by
kopitiam-runtime’s Qwen inference stack. See [local]’s module docs
for the full local-vs-cloud architecture and why depending on
kopitiam-runtime from here does not violate the Semantic Runtime’s
dependency rule.
Two other pieces round out the boundary for a live chat UI:
- Streaming — alongside the blocking
ModelAdapter::complete, every adapter canModelAdapter::streamits reply token-by-token over a channel ofStreamChunks, so a UI renders tokens as they land instead of freezing on a slow generation.EchoAdapterandLocalAdapterdo this on a real background thread (the AID-0028 actor discipline, std threads +mpsc, no async runtime). - Cloud scaffold —
CloudAdapter+CloudStubfor Claude/GPT/Gemini (CloudVendor), gated on an API key from the environment. Key-detection and the “no key →CloudUnavailable” path are real; the network layer itself is a deliberate follow-up.
Structs§
- Applied
- The result of
Glossary::apply: the rewrittenoutput, plus the audit report of exactly what was substituted. - Bilingual
Options - Options for
render_bilingual. - Bilingual
Segment - One aligned source/target pair with a stable anchor.
- Bucket
- One severity bucket of diagnostics: a
labeland the distinct diagnostics that fell under it. - Cloud
Stub - A scaffold
CloudAdapterfor oneCloudVendor: does key-detection for real, and stands in for the not-yet-built network layer by returning a clearCloudUnavailableeither way. - Completion
Request - A request to a
crate::ModelAdapter. - Completion
Response - A
crate::ModelAdapter’s reply to aCompletionRequest. - Confidence
Signals - The composable evidence behind one segment’s
confidence, recorded so every decision is auditable (never a silent accept). - Diagnostic
Buckets - The result of
classify_diagnostics: severity buckets over the deduplicated diagnostics. - Drop
Report - A record of what a preprocessing step removed, filtered, or could not judge.
- Echo
Adapter - A
ModelAdapterthat invokes no model at all: it echoes the lastRole::Usermessage back as the response. - Entry
- One glossary rule: replace every (deterministically matched) occurrence of
sourcewithtarget. - Glossary
- An ordered set of
Entrys applied deterministically to text. - Local
Adapter - A
crate::ModelAdapterthat runs a GGUF Qwen model entirely on this machine’s CPU viakopitiam-runtime— no network, no cloud account, no API key. This is what makes CLAUDE.md’s Offline First pipeline (“existing knowledge, then native Rust, then local AI, then cloud AI as the final fallback”) a real, callable rung rather than a promise: before this type existed, “local AI” had nothing behind it butcrate::EchoAdapter, which invokes no model at all. - Message
- One turn in a
CompletionRequest. - Preprocessed
- A preprocessing result: the compact
output, plus theDropReportof what producing it removed or set aside. - Review
Coverage - The quantified review saving: of
totalsegments,flaggedneed a look, so a reviewer readsreview_fractionof the document (§13 measurement). - Segment
Plan - The plan for one segment: the local draft, the confidence, the routing decision, and the signals behind it.
- Substitution
- One reported substitution:
sourcewas replaced bytargetexactlycounttimes. Only terms that actually fired appear in anAppliedreport. - TwoPass
Config - Configuration for
draft_and_route: the routing threshold, the length comfort band, and the source/target language hints used only to frame the draft prompt. - TwoPass
Plan - The result of
draft_and_route: oneSegmentPlanper input segment, plus any honesty caveats that apply to the whole plan. - TwoPass
Summary - The measurable split produced by
TwoPassPlan::summary.
Enums§
- Cloud
Unavailable - Why a cloud rung couldn’t answer. Both variants are the honest miss
signal the design’s dispatch ladder relies on (
temp_ai_design.md§2): the provider reports it can’t cover the task instead of bluffing, and the dispatcher falls through. - Cloud
Vendor - Which cloud vendor a
CloudAdaptertalks to. Each knows the environment variable its API key lives in, a human-facing name, and a sensible default model id — the minimum a dispatcher needs to probe the rung before any network layer exists. - Decision
- What to do with one drafted segment.
- Layout
- How to lay the aligned pairs out.
- Role
- Who authored a
Messagein aCompletionRequest. - Source
Kind - Which deterministic matching rule an
Entry’ssourceuses, decided from the source text itself (rule 2 above). - Stream
Chunk - One piece of a streamed model reply, delivered in order over the
ReceiverthatModelAdapter::streamreturns.
Constants§
- DEFAULT_
ACCEPT_ THRESHOLD - The conservative default
TwoPassConfig::accept_threshold. - DEFAULT_
REVIEW_ THRESHOLD - The default confidence below which a segment is treated as needing review.
- ECHO_
PASSTHROUGH_ NOTE - Stamped into a
DropReportwhenever preprocessing ran against the echo stub instead of a real local model: the “output” is the input echoed back, not a filtered or compressed result, and must not be trusted as one. - REVIEW_
MARKER - The visible marker stamped on a segment that needs review, so a human
scanning the aligned output lands on it immediately. Kept as a stable
literal substring so tooling (and
review_targetsconsumers) can grep for it. - TWO_
PASS_ ECHO_ PASSTHROUGH_ NOTE - Stamped into a
TwoPassPlanwhenever drafting ran against the echo stub instead of a real local model: the “draft” is the source echoed back and the round-trip agreement is trivially perfect, so the round-trip signal carries no information and is folded in as neutral. Do not read a highlocal_fractionfrom an echo run as evidence the local model is good enough.
Traits§
- Cloud
Adapter - The vendor-specific seam of a cloud model adapter.
- Model
Adapter - A pluggable connection to one model backend.
Functions§
- classify_
diagnostics - Bucket raw compiler-diagnostic text by severity, after removing exact duplicates.
- dice_
similarity - Character-bigram Sørensen–Dice similarity in
0..=1(1.0= identical), the round-trip agreement metric. Deterministic, dependency-free, and character-based so it works on CJK source text. - draft_
and_ route - Draft every segment with the local
adapter, apply the III-5glossarydeterministically, score confidence from composable signals, and route each segment toAcceptLocalorSendToCloudagainstcfg.accept_threshold. - draft_
commit_ message - Draft a commit-message subject line for
diffby routing the whole diff through the local model (optional helper; card II-6). - from_
two_ pass - Bridge from III-6: build aligned segments from a slice of two-pass
crate::SegmentPlans and a parallel slice of finishedtargets(the reviewed/final target text for each plan, in the same order). - glossary_
score - Glossary sub-score in
0..=1. Neutral0.5when no glossary was supplied or nothing hit; rising with diminishing returns as more project-decided terms are pinned deterministically (0.5 + 0.5·(1 − 1/(1+hits))). Hits are positive evidence — never a penalty for a term-free segment. - length_
score - Length sub-score in
0..=1:1.0within the comfortable band[min, max], falling off linearly to0.0at zero length and decaying toward a0.3floor for over-long segments. - render_
bilingual - Render aligned source/target output with stable per-segment anchors.
- review_
coverage - Compute the
ReviewCoveragefor a set of segments using the default review threshold — the measurement backing the card: a reviewer readsflaggedoftotal. - review_
targets - The anchors of the segments a reviewer must actually check — the “read only
these” list (§0.1). A segment is included when it is
needs_reviewor its recorded confidence is belowDEFAULT_REVIEW_THRESHOLD. Returned in ascendingindexorder to match the rendered output. - summarize
- Compress
textto at mosttarget_lineslines by routing it through the local model, then hard-capping the reply attarget_lines. - triage
- Filter
candidates(e.g. grep-hit snippets) down to the subset plausibly relevant toquery, by asking the local model which to keep.