Skip to main content

Python SDK for the GuruCloud Knowledge Bank API

Project description

GuruCloud KB SDK

Python SDK for the GuruCloud Knowledge Bank API — a multi-dimensional, semantic vector store. Every Knowledge Bank has a configurable dimension schema: each dimension is its own embedding space, and search is a weighted combination across the dimensions you choose.

pip install gurucloud-kb

Authenticate

from gurucloud_kb import GuruCloudClient

client = GuruCloudClient(api_key="kb_your_api_key")   # keys start with "kb_"

API keys carry scopes: read (search, list), write (add/update entries), admin (create/delete KBs, change the schema).


Mental model (read this first)

A Knowledge Bank is not a single vector index. It is a set of named dimensions, each of which is embedded separately:

Concept What it is
Dimension A named field that gets its own embedding(s). The default KB has content, useful_for, relevant_systems, relevant_tasks.
single dimension One vector per entry (e.g. content).
multi dimension A list of values, each embedded; matches ANY value (e.g. relevant_systems).
text_only dimension Stored (in entry metadata) but NOT embedded; non-semantic exact-match filtering of IDs / tags / enums. Searching it applies an exact-match filter rather than ranking.
Weighted search You query several dimensions at once; each has a weight; scores combine into one ranked result.
metadata_filters Exact (non-semantic) JSONB filtering layered on top of the semantic ranking.

You can use the 4 default dimensions, or define your own semantic dimensions when you create a KB.


Create a KB with custom semantic dimensions

Pass a dimension_schema to create_kb. Each dimension becomes its own embedding space and is automatically searchable.

kb = client.create_kb(
    name="support-kb",
    description="Resolved support tickets",
    dimension_schema={
        "version": 1,
        "combination_mode": "weighted_sum",
        "dimensions": [
            # one vector per entry, required
            {"name": "symptom", "display_name": "Symptom",
             "description": "What the user reported",
             "dimension_type": "single", "required": True, "default_weight": 1.5},

            {"name": "resolution", "display_name": "Resolution",
             "description": "How it was fixed",
             "dimension_type": "single", "required": True},

            # a list field — each value embedded, matches ANY
            {"name": "products", "display_name": "Products",
             "description": "Affected products",
             "dimension_type": "multi", "max_items": 8},

            # stored but NOT embedded — exact-match filter only (e.g. region code)
            {"name": "region", "display_name": "Region",
             "description": "Data-center region (exact match)",
             "dimension_type": "text_only"},
        ],
    },
)
print(kb.id, kb.name)

If you omit dimension_schema, you get the default 4-dimension schema (content, useful_for, relevant_systems, relevant_tasks).

Embedding model. Every dimension in a KB shares one model (text-embedding-3-small, 1536-dim). The model is not currently selectable through the SDK.

Accumulate-only KBs (never overwrite or delete)

By default, deduplication may merge a near-duplicate into an existing entry (update) or merge-and-replace conflicting entries (conflict). For an observation / "connect-the-dots" KB — where every signal should be kept and a later rollup should coexist with the entries it summarizes — set allow_updates=False:

kb = client.create_kb("signals", allow_updates=False)   # at creation
kb.set_allow_updates(False)                              # or toggle later (write scope)

With allow_updates=False the dedup LLM's update/conflict verdicts are downgraded to new, so existing entries are never overwritten or deleted — the KB only accumulates. Exact duplicates are still skipped (redundant). The flag lives on the KB's schema (round-trips through get_schema()/update_schema()); the default is True, which preserves the historical merge behavior.

REST API. The same control is available without the SDK: POST /api/v1/kb/banks accepts "allow_updates": false, and PATCH /api/v1/kb/banks/{id} with {"allow_updates": false} toggles it.

Evolve the schema later (admin scope)

kb.get_schema()                       # current KBDimensionSchema
kb.validate_schema(new_schema)        # returns warnings, applies nothing
kb.update_schema(new_schema)          # replace the whole schema
kb.add_dimension({"name": "severity_notes", "display_name": "Severity",
                  "description": "Severity context", "dimension_type": "single"})
