Skip to content

Latest commit

 

History

History
420 lines (321 loc) · 9.47 KB

File metadata and controls

420 lines (321 loc) · 9.47 KB

Scintirete Python SDK

English | 中文

Scintirete 向量数据库的官方 Python 客户端库。

PyPI version Python License

特性

  • 🚀 高性能: 基于 gRPC 构建,支持连接池和压缩
  • 🔄 同步 & 异步: 支持同步和异步操作
  • 🔐 身份认证: 简单的密码认证机制
  • 📊 丰富类型: 完整的类型提示和数据模型
  • 🧪 测试完备: 广泛的单元测试和集成测试
  • 📖 文档完善: 详细的 API 文档和示例

安装

pip install scintirete-sdk

支持异步操作:

pip install scintirete-sdk[async]

开发环境:

pip install scintirete-sdk[dev]

快速开始

同步客户端

from scintirete_sdk import ScintireteClient, DistanceMetric, Vector

# 创建客户端
client = ScintireteClient("localhost:50051", password="your_password")

# 创建数据库
client.create_database("my_db")

# 创建集合
client.create_collection(
    "my_db", 
    "my_collection", 
    metric_type=DistanceMetric.COSINE
)

# 插入向量
vectors = [
    Vector(elements=[0.1, 0.2, 0.3], metadata={"label": "sample1"}),
    Vector(elements=[0.4, 0.5, 0.6], metadata={"label": "sample2"}),
]
ids, count = client.insert_vectors("my_db", "my_collection", vectors)

# 搜索向量
results = client.search(
    "my_db", 
    "my_collection", 
    query_vector=[0.1, 0.2, 0.3], 
    top_k=5
)

for result in results:
    print(f"ID: {result.id}, 距离: {result.distance}")

# 关闭连接
client.close()

异步客户端

import asyncio
from scintirete_sdk import ScintireteAsyncClient, DistanceMetric, Vector

async def main():
    # 创建异步客户端
    async with ScintireteAsyncClient("localhost:50051") as client:
        # 创建数据库
        await client.create_database("my_db")
        
        # 创建集合
        await client.create_collection(
            "my_db", 
            "my_collection", 
            metric_type=DistanceMetric.COSINE
        )
        
        # 插入向量
        vectors = [
            Vector(elements=[0.1, 0.2, 0.3], metadata={"label": "sample1"}),
            Vector(elements=[0.4, 0.5, 0.6], metadata={"label": "sample2"}),
        ]
        ids, count = await client.insert_vectors("my_db", "my_collection", vectors)
        
        # 搜索向量
        results = await client.search(
            "my_db", 
            "my_collection", 
            query_vector=[0.1, 0.2, 0.3], 
            top_k=5
        )
        
        for result in results:
            print(f"ID: {result.id}, 距离: {result.distance}")

# 运行异步函数
asyncio.run(main())

上下文管理器

# 同步上下文管理器
with ScintireteClient("localhost:50051") as client:
    databases = client.list_databases()
    print(databases)

# 异步上下文管理器
async with ScintireteAsyncClient("localhost:50051") as client:
    databases = await client.list_databases()
    print(databases)

配置

客户端选项

from scintirete_sdk import ScintireteClient

client = ScintireteClient(
    address="localhost:50051",
    password="your_password",          # 认证密码
    use_tls=False,                     # 启用 TLS/SSL
    default_timeout=30.0,              # 默认超时时间(秒)
    enable_gzip=True,                  # 启用 gRPC 压缩
    options=[                          # 自定义 gRPC 选项
        ("grpc.keepalive_time_ms", 30000),
        ("grpc.max_receive_message_length", 64 * 1024 * 1024),
    ]
)

HNSW 配置

from scintirete_sdk import HnswConfig, DistanceMetric

# 自定义 HNSW 参数
hnsw_config = HnswConfig(
    m=32,                    # 每个节点的最大连接数
    ef_construction=400      # 构建时的搜索范围大小
)

# 使用自定义 HNSW 配置创建集合
client.create_collection(
    "my_db",
    "my_collection", 
    metric_type=DistanceMetric.L2,
    hnsw_config=hnsw_config
)

API 参考

数据库操作

# 创建数据库
success = client.create_database("my_database")

# 列出数据库
databases = client.list_databases()

# 删除数据库
success, dropped_collections = client.drop_database("my_database")

集合操作

# 创建集合
info = client.create_collection(
    db_name="my_db",
    collection_name="my_collection",
    metric_type=DistanceMetric.COSINE,
    hnsw_config=HnswConfig(m=16, ef_construction=200)
)

