Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

1.4 KB
Raw Blame
import { decodeUnicodeEscapesOnly } from "./unicode";

// Replacer that keeps bigints JSON-serializable and decodes \uXXXX escapes so
// that non-ASCII content (e.g. Japanese ingested with Python ensure_ascii=True)
// renders as real characters instead of escape sequences.
const stringifyReplacer = (_key: string, value: unknown) => {
  if (typeof value === "bigint") return Number.parseInt(value.toString());
  if (typeof value === "string") return decodeUnicodeEscapesOnly(value, true);
  return value;
};

export const stringify = (data: any, key?: string, indent?: number): string => {
  // For comment fields, use pretty-print formatting for better readability
  // Other fields use compact format to reduce file size, unless an explicit
  // indent is requested by the caller (e.g. human-readable trace downloads).
  const resolvedIndent = indent ?? (key === "comments" ? 2 : undefined);

  return JSON.stringify(data, stringifyReplacer, resolvedIndent);
};

/**
 * CSV-specific stringify that returns strings as-is instead of JSON-encoding them.
 * This avoids double-encoding when string fields (e.g. JSON input/output from ClickHouse)
 * are passed through JSON.stringify and then CSV-escaped.
 */
export const stringifyForCsv = (data: any, key?: string): string => {
  if (typeof data === "string") return decodeUnicodeEscapesOnly(data, true);
  return stringify(data, key);
};