kb.remove_dimension("severity_notes")

Add entries

Provide a value for each dimension. single dimensions take a string; multi dimensions take a list of strings.

kb.add_entry({
    "dimensions": {
        "symptom": "Login loops back to the sign-in page after SSO",
        "resolution": "Cleared the stale SAML session cookie on the gateway",
        "products": ["web app", "mobile app"],
        "region": "us-east-1",   # text_only — stored in metadata, exact-match only
    },
    "metadata": {"status": "resolved", "severity": "high"},
})

# Batch ingest (deduplicates by default)
kb.ingest([{ "dimensions": {...} }, { "dimensions": {...} }])

add_entry / ingest are synchronous — they return the stored entry (or raise on failure), so the call itself tells you the write landed. This differs from the agent-facing MCP report_learning tool, which queues the write and is confirmed separately via check_learning_status.


Search

Simple — one string against content

results = kb.search("how does authentication work?")

Multi-dimensional weighted search

Map each dimension to a query. The required per-dimension key is query_text, and weight scales that dimension's contribution. Scores are combined per combination_mode.

results = kb.search({
    "dimensions": {
        "symptom":  {"query_text": "login loops after SSO", "weight": 2.0},
        "products": {"query_text": "mobile app",            "weight": 0.5},
    },
    "combination_mode": "weighted_sum",
    "metadata_filters": {"status": "resolved"},   # exact, non-semantic
    "k": 10,
    "threshold": 0.35,
})

for r in results:
    print(r["combined_score"], r["dimensions"] if "dimensions" in r else r)

Per-dimension you can also override aggregation, top_k, and min_threshold:

"products": {"query_text": "mobile", "weight": 1.0,
             "aggregation": "max", "min_threshold": 0.2}

Exact-match filtering with text_only dimensions

A text_only dimension is matched exactly, not ranked. Pass it alongside at least one semantic (single/multi) dimension; its query_text folds into an exact-match filter (equivalent to a metadata_filters entry) and never contributes to the score:

results = kb.search({
    "dimensions": {
        "symptom": {"query_text": "login loops after SSO"},
        "region":  {"query_text": "us-east-1"},   # text_only → exact match
    },
})

A search containing only text_only dimensions is rejected (there is nothing to rank) — add a semantic (single/multi) dimension. The same is true of metadata_filters (below): it is an exact post-filter layered on the ranking, so every search still needs at least one semantic dimension. A text_only dimension defined with searchable=False is stored but cannot be used as a search filter.

Exact filtering with metadata_filters

metadata_filters is an exact (non-semantic) JSONB-containment filter applied on top of the semantic ranking — only entries whose metadata contains all the given key/values survive. Pair it with at least one semantic dimension:

results = kb.search({
    "dimensions": {"observation": {"query_text": "late delivery"}},
    "metadata_filters": {"order_id": "SO-1234", "type": "quality_issue"},
})

It narrows the ranked results; it does not rank on its own. To gather every entry for a key regardless of relevance, widen k and pass a broad semantic query alongside the filter.

Filter by time

Restrict results to a time window with a hard filter on entry timestamps (UTC) — it removes out-of-window entries without affecting the ranking. Bounds accept an ISO-8601 string or a datetime. For a string query they're keyword args:

from datetime import datetime, timedelta, timezone

# Only knowledge created in the last 30 days
recent = kb.search(
    "deployment pipeline",
    created_after=datetime.now(timezone.utc) - timedelta(days=30),
)

For a dict query, set the same keys inline:

results = kb.search({
    "dimensions": {"content": {"query_text": "deployment pipeline"}},
    "created_after": "2026-05-01T00:00:00Z",
    "created_before": "2026-06-01",          # bare date == 00:00:00Z
    "k": 10,
})

