create-wirejs-app 2.0.135 → 2.0.136-llm

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-wirejs-app",
3
- "version": "2.0.135",
3
+ "version": "2.0.136-llm",
4
4
  "description": "Initializes a wirejs package.",
5
5
  "author": "Jon Wire",
6
6
  "license": "MIT",
@@ -0,0 +1,57 @@
1
+ import {
2
+ AuthenticationApi,
3
+ BackgroundJob,
4
+ RealtimeService,
5
+ User,
6
+ LLM as LLMResource,
7
+ LLMMessage,
8
+ withContext
9
+ } from "wirejs-resources";
10
+
11
+ export type Message = '**start**' | '**end**' | LLMMessage;
12
+
13
+ const llm = new LLMResource('app', 'llm', {
14
+ models: ['claude-haiku', 'llama3.2', 'llama3:8b', 'llama2']
15
+ });
16
+ const llmRealtimeService = new RealtimeService<Message>('app', 'llm');
17
+
18
+ const chatRunner = new BackgroundJob('app', 'chatRunner', {
19
+ handler: async (room: string, history: LLMMessage[]) => {
20
+ await llmRealtimeService.publish(room, [`**start**`]);
21
+ await llm.continueConversation([
22
+ { role: 'system', content: 'You are a helpful (but generally concise) assistant.'},
23
+ ...history
24
+ ], chunk => {
25
+ llmRealtimeService.publish(room, [chunk.message]);
26
+ })
27
+ await llmRealtimeService.publish(room, [`**end**`]);
28
+ }
29
+ });
30
+
31
+
32
+ const assertIsAuthorized = (user: User, room: string) => {
33
+ if (!room.startsWith(`${user.id}/`)) {
34
+ throw new Error("Not authorized");
35
+ }
36
+ }
37
+
38
+ export const LLM = (auth: AuthenticationApi) => withContext(context => ({
39
+ async send(room: string, history: LLMMessage[]) {
40
+ const user = await auth.requireCurrentUser(context);
41
+ assertIsAuthorized(user, room);
42
+ if (!room || !history || !history.length) {
43
+ throw new Error('Room and history are required');
44
+ }
45
+ chatRunner.start(room, history);
46
+ },
47
+ async getRoom(room: string) {
48
+ const user = await auth.requireCurrentUser(context);
49
+ assertIsAuthorized(user, room);
50
+ return llmRealtimeService.getStream(context, room);
51
+ },
52
+ async createRoom() {
53
+ const user = await auth.requireCurrentUser(context);
54
+ const id = crypto.randomUUID();
55
+ return `${user.id}/${id}`;
56
+ }
57
+ }));
@@ -4,10 +4,12 @@ import { Todos } from './apps/todos.js';
4
4
  import { Wiki } from './apps/wiki.js';
5
5
  import { Store } from './apps/store.js';
6
6
  import { Admin } from './apps/admin.js';
7
+ import { LLM } from './apps/llm.js';
7
8
 
8
9
  export type * from './apps/todos.js';
9
10
  export type * from './apps/store.js';
10
11
  export type * from './apps/admin.js';
12
+ export type * from './apps/llm.js';
11
13
 
12
14
  const authService = new AuthenticationService('app', 'core-users');
13
15
 
@@ -17,6 +19,7 @@ export const todos = Todos(auth);
17
19
  export const wiki = Wiki(auth);
18
20
  export const store = Store(auth);
19
21
  export const admin = Admin(auth);
22
+ export const llm = LLM(auth);
20
23
 
