@thinkhive/sdk 2.0.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.
@@ -0,0 +1,629 @@
1
+ /**
2
+ * ThinkHive TypeScript SDK
3
+ * OpenTelemetry-based observability for AI agents with Explainer integration
4
+ *
5
+ * @version 2.0.0
6
+ */
7
+ export interface InitOptions {
8
+ /** ThinkHive API key (starts with th_) */
9
+ apiKey?: string;
10
+ /** Agent ID for legacy authentication */
11
+ agentId?: string;
12
+ /** ThinkHive API endpoint */
13
+ endpoint?: string;
14
+ /** Service name for traces */
15
+ serviceName?: string;
16
+ /** Enable auto-instrumentation */
17
+ autoInstrument?: boolean;
18
+ /** Frameworks to auto-instrument */
19
+ frameworks?: Array<'langchain' | 'openai' | 'anthropic' | 'llamaindex'>;
20
+ /** Enable debug logging */
21
+ debug?: boolean;
22
+ }
23
+ export interface TraceOptions {
24
+ /** User's message/query */
25
+ userMessage: string;
26
+ /** Agent's response */
27
+ agentResponse: string;
28
+ /** User's detected intent */
29
+ userIntent?: string;
30
+ /** Outcome: success, failure, partial_success */
31
+ outcome?: 'success' | 'failure' | 'partial_success';
32
+ /** Duration in milliseconds */
33
+ duration?: number;
34
+ /** Session ID for conversation tracking */
35
+ sessionId?: string;
36
+ /** Conversation history */
37
+ conversationHistory?: Array<{
38
+ role: string;
39
+ content: string;
40
+ }>;
41
+ /** Span data for detailed analysis */
42
+ spans?: SpanData[];
43
+ /** Business context for ROI calculation */
44
+ businessContext?: BusinessContext;
45
+ /** Custom metadata */
46
+ metadata?: Record<string, unknown>;
47
+ }
48
+ export interface SpanData {
49
+ id?: string;
50
+ name: string;
51
+ type: 'llm' | 'tool' | 'retrieval' | 'embedding' | 'chain' | 'custom';
52
+ startTime?: Date;
53
+ endTime?: Date;
54
+ durationMs?: number;
55
+ status?: 'ok' | 'error' | 'timeout';
56
+ error?: string;
57
+ input?: unknown;
58
+ output?: unknown;
59
+ model?: string;
60
+ provider?: string;
61
+ promptTokens?: number;
62
+ completionTokens?: number;
63
+ toolName?: string;
64
+ toolParameters?: Record<string, unknown>;
65
+ query?: string;
66
+ documentCount?: number;
67
+ topScore?: number;
68
+ sources?: string[];
69
+ children?: SpanData[];
70
+ }
71
+ export interface BusinessContext {
72
+ /** Customer ID */
73
+ customerId?: string;
74
+ /** Transaction value in dollars */
75
+ transactionValue?: number;
76
+ /** Priority level */
77
+ priority?: 'low' | 'medium' | 'high' | 'critical';
78
+ /** Department */
79
+ department?: string;
80
+ /** Industry vertical */
81
+ industry?: string;
82
+ /** Custom fields */
83
+ custom?: Record<string, unknown>;
84
+ }
85
+ export interface ExplainabilityResult {
86
+ traceId: string;
87
+ explainabilityId: string;
88
+ summary: string;
89
+ outcome: {
90
+ verdict: 'success' | 'partial_success' | 'failure';
91
+ confidence: number;
92
+ reasoning: string;
93
+ };
94
+ businessImpact: {
95
+ impactScore: number;
96
+ customerSatisfaction: number;
97
+ revenueRisk: string;
98
+ };
99
+ recommendations: Array<{
100
+ priority: string;
101
+ category: string;
102
+ action: string;
103
+ expectedImpact: string;
104
+ }>;
105
+ ragEvaluation?: {
106
+ groundedness: number;
107
+ faithfulness: number;
108
+ answerRelevance: number;
109
+ };
110
+ hallucinationReport?: {
111
+ detected: boolean;
112
+ types: string[];
113
+ severity: string;
114
+ };
115
+ processingTimeMs: number;
116
+ }
117
+ export interface AnalyzeOptions {
118
+ /** Force a specific analysis tier */
119
+ tier?: 'rule_based' | 'fast_llm' | 'full_llm' | 'deep';
120
+ /** Include RAG evaluation */
121
+ includeRagEvaluation?: boolean;
122
+ /** Include hallucination detection */
123
+ includeHallucinationCheck?: boolean;
124
+ /** Wait for analysis to complete (sync mode) */
125
+ waitForResult?: boolean;
126
+ /** Webhook URL for async notification */
127
+ webhookUrl?: string;
128
+ }
129
+ export interface FeedbackOptions {
130
+ /** Trace ID to provide feedback for */
131
+ traceId: string;
132
+ /** User rating (1-5) */
133
+ rating?: number;
134
+ /** Was the response helpful */
135
+ wasHelpful?: boolean;
136
+ /** Specific issues encountered */
137
+ issues?: Array<'slow_response' | 'incorrect' | 'unhelpful' | 'hallucination' | 'off_topic' | 'other'>;
138
+ /** Free-form comment */
139
+ comment?: string;
140
+ }
141
+ /**
142
+ * Initialize ThinkHive SDK
143
+ *
144
+ * @example
145
+ * ```typescript
146
+ * import { init } from '@thinkhive/sdk';
147
+ *
148
+ * init({
149
+ * apiKey: 'th_your_api_key',
150
+ * serviceName: 'my-ai-agent',
151
+ * autoInstrument: true,
152
+ * frameworks: ['langchain', 'openai'],
153
+ * });
154
+ * ```
155
+ */
156
+ export declare function init(options?: InitOptions): void;
157
+ /**
158
+ * Get the global tracer
159
+ */
160
+ export declare function getTracer(): import("@opentelemetry/api").Tracer;
161
+ /**
162
+ * Check if SDK is initialized
163
+ */
164
+ export declare function isInitialized(): boolean;
165
+ /**
166
+ * Trace an LLM call
167
+ *
168
+ * @example
169
+ * ```typescript
170
+ * const response = await traceLLM({
171
+ * name: 'chat_completion',
172
+ * modelName: 'gpt-4',
173
+ * provider: 'openai',
174
+ * }, async () => {
175
+ * return await openai.chat.completions.create({ ... });
176
+ * });
177
+ * ```
178
+ */
179
+ export declare function traceLLM<T>(options: {
180
+ name: string;
181
+ modelName?: string;
182
+ provider?: string;
183
+ input?: unknown;
184
+ }, fn: () => Promise<T>): Promise<T>;
185
+ /**
186
+ * Trace a retrieval operation
187
+ *
188
+ * @example
189
+ * ```typescript
190
+ * const docs = await traceRetrieval({
191
+ * name: 'vector_search',
192
+ * query: 'What is the return policy?',
193
+ * }, async () => {
194
+ * return await vectorStore.similaritySearch(query, 5);
195
+ * });
196
+ * ```
197
+ */
198
+ export declare function traceRetrieval<T>(options: {
199
+ name: string;
200
+ query?: string;
201
+ topK?: number;
202
+ }, fn: () => Promise<T>): Promise<T>;
203
+ /**
204
+ * Trace a tool call
205
+ *
206
+ * @example
207
+ * ```typescript
208
+ * const result = await traceTool({
209
+ * name: 'search_orders',
210
+ * toolName: 'OrderLookup',
211
+ * parameters: { orderId: '12345' },
212
+ * }, async () => {
213
+ * return await orderService.lookup('12345');
214
+ * });
215
+ * ```
216
+ */
217
+ export declare function traceTool<T>(options: {
218
+ name: string;
219
+ toolName?: string;
220
+ parameters?: Record<string, unknown>;
221
+ }, fn: () => Promise<T>): Promise<T>;
222
+ /**
223
+ * Trace a chain/workflow
224
+ *
225
+ * @example
226
+ * ```typescript
227
+ * const result = await traceChain({
228
+ * name: 'customer_support_chain',
229
+ * }, async () => {
230
+ * // Multiple LLM calls, tools, etc.
231
+ * });
232
+ * ```
233
+ */
234
+ export declare function traceChain<T>(options: {
235
+ name: string;
236
+ input?: unknown;
237
+ }, fn: () => Promise<T>): Promise<T>;
238
+ /**
239
+ * Explainer API client for trace analysis
240
+ */
241
+ export declare const explainer: {
242
+ /**
243
+ * Analyze a trace and get explainability insights
244
+ *
245
+ * @example
246
+ * ```typescript
247
+ * const result = await explainer.analyze({
248
+ * userMessage: 'Help me with my order #12345',
249
+ * agentResponse: 'I found your order...',
250
+ * outcome: 'success',
251
+ * spans: [
252
+ * { name: 'order_lookup', type: 'tool', durationMs: 150 },
253
+ * { name: 'gpt-4', type: 'llm', durationMs: 2500, model: 'gpt-4' },
254
+ * ],
255
+ * });
256
+ * ```
257
+ */
258
+ analyze(trace: TraceOptions, options?: AnalyzeOptions): Promise<ExplainabilityResult>;
259
+ /**
260
+ * Batch analyze multiple traces
261
+ *
262
+ * @example
263
+ * ```typescript
264
+ * const results = await explainer.analyzeBatch([
265
+ * { userMessage: 'Q1', agentResponse: 'A1' },
266
+ * { userMessage: 'Q2', agentResponse: 'A2' },
267
+ * ]);
268
+ * ```
269
+ */
270
+ analyzeBatch(traces: TraceOptions[], options?: AnalyzeOptions): Promise<{
271
+ results: ExplainabilityResult[];
272
+ summary: {
273
+ total: number;
274
+ successCount: number;
275
+ failureCount: number;
276
+ averageProcessingTime: number;
277
+ };
278
+ }>;
279
+ /**
280
+ * Get a previously analyzed trace
281
+ */
282
+ get(traceId: string): Promise<ExplainabilityResult>;
283
+ /**
284
+ * Search traces semantically
285
+ *
286
+ * @example
287
+ * ```typescript
288
+ * const results = await explainer.search({
289
+ * query: 'order refund issues',
290
+ * filters: { outcome: 'failure' },
291
+ * limit: 10,
292
+ * });
293
+ * ```
294
+ */
295
+ search(params: {
296
+ query: string;
297
+ filters?: {
298
+ outcome?: "success" | "failure" | "partial_success";
299
+ minImpactScore?: number;
300
+ dateRange?: {
301
+ from: Date;
302
+ to: Date;
303
+ };
304
+ };
305
+ limit?: number;
306
+ }): Promise<{
307
+ results: Array<ExplainabilityResult & {
308
+ similarity: number;
309
+ }>;
310
+ total: number;
311
+ }>;
312
+ };
313
+ /**
314
+ * Feedback API for improving analysis quality
315
+ */
316
+ export declare const feedback: {
317
+ /**
318
+ * Submit feedback for a trace
319
+ *
320
+ * @example
321
+ * ```typescript
322
+ * await feedback.submit({
323
+ * traceId: 'trace_123',
324
+ * rating: 5,
325
+ * wasHelpful: true,
326
+ * });
327
+ * ```
328
+ */
329
+ submit(options: FeedbackOptions): Promise<{
330
+ success: boolean;
331
+ }>;
332
+ };
333
+ /**
334
+ * Quality metrics API for RAG evaluation and hallucination detection
335
+ */
336
+ export declare const quality: {
337
+ /**
338
+ * Get RAG evaluation scores for a trace
339
+ */
340
+ getRagScores(traceId: string): Promise<{
341
+ contextRelevance: number;
342
+ contextPrecision: number;
343
+ contextRecall: number;
344
+ groundedness: number;
345
+ faithfulness: number;
346
+ answerRelevance: number;
347
+ citationAccuracy: number;
348
+ citationCompleteness: number;
349
+ overallGrade: string;
350
+ }>;
351
+ /**
352
+ * Get hallucination report for a trace
353
+ */
354
+ getHallucinationReport(traceId: string): Promise<{
355
+ hasHallucinations: boolean;
356
+ severity: "none" | "low" | "medium" | "high";
357
+ confidence: number;
358
+ detectedTypes: Array<{
359
+ type: string;
360
+ description: string;
361
+ evidence: string;
362
+ severity: string;
363
+ }>;
364
+ }>;
365
+ /**
366
+ * Evaluate RAG quality for custom input
367
+ */
368
+ evaluateRag(input: {
369
+ query: string;
370
+ response: string;
371
+ contexts: Array<{
372
+ content: string;
373
+ source?: string;
374
+ score?: number;
375
+ }>;
376
+ }): Promise<{
377
+ scores: Record<string, number>;
378
+ grade: string;
379
+ groundedSpans: string[];
380
+ ungroundedSpans: string[];
381
+ }>;
382
+ };
383
+ /**
384
+ * ROI analytics API for business impact tracking
385
+ */
386
+ export declare const analytics: {
387
+ /**
388
+ * Get ROI summary for the account
389
+ */
390
+ getRoiSummary(): Promise<{
391
+ totalRevenueSaved: number;
392
+ supportCostReduction: number;
393
+ averageResolutionTime: number;
394
+ customerSatisfaction: number;
395
+ trends: Array<{
396
+ date: string;
397
+ revenueSaved: number;
398
+ tracesAnalyzed: number;
399
+ }>;
400
+ }>;
401
+ /**
402
+ * Get ROI by agent
403
+ */
404
+ getRoiByAgent(agentId: string): Promise<{
405
+ agentId: string;
406
+ revenueSaved: number;
407
+ tracesAnalyzed: number;
408
+ successRate: number;
409
+ topIssues: Array<{
410
+ issue: string;
411
+ count: number;
412
+ impact: number;
413
+ }>;
414
+ }>;
415
+ /**
416
+ * Get correlation analysis
417
+ */
418
+ getCorrelations(): Promise<{
419
+ correlations: Array<{
420
+ type: string;
421
+ coefficient: number;
422
+ description: string;
423
+ actionableInsight: string;
424
+ }>;
425
+ }>;
426
+ };
427
+ /**
428
+ * Create a trace and analyze it in one call
429
+ *
430
+ * @example
431
+ * ```typescript
432
+ * const { trace, analysis } = await createAndAnalyze({
433
+ * userMessage: 'Help me track my order',
434
+ * agentResponse: 'Your order is on the way...',
435
+ * });
436
+ * ```
437
+ */
438
+ export declare function createAndAnalyze(traceData: TraceOptions, options?: AnalyzeOptions): Promise<{
439
+ trace: TraceOptions;
440
+ analysis: ExplainabilityResult;
441
+ }>;
442
+ declare const _default: {
443
+ init: typeof init;
444
+ getTracer: typeof getTracer;
445
+ isInitialized: typeof isInitialized;
446
+ traceLLM: typeof traceLLM;
447
+ traceRetrieval: typeof traceRetrieval;
448
+ traceTool: typeof traceTool;
449
+ traceChain: typeof traceChain;
450
+ explainer: {
451
+ /**
452
+ * Analyze a trace and get explainability insights
453
+ *
454
+ * @example
455
+ * ```typescript
456
+ * const result = await explainer.analyze({
457
+ * userMessage: 'Help me with my order #12345',
458
+ * agentResponse: 'I found your order...',
459
+ * outcome: 'success',
460
+ * spans: [
461
+ * { name: 'order_lookup', type: 'tool', durationMs: 150 },
462
+ * { name: 'gpt-4', type: 'llm', durationMs: 2500, model: 'gpt-4' },
463
+ * ],
464
+ * });
465
+ * ```
466
+ */
467
+ analyze(trace: TraceOptions, options?: AnalyzeOptions): Promise<ExplainabilityResult>;
468
+ /**
469
+ * Batch analyze multiple traces
470
+ *
471
+ * @example
472
+ * ```typescript
473
+ * const results = await explainer.analyzeBatch([
474
+ * { userMessage: 'Q1', agentResponse: 'A1' },
475
+ * { userMessage: 'Q2', agentResponse: 'A2' },
476
+ * ]);
477
+ * ```
478
+ */
479
+ analyzeBatch(traces: TraceOptions[], options?: AnalyzeOptions): Promise<{
480
+ results: ExplainabilityResult[];
481
+ summary: {
482
+ total: number;
483
+ successCount: number;
484
+ failureCount: number;
485
+ averageProcessingTime: number;
486
+ };
487
+ }>;
488
+ /**
489
+ * Get a previously analyzed trace
490
+ */
491
+ get(traceId: string): Promise<ExplainabilityResult>;
492
+ /**
493
+ * Search traces semantically
494
+ *
495
+ * @example
496
+ * ```typescript
497
+ * const results = await explainer.search({
498
+ * query: 'order refund issues',
499
+ * filters: { outcome: 'failure' },
500
+ * limit: 10,
501
+ * });
502
+ * ```
503
+ */
504
+ search(params: {
505
+ query: string;
506
+ filters?: {
507
+ outcome?: "success" | "failure" | "partial_success";
508
+ minImpactScore?: number;
509
+ dateRange?: {
510
+ from: Date;
511
+ to: Date;
512
+ };
513
+ };
514
+ limit?: number;
515
+ }): Promise<{
516
+ results: Array<ExplainabilityResult & {
517
+ similarity: number;
518
+ }>;
519
+ total: number;
520
+ }>;
521
+ };
522
+ feedback: {
523
+ /**
524
+ * Submit feedback for a trace
525
+ *
526
+ * @example
527
+ * ```typescript
528
+ * await feedback.submit({
529
+ * traceId: 'trace_123',
530
+ * rating: 5,
531
+ * wasHelpful: true,
532
+ * });
533
+ * ```
534
+ */
535
+ submit(options: FeedbackOptions): Promise<{
536
+ success: boolean;
537
+ }>;
538
+ };
539
+ quality: {
540
+ /**
541
+ * Get RAG evaluation scores for a trace
542
+ */
543
+ getRagScores(traceId: string): Promise<{
544
+ contextRelevance: number;
545
+ contextPrecision: number;
546
+ contextRecall: number;
547
+ groundedness: number;
548
+ faithfulness: number;
549
+ answerRelevance: number;
550
+ citationAccuracy: number;
551
+ citationCompleteness: number;
552
+ overallGrade: string;
553
+ }>;
554
+ /**
555
+ * Get hallucination report for a trace
556
+ */
557
+ getHallucinationReport(traceId: string): Promise<{
558
+ hasHallucinations: boolean;
559
+ severity: "none" | "low" | "medium" | "high";
560
+ confidence: number;
561
+ detectedTypes: Array<{
562
+ type: string;
563
+ description: string;
564
+ evidence: string;
565
+ severity: string;
566
+ }>;
567
+ }>;
568
+ /**
569
+ * Evaluate RAG quality for custom input
570
+ */
571
+ evaluateRag(input: {
572
+ query: string;
573
+ response: string;
574
+ contexts: Array<{
575
+ content: string;
576
+ source?: string;
577
+ score?: number;
578
+ }>;
579
+ }): Promise<{
580
+ scores: Record<string, number>;
581
+ grade: string;
582
+ groundedSpans: string[];
583
+ ungroundedSpans: string[];
584
+ }>;
585
+ };
586
+ analytics: {
587
+ /**
588
+ * Get ROI summary for the account
589
+ */
590
+ getRoiSummary(): Promise<{
591
+ totalRevenueSaved: number;
592
+ supportCostReduction: number;
593
+ averageResolutionTime: number;
594
+ customerSatisfaction: number;
595
+ trends: Array<{
596
+ date: string;
597
+ revenueSaved: number;
598
+ tracesAnalyzed: number;
599
+ }>;
600
+ }>;
601
+ /**
602
+ * Get ROI by agent
603
+ */
604
+ getRoiByAgent(agentId: string): Promise<{
605
+ agentId: string;
606
+ revenueSaved: number;
607
+ tracesAnalyzed: number;
608
+ successRate: number;
609
+ topIssues: Array<{
610
+ issue: string;
611
+ count: number;
612
+ impact: number;
613
+ }>;
614
+ }>;
615
+ /**
616
+ * Get correlation analysis
617
+ */
618
+ getCorrelations(): Promise<{
619
+ correlations: Array<{
620
+ type: string;
621
+ coefficient: number;
622
+ description: string;
623
+ actionableInsight: string;
624
+ }>;
625
+ }>;
626
+ };
627
+ createAndAnalyze: typeof createAndAnalyze;
628
+ };
629
+ export default _default;