Available bounds: created_after, created_before, updated_after, updated_before. Each result includes created_at / updated_at so you can verify the window and sort by recency client-side.

Search request reference

Field Type Notes
dimensions {name: {query_text, weight, aggregation?, top_k?, min_threshold?}} At least one searchable dimension required. A text_only dimension here folds into an exact-match filter (and needs a single/multi dimension alongside it).
combination_mode weighted_sum | weighted_product | max | min | custom How dimension scores combine.
custom_formula str Required when combination_mode="custom"; SQL over <dim>_score.
metadata_filters dict Exact JSONB containment, e.g. {"status": "resolved"}.
category_filters [{tag, max_results, min_score}] Bucket results by metadata tag.
created_after / created_before str | datetime Hard filter on entry creation time (UTC, ISO-8601).
updated_after / updated_before str | datetime Hard filter on entry last-modified time (UTC, ISO-8601).
k, threshold int, float Result count / minimum combined score.

aggregation (for multi dimensions): max, avg, min, top_k_avg, sum, count.

The SDK also accepts the older spellings query (per dimension) and filters (top level) and rewrites them to query_text / metadata_filters for you — but prefer the canonical names above.


Use the KB as an MCP server (agent injection)

mcp_def = kb.get_mcp_server_definition()
agent_config = {
    "mcpServers": {
        mcp_def["server_name"]: {
            "type": mcp_def["type"],
            "url": mcp_def["url"],
            "headers": {"Authorization": f"Bearer {api_key}"},
        }
    }
}
# Or mint a dedicated never-expiring token (admin scope):
pat = kb.generate_pat(token_name="My Agent")

The MCP tools (query_knowledge_bank, report_learning) are generated from your schema — every searchable dimension becomes a <dimension>_query parameter automatically.


Async

The async client mirrors the sync API exactly — every method is awaitable.

from gurucloud_kb import AsyncGuruCloudClient

async with AsyncGuruCloudClient(api_key="kb_...") as client:
    kb = await client.get_kb("your-kb-uuid")
    results = await kb.search({
        "dimensions": {"content": {"query_text": "JWT", "weight": 1.0}},
        "k": 5,
    })

Typed contracts

All request/response shapes are exported as TypedDicts / Literals for editor + agent autocompletion:

from gurucloud_kb import (
    DimensionConfig, DimensionSchema, DimensionType,
    DimensionQuery, SearchRequest, CombinationMode, Aggregation,
    CategoryFilter, EntryInput, EntryResult, KBInfo,
)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

gurucloud_kb-0.1.2.tar.gz (22.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

gurucloud_kb-0.1.2-py3-none-any.whl (28.6 kB view details)

Uploaded Python 3

File details

Details for the file gurucloud_kb-0.1.2.tar.gz.

File metadata

  • Download URL: gurucloud_kb-0.1.2.tar.gz
  • Upload date:
  • Size: 22.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.12

File hashes

Hashes for gurucloud_kb-0.1.2.tar.gz
Algorithm Hash digest
SHA256 be9759fdc69c157cf16e39f1a2e5fa8955d9e48db55105605d17aa1ee4f8feef
MD5 0150e8bb797ac2689dd8cc5fba83fc74
BLAKE2b-256 6b1cacbaa6a28eefbbfb5f8f2f484ac9326dec6b111f7e0c008e6a3aa5db3c2f

See more details on using hashes here.

File details

Details for the file gurucloud_kb-0.1.2-py3-none-any.whl.

File metadata

  • Download URL: gurucloud_kb-0.1.2-py3-none-any.whl
  • Upload date:
  • Size: 28.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.12

File hashes

Hashes for gurucloud_kb-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 836aa1fdc72ec948af9afffa532ceaa9bccaf4d4541e54640f81d9cfe68a7eb4
MD5 3fc84e535d51d90c612ae21fca124b48
BLAKE2b-256 4959569d17f7c98c66c4d27e45acb6a81f4c6ae1e0729fb9c4e2a8009c46eeb3

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page