4
5/**
6 * Plays a bell sound notification using the Web Audio API
7 * @returns A Promise that resolves when the sound has started playing
8 */
13 const AudioContext = window.AudioContext || (window as any).webkitAudioContext;
14 if (!AudioContext) {
15 console.warn("Web Audio API not supported in this browser");
16 resolve();
17 return;
65
66/**
67 * Plays a simple notification sound using the Web Audio API
68 * This is a simpler, shorter bell sound
69 * @returns A Promise that resolves when the sound has started playing
75 const AudioContext = window.AudioContext || (window as any).webkitAudioContext;
76 if (!AudioContext) {
77 console.warn("Web Audio API not supported in this browser");
78 resolve();
79 return;
28 }
29
30 const { messages, project, branchId, anthropicApiKey, selectedFiles, images } = await c.req.json();
31
32 // do we want to allow user-provided tokens still
33 const apiKey = anthropicApiKey || Deno.env.get("ANTHROPIC_API_KEY");
34 const our_api_token = apiKey === Deno.env.get("ANTHROPIC_API_KEY");
35
36 if (our_api_token) {
37 if (await overLimit(bearerToken)) {
38 const user = await getUser(bearerToken);
59
60 const rowid = await startTrackingUsage({
61 our_api_token,
62 bearerToken, // will look up the userId from this
63 branch_id: branchId,
68
69 // Initialize PostHog client
70 const projectApiKey = Deno.env.get("POSTHOG_PROJECT_API_KEY");
71
72 let tracedModel;
73
74 if (projectApiKey) {
75 const phClient = new PostHog(projectApiKey, {
76 host: "https://us.i.posthog.com"
77 });
84 const traceId = `townie_${rowid}_${Date.now()}`;
85
86 const anthropic = createAnthropic({ apiKey });
87
88 // Wrap the Anthropic model with PostHog tracing
94 townie_branch_id: branchId,
95 townie_usage_id: rowid,
96 townie_our_api_token: our_api_token,
97 townie_num_images: images?.length || 0,
98 townie_selected_files_count: selectedFiles?.length || 0,
107 } else {
108 // Fallback to regular Anthropic call if PostHog is not configured
109 const anthropic = createAnthropic({ apiKey });
110 tracedModel = anthropic(model);
111 }
19 finish_reason?: string;
20 num_images?: number;
21 our_api_token: boolean;
22}
23
44 finish_reason TEXT,
45 num_images INTEGER,
46 our_api_token INTEGER NOT NULL,
47 finish_timestamp INTEGER
48 )
17 finish_reason: string | null;
18 num_images: number | null;
19 our_api_token: number;
20}
21
57
58 // Fetch the inference calls data
59 fetch('/api/inference-calls?usage_id=' + usageId)
60 .then(response => response.json())
61 .then(data => {
192 <th>Finish</th>
193 <th>Images</th>
194 <th>Our API</th>
195 </tr>
196 </thead>
216 <td>${row.finish_reason || '-'}</td>
217 <td>${formatNumber(row.num_images)}</td>
218 <td>${formatBoolean(row.our_api_token)}</td>
219 </tr>
220 `).join("")}
17Townie is fully open-source and itself runs on Val Town. Pull requests welcome!
18
19To get Townie running in your Val Town account, click the **Remix** button and then add your ANTHROPIC_API_KEY. You can leave all the other environment variables blank.
20
21Authentication in Townie is handled via Val Town Oauth. However, we have not yet opened up our OAuth to anyone else, which currently makes it very awkward to use your own Townie. Here is a temporary workaround:
1# Usage Dashboard
2
3A dashboard for monitoring API usage and inference calls.
4
5## Features
20 index.ts # Main entry point and routing
21 auth.ts # Authentication logic
22 /api/
23 index.ts # API request handler
24 requests.ts # API endpoints for requests data
25 inference-calls.ts # API endpoints for inference calls
26 user-summary.ts # API endpoints for user summary data
27 /views/
28 layout.ts # Common layout template
54 - Links back to the associated request
55
56### API Endpoints
57
58- `/api/requests` - Get paginated requests
59- `/api/requests?usage_id=123` - Get a specific request
60- `/api/inference-calls` - Get paginated inference calls
61- `/api/inference-calls?usage_id=123` - Get inference calls for a specific request
62- `/api/user-summary` - Get user summary data
63
64## Debugging
24 user_id = ?
25 AND timestamp > ?
26 AND our_api_token = 1
27 `,
28 [userId, new Date().getTime() - 24 * 60 * 60 * 1000],
113 branch_id,
114 model,
115 our_api_token,
116 num_images,
117}: {
120 branch_id: string;
121 model: string;
122 our_api_token: boolean;
123 num_images: number;
124}) {
132 branch_id,
133 model,
134 our_api_token,
135 num_images
136 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
143 branch_id,
144 model,
145 our_api_token ? 1 : 0,
146 num_images,
147 ],
41);
42
43// token middleware for API requests
44app.all("/api/*", async (c, next) => {
45 const sessionCookie = getCookie(c, "_session");
46 if (!sessionCookie) {
52});
53
54app.route("/api", backend);
55
56app.get("/frontend/*", (c) => {
1import { basicAuthMiddleware } from "./auth.ts";
2import { handleApiRequest } from "./api/index.ts";
3import { getRequests } from "./api/requests.ts";
4import { getUserSummary } from "./api/user-summary.ts";
5import { getInferenceCalls } from "./api/inference-calls.ts";
6import { renderDashboard } from "./views/dashboard.ts";
7import { renderRequests } from "./views/requests.ts";
22 const path = url.pathname;
23
24 // Handle API requests
25 if (path.startsWith("/api/")) {
26 return handleApiRequest(req);
27 }
28
4
5/**
6 * Handle API requests
7 */
8export async function handleApiRequest(req: Request): Promise<Response> {
9 const url = new URL(req.url);
10 const path = url.pathname.replace("/api/", "");
11
12 try {
13 // Route to the appropriate API handler
14 if (path === "requests") {
15 const usageId = url.searchParams.get("usage_id");
59 }
60 } catch (error) {
61 console.error("API error:", error);
62 return new Response(JSON.stringify({ error: error.message }), {
63 status: 500,