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.guardrailsandkatonic.toolsbuild an agent's bindings;katonic.composewires sub-agents into NAT workflows;katonic.scaffoldwrites blueprint packages;katonic.evaluatewrites local evaluation configs;katonic.connectorsis 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 raisesValidationError(knowledge.unknown_team, naming each one) and a name two teams answer to raisesknowledge.ambiguous_team, both before anything is created.teams=applies when the knowledge base is created;get_or_createleaves an existing one's sharing as it is.k.teams.list()returns the organisation's active teams asTeam(id, name, display_name), andk.teams.get_by_name(name)finds one by its name or the name the web UI shows (NotFoundErrorwhen none matches; aValueErrornaming both teams when two do). Both need thedocumentsscope.- 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) orfailedwith acode. - 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) andMetadataNotEditableError(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_nameand 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 withupdate_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
failedwith the server'scodeand the rest still go; the files already sent stay added. update_metadata(unset=[...])removes an edit made withupdate_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_documentsandwaitread documents by external id.- The key needs the
documentsscope, 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 itsindex_data(my_chunks)are bothadd_documents(...): there is no cutting step in the script. -
Objects sharing
external_id(a LlamaIndex node'sref_doc_id) are one document, its pages in order: the same idadd_filesand every result callexternal_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.titleis the title, else thesourcefile name.source,web_urlandpage_numberare 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 raisesKatonicAPIError(knowledge.storage_unreachable). -
link_filechecks the file before sending anything and raisesValidationErrorwith 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_urlis always an http(s) link. A file path is not a link: store the file withlink_fileand use its link. A document whoseweb_urlis not an http(s) link comes backfailedwithknowledge.invalid_source_url. A document whose pages name different links comes backfailedwithknowledge.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 withknowledge.file_not_found. -
No
web_urlmeans no link. A document sent again without one keeps the link or file it has. -
sourceis never read as a file. It is only the title when there is notitle. -
A loader fills in labels itself, so
add_documentsleaves 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 islimits()["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"]isFalse).
add_files(metadata=...)still refuses all of these, since that metadata is asked for by name. - keys the platform records itself (LlamaIndex's
-
A page is a citation's page through
page_number, counted from 1. Give a document's pages oneweb_url: v6's per-page#page=Nanchors are different links, so put the page inpage_numberinstead. A loader's ownpagekey (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
unchangedand nothing is processed; a changed title, link or metadata alone isupdatedwithout processing the text again; changed content replaces the document in place. Results areDocumentResult(FileResult). -
Checked before anything is sent, against
limits()["content"], with the server's codes onValidationError.code:Rule Default Code Text in one document, all pages together 10 MiB ( max_text_bytes); split a larger one into several documentsknowledge.text_too_largePages in one document 2,000 ( max_parts_per_document)knowledge.too_many_partsA page with no text, or text that is not valid UTF-8 knowledge.empty_text,knowledge.invalid_textEmbedding vectors ( embedding,vector, ...) in the metadatanot accepted: the platform embeds knowledge.vectors_not_acceptedMetadata as for add_files; a page's own labels follow the size bounds and reserved keysknowledge.invalid_metadata -
More documents than one request carries (100 by default) are sent in batches; a later batch that fails comes back
failedand 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/andreports/folders at the top of a Job's mount are skipped;includeandexcludetake glob patterns (**spans folders). - A file over the limit or with bad metadata is
failedon its own; a type the organisation does not accept isskipped; a document whose file is gone ismissingand kept. prune=Truedeletes the documents whose files are gone instead, and reports themdeleted; the key then also needsknowledge:delete. A file counts as gone only when nothing is at its path any more: one thatinclude,exclude, a dot-name or the mount'soutputs/andreports/leave out is still on disk and is never deleted, and neither is a document added in Studio or withadd_documents(its title is not the file's name). Prune needsexternal_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 withblock raisesSyncFailedErroras it closes, after every sync in it has run, so the Job ends Failed. Passfail_on_error=Falseto only report. dry_run=Truewrites nothing and lists every problem inreport.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()andtrack()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 ink.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(aValueError) for a negative token count, an empty model,ttft_msabovelatency_ms, a status other than"success"or"error", or an app name the platform does not accept. - An exception inside
track()is reported asstatus="error"with the exception's class name, and reaches your code unchanged. log()andtrack()send only the numbers: no prompt, no response, no provider key. Thekapi_key goes only in theAuthorizationheader. The platform prices the calls with its own price list; the SDK carries none. To report what was asked and answered, uselog_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 callk.flush()(orawait 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=1turns 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, itsdict, 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 asanswer=. - 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_requestsends 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.providerdefaults to"other". - Embeddings: pass the input as
questionand the embeddings reply asresponse; no answer is stored. - Size and characters:
questionandanswerare each cut to 32 KB of UTF-8 and marked as cut.end_usertakes 1-256 characters in any language, an email included, and no control characters (Nonewhen your app has no user to name); anything else raisesValidationErrorand 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 ink.usage.stats()["text_dropped"]. Text the platform could not store is counted instats()["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 asresponse=from yourexceptblock:statusis 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,AzureOpenAIandAsyncAzureOpenAI(openai 1.55.3 or later), forchat.completions.create()andchat.completions.parse(). A client made from it withwith_options()orcopy()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 withoutusage, the tokens are estimated from the length of the text (about four characters a token) and the event is markedtokens_estimated. - The provider comes from the client:
azure_openaifor an Azure client, else the host of itsbase_url(openai,groq,together,mistral,openrouter,perplexity,nvidia,google), andcustomfor any other host. Name it yourself withprovider=, 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 instats()["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 asttft_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 nostream_optionsis sent withstream_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: passstream_options={"include_usage": True}yourself where the server supports it, or the tokens are estimated from the length of the streamed text and markedtokens_estimated. - The key and address come from
KATONIC_API_KEYandKATONIC_BASE_URL, orapi_key=/base_url=. A badapp_nameraisesValidationError, a missing keyValueError, and an object that is not anopenaiclientTypeError, all frominstrument()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, calllog_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: pinkatonic-sdk<7if you still need it. Earlier 7.x documentation called this packagekatonic-platform; it was never published under that name. - Import name:
import katonic. The legacykatonic6.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.Ziskatonic-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)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| 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.