29 }
30
31 const { messages, project, branchId, anthropicApiKey, selectedFiles, images } = await c.req.json();
32
33 // do we want to allow user-provided tokens still
34 const apiKey = anthropicApiKey || Deno.env.get("ANTHROPIC_API_KEY");
35 const our_api_token = apiKey === Deno.env.get("ANTHROPIC_API_KEY");
36
37 if (our_api_token) {
38 if (await hasInsufficientCredits({bearerToken})) {
39 return Response.json({
51
52 const rowid = await startTrackingUsage({
53 our_api_token,
54 bearerToken, // will look up the userId from this
55 branch_id: branchId,
60
61 // Initialize PostHog client
62 const projectApiKey = Deno.env.get("POSTHOG_PROJECT_API_KEY");
63
64 let tracedModel;
65
66 if (projectApiKey) {
67 const phClient = new PostHog(projectApiKey, {
68 host: "https://us.i.posthog.com"
69 });
76 const traceId = `townie_${rowid}_${Date.now()}`;
77
78 const anthropic = createAnthropic({ apiKey });
79
80 // Wrap the Anthropic model with PostHog tracing
86 townie_branch_id: branchId,
87 townie_usage_id: rowid,
88 townie_our_api_token: our_api_token,
89 townie_num_images: images?.length || 0,
90 townie_selected_files_count: selectedFiles?.length || 0,
99 } else {
100 // Fallback to regular Anthropic call if PostHog is not configured
101 const anthropic = createAnthropic({ apiKey });
102 tracedModel = anthropic(model);
103 }
236 });
237
238 if (our_api_token) {
239 const stillHasCredits = !(await hasInsufficientCredits({bearerToken})); // Check for at least 1 cent
240 if (!stillHasCredits) {
20 finish_reason?: string;
21 num_images?: number;
22 our_api_token: boolean;
23}
24
45 finish_reason TEXT,
46 num_images INTEGER,
47 our_api_token INTEGER NOT NULL,
48 finish_timestamp INTEGER
49 )`,
17 finish_reason: string | null;
18 num_images: number | null;
19 our_api_token: number;
20}
21
69 <th>Finish</th>
70 <th>Images</th>
71 <th>Our API</th>
72 </tr>
73 </thead>
88 <td>${row.finish_reason || '-'}</td>
89 <td>${formatNumber(row.num_images)}</td>
90 <td>${formatBoolean(row.our_api_token)}</td>
91 </tr>
92 `).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
140 branch_id,
141 model,
142 our_api_token,
143 num_images,
144 tablePrefix = "",
148 branch_id: string;
149 model: string;
150 our_api_token: boolean;
151 num_images: number;
152 tablePrefix: string;
161 branch_id,
162 model,
163 our_api_token,
164 num_images
165 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
172 branch_id,
173 model,
174 our_api_token ? 1 : 0,
175 num_images,
176 ],
28 branch_id,
29 model,
30 our_api_token,
31 num_images
32 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
14const stripe = stripeSecretKey
15 ? new Stripe(stripeSecretKey, {
16 apiVersion: "2024-04-10",
17 })
18 : null;
57 // user_id: user.id,
58 // username: user.username,
59 // purchase_source: source || "api", // e.g., "insufficient_credits", "settings_page"
60 // },
61 // description: `Townie credits purchase - $${amount} for ${user.username}`,
62 // api_key: stripeSecretKey,
63 // });
64
69 "metadata[user_id]": user.id,
70 "metadata[username]": user.username,
71 "metadata[purchase_source]": source || "api",
72 description: `Townie credits purchase - $${amount} for ${user.username}`,
73 });
74
75 const response = await fetch("https://api.stripe.com/v1/payment_intents", {
76 method: "POST",
77 headers: {
84 const paymentIntent = await response.json();
85 if (!response.ok) {
86 throw new Error(`Stripe API error: ${paymentIntent.error?.message || "Unknown error"}`);
87 }
88
15 const fetchBalance = async () => {
16 try {
17 const response = await fetch("/api/credit-balance");
18 if (response.ok) {
19 const data = await response.json();
35
36 try {
37 const response = await fetch("/api/purchase-credits", {
38 method: "POST",
39 headers: { "Content-Type": "application/json" },
41);
42
43// token middleware for API requests
44app.all("/api/*", async (c, next) => {
45 if (c.req.path === "/api/stripe-webhook") {
46 return next();
47 }
55});
56
57app.route("/api", backend);
58
59app.get("/frontend/*", (c) => {