llmkit 0.1.3

Production-grade LLM client - 100+ providers, 11,000+ models. Pure Rust.
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
# Getting Started with LLMKit (Rust)

LLMKit is a unified LLM API client that provides a single interface to 100+ LLM providers and 11,000+ models including Anthropic, OpenAI, Azure, AWS Bedrock, Google Vertex AI, and many more.

## Installation

Add to your `Cargo.toml`:

```toml
[dependencies]
llmkit = { version = "0.1", features = ["anthropic", "openai"] }
tokio = { version = "1", features = ["full"] }
```

### Feature Flags

Select only the providers you need:

```toml
[dependencies]
# Minimal - just Anthropic
llmkit = { version = "0.1", features = ["anthropic"] }

# Common providers
llmkit = { version = "0.1", features = ["anthropic", "openai", "groq"] }

# All providers
llmkit = { version = "0.1", features = ["all-providers"] }
```

Available feature flags:
- `anthropic` - Anthropic Claude (default)
- `openai` - OpenAI GPT (default)
- `azure` - Azure OpenAI
- `bedrock` - AWS Bedrock
- `vertex` - Google Vertex AI
- `google` - Google AI (Gemini)
- `groq` - Groq
- `mistral` - Mistral AI
- `cohere` - Cohere
- `deepseek` - DeepSeek
- `openrouter` - OpenRouter
- `ollama` - Ollama (local)
- And 25+ more...
- `all-providers` - Enable all providers

## Quick Start

```rust
use llmkit::{LLMKitClient, Message, CompletionRequest};

#[tokio::main]
async fn main() -> llmkit::Result<()> {
    // Create client from environment variables
    let client = LLMKitClient::builder()
        .with_anthropic_from_env()
        .build()?;

    // Make a completion request
    let request = CompletionRequest::new(
        "claude-sonnet-4-20250514",
        vec![Message::user("What is the capital of France?")]
    );

    let response = client.complete(request).await?;
    println!("{}", response.text_content());

    Ok(())
}
```

## Environment Setup

Set one or more provider API keys:

```bash
# Core providers
export ANTHROPIC_API_KEY=sk-ant-...
export OPENAI_API_KEY=sk-...

# Cloud providers
export AZURE_OPENAI_API_KEY=...
export AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com
export AZURE_OPENAI_DEPLOYMENT=gpt-4
export AWS_REGION=us-east-1  # For Bedrock

# Fast inference
export GROQ_API_KEY=...
export MISTRAL_API_KEY=...
```

## Explicit Configuration

Configure providers explicitly:

```rust
use llmkit::LLMKitClient;

let client = LLMKitClient::builder()
    .with_anthropic("your-api-key")
    .with_openai("your-openai-key")
    .with_azure("your-azure-key", "endpoint", "deployment")
    .with_default_retry()
    .build()?;
```

## Streaming

Stream responses in real-time:

```rust
use futures::StreamExt;

let request = CompletionRequest::new(
    "claude-sonnet-4-20250514",
    vec![Message::user("Write a haiku about programming")]
).with_stream(true);

let mut stream = client.complete_stream(request).await?;

while let Some(result) = stream.next().await {
    let chunk = result?;
    if let Some(text) = chunk.text() {
        print!("{}", text);
    }
}
println!();
```

## Tool Calling (Function Calling)

Define and use tools:

```rust
use llmkit::{ToolDefinition, ContentBlock};
use serde_json::json;

// Define a tool
let weather_tool = ToolDefinition {
    name: "get_weather".to_string(),
    description: "Get current weather for a city".to_string(),
    input_schema: json!({
        "type": "object",
        "properties": {
            "city": {
                "type": "string",
                "description": "City name"
            },
            "unit": {
                "type": "string",
                "enum": ["celsius", "fahrenheit"]
            }
        },
        "required": ["city"]
    }),
};

// Make request with tools
let request = CompletionRequest::new(
    "claude-sonnet-4-20250514",
    vec![Message::user("What's the weather in Paris?")]
).with_tools(vec![weather_tool]);

let response = client.complete(request).await?;

// Check if the model wants to use a tool
if response.has_tool_use() {
    for content in &response.content {
        if let ContentBlock::ToolUse { id, name, input } = content {
            println!("Tool: {}", name);
            println!("Input: {}", input);

            // Execute the tool and send results back
            let tool_result = ContentBlock::ToolResult {
                tool_use_id: id.clone(),
                content: r#"{"temperature": 22, "unit": "celsius"}"#.to_string(),
                is_error: false,
            };

            // Continue the conversation
            let mut messages = vec![
                Message::user("What's the weather in Paris?"),
                Message::assistant_with_content(response.content.clone()),
                Message::user_with_content(vec![tool_result]),
            ];

            let final_response = client.complete(
                CompletionRequest::new("claude-sonnet-4-20250514", messages)
            ).await?;

            println!("{}", final_response.text_content());
        }
    }
}
```

## Structured Output

Get JSON responses with schema validation:

```rust
use serde::{Deserialize, Serialize};
use serde_json::json;

#[derive(Debug, Serialize, Deserialize)]
struct Person {
    name: String,
    age: u32,
    city: String,
}

let schema = json!({
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "age": {"type": "integer"},
        "city": {"type": "string"}
    },
    "required": ["name", "age", "city"]
});

let request = CompletionRequest::new(
    "claude-sonnet-4-20250514",
    vec![Message::user("Generate a fake person's info")]
).with_json_schema("person", schema);

let response = client.complete(request).await?;
let person: Person = serde_json::from_str(&response.text_content())?;
println!("{:?}", person);
```

