Vector
The Vector Module provides vector storage and embedding generation for Retrieval-Augmented Generation (RAG). It decouples vector stores from embedding providers, allowing you to mix and match infrastructure freely.
Kirak currently launches with an initial set of supported vector stores (Pinecone, Amazon S3 Vectors) and embedding providers (OpenAI, Google Gemini, Ollama), with new vector databases, local embedders, and cloud providers continuously being added by both the core team and community contributors. Custom stores and embedders can be plugged in easily via Kirak’s modular provider architecture.
Installation & Setup
Section titled “Installation & Setup”Install provider extras as needed:
# Pinecone and embedding providers (OpenAI, Gemini, Ollama) need no extra installspip install "kirak[vector-s3vectors]" # Amazon S3 Vectors (boto3)pip install "kirak[all-vector]" # All vector providerspip install "kirak[all]" # All Kirak extrasEnable the module in kirak.json:
{ "modules": ["vector"], "vector": { "store": { "default_provider": "pine", "providers": { "pine": { "type": "pinecone" } } }, "embedding": { "default_provider": "openai", "providers": { "openai": { "type": "openai", "model": "text-embedding-3-small" } } } }}Credentials are read from environment variables matching KIRAK_VECTOR_<CATEGORY>_<INSTANCE>_<FIELD>:
KIRAK_VECTOR_STORE_PINE_API_KEY=pcsk_...KIRAK_VECTOR_EMBEDDING_OPENAI_API_KEY=sk-...Retrieval-Augmented Generation (RAG) Architecture
Section titled “Retrieval-Augmented Generation (RAG) Architecture”The Vector module powers a dual-path RAG pipeline, separating offline document ingestion from real-time agent retrieval:
flowchart TD subgraph IngestionPipeline["1. Ingestion & Indexing Pipeline (Write Path)"] direction TB RawDoc["Raw Documents<br/>(PDF, Markdown, HTML)"] --> Chunking["App-Level Chunking<br/>(Unstructured / LangChain)"] Chunking --> TextList["List of Text Chunks<br/>[{id: 'faq-1', text: '...'}, ...]"] TextList --> UpsertCall["kirak.vector.upsert(index='docs', vectors=...)"] UpsertCall --> EmbedGen["Embedding Provider<br/>(OpenAI / Gemini / Ollama)<br/>Batch Turn Text to Vectors"] EmbedGen --> DimCheck{"Verify Vector Dimensions<br/>against Index Schema"} DimCheck -- "Mismatch" --> DimErr["Raise 400 VECTOR_DIMENSION_MISMATCH"] DimCheck -- "Valid" --> StoreWrite["Persist to Vector Store<br/>(Pinecone Index / S3 Vector Bucket)"] end
subgraph QueryPipeline["2. Agentic Retrieval Pipeline (Read Path)"] direction TB UserQuery["User Asks Question<br/>'What is your refund policy?'"] --> Agent["AI Agent (pydantic-ai)"] Agent --> ToolCall["Agent Calls Tool: vector.search(text='refund policy')"] ToolCall --> HookTenant{"Execute before_search Hook<br/>(Inject Tenant/User RLS Filter)"} HookTenant --> QueryEmbed["Embedding Provider<br/>Turn Query to 1536-dim Vector"] QueryEmbed --> SimilaritySearch["Vector Store Similarity Search<br/>(Cosine / Euclidean distance, top_k=5)"] SimilaritySearch --> ReturnMatches["Return Top-K Matched Chunks + Metadata"] ReturnMatches --> AgentSynthesis["Agent Synthesizes Verified Answer<br/>using Retrieved Context"] endProviders & Backends
Section titled “Providers & Backends”| Category | Type | Notes & Capabilities |
|---|---|---|
| Store | pinecone |
Serverless indexes. Metrics: cosine, euclidean, dotproduct. Supports tenant namespaces and delete by metadata filter. |
| Store | s3_vectors |
Amazon S3 Vector buckets (requires kirak[vector-s3vectors]). Metrics: cosine and euclidean. Delete by ID only (no filter delete). |
| Embedding | openai |
OpenAI /v1/embeddings API. Configurable model and dimensions. Supports OpenAI-compatible self-hosted endpoints via base_url. |
| Embedding | google |
Google Gemini batchEmbedContents. Automatically applies semantic retrieval task types (RETRIEVAL_QUERY vs RETRIEVAL_DOCUMENT). |
| Embedding | ollama |
Local or self-hosted Ollama server for zero-cost, local embeddings. No API keys required. |
All Vector Settings, Provider Settings & Environment Variables
vector key |
Type | Description |
|---|---|---|
store |
object | Vector store providers (e.g. pinecone, s3_vectors). |
embedding |
object | Embedding providers (e.g. openai, google, ollama). |
<INSTANCE> is the provider instance’s name in kirak.json, upper-cased: an instance
named main reads ..._MAIN_....
store / pinecone (no extra install) – Pinecone serverless indexes.
Credential check (check()): GET /indexes.
| Name | Where | Required / default | Description |
|---|---|---|---|
cloud |
kirak.json | default aws |
Cloud of new indexes. |
region |
kirak.json | default us-east-1 |
Region of new indexes. |
api_version |
kirak.json | default 2026-04 |
Pinecone API version. |
batch_size |
kirak.json | default 100 |
Vectors per upsert request (at most 1000). |
ready_timeout |
kirak.json | default 120 |
Seconds create_index waits for the index to be ready. |
max_retries |
kirak.json | default 3 |
Retries on rate limits and server errors. |
timeout |
kirak.json | default 30.0 |
Request timeout in seconds. |
KIRAK_VECTOR_STORE_<INSTANCE>_API_KEY |
environment | required | Pinecone API key. |
store / s3_vectors (pip install "kirak[vector-s3vectors]") – Amazon S3 Vectors indexes in an existing vector bucket.
Credential check (check()): GetVectorBucket on the configured bucket.
| Name | Where | Required / default | Description |
|---|---|---|---|
bucket |
kirak.json | required | Existing vector bucket. |
region |
kirak.json | required | Bucket region. |
non_filterable_metadata_keys |
kirak.json | Metadata keys stored but not usable in filters, for new indexes. | |
max_retries |
kirak.json | default 3 |
Retries on rate limits and server errors. |
KIRAK_VECTOR_STORE_<INSTANCE>_ACCESS_KEY_ID |
environment | AWS access key ID. Optional: boto3’s default credential chain is used when unset. | |
KIRAK_VECTOR_STORE_<INSTANCE>_SECRET_ACCESS_KEY |
environment | AWS secret access key. Set together with the access key ID. |
embedding / openai (no extra install) – OpenAI embeddings, or any OpenAI-compatible endpoint through base_url.
Credential check (check()): GET /models; the configured model must be listed.
| Name | Where | Required / default | Description |
|---|---|---|---|
model |
kirak.json | required | Embedding model name. |
base_url |
kirak.json | default https://api.openai.com/v1 |
API base URL. |
dimensions |
kirak.json | Output vector length, for models that can shorten it. | |
batch_size |
kirak.json | default 100 |
Texts per request (at most 2048). |
max_retries |
kirak.json | default 3 |
Retries on rate limits and server errors. |
timeout |
kirak.json | default 30.0 |
Request timeout in seconds. |
KIRAK_VECTOR_EMBEDDING_<INSTANCE>_API_KEY |
environment | required | OpenAI API key. |
embedding / google (no extra install) – Google Gemini embeddings.
Credential check (check()): GET /models/
| Name | Where | Required / default | Description |
|---|---|---|---|
model |
kirak.json | required | Embedding model name. |
dimensions |
kirak.json | Output vector length, for models that can shorten it. | |
batch_size |
kirak.json | default 100 |
Texts per request (at most 100). |
max_retries |
kirak.json | default 3 |
Retries on rate limits and server errors. |
timeout |
kirak.json | default 30.0 |
Request timeout in seconds. |
KIRAK_VECTOR_EMBEDDING_<INSTANCE>_API_KEY |
environment | required | Gemini API key. |
embedding / ollama (no extra install) – Embeddings from a local or self-hosted Ollama server.
Credential check (check()): GET /api/tags; the configured model must be pulled.
| Name | Where | Required / default | Description |
|---|---|---|---|
model |
kirak.json | required | Embedding model name. |
base_url |
kirak.json | default http://localhost:11434 |
Ollama server URL. |
batch_size |
kirak.json | default 100 |
Texts per request. |
max_retries |
kirak.json | default 3 |
Retries on rate limits and server errors. |
timeout |
kirak.json | default 30.0 |
Request timeout in seconds. |
Core Operations
Section titled “Core Operations”All vector operations return the standard Kirak response envelope. Administrative and write operations (create_index, delete_index, upsert, delete) require an Admin caller or code running as system; read operations (search, fetch, embed) require any Authenticated caller.
1. upsert (Ingesting Vectors or Raw Text)
Section titled “1. upsert (Ingesting Vectors or Raw Text)”When you pass text, Kirak automatically batches the strings through the active embedding provider before writing them to the vector store:
await kirak.vector.upsert({ "index": "docs", "vectors": [ { "id": "faq-101", "text": "Refunds are processed within 5 to 7 business days.", "metadata": {"category": "billing", "tenant_id": "tenant-42"}, }, { "id": "faq-102", # Or pass pre-computed float values directly: "values": [0.0124, -0.0431, 0.0892, ...], "metadata": {"category": "shipping"}, }, ], "namespace": "tenant-42", # Optional: Pinecone tenant isolation})2. search (Similarity Search)
Section titled “2. search (Similarity Search)”Retrieves the most semantically relevant vectors for a natural language query or raw embedding:
result = await kirak.vector.search({ "index": "docs", "text": "How long until I receive my refund?", "top_k": 5, "filter": {"category": {"$eq": "billing"}}, # Metadata filter passed to store})
matches = result["data"]["matches"]# [# {"id": "faq-101", "score": 0.94, "metadata": {"category": "billing", ...}},# ...# ]3. embed and embed_batch (Standalone Embeddings)
Section titled “3. embed and embed_batch (Standalone Embeddings)”Generate vector representations without writing to a store:
# Embed a single query (optimized for query retrieval):query_vec = (await kirak.vector.embed({"text": "What is Kirak?"}))["data"]["embedding"]
# Embed a batch of documents (optimized for indexing):doc_vecs = (await kirak.vector.embed_batch({ "texts": ["Kirak is a rapid API runtime.", "FastAPI with model-driven CRUD."]}))["data"]["embeddings"]4. Index Management (create_index, delete_index, describe_index)
Section titled “4. Index Management (create_index, delete_index, describe_index)”# Create an index with dimension and metric specifications:await kirak.vector.create_index({ "name": "docs", "dimensions": 1536, "metric": "cosine", # "cosine", "euclidean", or "dotproduct"})
# List active indexes:indexes = (await kirak.vector.list_indexes({}))["data"]["indexes"]
# Delete index:await kirak.vector.delete_index({"name": "old-index"})create_index and describe_index (and each entry of list_indexes) return the same keys on every store: {"name", "dimensions", "metric", "ready"} (ready: the index takes upserts and queries), plus the store’s own extras (Pinecone’s host, S3 Vectors’ arn).
delete returns {"deleted": N}, the number of ids it deleted, on every store. A delete by filter (Pinecone only) returns {"deleted": null}: the store does not say how many vectors matched.
Equipping AI Agents with Vector Search
Section titled “Equipping AI Agents with Vector Search”There are two primary patterns for integrating vector search into declarative AI agents:
Pattern A: Declarative Tool in agents/<name>.json
Section titled “Pattern A: Declarative Tool in agents/<name>.json”Bind vector.search directly into the agent declaration, using fixed to pin the index so the LLM cannot query unauthorized stores:
{ "name": "support-agent", "model": "openai:gpt-4o", "instructions": "Answer questions using the knowledge base. Always search 'kb-index' first.", "tools": { "search_docs": { "operation": "vector.search", "description": "Search company documentation for answers", "fixed": { "index": "docs", "provider": "pine" }, "params": { "top_k": { "maximum": 10 } } } }}Pattern B: Custom Python Agent Tool
Section titled “Pattern B: Custom Python Agent Tool”For advanced filtering, tenant resolution, or database lookups before querying vectors:
from pydantic_ai import RunContextfrom kirak.ai import KirakDeps
def on_kirak_ready(kirak):
@kirak.agent("support-agent").tool async def search_knowledge_base(ctx: RunContext[KirakDeps], query: str) -> list: """Search company knowledge base for relevant articles.""" user = ctx.deps.current_user tenant_id = user.get("tenant_id")
# Automatically confine search to the caller's tenant: res = await kirak.vector.search({ "index": "docs", "text": query, "top_k": 5, "filter": {"tenant_id": {"$eq": tenant_id}}, }) return [m["metadata"]["text"] for m in res["data"]["matches"]]Multi-Tenant Security via Synchronous Hooks
Section titled “Multi-Tenant Security via Synchronous Hooks”To enforce row-level security across vector searches without relying on the LLM to provide tenant filters, implement a synchronous before_search hook:
from kirak.core.context import get_user_contextfrom kirak.core.exceptions import PermissionDenied
@kirak.vector.hook("before_search")def scope_search_to_tenant(params: dict) -> dict: caller = get_user_context() if not caller or "tenant_id" not in caller: raise PermissionDenied("Search requires authenticated tenant context")
# Inject tenant filter into store query: params["filter"] = {"tenant_id": {"$eq": caller["tenant_id"]}} return params[!IMPORTANT] Use Synchronous
def, Neverasync def: A synchronous hook runs to completion before the vector store is queried. If it raises an exception (e.g.PermissionDenied), execution aborts immediately. Asynchronous hooks isolate errors to prevent crashing background tasks; an async hook that raises would be skipped, inadvertently executing the vector search without the tenant filter!
Architectural Notice: Zero-Public-HTTP Surface
Section titled “Architectural Notice: Zero-Public-HTTP Surface”The Vector module deliberately mounts no public HTTP endpoints (router() returns an empty APIRouter()). This is an intentional security design:
- Quota Protection: Public
embedendpoints would allow anonymous users to exhaust your OpenAI or Gemini embedding budget. - Infrastructure Shielding: Index creation and deletion are DevOps/administrative tasks that should not be exposed to the public Internet.
- Data Scoping: Raw unauthenticated vector search could expose the entire index. Vector operations should always run in-process within authenticated agent tools or custom API routes.