aethershell 0.3.1

The world's first multi-agent shell with typed functional pipelines and multi-modal AI
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
//! Anthropic Claude Provider Implementation
//!
//! Native implementation for Anthropic's Claude API with full support for:
//! - Messages API with system prompts
//! - Tool use (function calling)
//! - Vision (images)
//! - Extended thinking

use async_trait::async_trait;
use futures::Stream;
use reqwest::Client;
use serde_json::{json, Value as JsonValue};
use std::pin::Pin;

use crate::providers::{
    ChatRequest, ChatResponse, ContentPart, EmbeddingRequest, EmbeddingResponse, LLMProvider,
    Message, ModelInfo, ModelUri, ProviderConfig, ProviderError, ProviderType, StreamChunk,
    ToolCall, ToolSchema, Usage,
};

const ANTHROPIC_API_VERSION: &str = "2023-06-01";

/// Anthropic Claude API provider
pub struct AnthropicProvider {
    config: ProviderConfig,
    client: Client,
}

impl AnthropicProvider {
    pub fn new(config: ProviderConfig) -> Self {
        Self {
            config,
            client: Client::new(),
        }
    }

    fn base_url(&self) -> String {
        self.config
            .base_url
            .clone()
            .unwrap_or_else(|| "https://api.anthropic.com/v1".to_string())
    }

    fn api_key(&self) -> Option<&str> {
        self.config.api_key.as_deref()
    }

    /// Convert messages to Anthropic format, extracting system message
    fn build_request(&self, messages: &[Message]) -> (Option<String>, Vec<JsonValue>) {
        let mut system = None;
        let mut anthropic_messages = Vec::new();

        for msg in messages {
            if msg.role == "system" {
                system = Some(msg.text());
                continue;
            }

            let content = if msg.content.len() == 1 {
                match &msg.content[0] {
                    ContentPart::Text { text } => json!(text),
                    ContentPart::Image {
                        data, media_type, ..
                    } => {
                        if let (Some(data), Some(mt)) = (data, media_type) {
                            json!([{
                                "type": "image",
                                "source": {
                                    "type": "base64",
                                    "media_type": mt,
                                    "data": data
                                }
                            }])
                        } else {
                            json!(msg.text())
                        }
                    }
                    _ => json!(msg.text()),
                }
            } else {
                json!(msg
                    .content
                    .iter()
                    .map(|part| {
                        match part {
                            ContentPart::Text { text } => json!({"type": "text", "text": text}),
                            ContentPart::Image {
                                data, media_type, ..
                            } => {
                                if let (Some(d), Some(mt)) = (data, media_type) {
                                    json!({
                                        "type": "image",
                                        "source": {
                                            "type": "base64",
                                            "media_type": mt,
                                            "data": d
                                        }
                                    })
                                } else {
                                    json!({"type": "text", "text": ""})
                                }
                            }
                            _ => json!({"type": "text", "text": ""}),
                        }
                    })
                    .collect::<Vec<_>>())
            };

            // Map roles
            let role = match msg.role.as_str() {
                "assistant" => "assistant",
                "tool" => "user", // Tool results go as user messages
                _ => "user",
            };

            // Handle tool results
            if msg.role == "tool" {
                if let Some(ref tool_call_id) = msg.tool_call_id {
                    anthropic_messages.push(json!({
                        "role": "user",
                        "content": [{
                            "type": "tool_result",
                            "tool_use_id": tool_call_id,
                            "content": msg.text()
                        }]
                    }));
                    continue;
                }
            }

            // Handle assistant messages with tool calls
            if msg.role == "assistant" {
                if let Some(ref tool_calls) = msg.tool_calls {
                    let mut content_blocks: Vec<JsonValue> = Vec::new();

                    if let Some(text) = msg.content.first() {
                        if let ContentPart::Text { text } = text {
                            if !text.is_empty() {
                                content_blocks.push(json!({"type": "text", "text": text}));
                            }
                        }
                    }

                    for tc in tool_calls {
                        content_blocks.push(json!({
                            "type": "tool_use",
                            "id": tc.id,
                            "name": tc.name,
                            "input": serde_json::from_str::<JsonValue>(&tc.arguments)
                                .unwrap_or(json!({}))
                        }));
                    }

                    anthropic_messages.push(json!({
                        "role": "assistant",
                        "content": content_blocks
                    }));
                    continue;
                }
            }

            anthropic_messages.push(json!({
                "role": role,
                "content": content,
            }));
        }

        (system, anthropic_messages)
    }

    fn build_tools(&self, tools: &[ToolSchema]) -> Vec<JsonValue> {
        tools
            .iter()
            .map(|tool| {
                json!({
                    "name": tool.name,
                    "description": tool.description,
                    "input_schema": tool.parameters
                })
            })
            .collect()
    }

    fn parse_tool_use(&self, content: &JsonValue) -> Vec<ToolCall> {
        content
            .as_array()
            .map(|arr| {
                arr.iter()
                    .filter_map(|block| {
                        if block["type"] == "tool_use" {
                            Some(ToolCall {
                                id: block["id"].as_str()?.to_string(),
                                name: block["name"].as_str()?.to_string(),
                                arguments: block["input"].to_string(),
                            })
                        } else {
                            None
                        }
                    })
                    .collect()
            })
            .unwrap_or_default()
    }

    fn extract_text(&self, content: &JsonValue) -> Option<String> {
        content
            .as_array()
            .map(|arr| {
                arr.iter()
                    .filter_map(|block| {
                        if block["type"] == "text" {
                            block["text"].as_str().map(|s| s.to_string())
                        } else {
                            None
                        }
                    })
                    .collect::<Vec<_>>()
                    .join("")
            })
            .filter(|s| !s.is_empty())
    }
}

