File size: 12,738 Bytes
58843c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
/* eslint-disable no-useless-escape */
import { describe, it, expect } from "vitest";
import { modifySnippet } from "./snippets.js";

// Shared object to add, including various types
const SHARED_OBJ_TO_ADD = {
	maxTokens: 200,
	frequencyPenalty: 0.3,
	presencePenalty: null,
	stopSequences: ["stop1", "stop2"],
	complexObject: {
		nestedKey: "nestedValue",
		nestedNum: 123,
		nestedBool: false,
		nestedArr: ["a", 1, true, null],
	},
	anotherString: "test string",
	isStreaming: true,
};

// Helper to create regex for matching stringified values (JS/JSON and Python)
// This version is updated to handle multi-line, indented ("pretty-printed") structures.
function createValueRegex(value: unknown, language: "js" | "python" | "json"): string {
	// Flexible whitespace: matches any number of spaces, tabs, or newlines.
	const ws = "(?:\\s|\\n)*";

	if (typeof value === "string") {
		return `"${value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}"`; // Escape special regex chars in string
	}
	if (value === null) {
		return language === "python" ? "None" : "null";
	}
	if (typeof value === "boolean") {
		return language === "python" ? (value ? "True" : "False") : String(value);
	}
	if (typeof value === "number") {
		return String(value);
	}
	if (Array.isArray(value)) {
		if (value.length === 0) {
			return `\\[${ws}\\]`; // Matches "[]" or "[ \n ]" etc.
		}
		const itemRegexes = value.map(item => createValueRegex(item, language)).join(`${ws},${ws}`);
		return `\\[${ws}${itemRegexes}${ws}\\]`;
	}
	if (typeof value === "object" && value !== null) {
		const entries = Object.entries(value);
		if (entries.length === 0) {
			return `\\{${ws}\\}`; // Matches "{}" or "{ \n }" etc.
		}
		const entriesRegex = entries
			.map(([k, v]) => {
				// In Python kwargs, keys are not quoted. This regex builder is for values that look like JSON/Python dicts.
				// The main test loops handle Python kwarg key formatting separately.
				const keyRegex = `"${k.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}"`;
				const valueRegexPart = createValueRegex(v, language);
				return `${keyRegex}${ws}:${ws}${valueRegexPart}`;
			})
			.join(`${ws},${ws}`); // Join key-value pairs with a comma and flexible whitespace
		return `\\{${ws}${entriesRegex}${ws}\\}`;
	}
	return String(value).replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // Fallback for other primitive types
}

type TestCase = {
	snippet: string;
	objToAdd: Record<string, unknown>;
	description: string; // Optional description for the test
	pythonSyntax?: "kwargs" | "dict"; // Add this field
};

// JavaScript/TypeScript test cases
const jsTestCases: TestCase[] = [
	{
		description: "JavaScript InferenceClient with chatCompletionStream",
		snippet: `
import { InferenceClient } from "@huggingface/inference";

const client = new InferenceClient("YOUR_HF_TOKEN");

let out = "";

const stream = client.chatCompletionStream({
    provider: "cerebras",
    model: "Qwen/Qwen3-32B",
    messages: [
        {
            role: "user",
            content: "What is the capital of Brazil?",
        },
        {
            content: "{\"answer_the_question\": 5, \"how_many_legs_does_a_dog_have\": true, \"answer_the_question_HERE\": \"elderberry\"}",
            role: "assistant",
        },
    ],
    temperature: 0.5,
    top_p: 0.7,
});

for await (const chunk of stream) {
  if (chunk.choices && chunk.choices.length > 0) {
    const newContent = chunk.choices[0].delta.content;
    out += newContent;
    console.log(newContent);
  }
}
`,
		objToAdd: SHARED_OBJ_TO_ADD,
	},
	{
		description: "JavaScript InferenceClient without streaming",
		snippet: `import { InferenceClient } from "@huggingface/inference";

const client = new InferenceClient("YOUR_HF_TOKEN");

const chatCompletion = await client.chatCompletion({
    provider: "cohere",
    model: "CohereLabs/c4ai-command-r-plus",
    messages: [
        {
            role: "user",
            content: "hey, how are you???",
        },
        {
            role: "assistant",
            content: "{ \"answer_the_question\": \n\n\n\n            \n           \n\n-1.175\n\n\n\n, \n \"how_many_legs_does_a_dog_have\": \nfalse, \n\n\"answer_the_question_HERE\": \n\n\"A\"\n\n\n}",
        },
    ],
    temperature: 0.5,
    top_p: 0.7,
});

console.log(chatCompletion.choices[0].message);`,
		objToAdd: SHARED_OBJ_TO_ADD,
	},
	{
		description: "JavaScript with OpenAI library",
		snippet: `import { OpenAI } from "openai";

const client = new OpenAI({
	baseURL: "https://api.cerebras.ai/v1",
	apiKey: "YOUR_HF_TOKEN",
});

const stream = await client.chat.completions.create({
    model: "qwen-3-32b",
    messages: [
        {
            role: "user",
            content: "What is the capital of Brazil?",
        },
        {
            content: "{\"answer_the_question\": 5, \"how_many_legs_does_a_dog_have\": true, \"answer_the_question_HERE\": \"elderberry\"}",
            role: "assistant",
        },
    ],
    temperature: 0.5,
    top_p: 0.7,
    stream: true,
});

for await (const chunk of stream) {
    process.stdout.write(chunk.choices[0]?.delta?.content || "");
}`,
		objToAdd: SHARED_OBJ_TO_ADD,
	},
];

