appam 0.1.1

High-throughput, traceable, reliable Rust agent framework for long-horizon AI sessions and easy extensibility
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
//! Conversion helpers between appam unified types and Vertex payloads.

use std::collections::HashMap;

use serde_json::json;

use super::types::{
    VertexContent, VertexFunctionCall, VertexFunctionDeclaration, VertexFunctionResponse,
    VertexPart, VertexTool,
};
use crate::llm::unified::{UnifiedContentBlock, UnifiedMessage, UnifiedRole, UnifiedTool};

/// Converted conversation payload split into system instruction and chat contents.
#[derive(Debug, Clone, Default)]
pub struct VertexConversation {
    /// Optional system instruction payload.
    pub system_instruction: Option<VertexContent>,
    /// User/model contents for `contents` field.
    pub contents: Vec<VertexContent>,
}

/// Convert unified messages into Vertex conversation content.
///
/// This conversion preserves tool-call IDs through an internal map and encodes
/// signature metadata as empty `Thinking` blocks so follow-up turns can
/// reconstruct `thoughtSignature` values required by Vertex.
pub fn from_unified_messages(messages: &[UnifiedMessage]) -> VertexConversation {
    let mut system_parts = Vec::new();
    let mut contents = Vec::new();
    let mut tool_name_by_call_id: HashMap<String, String> = HashMap::new();

    let mut message_index = 0usize;
    while message_index < messages.len() {
        let message = &messages[message_index];

        if message.role == UnifiedRole::System {
            for block in &message.content {
                if let UnifiedContentBlock::Text { text } = block {
                    if !text.trim().is_empty() {
                        system_parts.push(VertexPart {
                            text: Some(text.clone()),
                            ..Default::default()
                        });
                    }
                }
            }
            message_index += 1;
            continue;
        }

        if message_has_only_tool_results(message) {
            let mut parts = Vec::new();

            // Vertex requires the tool-result turn to contain a functionResponse
            // part for each functionCall part emitted by the immediately
            // preceding model turn, so we batch consecutive tool-result messages.
            while message_index < messages.len() {
                let candidate = &messages[message_index];
                if !message_has_only_tool_results(candidate) {
                    break;
                }

                for block in &candidate.content {
                    if let UnifiedContentBlock::ToolResult {
                        tool_use_id,
                        content,
                        ..
                    } = block
                    {
                        let name = tool_name_by_call_id
                            .get(tool_use_id)
                            .cloned()
                            .unwrap_or_else(|| "tool_result".to_string());

                        let response = if content.is_object() {
                            content.clone()
                        } else {
                            json!({ "result": content })
                        };

                        parts.push(VertexPart {
                            function_response: Some(VertexFunctionResponse { name, response }),
                            ..Default::default()
                        });
                    }
                }

                message_index += 1;
            }

            if !parts.is_empty() {
                contents.push(VertexContent {
                    role: Some("user".to_string()),
                    parts,
                });
            }

            continue;
        }

        let role = match message.role {
            UnifiedRole::User => "user",
            UnifiedRole::Assistant => "model",
            UnifiedRole::System => "user",
        };

        let mut parts = Vec::new();
        let mut idx = 0usize;
        while idx < message.content.len() {
            let block = &message.content[idx];
            let signature = message
                .content
                .get(idx + 1)
                .and_then(signature_metadata)
                .cloned();

            let mut consumed_signature = false;

            match block {
                UnifiedContentBlock::Text { text } => {
                    if !text.is_empty() {
                        parts.push(VertexPart {
                            text: Some(text.clone()),
                            thought_signature: signature,
                            ..Default::default()
                        });
                        consumed_signature = parts
                            .last()
                            .and_then(|p| p.thought_signature.as_ref())
                            .is_some();
                    }
                }
                UnifiedContentBlock::ToolUse { id, name, input } => {
                    tool_name_by_call_id.insert(id.clone(), name.clone());
                    parts.push(VertexPart {
                        function_call: Some(VertexFunctionCall {
                            name: Some(name.clone()),
                            args: Some(input.clone()),
                            ..Default::default()
                        }),
                        thought_signature: signature,
                        ..Default::default()
                    });
                    consumed_signature = parts
                        .last()
                        .and_then(|p| p.thought_signature.as_ref())
                        .is_some();
                }
                UnifiedContentBlock::ToolResult {
                    tool_use_id,
                    content,
                    ..
                } => {
                    let name = tool_name_by_call_id
                        .get(tool_use_id)
                        .cloned()
                        .unwrap_or_else(|| "tool_result".to_string());

                    let response = if content.is_object() {
                        content.clone()
                    } else {
                        json!({ "result": content })
                    };

                    parts.push(VertexPart {
                        function_response: Some(VertexFunctionResponse { name, response }),
                        ..Default::default()
                    });
                }
                UnifiedContentBlock::Thinking {
                    thinking,
                    signature,
                    ..
                } => {
                    if thinking.is_empty() && signature.is_some() {
                        // Signature-only metadata blocks are consumed by lookahead.
                    } else {
                        parts.push(VertexPart {
                            text: Some(thinking.clone()),
                            thought: Some(true),
                            thought_signature: signature.clone(),
                            ..Default::default()
                        });
                    }
                }
                _ => {}
            }

            idx += if consumed_signature { 2 } else { 1 };
        }

        if !parts.is_empty() {
            contents.push(VertexContent {
                role: Some(role.to_string()),
                parts,
            });
        }

        message_index += 1;
    }

    let system_instruction = if system_parts.is_empty() {
        None
    } else {
        Some(VertexContent {
            role: None,
            parts: system_parts,
        })
    };

    VertexConversation {
        system_instruction,
        contents,
    }
}

