aether-llm 0.1.9

Multi-provider LLM abstraction layer for the Aether AI agent framework
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
use super::types::{ContentBlockDeltaData, ContentBlockStartData, StreamEvent};
use crate::{LlmError, LlmResponse, Result, StopReason, ToolCallRequest};
use async_stream;
use futures::Stream;
use std::collections::HashMap;
use tokio_stream::StreamExt;
use tracing::{debug, warn};

pub fn process_anthropic_stream<T: Stream<Item = Result<String>> + Send + Sync + Unpin>(
    stream: T,
) -> impl Stream<Item = Result<LlmResponse>> + Send {
    async_stream::stream! {
        let message_id = uuid::Uuid::new_v4().to_string();
        yield Ok(LlmResponse::Start { message_id });

        let mut active_tool_calls: HashMap<String, (String, String)> = HashMap::new();
        let mut index_to_id: HashMap<u32, String> = HashMap::new();
        let mut stream = Box::pin(stream);
        let mut last_stop_reason: Option<StopReason> = None;

        while let Some(result) = stream.next().await {
            match result {
                Ok(line) => {
                    let event: StreamEvent = match serde_json::from_str(&line) {
                        Ok(event) => event,
                        Err(e) => {
                            debug!("Failed to parse SSE line: {} - Error: {}", line, e);
                            continue;
                        }
                    };

                    match process_stream_event(event, &mut active_tool_calls, &mut index_to_id) {
                        Ok((response, stop_reason)) => {
                            if let Some(stop_reason) = stop_reason {
                                last_stop_reason = Some(stop_reason);
                            }
                            if let Some(response) = response {
                                yield Ok(response);
                            }
                        }
                        Err(e) => {
                            yield Err(e);
                            break;
                        }
                    }
                }
                Err(e) => {
                    yield Err(e);
                    break;
                }
            }
        }

        for (id, (name, arguments)) in active_tool_calls {
            let tool_call = ToolCallRequest { id, name, arguments };
            yield Ok(LlmResponse::ToolRequestComplete { tool_call });
        }

        yield Ok(LlmResponse::Done {
            stop_reason: last_stop_reason,
        });
    }
}

fn process_stream_event(
    event: StreamEvent,
    active_tool_calls: &mut HashMap<String, (String, String)>,
    index_to_id: &mut HashMap<u32, String>,
) -> Result<(Option<LlmResponse>, Option<StopReason>)> {
    use StreamEvent::{
        ContentBlockDelta, ContentBlockStart, ContentBlockStop, Error, MessageDelta, MessageStart, MessageStop, Ping,
    };
    match event {
        MessageStart { .. } => Ok(handle_message_start()),
        ContentBlockStart { data } => Ok(handle_content_block_start(data, active_tool_calls, index_to_id)),
        ContentBlockDelta { data } => Ok(handle_content_block_delta(data, active_tool_calls, index_to_id)),
        ContentBlockStop { data } => Ok(handle_content_block_stop(&data, active_tool_calls, index_to_id)),
        MessageDelta { data } => Ok(handle_message_delta(&data)),
        MessageStop { .. } => Ok(handle_message_stop()),
        Error { data } => {
            Err(LlmError::ApiError(format!("Anthropic API error: {} - {}", data.error.error_type, data.error.message,)))
        }
        Ping => Ok(handle_ping()),
    }
}

fn map_anthropic_stop_reason(reason: &str) -> StopReason {
    match reason {
        "end_turn" | "stop_sequence" => StopReason::EndTurn,
        "tool_use" => StopReason::ToolCalls,
        "max_tokens" => StopReason::Length,
        _ => StopReason::Unknown(reason.to_string()),
    }
}

type EventResult = (Option<LlmResponse>, Option<StopReason>);

fn handle_message_start() -> EventResult {
    debug!("Message started");
    (None, None)
}

