SDKs
Keln's Python and TypeScript SDKs cover chat completions, responses, embeddings, rerank, decisions, transcription, speech, images, web search and sandboxes.
Inference methods accept the same arguments as OpenAI's SDKs, so you can switch clients without changing your existing calls.
| Python | TypeScript | |
|---|---|---|
| Package | keln-sdk |
@keln.ai/sdk |
| Runtime | Python 3.11 or newer | Node.js 22 or newer, as an ES module, in server-side code |
| Install | pip install keln-sdk |
npm install @keln.ai/sdk |
Use the SDKs on the server side. Running them in a browser exposes your API key to users.
Quickstart
Set the KELN_API_KEY environment variable. Both clients read it by default.
from keln import Keln
keln = Keln()
completion = keln.chat.completions.create(
model="zai-org/glm-5.3",
messages=[{"role": "user", "content": "Capital of France?"}],
)
print(completion.choices[0].message.content)
import { Keln } from "@keln.ai/sdk";
const keln = new Keln();
const completion = await keln.chat.completions.create({
model: "zai-org/glm-5.3",
messages: [{ role: "user", content: "Capital of France?" }],
});
console.log(completion.choices[0]?.message.content);
For async Python code, use AsyncKeln. It exposes the same methods, called with await.
Streaming
Set stream=True (stream: true in TypeScript) and iterate over the response chunks.
stream = keln.chat.completions.create(
model="zai-org/glm-5.3",
messages=[{"role": "user", "content": "Write a haiku about the sea."}],
stream=True,
)
for chunk in stream:
print(chunk.choices[0].delta.content or "", end="")
const stream = await keln.chat.completions.create({
model: "zai-org/glm-5.3",
messages: [{ role: "user", content: "Write a haiku about the sea." }],
stream: true,
});
for await (const chunk of stream) process.stdout.write(chunk.choices[0]?.delta.content ?? "");
Sandboxes
Create a sandbox, run commands, read and write files, and delete it when you're done.
with keln.sandboxes.create(timeout_s=600) as sandbox:
result = sandbox.commands.run("python3 -c 'print(2 ** 100)'")
print(result.stdout, result.exit_code)
sandbox.files.write("/tmp/notes.txt", "hello")
print(sandbox.files.read_text("/tmp/notes.txt"))
const sandbox = await keln.sandboxes.create({ timeoutS: 600 });
try {
const result = await sandbox.commands.run("python3 -c 'print(2 ** 100)'");
console.log(result.stdout, result.exitCode);
await sandbox.files.write("/tmp/notes.txt", "hello");
console.log(await sandbox.files.readText("/tmp/notes.txt"));
} finally {
await sandbox.delete();
}
See Sandboxes for templates, files, terminals, pausing and images.
SDK methods
| Method | Endpoint |
|---|---|
chat.completions.create |
POST /v1/chat/completions |
responses.create |
POST /v1/responses |
embeddings.create |
POST /v1/embeddings |
rerank.create |
POST /v1/rerank |
decisions.create |
POST /v1/decisions |
audio.transcriptions.create |
POST /v1/audio/transcriptions |
audio.speech.create |
POST /v1/audio/speech |
images.generate, images.edit |
POST /v1/images/generations, POST /v1/images/edits |
models.list |
GET /v1/models |
web.search, web.fetch |
POST /v1/web/search, POST /v1/web/fetch |
sandboxes, sandbox_images (sandboxImages), templates |
Sandbox API |
The SDK forwards unknown arguments to the API unchanged. Responses include all fields returned by the API, even those introduced after your SDK version was released.
Errors
All errors inherit from KelnError. Use code for programmatic error handling and message for human-readable descriptions.
from keln import KelnApiError
try:
sandbox.files.read("/no/such/file")
except KelnApiError as e:
if e.code != "file_not_found":
raise
import { KelnApiError } from "@keln.ai/sdk";
try {
await sandbox.files.read("/no/such/file");
} catch (e) {
if (!(e instanceof KelnApiError) || e.code !== "file_not_found") throw e;
}
KelnApiError: the API returned an error. Includesstatus,code,type,param,messageand the full response body. Each status has its own class:BadRequestError(400),AuthenticationError(401),PermissionDeniedError(403),NotFoundError(404),ConflictError(409),UnprocessableEntityError(422),RateLimitError(429) andInternalServerError(5xx).KelnConnectionError: the SDK could not reach the API.KelnTimeoutError: the request exceeded its timeout.
See Errors for the full list of error codes.
Retries and timeouts
- Retries: The SDK retries connection errors and
408,409,429and5xxresponses twice by default, with backoff, and followsRetry-After. Sandbox calls are retried only when safe to repeat, up to 5 times by default. Setmax_retries(maxRetries) on the client to change the retry count. - Streams: If a command stream is interrupted, the SDK reconnects from where it left off without losing or duplicating output.
- Timeouts: No timeout is set by default. In Python, pass
timeoutin seconds to the client or individual call. In TypeScript, passtimeoutin milliseconds or asignalto the call.
Response headers
You can access the raw HTTP response for each call, including rate limit headers, x-keln-inert-params and the request ID.
raw = keln.chat.completions.with_raw_response.create(
model="zai-org/glm-5.3", messages=[{"role": "user", "content": "Hi"}]
)
print(raw.request_id, raw.headers.get("x-ratelimit-remaining-requests"))
completion = raw.parse()
const { data, response, request_id } = await keln.chat.completions
.create({ model: "zai-org/glm-5.3", messages: [{ role: "user", content: "Hi" }] })
.withResponse();
console.log(request_id, response.headers.get("x-ratelimit-remaining-requests"));
MCP server
@keln.ai/mcp is a local MCP server that exposes Keln sandboxes and web search as tools in clients like Claude Code, Cursor and Claude Desktop.
claude mcp add keln -e KELN_API_KEY="$KELN_API_KEY" -- npx -y @keln.ai/mcp
For a setup without local installation, use the hosted MCP server.
Versions
Both SDKs follow semantic versioning. Release changelogs are available on PyPI and npm.