npm package: @monetzly/server-sdk
Description: Monetzly JS Server SDK for Node.js/TypeScript applications to interact with Monetzly Ads Services
Author: Monetzly
Latest version: 1.2.0

# Monetzly JavaScript SDK

A gRPC-based TypeScript/JavaScript SDK for Node.js applications to interact with Monetzly Ads Services. This SDK enables streaming token injection with advertisements for enhanced monetization of your AI applications.

## Features

- **gRPC Streaming**: High-performance bidirectional streaming
- **TypeScript Support**: Full TypeScript support with type definitions
- **LangChain Integration**: Easy integration with LangChain LLMs
- **Async/Await**: Modern async/await patterns
- **Error Handling**: Graceful fallback to original streams on errors
- **Auto-reconnection**: Automatic connection management

## Installation

```bash
npm install @monetzly/server-sdk
```

## Quick Start

### Basic Usage

```typescript
import { MonetzlySDK, MonetzlyConfig, InjectParams } from '@monetzly/server-sdk';

// Configure the SDK
const config: MonetzlyConfig = {
  apiKey: 'your-api-key',
  serverAddress: 'your-server.com:443',  // gRPC server address
  useSSL: true,  // Use SSL for production
  timeout: 30000
};

// Create SDK instance
const sdk = new MonetzlySDK(config);

async function example() {
  try {
    // Connect to gRPC server
    await sdk.connect();
    
    // Create a simple token stream
    async function* simpleTokenStream() {
      const tokens = ['Hello', ' world', '!', ' This', ' is', ' a', ' test', '.'];
      for (const token of tokens) {
        yield { content: token };
        await new Promise(resolve => setTimeout(resolve, 100));
      }
    }
    
    // Inject ads into the token stream
    for await (const enhancedToken of sdk.inject(simpleTokenStream(), {
      sessionId: 'my-session-123',
      prompt: 'Test prompt',
      metadata: { userType: 'premium' }
    })) {
      process.stdout.write(enhancedToken.content);
    }
    
  } finally {
    await sdk.disconnect();
  }
}

example().catch(console.error);
```

### LangChain Integration

```typescript
import { ChatGoogleGenerativeAI } from '@langchain/google-genai';
import { MonetzlySDK, MonetzlyConfig } from '@monetzly/server-sdk';

const llm = new ChatGoogleGenerativeAI({
  model: "gemini-2.0-flash",
  temperature: 0.7,
  apiKey: process.env.GOOGLE_API_KEY
});

const sdk = new MonetzlySDK({
  apiKey: process.env.MONETZLY_API_KEY!,
  serverAddress: process.env.MONETZLY_SERVER_ADDRESS || 'localhost:8080',
  useSSL: false // Use false for local development
});

async function langchainExample() {
  try {
    await sdk.connect();
    
    // Create LLM stream
    const llmStream = await llm.stream([
      ['system', 'You are a helpful assistant.'],
      ['human', 'What are the benefits of renewable energy?']
    ]);
    
    // Process with ad injection
    for await (const enhancedToken of sdk.inject(llmStream, {
      prompt: 'What are the benefits of renewable energy?',
      metadata: { topic: 'environment', userType: 'business' }
    })) {
      process.stdout.write(enhancedToken.content || '');
    }
    
  } finally {
    await sdk.disconnect();
  }
}
```

## Configuration

### MonetzlyConfig

```typescript
interface MonetzlyConfig {
  apiKey: string;           // Required: Your Monetzly API key
  serverAddress: string;    // Required: gRPC server address (host:port)
  timeout?: number;         // Optional: Timeout in milliseconds (default: 30000)
  useSSL?: boolean;        // Optional: Use SSL/TLS (default: true)
  metadata?: Record<string, string>; // Optional: Additional gRPC metadata
}
```

### InjectParams

```typescript
interface InjectParams {
  sessionId?: string;       // Optional: Session identifier
  prompt?: string;          // Optional: The original prompt
  metadata?: Record<string, string>; // Optional: Additional context
}
```

## API Reference

### MonetzlySDK

#### Methods

- `constructor(config: MonetzlyConfig)`: Initialize the SDK
- `async connect(): Promise<void>`: Connect to the gRPC server
- `async disconnect(): Promise<void>`: Disconnect from the gRPC server
- `async *inject(tokenStream, params?): AsyncGenerator<TokenChunk>`: Inject ads into token stream
- `isConfigured(): boolean`: Check if SDK is properly configured
- `updateConfig(updates: Partial<MonetzlyConfig>): void`: Update configuration

#### Static Properties

- `MonetzlySDK.version: string`: SDK version

## Error Handling

The SDK includes graceful error handling. If the gRPC connection fails or encounters an error, it will automatically fall back to yielding the original token stream without ads:

```typescript
try {
  for await (const token of sdk.inject(stream, params)) {
    process.stdout.write(token.content || '');
  }
} catch (error) {
  console.error('Error:', error);
  // SDK automatically falls back to original stream
}
```

## Environment Variables

You can use environment variables for configuration:

```bash
export MONETZLY_API_KEY="your-api-key"
export MONETZLY_SERVER_ADDRESS="your-server.com:443"
```

```typescript
const config: MonetzlyConfig = {
  apiKey: process.env.MONETZLY_API_KEY!,
  serverAddress: process.env.MONETZLY_SERVER_ADDRESS!
};
```

## Development

### Building

```bash
npm run build
```

### Testing

```bash
npm test
```

### Running Examples

```bash
# Make sure to set environment variables first
npm run build
node examples/langchain-example.js
```

## Migration from v1.x

The v2.0 SDK has been completely rewritten to use gRPC instead of HTTP/WebSocket:

### Changes:
- **Transport**: Now uses gRPC instead of HTTP/WebSocket
- **Configuration**: `baseUrl` → `serverAddress`, added `useSSL` option
- **Parameters**: `context` → `metadata`, removed `transport` option
- **Connection**: Added explicit `connect()`/`disconnect()` methods

### Migration Example:

```typescript
// v1.x (old)
const sdk = new MonetzlySDK({
  apiKey: 'key',
  baseUrl: 'https://api.example.com'
});

for await (const token of sdk.inject(stream, {
  context: { userType: 'premium' },
  transport: 'ws'
})) {
  // process token
}

// v2.x (new)
const sdk = new MonetzlySDK({
  apiKey: 'key',
  serverAddress: 'api.example.com:443',
  useSSL: true
});

await sdk.connect();
try {
  for await (const token of sdk.inject(stream, {
    metadata: { userType: 'premium' }
  })) {
    // process token
  }
} finally {
  await sdk.disconnect();
}
```

## License

MIT License - see LICENSE file for details.

## Support

For issues and questions:
- GitHub Issues: https://github.com/monetzly/server-sdk-js/issues
- Documentation: https://docs.monetzly.com
- Email: support@monetzly.com