Tutorial

Hello world: classify text in Python.

Send your first request, read the answer and its confidence score, then classify many texts at once. About 10 minutes, no libraries to install.

View OpenAPI spec
Example outputJSON
{
  "sentiment": {
    "value": "positive",
    "confidence": 0.99
  }
}

What you’ll build

In about 10 minutes you’ll have a Python script that labels text as positive, neutral, or negative, first for one text and then for ten at once.

The scripts use only Python’s standard library, so there’s nothing to install. You need Python 3.8 or later and a Svift API key.

Set up your key

Your key starts with svift_sk_ and is shown only once, when it’s created. Store it in an environment variable rather than in your code:

Terminal
export SVIFT_API_KEY="svift_sk_your_key_here"

Replace svift_sk_your_key_here with your own key. Keep the key on your server: never commit it to git or put it in a browser or mobile app. If a key leaks, ask us to revoke it and issue a new one.

Step 1: Send your first request

Every request goes to POST https://api.svift.ai/v1/run with three parts:

  • input: the text to process.
  • instructions (optional): what to do with it, in plain language.
  • output: the fields you want back. Here that’s one field, sentiment, which must be one of three values.

Save this as hello_svift.py:

hello_svift.py
import json
import os
import sys
import urllib.error
import urllib.request

API_URL = "https://api.svift.ai/v1/run"

api_key = os.environ.get("SVIFT_API_KEY")
if not api_key:
    sys.exit("Set SVIFT_API_KEY first.")

body = {
    "instructions": "Classify the sentiment of the text.",
    "input": "Hello world! I'm excited to try this new API.",
    "output": {
        "sentiment": {"type": "string", "enum": ["positive", "neutral", "negative"]},
    },
}

req = urllib.request.Request(
    API_URL,
    data=json.dumps(body).encode(),
    headers={
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
    },
    method="POST",
)

try:
    # Slow requests can take several minutes, so use a long timeout.
    with urllib.request.urlopen(req, timeout=420) as resp:
        result = json.load(resp)
except urllib.error.HTTPError as e:
    sys.exit(f"HTTP {e.code}: {e.read().decode()}")

print(json.dumps(result, indent=2, ensure_ascii=False))

Run it with python3 hello_svift.py. You should see something like this:

Response
{
  "request_id": "01a16054-d080-7712-88c5-a6178ca40695",
  "effort": "low",
  "output": {
    "sentiment": {"value": "positive", "confidence": 1}
  },
  "usage": {"input_tokens": 92, "output_fields": 1}
}

Step 2: Read the response

The answer is in output: each field you asked for comes back as a value and a confidence from 0 to 0.99.

FieldWhat it tells you
request_idA unique ID for this request. Include it if you contact support.
effortlow when no enum field was answered again, medium when at least one needed a reasoning step, high when at least one went to a larger model.
outputOne entry per requested field, in the order you listed them.
usage.input_tokensThe tokens in your request, counted once: your instructions, input and output schema. Above 2,000, every field costs 2 units.
usage.output_fieldsHow many fields were returned. Each one is charged: 1 unit, or 2 when usage.input_tokens is above 2,000.

If the model can’t give a valid answer for a field, it returns "value": null with "confidence": 0. Treat that as unknown.

Step 3: Classify many texts

Each request takes one input, so to classify ten texts you send ten requests. Sending them in parallel keeps it fast. Save this as hello_svift_batch.py:

hello_svift_batch.py
import json
import os
import sys
import urllib.error
import urllib.request
from concurrent.futures import ThreadPoolExecutor

API_URL = "https://api.svift.ai/v1/run"

ROWS = [
    "Hello world! I'm excited to try this new API.",
    "The delivery was late and the box was crushed.",
    "It works. Nothing special, nothing broken.",
    "Best customer support I've had in years, thank you!",
    "I've asked for a refund three times and nobody answers.",
    "The meeting is moved to Thursday at 10.",
    "Honestly the new update made everything slower.",
    "Love the colors, the fit is perfect.",
    "Not sure yet, I'll give it another week.",
    "Terrible. Uninstalled after five minutes.",
]

