Metadata-Version: 2.4
Name: gastarbeiter
Version: 0.1.0
Summary: Python client for the Gastarbeiter API: the OpenAI SDK plus rerank, classifications and Flows.
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, a German, OpenAI-compatible inference API.

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

```bash
uv add gastarbeiter
```

or

```bash
pip install gastarbeiter
```

Python 3.10 or newer.

## Quickstart

Create an API key at [gastarbeiter.ai](https://gastarbeiter.ai). Keys look like `ga_live_...`. Put it in the environment:

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

Then:

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

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

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

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

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

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

```python
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 `TypedDict`s (`FlowGraph`, `FlowNode`, `FlowEdge`) if you want your type checker to check it.

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

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

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

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.

## Links

- Website and API keys: [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
