Skip to main content

gastarbeiter

The Python client for the Gastarbeiter API: an OpenAI-compatible API for models and for services, which are pipelines of model calls.

It is a thin layer on the official openai package. Gastarbeiter and AsyncGastarbeiter are the OpenAI SDK's clients with a Gastarbeiter key and base URL. They add three things the OpenAI SDK doesn't have:

  • rerank: score documents against a query.
  • classifications: zero-shot classification into your own labels.
  • services: run a graph of model calls and steps in one request.

They also raise their own exceptions for the API's error codes.

Install

uv add gastarbeiter

or

pip install gastarbeiter

Python 3.10 or newer.

Quickstart

Access is by invitation for now.

  1. Sign in at demo.gastarbeiter.ai and create a key under API-Schlüssel (demo.gastarbeiter.ai/api-keys). Keys look like ga_live_..., and the portal shows each one only once.
  2. Calls are billed from your account's credit. A new account starts at 0 €, and there is no self-service top-up yet: ask us for credit.
  3. Put the key in the environment:
export GASTARBEITER_API_KEY=ga_live_...

Then chat with a model:

from gastarbeiter import Gastarbeiter

client = Gastarbeiter()  # reads GASTARBEITER_API_KEY

reply = client.chat.completions.create(
    model="gpt-oss-20b",
    messages=[{"role": "user", "content": "Hallo!"}],
)
print(reply.choices[0].message.content)

And run a saved service by its svc_ id, which its page in the portal shows together with an example input:

run = client.services.runs.create(
    service="svc_...",
    input={"ticket": "I was charged twice this month."},
)
print(run.output)

client.models.list() shows which models your key can use. To check your key and every endpoint at once:

python -m gastarbeiter.check                       # models, chat, streaming, services
python -m gastarbeiter.check --service svc_... --input '{"ticket": "..."}'   # also a saved service

It runs one small call of each kind, prints ok or FAILED per line, and costs a few cents of credit. It never prints your key.

Where the models run: for now, the chat models answer through Ollama Cloud, a hosted service that is not ours, so your chat prompts and answers pass through it. The embedding, rerank and classification models run on our own servers.

Configuration

Setting Argument Environment variable Default
API key api_key= GASTARBEITER_API_KEY none, the client raises GastarbeiterError without one
Base URL base_url= GASTARBEITER_BASE_URL https://api.gastarbeiter.ai/v1

An argument wins over the environment variable. The client never reads OPENAI_API_KEY, and it doesn't send the OpenAI-Organization or OpenAI-Project headers even when OPENAI_ORG_ID or OPENAI_PROJECT_ID are set.

client = Gastarbeiter(api_key="ga_live_...", base_url="https://api.gastarbeiter.ai/v1")

The clients are the OpenAI SDK's, so its other constructor options work as documented there: timeout, max_retries, default_headers, default_query and http_client.

client = Gastarbeiter(timeout=30.0, max_retries=5)

with_options gives a copy with other options, for one call or a few:

client.with_options(timeout=5.0).models.list()

chat, embeddings and models are the OpenAI SDK's own resources, so per-request options such as timeout= and with_raw_response work on them unchanged:

raw = client.chat.completions.with_raw_response.create(
    model="gpt-oss-20b",
    messages=[{"role": "user", "content": "Hallo!"}],
)
print(raw.headers.get("x-request-id"))
reply = raw.parse()

rerank, classifications and services take timeout=, extra_headers=, extra_query= and extra_body= per request, but have no with_raw_response.

Models

for model in client.models.list():
    print(model.id, model.task)

Each model has a task: chat, embedding, rerank or classification. A model only works with the endpoint for its task. The examples below use placeholder ids like your-embedding-model; replace them with ids from this list.

Chat

reply = client.chat.completions.create(
    model="gpt-oss-20b",
    messages=[
        {"role": "system", "content": "Answer in one sentence."},
        {"role": "user", "content": "Was ist ein Gastarbeiter?"},
    ],
)
print(reply.choices[0].message.content)

