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

ThreadTitleContext.ts

99 lines4.2 KB

1import type { ChatAttachment } from "@t3tools/contracts";
2import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations";
3​
4export type ThreadTitleMessage = {
5 readonly role: "user" | "assistant" | "system";
6 readonly text: string;
7 readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;
8};
9​
10const MAX_CONTEXT = 8_000;
11const MAX_MESSAGE = 2_000;
12const OMITTED = "[Earlier content truncated]\n\n";
13const TRUNCATED = "\n[Content truncated]\n";
14​
15/** Keep the request and its final constraints when a message is too long. */
16export function limitTitleMessage(text: string, budget: number): string {
17 if (text.length <= budget) return text;
18 if (budget <= TRUNCATED.length) return "";
19 const available = budget - TRUNCATED.length;
20 const head = Math.ceil(available / 2);
21 const tail = available - head;
22 return `${text.slice(0, head)}${TRUNCATED}${tail > 0 ? text.slice(-tail) : ""}`;
24​
25/** Reserve space for user intent before adding assistant findings, in conversation order. */
26export function formatThreadTitleContext(messages: ReadonlyArray<ThreadTitleMessage>) {
27 const sections = messages.flatMap((message, index) => {
28 if (message.role === "system" || (!message.text.trim() && !message.attachments?.length))
29 return [];
30 return [{ index, message, prefix: `${message.role.toUpperCase()}:\n` }];
31 });
32 const formatted = new Map<number, string>();
33 const contentsFor = (section: (typeof sections)[number]) => {
34 const cached = formatted.get(section.index);
35 if (cached !== undefined) return cached;
36 const text = assistantCitationsToPlainText(section.message.text).trim();
37 const names = section.message.attachments?.map((attachment) => attachment.name).join(", ");
38 const contents = [text, ...(names ? [`[Attachments: ${names}]`] : [])]
39 .filter(Boolean)
40 .join("\n");
41 formatted.set(section.index, contents);
42 return contents;
43 };
44 const selected = new Map<number, string>();
45 let remaining = MAX_CONTEXT - OMITTED.length;
46 const add = (section: (typeof sections)[number], budget: number) => {
47 if (selected.has(section.index)) return;
48 const limit = Math.min(budget, remaining) - section.prefix.length - 2;
49 if (limit <= TRUNCATED.length) return;
50 const contents = limitTitleMessage(contentsFor(section), limit);
51 if (!contents) return;
52 const text = section.prefix + contents;
53 selected.set(section.index, text);
54 remaining -= text.length + 2;
55 };
56​
57 const firstUser = sections.find((section) => section.message.role === "user");
58 if (firstUser) add(firstUser, MAX_MESSAGE);
59 // Up to 6,000 characters go to user messages. Assistant output cannot evict them.
60 for (const section of sections.toReversed()) {
61 if (section.message.role === "user") {
62 add(section, Math.min(MAX_MESSAGE, remaining - 2_000));
63 }
64 }
65 for (const section of sections.toReversed()) {
66 if (section.message.role === "assistant") add(section, MAX_MESSAGE);
67 }
68 // Use spare space when the conversation has only a few messages.
69 for (const role of ["user", "assistant"] as const) {
70 for (const section of sections.toReversed()) {
71 const previous = selected.get(section.index);
72 if (section.message.role !== role || previous === undefined) continue;
73 const expanded =
74 section.prefix +
75 limitTitleMessage(
76 contentsFor(section),
77 previous.length + remaining - section.prefix.length,
78 );
79 remaining -= expanded.length - previous.length;
80 selected.set(section.index, expanded);
81 }
82 }
83 const retained = sections.filter((section) => selected.has(section.index));
84 const truncated = retained.some(
85 (section) => selected.get(section.index) !== section.prefix + contentsFor(section),
86 );
87 const attachments = retained.flatMap((section) => section.message.attachments ?? []);
88 const firstAttachment = firstUser?.message.attachments?.[0];
89 const recentAttachments = attachments.filter(
90 (attachment) => attachment.id !== firstAttachment?.id,
91 );
92 return {
93 message: `${truncated || retained.length < sections.length ? OMITTED : ""}${retained.map((section) => selected.get(section.index)).join("\n\n")}`,
94 attachments: [
95 ...(firstAttachment ? [firstAttachment] : []),
96 ...recentAttachments.slice(firstAttachment ? -3 : -4),
97 ],
98 };