CortexDB 类型脚本 SDK
██████╗ ██████╗ ██████╗ ██████╗ ██████╗
██╔══██╗██╔═══██╗██╔═══██╗██╔═══██╗██╔══██╗
██║ ██║██║ ██║██║ ██║██║ ██║██████╔╝
██║ ██║██║ ██║██║ ██║██║ ██║██╔══██╗
██████╔╝╚██████╔╝╚██████╔╝╚██████╔╝██║ ██║
╚═════╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝
CortexDB 的官方类型 脚本/ JavaScript SDK
CortexDB是什么来着?
CortexDB是一个多模式的RAG(检索增强生成)平台,将传统的数据库能力与向量搜索和高级文档处理相结合. 它使你能够:
- 在统一数据库中储存结构化和非结构化数据
- 使用 Docling 从文档( PDF、 DOCX、 XLSX) 自动取出文本
- 使用各种提供者生成嵌入语义搜索( OpenAI, 双子座等)
- 执行混合搜索,将过滤器和矢量相似性结合起来
- 以自动块和向量化构建RAG应用程序
CortexDB处理一个简单的API背后的向量数据库(Qdrant),对象存储(MinIO)和传统数据库(PostgreSQL)等复杂的基础设施.
特征
- 多式联运文件处理: 上传 PDF 、 DOCX 、 XLSX 文件并自动从 OCR 中取出文本
- 语义搜索: 基于矢量的搜索,使用来自OpenAI、双子座或自定义提供者的嵌入
- 自动块: 为RAG 应用程序优化了智能文本分割
- 弹性方案: 以打字字段(字符串、数字、布尔、文件、阵列)定义收藏
- 混合查询: 将精确的过滤器与语义搜索相结合
- 存储控制: 选择每个字段的存储位置( PostgreSQL, Qdrant, MinIO)
- 类型安全: 包含全面类型定义的完整类型脚本支持
- 现代 API: Async/await 使用本地取取取(18+节点)
- 基层管理: 数据库(
client.databases)和嵌入提供者(client.embeddingProvidersAPIs 内置 - QQ 类型脚本装饰器: 使用装潢器( 类似 TypeORM) 定义具有完整 IDE 支持的计划 - 见 Schema 装饰器指南
安装
npm install @dooor-ai/cortexdb
或用纱线:
yarn add @dooor-ai/cortexdb
或与平按:
pnpm add @dooor-ai/cortexdb
快速启动
import { CortexClient, FieldType, StoreLocation } from '@dooor-ai/cortexdb';
async function main() {
// Initialize with database in connection string
const client = new CortexClient('cortexdb://my-api-key@localhost:8000/production');
// Create a collection with vectorization enabled
await client.collections.create(
'documents',
[
{ name: 'title', type: FieldType.STRING },
{ name: 'content', type: FieldType.TEXT, vectorize: true },
{ name: 'published_at', type: FieldType.DATETIME, store_in: [StoreLocation.POSTGRES] }
],
'your-embedding-provider-id' // Required when vectorize=true
// database parameter is optional here since we set 'production' as default
);
// Create a record
const record = await client.records.create('documents', {
title: 'Introduction to AI',
content: 'Artificial intelligence is transforming how we build software...'
});
// Semantic search - finds relevant content by meaning, not just keywords
const results = await client.records.search(
'documents',
'How is AI changing software development?',
undefined, // filters
10 // limit - database parameter optional since we have default
);
results.results.forEach(result => {
console.log(`Score: ${result.score.toFixed(4)}`);
console.log(`Title: ${result.record.data.title}`);
console.log(`Content: ${result.record.data.content}\n`);
});
await client.close();
}
main();
项目特定打字
SDK一旦应用了你的YAML schema 和 Dooor CLI ,就变得完全类型安全:
npx dooor schema apply # reads dooor/schemas by default and generates types in dooor/generated/
此命令创建 dooor/generated/cortex-schema.ts 并自动增强 SDK 类型。 在您的工程中文件存在后, 您可以继续导入 CortexClient 从 @dooor-ai/cortexdb; TypeScript 将推断 YAML 中定义的字段/收藏 。 无效的字段名称或缺少所需的属性 client.records.create('my_collection', {...}) 现在触发编译时间错误, Prisma 风格 .
如果您需要清晰的工厂, 生成的文件也会导出 createCortexClient() 财务报告和审定财务报表 TypedCortexClient 帮手.
i️ CLI 也降低一个轻量级
.d.ts闪入node_modules/@dooor-ai/cortexdb/generated/schema.d.ts,所以 TypeScript 自动拾取您的图案- 不需要调整tsconfig.json。 。 。 .
类似 Prisma 的记录代表
一旦生成了计划, 您可以使用属性访问调用收藏, 而不是传递字符串 :
// Fully typed
const record = await client.records.tool_calls.create({
chatId: "chat-123",
description: "RAG invocation summary",
createdAt: new Date().toISOString(),
});
// String form still available when you need something dynamic
await client.records.create("tool_calls", {
chatId,
description,
createdAt,
});
使用量
初始化客户端
import { CortexClient } from '@dooor-ai/cortexdb';
// Using connection string with database (recommended)
const client = new CortexClient('cortexdb://my-api-key@localhost:8000/production');
// Without database in connection string (must pass database to each method)
const client = new CortexClient('cortexdb://my-api-key@localhost:8000');
// Production (HTTPS auto-detected)
const client = new CortexClient('cortexdb://[email protected]/production');
// Using options object (alternative)
const client = new CortexClient({
baseUrl: 'http://localhost:8000',
apiKey: 'your-api-key',
database: 'production', // Optional: set default database
timeout: 1800000, // Optional: override timeout (default = 30 min to cover large uploads)
waitUntilComplete: true, // Optional: keep SDK waiting for async ingestion to finish (default = true)
});
连接字符串格式 :
cortexdb://[api_key@]host[:port][/database]
福利:
- 单字符串配置
- 易于在环境变量中存储
- 更熟悉的模式( 如 PostgreSQL, MongoDB, Redis)
- 自动检测 HTTP 对 HTTPS
- 多租户隔离的可选数据库规格
数据库参数 :
- 如果您在连接字符串或选项中指定了一个数据库, 它将成为所有操作的默认值
- 您可以按每方法覆盖默认数据库
- 如果没有设置默认数据库,则您 必须 通过
database每种方法的参数
Async 文件上传和处理
大文件(PDF,DOCX等)被同步摄取来避免超时. 当你打电话 client.records.create(...) 网关现在立即以有效载荷作出反应,例如:
{
"id": "rec_123",
"status": "pending",
"processing_state": {
"record_id": "rec_123",
"status": "pending",
"processed_chunks": 0,
"total_chunks": 0
}
}
默认SDK会继续投票 processing_state 结束点,直到背景工人完成 并且只有最后决定 CreateRecordResponse。这保留了与现有后端的后置兼容性,后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置前置后置后置后置后置后置后置后置后置后置后置后置后置后出后置后置后置后置后置前置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置前置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后置后 create() 返回.
您可以控制这种行为 :
// Return immediately (HTTP 202) and poll manually later
const pending = await client.records.create(
'documents',
{ title: 'Async', content: '...' },
undefined,
{ waitUntilComplete: false }
);
// Later in your workflow…
const status = await client.records.getStatus('documents', pending.id);
if (status?.status === 'completed') {
const finalRecord = await client.records.waitForCompletion('documents', pending.id);
}
有用的选项 :
waitUntilComplete(默认)true让SDK的民意调查自动进行.pollingIntervalMs(默认)5000:改变SDK检查状态的频率.timeoutMs(默认)30 min:上行为自通环.
在引擎盖下 SDK的电话 GET /records/{id}/status 直到工人更新 processing_state 改为 completed 或者说 failed。也可以直接通过 client.records.getStatus(...) 以驱动自定义进度指标.
数据库
// Create database
await client.databases.create({ name: 'ai_docs', description: 'Knowledge base' });
// List databases
const databases = await client.databases.list();
// Delete database
await client.databases.delete('ai_docs');
嵌入供应商
await client.embeddingProviders.create({
name: 'Gemini Flash',
provider: 'gemini',
embedding_model: 'models/text-embedding-004',
api_key: process.env.GEMINI_API_KEY!,
});
const providers = await client.embeddingProviders.list();
收款
收藏定义了您数据的策略 。 每个收藏可以有多个字段,有不同的类型和存储选项.
import { FieldType, StoreLocation } from '@dooor-ai/cortexdb';
// Create collection with vectorization (database required)
const collection = await client.collections.create(
'articles',
[
{
name: 'title',
type: FieldType.STRING
},
{
name: 'content',
type: FieldType.TEXT,
vectorize: true // Enable semantic search on this field
},
{
name: 'year',
type: FieldType.INT,
store_in: [StoreLocation.POSTGRES, StoreLocation.QDRANT_PAYLOAD]
}
],
'embedding-provider-id', // Required when any field has vectorize=true
'production' // Database name (or omit if default database is set)
);
// List collections (uses default database if set, or pass specific database)
const collections = await client.collections.list('production');
// Get collection schema
const schema = await client.collections.get('articles', 'production');
// Delete collection and all its records
await client.collections.delete('articles', 'production');
// If you set a default database in the client, you can omit it:
const client = new CortexClient('cortexdb://key@host:8000/production');
const collections = await client.collections.list(); // Uses 'production'
记录
记录是收藏中存储的实际数据. 他们必须符合收集计划.
import fs from 'node:fs';
// Create record (with optional file upload and database)
const created = await client.records.create(
'articles',
{
title: 'Machine Learning Basics',
content: 'Machine learning is a subset of AI focused on learning from data...',
year: 2024,
},
{
attachment: fs.readFileSync('ml-intro.pdf'),
},
'production' // Database name
);
// Get record by ID
const fetched = await client.records.get('articles', created.id, 'production');
// Update record
const updated = await client.records.update('articles', created.id, {
year: 2025,
}, 'production');
// Delete record
await client.records.delete('articles', created.id, 'production');
// List records with filters/pagination
const results = await client.records.list('articles', {
limit: 10,
offset: 0,
filters: { year: { $gte: 2023 } },
});
标记(元数据)
标记作为元数据存储( 不是您计划的一部分)并保存外壳 。 更新标记取代整个集 . 限制:每个记录最多有10个标记,每个标记最多有50个字符.
// Create with tags (options param; database optional)
const tagged = await client.records.create(
'articles',
{
title: 'Mercado outlook',
content: 'Q1 macro trends and earnings guidance...',
},
undefined,
{ tags: ['Mercado', 'Q1-2024'] }
);
// Update tags (replaces existing tags; pass [] to clear)
await client.records.update(
'articles',
tagged.id,
{ year: 2025 },
{ tags: ['Mercado', 'Q2-2024'] }
);
// Filter by tags
const withTag = await client.records.list('articles', {
filters: { tags: { $in: ['Mercado'] } },
});
// If your schema already has a "tags" field, use "__tags" to filter metadata tags instead.
斯克马 CLI (YAML)
安装 CLI( 在 deddependents 中推荐) :
npm install --save-dev dooor
使用统一 dooor CLI来同步申报计划.
同时为实时验证(Open VSX)在VS代码/ursor中安装"门工具"扩展.
# Check differences between local YAML and CortexDB
npx dooor schema diff --dir dooor/schemas
# Create collections that don't exist yet
npx dooor schema apply --dir dooor/schemas
# Apply without generating types (by default apply already generates them)
npx dooor schema apply --no-generate-types
# Generate TypeScript types for use in services
npx dooor schema generate-types --dir dooor/schemas --out src/generated/cortex-schema.ts
自动收藏打字
同步计划后, CLI 生成 dooor/generated/cortex-schema.ts 带有衍生类型。 向 SDK 提供此方案, 以便获得类似 Prisma 的自动完成和验证 :
import { CortexClient } from '@dooor-ai/cortexdb';
import type {
CortexGeneratedSchema,
CollectionCreateInput,
} from '../dooor/generated/cortex-schema';
const client = new CortexClient<CortexGeneratedSchema>(
process.env.CORTEXDB_CONNECTION!,
);
const payload: CollectionCreateInput<'tool_calls'> = {
chatId,
workspaceId,
toolName,
description,
toolOutput,
createdAt: new Date().toISOString(),
};
await client.records.create('tool_calls', payload);
通用软件 records.update, (中文(简体) ), records.list, (中文(简体) ), records.get,以及 records.search。如果选择旧的动态模式,即时 new CortexClient() 没有通用参数.
设定 CORTEXDB_CONNECTION (例如, cortexdb://key@host:8000)或为: CORTEXDB_BASE_URL + 键 CORTEXDB_API_KEY 变量在运行命令前。 如果没有指定目录, CLI 将自动查看 dooor/schemas。 。 。 .
为避免重复标记, 配置 dooor/config.yaml 项目根 :
cortexdb:
connection: env(CORTEXDB_CONNECTION)
defaultEmbeddingProvider: default-provider
schema:
dir: dooor/schemas
typesOut: dooor/generated/cortex-schema.ts
您可以使用 dooor/config.local.yaml 或通过 DOOOR_CONFIG。 。 。 .
语义搜索
语义搜索从意思上找到记录,而不仅仅是准确的关键词匹配. 它使用向量嵌入来理解上下文.
// Basic semantic search
const results = await client.records.search(
'articles',
'machine learning fundamentals',
undefined,
10
);
// Search with filters - combine semantic search with exact matches
const filteredResults = await client.records.search(
'articles',
'neural networks',
{
year: 2024,
category: 'AI'
},
5
);
// Process results - ordered by relevance score
filteredResults.results.forEach(result => {
console.log(`Score: ${result.score.toFixed(4)}`); // Higher = more relevant
console.log(`Title: ${result.record.data.title}`);
console.log(`Year: ${result.record.data.year}`);
});
处理文件
CortexDB可以处理文档并自动取出文本来进行向量化.
// Create collection with file field
await client.collections.create(
'documents',
[
{ name: 'title', type: FieldType.STRING },
{
name: 'document',
type: FieldType.FILE,
vectorize: true // Extract text and create embeddings
}
],
'embedding-provider-id'
);
// Note: File upload support is currently available in the REST API
// TypeScript SDK file upload will be added in a future version
过滤运算符
// Exact match filters
const results = await client.records.list('articles', {
filters: {
category: 'technology',
published: true,
year: 2024
}
});
// Combine multiple filters
const filtered = await client.records.list('articles', {
filters: {
year: 2024,
category: 'AI',
author: 'John Doe'
},
limit: 20
});
处理错误
SDK为不同的故障情况提供了特定的出错类型.
import {
CortexDBError,
CortexDBNotFoundError,
CortexDBValidationError,
CortexDBConnectionError,
CortexDBTimeoutError
} from '@dooor-ai/cortexdb';
try {
const record = await client.records.get('articles', 'invalid-id');
} catch (error) {
if (error instanceof CortexDBNotFoundError) {
console.log('Record not found');
} else if (error instanceof CortexDBValidationError) {
console.log('Invalid data:', error.message);
} else if (error instanceof CortexDBConnectionError) {
console.log('Connection failed:', error.message);
} else if (error instanceof CortexDBTimeoutError) {
console.log('Request timed out:', error.message);
} else if (error instanceof CortexDBError) {
console.log('General error:', error.message);
}
}
实例
检查 examples/ 完整工作示例目录 :
quickstart.ts- 完全通过SDK特性search.ts- 与过滤器和提供者进行语义搜索basic.ts- CRUD基本业务
运行示例 :
npx ts-node -O '{"module":"commonjs"}' examples/quickstart.ts
发展
设置
# Clone repository
git clone https://github.com/yourusername/cortexdb
cd cortexdb/clients/typescript
# Install dependencies
npm install
# Build
npm run build
脚本
# Build TypeScript
npm run build
# Build in watch mode
npm run build:watch
# Clean build artifacts
npm run clean
# Lint code
npm run lint
# Format code
npm run format
所需资源
- 节点.js QQ 18.0.0(用于本地获取支持)
- 本地或远程运行的 CortexDB 网关
- 如果使用矢量化,则配置嵌入提供者( OpenAI, 双子座等)
建筑
CortexDB集成多种技术:
- 邮递SQL: 储存结构化数据和元数据
- 问题: 用于语义搜索的矢量数据库
- 米尼奥: 文件对象存储
- 调试: 高级文档处理和文本提取
SDK将这种复杂性集成一个简单,统一的API.
高级RAG战略(v. 4.0+)
CortexDB现在支持多个RAG策略来提高搜索质量和相关性. 选择最适合您使用的策略 :
可用战略
- 标 题: 基本矢量相似性搜索(默认)
- 毛里求斯: 利用对等排名合并生成多个查询变量并合并结果
- 希地语NAME: 生成假设文档并用于改进检索
- 卢旺达: 使用 LLM 按相关性重新排序搜索结果
- 未来: 将多克力扩展与 LLM 重排结合
- 背景: 根据对话背景重排查询
设置 AI 供应商
在使用高级策略之前, 配置 AI 提供者 :
// Create an AI provider for query expansion/reranking
const aiProvider = await client.aiProviders.create({
name: "Gemini Flash",
provider: "gemini",
api_key: "your-gemini-api-key",
model: "gemini-2.5-flash",
enabled: true,
});
// List providers
const providers = await client.aiProviders.list();
// Update provider
await client.aiProviders.update(aiProvider.id, {
model: "gemini-2.0-flash",
});
使用高级搜索
import { RAGStrategy } from '@dooor-ai/cortexdb';
// Simple search (default)
const simpleResults = await client.records.searchAdvanced('documents', {
query: 'What is machine learning?',
limit: 10,
strategy: RAGStrategy.SIMPLE,
});
// Multi-query with automatic query expansion
const multiQueryResults = await client.records.searchAdvanced('documents', {
query: 'What is machine learning?',
limit: 10,
strategy: RAGStrategy.MULTI_QUERY,
strategyConfig: {
num_queries: 5, // Generate 5 query variations
},
aiProviderName: "Gemini Flash", // Use provider by name
});
// HyDE: Generate hypothetical document for better retrieval
const hydeResults = await client.records.searchAdvanced('documents', {
query: 'Explain neural networks',
limit: 10,
strategy: RAGStrategy.HYDE,
strategyConfig: {
document_length: 200, // Length of hypothetical document
},
aiProviderName: "Gemini Flash",
});
// Rerank: Use LLM to reorder results by relevance
const rerankResults = await client.records.searchAdvanced('documents', {
query: 'Benefits of deep learning',
limit: 10,
strategy: RAGStrategy.RERANK,
strategyConfig: {
initial_k: 50, // Fetch 50 results then rerank to top 10
},
aiProviderName: "Gemini Flash",
});
// Fusion: Best of both worlds (multi-query + reranking)
const fusionResults = await client.records.searchAdvanced('documents', {
query: 'How does AI work?',
limit: 10,
strategy: RAGStrategy.FUSION,
strategyConfig: {
num_queries: 5,
initial_k: 50,
},
aiProviderName: "Gemini Flash",
});
// Contextual: Reformulate query based on conversation history
const contextualResults = await client.records.searchAdvanced('documents', {
query: 'What about its applications?',
limit: 10,
strategy: RAGStrategy.CONTEXTUAL_QUERY,
strategyConfig: {
context: [
'Previous: What is machine learning?',
'Answer: Machine learning is a subset of AI...',
],
},
aiProviderName: "Gemini Flash",
});
// Access results
fusionResults.results.forEach(result => {
console.log(`Score: ${result.score}`);
console.log(`Content: ${result.record.content}`);
console.log(`Strategy used: ${fusionResults.strategy_used}`);
});
收集 -- -- 特定代表
收集代表也可查阅:
// Using the facade pattern
const results = await client.records.documents.searchAdvanced({
query: 'Machine learning applications',
strategy: RAGStrategy.FUSION,
aiProviderName: "Gemini Flash",
});
关键字搜索( 精确匹配)
对于按精确关键字匹配(不是语义)查找文档,请使用 findByKeyword数字 :
// Find all documents containing "contract" in any text field
const results = await client.records.findByKeyword('documents', {
keywords: ['contract'],
});
// Find documents containing ALL keywords (AND)
const allKeywords = await client.records.findByKeyword('documents', {
keywords: ['contract', 'signature'],
matchAll: true, // must contain BOTH keywords
});
// Find documents containing ANY keyword (OR) - default
const anyKeyword = await client.records.findByKeyword('documents', {
keywords: ['contract', 'agreement'],
matchAll: false,
});
// Search only in specific fields
const inFields = await client.records.findByKeyword('documents', {
keywords: ['quarterly'],
fields: ['title', 'content'], // only search these fields
});
// Combine with filters and tags
const filtered = await client.records.findByKeyword('documents', {
keywords: ['report'],
filters: {
status: 'published',
__tags: { $in: ['finance'] }
},
limit: 50,
offset: 0,
});
回应:
{
results: [{ id, record, files?, previews?, tags? }],
total: number,
keywords: string[],
match_all: boolean
}
性能提示
- 标 题: 最快,用于基本的语义搜索
- 毛里求斯: 5x 慢于简单( 生成 5 个查询)
- 希地语NAME: 类似于多克力, 适合提问
- 卢旺达: 成本适中,对准确性提高有很大帮助
- 未来:最高成本和耐用性,质量最佳
- 背景: 用于对话界面
详情见 RAG 战略文件。 。 。 .
许可证
麻省理工学院执照 - 看 自由主义 详细情况.
相关
- CortexDB Python SDK 软件 - CortexDB 的 Python 客户端
- CortexDB 文档 - 完成平台文件