feat(*): Add websockets via partykit for live notifications of tool usage

This commit is contained in:
Josh Creek
2025-04-21 15:20:32 +01:00
parent 839e1183a6
commit 76fcdac563
19 changed files with 2205 additions and 8 deletions
+9 -1
View File
@@ -1,4 +1,12 @@
AI_FOUNDRY_PROJECT_CONNECTION_STRING=
BING_GROUNDING_CONNECTION_ID=
AI_SEARCH_CONNECTION_ID=
AI_MODEL=gpt-4o
AI_MODEL=gpt-4o
# For production:
VITE_PARTYKIT_BASE_URL=wss://your-partykit-project.partykit.dev
PARTYKIT_BASE_URL=wss://your-partykit-project.partykit.dev
# For local development:
# VITE_PARTYKIT_BASE_URL=ws://127.0.0.1:1999
# PARTYKIT_BASE_URL=ws://127.0.0.1:1999
+49
View File
@@ -97,6 +97,55 @@ pnpm run build
You can preview the production build with `npm run preview`.
## 🕹️ Real-Time Events: PartyKit Setup
This project uses [PartyKit](https://partykit.io/) for real-time tool usage event streaming between the frontend and backend.
### Running PartyKit Locally
1. **Install dependencies** for PartyKit:
```sh
cd partykit
npm install
```
2. **Set up your `.env` file** (in the project root):
```env
VITE_PARTYKIT_BASE_URL=ws://127.0.0.1:1999
PARTYKIT_BASE_URL=ws://127.0.0.1:1999
```
These variables are required for both the SvelteKit frontend and backend to connect to your local PartyKit server.
3. **Start the PartyKit dev server**:
```sh
cd partykit
npm run dev
```
The server will be available at `ws://127.0.0.1:1999/party/<room>`.
4. **Start the SvelteKit frontend** (in a separate terminal):
```sh
pnpm run dev
```
### Deploying PartyKit to Production
1. **Update your `.env` for production**:
```env
VITE_PARTYKIT_BASE_URL=wss://<your-connection-string>.partykit.dev
PARTYKIT_BASE_URL=wss://<your-connection-string>.partykit.dev
```
2. **Deploy PartyKit**:
```sh
cd partykit
npm run deploy
```
Wait for the domain provisioning to complete.
3. **Update your frontend/backend to use the production WebSocket URL** (as above).
### Troubleshooting
- If you see `Invalid URL` errors, make sure your environment variables are set and that you have restarted your dev servers after editing `.env`.
- Always run the PartyKit dev server from the `partykit` directory.
See also `.env.example` for sample configuration.
## 📚 Resources
- [Hack Together: AI Agents Hackathon Introduction & Getting Started](https://www.youtube.com/watch?v=RNphlRKvmJQ)
- [Hack Together: AI Agents Hackathon Building Your Agent](https://www.youtube.com/watch?v=Aq30zfbWNSQ)
+170
View File
@@ -0,0 +1,170 @@
# Logs
logs
_.log
npm-debug.log_
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
# Runtime data
pids
_.pid
_.seed
\*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
\*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
\*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
\*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
.cache
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.\*
.partykit
.DS_Store
+11
View File
@@ -0,0 +1,11 @@
{
"configurations": [
{
"type": "node",
"request": "attach",
"name": "PartyKit debugger",
"address": "localhost",
"port": 9229
}
]
}
+11
View File
@@ -0,0 +1,11 @@
{
"files.associations": {
"partykit.json": "jsonc"
},
"json.schemas": [
{
"fileMatch": ["partykit.json"],
"url": "https://www.partykit.io/schema.json"
}
]
}
+38
View File
@@ -0,0 +1,38 @@
## 🎈 PartyKit Tool Usage Broadcaster
Welcome to the PartyKit Tool Usage Broadcaster
This PartyKit project provides a websocket server for broadcasting tool usage events in real time to your SvelteKit frontend.
## How it works
- The server receives websocket messages (tool usage events) from your backend (e.g., ai.ts)
- It broadcasts each message to all connected clients (e.g., your Svelte frontend)
## Usage
- Your websocket URL will be:
```
wss://<your-partykit-project>.partykit.dev/party/tool-usage-server
```
Replace `<your-partykit-project>` with your deployment name.
- Connect to this URL from both your backend (to send events) and frontend (to receive/display events).
## Developing locally
To start a local development server:
```bash
npm run dev
```
## Deploying
To deploy your PartyKit project:
```bash
npm run deploy
```
This will deploy your project to PartyKit Cloud. You will get a URL you can use to connect to your server.
Refer to our docs for more information: https://github.com/partykit/partykit/blob/main/README.md. For more help, reach out to us on [Discord](https://discord.gg/g5uqHQJc3z), [GitHub](https://github.com/partykit/partykit), or [Twitter](https://twitter.com/partykit_io).
+1264
View File
File diff suppressed because it is too large Load Diff
+16
View File
@@ -0,0 +1,16 @@
{
"name": "partykit",
"version": "0.0.0",
"private": true,
"scripts": {
"dev": "partykit dev --live",
"deploy": "partykit deploy"
},
"dependencies": {
"partysocket": "^1.0.2"
},
"devDependencies": {
"partykit": "^0.0.110",
"typescript": "^5.5.4"
}
}
+10
View File
@@ -0,0 +1,10 @@
{
"$schema": "https://www.partykit.io/schema.json",
"name": "partykit",
"main": "src/server.ts",
"compatibilityDate": "2025-04-21",
"serve": {
"path": "public",
"build": "src/client.ts"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

+29
View File
@@ -0,0 +1,29 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, shrink-to-fit=no"
/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>PartyKit: Everything's better with friends!</title>
<!-- Favicon -->
<link rel="icon" href="/favicon.ico" sizes="any" />
<!-- Primary Meta Tags -->
<meta name="title" content="PartyKit" />
<meta name="description" content="Everything's better with friends!" />
<meta name="author" content="PartyKit" />
<!-- Theme Colour -->
<meta name="theme-color" content="#ffffff" />
<link rel="stylesheet" href="/normalize.css" />
<link rel="stylesheet" href="/dist/client.css" />
</head>
<body>
<div id="app">
<h1>🎈 Welcome to PartyKit!</h1>
</div>
<script type="module" src="/dist/client.js"></script>
</body>
</html>
+351
View File
@@ -0,0 +1,351 @@
/*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */
/* Document
========================================================================== */
/**
* 1. Correct the line height in all browsers.
* 2. Prevent adjustments of font size after orientation changes in iOS.
*/
html {
line-height: 1.15; /* 1 */
-webkit-text-size-adjust: 100%; /* 2 */
}
/* Sections
========================================================================== */
/**
* Remove the margin in all browsers.
*/
body {
margin: 0;
}
/**
* Render the `main` element consistently in IE.
*/
main {
display: block;
}
/**
* Correct the font size and margin on `h1` elements within `section` and
* `article` contexts in Chrome, Firefox, and Safari.
*/
h1 {
font-size: 2em;
margin: 0.67em 0;
}
/* Grouping content
========================================================================== */
/**
* 1. Add the correct box sizing in Firefox.
* 2. Show the overflow in Edge and IE.
*/
hr {
box-sizing: content-box; /* 1 */
height: 0; /* 1 */
overflow: visible; /* 2 */
}
/**
* 1. Correct the inheritance and scaling of font size in all browsers.
* 2. Correct the odd `em` font sizing in all browsers.
*/
pre {
font-family: monospace, monospace; /* 1 */
font-size: 1em; /* 2 */
}
/* Text-level semantics
========================================================================== */
/**
* Remove the gray background on active links in IE 10.
*/
a {
background-color: transparent;
}
/**
* 1. Remove the bottom border in Chrome 57-
* 2. Add the correct text decoration in Chrome, Edge, IE, Opera, and Safari.
*/
abbr[title] {
border-bottom: none; /* 1 */
text-decoration: underline; /* 2 */
text-decoration: underline dotted; /* 2 */
}
/**
* Add the correct font weight in Chrome, Edge, and Safari.
*/
b,
strong {
font-weight: bolder;
}
/**
* 1. Correct the inheritance and scaling of font size in all browsers.
* 2. Correct the odd `em` font sizing in all browsers.
*/
code,
kbd,
samp {
font-family: monospace, monospace; /* 1 */
font-size: 1em; /* 2 */
}
/**
* Add the correct font size in all browsers.
*/
small {
font-size: 80%;
}
/**
* Prevent `sub` and `sup` elements from affecting the line height in
* all browsers.
*/
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sub {
bottom: -0.25em;
}
sup {
top: -0.5em;
}
/* Embedded content
========================================================================== */
/**
* Remove the border on images inside links in IE 10.
*/
img {
border-style: none;
}
/* Forms
========================================================================== */
/**
* 1. Change the font styles in all browsers.
* 2. Remove the margin in Firefox and Safari.
*/
button,
input,
optgroup,
select,
textarea {
font-family: inherit; /* 1 */
font-size: 100%; /* 1 */
line-height: 1.15; /* 1 */
margin: 0; /* 2 */
}
/**
* Show the overflow in IE.
* 1. Show the overflow in Edge.
*/
button,
input {
/* 1 */
overflow: visible;
}
/**
* Remove the inheritance of text transform in Edge, Firefox, and IE.
* 1. Remove the inheritance of text transform in Firefox.
*/
button,
select {
/* 1 */
text-transform: none;
}
/**
* Correct the inability to style clickable types in iOS and Safari.
*/
button,
[type="button"],
[type="reset"],
[type="submit"] {
-webkit-appearance: button;
}
/**
* Remove the inner border and padding in Firefox.
*/
button::-moz-focus-inner,
[type="button"]::-moz-focus-inner,
[type="reset"]::-moz-focus-inner,
[type="submit"]::-moz-focus-inner {
border-style: none;
padding: 0;
}
/**
* Restore the focus styles unset by the previous rule.
*/
button:-moz-focusring,
[type="button"]:-moz-focusring,
[type="reset"]:-moz-focusring,
[type="submit"]:-moz-focusring {
outline: 1px dotted ButtonText;
}
/**
* Correct the padding in Firefox.
*/
fieldset {
padding: 0.35em 0.75em 0.625em;
}
/**
* 1. Correct the text wrapping in Edge and IE.
* 2. Correct the color inheritance from `fieldset` elements in IE.
* 3. Remove the padding so developers are not caught out when they zero out
* `fieldset` elements in all browsers.
*/
legend {
box-sizing: border-box; /* 1 */
color: inherit; /* 2 */
display: table; /* 1 */
max-width: 100%; /* 1 */
padding: 0; /* 3 */
white-space: normal; /* 1 */
}
/**
* Add the correct vertical alignment in Chrome, Firefox, and Opera.
*/
progress {
vertical-align: baseline;
}
/**
* Remove the default vertical scrollbar in IE 10+.
*/
textarea {
overflow: auto;
}
/**
* 1. Add the correct box sizing in IE 10.
* 2. Remove the padding in IE 10.
*/
[type="checkbox"],
[type="radio"] {
box-sizing: border-box; /* 1 */
padding: 0; /* 2 */
}
/**
* Correct the cursor style of increment and decrement buttons in Chrome.
*/
[type="number"]::-webkit-inner-spin-button,
[type="number"]::-webkit-outer-spin-button {
height: auto;
}
/**
* 1. Correct the odd appearance in Chrome and Safari.
* 2. Correct the outline style in Safari.
*/
[type="search"] {
-webkit-appearance: textfield; /* 1 */
outline-offset: -2px; /* 2 */
}
/**
* Remove the inner padding in Chrome and Safari on macOS.
*/
[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
/**
* 1. Correct the inability to style clickable types in iOS and Safari.
* 2. Change font properties to `inherit` in Safari.
*/
::-webkit-file-upload-button {
-webkit-appearance: button; /* 1 */
font: inherit; /* 2 */
}
/* Interactive
========================================================================== */
/*
* Add the correct display in Edge, IE 10+, and Firefox.
*/
details {
display: block;
}
/*
* Add the correct display in all browsers.
*/
summary {
display: list-item;
}
/* Misc
========================================================================== */
/**
* Add the correct display in IE 10+.
*/
template {
display: none;
}
/**
* Add the correct display in IE 10.
*/
[hidden] {
display: none;
}
+40
View File
@@ -0,0 +1,40 @@
import "./styles.css";
import PartySocket from "partysocket";
declare const PARTYKIT_HOST: string;
let pingInterval: ReturnType<typeof setInterval>;
// Let's append all the messages we get into this DOM element
const output = document.getElementById("app") as HTMLDivElement;
// Helper function to add a new line to the DOM
function add(text: string) {
output.appendChild(document.createTextNode(text));
output.appendChild(document.createElement("br"));
}
// A PartySocket is like a WebSocket, except it's a bit more magical.
// It handles reconnection logic, buffering messages while it's offline, and more.
const conn = new PartySocket({
host: PARTYKIT_HOST,
room: "my-new-room",
});
// You can even start sending messages before the connection is open!
conn.addEventListener("message", (event) => {
add(`Received -> ${event.data}`);
});
// Let's listen for when the connection opens
// And send a ping every 2 seconds right after
conn.addEventListener("open", () => {
add("Connected!");
add("Sending a ping every 2 seconds...");
// TODO: make this more interesting / nice
clearInterval(pingInterval);
pingInterval = setInterval(() => {
conn.send("ping");
}, 1000);
});
+18
View File
@@ -0,0 +1,18 @@
import type * as Party from "partykit/server";
export default class Server implements Party.Server {
constructor(readonly room: Party.Room) {}
onConnect(conn: Party.Connection, ctx: Party.ConnectionContext) {
// Log connection details
console.log(
`Connected:\n id: ${conn.id}\n room: ${this.room.id}\n url: ${new URL(ctx.request.url).pathname}`
);
}
onMessage(message: string, sender: Party.Connection) {
// Broadcast the message to all connected clients in the room
this.room.broadcast(message);
}
}
+31
View File
@@ -0,0 +1,31 @@
/*
We've already included normalize.css.
But we'd like a modern looking boilerplate.
Clean type, sans-serif, and a nice color palette.
*/
body {
font-family: sans-serif;
font-size: 16px;
line-height: 1.5;
color: #333;
}
h1,
h2,
h3,
h4,
h5,
h6 {
font-family: sans-serif;
font-weight: 600;
line-height: 1.25;
margin-top: 0;
margin-bottom: 0.5rem;
}
#app {
padding: 1rem;
}
+109
View File
@@ -0,0 +1,109 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2020" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
"jsx": "react-jsx" /* Specify what JSX code is generated. */,
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "ES2020" /* Specify what module code is generated. */,
// "rootDir": "./", /* Specify the root folder within your source files. */
"moduleResolution": "Bundler" /* Specify how TypeScript looks up a file from a given module specifier. */,
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
"resolveJsonModule": true /* Enable importing .json files. */,
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
// "outDir": "./", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
"noEmit": true /* Disable emitting files from a compilation. */,
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
"verbatimModuleSyntax": true /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */,
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
/* Type Checking */
"strict": true /* Enable all strict type-checking options. */,
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */,
},
}
+20 -5
View File
@@ -1,9 +1,6 @@
import { client, agent } from '../agent/services/agentService';
import type { MessageTextContentOutput, ToolOutput } from '@azure/ai-projects';
const OPENAI_API_KEY = process.env['AZURE_OPENAI_API_KEY'];
const OPENAI_ENDPOINT = process.env['AZURE_OPENAI_ENDPOINT'];
const OPENAI_DEPLOYMENT = process.env['AZURE_OPENAI_DEPLOYMENT'] || 'gpt-4';
import { PARTYKIT_BASE_URL } from '$env/static/private';
// Prompt template for grading and feedback
export function buildGradingPrompt(submission: string, task: string) {
@@ -66,7 +63,7 @@ function fallbackGrade(submission: string, task: string): OpenAIResponse {
};
}
export async function gradeSubmissionWithAgent(submission: string, task: string): Promise<OpenAIResponse> {
export async function gradeSubmissionWithAgent(submission: string, task: string, roomId?: string): Promise<OpenAIResponse> {
try {
if (!client || !agent) throw new Error('Agent not available');
@@ -111,6 +108,24 @@ export async function gradeSubmissionWithAgent(submission: string, task: string)
let output = '';
const args = JSON.parse(call.function.arguments);
if (roomId) {
try {
const ws = new (typeof WebSocket !== 'undefined' ? WebSocket : (await import('ws')).default)(`${PARTYKIT_BASE_URL}/party/tool-usage-server-${roomId}`);
// Wait for connection to open
await new Promise<void>((resolve, reject) => {
ws.onopen = () => resolve();
ws.onerror = (err) => reject(err);
});
ws.send(JSON.stringify({ tool: call.function.name, time: new Date().toISOString() }));
ws.close();
} catch (err) {
console.error('Failed to send tool usage event to PartyKit:', err);
}
}
if (
call.function.name === 'matchRubric' ||
call.function.name === 'analyzeEssay'
+2 -1
View File
@@ -8,6 +8,7 @@ export const POST: RequestHandler = async (event: RequestEvent) => {
const file = data.get('file');
const text = data.get('text');
const task = data.get('task');
const roomId = data.get('roomId') as string | undefined;
let submission = '';
if (!task || typeof task !== 'string' || !task.trim()) {
@@ -29,7 +30,7 @@ export const POST: RequestHandler = async (event: RequestEvent) => {
}
// Call the AI grading agent with threading and fallback
const aiResult = await gradeSubmissionWithAgent(submission, task.trim());
const aiResult = await gradeSubmissionWithAgent(submission, task.trim(), roomId);
return new Response(JSON.stringify({
success: true,
+27 -1
View File
@@ -7,6 +7,10 @@ let taskDescription = '';
let submitting = false;
let successMsg = '';
let errorMsg = '';
let toolEvents: Array<{ tool: string, time: string }> = [];
let roomId: string = '';
let ws: WebSocket | null = null;
const PARTYKIT_BASE_URL = import.meta.env.VITE_PARTYKIT_BASE_URL;
function handleFileChange(event: Event) {
const target = event.target as HTMLInputElement;
@@ -33,6 +37,19 @@ async function handleSubmit(event: Event) {
submitting = true;
successMsg = '';
errorMsg = '';
toolEvents = [];
// Generate a unique roomId for this submission
roomId = crypto.randomUUID();
// Connect to PartyKit for this session
if (ws) ws.close();
ws = new WebSocket(`${PARTYKIT_BASE_URL}/party/tool-usage-server-${roomId}`);
ws.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
toolEvents = [...toolEvents, data];
} catch {}
};
if (!taskDescription.trim()) {
errorMsg = 'Please provide a description of the task or assignment.';
@@ -46,6 +63,7 @@ async function handleSubmit(event: Event) {
} else if (textInput.trim().length > 0) {
formData.append('text', textInput.trim());
}
formData.append('roomId', roomId);
errorMsg = '';
try {
@@ -109,13 +127,21 @@ async function handleSubmit(event: Event) {
</div>
{/if}
{#if submitting}
<div class="absolute inset-0 flex flex-col items-center justify-center bg-white bg-opacity-80 z-20" role="status" aria-busy="true" aria-live="polite" tabindex="-1">
<div id="submitting-container" class="absolute inset-0 flex flex-col items-center justify-center bg-white bg-opacity-80 z-20" role="status" aria-busy="true" aria-live="polite" tabindex="-1">
<svg class="animate-spin h-10 w-10 text-blue-600 mb-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" aria-hidden="true">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"></path>
</svg>
<span class="sr-only">Loading...</span>
<span class="text-blue-700 font-semibold">Grading in progress...</span>
<div class="mt-4 w-full max-w-md">
{#each toolEvents as event, i}
<div class="flex items-center space-x-2 text-sm text-gray-700 bg-blue-50 rounded p-2 my-1">
<span>🛠️ {event.tool}</span>
<span class="text-xs text-gray-400">{new Date(event.time).toLocaleTimeString()}</span>
</div>
{/each}
</div>
</div>
{/if}
<form class="space-y-6" on:submit|preventDefault={handleSubmit}>