Skip to main content

SilkLLM Python SDK

The official Python SDK for SilkLLM — one API key for OpenAI, Anthropic, Google, DeepSeek, and xAI.

Installation

pip install silkllm

Requires Python 3.9+. No other dependencies except httpx.


Authentication

Get your API key from the SilkLLM Dashboard.

import silkllm

# Pass the key directly
client = silkllm.Client(api_key="silk_your_key_here")

# Or set the environment variable (recommended for production)
# export SILKLLM_API_KEY=silk_your_key_here
client = silkllm.Client()

Basic Usage

import silkllm

client = silkllm.Client(api_key="silk_your_key_here")

response = client.generate(
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user",   "content": "What is the capital of France?"},
    ]
)

print(response.content)       # "The capital of France is Paris."
print(response.model)         # "gpt-4o" (or whichever model was used)
print(response.provider)      # "openai"
print(f"${response.cost_usd:.6f}")   # "$0.000150"
print(f"${response.balance_after:.4f}")  # remaining balance

Choosing a Model or Provider

# Request a specific model
response = client.generate(
    messages=[{"role": "user", "content": "Explain recursion."}],
    model="claude-3-5-sonnet-20241022",
)

# Request from a specific provider (uses their best available model)
response = client.generate(
    messages=[{"role": "user", "content": "Write a haiku."}],
    provider="anthropic",
)

# No preference — routes to cheapest healthy model automatically
response = client.generate(
    messages=[{"role": "user", "content": "Hi!"}],
)

Streaming

import silkllm

client = silkllm.Client(api_key="silk_your_key_here")

print("Assistant: ", end="")
for chunk in client.stream(
    messages=[{"role": "user", "content": "Write a short story about a robot."}],
    model="gpt-4o",
):
    print(chunk, end="", flush=True)
print()  # newline at end

Multi-turn Conversations

import silkllm

client = silkllm.Client(api_key="silk_your_key_here")

conversation = [{"role": "system", "content": "You are a helpful coding assistant."}]

while True:
    user_input = input("You: ")
    if user_input.lower() in ("exit", "quit"):
        break

    conversation.append({"role": "user", "content": user_input})

    response = client.generate(messages=conversation, model="gpt-4o")
    print(f"Assistant: {response.content}")

    # Add the assistant reply to history for next turn
    conversation.append({"role": "assistant", "content": response.content})

Checking Balance

balance = client.balance()
print(f"Balance: ${balance.balance_usd:.4f} USD")

Listing Available Models

# All models
models = client.models()
for m in models.models:
    print(f"{m.id:45} ${m.input_cost_per_1k_usd:.6f}/1K in  ${m.output_cost_per_1k_usd:.6f}/1K out")

# Filter by provider
openai_models = client.models(provider="openai")

Usage History

usage = client.usage(page=1, page_size=20)
print(f"Total requests: {usage.total}")
for entry in usage.entries:
    print(f"{entry.created_at}  {entry.entry_type:10}  ${abs(entry.amount):.6f}")

Error Handling

import silkllm

client = silkllm.Client(api_key="silk_your_key_here")

try:
    response = client.generate(
        messages=[{"role": "user", "content": "Hello!"}],
        model="gpt-4o",
    )
    print(response.content)

except silkllm.InsufficientBalanceError:
    print("Out of credits — visit dashboard to add more.")

except silkllm.ModelNotFoundError as e:
    print(f"Model not available: {e}")

except silkllm.RateLimitError:
    print("Rate limited — slow down requests.")

except silkllm.ProviderError as e:
    print(f"All providers failed: {e}")

except silkllm.AuthenticationError:
    print("Invalid API key.")

except silkllm.SilkLLMError as e:
    print(f"Unexpected error: {e}")

Context Manager

with silkllm.Client(api_key="silk_...") as client:
    response = client.generate(messages=[{"role": "user", "content": "Hello!"}])
    print(response.content)
# HTTP connection closed automatically

All Parameters

response = client.generate(
    messages=[...],           # Required. List of {role, content} dicts.
    model="gpt-4o",           # Optional. Specific model ID.
    provider="openai",        # Optional. Specific provider.
    temperature=0.7,          # Optional. 0.0–2.0 (default 0.7).
    max_tokens=2048,          # Optional. Max output tokens (default 2048).
)

Environment Variable Reference

Variable Description
SILKLLM_API_KEY Your silk_ API key

Response Fields

Field Type Description
content str The generated text
model str Model that handled the request
provider str Provider that handled the request
usage.prompt_tokens int Input tokens used
usage.completion_tokens int Output tokens generated
usage.total_tokens int Total tokens
cost_usd float Cost in USD (provider cost + 10% markup)
balance_after float Your remaining balance after this request

Metadata

Release files for silkllm 1.0.0

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

Source distribution (sdist)

Source distribution for silkllm 1.0.0
File Size Uploaded Provenance Actions
silkllm-1.0.0.tar.gz 8.5 kB Without provenance Details for silkllm-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for silkllm 1.0.0
File Interpreter ABI Platform Actions
silkllm-1.0.0-py3-none-any.whl Python 3 none any Details for silkllm-1.0.0-py3-none-any.whl

Total release size: 16.1 kB

Release files / silkllm-1.0.0.tar.gz

Download URL silkllm-1.0.0.tar.gz
Size 8.5 kB
Tags Source
SHA-256 checksum
How to use checksums
983b7e5fc81701a3302b976efb4c5e78a654cac0f38446a1c230a4b55f4fa42d
BLAKE2b-256 checksum
How to use checksums
58bf3b6251d4581d5b904eef1b56cae9f245097be634c606f72a69df0dc7c0ff
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.10.20

Release files / silkllm-1.0.0-py3-none-any.whl

Download URL silkllm-1.0.0-py3-none-any.whl
Size 7.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
6152d416be76651f9df985d75c6b7aebe15d388cefea8b4b1f108570cac6669b
BLAKE2b-256 checksum
How to use checksums
3d0adea450b88f42e50a764391ff2f62365c215172b13ccf3970a410ec2690fd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.10.20

Security for silkllm 1.0.0

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

1.0.0 This release

2 release files 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