The Flow Book
  1. Why Flow

One week at the support desk

  1. A payment that timed out
  2. What the run was told
  3. Writing the payments library
  4. Waiting for the manager
  5. The next morning
  6. When the process dies mid-call
  7. Fixing a bug in a half-finished run
  8. Three carriers at once
  9. Answering calls from your own service

Projects

  1. What people build
  2. A research agent you can check

The language tour

  1. Values, functions and blocks
  2. Records, choices and match
  3. Modules, libraries and Python functions
  4. Result, ToolProblem and ?

Appendix

  1. The flow command
Language reference ↗

Writing the payments library

So far payments has been a directory you used without opening. The program called payments.refund, and something answered with a receipt, a refusal or a NetworkError. On Thursday the team lead asks where that something lives. The real provider's client is about to replace the stand-in, and the lead wants to know what keeps the code that talks to the provider in step with what the program expects of it.

In most stacks, nothing does. An agent framework has you describe each tool twice, once as a function and once as a JSON schema for the model. A service has an OpenAPI file beside the handlers. A Temporal activity's signature is repeated in the workflow that calls it. Each copy is kept in step by hand, by whoever remembers, and the bug shows up when one side changes: a field renamed in the code but not in the schema, an amount that became a float.

A Flow library has one copy. You write the Python, and Flow reads the Flow side from it.

What is in the directory

A Python library is a directory with a flow.toml that names the Python toolkit's commands and the module its Tools are in, the Python itself, and the contract flow build writes from it. In 1-refund-timed-out that is all payments holds:

[process]command = "flow-toolkit-python serve payments"extract = "flow-toolkit-python extract payments"
The whole configuration: the Python toolkit serves the module payments and writes its contract.

There's no virtual environment to set up: the Python toolkit, flow-toolkit-python, serves the library on the Python it was installed with, its own flow_toolkit package included. A library that needs other Python packages lists them in a pyproject.toml with a uv.lock beside it, and the toolkit installs exactly what the lock says into its own cache.

payments.py holds the Tools. provider.py stands in for the provider's own Python client, the code your team would install from the provider rather than write; this one keeps its ledger in a file so you can watch what it does.

Show payments/provider.py · 71 lines
# A stand-in for the payment provider's Python client. Nothing leaves this# directory: ledger.txt is the provider's record of money paid out, one line per# refund, and keys.txt holds the idempotency keys it has seen.## PROVIDER chooses what the provider does with a refund request:#   lost      (the default) it pays, and its answer is lost on the way back#   down      it can't be reached, so the request never leaves#   declined  it refuses the refund#   busy      it turns the request away for now#   slow      it pays at once and takes 30 seconds to answer#   paid      it pays and answersimport osimport timefrom pathlib import PathLEDGER = Path("ledger.txt")KEYS = Path("keys.txt")class Declined(Exception):    passclass RateLimited(Exception):    def __init__(self, retry_after):        super().__init__(f"retry after {retry_after}s")        self.retry_after = retry_afterclass Unreachable(Exception):    passclass Timeout(Exception):    passdef lines(path):    return path.read_text().splitlines() if path.exists() else []def append(path, line):    with path.open("a") as file:        file.write(line + "\n")def refund(order, dollars, idempotency_key):    mode = os.environ.get("PROVIDER", "lost")    if mode == "down":        raise Unreachable("could not connect to the provider")    if mode == "declined":        raise Declined("the payment is older than 180 days")    if mode == "busy":        raise RateLimited(30)    refund_id = "re_" + order.removeprefix("A-")    if idempotency_key not in lines(KEYS):  # a repeated key pays nothing more        append(LEDGER, f"{order} {dollars} {refund_id}")        append(KEYS, idempotency_key)    if mode == "slow":        time.sleep(30)    if mode == "lost":        raise Timeout("no answer from the provider in 10s")    return refund_iddef find_refund(order):    for line in lines(LEDGER):        paid_order, _, refund_id = line.split()        if paid_order == order:            return refund_id    return None
The stand-in client. It raises an exception for each way a request can go wrong.

Types are the boundary

The top of payments.py declares what crosses between the program and the provider:

@dataclass(frozen=True)class Receipt:    refund_id: str@variant@dataclass(frozen=True)class Declined:    reason: str@variant@dataclass(frozen=True)class RateLimited:    seconds: intPayError = Declined | RateLimited
Show all 50 lines of payments/payments.py
# The shop's refunds, as Flow Tools. Each function calls the provider's client# and says honestly what came of the call.from dataclasses import dataclassimport providerfrom flow_toolkit import Err, NetworkError, Ok, Result, context, tool, variant@dataclass(frozen=True)class Receipt:    refund_id: str@variant@dataclass(frozen=True)class Declined:    reason: str@variant@dataclass(frozen=True)class RateLimited:    seconds: intPayError = Declined | RateLimited@tooldef refund(order: str, dollars: int) -> Result[Receipt, PayError]:    """Refund an order. A request sent again under the same key pays nothing more."""    call = context()    try:        refund_id = provider.refund(order, dollars, idempotency_key=f"{call.run}/{call.call}")    except provider.Declined as error:        return Err(Declined(str(error)))    except provider.RateLimited as error:        return Err(RateLimited(error.retry_after))    except provider.Unreachable as error:        raise NetworkError(sent=False, reason=str(error))    except provider.Timeout as error:        raise NetworkError(sent=True, reason=str(error))    return Ok(Receipt(refund_id))@tooldef find_refund(order: str) -> Receipt | None:    """The provider's refund for an order, if it has made one."""    refund_id = provider.find_refund(order)    return None if refund_id is None else Receipt(refund_id)
Plain dataclasses. @variant marks each case of a union.

