Skip to main content

katonic-sdk

The Python SDK for the Katonic 7.0 platform: the public API client (KatonicClient), agent authoring, blueprint scaffolding, multi-agent composition, and local evaluation.

pip install "katonic-sdk>=7"
# or pin it to the version of the platform you deploy (X.Y.Z):
pip install "katonic-sdk==X.Y.Z"

Sovereign / air-gapped installs: download the wheel from your deployment's Developer Hub instead.

Quickstart

export KATONIC_BASE_URL=https://<your-studio-host>   # the host; the client adds /public/v1
export KATONIC_API_KEY=kapi_...                      # Studio > Public API > API keys
import asyncio
from katonic import KatonicClient

async def main():
    async with KatonicClient() as k:  # reads KATONIC_API_KEY / KATONIC_BASE_URL
        agent = (await k.list_agents())[0]  # published agents; chat takes the agent's id
        resp = await k.chat(agent.id, "What is the PTO policy?")
        print(resp.message.content)

asyncio.run(main())

The katonic command ships with the package (katonic login, katonic agents list, katonic search … — see katonic --help; python -m katonic … where the script is not on PATH).

In a Katonic workspace, start with examples/workspace/: one runnable example per area of the SDK, a notebook that walks through them, and the set-up a workspace needs (a Developer Hub key and the Studio origin as KATONIC_BASE_URL). In a notebook cell, await main() replaces asyncio.run(main()): the kernel's event loop is already running.

What the client covers

KatonicClient wraps the platform's public API, one async method per call:

Area Methods
Agents list_agents, get_agent, create_agent, update_agent, validate_agent, publish_agent
Chat and sessions chat, chat_stream, create_session, list_sessions, get_history, delete_session, submit_feedback
Models list_models, get_model, completions (OpenAI-compatible)
Knowledge list_sources, create_source, upload_documents, ingest, sync_source, search
Knowledge graph load_graph, get_graph_schema, query_graph
Graph schemas list_ontologies, create_ontology, get_ontology, update_ontology, publish_ontology, new_ontology_version, delete_ontology, validate_ontology, discover_ontology, list_source_ontologies, attach_ontology, detach_ontology, set_ontology_mode, baseline_ontology_violations
Evaluation list_evaluators, list_datasets, upload_dataset, run_evaluation, get_evaluation, poll_evaluation, compare_evaluations
Prompt optimization optimize_prompt, get_optimization, poll_optimization, list_optimizations, apply_optimization, pause_optimization, resume_optimization, cancel_optimization
Data flywheel ingest_traces, get_quality_trend, build_flywheel_dataset
Skills list_skills, get_skill, import_skills
Tools list_tools, execute_tool
Guardrails evaluate_guardrails
Usage and cost get_usage, get_analytics_usage, get_cost_breakdown
Reporting LLM calls made outside the AI Gateway usage.log, usage.track, flush, aflush (see below)
Question, answer and end user of any LLM call usage.log_request (see below)

create_agent() builds a publish-ready agent in one call from what the list calls return, checks every argument before sending anything, and creates nothing if a reference is not in the key's tenant (KatonicAPIError.errors names each):

tool = next(t for t in await k.list_tools() if t.available)
source = (await k.list_sources())[0]
agent = await k.create_agent(
    "Leave helper", system_prompt="Answer leave-policy questions.",
    temperature=0.2, max_tokens=1024, tools=[tool],
    knowledge=[{"id": source, "top_k": 5}], skills=["cite-sources"],
    surfaces=["workroom", "api"],
)
if not await k.validate_agent(agent.id):  # what would stop a publish; changes nothing
    await k.publish_agent(agent.id)

Each call needs the matching scope on the key. A few are refused by the platform whatever the key holds, while the public API does not yet allow them: creating knowledge sources, uploading documents, and creating, changing, validating or deleting graph schemas.

The rest of the package authors agents offline, with no platform:

  • katonic.gateway, katonic.knowledge, katonic.guardrails and katonic.tools build an agent's bindings;
  • katonic.compose wires sub-agents into NAT workflows;
  • katonic.scaffold writes blueprint packages;
  • katonic.evaluate writes local evaluation configs;
  • katonic.connectors is the base class for custom knowledge connectors.

Knowledge bases from a script

k.knowledge creates knowledge bases and finds them by id or name. A knowledge base adds files so that running the same script again sends only what changed:

