Serve your agent
By the end of this page, your own agent runs in a container, and your app calls it over HTTP. It takes about an hour. You need Docker, curl, and an API key for a model.
Each step has the command, and what you should see. Every command and snippet comes from a file in examples/serve, and a test runs or parses that file, so the page matches the code.
1. What serve mode is
golem serve is golem on a server, as the agent behind your app. It is not golem on your own machine.
| golem on your machine | golem serve | |
|---|---|---|
| Who talks to it | You, in a terminal or the browser | Your app's backend, over HTTP, with a key |
| What it can do | Shell, file edits, your folders | Only what your app folder allows. No shell, no file writes |
| Who answers a question | You | Nobody (deny), or your app's user (app) |
| Secrets | The Keychain | Environment variables and files |
| Settings | You change them while it runs | Read from one folder at start, never written |
| Models | A local one, or a hosted one | Endpoints by URL. The model is never inside the container |
Your app talks to it in two ways:
- A workflow run. Your app starts a Python workflow for one of its users, follows the run, and reads the result. A workflow can ask a person to review a draft, and it can run for minutes or days.
- Chat. Your app points an OpenAI client at golem. The
modelis the name of an agent.
The design is in ADR-064 and the vision. The calls are in the Serve API.
2. The app folder
An app is a folder. golem reads it and never writes into it. The page What goes in /app has every part. Start with three files.
Make a folder, app, in an empty project, with the layout below. The example has the same files, so you can copy examples/serve/app to start.
app/
├── config.toml
├── agents/support.md
└── workflows/count_words.pyconfig.toml says which model to use, where its key comes from, and how the container behaves:
default_model = "anthropic/claude-sonnet-4-5"
[providers.anthropic]
api_key_env = "ANTHROPIC_API_KEY" # the name of the variable. The key itself is never in this file
[serve]
ask = "app" # a review waits for your app's user. The default, "deny", answers "reject" at once
keep_events_days = 30 # how long the events of a finished run are kept in full
keep_days = 90 # a finished run, and all that belongs to it, is removed after 90 days
metrics = true # turns on GET /metrics (it needs a key)
[serve.limits]
requests_per_minute = 600 # per key
runs_at_once = 4 # per user
user_usd_per_day = 2.00 # per user, per UTC day
key_usd_per_day = 50.00 # per key, per UTC dayapi_key_envis the name of a variable. A key written in this file is refused.ask = "app"lets a workflow wait for your app's user. Step 6 uses it.- The limits and
keep_daysare step 8.metricsis step 9. - Every key is in the settings.
An agent is a Markdown file. Its name, support, is the model of a chat call:
---
description: Answers questions from the customers of a small shop, in a few short sentences.
---
You answer questions from the customers of a small shop.
- Answer in two or three short sentences, in plain words.
- If you do not know, say so. Never make up an order, a price or a date.A workflow is a Python function. This one counts words and needs no model, so you can try everything without spending anything. Its name is the name in the URL:
# examples/serve/app/workflows/count_words.py
#
# The smallest workflow an app can start over HTTP: no model, no review. It counts the words of a text.
# POST /v1/workflows/count_words/runs {"input": {"text": "one two three"}, "user": "u_1"}
from golem.workflow import Run, workflow
def count(text: str) -> int:
return len(text.split())
@workflow(
inputs={"text": str},
title="Count the words",
description="Count the words of a text.",
)
async def count_words(run: Run, text: str = "") -> dict[str, int]:
words = await run.step("Count", count, text)
await run.output({"words": words}, title="Words", summary=f"{words} words")
return {"words": words}The example also has review_reply.py, a workflow that asks before it sends a reply. Step 6 uses it. How to write a workflow is in Workflows.
3. Check it, then run it
First check the folder. The check starts nothing and calls no model:
# Starts nothing and calls no model. Prints "ok" or one line for each problem, and exits 1 on a problem.
export ANTHROPIC_API_KEY=sk-ant-...
GOLEM_APP=./app golem serve checkokEach problem is one line, and the exit code is 1. It finds a config.toml that does not parse, an agent or workflow that does not load, a secret that is named and not set, and a model with no endpoint. Run it in your CI before you build.
You have no golem on this machine? Use the image's own:
# The same check with the image's own golem, without golem on this machine.
docker compose run --rm --entrypoint golem golem serve checkNow run it. The Compose file runs the image with your app folder read-only at /app, and a volume at /data where golem keeps everything it writes. It also publishes port 8080 on 127.0.0.1 only, so you can call it from your shell.
# golem next to a stub app, on a private network. Only your own machine (127.0.0.1) can reach it
# from outside Docker; inside the network the app calls http://golem:8080.
#
# export ANTHROPIC_API_KEY=...
# docker compose up -d
#
# Replace `app` with your own container. The guide: docs/guide/serve.md
services:
golem:
image: ghcr.io/milanpavel/golem:latest
ports:
- "127.0.0.1:8080:8080" # for curl from this machine. Remove it when only your app calls golem
volumes:
- ./app:/app:ro # what the app is: config.toml, skills, agents, workflows. Read-only.
- golem-data:/data # what golem keeps: databases, logs, tokens.
environment:
ANTHROPIC_API_KEY: # taken from your shell; the key is never written to a file
GOLEM_SECRET_WEBHOOK_APP: # the webhook signing secret, only when config.toml has [serve.webhooks]
networks: [private]
restart: unless-stopped
stop_grace_period: 50s # drain_seconds (25) plus up to 20 seconds for the daemon to stop
app:
image: busybox:1.37
# Stub: asks golem's health page every ten seconds. Your app calls golem the same way.
command:
- sh
- -c
- 'while true; do wget -q -O - http://golem:8080/readyz || echo "golem is not up yet"; echo; sleep 10; done'
depends_on: [golem]
networks: [private]
volumes:
golem-data:
networks:
private:
internal: false # the golem container may reach the model's APIexport ANTHROPIC_API_KEY=sk-ant-...
docker compose up -d
curl -sS http://127.0.0.1:8080/readyzok/readyz says ok when golem has loaded the app and has a model it can reach. Before that it answers 503.
Now make a key for your app. The key is shown once, and golem keeps only a digest of it:
docker compose exec golem golem serve keys create --name my-appgk_app_x5ZdZjeqrjXYDtikGgBhgmxIfEXrbVksbXum4Rdqu6j_1GoFMF
Key key_... (my-app). This is the only time it is shown: keep it now.Put the key in a variable for the next steps: export KEY=gk_app_.... Your app keeps it in its own secrets.
4. Call it
Your app starts a run for one of its users. user is your own id for a person. You pick it, and golem trusts it. A user can only see their own runs.
With curl
# 1. Start. The Idempotency-Key makes a retry of this call start the same run, not another.
START=$(curl -sS -i "$GOLEM/v1/workflows/count_words/runs" \
-H "Authorization: Bearer $KEY" \
-H "Idempotency-Key: demo-$(date +%s)" \
-H "Content-Type: application/json" \
-d "{\"input\": {\"text\": \"one two three four\"}, \"user\": \"$USER_ID\"}")
printf '%s\n' "$START"
RUN=$(printf '%s\n' "$START" | sed -n 's/^[Ll]ocation: *//p' | tr -d '\r')HTTP/1.1 202 Accepted
Location: /v1/runs/wr_663b6f15248d4ee5bba09da5fad9e9b4
{"id":"wr_663b6f15248d4ee5bba09da5fad9e9b4","workflow":"count_words","user":"u_demo","status":"working", ...}202means golem took the run. The run goes on without you.Locationis the run's place. A run id is opaque: keep it and do not read it.- A retry with the same
Idempotency-Keyreturns the same run, with200. The same key with another body is409.
Follow it:
# 2. Follow it. -N keeps curl from buffering; the stream ends after the run's last event.
# After a dropped connection, add -H "Last-Event-ID: <the last id you saw>".
curl -sS -N "$GOLEM$RUN/events?user=$USER_ID" -H "Authorization: Bearer $KEY"id: 1
event: run.status
data: {"status":"working"}
id: 2
event: step.started
data: {"key":"Count","kind":"step","title":"Count","group":null,"item":null,"attempts":1}
id: 3
event: step.finished
data: {"key":"Count","kind":"step","title":"Count","status":"done","error":null,"cost_usd":null,"line":"4"}
id: 4
event: run.output
data: {"position":0,"title":"Words","summary":"4 words","value":{"words":4}}
id: 5
event: run.status
data: {"status":"completed"}- A new connection starts with the run's state, in a
run.statuswith noid:. You may see that state twice. - The stream stays open while the run goes on, and ends after the last event.
- If the connection drops, connect again with
Last-Event-ID: <the last id you saw>. You get the events after it, with no gap and no repeat.
Read the run:
# 3. Read the run and its output.
curl -sS "$GOLEM$RUN?user=$USER_ID" -H "Authorization: Bearer $KEY"{"id": "wr_...", "workflow": "count_words", "user": "u_demo", "status": "completed",
"interrupts": [], "usage": {"cost_usd": 0},
"output": {"result": {"words": 4}, "items": [{"position": 0, "title": "Words", "summary": "4 words", "value": {"words": 4}}]}}status is one of submitted, working, input-required, completed, failed and canceled. The last three are final. When it is completed, output.result is what the workflow returned.
With Python and TypeScript
The same three calls. Each file runs on its own, with KEY and GOLEM set.
def run_workflow(
golem: str, key: str, user: str, workflow: str, run_input: dict[str, Any]
) -> dict[str, Any]:
"""Start a run for `user`, print its events as they come, and return the finished run."""
with httpx.Client(
base_url=golem, headers={"Authorization": f"Bearer {key}"}, timeout=30
) as http:
# 1. Start. A retry with the same Idempotency-Key is the same run, not another.
started = http.post(
f"/v1/workflows/{workflow}/runs",
headers={"Idempotency-Key": str(uuid.uuid4())},
json={"input": run_input, "user": user},
)
started.raise_for_status() # 202
place = started.headers["Location"] # /v1/runs/run_...
# 2. Follow it. The stream ends after the run's last event.
with http.stream("GET", f"{place}/events", params={"user": user}, timeout=None) as events:
events.raise_for_status()
name = ""
for line in events.iter_lines():
if line.startswith("event: "):
name = line.removeprefix("event: ")
elif line.startswith("data: "):
print(name, line.removeprefix("data: "))
# 3. Read the run. `output` has the result when the status is "completed".
finished = http.get(place, params={"user": user})
finished.raise_for_status()
return finished.json()export async function runWorkflow(
golem: string,
key: string,
user: string,
workflow: string,
input: Record<string, unknown>,
): Promise<{ status: string; output?: { result: unknown } }> {
const auth = { Authorization: `Bearer ${key}` };
// 1. Start. A retry with the same Idempotency-Key is the same run, not another.
const started = await fetch(`${golem}/v1/workflows/${workflow}/runs`, {
method: "POST",
headers: { ...auth, "Content-Type": "application/json", "Idempotency-Key": crypto.randomUUID() },
body: JSON.stringify({ input, user }),
});
if (started.status !== 202) throw new Error(`start answered ${started.status}: ${await started.text()}`);
const place = started.headers.get("Location") ?? "";
// 2. Follow it. The stream ends after the run's last event.
const events = await fetch(`${golem}${place}/events?user=${encodeURIComponent(user)}`, { headers: auth });
if (!events.ok || events.body === null) throw new Error(`events answered ${events.status}`);
const reader = events.body.getReader();
const decoder = new TextDecoder();
let pending = "";
let name = "";
for (;;) {
const { done, value } = await reader.read();
if (done) break;
pending += decoder.decode(value, { stream: true });
const lines = pending.split("\n");
pending = lines.pop() ?? "";
for (const line of lines) {
if (line.startsWith("event: ")) name = line.slice("event: ".length);
else if (line.startsWith("data: ")) console.log(name, line.slice("data: ".length));
}
}
// 3. Read the run. `output` has the result when the status is "completed".
const finished = await fetch(`${golem}${place}?user=${encodeURIComponent(user)}`, { headers: auth });
if (!finished.ok) throw new Error(`read answered ${finished.status}`);
return (await finished.json()) as { status: string; output?: { result: unknown } };
}The Python file needs pip install httpx. The TypeScript file needs Node 22 or newer and nothing else.
When a call fails
A failed call is application/problem+json. Branch on code, not on the text. The full list is in Errors. The ones you meet first:
| Status | code | Means |
|---|---|---|
| 401 | invalid_key | The key is missing, wrong or revoked |
| 404 | workflow_not_found | The app has no such workflow |
| 404 | not_found | No such run, or it is another user's |
| 422 | input_invalid | input does not fit the workflow. field names it |
| 429 | rate_limited, budget_exceeded | A limit. See Retry-After. Step 8 |
| 503 | draining, not_ready | golem is stopping, or has not loaded the app. Try again |
5. Chat with the OpenAI SDK
An agent of your app is a model. Point any OpenAI client at $GOLEM/v1, and use the agent's name as model. GET /v1/models lists them:
curl -sS http://127.0.0.1:8080/v1/models -H "Authorization: Bearer $KEY"{"object":"list","data":[{"id":"support","object":"model","owned_by":"app","description":"Answers questions from the customers of a small shop, in a few short sentences."}]}def ask_support(golem: str, key: str, user: str, question: str) -> str:
client = OpenAI(base_url=f"{golem}/v1", api_key=key)
answer = client.chat.completions.create(
model="support", # an agent of the app: app/agents/support.md
messages=[{"role": "user", "content": question}],
user=user, # your own id for the person. A call with no user is refused
)
return answer.choices[0].message.content or ""
def stream_support(golem: str, key: str, user: str, question: str) -> str:
client = OpenAI(base_url=f"{golem}/v1", api_key=key)
stream = client.chat.completions.create(
model="support",
messages=[{"role": "user", "content": question}],
user=user,
stream=True,
)
text = ""
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
text += chunk.choices[0].delta.content
print(chunk.choices[0].delta.content, end="", flush=True)
print()
return text- Every call needs
user(orsafety_identifier), your own id for the person. Without it the call is400,user_required. - Each call is stateless: golem seeds a short session with the
messagesyou send, and runs the last one. Send the history you want it to see. - Your
systemmessage is added to the agent's own instructions. It does not replace them. - With
stream=Trueyou get the assistant's text as it comes. A client that hangs up cancels the turn. toolsare refused with400. Your client does not run tools in version 1.
6. Ask your user
Some work should not go out without a person. A workflow can ask for a review. The run then waits as input-required, for as long as it takes, and it waits through a restart.
This needs ask = "app" in config.toml. The example has it. With the default, ask = "deny", golem answers every review reject at once, and the run never waits.
review_reply.py drafts a reply and asks:
# examples/serve/app/workflows/review_reply.py
#
# A workflow with a review, and no model. It drafts a reply, then asks the app's user to look at it.
# The run waits as `input-required` when app/config.toml has
#
# [serve]
# ask = "app"
#
# and the app answers with POST /v1/runs/{id}/resume (see ../../answer.sh). With the default,
# ask = "deny", the review is answered `reject` at once and the run finishes as "not sent".
from golem.workflow import Run, workflow
def draft(name: str) -> str:
return f"Hello {name}, your refund is on its way."
@workflow(
inputs={"name": str},
title="Review a reply",
description="Draft a reply and ask the user before it is sent.",
)
async def review_reply(run: Run, name: str = "there") -> dict[str, str]:
text = await run.step("Draft", draft, name)
answer = await run.review(
text,
ask="Look at the reply before it goes out.",
key="review:reply",
title="Send this reply?",
)
if answer["verdict"] == "reject":
await run.output("not sent", title="Reply", summary="rejected")
return {"sent": "no"}
await run.output(answer["text"], title="Reply", summary="sent")
return {"sent": "yes", "text": answer["text"]}Start it, and read the run. It holds the question in interrupts:
# 1. Start the run. It stops at the review.
LOCATION=$(curl -sS -i "$GOLEM/v1/workflows/review_reply/runs" \
-H "Authorization: Bearer $KEY" \
-H "Content-Type: application/json" \
-d "{\"input\": {\"name\": \"Ana\"}, \"user\": \"$USER_ID\"}" | sed -n 's/^[Ll]ocation: *//p' | tr -d '\r')
sleep 1
# 2. The run is input-required, and interrupts[] holds the question: id, title, ask, draft.
curl -sS "$GOLEM$LOCATION?user=$USER_ID" -H "Authorization: Bearer $KEY"
echo{"id":"wr_...","workflow":"review_reply","status":"input-required",
"interrupts":[{"id":"review:reply","kind":"review","title":"Send this reply?","ask":"Look at the reply before it goes out.","draft":"Hello Ana, your refund is on its way."}], ...}Show the draft to your user in your app. Then send their answer. Answer every open question in one call. A verdict is approve, reject, or edit with your user's own text:
# 3. Answer it: approve, reject, or edit with your own text. Every open interrupt goes in one call.
curl -sS "$GOLEM$LOCATION/resume?user=$USER_ID" \
-H "Authorization: Bearer $KEY" \
-H "Content-Type: application/json" \
-d '{"answers": [{"id": "review:reply", "verdict": "edit", "text": "Hello Ana, your refund arrives on Friday."}]}'
echo{"id":"wr_...","status":"working","interrupts":[], ...}The run goes on. Read it again and it is completed, with the reply your user wrote in output.
| If | Then |
|---|---|
| An open question has no answer | 422, answers_incomplete. missing lists the ids |
The verdict is unknown, or edit has no text | 422, answer_invalid |
| The run is not waiting | 409, run_not_waiting |
The events of the run have the question too (run.interrupt), so you can show it as soon as it comes. A tool call that would ask is denied in both settings, so a tool is never a question in version 1.
7. Know when a run ends
Instead of polling, let golem call your app when a run ends or needs an answer. Add this to config.toml:
[serve.webhooks]
url = "http://app:3000/hooks/golem" # your app, on the private network. A public address must be https
secret = "secret:webhook/app" # whsec_ and base64. golem reads it from GOLEM_SECRET_WEBHOOK_APP
events = ["run.completed", "run.failed", "run.canceled", "run.input_required"]Make a signing secret, and give it to the container. It is never in a file of the app:
# A signing secret: whsec_ and base64. Keep it in your shell or your secret store, not in config.toml.
export GOLEM_SECRET_WEBHOOK_APP="whsec_$(openssl rand -base64 32)"docker compose up -d reads GOLEM_SECRET_WEBHOOK_APP from your shell. Run golem serve check again: it refuses a secret that is not set, and a url that is not https. Plain http passes only for localhost and private names, such as app here, and it prints a warning.
golem sends a POST for each event. The body is small on purpose. It has no input, no output and no draft, so nothing private leaves golem:
POST /hooks/golem HTTP/1.1
Content-Type: application/json
webhook-id: msg_2f1c0b9a7e4d4c0f8a1b3d5e6f708192
webhook-timestamp: 1796115600
webhook-signature: v1,K5oZfzN95Z9UkDG9n6bC6Wt2Ow3xC5kq1pU0m0hQ0aY=
{"type":"run.input_required","timestamp":"2026-12-01T09:00:00+00:00","data":{"run":{"id":"wr_...","workflow":"review_reply","status":"input-required","user":"u_demo"}}}Check the signature before you trust a call. Do it on the raw body, before you parse the JSON:
def verify(secret: str, headers: dict[str, str], body: bytes) -> bool:
key = base64.b64decode(secret.removeprefix("whsec_"))
if abs(time.time() - int(headers["webhook-timestamp"])) > 300:
return False
signed = f"{headers['webhook-id']}.{headers['webhook-timestamp']}.".encode() + body
expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()
return any(
hmac.compare_digest(expected, part.removeprefix("v1,"))
for part in headers["webhook-signature"].split()
if part.startswith("v1,")
)import { createHmac, timingSafeEqual } from "node:crypto";
export function verify(secret: string, headers: Headers, body: string): boolean {
const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
const id = headers.get("webhook-id") ?? "";
const timestamp = headers.get("webhook-timestamp") ?? "";
if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false;
const expected = createHmac("sha256", key).update(`${id}.${timestamp}.${body}`).digest();
return (headers.get("webhook-signature") ?? "").split(" ").some((part) => {
if (!part.startsWith("v1,")) return false;
const given = Buffer.from(part.slice(3), "base64");
return given.length === expected.length && timingSafeEqual(given, expected);
});
}Then read the run with GET /v1/runs/{id}?user=... for what you need.
- Answer
2xxto end the delivery. golem tries again after 5 seconds, 30 seconds, 2 minutes, 10 minutes and 1 hour, then every 6 hours, for 3 days. webhook-idis the same on every try. Use it to ignore a repeat.410 Gonetells golem to stop sending to that address.- See what is stuck:
curl -sS "http://127.0.0.1:8080/v1/webhooks/deliveries?status=failed" -H "Authorization: Bearer $KEY"The rules are in Webhooks.
8. Keep it safe and cheap
Keys and users
- A key is your app. Make one for each place that calls golem, such as your backend and your metrics scraper. Name it for what it is.
- A user is your own id for a person. A key can reach every user of the app. Your app decides who may call, and golem keeps one user's runs apart from another's: a run of another user is
404. - To change a key, make a new one, switch your app to it, and revoke the old one. The data it made stays with the user.
docker compose exec golem golem serve keys list
docker compose exec golem golem serve keys revoke my-appLimits and budgets
One user, or one leaked key, cannot run up the bill. Set the limits in config.toml. The example has these:
[serve.limits]
requests_per_minute = 600 # per key
runs_at_once = 4 # per user
user_usd_per_day = 2.00 # per user, per UTC day
key_usd_per_day = 50.00 # per key, per UTC dayA caller that goes over gets 429, and Retry-After says how many seconds to wait. limit names the limit:
{"status": 429, "code": "budget_exceeded", "limit": "user_usd_per_day", "detail": "..."}runs_at_onceandrequests_per_minutegiverate_limited. The money limits givebudget_exceeded, andRetry-Afteris the time to midnight UTC. Show your user "come back tomorrow".- Money is checked before a run starts, and before each model call inside it. A run that reaches the limit in the middle ends
failed, witherror.codebudget_exceeded. - Show your user how much is left:
curl -sS "http://127.0.0.1:8080/v1/usage?user=u_demo" -H "Authorization: Bearer $KEY"{"user":"u_demo","day":"2026-11-29","cost_usd":0,"limits":{"runs_at_once":4,"user_usd_per_day":2,"runs_at_once_total":32},"remaining_usd":2}All the limits are in the settings and in Limits.
Delete and export a user
Your users may ask you to erase what you hold about them, or to hand it over. Two calls do it. A user is your id of a person, across all the keys of the app, so any key may do both, and data made under a revoked key is included.
curl -sS "$GOLEM/v1/users/$USER_ID/export" -H "Authorization: Bearer $KEY" -o "$USER_ID.json"curl -sS -X DELETE "$GOLEM/v1/users/$USER_ID" -H "Authorization: Bearer $KEY"{"user":"u_demo","deleted":true}- Export is one JSON document: the user's runs with their steps, outputs, reviews, events and webhook deliveries, their chats, and their usage. It changes nothing.
- Delete cancels the user's runs that have not ended, then removes it all. It is done when it answers
202. Call it twice and you get the same answer. - The usage numbers stay, without the user's id, so a key's spend of the day does not drop.
- golem cannot reach what you already hold: the webhook bodies you received, and the answers you stored.
- What golem stores about a user lists every place.
Old data leaves by itself
keep_days = 90 in the example removes a run that ended more than 90 days ago, and everything that belongs to it, once a day. Leave it out to keep runs for ever. keep_events_days may not be longer.
9. Watch it
Logs. golem writes one JSON object per line to its output. No key and no message text is ever in it:
docker compose logs -f golem{"ts":"2026-12-01T09:00:00.000Z","process":"gateway","level":"info","msg":"request","request_id":"req_1f0c","trace_id":"0af7651916cd43dd8448eb211c80319c","method":"POST","path":"/v1/workflows/count_words/runs","route":"/v1/workflows/:name/runs","status":202,"ms":41}Send a traceparent header and its trace id is on every log line of the request, and in the trace of the run. Every response has X-Request-Id. Quote it when you ask for help.
Metrics. The example turns on metrics = true. GET /metrics is Prometheus text, and it needs a key:
curl -sS http://127.0.0.1:8080/metrics -H "Authorization: Bearer $KEY"# HELP golem_daemon_up 1 when the daemon answers and has a model endpoint (what /readyz checks), else 0.
# TYPE golem_daemon_up gauge
golem_daemon_up 1
...
golem_runs_started_total{workflow="count_words"} 1
golem_runs_finished_total{workflow="count_words",status="completed"} 1Use golem_daemon_up == 1 for "is it up", and golem_limit_refusals_total for "is a limit biting". No user id and no run id is ever a label. The list of metrics, a Prometheus scrape example and some queries are in Watching a served golem.
Load. One container, with a workflow that calls no model, ran about 70 runs a second at 20 at once on 4 cpus in CI, with no errors, and the gateway and the daemon used about 300 MiB together. A real model takes seconds and sets the pace of a real app, so read this as the room the container has. How it was measured is in Watching a served golem.
10. Deploy
One small server, with Compose
Any server with Docker will do. Plan for 1 GB of memory: the container used about 300 MiB at its peak in the load test.
- Copy the
examples/servefolder to the server, and put yourappfolder in it. - Export
ANTHROPIC_API_KEYin the shell, and rundocker compose up -d, as in step 3. - Make a key, as in step 3.
- Replace the stub
appservice with your own container. It callshttp://golem:8080on the private network. Take out theportsline when only your app calls golem.
restart: unless-stopped starts it again after a reboot. stop_grace_period is long enough for drain_seconds, so a stop lets open requests finish. Runs that are still going wait for the next start.
To change the app, edit the app folder and run docker compose up -d again. To get a new golem:
docker compose pull golem
docker compose up -d golemBack up the golem-data volume. It is the state of the app: runs, chats and keys.
Run one golem for one /data. More than one replica on the same volume is not supported, and the request limits are kept in memory for one replica.
Fly.io
Not run in CI.
The Fly example follows Fly's documented fly.toml format. It is not deployed from CI, so read it, and try it before you rely on it.
On Fly there is no folder to mount, so the Dockerfile copies your app into the image:
# The image for a host with no folder to mount, such as Fly: golem's image with your app folder inside.
#
# docker build -t my-golem examples/serve
#
# /app is read-only in practice: golem never writes there. /data is the volume.
FROM ghcr.io/milanpavel/golem:latest
COPY app /app
# A new volume on Fly belongs to root, and golem runs as the user "golem". This script gives the
# volume to that user, then starts golem as that user.
USER root
COPY --chmod=755 fly-entrypoint.sh /usr/local/bin/fly-entrypoint
ENTRYPOINT ["/usr/bin/tini", "--", "fly-entrypoint"]A new Fly volume belongs to root, and golem runs as the user golem. This small script gives the volume to that user, and then starts golem as that user:
#!/bin/sh
# Run as root so a new volume can be given to golem, then drop to the user "golem" and start it.
set -eu
chown golem:golem /data
exec setpriv --reuid=golem --regid=golem --init-groups golem-entrypoint# golem on Fly.io. Not run in CI: it follows Fly's documented fly.toml format and is not deployed from here.
#
# The commands to deploy it are in the guide, under "Fly.io".
#
# The guide: docs/guide/serve.md
app = "my-golem"
primary_region = "ams"
[build]
dockerfile = "Dockerfile"
# The state: databases, logs, keys. One volume holds one machine's state, so run one machine.
[[mounts]]
source = "golem_data"
destination = "/data"
[http_service]
internal_port = 8080
force_https = true
auto_stop_machines = "off" # a stopped machine cannot finish a run
auto_start_machines = false
min_machines_running = 1
[[http_service.checks]]
method = "GET"
path = "/healthz"
interval = "15s"
timeout = "5s"
grace_period = "30s"
[[vm]]
memory = "1gb"
cpu_kind = "shared"
cpus = 1internal_port = 8080is where golem listens.- The volume
golem_datais/data. - The check is
GET /healthz. It needs no key. auto_stop_machines = "off", because a stopped machine cannot finish a run.- The secrets are set with
fly secrets set. They never go infly.tomlor in the image.
The commands, in order:
fly launch --no-deploy --copy-config --name my-golem --region ams
fly volumes create golem_data --size 1 --region ams
fly secrets set ANTHROPIC_API_KEY=sk-ant-...
fly deploy
fly ssh console --user golem -C "env GOLEM_RUN=/run/golem /opt/golem/bin/golem serve keys create --name my-app"Fly gives the app a public address by default. golem's API is made for a private network: it needs a key, and it has no CORS, so a browser cannot call it. Use Fly's private network between your app and golem, and release the public address. See Fly's documentation.
What is not in version 1
The list is in one place: Not in version 1.
Next
- The Serve API, every call, code and limit.
- What goes in /app and the settings.
- Watching a served golem.
- Workflows, to write your own.