// Python test cases
const pythonTestCases: TestCase[] = [
	{
		description: "Python HuggingFace client",
		snippet: `from huggingface_hub import InferenceClient

client = InferenceClient(
    provider="cerebras",
    api_key="YOUR_HF_TOKEN",
)

stream = client.chat.completions.create(
    model="Qwen/Qwen3-32B",
    messages=[
        {
            "role": "user",
            "content": "What is the capital of Brazil?"
        },
        {
            "content": "{\"answer_the_question\": 5, \"how_many_legs_does_a_dog_have\": true, \"answer_the_question_HERE\": \"elderberry\"}",
            "role": "assistant"
        }
    ],
    temperature=0.5,
    top_p=0.7,
    stream=True,
)

for chunk in stream:
    print(chunk.choices[0].delta.content, end="")`,
		objToAdd: SHARED_OBJ_TO_ADD, // Use shared object
		pythonSyntax: "kwargs",
	},
	{
		description: "Python with Requests",
		snippet: `import json
import requests

API_URL = "https://api.cerebras.ai/v1/chat/completions"
headers = {
    "Authorization": "Bearer YOUR_HF_TOKEN",
}

def query(payload):
    response = requests.post(API_URL, headers=headers, json=payload, stream=True)
    for line in response.iter_lines():
        if not line.startswith(b"data:"):
            continue
        if line.strip() == b"data: [DONE]":
            return
        yield json.loads(line.decode("utf-8").lstrip("data:").rstrip("/n"))

chunks = query({
    "messages": [
        {
            "role": "user",
            "content": "What is the capital of Brazil?"
        },
        {
            "content": "{\"answer_the_question\": 5, \"how_many_legs_does_a_dog_have\": true, \"answer_the_question_HERE\": \"elderberry\"}",
            "role": "assistant"
        }
    ],
    "temperature": 0.5,
    "top_p": 0.7,
    "model": "qwen-3-32b",
    "stream": True,
})

for chunk in chunks:
    print(chunk["choices"][0]["delta"]["content"], end="")`,
		objToAdd: SHARED_OBJ_TO_ADD, // Use shared object
		pythonSyntax: "dict",
	},
	{
		description: "Python OpenAI client",
		snippet: `from openai import OpenAI

client = OpenAI(
    base_url="https://api.cerebras.ai/v1",
    api_key="YOUR_HF_TOKEN",
)

stream = client.chat.completions.create(
    model="qwen-3-32b",
    messages=[
        {
            "role": "user",
            "content": "What is the capital of Brazil?"
        },
        {
            "content": "{\"answer_the_question\": 5, \"how_many_legs_does_a_dog_have\": true, \"answer_the_question_HERE\": \"elderberry\"}",
            "role": "assistant"
        }
    ],
    temperature=0.5,
    top_p=0.7,
    stream=True,
)

for chunk in stream:
    print(chunk.choices[0].delta.content, end="")`,
		objToAdd: SHARED_OBJ_TO_ADD, // Use shared object
		pythonSyntax: "kwargs",
	},
	// Add more Python test cases as needed
];

// Shell/curl test cases
const shellTestCases: TestCase[] = [
	{
		description: "curl request to Cerebras API",
		snippet: `
curl https://api.cerebras.ai/v1/chat/completions \\
    -H 'Authorization: Bearer YOUR_HF_TOKEN' \\
    -H 'Content-Type: application/json' \\
    -d '{
        "messages": [
            {
                "role": "user",
                "content": "What is the capital of Brazil?"
            },
            {
                "content": "{\"answer_the_question\": 5, \"how_many_legs_does_a_dog_have\": true, \"answer_the_question_HERE\": \"elderberry\"}",
                "role": "assistant"
            }
        ],
        "temperature": 0.5,
        "top_p": 0.7,
        "model": "qwen-3-32b",
        "stream": false
    }'
`,
		objToAdd: SHARED_OBJ_TO_ADD, // Use shared object
	},
	// Add more shell test cases as needed
];

