← Catalog

@abhishek944/pi-embeddings

Config-driven text embeddings for Pi and MCP with local, OpenAI, Sarvam, Gemini, Vertex ADC, OpenCode and gateway routes, ordered fallback and explicit comparisons.

Package

Install

Install with PiG

pig install npm:@abhishek944/pi-embeddings

Install with Pi

pi install npm:@abhishek944/pi-embeddings
Review before installing

Packages run code with your permissions and influence agent behavior. Catalog inclusion is not a security audit. Review the source before installing a third-party package.

Pi manifest JSON

The pi field of package.json.

{
  "extensions": [
    "./dist/extension.js"
  ]
}

README

Written by the package's publisher, shown as published in version 0.5.0 (README.md). PiG does not review it.

pi-embeddings

Config-driven text embeddings for Pi and MCP. The package owns provider configuration, credentials, request construction, preparation, mandatory batching, transport, local runtime lifecycle, validation, normalization, fallback, explicit comparison and usage accounting. Callers own storage and compatibility decisions.

Public surfaces

  • @abhishek944/pi-embeddings — typed library factory and derived public types. No Pi runtime imports.
  • @abhishek944/pi-embeddings/schemas — authoritative TypeBox schemas for settings, requests, outcomes, attempts, results, context, descriptors and actual generation metadata.
  • @abhishek944/pi-embeddings/extension — Pi extension registered in pi.extensions.
  • @abhishek944/pi-embeddings/mcp — createEmbeddingsMcpServer; transport-neutral, no Pi runtime dependency.
  • pi-embeddings-mcp — stdio binary. stdout carries JSON-RPC only; diagnostics go to stderr.

MCP tools are embed and embed_compare. Vectors and their actual generating metadata are returned in structuredContent.result; the text content is a short summary. Pi commands are /embeddings list, doctor, reload, use <provider> <model> and compare <text>. There is no describe tool.

import { createEmbeddingsRuntime } from '@abhishek944/pi-embeddings';

const runtime = createEmbeddingsRuntime({ settings, cwd });
const result = await runtime.embed({ inputs: ['Attribute: value'] }, { signal, context });
console.log(result.provider, result.model, result.space, result.generations);
await runtime.close();

There are no per-call provider, model, endpoint, credential or expected-space parameters. The result reports the provider, model and complete space that actually generated the vectors. generations lists every distinct actual generation in first-seen order; the singular fields are populated only when one generation produced every vector. Mixed fallback results are never collapsed into a guessed route or space.

Settings

Settings live under the pi-embeddings namespace. Pi loading follows global < agent config < explicitly trusted project; environment interpolation applies only to the global and agent layers. A standalone CLI never reads project settings. A service host passes operator-approved settings explicitly.

{
  "pi-embeddings": {
    "version": 1,
    "default": { "provider": "local", "model": "embeddinggemma-2" },
    "fallback": [{ "provider": "openai", "model": "text-embedding-3-small" }],
    "compare": [{ "provider": "sarvam", "model": "embeddinggemma-2" }],
    "providers": {
      "local": {
        "executable": "/operator-supplied/runtime/llama-server",
        "modelPath": "/operator-supplied/model/embeddinggemma-2-Q8_0.gguf"
      },
      "openai": { "apiKey": "${OPENAI_API_KEY}" },
      "sarvam": { "apiKey": "${SARVAM_API_KEY}" },
      "gateway": {
        "baseUrl": "https://operator-gateway.example",
        "apiKey": "${LITELLM_INFERENCE_KEY}",
        "model": "openai/text-embedding-3-small",
        "stage": "dev"
      },
      "openrouter": { "apiKey": "${OPENROUTER_API_KEY}" },
      "cloudflare": {
        "accountId": "${CLOUDFLARE_ACCOUNT_ID}",
        "apiKey": "${CLOUDFLARE_API_TOKEN}",
        "gatewayId": "${CLOUDFLARE_AI_GATEWAY_ID}",
        "model": "@cf/baai/bge-base-en-v1.5",
        "pooling": "cls"
      },
      "gemini": {
        "apiKey": "${GEMINI_API_KEY}",
        "dimensions": 3072,
        "taskFormat": "retrieval-document"
      },
      "opencode": { "apiKey": "${OPENCODE_API_KEY}" },
      "opencode-go": { "apiKey": "${OPENCODE_API_KEY}" }
    }
  }
}

Provider IDs are route identifiers: local, openai, sarvam, gateway, openrouter, cloudflare, gemini, vertex, opencode and opencode-go. Only the declared model pairs are valid. Omitted or empty fallback and compare lists are inactive. No route is activated by a schema annotation, a present key or existing model files. Credentials and identifiers may also come from OPENROUTER_API_KEY, CLOUDFLARE_ACCOUNT_ID, CLOUDFLARE_API_TOKEN, CLOUDFLARE_AI_GATEWAY_ID, GEMINI_API_KEY and OPENCODE_API_KEY in the trusted host environment. An environment fallback works only when the MCP process itself receives that variable; a hosted settings file that is copied without environment forwarding must carry the relevant providers.<route>.apiKey directly. In the Pi extension, OpenCode routes can also use the provider key already resolved by Pi through ModelRegistry.getApiKeyForProvider; the library and MCP server never read Pi's credential file.

