agentgen-cli 0.1.4

CLI for the AgentGen API — HTML to PDF and Image
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
# agentgen · Rust SDK + CLI

Async Rust client and command-line tool for the [AgentGen API](https://www.agent-gen.com) — HTML → PDF and HTML → Image generation.

This directory is a Cargo workspace with two crates:

| Crate | Type | Description |
|-------|------|-------------|
| [`agentgen`]./agentgen/ | Library | Async Rust client — use in your own Rust projects |
| [`agentgen-cli`]./agentgen-cli/ | Binary | `agentgen` CLI — use from any shell or CI pipeline |

---

## Library — `agentgen`

### Adding to your project

```toml
# Cargo.toml
[dependencies]
agentgen = { path = "./agentgen" }   # local
# — or once published to crates.io —
agentgen = "0.1"

tokio = { version = "1", features = ["full"] }
```

### Quick start

```rust
use agentgen::{AgentGenClient, types::{GenerateImageRequest, ImageFormat, PdfPage, PdfFormat, GeneratePdfRequest}};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = AgentGenClient::new(std::env::var("AGENTGEN_API_KEY")?);

    // Render HTML to a PNG image
    let image = client
        .generate_image(
            GenerateImageRequest::new("<h1 style='font-family:sans-serif'>Hello!</h1>")
                .viewport_width(1200)
                .format(ImageFormat::Png),
        )
        .await?;

    println!("Image URL: {}", image.url);

    // Render HTML to a PDF
    let pdf = client
        .generate_pdf_with_optimize(GeneratePdfRequest::SinglePage(
            PdfPage::new("<h1>Invoice #42</h1><p>Amount due: $99.00</p>")
                .format(PdfFormat::A4)
                .print_background(true),
        ), Some(true))
        .await?;

    println!("PDF URL: {}", pdf.url);

    // Check balance
    let balance = client.get_balance().await?;
    println!("Remaining tokens: {}", balance.tokens);

    Ok(())
}
```

---

### Creating the client

```rust
// Production (default base URL: https://www.agent-gen.com/api)
let client = AgentGenClient::new("agk_...");

// Custom base URL — useful for local development or testing
let client = AgentGenClient::with_base_url("agk_...", "http://localhost:3000/api");
```

---

### `generate_image` — Costs 1 token

Build a `GenerateImageRequest` with the provided builder methods and await the call.

```rust
use agentgen::types::{GenerateImageRequest, ImageFormat};

let result = client
    .generate_image(
        GenerateImageRequest::new("<div style='background:#6366f1;color:#fff;padding:40px'>Hello</div>")
            .viewport_width(1200)      // default: 1200
            .viewport_height(800)      // default: 800
            .selector("#card")         // optional CSS selector to capture
            .format(ImageFormat::Png)  // Png | Jpeg | Webp, default Png
            .device_scale_factor(2.0), // 1.0–3.0, default 2.0
    )
    .await?;

println!("URL:        {}", result.url);
println!("Size:       {}×{}", result.width, result.height);
println!("Format:     {:?}", result.format);
println!("Tokens:     {}", result.tokens_used);
println!("Request ID: {}", result.request_id);
```

`GenerateImageRequest::new(html)` is the only required call; all builder methods are optional.

---

### `generate_pdf` — Costs 2 tokens per page

Pass a `GeneratePdfRequest` — either `SinglePage(PdfPage)` for one page, or `MultiPage { pages: Vec<PdfPage> }` for multiple pages.
Use `generate_pdf_with_optimize(..., Some(false))` if you need the unoptimized Chromium PDF.

#### Single-page PDF

```rust
use agentgen::types::{GeneratePdfRequest, PdfPage, PdfFormat, PdfMargin, PdfPageSizeSource};

let result = client
    .generate_pdf_with_optimize(GeneratePdfRequest::SinglePage(
        PdfPage::new(r#"
            <html>
              <body style="font-family:sans-serif;padding:40px">
                <h1>Invoice #42</h1>
                <p>Amount due: $99.00</p>
              </body>
            </html>
        "#)
        .page_size_source(PdfPageSizeSource::Css)
        .format(PdfFormat::A4)        // A4 | Letter | A3 | Legal
        .landscape(false)             // default false
        .print_background(true)       // default true
        .margin(PdfMargin {
            top: Some("20mm".into()),
            bottom: Some("20mm".into()),
            left: Some("15mm".into()),
            right: Some("15mm".into()),
        }),
    ), Some(true))
    .await?;

println!("PDF URL:   {}", result.url);
println!("Pages:     {}", result.pages);
println!("Tokens:    {}", result.tokens_used);
```

#### Shorthand for uniform margins

```rust
use agentgen::types::PdfMargin;

// Sets top/bottom/left/right to the same value
let margin = PdfMargin::all("20mm");
```

#### Multi-page PDF

```rust
let result = client
    .generate_pdf_with_optimize(GeneratePdfRequest::MultiPage {
        pages: vec![
            PdfPage::new("<h1 style='padding:40px'>Page 1 — Cover</h1>")
                .page_size_source(PdfPageSizeSource::Css)
                .format(PdfFormat::A4),
            PdfPage::new("<h1 style='padding:40px'>Page 2 — Content</h1>")
                .page_size_source(PdfPageSizeSource::Css)
                .format(PdfFormat::A4)
                .landscape(true),
            PdfPage::new("<h1 style='padding:40px'>Page 3 — Appendix</h1>")
                .page_size_source(PdfPageSizeSource::Css)
                .format(PdfFormat::A4)
                .margin(PdfMargin::all("10mm")),
        ],
    }, Some(true))
    .await?;

println!("Generated {} pages, used {} tokens", result.pages, result.tokens_used);
```

Up to 100 pages per request.

---

### `upload_temp` — Free

Upload a local file so you can reference it by URL inside your HTML. Auto-deleted after **24 hours**.

```rust
use std::path::Path;

let upload = client.upload_temp(Path::new("./logo.png")).await?;

println!("URL:        {}", upload.url);
println!("Key:        {}", upload.key);
println!("Size:       {} bytes", upload.size);
println!("Expires at: {}", upload.expires_at);

// Embed the URL in HTML and then generate
let image = client
    .generate_image(
        GenerateImageRequest::new(format!(
            r#"<img src="{}" style="width:200px" />"#,
            upload.url
        )),
    )
    .await?;
```

---

### `get_balance` — Free

```rust
let balance = client.get_balance().await?;
println!("Remaining tokens: {}", balance.tokens);
```

---

### Error handling

All methods return `Result<T, AgentGenError>`. The error type is defined in `agentgen::AgentGenError`:

```rust
use agentgen::AgentGenError;

match client.generate_image(req).await {
    Ok(result) => println!("{}", result.url),
    Err(AgentGenError::InsufficientTokens { balance, required, buy_more_url }) => {
        eprintln!("Not enough tokens. Have {balance}, need {required}.");
        eprintln!("Buy more at: {buy_more_url}");
    }
    Err(AgentGenError::Api { status, message, detail }) => {
        eprintln!("API error {status}: {message}");
        if let Some(d) = detail {
            eprintln!("Detail: {d}");
        }
    }
    Err(AgentGenError::Http(e)) => eprintln!("Network error: {e}"),
    Err(AgentGenError::Io(e)) => eprintln!("I/O error: {e}"),
}
```

#### `AgentGenError` variants

| Variant | When | Fields |
|---------|------|--------|
| `Api { status, message, detail }` | Non-2xx API response (except 402) | HTTP status, error message, optional detail |
| `InsufficientTokens { balance, required, buy_more_url }` | HTTP 402 | Current balance, required tokens, buy URL |
| `Http(reqwest::Error)` | Network / transport failure | Wrapped reqwest error |
| `Io(std::io::Error)` | File read failure (upload_temp) | Wrapped I/O error |

---

### Type reference

```rust
use agentgen::types::{
    // Image
    GenerateImageRequest,
    GenerateImageResponse,
    ImageFormat,        // Png | Jpeg | Webp

    // PDF
    GeneratePdfRequest, // SinglePage(PdfPage) | MultiPage { pages }
    GeneratePdfResponse,
    PdfPage,
    PdfMargin,
    PdfFormat,          // A4 | Letter | A3 | Legal
    PdfPageSizeSource,  // Css | Format

    // Upload
    UploadTempResponse,

    // Balance
    BalanceResponse,
};
```

---

## CLI — `agentgen`

The `agentgen` binary lets you use the API directly from a terminal, shell script, or CI pipeline without writing any code.

### Building

```bash
# From the rust/ workspace root
cargo build --release -p agentgen-cli

# The binary is at:
./target/release/agentgen
```

Or install it system-wide:

```bash
cargo install --path agentgen-cli
```

### Authentication

Provide your API key via the `AGENTGEN_API_KEY` environment variable (recommended) or the `--api-key` flag:

```bash
export AGENTGEN_API_KEY="agk_..."

# or pass it inline
agentgen --api-key agk_... balance
```

---

### `agentgen balance`

Check your current token balance.

```bash
$ agentgen balance
Token balance: 42
```

---

### `agentgen image`

Render HTML to an image (PNG / JPEG / WebP). **Costs 1 token.**

```
agentgen image (--html <string> | --file <path>)
               [--viewport-width <px>]
               [--viewport-height <px>]
               [--selector <css>]
               [--format png|jpeg|webp]
               [--scale <1-3>]
               [--output <path>]
```

**Inline HTML:**

```bash
agentgen image --html '<h1 style="font-family:sans-serif">Hello!</h1>' \
               --viewport-width 1200
```

**From a file:**

```bash
agentgen image --file ./template.html --viewport-width 1200 --format png
```

**Download the result locally:**

```bash
agentgen image --file ./og-template.html \
               --viewport-width 1200 \
               --selector '#card' \
               --output og-image.png
```

**Example output:**

```
✓ Image generated
  URL:           https://…/output.png
  Dimensions:    1200 × 630 px
  Format:        PNG
  Tokens used:   1
  Request ID:    req_abc123
✓ Saved → og-image.png
```

**Options:**

| Flag | Default | Description |
|------|---------|-------------|
| `--html <string>` || Inline HTML string to render |
| `--file <path>` || Read HTML from a file (mutually exclusive with `--html`) |
| `--viewport-width <px>` | 1200 | Viewport width in pixels used for layout before capture |
| `--viewport-height <px>` | 800 | Viewport height in pixels used for layout before capture |
| `--selector <css>` || Capture a specific element instead of the full rendered document |
| `--format` | `png` | Output format: `png`, `jpeg`, or `webp` |
| `--scale <n>` | 2 | Device pixel ratio (1–3) |
| `--output / -o <path>` || Download the generated image to this path |

---

### `agentgen pdf`

Render HTML to a PDF. **Costs 2 tokens per page.**

```
agentgen pdf (--html <string> | --file <path> | --pages <file1> <file2> …)
             [--page-size-source css|format]
             [--format A4|Letter|A3|Legal]
             [--landscape]
             [--print-background]
             [--no-optimize]
             [--margin-top <value>] [--margin-bottom <value>]
             [--margin-left <value>] [--margin-right <value>]
             [--output <path>]
```

**Single-page — inline HTML:**

```bash
agentgen pdf --html '<h1>Invoice #42</h1>' \
             --page-size-source css \
             --format A4 \
             --margin-top 20mm --margin-bottom 20mm \
             --output invoice.pdf
```

**Single-page — from a file:**

```bash
agentgen pdf --file ./invoice.html \
             --page-size-source css \
             --format A4 \
             --print-background \
             --no-optimize \
             --output invoice.pdf
```

**Multi-page — one HTML file per page:**

```bash
agentgen pdf --pages cover.html content.html appendix.html \
             --page-size-source css \
             --format A4 \
             --output report.pdf
```

Each file in `--pages` becomes one independent page. All pages share the same `--format`, `--landscape`, and margin settings.

**Example output:**

```
✓ PDF generated
  URL:           https://…/output.pdf
  Pages:         3 page(s)
  Tokens used:   6 token(s)
  Request ID:    req_def456
✓ Saved → report.pdf
```

**Options:**

| Flag | Default | Description |
|------|---------|-------------|
| `--html <string>` || Inline HTML for a single-page PDF |
| `--file <path>` || Read HTML from a file (single-page) |
| `--pages <files…>` || Multiple HTML files — one per page |
| `--page-size-source` | `css` | Prefer CSS `@page` size or fallback format |
| `--format` | `A4` | Fallback paper size: `A4`, `Letter`, `A3`, `Legal` |
| `--landscape` | off | Landscape orientation |
| `--print-background` | off | Render CSS backgrounds |
| `--no-optimize` | off | Disable PDF shrinking post-processing |
| `--margin-top <value>` || Top margin (CSS length, e.g. `20mm`) |
| `--margin-bottom <value>` || Bottom margin |
| `--margin-left <value>` || Left margin |
| `--margin-right <value>` || Right margin |
| `--output / -o <path>` || Download the generated PDF to this path |

---

### `agentgen upload`

Upload a local file to temporary storage. **Free — no tokens consumed.** Auto-deleted after **24 hours**.

```bash
agentgen upload ./logo.png
```

**Example output:**

```
✓ File uploaded
  URL:           https://…/logo.png
  Key:           tmp/…/logo.png
  Size:          14832 bytes
  Expires at:    2026-03-03T10:00:00.000Z
```

Use the printed URL inside your HTML before calling `image` or `pdf`.

---

### Global flags

| Flag | Description |
|------|-------------|
| `--api-key <key>` | API key (or set `AGENTGEN_API_KEY` env var) |
| `--version` | Print version and exit |
| `--help` | Print help and exit |

---

## Token pricing

| Operation | Cost |
|-----------|------|
| Generate image | 1 token |
| Generate PDF (per page) | 2 tokens |
| Upload temp file | Free |
| Check balance | Free |

Purchase tokens at [agent-gen.com](https://www.agent-gen.com).