The System One EventUtahGo To Event Page →

Docs

Set up Midium, use every part of it, run it for your team, and build on it.

Python SDK

courier-os, Midium's Python agent SDK — tools from plain functions, a managed tool loop, streaming, durable sessions and structured output, against Midium or any OpenAI-compatible API.

For developers

The Midium SDK is a Python library for building tool-using agents. It's published on PyPI as courier-os (import courier_os), version 0.1.6, Apache-2.0, for Python 3.11 and later. Point it at Midium on this Mac or at any OpenAI-compatible API — the agent code is the same either way. Its only dependencies are httpx, pydantic and python-dotenv.

Install#

Shell
pip install courier-os
# or
uv add courier-os

The SDK also has a local extra (courier-os[local]) for running models in-process with MLX instead of through an API. It depends on courier-os-binary, which isn't on public PyPI yet, so the extra can't be installed from PyPI today. Use the API mode below, pointed at Midium — the models run on this Mac either way.

Quickstart#

Python
from courier_os import Agent, Model, Operator

def get_weather(city: str) -> dict:
    """Get the current weather for a city."""
    return {"city": city, "temp_f": 72}

model = Model("YOUR_MODEL", base_url="http://127.0.0.1:9100/v1", api_key="YOUR_API_KEY")
agent = Agent(model, tools=[get_weather])

out = Operator(agent).relay([{"role": "user", "content": "What's the weather in Denver?"}])
print(out.content)

Operator(agent).relay(messages) runs the whole tool loop: it calls the model, runs the tools it asks for, sends the results back, and repeats until the model answers without calling a tool.

Configuration#

NameWhereDescription
modelModel(...) first argumentThe model's name, as the API knows it (on Midium, the name in Settings → Models).
base_urlModel(..., base_url=) or COURIER_OS_BASE_URLThe API's base URL, with /v1 — for Midium, http://127.0.0.1:9100/v1. OPENAI_BASE_URL works too.
api_keyModel(..., api_key=) or COURIER_OS_API_KEYYour key. OPENAI_API_KEY works too.
timeoutModel(..., timeout=)Seconds per request. Default 60.

A .env file in the working directory is read automatically. With the two environment variables set, Model("YOUR_MODEL") is enough:

Shell
export COURIER_OS_BASE_URL=http://127.0.0.1:9100/v1
export COURIER_OS_API_KEY=$(midium key --bare)

Tools#

Any function with type hints is a tool. Its name becomes the tool's name, the docstring's first line its description, and the parameters its JSON Schema (a parameter without a type hint is treated as a string, with a warning). Pass functions in tools=; the @tool decorator is optional.

Python
from courier_os import tool

@tool
def search_orders(customer_id: str, limit: int = 5) -> list[dict]:
    """Find a customer's recent orders."""
    ...

What a tool returns is sent back to the model as its result. Agent(..., tool_choice=...) takes the same values as the API's tool_choice ("auto" by default). See Tool calling for how Midium handles the calls.

Streaming#

relay(..., stream=True) yields events through the whole loop:

Python
for event in Operator(agent).relay(
    [{"role": "user", "content": "What's the weather in Denver?"}],
    stream=True,
):
    if event.type == "content.delta":
        print(event.data, end="", flush=True)
    elif event.type == "tool_call.start":
        print(f"\n[calling {event.data['name']}]")
event.typeevent.data
content.deltaA piece of the model's text.
tool_calls.deltaA piece of a tool call as it streams.
tool_call.startA tool is about to run.
tool_call.result / tool_call.errorA tool finished, or raised.
iteration.endOne model turn with tool calls is done.
finishThe final finish_reason.

Structured output#

Pass a Pydantic model as response_format and read .parsed:

Python
from pydantic import BaseModel

class Weather(BaseModel):
    city: str
    temp_f: float

out = Operator(agent).relay(
    [{"role": "user", "content": "Weather in Denver, as JSON."}],
    response_format=Weather,
)
print(out.parsed)   # Weather(city='Denver', temp_f=72.0)

A plain response_format dict works too. See Structured output.

Sessions#

A Session is an append-only log of everything that happened — messages, tool calls, registered tools. Dump it anywhere (a file, Postgres, Redis, S3) and resume it later; the conversation and its tools survive a restart:

Python
from courier_os import Agent, Operator, Session

session = Session.open()
agent = Agent(model, tools=[get_weather], session=session)
Operator(agent).relay([{"role": "user", "content": "Remember: my name is Alex."}])
saved = session.model_dump()                 # store this

session = Session.resume(saved)              # later, maybe in another process
agent = Agent(model, session=session)
out = Operator(agent).relay([{"role": "user", "content": "What's my name?"}])

Tools defined at module level are re-bound automatically on resume. Pass Session.resume(saved, tools=[...]) for lambdas, closures or functions defined in __main__.

The result#

relay() returns a RelayResponse:

FieldDescription
contentThe final answer's text.
parsedThe response_format model instance, when you passed one.
messagesThe whole conversation, tool turns included.
tool_callsEvery tool call made, with its arguments and result.
iterationsHow many model turns the loop took.
finish_reasonThe last turn's finish reason.
usageToken counts (prompt_tokens, completion_tokens, total_tokens).

More in the SDK#

  • Operator(agent, max_tool_iterations=N) — cap the loop; MaxToolIterationsError is raised past it, carrying the partial result.
  • relay(..., web_search=True) — adds Midium's web_search tool, which Midium runs itself with Brave Search (see Tool calling). relay() also takes temperature, top_p, max_tokens, stop and extra_body.
  • Model.chat() / Model.chat_stream() — one model call, no tool loop.
  • relay_async() — the same loop with async/await; await it, or async for over it with stream=True. AsyncSession is the async session.
  • InterceptEvent (Operator(agent, on_intercept=...)) — watch or change the conversation mid-loop: append or replace messages, edit a tool result, register a tool, or stop.
  • ToolExecutor (Operator(agent, tool_executor=...)) — run tools somewhere else, such as a remote worker.
  • Errors: AuthError, InvalidRequestError, InvalidToolCallError, RateLimitError, ServerError, TransportError, all subclasses of CourierOSError.

Something here wrong or out of date? Tell us.