npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@natyapp/langchain

v1.0.0

Published

TypeScript client for Naty LangChain API

Readme

Naty LangChain Client

TypeScript client for the Naty LangChain API - Updated for OpenAPI 3.1.0 specification.

Installation

npm install @natyapp/langchain
# or
yarn add @natyapp/langchain

Quick Start

New API (Recommended)

import { NatyLangChainClient } from '@natyapp/langchain';

// Initialize the client with API key authentication
const client = new NatyLangChainClient({
  baseURL: 'http://localhost:8000',
  apiKey: 'nlck-key_prod_1',           // New: X-API-Key authentication
  tenantId: 'demo-tenant',             // Optional: X-Tenant-ID header
  requestId: 'custom-request-id',      // Optional: Custom X-Request-ID (auto-generated if not provided)
});

// Make a QA request (equivalent to curl example in requirements)
const response = await client.qa.ask({
  question: 'Olá?',
  k: 3,
});
console.log(response.answer);

Backward Compatibility

import { NatyClient } from '@natyapp/langchain';

// Legacy client still works (shows deprecation warning)
const legacyClient = new NatyClient({
  baseURL: 'http://localhost:8000',
  token: 'legacy-token',    // Will be used as X-API-Key
  tenantId: 'demo-tenant',
});

cURL Equivalent

The following client usage:

const client = new NatyLangChainClient({
  baseURL: 'http://localhost:8000',
  apiKey: 'nlck-key_prod_1',
  tenantId: 'demo-tenant',
  requestId: 'demo-request-id',
});

await client.qa.ask({ question: 'Olá?', k: 3 });

Is equivalent to this cURL command:

curl -X POST http://localhost:8000/v1/qa \
  -H "Content-Type: application/json" \
  -H "X-Tenant-ID: demo-tenant" \
  -H "X-API-Key: nlck-key_prod_1" \
  -H "X-Request-ID: demo-request-id" \
  -d '{"question": "Olá?", "k": 3}'

API Reference

Configuration

interface NatyLangChainClientConfig {
  baseURL: string;
  apiKey?: string;      // API key for X-API-Key header
  tenantId?: string;    // Tenant ID for X-Tenant-ID header
  requestId?: string;   // Custom request ID (auto-generated if not provided)
}

// Backward compatibility
interface NatyClientConfig extends NatyLangChainClientConfig {
  token?: string;       // Legacy token (deprecated, use apiKey)
}

Authentication & Headers

The client automatically manages the following headers:

  • Content-Type: application/json - Always included
  • X-API-Key - API key authentication (replaces Bearer tokens)
  • X-Tenant-ID - Multi-tenant support (when tenantId provided)
  • X-Request-ID - Request tracking (auto-generated UUID if not provided)

Available APIs

QA API

// Simple QA request
const qaResponse = await client.qa.ask({
  question: 'What is LangChain?',
  k: 4,                    // Optional: number of documents to retrieve
  filters: {               // Optional: vector store filters
    category: { $eq: 'tech' }
  }
});

// Override tenant ID per request
const response = await client.qa.ask(request, 'different-tenant-id');

Custom QA API

// Custom QA with system prompt
const customResponse = await client.customQA.ask({
  system_prompt: 'You are a helpful assistant that responds in Portuguese.',
  question: 'Como posso ajudar você hoje?',
  contexts_text: 'Optional explicit context',  // Optional
  filters: { tenant_id: { $eq: 'demo-tenant' } }, // Optional
  k: 4,                                           // Optional
  strict_context: true,                           // Optional
});

// Streaming custom QA
const stream = await client.customQA.stream({
  system_prompt: 'You are a helpful assistant.',
  question: 'Tell me about AI',
  strict_context: false,
});

// Process stream
const reader = stream.getReader();
while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  console.log(new TextDecoder().decode(value));
}

Documents API

// Create documents
const createResponse = await client.documents.create([
  {
    text: 'Document content here',
    metadata: {
      title: 'Document Title',
      category: 'technology',
      source: 'internal',
    },
  },
]);

// Create documents in batch (async operation)
const batchResponse = await client.documents.createBatch([...documents]);

// List documents
const listResponse = await client.documents.list();

// Search documents
const searchResponse = await client.documents.search({
  query: 'search term',
  filters: { category: { $eq: 'technology' } },
  k: 5,
});

// Delete documents by IDs
const deleteResponse = await client.documents.delete(['doc-id-1', 'doc-id-2']);

Error Handling

The client uses enhanced error handling with NatyLangChainError:

import { NatyLangChainError } from '@natyapp/langchain';

try {
  const response = await client.qa.ask({ question: 'Test' });
} catch (error) {
  if (error instanceof NatyLangChainError) {
    console.error('API Error:', error.message);
    console.error('Status:', error.status);      // HTTP status code
    console.error('Code:', error.code);          // Error code
    console.error('Details:', error.details);    // Additional error details
  } else {
    console.error('Unknown error:', error);
  }
}

Logging

The client automatically logs request headers (with API key masking for security):

// Example log output:
// Request headers: {
//   'X-Tenant-ID': 'demo-tenant',
//   'X-Request-ID': 'a90e-fb3b-4931-8dc4-51cc8adabf4e',
//   'X-API-Key': 'nlck...od_1'  // Masked for security
// }

Utility Functions

import { generateRequestId, maskApiKey } from '@natyapp/langchain';

// Generate UUID-like request ID
const requestId = generateRequestId();
console.log(requestId); // "a90e-fb3b-4931-8dc4-51cc8adabf4e"

// Mask API key for logging
const maskedKey = maskApiKey('nlck-key_prod_1234567890');
console.log(maskedKey); // "nlck...7890"

Migration Guide

From v1.x to v2.x

  1. Update client initialization:

    // Old
    const client = new NatyClient({
      baseURL: 'http://localhost:8000',
      token: 'bearer-token',
      tenantId: 'tenant-id',
    });
    
    // New
    const client = new NatyLangChainClient({
      baseURL: 'http://localhost:8000',
      apiKey: 'nlck-key_prod_1',  // Changed from token
      tenantId: 'tenant-id',
    });
  2. Update API URLs:

    • Documents: /documents/v1/documents
    • QA: /v1/qa (unchanged)
    • Custom QA: /v1/qa/custom (unchanged)
  3. Remove query parameters:

    • No longer need to pass llm, embeddings, retriever query parameters
    • These are now handled by the API internally
  4. Update error handling:

    // Old
    catch (error) {
      console.error(error.message);
    }
    
    // New
    catch (error) {
      if (error instanceof NatyLangChainError) {
        console.error('Status:', error.status);
        console.error('Code:', error.code);
        console.error('Message:', error.message);
      }
    }

Development

# Install dependencies
npm install

# Build
npm run build

# Run tests
npm test

# Run integration tests only
npm test -- tests/integration.test.ts

# Lint
npm run lint

# Format code
npm run format

Examples

See the examples/ directory for complete usage examples:

  • examples/usage-example.ts - Comprehensive usage demonstration

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

MIT License