Spaces:
Sleeping
Sleeping
File size: 12,043 Bytes
76a90de | 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 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 | /**
* Response processing utilities for formatting model output.
* Handles code extraction, markdown formatting, math delimiters, and indentation.
*/
const FENCE_PLACEHOLDER = '\u0000FENCE';
/**
* Convert LaTeX `\(...\)` / `\[...\]` to `$...$` / `$$...$$` for remark-math.
* Matches the closing backslash-delimiter so nested parentheses stay intact.
* Fenced code blocks are left unchanged.
*/
export function normalizeMathDelimiters(content: string): string {
if (!content) return content;
const fences: string[] = [];
const withPlaceholders = content.replace(/```[\s\S]*?```/g, (block) => {
const token = `${FENCE_PLACEHOLDER}${fences.length}\u0000`;
fences.push(block);
return token;
});
const converted = convertLatexDelimiters(withPlaceholders);
return converted.replace(
new RegExp(`${FENCE_PLACEHOLDER}(\\d+)\u0000`, 'g'),
(_, i) => fences[Number(i)]
);
}
function convertLatexDelimiters(content: string): string {
let result = '';
let i = 0;
const n = content.length;
while (i < n) {
if (content[i] === '\\' && i + 1 < n) {
const next = content[i + 1];
if (next === '[' || next === '(') {
const closer = next === '[' ? '\\]' : '\\)';
const close = findClosingDelimiter(content, i + 2, closer);
if (close !== -1) {
const inner = content.slice(i + 2, close).trim();
if (next === '[') {
result += `\n$$\n${inner}\n$$\n`;
} else {
result += `$${inner}$`;
}
i = close + 2;
continue;
}
}
}
result += content[i];
i++;
}
return result;
}
function findClosingDelimiter(content: string, start: number, closer: string): number {
for (let i = start; i < content.length - 1; i++) {
if (content[i] !== closer[0] || content[i + 1] !== closer[1]) continue;
let backslashes = 0;
for (let j = i - 1; j >= start && content[j] === '\\'; j--) {
backslashes++;
}
if (backslashes % 2 === 0) {
return i;
}
}
return -1;
}
/**
* Detect whether text looks like Python/Qiskit (or similar) code.
*/
export function looksLikeCode(text: string): boolean {
if (text.includes('\n')) {
const codeIndicators = [
/^from\s+/m,
/^import\s+/m,
/^def\s+/m,
/^class\s+/m,
/^\s*return\s+/m,
/QuantumCircuit/,
/Parameter\(/,
/\.\w+\([^)]*\)/m,
];
return codeIndicators.some((p) => p.test(text));
}
const singleLinePatterns = [
/^return\s+\w+/,
/^\w+\s*=\s*\w+\([^)]*\)/,
/^\w+\.\w+\([^)]*\)$/,
/\w+\s*=\s*\w+\([^)]*\)(?:\s+\w+\.|\s+\w+\s*=)/,
/QuantumCircuit\(/,
/Parameter\(/,
/\.control\(/,
/\.measure\(/,
];
return singleLinePatterns.some((p) => p.test(text.trim()));
}
/**
* Prepare model output for markdown rendering: math delimiters, then
* wrap unfenced code in a python block when the whole response is code.
*/
export function prepareMarkdownContent(content: string): string {
let prepared = normalizeMathDelimiters(content);
if (
!prepared.includes('```') &&
!prepared.includes('$$') &&
!prepared.includes('$') &&
looksLikeCode(prepared)
) {
prepared = prepared
.replace(/(\w+\s*=\s*\w+\([^)]*\))\s+(\w+\.)/g, '$1\n$2')
.replace(/(\w+\.[a-z_]+\([^)]*\))\s+(\w+\.)/g, '$1\n$2');
prepared = '```python\n' + prepared + '\n```';
}
return prepared;
}
/**
* Strip markdown fences and collapse whitespace for compact list previews.
* If the question is only a code fence, keep a short excerpt (e.g. the def line).
*/
export function previewText(text: string, maxLength: number = 120): string {
const fenceBodies: string[] = [];
const withoutFences = text.replace(/```(?:\w+)?\s*\n?([\s\S]*?)```/g, (_, body) => {
fenceBodies.push(body);
return ' ';
});
let preview = withoutFences
.replace(/`+/g, '')
.replace(/!\[[^\]]*\]\([^)]*\)/g, ' ')
.replace(/\s+/g, ' ')
.trim();
if (preview.length < 24 && fenceBodies.length > 0) {
const lines = fenceBodies[0]
.split('\n')
.map((line) => line.trim())
.filter((line) => line.length > 0 && line !== 'pass' && !line.startsWith('#'));
const excerpt = lines.find((line) => line.startsWith('def ')) || lines[0];
if (excerpt) {
preview = preview ? `${preview} ${excerpt}` : excerpt;
}
}
if (preview.length <= maxLength) return preview;
return preview.substring(0, maxLength).trimEnd() + '...';
}
/**
* Extract code blocks from model response.
* Handles markdown code blocks and detects code patterns.
*/
export function extractCodeFromResponse(response: string, entryPoint?: string): string {
// Find all markdown code blocks
const codeBlockRegex = /```(?:python)?\s*\n([\s\S]*?)```/g;
const matches: string[] = [];
let match;
while ((match = codeBlockRegex.exec(response)) !== null) {
// Preserve indentation - only trim trailing whitespace, not leading
matches.push(match[1].replace(/\s+$/, ''));
}
if (matches.length === 0) {
// No code blocks found - the response itself might be code
// Preserve indentation by only trimming trailing whitespace
return response.replace(/\s+$/, '');
}
if (matches.length === 1) {
return matches[0];
}
// If multiple blocks, prefer one with entry point
if (entryPoint) {
const entryPointRegex = new RegExp(`def\\s+${escapeRegex(entryPoint)}\\s*\\(`);
for (const block of matches) {
if (entryPointRegex.test(block)) {
return block;
}
}
}
// Return longest block
return matches.reduce((a, b) => (a.length > b.length ? a : b));
}
/**
* Detect if text contains Python code patterns.
*/
export function detectsPythonCode(text: string): boolean {
const pythonPatterns = [
/^from\s+\w+\s+import/m,
/^import\s+\w+/m,
/^def\s+\w+\s*\(/m,
/^class\s+\w+/m,
/^\s*@\w+/m, // decorators
/QuantumCircuit\s*\(/,
/\.h\s*\(/,
/\.cx\s*\(/,
/\.measure/,
/qc\s*=\s*QuantumCircuit/,
];
return pythonPatterns.some((pattern) => pattern.test(text));
}
/**
* Format response with proper markdown code blocks.
* Ensures code is properly fenced for rendering.
*/
export function formatResponseWithCodeBlocks(response: string): string {
// If response already has code blocks, return as-is
if (/```[\s\S]*```/.test(response)) {
return response;
}
// Check if the entire response looks like code
const lines = response.split('\n');
const codeLines = lines.filter((line) => {
const trimmed = line.trim();
return (
trimmed.startsWith('from ') ||
trimmed.startsWith('import ') ||
trimmed.startsWith('def ') ||
trimmed.startsWith('class ') ||
trimmed.startsWith('@') ||
trimmed.startsWith('#') ||
/^\s*\w+\s*=/.test(trimmed) ||
/^\s*\w+\.\w+\(/.test(trimmed) ||
/^\s*return\s/.test(trimmed) ||
/^\s*if\s/.test(trimmed) ||
/^\s*for\s/.test(trimmed) ||
/^\s*while\s/.test(trimmed) ||
/^\s*try:/.test(trimmed) ||
/^\s*except/.test(trimmed) ||
trimmed === '' ||
trimmed === 'pass'
);
});
// If most lines look like code, wrap entire response
if (codeLines.length > lines.length * 0.7 && detectsPythonCode(response)) {
return '```python\n' + response.trim() + '\n```';
}
// Try to detect inline code that should be blocks
// Pattern: text followed by code on same line or multiple statements
const inlineCodePattern =
/(from\s+\w+\s+import\s+[\w,\s]+)\s+([\w]+\s*=\s*\w+\([^)]*\)(?:\s+[\w.]+\([^)]*\))*)/g;
if (inlineCodePattern.test(response)) {
// Split inline code into proper lines
const formatted = response
.replace(
/(from\s+\w+\s+import\s+[\w,\s]+)/g,
'\n```python\n$1'
)
.replace(
/\s+([\w]+\s*=\s*\w+\([^)]*\))/g,
'\n$1'
)
.replace(
/(\s+[\w.]+\([^)]*\))(?=\s+[\w.]+\()/g,
'$1\n'
);
// Clean up and close code block
const lines = formatted.split('\n');
let inCodeBlock = false;
const result: string[] = [];
for (const line of lines) {
if (line.includes('```python')) {
inCodeBlock = true;
}
result.push(line);
}
if (inCodeBlock) {
result.push('```');
}
return result.join('\n');
}
return response;
}
/**
* Process streaming chunk to maintain markdown structure.
* Handles partial code blocks during streaming.
*/
export function processStreamingContent(
fullContent: string,
previousContent: string
): { content: string; isInCodeBlock: boolean } {
// Count code block markers
const openMarkers = (fullContent.match(/```/g) || []).length;
const isInCodeBlock = openMarkers % 2 === 1;
return {
content: fullContent,
isInCodeBlock,
};
}
/**
* Normalize code indentation.
* Similar to _normalize_body_indentation in synthetic.py
*
* Handles the common pattern where model outputs function completion code with:
* - First line at 0 indentation
* - Subsequent lines with extra indentation (e.g., 4 spaces)
*/
export function normalizeIndentation(code: string, targetIndent: number = 0): string {
const lines = code.split('\n');
const nonEmptyLines = lines
.map((line, idx) => ({ line, idx }))
.filter(({ line }) => line.trim().length > 0);
if (nonEmptyLines.length === 0) {
return code;
}
// Get first non-empty line's indentation
const firstNonEmpty = nonEmptyLines[0];
const firstIndent = getIndent(firstNonEmpty.line);
// Check for the common pattern: first line at 0, rest at 4+
if (firstIndent === 0 && nonEmptyLines.length > 1) {
const subsequentIndents = nonEmptyLines.slice(1).map(({ line }) => getIndent(line));
const minSubsequent = Math.min(...subsequentIndents);
// If subsequent lines have extra indentation, they should align with first line
if (minSubsequent > 0) {
const result: string[] = [];
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (!line.trim()) {
result.push('');
} else if (i === firstNonEmpty.idx) {
// First line gets target indent
result.push(' '.repeat(targetIndent) + line.trim());
} else {
// Subsequent lines: remove extra base indent, add target
const currentIndent = getIndent(line);
const relative = currentIndent - minSubsequent;
const newIndent = ' '.repeat(targetIndent + Math.max(0, relative));
result.push(newIndent + line.trim());
}
}
return result.join('\n');
}
}
// Standard case: subtract min indent and add target
const minIndent = Math.min(
...nonEmptyLines.map(({ line }) => getIndent(line))
);
return lines
.map((line) => {
if (line.trim().length === 0) {
return '';
}
const currentIndent = getIndent(line);
const relativeIndent = currentIndent - minIndent;
const newIndent = ' '.repeat(targetIndent + relativeIndent);
return newIndent + line.trim();
})
.join('\n');
}
/**
* Get the indentation level of a line.
*/
function getIndent(line: string): number {
const match = line.match(/^(\s*)/);
return match ? match[1].length : 0;
}
/**
* Post-process complete response for display.
* Applies formatting, code detection, and normalization.
*/
export function postProcessResponse(response: string): string {
if (!response || response.trim().length === 0) {
return response;
}
// First, try to format with proper code blocks
let processed = formatResponseWithCodeBlocks(response);
// Normalize indentation within code blocks
processed = processed.replace(
/```python\n([\s\S]*?)```/g,
(match, code) => {
const normalized = normalizeIndentation(code.trim());
return '```python\n' + normalized + '\n```';
}
);
return processed;
}
function escapeRegex(string: string): string {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
|