# 获取集合信息
info = client.get_collection_info("my_db", "my_collection")
print(f"维度: {info.dimension}, 向量数: {info.vector_count}")

# 列出集合
collections = client.list_collections("my_db")

# 删除集合
success, dropped_vectors = client.drop_collection("my_db", "my_collection")

向量操作

from scintirete_sdk import Vector

# 插入向量
vectors = [
    Vector(
        elements=[0.1, 0.2, 0.3, 0.4],
        metadata={"source": "document1", "category": "text"}
    ),
    Vector(
        elements=[0.5, 0.6, 0.7, 0.8],
        metadata={"source": "document2", "category": "image"}
    )
]

inserted_ids, count = client.insert_vectors("my_db", "my_collection", vectors)

# 搜索向量
results = client.search(
    db_name="my_db",
    collection_name="my_collection",
    query_vector=[0.1, 0.2, 0.3, 0.4],
    top_k=10,
    ef_search=50,          # 覆盖 HNSW 搜索参数
    include_vector=True    # 在结果中包含向量数据
)

# 删除向量
deleted_count = client.delete_vectors("my_db", "my_collection", [1, 2, 3])

文本嵌入操作

from scintirete_sdk import TextWithMetadata

# 列出可用的嵌入模型
models, default_model = client.list_embedding_models()
print(f"默认模型: {default_model}")

# 文本嵌入
texts = ["Hello world", "Python programming"]
results = client.embed_text(texts, embedding_model="text-embedding-ada-002")

for result in results:
    print(f"文本: {result.text}")
    print(f"嵌入向量: {result.embedding[:5]}...")  # 前 5 个维度

# 嵌入并插入
texts_with_metadata = [
    TextWithMetadata(
        text="自然语言处理",
        metadata={"topic": "AI", "difficulty": "advanced"}
    ),
    TextWithMetadata(
        text="机器学习基础",
        metadata={"topic": "AI", "difficulty": "beginner"}
    )
]

ids, count = client.embed_and_insert(
    "my_db", 
    "my_collection", 
    texts_with_metadata,
    embedding_model="text-embedding-ada-002"
)

# 嵌入并搜索
results = client.embed_and_search(
    db_name="my_db",
    collection_name="my_collection",
    query_text="什么是机器学习?",
    top_k=5,
    embedding_model="text-embedding-ada-002"
)

持久化操作

# 同步保存
success, message, size, duration = client.save()
print(f"保存了 {size} 字节,耗时 {duration} 秒")

# 后台保存
success, message, job_id = client.bg_save()
print(f"后台保存任务: {job_id}")

距离度量

SDK 支持多种距离度量:

from scintirete_sdk import DistanceMetric

# 可用度量
DistanceMetric.L2              # 欧氏距离
DistanceMetric.COSINE          # 余弦相似度  
DistanceMetric.INNER_PRODUCT   # 内积

错误处理

from scintirete_sdk.exceptions import (
    ScintireteError,
    ConnectionError,
    AuthenticationError,
    DatabaseError,
    VectorError
)

try:
    client.create_database("my_db")
except AuthenticationError as e:
    print(f"认证失败: {e}")
except ConnectionError as e:
    print(f"连接失败: {e}")
except DatabaseError as e:
    print(f"数据库错误: {e}")
except ScintireteError as e:
    print(f"通用错误: {e}")

开发

设置开发环境

# 克隆仓库
git clone https://github.com/scintirete/scintirete.git
cd scintirete/sdk/python

# 安装开发依赖
make install-dev

# 生成 proto 文件
make gen

运行测试

# 运行单元测试
make test

# 运行测试并生成覆盖率报告
make test-cov

# 运行集成测试(需要运行 Scintirete 服务器)
pytest tests/integration/ -m integration

代码质量

# 格式化代码
make format

# 代码检查
make lint

# 类型检查
mypy src/

构建和发布

# 构建包
make build

# 发布到 PyPI(需要凭证)
make publish

贡献

  1. Fork 仓库
  2. 创建功能分支 (git checkout -b feature/amazing-feature)
  3. 提交更改 (git commit -m 'Add some amazing feature')
  4. 推送到分支 (git push origin feature/amazing-feature)
  5. 打开 Pull Request

示例

查看 examples 目录了解更多综合使用示例:

许可证

该项目采用 MIT 许可证 - 查看 LICENSE 文件了解详情。

支持

更新日志

查看 CHANGELOG.md 了解每个版本的更改列表。