Skip to main content

Python SDK for the Knowledge2 retrieval platform

Project description

Knowledge2 Python SDK

PyPI version Python 3.11+ License: MIT

Official Python client for the Knowledge2 retrieval platform. The supported customer journey is:

create corpus -> ingest documents -> build indexes -> search -> optimize retrieval

Installation

From PyPI:

pip install knowledge2
pip install "knowledge2[config]"
pip install "knowledge2[pydantic]"
pip install "knowledge2[yaml]"

From source:

pip install -e .
pip install -e ".[config]"
pip install -e ".[pydantic]"
pip install -e ".[yaml]"

Surface Categories

Category Surface
Core retrieval workflow orgs, auth, projects, corpora, documents, indexes, search, jobs, metadata, onboarding, audit, usage, console, generation models
Enterprise capabilities agents, feeds, pipelines, A2A

The main docs and examples below focus on the core retrieval workflow.

Quick Start

from sdk import Knowledge2

client = Knowledge2(api_key="k2_...")

project = client.create_project("My Project")
corpus = client.create_corpus(project["id"], "My Corpus")

client.upload_documents_batch(
    corpus["id"],
    [
        {
            "source_uri": "doc://overview",
            "raw_text": "Knowledge2 builds dense and sparse indexes for hybrid retrieval.",
            "metadata": {"topic": "overview"},
        },
        {
            "source_uri": "doc://search",
            "raw_text": "Hybrid retrieval combines semantic similarity with exact keyword matching.",
            "metadata": {"topic": "search"},
        },
    ],
    wait=True,
    auto_index=False,
)
client.sync_indexes(corpus["id"], wait=True)

results = client.search(
    corpus["id"],
    "what is hybrid retrieval",
    top_k=3,
    return_config={"include_text": True, "include_scores": True},
)

for hit in results["results"]:
    print(hit["score"], hit.get("text", "")[:80])

Improve Retrieval Quality

profile = client.get_query_profile(corpus["id"])
print(profile["example_queries"])

job = client.optimize_indexes(
    corpus["id"],
    example_queries=[
        "how does hybrid retrieval work",
        "what is bm25 tuning",
        "how does rrf combine dense and sparse search",
    ],
    query_count=25,
    top_k=10,
    metric="ndcg",
    wait=False,
)
print(job["job_id"], job["job_type"])

Examples

  • sdk/examples/retrieval_quickstart.py: minimal happy path from empty corpus to working hybrid search
  • sdk/examples/e2e_lifecycle.py: full retrieval-quality workflow with query profile inspection and indexes:optimize

Run either example with:

export K2_BASE_URL=https://api.knowledge2.ai
export K2_API_KEY=<api-key>
python sdk/examples/retrieval_quickstart.py
python sdk/examples/e2e_lifecycle.py

Authentication

Method Header Typical use
API key X-API-Key primary programmatic access
Bearer token Authorization: Bearer <token> console / Auth0 session
Admin token X-Admin-Token bootstrap and admin operations
client = Knowledge2(api_key="k2_...")
client = Knowledge2.from_env()
client = Knowledge2(bearer_token="...")

Configuration

Important constructor knobs:

  • api_host: defaults to https://api.knowledge2.ai
  • api_key: API key for programmatic access
  • org_id: auto-detected from GET /v1/auth/whoami when omitted
  • timeout: float or ClientTimeouts
  • limits: connection-pool settings via ClientLimits
  • max_retries: transient retry budget
  • validate_responses: enable Pydantic response validation
  • http_client: bring your own httpx.Client
from sdk import ClientTimeouts, Knowledge2

client = Knowledge2(
    api_key="k2_...",
    timeout=ClientTimeouts(connect=5, read=120, write=30, pool=10),
)

Namespaces

The flat client API is canonical. Namespace helpers group the same methods without changing behavior:

  • client.documents.*
  • client.corpora.*
  • client.search_ns.*
  • client.jobs.*
  • client.auth.*

Framework Integrations

The SDK ships LangChain and LlamaIndex integration modules in-package. Install the framework dependency separately, then import the adapter:

from sdk.integrations.langchain import K2LangChainRetriever
from sdk.integrations.llamaindex import K2LlamaIndexRetriever

Enterprise Capabilities

Agents, feeds, pipelines, and A2A are available for enterprise deployments. Keep the primary examples focused on the core retrieval flow.

Error Handling

All SDK exceptions inherit from Knowledge2Error.

from sdk.errors import Knowledge2Error, NotFoundError, RateLimitError

try:
    client.get_corpus("missing")
except NotFoundError:
    ...
except RateLimitError as exc:
    print(exc.retry_after)
except Knowledge2Error as exc:
    print(exc)

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

knowledge2-0.5.0.tar.gz (113.9 kB view details)

Uploaded Source

Built Distribution

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

knowledge2-0.5.0-py3-none-any.whl (165.4 kB view details)

Uploaded Python 3

File details

Details for the file knowledge2-0.5.0.tar.gz.

File metadata

  • Download URL: knowledge2-0.5.0.tar.gz
  • Upload date:
  • Size: 113.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.0.1 CPython/3.12.8

File hashes

Hashes for knowledge2-0.5.0.tar.gz
Algorithm Hash digest
SHA256 ba0a804ee7109d756b5795f0215d3c13ced637f82063300f1dd29d9cb3c32559
MD5 f75cce1f0cf3744ff6f4de6cebbc9d1a
BLAKE2b-256 456a7489ebe405fb75595959c57fbc875aa01a065c94042a358a8950156ba6a3

See more details on using hashes here.

Provenance

The following attestation bundles were made for knowledge2-0.5.0.tar.gz:

Publisher: pypi-release.yml on knowledge2-ai/knowledge2-python-sdk

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file knowledge2-0.5.0-py3-none-any.whl.

File metadata

  • Download URL: knowledge2-0.5.0-py3-none-any.whl
  • Upload date:
  • Size: 165.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.0.1 CPython/3.12.8

File hashes

Hashes for knowledge2-0.5.0-py3-none-any.whl
Algorithm Hash digest
SHA256 130f69e9925386d24e341490c7c54ed3ac32fda4f83d398624eb4b8ff260a3a3
MD5 6ff546a679954cc6096fd55eb50ac010
BLAKE2b-256 a62c61506dd47e9244b76206352912e0807c2df888f30266edc2b4a0553212aa

See more details on using hashes here.

Provenance

The following attestation bundles were made for knowledge2-0.5.0-py3-none-any.whl:

Publisher: pypi-release.yml on knowledge2-ai/knowledge2-python-sdk

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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