Created
September 17, 2024 12:09
-
-
Save charl-kruger/df461db95f98667029515592528ff4d3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { Ai } from "partykit-ai"; | |
| import type * as Party from "partykit/server"; | |
| type MessageTypes = 'initialize' | 'fingerprint.get' | 'fingerprint.set' | 'fingerprint.set.success'; | |
| export default class Server implements Party.Server { | |
| ai: Ai; | |
| constructor(public room: Party.Room) { | |
| this.ai = new Ai(room.context.ai); | |
| } | |
| onConnect(conn: Party.Connection, ctx: Party.ConnectionContext) { | |
| // A websocket just connected! | |
| console.log( | |
| `Connected: | |
| id: ${conn.id} | |
| room: ${this.room.id} | |
| url: ${new URL(ctx.request.url).pathname}` | |
| ); | |
| // if the connection is allowed, tell the client to initialize | |
| conn.send(JSON.stringify({ | |
| type: "fingerprint.get", | |
| })); | |
| } | |
| async onMessage(message: string, sender: Party.Connection) { | |
| // let's log the message | |
| console.log(`connection ${sender.id} sent message: ${message}`); | |
| const parsedMessage = JSON.parse(message) as { type: MessageTypes, payload?: any }; | |
| if (parsedMessage.type === 'fingerprint.set') { | |
| console.log('we got a fingerprint', parsedMessage.payload); | |
| // Corrected code: pass the payload as 'input' in an options object | |
| const res = await this.ai.run('@cf/baai/bge-base-en-v1.5', { text: parsedMessage.payload }); | |
| console.log('we got a vector', res); | |
| // const myIndex = this.room.context.vectorize.runiquePartyIndex; | |
| // TODO: store the fingerprint | |
| // await this.room.storage.put('fingerprint', parsedMessage.payload); | |
| sender.send(JSON.stringify({ | |
| type: "fingerprint.set.success", | |
| payload: parsedMessage.payload, | |
| })); | |
| } | |
| // as well as broadcast it to all the other connections in the room... | |
| this.room.broadcast( | |
| `${sender.id}: ${message}`, | |
| // ...except for the connection it came from | |
| [sender.id] | |
| ); | |
| } | |
| } | |
| Server satisfies Party.Worker; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment