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#
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#
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#
| Name | Where | Description |
|---|---|---|
model | Model(...) first argument | The model's name, as the API knows it (on Midium, the name in Settings → Models). |
base_url | Model(..., base_url=) or COURIER_OS_BASE_URL | The API's base URL, with /v1 — for Midium, http://127.0.0.1:9100/v1. OPENAI_BASE_URL works too. |
api_key | Model(..., api_key=) or COURIER_OS_API_KEY | Your key. OPENAI_API_KEY works too. |
timeout | Model(..., 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:
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.
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:
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.type | event.data |
|---|---|
content.delta | A piece of the model's text. |
tool_calls.delta | A piece of a tool call as it streams. |
tool_call.start | A tool is about to run. |
tool_call.result / tool_call.error | A tool finished, or raised. |
iteration.end | One model turn with tool calls is done. |
finish | The final finish_reason. |
Structured output#
Pass a Pydantic model as response_format and read .parsed:
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:
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:
| Field | Description |
|---|---|
content | The final answer's text. |
parsed | The response_format model instance, when you passed one. |
messages | The whole conversation, tool turns included. |
tool_calls | Every tool call made, with its arguments and result. |
iterations | How many model turns the loop took. |
finish_reason | The last turn's finish reason. |
usage | Token counts (prompt_tokens, completion_tokens, total_tokens). |
More in the SDK#
Operator(agent, max_tool_iterations=N)— cap the loop;MaxToolIterationsErroris raised past it, carrying the partial result.relay(..., web_search=True)— adds Midium'sweb_searchtool, which Midium runs itself with Brave Search (see Tool calling).relay()also takestemperature,top_p,max_tokens,stopandextra_body.Model.chat()/Model.chat_stream()— one model call, no tool loop.relay_async()— the same loop withasync/await;awaitit, orasync forover it withstream=True.AsyncSessionis 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 ofCourierOSError.
Something here wrong or out of date? Tell us.
