shimmy 2.0.0

Lightweight Ollama-compatible inference server with native SafeTensors support. No Python dependencies, cross-platform WebGPU acceleration via Airframe.
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
use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::Path;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum TemplateFamily {
    ChatML,
    Llama3,
    OpenChat,
}

impl TemplateFamily {
    pub fn render(
        &self,
        system: Option<&str>,
        messages: &[(String, String)],
        input: Option<&str>,
    ) -> String {
        match self {
            TemplateFamily::ChatML => {
                let mut s = String::new();
                if let Some(sys) = system {
                    s.push_str(&format!("<|im_start|>system\n{}<|im_end|>\n", sys));
                }
                for (role, content) in messages {
                    s.push_str(&format!("<|im_start|>{}\n{}<|im_end|>\n", role, content));
                }
                if let Some(inp) = input {
                    s.push_str(&format!(
                        "<|im_start|>user\n{}<|im_end|>\n<|im_start|>assistant\n",
                        inp
                    ));
                }
                s
            }
            TemplateFamily::Llama3 => {
                let mut s = String::new();
                if let Some(sys) = system {
                    s.push_str(&format!(
                        "<|begin_of_text|><|start_header_id|>system<|end_header_id|>\n{}<|eot_id|>",
                        sys
                    ));
                }
                for (role, content) in messages {
                    s.push_str(&format!(
                        "<|start_header_id|>{}<|end_header_id|>\n{}<|eot_id|>",
                        role, content
                    ));
                }
                if let Some(inp) = input {
                    s.push_str(&format!("<|start_header_id|>user<|end_header_id|>\n{}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n", inp));
                }
                s
            }
            TemplateFamily::OpenChat => {
                let mut s = String::new();
                for (role, content) in messages {
                    s.push_str(&format!("{}: {}\n", role, content));
                }
                if let Some(inp) = input {
                    s.push_str(&format!("user: {}\nassistant: ", inp));
                } else {
                    s.push_str("assistant: ");
                }
                s
            }
        }
    }

    /// Get the stop tokens for this template family
    pub fn stop_tokens(&self) -> Vec<String> {
        match self {
            TemplateFamily::ChatML => vec!["<|im_end|>".to_string(), "<|im_start|>".to_string()],
            TemplateFamily::Llama3 => vec!["<|eot_id|>".to_string(), "<|end_of_text|>".to_string()],
            TemplateFamily::OpenChat => vec![],
        }
    }
}

// Template generation functions for deployment platforms

/// Generate Docker deployment template
pub fn generate_docker_template(output_dir: &str, project_name: Option<&str>) -> Result<()> {
    let output_path = Path::new(output_dir);
    fs::create_dir_all(output_path)?;

    // Copy Dockerfile
    let dockerfile_content = include_str!("../templates/docker/Dockerfile");
    fs::write(output_path.join("Dockerfile"), dockerfile_content)?;

    // Copy docker-compose.yml
    let compose_content = include_str!("../templates/docker/docker-compose.yml");
    let customized_compose = if let Some(name) = project_name {
        compose_content.replace("shimmy-ai", &format!("{}-shimmy", name))
    } else {
        compose_content.to_string()
    };
    fs::write(output_path.join("docker-compose.yml"), customized_compose)?;

    // Copy nginx.conf
    let nginx_content = include_str!("../templates/docker/nginx.conf");
    fs::write(output_path.join("nginx.conf"), nginx_content)?;

    // Create .dockerignore
    let dockerignore_content = r#"target/
Cargo.lock
*.md
docs/
tests/
.git/
.gitignore
README.md
"#;
    fs::write(output_path.join(".dockerignore"), dockerignore_content)?;

    Ok(())
}

