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
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
# Image Generation API

Generate images from text prompts using various providers including DALL-E, Stable Diffusion, and more.

## Quick Start

### Python

```python
from llmkit import LLMKitClient, ImageGenerationRequest, ImageSize

client = LLMKitClient.from_env()

# Generate an image
request = ImageGenerationRequest("dall-e-3", "A serene mountain landscape")
response = client.generate_image(request)

print(f"Generated {response.count} image(s)")
print(f"Image URL: {response.first().url}")
```

### TypeScript

```typescript
import { LLMKitClient, ImageGenerationRequest, ImageSize } from 'llmkit'

const client = LLMKitClient.fromEnv()

// Generate an image
const request = new ImageGenerationRequest('dall-e-3', 'A serene mountain landscape')
const response = await client.generateImage(request)

console.log(`Generated ${response.count} image(s)`)
console.log(`Image URL: ${response.first()?.url}`)
```

## Supported Models

### OpenAI (DALL-E)

| Model | ID | Max Images | Features |
|-------|----|----|----------|
| DALL-E 3 | `dall-e-3` | 1 | Photorealistic, style control |
| DALL-E 2 | `dall-e-2` | 10 | Fast, flexible |

### FAL AI

| Model | ID | Features |
|-------|----|----|
| FLUX Dev | `fal-ai/flux/dev` | High quality, flexible |
| FLUX Schnell | `fal-ai/flux/schnell` | Fast, real-time |
| Stable Diffusion 3 | `fal-ai/stable-diffusion-3` | Latest SD model |

### Stability AI

| Model | ID | Features |
|-------|----|----|
| SDXL | `stability-ai/stable-diffusion-xl` | Highly capable |
| Stable Diffusion 3 | `stability-ai/stable-diffusion-3` | Latest release |

### Recraft

| Model | ID | Features |
|-------|----|----|
| Recraft V3 | `recraft-v3` | Vector/design focused |

### RunwayML

Multiple models for image generation and manipulation.

## API Reference

### ImageGenerationRequest

Request object for image generation.

#### Constructor

**Python:**
```python
request = ImageGenerationRequest(model: str, prompt: str)
```

**TypeScript:**
```typescript
const request = new ImageGenerationRequest(model: string, prompt: string)
```

#### Builder Methods

##### with_n(count: int)

Set number of images to generate (1-10).

```python
request = request.with_n(4)
```

##### with_size(size: ImageSize)

Set image dimensions.

**Available sizes:**
- `ImageSize.Square256` - 256x256
- `ImageSize.Square512` - 512x512
- `ImageSize.Square1024` - 1024x1024 (default)
- `ImageSize.Portrait1024x1792` - 1024x1792
- `ImageSize.Landscape1792x1024` - 1792x1024

```python
request = request.with_size(ImageSize.Landscape1792x1024)
```

##### with_quality(quality: ImageQuality)

Set image quality (DALL-E 3 only).

```python
request = request.with_quality(ImageQuality.Hd)
```

**Options:**
- `ImageQuality.Standard` - Faster, cheaper
- `ImageQuality.Hd` - More detail

##### with_style(style: ImageStyle)

Set image style (DALL-E 3 only).

```python
request = request.with_style(ImageStyle.Vivid)
```

**Options:**
- `ImageStyle.Natural` - Realistic
- `ImageStyle.Vivid` - Dramatic, vivid

##### with_format(format: ImageFormat)

Set response format.

```python
request = request.with_format(ImageFormat.B64Json)
```

**Options:**
- `ImageFormat.Url` - Return download URL
- `ImageFormat.B64Json` - Return base64-encoded data

##### with_negative_prompt(prompt: str)

Describe what NOT to include (Stability AI models).

```python
request = request.with_negative_prompt("blurry, low quality, watermark")
```

##### with_seed(seed: int)

Set seed for reproducible results.

```python
request = request.with_seed(12345)
```

#### Complete Example

**Python:**
```python
request = (
    ImageGenerationRequest("dall-e-3", "A Renaissance painting style portrait")
    .with_n(1)
    .with_size(ImageSize.Landscape1792x1024)
    .with_quality(ImageQuality.Hd)
    .with_style(ImageStyle.Vivid)
    .with_format(ImageFormat.Url)
)
```