Streaming

stream = client.chat.completions.create(
    model="gpt-oss-20b",
    messages=[{"role": "user", "content": "Count to ten."}],
    stream=True,
)
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)

Embeddings

result = client.embeddings.create(
    model="your-embedding-model",
    input=["Rechnung nicht erhalten", "Passwort vergessen"],
)
vectors = [item.embedding for item in result.data]

Rerank

Scores documents by how well they answer a query, best first. Documents are strings or {"text": ...}, 1 to 1000 of them.

result = client.rerank.create(
    model="your-rerank-model",
    query="How do I reset my password?",
    documents=[
        "Invoices are sent on the first of each month.",
        "Use 'Forgot password' on the sign-in page.",
        "Our office is in Berlin.",
    ],
    top_n=2,                # optional: keep only the best two
    return_documents=True,  # optional: include each document's text
)
for r in result.results:
    print(r.index, r.relevance_score, r.document.text if r.document else None)

r.index is the document's position in documents.

Classifications

Zero-shot classification: score one text against 2 to 50 labels you choose.

result = client.classifications.create(
    model="your-classification-model",
    input="I was charged twice this month.",
    labels=["billing", "access", "other"],
)
print(result.label)   # the label with the highest score, e.g. "billing"
print(result.scores)  # score per label, e.g. {"billing": 0.91, "access": 0.04, "other": 0.05}

result.top is the best ClassificationResult (label and score), and result.results holds all of them.

Services

A service is a graph of nodes joined by edges. You send the whole graph with each run. Build it in the service editor at demo.gastarbeiter.ai and export it, or write it as a dict.

Node types are input, output, model, similar, template, route, transform and merge. An edge connects an output port (sourceHandle) of one node to an input port (targetHandle) of another. A model node's ports depend on the model's task: a chat model reads prompt, a classification or embedding model reads text, and every model writes output.

This service classifies a support ticket, then has a chat model write a reply that knows the category:

graph = {
    "nodes": [
        {"id": "in", "type": "input", "data": {"fields": [{"name": "ticket", "type": "text"}]}},
        {"id": "classify", "type": "model", "data": {
            "model": "your-classification-model",
            "labels": ["billing", "access", "other"],
        }},
        {"id": "prompt", "type": "template", "data": {
            "template": "Category: {{classify.label}}\n\nTicket: {{ticket}}",
        }},
        {"id": "reply", "type": "model", "data": {
            "model": "gpt-oss-20b",
            "instructions": "Write a short, polite reply to this support ticket.",
        }},
        {"id": "out", "type": "output", "data": {"fields": [{"name": "category"}, {"name": "reply"}]}},
    ],
    "edges": [
        {"source": "in", "sourceHandle": "ticket", "target": "classify", "targetHandle": "text"},
        {"source": "in", "sourceHandle": "ticket", "target": "prompt", "targetHandle": "ticket"},
        {"source": "classify", "sourceHandle": "output", "target": "prompt", "targetHandle": "classify"},
        {"source": "prompt", "sourceHandle": "output", "target": "reply", "targetHandle": "prompt"},
        {"source": "classify", "sourceHandle": "output", "target": "out", "targetHandle": "category"},
        {"source": "reply", "sourceHandle": "output", "target": "out", "targetHandle": "reply"},
    ],
}

A template node gets one input port per placeholder name: {{ticket}} and {{classify.label}} make the ports ticket and classify.

Validate

services.validate checks a graph without running it. It costs nothing. A graph with problems is not an error: valid is False and problems says what is wrong.

check = client.services.validate(graph=graph)
if check.valid:
    print([port.name for port in check.inputs])  # ["ticket"]
    print(check.outputs)                         # ["category", "reply"]
else:
    for problem in check.problems:
        print(problem.node or problem.edge, problem.message)

Run

