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

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