Metadata-Version: 2.4
Name: gastarbeiter
Version: 0.2.0
Summary: Python client for the Gastarbeiter API: the OpenAI SDK plus rerank, classifications and services.
Keywords: gastarbeiter,openai,llm,inference,rerank,classification
Author: Gastarbeiter
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Typing :: Typed
Requires-Dist: openai>=1.66,<4
Requires-Python: >=3.10
Project-URL: Homepage, https://gastarbeiter.ai
Description-Content-Type: text/markdown

# gastarbeiter

The Python client for the [Gastarbeiter](https://gastarbeiter.ai) 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`](https://pypi.org/project/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

```bash
uv add gastarbeiter
```

or

```bash
pip install gastarbeiter
```

Python 3.10 or newer.

## Quickstart

Access is by invitation for now.

1. Sign in at [demo.gastarbeiter.ai](https://demo.gastarbeiter.ai) and create a key under **API-Schlüssel** ([demo.gastarbeiter.ai/api-keys](https://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:

```bash
export GASTARBEITER_API_KEY=ga_live_...
```

Then chat with a model:

```python
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:

```python
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:

```bash
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](https://ollama.com), 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.

```python
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`.

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

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

```python
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:

```python
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

```python
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

```python
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

```python
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

```python
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.

```python
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.

```python
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](https://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:

```python
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.

```python
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

```python
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 `TypedDict`s (`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:

```python
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.

```python
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.

```python
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.

```python
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.

## Links

- API keys: [demo.gastarbeiter.ai/api-keys](https://demo.gastarbeiter.ai/api-keys)
- Website: [gastarbeiter.ai](https://gastarbeiter.ai)
- OpenAI Python SDK, for everything the clients inherit: [github.com/openai/openai-python](https://github.com/openai/openai-python)

## License

MIT
