Swfte Python SDK
The official Python SDK for Swfte — the unified AI infrastructure platform giving teams one API for 200+ models from OpenAI, Anthropic, Google, Mistral, Meta and self-hosted GPU deployments, plus production-grade agents, workflows, chatflows, RAG, voice, and MCP servers.
About Swfte
Swfte is the unified AI infrastructure platform — one API for 200+ models from OpenAI, Anthropic, Google, Mistral, Meta and self-hosted GPU deployments, plus production-grade agents, workflows, chatflows, RAG, voice, and MCP servers.
Read the full company profile in ABOUT.md, or visit swfte.com to get started for free.
| Resource | Link |
|---|---|
| Product home | https://www.swfte.com |
| Documentation | swfte.com/resources |
| API reference | swfte.com/developers |
| Pricing | swfte.com/pricing |
| Security | swfte.com/security |
| Status | status.swfte.com |
| GitHub org | github.com/SwfteAI |
Other official Swfte SDKs
- swfte-python — Python SDK (PyPI)
- swfte-node — Node.js / TypeScript SDK (npm)
- swfte-java — Java SDK (Maven Central)
- swfte-chat-widget — embeddable chat widget (npm)
- swfte-chatflow-widget — embeddable conversational form widget (npm)
Documentation
Full API reference and guides are available at swfte.com/developers. Runnable Python recipes for the top-15 V2 controllers live in docs/cookbook/.
Installation
pip install swfte-sdk # the package is swfte-sdk; you import it as `swfte`
Quick Start
from swfte import SwfteClient
client = SwfteClient(api_key="sk-swfte-...")
response = client.chat.completions.create(
model="openai:gpt-4",
messages=[{"role": "user", "content": "Hello, world!"}],
)
print(response["choices"][0]["message"]["content"])
Usage
Chat Completions
response = client.chat.completions.create(
model="anthropic:claude-3-opus",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Explain quantum computing in one sentence."},
],
temperature=0.7,
max_tokens=256,
)
Streaming
stream = client.chat.completions.create(
model="openai:gpt-4",
messages=[{"role": "user", "content": "Write a short poem."}],
stream=True,
)
for chunk in stream:
content = chunk.get("choices", [{}])[0].get("delta", {}).get("content", "")
print(content, end="", flush=True)
Agents
# Create an agent
agent = client.agents.create(
name="Research Assistant",
system_prompt="You are a research assistant specializing in AI.",
provider="OPENAI",
model="gpt-4",
)
# List agents
agents = client.agents.list()
# Update an agent
client.agents.update(agent.id, description="Updated description")
# Chat with an agent: POST /v1/agents/{id}/chat/{user_id}, reply text in .response
reply = client.agents.chat(agent.id, "What changed in Q3?", user_id="user-42")
print(reply.response)
# Continue the same conversation (user_id defaults to "sdk-user" when omitted)
follow_up = client.agents.chat(
agent.id, "And Q4?", user_id="user-42", conversation_id=reply.conversation_id
)
# Delete an agent
client.agents.delete(agent.id)
Workflows
# Create a workflow
workflow = client.workflows.create(
name="Content Pipeline",
nodes=[
{"id": "start", "type": "TRIGGER", "config": {"triggerType": "MANUAL"}},
{"id": "llm", "type": "LLM", "config": {"model": "gpt-4", "prompt": "Summarize: {{input}}"}},
{"id": "end", "type": "END", "config": {}},
],
edges=[
{"id": "e1", "source": "start", "target": "llm"},
{"id": "e2", "source": "llm", "target": "end"},
],
)
# Production: run the PUBLISHED version (POST /v2/workflows/{id}/invoke, 202 + executionId)
invocation = client.workflows.invoke(workflow.id, {"input": "Hello"})
status = client.workflows.get_execution_status(invocation.execution_id)
print(status.status_raw, status.progress)
# ...or invoke and poll until the run finishes (timeout/poll_interval in seconds)
from swfte import WorkflowExecutionError, WorkflowTimeoutError
try:
done = client.workflows.invoke_and_wait(
workflow.id, {"input": "Hello"}, timeout=120, poll_interval=2
)
print(done.status_raw, done.outputs) # SUCCESS / SUCCEEDED / COMPLETED
except WorkflowExecutionError as err: # FAILED, TIMEOUT, CANCELLED/CANCELED
print("run ended", err.status, err)
except WorkflowTimeoutError as err: # gave up polling; the run continues
print("still running", err.execution_id)
# Test run of the current (unpublished) definition — Studio's draft path
execution = client.workflows.execute(workflow.id, {"input": "Hello", "testingFlag": True})
invoke() runs the published snapshot and is what production callers should
use; unpublished edits do not affect it, and a never-published workflow answers
409. execute() runs the editable definition (the draft) and exists for test
runs. Neither is retried by the SDK, so a network blip never starts a run twice.
Catalog
# Find proven artifacts across kinds
page = client.catalog.search(
q="invoice triage",
kinds=["workflow", "agent"],
scope="all",
min_evidence="corroborated",
limit=10,
)
for item in page["items"]:
print(item["catalogRef"], item["evidence"]["level"])
# Evidence, reviews and dependencies for one entry
detail = client.catalog.get("workflow", page["items"][0]["id"])
# How to call it: method, path, input/output JSON Schema and code snippets
contract = client.catalog.contract("workflow", page["items"][0]["id"])
print(contract["invoke"]["method"], contract["invoke"]["path"])
GPU Model Deployments
# Deploy a model to GPU infrastructure
deployment = client.deployments.create(
model_name="meta-llama/Llama-3.2-8B-Instruct",
model_type="chat",
)
# Wait for deployment to be ready
ready = client.deployments.wait_for_ready(deployment.id, timeout_ms=600000)
print(f"Endpoint: {ready.endpoint_url}")
# Clean up
client.deployments.delete(deployment.id)
Images
response = client.images.generate(
model="openai:dall-e-3",
prompt="A sunset over a mountain range, oil painting style",
size="1024x1024",
quality="hd",
)
Embeddings
response = client.embeddings.create(
model="openai:text-embedding-3-small",
input="The quick brown fox jumps over the lazy dog",
)
Audio
# Speech to text
transcript = client.audio.transcriptions.create(
model="openai:whisper-1",
file=open("recording.mp3", "rb").read(),
)
# Text to speech
audio_bytes = client.audio.speech.create(
model="openai:tts-1",
input="Hello, welcome to Swfte.",
voice="alloy",
)
Secrets
# Store an API key securely
secret = client.secrets.create(
name="my-api-key",
secret_type="API_KEY",
value="sk-...",
environment="production",
)
# Validate a secret
is_valid = client.secrets.validate(secret.id)
ChatFlows, Datasets, RAG, MCP, Voice and more (V2)
Version 1.1.0 adds first-class clients for the full V2 surface. See docs/cookbook/ for a runnable example per resource.
# ChatFlows — conversational forms with field extraction and branching
flow = client.chatflows.create({"name": "Lead Q", "fields": [...]})
client.chatflows.deploy(flow["id"])
session = client.chatflows.start_session(flow["id"], channel="WEB")
# RAG — hybrid search and reranking
hits = client.rag.search(query="refund policy", dataset_ids=["ds-faq"], top_k=5)
# MCP — connect a remote tool server, list and execute tools
client.mcp.connect_server("hubspot", endpoint="https://mcp.example.com/sse")
result = client.mcp.execute("hubspot.create_contact", {"email": "ada@example.com"})
# Voice — list calls, fetch transcripts and recordings
calls = client.voice_calls.list(status="completed")
transcript = client.voice_calls.transcript(calls["content"][0]["sid"])
# Cost control — enforce caps and routing rules
client.cost_control.set_workspace_cap({"period": "MONTH", "currency": "USD", "limit": 1000})
Other clients exposed on SwfteClient: client.datasets, client.documents, client.files, client.modules, client.marketplace, client.audit, client.agent_wizard.
Conversations
# Create a conversation
conversation = client.conversations.create(title="Support Chat")
# Add messages
client.conversations.add_message(conversation.id, role="user", content="Hello!")
client.conversations.add_message(conversation.id, role="assistant", content="Hi there!")
# Retrieve message history
messages = client.conversations.get_messages(conversation.id)
Configuration
client = SwfteClient(
api_key="sk-swfte-...", # Required. Also reads SWFTE_API_KEY env var.
base_url="https://api.swfte.com/agents/v2/gateway", # Default
timeout=60, # Request timeout in seconds
max_retries=3, # Chat attempts after a pre-send connect timeout only
workspace_id="ws-...", # Workspace scoping. Also reads SWFTE_WORKSPACE_ID.
# api_base_url="https://api.swfte.com/agents", # Optional; derived from base_url
)
| Parameter | Type | Default | Description |
|---|---|---|---|
api_key |
str |
SWFTE_API_KEY env |
Your Swfte API key (sk-swfte-...) or personal access token (pat_...) |
base_url |
str |
https://api.swfte.com/agents/v2/gateway |
Gateway URL (chat completions, images, embeddings, audio, models) |
api_base_url |
str |
SWFTE_API_BASE_URL env, else base_url minus /v2/gateway, /v1/gateway or /gateway |
agents-service root used by agents, workflows, catalog and the other management resources |
timeout |
int |
60 |
Request timeout (seconds) |
max_retries |
int |
3 |
Attempts for non-streaming chat only after requests.exceptions.ConnectTimeout, which occurs before sending. Generic connection errors, read timeouts, HTTP errors and all other calls are never retried. Values below 1 mean one attempt |
workspace_id |
str |
SWFTE_WORKSPACE_ID env |
Workspace ID |
Error Handling
from swfte import SwfteClient, AuthenticationError, RateLimitError, APIError
client = SwfteClient(api_key="sk-swfte-...")
try:
response = client.chat.completions.create(
model="openai:gpt-4",
messages=[{"role": "user", "content": "Hello"}],
)
except AuthenticationError:
print("Invalid API key")
except RateLimitError:
print("Rate limit exceeded, retry later")
except APIError as e:
print(f"API error: {e}")
| Exception | Description |
|---|---|
SwfteError |
Base exception for all SDK errors |
AuthenticationError |
Invalid or missing API key |
RateLimitError |
Rate limit exceeded (HTTP 429) |
APIError |
General API error; status_code and parsed body are set by agents.chat, workflows.invoke*, get_execution_status, catalog.* |
InvalidRequestError |
Malformed request (HTTP 400), or a missing required argument caught before the call |
WorkflowExecutionError |
invoke_and_wait / wait_for_completion: the run ended FAILED, TIMEOUT or CANCELLED/CANCELED (also a RuntimeError) |
WorkflowTimeoutError |
invoke_and_wait / wait_for_completion: gave up polling; the run is not cancelled (also a TimeoutError) |
Every call maps 401/403 to AuthenticationError and 429 to RateLimitError.
Other HTTP errors are APIError (chat, agents.chat, workflows.invoke*,
get_execution_status, catalog.*) or requests.HTTPError (the remaining
management resources).
Supported Providers
| Provider | Models | Qualifier Prefix |
|---|---|---|
| OpenAI | GPT-4, GPT-4o, o1, DALL-E, Whisper, TTS | openai: |
| Anthropic | Claude 3.5, Claude 3 Opus/Sonnet/Haiku | anthropic: |
| Gemini 2.0, Gemini 1.5 Pro/Flash | google: |
|
| Self-hosted | Any model via RunPod/vLLM deployment | runpod: |
Requirements
- Python 3.10 or later
requests>= 2.32.4urllib3>= 2.8.0
Contributing
We welcome contributions. Please see CONTRIBUTING.md for guidelines and our Code of Conduct.
All contributors must sign the Swfte CLA before their first pull request can be merged.
Security
- API key handling. Pass the key with
api_key=orSWFTE_API_KEY; do not commit it. The key is sent only as anAuthorization: Bearerheader and is not retained in ordinaryvars(client)orrepr(client), and SDK failure diagnostics redact it. Clients cannot be pickled. Explicitclient.api_keyaccess remains available for compatibility; avoid logging it or request headers. Successful API values are returned unchanged. The SDK does not log. - TLS. Certificates are always verified. A
base_url/api_base_url(orSWFTE_API_BASE_URL) that useshttp://to a non-loopback host raisesInvalidRequestErrorwhen the client is constructed, because the key would travel in cleartext.http://is accepted only forlocalhost,127.0.0.1and::1. - Retries. Only
chat.completions.create(non-streaming) retries, up tomax_retriesattempts, and only afterConnectTimeoutbefore the request body was sent. GenericConnectionErrorcan mean a lost response after the server already executed the call; it is never retried. Read timeouts, HTTP errors (including 401/403/429/5xx) and every other call are not retried, so a call that may already have run is never repeated. - Timeouts. Every request has a timeout (
timeout, 60 seconds by default). - Redirects. SDK requests never follow redirects, including 302 and 307.
A redirect raises
APIErrorwith its HTTP status and response body. StrippingAuthorizationalone would still forward prompts, files or audio on 307/308. Configure the final endpoint URL directly instead of depending on redirects.
Report vulnerabilities to security@swfte.com (see SECURITY.md).
License
This project is licensed under the MIT License. See LICENSE for details.
Copyright (c) 2024-2026 Swfte, Inc.
Resources
- Swfte — product home
- swfte.com/resources — guides, cookbooks, recipes
- swfte.com/developers — full API reference
- swfte.com/pricing — pay-as-you-go, transparent pricing
- swfte.com/security — security posture and compliance
- status.swfte.com — uptime and incident history
- swfte.com/marketplace — agent, workflow and tool marketplace
Other official Swfte SDKs
- swfte-python — this repo (PyPI)
- swfte-node — Node.js / TypeScript SDK (npm)
- swfte-java — Java SDK (Maven Central)
- swfte-chat-widget — embeddable chat widget (npm)
- swfte-chatflow-widget — embeddable conversational form widget (npm)
Metadata
Release files for swfte-sdk 1.2.0
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 |
|---|---|---|---|---|
| swfte_sdk-1.2.0.tar.gz | 84.0 kB | Without provenance | Details for swfte_sdk-1.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| swfte_sdk-1.2.0-py3-none-any.whl | Python 3 | none | any | Details for swfte_sdk-1.2.0-py3-none-any.whl |
Total release size: 178.4 kB
Release files / swfte_sdk-1.2.0.tar.gz
| Download URL | swfte_sdk-1.2.0.tar.gz |
|---|---|
| Size | 84.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
7a2f1eb1a34d160cd6a634b62d8c96114319704365632949b6b9922429910976
|
|
BLAKE2b-256 checksum How to use checksums |
8ff6160f5ef2837f46d778aa404decec6aa7be1269a1bdcbc83c206d63a0c93e
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.13
|
Release files / swfte_sdk-1.2.0-py3-none-any.whl
| Download URL | swfte_sdk-1.2.0-py3-none-any.whl |
|---|---|
| Size | 94.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
7f996b3c1f6cae6d218aca5172906ca23cd4a26c9e2e11c9efa45dce4f1a8401
|
|
BLAKE2b-256 checksum How to use checksums |
afa84e8bb1ac110fb4feb950600415626cccf6dda2f2549e6334b7b045a241f1
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.13
|
Security for swfte-sdk 1.2.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.