Google Cloud Vertex (keyless ADC)

Vertex is a separate route, not a Gemini Developer API endpoint override. All four configuration fields are explicit; no API key, credential JSON, token or custom URL is accepted in package settings:

{
  "pi-embeddings": {
    "version": 1,
    "default": { "provider": "vertex", "model": "gemini-embedding-2" },
    "fallback": [],
    "providers": {
      "vertex": {
        "project": "highsku",
        "location": "us",
        "dimensions": 768,
        "taskFormat": "retrieval-document"
      }
    }
  }
}

location is us, eu or global, the documented Gemini Embedding 2 locations. The us multi-region is not Iowa-only. dimensions accepts 128–3072 and taskFormat uses the same instruction formats as Gemini below. Selecting a Vertex route without its provider configuration fails validation before inference.

The official google-auth-library discovers ADC in the trusted host environment: local user ADC, attached service account metadata, workload/workforce federation or impersonation. Private-key service-account/GDCH credentials, including an impersonation source, are rejected. The adapter never runs gcloud, reads the operator's gcloud token cache, accepts a Gemini API key or creates credentials. The runtime identity needs aiplatform.endpoints.predict on the target project/model for both operations; API enablement, IAM, quota and billing remain operator responsibilities. No IAM/API change happens automatically. Local ADC is distinct from gcloud auth login; configure it through Google's documented ADC setup outside this package.

Both countTokens and embedContent use the same Vertex host and full resource path. US uses https://aiplatform.us.rep.googleapis.com/v1/projects/{project}/locations/us/publishers/google/models/gemini-embedding-2:{method}; EU uses the corresponding eu host; global uses https://aiplatform.googleapis.com with locations/global. Only the SDK's bearer authorization and optional quota-project header are forwarded. Native model requests reject redirects and have no automatic retry. ADC discovery/refresh errors are sanitized to configuration-invalid, not guessed to be fallback-eligible HTTP errors. Cancellation stops waiting for ADC and prevents a subsequent model request; an already-running SDK credential refresh may finish in the background.

Provider-free diagnostics validate configuration only: they do not prove ADC, API activation, permissions or live model readiness. A real successful neutral call is required to establish endpoint/counting acceptance for the selected project/location. The generic Vertex countTokens contract is documented, but model-specific support must not be claimed from static schema validation alone.

Ordinary calls use the configured default, then configured fallback in order, advancing only for typed missing credentials or HTTP 401/404/429 from route acquisition, provider preparation or embedding. Gemini countTokens preflight errors therefore follow the same fallback rule. There is no fallback for 403, refusal, 400/422, invalid input or vector, malformed response, token-count mismatch, ambiguous network failure, timeout, 5xx or cancellation. Successful inputs are never replayed on another route. Explicit comparison runs exactly the configured compare list in order, without fallback, ranking or default mutation.

