File size: 11,955 Bytes
8227e25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html>

<head>
    <title>Chat System with LLM Proxy</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
        }

        .container {
            display: flex;
            gap: 20px;
            height: 90vh;
        }

        .panel {
            flex: 1;
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 15px;
            display: flex;
            flex-direction: column;
        }

        h2 {
            margin-top: 0;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
        }

        .chat-container {
            height: 300px;
            overflow-y: scroll;
            border: 1px solid #eee;
            padding: 10px;
            margin-bottom: 10px;
            flex: 1;
        }

        .input-container {
            display: flex;
            gap: 10px;
        }

        input[type="text"],
        input[type="password"] {
            flex: 1;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        button {
            padding: 8px 15px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        button:hover {
            background-color: #45a049;
        }

        .message {
            margin-bottom: 10px;
            padding: 8px;
            border-radius: 8px;
        }

        .user-message {
            background-color: #e1f5fe;
            align-self: flex-end;
        }

        .assistant-message {
            background-color: #f1f1f1;
        }

        .connection-status {
            color: #666;
            font-size: 0.9em;
            margin-top: 10px;
        }

        .message-entry {
            margin: 5px 0;
            padding: 8px;
            border-radius: 8px;
            background: white;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            font-family: monospace;
        }

        .incoming {
            border-left: 4px solid #4CAF50;
        }

        .outgoing {
            border-left: 4px solid #2196F3;
        }

        .system {
            border-left: 4px solid #9C27B0;
        }

        .error {
            border-left: 4px solid #F44336;
        }

        .message-header {
            display: flex;
            justify-content: space-between;
            font-size: 0.8em;
            color: #666;
            margin-bottom: 4px;
        }

        .tabs {
            display: flex;
            margin-bottom: 15px;
        }

        .tab {
            padding: 10px 20px;
            cursor: pointer;
            border: 1px solid #ddd;
            border-radius: 4px 4px 0 0;
            margin-right: 5px;
        }

        .tab.active {
            background-color: #f1f1f1;
            border-bottom: none;
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
            flex: 1;
            display: flex;
            flex-direction: column;
        }
    </style>
</head>

<body>
    <div class="tabs">
        <div class="tab active" onclick="switchTab('chat')">Chat Client</div>
        <div class="tab" onclick="switchTab('proxy')">Proxy Configuration</div>
    </div>

    <div class="container">
        <!-- Chat Client Panel -->
        <div id="chat-tab" class="tab-content active panel">
            <h2>Chat Client</h2>
            <div id="chat" class="chat-container"></div>
            <div class="input-container">
                <input id="msg" type="text" placeholder="Type your message here...">
                <button onclick="sendMessage()">Send</button>
            </div>
            <div id="client-status" class="connection-status">Connecting...</div>
        </div>

        <!-- Proxy Configuration Panel -->
        <div id="proxy-tab" class="tab-content panel">
            <h2>LLM Proxy Configuration</h2>
            <div style="margin-bottom: 20px;">
                <input type="password" id="apiKey" placeholder="Enter API Key" style="width: 100%;">
                <button onclick="initializeClient()" style="margin-top: 10px;">Fetch Models</button>
            </div>
            <select id="modelSelect" style="width: 100%; margin-bottom: 20px;"></select>
            <div id="systemStatus" class="connection-status"></div>

            <h3>Message Flow</h3>
            <div id="messageFlow"
                style="flex: 1; border: 1px solid #eee; padding: 10px; overflow-y: auto; background: #f9f9f9;">
                <div style="text-align: center; color: #999; margin-bottom: 10px;">Message Flow</div>
            </div>
            <div id="detailedStatus" class="connection-status"></div>
        </div>
    </div>

    <script>
        function showStatus(message, type = 'info') {
            const statusDiv = document.getElementById('systemStatus');
            statusDiv.innerHTML = `<div style="color: ${type === 'error' ? '#F44336' : '#4CAF50'}">${message}</div>`;
            addMessageEntry('system', 'system', 'proxy', message);
        }
        // Tab switching functionality
        function switchTab(tabName) {
            document.querySelectorAll('.tab').forEach(tab => tab.classList.remove('active'));
            document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));

            document.querySelector(`.tab[onclick="switchTab('${tabName}')"]`).classList.add('active');
            document.getElementById(`${tabName}-tab`).classList.add('active');
        }

        // Client WebSocket
        const clientWs = new WebSocket('wss://' + window.location.host + '/ws');
        clientWs.onopen = () => {
            clientWs.send(JSON.stringify({
                source: 'user'
            }));
            document.getElementById('client-status').textContent = 'Connected';
        };
        clientWs.onclose = () => {
            document.getElementById('client-status').textContent = 'Disconnected';
        };
        clientWs.onmessage = e => {
            const msg = JSON.parse(e.data);
            const chatDiv = document.getElementById('chat');
            chatDiv.innerHTML += `<div class="message assistant-message">${msg.content}</div>`;
            chatDiv.scrollTop = chatDiv.scrollHeight;
        };

        function sendMessage() {
            const input = document.getElementById('msg');
            const content = input.value.trim();
            if (content) {
                const message = {
                    content: content,
                    source: 'user',
                    destination: 'proxy',
                    request_id: generateUUID()
                };
                clientWs.send(JSON.stringify(message));

                const chatDiv = document.getElementById('chat');
                chatDiv.innerHTML += `<div class="message user-message">${content}</div>`;
                chatDiv.scrollTop = chatDiv.scrollHeight;

                input.value = '';
            }
        }
        document.getElementById('msg').addEventListener('keypress', function (e) {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });

        // Proxy WebSocket
        let proxyWs = new WebSocket('wss://' + window.location.host + '/ws');
        proxyWs.onopen = () => {
            proxyWs.send(JSON.stringify({
                source: 'proxy'
            }));
            showStatus('Connected to server');
        };
        proxyWs.onclose = () => {
            showStatus('Disconnected from server', 'error');
        };
        proxyWs.onmessage = async e => {
            const msg = JSON.parse(e.data);

            // Display incoming messages
            if (msg.destination === 'proxy') {
                let tools = null
                addMessageEntry('incoming', msg.source, 'proxy', msg.content);
                document.getElementById('detailedStatus').textContent = `Processing ${msg.source} request...`;
                
                try {
                    const response = await fetch("/list-tools");
                    tools = await response.json();
                } catch (error) {
                    console.log(`Failed to fetch tools : ${error}`);
                    tools = null;
                }

                try {
                    if (!agentClient) {
                        throw new Error(
                            "LLM client not initialized. Please enter API key and fetch models first.");
                    }

                    if (!currentModel) {
                        throw new Error("No model selected. Please select a model first.");
                    }

                    let llmResponse = await agentClient.call(
                        currentModel,
                        msg.content,
                        conversationHistory,
                        tools
                    );

                    conversationHistory = llmResponse.history

                    // Display outgoing response
                    addMessageEntry('outgoing', 'proxy', msg.source, llmResponse.response);

                    if(llmResponse.response.tool_calls != null){
                        try {
                            console.log("Calling ....")
                            const toolCalls = await fetch("/call-tools", {
                                method: "POST",
                                headers: {
                                    "Content-Type": "application/json"
                                },
                                body: JSON.stringify({tool_calls: llmResponse.response.tool_calls})
                            })
                            const toolCallsJson = await toolCalls.json()
                            console.log("Succeed !")
                            for(const toolCall of toolCallsJson){
                                conversationHistory.push(toolCall)
                            }

                            llmResponse = await agentClient.call(
                                currentModel,
                                null,
                                conversationHistory,
                                null
                            )

                            conversationHistory = llmResponse.history
                        } catch (error) {
                            throw new Error("Error on calling tools " + error)
                        }
                    }

                    const responseMsg = {
                        request_id: msg.request_id,
                        content: llmResponse.response.content,
                        source: 'proxy',
                        destination: msg.source
                    };
                    proxyWs.send(JSON.stringify(responseMsg));

                    document.getElementById('detailedStatus').textContent = `Response sent to ${msg.source}`;
                } catch (error) {
                    addMessageEntry('error', 'system', 'proxy', `Error: ${error.message}`);
                    const errorResponse = {
                        request_id: msg.request_id,
                        content: `Error: ${error.message}`,
                        source: 'proxy',
                        destination: msg.source
                    };
                    proxyWs.send(JSON.stringify(errorResponse));
                }
            }
        };

        function generateUUID() {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                var r = Math.random() * 16 | 0,
                    v = c == 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
        }
    </script>
    <script src="/static/proxy_llm.js"></script>
</body>

</html>