testcases.ts 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. import { copyFile, mkdir, readdir, readFile, stat } from "node:fs/promises";
  2. import { basename, join } from "node:path";
  3. import { loadFixture, type PromptTrajectoryFixture } from "./fixture.js";
  4. import { recordPromptTrajectoryFromFixture } from "./record.js";
  5. export interface PromptTrajectoryCase {
  6. directory: string;
  7. expectPath: string;
  8. fixturePath?: string;
  9. name: string;
  10. promptPath?: string;
  11. }
  12. export interface SharedModelOptions {
  13. apiKey?: string;
  14. apiKeyEnv?: string;
  15. modelId?: string;
  16. upstreamBaseURL?: string;
  17. }
  18. export async function discoverPromptTrajectoryCases(
  19. casesDir: string,
  20. ): Promise<PromptTrajectoryCase[]> {
  21. const entries = await readdir(casesDir, { withFileTypes: true });
  22. const cases: PromptTrajectoryCase[] = [];
  23. for (const entry of entries) {
  24. if (!entry.isDirectory()) continue;
  25. const directory = join(casesDir, entry.name);
  26. const promptPath = join(directory, "prompt.txt");
  27. const fixturePath = join(directory, "fixture.json");
  28. const expectPath = join(directory, "expect.json");
  29. if (!(await fileExists(expectPath))) continue;
  30. const hasPrompt = await fileExists(promptPath);
  31. const hasFixture = await fileExists(fixturePath);
  32. if (!hasPrompt && !hasFixture) continue;
  33. cases.push({
  34. directory,
  35. expectPath,
  36. ...(hasFixture ? { fixturePath } : {}),
  37. name: entry.name,
  38. ...(hasPrompt ? { promptPath } : {}),
  39. });
  40. }
  41. return cases.sort((left, right) => left.name.localeCompare(right.name));
  42. }
  43. export async function createTimestampedRunDirectory(
  44. outRoot: string,
  45. now = new Date(),
  46. ): Promise<string> {
  47. const directory = join(outRoot, `test${formatTimestamp(now)}`);
  48. await mkdir(directory, { recursive: true });
  49. return directory;
  50. }
  51. export async function createTimestampedPromptDirectory(
  52. outRoot: string,
  53. now = new Date(),
  54. ): Promise<string> {
  55. const directory = join(outRoot, `prompt${formatTimestamp(now)}`);
  56. await mkdir(directory, { recursive: true });
  57. return directory;
  58. }
  59. export async function promptFixtureFromCase(
  60. testcase: PromptTrajectoryCase,
  61. modelOptions?: SharedModelOptions,
  62. ): Promise<PromptTrajectoryFixture> {
  63. if (testcase.fixturePath) {
  64. const fixture = await loadFixture(testcase.fixturePath);
  65. return mergeFixtureModelOptions(fixture, modelOptions);
  66. }
  67. if (!testcase.promptPath) {
  68. throw new Error(`Prompt trajectory case ${testcase.name} is missing prompt.txt or fixture.json`);
  69. }
  70. return promptFixtureFromText({
  71. modelOptions,
  72. name: testcase.name,
  73. prompt: await readFile(testcase.promptPath, "utf8"),
  74. });
  75. }
  76. function mergeFixtureModelOptions(
  77. fixture: PromptTrajectoryFixture,
  78. modelOptions?: SharedModelOptions,
  79. ): PromptTrajectoryFixture {
  80. const model = createFixtureModel(modelOptions);
  81. const merged = {
  82. ...fixture,
  83. ...(model
  84. ? {
  85. model: {
  86. ...fixture.model,
  87. ...model,
  88. },
  89. }
  90. : {}),
  91. };
  92. requireExplicitModel(merged.model);
  93. return merged;
  94. }
  95. export function promptFixtureFromText(input: {
  96. modelOptions?: SharedModelOptions;
  97. name: string;
  98. prompt: string;
  99. }): PromptTrajectoryFixture {
  100. const model = createFixtureModel(input.modelOptions);
  101. requireExplicitModel(model);
  102. return {
  103. model,
  104. name: input.name,
  105. runtimeConfig: {
  106. mode: "yolo",
  107. modelStreaming: "on",
  108. },
  109. steps: [
  110. {
  111. text: input.prompt,
  112. type: "submitPrompt",
  113. },
  114. ],
  115. };
  116. }
  117. function requireExplicitModel(
  118. model: PromptTrajectoryFixture["model"] | undefined,
  119. ): asserts model is NonNullable<PromptTrajectoryFixture["model"]> {
  120. const hasIdentity = Boolean(model?.id || (model?.provider && model.model));
  121. if (!hasIdentity || !model?.upstreamBaseURL) {
  122. throw new Error(
  123. "Explicit model options are required: provide provider/model and upstreamBaseURL.",
  124. );
  125. }
  126. }
  127. export async function runPromptTrajectoryCases(input: {
  128. casesDir: string;
  129. modelOptions?: SharedModelOptions;
  130. outRoot: string;
  131. }): Promise<{
  132. caseCount: number;
  133. runDir: string;
  134. }> {
  135. const cases = await discoverPromptTrajectoryCases(input.casesDir);
  136. if (cases.length === 0) {
  137. throw new Error(`No prompt trajectory cases found in ${input.casesDir}`);
  138. }
  139. const runDir = await createTimestampedRunDirectory(input.outRoot);
  140. for (const testcase of cases) {
  141. const caseOutDir = join(runDir, sanitizeCaseName(testcase.name));
  142. await mkdir(caseOutDir, { recursive: true });
  143. await copyFile(testcase.expectPath, join(caseOutDir, "expect.json"));
  144. await recordPromptTrajectoryFromFixture({
  145. fixture: await promptFixtureFromCase(testcase, input.modelOptions),
  146. outDir: caseOutDir,
  147. });
  148. }
  149. return {
  150. caseCount: cases.length,
  151. runDir,
  152. };
  153. }
  154. function createFixtureModel(
  155. modelOptions: SharedModelOptions | undefined,
  156. ): PromptTrajectoryFixture["model"] | undefined {
  157. if (!modelOptions) return undefined;
  158. const model: PromptTrajectoryFixture["model"] = {};
  159. if (modelOptions.modelId !== undefined) {
  160. model.id = modelOptions.modelId;
  161. }
  162. if (modelOptions.upstreamBaseURL !== undefined) {
  163. model.upstreamBaseURL = modelOptions.upstreamBaseURL;
  164. }
  165. if (modelOptions.apiKey !== undefined) {
  166. model.apiKey = modelOptions.apiKey;
  167. }
  168. if (modelOptions.apiKeyEnv !== undefined) {
  169. model.apiKeyEnv = modelOptions.apiKeyEnv;
  170. }
  171. if (Object.keys(model).length === 0) return undefined;
  172. model.kind = "openai-compatible";
  173. return model;
  174. }
  175. function formatTimestamp(now: Date): string {
  176. const pad = (value: number) => String(value).padStart(2, "0");
  177. return [
  178. now.getFullYear(),
  179. pad(now.getMonth() + 1),
  180. pad(now.getDate()),
  181. "-",
  182. pad(now.getHours()),
  183. pad(now.getMinutes()),
  184. pad(now.getSeconds()),
  185. ].join("");
  186. }
  187. function sanitizeCaseName(name: string): string {
  188. const sanitized = basename(name).replace(/[^a-zA-Z0-9._-]+/gu, "_");
  189. return sanitized.length > 0 ? sanitized : "case";
  190. }
  191. async function fileExists(path: string): Promise<boolean> {
  192. try {
  193. return (await stat(path)).isFile();
  194. } catch {
  195. return false;
  196. }
  197. }