ai-database 0.0.0-development → 0.1.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.
package/README.md CHANGED
@@ -1,72 +1,114 @@
1
1
  # ai-database
2
2
 
3
- [![npm version](https://badge.fury.io/js/ai-database.svg)](https://badge.fury.io/js/ai-database)
4
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
-
6
- AI-native database abstraction with hybrid vector search capabilities for synthetic data, tool-calling, and RAG applications.
7
-
8
- ## Features
9
- - Hybrid vector search optimized for AI workloads
10
- - Synthetic data generation and management
11
- - Tool-calling interface compatible with major AI SDKs
12
- - Built-in support for RAG (Retrieval Augmented Generation)
13
- - Seamless integration with mdxdb for document storage
3
+ Direct interface to Payload CMS with database.do compatibility.
14
4
 
15
5
  ## Installation
6
+
16
7
  ```bash
17
8
  npm install ai-database
18
9
  # or
19
- pnpm add ai-database
20
- # or
21
10
  yarn add ai-database
11
+ # or
12
+ pnpm add ai-database
22
13
  ```
23
14
 
24
- ## Quick Start
15
+ ## Usage
16
+
17
+ ### Node.js Environment
18
+
25
19
  ```typescript
26
- import { createDatabase } from 'ai-database'
20
+ import { getPayload } from 'payload'
21
+ import config from '@payload-config'
22
+ import { DB } from 'ai-database'
23
+
24
+ // Initialize with Payload instance
25
+ const payload = await getPayload({ config })
26
+ const db = DB({ payload })
27
27
 
28
- // Initialize database with vector search capabilities
29
- const db = createDatabase({
30
- namespace: 'my-app',
31
- vectorSearch: true
28
+ // Use the same interface as database.do
29
+ const posts = await db.posts.find({
30
+ where: { status: 'published' },
31
+ limit: 10,
32
32
  })
33
33
 
34
- // Store documents with embeddings
35
- await db.collection('documents').store({
36
- content: 'Example document',
37
- embeddings: [0.1, 0.2, 0.3]
34
+ const post = await db.posts.findOne('post-123')
35
+ ```
36
+
37
+ ### Edge Environment
38
+
39
+ ```typescript
40
+ import { DB } from 'ai-database'
41
+
42
+ // Initialize with REST API URL
43
+ const db = DB({
44
+ apiUrl: 'https://your-payload-api.com/api',
45
+ apiKey: 'your-api-key',
38
46
  })
39
47
 
40
- // Perform hybrid search
41
- const results = await db.collection('documents').search({
42
- query: 'example',
43
- vector: [0.1, 0.2, 0.3],
44
- threshold: 0.8
48
+ // Use the same interface as database.do
49
+ const posts = await db.posts.find({
50
+ where: { status: 'published' },
51
+ limit: 10,
45
52
  })
53
+
54
+ const post = await db.posts.findOne('post-123')
55
+ ```
56
+
57
+ ### Generating Embeddings
58
+
59
+ ```typescript
60
+ import { generateEmbedding, calculateSimilarity } from 'ai-database'
61
+
62
+ // Generate embeddings for text
63
+ const result = await generateEmbedding('Text to embed')
64
+
65
+ if (result.success) {
66
+ console.log('Embedding:', result.embedding)
67
+ console.log('Model used:', result.model)
68
+
69
+ // Calculate similarity between two embeddings
70
+ const embedding1 = result.embedding[0]
71
+ const embedding2 = await generateEmbedding('Similar text').then((r) => r.embedding?.[0])
72
+
73
+ if (embedding1 && embedding2) {
74
+ const similarity = calculateSimilarity(embedding1, embedding2)
75
+ console.log('Similarity score:', similarity)
76
+ }
77
+ }
46
78
  ```
47
79
 
48
- ## Tool Integration
49
- ai-database exports AI-compatible tools that work with any LLM supporting function calling:
80
+ ## API
81
+
82
+ The API is compatible with `database.do`, providing the same methods for each collection:
83
+
84
+ - `find(options?)`: Find documents in the collection
85
+ - `findOne(id)`: Find a single document by ID
86
+ - `create(data)`: Create a new document
87
+ - `update(id, data)`: Update an existing document
88
+ - `delete(id)`: Delete a document
89
+ - `search(query, options?)`: Search for documents
90
+
91
+ ## Environment-specific Adapters
92
+
93
+ For more control over environment-specific initialization:
50
94
 
51
95
  ```typescript
52
- import { tools } from 'ai-database'
96
+ import { createNodeClient, createEdgeClient } from 'ai-database/adapters'
97
+
98
+ // Node.js
99
+ const nodeDb = createNodeClient({ payload })
53
100
 
54
- // Use with any AI SDK (Vercel AI, LangChain, etc)
55
- const searchTool = tools.vectorSearch({
56
- collection: 'documents',
57
- namespace: 'my-app'
101
+ // Edge
102
+ const edgeDb = createEdgeClient({
103
+ apiUrl: 'https://your-payload-api.com/api',
58
104
  })
59
105
  ```
60
106
 
61
- ## Integration with AI Primitives
62
- ai-database is designed to work seamlessly with other AI Primitives packages:
107
+ ## Embedding Functions
63
108
 
64
- - **ai-functions**: Provides database operations as callable AI functions
65
- - **ai-workflows**: Enables database integration in AI workflow definitions
66
- - **ai-agents**: Offers database access tools for AI agents
109
+ - `generateEmbedding(text, options?)`: Generate embeddings for text using the AI SDK
110
+ - `calculateSimilarity(embedding1, embedding2)`: Calculate cosine similarity between two embeddings
67
111
 
68
- ## API Reference
69
- [API documentation link]
112
+ ## License
70
113
 
71
- ## Dependencies
72
- Built on top of [mdxdb](https://github.com/ai-primitives/mdxdb) for robust document storage and vector search capabilities.
114
+ MIT
@@ -0,0 +1,195 @@
1
+ import { ListResponse } from 'apis.do/types';
2
+ export { ClientOptions, ErrorResponse, ListResponse, QueryParams } from 'apis.do/types';
3
+
4
+ /**
5
+ * Types for ai-database package
6
+ */
7
+
8
+ /**
9
+ * Options for embedding generation
10
+ */
11
+ interface EmbeddingOptions {
12
+ /** Embedding model to use (defaults to openai:text-embedding-3-small) */
13
+ model?: string;
14
+ /** Additional options for the embedding model */
15
+ [key: string]: any;
16
+ }
17
+ /**
18
+ * Result of embedding generation
19
+ */
20
+ interface EmbeddingResult {
21
+ /** Generated embedding vectors */
22
+ embedding: number[][] | null;
23
+ /** Model used for embedding generation */
24
+ model: string;
25
+ /** Whether the embedding generation was successful */
26
+ success: boolean;
27
+ /** Error message if embedding generation failed */
28
+ error?: string;
29
+ }
30
+ /**
31
+ * Generic collection data type
32
+ */
33
+ type CollectionData = Record<string, any>;
34
+ /**
35
+ * Query options for database operations
36
+ */
37
+ interface QueryOptions {
38
+ /** Filter criteria */
39
+ where?: Record<string, any>;
40
+ /** Sorting options (field:direction) */
41
+ sort?: string | string[];
42
+ /** Number of results per page */
43
+ limit?: number;
44
+ /** Page number for pagination */
45
+ page?: number;
46
+ /** Fields to include in the result */
47
+ select?: string | string[];
48
+ /** Relations to populate */
49
+ populate?: string | string[];
50
+ }
51
+ /**
52
+ * Methods available for each collection
53
+ * @template T Document type for the collection
54
+ */
55
+ interface CollectionMethods<T = CollectionData> {
56
+ /** Find documents in the collection */
57
+ find: (options?: QueryOptions) => Promise<ListResponse<T>>;
58
+ /** Find a single document by ID */
59
+ findOne: (id: string) => Promise<T>;
60
+ /** Create a new document */
61
+ create: (data: Partial<T>) => Promise<T>;
62
+ /** Update an existing document */
63
+ update: (id: string, data: Partial<T>) => Promise<T>;
64
+ /** Delete a document */
65
+ delete: (id: string) => Promise<T>;
66
+ /** Search for documents */
67
+ search: (query: string, options?: QueryOptions) => Promise<ListResponse<T>>;
68
+ }
69
+ /**
70
+ * Database client interface
71
+ */
72
+ interface DatabaseClientType {
73
+ /** Dynamic access to any collection */
74
+ [collection: string]: CollectionMethods;
75
+ }
76
+ /**
77
+ * Payload instance interface defining the minimum required methods
78
+ */
79
+ interface PayloadInstance {
80
+ find?: (options: any) => Promise<any>;
81
+ findByID?: (options: any) => Promise<any>;
82
+ create?: (options: any) => Promise<any>;
83
+ update?: (options: any) => Promise<any>;
84
+ delete?: (options: any) => Promise<any>;
85
+ db?: any;
86
+ [key: string]: any;
87
+ }
88
+ /**
89
+ * Configuration for REST API-based Payload client
90
+ */
91
+ interface RestClientConfig {
92
+ apiUrl: string;
93
+ apiKey?: string;
94
+ headers?: Record<string, string>;
95
+ fetchOptions?: RequestInit;
96
+ }
97
+ /**
98
+ * Options for DB initialization
99
+ */
100
+ interface DBOptions {
101
+ baseUrl?: string;
102
+ apiKey?: string;
103
+ payload?: PayloadInstance;
104
+ apiUrl?: string;
105
+ headers?: Record<string, string>;
106
+ fetchOptions?: RequestInit;
107
+ [collection: string]: any;
108
+ }
109
+ /**
110
+ * Collection handler options
111
+ */
112
+ interface CollectionHandlerOptions {
113
+ payload: PayloadInstance;
114
+ collectionName: string;
115
+ }
116
+
117
+ /**
118
+ * Node.js adapter for ai-database
119
+ */
120
+
121
+ /**
122
+ * Creates a database client for Node.js environments
123
+ * @param options Configuration options
124
+ * @returns Database client instance
125
+ * @example
126
+ * import { getPayload } from 'payload'
127
+ * import config from '@payload-config'
128
+ * import { createNodeClient } from 'ai-database/adapters'
129
+ *
130
+ * const payload = await getPayload({ config })
131
+ * const db = createNodeClient({ payload })
132
+ */
133
+ declare const createNodeClient: (options?: DBOptions) => DatabaseClientType;
134
+
135
+ /**
136
+ * Edge runtime adapter for ai-database
137
+ */
138
+
139
+ /**
140
+ * Creates a database client for Edge runtime environments
141
+ * @param options Configuration options (must include apiUrl)
142
+ * @returns Database client instance
143
+ * @example
144
+ * import { createEdgeClient } from 'ai-database/adapters'
145
+ *
146
+ * const db = createEdgeClient({
147
+ * apiUrl: 'https://your-payload-api.com/api',
148
+ * apiKey: 'your-api-key'
149
+ * })
150
+ */
151
+ declare const createEdgeClient: (options?: DBOptions) => DatabaseClientType;
152
+
153
+ /**
154
+ * Embedding functionality for ai-database
155
+ * Uses OpenAI API directly for generating embeddings
156
+ */
157
+
158
+ /**
159
+ * Generate embeddings for text using OpenAI API
160
+ * @param text Text to generate embeddings for
161
+ * @param options Embedding options
162
+ * @returns Promise resolving to embedding result
163
+ */
164
+ declare function generateEmbedding(text: string | string[], options?: EmbeddingOptions): Promise<EmbeddingResult>;
165
+ /**
166
+ * Calculate cosine similarity between two embeddings
167
+ * @param embedding1 First embedding vector
168
+ * @param embedding2 Second embedding vector
169
+ * @returns Cosine similarity score (0-1)
170
+ */
171
+ declare function calculateSimilarity(embedding1: number[], embedding2: number[]): number;
172
+
173
+ /**
174
+ * ai-database
175
+ * Direct interface to Payload CMS with database.do compatibility
176
+ */
177
+
178
+ /**
179
+ * Creates a database client with the provided options
180
+ * @param options Configuration options for the database client
181
+ * @returns A proxy-based database client that provides collection-based access
182
+ * @example
183
+ * const db = DB({ payload }) // Node.js with Payload instance
184
+ * const db = DB({ apiUrl: 'https://api.example.com' }) // Edge with REST API
185
+ */
186
+ declare const DB: (options?: DBOptions) => DatabaseClientType;
187
+ /**
188
+ * Default database client instance
189
+ * Note: This will attempt to use a global Payload instance if available,
190
+ * otherwise it will throw an error. In most cases, you should use the DB
191
+ * function directly with explicit options.
192
+ */
193
+ declare const db: DatabaseClientType;
194
+
195
+ export { type CollectionData, type CollectionHandlerOptions, type CollectionMethods, DB, type DBOptions, type DatabaseClientType, type EmbeddingOptions, type EmbeddingResult, type PayloadInstance, type QueryOptions, type RestClientConfig, calculateSimilarity, createEdgeClient, createNodeClient, db, DB as default, generateEmbedding };
@@ -0,0 +1,195 @@
1
+ import { ListResponse } from 'apis.do/types';
2
+ export { ClientOptions, ErrorResponse, ListResponse, QueryParams } from 'apis.do/types';
3
+
4
+ /**
5
+ * Types for ai-database package
6
+ */
7
+
8
+ /**
9
+ * Options for embedding generation
10
+ */
11
+ interface EmbeddingOptions {
12
+ /** Embedding model to use (defaults to openai:text-embedding-3-small) */
13
+ model?: string;
14
+ /** Additional options for the embedding model */
15
+ [key: string]: any;
16
+ }
17
+ /**
18
+ * Result of embedding generation
19
+ */
20
+ interface EmbeddingResult {
21
+ /** Generated embedding vectors */
22
+ embedding: number[][] | null;
23
+ /** Model used for embedding generation */
24
+ model: string;
25
+ /** Whether the embedding generation was successful */
26
+ success: boolean;
27
+ /** Error message if embedding generation failed */
28
+ error?: string;
29
+ }
30
+ /**
31
+ * Generic collection data type
32
+ */
33
+ type CollectionData = Record<string, any>;
34
+ /**
35
+ * Query options for database operations
36
+ */
37
+ interface QueryOptions {
38
+ /** Filter criteria */
39
+ where?: Record<string, any>;
40
+ /** Sorting options (field:direction) */
41
+ sort?: string | string[];
42
+ /** Number of results per page */
43
+ limit?: number;
44
+ /** Page number for pagination */
45
+ page?: number;
46
+ /** Fields to include in the result */
47
+ select?: string | string[];
48
+ /** Relations to populate */
49
+ populate?: string | string[];
50
+ }
51
+ /**
52
+ * Methods available for each collection
53
+ * @template T Document type for the collection
54
+ */
55
+ interface CollectionMethods<T = CollectionData> {
56
+ /** Find documents in the collection */
57
+ find: (options?: QueryOptions) => Promise<ListResponse<T>>;
58
+ /** Find a single document by ID */
59
+ findOne: (id: string) => Promise<T>;
60
+ /** Create a new document */
61
+ create: (data: Partial<T>) => Promise<T>;
62
+ /** Update an existing document */
63
+ update: (id: string, data: Partial<T>) => Promise<T>;
64
+ /** Delete a document */
65
+ delete: (id: string) => Promise<T>;
66
+ /** Search for documents */
67
+ search: (query: string, options?: QueryOptions) => Promise<ListResponse<T>>;
68
+ }
69
+ /**
70
+ * Database client interface
71
+ */
72
+ interface DatabaseClientType {
73
+ /** Dynamic access to any collection */
74
+ [collection: string]: CollectionMethods;
75
+ }
76
+ /**
77
+ * Payload instance interface defining the minimum required methods
78
+ */
79
+ interface PayloadInstance {
80
+ find?: (options: any) => Promise<any>;
81
+ findByID?: (options: any) => Promise<any>;
82
+ create?: (options: any) => Promise<any>;
83
+ update?: (options: any) => Promise<any>;
84
+ delete?: (options: any) => Promise<any>;
85
+ db?: any;
86
+ [key: string]: any;
87
+ }
88
+ /**
89
+ * Configuration for REST API-based Payload client
90
+ */
91
+ interface RestClientConfig {
92
+ apiUrl: string;
93
+ apiKey?: string;
94
+ headers?: Record<string, string>;
95
+ fetchOptions?: RequestInit;
96
+ }
97
+ /**
98
+ * Options for DB initialization
99
+ */
100
+ interface DBOptions {
101
+ baseUrl?: string;
102
+ apiKey?: string;
103
+ payload?: PayloadInstance;
104
+ apiUrl?: string;
105
+ headers?: Record<string, string>;
106
+ fetchOptions?: RequestInit;
107
+ [collection: string]: any;
108
+ }
109
+ /**
110
+ * Collection handler options
111
+ */
112
+ interface CollectionHandlerOptions {
113
+ payload: PayloadInstance;
114
+ collectionName: string;
115
+ }
116
+
117
+ /**
118
+ * Node.js adapter for ai-database
119
+ */
120
+
121
+ /**
122
+ * Creates a database client for Node.js environments
123
+ * @param options Configuration options
124
+ * @returns Database client instance
125
+ * @example
126
+ * import { getPayload } from 'payload'
127
+ * import config from '@payload-config'
128
+ * import { createNodeClient } from 'ai-database/adapters'
129
+ *
130
+ * const payload = await getPayload({ config })
131
+ * const db = createNodeClient({ payload })
132
+ */
133
+ declare const createNodeClient: (options?: DBOptions) => DatabaseClientType;
134
+
135
+ /**
136
+ * Edge runtime adapter for ai-database
137
+ */
138
+
139
+ /**
140
+ * Creates a database client for Edge runtime environments
141
+ * @param options Configuration options (must include apiUrl)
142
+ * @returns Database client instance
143
+ * @example
144
+ * import { createEdgeClient } from 'ai-database/adapters'
145
+ *
146
+ * const db = createEdgeClient({
147
+ * apiUrl: 'https://your-payload-api.com/api',
148
+ * apiKey: 'your-api-key'
149
+ * })
150
+ */
151
+ declare const createEdgeClient: (options?: DBOptions) => DatabaseClientType;
152
+
153
+ /**
154
+ * Embedding functionality for ai-database
155
+ * Uses OpenAI API directly for generating embeddings
156
+ */
157
+
158
+ /**
159
+ * Generate embeddings for text using OpenAI API
160
+ * @param text Text to generate embeddings for
161
+ * @param options Embedding options
162
+ * @returns Promise resolving to embedding result
163
+ */
164
+ declare function generateEmbedding(text: string | string[], options?: EmbeddingOptions): Promise<EmbeddingResult>;
165
+ /**
166
+ * Calculate cosine similarity between two embeddings
167
+ * @param embedding1 First embedding vector
168
+ * @param embedding2 Second embedding vector
169
+ * @returns Cosine similarity score (0-1)
170
+ */
171
+ declare function calculateSimilarity(embedding1: number[], embedding2: number[]): number;
172
+
173
+ /**
174
+ * ai-database
175
+ * Direct interface to Payload CMS with database.do compatibility
176
+ */
177
+
178
+ /**
179
+ * Creates a database client with the provided options
180
+ * @param options Configuration options for the database client
181
+ * @returns A proxy-based database client that provides collection-based access
182
+ * @example
183
+ * const db = DB({ payload }) // Node.js with Payload instance
184
+ * const db = DB({ apiUrl: 'https://api.example.com' }) // Edge with REST API
185
+ */
186
+ declare const DB: (options?: DBOptions) => DatabaseClientType;
187
+ /**
188
+ * Default database client instance
189
+ * Note: This will attempt to use a global Payload instance if available,
190
+ * otherwise it will throw an error. In most cases, you should use the DB
191
+ * function directly with explicit options.
192
+ */
193
+ declare const db: DatabaseClientType;
194
+
195
+ export { type CollectionData, type CollectionHandlerOptions, type CollectionMethods, DB, type DBOptions, type DatabaseClientType, type EmbeddingOptions, type EmbeddingResult, type PayloadInstance, type QueryOptions, type RestClientConfig, calculateSimilarity, createEdgeClient, createNodeClient, db, DB as default, generateEmbedding };