diff --git a/README.md b/README.md
index ff07e76..25e0b49 100644
--- a/README.md
+++ b/README.md
@@ -134,6 +134,32 @@ for hit in experts.knowledge.search("refund policy", collections=[collections[0]
`search()` returns passages, closest first, each with the document it came from. `list_documents(collection=..., search=...)` lists and filters documents by name, title or summary; `delete_document(uid)` removes one. Allow longer than the two-minute default for large files, and much longer for recordings, which are transcribed before they become documents.
+## Decisions
+
+Experts 1.2 adds decision models: small models that answer named questions about a case in a fraction of a second, without writing text. Sorting mail, routing a ticket, a second opinion before something is sent. The install's own decision model answers unless you name one.
+
+```python
+decision = experts.decide(
+ "Hi, invoice INV-2231 was charged twice. Could you refund one?",
+ {
+ "kind": {
+ "type": "choice",
+ "instructions": "What kind of email is this?",
+ "criteria": {
+ "billing": "About an invoice, a charge or a refund",
+ "support": "A question about using the product",
+ "sales": "Wants to buy, or asks for a price",
+ },
+ }
+ },
+)
+answer = decision["kind"]
+answer.choice # "billing"
+answer.probability # 0.94, the pick's own probability
+```
+
+Set thresholds on `probability`, never on `confidence`: the model's confidence measures how spread its answer is, not how likely its pick is. A `noul` question answers a yes as one probability (`answer.noul`); measure where to cut it on your own cases, since small models seldom reach 0.5. Put the case alone in the state and facts about it in the options' descriptions. Server clients only: the install refuses a browser session.
+
## Errors
```python
diff --git a/pyproject.toml b/pyproject.toml
index 061c06a..96eb5f1 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "klavi-experts"
-version = "0.2.0"
+version = "0.3.0"
description = "Official Python SDK for the Klavi Experts API — conversations, streaming, experts, and knowledge."
readme = "README.md"
license = "MIT"
diff --git a/spec/openapi.json b/spec/openapi.json
index b122066..a327f91 100644
--- a/spec/openapi.json
+++ b/spec/openapi.json
@@ -2,7 +2,7 @@
"openapi": "3.1.0",
"info": {
"title": "Klavi Experts API",
- "version": "1.1.0",
+ "version": "1.2.0",
"description": "The HTTP API of a Klavi Experts installation.\n\n## Authentication\n\nSend your API key as `Authorization: Bearer sk-...`. `X-API-Key: sk-...` is\nalso accepted, but send exactly ONE of them \u2014 the gateway checks\n`Authorization` first and that check is terminal, so a stale bearer token\ndecides the request even when a valid key is present in the other header.\n\nA key is a full user identity on the install. It belongs on a server. For\nanything browser-facing, mint a session token with\n`POST /api/v1/public/sessions`.\n\n## Streaming\n\n`POST /api/v1/conversations/chat` returns `application/x-ndjson` over plain\nHTTP \u2014 one JSON object per line, terminated by one carrying `done: true`. No\nWebSocket is required.\n\nTwo things about it surprise people:\n\n* **Sending a message is three calls.** `/chat` never CREATES message rows; it\n updates one you make first. Create the user's turn and an assistant\n placeholder with `POST /api/v1/responses/`, then pass the placeholder's uid\n as `response`. Omit it and the model still answers, but nothing persists.\n* **HTTP 200 is not proof of an answer.** Generation reports its own failures\n in the terminal event's `error` field, not in the status code.\n\nDurations in the terminal event are NANOSECONDS.\n\n## Errors\n\n`403` with `{\"error\": \"license_expired\"}` is an installation-level failure,\nnot a permission problem: nothing about the request is wrong, and only the\ninstall's administrator can resolve it.\n\nFor 30 days after a licence expires the install is read-only rather than\ndark: GET and HEAD are served, and every other method answers `403` with\n`{\"error\": \"license_expired_readonly\"}`. That includes the reads sent as a\nPOST: a chat turn and `/api/v1/similarity_search/`.\n\n`403` with `{\"detail\": {\"reason\": \"expert_not_available\"}}` from `/chat` means\nthe caller may not use that expert (its role, privacy or org profiles). Before\n1.1 the turn silently answered on the site default model instead.\n",
"license": {
"name": "Proprietary"
@@ -159,6 +159,48 @@
"title": "AdoptContextRequest",
"description": "Request to link already-embedded documents into a conversation's hidden\nupload collection, matched by content hash.\n\nFields:\n- `conversation_uid`: The conversation whose upload collection should\nreceive the documents (created on first adoption).\n- `keys`: Context keys \u2014 SHA-256 content hashes for file attachments.\nNon-document keys (e.g. web-page URLs) are skipped, not errors."
},
+ "AdviceWorkflow": {
+ "properties": {
+ "name": {
+ "type": "string",
+ "maxLength": 400,
+ "title": "Name",
+ "default": ""
+ },
+ "description": {
+ "anyOf": [
+ {
+ "type": "string",
+ "maxLength": 4000
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Description"
+ }
+ },
+ "type": "object",
+ "title": "AdviceWorkflow"
+ },
+ "Answer": {
+ "properties": {
+ "approve": {
+ "type": "boolean",
+ "title": "Approve"
+ },
+ "all": {
+ "type": "boolean",
+ "title": "All",
+ "default": false
+ }
+ },
+ "type": "object",
+ "required": [
+ "approve"
+ ],
+ "title": "Answer"
+ },
"AssignRequest": {
"properties": {
"conversationUid": {
@@ -173,6 +215,33 @@
],
"title": "AssignRequest"
},
+ "BackfillRequest": {
+ "properties": {
+ "collection_uids": {
+ "anyOf": [
+ {
+ "items": {
+ "type": "string",
+ "format": "uuid"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Collection Uids"
+ },
+ "retry": {
+ "type": "boolean",
+ "title": "Retry",
+ "default": false
+ }
+ },
+ "additionalProperties": false,
+ "type": "object",
+ "title": "BackfillRequest"
+ },
"BackgroundTaskResponse": {
"properties": {
"timestamp": {
@@ -195,6 +264,59 @@
"title": "BackgroundTaskResponse",
"description": "Response model returned to an API request that results in a background task\nbeing spawned. E.g. `/api/v1/predict`, the response returns immediately and\nqueues a webhook reponse as a callback once the process has completed.\n\nFields:\n- `status`: int, HTTP status code for the request\n- `message`: str, status response message\n\nInherited:\n- `timestamp`: int, the current UTC datetime in Epoch millis"
},
+ "Body_accept_workspace_api_v1_internal_conversations__conversation_uid__workspace_post": {
+ "properties": {
+ "archive": {
+ "type": "string",
+ "format": "binary",
+ "title": "Archive"
+ },
+ "sender_uid": {
+ "type": "string",
+ "format": "uuid",
+ "title": "Sender Uid"
+ },
+ "name": {
+ "type": "string",
+ "title": "Name"
+ },
+ "sha256": {
+ "type": "string",
+ "title": "Sha256"
+ },
+ "replaces": {
+ "anyOf": [
+ {
+ "type": "string",
+ "format": "uuid"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Replaces"
+ },
+ "ml_model_name": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Ml Model Name"
+ }
+ },
+ "type": "object",
+ "required": [
+ "archive",
+ "sender_uid",
+ "name",
+ "sha256"
+ ],
+ "title": "Body_accept_workspace_api_v1_internal_conversations__conversation_uid__workspace_post"
+ },
"Body_add_file_upload_to_context_api_v1_conversations_add_context__post": {
"properties": {
"files": {
@@ -393,6 +515,20 @@
],
"title": "Body_add_file_upload_to_context_api_v1_conversations_files__post"
},
+ "Body_extract_text_api_v1_extract_text_post": {
+ "properties": {
+ "file": {
+ "type": "string",
+ "format": "binary",
+ "title": "File"
+ }
+ },
+ "type": "object",
+ "required": [
+ "file"
+ ],
+ "title": "Body_extract_text_api_v1_extract_text_post"
+ },
"Body_init_job_queue_api_v1_documents_init_job_queue_post": {
"properties": {
"total_files": {
@@ -1488,6 +1624,18 @@
],
"title": "Researchcollectionuid"
},
+ "client": {
+ "anyOf": [
+ {
+ "additionalProperties": true,
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Client"
+ },
"researchObjective": {
"anyOf": [
{
@@ -1535,6 +1683,87 @@
"type": "object",
"title": "ChatRequest"
},
+ "ClientResult": {
+ "properties": {
+ "nonce": {
+ "type": "string",
+ "maxLength": 128,
+ "minLength": 8,
+ "title": "Nonce"
+ },
+ "ok": {
+ "type": "boolean",
+ "title": "Ok"
+ },
+ "content": {
+ "type": "string",
+ "maxLength": 1000000,
+ "title": "Content",
+ "default": ""
+ },
+ "error": {
+ "anyOf": [
+ {
+ "type": "string",
+ "maxLength": 2000
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Error"
+ },
+ "ms": {
+ "anyOf": [
+ {
+ "type": "integer",
+ "minimum": 0.0
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Ms"
+ },
+ "decision": {
+ "anyOf": [
+ {
+ "type": "string",
+ "enum": [
+ "applied",
+ "declined"
+ ]
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Decision"
+ },
+ "allowed_by": {
+ "anyOf": [
+ {
+ "type": "string",
+ "enum": [
+ "person",
+ "folder"
+ ]
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Allowed By"
+ }
+ },
+ "type": "object",
+ "required": [
+ "nonce",
+ "ok"
+ ],
+ "title": "ClientResult",
+ "description": "What the owner's desktop app did with a call it was handed: what it\nread (M7a), or for a change (M7b) whether the person applied it, and\nhow it was allowed (`person`: they saw it and applied it; `folder`: they\nlet that folder be edited without asking)."
+ },
"Collection": {
"properties": {
"created_at": {
@@ -1943,6 +2172,25 @@
"title": "ConversationForkRequest",
"description": "Fork (branch) a conversation into a new one.\n\ntitle \u2014 name for the fork; empty \u2192 server generates a fresh\n summary of the transcript (fallback \"
V2\").\nresponse_uid \u2014 branch point: copy messages up to and including this\n response. None copies the whole conversation.\ntarget_user \u2014 fork into another user's account (the source stays with\n the caller). None/self keeps the fork in the caller's."
},
+ "ConversationSettingsBody": {
+ "properties": {
+ "autoReads": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Autoreads"
+ }
+ },
+ "additionalProperties": false,
+ "type": "object",
+ "title": "ConversationSettingsBody",
+ "description": "A chat's own settings, as its header sets them. Each is optional: what\nis left out stays as it was."
+ },
"ConversationStartRequest": {
"properties": {
"title": {
@@ -2241,6 +2489,38 @@
],
"title": "ConversationUpdateRequest"
},
+ "CreateFamilyRequest": {
+ "properties": {
+ "document_uids": {
+ "items": {
+ "type": "string",
+ "format": "uuid"
+ },
+ "type": "array",
+ "maxItems": 2500,
+ "minItems": 1,
+ "title": "Document Uids"
+ },
+ "name": {
+ "anyOf": [
+ {
+ "type": "string",
+ "maxLength": 200
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Name"
+ }
+ },
+ "additionalProperties": false,
+ "type": "object",
+ "required": [
+ "document_uids"
+ ],
+ "title": "CreateFamilyRequest"
+ },
"CreateSmartCollectionRequest": {
"properties": {
"name": {
@@ -2307,6 +2587,85 @@
"title": "CreateSmartCollectionRequest",
"description": "Request to create a new smart collection watching a filesystem path."
},
+ "DecideRequest": {
+ "properties": {
+ "state": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "additionalProperties": true,
+ "type": "object"
+ },
+ {
+ "items": {},
+ "type": "array"
+ }
+ ],
+ "title": "State"
+ },
+ "questions": {
+ "additionalProperties": true,
+ "type": "object",
+ "title": "Questions"
+ },
+ "model": {
+ "anyOf": [
+ {
+ "type": "string",
+ "maxLength": 200
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Model"
+ },
+ "backend": {
+ "anyOf": [
+ {
+ "type": "string",
+ "maxLength": 64
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Backend"
+ },
+ "feature": {
+ "anyOf": [
+ {
+ "type": "string",
+ "maxLength": 60
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Feature"
+ },
+ "reference_id": {
+ "anyOf": [
+ {
+ "type": "string",
+ "maxLength": 200
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Reference Id"
+ }
+ },
+ "type": "object",
+ "required": [
+ "state",
+ "questions"
+ ],
+ "title": "DecideRequest"
+ },
"Deck": {
"properties": {
"width_emu": {
@@ -3807,6 +4166,11 @@
}
],
"title": "Reference Id"
+ },
+ "code_agent": {
+ "type": "boolean",
+ "title": "Code Agent",
+ "default": false
}
},
"type": "object",
@@ -4257,72 +4621,197 @@
},
"type": "object",
"required": [
- "setupToken",
- "name",
- "email",
- "username",
- "password"
+ "setupToken",
+ "name",
+ "email",
+ "username",
+ "password"
+ ],
+ "title": "InitAdminRequest"
+ },
+ "InitSiteRequest": {
+ "properties": {
+ "gatewayApi": {
+ "type": "string",
+ "title": "Gatewayapi"
+ }
+ },
+ "type": "object",
+ "required": [
+ "gatewayApi"
+ ],
+ "title": "InitSiteRequest"
+ },
+ "InlineDocEmbedResponse": {
+ "properties": {
+ "timestamp": {
+ "type": "integer",
+ "title": "Timestamp"
+ },
+ "status": {
+ "type": "integer",
+ "title": "Status",
+ "default": 200
+ },
+ "message": {
+ "type": "string",
+ "title": "Message",
+ "default": "OK"
+ },
+ "collection": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/Collection"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "upload_flavor": {
+ "$ref": "#/components/schemas/DocUploadFlavorId",
+ "default": 1
+ },
+ "docs": {
+ "items": {
+ "$ref": "#/components/schemas/DocWithSplitTexts"
+ },
+ "type": "array",
+ "title": "Docs"
+ }
+ },
+ "additionalProperties": true,
+ "type": "object",
+ "required": [
+ "docs"
+ ],
+ "title": "InlineDocEmbedResponse",
+ "description": "Response object for an inline (non-job-queue) document upload which returns\na collection, conversation or None, depending on the `flavorId` flag. A\ndocument list and text splits for each document."
+ },
+ "InternalAdviceRequest": {
+ "properties": {
+ "user_uid": {
+ "type": "string",
+ "format": "uuid",
+ "title": "User Uid"
+ },
+ "workflow": {
+ "$ref": "#/components/schemas/AdviceWorkflow"
+ },
+ "tool": {
+ "type": "string",
+ "maxLength": 200,
+ "title": "Tool"
+ },
+ "args": {
+ "anyOf": [
+ {
+ "additionalProperties": true,
+ "type": "object"
+ },
+ {
+ "items": {},
+ "type": "array"
+ },
+ {
+ "type": "string"
+ },
+ {
+ "type": "integer"
+ },
+ {
+ "type": "number"
+ },
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Args"
+ },
+ "reference_id": {
+ "anyOf": [
+ {
+ "type": "string",
+ "maxLength": 200
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Reference Id"
+ }
+ },
+ "type": "object",
+ "required": [
+ "user_uid",
+ "workflow",
+ "tool"
],
- "title": "InitAdminRequest"
+ "title": "InternalAdviceRequest"
},
- "InitSiteRequest": {
+ "InternalDecideRequest": {
"properties": {
- "gatewayApi": {
+ "user_uid": {
"type": "string",
- "title": "Gatewayapi"
- }
- },
- "type": "object",
- "required": [
- "gatewayApi"
- ],
- "title": "InitSiteRequest"
- },
- "InlineDocEmbedResponse": {
- "properties": {
- "timestamp": {
- "type": "integer",
- "title": "Timestamp"
+ "format": "uuid",
+ "title": "User Uid"
},
- "status": {
- "type": "integer",
- "title": "Status",
- "default": 200
+ "state": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "additionalProperties": true,
+ "type": "object"
+ },
+ {
+ "items": {},
+ "type": "array"
+ }
+ ],
+ "title": "State"
},
- "message": {
- "type": "string",
- "title": "Message",
- "default": "OK"
+ "questions": {
+ "additionalProperties": true,
+ "type": "object",
+ "title": "Questions"
},
- "collection": {
+ "feature": {
"anyOf": [
{
- "$ref": "#/components/schemas/Collection"
+ "type": "string",
+ "maxLength": 60
},
{
"type": "null"
}
- ]
- },
- "upload_flavor": {
- "$ref": "#/components/schemas/DocUploadFlavorId",
- "default": 1
+ ],
+ "title": "Feature"
},
- "docs": {
- "items": {
- "$ref": "#/components/schemas/DocWithSplitTexts"
- },
- "type": "array",
- "title": "Docs"
+ "reference_id": {
+ "anyOf": [
+ {
+ "type": "string",
+ "maxLength": 200
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Reference Id"
}
},
- "additionalProperties": true,
"type": "object",
"required": [
- "docs"
+ "user_uid",
+ "state",
+ "questions"
],
- "title": "InlineDocEmbedResponse",
- "description": "Response object for an inline (non-job-queue) document upload which returns\na collection, conversation or None, depending on the `flavorId` flag. A\ndocument list and text splits for each document."
+ "title": "InternalDecideRequest"
},
"InviteAcceptRequest": {
"properties": {
@@ -4839,6 +5328,38 @@
],
"title": "ManualMember"
},
+ "MayRead": {
+ "properties": {
+ "user_uid": {
+ "type": "string",
+ "format": "uuid",
+ "title": "User Uid"
+ },
+ "file_id": {
+ "type": "string",
+ "format": "uuid",
+ "title": "File Id"
+ },
+ "run_id": {
+ "anyOf": [
+ {
+ "type": "string",
+ "format": "uuid"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Run Id"
+ }
+ },
+ "type": "object",
+ "required": [
+ "user_uid",
+ "file_id"
+ ],
+ "title": "MayRead"
+ },
"McpCollectionUpdate": {
"properties": {
"mcp_banned": {
@@ -5801,6 +6322,11 @@
"title": "Disablethinking",
"default": false
},
+ "codeAgent": {
+ "type": "boolean",
+ "title": "Codeagent",
+ "default": false
+ },
"minRoleId": {
"anyOf": [
{
@@ -6504,6 +7030,53 @@
"type": "object",
"title": "Run"
},
+ "SaveArtifact": {
+ "properties": {
+ "kind": {
+ "type": "string",
+ "title": "Kind"
+ },
+ "title": {
+ "type": "string",
+ "maxLength": 400,
+ "minLength": 1,
+ "title": "Title"
+ },
+ "content": {
+ "type": "string",
+ "maxLength": 5242880,
+ "minLength": 1,
+ "title": "Content"
+ },
+ "responseUid": {
+ "type": "string",
+ "format": "uuid",
+ "title": "Responseuid"
+ }
+ },
+ "type": "object",
+ "required": [
+ "kind",
+ "title",
+ "content",
+ "responseUid"
+ ],
+ "title": "SaveArtifact"
+ },
+ "ScopeOf": {
+ "properties": {
+ "user_uid": {
+ "type": "string",
+ "format": "uuid",
+ "title": "User Uid"
+ }
+ },
+ "type": "object",
+ "required": [
+ "user_uid"
+ ],
+ "title": "ScopeOf"
+ },
"SemanticDocumentSearchRequest": {
"properties": {
"user_uid": {
@@ -8291,68 +8864,247 @@
"type": "null"
}
],
- "title": "Name"
+ "title": "Name"
+ },
+ "groups": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array",
+ "title": "Groups"
+ },
+ "roles": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array",
+ "title": "Roles"
+ },
+ "groupsOverage": {
+ "type": "boolean",
+ "title": "Groupsoverage",
+ "default": false
+ },
+ "hostedDomain": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Hosteddomain"
+ },
+ "ip": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Ip"
+ },
+ "refreshTokenEnc": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Refreshtokenenc"
+ }
+ },
+ "type": "object",
+ "required": [
+ "provider",
+ "tenantId",
+ "subject"
+ ],
+ "title": "SsoCompleteRequest"
+ },
+ "StartRun": {
+ "properties": {
+ "conversation_uid": {
+ "type": "string",
+ "format": "uuid",
+ "title": "Conversation Uid"
+ },
+ "question": {
+ "type": "string",
+ "maxLength": 20000,
+ "minLength": 1,
+ "title": "Question"
+ },
+ "expert_uid": {
+ "anyOf": [
+ {
+ "type": "string",
+ "format": "uuid"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Expert Uid"
+ },
+ "model": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Model"
+ },
+ "budget": {
+ "anyOf": [
+ {
+ "additionalProperties": true,
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Budget"
+ }
+ },
+ "type": "object",
+ "required": [
+ "conversation_uid",
+ "question"
+ ],
+ "title": "StartRun"
+ },
+ "StartStep": {
+ "properties": {
+ "user_uid": {
+ "type": "string",
+ "format": "uuid",
+ "title": "User Uid"
},
- "groups": {
- "items": {
- "type": "string"
- },
- "type": "array",
- "title": "Groups"
+ "expert_uid": {
+ "type": "string",
+ "format": "uuid",
+ "title": "Expert Uid"
},
- "roles": {
- "items": {
- "type": "string"
- },
- "type": "array",
- "title": "Roles"
+ "instruction": {
+ "type": "string",
+ "maxLength": 20000,
+ "minLength": 1,
+ "title": "Instruction"
},
- "groupsOverage": {
- "type": "boolean",
- "title": "Groupsoverage",
- "default": false
+ "input": {
+ "title": "Input"
},
- "hostedDomain": {
+ "output_schema": {
"anyOf": [
{
- "type": "string"
+ "additionalProperties": true,
+ "type": "object"
},
{
"type": "null"
}
],
- "title": "Hosteddomain"
+ "title": "Output Schema"
},
- "ip": {
+ "budget": {
"anyOf": [
{
- "type": "string"
+ "additionalProperties": true,
+ "type": "object"
},
{
"type": "null"
}
],
- "title": "Ip"
+ "title": "Budget"
},
- "refreshTokenEnc": {
+ "pipeline_node_run_id": {
+ "type": "string",
+ "format": "uuid",
+ "title": "Pipeline Node Run Id"
+ },
+ "conversation_uid": {
"anyOf": [
{
- "type": "string"
+ "type": "string",
+ "format": "uuid"
},
{
"type": "null"
}
],
- "title": "Refreshtokenenc"
+ "title": "Conversation Uid"
+ },
+ "workflow": {
+ "type": "string",
+ "maxLength": 200,
+ "minLength": 1,
+ "title": "Workflow"
+ },
+ "tainted": {
+ "type": "boolean",
+ "title": "Tainted",
+ "default": false
}
},
+ "additionalProperties": false,
"type": "object",
"required": [
- "provider",
- "tenantId",
- "subject"
+ "user_uid",
+ "expert_uid",
+ "instruction",
+ "pipeline_node_run_id",
+ "workflow"
],
- "title": "SsoCompleteRequest"
+ "title": "StartStep"
+ },
+ "StartUpload": {
+ "properties": {
+ "name": {
+ "type": "string",
+ "maxLength": 255,
+ "minLength": 1,
+ "title": "Name"
+ },
+ "size": {
+ "type": "integer",
+ "exclusiveMinimum": 0.0,
+ "title": "Size"
+ },
+ "unpacked": {
+ "type": "integer",
+ "minimum": 0.0,
+ "title": "Unpacked"
+ },
+ "files": {
+ "type": "integer",
+ "exclusiveMinimum": 0.0,
+ "title": "Files"
+ },
+ "sha256": {
+ "type": "string",
+ "title": "Sha256"
+ }
+ },
+ "type": "object",
+ "required": [
+ "name",
+ "size",
+ "unpacked",
+ "files",
+ "sha256"
+ ],
+ "title": "StartUpload"
},
"StringListResponse": {
"properties": {
@@ -9523,6 +10275,164 @@
],
"title": "WebhookRequest",
"description": "Struct encapsulating a webhook. When the specified event(s) trigger(s),\nPOSTS a JSON encoded WebhookResponse to the callback url, adding the token\nto the `Authorization` response header. `Authorization: bearer TOKEN`\nResponses from this callback are discarded & any errors ignored."
+ },
+ "WorkflowDone": {
+ "properties": {
+ "pipeline_run": {
+ "type": "string",
+ "format": "uuid",
+ "title": "Pipeline Run"
+ },
+ "state": {
+ "type": "string",
+ "enum": [
+ "done",
+ "failed",
+ "cancelled"
+ ],
+ "title": "State"
+ },
+ "output": {
+ "title": "Output"
+ },
+ "error": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Error"
+ },
+ "tainted": {
+ "type": "boolean",
+ "title": "Tainted",
+ "default": false
+ }
+ },
+ "type": "object",
+ "required": [
+ "pipeline_run",
+ "state"
+ ],
+ "title": "WorkflowDone"
+ },
+ "WorkflowMessage": {
+ "properties": {
+ "user_uid": {
+ "type": "string",
+ "format": "uuid",
+ "title": "User Uid"
+ },
+ "text": {
+ "type": "string",
+ "maxLength": 100000,
+ "minLength": 1,
+ "title": "Text"
+ },
+ "workflow": {
+ "type": "string",
+ "maxLength": 200,
+ "minLength": 1,
+ "title": "Workflow"
+ },
+ "run_id": {
+ "type": "string",
+ "format": "uuid",
+ "title": "Run Id"
+ }
+ },
+ "additionalProperties": false,
+ "type": "object",
+ "required": [
+ "user_uid",
+ "text",
+ "workflow",
+ "run_id"
+ ],
+ "title": "WorkflowMessage"
+ },
+ "WorkspaceAccepted": {
+ "properties": {
+ "collection_uid": {
+ "type": "string",
+ "title": "Collection Uid"
+ },
+ "job_queue_run_id": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Job Queue Run Id"
+ },
+ "folder": {
+ "type": "string",
+ "title": "Folder"
+ },
+ "files": {
+ "type": "integer",
+ "title": "Files"
+ },
+ "unpacked": {
+ "type": "integer",
+ "title": "Unpacked"
+ },
+ "queued": {
+ "type": "integer",
+ "title": "Queued",
+ "default": 0
+ },
+ "skipped_large": {
+ "type": "integer",
+ "title": "Skipped Large",
+ "default": 0
+ },
+ "skipped_type": {
+ "type": "integer",
+ "title": "Skipped Type",
+ "default": 0
+ },
+ "skipped_hidden": {
+ "type": "integer",
+ "title": "Skipped Hidden",
+ "default": 0
+ },
+ "skipped_secret": {
+ "type": "integer",
+ "title": "Skipped Secret",
+ "default": 0
+ }
+ },
+ "type": "object",
+ "required": [
+ "collection_uid",
+ "folder",
+ "files",
+ "unpacked"
+ ],
+ "title": "WorkspaceAccepted"
+ },
+ "WorkspaceRemoved": {
+ "properties": {
+ "found": {
+ "type": "boolean",
+ "title": "Found",
+ "default": false
+ },
+ "documents_deleted": {
+ "type": "integer",
+ "title": "Documents Deleted",
+ "default": 0
+ }
+ },
+ "type": "object",
+ "title": "WorkspaceRemoved"
}
}
},
@@ -9957,7 +10867,7 @@
"Chat"
],
"summary": "Cancel Chat",
- "description": "Stop a detached generation. Client disconnects no longer cancel the\nmodel (generation is deliberately connection-independent), so the Stop\nbutton calls this to actually halt it. The cancelled task persists its\npartial text and publishes a done event on the conversation stream.",
+ "description": "Stop a detached generation. Client disconnects no longer cancel the\nmodel (generation is deliberately connection-independent), so the Stop\nbutton calls this to actually halt it. The cancelled task persists its\npartial text and publishes a done event on the conversation stream.\n\nOnly someone who may write to the generation's conversation (its owner,\nor a person it is shared with: the rule that let them ask) can stop it;\nanyone else gets the conversation's 404.",
"operationId": "cancel_chat_api_v1_conversations_chat__response_uid__cancel_post",
"security": [
{
@@ -10830,6 +11740,54 @@
}
}
},
+ "/api/v1/llm/decide": {
+ "post": {
+ "tags": [
+ "Decisions"
+ ],
+ "summary": "Decide",
+ "operationId": "decide_api_v1_llm_decide_post",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/DecideRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "additionalProperties": true,
+ "type": "object",
+ "title": "Response Decide Api V1 Llm Decide Post"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ },
+ "security": [
+ {
+ "OAuth2PasswordBearer": []
+ }
+ ]
+ }
+ },
"/api/v1/llm/exec": {
"post": {
"tags": [
diff --git a/src/klavi_experts/__init__.py b/src/klavi_experts/__init__.py
index c64ee17..b3bf60c 100644
--- a/src/klavi_experts/__init__.py
+++ b/src/klavi_experts/__init__.py
@@ -39,6 +39,8 @@
Collection,
Conversation,
ConversationWithMessages,
+ Decision,
+ DecisionAnswer,
DoneEvent,
Expert,
KeepaliveEvent,
@@ -57,7 +59,7 @@
Usage,
)
-__version__ = "0.2.0"
+__version__ = "0.3.0"
# Grouped by what a reader is looking for — clients, then errors, then wire
# types — rather than alphabetised. RUF022 wants the latter; the grouping
@@ -89,6 +91,8 @@
"Expert",
"Conversation",
"ConversationWithMessages",
+ "Decision",
+ "DecisionAnswer",
"Message",
"SourceDocument",
"Usage",
diff --git a/src/klavi_experts/async_client.py b/src/klavi_experts/async_client.py
index ba59971..0d22477 100644
--- a/src/klavi_experts/async_client.py
+++ b/src/klavi_experts/async_client.py
@@ -26,6 +26,7 @@
from ._transport import AsyncTransport, Request
from .errors import ExpertsError, NotFoundError, StreamError
from .resources import conversations as _conv
+from .resources import decisions as _decisions
from .resources import experts as _experts
from .resources import knowledge as _knowledge
from .resources import sessions as _sessions
@@ -34,6 +35,7 @@
Collection,
Conversation,
ConversationWithMessages,
+ Decision,
Expert,
KnowledgeDocument,
SearchHit,
@@ -334,6 +336,37 @@ def __init__(
def transport(self) -> AsyncTransport:
return self._transport
+ async def decide(
+ self,
+ state: str | dict[str, Any] | list[Any],
+ questions: dict[str, dict[str, Any]],
+ *,
+ model: str | None = None,
+ backend: str | None = None,
+ feature: str | None = None,
+ reference_id: str | None = None,
+ ) -> Decision:
+ """Ask the install's decision model named questions about a case.
+
+ ``questions`` is ``{name: {type, instructions, criteria}}``; see
+ :mod:`klavi_experts.resources.decisions`. Answers come back by name:
+ ``decision["kind"].choice`` and ``.probability`` for a choice question.
+ Experts 1.2 and later; a server's key only (the install refuses a
+ browser session).
+ """
+ return _decisions.to_decision(
+ await self._transport.request(
+ _decisions.decide_request(
+ state=state,
+ questions=questions,
+ model=model,
+ backend=backend,
+ feature=feature,
+ reference_id=reference_id,
+ )
+ )
+ )
+
async def request(self, method: str, path: str, **kw: Any) -> Any:
return await self._transport.request(Request(method=method, path=path, **kw))
diff --git a/src/klavi_experts/client.py b/src/klavi_experts/client.py
index 8abdc2d..d7acab0 100644
--- a/src/klavi_experts/client.py
+++ b/src/klavi_experts/client.py
@@ -28,6 +28,7 @@
from ._transport import Request, SyncTransport
from .errors import ExpertsError, NotFoundError, StreamError
from .resources import conversations as _conv
+from .resources import decisions as _decisions
from .resources import experts as _experts
from .resources import knowledge as _knowledge
from .resources import sessions as _sessions
@@ -36,6 +37,7 @@
Collection,
Conversation,
ConversationWithMessages,
+ Decision,
Expert,
KnowledgeDocument,
SearchHit,
@@ -394,6 +396,37 @@ def transport(self) -> SyncTransport:
"""Escape hatch for endpoints this SDK does not wrap yet."""
return self._transport
+ def decide(
+ self,
+ state: str | dict[str, Any] | list[Any],
+ questions: dict[str, dict[str, Any]],
+ *,
+ model: str | None = None,
+ backend: str | None = None,
+ feature: str | None = None,
+ reference_id: str | None = None,
+ ) -> Decision:
+ """Ask the install's decision model named questions about a case.
+
+ ``questions`` is ``{name: {type, instructions, criteria}}``; see
+ :mod:`klavi_experts.resources.decisions`. Answers come back by name:
+ ``decision["kind"].choice`` and ``.probability`` for a choice question.
+ Experts 1.2 and later; a server's key only (the install refuses a
+ browser session).
+ """
+ return _decisions.to_decision(
+ self._transport.request(
+ _decisions.decide_request(
+ state=state,
+ questions=questions,
+ model=model,
+ backend=backend,
+ feature=feature,
+ reference_id=reference_id,
+ )
+ )
+ )
+
def request(self, method: str, path: str, **kw: Any) -> Any:
"""Call an endpoint directly, with auth and error handling applied."""
return self._transport.request(Request(method=method, path=path, **kw))
diff --git a/src/klavi_experts/resources/decisions.py b/src/klavi_experts/resources/decisions.py
new file mode 100644
index 0000000..f8bc3df
--- /dev/null
+++ b/src/klavi_experts/resources/decisions.py
@@ -0,0 +1,90 @@
+"""A decision model's answers (Experts 1.2, ``POST /api/v1/llm/decide``).
+
+A decision model is a small model that answers named questions about a case
+in a fraction of a second: one of a few choices, a yes/no as a probability,
+or a score. It never writes text. The install's own decision model answers
+unless you name a model (and, optionally, the Ollama backend it is on).
+
+Each question is ``{type, instructions, criteria}``:
+
+- ``choice``: ``criteria`` names 2 to 16 options, ``{option: what it means}``,
+ lower-case names. The answer's ``choice`` is the pick.
+- ``noul``: no criteria; the answer's ``noul`` is the probability of yes.
+ Measure your own threshold: on small models it seldom reaches 0.5.
+- ``score``: ``criteria`` is a list of descriptions.
+
+Put the case alone in ``state``, and facts about it in the options'
+descriptions: with facts in the state, small models pick the same option for
+nearly everything. Usage is counted under ``feature`` (default ``decide``).
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from .._transport import Request
+from ..types import Decision, DecisionAnswer
+
+
+def decide_request(
+ *,
+ state: str | dict[str, Any] | list[Any],
+ questions: dict[str, dict[str, Any]],
+ model: str | None,
+ backend: str | None,
+ feature: str | None,
+ reference_id: str | None,
+) -> Request:
+ body: dict[str, Any] = {"state": state, "questions": questions}
+ named = (
+ ("model", model),
+ ("backend", backend),
+ ("feature", feature),
+ ("reference_id", reference_id),
+ )
+ for key, value in named:
+ if value is not None:
+ body[key] = value
+ # A decision changes nothing, so a 5xx (the model still downloading) is
+ # tried again like any read
+ return Request(method="POST", path="/api/v1/llm/decide", json=body)
+
+
+def _floats(raw: Any) -> dict[str, float]:
+ if not isinstance(raw, dict):
+ return {}
+ return {str(k): float(v) for k, v in raw.items() if isinstance(v, (int, float))}
+
+
+def _num(raw: Any) -> float | None:
+ if isinstance(raw, bool) or not isinstance(raw, (int, float)):
+ return None
+ return float(raw)
+
+
+def to_answer(raw: Any) -> DecisionAnswer:
+ raw = raw if isinstance(raw, dict) else {}
+ legend = raw.get("legend") if isinstance(raw.get("legend"), dict) else {}
+ return DecisionAnswer(
+ type=str(raw.get("type") or ""),
+ choice=raw.get("choice") if isinstance(raw.get("choice"), str) else None,
+ probabilities=_floats(raw.get("probabilities")),
+ confidence=_num(raw.get("confidence")),
+ noul=_num(raw.get("noul")),
+ score=_num(raw.get("score")),
+ legend={str(k): str(v) for k, v in legend.items()},
+ )
+
+
+def to_decision(raw: Any) -> Decision:
+ raw = raw if isinstance(raw, dict) else {}
+ answers = raw.get("answers") if isinstance(raw.get("answers"), dict) else {}
+ usage = raw.get("usage") if isinstance(raw.get("usage"), dict) else {}
+ backend = raw.get("backend")
+ return Decision(
+ model=str(raw.get("model") or ""),
+ answers={str(name): to_answer(a) for name, a in answers.items()},
+ backend=str(backend) if backend else None,
+ input_tokens=int(usage.get("input_tokens") or 0),
+ output_tokens=int(usage.get("output_tokens") or 0),
+ )
diff --git a/src/klavi_experts/types.py b/src/klavi_experts/types.py
index 676c4a1..6953c07 100644
--- a/src/klavi_experts/types.py
+++ b/src/klavi_experts/types.py
@@ -553,3 +553,48 @@ class BrowserSession:
conversation: UUIDStr
expert_uid: UUIDStr
expert_name: str = ""
+
+
+@dataclass(slots=True)
+class DecisionAnswer:
+ """One question's answer from a decision model (Experts 1.2)."""
+
+ #: "choice", "noul" (a yes/no as one probability) or "score".
+ type: str
+ #: A choice question's pick.
+ choice: str | None = None
+ #: Each option's probability (a choice question's by option, a score
+ #: question's by the criterion's index as text).
+ probabilities: dict[str, float] = field(default_factory=dict)
+ #: The model's own confidence: one minus the answer's normalised entropy.
+ #: It says how spread the probabilities are, not how likely the pick is;
+ #: for that, read ``probability``.
+ confidence: float | None = None
+ #: A "noul" question's probability of yes.
+ noul: float | None = None
+ #: A "score" question's score, and its criteria by index.
+ score: float | None = None
+ legend: dict[str, str] = field(default_factory=dict)
+
+ @property
+ def probability(self) -> float | None:
+ """The pick's own probability: what a threshold should be set on.
+ None for a question with no pick."""
+ if self.choice is None:
+ return None
+ return self.probabilities.get(self.choice)
+
+
+@dataclass(slots=True)
+class Decision:
+ """A decision model's answers, by question name."""
+
+ model: str
+ answers: dict[str, DecisionAnswer] = field(default_factory=dict)
+ #: The install's backend that answered, when it says.
+ backend: str | None = None
+ input_tokens: int = 0
+ output_tokens: int = 0
+
+ def __getitem__(self, question: str) -> DecisionAnswer:
+ return self.answers[question]
diff --git a/tests/test_async_parity.py b/tests/test_async_parity.py
index 1aafa90..77232c7 100644
--- a/tests/test_async_parity.py
+++ b/tests/test_async_parity.py
@@ -216,3 +216,30 @@ def replies():
assert s_rec.paths == a_rec.paths
assert s_rec.body(0) == a_rec.body(0)
+
+
+
+DECISION = {
+ "model": "tev1:0.8b",
+ "answers": {
+ "kind": {"type": "choice", "choice": "a", "probabilities": {"a": 0.9, "b": 0.1}}
+ },
+}
+CRITERIA = {"a": "x", "b": "y"}
+KIND = {"kind": {"type": "choice", "instructions": "?", "criteria": CRITERIA}}
+
+
+class TestDecideParity:
+ def test_the_signatures_agree(self):
+ sync, aio = ExpertsClient.decide, AsyncExpertsClient.decide
+ assert inspect.signature(sync) == inspect.signature(aio)
+
+ async def test_both_send_the_same_request_and_read_the_same_answer(self):
+ sync, srec = sync_client([httpx.Response(200, json=DECISION)])
+ aio, arec = async_client([httpx.Response(200, json=DECISION)])
+ got = sync.decide("case", KIND, model="tev1:4b")
+ agot = await aio.decide("case", KIND, model="tev1:4b")
+ assert srec.body(0) == arec.body(0)
+ assert srec.paths == arec.paths == ["POST /api/v1/llm/decide"]
+ assert got == agot and got["kind"].probability == 0.9
+ await aio.aclose()
diff --git a/tests/test_client.py b/tests/test_client.py
index cf387e6..fbe5c7a 100644
--- a/tests/test_client.py
+++ b/tests/test_client.py
@@ -403,3 +403,83 @@ def test_revoking_is_scoped_to_the_session(self):
client, rec = make_client([ok({"revoked": True})])
client.sessions.revoke("s_abc")
assert rec.paths[0] == "DELETE /api/v1/public/sessions/s_abc"
+
+
+
+DECISION = {
+ "model": "tev1:0.8b",
+ "backend": "local",
+ "answers": {
+ "kind": {
+ "type": "choice",
+ "choice": "billing",
+ "confidence": 0.98,
+ "probabilities": {"billing": 0.94, "support": 0.04, "sales": 0.02},
+ },
+ "risky": {"type": "noul", "noul": 0.25},
+ "urgency": {
+ "type": "score",
+ "score": 0.33,
+ "legend": {"0": "waiting on money", "1": "a deadline"},
+ "probabilities": {"0": 0.67, "1": 0.33},
+ "confidence": 0.08,
+ },
+ },
+ "usage": {"input_tokens": 159, "output_tokens": 0},
+}
+KIND = {
+ "kind": {
+ "type": "choice",
+ "instructions": "What kind of email?",
+ "criteria": {"billing": "money", "support": "help", "sales": "buying"},
+ }
+}
+
+
+class TestDecide:
+ def test_it_posts_the_case_and_reads_each_answer_by_name(self):
+ client, rec = make_client([httpx.Response(200, json=DECISION)])
+ decision = client.decide("refund INV-2231", KIND, feature="mail_sort")
+ assert rec.paths == ["POST /api/v1/llm/decide"]
+ assert rec.body(0) == {
+ "state": "refund INV-2231",
+ "questions": KIND,
+ "feature": "mail_sort",
+ }
+ assert rec.calls[0].headers["authorization"] == f"Bearer {KEY}"
+ kind = decision["kind"]
+ assert (kind.type, kind.choice) == ("choice", "billing")
+ # The pick's probability, apart from the model's own confidence
+ assert (kind.probability, kind.confidence) == (0.94, 0.98)
+ risky, urgency = decision["risky"], decision["urgency"]
+ assert risky.noul == 0.25 and risky.probability is None
+ assert urgency.score == 0.33 and urgency.legend["1"] == "a deadline"
+ assert decision.model == "tev1:0.8b" and decision.backend == "local"
+ assert decision.input_tokens == 159
+
+ def test_a_model_and_backend_go_only_when_named(self):
+ client, rec = make_client([httpx.Response(200, json=DECISION)])
+ client.decide(
+ {"subject": "x"}, KIND, model="tev1:4b", backend="b1", reference_id="r"
+ )
+ assert rec.body(0) == {
+ "state": {"subject": "x"},
+ "questions": KIND,
+ "model": "tev1:4b",
+ "backend": "b1",
+ "reference_id": "r",
+ }
+
+ def test_a_malformed_question_is_refused_in_words(self):
+ refused = httpx.Response(422, json={"detail": "Question kind is a choice"})
+ client, _ = make_client([refused])
+ with pytest.raises(BadRequestError, match="Question kind is a choice"):
+ client.decide("x", KIND)
+
+ def test_a_model_still_downloading_is_asked_again(self):
+ coming = httpx.Response(503, json={"detail": "tev1:0.8b is downloading"})
+ client, rec = make_client(
+ [coming, httpx.Response(200, json=DECISION)], max_retries=2
+ )
+ assert client.decide("x", KIND)["kind"].choice == "billing"
+ assert len(rec.calls) == 2