omp packages

@abhishek944/pi-embeddings0.6.1

Config-driven text embeddings for Pi and MCP with local, OpenAI, Sarvam, Gemini, Vertex ADC, OpenCode, Voyage, Cohere, Jina, Alibaba DashScope, Hetzner, gateway and OpenRouter routes, ordered fallback and explicit comparisons.

GitHub Actions Published 15 hours ago Apache-2.0 ~1K downloads/mo

Untested on omp

This is a pi package. No one has reported whether it works on omp yet. If you try it, add your result below.

Did it work for you?

Result

One report per person. A new report replaces your old one.

Reports 0

No reports yet.

Readme

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}" },
      "voyage": { "apiKey": "${VOYAGE_API_KEY}", "dimensions": 1024 },
      "cohere": { "apiKey": "${COHERE_API_KEY}", "dimensions": 2048 },
      "jina": { "apiKey": "${JINA_API_KEY}", "dimensions": 1024 },
      "dashscope": {
        "baseUrl": "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com",
        "apiKey": "${DASHSCOPE_API_KEY}",
        "dimensions": 1024
      },
      "hetzner": { "apiKey": "${HETZNER_INFERENCE_TOKEN}" }
    }
  }
}

Provider IDs are route identifiers: local, openai, sarvam, gateway, openrouter, cloudflare, gemini, vertex, opencode, opencode-go, voyage, cohere, jina, dashscope and hetzner. 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, OPENCODE_API_KEY, VOYAGE_API_KEY, COHERE_API_KEY, JINA_API_KEY, DASHSCOPE_API_KEY, DASHSCOPE_BASE_URL and HETZNER_INFERENCE_TOKEN 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 (ADC, or an explicit credential file)

Vertex is a separate route, not a Gemini Developer API endpoint override. project, location, dimensions and taskFormat are explicit, plus the optional credentialsFile path; no API key, inline 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.

Without credentialsFile 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, stay rejected on that path. credentialsFile is a filesystem path to a service-account or authorized-user JSON key that the operator placed outside the settings file. When it is set, the package reads the file as data, parses it, and hands it to the SDK as in-memory credentials; the deprecated keyFilename option is not used. A private-key service_account key is accepted only through this explicit field, an unreadable or unparsable file fails closed as configuration-invalid, and inline credential JSON is never accepted. Relative paths resolve from the process working directory. Either 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. No path is written to logs or descriptors. The adapter never runs gcloud, reads the operator's gcloud token cache, accepts a Gemini API key or creates credentials. Local ADC is distinct from gcloud auth login; configure it through Google's documented ADC setup outside this package.

