-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpull-model-form.tsx
190 lines (177 loc) · 5.79 KB
/
pull-model-form.tsx
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
'use client';
import React, { useState } from 'react';
import {
Form,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form';
import { Button } from './ui/button';
import { z } from 'zod';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { toast } from 'sonner';
import { Loader2Icon } from 'lucide-react';
import { Input } from './ui/input';
import { useRouter } from 'next/navigation';
const formSchema = z.object({
name: z.string().min(1, {
message: 'Please select a model to pull',
}),
});
export default function PullModelForm() {
const [isDownloading, setIsDownloading] = useState(false);
const [name, setName] = useState('');
const router = useRouter();
const env = process.env.NODE_ENV;
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
});
function onSubmit(data: z.infer<typeof formSchema>) {
// Trim whitespace
data.name = data.name.trim();
setIsDownloading(true);
// Send the model name to the server
if (env === 'production') {
// Make a post request to localhost
const pullModel = async () => {
const response = await fetch(
process.env.NEXT_PUBLIC_OLLAMA_URL + '/api/pull',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
}
);
const json = await response.json();
if (json.error) {
toast.error('Error: ' + json.error);
setIsDownloading(false);
return;
} else if (json.status === 'success') {
toast.success('Model pulled successfully');
setIsDownloading(false);
return;
}
};
pullModel();
} else {
fetch('/api/model', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then((response) => {
// Check if response is successful
if (!response.ok) {
throw new Error('Network response was not ok');
}
if (!response.body) {
throw new Error('Something went wrong');
}
// Create a new ReadableStream from the response body
const reader = response.body.getReader();
// Read the data in chunks
reader.read().then(function processText({ done, value }) {
if (done) {
setIsDownloading(false);
return;
}
// Convert the chunk of data to a string
const text = new TextDecoder().decode(value);
// Split the text into individual JSON objects
const jsonObjects = text.trim().split('\n');
jsonObjects.forEach((jsonObject) => {
try {
const responseJson = JSON.parse(jsonObject);
if (responseJson.error) {
// Display an error toast if the response contains an error
toast.error('Error: ' + responseJson.error);
setIsDownloading(false);
return;
} else if (responseJson.status === 'success') {
// Display a success toast if the response status is success
toast.success('Model pulled successfully');
setIsDownloading(false);
return;
}
} catch (error) {
toast.error('Error parsing JSON');
setIsDownloading(false);
return;
}
});
// Continue reading the next chunk
reader.read().then(processText);
});
})
.catch((error) => {
setIsDownloading(false);
console.error('Error pulling model:', error);
toast.error('Error pulling model');
});
}
}
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
e.preventDefault();
form.setValue('name', e.currentTarget.value);
setName(e.currentTarget.value);
};
console.log('enter model');
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="w-full space-y-6">
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>Model name</FormLabel>
<Input
{...field}
type="text"
placeholder="llama2"
value={name}
onChange={(e) => handleChange(e)}
/>
<p className="text-xs pt-1">
Check the{' '}
<a
href="https://ollama.com/library"
target="_blank"
className="text-blue-500 underline"
>
library
</a>{' '}
for a list of available models.
</p>
<FormMessage />
</FormItem>
)}
/>
<div className="space-y-2 w-full">
<Button type="submit" className="w-full " disabled={isDownloading}>
{isDownloading ? (
<div className="flex items-center gap-2">
<Loader2Icon className="animate-spin w-4 h-4" />
<span>Pulling model...</span>
</div>
) : (
'Pull model'
)}
</Button>
<p className="text-xs text-center">
{isDownloading
? 'This may take a while. You can safely close this modal and continue using the app'
: 'Pressing the button will download the specified model to your device.'}
</p>
</div>
</form>
</Form>
);
}