netra-sdk 1.8.0 → 1.10.0

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.
package/dist/index.js CHANGED
@@ -579,7 +579,7 @@ var Usage = class {
579
579
  };
580
580
 
581
581
  // src/version.ts
582
- var SDK_VERSION = "1.8.0";
582
+ var SDK_VERSION = "1.10.0";
583
583
 
584
584
  // src/config.ts
585
585
  var NetraInstruments = /* @__PURE__ */ ((NetraInstruments2) => {
@@ -669,11 +669,6 @@ var _Config = class _Config {
669
669
  "NETRA_DEBUG",
670
670
  false
671
671
  );
672
- this.enableRootSpan = this._getBoolConfig(
673
- config.enableRootSpan,
674
- "NETRA_ENABLE_ROOT_SPAN",
675
- false
676
- );
677
672
  this.enableScrubbing = this._getBoolConfig(
678
673
  config.enableScrubbing,
679
674
  "NETRA_ENABLE_SCRUBBING",
@@ -823,6 +818,11 @@ _Config.SDK_NAME = "netra";
823
818
  _Config.LIBRARY_NAME = "netra";
824
819
  _Config.LIBRARY_VERSION = SDK_VERSION;
825
820
  _Config.TRIAL_BLOCK_DURATION_SECONDS = 900;
821
+ // 15 minutes
822
+ // Root-span attribute marking traces produced by evaluation/simulation runs
823
+ // so the FE/BE can distinguish them from normal workflow invocations.
824
+ _Config.TRACE_ORIGIN_KEY = "netra.trace.origin";
825
+ _Config.TRACE_ORIGIN_EVALUATION = "evaluation";
826
826
  var Config = _Config;
827
827
 
828
828
  // src/utils/pattern-matching.ts
@@ -1943,13 +1943,13 @@ async function runSingleEvaluator(params) {
1943
1943
  if (config) {
1944
1944
  expectedName = config.name;
1945
1945
  }
1946
- const context17 = {
1946
+ const context16 = {
1947
1947
  input: itemInput,
1948
1948
  taskOutput,
1949
1949
  expectedOutput,
1950
1950
  metadata
1951
1951
  };
1952
- let result = evaluator.evaluate(context17);
1952
+ let result = evaluator.evaluate(context16);
1953
1953
  if (result instanceof Promise) {
1954
1954
  result = await result;
1955
1955
  }
@@ -2293,7 +2293,11 @@ var Evaluation = class {
2293
2293
  */
2294
2294
  async executeItemPipeline(runId, runName, ctx, task2, evaluators, results, bgEvalTasks) {
2295
2295
  const spanName = `TestRun.${runName}`;
2296
- const span2 = new SpanWrapper(spanName, {}, "netra.evaluation");
2296
+ const span2 = new SpanWrapper(
2297
+ spanName,
2298
+ { [Config.TRACE_ORIGIN_KEY]: Config.TRACE_ORIGIN_EVALUATION },
2299
+ "netra.evaluation"
2300
+ );
2297
2301
  span2.start();
2298
2302
  try {
2299
2303
  const otelSpan = span2.getCurrentSpan();
@@ -2696,6 +2700,42 @@ var DashboardHttpClient = class extends NetraHttpClient {
2696
2700
  return null;
2697
2701
  }
2698
2702
  }
2703
+ /**
2704
+ * Get detailed information for a specific session including all its traces.
2705
+ *
2706
+ * Args:
2707
+ * sessionId: The session ID to retrieve details for.
2708
+ *
2709
+ * Returns:
2710
+ * The session details response data or null on error.
2711
+ */
2712
+ async getSessionDetails(sessionId) {
2713
+ if (!this.isInitialized()) {
2714
+ Logger.error(
2715
+ "netra.dashboard: Dashboard client is not initialized; cannot get session details"
2716
+ );
2717
+ return null;
2718
+ }
2719
+ try {
2720
+ const url = `/public/dashboard/session/${encodeURIComponent(sessionId)}`;
2721
+ const response = await this.get(url);
2722
+ if (!response.ok) {
2723
+ const errorMessage = response.data?.error?.message ?? "Unknown error";
2724
+ Logger.error(
2725
+ `netra.dashboard: Failed to fetch session details: ${errorMessage}`
2726
+ );
2727
+ return null;
2728
+ }
2729
+ return response.data;
2730
+ } catch (err) {
2731
+ const message = err?.response?.data?.error?.message ?? "";
2732
+ Logger.error(
2733
+ "netra.dashboard: Failed to fetch session details:",
2734
+ message
2735
+ );
2736
+ return null;
2737
+ }
2738
+ }
2699
2739
  };
2700
2740
 
2701
2741
  // src/api/dashboard/models.ts
@@ -2919,6 +2959,19 @@ var Dashboard = class {
2919
2959
  }
2920
2960
  return result.data ?? {};
2921
2961
  }
2962
+ async getSessionDetails(sessionId) {
2963
+ if (!sessionId) {
2964
+ Logger.error(
2965
+ "netra.dashboard: session_id is required to fetch session details"
2966
+ );
2967
+ return null;
2968
+ }
2969
+ const result = await this.client.getSessionDetails(sessionId);
2970
+ if (!result) {
2971
+ return null;
2972
+ }
2973
+ return result.data ?? result;
2974
+ }
2922
2975
  isValidScope(scope) {
2923
2976
  return Object.values(Scope).includes(scope);
2924
2977
  }
@@ -2939,6 +2992,33 @@ var Dashboard = class {
2939
2992
  }
2940
2993
  };
2941
2994
 
2995
+ // src/cache.ts
2996
+ var TTLCache = class {
2997
+ constructor(defaultTtl = 60) {
2998
+ this.store = /* @__PURE__ */ new Map();
2999
+ this.defaultTtl = defaultTtl;
3000
+ }
3001
+ get(key) {
3002
+ const entry = this.store.get(key);
3003
+ if (!entry) return void 0;
3004
+ if (performance.now() > entry.expiresAt) {
3005
+ this.store.delete(key);
3006
+ return void 0;
3007
+ }
3008
+ return entry.value;
3009
+ }
3010
+ set(key, value, ttl) {
3011
+ const ttlMs = (ttl ?? this.defaultTtl) * 1e3;
3012
+ this.store.set(key, { value, expiresAt: performance.now() + ttlMs });
3013
+ }
3014
+ invalidate(key) {
3015
+ this.store.delete(key);
3016
+ }
3017
+ clear() {
3018
+ this.store.clear();
3019
+ }
3020
+ };
3021
+
2942
3022
  // src/api/prompts/client.ts
2943
3023
  var PromptsHttpClient = class extends NetraHttpClient {
2944
3024
  constructor(config) {
@@ -2974,17 +3054,27 @@ var PromptsHttpClient = class extends NetraHttpClient {
2974
3054
  }
2975
3055
  };
2976
3056
 
3057
+ // src/api/prompts/models.ts
3058
+ var PROMPT_CACHE_TTL_SECONDS = 60;
3059
+
2977
3060
  // src/api/prompts/api.ts
2978
3061
  var Prompts = class {
2979
3062
  constructor(config) {
2980
3063
  this.config = config;
2981
3064
  this.client = new PromptsHttpClient(config);
3065
+ this.cache = new TTLCache(PROMPT_CACHE_TTL_SECONDS);
3066
+ }
3067
+ /** Clear all cached prompt entries. */
3068
+ clearCache() {
3069
+ this.cache.clear();
2982
3070
  }
2983
3071
  /**
2984
3072
  * Fetch prompt version by name and label.
2985
3073
  *
2986
- * @param params.name - Name of the prompt (required)
2987
- * @param params.label - Label of the prompt version (default: "production")
3074
+ * @param params.name - Name of the prompt (required)
3075
+ * @param params.label - Label of the prompt version (default: "production")
3076
+ * @param params.useCache - When true, read/write the in-memory cache (default: false)
3077
+ * @param params.cacheTtl - Per-call cache TTL in seconds (default: PROMPT_CACHE_TTL_SECONDS)
2988
3078
  */
2989
3079
  async getPrompt(params) {
2990
3080
  if (!params || typeof params.name !== "string" || !params.name) {
@@ -2992,11 +3082,99 @@ var Prompts = class {
2992
3082
  return null;
2993
3083
  }
2994
3084
  const label = params.label ?? "production";
3085
+ const useCache = params.useCache === true;
3086
+ const cacheKey = `prompt:${params.name}:${label}`;
3087
+ if (useCache) {
3088
+ const cached = this.cache.get(cacheKey);
3089
+ if (cached !== void 0) {
3090
+ return cached;
3091
+ }
3092
+ }
2995
3093
  const result = await this.client.getPromptVersion(params.name, label);
2996
3094
  if (!result) {
2997
3095
  return null;
2998
3096
  }
2999
- return result.data ?? null;
3097
+ const data = result.data ?? null;
3098
+ if (data !== null && useCache) {
3099
+ this.cache.set(cacheKey, data, params.cacheTtl);
3100
+ }
3101
+ return data;
3102
+ }
3103
+ };
3104
+
3105
+ // src/api/models/client.ts
3106
+ var ModelsHttpClient = class extends NetraHttpClient {
3107
+ constructor(config) {
3108
+ super(config, "NETRA_MODELS_TIMEOUT", 10);
3109
+ }
3110
+ async getModelPricing(name) {
3111
+ if (!this.isInitialized()) {
3112
+ Logger.error(
3113
+ "netra.models: Models client is not initialized; cannot fetch model pricing"
3114
+ );
3115
+ return null;
3116
+ }
3117
+ try {
3118
+ const params = name ? { name } : void 0;
3119
+ const response = await this.get("/sdk/models", params);
3120
+ if (!response.ok) {
3121
+ const errorMessage = response.data?.error?.message ?? "Unknown error";
3122
+ Logger.error(
3123
+ `netra.models: Failed to fetch model pricing: ${errorMessage}`
3124
+ );
3125
+ return null;
3126
+ }
3127
+ const items = this.extractData(response, null);
3128
+ if (items !== null && !Array.isArray(items)) {
3129
+ Logger.error(
3130
+ "netra.models: Unexpected response format; expected an array"
3131
+ );
3132
+ return null;
3133
+ }
3134
+ return items;
3135
+ } catch (err) {
3136
+ const message = err?.response?.data?.error?.message ?? err?.message ?? "";
3137
+ Logger.error("netra.models: Failed to fetch model pricing:", message);
3138
+ return null;
3139
+ }
3140
+ }
3141
+ };
3142
+
3143
+ // src/api/models/models.ts
3144
+ var MODEL_PRICING_CACHE_TTL_SECONDS = 300;
3145
+
3146
+ // src/api/models/api.ts
3147
+ var Models = class {
3148
+ constructor(config) {
3149
+ this.config = config;
3150
+ this.client = new ModelsHttpClient(config);
3151
+ this.cache = new TTLCache(MODEL_PRICING_CACHE_TTL_SECONDS);
3152
+ }
3153
+ /** Clear all cached model pricing entries. */
3154
+ clearCache() {
3155
+ this.cache.clear();
3156
+ }
3157
+ /**
3158
+ * Fetch model pricing from the backend.
3159
+ *
3160
+ * @param params.name - Optional model name filter
3161
+ * @param params.useCache - When true, read/write the in-memory cache (default: false)
3162
+ * @param params.cacheTtl - Per-call cache TTL in seconds (default: MODEL_PRICING_CACHE_TTL_SECONDS)
3163
+ */
3164
+ async getModelPricing(params = {}) {
3165
+ const useCache = params.useCache === true;
3166
+ const cacheKey = `model:pricing:${params.name ?? "all"}`;
3167
+ if (useCache) {
3168
+ const cached = this.cache.get(cacheKey);
3169
+ if (cached !== void 0) {
3170
+ return cached;
3171
+ }
3172
+ }
3173
+ const data = await this.client.getModelPricing(params.name);
3174
+ if (data !== null && useCache) {
3175
+ this.cache.set(cacheKey, data, params.cacheTtl);
3176
+ }
3177
+ return data;
3000
3178
  }
3001
3179
  };
3002
3180
 
@@ -3834,6 +4012,13 @@ var SpanIOProcessor = class {
3834
4012
  if (key === _USAGE_OUTPUT_TOKENS) {
3835
4013
  return original(_USAGE_COMPLETION_TOKENS, value);
3836
4014
  }
4015
+ if (key === "db.statement") {
4016
+ original(key, value);
4017
+ if (!inputLocked() && inputIsEmpty() && !isEmpty(value)) {
4018
+ original("input", typeof value === "string" ? value : String(value));
4019
+ }
4020
+ return span2;
4021
+ }
3837
4022
  return original(key, value);
3838
4023
  } catch (e) {
3839
4024
  Logger.debug(`SpanIOProcessor: error processing key=${key}`, e);
@@ -4414,7 +4599,7 @@ function setUsageAttributes(span2, response) {
4414
4599
  Number(cacheReadTokens)
4415
4600
  );
4416
4601
  }
4417
- const cacheCreationTokens = usage.cache_creation_input_tokens;
4602
+ const cacheCreationTokens = usage.cache_creation_input_tokens ?? (usage.prompt_tokens_details ?? usage.input_tokens_details)?.cache_write_tokens;
4418
4603
  if (cacheCreationTokens !== void 0) {
4419
4604
  span2.setAttribute(
4420
4605
  SpanAttributes2.LLM_USAGE_CACHE_CREATION_INPUT_TOKENS,
@@ -12359,7 +12544,7 @@ var SimulationHttpClient = class {
12359
12544
  * Used in the two-phase flow so that beforeAll/before hooks can run
12360
12545
  * before any LLM spend.
12361
12546
  */
12362
- async initializeRun(name, datasetId, context17, hooksMeta) {
12547
+ async initializeRun(name, datasetId, context16, hooksMeta) {
12363
12548
  if (!this.client) {
12364
12549
  Logger.error(`${LOG_PREFIX5}: Client not initialized`);
12365
12550
  return null;
@@ -12369,7 +12554,7 @@ var SimulationHttpClient = class {
12369
12554
  const payload = {
12370
12555
  name,
12371
12556
  datasetId,
12372
- context: context17 || {}
12557
+ context: context16 || {}
12373
12558
  };
12374
12559
  if (hooksMeta) {
12375
12560
  payload.lifecycleHooks = hooksMeta;
@@ -12687,7 +12872,7 @@ var Simulation = class {
12687
12872
  name,
12688
12873
  datasetId,
12689
12874
  task: task2,
12690
- context: context17,
12875
+ context: context16,
12691
12876
  maxConcurrency = 5,
12692
12877
  hooks
12693
12878
  } = options;
@@ -12699,7 +12884,7 @@ var Simulation = class {
12699
12884
  const initResult = await this._client.initializeRun(
12700
12885
  name,
12701
12886
  datasetId,
12702
- context17,
12887
+ context16,
12703
12888
  hooksMeta && Object.keys(hooksMeta).length > 0 ? hooksMeta : null
12704
12889
  );
12705
12890
  if (!initResult) {
@@ -13000,7 +13185,11 @@ var Simulation = class {
13000
13185
  let sessionId = null;
13001
13186
  let rawFiles = initialFiles ?? [];
13002
13187
  while (true) {
13003
- const span2 = new SpanWrapper(SPAN_NAME, {}, LOG_PREFIX7);
13188
+ const span2 = new SpanWrapper(
13189
+ SPAN_NAME,
13190
+ { [Config.TRACE_ORIGIN_KEY]: Config.TRACE_ORIGIN_EVALUATION },
13191
+ LOG_PREFIX7
13192
+ );
13004
13193
  span2.start();
13005
13194
  try {
13006
13195
  const traceId = span2.getCurrentSpan()?.spanContext().traceId ?? "";
@@ -13261,6 +13450,9 @@ var Netra = class {
13261
13450
  static isInitialized() {
13262
13451
  return this._initialized;
13263
13452
  }
13453
+ /**
13454
+ * Initialize the Netra SDK.
13455
+ */
13264
13456
  static async init(config = {}) {
13265
13457
  if (this._initialized) {
13266
13458
  Logger.warn("Netra.init() called more than once; ignoring subsequent calls.");
@@ -13302,6 +13494,11 @@ var Netra = class {
13302
13494
  } catch (e) {
13303
13495
  Logger.warn("Netra: failed to initialize prompts client:", e);
13304
13496
  }
13497
+ try {
13498
+ this.models = new Models(cfg);
13499
+ } catch (e) {
13500
+ Logger.warn("Netra: failed to initialize models client:", e);
13501
+ }
13305
13502
  this._initialized = true;
13306
13503
  Logger.info("Netra successfully initialized.");
13307
13504
  {
@@ -13340,26 +13537,6 @@ Received ${signal}. Shutting down Netra SDK...`);
13340
13537
  process.once("SIGINT", () => handleSignal("SIGINT"));
13341
13538
  process.once("SIGTERM", () => handleSignal("SIGTERM"));
13342
13539
  process.once("uncaughtException", handleUncaughtException);
13343
- if (cfg.enableRootSpan) {
13344
- const tracer2 = this._tracer || trace.getTracer("netra.root.span");
13345
- const rootName = `${Config.LIBRARY_NAME}.root.span`;
13346
- this._rootSpan = tracer2.startSpan(rootName, {
13347
- kind: SpanKind.INTERNAL
13348
- });
13349
- if (this._rootSpan) {
13350
- if (cfg.appName) {
13351
- this._rootSpan.setAttribute("service.name", cfg.appName);
13352
- }
13353
- this._rootSpan.setAttribute("netra.environment", cfg.environment);
13354
- this._rootSpan.setAttribute(
13355
- "netra.library.version",
13356
- Config.LIBRARY_VERSION
13357
- );
13358
- Logger.info(
13359
- "Netra root span created. Use Netra.runWithRootSpan() to parent spans under it."
13360
- );
13361
- }
13362
- }
13363
13540
  await instrumentationsReady;
13364
13541
  }
13365
13542
  static async shutdown() {
@@ -13371,14 +13548,6 @@ Received ${signal}. Shutting down Netra SDK...`);
13371
13548
  } catch (e) {
13372
13549
  Logger.error("Error during uninstrumentAll:", e);
13373
13550
  }
13374
- if (this._rootSpan) {
13375
- try {
13376
- this._rootSpan.end();
13377
- } catch (e) {
13378
- } finally {
13379
- this._rootSpan = void 0;
13380
- }
13381
- }
13382
13551
  const FLUSH_TIMEOUT_MS = 5e3;
13383
13552
  try {
13384
13553
  const traceProvider = trace.getTracerProvider();
@@ -13397,6 +13566,12 @@ Received ${signal}. Shutting down Netra SDK...`);
13397
13566
  } catch (e) {
13398
13567
  Logger.error("Error during Netra trace shutdown:", e);
13399
13568
  }
13569
+ try {
13570
+ this.prompts?.clearCache();
13571
+ this.models?.clearCache();
13572
+ } catch (e) {
13573
+ Logger.error("Error clearing SDK API caches:", e);
13574
+ }
13400
13575
  this._initialized = false;
13401
13576
  this._tracer = void 0;
13402
13577
  }
@@ -13415,20 +13590,6 @@ Received ${signal}. Shutting down Netra SDK...`);
13415
13590
  static setRootOutput(value) {
13416
13591
  SessionManager.setRootOutput(value);
13417
13592
  }
13418
- /**
13419
- * Run a function with the root span as the active parent context.
13420
- * All spans created within this function will be children of the root span.
13421
- * Note: required in JS because OTel JS has no persistent context.attach()
13422
- */
13423
- static runWithRootSpan(fn) {
13424
- if (!this._rootSpan) {
13425
- Logger.warn(
13426
- "runWithRootSpan: No root span available. Running function without parent context."
13427
- );
13428
- return fn();
13429
- }
13430
- return context.with(trace.setSpan(context.active(), this._rootSpan), fn);
13431
- }
13432
13593
  static setSessionId(sessionId) {
13433
13594
  if (typeof sessionId !== "string") {
13434
13595
  Logger.error(`setSessionId: sessionId must be a string, got ${typeof sessionId}`);
@@ -13569,6 +13730,6 @@ Netra._metricsEnabled = false;
13569
13730
  Netra.withBlockedSpansLocal = withBlockedSpansLocal;
13570
13731
  var index_default = Netra;
13571
13732
 
13572
- export { Aggregation, BaseTask, ChartType, Config, ConversationType, DEFAULT_INSTRUMENTS, DEFAULT_INSTRUMENTS_FOR_ROOT, Dashboard, DimensionField, EntryStatus, Evaluation, FilterField, FilterType, FilteringSpanExporter, GroupBy, InstrumentationSpanProcessor, Measure, Netra, NetraAgentsTracingProcessor, NetraInstruments, NetraOpenAIAgentsInstrumentor, Operator, Prompts, RunEntryContext, RunStatus, Scope, ScrubbingSpanProcessor, SerializationSpanProcessor, SessionSpanProcessor, Simulation, SpanIOProcessor, SpanType, TrialAwareOTLPExporter, TruncatingSerializer, Usage, agent, index_default as default, metadataField, mistralAIInstrumentor, netraExpressMiddleware, openaiAgentsInstrumentor, runWithExtractedContext, safeStringify, span, task, workflow };
13733
+ export { Aggregation, BaseTask, ChartType, Config, ConversationType, DEFAULT_INSTRUMENTS, DEFAULT_INSTRUMENTS_FOR_ROOT, Dashboard, DimensionField, EntryStatus, Evaluation, FilterField, FilterType, FilteringSpanExporter, GroupBy, InstrumentationSpanProcessor, MODEL_PRICING_CACHE_TTL_SECONDS, Measure, Models, Netra, NetraAgentsTracingProcessor, NetraInstruments, NetraOpenAIAgentsInstrumentor, Operator, PROMPT_CACHE_TTL_SECONDS, Prompts, RunEntryContext, RunStatus, Scope, ScrubbingSpanProcessor, SerializationSpanProcessor, SessionSpanProcessor, Simulation, SpanIOProcessor, SpanType, TrialAwareOTLPExporter, TruncatingSerializer, Usage, agent, index_default as default, metadataField, mistralAIInstrumentor, netraExpressMiddleware, openaiAgentsInstrumentor, runWithExtractedContext, safeStringify, span, task, workflow };
13573
13734
  //# sourceMappingURL=index.js.map
13574
13735
  //# sourceMappingURL=index.js.map