run = client.services.runs.create(
    graph=graph,
    input={"ticket": "I was charged twice this month."},
    trace=True,
)
print(run.output["category"]["label"])
print(run.output["reply"])
print(run.usage.cost_micro_cents)  # millionths of a cent

for step in run.trace:
    print(step.node, step.status, step.latency_ms, step.cost_micro_cents)

run.output holds the fields of the output node. run.trace is only there with trace=True; it lists what each node did. Every model call in a run is billed as its own request. The service itself adds no fee.

graph is a plain dict. The gastarbeiter.types module has TypedDicts (FlowGraph, FlowNode, FlowEdge) if you want your type checker to check it.

Run a saved service

A service saved in the portal runs by its svc_ id. That runs its live version, whatever happens to its draft, and bills you, also when someone else shared the service with you:

run = client.services.runs.create(
    service="svc_4f9KpQ2xLm7a",
    input={"ticket": "I was charged twice this month."},
)
print(run.version)  # the live version's number

If you may see the service's graph, version= runs an older version and trace=True returns the trace. Its owner can also pass version="draft".

Services used to be called flows. client.flows still works, with a DeprecationWarning, and calls the same endpoints as client.services. The old names FlowRun, FlowValidation, InvalidFlowError, FlowNodeFailedError and FlowTimeoutError are the same classes as the new ones. The API's old paths /v1/flows/runs and /v1/flows/validate keep working until 2027-03-31.

Async

AsyncGastarbeiter has the same methods. Await them.

import asyncio

from gastarbeiter import AsyncGastarbeiter


async def main() -> None:
    client = AsyncGastarbeiter()

    reply = await client.chat.completions.create(
        model="gpt-oss-20b",
        messages=[{"role": "user", "content": "Hallo!"}],
    )
    print(reply.choices[0].message.content)

    result = await client.classifications.create(
        model="your-classification-model",
        input="I can't sign in.",
        labels=["billing", "access", "other"],
    )
    print(result.label)

    stream = await client.chat.completions.create(
        model="gpt-oss-20b",
        messages=[{"role": "user", "content": "Count to ten."}],
        stream=True,
    )
    async for chunk in stream:
        if chunk.choices and chunk.choices[0].delta.content:
            print(chunk.choices[0].delta.content, end="", flush=True)


asyncio.run(main())

Errors

For the API's own error codes the client raises the exceptions below, all importable from gastarbeiter. Each one subclasses gastarbeiter.GastarbeiterAPIError and, where there is one, the openai exception for its status, so code that already catches openai.RateLimitError or openai.BadRequestError keeps working.

Exception Status Code What to do
ContentPolicyViolationError 400 content_policy_violation Moderation blocked the input. It isn't billed. Change the input. Repeated violations suspend the account for a while.
InvalidServiceError 400 invalid_service The service's graph doesn't compile. e.problems lists what is wrong.
InsufficientCreditError 402 insufficient_quota The credit doesn't cover the request. Ask us for credit; there is no self-service top-up yet.
AccountSuspendedError 403 api_key_suspended The account is suspended, for example after repeated content policy violations. Wait until the suspension ends.
ServiceNodeFailedError 422, 502 service_node_failed A node failed during a service run (502: the model server behind it failed). e.node says which one.
RateLimitError 429 rate_limit_exceeded Too many requests per minute, per key or per account. The client already retries these. e.retry_after is the wait the server asked for, in seconds.
ServiceUnavailableError 503 model_unavailable, model_overloaded, moderation_unavailable, service_unavailable The model is down or busy, or moderation or the service is down for now. The client already retries these. Retry later.
ServiceTimeoutError 504 service_timeout The service run took longer than the gateway allows. Make the service smaller or faster.

InsufficientCreditError subclasses openai.APIStatusError, because the OpenAI SDK has no exception for 402, and so does ServiceNodeFailedError, whose status varies. The others subclass openai.BadRequestError, openai.PermissionDeniedError, openai.RateLimitError or openai.InternalServerError, by status.