async with KatonicClient() as k:
    kb = await k.knowledge.get_or_create("hr-policies", visibility="teams", teams=["HR", "All-Users"])
    results = await kb.add_files(
        [{"file": path, "metadata": {"department": "HR", "regions": ["EMEA"]}}
         for path in ["policies/leave.pdf", "policies/travel.pdf"]],
        wait=True,
    )
    for r in results:
        print(r.external_id, r.outcome, r.code or "")
    await kb.update_metadata("policies/leave.pdf", set={"regions": ["EMEA", "APAC"]})
  • teams= takes team names, as Users & Teams in Studio shows them, matched exactly against a team's name and then its display name. A name the organisation does not have raises ValidationError (knowledge.unknown_team, naming each one) and a name two teams answer to raises knowledge.ambiguous_team, both before anything is created. teams= applies when the knowledge base is created; get_or_create leaves an existing one's sharing as it is.
  • k.teams.list() returns the organisation's active teams as Team(id, name, display_name), and k.teams.get_by_name(name) finds one by its name or the name the web UI shows (NotFoundError when none matches; a ValueError naming both teams when two do). Both need the documents scope.
  • Each file is kept under an external id (its path as given, by default) and compared by SHA-256. It comes back created, updated (replaced in place), unchanged (nothing was sent) or failed with a code.
  • Every file and its metadata are checked against the organisation's limits (await k.knowledge.limits()) before anything is sent: PayloadTooLargeError (limit), UnsupportedFileTypeError (content_type), ValidationError (rule, field) and MetadataNotEditableError (setting).
  • Metadata follows the organisation's metadata fields: required fields must be given, a multi-select takes a list, and the keys the platform records (uploaded_by, file_name and the like) cannot be set. A changed file's metadata is replaced by what is sent with it; an unchanged file's is left as it is, so change it with update_metadata.
  • Files are hashed in chunks and read again only when sent, so memory holds one upload's worth however many files there are. If a later upload in the call is refused, its files come back failed with the server's code and the rest still go; the files already sent stay added.
  • update_metadata(unset=[...]) removes an edit made with update_metadata, not metadata a file was added with. An edit outranks the metadata a file is added with, also after the file changes.
  • Keys named like credentials (api_key, token_type, key) are refused: metadata is not secret.
  • The default external id is the path as given. Use relative paths (or pass external_id) so the same file has the same id on every machine.
  • get_document, list_documents and wait read documents by external id.
  • The key needs the documents scope, and its owner must have created the knowledge base or manage it.

Content a script already read

When the script reads its files itself (its own OCR or parser), it adds what it read instead of letting the platform read the file, as the LangChain Documents (or LlamaIndex nodes) a loader gives it. Each page's web_url is the link its citation opens. kb.link_file(path) copies a file into Katonic and returns a Katonic link to it, so a citation opens the file itself, at the cited page. Any other link (SharePoint, a wiki, a ticket) is opened as it is.

You have Call The platform
The file, and the platform reads it well add_files (above) reads, cuts and embeds it
Documents you read from a file yourself link_file(path), then add_documents(docs) keeps the file for citations; cuts each page and embeds it
Documents with a link of their own, or none add_documents(docs) cuts each page and embeds it
link = await kb.link_file("scans/orders.pdf")        # copies the file into Katonic
pages = PDFMinerLoader("scans/orders.pdf", concatenate_pages=False).load()   # one Document per page
for number, page in enumerate(pages, start=1):
    page.metadata["external_id"] = "orders"          # required: which document it belongs to
    page.metadata["web_url"] = link                  # optional: the link a citation opens
    page.metadata["page_number"] = number            # optional: citations open this page
    page.metadata["title"] = "Orders"                # optional: else the source file name