21
24
  new Endpoint('app', 'sample-endpoint', {
22
25
  description: "Sample endpoint to show dynamic endpoint creation.",
@@ -12,13 +12,13 @@
12
12
  "dompurify": "^3.2.3",
13
13
  "marked": "^15.0.6",
14
14
  "wirejs-dom": "^1.0.42",
15
- "wirejs-resources": "^0.1.130",
16
- "wirejs-components": "^0.1.73",
17
- "wirejs-module-payments-stripe": "^0.1.24",
18
- "wirejs-web-worker": "^1.0.27"
15
+ "wirejs-resources": "^0.1.131-llm",
16
+ "wirejs-components": "^0.1.74-llm",
17
+ "wirejs-module-payments-stripe": "^0.1.25-llm",
18
+ "wirejs-web-worker": "^1.0.28-llm"
19
19
  },
20
20
  "devDependencies": {
21
- "wirejs-scripts": "^3.0.128",
21
+ "wirejs-scripts": "^3.0.129-llm",
22
22
  "typescript": "^5.7.3"
23
23
  },
24
24
  "scripts": {
@@ -0,0 +1,218 @@
1
+ import { marked } from 'marked';
2
+ import DOMPurify from 'dompurify';
3
+ import { html, id, css, attribute, hydrate, list, text, node } from 'wirejs-dom/v2';
4
+ import { AuthenticatedContent } from 'wirejs-components';
5
+ import { Main } from '../layouts/main.js';
6
+ import { llm, Message } from 'internal-api';
7
+
8
+ const sheet = css`
9
+ .messages {
10
+ height: calc(100vh - 30rem);
11
+ overflow: scroll;
12
+ }
13
+ .flex-row {
14
+ display: flex;
15
+ flex-direction: row;
16
+ }
17
+ .flex-row > textarea {
18
+ margin-right: 10px;
19
+ }
20
+ `;
21
+
22
+ function formatMessage(message: string): string {
23
+ return DOMPurify.sanitize(marked.parse(message) as string);
24
+ }
25
+
26
+ async function Chat() {
27
+ const self = html`<div id='chat'>
28
+ ${sheet}
29
+ <!-- All messages. Markdown formatted. Sanitized. -->
30
+ <div ${id('messageContainer', HTMLDivElement)} class='messages'>
31
+ ${list('messages', (m: Exclude<Message, string>) =>
32
+ html`<div>
33
+ <b>${m.role}</b><br />
34
+ ${formatMessage(m.content)}
35
+ </div>`
36
+ )}
37
+ ${node('pendingMessage', (md) => md ? html`<div style='color: #333;'>
38
+ <b>assistant</b><br />
39
+ ${formatMessage(md || '')}
40
+ </div>` : html`<div></div>`)}
41
+ </div>
42
+
43
+ <!-- New message form -->
44
+ <form ${id('messageForm', HTMLFormElement)}
45
+ onsubmit=${async (event: Event) => {
46
+ event.preventDefault();
47
+ if (!self.activeRoom) {
48
+ self.data.pendingMessage = "<b>Not connected!</b>";
49
+ return;
50
+ }
51
+ self.data.messages.push({
52
+ role: 'user',
53
+ content: self.data.message.value.trim()
54
+ });
55
+ self.data.message.value = '';
56
+ self.data.message.disabled = true;
57
+ self.data.submitButton.disabled = true;
58
+ self.data.message.style.height = 'auto';
59
+ self.data.pendingMessage = '<i>Thinking ...</i>';
60
+ self.autoscroll();
61
+ llm.send(null, self.activeRoom, self.data.messages).catch(error => {
62
+ console.error(error);
63
+ self.data.pendingMessage = '<b>Error. Try again.</b>';
64
+ self.data.message.disabled = false;
65
+ self.data.submitButton.disabled = false;
66
+ });
67
+ }}
68
+ ><div class='flex-row'>
69
+ <textarea
70
+ ${id('message', HTMLTextAreaElement)}
71
+ autocomplete="on"
72
+ autocorrect="on"
73
+ autocapitalize="on"
74
+ type='text'
75
+ style="
76
+ width: calc(100% - 5rem);
77
+ height: auto;
78
+ tab-size: 4;
79
+ "
80
+ oninput=${() => {
81
+ // reset height to auto to calculate scrollHeight correctly
82
+ self.data.message.style.height = 'auto';
83
+ // only then set it to scrollHeight, which will not be based on the raw
84
+ // height of the content, excluding padding, etc.
85
+ self.data.message.style.height = self.data.message.scrollHeight + 'px';
86
+ }}
87
+ onkeydown=${(event: KeyboardEvent) => {
88
+ if (event.key === 'Enter' && !event.shiftKey) {
89
+ event.preventDefault();
90
+ self.data.messageForm.dispatchEvent(new Event('submit'));
91
+ }
92
+ if (event.key === 'Tab') {
93
+ event.preventDefault();
94
+ const textarea = self.data.message;
95
+ const start = textarea.selectionStart;
96
+ const end = textarea.selectionEnd;
97
+ if (start === end) {
98
+ // If no selection, insert a tab at the cursor position
99
+ textarea.value = textarea.value.substring(0, start)
100
+ + '\t' + textarea.value.substring(end);
101
+ textarea.selectionStart = textarea.selectionEnd = start + 1;
102
+ return;
103
+ }
104
+ let lines = textarea.value.split('\n');
105
+ const selectedLines = lines.slice(
106
+ textarea.value.substring(0, start).split('\n').length - 1,
107
+ textarea.value.substring(0, end).split('\n').length
108
+ );
109
+ let updatedLines = [];
110
+ let selectionStartOffset = 0;
111
+ if (event.shiftKey) {
112
+ updatedLines = selectedLines.map(line => line.startsWith('\t') ? line.substring(1) : line);
113
+ selectionStartOffset = -1;
114
+ } else {
115
+ updatedLines = selectedLines.map(line => '\t' + line);
116
+ selectionStartOffset = 1;
117
+ }
118
+ lines.splice(
119
+ start === end ? start : textarea.value.substring(0, start).split('\n').length - 1,
120
+ selectedLines.length,
121
+ ...updatedLines
122
+ );
123
+ textarea.value = lines.join('\n');
124
+ textarea.selectionStart = start + selectionStartOffset;
125
+ textarea.selectionEnd = end + updatedLines.length;
126
+ }
127
+ }}
128
+ ></textarea>
129
+ <input ${id('submitButton', HTMLInputElement)}
130
+ type='submit' value='&gt;' style='width: 2em; height: 2em;' />
131
+ </div></form>
132
+
133
+ <!-- Connection status -->
134
+ <span style='color: var(--color-muted)'>${text('status', 'Connecting ...')}</span>
135
+
136
+ </div>`.extend(() => ({
137
+ activeRoom: undefined as string | undefined,
138
+ isScrolledDownWithinMargin(margin: number) {
139
+ const container = self.data.messageContainer;
140
+ const scrollTop = container.scrollTop;
141
+ const scrollHeight = container.scrollHeight;
142
+ const clientHeight = container.clientHeight;
143
+ return (scrollHeight - (scrollTop + clientHeight)) <= margin;
144
+ },
145
+ autoscroll() {
146
+ const container = self.data.messageContainer;
147
+ container.scrollTop = container.scrollHeight - container.clientHeight;
148
+ },
149
+ disconnect() {
150
+ // no implementation until connected
151
+ },
152
+ async connect() {
153
+ self.activeRoom = await llm.createRoom(null);
154
+ const roomStream = await llm.getRoom(null, self.activeRoom);
155
+ let isThinking = false;
156
+ self.disconnect = roomStream.subscribe({
157
+ onopen() {
158
+ self.data.status = `Connected.`;
159
+ },
160
+ onmessage(message) {
161
+ const startedAtBottom = self.isScrolledDownWithinMargin(50);
162
+ if (message === '**start**') {
163
+ isThinking = true;
164
+ self.data.pendingMessage = '<i>Thinking ...</i>';
165
+ self.data.message.disabled = true;
166
+ self.data.submitButton.disabled = true;
167
+ } else if (message === '**end**') {
168
+ isThinking = false;
169
+ self.data.messages.push({
170
+ role: 'assistant',
171
+ content: self.data.pendingMessage
172
+ });
173
+ self.data.pendingMessage = '';
174
+ self.data.submitButton.disabled = false;
175
+ self.data.message.disabled = false;
176
+ self.data.message.focus();
177
+ } else {
178
+ if (isThinking) {
179
+ self.data.pendingMessage = message.content;
180
+ } else {
181
+ self.data.pendingMessage += message.content;
182
+ }
183
+ isThinking = false;
184
+ }
185
+ if (startedAtBottom) self.autoscroll();
186
+ },
187
+ onclose(reason) {
188
+ if (reason !== 'unsubscribed') {
189
+ self.data.status = 'Disconnected. (Refresh to try reconnecting.)';
190
+ }
191
+ }
192
+ });
193
+ }
194
+ }))
195
+ .onadd(async () => {
196
+ self.connect();
197
+ self.data.message.value = '';
198
+ });
199
+ return self;
200
+ }
201
+
202
+ async function App() {
203
+ return html`<div id='app'>
204
+ ${await AuthenticatedContent({
205
+ authenticated: Chat,
206
+ unauthenticated: () => html`<p>Sign in for the LLM demo.</p>`
207
+ })}
208
+ </div>`;
209
+ }
210
+
211
+ export async function generate() {
212
+ return Main({
213
+ pageTitle: 'LLM Demo',
214
+ content: await App()
215
+ })
216
+ }
217
+
218
+ hydrate('app', App as any);
@@ -13,6 +13,7 @@ export async function generate() {
13
13
  <li><a href='/realtime-test.html'>Realtime Test</a></li>
14
14
  <li><a href='/web-worker-test.html'>Web Worker Test</a></li>
15
15
  <li><a href='/storefront.html'>Storefront</a></li>
16
+ <li><a href='/chatbot.html'>Chatbot</a></li>
16
17
  <li><a href='/admin.html'>Admin</a></li>
17
18
  </ul>
18
19
  </div>`
@@ -104,7 +104,6 @@ async function Chat() {
104
104
 
105
105
  async function App() {
106
106
  return html`<div id='app'>
107
- <h4>Realtime Demo</h4>
108
107
  ${await AuthenticatedContent({
109
108
  authenticated: Chat,
110
109
  unauthenticated: () => html`<p>Sign in for the realtime demo.</p>`
@@ -114,7 +113,7 @@ async function App() {
114
113
 
115
114
  export async function generate() {
116
115
  return Main({
117
- pageTitle: 'Welcome!',
116
+ pageTitle: 'Realtime Demo',
118
117
  content: await App()
119
118
  })
120
119
  }
@@ -4,7 +4,6 @@ import { worker } from 'web-worker';
4
4
 
5
5
  async function App() {
6
6
  return html`<div id='app'>
7
- <h4>Web Worker Demo</h4>
8
7
  <div>${text('status', '...')}</div>
9
8
  <div>Web Worker output: ${text('output', '...')}</div>
10
9
  </div>`.onadd(async self => {
@@ -17,7 +16,7 @@ async function App() {
17
16
 
18
17
  export async function generate() {
19
18
  return Main({
20
- pageTitle: 'Welcome!',
19
+ pageTitle: 'Web Worker Demo',
21
20
  content: await App()
22
21
  })
23
22
  }