Skip to main content

gastarbeiter

The Python client for the Gastarbeiter API, a German, OpenAI-compatible inference API.

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.
  • flows: 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

Create an API key at gastarbeiter.ai. Keys look like ga_live_.... Put it in the environment:

export GASTARBEITER_API_KEY=ga_live_...

Then:

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)

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 flows 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.

Flows

A flow is a graph of nodes joined by edges. You send the whole graph with each run. Build it in the flow editor at 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 flow 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

flows.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.flows.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.flows.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 flow 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.

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.
InvalidFlowError 400 invalid_flow The flow graph doesn't compile. e.problems lists what is wrong.
InsufficientCreditError 402 insufficient_quota The credit doesn't cover the request. Top up at gastarbeiter.ai.
AccountSuspendedError 403 api_key_suspended The account is suspended, for example after repeated content policy violations. Wait until the suspension ends.
FlowNodeFailedError 422, 502 flow_node_failed A node failed during a flow run (502: the model server behind it failed). e.node says which one.
RateLimitError 429 rate_limit_exceeded, concurrency_limit_exceeded Too many requests per minute, or too many at once. The client already retries these. e.retry_after is the wait the server asked for, in seconds.
ServiceUnavailableError 503 model_unavailable, moderation_unavailable The model or moderation is down for now. Retry later.
FlowTimeoutError 504 flow_timeout The flow run took longer than the gateway allows. Make the flow smaller or faster.

InsufficientCreditError subclasses openai.APIStatusError, because the OpenAI SDK has no exception for 402, and so does FlowNodeFailedError, 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 flow 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: AuthenticationError (401, invalid_api_key), NotFoundError (404, model_not_found), BadRequestError (400, for example invalid_request or context_length_exceeded), InternalServerError (502, upstream_error), and APIConnectionError or APITimeoutError 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. Top up at https://gastarbeiter.ai.")
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.

Flow runs are the exception: flows.runs.create doesn't retry, because a retry runs the whole flow 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.1.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.1.0
File Size Uploaded Provenance Actions
gastarbeiter-0.1.0.tar.gz 13.4 kB Without provenance Details for gastarbeiter-0.1.0.tar.gz

Built distribution (wheel)

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

Total release size: 29.6 kB

Release files / gastarbeiter-0.1.0.tar.gz

Download URL gastarbeiter-0.1.0.tar.gz
Size 13.4 kB
Tags Source
SHA-256 checksum
How to use checksums
49b6c4213c8a290d805ad97d2816e3fc0f40a74267a074f894062b764c0e314c
BLAKE2b-256 checksum
How to use checksums
555952d524cc4372ffa81f28ef44f1dc42044c5e8ee05b1c4bca118fde611d46
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.1.0-py3-none-any.whl

Download URL gastarbeiter-0.1.0-py3-none-any.whl
Size 16.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
611eb2f07b7d12b3bc98d073db165486000dfd5cab540fe444433fdf8da877f6
BLAKE2b-256 checksum
How to use checksums
61a290e31b2774ceff1866af36a7c680136347ff34f2b948952c882ea589ffd3
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.1.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