@garrix82/reactgenie-dsl 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/.env +10 -0
  2. package/.env.example +17 -0
  3. package/.github/workflows/publish.yml +20 -0
  4. package/README.md +5 -1
  5. package/package.json +1 -5
  6. package/dist/__test__/dsl-descriptor.test.d.ts +0 -1
  7. package/dist/__test__/dsl-descriptor.test.js +0 -27
  8. package/dist/__test__/dsl-descriptor.test.js.map +0 -1
  9. package/dist/__test__/example_descriptor.d.ts +0 -125
  10. package/dist/__test__/example_descriptor.js +0 -607
  11. package/dist/__test__/example_descriptor.js.map +0 -1
  12. package/dist/__test__/food_descriptor.state.json +0 -1
  13. package/dist/__test__/food_descriptor.test.d.ts +0 -74
  14. package/dist/__test__/food_descriptor.test.js +0 -205
  15. package/dist/__test__/food_descriptor.test.js.map +0 -1
  16. package/dist/__test__/nl-interpreter-provider-selection.test.d.ts +0 -1
  17. package/dist/__test__/nl-interpreter-provider-selection.test.js +0 -73
  18. package/dist/__test__/nl-interpreter-provider-selection.test.js.map +0 -1
  19. package/dist/__test__/nl-interpreter.test.d.ts +0 -1
  20. package/dist/__test__/nl-interpreter.test.js +0 -86
  21. package/dist/__test__/nl-interpreter.test.js.map +0 -1
  22. package/dist/decorators/__test__/decorators.test.d.ts +0 -1
  23. package/dist/decorators/__test__/decorators.test.js +0 -182
  24. package/dist/decorators/__test__/decorators.test.js.map +0 -1
  25. package/dist/decorators/__test__/inheritance-descriptor.test.d.ts +0 -1
  26. package/dist/decorators/__test__/inheritance-descriptor.test.js +0 -107
  27. package/dist/decorators/__test__/inheritance-descriptor.test.js.map +0 -1
  28. package/dist/dsl/__test__/dsl-interpreter.test.d.ts +0 -1
  29. package/dist/dsl/__test__/dsl-interpreter.test.js +0 -334
  30. package/dist/dsl/__test__/dsl-interpreter.test.js.map +0 -1
  31. package/dist/dsl/__test__/parser.gen.test.d.ts +0 -1
  32. package/dist/dsl/__test__/parser.gen.test.js +0 -283
  33. package/dist/dsl/__test__/parser.gen.test.js.map +0 -1
  34. package/dist/nl/__test__/context-aware-prompt.test.d.ts +0 -1
  35. package/dist/nl/__test__/context-aware-prompt.test.js +0 -247
  36. package/dist/nl/__test__/context-aware-prompt.test.js.map +0 -1
  37. package/dist/nl/__test__/context-selector.test.d.ts +0 -1
  38. package/dist/nl/__test__/context-selector.test.js +0 -20
  39. package/dist/nl/__test__/context-selector.test.js.map +0 -1
  40. package/dist/nl/__test__/nl-parser-groq-transport.test.d.ts +0 -1
  41. package/dist/nl/__test__/nl-parser-groq-transport.test.js +0 -87
  42. package/dist/nl/__test__/nl-parser-groq-transport.test.js.map +0 -1
  43. package/dist/nl/__test__/nl-parser-openai-parity.test.d.ts +0 -1
  44. package/dist/nl/__test__/nl-parser-openai-parity.test.js +0 -206
  45. package/dist/nl/__test__/nl-parser-openai-parity.test.js.map +0 -1
  46. package/dist/nl/__test__/nl-parser-openai-sampling.test.d.ts +0 -1
  47. package/dist/nl/__test__/nl-parser-openai-sampling.test.js +0 -44
  48. package/dist/nl/__test__/nl-parser-openai-sampling.test.js.map +0 -1
  49. package/dist/nl/__test__/nl-parser-openai-transport.test.d.ts +0 -1
  50. package/dist/nl/__test__/nl-parser-openai-transport.test.js +0 -55
  51. package/dist/nl/__test__/nl-parser-openai-transport.test.js.map +0 -1
  52. package/dist/nl/__test__/nl-parser-utils.test.d.ts +0 -1
  53. package/dist/nl/__test__/nl-parser-utils.test.js +0 -70
  54. package/dist/nl/__test__/nl-parser-utils.test.js.map +0 -1
  55. package/dist/nl/__test__/nl-parser.test.d.ts +0 -1
  56. package/dist/nl/__test__/nl-parser.test.js +0 -64
  57. package/dist/nl/__test__/nl-parser.test.js.map +0 -1
  58. package/dist/nl/__test__/parameter-tuning.test.d.ts +0 -1
  59. package/dist/nl/__test__/parameter-tuning.test.js +0 -95
  60. package/dist/nl/__test__/parameter-tuning.test.js.map +0 -1
  61. package/dist/nl/__test__/semantic-parsing-experiment.test.d.ts +0 -1
  62. package/dist/nl/__test__/semantic-parsing-experiment.test.js +0 -178
  63. package/dist/nl/__test__/semantic-parsing-experiment.test.js.map +0 -1
  64. package/dist/nl/llm-monitoring.test.d.ts +0 -5
  65. package/dist/nl/llm-monitoring.test.js +0 -101
  66. package/dist/nl/llm-monitoring.test.js.map +0 -1
  67. package/lib/__test__/dsl-descriptor.test.ts +0 -27
  68. package/lib/__test__/example_descriptor.ts +0 -762
  69. package/lib/__test__/food_descriptor.state.json +0 -1
  70. package/lib/__test__/food_descriptor.test.ts +0 -331
  71. package/lib/__test__/nl-interpreter-provider-selection.test.ts +0 -126
  72. package/lib/__test__/nl-interpreter.test.ts +0 -129
  73. package/lib/decorators/__test__/decorators.test.ts +0 -177
  74. package/lib/decorators/__test__/inheritance-descriptor.test.ts +0 -92
  75. package/lib/decorators/decorators.ts +0 -754
  76. package/lib/decorators/index.ts +0 -2
  77. package/lib/decorators/store.ts +0 -47
  78. package/lib/dsl/__test__/dsl-interpreter.test.ts +0 -453
  79. package/lib/dsl/__test__/parser.gen.test.ts +0 -296
  80. package/lib/dsl/dsl-interpreter.ts +0 -974
  81. package/lib/dsl/index.ts +0 -1
  82. package/lib/dsl/parser.gen.js +0 -1479
  83. package/lib/dsl/parser.pegjs +0 -130
  84. package/lib/dsl-descriptor.ts +0 -241
  85. package/lib/index.ts +0 -5
  86. package/lib/nl/__test__/context-aware-prompt.test.ts +0 -372
  87. package/lib/nl/__test__/context-selector.test.ts +0 -27
  88. package/lib/nl/__test__/nl-parser-groq-transport.test.ts +0 -139
  89. package/lib/nl/__test__/nl-parser-openai-parity.test.ts +0 -381
  90. package/lib/nl/__test__/nl-parser-openai-sampling.test.ts +0 -73
  91. package/lib/nl/__test__/nl-parser-openai-transport.test.ts +0 -79
  92. package/lib/nl/__test__/nl-parser-utils.test.ts +0 -98
  93. package/lib/nl/__test__/nl-parser.test.ts +0 -119
  94. package/lib/nl/__test__/parameter-tuning.test.ts +0 -137
  95. package/lib/nl/__test__/semantic-parsing-experiment.test.ts +0 -260
  96. package/lib/nl/context-selector.ts +0 -123
  97. package/lib/nl/index.ts +0 -19
  98. package/lib/nl/llm-monitoring.test.ts +0 -136
  99. package/lib/nl/llm-monitoring.ts +0 -339
  100. package/lib/nl/nl-parser-groq.ts +0 -510
  101. package/lib/nl/nl-parser-utils.ts +0 -310
  102. package/lib/nl/nl-parser.ts +0 -616
  103. package/lib/nl/prompt-gen.ts +0 -607
  104. package/lib/nl/prompt-res.ts +0 -207
  105. package/lib/nl-interpreter.ts +0 -262