/// Generate Kubernetes deployment template
pub fn generate_kubernetes_template(output_dir: &str, project_name: Option<&str>) -> Result<()> {
    let output_path = Path::new(output_dir);
    fs::create_dir_all(output_path)?;

    let name = project_name.unwrap_or("shimmy");

    // Generate deployment.yaml
    let deployment_content = include_str!("../templates/kubernetes/deployment.yaml")
        .replace("shimmy-deployment", &format!("{}-deployment", name))
        .replace("app: shimmy", &format!("app: {}", name));
    fs::write(output_path.join("deployment.yaml"), deployment_content)?;

    // Generate service.yaml
    let service_content = include_str!("../templates/kubernetes/service.yaml")
        .replace("shimmy-service", &format!("{}-service", name))
        .replace("shimmy-loadbalancer", &format!("{}-loadbalancer", name))
        .replace("app: shimmy", &format!("app: {}", name));
    fs::write(output_path.join("service.yaml"), service_content)?;

    // Generate configmap.yaml
    let configmap_content = include_str!("../templates/kubernetes/configmap.yaml")
        .replace("shimmy-config", &format!("{}-config", name))
        .replace("shimmy-models-pvc", &format!("{}-models-pvc", name))
        .replace("app: shimmy", &format!("app: {}", name));
    fs::write(output_path.join("configmap.yaml"), configmap_content)?;

    Ok(())
}

/// Generate Railway deployment template
pub fn generate_railway_template(output_dir: &str, _project_name: Option<&str>) -> Result<()> {
    let output_path = Path::new(output_dir);
    fs::create_dir_all(output_path)?;

    let railway_content = include_str!("../templates/railway/railway.toml");
    fs::write(output_path.join("railway.toml"), railway_content)?;

    // Generate Dockerfile for Railway
    let dockerfile_content = include_str!("../templates/docker/Dockerfile");
    fs::write(output_path.join("Dockerfile"), dockerfile_content)?;

    Ok(())
}

/// Generate Fly.io deployment template
pub fn generate_fly_template(output_dir: &str, project_name: Option<&str>) -> Result<()> {
    let output_path = Path::new(output_dir);
    fs::create_dir_all(output_path)?;

    let fly_content = include_str!("../templates/fly/fly.toml");
    let customized_fly = if let Some(name) = project_name {
        fly_content.replace("shimmy-ai", &format!("{}-ai", name))
    } else {
        fly_content.to_string()
    };
    fs::write(output_path.join("fly.toml"), customized_fly)?;

    // Generate Dockerfile for Fly
    let dockerfile_content = include_str!("../templates/docker/Dockerfile");
    fs::write(output_path.join("Dockerfile"), dockerfile_content)?;

    Ok(())
}

/// Generate FastAPI integration template
pub fn generate_fastapi_template(output_dir: &str, _project_name: Option<&str>) -> Result<()> {
    let output_path = Path::new(output_dir);
    fs::create_dir_all(output_path)?;

    let main_content = include_str!("../templates/frameworks/fastapi/main.py");
    fs::write(output_path.join("main.py"), main_content)?;

    let requirements_content = include_str!("../templates/frameworks/fastapi/requirements.txt");
    fs::write(output_path.join("requirements.txt"), requirements_content)?;

    Ok(())
}

/// Generate Express.js integration template
pub fn generate_express_template(output_dir: &str, project_name: Option<&str>) -> Result<()> {
    let output_path = Path::new(output_dir);
    fs::create_dir_all(output_path)?;

    let app_content = include_str!("../templates/frameworks/express/app.js");
    fs::write(output_path.join("app.js"), app_content)?;

    let package_content = include_str!("../templates/frameworks/express/package.json");
    let customized_package = if let Some(name) = project_name {
        package_content.replace(
            "shimmy-express-integration",
            &format!("{}-shimmy-integration", name),
        )
    } else {
        package_content.to_string()
    };
    fs::write(output_path.join("package.json"), customized_package)?;

    Ok(())
}

