SDK Reference

SDK Reference

First-party SDKs for Python and TypeScript. Both target the Wayforth gateway at gateway.wayforth.io, include retry logic, and ship with typed error classes.

Python SDK

bash
pip install wayforth-sdk

Requires Python 3.12+. The only runtime dependency is httpx >= 0.27.

Quick start

python
from wayforth import Wayforth

client = Wayforth(api_key="wf_live_...")

results = client.search("translate to spanish")
print(results[0]["name"])  # DeepL Translation

result = client.execute("deepl", text="Hello", target_lang="ES")
print(result["translation"])  # Hola

result = client.run("translate Hello to Spanish")
print(result["output"])  # Hola

Wayforth (sync)

Synchronous client backed by httpx.Client. Supports context manager usage.

class Wayforth(
  api_key: str,
  base_url: str = "https://gateway.wayforth.io"
)

Methods

search()

search(query: str, **filters) -> list[dict]

Natural language search. Supports filters: max_price_usd, tier, payment_rail, region, limit.

python
results = client.search(
    "image classification",
    tier=2,
    max_price_usd=0.01,
    region="eu-west",
    limit=5
)
for svc in results:
    print(svc["slug"], svc["wri_score"])

query()

query(ql: str) -> list[dict]

WayforthQL structured query. See WayforthQL v1.1 for syntax.

python
results = client.query(
    "category:vision AND tier:>=3 SORT BY wri_score DESC LIMIT 5"
)

execute()

execute(slug: str, **params) -> dict

Execute a managed service. Parameters are service-specific.

python
# Translation
result = client.execute("deepl", text="Bonjour", target_lang="EN")

# Embeddings
result = client.execute(
    "openai-embeddings",
    input="The quick brown fox",
    model="text-embedding-3-large"
)
print(len(result["embedding"]))  # 3072

# Transcription
result = client.execute(
    "whisper-large",
    audio_url="https://example.com/recording.mp3",
    language="en"
)

run()

run(query: str, **params) -> dict

Find the best match and execute in one call. Wayforth selects the service with the highest relevance × WRI score.

python
result = client.run(
    "transcribe this audio to English",
    audio_url="https://example.com/clip.mp3"
)
print(result["output"])   # "Hello, this is a test recording"
print(result["service"])  # "whisper-large"

balance()

balance() -> dict

Returns account credits, tier, and usage forecast.

python
info = client.balance()
print(info["credits_remaining"])  # 847
print(info["tier"])               # "builder"
print(info["forecast"]["will_exhaust_before_reset"])  # False

services()

services(category: str | None = None) -> list[dict]

Browse the service catalog. Optionally filter by category slug.

python
all_services = client.services()
audio_services = client.services(category="audio")
for svc in audio_services:
    print(f"{svc['slug']:20} WRI {svc['wri_score']}")

Context manager

python
with Wayforth(api_key="wf_live_...") as client:
    results = client.search("translate to french")
    # Connection pool closed automatically on exit

AsyncWayforth

Async client backed by httpx.AsyncClient. Drop-in async equivalent — all method signatures are identical, just add await.

python
import asyncio
from wayforth import AsyncWayforth

async def main():
    async with AsyncWayforth(api_key="wf_live_...") as client:
        # Run searches concurrently
        search, balance = await asyncio.gather(
            client.search("translate to spanish"),
            client.balance(),
        )
        print(search[0]["name"])
        print(balance["credits_remaining"])

        # Execute
        result = await client.execute("deepl", text="Hello", target_lang="ES")
        print(result["translation"])

asyncio.run(main())

Concurrent execution

python
import asyncio
from wayforth import AsyncWayforth

async def batch_translate(texts: list[str], target_lang: str) -> list[str]:
    async with AsyncWayforth(api_key="wf_live_...") as client:
        tasks = [
            client.execute("deepl", text=t, target_lang=target_lang)
            for t in texts
        ]
        results = await asyncio.gather(*tasks)
        return [r["translation"] for r in results]

translated = asyncio.run(batch_translate(
    ["Hello", "Good morning", "Goodbye"],
    target_lang="ES"
))
# ["Hola", "Buenos días", "Adiós"]

Python error handling

python
from wayforth import (
    WayforthError,
    AuthenticationError,        # 401
    InsufficientCreditsError,   # 402
    ServiceUnavailableError,    # 5xx after 3 retries
)

try:
    result = client.execute("deepl", text="Hello", target_lang="ES")
except AuthenticationError:
    print("Invalid API key — check WAYFORTH_API_KEY")
except InsufficientCreditsError:
    print("Out of credits — top up at https://wayforth.io/billing")
