count-tokens-body.ts 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. /**
  2. * count_tokens request-body builder + CJK-aware char fallback for
  3. * {@link RemoteTokenCounter}.
  4. *
  5. * Why flatten to alternating text
  6. * -------------------------------
  7. * The remote `count_tokens` endpoint is Messages-compatible-shaped. Faithfully
  8. * reconstructing `tool_use` / `tool_result` pairing (matching `tool_use_id`s
  9. * across messages) is fragile — a single mismatch makes the provider reject the
  10. * body with a 4xx, which would defeat the whole point of asking it for a count.
  11. *
  12. * Since we only need a token *count*, we degrade every non-text block to text:
  13. * tool calls become `name(args-json)`, tool results become a labelled text
  14. * block, thinking is inlined, images become a short placeholder. The result is
  15. * always a valid alternating user/assistant transcript. This slightly
  16. * over-counts thinking and under-counts image binary; both directions are
  17. * absorbed by the manager's `safetyMarginTokens` / `reserveTokens` headroom.
  18. */
  19. import { convertToLlm } from '@earendil-works/pi-coding-agent';
  20. import type { AgentMessage } from '@earendil-works/pi-agent-core';
  21. import type { Api, Model, Tool } from '@earendil-works/pi-ai';
  22. /** Temperature is required by the gateway body but ignored for counting. */
  23. const COUNT_TOKENS_TEMPERATURE = 1;
  24. /** Placeholder so image binary does not bloat the request; count is approximate. */
  25. const IMAGE_PLACEHOLDER = '[image]';
  26. /** Messages-compatible endpoints reject empty content blocks; substitute a marker. */
  27. const EMPTY_TEXT_PLACEHOLDER = '(empty)';
  28. /** Per-message structural overhead used by the char-count fallback. */
  29. const FALLBACK_MESSAGE_OVERHEAD = 4;
  30. export interface CountTokensTextBlock {
  31. type: 'text';
  32. text: string;
  33. }
  34. export interface CountTokensMessage {
  35. role: 'user' | 'assistant';
  36. content: CountTokensTextBlock[];
  37. }
  38. export interface CountTokensRequestBody {
  39. model: string;
  40. max_tokens: number;
  41. stream: false;
  42. temperature: number;
  43. messages: CountTokensMessage[];
  44. system?: CountTokensTextBlock[];
  45. /** Tool declarations included in the count; omitted when the request has no tools. */
  46. tools?: CountTokensTool[];
  47. }
  48. /**
  49. * Tool declaration shape for the Messages-compatible count_tokens endpoint. Tool declarations are
  50. * part of the actual LLM request payload (tens of thousands of tokens in MCP-heavy sessions), so
  51. * count requests must include the same declarations to avoid systematic undercounting.
  52. * `input_schema` is the tool parameter JSON Schema.
  53. */
  54. export interface CountTokensTool {
  55. name: string;
  56. description: string;
  57. input_schema: unknown;
  58. }
  59. type PiContentBlock = { type: string; [key: string]: unknown };
  60. function textFromContent(content: unknown): string {
  61. if (typeof content === 'string') return content;
  62. if (!Array.isArray(content)) return '';
  63. const parts: string[] = [];
  64. for (const block of content as PiContentBlock[]) {
  65. if (block.type === 'text' && typeof block.text === 'string') {
  66. parts.push(block.text);
  67. } else if (block.type === 'image') {
  68. parts.push(IMAGE_PLACEHOLDER);
  69. }
  70. }
  71. return parts.join('\n');
  72. }
  73. function safeJsonStringify(value: unknown): string {
  74. try {
  75. return JSON.stringify(value) ?? '';
  76. } catch {
  77. return '[unserializable]';
  78. }
  79. }
  80. function assistantText(content: unknown): string {
  81. if (!Array.isArray(content)) return textFromContent(content);
  82. const parts: string[] = [];
  83. for (const block of content as PiContentBlock[]) {
  84. if (block.type === 'text' && typeof block.text === 'string') {
  85. parts.push(block.text);
  86. } else if (block.type === 'thinking' && typeof block.thinking === 'string') {
  87. parts.push(block.thinking);
  88. } else if (block.type === 'toolCall') {
  89. const name = typeof block.name === 'string' ? block.name : 'tool';
  90. parts.push(`${name}(${safeJsonStringify(block.arguments)})`);
  91. }
  92. }
  93. return parts.join('\n');
  94. }
  95. /**
  96. * Map normalized pi-ai messages to an alternating user/assistant text
  97. * transcript. Consecutive same-role messages are merged; if the transcript
  98. * would start with `assistant`, a synthetic leading user turn is prepended
  99. * (The endpoint requires the first message to be `user`).
  100. */
  101. function flattenToAlternatingText(messages: ReturnType<typeof convertToLlm>): CountTokensMessage[] {
  102. const out: CountTokensMessage[] = [];
  103. for (const m of messages) {
  104. let role: 'user' | 'assistant';
  105. let text: string;
  106. if (m.role === 'assistant') {
  107. role = 'assistant';
  108. text = assistantText(m.content);
  109. } else if (m.role === 'toolResult') {
  110. role = 'user';
  111. const label = `[tool_result ${m.toolName}]`;
  112. const body = textFromContent(m.content);
  113. text = body ? `${label}\n${body}` : label;
  114. } else {
  115. role = 'user';
  116. text = textFromContent(m.content);
  117. }
  118. if (!text) text = EMPTY_TEXT_PLACEHOLDER;
  119. const last = out[out.length - 1];
  120. if (last && last.role === role) {
  121. last.content[0]!.text += `\n${text}`;
  122. } else {
  123. out.push({ role, content: [{ type: 'text', text }] });
  124. }
  125. }
  126. if (out[0]?.role === 'assistant') {
  127. out.unshift({ role: 'user', content: [{ type: 'text', text: '(context)' }] });
  128. }
  129. return out;
  130. }
  131. /**
  132. * Build a count_tokens request body from the active transcript and the
  133. * SessionController-composed system prompt.
  134. */
  135. export function buildCountTokensRequestBody(
  136. messages: AgentMessage[],
  137. systemPrompt: string | undefined,
  138. model: Model<Api>,
  139. tools?: Tool[],
  140. ): CountTokensRequestBody {
  141. const llm = convertToLlm(messages);
  142. const turns = flattenToAlternatingText(llm);
  143. // Normalize rather than filter: real LLM requests include all registered tools, even with empty
  144. // descriptions or missing schemas. Silently dropping them would underestimate the payload. Only
  145. // discard invalid entries without a name, and fill missing fields with valid defaults.
  146. const countTools = tools
  147. ?.filter((tool) => tool.name)
  148. .map((tool) => ({
  149. name: tool.name,
  150. description: tool.description ?? '',
  151. input_schema: tool.parameters ?? { type: 'object', properties: {} },
  152. }));
  153. return {
  154. model: model.id,
  155. max_tokens: model.maxTokens > 0 ? model.maxTokens : 1,
  156. stream: false,
  157. temperature: COUNT_TOKENS_TEMPERATURE,
  158. messages: turns,
  159. ...(systemPrompt?.trim() ? { system: [{ type: 'text', text: systemPrompt }] } : {}),
  160. ...(countTools && countTools.length > 0 ? { tools: countTools } : {}),
  161. };
  162. }
  163. /**
  164. * CJK / fullwidth ranges that consume roughly one BPE token per character.
  165. * Expressed as \u code-point escapes to avoid source-encoding ambiguity.
  166. * Covers: CJK symbols & punctuation, Hiragana/Katakana, CJK Ext-A, CJK
  167. * Unified Ideographs, CJK Compatibility Ideographs, halfwidth/fullwidth forms,
  168. * Hangul syllables, and CJK Ext-B+ (astral).
  169. */
  170. const CJK_RE =
  171. /[\u{3000}-\u{303F}\u{3040}-\u{30FF}\u{3400}-\u{4DBF}\u{4E00}-\u{9FFF}\u{F900}-\u{FAFF}\u{FF00}-\u{FFEF}\u{AC00}-\u{D7AF}\u{20000}-\u{2FA1F}]/u;
  172. /**
  173. * CJK-aware char→token estimate. CJK / fullwidth code points consume roughly
  174. * one token each; other (mostly ASCII) text averages ~4 chars per token. This
  175. * is the fallback when the remote endpoint times out or fails — far closer to
  176. * truth for Chinese than the legacy `chars/4` which under-counts CJK 4-8x.
  177. */
  178. export function estimateCharsToTokensCjkAware(text: string): number {
  179. if (!text) return 0;
  180. let cjk = 0;
  181. let other = 0;
  182. for (const ch of text) {
  183. if (CJK_RE.test(ch)) cjk += 1;
  184. else other += 1;
  185. }
  186. return cjk + Math.ceil(other / 4);
  187. }
  188. /**
  189. * Fallback total-token estimate from the same body the remote call would send,
  190. * so the trigger sees a consistent shape whether or not the network succeeded.
  191. */
  192. export function cjkFallbackTokens(
  193. messages: AgentMessage[],
  194. systemPrompt: string | undefined,
  195. model: Model<Api>,
  196. tools?: Tool[],
  197. ): number {
  198. return cjkFallbackTokensForBody(
  199. buildCountTokensRequestBody(messages, systemPrompt, model, tools),
  200. );
  201. }
  202. /**
  203. * Body-based variant of {@link cjkFallbackTokens}: callers such as local-runtime's
  204. * `HttpRemoteTokenCounter` have already built a count_tokens body for the remote request. Reuse it
  205. * for fallback estimation after remote failure instead of converting and flattening the full
  206. * transcript again. Both paths use the same body, keeping the trigger's view aligned with remote
  207. * counting.
  208. */
  209. export function cjkFallbackTokensForBody(body: CountTokensRequestBody): number {
  210. let total = body.system ? estimateCharsToTokensCjkAware(body.system[0]!.text) : 0;
  211. for (const m of body.messages) {
  212. total += FALLBACK_MESSAGE_OVERHEAD + estimateCharsToTokensCjkAware(m.content[0]!.text);
  213. }
  214. // Include tool declarations in fallback estimates, matching the body seen by the remote endpoint.
  215. for (const tool of body.tools ?? []) {
  216. total +=
  217. FALLBACK_MESSAGE_OVERHEAD +
  218. estimateCharsToTokensCjkAware(tool.name) +
  219. estimateCharsToTokensCjkAware(tool.description) +
  220. estimateCharsToTokensCjkAware(safeJsonStringify(tool.input_schema));
  221. }
  222. return total;
  223. }