-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchat.html
More file actions
205 lines (182 loc) · 6.95 KB
/
Copy pathchat.html
File metadata and controls
205 lines (182 loc) · 6.95 KB
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OpenRouter Auth and Chat</title>
<style>
#chatBox {
width: 100%;
height: 300px;
border: 1px solid #ccc;
padding: 10px;
overflow-y: auto;
margin-bottom: 10px;
}
#userInput {
width: calc(100% - 100px);
}
#sendButton {
width: 80px;
}
</style>
</head>
<body>
<button id="connectButton">Connect to OpenRouter</button>
<button id="clearChatButton">Clear Chat</button>
<div id="chatBox"></div>
<input type="text" id="userInput" placeholder="Type a message...">
<button id="sendButton">Send</button>
<script>
function generateRandomString(length) {
const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~';
let randomString = '';
const array = new Uint8Array(length);
window.crypto.getRandomValues(array);
for (let i = 0; i < length; i++) {
randomString += charset[array[i] % charset.length];
}
return randomString;
}
async function sha256CodeChallenge(input) {
const encoder = new TextEncoder();
const data = encoder.encode(input);
const hash = await crypto.subtle.digest('SHA-256', data);
return btoa(String.fromCharCode.apply(null, new Uint8Array(hash)))
.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
async function sendChatCompletion(apiKey, messages) {
const response = await fetch("https://openrouter.ai/api/v1/chat/completions", {
method: "POST",
headers: {
"Authorization": `Bearer ${apiKey}`,
"HTTP-Referer": `https://versabot.ai/pixie`,
"X-Title": `OpenPixie`,
"Content-Type": "application/json"
},
body: JSON.stringify({
"model": "openai/gpt-4",
"messages": messages,
"stream": true
})
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
const reader = response.body.getReader();
const decoder = new TextDecoder('utf-8');
let chatData = '';
let fullResponse = '';
document.getElementById('chatBox').innerHTML += `<p><strong>Assistant:</strong></p>`;
while (true) {
const { done, value } = await reader.read();
if (done) break;
chatData += decoder.decode(value, { stream: true });
if (chatData.endsWith('\n')) {
fullResponse += parseDeltas(chatData);
chatData = '';
}
}
let chatHistory = JSON.parse(localStorage.getItem('chatHistory')) || [];
chatHistory.push({ sender: 'Assistant', message: fullResponse.trim() });
localStorage.setItem('chatHistory', JSON.stringify(chatHistory));
updateChatBox();
}
function parseDeltas(data) {
const chatBox = document.getElementById('chatBox');
const lines = data.split('\n').filter(line => line.startsWith('data: '));
let responseChunk = '';
lines.forEach(line => {
const json = line.replace('data: ', '');
if (json !== '[DONE]') {
const parsedJson = JSON.parse(json);
if (parsedJson.choices && parsedJson.choices[0].delta && parsedJson.choices[0].delta.content) {
const content = parsedJson.choices[0].delta.content;
chatBox.innerHTML += content;
responseChunk += content;
}
}
});
chatBox.scrollTop = chatBox.scrollHeight;
return responseChunk;
}
function updateChatBox() {
const chatBox = document.getElementById('chatBox');
const chatHistory = JSON.parse(localStorage.getItem('chatHistory')) || [];
chatBox.innerHTML = chatHistory.map(entry => `<p><strong>${entry.sender}:</strong></p> ${entry.message}`).join('');
chatBox.scrollTop = chatBox.scrollHeight;
}
document.getElementById('connectButton').addEventListener('click', async () => {
let codeVerifier = generateRandomString(128);
sessionStorage.setItem('code_verifier', codeVerifier);
const callbackUrl = window.location.origin + window.location.pathname;
const codeChallenge = await sha256CodeChallenge(codeVerifier);
const authUrl = `https://openrouter.ai/auth?callback_url=${encodeURIComponent(callbackUrl)}&code_challenge=${codeChallenge}&code_challenge_method=S256`;
window.location.href = authUrl;
});
document.getElementById('sendButton').addEventListener('click', async () => {
const userInput = document.getElementById('userInput').value;
document.getElementById('userInput').value = '';
const apiKey = sessionStorage.getItem('api_key');
if (!apiKey) {
alert('Please connect to OpenRouter first.');
return;
}
let chatHistory = JSON.parse(localStorage.getItem('chatHistory')) || [];
chatHistory.push({ sender: 'You', message: userInput });
localStorage.setItem('chatHistory', JSON.stringify(chatHistory));
updateChatBox();
const messages = chatHistory.map(entry => {
return { role: entry.sender === 'You' ? 'user' : 'assistant', content: entry.message };
});
messages.unshift({ role: 'system', content: 'You are a helpful assistant.' });
try {
await sendChatCompletion(apiKey, messages);
} catch (error) {
chatHistory = JSON.parse(localStorage.getItem('chatHistory')) || [];
chatHistory.push({ sender: 'Error', message: error.message });
localStorage.setItem('chatHistory', JSON.stringify(chatHistory));
updateChatBox();
}
});
document.getElementById('clearChatButton').addEventListener('click', () => {
localStorage.removeItem('chatHistory');
updateChatBox();
});
(async () => {
const urlParams = new URLSearchParams(window.location.search);
const authCode = urlParams.get('code');
let codeVerifier = sessionStorage.getItem('code_verifier');
if (authCode) {
fetch('https://openrouter.ai/api/v1/auth/keys', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
code: authCode,
code_verifier: codeVerifier,
code_challenge_method: 'S256'
})
})
.then(response => response.json())
.then(data => {
localStorage.removeItem('chatHistory');
alert('API Key Received: ' + data.key);
sessionStorage.setItem('api_key', data.key);
sessionStorage.removeItem('code_verifier');
document.getElementById('connectButton').style.display = 'none';
})
.catch((error) => {
alert('Error: ' + error);
sessionStorage.removeItem('code_verifier');
});
}
if (sessionStorage.getItem('api_key')) {
document.getElementById('connectButton').style.display = 'none';
}
updateChatBox();
})();
</script>
</body>
</html>