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
//! Transport-neutral native compaction request and response contracts.
use crate::driver_registry::{LlmContentPart, LlmMessage, LlmMessageContent, LlmMessageRole};
use serde::{Deserialize, Serialize};
/// Request body for the Open Responses `/v1/responses/compact` endpoint.
#[derive(Debug, Clone, Serialize)]
pub struct CompactRequest {
/// Model used for compaction.
pub model: String,
/// Current conversation items to compact.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub input: Vec<CompactInputItem>,
/// Previous response identifier, as an alternative to a complete input.
#[serde(skip_serializing_if = "Option::is_none")]
pub previous_response_id: Option<String>,
/// Optional system instructions for this compaction request.
#[serde(skip_serializing_if = "Option::is_none")]
pub instructions: Option<String>,
}
/// Transport-neutral input item accepted by native conversation compaction.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum CompactInputItem {
/// User, assistant, or developer message.
#[serde(rename = "message")]
Message {
/// Protocol role name.
role: String,
/// Message content.
content: CompactContent,
},
/// Function call emitted by the assistant.
#[serde(rename = "function_call")]
FunctionCall {
/// Provider-visible call identifier.
call_id: String,
/// Function name.
name: String,
/// JSON-encoded arguments.
arguments: String,
},
/// Output corresponding to a function call.
#[serde(rename = "function_call_output")]
FunctionCallOutput {
/// Provider-visible call identifier.
call_id: String,
/// String-encoded function output.
output: String,
},
/// Opaque output from an earlier compaction pass.
#[serde(rename = "compaction")]
Compaction {
/// Provider-produced encrypted latent context.
encrypted_content: String,
},
}
impl From<&CompactOutputItem> for CompactInputItem {
fn from(item: &CompactOutputItem) -> Self {
match item {
CompactOutputItem::Message { role, content } => Self::Message {
role: role.clone(),
content: content.clone(),
},
CompactOutputItem::Compaction { encrypted_content } => Self::Compaction {
encrypted_content: encrypted_content.clone(),
},
}
}
}
/// Text or multipart content carried by a compact message.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CompactContent {
/// Plain text content.
Text(String),
/// Ordered text and image parts.
Parts(Vec<CompactContentPart>),
}
/// One multipart content item in a compact message.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum CompactContentPart {
/// Text input.
#[serde(rename = "input_text")]
InputText {
/// Text value.
text: String,
},
/// Image input.
#[serde(rename = "input_image")]
InputImage {
/// Image URL or data URL.
image_url: String,
},
}
/// Decoded response from native conversation compaction.
#[derive(Debug, Clone, Deserialize)]
pub struct CompactResponse {
/// Ordered compacted output items.
pub output: Vec<CompactOutputItem>,
/// Optional provider token and cost accounting.
pub usage: Option<CompactUsage>,
}
/// Output item returned by native conversation compaction.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum CompactOutputItem {
/// User message preserved verbatim.
#[serde(rename = "message")]
Message {
/// Protocol role name.
role: String,
/// Message content.
content: CompactContent,
},
/// Opaque replacement for earlier assistant/tool context.
#[serde(rename = "compaction")]
Compaction {
/// Provider-produced encrypted latent context.
encrypted_content: String,
},
}
/// Provider-reported accounting for one compact request.
#[derive(Debug, Clone, Deserialize)]
pub struct CompactUsage {
/// Input tokens processed.
pub input_tokens: Option<u32>,
/// Output tokens produced.
pub output_tokens: Option<u32>,
/// Total tokens billed.
pub total_tokens: Option<u32>,
/// Authoritative provider-reported per-request cost in USD, when supplied.
#[serde(default)]
pub cost: Option<f64>,
}
impl CompactInputItem {
/// Convert one provider-neutral message to its ordered compact input items.
///
/// Assistant tool calls expand to function-call items and tool messages
/// become function-call outputs.
pub fn from_llm_message(msg: &LlmMessage) -> Vec<Self> {
let mut items = Vec::new();
let role = match msg.role {
LlmMessageRole::System => "developer",
LlmMessageRole::User => "user",
LlmMessageRole::Assistant => "assistant",
LlmMessageRole::Tool => "tool",
};
if msg.role == LlmMessageRole::Tool
&& let Some(tool_call_id) = &msg.tool_call_id
{
let output = match &msg.content {
LlmMessageContent::Text(text) => text.clone(),
LlmMessageContent::Parts(parts) => parts
.iter()
.filter_map(|part| match part {
LlmContentPart::Text { text } => Some(text.clone()),
_ => None,
})
.collect::<Vec<_>>()
.join(""),
};
items.push(Self::FunctionCallOutput {
call_id: tool_call_id.clone(),
output,
});
return items;
}
let content = Self::content_from_llm_message(msg);
let has_content = match &content {
CompactContent::Text(text) => !text.is_empty(),
CompactContent::Parts(parts) => !parts.is_empty(),
};
if has_content || msg.tool_calls.is_none() {
items.push(Self::Message {
role: role.to_string(),
content,
});
}
if msg.role == LlmMessageRole::Assistant
&& let Some(tool_calls) = &msg.tool_calls
{
items.extend(tool_calls.iter().map(|call| Self::FunctionCall {
call_id: call.id.clone(),
name: call.name.clone(),
arguments: call.arguments.to_string(),
}));
}
items
}
fn content_from_llm_message(msg: &LlmMessage) -> CompactContent {
match &msg.content {
LlmMessageContent::Text(text) => CompactContent::Text(text.clone()),
LlmMessageContent::Parts(parts) => {
let compact_parts = parts
.iter()
.filter_map(|part| match part {
LlmContentPart::Text { text } => {
Some(CompactContentPart::InputText { text: text.clone() })
}
LlmContentPart::Image { url } => Some(CompactContentPart::InputImage {
image_url: url.clone(),
}),
LlmContentPart::Audio { .. } => None,
})
.collect::<Vec<_>>();
if compact_parts.len() == 1
&& let CompactContentPart::InputText { text } = &compact_parts[0]
{
return CompactContent::Text(text.clone());
}
CompactContent::Parts(compact_parts)
}
}
}
}
/// Convert provider-neutral messages into ordered native compact input items.
pub fn messages_to_compact_input(messages: &[LlmMessage]) -> Vec<CompactInputItem> {
messages
.iter()
.flat_map(CompactInputItem::from_llm_message)
.collect()
}