A dataclass is a record. A union of dataclasses marked @variant is a choice with one case for each, in union order, so PayError is Declined or RateLimited. str is Text and int is Int. Nothing here is special to Flow except @variant, and the dataclasses work as ordinary Python wherever else you use them.

flow build payments reads the file without running it and writes the contract you have been reading since the timeout:

flow build payments…/1-refund-timed-out/payments: contract is current
// Generated by flow build from python module payments. Do not edit.// from payments.py: Receiptpub type Receipt { pub refund_id: Text }// from payments.py: PayErrorpub type PayError { Declined { reason: Text }, RateLimited { seconds: Int } }/// Refund an order. A request sent again under the same key pays nothing more.// from payments.py: refundpub flow refund(order: Text, dollars: Int) -> Result<Receipt, PayError>/// The provider's refund for an order, if it has made one.// from payments.py: find_refundpub flow find_refund(order: Text) -> Option<Receipt>
The contract again. Each declaration says which Python definition it came from, and a docstring becomes a doc comment.

You commit the contract with the code and never edit it. When you change a signature, the next flow check, flow run or editor save rewrites it and says what changed, and CI can run flow build --check payments to catch a contract someone forgot to commit.

Because the contract is generated, a change on the Python side reaches the program's checker. Suppose a colleague, thinking ahead to partial refunds, changes dollars: int to dollars: float:

Goes wrong
flow check main.flowFound 1 error error[tool-preparation]   × cannot generate the contract of……  --> main.flow   Note  flow-toolkit-python: …/1-refund-timed-out/payments/payments.py:30:33: float is not exact; annotate int for integers or decimal.Decimal for decimals   Why  A library's contract could not be made current; no execution was started.   Help  Check the library's native source and the reported generator or compiler cause, and that its  toolchain and dependencies are available. When operating offline, required dependencies must  already be cached.   Regenerate the program's library contracts after resolving the cause      flow build main.flow

A float can't hold most amounts of money exactly, so the generator refuses to describe one, and the mistake stops at flow check. Had the colleague written str instead, the contract would have changed quietly and the error would have moved into main.flow, which passes an Int where refund now wants Text. Either way the two sides can't disagree at run time.

Saying what happened

The interesting part of the library is refund, because it has to tell the program what came of the call:

@tooldef refund(order: str, dollars: int) -> Result[Receipt, PayError]:    """Refund an order. A request sent again under the same key pays nothing more."""    call = context()    try:        refund_id = provider.refund(order, dollars, idempotency_key=f"{call.run}/{call.call}")    except provider.Declined as error:        return Err(Declined(str(error)))    except provider.RateLimited as error:        return Err(RateLimited(error.retry_after))    except provider.Unreachable as error:        raise NetworkError(sent=False, reason=str(error))    except provider.Timeout as error:        raise NetworkError(sent=True, reason=str(error))    return Ok(Receipt(refund_id))
Show all 50 lines of payments/payments.py
# The shop's refunds, as Flow Tools. Each function calls the provider's client# and says honestly what came of the call.from dataclasses import dataclassimport providerfrom flow_toolkit import Err, NetworkError, Ok, Result, context, tool, variant@dataclass(frozen=True)class Receipt:    refund_id: str@variant@dataclass(frozen=True)class Declined:    reason: str@variant@dataclass(frozen=True)class RateLimited:    seconds: intPayError = Declined | RateLimited@tooldef refund(order: str, dollars: int) -> Result[Receipt, PayError]:    """Refund an order. A request sent again under the same key pays nothing more."""    call = context()    try:        refund_id = provider.refund(order, dollars, idempotency_key=f"{call.run}/{call.call}")    except provider.Declined as error:        return Err(Declined(str(error)))    except provider.RateLimited as error:        return Err(RateLimited(error.retry_after))    except provider.Unreachable as error:        raise NetworkError(sent=False, reason=str(error))    except provider.Timeout as error:        raise NetworkError(sent=True, reason=str(error))    return Ok(Receipt(refund_id))@tooldef find_refund(order: str) -> Receipt | None:    """The provider's refund for an order, if it has made one."""    refund_id = provider.find_refund(order)    return None if refund_id is None else Receipt(refund_id)
Each of the client's exceptions becomes one honest answer.

A function answers in the way Python functions do. Returning a value is the answer, and since refund is declared to return Result[Receipt, PayError], the provider's refusals are values too: Err(Declined(...)) is the provider saying no, which the program sees as Ok(Err(...)). Only the cases where the call itself got no value back are raised, and each says something different about whether trying again is safe:

What you know Answer
The work produced a value, a refusal included return it
The work never began, say a dependency was down before you sent anything raise NotStarted(reason)
The work began, and you couldn't get a value back raise Interrupted(reason)
Your network to the service failed raise NetworkError(...), with sent=True if the request may have left
Anything else, a bug included let it raise

The two NetworkError lines are where the library earns its keep. The provider's client raises Unreachable when it can't connect, so nothing was sent, and Timeout when it sent the request and gave up waiting for the answer. Only this code knows which of the two happened, and the match in main.flow depends on it telling the truth.

An exception you didn't plan for

The last row of the table matters as much as the others. Delete the except provider.Timeout lines and run the lost refund again:

Goes wrong
flow run main.flow order=A-1042 dollars=40run d3b6167ecf6cd3b6167ecf6c stopped: root#1 has no answer: its implementation has no answer: Timeout: no answer from the provider in 10sopen root#1  it may have done its work already, and a resend asks it again under the same key  resend: flow resume d3b6167ecf6c --resend 'root#1'  payments.refund    arguments: {"dollars":40,"order":"A-1042"}reply details: flow show d3b6167ecf6c 'root#1'next: flow show d3b6167ecf6c
cat payments/ledger.txtA-1042 40 re_1042

The provider paid, and the exception escaped refund. The toolkit can't tell an exception you forgot from a bug, and any answer it chose for you would be a guess about code it didn't write, so it chooses none. The call has no answer. It stays open, the run stops, and the history ends at the request.

A stopped call waits for a person, who decides what to do with it. Here the bug is yours, so put the except provider.Timeout lines back and send the call again. --resend sends each call that was left without an answer again, under the same key:

PROVIDER=paid flow resume d3b6167ecf6c --resendRefunded(Receipt { refund_id: "re_1042" })note: Open calls were selected for resend. The original call ID does not guarantee external deduplication; an external effect may happen again.d3b6167ecf6c completednext: flow replay d3b6167ecf6c
cat payments/ledger.txtA-1042 40 re_1042

The second request reached the provider with the same idempotency key as the first, so the provider recognised it, paid nothing more, and answered with the receipt it had already issued.

Catching every exception and raising Interrupted would have kept this run going, and it would have been wrong in a way nobody notices for a while: the program would have been told something the library didn't know. Letting a bug stop the run costs you an interruption today, against a wrong answer in the record forever.

The key

refund passes the provider an idempotency key built from context(), which describes the call being answered: its run and its call, the call's place in the run. Together they are the call's key. The key stays the same when the call is sent again, after a crash or after a fix, so a provider that remembers keys pays once however many times the request arrives. The stand-in remembers them in keys.txt.

Flow doesn't send a call twice by itself, as A payment that timed out said. A person can, though, and When the process dies mid-call is about the moment you'll want to. The key is what makes that decision safe for this library. A service with no idempotency key needs the lookup instead, which is why find_refund is here too.

What replay starts

Replay runs the program against its record and never starts the library:

flow replay d3b6167ecf6cReplay d3b6167ecf6c: matchedNo tools were called.
cat payments/ledger.txtA-1042 40 re_1042

It needs only the contract, so a run can be checked on a machine that has no Python, no toolkit and no credentials for the provider.

What it costs

A library is a Python process the run starts and talks to for as long as the run's process lives. A library in your own project starts without asking, since it's your code; one fetched from a repository runs only after you approve it with flow approve, so read it first. The CLI brings the toolkit, which keeps a small library free of setup but ties it to the toolkit version of the flow you run, and Flow is young enough that the toolkit still changes. The library guide covers the rest.

Python isn't the only way in. A Rust library marks its functions #[tool] and derives its types, and flow build reads the crate the same way. A library in any other language is a process that speaks Flow's Tool protocol, named in a [process] table with the commands that serve it and write its contract. Any MCP server can be a library too, with a flow.toml that says how to start it; its tools become declarations, though an MCP server has no way to say NetworkError { sent }, so the program gets less to decide with.

Exercises

  1. Change RateLimited's field from seconds: int to seconds: float and run flow check main.flow. Then change it to retry_after: int. Which file changes, and does main.flow still check?
  2. Run PROVIDER=busy flow run main.flow order=A-1042 dollars=40. Which arm of main.flow takes the answer?
  3. Make refund raise NotStarted when dollars is zero or less, before calling the provider. What does a run with "dollars":0 end as, and what is in payments/ledger.txt?
  4. Delete the except provider.Unreachable lines and run with PROVIDER=down. The run stops the same way the missing Timeout did. What would you have answered for this call, and why is it a different answer from the one above?