1use crate::{Citation, ContextError, ContextSnapshot, TokenCounter, digest};
2use serde::{Deserialize, Serialize};
3use std::collections::{BTreeMap, BTreeSet};
4
5#[derive(Clone, Eq, PartialEq, Serialize, Deserialize)]
12#[serde(deny_unknown_fields)]
13pub struct ContextPrompt {
14 schema: String,
15 id: String,
16 snapshot_id: String,
17 tokenizer: String,
18 rendered: String,
19 rendered_tokens: usize,
20 max_tokens: usize,
21 citations: BTreeMap<String, Vec<Citation>>,
22}
23
24impl std::fmt::Debug for ContextPrompt {
25 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26 f.debug_struct("ContextPrompt")
27 .field("bytes", &self.rendered.len())
28 .field("rendered_tokens", &self.rendered_tokens)
29 .finish_non_exhaustive()
30 }
31}
32
33#[derive(Serialize)]
34struct PromptBlock<'a> {
35 cite: &'a str,
36 sources: BTreeSet<(&'a str, usize, usize)>,
37 text: &'a str,
38}
39
40impl ContextSnapshot {
41 pub fn prompt_view(
46 &self,
47 max_tokens: usize,
48 tokenizer: &impl TokenCounter,
49 ) -> Result<ContextPrompt, ContextError> {
50 self.verify(tokenizer)?;
51 if max_tokens == 0 || max_tokens > 1_000_000 {
52 return Err(ContextError::InvalidInput);
53 }
54 let mut citations = BTreeMap::new();
55 let mut rendered = String::new();
56 for (index, block) in self.blocks().iter().enumerate() {
57 let reference = format!("c{}", index + 1);
58 let value = PromptBlock {
59 cite: &reference,
60 sources: block
61 .citations
62 .iter()
63 .map(|citation| {
64 (
65 citation.source.as_str(),
66 citation.start_line,
67 citation.end_line,
68 )
69 })
70 .collect(),
71 text: &block.text,
72 };
73 if !rendered.is_empty() {
74 rendered.push('\n');
75 }
76 rendered.push_str(&serde_json::to_string(&value).map_err(|_| ContextError::Integrity)?);
77 citations.insert(reference, block.citations.clone());
78 }
79 let rendered_tokens = tokenizer.count(&rendered)?;
80 if rendered_tokens > max_tokens {
81 return Err(ContextError::BudgetUnsatisfiable);
82 }
83 let mut prompt = ContextPrompt {
84 schema: "cigar.context-prompt.v1".into(),
85 id: String::new(),
86 snapshot_id: self.id().to_owned(),
87 tokenizer: tokenizer.identity().to_owned(),
88 rendered,
89 rendered_tokens,
90 max_tokens,
91 citations,
92 };
93 prompt.id = digest("cigar.context-prompt.v1", &prompt)?;
94 Ok(prompt)
95 }
96}
97
98impl ContextPrompt {
99 #[must_use]
101 pub fn id(&self) -> &str {
102 &self.id
103 }
104
105 #[must_use]
107 pub fn render(&self) -> &str {
108 &self.rendered
109 }
110
111 #[must_use]
113 pub const fn rendered_tokens(&self) -> usize {
114 self.rendered_tokens
115 }
116
117 pub fn verify(
120 &self,
121 snapshot: &ContextSnapshot,
122 tokenizer: &impl TokenCounter,
123 ) -> Result<(), ContextError> {
124 if self.snapshot_id != snapshot.id() {
125 return Err(ContextError::BaseMismatch);
126 }
127 let expected = snapshot.prompt_view(self.max_tokens, tokenizer)?;
128 if self != &expected {
129 return Err(ContextError::Integrity);
130 }
131 Ok(())
132 }
133
134 pub fn resolve<'a>(
136 &'a self,
137 reference: &str,
138 snapshot: &ContextSnapshot,
139 tokenizer: &impl TokenCounter,
140 ) -> Result<&'a [Citation], ContextError> {
141 self.verify(snapshot, tokenizer)?;
142 self.citations
143 .get(reference)
144 .map(Vec::as_slice)
145 .ok_or(ContextError::InvalidInput)
146 }
147}