Skip to main content

Knowledge Stack API

Project description

ksapi — Python SDK Quickstart

The official Python client for the Knowledge Stack API. One client authenticates with an API key, ingests documents, asks the agent, and streams chat.

The full per-endpoint reference is generated alongside this package under ./docs/.

Install

pip install ksapi

Authenticate

Mint an API key (in the app under API Keys, or POST /v1/api-keys) and pass it as access_token. The client sends it as Authorization: Bearer <key> on every request:

import ksapi
from ksapi.api.documents_api import DocumentsApi

config = ksapi.Configuration(
    host="https://api.your-host.example",
    access_token="sk-user-...",  # your API key
)
client = ksapi.ApiClient(config)

# Smoke test — list documents you can access
print(DocumentsApi(client).list_documents(limit=10).total, "documents")

Browser/session callers authenticate with the ks_uat cookie instead: ksapi.Configuration(host=..., api_key={"cookieAuth": "<ks_uat value>"}).

Ingest a document and wait until it's searchable

Ingestion is asynchronous. Upload, then poll until the active version's pipeline status is completed — at that point the chunks are embedded and searchable:

import time
from ksapi.api.documents_api import DocumentsApi

docs = DocumentsApi(client)

with open("contract.pdf", "rb") as fh:
    created = docs.ingest_document(
        file=fh.read(),
        path_part_id="<parent-folder-path-part-id>",  # a FOLDER
        name="contract.pdf",
    )

while True:
    version = docs.get_document(created.document_id).active_version
    meta = version.system_metadata
    status = meta.pipeline_state.status if meta and meta.pipeline_state else None
    if status in ("completed", "failed"):
        break
    time.sleep(2)
print("ingestion:", status)

Ask the agent

from ksapi.api.agent_api import AgentApi
from ksapi.models.ask_request import AskRequest

answer = AgentApi(client).agent_ask(AskRequest(prompt="What are the renewal terms?"))
print(answer.text)

Citation-grounded, multi-turn chat runs through threads; each assistant message exposes content.citations. Stream those tokens live below.

Stream chat responses (SSE)

The agent streams over Server-Sent Events at GET /v1/threads/{thread_id}/stream. The generated stream_thread() method buffers the whole response, so consume the stream directly — the body is data: <json> lines terminated by data: [DONE]:

import httpx

def stream_thread(host: str, api_key: str, thread_id: str):
    headers = {"Authorization": f"Bearer {api_key}"}
    with httpx.Client(base_url=host, headers=headers, timeout=60) as http:
        with http.stream("GET", f"/v1/threads/{thread_id}/stream") as response:
            for line in response.iter_lines():
                if not line.startswith("data:"):
                    continue  # skip event:/id:/keepalive lines
                payload = line[len("data:"):].strip()
                if payload == "[DONE]":
                    return
                yield payload  # JSON event — parse with json.loads()

for event in stream_thread(config.host, "sk-user-...", "<thread-id>"):
    print(event)

Errors

Every error response keeps detail and adds a machine-readable code plus the request_id (also returned as the x-request-id header) — quote it to support:

from ksapi.exceptions import NotFoundException

try:
    DocumentsApi(client).get_document("00000000-0000-0000-0000-000000000000")
except NotFoundException as exc:
    body = exc.body  # {"detail": ..., "code": "not_found", "request_id": "..."}
    print(exc.status, body)

The client raises a typed exception per status: BadRequestException (400), UnauthorizedException (401), ForbiddenException (403), NotFoundException (404), ConflictException (409), UnprocessableEntityException (422), and ServiceException (5xx).

Project details


Release history Release notifications | RSS feed

Download files

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

Source Distribution

ksapi-1.115.1.tar.gz (281.0 kB view details)

Uploaded Source

Built Distribution

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

ksapi-1.115.1-py3-none-any.whl (588.0 kB view details)

Uploaded Python 3

File details

Details for the file ksapi-1.115.1.tar.gz.

File metadata

  • Download URL: ksapi-1.115.1.tar.gz
  • Upload date:
  • Size: 281.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.2.0 CPython/3.14.6

File hashes

Hashes for ksapi-1.115.1.tar.gz
Algorithm Hash digest
SHA256 04d4f871a4ab53e68bd87d0a9d210c3109485505036cae278b22392977803e7c
MD5 ba26db78c638514da4a406473f2aa9eb
BLAKE2b-256 efc876dad98221bf477ba151cbef339be30ce20dc042614742f8ab7b387c64c1

See more details on using hashes here.

File details

Details for the file ksapi-1.115.1-py3-none-any.whl.

File metadata

  • Download URL: ksapi-1.115.1-py3-none-any.whl
  • Upload date:
  • Size: 588.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.2.0 CPython/3.14.6

File hashes

Hashes for ksapi-1.115.1-py3-none-any.whl
Algorithm Hash digest
SHA256 e6def0098405cb18a0b5c1e5511a2d28f7a94786a8b5d083ccc50c6ff431e92d
MD5 e9b3523ee15ed7496f7a9f987be507fa
BLAKE2b-256 5f49c9610a6caadf5c242e5fba7d39c61573239ea8f39e3b06d3bb99d6dd3eaa

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