Every API exception has status_code, code, message and request_id. Send us the request_id when you report a problem.

In a service run, a refusal about the account (402, 403, 429) raises the same exception as a direct request, with e.node set to the node whose model call was refused. If the run was sent with trace=True, e.trace holds what each node did before it failed.

Other errors raise the OpenAI SDK's exceptions, which gastarbeiter re-exports. e.code tells them apart:

Exception Status Code
AuthenticationError 401 invalid_api_key
BadRequestError 400 for example invalid_request or context_length_exceeded
PermissionDeniedError 403 trace_not_allowed, version_not_allowed, draft_not_allowed: you may run the service, but not see its graph, run another version, or run its draft
NotFoundError 404 model_not_found, service_not_found, version_not_found
ConflictError 409 service_not_live: the service has no live version yet
InternalServerError 502 upstream_error, upstream_unavailable: the model server failed

APIConnectionError or APITimeoutError is raised when the API can't be reached. GastarbeiterError is raised by the client itself, for example when no API key is set.

import gastarbeiter
from gastarbeiter import Gastarbeiter

client = Gastarbeiter()

try:
    reply = client.chat.completions.create(
        model="gpt-oss-20b",
        messages=[{"role": "user", "content": "Hallo!"}],
    )
except gastarbeiter.InsufficientCreditError:
    print("Out of credit. Ask us for more.")
except gastarbeiter.ContentPolicyViolationError as e:
    print("Input blocked:", e.message)
except gastarbeiter.RateLimitError as e:
    print("Still rate limited after retries. Wait", e.retry_after, "seconds.")
except gastarbeiter.APIStatusError as e:
    print(e.status_code, e.code, e.message, e.request_id)

Blocked answers

Moderation also checks what a chat model writes. A blocked answer is not an exception: it comes back with empty content and finish_reason == "content_filter". It is billed.

choice = reply.choices[0]
if choice.finish_reason == "content_filter":
    print("The answer was blocked by moderation.")

A blocked stream ends early, with a last chunk whose finish_reason is "content_filter". Some of the answer may already have arrived before the cut.

Retries

Like the OpenAI SDK, the client retries connection errors, 408, 409, 429 and 5xx responses, twice by default, with a growing wait. Set max_retries on the client to change that.

Service runs are the exception: services.runs.create doesn't retry, because a retry runs the whole service again and bills its model calls again. Pass max_retries= to that call if you want retries anyway.

License

MIT

Metadata

Release files for gastarbeiter 0.2.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 gastarbeiter 0.2.0
File Size Uploaded Provenance Actions
gastarbeiter-0.2.0.tar.gz 18.2 kB Without provenance Details for gastarbeiter-0.2.0.tar.gz

Built distribution (wheel)

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

Total release size: 39.8 kB

Release files / gastarbeiter-0.2.0.tar.gz

Download URL gastarbeiter-0.2.0.tar.gz
Size 18.2 kB
Tags Source
SHA-256 checksum
How to use checksums
66a9b68ec1a2785b4166d38f9a9fb45e281a64533668559cbcb3bbd5de349b7d
BLAKE2b-256 checksum
How to use checksums
06258d7a9db0710ba5fcc044ab3e78ea8d094b2a1ce2c8102af31573ca309709
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.11.17 {"installer":{"name":"uv","version":"0.11.17","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / gastarbeiter-0.2.0-py3-none-any.whl

Download URL gastarbeiter-0.2.0-py3-none-any.whl
Size 21.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ffd8fb3ca8a17e7c537fd7291c4a82ced118a63e0fd94b5ae4d9166b959e034d
BLAKE2b-256 checksum
How to use checksums
f492503be0ec019dc0522584548831d44d61f32fc479b74e19218b809e5b9769
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.11.17 {"installer":{"name":"uv","version":"0.11.17","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for gastarbeiter 0.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.

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