/// Generic template generation function that dispatches to specific template generators
pub fn generate_template(
    template: &str,
    output_dir: &str,
    project_name: Option<&str>,
) -> Result<String> {
    match template.to_lowercase().as_str() {
        "docker" => {
            generate_docker_template(output_dir, project_name)?;
            Ok(format!("✅ Docker template generated in {}", output_dir))
        }
        "kubernetes" | "k8s" => {
            generate_kubernetes_template(output_dir, project_name)?;
            Ok(format!(
                "✅ Kubernetes template generated in {}",
                output_dir
            ))
        }
        "railway" => {
            generate_railway_template(output_dir, project_name)?;
            Ok(format!("✅ Railway template generated in {}", output_dir))
        }
        "fly" => {
            generate_fly_template(output_dir, project_name)?;
            Ok(format!("✅ Fly.io template generated in {}", output_dir))
        }
        "fastapi" => {
            generate_fastapi_template(output_dir, project_name)?;
            Ok(format!("✅ FastAPI template generated in {}", output_dir))
        }
        "express" => {
            generate_express_template(output_dir, project_name)?;
            Ok(format!(
                "✅ Express.js template generated in {}",
                output_dir
            ))
        }
        _ => {
            anyhow::bail!("Unknown template type: {}. Available: docker, kubernetes, railway, fly, fastapi, express", template)
        }
    }
}

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

    #[test]
    fn test_chatml_render() {
        let template = TemplateFamily::ChatML;
        let messages = vec![("user".to_string(), "Hello".to_string())];
        let result = template.render(None, &messages, None);
        assert!(result.contains("<|im_start|>user"));
        assert!(result.contains("Hello"));
        assert!(result.contains("<|im_end|>"));
    }

    #[test]
    fn test_llama3_render() {
        let template = TemplateFamily::Llama3;
        let messages = vec![("user".to_string(), "Test".to_string())];
        let result = template.render(None, &messages, None);
        assert!(result.contains("<|start_header_id|>user<|end_header_id|>"));
        assert!(result.contains("Test"));
        assert!(result.contains("<|eot_id|>"));
    }

    #[test]
    fn test_openchat_render() {
        let template = TemplateFamily::OpenChat;
        let messages = vec![("user".to_string(), "Hi".to_string())];
        let result = template.render(None, &messages, None);
        assert!(result.contains("user: Hi"));
        assert!(result.contains("assistant: "));
    }

    #[test]
    fn test_chatml_stop_tokens() {
        let template = TemplateFamily::ChatML;
        let stop_tokens = template.stop_tokens();
        assert_eq!(stop_tokens.len(), 2);
        assert!(stop_tokens.contains(&"<|im_end|>".to_string()));
        assert!(stop_tokens.contains(&"<|im_start|>".to_string()));
    }

    #[test]
    fn test_llama3_stop_tokens() {
        let template = TemplateFamily::Llama3;
        let stop_tokens = template.stop_tokens();
        assert_eq!(stop_tokens.len(), 2);
        assert!(stop_tokens.contains(&"<|eot_id|>".to_string()));
        assert!(stop_tokens.contains(&"<|end_of_text|>".to_string()));
    }

    #[test]
    fn test_openchat_stop_tokens() {
        let template = TemplateFamily::OpenChat;
        let stop_tokens = template.stop_tokens();
        assert_eq!(stop_tokens.len(), 0);
    }

    #[test]
    fn test_chatml_render_with_system_and_input() {
        let template = TemplateFamily::ChatML;
        let messages = vec![("user".to_string(), "Hello".to_string())];
        let result = template.render(Some("You are helpful"), &messages, Some("New question"));
        assert!(result.contains("<|im_start|>system\nYou are helpful<|im_end|>"));
        assert!(result.contains("<|im_start|>user\nNew question<|im_end|>"));
        assert!(result.contains("<|im_start|>assistant\n"));
    }

    #[test]
    fn test_llama3_render_with_system_and_input() {
        let template = TemplateFamily::Llama3;
        let messages = vec![("user".to_string(), "Hi".to_string())];
        let result = template.render(Some("Be concise"), &messages, Some("Ask me anything"));
        assert!(result.contains("<|begin_of_text|><|start_header_id|>system<|end_header_id|>"));
        assert!(result.contains("Be concise<|eot_id|>"));
        assert!(result.contains("<|start_header_id|>assistant<|end_header_id|>"));
    }

    #[test]
    fn test_openchat_render_with_input() {
        let template = TemplateFamily::OpenChat;
        let messages = vec![("user".to_string(), "Hello".to_string())];
        let result = template.render(None, &messages, Some("Final question"));
        assert!(result.contains("user: Final question\nassistant: "));
    }

    #[test]
    fn test_openchat_render_no_input() {
        let template = TemplateFamily::OpenChat;
        let messages: Vec<(String, String)> = vec![];
        let result = template.render(None, &messages, None);
        assert_eq!(result, "assistant: ");
    }

    #[test]
    fn test_generate_docker_template_creates_files() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let output = temp_dir.path().to_str().unwrap();
        generate_docker_template(output, None).unwrap();
        assert!(temp_dir.path().join("Dockerfile").exists());
        assert!(temp_dir.path().join("docker-compose.yml").exists());
        assert!(temp_dir.path().join("nginx.conf").exists());
        assert!(temp_dir.path().join(".dockerignore").exists());
    }

    #[test]
    fn test_generate_docker_template_project_name_substitution() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let output = temp_dir.path().to_str().unwrap();
        generate_docker_template(output, Some("myproject")).unwrap();
        let compose = fs::read_to_string(temp_dir.path().join("docker-compose.yml")).unwrap();
        assert!(compose.contains("myproject-shimmy"));
    }

    #[test]
    fn test_generate_kubernetes_template_creates_files() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let output = temp_dir.path().to_str().unwrap();
        generate_kubernetes_template(output, Some("testapp")).unwrap();
        assert!(temp_dir.path().join("deployment.yaml").exists());
        assert!(temp_dir.path().join("service.yaml").exists());
        assert!(temp_dir.path().join("configmap.yaml").exists());
        let deployment = fs::read_to_string(temp_dir.path().join("deployment.yaml")).unwrap();
        assert!(deployment.contains("testapp-deployment"));
    }

    #[test]
    fn test_generate_railway_template_creates_files() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let output = temp_dir.path().to_str().unwrap();
        generate_railway_template(output, None).unwrap();
        assert!(temp_dir.path().join("railway.toml").exists());
        assert!(temp_dir.path().join("Dockerfile").exists());
    }

    #[test]
    fn test_generate_fly_template_creates_files() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let output = temp_dir.path().to_str().unwrap();
        generate_fly_template(output, Some("myfly")).unwrap();
        assert!(temp_dir.path().join("fly.toml").exists());
        assert!(temp_dir.path().join("Dockerfile").exists());
        let fly = fs::read_to_string(temp_dir.path().join("fly.toml")).unwrap();
        assert!(fly.contains("myfly-ai"));
    }

    #[test]
    fn test_generate_fastapi_template_creates_files() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let output = temp_dir.path().to_str().unwrap();
        generate_fastapi_template(output, None).unwrap();
        assert!(temp_dir.path().join("main.py").exists());
        assert!(temp_dir.path().join("requirements.txt").exists());
    }

    #[test]
    fn test_generate_express_template_creates_files() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let output = temp_dir.path().to_str().unwrap();
        generate_express_template(output, Some("myexpress")).unwrap();
        assert!(temp_dir.path().join("app.js").exists());
        assert!(temp_dir.path().join("package.json").exists());
        let pkg = fs::read_to_string(temp_dir.path().join("package.json")).unwrap();
        assert!(pkg.contains("myexpress-shimmy-integration"));
    }

    #[test]
    fn test_generate_template_dispatcher_docker() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let output = temp_dir.path().to_str().unwrap();
        let msg = generate_template("docker", output, None).unwrap();
        assert!(msg.contains("Docker template generated"));
    }

    #[test]
    fn test_generate_template_dispatcher_kubernetes_alias() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let output = temp_dir.path().to_str().unwrap();
        let msg = generate_template("k8s", output, Some("myapp")).unwrap();
        assert!(msg.contains("Kubernetes template generated"));
    }

    #[test]
    fn test_generate_template_dispatcher_all_types() {
        let types = ["railway", "fly", "fastapi", "express"];
        for template_type in &types {
            let temp_dir = tempfile::TempDir::new().unwrap();
            let output = temp_dir.path().to_str().unwrap();
            let result = generate_template(template_type, output, None);
            assert!(result.is_ok(), "Template type '{}' failed", template_type);
        }
    }

    #[test]
    fn test_generate_template_unknown_type() {
        let result = generate_template("bogustype", "/tmp", None);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Unknown template type"));
    }
}