**TypeScript:**
```typescript
const request = new ImageGenerationRequest(
  'dall-e-3',
  'A Renaissance painting style portrait'
)
  .with_n(1)
  .with_size(ImageSize.Landscape1792x1024)
  .with_quality(ImageQuality.Hd)
  .with_style(ImageStyle.Vivid)
  .with_format(ImageFormat.Url)
```

### ImageGenerationResponse

Response object containing generated images.

#### Properties

- `created` (int): Unix timestamp of creation
- `images` (List[GeneratedImage]): Array of generated images
- `count` (int, read-only): Number of images generated
- `total_size` (int, read-only): Total size of all image data

#### Methods

##### first()

Get the first image (convenience for n=1 requests).

```python
image = response.first()
if image:
    print(f"URL: {image.url}")
```

### GeneratedImage

Individual generated image.

#### Properties

- `url` (str, optional): Download URL for the image
- `b64_json` (str, optional): Base64-encoded image data
- `revised_prompt` (str, optional): Prompt used by the model

#### Methods

##### from_url(url: str)

Create image from URL (static method).

```python
image = GeneratedImage.from_url("https://example.com/image.png")
```

##### from_b64(data: str)

Create image from base64 data (static method).

```python
image = GeneratedImage.from_b64(b64_encoded_data)
```

##### with_revised_prompt(prompt: str)

Set the revised prompt.

```python
image = image.with_revised_prompt("Updated prompt description")
```

## LLMKitClient.generate_image()

Generate images from a text prompt.

#### Signature

**Python:**
```python
def generate_image(self, request: ImageGenerationRequest) -> ImageGenerationResponse
```

**TypeScript:**
```typescript
async generateImage(request: ImageGenerationRequest): Promise<ImageGenerationResponse>
```

#### Example

**Python:**
```python
request = ImageGenerationRequest("dall-e-3", "A sunset over mountains")
response = client.generate_image(request)
```

**TypeScript:**
```typescript
const request = new ImageGenerationRequest('dall-e-3', 'A sunset over mountains')
const response = await client.generateImage(request)
```

## Accessing Image Data

### Option 1: Via URL

```python
response = client.generate_image(request)
if response.first()?.url:
    import requests
    r = requests.get(response.first().url)
    with open("image.png", "wb") as f:
        f.write(r.content)
```

### Option 2: Via Base64

```python
response = client.generate_image(request.with_format(ImageFormat.B64Json))
if response.first()?.b64_json:
    import base64
    image_data = base64.b64decode(response.first().b64_json)
    with open("image.png", "wb") as f:
        f.write(image_data)
```

## Resolution Guide

| Name | Dimensions | Use Case |
|------|-----------|----------|
| Square 256 | 256x256 | Thumbnails, icons |
| Square 512 | 512x512 | Small avatars |
| Square 1024 | 1024x1024 | Standard quality |
| Portrait | 1024x1792 | Character portraits, posters |
| Landscape | 1792x1024 | Wide scenes, backgrounds |

## Cost and Speed Trade-offs

| Model | Speed | Quality | Cost | Best For |
|-------|-------|---------|------|----------|
| FLUX Schnell | Very Fast | Good | Low | Real-time apps |
| DALL-E 2 | Fast | Good | Low | General use |
| DALL-E 3 Standard | Medium | Excellent | Medium | Quality |
| DALL-E 3 HD | Slower | Premium | High | High-end |
| Stable Diffusion 3 | Medium | Excellent | Low | Open-source |

## Complete Working Examples

### Python: Save Generated Images

```python
from llmkit import LLMKitClient, ImageGenerationRequest, ImageSize, ImageQuality
import base64
from pathlib import Path

def generate_and_save_images(prompts: list, output_dir: str = "generated_images"):
    client = LLMKitClient.from_env()
    Path(output_dir).mkdir(exist_ok=True)

    for i, prompt in enumerate(prompts):
        request = (
            ImageGenerationRequest("dall-e-3", prompt)
            .with_size(ImageSize.Square1024)
            .with_quality(ImageQuality.Hd)
        )

        response = client.generate_image(request)

        if response.first()?.b64_json:
            image_data = base64.b64decode(response.first().b64_json)
            filepath = Path(output_dir) / f"image_{i}.png"
            filepath.write_bytes(image_data)
            print(f"✓ Saved: {filepath}")

# Usage
prompts = [
    "A serene mountain landscape",
    "A futuristic city at night",
    "A peaceful forest with sunlight",
]
generate_and_save_images(prompts)
```

