everything-gemini 1.8.0 → 1.9.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.
@@ -0,0 +1,193 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Everything Gemini (everything-gemini) Python SDK Example
4
+ Cloud Platform Provisioning & Zero-Trust Infrastructure Pipeline
5
+
6
+ Orchestrates a 4-stage automated cloud delivery loop:
7
+ Architect -> Platform Engineer -> Security Auditor -> Release Engineer
8
+ """
9
+
10
+ import sys
11
+ import json
12
+ from dataclasses import dataclass, field
13
+ from typing import List, Dict, Any, Optional
14
+
15
+ @dataclass
16
+ class PlatformWorkloadRequest:
17
+ workload_id: str
18
+ environment: str # staging, production
19
+ cloud_provider: str # gcp, aws, azure
20
+ cluster_region: str
21
+ expected_qps: int
22
+ data_retention_days: int
23
+ services: List[str] = field(default_factory=list)
24
+ compliance_frameworks: List[str] = field(default_factory=list)
25
+
26
+ class PlatformProvisioningPipeline:
27
+ """Automates multi-agent cloud platform provisioning and compliance auditing."""
28
+
29
+ def __init__(self, request: PlatformWorkloadRequest):
30
+ self.request = request
31
+ self.audit_trail: List[Dict[str, Any]] = []
32
+ self.iac_manifests: Dict[str, str] = {}
33
+ self.security_clearance: bool = False
34
+ self.deployment_ready: bool = False
35
+
36
+ def log_event(self, agent: str, phase: str, status: str, details: str):
37
+ event = {
38
+ "agent": agent,
39
+ "phase": phase,
40
+ "status": status,
41
+ "details": details
42
+ }
43
+ self.audit_trail.append(event)
44
+ print(f"[{agent.upper()}] ({phase}): {status} - {details}")
45
+
46
+ def stage_1_architecture_blueprint(self) -> bool:
47
+ """Stage 1: Architect subagent designs high-availability topology and VPC segmentation."""
48
+ self.log_event(
49
+ agent="architect",
50
+ phase="topology_design",
51
+ status="DESIGNED",
52
+ details=f"Designed multi-zone VPC topology in {self.request.cluster_region} for {len(self.request.services)} services."
53
+ )
54
+
55
+ # Architectural scaling rules
56
+ if self.request.expected_qps > 5000:
57
+ topology = "multi-region-active-active"
58
+ else:
59
+ topology = "multi-zone-ha-regional"
60
+
61
+ self.log_event(
62
+ agent="architect",
63
+ phase="scaling_strategy",
64
+ status="CONFIRMED",
65
+ details=f"Selected topology: {topology} with horizontal pod autoscaling (HPA) target 75% CPU."
66
+ )
67
+ return True
68
+
69
+ def stage_2_platform_provisioning(self) -> bool:
70
+ """Stage 2: Platform Engineer generates Terraform/Helm modules and sizes compute resources."""
71
+ self.log_event(
72
+ agent="platform-engineer",
73
+ phase="iac_generation",
74
+ status="GENERATED",
75
+ details="Generated Terraform modules for GKE/EKS cluster, node pools, and VPC CNI."
76
+ )
77
+
78
+ # Resource right-sizing
79
+ cpu_request = "500m" if self.request.expected_qps < 1000 else "2000m"
80
+ ram_request = "1Gi" if self.request.expected_qps < 1000 else "4Gi"
81
+
82
+ self.iac_manifests["helm_values"] = f"""
83
+ replicaCount: 3
84
+ resources:
85
+ requests:
86
+ cpu: {cpu_request}
87
+ memory: {ram_request}
88
+ limits:
89
+ cpu: {cpu_request}
90
+ memory: {ram_request}
91
+ autoscaling:
92
+ enabled: true
93
+ minReplicas: 3
94
+ maxReplicas: 20
95
+ targetCPUUtilizationPercentage: 75
96
+ """
97
+ self.log_event(
98
+ agent="platform-engineer",
99
+ phase="resource_sizing",
100
+ status="OPTIMIZED",
101
+ details=f"Container resource requests sized to {cpu_request} CPU, {ram_request} RAM per pod."
102
+ )
103
+ return True
104
+
105
+ def stage_3_security_and_compliance_gate(self) -> bool:
106
+ """Stage 3: Security Auditor validates zero-trust network policies, RBAC, and Vault secrets."""
107
+ self.log_event(
108
+ agent="security-auditor",
109
+ phase="policy_scan",
110
+ status="INSPECTING",
111
+ details=f"Scanning against compliance standards: {', '.join(self.request.compliance_frameworks)}."
112
+ )
113
+
114
+ # Check for zero-trust network boundaries
115
+ has_ebpf_mtls = True
116
+ has_ephemeral_secrets = True
117
+
118
+ if has_ebpf_mtls and has_ephemeral_secrets:
119
+ self.security_clearance = True
120
+ self.log_event(
121
+ agent="security-auditor",
122
+ phase="zero_trust_verification",
123
+ status="APPROVED",
124
+ details="Zero-trust CiliumNetworkPolicy, Workload Identity, and Vault AppRole verified with zero findings."
125
+ )
126
+ return True
127
+ else:
128
+ self.log_event(
129
+ agent="security-auditor",
130
+ phase="zero_trust_verification",
131
+ status="REJECTED",
132
+ details="Missing automated mTLS or ephemeral secret rotation."
133
+ )
134
+ return False
135
+
136
+ def stage_4_release_and_canary_plan(self) -> bool:
137
+ """Stage 4: Release Engineer compiles progressive delivery plan and automated rollback triggers."""
138
+ if not self.security_clearance:
139
+ print("[RELEASE-ENGINEER] Blocked: Security clearance not granted.")
140
+ return False
141
+
142
+ self.log_event(
143
+ agent="release-engineer",
144
+ phase="canary_orchestration",
145
+ status="SCHEDULED",
146
+ details="Formulated 5% -> 25% -> 100% canary rollout with automated rollback on error rate > 0.5%."
147
+ )
148
+ self.deployment_ready = True
149
+ return True
150
+
151
+ def execute(self) -> Dict[str, Any]:
152
+ """Execute full platform delivery pipeline."""
153
+ print(f"\n🚀 Initiating Platform Provisioning Pipeline for '{self.request.workload_id}' ({self.request.environment})...\n")
154
+
155
+ ok = self.stage_1_architecture_blueprint()
156
+ if ok:
157
+ ok = self.stage_2_platform_provisioning()
158
+ if ok:
159
+ ok = self.stage_3_security_and_compliance_gate()
160
+ if ok:
161
+ ok = self.stage_4_release_and_canary_plan()
162
+
163
+ report = {
164
+ "workload_id": self.request.workload_id,
165
+ "environment": self.request.environment,
166
+ "cloud_provider": self.request.cloud_provider,
167
+ "security_clearance": self.security_clearance,
168
+ "deployment_ready": self.deployment_ready,
169
+ "audit_trail_events": len(self.audit_trail),
170
+ "status": "APPROVED" if self.deployment_ready else "BLOCKED"
171
+ }
172
+
173
+ print(f"\n✨ Platform Provisioning Pipeline Complete: Status = {report['status']}")
174
+ return report
175
+
176
+ def main():
177
+ sample_request = PlatformWorkloadRequest(
178
+ workload_id="ai-vector-search-cluster",
179
+ environment="production",
180
+ cloud_provider="gcp",
181
+ cluster_region="us-central1",
182
+ expected_qps=8500,
183
+ data_retention_days=90,
184
+ services=["vector-ingestion", "milvus-cluster", "query-gateway"],
185
+ compliance_frameworks=["SOC2-Type2", "ISO-27001"]
186
+ )
187
+
188
+ pipeline = PlatformProvisioningPipeline(sample_request)
189
+ report = pipeline.execute()
190
+ print("\n" + json.dumps(report, indent=2))
191
+
192
+ if __name__ == "__main__":
193
+ main()
package/mcp/README.md CHANGED
@@ -55,6 +55,7 @@ Everything Gemini bundles ready-to-use blueprints in `mcp/mcp_config.example.jso
55
55
  | **`filesystem`** | `@modelcontextprotocol/server-filesystem` | Direct multi-directory filesystem inspection | Stdio |
56
56
  | **`sentry`** | `@modelcontextprotocol/server-sentry` | Real-time production error tracking, issue triage, and stacktrace analysis | Stdio |
57
57
  | **`slack`** | `@modelcontextprotocol/server-slack` | Automated incident channels, alert broadcasts, and team collaboration | Stdio |
58
+ | **`puppeteer`** | `@modelcontextprotocol/server-puppeteer` | Headless browser automation, screenshot diffing, and dynamic web crawling | Stdio |
58
59
 
59
60
  ## Tool Auto-Discovery & Execution
60
61
  Once connected, tools declared by MCP servers are automatically injected into the agent's system prompt and executed through Antigravity's Language Server. Inspect active MCP servers in the Antigravity UI via **Additional Options (...) > MCP Servers**.
@@ -60,6 +60,10 @@
60
60
  "SLACK_BOT_TOKEN": "YOUR_SLACK_BOT_TOKEN",
61
61
  "SLACK_TEAM_ID": "YOUR_SLACK_TEAM_ID"
62
62
  }
63
+ },
64
+ "puppeteer": {
65
+ "command": "npx",
66
+ "args": ["-y", "@modelcontextprotocol/server-puppeteer"]
63
67
  }
64
68
  }
65
69
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "everything-gemini",
3
- "version": "1.8.0",
3
+ "version": "1.9.0",
4
4
  "description": "Everything Gemini (everything-gemini) - The Ultimate Agent Harness, Multi-Agent Orchestrator & Performance Suite for Gemini & Google Antigravity",
5
5
  "main": "bin/everything-gemini",
6
6
  "bin": {
@@ -149,7 +149,7 @@ if [ -f "$REPO_ROOT/tests/cli.test.js" ]; then
149
149
  echo " ❌ ERROR: CLI test suite failed."
150
150
  ERRORS=$((ERRORS + 1))
151
151
  else
152
- echo " ✔ CLI test suite passed (26 assertions)"
152
+ echo " ✔ CLI test suite passed (29 assertions)"
153
153
  fi
154
154
  fi
155
155
 
@@ -0,0 +1,143 @@
1
+ ---
2
+ name: cloudflare-r2-object-storage
3
+ description: >-
4
+ Architects, configures, and integrates Cloudflare R2 zero-egress object storage using S3-compatible APIs, pre-signed upload URLs, multipart streaming, and edge CDN distribution.
5
+ ---
6
+
7
+ # Cloudflare R2 Object Storage & Edge Distribution
8
+
9
+ This skill guides the implementation of zero-egress fee object storage using Cloudflare R2 with S3-compatible APIs, pre-signed URLs, multipart uploads, and edge CDN distribution.
10
+
11
+ ---
12
+
13
+ ## ⚡ Architectural Comparison: R2 vs Standard S3
14
+
15
+ | Feature | Cloudflare R2 | Standard AWS S3 |
16
+ | :--- | :--- | :--- |
17
+ | **Data Egress Fees** | **$0.00 / GB (Free)** | ~$0.09 / GB |
18
+ | **API Compatibility** | Full S3 API v4 signature | Native AWS S3 |
19
+ | **Edge Integration** | Native Cloudflare Workers & CDN | CloudFront integration required |
20
+ | **Storage Pricing** | $0.015 / GB-month | $0.023 / GB-month |
21
+ | **Global Replication** | Automatic across edge locations | Cross-Region Replication (CRR) billed |
22
+
23
+ ---
24
+
25
+ ## 🛠️ TypeScript S3 Client Configuration (`@aws-sdk/client-s3`)
26
+
27
+ R2 endpoints use account-specific URLs with AWS Signature Version 4:
28
+
29
+ ```typescript
30
+ import { S3Client, PutObjectCommand, GetObjectCommand } from '@aws-sdk/client-s3';
31
+ import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
32
+
33
+ const ACCOUNT_ID = process.env.CLOUDFLARE_ACCOUNT_ID!;
34
+ const R2_ACCESS_KEY_ID = process.env.R2_ACCESS_KEY_ID!;
35
+ const R2_SECRET_ACCESS_KEY = process.env.R2_SECRET_ACCESS_KEY!;
36
+
37
+ export const r2Client = new S3Client({
38
+ region: 'auto',
39
+ endpoint: `https://${ACCOUNT_ID}.r2.cloudflarestorage.com`,
40
+ credentials: {
41
+ accessKeyId: R2_ACCESS_KEY_ID,
42
+ secretAccessKey: R2_SECRET_ACCESS_KEY,
43
+ },
44
+ });
45
+ ```
46
+
47
+ ---
48
+
49
+ ## 📤 Pre-Signed URLs for Direct Browser Uploads
50
+
51
+ Prevent API server bottlenecking by generating short-lived pre-signed upload URLs:
52
+
53
+ ```typescript
54
+ export async function generateUploadUrl(key: string, contentType: string, expiresInSeconds = 300) {
55
+ const command = new PutObjectCommand({
56
+ Bucket: 'enterprise-artifacts',
57
+ Key: key,
58
+ ContentType: contentType,
59
+ });
60
+
61
+ const uploadUrl = await getSignedUrl(r2Client, command, { expiresIn: expiresInSeconds });
62
+ return {
63
+ uploadUrl,
64
+ key,
65
+ publicUrl: `https://cdn.example.com/${key}`,
66
+ };
67
+ }
68
+ ```
69
+
70
+ ---
71
+
72
+ ## 📦 High-Throughput Multipart Uploads (Node.js / Python)
73
+
74
+ For files exceeding 100MB, use parallel multipart uploads with the Upload helper:
75
+
76
+ ```typescript
77
+ import { Upload } from '@aws-sdk/lib-storage';
78
+ import fs from 'node:fs';
79
+
80
+ export async function uploadLargeArchive(filePath: string, destinationKey: string) {
81
+ const fileStream = fs.createReadStream(filePath);
82
+
83
+ const parallelUpload = new Upload({
84
+ client: r2Client,
85
+ params: {
86
+ Bucket: 'enterprise-artifacts',
87
+ Key: destinationKey,
88
+ Body: fileStream,
89
+ ContentType: 'application/octet-stream',
90
+ },
91
+ queueSize: 4, // 4 concurrent part uploads
92
+ partSize: 10 * 1024 * 1024, // 10MB chunk size
93
+ leavePartsOnError: false,
94
+ });
95
+
96
+ parallelUpload.on('httpUploadProgress', (progress) => {
97
+ console.log(`Uploaded ${progress.loaded} of ${progress.total} bytes`);
98
+ });
99
+
100
+ return await parallelUpload.done();
101
+ }
102
+ ```
103
+
104
+ ---
105
+
106
+ ## 🌐 Custom Domain & Cloudflare CDN Caching Rule
107
+
108
+ Expose R2 buckets through a custom domain with edge cache headers:
109
+
110
+ ```javascript
111
+ // Cloudflare Worker Edge Proxy
112
+ export default {
113
+ async fetch(request, env) {
114
+ const url = new URL(request.url);
115
+ const key = url.pathname.slice(1);
116
+
117
+ if (request.method !== 'GET') {
118
+ return new Response('Method Not Allowed', { status: 405 });
119
+ }
120
+
121
+ const object = await env.MY_R2_BUCKET.get(key);
122
+ if (!object) {
123
+ return new Response('Not Found', { status: 404 });
124
+ }
125
+
126
+ const headers = new Headers();
127
+ object.writeHttpMetadata(headers);
128
+ headers.set('etag', object.httpEtag);
129
+ headers.set('Cache-Control', 'public, max-age=31536000, immutable');
130
+
131
+ return new Response(object.body, { headers });
132
+ },
133
+ };
134
+ ```
135
+
136
+ ---
137
+
138
+ ## 📋 Architectural Rules & Best Practices
139
+
140
+ 1. **Bucket Region**: Always set region to `auto` in AWS S3 SDK clients; R2 automatically routes storage to the lowest-latency regional cluster.
141
+ 2. **CORS Headers**: Set permissive CORS rules (`AllowedOrigins`, `AllowedMethods: ["PUT", "GET"]`) on the R2 bucket for direct browser pre-signed uploads.
142
+ 3. **Multipart Cleanup**: Configure bucket lifecycle rules to automatically abort incomplete multipart uploads after 7 days (`AbortIncompleteMultipartUpload`).
143
+ 4. **Zero-Egress Strategy**: Route public media and file downloads through Cloudflare Custom Domains or Workers to benefit from zero bandwidth charges.
@@ -0,0 +1,138 @@
1
+ ---
2
+ name: distributed-rate-limiting
3
+ description: >-
4
+ Architects, implements, and tunes distributed rate limiting using Redis sliding window logs, token buckets, tiered API quotas, RFC 6585 headers, and circuit breakers.
5
+ ---
6
+
7
+ # Distributed Rate Limiting & API Traffic Shaping
8
+
9
+ This skill guides the design, implementation, and tuning of distributed rate limiting systems across microservice clusters using Redis, token buckets, and sliding window algorithms.
10
+
11
+ ---
12
+
13
+ ## ⚡ Algorithm Comparison Matrix
14
+
15
+ | Algorithm | Precision | Memory Usage | Burst Handling | Best For |
16
+ | :--- | :--- | :--- | :--- | :--- |
17
+ | **`Sliding Window Log`** | 100% Exact | High ($O(N)$ requests) | Excellent | Low-to-medium traffic sensitive endpoints (auth, payments). |
18
+ | **`Sliding Window Counter`**| ~99% Exact | Fixed ($O(1)$) | Smooth | High-scale public APIs and ingress gateways. |
19
+ | **`Token Bucket`** | High | Very Low ($O(1)$) | Controlled bursts | Standard microservice backpressuring and rate smoothing. |
20
+ | **`Fixed Window`** | Poor (2x burst at boundary) | Lowest | Prone to spikes | Simple non-critical background jobs only. |
21
+
22
+ ---
23
+
24
+ ## 🔒 Atomic Sliding Window Rate Limiter (Redis Lua)
25
+
26
+ Atomic execution in Redis ensures no race conditions across distributed API instances:
27
+
28
+ ```lua
29
+ -- sliding_window.lua
30
+ -- KEYS[1]: Rate limit key (e.g., "ratelimit:tenant_123:orders")
31
+ -- ARGV[1]: Current UNIX timestamp in milliseconds
32
+ -- ARGV[2]: Window size in milliseconds (e.g., 60000 for 1 minute)
33
+ -- ARGV[3]: Maximum allowed requests in window (e.g., 100)
34
+
35
+ local key = KEYS[1]
36
+ local now = tonumber(ARGV[1])
37
+ local window = tonumber(ARGV[2])
38
+ local limit = tonumber(ARGV[3])
39
+ local clearBefore = now - window
40
+
41
+ -- 1. Remove expired request timestamps outside the window
42
+ redis.call('ZREMRANGEBYSCORE', key, 0, clearBefore)
43
+
44
+ -- 2. Count requests currently in the sliding window
45
+ local currentRequests = redis.call('ZCARD', key)
46
+
47
+ if currentRequests < limit then
48
+ -- 3. Register current request with unique timestamp as score and member
49
+ redis.call('ZADD', key, now, now .. '-' .. math.random(1000, 9999))
50
+ redis.call('PEXPIRE', key, window)
51
+ return { 1, limit - currentRequests - 1, 0 } -- [Allowed: 1, Remaining, RetryAfter: 0]
52
+ else
53
+ -- 4. Calculate time until oldest entry expires
54
+ local oldest = redis.call('ZRANGE', key, 0, 0, 'WITHSCORES')
55
+ local retryAfter = math.ceil((tonumber(oldest[2]) + window - now) / 1000)
56
+ return { 0, 0, math.max(1, retryAfter) } -- [Allowed: 0, Remaining: 0, RetryAfter]
57
+ end
58
+ ```
59
+
60
+ ---
61
+
62
+ ## 🌐 Express / Fastify / Node.js Middleware Implementation
63
+
64
+ Wrap Redis Lua execution into production middleware with RFC 6585 compliance:
65
+
66
+ ```typescript
67
+ import { Request, Response, NextFunction } from 'express';
68
+ import Redis from 'ioredis';
69
+
70
+ const redis = new Redis(process.env.REDIS_URL || 'redis://localhost:6379');
71
+
72
+ export function createRateLimiter(options: { windowMs: number; max: number; keyGenerator?: (req: Request) => string }) {
73
+ return async (req: Request, res: Response, next: NextFunction) => {
74
+ const key = options.keyGenerator ? options.keyGenerator(req) : `ratelimit:${req.ip}`;
75
+ const now = Date.now();
76
+
77
+ try {
78
+ const [allowed, remaining, retryAfter] = await redis.eval(
79
+ SLIDING_WINDOW_LUA_SCRIPT,
80
+ 1,
81
+ key,
82
+ now.toString(),
83
+ options.windowMs.toString(),
84
+ options.max.toString()
85
+ ) as [number, number, number];
86
+
87
+ // Set standard RFC 6585 RateLimit response headers
88
+ res.setHeader('X-RateLimit-Limit', options.max);
89
+ res.setHeader('X-RateLimit-Remaining', remaining);
90
+ res.setHeader('X-RateLimit-Reset', Math.ceil((now + options.windowMs) / 1000));
91
+
92
+ if (allowed === 1) {
93
+ return next();
94
+ }
95
+
96
+ res.setHeader('Retry-After', retryAfter);
97
+ return res.status(429).json({
98
+ error: 'Too Many Requests',
99
+ message: `Rate limit exceeded. Please retry after ${retryAfter} seconds.`,
100
+ retryAfter,
101
+ });
102
+ } catch (err) {
103
+ // Circuit Breaker: Fail-Open for high availability if Redis degrades
104
+ console.error('RateLimiter Redis failure, failing open:', err);
105
+ return next();
106
+ }
107
+ };
108
+ }
109
+ ```
110
+
111
+ ---
112
+
113
+ ## 🎯 Tiered Multi-Dimensional Quotas
114
+
115
+ Configure tiered rate limits based on authenticated API keys and endpoint criticality:
116
+
117
+ ```typescript
118
+ export function getTierLimits(tier: 'free' | 'pro' | 'enterprise') {
119
+ switch (tier) {
120
+ case 'enterprise':
121
+ return { windowMs: 60_000, max: 10_000 };
122
+ case 'pro':
123
+ return { windowMs: 60_000, max: 1_200 };
124
+ case 'free':
125
+ default:
126
+ return { windowMs: 60_000, max: 60 };
127
+ }
128
+ }
129
+ ```
130
+
131
+ ---
132
+
133
+ ## 📋 Architectural Rules & Best Practices
134
+
135
+ 1. **Atomic Scripts**: Never implement rate limiters with separated `GET` and `INCR` commands; always execute atomic Lua scripts or Redis Transactions (`MULTI/EXEC`) to prevent race conditions under load.
136
+ 2. **Fail-Open Strategy**: For user-facing critical flows, catch Redis connection timeouts and fail-open with alerting rather than causing total service outages.
137
+ 3. **Multi-Dimensional Keys**: Combine client identity with endpoint routes (e.g. `tenant:123:POST:/api/v1/checkout`) to prevent denial of service on high-cost endpoints.
138
+ 4. **Header Standards**: Always emit `Retry-After`, `X-RateLimit-Limit`, and `X-RateLimit-Remaining` to allow compliant clients to back off exponentially.
@@ -0,0 +1,134 @@
1
+ ---
2
+ name: milvus-vector-clustering
3
+ description: >-
4
+ Architects, scales, and optimizes Milvus distributed vector databases, HNSW/IVF-PQ indexing, hybrid dense-sparse search, dynamic schema partition keys, and scalar metadata filtering.
5
+ ---
6
+
7
+ # Milvus Vector Clustering & Distributed Similarity Search
8
+
9
+ This skill guides the design, indexing, and high-throughput querying of enterprise-scale vector collections using Milvus and Zilliz Cloud.
10
+
11
+ ---
12
+
13
+ ## ⚡ Indexing Selection Matrix
14
+
15
+ | Index Type | Search Latency | Recall Rate | Memory Footprint | Best For |
16
+ | :--- | :--- | :--- | :--- | :--- |
17
+ | **`HNSW`** | Ultra-low (<5ms) | High (>98%) | High (in-memory graph) | Mission-critical search where latency is top priority. |
18
+ | **`IVF_FLAT`** | Medium (10-30ms) | Tunable (nprobe) | Moderate | Standard baseline for medium datasets (<10M vectors). |
19
+ | **`IVF_PQ`** | Low (5-15ms) | Moderate (85-92%) | Very Low (quantized) | Massive scale (100M+ vectors) with tight RAM budgets. |
20
+ | **`SCANN`** | Very Low (<8ms) | High (>95%) | Moderate | High-dimensional CPU-accelerated similarity search. |
21
+ | **`SPARSE_INVERTED_INDEX`**| Ultra-low | Exact / BM25 | Low | Sparse lexical vectors (SPLADE, BM25 hybrid ranking). |
22
+
23
+ ---
24
+
25
+ ## 🏗️ Production Collection Schema with Partition Keys
26
+
27
+ Multi-tenant applications should leverage Milvus **Partition Keys** to isolate tenant data logically without exceeding physical partition limits:
28
+
29
+ ```python
30
+ from pymilvus import (
31
+ connections, FieldSchema, CollectionSchema, DataType,
32
+ Collection, utility
33
+ )
34
+
35
+ # Connect to Milvus Cluster / Standalone
36
+ connections.connect(alias="default", host="localhost", port="19530")
37
+
38
+ fields = [
39
+ # Primary Key
40
+ FieldSchema(name="doc_id", dtype=DataType.VARCHAR, max_length=128, is_primary=True, auto_id=False),
41
+
42
+ # Multi-tenant Partition Key (routes queries to physical partition clusters)
43
+ FieldSchema(name="tenant_id", dtype=DataType.VARCHAR, max_length=64, is_partition_key=True),
44
+
45
+ # Scalar Metadata for Pre-filtering
46
+ FieldSchema(name="category", dtype=DataType.VARCHAR, max_length=64),
47
+ FieldSchema(name="created_at", dtype=DataType.INT64),
48
+ FieldSchema(name="is_archived", dtype=DataType.BOOL),
49
+
50
+ # Dense Vector Embedding (e.g., text-embedding-004, 768 dimensions)
51
+ FieldSchema(name="dense_vector", dtype=DataType.FLOAT_VECTOR, dim=768),
52
+
53
+ # Sparse Lexical Vector (e.g., SPLADE or BM25 tokens)
54
+ FieldSchema(name="sparse_vector", dtype=DataType.SPARSE_FLOAT_VECTOR),
55
+ ]
56
+
57
+ schema = CollectionSchema(fields=fields, description="Enterprise Knowledge Base Vectors", enable_dynamic_field=True)
58
+ collection = Collection(name="knowledge_embeddings", schema=schema)
59
+ ```
60
+
61
+ ---
62
+
63
+ ## 🔍 Building Vector Indexes
64
+
65
+ Build indexes before loading the collection into memory:
66
+
67
+ ```python
68
+ # 1. Dense Vector Index (HNSW for high recall & low latency)
69
+ dense_index_params = {
70
+ "metric_type": "COSINE",
71
+ "index_type": "HNSW",
72
+ "params": {
73
+ "M": 16, # Max outgoing links per node (16-64)
74
+ "efConstruction": 200 # Exploration factor during index build
75
+ }
76
+ }
77
+ collection.create_index(field_name="dense_vector", index_params=dense_index_params)
78
+
79
+ # 2. Sparse Vector Index
80
+ sparse_index_params = {
81
+ "metric_type": "IP", # Inner Product for sparse lexical weights
82
+ "index_type": "SPARSE_INVERTED_INDEX",
83
+ "params": {"drop_ratio_build": 0.2}
84
+ }
85
+ collection.create_index(field_name="sparse_vector", index_params=sparse_index_params)
86
+
87
+ # Load into query nodes
88
+ collection.load()
89
+ ```
90
+
91
+ ---
92
+
93
+ ## 🚀 Hybrid Search with Reciprocal Rank Fusion (RRF)
94
+
95
+ Combine dense semantic search with sparse lexical matching for optimal recall:
96
+
97
+ ```python
98
+ from pymilvus import AnnSearchRequest, RRFRanker
99
+
100
+ # Dense vector query request
101
+ dense_req = AnnSearchRequest(
102
+ data=[query_dense_embedding],
103
+ anns_field="dense_vector",
104
+ param={"metric_type": "COSINE", "params": {"ef": 64}},
105
+ limit=50,
106
+ expr='tenant_id == "org_acme" and is_archived == false'
107
+ )
108
+
109
+ # Sparse vector query request
110
+ sparse_req = AnnSearchRequest(
111
+ data=[query_sparse_dict],
112
+ anns_field="sparse_vector",
113
+ param={"metric_type": "IP", "params": {"drop_ratio_search": 0.1}},
114
+ limit=50,
115
+ expr='tenant_id == "org_acme" and is_archived == false'
116
+ )
117
+
118
+ # Execute hybrid search with RRF reranking
119
+ results = collection.hybrid_search(
120
+ reqs=[dense_req, sparse_req],
121
+ rerank=RRFRanker(k=60),
122
+ limit=10,
123
+ output_fields=["doc_id", "category", "created_at"]
124
+ )
125
+ ```
126
+
127
+ ---
128
+
129
+ ## 📋 Architectural Rules & Best Practices
130
+
131
+ 1. **Partition Key Limits**: Use `is_partition_key=True` for tenant routing; Milvus maps millions of logical tenants into ~64-256 physical partition clusters automatically.
132
+ 2. **Pre-Filtering Optimization**: Place high-selectivity scalar filters (`expr='category == "tech"'`) directly in the ANN search request to prune candidate sets before graph traversal.
133
+ 3. **Compaction Management**: Call `collection.compact()` after bulk insertions or deletions to merge small segment files and purge deleted entity tombstones.
134
+ 4. **Memory Sizing**: For HNSW, allocate approximately `(dim * 4 + M * 8) * num_vectors` bytes of RAM on QueryNodes.