llm-toolkit 0.63.1

A low-level, unopinionated Rust toolkit for the LLM last mile problem.
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
//! AnthropicApiAgent - Direct REST API implementation for Claude (Anthropic).
//!
//! This agent calls the Claude REST API directly without CLI dependency.
//! API key can be provided directly or loaded from environment variables.
//!
//! # Example
//!
//! ```rust,no_run
//! use llm_toolkit::agent::impls::AnthropicApiAgent;
//! use llm_toolkit::agent::Agent;
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // From environment variable (ANTHROPIC_API_KEY)
//! let agent = AnthropicApiAgent::try_from_env()?;
//! let response = agent.execute("Hello, world!".into()).await?;
//!
//! // Direct API key
//! let agent = AnthropicApiAgent::new("your-api-key", "claude-sonnet-4-6");
//!
//! // With options
//! let agent = AnthropicApiAgent::new("your-api-key", "claude-sonnet-4-6")
//!     .with_system("You are a helpful assistant")
//!     .with_max_tokens(4096);
//! # Ok(())
//! # }
//! ```

use crate::agent::{Agent, AgentError, Payload};
use crate::attachment::Attachment;
use crate::models::ClaudeModel;
use async_trait::async_trait;
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use reqwest::{Client, StatusCode, header::HeaderValue};
use serde::{Deserialize, Serialize};
use std::env;
use std::time::Duration;
const BASE_URL: &str = "https://api.anthropic.com/v1/messages";
const ANTHROPIC_VERSION: &str = "2023-06-01";

/// Agent implementation that talks to the Claude (Anthropic) HTTP API.
#[derive(Clone)]
pub struct AnthropicApiAgent {
    client: Client,
    api_key: String,
    model: String,
    system: Option<String>,
    max_tokens: u32,
}

impl AnthropicApiAgent {
    /// Creates a new agent with the provided API key and model.
    pub fn new(api_key: impl Into<String>, model: impl Into<String>) -> Self {
        Self {
            client: Client::new(),
            api_key: api_key.into(),
            model: model.into(),
            system: None,
            max_tokens: 4096,
        }
    }

    /// Loads configuration from environment variables.
    ///
    /// Environment variables:
    /// - `ANTHROPIC_API_KEY` (required)
    /// - `ANTHROPIC_MODEL` (optional, defaults to Claude Sonnet 4.6)
    pub fn try_from_env() -> Result<Self, AgentError> {
        let api_key = env::var("ANTHROPIC_API_KEY").map_err(|_| {
            AgentError::ExecutionFailed(
                "ANTHROPIC_API_KEY environment variable not set".to_string(),
            )
        })?;

        let model = env::var("ANTHROPIC_MODEL")
            .map(|s| {
                s.parse::<ClaudeModel>()
                    .unwrap_or_default()
                    .as_api_id()
                    .to_string()
            })
            .unwrap_or_else(|_| ClaudeModel::default().as_api_id().to_string());

        Ok(Self::new(api_key, model))
    }

    /// Overrides the model after construction using a string.
    pub fn with_model(mut self, model: impl Into<String>) -> Self {
        self.model = model.into();
        self
    }

    /// Overrides the model using a typed [`ClaudeModel`].
    pub fn with_claude_model(mut self, model: ClaudeModel) -> Self {
        self.model = model.as_api_id().to_string();
        self
    }

    /// Adds a system prompt that will be sent alongside every request.
    pub fn with_system(mut self, system: impl Into<String>) -> Self {
        self.system = Some(system.into());
        self
    }

    /// Sets the maximum number of tokens to generate.
    pub fn with_max_tokens(mut self, max_tokens: u32) -> Self {
        self.max_tokens = max_tokens;
        self
    }

    async fn build_content(&self, payload: &Payload) -> Result<Vec<ContentBlock>, AgentError> {
        let mut content_blocks = Vec::new();

        let text = payload.to_text();
        if !text.trim().is_empty() {
            content_blocks.push(ContentBlock::Text { text });
        }

        for attachment in payload.attachments() {
            if let Some(block) = Self::attachment_to_content_block(attachment).await? {
                content_blocks.push(block);
            }
        }

        if content_blocks.is_empty() {
            return Err(AgentError::ExecutionFailed(
                "Claude payload must include text or supported attachments".into(),
            ));
        }

        Ok(content_blocks)
    }

    async fn attachment_to_content_block(
        attachment: &Attachment,
    ) -> Result<Option<ContentBlock>, AgentError> {
        if let Attachment::Remote(_) = attachment {
            return Err(AgentError::ExecutionFailed(
                "Remote attachments are not supported for Claude API".into(),
            ));
        }

        let bytes = attachment.load_bytes().await.map_err(|err| {
            AgentError::ExecutionFailed(format!("Failed to load attachment for Claude API: {err}"))
        })?;

        let media_type = attachment
            .mime_type()
            .unwrap_or_else(|| "application/octet-stream".to_string());

        let data = BASE64_STANDARD.encode(bytes);

        Ok(Some(ContentBlock::Image {
            source: ImageSource {
                r#type: "base64".to_string(),
                media_type,
                data,
            },
        }))
    }

