Skip to main content

perspt_sdk/prompt/
compose.rs

1//! Stage composition (PSP-10 system 24).
2//!
3//! A stage composer is ordinary typed Rust: inclusion predicates are code
4//! (`section_if`), variables are typed struct fields, and every section
5//! renders eagerly, so object safety never arises. Compilation fits the
6//! dialect's token budget deterministically and lays the surviving
7//! sections out per the dialect's system-slot policy.
8
9use crate::error::{Result, SdkError};
10
11use super::budget::fit_budget;
12use super::dialect::{ModelDialect, SystemSlotPolicy};
13use super::digest::{CompiledPromptMessage, CompiledPromptProgram};
14use super::route::PromptRoute;
15use super::section::{
16    OverrideOrigin, PromptMessageRole, PromptSection, RenderedSection, SectionProvenance,
17};
18use super::stage::PromptStage;
19
20/// An in-progress composition for one stage.
21#[derive(Debug)]
22pub struct StageComposition {
23    stage: PromptStage,
24    sections: Vec<(RenderedSection, OverrideOrigin)>,
25    error: Option<SdkError>,
26    system_separator: Option<String>,
27}
28
29impl StageComposition {
30    pub fn new(stage: PromptStage) -> Self {
31        Self {
32            stage,
33            sections: Vec::new(),
34            error: None,
35            system_separator: None,
36        }
37    }
38
39    /// Use the stage's declared section separator when the dialect
40    /// concatenates system sections into one slot (the migrated platform
41    /// literals' byte identity depends on it). Without this, the dialect's
42    /// boundary marker joins.
43    pub fn system_separator(mut self, separator: &str) -> Self {
44        self.system_separator = Some(separator.to_string());
45        self
46    }
47
48    /// Append a typed base section, rendering it eagerly.
49    pub fn section(mut self, section: impl PromptSection) -> Self {
50        if self.error.is_some() {
51            return self;
52        }
53        match section.render() {
54            Ok(rendered) => self.sections.push((rendered, OverrideOrigin::Base)),
55            Err(error) => self.error = Some(error),
56        }
57        self
58    }
59
60    /// Typed inclusion predicate: append only when `include` holds.
61    pub fn section_if(self, include: bool, section: impl PromptSection) -> Self {
62        if include { self.section(section) } else { self }
63    }
64
65    /// Append an already-resolved section (the template-resolution path;
66    /// carries its override origin).
67    pub fn resolved(mut self, rendered: RenderedSection, origin: OverrideOrigin) -> Self {
68        if self.error.is_none() {
69            self.sections.push((rendered, origin));
70        }
71        self
72    }
73
74    /// Compile: deterministic budget fit, dialect layout, digests.
75    pub fn compile(
76        self,
77        route: &PromptRoute,
78        dialect: &ModelDialect,
79        tool_spec_hash: &str,
80    ) -> Result<CompiledPromptProgram> {
81        if let Some(error) = self.error {
82            return Err(error);
83        }
84        let token_budget = dialect.context_window_tokens;
85        let mut origins: std::collections::BTreeMap<String, OverrideOrigin> =
86            std::collections::BTreeMap::new();
87        let mut rendered = Vec::with_capacity(self.sections.len());
88        for (section, origin) in self.sections {
89            origins.insert(section.id.0.clone(), origin);
90            rendered.push(section);
91        }
92        let fit = fit_budget(rendered, &dialect.token_accountant, token_budget)?;
93        let separator = self
94            .system_separator
95            .as_deref()
96            .unwrap_or(&dialect.boundary_marker);
97        let messages = layout_messages(&fit.kept, dialect, separator, &origins);
98        let total_bytes: usize = messages.iter().map(|message| message.content.len()).sum();
99        if total_bytes as u64 > dialect.max_prompt_bytes {
100            return Err(SdkError::Domain(format!(
101                "compiled program of {total_bytes} bytes exceeds the dialect's \
102                 {}-byte limit",
103                dialect.max_prompt_bytes
104            )));
105        }
106        let program_digest = CompiledPromptProgram::compute_digest(
107            route,
108            self.stage,
109            &dialect.dialect_ref(),
110            &dialect.token_accountant.id,
111            token_budget,
112            &messages,
113            &fit.dropped,
114            tool_spec_hash,
115        );
116        Ok(CompiledPromptProgram {
117            route: route.clone(),
118            stage: self.stage,
119            dialect: dialect.dialect_ref(),
120            messages,
121            dropped_sections: fit.dropped,
122            tool_spec_hash: tool_spec_hash.to_string(),
123            program_digest,
124        })
125    }
126}
127
128fn provenance(
129    section: &RenderedSection,
130    origins: &std::collections::BTreeMap<String, OverrideOrigin>,
131) -> SectionProvenance {
132    SectionProvenance {
133        id: section.id.clone(),
134        version: section.version,
135        content_hash: section.content_hash.clone(),
136        origin: origins
137            .get(&section.id.0)
138            .cloned()
139            .unwrap_or(OverrideOrigin::Base),
140    }
141}
142
143/// Lay the surviving sections out per the dialect: separate system messages
144/// under [`SystemSlotPolicy::Many`], or one deterministic concatenation with
145/// the boundary marker under [`SystemSlotPolicy::SingleConcatenated`].
146/// User-role sections are always separate messages.
147fn layout_messages(
148    kept: &[RenderedSection],
149    dialect: &ModelDialect,
150    separator: &str,
151    origins: &std::collections::BTreeMap<String, OverrideOrigin>,
152) -> Vec<CompiledPromptMessage> {
153    let mut messages = Vec::new();
154    let system: Vec<&RenderedSection> = kept
155        .iter()
156        .filter(|section| section.role == PromptMessageRole::System)
157        .collect();
158    match dialect.system_slots {
159        SystemSlotPolicy::Many => {
160            for section in &system {
161                messages.push(message(
162                    PromptMessageRole::System,
163                    section.content.clone(),
164                    vec![provenance(section, origins)],
165                ));
166            }
167        }
168        SystemSlotPolicy::SingleConcatenated => {
169            if !system.is_empty() {
170                let content = system
171                    .iter()
172                    .map(|section| section.content.as_str())
173                    .collect::<Vec<_>>()
174                    .join(separator);
175                let sections = system
176                    .iter()
177                    .map(|section| provenance(section, origins))
178                    .collect();
179                messages.push(message(PromptMessageRole::System, content, sections));
180            }
181        }
182    }
183    for section in kept
184        .iter()
185        .filter(|section| section.role == PromptMessageRole::User)
186    {
187        messages.push(message(
188            PromptMessageRole::User,
189            section.content.clone(),
190            vec![provenance(section, origins)],
191        ));
192    }
193    messages
194}
195
196fn message(
197    role: PromptMessageRole,
198    content: String,
199    sections: Vec<SectionProvenance>,
200) -> CompiledPromptMessage {
201    let rendered_hash = CompiledPromptMessage::hash_content(&content);
202    CompiledPromptMessage {
203        role,
204        content,
205        sections,
206        rendered_hash,
207    }
208}
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213    use crate::model::ModelFamily;
214    use crate::prompt::section::{PromptSectionId, PromptSectionVersion};
215
216    fn rendered(id: &str, role: PromptMessageRole, body: &str) -> RenderedSection {
217        RenderedSection {
218            id: PromptSectionId(id.into()),
219            version: PromptSectionVersion(1),
220            role,
221            required: true,
222            priority: 0,
223            content_hash: format!("sha256:{id}"),
224            content: body.into(),
225        }
226    }
227
228    fn route() -> PromptRoute {
229        PromptRoute {
230            adapter: "scripted".into(),
231            family: ModelFamily::Other("scripted".into()),
232            exact_model: None,
233        }
234    }
235
236    #[test]
237    fn the_two_dialects_lay_out_the_same_program_differently() {
238        let build = || {
239            StageComposition::new(PromptStage::BranchCorrect)
240                .resolved(
241                    rendered("branch_correct/role", PromptMessageRole::System, "You fix."),
242                    OverrideOrigin::Base,
243                )
244                .resolved(
245                    rendered(
246                        "branch_correct/output_contract",
247                        PromptMessageRole::System,
248                        "Reply with JSON.",
249                    ),
250                    OverrideOrigin::Base,
251                )
252        };
253        let many = build()
254            .compile(&route(), &ModelDialect::native_tools_v1(), "sha256:tools")
255            .unwrap();
256        let single = build()
257            .compile(
258                &route(),
259                &ModelDialect::json_single_slot_v1(),
260                "sha256:tools",
261            )
262            .unwrap();
263        assert_eq!(many.messages.len(), 2);
264        assert_eq!(single.messages.len(), 1);
265        assert!(single.messages[0].content.contains("perspt:boundary"));
266        assert_ne!(many.program_digest, single.program_digest);
267    }
268
269    #[test]
270    fn identical_inputs_yield_identical_digests() {
271        let build = || {
272            StageComposition::new(PromptStage::BranchCorrect).resolved(
273                rendered("branch_correct/role", PromptMessageRole::System, "You fix."),
274                OverrideOrigin::Base,
275            )
276        };
277        let dialect = ModelDialect::native_tools_v1();
278        let first = build().compile(&route(), &dialect, "sha256:tools").unwrap();
279        let second = build().compile(&route(), &dialect, "sha256:tools").unwrap();
280        assert_eq!(first.program_digest, second.program_digest);
281        assert_eq!(first.messages, second.messages);
282        assert_eq!(first.dropped_sections, second.dropped_sections);
283    }
284
285    #[test]
286    fn oversize_programs_fail_the_dialect_byte_limit() {
287        let mut dialect = ModelDialect::native_tools_v1();
288        dialect.max_prompt_bytes = 4;
289        let composition = StageComposition::new(PromptStage::BranchCorrect).resolved(
290            rendered("branch_correct/role", PromptMessageRole::System, "too long"),
291            OverrideOrigin::Base,
292        );
293        assert!(
294            composition
295                .compile(&route(), &dialect, "sha256:tools")
296                .is_err()
297        );
298    }
299}