## Extended Thinking

Enable reasoning mode for complex tasks:

```rust
let request = CompletionRequest::new(
    "claude-sonnet-4-20250514",
    vec![Message::user("Solve this puzzle: ...")]
).with_thinking(5000);  // 5000 token budget

let response = client.complete(request).await?;

// Get thinking content (reasoning process)
if let Some(thinking) = response.thinking_content() {
    println!("Thinking: {}", thinking);
}

println!("Answer: {}", response.text_content());
```

## Vision / Image Analysis

Analyze images:

```rust
use std::fs;
use base64::Engine;

// From file
let image_bytes = fs::read("image.png")?;
let image_data = base64::engine::general_purpose::STANDARD.encode(&image_bytes);

let message = Message::user_with_content(vec![
    ContentBlock::Text { text: "What's in this image?".to_string() },
    ContentBlock::Image {
        media_type: "image/png".to_string(),
        data: image_data,
    },
]);

let response = client.complete(
    CompletionRequest::new("claude-sonnet-4-20250514", vec![message])
).await?;

println!("{}", response.text_content());
```

## Error Handling

Handle errors gracefully:

```rust
use llmkit::error::Error;

match client.complete(request).await {
    Ok(response) => {
        println!("{}", response.text_content());
    }
    Err(Error::Authentication(msg)) => {
        eprintln!("Invalid API key: {}", msg);
    }
    Err(Error::RateLimit { retry_after, .. }) => {
        eprintln!("Rate limited. Retry after: {:?}", retry_after);
    }
    Err(Error::ContextLength { max, actual, .. }) => {
        eprintln!("Input too long: {} tokens (max: {})", actual, max);
    }
    Err(Error::InvalidRequest(msg)) => {
        eprintln!("Invalid request: {}", msg);
    }
    Err(Error::ProviderNotFound(provider)) => {
        eprintln!("Provider not configured: {}", provider);
    }
    Err(Error::Timeout) => {
        eprintln!("Request timed out");
    }
    Err(e) => {
        eprintln!("Error: {}", e);
    }
}
```

## Multiple Providers

Use different providers for different tasks:

```rust
// Configure multiple providers
let client = LLMKitClient::builder()
    .with_anthropic_from_env()
    .with_openai_from_env()
    .with_groq_from_env()
    .build()?;

// Use a specific provider by model prefix
let response = client.complete(
    CompletionRequest::new("gpt-4o", vec![Message::user("Hello!")])
).await?;

// Or explicitly
let response = client.complete_with_provider(
    "openai",
    CompletionRequest::new("gpt-4o", vec![Message::user("Hello!")])
).await?;
```

## Prompt Caching

Cache frequently used prompts (Anthropic):

```rust
let request = CompletionRequest::new(
    "claude-sonnet-4-20250514",
    vec![Message::user("Summarize this document: ...")]
)
.with_system("You are a document summarizer.")
.with_cache_control(CacheControl::Ephemeral);  // 5-minute cache

let response = client.complete(request).await?;

// Check cache usage
if let Some(usage) = &response.usage {
    println!("Cache creation: {:?}", usage.cache_creation_input_tokens);
    println!("Cache read: {:?}", usage.cache_read_input_tokens);
}
```

## Model Registry

Query available models:

```rust
use llmkit::model_registry::{
    get_model_info,
    get_all_models,
    get_models_by_provider,
    get_available_models,
    Provider,
};

// Get info about a specific model
if let Some(info) = get_model_info("claude-sonnet-4-20250514") {
    println!("Name: {}", info.name);
    println!("Price: ${}/1M input tokens", info.pricing.input_per_1m);
    println!("Max context: {}", info.capabilities.max_context);
    println!("Supports vision: {}", info.capabilities.vision);
}

// Get all Anthropic models
let anthropic_models = get_models_by_provider(Provider::Anthropic);
for model in anthropic_models {
    println!("{}: {}", model.name, model.description);
}

// Get available models (with configured API keys)
let available = get_available_models();
println!("{} models available", available.len());
```

## Async Runtime

LLMKit requires an async runtime. We recommend Tokio:

```rust
// Using tokio::main macro
#[tokio::main]
async fn main() -> llmkit::Result<()> {
    // Your code here
    Ok(())
}

// Or build a runtime manually
fn main() -> llmkit::Result<()> {
    let rt = tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()?;

    rt.block_on(async {
        // Your async code here
        Ok(())
    })
}
```

## Performance Tips

1. **Reuse clients**: Create one client and share it across requests
2. **Use feature flags**: Only enable providers you need
3. **Enable streaming**: For long responses, streaming reduces time-to-first-token
4. **Use prompt caching**: Cache system prompts to reduce costs and latency

```rust
use std::sync::Arc;

// Create a shared client
let client = Arc::new(LLMKitClient::builder()
    .with_anthropic_from_env()
    .build()?);

// Clone Arc for each task
let client_clone = client.clone();
tokio::spawn(async move {
    let response = client_clone.complete(request).await?;
    // ...
});
```

## Next Steps

- Check out the [examples]../examples/ for more complete code samples
- Run examples with `cargo run --example simple_completion`
- See the API docs with `cargo doc --open`