glass-ai
v0.1.1
Published
Glass AI TypeScript SDK - OpenTelemetry tracing for AI applications
Maintainers
Readme
Glass AI TypeScript SDK
OpenTelemetry tracing for AI applications.
Installation
npm install glass-ai
# or
yarn add glass-ai
# or
pnpm add glass-aiQuick Start
import * as glass from 'glass-ai';
// Initialize the SDK
glass.init({ apiKey: 'your-api-key' });
// Wrap functions with tracing
const processMessage = glass.trace(async (message: string) => {
// Your AI logic here
return `Processed: ${message}`;
}, { name: 'processMessage' });
// Track user interactions
await glass.interaction({ userId: 'user-123', input: 'Hello!' }, async (ctx) => {
const result = await processMessage('Hello!');
ctx.finish({ response: result });
return result;
});API Reference
Initialization
glass.init(options?: InitOptions): voidInitialize the Glass SDK and configure OpenTelemetry.
Options:
apiKey?: string- Glass API key (or setGLASS_API_KEYenvironment variable)debug?: boolean- Enable console logging of traces (default:false)instrumentations?: Instrumentor[]- Custom OpenTelemetry instrumentorsskipDefaultInstrumentations?: boolean- Skip auto-instrumenting AI libraries (default:false)traceEndpoint?: string- Custom OTLP endpoint URL
Example:
// Basic initialization
glass.init({ apiKey: 'your-api-key' });
// With debug mode
glass.init({ apiKey: 'your-api-key', debug: true });
// Using environment variable
process.env.GLASS_API_KEY = 'your-api-key';
glass.init();trace()
glass.trace<T>(fn: T, options?: TraceOptions): THigher-order function that wraps a function with OpenTelemetry tracing.
Options:
name?: string- Custom span name (defaults to function name)attributes?: Record<string, unknown>- Additional span attributes
Example:
// Wrap a sync function
const add = glass.trace((a: number, b: number) => a + b, { name: 'add' });
// Wrap an async function
const fetchUser = glass.trace(async (id: string) => {
const response = await fetch(`/api/users/${id}`);
return response.json();
}, { name: 'fetchUser' });
// With attributes
const analyzeText = glass.trace(
async (text: string) => { /* ... */ },
{ name: 'analyzeText', attributes: { model: 'gpt-4' } }
);interaction()
glass.interaction<T>(
metadata: InteractionMetadata,
callback: (ctx: InteractionContext) => T | Promise<T>
): Promise<T>Track a user interaction with a span. Metadata flows to nested traced functions.
Metadata:
userId?: string- User identifiersessionId?: string- Session identifierproject?: string- Project classificationinput?: string- User input textservice?: string- Service name[key: string]: unknown- Additional custom metadata
Context methods:
ctx.finish(output)- Record the final outputctx.setAttribute(key, value)- Set a span attributectx.recordException(error)- Record an exception
Example:
const response = await glass.interaction(
{ userId: 'user-123', sessionId: 'session-456', project:'conversational-chat', input: 'Hello!' },
async (ctx) => {
// Nested traces automatically inherit userId, sessionId
const result = await processMessage('Hello!');
// Set additional attributes
ctx.setAttribute('tokens_used', 150);
// Record the final output
ctx.finish({ response: result, tokens: 150 });
return result;
}
);task()
glass.task<T>(
name: string,
callback: (ctx: TaskContext) => T | Promise<T>,
options?: TaskOptions
): Promise<T>Create a manual task span with explicit input/output recording.
Options:
attributes?: Record<string, unknown>- Additional span attributes
Context methods:
ctx.recordInput(data)- Record input datactx.recordOutput(data)- Record output datactx.setAttribute(key, value)- Set a span attributectx.recordException(error)- Record an exception
Example:
const result = await glass.task('embed-documents', async (ctx) => {
const documents = ['doc1', 'doc2', 'doc3'];
// Record the input
ctx.recordInput({ documents, count: documents.length });
// Do the work
const embeddings = await embedDocuments(documents);
// Record the output
ctx.recordOutput({ embeddings_count: embeddings.length });
return embeddings;
}, { attributes: { model: 'text-embedding-ada-002' } });Advanced Usage
Access Active Metadata
import { getActiveMetadata } from 'glass-ai';
// Inside a traced function or interaction callback
const metadata = getActiveMetadata();
console.log(metadata.userId); // Access inherited metadataCustom Context Propagation
import { runWithMetadata } from 'glass-ai';
// Run code with custom metadata
runWithMetadata({ customField: 'value' }, () => {
// All traced functions here will have customField in their metadata
});Shutdown
import { shutdown } from 'glass-ai';
// Gracefully shutdown and flush pending spans
await shutdown();Requirements
- Node.js >= 18.0.0
- TypeScript >= 5.0 (for TypeScript users)
License
MIT