@@ -1,372 +0,0 @@
1
- import { ContextAwareDescriptorPromptGen, ExampleParse } from "../prompt-gen";
2
-
3
- function fakeDescriptor(
4
- description: string,
5
- genieObjectType: "DataClass" | "HelperClass" = "DataClass"
6
- ) {
7
- const match = description.match(/class\s+([A-Za-z_][A-Za-z0-9_]*)/);
8
- return {
9
- className: match?.[1] || "",
10
- description: () => description,
11
- classConstructor: {
12
- __genieObjectType: genieObjectType,
13
- },
14
- } as any;
15
- }
16
-
17
- describe("ContextAwareDescriptorPromptGen", () => {
18
- test("zero-shot prompt keeps filtered top-N classes and top-M examples", () => {
19
- const prompt = new ContextAwareDescriptorPromptGen(
20
- [
21
- fakeDescriptor("class Restaurant { static Restaurant Current(); string name; }"),
22
- fakeDescriptor("class Counter { static Counter Current(); void increment(); int count; }"),
23
- fakeDescriptor("class Probe { static Probe Current(); string status; }"),
24
- ],
25
- [
26
- new ExampleParse("increment counter", "Counter.Current().increment()"),
27
- new ExampleParse("what is counter count", "Counter.Current().count"),
28
- new ExampleParse("show restaurant", "Restaurant.Current().name"),
29
- new ExampleParse("show probe status", "Probe.Current().status"),
30
- ],
31
- undefined,
32
- {
33
- topNClassDescriptions: 1,
34
- topMExamples: 2,
35
- }
36
- );
37
-
38
- const built = prompt.zero_shot_prompt("counter action");
39
-
40
- expect(built).not.toContain("class Restaurant");
41
- expect(built).toContain("class Counter");
42
- expect(built).not.toContain("class Probe");
43
-
44
- expect(built).toContain("increment counter");
45
- expect(built).toContain("what is counter count");
46
- expect(built).not.toContain("show restaurant");
47
- expect(built).not.toContain("show probe status");
48
- });
49
-
50
- test("constrained selection does not fall back to all examples when no root examples match", () => {
51
- const prompt = new ContextAwareDescriptorPromptGen(
52
- [
53
- fakeDescriptor("class Probe { static Probe Current(); string status; }"),
54
- fakeDescriptor("class Counter { static Counter Current(); void increment(); }"),
55
- ],
56
- [new ExampleParse("increment counter", "Counter.Current().increment()")],
57
- undefined,
58
- {
59
- topNClassDescriptions: 1,
60
- topMExamples: 1,
61
- }
62
- );
63
-
64
- prompt.setRuntimeContext({
65
- tapClassName: "Probe",
66
- visibleClassNames: ["Probe"],
67
- isDeicticUtterance: true,
68
- });
69
-
70
- const built = prompt.prompt("show this status");
71
- expect(built).not.toContain("increment counter");
72
- });
73
-
74
- test("selection does not auto-include helper classes beyond ranked top-N", () => {
75
- const prompt = new ContextAwareDescriptorPromptGen(
76
- [
77
- fakeDescriptor(
78
- "class ProbeDraftIntent { static ProbeDraftIntent Current(); ProbeDateTime sampledAt; }",
79
- "DataClass"
80
- ),
81
- fakeDescriptor(
82
- "class ProbeDateTime { static ProbeDateTime now(); int minute; }",
83
- "HelperClass"
84
- ),
85
- fakeDescriptor(
86
- "class DateTime { static DateTime now(); int minute; }",
87
- "HelperClass"
88
- ),
89
- ],
90
- [
91
- new ExampleParse(
92
- "set sampled at now",
93
- "ProbeDraftIntent.Current().setSampledAt(value: ProbeDateTime.now())"
94
- ),
95
- ],
96
- undefined,
97
- {
98
- topNClassDescriptions: 1,
99
- topMExamples: 1,
100
- }
101
- );
102
-
103
- const built = prompt.zero_shot_prompt("draft intent");
104
- expect(built).toContain("class ProbeDraftIntent");
105
- expect(built).not.toContain("class ProbeDateTime");
106
- expect(built).not.toContain("class DateTime");
107
- });
108
-
109
- test("deictic utterance with no tap and no visible classes rescues self-resolving matches", () => {
110
- const prompt = new ContextAwareDescriptorPromptGen(
111
- [
112
- fakeDescriptor(
113
- "class Probe { static Probe[] getAllProbes(); static Probe Current(); string status; ProbeAnalysis openAnalysis(); }"
114
- ),
115
- fakeDescriptor(
116
- "class ProbeAnalysis { static ProbeAnalysis openForProbe(string probeId); string probeId; }"
117
- ),
118
- fakeDescriptor("class Counter { static Counter Current(); void increment(); }"),
119
- ],
120
- [
121
- new ExampleParse(
122
- "show me the latest probe and start analysis for it",
123
- "Probe.getAllProbes().sort(field: .receivedAt, ascending: false).index(index: 0).openAnalysis()"
124
- ),
125
- new ExampleParse("show probe status", "Probe.Current().status"),
126
- new ExampleParse("increment counter", "Counter.Current().increment()"),
127
- ]
128
- );
129
-
130
- prompt.setRuntimeContext({
131
- tapClassName: undefined,
132
- visibleClassNames: [],
133
- isDeicticUtterance: true,
134
- });
135
-
136
- const built = prompt.prompt("show me the latest probe and start analysis for it");
137
- expect(built).toContain("class Probe");
138
- expect(built).not.toContain("class Counter");
139
- expect(built).toContain("show me the latest probe and start analysis for it");
140
- expect(built).not.toContain("show probe status");
141
- expect(built).not.toContain("increment counter");
142
- });
143
-
144
- test("selects top-N class descriptions and top-M examples", () => {
145
- const prompt = new ContextAwareDescriptorPromptGen(
146
- [
147
- fakeDescriptor("class Restaurant { static Restaurant[] all(); string name; int price; }"),
148
- fakeDescriptor("class Counter { static Counter Current(); void increment(); }"),
149
- ],
150
- [
151
- new ExampleParse("show me cheap restaurants", "Restaurant.all().sort(field: .price, ascending: true)"),
152
- new ExampleParse("increment counter", "Counter.Current().increment()"),
153
- ],
154
- undefined,
155
- {
156
- topNClassDescriptions: 1,
157
- topMExamples: 1,
158
- }
159
- );
160
-
161
- const built = prompt.prompt("find restaurant by name");
162
-
163
- expect(built).toContain("class Restaurant");
164
- expect(built).not.toContain("class Counter");
165
- expect(built).toContain("show me cheap restaurants");
166
- expect(built).not.toContain("increment counter");
167
- });
168
-
169
- test("injects short structured history", () => {
170
- const prompt = new ContextAwareDescriptorPromptGen(
171
- [fakeDescriptor("class Order { static Order current(); void submit(); }")],
172
- [new ExampleParse("submit order", "Order.current().submit()")],
173
- undefined,
174
- {
175
- recentTurnsWindow: 2,
176
- }
177
- );
178
-
179
- prompt.recordInteraction({
180
- utterance: "open order",
181
- parsed: "Order.current()",
182
- success: true,
183
- resultSummary: "execute_ok",
184
- });
185
- prompt.recordInteraction({
186
- utterance: "submit it",
187
- parsed: "Order.current().submit()",
188
- success: true,
189
- resultSummary: "execute_ok",
190
- });
191
-
192
- const built = prompt.prompt("submit again");
193
- expect(built).toContain("// Conversation context");
194
- expect(built).toContain("recent_turns:");
195
- expect(built).toContain("user=open order");
196
- expect(built).toContain("user=submit it");
197
- });
198
-
199
- test("response prompt is lightweight and excludes DSL context", () => {
200
- const prompt = new ContextAwareDescriptorPromptGen(
201
- [fakeDescriptor("class Restaurant { static Restaurant[] all(); }")],
202
- [new ExampleParse("show restaurants", "Restaurant.all()")],
203
- "extra-instruction"
204
- );
205
-
206
- const built = prompt.response_prompt(
207
- "show cheapest restaurant",
208
- "Restaurant.all().sort(field: .price, ascending: true)[0]",
209
- '{"summary":"success"}'
210
- );
211
-
212
- expect(built).toContain("user: show cheapest restaurant");
213
- expect(built).toContain("parsed: Restaurant.all().sort(field: .price, ascending: true)[0]");
214
- expect(built).toContain("response_context:");
215
- expect(built).not.toContain("// Here are all the functions");
216
- expect(built).not.toContain("class Restaurant");
217
- expect(built).not.toContain("show restaurants");
218
- expect(built).not.toContain("// Conversation context");
219
- });
220
-
221
- test("parse prompt forbids quoted field arguments for array query operators", () => {
222
- const prompt = new ContextAwareDescriptorPromptGen(
223
- [fakeDescriptor("class Probe { static Probe[] getAllProbes(); string customerName; }")],
224
- [new ExampleParse("show probes for customer Acme", 'Probe.getAllProbes().contains(field: .customerName, value: "Acme")')]
225
- );
226
-
227
- const built = prompt.prompt("show probes for customer Freshmarket");
228
-
229
- expect(built).toContain("For matching, contains, equals, between, and sort, the field parameter MUST be a dotted accessor");
230
- expect(built).toContain('✅ CORRECT: Probe.getAllProbes().contains(field: .customerName, value: "Freshmarket")');
231
- expect(built).toContain('❌ WRONG: Probe.getAllProbes().contains(field: "customerName", value: "Freshmarket")');
232
- });
233
-
234
- test("injects runtime UI context and deictic guidance into parse prompt", () => {
235
- const prompt = new ContextAwareDescriptorPromptGen(
236
- [
237
- fakeDescriptor("class Probe { static Probe Current(); string testPlanName; }"),
238
- fakeDescriptor("class ProbeDraftIntent { static ProbeDraftIntent Current(); string testPlan; }"),
239
- ],
240
- [
241
- new ExampleParse("what test plan is used", "Probe.getCurrent().testPlanName"),
242
- new ExampleParse("what is the test plan", "ProbeDraftIntent.Current().testPlan"),
243
- ]
244
- );
245
-
246
- prompt.setRuntimeContext({
247
- tapClassName: "Probe",
248
- visibleClassNames: ["Probe", "Probe[]"],
249
- isDeicticUtterance: true,
250
- });
251
-
252
- const built = prompt.prompt("what is the test plan for this");
253
- expect(built).toContain("// Runtime UI context");
254
- expect(built).toContain("current_tap_class=Probe");
255
- expect(built).toContain("visible_classes=Probe, Probe[]");
256
- expect(built).toContain("deictic_utterance=true");
257
- expect(built).toContain("deictic_rules:");
258
- });
259
-
260
- test("updates class/example selection when deictic runtime context changes", () => {
261
- const prompt = new ContextAwareDescriptorPromptGen(
262
- [
263
- fakeDescriptor("class Restaurant { static Restaurant Current(); string name; }"),
264
- fakeDescriptor("class Counter { static Counter Current(); int count; void increment(); }"),
265
- ],
266
- [
267
- new ExampleParse("show this restaurant", "Restaurant.Current().name"),
268
- new ExampleParse("show this counter", "Counter.Current().count"),
269
- ],
270
- undefined,
271
- {
272
- topNClassDescriptions: 1,
273
- topMExamples: 1,
274
- }
275
- );
276
-
277
- prompt.setRuntimeContext({
278
- tapClassName: "Restaurant",
279
- visibleClassNames: ["Restaurant"],
280
- isDeicticUtterance: true,
281
- });
282
- const restaurantPrompt = prompt.prompt("show this");
283
- expect(restaurantPrompt).toContain("class Restaurant");
284
- expect(restaurantPrompt).toContain("show this restaurant");
285
-
286
- prompt.setRuntimeContext({
287
- tapClassName: "Counter",
288
- visibleClassNames: ["Counter"],
289
- isDeicticUtterance: true,
290
- });
291
- const counterPrompt = prompt.prompt("show this");
292
- expect(counterPrompt).toContain("class Counter");
293
- expect(counterPrompt).toContain("show this counter");
294
- });
295
-
296
- test("biases non-deictic selection toward a single visible root class", () => {
297
- const prompt = new ContextAwareDescriptorPromptGen(
298
- [
299
- fakeDescriptor("class Probe { static Probe getCurrent(); Probe updateProbe(string batch); }"),
300
- fakeDescriptor("class ProbeDraftIntent { static ProbeDraftIntent Current(); ProbeDraftIntent setBatch(string value); }"),
301
- ],
302
- [
303
- new ExampleParse("update probe batch to B-245", 'Probe.getCurrent().updateProbe(batch: "B-245")'),
304
- new ExampleParse("update the batch to B-245", 'ProbeDraftIntent.Current().setBatch(value: "B-245")'),
305
- ],
306
- undefined,
307
- {
308
- topNClassDescriptions: 1,
309
- topMExamples: 1,
310
- }
311
- );
312
-
313
- prompt.setRuntimeContext({
314
- tapClassName: undefined,
315
- visibleClassNames: ["Probe"],
316
- isDeicticUtterance: false,
317
- });
318
-
319
- const built = prompt.prompt("update the batch to batch-2026-010");
320
-
321
- expect(built).toContain("class Probe");
322
- expect(built).not.toContain("class ProbeDraftIntent");
323
- expect(built).toContain("update probe batch to B-245");
324
- expect(built).not.toContain("update the batch to B-245");
325
- });
326
-
327
- test("does not auto-pin helper class descriptions or examples", () => {
328
- const prompt = new ContextAwareDescriptorPromptGen(
329
- [
330
- fakeDescriptor(
331
- "class ProbeDraftIntent { static ProbeDraftIntent Current(); ProbeDraftIntent setSampledAt(value: DateTime); DateTime sampledAt; }",
332
- ),
333
- fakeDescriptor(
334
- "class DateTime { static DateTime now(); DateTime addDateOffset(minute: int? = `0`); }",
335
- ),
336
- fakeDescriptor("class Counter { static Counter Current(); void increment(); }"),
337
- ],
338
- [
339
- new ExampleParse(
340
- "set sampled at to now",
341
- "ProbeDraftIntent.Current().setSampledAt(value: DateTime.now())",
342
- ),
343
- new ExampleParse(
344
- "10 minutes from now",
345
- "DateTime.now().addDateOffset(minute: 10)",
346
- ),
347
- new ExampleParse("increment counter", "Counter.Current().increment()"),
348
- ],
349
- undefined,
350
- {
351
- topNClassDescriptions: 1,
352
- topMExamples: 1,
353
- },
354
- );
355
-
356
- prompt.setRuntimeContext({
357
- tapClassName: "ProbeDraftIntent",
358
- visibleClassNames: ["ProbeDraftIntent"],
359
- isDeicticUtterance: true,
360
- });
361
-
362
- const built = prompt.prompt("set sampled at to 10 minutes from now");
363
-
364
- expect(built).toContain("class ProbeDraftIntent");
365
- expect(built).not.toContain("class DateTime");
366
- expect(built).toContain("set sampled at to now");
367
- expect(built).toContain("10 minutes from now");
368
- expect(built).not.toContain("DateTime.now().addDateOffset");
369
- expect(built).not.toContain("class Counter");
370
- expect(built).not.toContain("increment counter");
371
- });
372
- });
@@ -1,27 +0,0 @@
1
- import { rankByQuery, scoreTextOverlap } from "../context-selector";
2
-
3
- describe("context selector", () => {
4
- test("splits camelCase tokens for overlap scoring", () => {
5
- const score = scoreTextOverlap("sampled at", "setSampledAt value");
6
- expect(score).toBeGreaterThan(0);
7
- });
8
-
9
- test("splits snake_case tokens for overlap scoring", () => {
10
- const score = scoreTextOverlap("sampled at", "sampled_at value");
11
- expect(score).toBeGreaterThan(0);
12
- });
13
-
14
- test("rankByQuery can disable zero-score backfill", () => {
15
- const ranked = rankByQuery(
16
- "probe",
17
- ["counter", "probe"],
18
- (item) => item,
19
- 2,
20
- { allowZeroScoreBackfill: false }
21
- );
22
-
23
- expect(ranked).toHaveLength(1);
24
- expect(ranked[0].index).toBe(1);
25
- expect(ranked[0].score).toBeGreaterThan(0);
26
- });
27
- });
@@ -1,139 +0,0 @@
1
- import { NlParserGroq } from "../nl-parser-groq";
2
- import { PromptGen } from "../prompt-gen";
3
-
4
- function toHeaderRecord(headers: any): Record<string, string> {
5
- if (!headers) return {};
6
- if (typeof headers.entries === "function") {
7
- return Object.fromEntries(
8
- Array.from(headers.entries()).map(([key, value]) => [
9
- String(key).toLowerCase(),
10
- String(value),
11
- ])
12
- );
13
- }
14
- return Object.fromEntries(
15
- Object.entries(headers).map(([key, value]) => [
16
- String(key).toLowerCase(),
17
- String(value),
18
- ])
19
- );
20
- }
21
-
22
- const promptStub: PromptGen = {
23
- prompt: () => "legacy prompt",
24
- zero_shot_prompt: () => "parse prompt",
25
- response_prompt: () => "respond prompt",
26
- };
27
-
28
- describe("NlParserGroq transport", () => {
29
- const originalFetch = global.fetch;
30
-
31
- afterEach(() => {
32
- global.fetch = originalFetch;
33
- jest.restoreAllMocks();
34
- });
35
-
36
- test("uses proxy chat completions endpoint without sdk stainless headers", async () => {
37
- const fetchMock = jest.fn().mockResolvedValue(
38
- new Response(
39
- JSON.stringify({
40
- choices: [{ message: { content: JSON.stringify({ command: "Light.on()" }) } }],
41
- usage: { prompt_tokens: 10, completion_tokens: 4, total_tokens: 14 },
42
- }),
43
- {
44
- status: 200,
45
- headers: { "content-type": "application/json" },
46
- }
47
- )
48
- );
49
- global.fetch = fetchMock as any;
50
-
51
- const parser = new NlParserGroq(
52
- promptStub,
53
- "proxy-token",
54
- "llama-3.3-70b-versatile",
55
- undefined,
56
- "https://proxy.example.com/openai/v1"
57
- );
58
-
59
- const parsed = await parser.parse("turn the lights on");
60
-
61
- expect(parsed).toBe("Light.on()");
62
- expect(fetchMock).toHaveBeenCalledTimes(1);
63
-
64
- const [url, init] = fetchMock.mock.calls[0] as [string, any];
65
- expect(String(url)).toBe("https://proxy.example.com/openai/v1/chat/completions");
66
- expect(init?.method).toBe("POST");
67
-
68
- const headers = toHeaderRecord(init?.headers);
69
- expect(headers.authorization).toBe("Bearer proxy-token");
70
- expect(headers["x-genie-provider"]).toBe("groq");
71
- expect(
72
- Object.keys(headers).some((key) => key.startsWith("x-stainless-"))
73
- ).toBe(false);
74
-
75
- const body = JSON.parse(String(init?.body || "{}"));
76
- expect(body.response_format?.type).toBe("json_schema");
77
- expect(body.response_format?.json_schema?.name).toBe("dsl_command");
78
- });
79
-
80
- test("repairs one invalid command after semantic validation fails", async () => {
81
- const validateCommand = jest
82
- .fn<Promise<void>, [string]>()
83
- .mockImplementation(async (command: string) => {
84
- if (command === 'Light.on(field: "name")') {
85
- throw new Error(
86
- "Invalid DSL: matching(field: ...) requires a dotted accessor such as .name, but received string."
87
- );
88
- }
89
- });
90
-
91
- const fetchMock = jest
92
- .fn()
93
- .mockResolvedValueOnce(
94
- new Response(
95
- JSON.stringify({
96
- choices: [{ message: { content: JSON.stringify({ command: 'Light.on(field: "name")' }) } }],
97
- usage: {},
98
- }),
99
- {
100
- status: 200,
101
- headers: { "content-type": "application/json" },
102
- }
103
- )
104
- )
105
- .mockResolvedValueOnce(
106
- new Response(
107
- JSON.stringify({
108
- choices: [{ message: { content: JSON.stringify({ command: "Light.on(field: .name)" }) } }],
109
- usage: {},
110
- }),
111
- {
112
- status: 200,
113
- headers: { "content-type": "application/json" },
114
- }
115
- )
116
- );
117
- global.fetch = fetchMock as any;
118
-
119
- const parser = new NlParserGroq(
120
- promptStub,
121
- "proxy-token",
122
- "llama-3.3-70b-versatile",
123
- undefined,
124
- "https://proxy.example.com/openai/v1",
125
- undefined,
126
- undefined,
127
- undefined,
128
- validateCommand
129
- );
130
-
131
- await expect(parser.parse("turn the lights on")).resolves.toBe("Light.on(field: .name)");
132
- expect(validateCommand).toHaveBeenCalledTimes(2);
133
-
134
- const repairBody = JSON.parse(String(fetchMock.mock.calls[1][1]?.body || "{}"));
135
- expect(repairBody.messages[1].content).toBe('Light.on(field: "name")');
136
- expect(repairBody.messages[2].content).toContain("The previous DSL command is invalid.");
137
- expect(repairBody.messages[2].content).toContain("requires a dotted accessor");
138
- });
139
- });