api_key = os.environ.get("SVIFT_API_KEY")
if not api_key:
    sys.exit("Set SVIFT_API_KEY first.")


def run(text):
    body = {
        "instructions": "Classify the sentiment of the text.",
        "input": text,
        "output": {
            "sentiment": {"type": "string", "enum": ["positive", "neutral", "negative"]},
        },
    }
    req = urllib.request.Request(
        API_URL,
        data=json.dumps(body).encode(),
        headers={
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json",
        },
        method="POST",
    )
    try:
        with urllib.request.urlopen(req, timeout=420) as resp:
            return json.load(resp)
    except urllib.error.HTTPError as e:
        return {"error": f"HTTP {e.code}: {e.read().decode()}"}


# Five requests at a time.
with ThreadPoolExecutor(max_workers=5) as pool:
    results = list(pool.map(run, ROWS))

for text, result in zip(ROWS, results):
    if "error" in result:
        print(f"ERROR  {text}: {result['error']}")
        continue
    field = result["output"]["sentiment"]
    print(f"{field['value']:<10} {field['confidence']:>5.2f}  {result['effort']:<6}  {text}")

Run it with python3 hello_svift_batch.py. The columns are the label, its confidence, and the effort:

Output
positive    0.99  low     Hello world! I'm excited to try this new API.
negative    0.99  low     The delivery was late and the box was crushed.
neutral     0.99  low     It works. Nothing special, nothing broken.
positive    0.99  low     Best customer support I've had in years, thank you!
negative    0.99  low     I've asked for a refund three times and nobody answers.
neutral     0.99  low     The meeting is moved to Thursday at 10.
negative    0.99  low     Honestly the new update made everything slower.
positive    0.99  low     Love the colors, the fit is perfect.
neutral     0.99  low     Not sure yet, I'll give it another week.
negative    0.99  low     Terrible. Uninstalled after five minutes.

If one request fails, that row prints the error and the others still run. This run costs 10 units, one per text.

Step 4: Check confidence and set the effort

Every field is answered by a fast model, and enum fields are also answered by a second model. If the models aren’t confident enough in an enum field, both answer that field again with reasoning, the majority wins, and effort becomes medium. The hardest fields then go to a larger model, and effort becomes high. The effort doesn’t change the price.

The answer is returned even if its confidence is still low, so decide what you need and check it yourself. As a guide:

confidenceLevel
≥ 0.9Very high
≥ 0.8High
≥ 0.7Medium
< 0.7Low

For example, to send low-confidence and unknown answers for review:

Python
field = result["output"]["sentiment"]
if field["value"] is None or field["confidence"] < 0.7:
    print("Needs human review:", text)

To control speed, add "max_effort": "low" to the request body. It sets the highest effort level the request may use: low (typically 0.2–0.5 s), medium (0.5–1.5 s), or high (1–10 s). The response’s effort tells you which level was used.

Next steps

Ask for more fields in the same request. You can ask for up to 16, each costing one unit, and a description tells the model what you want:

JSON
"output": {
  "sentiment": {"type": "string", "enum": ["positive", "neutral", "negative"]},
  "topic":     {"type": "string", "enum": ["product", "delivery", "support", "billing"]},
  "stars":     {"type": "integer", "minimum": 1, "maximum": 5, "description": "the rating the writer would likely give"},
  "summary":   {"type": "string", "max_length": 100, "description": "one sentence"}
}

Fields come back in the order you list them. Don’t rely on one field’s answer to decide another; to ask for a field only for some answers, use conditional fields. All field types, options, and limits are in the API documentation.

Let’s build what’s next

Show us your BS (and we’ll help you fix it).

Bring a real task. We’ll run it across the top models and show you where they make things up, which one wins, and what it costs.

Talk to us

Tell us a little about your use case and we’ll get back to you.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.