Skip to content

Commit

Permalink
some cleanups
Browse files Browse the repository at this point in the history
- the input form isn't dependent on the user
- clean up some types
- user hoisted to module scope
  • Loading branch information
threepointone committed Feb 14, 2024
1 parent d380c6e commit b60ead6
Show file tree
Hide file tree
Showing 11 changed files with 86 additions and 50 deletions.
2 changes: 1 addition & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ module.exports = {
"plugin:react-hooks/recommended",
"plugin:deprecation/recommended",
],
ignorePatterns: ["node_modules", ".eslintrc.js", "*.d.ts", "public/dist"],
ignorePatterns: ["node_modules", ".eslintrc.js", "*.d.ts", "**/public/dist"],
rules: {
"@typescript-eslint/consistent-type-imports": "error",
"@typescript-eslint/return-await": "error",
Expand Down
11 changes: 11 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"configurations": [
{
"type": "node",
"request": "attach",
"name": "PartyKit debugger",
"address": "localhost",
"port": 9229
}
]
}
11 changes: 11 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"files.associations": {
"partykit.json": "jsonc"
},
"json.schemas": [
{
"fileMatch": ["partykit.json"],
"url": "https://www.partykit.io/schema.json"
}
]
}
2 changes: 1 addition & 1 deletion templates/chat-room/.env.example
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
OPENAI_API_KEY=sk-
OPENAI_API_ORGANIZATION=org-
OPENAI_API_ORGANIZATION=
11 changes: 11 additions & 0 deletions templates/chat-room/.vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"configurations": [
{
"type": "node",
"request": "attach",
"name": "PartyKit debugger",
"address": "localhost",
"port": 9229
}
]
}
11 changes: 11 additions & 0 deletions templates/chat-room/.vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"files.associations": {
"partykit.json": "jsonc"
},
"json.schemas": [
{
"fileMatch": ["partykit.json"],
"url": "https://www.partykit.io/schema.json"
}
]
}
24 changes: 9 additions & 15 deletions templates/chat-room/app/components/AddMessageForm.tsx
Original file line number Diff line number Diff line change
@@ -1,37 +1,31 @@
import styles from "./AddMessageForm.module.css";
import { useState } from "react";
import type { Message, User } from "../../party/shared";
import { createMessage } from "../../party/shared";
import { useRef } from "react";

export default function AddMessageForm(props: {
addMessage: (message: Message) => void;
user: User | null;
onSubmit: (message: string) => void;
}) {
const [message, setMessage] = useState("");
const inputRef = useRef<HTMLInputElement>(null);

const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const message = inputRef.current!.value.trim();
if (!message) return;
if (!props.user) return;
props.addMessage(createMessage(props.user, message));
setMessage("");
props.onSubmit(message);
inputRef.current!.value = "";
};

const disabled = !props.user;

