kbot-py-client
This package contains utilities which you may use to easily interact with Konverso Kbot application.
In particular, you may:
- Invoke some of the APIs to view / update / create Kbot configuration objects such as Intents, Message, etc.
- Collect metrics showing how the bot is performing.
- Create a Conversation and interact with it, sending message and getting responses
See also
Access Konverso Support
You may contact us:
- For any commercial inquiry: contact@konverso.ai
- For support: https://konverso.atlassian.net/servicedesk/customer/portals
License
This client code is open source such that you can freely view it, modify it, create your own version. We of course appreciate any contribution and sharing of enhancements made.
Installation
You may use pip3 to install the software on your Kbot instance:
pip3 install kbot-py-client
Alternatively, you can invoke a more explicity pip installation request, with the URL path:
pip3 install -e git+https://github.com/konverso-ai/kbot-py-client.git#egg=kbot-py-client
Usage
You would typically first need to login and then invoke some of the API wrapped methods.
Login
import json
from kbot_client import Client
Using user / password
cli = Client("mybot.konverso.ai")
cli.login("myuser", "mysecretpassword")
The API Key may be created for a given user, with relevant permissions, from the Configuration / Users & Roles / Users / Accounts panel. Create an account of type "Local"
Using and api key
cli = Client("mybot.konverso.ai", api_key="xxxxxxxxxxxxxxxxxxx")
The API Key may be created for a given user, with relevant permissions, from the Configuration / Users & Roles / Users / Accounts panel. Create an account of type "API Key"
User impersonation
If you have an API key created with sufficient permissions, then you can use the client impersonation.
cli = Client("mybot.konverso.ai", api_key="xxxxxxxxxxxxxxxxxxx")
cli.impersonate(user_name, 'local', external_auth='')
The above will generate a client for the user 'user_name'. This user must exists. If you are in an integration where you need to create the user, then we suggest to add a call first to the lookup/create before.
</code></pre>
<p>The API Key may be created for a given user, with relevant permissions, from the Configuration / Users & Roles / Users / Accounts panel. Create an account of type "API Key"</p>
<h2 id="user-content-collect-metrics">Collect metrics<a href="#user-content-collect-metrics" aria-label="Link to heading 'Collect metrics'" data-heading-content="Collect metrics" class="anchor"></a></h2>
<p>Once authenticated, you can for example retrieve useful usage metrics, these can be used by a Monitoring application or for some business intelligence rendering:</p>
<pre><code class="language-python">metrics = cli.metric().json()
print("Collected metrics:")
print(json.dumps(metrics, indent=4))
Invoke a Workflow and retrieve result
This is the most powerful mechanism, that let you invoke any business and processing logic in a workflow, leveraging all the capabilities of our platform, and retrieve the result:
r = client.request("post",
"workflow/execute",
{
"name": "Test API Workflow",
"keywords": {
"var1": "abc"
},
"result": ["response"]
}
)
print(r.json())
Invoke a search
You may invoke a search on any of the configured Search Contexts Note the search context UUID passed in the URL, which you may retrieve from our Search Context portal.
r = client.request("post", "searchcontext/234923-235-sjdhfs-kdjf/search",
{
"sentence": "how to create a classifier",
"num_results": 20,
#"variables": {'kbs': {'value': ['Confluence_Security_KSEC']}}
}
)
Get list of objects and check if object with name is present in response
You may retrieve list of defined objects. Note that only objects visibled to the logged in users will be returned.
Here is a sample code that simply checks for a few objects existance:
for unit, name in (('intention' ,'Create ticket'),
('knowledge_base', 'faq'),
('workflow', 'Transfer to Agent')):
print(f"Get list of '{unit}'")
objs = cli.unit(unit)
if objs:
# Create dict with
# - key : object name
# - value : object json data
data = {obj['name']: obj for obj in objs}
if name in data:
print(f"'{name}' is present")
else:
print(f"'{name}' is not present")
else:
print("Get no data")
Conversation test
In this example, we create a conversation between the logged in user and the bot and then sends a sentence, and check if we get some expected text in the response. This could for example be the basis of automated testing of the bot
r = cli.conversation(username='bot')
if r.status_code == 201:
cid = r.json().get('id')
print("Created conversation with id '%s'" %(cid,))
response = cli.message(cid, 'hello')
# Process bot response
if response:
for resp in response:
for message in resp.get('message', []):
responses.append(message.get('value', '')) # dict {message type: message value}
resp_message = '\n'.join(responses)
print("Received response: ", resp_message)
if 'I am kbot' in resp_message:
print("Excepted response found")
break
else:
print("Did not receive the expected response")
else:
print("Did not receive any response")
else:
print("Could not create conversation due to: ", r.text)
User creation and impersonation
The following sample is a complete example you may use to kick off a chat for a given user with the kbot chatbot. Here there is no user authentication, but impersonation instead, and user/lookup. This example is a good starting point if you are looking at implementing your own chat interface on top of Kbot.
# Create a session using an API key with strong privileges
cli = Client("mytenant.konverso.ai", api_key="34exxxxxxxxxxxxxa7bfb6aeb")
# Lookup create the user in kbot
response = cli.post("user/lookup_create", data={
"user_name": user_email,
"account_name": user_email,
"account_type": "local",
"external_auth": "nice-in-connect",
})
response.raise_for_status()
cli.impersonate(user_email, 'local', 'nice-in-connect') #, application_uuid="b0d91200-833f-466c-b5fd-1b0402cc3a36")
# Start the client (loop… ends with Ctrl D)
AsyncChatClient(cli)
Uploading one file to kbot
Prerequisites
- A local file that you wish to send
- The UUID of the folder that will receive the files you want to upload
Code sample
current_top_folder = "uuid-of-a-folder"
filepath = "/tmp/test.pdf"
filename = os.path.basename(filepath)
# Upload to remote filemanager
with open(filepath, "rb") as fd:
files = {
"upload_files": fd
}
params= {
"override": False
}
data = {
"folder": current_top_folder,
"name": file_name,
}
response = self.client.post_file("attachment",
Uploading a batch of files to the file manager
Prerequisites
- An API key
- The UUID of the folder that will receive the files you want to upload
Code sample
In this example, we simply upload the content of a directory to a folder in the file manager.
from kbot_client import Client
from kbot_client.folder_sync import FolderSync
client = Client("mybot.konverso.ai", api_key="17ebXXXXXXXXXXXXXXXXXXXXX")
syncer = FolderSync(client)
syncer.sync("/tmp/my_source_folder/", "1831f-XXXXXXXXXXXXXXXXXXXXXXX")
print("Syncing is done :)")
Recording API activity
You may attach a Recorder to a client to trace every API call it makes. This is useful for debugging or for building your own logging.
Printing each request and response
from kbot_client import Client, Printer
cli = Client("mybot.konverso.ai", api_key="xxxxxxxxxxxxxxxxxxx", recorder=Printer())
cli.metric()
Printing the equivalent curl command
This is handy when you want to reproduce a call outside of Python, for example to share it with support or run it from a terminal.
from kbot_client import Client, CurlPrinter
cli = Client("mybot.konverso.ai", api_key="xxxxxxxxxxxxxxxxxxx", recorder=CurlPrinter())
cli.metric()
You can also set or change the recorder after the client is created:
cli.recorder = CurlPrinter()
If you need a different behavior, such as writing the activity to a file or a logger, subclass Recorder and override its record method.
A command line chatbot
We provide a sample command line chatbot, available in Sync or Async mode
In this example, we simply initialize a chatbot client after creating a relevant User and Impersonating to it. This is a good example of implementation of a custom Client for the Kbot product.
# Create your client
import json
from kbot_client import Client
from kbot_client import chatbot_client
cli = Client("mytenant.konverso.ai", api_key="mykey")
external_auth = "cmd-line-chatbot"
user_email = "a-user-name"
assistant = "225d9647-0b41-473d-b097-ef4be363958a"
# Create your target user
response = cli.post("user/lookup_create", data={
"user_name": user_email,
"account_name": user_email,
"account_type": "local",
"external_auth": external_auth,
})
response.raise_for_status()
# Impersonate accordingly
cli.impersonate(user_email, 'local', external_auth)
# Start the chat
chatbot_client.run(client=cli, assistant=assistant, convert_html_to_text=True, mode="asynchronous")
Note that the above example is using a asynchronous call, meaning the client will listen for bot messages in a loop and publish the messages as they are received
For a simple chatbot, you do not need to provide the 'assistant' parameter.
Alternatively, you can also use our synchronous client. This will listen for messages and only return once all the messages are received for the user question.
from kbot_client import chatbot_client
...
chatbot_client.run(mode="synchronous", client=cli, assistant=assistant, convert_html_to_text=True)
Development
Running the tests
The test suite lives in tests/ and runs against a local fake Kbot HTTP server, so no Kbot instance is needed:
uv run --group test pytest
Live tests
tests/live/ runs against a real Kbot instance. These tests are skipped unless the following environment variables are set (never commit the API key):
KBOT_LIVE_HOST: the Kbot host, such asmybot.konverso.aiKBOT_LIVE_API_KEY: an API key allowed to create and impersonate users. The tests create (once) and impersonate the end userkbot-py-client-tests@konverso.aiKBOT_LIVE_FOLDER_UUID(optional): a File Manager folder. File tests create a timestamped sub folder in it and delete it afterwards
KBOT_LIVE_HOST=mybot.konverso.ai KBOT_LIVE_API_KEY=xxxx KBOT_LIVE_FOLDER_UUID=yyyy uv run --group test pytest -m live
Use -m "not live" to run only the offline tests.
Linting and type checking
The CI runs the following checks, which must pass:
uv run ruff check --select F,E9,B,PLE kbot_client examples
uv run pylint --errors-only kbot_client examples tests
uv run ty check kbot_client examples tests
ruff.toml selects all Ruff rules: this is the target, not yet met by the codebase (uv run ruff check still reports style findings).
Metadata
Release files for kbot-py-client 2.1.6
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| kbot_py_client-2.1.6.tar.gz | 16.4 kB | Without provenance | Details for kbot_py_client-2.1.6.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| kbot_py_client-2.1.6-py3-none-any.whl | Python 3 | none | any | Details for kbot_py_client-2.1.6-py3-none-any.whl |
Total release size: 37.3 kB
Release files / kbot_py_client-2.1.6.tar.gz
| Download URL | kbot_py_client-2.1.6.tar.gz |
|---|---|
| Size | 16.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
329abe45abb0dc4e6a59e8a64d135aacb335bee7c3716f2e7a384a905c6fa97d
|
|
BLAKE2b-256 checksum How to use checksums |
d46f9e23b6e7646a0894b17de512d6f01e49ab2ce77498bccb7390dcd680d1af
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.13.6 {"installer":{"name":"uv","version":"0.13.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / kbot_py_client-2.1.6-py3-none-any.whl
| Download URL | kbot_py_client-2.1.6-py3-none-any.whl |
|---|---|
| Size | 21.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
225cb9f7ce613e2330195c72a68ace869f1fedaf66d3690494404d1612766928
|
|
BLAKE2b-256 checksum How to use checksums |
a3a9be8cd9fd92e00034d19975802735119fa19dcdf998721e4a45ee043558a8
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.13.6 {"installer":{"name":"uv","version":"0.13.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for kbot-py-client 2.1.6
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.