File size: 14,547 Bytes
b0b150b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

import React, { useState, useRef, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAgents } from '../contexts/AgentContext';
import client, { getPromptTemplates, analyzePrompt } from '../api/client';
import {
    Box,
    Typography,
    TextField,
    Button,
    Paper,
    CircularProgress,
    Alert,
    List,
    ListItem,
    ListItemIcon,
    ListItemText,
    IconButton,
    Chip,
    Grid,
    Card,
    CardContent,
    CardActionArea,
    Divider
} from '@mui/material';
import AutoFixHighIcon from '@mui/icons-material/AutoFixHigh';
import CloudUploadIcon from '@mui/icons-material/CloudUpload';
import InsertDriveFileIcon from '@mui/icons-material/InsertDriveFile';
import DeleteIcon from '@mui/icons-material/Delete';
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import DiamondIcon from '@mui/icons-material/Diamond';

const AgentCreation = () => {
    const navigate = useNavigate();
    const { fetchAgents } = useAgents();
    const fileInputRef = useRef(null);

    const [name, setName] = useState('');
    const [prompt, setPrompt] = useState('');
    const [files, setFiles] = useState([]);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState('');

    // Prompt templates
    const [templates, setTemplates] = useState([]);
    const [selectedTemplate, setSelectedTemplate] = useState(null);

    // Prompt analysis
    const [analyzing, setAnalyzing] = useState(false);
    const [analysis, setAnalysis] = useState(null);

    // Load templates on mount
    useEffect(() => {
        loadTemplates();
    }, []);

    const loadTemplates = async () => {
        try {
            const response = await getPromptTemplates();
            if (response.templates) {
                setTemplates(response.templates);
            }
        } catch (err) {
            console.error('Failed to load templates:', err);
        }
    };

    const handleTemplateSelect = (template) => {
        setSelectedTemplate(template);
        setPrompt(template.template);
        // Auto-analyze when template is selected
        handleAnalyzePrompt(template.template);
    };

    const handleAnalyzePrompt = async (promptText = prompt) => {
        if (!promptText || promptText.length < 20) return;

        setAnalyzing(true);
        try {
            const response = await analyzePrompt(promptText);
            if (response.analysis) {
                setAnalysis(response.analysis);
                // Auto-suggest agent name if empty
                if (!name && response.analysis.suggested_name) {
                    setName(response.analysis.suggested_name.toLowerCase().replace(/\s+/g, '_'));
                }
            }
        } catch (err) {
            console.error('Failed to analyze prompt:', err);
        } finally {
            setAnalyzing(false);
        }
    };

    const handleFileSelect = (e) => {
        const selectedFiles = Array.from(e.target.files);
        setFiles(prev => [...prev, ...selectedFiles]);
    };

    const handleRemoveFile = (index) => {
        setFiles(prev => prev.filter((_, i) => i !== index));
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        setLoading(true);
        setError('');

        try {
            if (files.length === 0) {
                setError('Please upload at least one knowledge file');
                setLoading(false);
                return;
            }

            // Create FormData for file upload
            const formData = new FormData();
            formData.append('agent_name', name);
            formData.append('system_prompt', prompt);
            files.forEach(file => formData.append('files', file));

            // Call the Phase 2 compile API
            const response = await client.post('/api/compile/', formData, {
                headers: { 'Content-Type': 'multipart/form-data' }
            });

            // Refresh agents list and navigate
            await fetchAgents();
            navigate(`/compile/${response.data.agent_name}`);
        } catch (err) {
            const message = err.response?.data?.detail || 'Failed to create agent';
            setError(message);
        } finally {
            setLoading(false);
        }
    };

    return (
        <Box maxWidth="lg" mx="auto" mt={4} px={2}>
            <Grid container spacing={3}>
                {/* Left Column - Templates */}
                <Grid item xs={12} md={4}>
                    <Paper sx={{ p: 3, height: '100%' }}>
                        <Typography variant="h6" gutterBottom sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                            <DiamondIcon color="primary" />
                            Prompt Templates
                        </Typography>
                        <Typography variant="body2" color="text.secondary" mb={2}>
                            Select a template to get started quickly
                        </Typography>

                        <Box sx={{ maxHeight: 400, overflowY: 'auto' }}>
                            {templates.map((template, index) => (
                                <Card
                                    key={index}
                                    sx={{
                                        mb: 1,
                                        border: selectedTemplate?.name === template.name ? 2 : 0,
                                        borderColor: 'primary.main'
                                    }}
                                >
                                    <CardActionArea onClick={() => handleTemplateSelect(template)}>
                                        <CardContent sx={{ py: 1.5 }}>
                                            <Box display="flex" justifyContent="space-between" alignItems="center">
                                                <Typography variant="subtitle2">{template.name}</Typography>
                                                {selectedTemplate?.name === template.name && (
                                                    <CheckCircleIcon color="primary" fontSize="small" />
                                                )}
                                            </Box>
                                            <Chip
                                                label={template.domain}
                                                size="small"
                                                sx={{ mt: 0.5 }}
                                            />
                                        </CardContent>
                                    </CardActionArea>
                                </Card>
                            ))}
                        </Box>
                    </Paper>
                </Grid>

                {/* Right Column - Form */}
                <Grid item xs={12} md={8}>
                    <Paper sx={{ p: 4 }}>
                        <Box display="flex" alignItems="center" gap={2} mb={3}>
                            <AutoFixHighIcon color="primary" sx={{ fontSize: 32 }} />
                            <Typography variant="h5" fontWeight="bold">
                                Create New Agent
                            </Typography>
                        </Box>

                        {error && <Alert severity="error" sx={{ mb: 3 }}>{error}</Alert>}

                        <form onSubmit={handleSubmit}>
                            <TextField
                                fullWidth
                                label="Agent Name"
                                placeholder="e.g. medical_assistant"
                                value={name}
                                onChange={(e) => setName(e.target.value)}
                                margin="normal"
                                required
                                helperText="Use lowercase letters and underscores"
                            />

                            <TextField
                                fullWidth
                                label="System Prompt"
                                placeholder="You are a helpful AI assistant specialized in..."
                                value={prompt}
                                onChange={(e) => setPrompt(e.target.value)}
                                onBlur={() => handleAnalyzePrompt()}
                                margin="normal"
                                required
                                multiline
                                rows={4}
                            />

                            {/* Analysis Results */}
                            {analyzing && (
                                <Box display="flex" alignItems="center" gap={1} mt={1}>
                                    <CircularProgress size={16} />
                                    <Typography variant="body2" color="text.secondary">
                                        Analyzing prompt...
                                    </Typography>
                                </Box>
                            )}

                            {analysis && !analyzing && (
                                <Alert severity="info" sx={{ mt: 2 }}>
                                    <Typography variant="subtitle2" gutterBottom>
                                        Detected Domain: <strong>{analysis.domain}</strong>
                                    </Typography>
                                    {analysis.capabilities && analysis.capabilities.length > 0 && (
                                        <Box display="flex" gap={0.5} flexWrap="wrap" mt={1}>
                                            {analysis.capabilities.slice(0, 5).map((cap, i) => (
                                                <Chip key={i} label={cap} size="small" variant="outlined" />
                                            ))}
                                        </Box>
                                    )}
                                </Alert>
                            )}

                            <Divider sx={{ my: 3 }} />

                            {/* File Upload Section */}
                            <Box>
                                <Typography variant="subtitle1" gutterBottom>
                                    Knowledge Files *
                                </Typography>

                                <input
                                    type="file"
                                    ref={fileInputRef}
                                    onChange={handleFileSelect}
                                    style={{ display: 'none' }}
                                    multiple
                                    accept=".csv,.pdf,.docx,.txt,.json"
                                />

                                <Button
                                    variant="outlined"
                                    startIcon={<CloudUploadIcon />}
                                    onClick={() => fileInputRef.current?.click()}
                                    sx={{ mb: 2 }}
                                >
                                    Upload Files
                                </Button>

                                <Box display="flex" gap={1} flexWrap="wrap" mb={1}>
                                    <Chip label="CSV" size="small" variant="outlined" />
                                    <Chip label="PDF" size="small" variant="outlined" />
                                    <Chip label="DOCX" size="small" variant="outlined" />
                                    <Chip label="TXT" size="small" variant="outlined" />
                                    <Chip label="JSON" size="small" variant="outlined" />
                                </Box>

                                {files.length > 0 && (
                                    <List dense>
                                        {files.map((file, index) => (
                                            <ListItem
                                                key={index}
                                                secondaryAction={
                                                    <IconButton
                                                        edge="end"
                                                        onClick={() => handleRemoveFile(index)}
                                                        size="small"
                                                    >
                                                        <DeleteIcon />
                                                    </IconButton>
                                                }
                                            >
                                                <ListItemIcon>
                                                    <InsertDriveFileIcon />
                                                </ListItemIcon>
                                                <ListItemText
                                                    primary={file.name}
                                                    secondary={`${(file.size / 1024).toFixed(1)} KB`}
                                                />
                                            </ListItem>
                                        ))}
                                    </List>
                                )}
                            </Box>

                            <Box mt={3} display="flex" gap={2}>
                                <Button
                                    variant="contained"
                                    type="submit"
                                    size="large"
                                    disabled={loading || !name || !prompt || files.length === 0}
                                >
                                    {loading ? <CircularProgress size={24} /> : 'Create & Compile Agent'}
                                </Button>
                                <Button
                                    variant="outlined"
                                    onClick={() => navigate('/dashboard')}
                                    disabled={loading}
                                >
                                    Cancel
                                </Button>
                            </Box>
                        </form>
                    </Paper>
                </Grid>
            </Grid>
        </Box>
    );
};

export default AgentCreation;