    async fn send_request(&self, body: &CreateMessageRequest) -> Result<String, AgentError> {
        let response = self
            .client
            .post(BASE_URL)
            .header("x-api-key", &self.api_key)
            .header("anthropic-version", ANTHROPIC_VERSION)
            .header("content-type", "application/json")
            .json(body)
            .send()
            .await
            .map_err(|err| AgentError::ProcessError {
                status_code: None,
                message: format!("Claude API request failed: {err}"),
                is_retryable: err.is_connect() || err.is_timeout(),
                retry_after: None,
            })?;

        if !response.status().is_success() {
            let status = response.status();
            let retry_after = parse_retry_after(response.headers().get("retry-after"));
            let body_text = response
                .text()
                .await
                .unwrap_or_else(|_| "Failed to read Claude error body".to_string());
            return Err(map_http_error(status, body_text, retry_after));
        }

        let parsed: CreateMessageResponse = response
            .json()
            .await
            .map_err(|err| AgentError::Other(format!("Failed to parse Claude response: {err}")))?;

        extract_text_response(parsed)
    }
}

#[async_trait]
impl Agent for AnthropicApiAgent {
    type Output = String;
    type Expertise = &'static str;

    fn expertise(&self) -> &Self::Expertise {
        &"Claude API agent for advanced reasoning and coding tasks"
    }

    async fn execute(&self, payload: Payload) -> Result<Self::Output, AgentError> {
        let content = self.build_content(&payload).await?;

        let messages = vec![Message {
            role: "user".to_string(),
            content,
        }];

        let request = CreateMessageRequest {
            model: self.model.clone(),
            messages,
            max_tokens: self.max_tokens,
            system: self.system.clone(),
        };

        self.send_request(&request).await
    }
}

#[derive(Serialize)]
struct CreateMessageRequest {
    model: String,
    messages: Vec<Message>,
    max_tokens: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    system: Option<String>,
}

#[derive(Serialize)]
struct Message {
    role: String,
    content: Vec<ContentBlock>,
}

enum ContentBlock {
    Text { text: String },
    Image { source: ImageSource },
}

impl Serialize for ContentBlock {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::SerializeMap;

        let mut map = serializer.serialize_map(None)?;

        match self {
            ContentBlock::Text { text } => {
                map.serialize_entry("type", "text")?;
                map.serialize_entry("text", text)?;
            }
            ContentBlock::Image { source } => {
                map.serialize_entry("type", "image")?;
                map.serialize_entry("source", source)?;
            }
        }

        map.end()
    }
}

#[derive(Serialize)]
struct ImageSource {
    r#type: String,
    media_type: String,
    data: String,
}

#[derive(Deserialize)]
struct CreateMessageResponse {
    content: Vec<ContentBlockResponse>,
}

#[derive(Deserialize)]
#[serde(tag = "type")]
enum ContentBlockResponse {
    #[serde(rename = "text")]
    Text { text: String },
}

#[derive(Deserialize)]
struct ErrorResponse {
    error: ErrorBody,
}

#[derive(Deserialize)]
struct ErrorBody {
    #[allow(dead_code)]
    r#type: String,
    message: String,
}

fn extract_text_response(response: CreateMessageResponse) -> Result<String, AgentError> {
    response
        .content
        .into_iter()
        .map(|block| match block {
            ContentBlockResponse::Text { text } => text,
        })
        .next()
        .ok_or_else(|| {
            AgentError::ExecutionFailed(
                "Claude API returned no text in the response content".into(),
            )
        })
}

fn map_http_error(status: StatusCode, body: String, retry_after: Option<Duration>) -> AgentError {
    let message = serde_json::from_str::<ErrorResponse>(&body)
        .map(|wrapper| wrapper.error.message)
        .unwrap_or_else(|_| body.clone());

    let is_retryable = matches!(
        status,
        StatusCode::TOO_MANY_REQUESTS
            | StatusCode::INTERNAL_SERVER_ERROR
            | StatusCode::BAD_GATEWAY
            | StatusCode::SERVICE_UNAVAILABLE
            | StatusCode::GATEWAY_TIMEOUT
    );

    if let Some(delay) = retry_after {
        AgentError::process_error_with_retry_after(status.as_u16(), message, is_retryable, delay)
    } else {
        AgentError::ProcessError {
            status_code: Some(status.as_u16()),
            message,
            is_retryable,
            retry_after: None,
        }
    }
}

