Elffuss BraidHub

kikocis/continue public

main · 6.7 KiBRawPermalink
1import { Mutex } from "async-mutex";
2import { spawn } from "child_process";
3import { LLMOptions, ModelInstaller } from "../../index.js";
4import OpenAI from "./OpenAI.js";
5
6/**
7 * Docker Model Runner provider
8 *
9 * Integrates with Docker Desktop's Model Runner feature (currently in beta)
10 * that allows running local AI models through Docker.
11 *
12 * Docker Model Runner provides an OpenAI-compatible API endpoint, making it
13 * easy to integrate with existing OpenAI-compatible code.
14 *
15 * More information at: https://docs.docker.com/desktop/features/model-runner/
16 */
17class Docker extends OpenAI implements ModelInstaller {
18 static providerName = "docker";
19 static defaultOptions: Partial<LLMOptions> = {
20 apiBase: "http://localhost:12434/engines/v1/",
21 model: "gemma3-4B-F4", // Default model
22 };
23
24 private modelMap: Record<string, string> = {
25 // Map of "continue model name" to Docker model name
26 // Models can be pulled using: docker model pull <model_name>
27 "llama3.3-70b": "ai/llama3.3:70B-Q4_K_M",
28 "smollm2-360M-F4": "ai/smollm2:360M-Q4_K_M",
29 "smollm2-360M-F16": "ai/ai/smollm2:360M-F16",
30 "qwen2.5-7B-F16": "ai/qwen2.5:7B-F16",
31 "qwen2.5-7B-F4": "ai/qwen2.5:7B-Q4_K_M",
32 "phi4-14B-F16": "ai/phi4:14B-F16",
33 "phi4-14B-F4": "ai/phi4:14B-Q4_K_M",
34 "mistral-7B-F16": "ai/mistral:7B-F16",
35 "mistral-7B-F4": "ai/mistral:7B-Q4_K_M",
36 "mistral-nemo-12B": "ai/mistral-nemo:12B-Q4_K_M",
37 "gemma3-4B-F16": "ai/gemma3:4B-F16",
38 "gemma3-4B-F4": "ai/gemma3:4B-Q4_K_M",
39 "llama3.2-3B-F16": "ai/llama3.2:3B-F16",
40 "llama3.2-3B-F4": "ai/llama3.2:3B-Q4_K_M",
41 "llama3.2-1B-F16": "ai/llama3.2:1B-F16",
42 "llama3.2-1B-F8": "ai/llama3.2:1B-Q8_0",
43 "qwq-32B-F16": "ai/qwq:32B-F16",
44 "qwq-32B-F4": "ai/qwq:32B-Q4_K_M",
45 "deepseek-r1-distill-llama-70B-F4":
46 "ai/deepseek-r1-distill-llama:70B-Q4_K_M",
47 "deepseek-r1-distill-llama-8B-F16": "ai/deepseek-r1-distill-llama:8B-F16",
48 "deepseek-r1-distill-llama-8B-Q4": "ai/deepseek-r1-distill-llama:8B-Q4_K_M",
49 };
50
51 private static modelsBeingInstalled: Set<string> = new Set();
52 private static modelsBeingInstalledMutex = new Mutex();
53
54 constructor(options: LLMOptions) {
55 super(options);
56
57 // Handle model name mapping
58 if (this.model && this.modelMap[this.model]) {
59 this.model = this.modelMap[this.model];
60 }
61
62 // Check if Docker Model Runner is active and enable it if needed
63 this.ensureModelRunnerEnabled().catch((e) => {});
64 }
65
66 /**
67 * Checks if Docker Model Runner is running at the expected port
68 * and enables it if not running
69 */
70 private async ensureModelRunnerEnabled(): Promise<void> {
71 try {
72 // Check if the Model Runner service is running on the expected port
73 const isRunning = await this.isPortBound(12434);
74
75 if (!isRunning) {
76 console.log(
77 "Docker Model Runner not detected. Attempting to enable it...",
78 );
79 await this.executeDockerCommand([
80 "desktop",
81 "enable",
82 "model-runner",
83 "--tcp",
84 "12434",
85 ]);
86 console.log("Docker Model Runner has been enabled on port 12434");
87 }
88 } catch (error) {
89 console.warn("Failed to enable Docker Model Runner:", error);
90 }
91 }
92
93 /**
94 * Checks if a port is currently bound/in use
95 */
96 private async isPortBound(port: number): Promise<boolean> {
97 try {
98 await this.fetch(`http://localhost:${port}`, {
99 method: "HEAD",
100 signal: AbortSignal.timeout(1000),
101 });
102 return true;
103 } catch (e) {
104 return false;
105 }
106 }
107
108 private async executeDockerCommand(
109 args: string[],
110 signal?: AbortSignal,
111 ): Promise<{ stdout: string; stderr: string }> {
112 return new Promise((resolve, reject) => {
113 const proc = spawn("docker", args, { shell: true });
114
115 let stdout = "";
116 let stderr = "";
117
118 proc.stdout.on("data", (data) => {
119 stdout += data.toString();
120 });
121
122 proc.stderr.on("data", (data) => {
123 stderr += data.toString();
124 });
125
126 proc.on("close", (code) => {
127 if (code === 0) {
128 resolve({ stdout, stderr });
129 } else {
130 reject(
131 new Error(`Docker command failed with code ${code}: ${stderr}`),
132 );
133 }
134 });
135
136 if (signal) {
137 signal.addEventListener("abort", () => {
138 proc.kill();
139 reject(new Error("Docker command was aborted"));
140 });
141 }
142 });
143 }
144
145 async listModels(): Promise<string[]> {
146 try {
147 // Execute docker model ls and parse the output
148 const { stdout } = await this.executeDockerCommand([
149 "model",
150 "ls",
151 "--format",
152 "{{.Repository}}/{{.Tag}}",
153 ]);
154 return stdout
155 .split("\n")
156 .map((line) => line.trim())
157 .filter(Boolean);
158 } catch (error) {
159 console.error("Failed to list Docker models:", error);
160 return Object.values(this.modelMap);
161 }
162 }
163
164 async installModel(
165 modelName: string,
166 signal: AbortSignal,
167 progressReporter?: (task: string, increment: number, total: number) => void,
168 ): Promise<any> {
169 const targetModel = this.modelMap[modelName] || modelName;
170
171 const release = await Docker.modelsBeingInstalledMutex.acquire();
172 try {
173 if (Docker.modelsBeingInstalled.has(modelName)) {
174 throw new Error(`Model '${modelName}' is already being installed.`);
175 }
176 Docker.modelsBeingInstalled.add(modelName);
177 } finally {
178 release();
179 }
180
181 try {
182 // Report starting the installation
183 progressReporter?.(`Installing Docker model ${targetModel}`, 0, 100);
184
185 // Pull the model
186 const { stdout, stderr } = await this.executeDockerCommand(
187 ["model", "pull", targetModel],
188 signal,
189 );
190
191 // Report completion
192 progressReporter?.(
193 `Docker model ${targetModel} installed successfully`,
194 100,
195 100,
196 );
197
198 return { success: true, stdout, stderr };
199 } catch (error) {
200 console.error(`Failed to install Docker model ${targetModel}:`, error);
201 // Fix: Type check the error before accessing message property
202 const errorMessage =
203 error instanceof Error ? error.message : String(error);
204 throw new Error(
205 `Failed to install Docker model ${targetModel}: ${errorMessage}`,
206 );
207 } finally {
208 const release = await Docker.modelsBeingInstalledMutex.acquire();
209 try {
210 Docker.modelsBeingInstalled.delete(modelName);
211 } finally {
212 release();
213 }
214 }
215 }
216
217 public async isInstallingModel(modelName: string): Promise<boolean> {
218 const release = await Docker.modelsBeingInstalledMutex.acquire();
219 try {
220 return Docker.modelsBeingInstalled.has(modelName);
221 } finally {
222 release();
223 }
224 }
225}
226
227export default Docker;