Metadata-Version: 2.4
Name: knowledge2
Version: 0.5.0
Summary: Python SDK for the Knowledge2 retrieval platform
Author-email: Knowledge2 <contact@knowledge2.ai>
License: MIT
Project-URL: Homepage, https://knowledge2.ai
Project-URL: Documentation, https://knowledge2.ai/docs
Project-URL: Repository, https://github.com/knowledge2-ai/knowledge2-python-sdk
Project-URL: Changelog, https://github.com/knowledge2-ai/knowledge2-python-sdk/blob/main/CHANGELOG.md
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
Requires-Dist: httpx>=0.27
Provides-Extra: config
Requires-Dist: pydantic-settings>=2.0; extra == "config"
Provides-Extra: pydantic
Requires-Dist: pydantic>=2.0; extra == "pydantic"
Provides-Extra: yaml
Requires-Dist: pyyaml>=6.0; extra == "yaml"

# Knowledge2 Python SDK

[![PyPI version](https://img.shields.io/pypi/v/knowledge2.svg)](https://pypi.org/project/knowledge2/)
[![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/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:

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

From source:

```bash
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

```python
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

```python
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:

```bash
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 |

```python
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`

```python
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:

```python
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`.

```python
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)
```
