Skip to content

Commit

Permalink
Wrap onFinish callback by waitUntil()
Browse files Browse the repository at this point in the history
  • Loading branch information
Rindrics committed Nov 1, 2024
1 parent 349eb8a commit f63a88c
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 15 deletions.
53 changes: 38 additions & 15 deletions app/(playground)/p/[agentId]/beta-proto/artifact/server-actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { createStreamableValue } from "ai/rsc";

import { getUserSubscriptionId, isRoute06User } from "@/app/(auth)/lib";
import { metrics } from "@opentelemetry/api";
import { waitUntil } from "@vercel/functions";
import { Langfuse } from "langfuse";
import { schema as artifactSchema } from "../artifact/schema";
import type { SourceIndex } from "../source/types";
Expand Down Expand Up @@ -62,21 +63,43 @@ ${sourcesToText(sources)}
isEnabled: true,
},
onFinish: async (result) => {
console.log("onFinish() envirenment: ", process.env.NEXT_RUNTIME);
const meter = metrics.getMeter("OpenAI");
const tokenCounter = meter.createCounter("token_consumed", {
description: "Number of OpenAI API tokens consumed by each request",
});
const subscriptionId = await getUserSubscriptionId();
const isR06User = await isRoute06User();
tokenCounter.add(result.usage.totalTokens, {
subscriptionId,
isR06User,
});
generation.end({
output: result,
});
await lf.shutdownAsync();
waitUntil(
(async () => {
try {
console.log("Start onFinish:", process.env.NEXT_RUNTIME);

const meter = metrics.getMeter("OpenAI");
console.log("Meter created");

const tokenCounter = meter.createCounter("token_consumed", {
description:
"Number of OpenAI API tokens consumed by each request",
});
console.log("Counter created");

const subscriptionId = await getUserSubscriptionId();
const isR06User = await isRoute06User();
console.log("Got user info");

tokenCounter.add(result.usage.totalTokens, {
subscriptionId,
isR06User,
});
console.log("Added to counter");

await new Promise((resolve) => setTimeout(resolve, 200));

generation.end({
output: result,
});
await lf.shutdownAsync();
console.log("onFinish complete");
} catch (error) {
console.error("Error in onFinish:", error);
throw error;
}
})(),
);
},
});

Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
"@trigger.dev/sdk": "3.0.0-beta.55",
"@vercel/blob": "0.23.4",
"@vercel/flags": "2.6.1",
"@vercel/functions": "^1.5.0",
"@vercel/otel": "1.10.0",
"@vercel/postgres": "0.9.0",
"@vercel/speed-insights": "1.0.12",
Expand Down

0 comments on commit f63a88c

Please sign in to comment.