Routes and batching

  • local: pinned EmbeddingGemma 2 Q8 CPU, 768 dimensions. The operator supplies assets; the package verifies the exact model hash and runtime commit, starts only its own loopback child, uses CPU-only flags, shares it across acquisitions and closes it once. No download, install, global binary search, warmup or foreign listener takeover.

  • openai: text-embedding-3-small, 1536 dimensions. Complete prefixed strings are submitted; cl100k_base counts the exact prepared string and a local encode/decode round-trip is checked. Mandatory limits are 8192 tokens per input, 2048 inputs and 300000 tokens per request.

  • sarvam: hosted embeddinggemma-2, 768 dimensions. Strings are submitted and the service enforces its documented per-string token estimate; no local count or borrowed aggregate cap is invented.

  • gateway: the declared OpenAI recipe through LiteLLM. Only text-embedding-3-small and openai/text-embedding-3-small aliases are supported. One request carries generic host attribution as x-litellm-customer-id and x-litellm-tags; missing or unsafe attribution refuses before inference.

  • openrouter: openai/text-embedding-3-small through https://openrouter.ai/api/v1/embeddings with bearer authentication and float output. It shares the OpenAI generating-space descriptor because the declared model, text preparation and normalization are identical.

  • cloudflare: @cf/baai/bge-base-en-v1.5 through Cloudflare's documented REST POST /ai/run/{model}. The Cloudflare API token goes in Authorization, and the gateway ID goes in cf-aig-gateway-id as Workers AI requires. pooling defaults to mean; cls produces a different generating space and is recorded in the result. The REST API wraps the model output in its standard result envelope; the parser also accepts the model's raw { shape, data, pooling } form. Cloudflare reports no local token usage, so usage fields are null.

  • gemini: gemini-embedding-2 through the fixed Gemini API POST /v1beta/models/gemini-embedding-2:embedContent endpoint with the x-goog-api-key header. dimensions accepts the documented 128–3072 range (768, 1536 and 3072 are Google's recommended sizes) and defaults to 3072. taskFormat selects the documented Gemini 2 text prefix (retrieval-document by default, plus query and single-input formats); the package does not send task_type, which applies only to gemini-embedding-001. Each exact prepared prompt is counted with the model's countTokens endpoint before a single-input embedContent request; inputs over the documented 8192-token boundary fail before inference, and the embed response token count must match the preflight count before a vector is accepted. autoTruncate: false is deliberately not sent because the official SDK marks it Enterprise/Vertex-only. The exact dimension, task format and prefix are recorded in the generating space.

  • opencode: OpenCode Console pay-as-you-go models through the fixed POST https://opencode.ai/inference/openai/v1/embeddings endpoint with bearer authentication. Pi calls this catalog OpenCode Zen. The twelve documented embedding model IDs are text-embedding-3-small, text-embedding-3-large, gemini-embedding-2, gemini-embedding-001, codestral-embed, mistral-embed, cohere-embed-v5-pro, cohere-embed-v5-fast, voyage-4, voyage-code-4, qwen3-embedding-8b and bge-m3. No dimensions option is guessed; the response's vector length becomes the observed dimension in the actual generating space. An echoed model that differs from the configured model fails closed.

  • opencode-go: OpenCode Go subscription through the fixed POST https://opencode.ai/inference/go/openai/v1/embeddings endpoint. The documented models are text-embedding-3-small, qwen3-embedding-8b and gemini-embedding-2. Embeddings do not need the chat x-opencode-session header; the adapter identifies itself with a pi-embeddings user agent. A missing or non-Go key returns HTTP 401 or 403; 403 entitlement failures do not advance fallback. Both OpenCode routes use explicit providers.opencode.apiKey or providers.opencode-go.apiKey, Pi's stored provider key in the extension, or OPENCODE_API_KEY, in that order.

  • vertex: Google Cloud gemini-embedding-2 through the fixed Vertex v1 embedContent and countTokens resource methods with keyless ADC. Each exact instruction-prefixed text is counted before inference and must fit the documented 8192-token window; role: user is consistent in both operations. Dimensions use embedContentConfig.outputDimensionality. The model's task_type and autoTruncate options are not used. A true response truncated flag, mismatched prompt count, missing usage, invalid dimensions or invalid vector fails closed; no truncated vector is accepted. Its complete descriptor has provider: vertex and runtime: vertex-ai-v1, distinct from gemini even for identical model names and dimensions.

The package supplies the document prefix title: none | text: exactly once and normalizes vectors with the recorded stable L2 identity. It never summarizes, trims, chunks or truncates input text.

MCP attribution

Hosts pass generic attribution in params._meta under pi-embeddings/context:

{ "pi-embeddings/context": { "endUser": "verified-owner", "tags": ["stage:dev", "base:..."] } }

This is attribution only. The authenticated server-to-server boundary supplies caller authority; metadata is never proof of ownership and cannot include provider, model, endpoint or credential overrides.

Generating spaces

Descriptors record canonical provider, model, known revision or explicit null, quantization/runtime/pooling provenance, dimensions, preparation prefix and normalization identity. Local, Sarvam and Cloudflare remain distinct at 768 dimensions, and Cloudflare mean and cls are distinct spaces. Gemini and Vertex dimensions and task formats are distinct spaces, including 768-dimensional MRL output; Vertex is never relabeled as the Developer API or vice versa, because the provider, prompt format and normalization provenance differ. Direct OpenAI, the declared gateway alias and the declared OpenRouter alias share the OpenAI descriptor only when the effective text, preparation and normalization remain identical. API keys, service URLs, account IDs and gateway IDs are route metadata, not implicit new spaces. The ordinary embed result carries these descriptors for actual successful work; no separate metadata call is required.

OpenCode Console and Go are always distinct from direct OpenAI and from each other, even when the model ID is the same: their runtime provenance differs, and bit-for-bit equivalence has not been verified. OpenCode preflight descriptors report dimensions: null; a successful outcome records the positive vector length observed in that response. Existing stored vector documents are preserved. Package outcome descriptors allow callers to compare complete identity before persistence; a successful inference from an incompatible space is still reported truthfully.

Limits

No application capacity caps are added. Provider request limits above are mandatory documented constraints. Sarvam, local, Cloudflare and OpenCode publish no aggregate request cap, so none is invented. OpenCode requires each input to fit the chosen model's context window; the package does not guess a local tokenizer or dimension ceiling for its multi-model catalog, so the service may reject an oversized input. Gemini publishes an 8192-token input boundary and no aggregate request cap; one exact prompt per request is pre-counted with countTokens, and a mismatched embed token count fails closed. Cloudflare documents a 512-token per-input ceiling for bge-base-en-v1.5; this package does not ship that model's tokenizer and does not approximate the ceiling locally, so Cloudflare may reject an oversized input. No cost estimator or pricing table is included; unknown provider accounting is reported as null. OpenCode's reported usage.cost and Go allowance are billing metadata outside the token-usage protocol and remain null in billedTokens.

Official Vertex contracts: embedContent, countTokens, multimodal model constraints and task instructions, and ADC discovery order.

The public result protocol is version 2; stored generating-space documents keep their existing descriptor format. Live cloud or local inference, service deployment and shared database writes are not performed by this package.