fn parse_retry_after(header: Option<&HeaderValue>) -> Option<Duration> {
    let value = header?.to_str().ok()?;
    if let Ok(seconds) = value.parse::<u64>() {
        return Some(Duration::from_secs(seconds));
    }
    None
}

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

    #[test]
    fn test_anthropic_api_agent_creation() {
        let agent = AnthropicApiAgent::new("test-key", "claude-sonnet-4-6");
        assert_eq!(agent.model, "claude-sonnet-4-6");
        assert!(agent.system.is_none());
        assert_eq!(agent.max_tokens, 4096);
    }

    #[test]
    fn test_builder_methods() {
        let agent = AnthropicApiAgent::new("test-key", "claude-sonnet-4-6")
            .with_model("claude-opus-4-20250514")
            .with_system("You are a helpful assistant")
            .with_max_tokens(8192);

        assert_eq!(agent.model, "claude-opus-4-20250514");
        assert_eq!(
            agent.system,
            Some("You are a helpful assistant".to_string())
        );
        assert_eq!(agent.max_tokens, 8192);
    }

    #[test]
    fn test_request_serialization() {
        let request = CreateMessageRequest {
            model: "claude-sonnet-4-6".to_string(),
            messages: vec![Message {
                role: "user".to_string(),
                content: vec![ContentBlock::Text {
                    text: "Hello".to_string(),
                }],
            }],
            max_tokens: 4096,
            system: None,
        };

        let json = serde_json::to_string(&request).unwrap();
        assert!(json.contains("\"model\":\"claude-sonnet-4-6\""));
        assert!(json.contains("\"role\":\"user\""));
        assert!(json.contains("\"type\":\"text\""));
        assert!(json.contains("\"max_tokens\":4096"));
    }

    #[test]
    fn test_request_serialization_with_system() {
        let request = CreateMessageRequest {
            model: "claude-sonnet-4-6".to_string(),
            messages: vec![Message {
                role: "user".to_string(),
                content: vec![ContentBlock::Text {
                    text: "Hello".to_string(),
                }],
            }],
            max_tokens: 4096,
            system: Some("You are a helpful assistant".to_string()),
        };

        let json = serde_json::to_string(&request).unwrap();
        assert!(json.contains("\"system\":\"You are a helpful assistant\""));
    }

    #[test]
    fn test_request_serialization_with_image() {
        let request = CreateMessageRequest {
            model: "claude-sonnet-4-6".to_string(),
            messages: vec![Message {
                role: "user".to_string(),
                content: vec![
                    ContentBlock::Text {
                        text: "What's in this image?".to_string(),
                    },
                    ContentBlock::Image {
                        source: ImageSource {
                            r#type: "base64".to_string(),
                            media_type: "image/png".to_string(),
                            data: "base64encodeddata".to_string(),
                        },
                    },
                ],
            }],
            max_tokens: 4096,
            system: None,
        };

        let json = serde_json::to_string(&request).unwrap();
        assert!(json.contains("\"type\":\"image\""));
        assert!(json.contains("\"media_type\":\"image/png\""));
    }

    #[test]
    fn test_response_parsing() {
        let json = r#"{
            "content": [{
                "type": "text",
                "text": "Hello, world!"
            }]
        }"#;

        let response: CreateMessageResponse = serde_json::from_str(json).unwrap();
        let text = extract_text_response(response).unwrap();
        assert_eq!(text, "Hello, world!");
    }

    #[test]
    fn test_response_parsing_empty_content() {
        let json = r#"{"content": []}"#;
        let response: CreateMessageResponse = serde_json::from_str(json).unwrap();
        let result = extract_text_response(response);
        assert!(result.is_err());
    }

    #[test]
    fn test_error_parsing() {
        let json = r#"{
            "error": {
                "type": "authentication_error",
                "message": "Invalid API key"
            }
        }"#;

        let error = map_http_error(StatusCode::UNAUTHORIZED, json.to_string(), None);
        match error {
            AgentError::ProcessError { message, .. } => {
                assert!(message.contains("Invalid API key"));
            }
            _ => panic!("Expected ProcessError"),
        }
    }

    #[test]
    fn test_retryable_status_codes() {
        let retryable_statuses = [
            StatusCode::TOO_MANY_REQUESTS,
            StatusCode::INTERNAL_SERVER_ERROR,
            StatusCode::BAD_GATEWAY,
            StatusCode::SERVICE_UNAVAILABLE,
            StatusCode::GATEWAY_TIMEOUT,
        ];

        for status in retryable_statuses {
            let error = map_http_error(status, "error".to_string(), None);
            match error {
                AgentError::ProcessError { is_retryable, .. } => {
                    assert!(is_retryable, "Status {:?} should be retryable", status);
                }
                _ => panic!("Expected ProcessError"),
            }
        }
    }

    #[test]
    fn test_non_retryable_status_codes() {
        let non_retryable_statuses = [
            StatusCode::BAD_REQUEST,
            StatusCode::UNAUTHORIZED,
            StatusCode::FORBIDDEN,
            StatusCode::NOT_FOUND,
        ];

        for status in non_retryable_statuses {
            let error = map_http_error(status, "error".to_string(), None);
            match error {
                AgentError::ProcessError { is_retryable, .. } => {
                    assert!(!is_retryable, "Status {:?} should not be retryable", status);
                }
                _ => panic!("Expected ProcessError"),
            }
        }
    }

    #[test]
    fn test_try_from_env_missing_key() {
        // SAFETY: This test runs single-threaded (--test-threads=1)
        unsafe { std::env::remove_var("ANTHROPIC_API_KEY") };
        let result = AnthropicApiAgent::try_from_env();
        assert!(result.is_err());
    }
}