### TypeScript: Batch Generation with Retry

```typescript
import { LLMKitClient, ImageGenerationRequest, ImageSize } from 'llmkit'
import * as fs from 'fs'

async function generateWithRetry(
  client: LLMKitClient,
  prompt: string,
  maxRetries: number = 3
) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      const request = new ImageGenerationRequest('dall-e-3', prompt).with_size(
        ImageSize.Square1024
      )
      const response = await client.generateImage(request)
      return response
    } catch (error) {
      console.error(`Attempt ${attempt} failed:`, error)
      if (attempt < maxRetries) {
        await sleep(1000 * attempt) // Exponential backoff
      } else {
        throw error
      }
    }
  }
}

async function sleep(ms: number) {
  return new Promise((resolve) => setTimeout(resolve, ms))
}

// Usage
const client = LLMKitClient.fromEnv()
const response = await generateWithRetry(client, 'A cat in space')
```

## Error Handling

### Python

```python
try:
    request = ImageGenerationRequest("dall-e-3", "Generate image")
    response = client.generate_image(request)
except Exception as e:
    print(f"Image generation failed: {e}")
    if "quota" in str(e).lower():
        print("Rate limit reached, try again later")
```

### TypeScript

```typescript
try {
  const request = new ImageGenerationRequest('dall-e-3', 'Generate image')
  const response = await client.generateImage(request)
} catch (error) {
  console.error(`Image generation failed: ${(error as Error).message}`)
  if ((error as Error).message.includes('quota')) {
    console.log('Rate limit reached, try again later')
  }
}
```

## Environment Variables

Configure provider-specific API keys:

- `OPENAI_API_KEY`: For DALL-E models
- `FAL_API_KEY`: For Fal.ai Flux models
- `STABILITY_API_KEY`: For Stability AI models
- `REPLICATE_API_TOKEN`: For Replicate models

## Tips & Best Practices

### Writing Good Prompts

**Effective prompt:**
> "A serene Japanese Zen garden with a wooden bridge over a koi pond, cherry blossom trees, stone lanterns, morning mist, peaceful atmosphere, professional photography, high detail"

**Less effective:**
> "garden"

### Quality Settings

- Use `ImageQuality.Hd` for final products
- Use `ImageQuality.Standard` for iterations and testing
- HD quality takes longer and costs more

### Caching Results

For frequently requested images, cache the URLs:

```python
from functools import lru_cache

@lru_cache(maxsize=100)
def generate_cached_image(prompt: str):
    request = ImageGenerationRequest("dall-e-3", prompt)
    response = client.generate_image(request)
    return response.first().url
```

### Batch Processing

When generating many images, add delays:

```python
import time

for prompt in large_prompt_list:
    request = ImageGenerationRequest("dall-e-3", prompt)
    response = client.generate_image(request)
    time.sleep(2)  # Respect rate limits
```

## Troubleshooting

### No Image Data in Response

**Issue:** Both `url` and `b64_json` are None

**Solutions:**
- Verify the model name is correct
- Check your API quota
- Verify API key has image generation permissions

### "Quota Exceeded" Error

**Issue:** Rate limiting or quota limits

**Solutions:**
- Implement retry logic with exponential backoff
- Add delays between requests
- Use Standard quality instead of HD

### Image Quality Issues

**Issue:** Generated images are low quality or blurry

**Solutions:**
- Use more descriptive prompts
- Set `ImageQuality.Hd` for better quality
- Try a different model (DALL-E 3 vs FLUX)
- Adjust style (Vivid vs Natural)

## See Also

- [Audio API]./audio-api.md - Speech recognition and synthesis
- [Video API]./video-api.md - Video generation
- [Complete API Reference]../README.md