fn handle_content_block_start(
    start_data: super::types::ContentBlockStart,
    active_tool_calls: &mut HashMap<String, (String, String)>,
    index_to_id: &mut HashMap<u32, String>,
) -> EventResult {
    match start_data.content_block {
        ContentBlockStartData::Text { .. } => {
            debug!("Text block started at index {}", start_data.index);
            (None, None)
        }
        ContentBlockStartData::Thinking { .. } => {
            debug!("Thinking block started at index {}", start_data.index);
            (None, None)
        }
        ContentBlockStartData::ToolUse { id, name } => {
            debug!("Tool use started: {} ({})", name, id);
            index_to_id.insert(start_data.index, id.clone());
            active_tool_calls.insert(id.clone(), (name.clone(), String::new()));
            (Some(LlmResponse::ToolRequestStart { id, name }), None)
        }
    }
}

fn handle_content_block_delta(
    delta_data: super::types::ContentBlockDelta,
    active_tool_calls: &mut HashMap<String, (String, String)>,
    index_to_id: &HashMap<u32, String>,
) -> EventResult {
    match delta_data.delta {
        ContentBlockDeltaData::TextDelta { text } => {
            if text.is_empty() {
                (None, None)
            } else {
                (Some(LlmResponse::Text { chunk: text }), None)
            }
        }
        ContentBlockDeltaData::ThinkingDelta { thinking } => {
            if thinking.is_empty() {
                (None, None)
            } else {
                (Some(LlmResponse::Reasoning { chunk: thinking }), None)
            }
        }
        ContentBlockDeltaData::InputJsonDelta { partial_json } => {
            if let Some(id) = index_to_id.get(&delta_data.index) {
                if let Some((_name, arguments)) = active_tool_calls.get_mut(id) {
                    arguments.push_str(&partial_json);
                    (Some(LlmResponse::ToolRequestArg { id: id.clone(), chunk: partial_json }), None)
                } else {
                    warn!("Received tool input delta for unknown tool call id: {}", id);
                    (None, None)
                }
            } else {
                warn!("Received tool input delta for unknown tool call index: {}", delta_data.index);
                (None, None)
            }
        }
    }
}

fn handle_content_block_stop(
    stop_data: &super::types::ContentBlockStop,
    active_tool_calls: &mut HashMap<String, (String, String)>,
    index_to_id: &mut HashMap<u32, String>,
) -> EventResult {
    if let Some(id) = index_to_id.remove(&stop_data.index) {
        if let Some((name, arguments)) = active_tool_calls.remove(&id) {
            let tool_call = ToolCallRequest { id, name, arguments };
            (Some(LlmResponse::ToolRequestComplete { tool_call }), None)
        } else {
            debug!("Content block stopped but tool call not found for id: {}", id);
            (None, None)
        }
    } else {
        debug!("Content block stopped at index {}", stop_data.index);
        (None, None)
    }
}

fn handle_message_delta(message_delta: &super::types::MessageDelta) -> EventResult {
    debug!("Message delta received");
    let stop_reason = message_delta.delta.stop_reason.as_deref().map(map_anthropic_stop_reason);

    let response = message_delta.usage.as_ref().map(|usage| LlmResponse::Usage { tokens: usage.into() });
    (response, stop_reason)
}

fn handle_message_stop() -> EventResult {
    debug!("Message stopped");
    (None, None)
}