describe("modifySnippet", () => {
	// Test JavaScript/TypeScript snippets
	describe("JavaScript/TypeScript", () => {
		jsTestCases.forEach((testCase, index) => {
			it(`should add properties to JS snippet #${index + 1}: ${testCase.description}`, () => {
				const result = modifySnippet(testCase.snippet, testCase.objToAdd);

				// Check that all new properties are added with correct JS syntax
				Object.entries(testCase.objToAdd).forEach(([key, value]) => {
					// For JS, keys are typically camelCase or as-is from the object.
					// The value needs to be regex-matched due to potential complex structures.
					const valueRegexStr = createValueRegex(value, "js");
					// Regex to match 'key: value' or '"key": value' (for keys that might be quoted if they have special chars, though not in SHARED_OBJ_TO_ADD)
					// Allowing for flexible spacing around colon.
					const propertyPattern = new RegExp(`"${key}"\\s*:\\s*${valueRegexStr}|${key}\\s*:\\s*${valueRegexStr}`);
					expect(result).toMatch(propertyPattern);
				});

				// Check that original properties are preserved
				expect(result).toContain("temperature: 0.5");
				expect(result).toContain("top_p: 0.7");

				// Check that the structure is maintained
				expect(result.includes("{") && result.includes("}")).toBeTruthy();
			});
		});
	});

	// Test Python snippets
	describe("Python", () => {
		pythonTestCases.forEach((testCase, index) => {
			it(`should add properties to Python snippet #${index + 1}: ${testCase.description}`, () => {
				const result = modifySnippet(testCase.snippet, testCase.objToAdd);

				// Check that all new properties are added with correct Python syntax
				Object.entries(testCase.objToAdd).forEach(([key, value]) => {
					const valueRegexStr = createValueRegex(value, "python");
					let propertyPattern;

					if (testCase.pythonSyntax === "dict") {
						// Python dict: "key": value
						propertyPattern = new RegExp(`"${key}"\\s*:\\s*${valueRegexStr}`);
					} else {
						// Python kwargs: key=value
						// Convert camelCase keys from SHARED_OBJ_TO_ADD to snake_case for Python kwargs
						const snakeKey = key.replace(/([A-Z])/g, "_$1").toLowerCase();
						propertyPattern = new RegExp(`${snakeKey}\\s*=\\s*${valueRegexStr}`);
					}
					expect(result).toMatch(propertyPattern);
				});

				// Check that original properties are preserved
				if (testCase.pythonSyntax === "dict") {
					expect(result).toContain('"temperature": 0.5');
					expect(result).toContain('"top_p": 0.7');
					expect(result.includes("{") && result.includes("}")).toBeTruthy();
				} else {
					// kwargs
					expect(result).toContain("temperature=0.5");
					expect(result).toContain("top_p=0.7");
					expect(result.includes("(") && result.includes(")")).toBeTruthy();
				}
			});
		});
	});

	// Test Shell/curl snippets
	describe("Shell/curl", () => {
		shellTestCases.forEach((testCase, index) => {
			it(`should add properties to shell snippet #${index + 1}: ${testCase.description}`, () => {
				const result = modifySnippet(testCase.snippet, testCase.objToAdd);

				// Check that all new properties are added with correct JSON syntax
				Object.entries(testCase.objToAdd).forEach(([key, value]) => {
					// For shell/JSON, keys are typically snake_case or as-is.
					// Values need to be regex-matched.
					// Convert camelCase keys from SHARED_OBJ_TO_ADD to snake_case for JSON
					const snakeKey = key.replace(/([A-Z])/g, "_$1").toLowerCase();
					const valueRegexStr = createValueRegex(value, "json");
					const propertyPattern = new RegExp(`"${snakeKey}"\\s*:\\s*${valueRegexStr}`);
					expect(result).toMatch(propertyPattern);
				});

				// Check that original properties are preserved
				expect(result).toContain(`"temperature": 0.5`);
				expect(result).toContain(`"top_p": 0.7`);

				// Check that the structure is maintained
				expect(result.includes("{") && result.includes("}")).toBeTruthy();
			});
		});
	});
});