npm package: @lineai/assistant-memory
Description: TypeScript SDK for episodic and procedural memory for @lineAI assistant and agents
Latest version: 0.1.1

# @lineai/assistant-memory

> TypeScript SDK for Cognee API - Episodic and procedural memory for @lineAI assistant and agents

[![TypeScript](https://img.shields.io/badge/TypeScript-5.9-blue)](https://www.typescriptlang.org/)
[![Node](https://img.shields.io/badge/Node-%3E%3D18-green)](https://nodejs.org/)

A functional, type-safe TypeScript SDK for interacting with the Cognee API. Build powerful knowledge graphs and semantic search applications with ease.

## Features

- 🔒 **Type-safe** - Full TypeScript support with comprehensive type definitions
- 🧩 **Functional** - Immutable data structures and pure functions
- 🎯 **Intelligent Search** - Automatic query classification and mode selection
- 🚀 **Zero Dependencies** - Uses native fetch (Node 18+)
- 📦 **Tree-shakeable** - Import only what you need
- 🔍 **11 Search Modes** - From simple chunks to advanced chain-of-thought reasoning

## Installation

```bash
npm install @lineai/assistant-memory
```

```bash
yarn add @lineai/assistant-memory
```

## Quick Start

```typescript
import { createCogneeClient, SearchType } from '@lineai/assistant-memory';

// Create client
const client = createCogneeClient({
  baseURL: 'https://api.cognee.ai',
  apiKey: 'your-api-key'
});

// Add data
const addResult = await client.add({
  textData: ['Important information about our product'],
  datasetName: 'product-docs'
});

// Transform into knowledge graph
if (addResult.success) {
  await client.cognify({
    datasets: ['product-docs']
  });
}

// Search with automatic mode selection
const route = client.routeQuery('Who are the key stakeholders?');
console.log(route.recommendedMode); // GRAPH_COMPLETION_COT

const searchResult = await client.search({
  query: 'Who are the key stakeholders?',
  searchType: route.recommendedMode,
  datasets: ['product-docs']
});

if (searchResult.success) {
  searchResult.data.forEach(result => {
    console.log(result.search_result);
  });
}
```

## Core Concepts

### Client Creation

```typescript
import { createCogneeClient } from '@lineai/assistant-memory';

const client = createCogneeClient({
  baseURL: 'https://api.cognee.ai',
  apiKey: 'your-api-key',
  timeout: 120000 // optional, default 2 minutes
});
```

### Data Management

#### Add Data

```typescript
const result = await client.add({
  textData: ['Text to add to knowledge base'],
  datasetName: 'my-dataset',
  nodeSet: ['optional-node-classification'] // optional
});
```

#### Cognify (Build Knowledge Graph)

```typescript
const result = await client.cognify({
  datasets: ['my-dataset'],
  customPrompt: 'Extract technical entities and relationships', // optional
  temporalCognify: false // optional
});
```

#### Delete Data

```typescript
const result = await client.delete({
  dataId: 'data-uuid',
  datasetId: 'dataset-uuid',
  mode: 'soft' // 'soft' or 'hard'
});
```

### Search Modes

The SDK supports 11 different search modes, each optimized for different query types:

#### Direct Retrieval (No LLM)
- **CHUNKS** - Fast raw text retrieval
- **SUMMARIES** - Pre-generated summaries
- **INSIGHTS** - Pre-extracted key insights

#### RAG (Single-Step LLM)
- **RAG_COMPLETION** - Standard retrieval-augmented generation

#### Graph-Enhanced (Leveraging Knowledge Graph)
- **GRAPH_COMPLETION** - Uses entity relationships
- **GRAPH_SUMMARY_COMPLETION** - Graph + summaries
- **GRAPH_COMPLETION_COT** - Chain-of-thought reasoning ⭐
- **GRAPH_COMPLETION_CONTEXT_EXTENSION** - Extended graph traversal

#### Specialized
- **CODE** - Optimized for code search
- **CYPHER** - Generate graph database queries
- **NATURAL_LANGUAGE** - Flexible conversational mode
- **FEELING_LUCKY** - Returns single best result

### Intelligent Search Helpers

#### Automatic Mode Selection

```typescript
// Classify query type
const queryType = client.classifyQuery('Who are the key consultants in NYC?');
// Returns: QueryType.ENTITY_LIST

// Select optimal search mode
const mode = client.selectSearchMode('Who are the key consultants in NYC?');
// Returns: SearchType.GRAPH_COMPLETION_COT

// Get full routing information
const route = client.routeQuery('Who are the key consultants in NYC?');
console.log(route);
// {
//   query: "Who are the key consultants in NYC?",
//   queryType: "entity_list",
//   recommendedMode: "GRAPH_COMPLETION_COT",
//   estimatedCost: "$$$$$",
//   estimatedTime: 3.5,
//   reasoning: "Entity list extraction requires Chain-of-Thought..."
// }
```

#### Query Type Detection

```typescript
// Check query characteristics
client.isEntityListQuery('Who are the experts?'); // true
client.isComparisonQuery('How does X differ from Y?'); // true
client.isNarrativeQuery('Why is this important?'); // true
client.isMultiHopQuery('If X then what should I do?'); // true
```

#### Search Builder

```typescript
import { createSearchBuilder } from '@lineai/assistant-memory';

const params = client.createSearchBuilder()
  .query('Who are the consultants in NYC?')
  .autoMode() // Automatically select best mode
  .inDatasets(['my-dataset'])
  .topK(5)
  .withSystemPrompt('Be concise')
  .build();

const result = await client.search(params);
```

### Cost & Performance Estimation

```typescript
import { SearchType } from '@lineai/assistant-memory';

// Estimate costs before running query
const cost = client.estimateCost(SearchType.GRAPH_COMPLETION_COT);
// Returns: "$$$$$" (very high)

const time = client.estimateTime(SearchType.GRAPH_COMPLETION_COT);
// Returns: 3.5 (seconds)
```

## Search Mode Selection Guide

### When to Use Each Mode

**CHUNKS** - Use for:
- Simple fact retrieval
- Exact text matching
- Debugging/development
- Speed is critical

**RAG_COMPLETION** - Use for:
- Narrative/explanatory questions
- "Why" questions
- Natural language output needed

**GRAPH_COMPLETION** - Use for:
- Entity comparisons
- Relationship-based questions
- When entities exist in graph

**GRAPH_COMPLETION_COT** ⭐ - Use for:
- Entity list extraction ("Who are the...")
- Multi-hop reasoning
- Complex queries with sub-questions
- Temporal queries
- Problem-solution patterns
- When other modes fail

**GRAPH_COMPLETION_CONTEXT_EXTENSION** - Use for:
- Exploratory queries
- Need comprehensive coverage
- Discovery of implicit connections

### Performance Characteristics

| Mode | Speed | Cost | Accuracy (Complex) |
|------|-------|------|-------------------|
| CHUNKS | ⚡⚡⚡⚡⚡ | $ | Low |
| RAG_COMPLETION | ⚡⚡⚡ | $$ | Medium |
| GRAPH_COMPLETION | ⚡⚡ | $$$ | High |
| GRAPH_COMPLETION_COT | ⚡ | $$$$$ | Very High |

## Advanced Usage

### Error Handling

The SDK uses a functional `Result` type for error handling:

```typescript
import { createCogneeClient } from '@lineai/assistant-memory';

const result = await client.search({
  query: 'test query',
  searchType: 'CHUNKS'
});

if (result.success) {
  // Access data
  console.log(result.data);
} else {
  // Handle error
  switch (result.error.type) {
    case 'AUTH_ERROR':
      console.error('Authentication failed:', result.error.message);
      break;
    case 'NETWORK_ERROR':
      console.error('Network error:', result.error.message);
      break;
    case 'API_ERROR':
      console.error('API error:', result.error.statusCode, result.error.message);
      break;
    // ... handle other error types
  }
}
```

### Visualization

```typescript
const result = await client.visualize('dataset-uuid');

if (result.success) {
  // result.data contains HTML visualization
  fs.writeFileSync('graph.html', result.data);
}
```

### Search History

```typescript
const history = await client.getSearchHistory();

if (history.success) {
  history.data.forEach(item => {
    console.log(`${item.createdAt}: ${item.text}`);
  });
}
```

## API Reference

### Client Methods

- `client.add(params)` - Add text data to dataset
- `client.cognify(params)` - Transform datasets into knowledge graphs
- `client.delete(params)` - Delete data from dataset
- `client.search(params)` - Search the knowledge graph
- `client.visualize(datasetId)` - Generate graph visualization
- `client.getSearchHistory()` - Get user's search history

### Search Helpers

- `client.classifyQuery(query)` - Classify query type
- `client.selectSearchMode(query)` - Select optimal search mode
- `client.routeQuery(query)` - Get full routing information
- `client.estimateCost(mode)` - Estimate cost for mode
- `client.estimateTime(mode)` - Estimate time for mode
- `client.createSearchBuilder()` - Create fluent search builder

### Type Guards

- `client.isEntityListQuery(query)` - Check if entity list query
- `client.isComparisonQuery(query)` - Check if comparison query
- `client.isNarrativeQuery(query)` - Check if narrative query
- `client.isMultiHopQuery(query)` - Check if multi-hop query

## Examples

### Basic Search

```typescript
const result = await client.search({
  query: 'What is the price range?',
  searchType: 'CHUNKS',
  topK: 5
});
```

### Entity Extraction

```typescript
// Use COT for entity lists
const result = await client.search({
  query: 'Who are the key lighting consultants in NYC?',
  searchType: 'GRAPH_COMPLETION_COT',
  datasets: ['market-research']
});
```

### Comparison Query

```typescript
const result = await client.search({
  query: 'How does Product A differ from Product B?',
  searchType: 'GRAPH_COMPLETION',
  datasets: ['products']
});
```

### Custom System Prompt

```typescript
const result = await client.search({
  query: 'Summarize the key points',
  searchType: 'RAG_COMPLETION',
  systemPrompt: 'Provide a concise 2-sentence summary',
  datasets: ['documents']
});
```

## TypeScript Types

All types are fully exported for your convenience:

```typescript
import type {
  CogneeClient,
  ClientConfig,
  SearchParams,
  SearchResult,
  SearchType,
  QueryType,
  QueryRoute,
  Result,
  CogneeError,
  UUID
} from '@lineai/assistant-memory';
```

## Development

```bash
# Install dependencies
npm install

# Build
npm run build

# Run tests
npm test

# Lint
npm run test:lint

# Format
npm run fix:prettier
```

## License

MIT

## Links

- [Cognee API Documentation](https://api.cognee.ai/docs)
- [GitHub Repository](https://github.com/oven-one/agent-memory)