Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

UsageLimitPolicy.ts

42 lines1.8 KB

1import {
2 DEFAULT_THREAD_CONTEXT_TOKEN_LIMIT,
3 type OrchestrationThreadActivity,
4} from "@t3tools/contracts";
5export { DEFAULT_THREAD_CONTEXT_TOKEN_LIMIT };
6export type UsageLimitViolation = { readonly code: "context-limit"; readonly detail: string };
7export function evaluateTurnStartLimits(input: {
8 readonly activities: ReadonlyArray<OrchestrationThreadActivity>;
9 readonly contextTokenLimit?: number;
10}): UsageLimitViolation | undefined {
11 const usedTokens = latestContextTokens(input.activities);
12 const contextTokenLimit = input.contextTokenLimit ?? DEFAULT_THREAD_CONTEXT_TOKEN_LIMIT;
13 if (usedTokens !== undefined && usedTokens >= contextTokenLimit) {
14 return {
15 code: "context-limit",
16 detail: `T3 usage limit: this thread has used ${usedTokens.toLocaleString("en-US")} context tokens. The hard limit is ${contextTokenLimit.toLocaleString("en-US")}. Start a new thread so the old conversation is not sent to the provider again.`,
17 };
18 }
19 return undefined;
21​
22function latestContextTokens(
23 activities: ReadonlyArray<OrchestrationThreadActivity>,
24): number | undefined {
25 for (let index = activities.length - 1; index >= 0; index -= 1) {
26 const activity = activities[index];
27 if (activity?.kind === "context-compaction") {
28 const payload = activity.payload as Record<string, unknown> | undefined;
29 const afterTokens = payload?.["afterTokens"];
30 return typeof afterTokens === "number" && Number.isFinite(afterTokens) && afterTokens >= 0
31 ? afterTokens
32 : undefined;
33 }
34 if (activity?.kind !== "context-window.updated") continue;
35 const payload = activity.payload as Record<string, unknown> | undefined;
36 const usedTokens = payload?.["usedTokens"];
37 if (typeof usedTokens === "number" && Number.isFinite(usedTokens) && usedTokens >= 0) {
38 return usedTokens;
39 }
40 }
41 return undefined;