results = await kb.add_documents(pages, wait=True)
for r in results:
    print(r.external_id, r.outcome, r.code or "")
  • A v6 script's index_data(prepare_data(docs)) and its index_data(my_chunks) are both add_documents(...): there is no cutting step in the script.

  • Objects sharing external_id (a LlamaIndex node's ref_doc_id) are one document, its pages in order: the same id add_files and every result call external_id. document_id, the v6 name for the id, is accepted as an alias, so a v6 script's ids carry over; an object that sets both to different values is refused. title is the title, else the source file name. source, web_url and page_number are not kept as labels. A label every page shares is the document's; the rest stay with their page.

  • link_file(path) stores the file as it is: it is never read or indexed. It returns <Studio address>/public/v1/sources/<knowledge base id>/files/<file id>. The same file gives the same link, and a file the knowledge base already holds is not sent again. The file goes straight to the platform's storage where that can be reached (inside the platform today), else in the request when it is at most 50 MiB. A larger file where storage cannot be reached raises KatonicAPIError (knowledge.storage_unreachable).

  • link_file checks the file before sending anything and raises ValidationError with a code: missing or a folder (knowledge.file_not_found), over the organisation's per-file limit or 100 MiB (limits()["content"]["max_original_bytes"]; knowledge.file_too_large), a type the organisation does not accept (knowledge.unsupported_file_type), or empty (knowledge.empty_file).

  • web_url is always an http(s) link. A file path is not a link: store the file with link_file and use its link. A document whose web_url is not an http(s) link comes back failed with knowledge.invalid_source_url. A document whose pages name different links comes back failed with knowledge.web_url_conflict. Either is not sent; the call's other documents go in. A Katonic link to a file of another knowledge base fails its document with knowledge.file_not_found.

  • No web_url means no link. A document sent again without one keeps the link or file it has.

  • source is never read as a file. It is only the title when there is no title.

  • A loader fills in labels itself, so add_documents leaves out what no label can hold instead of refusing the loader's output, with one warning naming what was left out:

    • keys the platform records itself (LlamaIndex's file_name, file_type, file_size; the list is limits()["metadata"]["reserved_keys"]);
    • values that are not single values (Unstructured's languages: ["eng"]), except a list for one of the organisation's multi-select fields;
    • every label, where the organisation has document metadata turned off (limits()["metadata"]["enabled"] is False).

    add_files(metadata=...) still refuses all of these, since that metadata is asked for by name.

  • A page is a citation's page through page_number, counted from 1. Give a document's pages one web_url: v6's per-page #page=N anchors are different links, so put the page in page_number instead. A loader's own page key (counted from 0) stays a label.

  • The platform cuts each page on its own with the knowledge base's chunk settings and never joins two pages, so a page smaller than a chunk stays one chunk. Chunks a script cut itself can be sent the same way: small ones are kept whole, and a longer one is cut.

  • Running the script again is safe, as with files: the same content and fields are unchanged and nothing is processed; a changed title, link or metadata alone is updated without processing the text again; changed content replaces the document in place. Results are DocumentResult (FileResult).

  • Checked before anything is sent, against limits()["content"], with the server's codes on ValidationError.code:

    Rule Default Code
    Text in one document, all pages together 10 MiB (max_text_bytes); split a larger one into several documents knowledge.text_too_large
    Pages in one document 2,000 (max_parts_per_document) knowledge.too_many_parts
    A page with no text, or text that is not valid UTF-8 knowledge.empty_text, knowledge.invalid_text
    Embedding vectors (embedding, vector, ...) in the metadata not accepted: the platform embeds knowledge.vectors_not_accepted
    Metadata as for add_files; a page's own labels follow the size bounds and reserved keys knowledge.invalid_metadata
  • More documents than one request carries (100 by default) are sent in batches; a later batch that fails comes back failed and the earlier ones stay added.

  • A page's own metadata is stored with it; search filters on the document's metadata.

Syncing a folder

sync_directory keeps a knowledge base in step with a folder. Run it from a scheduled Job and each run sends only what changed since the last:

async with KatonicClient() as k:
    hr = await k.knowledge.get_or_create("hr-policies")
    report = await hr.sync_directory(
        "/data/storage/hr",
        metadata_fn=lambda rel: {"department": "HR"},
    )
    print(report.new, report.changed, report.unchanged, report.missing, report.failed)
  • Every file is kept under its path relative to the folder, and the files sent are processed in one run, which the knowledge base's Runs tab shows with the sync's counts and the Job that ran it. The report is also printed as one JSON line for the Job's run logs.
  • Dot-files and the outputs/ and reports/ folders at the top of a Job's mount are skipped; include and exclude take glob patterns (** spans folders).
  • A file over the limit or with bad metadata is failed on its own; a type the organisation does not accept is skipped; a document whose file is gone is missing and kept.
  • prune=True deletes the documents whose files are gone instead, and reports them deleted; the key then also needs knowledge:delete. A file counts as gone only when nothing is at its path any more: one that include, exclude, a dot-name or the mount's outputs/ and reports/ leave out is still on disk and is never deleted, and neither is a document added in Studio or with add_documents (its title is not the file's name). Prune needs external_id_from="relative_path", is refused when the folder holds no file (an unmounted folder never empties the knowledge base), and deletes nothing when part of the folder could not be read.
  • If any file failed, the async with block raises SyncFailedError as it closes, after every sync in it has run, so the Job ends Failed. Pass fail_on_error=False to only report.
  • dry_run=True writes nothing and lists every problem in report.problems.

Reporting LLM calls made outside the AI Gateway

An app that calls a provider directly (OpenAI, Azure OpenAI, a vLLM server, ...) can report each call, so that the platform prices it and shows it in Analytics, under Cost and LLM Usage, beside AI Gateway traffic. The key needs the usage:write scope ("Report usage"), which a Builder can grant.

from katonic import KatonicClient

k = KatonicClient()  # no `async with` needed for reporting

# the SDK measures the call: latency, and TTFT from first_token()
with k.usage.track("openai", "gpt-4o-mini", app_name="claims-bot") as call:
    reply = openai_client.chat.completions.create(model="gpt-4o-mini", messages=messages)
    call.set_usage(reply.usage.prompt_tokens, reply.usage.completion_tokens)

# or report a call your app measured itself
k.usage.log("openai", "gpt-4o-mini", 812, 64, 930, "success", "claims-bot", ttft_ms=210)

k.flush()  # in asyncio code: await k.aflush()
  • It never slows down or breaks the call. log() and track() check the fields and queue the event; a background thread sends events in batches. When the platform is slow or unreachable, events wait in a bounded queue (5,000 by default) and are sent again later; when the queue is full, new events are dropped, counted in k.usage.stats(), and one warning is logged. Nothing raises because of the network or the platform.
  • Mistakes in the calling code do raise, at the call site: katonic.usage.ValidationError (a ValueError) for a negative token count, an empty model, ttft_ms above latency_ms, a status other than "success" or "error", or an app name the platform does not accept.
  • An exception inside track() is reported as status="error" with the exception's class name, and reaches your code unchanged.
  • log() and track() send only the numbers: no prompt, no response, no provider key. The kapi_ key goes only in the Authorization header. The platform prices the calls with its own price list; the SDK carries none. To report what was asked and answered, use log_request() (below).
  • Exit: the queue is flushed when the process exits, for up to 5 seconds. Leaving async with KatonicClient() flushes too, when the block reported calls, and waits for it (up to the same 5 seconds when the platform is unreachable); in a server, keep one client for the app's life rather than one per request. A serverless function or anything that may be frozen or killed should call k.flush() (or await k.aflush()) before it returns.
  • Settings: build a katonic.usage.UsageLogger(api_key=..., base_url=..., batch_size=..., flush_interval=..., max_queue=..., exit_timeout=...) to change how events are batched and sent; every logger for one key and address shares one queue per process. KATONIC_USAGE_DISABLED=1 turns reporting off.

Question, answer and end user: log_request()

Call k.usage.log_request() once after every LLM call, Katonic's or any other, to report what was asked, what was answered and for whom. Admins see them in Control Room → Analytics → LLM Usage → Requests, with an App and an End user column. The text you send is stored: it is kept for 30 days and only admins holding audit:unmask can read it, so send only what your org may keep.

# a call through the Katonic Developer Hub, streamed
chunks = []
for chunk in hub.chat.completions.create(model=model, messages=messages, stream=True):
    chunks.append(chunk)
full_answer = "".join(c.choices[0].delta.content or "" for c in chunks if c.choices)
k.usage.log_request(
    query, answer=full_answer, response=chunks[-1],
    end_user="user@example.com", app_name="claims-bot",
    latency_ms=elapsed_ms, status="success",
)

# a call to any other LLM, with or without its reply object
k.usage.log_request(query, answer=text, model="my-model",
                    end_user=user, app_name="claims-bot", provider="vllm")
  • Pass the reply as response= (an openai object, its dict, or any one chunk of a stream): the answer, the model and the token counts are read from it. For a streamed call, also pass the joined text as answer=.
  • A Developer Hub call is counted once. Its reply, and every chunk of its stream, carries katonic_event_id: the AI Gateway's own row for the call. log_request sends only the text, which the platform attaches to that row, and no usage, so the call is never counted or charged twice. Any other reply is reported as a new call, with its usage.
  • Token counts come from the arguments, else from the reply, else they are estimated from the text (about four characters a token) and marked tokens_estimated. provider defaults to "other".
  • Embeddings: pass the input as question and the embeddings reply as response; no answer is stored.
  • Size and characters: question and answer are each cut to 32 KB of UTF-8 and marked as cut. end_user takes 1-256 characters in any language, an email included, and no control characters (None when your app has no user to name); anything else raises ValidationError and nothing is queued. Text is sent as UTF-8.
  • Memory: the queue holds at most 16 MiB (max_queue_bytes) beside its 5,000 events. An event that would go over it is sent without its text, its usage kept, and counted in k.usage.stats()["text_dropped"]. Text the platform could not store is counted in stats()["text_unstored"] (the usage was kept).
  • Failed calls: with status="error" and no token counts, 0 tokens are sent, so a failed call is not charged for an estimate. Pass the exception as response= from your except block: status is then "error" unless you give one, and a Developer Hub refusal is not counted a second time.
  • Not with instrument() for the same call: for another provider, each reports the call's usage, so using both would count it twice.

Moving from log_request_to_platform: input_query → question, response (the text) → answer, user_name → end_user, model_name → model, product_type / product_name / project_name → one app_name, latency in seconds → latency_ms, and status="failed" → status="error".

OpenAI and Azure OpenAI clients

katonic.instrument() reports every chat completion an openai client makes, with no change to the calls themselves. Install the extra: pip install 'katonic-sdk[openai]'.

import katonic
from openai import AsyncOpenAI

client = katonic.instrument(AsyncOpenAI(), app_name="claims-bot")
reply = await client.chat.completions.create(model="gpt-4o-mini", messages=messages)
  • Works with OpenAI, AsyncOpenAI, AzureOpenAI and AsyncAzureOpenAI (openai 1.55.3 or later), for chat.completions.create() and chat.completions.parse(). A client made from it with with_options() or copy() reports too.
  • Each call is reported with the model the provider served (on Azure, the model, not the deployment name), the tokens from the response's usage, and the latency. When a server answers without usage, the tokens are estimated from the length of the text (about four characters a token) and the event is marked tokens_estimated.
  • The provider comes from the client: azure_openai for an Azure client, else the host of its base_url (openai, groq, together, mistral, openrouter, perplexity, nvidia, google), and custom for any other host. Name it yourself with provider=, e.g. provider="vllm" for a vLLM server.
  • A call that raises is reported with status="error" and the exception's class name, and the exception reaches your code unchanged. A response the SDK cannot read is not reported: it is counted in stats()["invalid"] and logged once, and your code gets the response as usual.
  • Streamed calls (stream=True, and the .stream() helper) are reported when the stream ends: read to the end, closed, broken by an error, or dropped before its end. Your code gets the same chunks, in the same order, with the same exceptions as without the SDK. The event carries the time to the first chunk that carries a choice as ttft_ms (Azure's prompt-filter chunk does not count) and the tokens from the final usage chunk.
  • For provider openai, a streamed call that sets no stream_options is sent with stream_options={"include_usage": True}, and the usage-only chunk that adds is kept from your code. Other providers, Azure included, are sent what you wrote: pass stream_options={"include_usage": True} yourself where the server supports it, or the tokens are estimated from the length of the streamed text and marked tokens_estimated.
  • The key and address come from KATONIC_API_KEY and KATONIC_BASE_URL, or api_key= / base_url=. A bad app_name raises ValidationError, a missing key ValueError, and an object that is not an openai client TypeError, all from instrument() itself.
  • A client pointed at the Katonic Developer Hub reports nothing: each reply carries katonic_event_id (a refusal carries it too), and the AI Gateway has already counted the call.
  • instrument() never sends text. To log text, call log_request() instead of instrumenting that client, not as well: for another provider both would report the call's usage.

Naming, versioning, and one caveat

  • Distribution name: katonic-sdk, from 7.x (this package). The 6.x releases under the same name are Katonic's legacy MLOps SDK, a different API: pin katonic-sdk<7 if you still need it. Earlier 7.x documentation called this package katonic-platform; it was never published under that name.
  • Import name: import katonic. The legacy katonic 6.2.0 package owns the same import name — installing both in one environment is a silent module collision. Keep them in separate environments.
  • Versioning: the SDK is released with the platform, at the platform's version: platform vX.Y.Z is katonic-sdk==X.Y.Z. Development builds, X.Y.Z.devN, are published to TestPyPI only. Install the version that matches your deployment. A newer SDK can call routes that an older platform does not have.

Support

Issues and questions go through your Katonic support channel; the API reference lives in your deployment's Developer Hub.

Metadata

Release files for katonic-sdk 7.0.19

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Built distribution (wheel)

Table of built distributions (wheels) for katonic-sdk 7.0.19
File Interpreter ABI Platform Actions
katonic_sdk-7.0.19-py3-none-any.whl Python 3 none any Details for katonic_sdk-7.0.19-py3-none-any.whl

Release files / katonic_sdk-7.0.19-py3-none-any.whl

Download URL katonic_sdk-7.0.19-py3-none-any.whl
Size 207.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
29f268b0ca0a7d3182442b2fb7f16696ee386acefd9e53add3060a22056450f5
BLAKE2b-256 checksum
How to use checksums
60112ed8586c60f12e50a689dfce91e279980b7daa0df1ec7098545183179b32
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Security for katonic-sdk 7.0.19

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

7.0.19 This release

1 release file No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page