forked from sonigeez/mac-computer-use
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
413 lines (366 loc) · 9.87 KB
/
script.js
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
const messageInput = document.querySelector(".message-input");
const sendButton = document.querySelector(".send-button");
const chatMessages = document.querySelector(".chat-messages");
const pushToTalkButton = document.querySelector(".push-to-talk");
const conversationHistory = [];
let mediaRecorder;
let isRecording = false;
let audioChunks = [];
const tools = [
{
type: "computer_20241022",
name: "computer",
display_width_px: 1440,
display_height_px: 768,
display_number: 1,
},
];
async function initializeRecording() {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
mediaRecorder = new MediaRecorder(stream);
mediaRecorder.ondataavailable = async (event) => {
if (event.data.size > 0) {
const reader = new FileReader();
reader.readAsDataURL(event.data);
reader.onloadend = async () => {
try {
const response = await fetch(
"https://api.deepgram.com/v1/listen?model=nova-2&smart_format=true",
{
method: "POST",
headers: {
Authorization: "Token DEEPGRAM_API_KEY",
"Content-Type": "audio/wav",
},
body: event.data,
},
);
const data = await response.json();
const transcript =
data.results.channels[0].alternatives[0].transcript;
messageInput.value = transcript;
sendMessage();
} catch (error) {
console.error("Error transcribing audio:", error);
}
};
}
};
} catch (error) {
console.error("Error accessing microphone:", error);
}
}
pushToTalkButton.addEventListener("mousedown", () => {
if (!mediaRecorder) {
initializeRecording().then(() => {
startRecording();
});
} else {
startRecording();
}
});
pushToTalkButton.addEventListener("mouseup", () => {
stopRecording();
});
pushToTalkButton.addEventListener("mouseleave", () => {
if (isRecording) {
stopRecording();
}
});
function startRecording() {
if (mediaRecorder && mediaRecorder.state === "inactive") {
mediaRecorder.start();
isRecording = true;
pushToTalkButton.classList.add("recording");
}
}
function stopRecording() {
if (mediaRecorder && mediaRecorder.state === "recording") {
mediaRecorder.stop();
isRecording = false;
pushToTalkButton.classList.remove("recording");
}
}
async function sendMessage() {
const message = messageInput.value.trim();
if (!message) return;
addMessageToChat(message, "sent");
conversationHistory.push({
role: "user",
content: [{ type: "text", text: message }],
});
const loadingElement = addMessageToChat("Thinking...", "received loading");
connectWebSocket();
try {
await processConversation();
} catch (error) {
console.error("Error:", error);
addMessageToChat(
"Sorry, there was an error processing your message.",
"received",
);
} finally {
removeMessageFromChat(loadingElement);
resetInputState();
}
}
async function processConversation() {
let loadingElement = null;
while (true) {
const response = await callClaudeAPI(conversationHistory);
console.log("Response:", response);
if (response.content) {
if (response.content.length > 0) {
if (response.content[0].type === "text") {
playAudio(response.content[0].text);
}
}
}
if (loadingElement) {
removeMessageFromChat(loadingElement);
}
const assistantMessage = response.content || response.text;
if (!assistantMessage) {
throw new Error("Invalid response from API");
}
let hasToolUse = false;
if (Array.isArray(assistantMessage)) {
for (const contentBlock of assistantMessage) {
if (contentBlock.type === "text") {
addMessageToChat(contentBlock.text, "received");
conversationHistory.push({
role: "assistant",
content: [contentBlock],
});
} else if (contentBlock.type === "tool_use") {
hasToolUse = true;
conversationHistory.push({
role: "assistant",
content: [contentBlock],
});
const toolResult = await handleToolUse(contentBlock);
conversationHistory.push({ role: "user", content: [toolResult] });
loadingElement = addMessageToChat(
"Processing tool result...",
"received loading",
);
}
}
} else {
addMessageToChat(assistantMessage, "received");
conversationHistory.push({
role: "assistant",
content: [{ type: "text", text: assistantMessage }],
});
}
if (!hasToolUse) {
break;
}
}
}
async function callClaudeAPI(conversation) {
console.log(
"Sending API request to Claude with conversation history:",
conversation,
);
const response = await fetch("https://api.anthropic.com/v1/messages", {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-api-key": "CLAUDE_API_KEY",
"anthropic-version": "2023-06-01",
"anthropic-dangerous-direct-browser-access": "true",
"anthropic-beta": "computer-use-2024-10-22",
},
body: JSON.stringify({
model: "claude-3-5-sonnet-20241022",
max_tokens: 1024,
tools: tools,
messages: conversation,
}),
});
if (!response.ok) {
console.error("API request failed with status:", response.status);
throw new Error("API request failed");
}
const data = await response.json();
console.log("Claude API response data:", data);
if (data.content || data.text) {
return data;
}
throw new Error("Invalid response structure");
}
async function handleToolUse(toolUse) {
const toolInput = toolUse.input;
const toolName = toolUse.name;
const toolUseId = toolUse.id;
try {
console.log("Processing tool use request:", toolInput);
const toolResultContent = [];
let isError = false;
if (toolName === "computer") {
console.log("Processing computer tool use request:", toolInput);
const computerToolResult = window.api.computerTool(
toolInput.action,
toolInput.text,
toolInput.coordinate,
);
console.log("Computer tool result:", computerToolResult);
toolResultContent.push({
type: "text",
text: "task done",
});
} else {
isError = true;
toolResultContent.push({
type: "text",
text: `Error: Unknown tool ${toolName}`,
});
}
return {
type: "tool_result",
content: toolResultContent,
tool_use_id: toolUseId,
is_error: isError,
};
} catch (error) {
console.error("Tool use action failed:", error);
return {
type: "tool_result",
content: [{ type: "text", text: `Error: ${error.message}` }],
tool_use_id: toolUseId,
is_error: true,
};
}
}
const config = {
USER_ID: "",
API_KEY: "",
MODEL: "Play3.0-mini",
};
async function getAuthenticatedWebSocketUrl() {
const url = "https://api.play.ai/api/v1/tts/auth";
const headers = {
Authorization: `Bearer ${config.API_KEY}`,
"X-User-Id": config.USER_ID,
"Content-Type": "application/json",
};
const response = await fetch(url, {
method: "POST",
headers: headers,
});
if (!response.ok) {
throw new Error(
`Failed to get authenticated websocket URL: ${response.status} ${response.statusText}`,
);
}
const result = await response.json();
return result[config.MODEL].webSocketUrl;
}
let wsUrl = "";
getAuthenticatedWebSocketUrl().then((url) => {
wsUrl = url;
console.log(wsUrl);
});
let socket;
function connectWebSocket() {
return new Promise((resolve, reject) => {
socket = new WebSocket(wsUrl);
socket.onmessage = async (event) => {
console.log("Received message from WebSocket:", event.data);
if (typeof event.data === "string") {
try {
const metadata = JSON.parse(event.data);
if (metadata.request_id) {
const audioBlob = new Blob(audioChunks, { type: "audio/wav" });
const audioUrl = URL.createObjectURL(audioBlob);
const audio = new Audio(audioUrl);
audio.onended = () => {
URL.revokeObjectURL(audioUrl);
};
audio.play();
audioChunks = [];
}
} catch (e) {
console.error("Error parsing message:", e);
}
} else if (event.data instanceof Blob) {
audioChunks.push(event.data);
}
};
socket.onopen = () => {
console.log("WebSocket connection established");
resolve(socket);
};
socket.onerror = (error) => {
console.error("WebSocket error:", error);
reject(error);
};
});
}
function generateRandomHex(length) {
return Array.from({ length }, () =>
Math.floor(Math.random() * 16).toString(16),
).join("");
}
async function playAudio(text) {
console.log("Sending text to WebSocket:", text);
if (socket && socket.readyState === WebSocket.OPEN) {
currentRequestId = generateRandomHex(16);
const command = {
text: text,
voice:
"s3://voice-cloning-zero-shot/775ae416-49bb-4fb6-bd45-740f205d20a1/jennifersaad/manifest.json",
request_id: currentRequestId,
speed: 1.6,
};
socket.send(JSON.stringify(command));
} else {
socket = await connectWebSocket();
currentRequestId = generateRandomHex(16);
const command = {
text: text,
voice:
"s3://voice-cloning-zero-shot/775ae416-49bb-4fb6-bd45-740f205d20a1/jennifersaad/manifest.json",
request_id: currentRequestId,
speed: 1.6,
};
socket.send(JSON.stringify(command));
}
}
function addMessageToChat(content, className) {
const messageElement = document.createElement("div");
messageElement.className = `message ${className}`;
if (typeof content === "string") {
messageElement.textContent = content;
} else if (Array.isArray(content)) {
for (const block of content) {
if (block.type === "text") {
const textElement = document.createElement("p");
textElement.textContent = block.text;
messageElement.appendChild(textElement);
}
}
}
chatMessages.appendChild(messageElement);
chatMessages.scrollTop = chatMessages.scrollHeight;
return messageElement;
}
function removeMessageFromChat(element) {
if (element?.parentNode) {
element.parentNode.removeChild(element);
}
}
function resetInputState() {
messageInput.value = "";
messageInput.disabled = false;
sendButton.disabled = false;
messageInput.focus();
}
sendButton.addEventListener("click", sendMessage);
messageInput.addEventListener("keypress", (e) => {
if (e.key === "Enter") {
sendMessage();
}
});