return (
<form className={styles.form} onSubmit={handleSubmit}>
<input
ref={inputRef}
type="text"
name="message"
defaultValue=""
placeholder="Your message..."
value={message}
className={styles.input}
onChange={(e) => setMessage(e.target.value)}
autoFocus
disabled={disabled}
/>
<button className={styles.button} type="submit" disabled={disabled}>
<button className={styles.button} type="submit">
Send
</button>
</form>
Expand Down
42 changes: 20 additions & 22 deletions templates/chat-room/app/components/ChatRoom.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import styles from "./ChatRoom.module.css";
import { useState, useMemo } from "react";
//import { useUser } from "~/providers/user-context";
import type { Message, User } from "../../party/shared";
import { useState } from "react";
import { createMessage, type Message, type User } from "../../party/shared";
import AddMessageForm from "./AddMessageForm";
import MessageList from "./MessageList";
import usePartySocket from "partysocket/react";

function getRandomUserName() {
function getRandomUser(): User {
const animals = [
"Ant",
"Bear",
Expand All @@ -22,18 +21,19 @@ function getRandomUserName() {
"Tiger",
];

return `Anonymous ${animals[Math.floor(Math.random() * animals.length)]}`;
return {
name: `Anonymous ${animals[Math.round(Math.random() * animals.length)]}`,
};
}

export default function ChatRoom(props: { host?: string; roomName: string }) {
// in production, we'd get the user from the server
// but for now, we'll just generate a random name
const user = getRandomUser();

export default function ChatRoom(props: { roomName: string }) {
const [messages, setMessages] = useState<Message[]>([]);
const { user } = {
user: {
name: useMemo(() => getRandomUserName(), []),
} as User,
};

const handleUpdate = (prevMessages: Message[], message: Message) => {
function handleUpdate(prevMessages: Message[], message: Message) {
// If message.id is already in prevMessages, replace it
// If not, add it to the end
const index = prevMessages.findIndex((m) => m.id === message.id);
Expand All @@ -43,15 +43,12 @@ export default function ChatRoom(props: { host?: string; roomName: string }) {
message,
...prevMessages.slice(index + 1),
];
} else {
return [...prevMessages, message];
}
}

return [...prevMessages, message];
};

// Imported like:
// import usePartySocket from "partysocket/react";
const socket = usePartySocket({
host: props.host, // defaults to window.location.host if not set
//party: "main", -- defaults to "main"
room: props.roomName,
onMessage(evt) {
Expand All @@ -63,16 +60,17 @@ export default function ChatRoom(props: { host?: string; roomName: string }) {
}
},
});
console.log("socket", socket.id);
const addMessage = (message: Message) => {

function onSubmit(text: string) {
const message = createMessage(user, text);
setMessages((prevMessages) => [...prevMessages, message]);
socket.send(JSON.stringify({ type: "message", message }));
};
}

return (
<div className={styles.chatRoom}>
<MessageList user={user} messages={messages} />
<AddMessageForm addMessage={addMessage} user={user} />
<AddMessageForm onSubmit={onSubmit} />
</div>
);
}
2 changes: 1 addition & 1 deletion templates/chat-room/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"version": "0.0.0",
"private": true,
"scripts": {
"dev": "partykit dev",
"dev": "partykit dev --live",
"deploy": "partykit deploy"
},
"dependencies": {
Expand Down
13 changes: 7 additions & 6 deletions templates/chat-room/party/openai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@ export async function getChatCompletionResponse(
messages: OpenAIMessage[],
onTokenCallback: (token: string) => void
) {
if (!process.env.OPENAI_API_ORGANIZATION) {
console.info(
"No OPENAI_API_ORGANIZATION set, usage will count against the default key owner"
);
}
// // If no organization is set, usage will count against the default key owner
// if (!process.env.OPENAI_API_ORGANIZATION) {
// console.info(
// "No OPENAI_API_ORGANIZATION set, usage will count against the default key owner"
// );
// }

const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
Expand All @@ -26,7 +27,7 @@ export async function getChatCompletionResponse(
role: "system",
content:
"You are a helpful AI assistant. Your responses are always accurate and extremely brief.",
} as OpenAIMessage,
} satisfies OpenAIMessage,
...messages,
];

Expand Down
7 changes: 3 additions & 4 deletions templates/chat-room/party/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ export default class ChatServer implements Party.Server {
ai: Ai;

constructor(public room: Party.Room) {
this.messages = [];
this.ai = new Ai(room.context.ai);
}

Expand Down Expand Up @@ -65,7 +64,7 @@ export default class ChatServer implements Party.Server {
async replyWithLlama() {
// 1. Setup
const messages = this.messages.map((msg) => {
return { role: msg.role, content: msg.body } as Message; //as OpenAIMessage;
return { role: msg.role, content: msg.body };
});
const aiMsg = createMessage(AI_USER, "Thinking...", "assistant");
this.messages.push(aiMsg);
Expand All @@ -76,11 +75,11 @@ export default class ChatServer implements Party.Server {
role: "system",
content:
"You are a helpful AI assistant. Your responses are always accurate and extremely brief.",
} as any, //as OpenAIMessage,
},
...messages,
];
const stream = await this.ai.run("@cf/meta/llama-2-7b-chat-int8", {
messages: prompt as any,
messages: prompt,
stream: true,
});
const eventStream = stream
Expand Down

0 comments on commit b60ead6

Please sign in to comment.