/// Convert unified tools into Vertex function declarations.
pub fn from_unified_tools(tools: &[UnifiedTool]) -> Vec<VertexTool> {
    if tools.is_empty() {
        return Vec::new();
    }

    let declarations: Vec<VertexFunctionDeclaration> = tools
        .iter()
        .map(|tool| VertexFunctionDeclaration {
            name: tool.name.clone(),
            description: Some(tool.description.clone()),
            parameters: extract_parameters_schema(&tool.parameters),
        })
        .collect();

    vec![VertexTool {
        function_declarations: declarations,
    }]
}

fn extract_parameters_schema(raw: &serde_json::Value) -> serde_json::Value {
    raw.as_object()
        .and_then(|obj| obj.get("parameters"))
        .cloned()
        .unwrap_or_else(|| raw.clone())
}

fn signature_metadata(block: &UnifiedContentBlock) -> Option<&String> {
    match block {
        UnifiedContentBlock::Thinking {
            thinking,
            signature: Some(signature),
            redacted,
            ..
        } if thinking.is_empty() && !redacted => Some(signature),
        _ => None,
    }
}

fn message_has_only_tool_results(message: &UnifiedMessage) -> bool {
    !message.content.is_empty()
        && message.role == UnifiedRole::User
        && message
            .content
            .iter()
            .all(|block| matches!(block, UnifiedContentBlock::ToolResult { .. }))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::llm::unified::{UnifiedMessage, UnifiedRole};

    #[test]
    fn test_from_unified_messages_preserves_tool_signature_metadata() {
        let messages = vec![UnifiedMessage {
            role: UnifiedRole::Assistant,
            content: vec![
                UnifiedContentBlock::ToolUse {
                    id: "call_1".to_string(),
                    name: "search_docs".to_string(),
                    input: serde_json::json!({"query": "vertex"}),
                },
                UnifiedContentBlock::Thinking {
                    thinking: String::new(),
                    signature: Some("sig-tool-1".to_string()),
                    encrypted_content: None,
                    redacted: false,
                },
            ],
            id: None,
            timestamp: None,
            reasoning: None,
            reasoning_details: None,
        }];

        let conversation = from_unified_messages(&messages);
        assert_eq!(conversation.contents.len(), 1);
        assert_eq!(conversation.contents[0].role.as_deref(), Some("model"));

        let part = &conversation.contents[0].parts[0];
        assert_eq!(
            part.function_call
                .as_ref()
                .and_then(|fc| fc.name.as_deref()),
            Some("search_docs")
        );
        assert_eq!(part.thought_signature.as_deref(), Some("sig-tool-1"));
    }

    #[test]
    fn test_from_unified_messages_maps_tool_result_to_function_response() {
        let messages = vec![
            UnifiedMessage {
                role: UnifiedRole::Assistant,
                content: vec![UnifiedContentBlock::ToolUse {
                    id: "call_1".to_string(),
                    name: "search_docs".to_string(),
                    input: serde_json::json!({"query": "vertex"}),
                }],
                id: None,
                timestamp: None,
                reasoning: None,
                reasoning_details: None,
            },
            UnifiedMessage {
                role: UnifiedRole::User,
                content: vec![UnifiedContentBlock::ToolResult {
                    tool_use_id: "call_1".to_string(),
                    content: serde_json::json!("ok"),
                    is_error: Some(false),
                }],
                id: None,
                timestamp: None,
                reasoning: None,
                reasoning_details: None,
            },
        ];

        let conversation = from_unified_messages(&messages);
        assert_eq!(conversation.contents.len(), 2);

        let response = conversation.contents[1].parts[0]
            .function_response
            .as_ref()
            .expect("expected functionResponse in user tool-result message");
        assert_eq!(response.name, "search_docs");
        assert_eq!(response.response, serde_json::json!({"result": "ok"}));
    }

    #[test]
    fn test_from_unified_messages_batches_consecutive_tool_results() {
        let messages = vec![
            UnifiedMessage {
                role: UnifiedRole::Assistant,
                content: vec![
                    UnifiedContentBlock::ToolUse {
                        id: "call_1".to_string(),
                        name: "mkdir".to_string(),
                        input: serde_json::json!({"path": "poem_generator"}),
                    },
                    UnifiedContentBlock::ToolUse {
                        id: "call_2".to_string(),
                        name: "write_file".to_string(),
                        input: serde_json::json!({"file_path": "poem_generator/generator.py"}),
                    },
                ],
                id: None,
                timestamp: None,
                reasoning: None,
                reasoning_details: None,
            },
            UnifiedMessage {
                role: UnifiedRole::User,
                content: vec![UnifiedContentBlock::ToolResult {
                    tool_use_id: "call_1".to_string(),
                    content: serde_json::json!({"success": true}),
                    is_error: Some(false),
                }],
                id: None,
                timestamp: None,
                reasoning: None,
                reasoning_details: None,
            },
            UnifiedMessage {
                role: UnifiedRole::User,
                content: vec![UnifiedContentBlock::ToolResult {
                    tool_use_id: "call_2".to_string(),
                    content: serde_json::json!({"success": true}),
                    is_error: Some(false),
                }],
                id: None,
                timestamp: None,
                reasoning: None,
                reasoning_details: None,
            },
        ];

        let conversation = from_unified_messages(&messages);
        assert_eq!(conversation.contents.len(), 2);
        assert_eq!(conversation.contents[1].role.as_deref(), Some("user"));
        assert_eq!(conversation.contents[1].parts.len(), 2);

        let first = conversation.contents[1].parts[0]
            .function_response
            .as_ref()
            .expect("expected first functionResponse");
        let second = conversation.contents[1].parts[1]
            .function_response
            .as_ref()
            .expect("expected second functionResponse");

        assert_eq!(first.name, "mkdir");
        assert_eq!(second.name, "write_file");
    }
}