compaction-openai-transport.integration.test.ts 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. import { createServer } from "node:http";
  2. import type { AddressInfo } from "node:net";
  3. import { streamSimple, type Context, type Model } from "@earendil-works/pi-ai";
  4. import { Type } from "typebox";
  5. import { afterEach, beforeEach, describe, expect, it } from "vitest";
  6. import { compactContext } from "../../src/service/turn-system/compaction/algorithm/compact-context.js";
  7. import { createCheckpointSession } from "../../src/service/turn-system/compaction/execution/checkpoint-provider.js";
  8. const summary =
  9. "The synthetic file was read. Continue with the pending user request.";
  10. function history(model: Model<"openai-completions">): Context["messages"] {
  11. return [
  12. { role: "user", content: "Read the synthetic file.", timestamp: 1 },
  13. {
  14. role: "assistant",
  15. content: [
  16. {
  17. type: "toolCall",
  18. id: "read-1",
  19. name: "read",
  20. arguments: { path: "fixture.txt" },
  21. },
  22. ],
  23. api: model.api,
  24. provider: model.provider,
  25. model: model.id,
  26. stopReason: "toolUse",
  27. timestamp: 2,
  28. usage: {
  29. input: 100,
  30. output: 10,
  31. cacheRead: 0,
  32. cacheWrite: 0,
  33. totalTokens: 110,
  34. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
  35. },
  36. },
  37. {
  38. role: "toolResult",
  39. toolCallId: "read-1",
  40. toolName: "read",
  41. content: [{ type: "text", text: "Synthetic file contents." }],
  42. isError: false,
  43. timestamp: 3,
  44. },
  45. ];
  46. }
  47. describe("OpenAI compaction HTTP transport", () => {
  48. let server: ReturnType<typeof createServer>;
  49. let model: Model<"openai-completions">;
  50. let requests: Record<string, unknown>[];
  51. beforeEach(async () => {
  52. requests = [];
  53. // Exercise the real SDK serializer and stream parser with a local fixture.
  54. // This models the reported validation rule, not acceptance by a live service.
  55. server = createServer(async (request, response) => {
  56. let raw = "";
  57. for await (const chunk of request) raw += chunk;
  58. const body = JSON.parse(raw);
  59. requests.push(body);
  60. if (Array.isArray(body.tools) && body.tools.length === 0) {
  61. response.writeHead(400, { "content-type": "application/json" }).end(
  62. JSON.stringify({
  63. error: {
  64. message: "tools must not be an empty array",
  65. type: "invalid_request_error",
  66. param: "tools",
  67. },
  68. }),
  69. );
  70. return;
  71. }
  72. response.writeHead(200, { "content-type": "text/event-stream" });
  73. response.write(
  74. `data: ${JSON.stringify({
  75. id: "synthetic-checkpoint",
  76. object: "chat.completion.chunk",
  77. model: body.model,
  78. choices: [
  79. { index: 0, delta: { content: summary }, finish_reason: null },
  80. ],
  81. })}\n\n`,
  82. );
  83. response.end(
  84. `data: ${JSON.stringify({
  85. choices: [{ index: 0, delta: {}, finish_reason: "stop" }],
  86. usage: {
  87. prompt_tokens: 100,
  88. completion_tokens: 15,
  89. total_tokens: 115,
  90. },
  91. })}\n\ndata: [DONE]\n\n`,
  92. );
  93. });
  94. await new Promise<void>((resolve, reject) => {
  95. server.once("error", reject);
  96. server.listen(0, "127.0.0.1", resolve);
  97. });
  98. model = {
  99. id: "fixture-model",
  100. name: "Fixture model",
  101. api: "openai-completions",
  102. provider: "custom",
  103. baseUrl: `http://127.0.0.1:${(server.address() as AddressInfo).port}/v1`,
  104. reasoning: false,
  105. input: ["text"],
  106. contextWindow: 32_768,
  107. maxTokens: 4096,
  108. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
  109. };
  110. });
  111. afterEach(async () => {
  112. if (!server?.listening) return;
  113. server.closeAllConnections();
  114. await new Promise<void>((resolve, reject) =>
  115. server.close((error) => (error ? reject(error) : resolve())),
  116. );
  117. });
  118. it.each(["custom", "openai"])(
  119. "compacts tool history through the %s provider without empty tools",
  120. async (provider) => {
  121. model = { ...model, provider };
  122. const result = await compactContext({
  123. history: history(model),
  124. allowLegacyToolTrim: false,
  125. limits: {
  126. providerInputLimit: 20_000,
  127. maxSerializedInputBytes: 100_000,
  128. },
  129. // Admission is synthetic; checkpoint generation and HTTP transport are real.
  130. measurePair: async () => ({
  131. before: { inputTokens: 1000, serializedBytes: 10_000 },
  132. after: { inputTokens: 100, serializedBytes: 1000 },
  133. }),
  134. checkpoint: {
  135. tokensBefore: 1000,
  136. timestamp: 4,
  137. open: () =>
  138. createCheckpointSession({
  139. model,
  140. streamFn: streamSimple,
  141. thinkingLevel: "off",
  142. apiKey: "synthetic-key",
  143. maxOutputTokens: 1024,
  144. providerInputLimit: 20_000,
  145. }),
  146. },
  147. });
  148. expect(requests).toHaveLength(1);
  149. expect(requests[0]).not.toHaveProperty("tools");
  150. expect(requests[0]).not.toHaveProperty("tool_choice");
  151. expect(requests[0].messages).toEqual(
  152. expect.arrayContaining([
  153. expect.objectContaining({
  154. role: "assistant",
  155. tool_calls: [expect.objectContaining({ id: "read-1" })],
  156. }),
  157. expect.objectContaining({
  158. role: "tool",
  159. tool_call_id: "read-1",
  160. content: "Synthetic file contents.",
  161. }),
  162. ]),
  163. );
  164. expect(result).toMatchObject({
  165. method: "llm_checkpoint",
  166. summary,
  167. generationAttempts: 1,
  168. });
  169. expect(result.replacementMessages[0]).toMatchObject({
  170. role: "compactionSummary",
  171. });
  172. },
  173. );
  174. it.each([
  175. { label: "absent", tools: undefined },
  176. { label: "empty", tools: [] },
  177. ])("omits $label tool definitions with tool history", async ({ tools }) => {
  178. const result = await streamSimple(
  179. model,
  180. { messages: history(model), tools },
  181. { apiKey: "synthetic-key" },
  182. ).result();
  183. expect(requests).toHaveLength(1);
  184. expect(requests[0]).not.toHaveProperty("tools");
  185. expect(result.stopReason).toBe("stop");
  186. });
  187. it.each(["explicit", "detected"])(
  188. "omits tools with %s Anthropic cache compatibility and tool history",
  189. async (mode) => {
  190. model =
  191. mode === "explicit"
  192. ? { ...model, compat: { cacheControlFormat: "anthropic" } }
  193. : { ...model, provider: "openrouter", id: "anthropic/fixture-model" };
  194. const result = await streamSimple(
  195. model,
  196. { messages: history(model) },
  197. {
  198. apiKey: "synthetic-key",
  199. cacheRetention: "none",
  200. },
  201. ).result();
  202. expect(result.stopReason).toBe("stop");
  203. expect(requests).toHaveLength(1);
  204. expect(requests[0]).not.toHaveProperty("tools");
  205. await streamSimple(
  206. model,
  207. {
  208. messages: [{ role: "user", content: "Hello", timestamp: 1 }],
  209. tools: [],
  210. },
  211. {
  212. apiKey: "synthetic-key",
  213. cacheRetention: "none",
  214. },
  215. ).result();
  216. expect(requests[1]).not.toHaveProperty("tools");
  217. },
  218. );
  219. it("preserves nonempty tool definitions on ordinary agent requests", async () => {
  220. const result = await streamSimple(
  221. model,
  222. {
  223. messages: history(model),
  224. tools: [
  225. {
  226. name: "read",
  227. description: "Read a synthetic file",
  228. parameters: Type.Object({ path: Type.String() }),
  229. },
  230. ],
  231. },
  232. { apiKey: "synthetic-key" },
  233. ).result();
  234. expect(result.stopReason).toBe("stop");
  235. expect(requests[0].tools).toEqual([
  236. expect.objectContaining({
  237. type: "function",
  238. function: expect.objectContaining({ name: "read" }),
  239. }),
  240. ]);
  241. });
  242. });