fn handle_ping() -> EventResult {
    debug!("Received ping event");
    (None, None)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::TokenUsage;
    use tokio_stream;

    #[tokio::test]
    async fn test_process_text_stream() {
        let lines = vec![
            "{\"type\": \"message_start\", \"message\": {\"id\": \"msg_123\", \"type\": \"message\", \"role\": \"assistant\", \"content\": [], \"model\": \"claude-3\", \"stop_reason\": null, \"stop_sequence\": null, \"usage\": {\"input_tokens\": 10, \"output_tokens\": 0}}}".to_string(),
            "{\"type\": \"content_block_start\", \"index\": 0, \"content_block\": {\"type\": \"text\", \"text\": \"\"}}".to_string(),
            "{\"type\": \"content_block_delta\", \"index\": 0, \"delta\": {\"type\": \"text_delta\", \"text\": \"Hello\"}}".to_string(),
            "{\"type\": \"content_block_delta\", \"index\": 0, \"delta\": {\"type\": \"text_delta\", \"text\": \" world\"}}".to_string(),
            "{\"type\": \"content_block_stop\", \"index\": 0}".to_string(),
            "{\"type\": \"message_delta\", \"delta\": {\"stop_reason\": \"end_turn\", \"stop_sequence\": null}, \"usage\": {\"input_tokens\": 10, \"output_tokens\": 25}}".to_string(),
            "{\"type\": \"message_stop\"}".to_string(),
        ];

        let stream = tokio_stream::iter(lines.into_iter().map(Ok));
        let mut response_stream = Box::pin(process_anthropic_stream(stream));

        let mut responses = Vec::new();
        while let Some(result) = response_stream.next().await {
            responses.push(result.unwrap());
        }

        assert!(matches!(responses[0], LlmResponse::Start { .. }));
        assert!(matches!(responses[1], LlmResponse::Text { ref chunk } if chunk == "Hello"));
        assert!(matches!(responses[2], LlmResponse::Text { ref chunk } if chunk == " world"));
        assert!(matches!(
            responses[3],
            LlmResponse::Usage { tokens: TokenUsage { input_tokens: 10, output_tokens: 25, .. } }
        ));
        assert!(matches!(responses[4], LlmResponse::Done { stop_reason: Some(StopReason::EndTurn) }));
    }

    #[tokio::test]
    async fn test_process_tool_use_stream() {
        let lines = vec![
            "{\"type\": \"message_start\", \"message\": {\"id\": \"msg_123\", \"type\": \"message\", \"role\": \"assistant\", \"content\": [], \"model\": \"claude-3\", \"stop_reason\": null, \"stop_sequence\": null, \"usage\": {\"input_tokens\": 10, \"output_tokens\": 0}}}".to_string(),
            "{\"type\": \"content_block_start\", \"index\": 0, \"content_block\": {\"type\": \"tool_use\", \"id\": \"tool_123\", \"name\": \"search\"}}".to_string(),
            "{\"type\": \"content_block_delta\", \"index\": 0, \"delta\": {\"type\": \"input_json_delta\", \"partial_json\": \"{\\\"query\\\":\\\"test\\\"}\"}".to_string(),
            "{\"type\": \"content_block_stop\", \"index\": 0}".to_string(),
            "{\"type\": \"message_delta\", \"delta\": {\"stop_reason\": \"tool_use\", \"stop_sequence\": null}, \"usage\": {\"input_tokens\": 10, \"output_tokens\": 15}}".to_string(),
            "{\"type\": \"message_stop\"}".to_string(),
        ];

        let stream = tokio_stream::iter(lines.into_iter().map(Ok));
        let mut response_stream = Box::pin(process_anthropic_stream(stream));

        let mut responses = Vec::new();
        while let Some(result) = response_stream.next().await {
            responses.push(result.unwrap());
        }

        assert!(matches!(responses[0], LlmResponse::Start { .. }));
        assert!(
            matches!(responses[1], LlmResponse::ToolRequestStart { ref id, ref name } if id == "tool_123" && name == "search")
        );
        assert!(
            matches!(responses[2], LlmResponse::ToolRequestComplete { ref tool_call } if tool_call.id == "tool_123" && tool_call.name == "search")
        );
        assert!(matches!(
            responses[3],
            LlmResponse::Usage { tokens: TokenUsage { input_tokens: 10, output_tokens: 15, .. } }
        ));
        assert!(matches!(responses[4], LlmResponse::Done { stop_reason: Some(StopReason::ToolCalls) }));
    }

    #[tokio::test]
    async fn test_multiple_tool_calls_with_same_index() {
        // This test demonstrates the issue with index-based tracking
        // If multiple tool calls happen to have the same index (which shouldn't happen
        // but could theoretically), the current implementation would overwrite them
        let lines = vec![
            r#"{"type": "message_start", "message": {"id": "msg_123", "type": "message", "role": "assistant", "content": [], "model": "claude-3", "stop_reason": null, "stop_sequence": null, "usage": {"input_tokens": 10, "output_tokens": 0}}}"#.to_string(),
            r#"{"type": "content_block_start", "index": 0, "content_block": {"type": "tool_use", "id": "tool_123", "name": "search"}}"#.to_string(),
            r#"{"type": "content_block_delta", "index": 0, "delta": {"type": "input_json_delta", "partial_json": "{\"query\":\"test1\"}"}}"#.to_string(),
            r#"{"type": "content_block_stop", "index": 0}"#.to_string(),
            // Another tool call with different ID but same index (simulating potential edge case)
            r#"{"type": "content_block_start", "index": 0, "content_block": {"type": "tool_use", "id": "tool_456", "name": "calculate"}}"#.to_string(),
            r#"{"type": "content_block_delta", "index": 0, "delta": {"type": "input_json_delta", "partial_json": "{\"expression\":\"2+2\"}"}}"#.to_string(),
            r#"{"type": "content_block_stop", "index": 0}"#.to_string(),
            r#"{"type": "message_stop"}"#.to_string(),
        ];

        let stream = tokio_stream::iter(lines.into_iter().map(Ok));
        let mut response_stream = Box::pin(process_anthropic_stream(stream));

        let mut responses = Vec::new();
        while let Some(result) = response_stream.next().await {
            responses.push(result.unwrap());
        }

        // We should get both tool calls, but with index-based tracking we might lose one
        let tool_starts: Vec<_> =
            responses.iter().filter(|r| matches!(r, LlmResponse::ToolRequestStart { .. })).collect();
        let tool_completes: Vec<_> =
            responses.iter().filter(|r| matches!(r, LlmResponse::ToolRequestComplete { .. })).collect();

        // With ID-based tracking, we should get both tool calls
        assert_eq!(tool_starts.len(), 2);
        assert_eq!(tool_completes.len(), 2);
    }

    #[tokio::test]
    async fn test_process_thinking_stream() {
        let lines = vec![
            r#"{"type": "message_start", "message": {"id": "msg_123", "type": "message", "role": "assistant", "content": [], "model": "claude-opus-4-6", "stop_reason": null, "stop_sequence": null, "usage": {"input_tokens": 10, "output_tokens": 0}}}"#.to_string(),
            r#"{"type": "content_block_start", "index": 0, "content_block": {"type": "thinking", "thinking": ""}}"#.to_string(),
            r#"{"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": "Let me think"}}"#.to_string(),
            r#"{"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": " about this"}}"#.to_string(),
            r#"{"type": "content_block_stop", "index": 0}"#.to_string(),
            r#"{"type": "content_block_start", "index": 1, "content_block": {"type": "text", "text": ""}}"#.to_string(),
            r#"{"type": "content_block_delta", "index": 1, "delta": {"type": "text_delta", "text": "Here is my answer"}}"#.to_string(),
            r#"{"type": "content_block_stop", "index": 1}"#.to_string(),
            r#"{"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence": null}, "usage": {"input_tokens": 10, "output_tokens": 50}}"#.to_string(),
            r#"{"type": "message_stop"}"#.to_string(),
        ];

        let stream = tokio_stream::iter(lines.into_iter().map(Ok));
        let mut response_stream = Box::pin(process_anthropic_stream(stream));

        let mut responses = Vec::new();
        while let Some(result) = response_stream.next().await {
            responses.push(result.unwrap());
        }

        assert!(matches!(responses[0], LlmResponse::Start { .. }));
        assert!(matches!(responses[1], LlmResponse::Reasoning { ref chunk } if chunk == "Let me think"));
        assert!(matches!(responses[2], LlmResponse::Reasoning { ref chunk } if chunk == " about this"));
        assert!(matches!(responses[3], LlmResponse::Text { ref chunk } if chunk == "Here is my answer"));
        assert!(matches!(
            responses[4],
            LlmResponse::Usage { tokens: TokenUsage { input_tokens: 10, output_tokens: 50, .. } }
        ));
        assert!(matches!(responses[5], LlmResponse::Done { stop_reason: Some(StopReason::EndTurn) }));
    }

    #[tokio::test]
    async fn test_message_delta_forwards_both_cache_read_and_creation() {
        let lines = vec![
            r#"{"type": "message_start", "message": {"id": "msg_xyz", "type": "message", "role": "assistant", "content": [], "model": "claude-3", "stop_reason": null, "stop_sequence": null, "usage": {"input_tokens": 10, "output_tokens": 0}}}"#.to_string(),
            r#"{"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}"#.to_string(),
            r#"{"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "ok"}}"#.to_string(),
            r#"{"type": "content_block_stop", "index": 0}"#.to_string(),
            r#"{"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence": null}, "usage": {"input_tokens": 100, "output_tokens": 25, "cache_creation_input_tokens": 40, "cache_read_input_tokens": 60}}"#.to_string(),
            r#"{"type": "message_stop"}"#.to_string(),
        ];

        let stream = tokio_stream::iter(lines.into_iter().map(Ok));
        let mut response_stream = Box::pin(process_anthropic_stream(stream));

        let mut responses = Vec::new();
        while let Some(result) = response_stream.next().await {
            responses.push(result.unwrap());
        }

        let usage = responses.iter().find_map(|r| match r {
            LlmResponse::Usage { tokens } => Some(*tokens),
            _ => None,
        });

        assert_eq!(
            usage,
            Some(TokenUsage {
                input_tokens: 100,
                output_tokens: 25,
                cache_read_tokens: Some(60),
                cache_creation_tokens: Some(40),
                ..TokenUsage::default()
            })
        );
    }

    #[tokio::test]
    async fn test_anthropic_stream_event_enum_deserialization() {
        use super::super::types::StreamEvent;

        // Test message_start deserialization
        let message_start_json = r#"{"type": "message_start", "message": {"id": "msg_123", "type": "message", "role": "assistant", "content": [], "model": "claude-3", "stop_reason": null, "stop_sequence": null, "usage": {"input_tokens": 10, "output_tokens": 0}}}"#;
        let event: StreamEvent = serde_json::from_str(message_start_json).unwrap();
        assert!(matches!(event, StreamEvent::MessageStart { .. }));

        // Test content_block_start deserialization
        let content_block_start_json =
            r#"{"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}"#;
        let event: StreamEvent = serde_json::from_str(content_block_start_json).unwrap();
        assert!(matches!(event, StreamEvent::ContentBlockStart { .. }));

        // Test content_block_delta deserialization
        let content_block_delta_json =
            r#"{"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Hello"}}"#;
        let event: StreamEvent = serde_json::from_str(content_block_delta_json).unwrap();
        assert!(matches!(event, StreamEvent::ContentBlockDelta { .. }));

        // Test ping deserialization
        let ping_json = r#"{"type": "ping"}"#;
        let event: StreamEvent = serde_json::from_str(ping_json).unwrap();
        assert!(matches!(event, StreamEvent::Ping));

        // Test error deserialization
        let error_json =
            r#"{"type": "error", "error": {"type": "rate_limit_error", "message": "Rate limit exceeded"}}"#;
        let event: StreamEvent = serde_json::from_str(error_json).unwrap();
        assert!(matches!(event, StreamEvent::Error { .. }));
    }
}