Both embedContent and, where a preflight applies, countTokens 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, live model readiness or token acceptance. A real successful neutral call is required to establish endpoint acceptance for the selected project/location.

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) or text-embedding-3-large (3072 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 or openai/text-embedding-3-large through https://openrouter.ai/api/v1/embeddings with bearer authentication and float output. Each model shares the matching direct-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 resource method with ADC or an explicitly configured credential file. This route does not preflight with countTokens: Vertex rejects that method for embedding models (countTokens and computeTokens return 400 for gemini-embedding-2), so the instruction-prefixed text is sent directly. The documented input window is 8192 tokens and the provider silently truncates longer input; the resulting vector is returned rather than refused, and the provider's own usageMetadata.promptTokenCount is reported as providerReportedInputTokens while preparedInputTokens stays null. A malformed response, missing usage, wrong dimensions, invalid vector or zero vector still fails closed. Dimensions use embedContentConfig.outputDimensionality; role: user is used and the model's task_type and autoTruncate options are not. Its complete descriptor has provider: vertex and runtime: vertex-ai-v1, distinct from gemini even for identical model names and dimensions.

  • voyage: voyage-4-large, voyage-4, voyage-4-lite or voyage-code-4 through the fixed POST https://api.voyageai.com/v1/embeddings endpoint with bearer authentication. Requests carry input_type: "document" (Voyage then prepends its documented document prompt), the configured output_dimension (1024 default; 256, 512 or 2048) and truncation: false, so an over-length input fails instead of being shortened. Documented limits are 32000 tokens per input and a 1000-input list; Voyage documents aggregate caps of 1M tokens for voyage-4-lite, 320K for voyage-4 and 120K for voyage-4-large, enforces them itself, and this package does not approximate the model tokenizer. No aggregate cap is documented for voyage-code-4, so none is claimed. voyage-4-nano is an open-weight Hugging Face release, not a Voyage API model, and voyage-context-4 is a separate contextualized-chunk endpoint that returns one vector per chunk; neither is a route here.

  • cohere: embed-v5.0-pro or embed-v5.0-fast through POST https://api.cohere.com/v2/embed with bearer authentication. Requests carry the required input_type: "search_document", texts, embedding_types: ["float"], the configured output_dimension (2048 default; 256, 512, 768, 1024 or 1536) and truncate: "NONE". Documented limits are 96 texts per call and a 128K-token context per text. Cohere also documents image and mixed PDF input for these models; this package stays text-in/text-out and sends only texts.

  • jina: jina-embeddings-v5-text-small or jina-embeddings-v5-text-nano through the fixed POST https://api.jina.ai/v1/embeddings endpoint with bearer authentication. Requests carry task: "retrieval.passage", the configured dimensions from that model's documented Matryoshka set (small: 32, 64, 128, 256, 512 or 1024 with a 1024 default; nano: 32, 64, 128, 256, 512 or 768 with a 768 default), embedding_type: "float", normalized: false because this package owns L2 normalization, and truncate: false. Context is 32K tokens for small and 8K for nano; Jina publishes RPM/TPM rate limits but no per-request input-count ceiling, so none is invented. The multimodal v5 Omni family is not declared.

  • dashscope: Alibaba Model Studio qwen3.7-text-embedding through the OpenAI-compatible POST {baseUrl}/compatible-mode/v1/embeddings endpoint and bearer DASHSCOPE_API_KEY. The host is workspace-scoped, so baseUrl is operator-supplied and required; the adapter appends /compatible-mode/v1/embeddings to it. Requests carry dimensions (1024 default; 64, 128, 256, 512, 768 or 2560) and encoding_format: "float". Documented limits are 20 rows per request and 128000 tokens per row; the response is OpenAI-shaped with usage.prompt_tokens. Model Studio's parameter reference restricts 1536 and 2048 to text-embedding-v4, so neither is declared; its model overview table also omits 64 and 128, while the parameter reference lists them for every model, so those two are kept and the conflict is recorded in the evidence file. The same DASHSCOPE_API_KEY serves the DashScope image route in pi-image-gen; it is a shared credential across packages, not a shared space.

  • hetzner: BAAI/bge-m3 through the fixed POST https://inference.hetzner.com/v1/embeddings endpoint with bearer HETZNER_INFERENCE_TOKEN. Hetzner Inference is EU-hosted and OpenAI-shaped for this endpoint: the request carries model, input and encoding_format: "float" (Hetzner's compatibility page documents float and base64), and the response returns data[i].embedding, text only. The model produces 1024 dimensions with an 8192-token context; documented request boundaries are a 32 MiB body and about 1M tokens recommended per request with no fixed input count. dimensions is not sent because BGE-M3 is not Matryoshka and Hetzner rejects a custom dimension for models that do not support one. Hetzner documents no embedding usage payload, so usage fields are null when the response omits them.

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.

Voyage, Cohere, Jina, DashScope and Hetzner each add their own descriptor family, and every declared model keeps its own model value. Two vendor-documented shared-space facts are recorded in the README rather than encoded by aliasing: Voyage states that all embeddings from the four general-purpose 4-series models (voyage-4-large, voyage-4, voyage-4-lite, voyage-4-nano) are compatible and can be mixed for asymmetric retrieval, and Cohere states that embed-v5.0-pro and embed-v5.0-fast share one space. Both claims are written down here; a result still reports the provider and model that actually generated it, so no model is relabeled as another and no distinct model is merged into a single space. voyage-code-4 is not covered by Voyage's compatibility statement and is therefore its own space. The new descriptors also record the provider-native prompt selector: inputType: "document" for Voyage, inputType: "search_document" for Cohere and task: "retrieval.passage" for Jina, so a document embedding is never confused with a differently prompted one. DashScope and Hetzner record only the model, runtime and dimensions they can verify.

Limits

No application capacity caps are added. Provider request limits above are mandatory documented constraints. Sarvam, local, Cloudflare, OpenCode, Jina and Hetzner publish no aggregate request cap, so none is invented; Jina and Hetzner also publish no per-request input count ceiling, and Hetzner's documented 32 MiB body limit is a transport ceiling this package does not approximate. Voyage, Cohere and DashScope publish input count ceilings (1000, 96 and 20) that the mandatory batching enforces; their per-input context limits (32000, 128K and 128K tokens) are provider-enforced because no local tokenizer is shipped. 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 (not offered for embedding models), multimodal model constraints and task instructions, and ADC discovery order.

Other official contracts: Voyage text embeddings and embeddings API reference, Cohere Embed models and Embed API v2, Jina embeddings API, Model Studio OpenAI-compatible embeddings, and Hetzner Inference embeddings.

Not implemented here, with the documented reason: Mistral Multimodal Embed ("Clipstral") is an Apache-2.0 open-weights release deployed on-premise or through Mistral Forge, and Mistral documents no hosted embedding endpoint for it; voyage-4-nano is open-weight on Hugging Face only; voyage-context-4 returns one vector per chunk from a separate endpoint; and Jina v5 Omni and Cohere image/PDF input are multimodal. Each would widen the package's text-in/text-out contract, so they are recorded as scope limits rather than routes.

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.