#[async_trait]
impl LLMProvider for AnthropicProvider {
    fn name(&self) -> &str {
        "Anthropic"
    }

    fn config(&self) -> &ProviderConfig {
        &self.config
    }

    async fn chat(&self, request: ChatRequest) -> Result<ChatResponse, ProviderError> {
        let url = format!("{}/messages", self.base_url());
        let (system, messages) = self.build_request(&request.messages);

        let mut body = json!({
            "model": request.model.model,
            "messages": messages,
            "max_tokens": request.max_tokens.unwrap_or(4096),
        });

        if let Some(sys) = system {
            body["system"] = json!(sys);
        }
        if let Some(temp) = request.temperature {
            body["temperature"] = json!(temp);
        }
        if let Some(ref stop) = request.stop {
            body["stop_sequences"] = json!(stop);
        }
        if !request.tools.is_empty() {
            body["tools"] = json!(self.build_tools(&request.tools));
        }

        let api_key = self
            .api_key()
            .ok_or_else(|| ProviderError::Authentication {
                message: "Missing API key".to_string(),
            })?;

        let response = self
            .client
            .post(&url)
            .header("Content-Type", "application/json")
            .header("x-api-key", api_key)
            .header("anthropic-version", ANTHROPIC_API_VERSION)
            .json(&body)
            .send()
            .await
            .map_err(|e| ProviderError::Network {
                message: e.to_string(),
            })?;

        if !response.status().is_success() {
            let status = response.status().as_u16();
            let text = response.text().await.unwrap_or_default();

            return Err(match status {
                401 => ProviderError::Authentication { message: text },
                429 => ProviderError::RateLimit { retry_after: None },
                _ => ProviderError::Api {
                    status,
                    message: text,
                },
            });
        }

        let json: JsonValue = response.json().await.map_err(|e| ProviderError::Unknown {
            message: e.to_string(),
        })?;

        self.parse_response(&json)
    }

    async fn chat_stream(
        &self,
        _request: ChatRequest,
    ) -> Result<Pin<Box<dyn Stream<Item = Result<StreamChunk, ProviderError>> + Send>>, ProviderError>
    {
        Err(ProviderError::Unsupported {
            feature: "streaming".to_string(),
        })
    }

    async fn embed(&self, _request: EmbeddingRequest) -> Result<EmbeddingResponse, ProviderError> {
        // Anthropic doesn't have a native embedding API
        Err(ProviderError::Unsupported {
            feature: "embeddings".to_string(),
        })
    }

    async fn list_models(&self) -> Result<Vec<ModelInfo>, ProviderError> {
        // Anthropic doesn't have a model listing endpoint
        Ok(vec![
            ModelInfo {
                id: "claude-3-5-sonnet-20241022".to_string(),
                name: "Claude 3.5 Sonnet".to_string(),
                provider: ProviderType::Anthropic,
                context_window: Some(200_000),
                max_output: Some(8192),
                supports_tools: Some(true),
                supports_vision: Some(true),
                supports_streaming: Some(true),
            },
            ModelInfo {
                id: "claude-3-opus-20240229".to_string(),
                name: "Claude 3 Opus".to_string(),
                provider: ProviderType::Anthropic,
                context_window: Some(200_000),
                max_output: Some(4096),
                supports_tools: Some(true),
                supports_vision: Some(true),
                supports_streaming: Some(true),
            },
            ModelInfo {
                id: "claude-3-5-haiku-20241022".to_string(),
                name: "Claude 3.5 Haiku".to_string(),
                provider: ProviderType::Anthropic,
                context_window: Some(200_000),
                max_output: Some(8192),
                supports_tools: Some(true),
                supports_vision: Some(true),
                supports_streaming: Some(true),
            },
        ])
    }

    fn format_tools(&self, tools: &[ToolSchema]) -> JsonValue {
        json!(self.build_tools(tools))
    }

    fn parse_response(&self, response: &JsonValue) -> Result<ChatResponse, ProviderError> {
        let content = &response["content"];
        let text = self.extract_text(content);
        let tool_calls = {
            let calls = self.parse_tool_use(content);
            if calls.is_empty() {
                None
            } else {
                Some(calls)
            }
        };

        let usage = response.get("usage").map(|u| Usage {
            prompt_tokens: u["input_tokens"].as_u64().unwrap_or(0) as u32,
            completion_tokens: u["output_tokens"].as_u64().unwrap_or(0) as u32,
            total_tokens: (u["input_tokens"].as_u64().unwrap_or(0)
                + u["output_tokens"].as_u64().unwrap_or(0)) as u32,
        });

        Ok(ChatResponse {
            id: response["id"].as_str().unwrap_or("").to_string(),
            model: response["model"].as_str().unwrap_or("").to_string(),
            content: text,
            tool_calls,
            finish_reason: response["stop_reason"].as_str().map(|s| s.to_string()),
            usage,
        })
    }
}

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

    #[test]
    fn test_anthropic_provider_creation() {
        let config = ProviderConfig::new(ProviderType::Anthropic).with_api_key("test-key");
        let provider = AnthropicProvider::new(config);
        assert_eq!(provider.name(), "Anthropic");
    }

    #[test]
    fn test_system_extraction() {
        let config = ProviderConfig::new(ProviderType::Anthropic);
        let provider = AnthropicProvider::new(config);

        let messages = vec![Message::system("You are helpful"), Message::user("Hello")];

        let (system, msgs) = provider.build_request(&messages);
        assert_eq!(system, Some("You are helpful".to_string()));
        assert_eq!(msgs.len(), 1); // Only user message
    }
}