except ServiceUnavailableError as e:
    print(f"Service down after retries: {e}")
except WayforthError as e:
    print(f"API error {e.status_code}: {e}")

Retry policy

Both Wayforth and AsyncWayforth automatically retry on 5xx responses with exponential backoff. Client errors (4xx) are raised immediately.

AttemptDelay before retry
1— (immediate)
21 second
32 seconds
4 (final)4 seconds — raises ServiceUnavailableError

TypeScript SDK

bash
npm install @wayforth/sdk

Requires Node.js 18+. No runtime dependencies — uses native fetch. Dual ESM + CommonJS export.

Quick start

typescript
import { Wayforth } from '@wayforth/sdk';

const wayforth = new Wayforth({ apiKey: 'wf_live_...' });

const results = await wayforth.search('translate to spanish');
console.log(results[0].name);  // DeepL Translation

const result = await wayforth.execute('deepl', { text: 'Hello', target_lang: 'ES' });
console.log(result.translation);  // Hola

const run = await wayforth.run('translate Hello to Spanish');
console.log(run.output);  // Hola

Wayforth class

new Wayforth({ apiKey: string; baseUrl?: string })

search()

search(query: string, options?: SearchOptions): Promise<SearchResult[]>
typescript
const results = await wayforth.search('image classification', {
  max_price_usd: 0.01,
  tier: 2,
  region: 'us-east',
  limit: 5,
});
results.forEach(r => console.log(r.slug, r.wri_score));

query()

query(ql: string): Promise<SearchResult[]>
typescript
const results = await wayforth.query(
  'category:nlp AND tier:>=3 SORT BY wri_score DESC'
);

execute()

execute(slug: string, params?: Record<string, unknown>): Promise<ExecuteResult>
typescript
const result = await wayforth.execute('deepl', {
  text: 'Hello, world!',
  target_lang: 'FR',
});
console.log(result.translation);  // Bonjour, le monde!

run()

run(query: string, params?: Record<string, unknown>): Promise<RunResult>
typescript
const result = await wayforth.run('transcribe this audio', {
  audio_url: 'https://example.com/clip.mp3',
});
console.log(result.output);   // "Hello, this is a test..."
console.log(result.service);  // "whisper-large"

balance()

balance(): Promise<BalanceResult>
typescript
const bal = await wayforth.balance();
console.log(bal.credits_remaining);  // 847
console.log(bal.tier);               // "builder"

services()

services(category?: string): Promise<SearchResult[]>
typescript
const all = await wayforth.services();
const audio = await wayforth.services('audio');

Factory function

typescript
import { createWayforth } from '@wayforth/sdk';

const wayforth = createWayforth({
  apiKey: process.env.WAYFORTH_API_KEY!,
  baseUrl: 'https://gateway.wayforth.io',  // optional override
});

TypeScript types

typescript
interface WayforthConfig {
  apiKey: string;
  baseUrl?: string;
}

interface SearchOptions {
  max_price_usd?: number;
  tier?: number;
  payment_rail?: string;
  region?: string;
  limit?: number;
}

interface SearchResult {
  slug: string;
  name: string;
  description: string;
  wri_score: number;
  tier: number;
  payment_rails: string[];
  category: string;
}

interface ExecuteResult {
  [key: string]: unknown;
}

interface RunResult {
  output: unknown;
  service: string;
}

interface BalanceResult {
  credits_remaining: number;
  tier: string;
  usage: unknown;
}

TypeScript error handling

typescript
import {
  Wayforth,
  WayforthError,
  AuthenticationError,
  InsufficientCreditsError,
  ServiceUnavailableError,
} from '@wayforth/sdk';

const wayforth = new Wayforth({ apiKey: process.env.WAYFORTH_API_KEY! });

try {
  const result = await wayforth.execute('deepl', {
    text: 'Hello',
    target_lang: 'ES',
  });
} catch (err) {
  if (err instanceof AuthenticationError) {
    console.error('Invalid API key');
  } else if (err instanceof InsufficientCreditsError) {
    console.error('Out of credits — visit https://wayforth.io/billing');
  } else if (err instanceof ServiceUnavailableError) {
    console.error(`Service down after retries: ${err.message}`);
  } else if (err instanceof WayforthError) {
    console.error(`API error ${err.statusCode}: ${err.message}`);
  }
}

Error classes

ClassHTTP statusDescription
AuthenticationError401Invalid or missing API key
InsufficientCreditsError402No credits remaining
ServiceUnavailableError5xxProvider down after 3 retries
WayforthErrorAny 4xx/5xxBase class — check statusCode