Skip to main content

firetail_finchly

Python SDK for the Finchly platform. A service or app uses it to register with a Finchly deployment, verify who is calling it, and reach the platform's database, object store, queue and other services.

Status: early. The package is tested, but only the first five modules exist.

The SDK implements the platform API, which is specified in FireTail-io/finchly under spec/. This release speaks platform API v1 (draft).

Install

pip install firetail_finchly

Requires Python 3.10 or later. Depends on PyJWT with its crypto extra. The db module also needs psycopg, installed with the db extra.

Use

from firetail_finchly import load_config, load_manifest

config = load_config()                         # reads PLATFORM_* settings
manifest = load_manifest(config.manifest_path)

Both raise a FinchlyError with a stable code and a problems tuple that names everything wrong, so a misconfigured container fails once with the full picture.

Who is calling

The gateway puts a short-lived signed token in the x-platform-identity header of every request it proxies. It is the only identity a service should accept.

from firetail_finchly import IdentityError, IdentityVerifier

# Once, at startup. It caches the gateway's issuer and signing keys, and
# is safe to share between threads.
identity = IdentityVerifier(slug=manifest["slug"], gateway_url=config.gateway_url)

# Per request.
try:
    caller = identity.from_headers(request.headers)
    caller.tenant_id # the tenant this request is for
    caller.subject   # user id, or "service:<slug>"
    caller.email     # None for a service calling as itself
    caller.groups    # platform groups
    caller.roles     # roles for this service: "user", "operator"
    caller.actor     # "service:<slug>" when a service acts for the user
except IdentityError as err:
    ...  # Unauthenticated: respond 401. err.reason is for logs only.

Any other FinchlyError from the verifier means the gateway could not be reached; respond 503.

A token is rejected unless it is signed with ES256 by a key the gateway publishes, names that gateway as issuer and this service as its only audience, and has not expired. The rules are in spec/identity-token.md in FireTail-io/finchly.

The tenant. One deployment serves several tenants, and every request is for exactly one: caller.tenant_id. Do everything for the caller within that tenant, and store whatever you keep for them under it. Take it from the verified identity only, never from a path, a header or a request body. A token that names no tenant is rejected.

No other header is ever consulted. On a path the manifest declares in publicPaths there is no token, and the service authenticates the request itself.

Calling another service

Services never address each other directly. A call goes through the gateway, signed by this instance's own key.

from firetail_finchly import ServiceClient

# Once, at startup. Safe to share between threads.
service = ServiceClient(
    slug=manifest["slug"],
    gateway_url=config.gateway_url,
    credential=config.service_credential,
)
service.start()   # optional: fail now, not on the first call

# As the service itself, for the tenant of the request being handled.
response = service.call(
    "notification-service",
    "/api/send",
    tenant_id=caller.tenant_id,
    method="POST",
    headers={"Content-Type": "application/json"},
    body=b'{"text": "hello"}',
)
response.status, response.headers, response.body, response.json()

# For a user: the target sees that user, and this service acting for them.
service.call(
    "notification-service",
    "/api/inbox",
    tenant_id=caller.tenant_id,
    as_user=caller.subject,
)

call returns the response, whatever its status.

  • tenant_id says which tenant the call is for. The target then works within that tenant. Pass it on every call to another service, and always from a verified identity. A user named in as_user must belong to it.
  • 403 means this service's manifest does not list the target in calls, or the user has no access to the target.
  • A redirect is handed back, not followed.
  • Nothing is retried. After a 401 the next call registers the key again, in case the gateway no longer knows it.

To use another HTTP client, such as requests or httpx, take the address and the header from the client and send the request yourself. A token is for one target and is valid for a minute, so get fresh headers each time:

requests.post(
    service.url("notification-service", "/api/send"),
    headers=service.headers("notification-service", tenant_id=caller.tenant_id),
    json={"text": "hello"},
    allow_redirects=False,
)

The instance makes an ES256 key pair in memory the first time it is needed. The private half never leaves the process. The public half is registered with the gateway using the credential the service was deployed with, and extended by itself for as long as the instance runs. The rules are in spec/service-token.md and spec/registration.md in FireTail-io/finchly.

An app registers itself

A built-in service has a credential. An app does not: it registers itself with the platform, and that is what gets its key accepted. Give the client an enrolment in place of a credential:

from firetail_finchly import ServiceClient, enrolment_from, load_config, load_manifest

config = load_config()
manifest = load_manifest(config.manifest_path)

service = ServiceClient(
    slug=manifest["slug"],
    gateway_url=config.gateway_url,
    credential=config.service_credential,          # a built-in service
    enrolment=enrolment_from(config, manifest),    # an app
)
service.start()

enrolment_from reads the enrolment token (PLATFORM_ENROLMENT_TOKEN) and the app's address (PLATFORM_APP_ADDRESS, or this machine's hostname and the manifest's port). It returns None when there is no token, so the same code serves a built-in service and an app.

Registration is the first call the client makes, and it sends the manifest exactly as it was loaded. What can come back:

Error code Meaning What to do
none Registered. Calls work
app_pending_approval The release waits for an administrator: it asks for more than the last one, or the app is at an address the deployment does not expect Keep running and try again. The client does not ask the platform again before it was told to
app_registration_refused The platform refused, and problems says why: a bad token, a manifest or address it will not accept, a lower version than the one running Fix the deployment. Trying again will not help
gateway_unreachable The gateway could not be reached Try again

The protocol is in spec/registration.md in FireTail-io/finchly.

The other half of the app module is not built: serving the /{slug}/_platform/* endpoints, which let an administrator register an app that is already running, and fetching the settings the platform creates for an app.

A database of its own

A service whose manifest sets permissions.db is given a PostgreSQL schema of its own for each tenant that uses it. The db extra installs psycopg:

pip install 'firetail_finchly[db]'
from pathlib import Path
from firetail_finchly import connect_database

# Once, at startup. Asks the platform for the role and schemas it made,
# and brings every tenant's schema up to date. Safe to share between threads.
database = connect_database(service=service)
database.migrate(Path(__file__).parent / "migrations")

# Per request: the database of the caller's tenant.
db = database.for_tenant(caller.tenant_id)

rows = db.execute("SELECT id, body FROM notes WHERE author = %s", [caller.subject]).rows

with db.transaction() as tx:
    tx.execute("INSERT INTO notes (body, author) VALUES (%s, %s)", ["hello", caller.subject])
    tx.execute("UPDATE authors SET notes = notes + 1 WHERE id = %s", [caller.subject])

# One instance at a time, for this tenant, across every instance of this service.
with db.advisory_lock("nightly-import") as tx:
    ...
  • There is no database without a tenant. SQL is run on the handle for_tenant gives, and happens in that tenant's schema. Take the tenant id from a verified identity, never from the request itself.
  • Names need no schema. notes means that tenant's table. The service cannot read the platform's tables or another service's, and working for one tenant it cannot reach another's.
  • Values go in the second argument, as %s. They are never built into the SQL. Rows come back as dicts.
  • A transaction commits if its block ends and rolls back if it raises.
  • Migrations are files named NNNN_name.sql, applied in order, once each, in every tenant's schema. Every instance may call migrate at startup: they take turns. A tenant that starts using the service later is migrated the first time its database is used. A migration that was applied is never edited; add a new one. A problem is a FinchlyError with code migration_invalid.
  • Work with no request behind it, such as a schedule, runs once for each tenant: database.tenants() lists them.
  • connect_database raises database_not_granted if the manifest does not ask for a database, and database_unavailable if the platform or the database cannot be reached. Using a tenant the service has no database for raises database_not_granted.
  • TLS. Where the deployment's database has a certificate authority of its own, as a managed PostgreSQL does, the platform says which with the URL. The connection is then encrypted and accepts only a certificate from that authority. There is nothing to configure.

To run a service on its own, without a platform, give the URL directly: connect_database(url=..., slug=...). Each tenant's schema is then made the first time it is used. ca names that database's certificate authority, as PEM text, if it has one of its own.

Hosted agents

A service whose manifest sets permissions.agents can list the agents it hosts on people's dashboards:

from firetail_finchly import create_agents

agents = create_agents(service=service)
mine = agents.for_tenant(caller.tenant_id)  # from a verified identity
agent = mine.publish(
    "expense-helper",
    name="Expense helper",
    description="Answers questions about the expenses policy",
    path="/agent-studio/agents/expense-helper",
    users=[caller.subject],  # omit for everyone who may use the service
)
mine.list()  # PublishedAgent objects, with updated_at as a datetime
mine.withdraw("expense-helper")  # False if already absent

The id is 1 to 64 letters, digits, dots, dashes or underscores, starting with a letter or digit. The path must stay under the hosting service's /{slug}/ prefix. Publishing again replaces the description; omitted optional fields are cleared. users narrows who sees the agent, never who can access its service. The service must enforce access to the agent itself.

At most 500 agents may be published per service per tenant. A missing manifest permission raises agents_not_granted, a full list raises agents_limit_reached, and other platform refusals raise agents_unavailable.

Secrets

A service whose manifest sets permissions.secrets keeps secrets with the platform, separately for each tenant:

from firetail_finchly import create_secrets

secrets = create_secrets(service=service)

# Per request: the secrets of the caller's tenant.
mine = secrets.for_tenant(caller.tenant_id)

mine.set("slack.token", token)
value = mine.get("slack.token")  # None if there is none
mine.list()  # ["slack.token"]
mine.delete("slack.token")  # True if there was one
  • A name is 1 to 100 letters, digits, dots, dashes or underscores. A value is text of at most 64 KiB. Do not log a value.
  • A tenant's secrets are read with that tenant's id and no other. Take the id from a verified identity, never from the request itself.

For values the service keeps in its own tables, the platform encrypts and decrypts under the tenant's key:

sealed = mine.encrypt(card_number, f"card:{card_id}")
opened = mine.decrypt(sealed, f"card:{card_id}")  # bytes

The context says what the value is. The same context must be given to decrypt, so a value copied to another row does not open there. What was encrypted for another tenant, another service or another context, or has been changed, raises secrets_cannot_decrypt.

A manifest that does not ask for secrets gets secrets_not_granted. Any other refusal is secrets_unavailable.

Objects

A service whose manifest sets permissions.blobs keeps objects with the platform, separately for each tenant: receipts, exports, files. The service holds no credentials for the object store. For each read and write the platform signs an address for that one object, and the bytes go straight to the store or come straight from it.

from firetail_finchly import create_blobs

blobs = create_blobs(service=service)

# Per request: the objects of the caller's tenant.
mine = blobs.for_tenant(caller.tenant_id)

mine.put(f"receipts/{receipt_id}.pdf", data, content_type="application/pdf")
receipt = mine.get(f"receipts/{receipt_id}.pdf")  # None if there is none
receipt.data  # bytes
receipt.content_type  # "application/pdf"

page = mine.list(prefix="receipts/", limit=100)  # page.objects, page.next
mine.delete(f"receipts/{receipt_id}.pdf")
  • A key is 1 to 512 letters, digits, dots, dashes and underscores, in segments divided by /. Do not use a key that is also the start of another followed by /, such as a and a/b.
  • put takes text or bytes held in memory. For a file or a stream, use upload, below.
  • A tenant's objects are reached with that tenant's id and no other. Take the id from a verified identity, never from the request itself.
  • A listing is in key order. When page.next is not None there are more: ask again with after=page.next.

Two writers do not lose each other's work if each writes on a condition:

# Only if there is none by that key. None if there was.
made = mine.put_if_absent("state.json", "{}", content_type="application/json")

# Only if it has not changed since it was read. None if it has:
# read again and decide again.
state = mine.get("state.json")
changed = change(json.loads(state.data))
written = mine.put_if_match("state.json", json.dumps(changed), state.etag, content_type="application/json")

State that needs transactions or queries belongs in the service's database, not in an object.

A file, or anything else that gives its content a piece at a time, is written with upload, without holding it in memory. It is sent in parts, so its length need not be known, and it may be very large:

with open(path, "rb") as source:
    etag = mine.upload(f"exports/{export_id}.csv", source, content_type="text/csv")
  • The source is a file opened for reading, or any iterable of text and bytes, such as a generator.
  • part_size is how much is sent at a time: 16 MiB unless told otherwise, and at least 5 MiB on S3. An object is at most 10,000 parts there.
  • concurrency is how many parts are sent at once, each on a thread of its own: 4 unless told otherwise, 16 at most. That many parts are held in memory.
  • if_absent=True or if_match=etag writes on a condition, as put_if_absent and put_if_match do; upload then returns None if it did not hold.
  • If sending fails part way, what was sent is thrown away and there is no object.

An address can be handed on, so that a file goes between a browser and the store without passing through the service:

# To fetch one object with a plain GET.
url = mine.presign_get(f"receipts/{receipt_id}.pdf", expires_seconds=60)

# To send one object of a stated size: a PUT to `to.url` with exactly `to.headers`.
to = mine.presign_put(f"uploads/{upload_id}", size=size, content_type=content_type, expires_seconds=300)
  • An address is for that one object and that one use. One made to send takes exactly that content type and that many bytes.
  • Whoever holds an address can use it until it runs out, with no sign-in: 1 to 3600 seconds, default 300. Ask for the shortest that will do, and do not log one.
  • The same addresses serve to stream an object too large to hold in memory.

A file too large for one request is handed on in parts. The service begins the upload and gives out an address for each part; whoever holds them sends the parts and reports the etag the store answered for each; the service has them put together:

begun = mine.begin_upload(f"uploads/{upload_id}", content_type=content_type)
addresses = mine.presign_parts(
    f"uploads/{upload_id}",
    begun.upload_id,
    [{"number": 1, "size": first_size}, {"number": 2, "size": second_size}],
)
# ... each part is sent with a PUT to its `url`; its etag is in the answer's header named by `etag_header` ...
etag = mine.complete_upload(
    f"uploads/{upload_id}",
    begun.upload_id,
    [{"number": 1, "etag": first_etag}, {"number": 2, "etag": second_etag}],
)
# Or, if it will not be finished:
mine.abort_upload(f"uploads/{upload_id}", begun.upload_id)
  • Parts are numbered from 1. Every part but the last is at least begun.min_part_bytes. Up to 100 addresses are given at once.
  • An upload belongs to the tenant, the service and the key it was begun for. Keep upload_id with the user's session, and take the tenant from the caller's identity each time, as everywhere else.
  • complete_upload takes if_absent or if_match, and then returns None if the condition did not hold.
  • An upload nobody completes is given up by the platform after 24 hours without a part being asked for.

A tenant may have a check on files: a hook, which looks at each file before it is kept and may refuse it. Nothing changes in how objects are written, and three things follow:

  • A write may be refused. It raises blobs_refused, whose message is the check's own words, written for whoever sent the file.
  • A large object, or one sent in parts, is held aside in the store until the check has let it through, and is the object only then. put, upload and complete_upload wait for that, for check_seconds (default 120). If the check takes longer they raise blobs_checking, and the object is kept or refused later: ask with confirm_upload.
  • An address that is handed on must be confirmed. presign_put then returns staged as well. What a browser sends there is not the object until the service says it was sent:
to = mine.presign_put(f"uploads/{upload_id}", size=size, content_type=content_type)
# ... the browser sends the file to to.url ...
if to.staged:
    upload = mine.confirm_upload(f"uploads/{upload_id}", to.staged)  # waits up to 60 seconds, unless told otherwise
    # upload.state is "kept" (with upload.etag), "checking" (ask again) or "unmet" (its condition did not hold)

begin_upload returns staged in the same case, for an upload whose check outlasts complete_upload. With no such check staged is None, and there is nothing to confirm.

A manifest that does not ask for objects gets blobs_not_granted. Any other refusal, a deployment with no object store among them, is blobs_unavailable.

A deployment may limit how much a tenant keeps, over all its services. A write the tenant has no room for raises blobs_limit_reached: put and its variants, upload, presign_put and presign_parts. It is not a fault to retry. Tell the user, or delete what is no longer needed and write again. Reading, listing and deleting are never refused for it.

A deployment whose store signs no addresses (a development store) passes objects through the platform instead: get, put and upload work the same, up to 16 MiB an object, and presign_get, presign_put and begin_upload raise blobs_unavailable.

None of this depends on which object store the deployment uses.

The queue

A message belongs to a tenant. The manifest lists the topics the service publishes to and consumes, in permissions.queue.publish and permissions.queue.consume.

from firetail_finchly import create_queue

queue = create_queue(service=service)

# Per request: publish for the caller's tenant.
queue.for_tenant(caller.tenant_id).publish("notifications", [{"to": caller.subject, "text": "Done"}])

# A worker: take messages of every tenant, and handle each in its own.
for message in queue.lease("notifications", max=10, visibility_seconds=60):
    db = database.for_tenant(message.tenant_id)
    try:
        deliver(db, message.body)
        message.ack()
    except Exception:
        message.retry()
  • Publishing takes 1 to 100 bodies, each any JSON value of at most 256 KiB, and returns their ids. All are published or none. delay_seconds holds them back, up to 7 days.
  • Leasing hands out messages for visibility_seconds (default 60). A message not answered for in that time is handed out again. An empty list means there is nothing to do; ask again later. tenant_id takes one tenant's messages only.
  • Each message says which tenant it is for. Handle it in that tenant.
  • Answer for every message: ack() when it is handled, retry() to have it handed out again after a wait that doubles each time (or retry(delay_seconds=...)), dead_letter(reason) when it never will be handled. Each returns False if the time ran out and the message went to another consumer. A message handed out five times without being handled is set aside.
  • A message may be handed out more than once, so handling one twice must be harmless.
  • A topic the manifest does not list raises queue_not_granted. Any other refusal is queue_unavailable.

Models

A service that uses a model says so in its manifest, and what for:

{ "permissions": { "llm": true },
  "models": [{ "task": "write", "purpose": "Drafts a report from your notes" }] }

Each tenant's administrators choose which model does which kind of task. The service asks the platform, naming the kind of task, and the platform calls the model the tenant chose. The service holds no provider's credentials and names no model.

from firetail_finchly import create_models

models = create_models(service=service)

# Per request: the models of the caller's tenant.
mine = models.for_tenant(caller.tenant_id)

answer = mine.chat({
    "model": "write",  # the kind of task, as the manifest lists it
    "messages": [
        {"role": "system", "content": "You draft short reports."},
        {"role": "user", "content": notes},
    ],
})
answer["choices"][0]["message"]["content"]

What is asked and what is answered are dicts in the shape of OpenAI's chat completions: messages, tools, tool_choice, response_format, max_completion_tokens. The kinds of task are chat, agent, code, write, summarise, extract, vision and embed.

  • Check finish_reason. stop: the model finished. tool_calls: run the tools and ask again. length: the answer is cut short. content_filter: the model declined, and refusal says so.
  • Tools. Append the model's message to the conversation as it came, then one tool message for each call, and ask again. The message carries the model's turn (finchly.state), which you do not read and must not drop. A call's arguments is JSON text the model wrote: parse it and check it before acting on it. "tool_choice": "required" asks firmly, and not every model can be made to call a tool, so check that a call came back.
  • Images. A user message may have image_url parts whose url is a data: URL holding a PNG, JPEG, GIF or WebP in base64. An address is refused: the platform fetches nothing.
  • JSON. "response_format": {"type": "json_schema", "json_schema": {"name": ..., "schema": ...}} holds the model to a schema, where the model can be held. Give every object additionalProperties: false and list every property in required. {"type": "json_object"} asks for JSON of any shape: parse the answer, and be ready for it not to be JSON.
  • An answer comes whole within 100 seconds. Stream what may be long.

As it is written. stream gives the pieces as they arrive, and the whole answer when it is done:

stream = mine.stream({"model": "chat", "messages": messages})
for piece in stream:
    for choice in piece["choices"]:
        print(choice["delta"].get("content") or "", end="")
whole = stream.completion()  # as chat() would have given it
messages.append(whole["choices"][0]["message"])

Embeddings. With embed in the manifest's models:

made = mine.embed(["First text", "Second text"])
made["embeddings"]  # one vector for each text, in order

Keep made["model"] with what you store: vectors from different models cannot be compared, and a tenant may change its embedding model.

Prompts. Keep what the service tells a model where a tenant can read it and change it. Register the defaults at startup, and ask for a prompt when it is used:

models.register_prompts([
    {"id": "report", "name": "Report drafting", "task": "write", "text": "You draft short reports."},
])

prompt = mine.prompt("report")  # {"id", "text", "modified"}, or None

text is the tenant's own where it has written one, else the default. Use what comes back, not the text in your code.

Variables. Say what a prompt's text has blanks for, and the platform holds the text to it:

models.register_prompts([
    {
        "id": "report",
        "name": "Report drafting",
        "task": "write",
        "text": "Write a short report for {{company}}.\nUse only these facts:\n{{facts}}",
        "variables": [
            {"name": "company", "description": "Who the report is for"},
            {"name": "facts", "description": "What the report may say"},
            {"name": "tone", "description": "How to write", "required": False},
        ],
    },
])

system = mine.render("report", {"company": caller_company, "facts": facts})
  • A variable is written {{name}} in the text. Its name is lower-case letters, digits and underscores, starting with a letter.
  • A variable is required unless it says not. The text must keep a required one: a tenant cannot save a text without it, so what you must say always has a place. One that is not required may be left out of the text, and of the values.
  • The text may use only the variables listed. The default is refused at registration if it does not fit, and a tenant's own text when it is saved.
  • render gives the tenant's text, or the default, with each variable replaced by its value. A value is put in as it is. It raises models_refused if a required variable has no value, or a value is for something the prompt does not take. render_prompt(prompt, values) does the same for a prompt you already have.
  • If you change a prompt's variables so that a tenant's text no longer fits, you are given the default until the tenant puts its text right.
  • Without variables, the text is kept as it is, and filling it in is yours to do.

OpenAI's client. If you already use it, point it at the platform:

from openai import OpenAI

client = OpenAI(**mine.openai())
client.chat.completions.create(model="write", messages=messages)

mine.model("write") says which model the tenant chose, or None if none: for showing, not for calling.

Code Means
models_not_granted The manifest does not set permissions.llm, or does not list the kind of task in models
models_no_model The tenant has chosen no model for this kind of task. An administrator chooses one
models_limit_reached The tenant's limit for the month, or this service's, is used up
models_refused What was asked is not taken, by the platform or by the model's provider. Asking again will not help
models_unavailable Anything else: the provider could not be reached, refused the tenant's credentials, or took too long

A model adapter

A service can stand in for a provider of models. A tenant that uses the service connects it on its Models page, and what that tenant asks of its models is then sent to the service, to send on to wherever the tenant's models are: an AI gateway of the organisation's own, for one, in whatever form the gateway takes. The manifest sets permissions.llmAdapter.

create_model_adapter answers the three routes the platform calls, checks that it is the platform calling, and turns what your functions give back into the answers the platform reads. You write the functions.

from firetail_finchly import (
    AdapterEnd, AdapterText, AdapterUsage, IdentityVerifier, ModelAdapterError, create_model_adapter,
)

def chat(request, caller):
    key = secrets.for_tenant(caller.tenant_id).get("gateway-key")
    upstream = ask_my_gateway(request, key=key, on_behalf_of=caller.user, app=caller.app)
    if upstream.status == 404:
        raise ModelAdapterError("model_not_found", f"The gateway knows no model called {request.model}")
    for text in upstream.text:
        yield AdapterText(text)
    yield AdapterEnd(AdapterUsage(upstream.used_in, upstream.used_out))

adapter = create_model_adapter(
    slug=config.manifest["slug"],
    identity=IdentityVerifier(slug=config.manifest["slug"], gateway_url=config.gateway_url),
    chat=chat,
    # Optional: with neither, a model's name is typed and the adapter makes no embeddings.
    models=lambda caller: ["corp-large", "corp-small"],
)

# In whatever serves your requests. With Flask:
@app.route("/<path:rest>", methods=["GET", "POST"])
def everything(rest):
    if adapter.handles(request.path):
        answer = adapter.handle(request.method, request.path, dict(request.headers), request.get_data())
        return Response(answer.body, answer.status, dict(answer.headers))
    ...
  • Who it is for. caller.tenant_id is from the verified identity token. One deployment serves several tenants: use that tenant's settings and credentials and no other's. caller.app is the service that asked the platform, caller.user the person it said it was asking for, and agent_id, agent_name and conversation_id where it gave them. These are for telling your gateway who is asking. They grant nothing.
  • Who may ask. Only the platform, as itself. Anything else is answered 401 or 403 before your functions are called.
  • What is asked. request.model is the name the tenant approved the model by. messages, tools, tool_choice and response_format are as OpenAI's chat completions have them, max_tokens is the most the model may write, and request.body is the request as it was sent.
  • The answer. Whole: AdapterChatAnswer(usage=..., text=..., tool_calls=...). As it is written: yield AdapterText and AdapterToolCallPiece, and last AdapterEnd(usage). Give whichever suits what you front: it is turned into what the platform asked for. usage is required, since it is what the tenant's use is counted from.
  • handle gives an AdapterResponse: a status, headers, and a body that is bytes, or for an answer as it is written an iterator of bytes to send as each comes.
  • When you cannot answer. Raise ModelAdapterError with model_not_found, rate_limited, rejected or failed, and a message for the tenant's administrators that holds no credential. Anything else raised is answered as a failure that says nothing of what it was, and given to on_error for your own log.
  • When the platform has gone, your generator is closed: stop asking your gateway.

A hook

A service can be asked about what happens in the platform, and refuse it or change it; or be told of it afterwards. A tenant that uses the service sets it as a hook on an event, one of the ways the manifest lists under permissions.hooks:

{ "permissions": { "hooks": [{ "event": "file.uploading", "mode": "sync" },
                             { "event": "file.uploading", "mode": "async" }] } }

create_hook_handler answers the route the platform asks by, checks that it is the platform asking, and answers in the shape the platform reads. You write a function for each event.

from firetail_finchly import (
    IdentityVerifier, allow_hook, block_hook, create_hook_handler, file_bytes, file_change, modify_hook,
)

def on_file(event):
    # Asked (sync): a file a person or an agent sent, before it is kept.
    found = scan(file_bytes(event.data), rules_for(event.tenant_id))
    if not found:
        return allow_hook()
    if found.fatal:
        return block_hook(f"{event.data['name']} holds {found.what}, which is not sent to agents here.")
    return modify_hook(file_change(event.data, content=redact(file_bytes(event.data), found)))

def after_file(event):
    # Told (async): the same file, once it was let through.
    archive.put(event.tenant_id, event.id, event.data)

hooks = create_hook_handler(
    slug=config.manifest["slug"],
    identity=IdentityVerifier(slug=config.manifest["slug"], gateway_url=config.gateway_url),
    on={"file.uploading": on_file},
    after={"file.uploading": after_file},
)

# In whatever serves your requests:
if hooks.handles(request.path):
    answer = hooks.handle(request.method, request.path, dict(request.headers), request.get_data())
    return Response(answer.body, answer.status, dict(answer.headers))
  • Who it is for. event.tenant_id is from the verified identity token. One deployment serves several tenants: decide by that tenant's rules and no other's. event.service is the service it happened in, event.user the person who did it, and event.process whether that was in a chat or an agent's run.
  • Who may ask. Only the platform, as itself. Anything else is answered 401 or 403 before your function is called.
  • The decision, for a hook that is asked: allow_hook(), block_hook(reason) or modify_hook(patch). The reason is shown to the person, or given to the agent: say what is wrong in words they can act on. A patch holds only what changes, and only what the event lets a hook change. For a file, file_change(event.data, name=..., content=...) makes one: the file stays the kind it was, and the hooks after yours and the platform go on with it as changed.
  • Time. A hook has as long as the tenant gave it, three seconds unless it said otherwise. One that takes longer, raises or decides nothing has not answered, and what that means is the tenant's to say: by default the thing is refused.
  • Told afterwards. A function under after is given the event once the thing was let through, and what it returns is not looked at. One that raises or takes too long is told again, later each time, five times in all. So it may be told of the same thing more than once: event.id is the same each time, and event.attempt says which try this is.
  • file.uploading carries name, mediaType, bytes and the file itself, which file_bytes(event.data) gives as bytes.
  • A file that is held aside. A file sent straight to the object store, or too large to travel with the event, is not in the event: it has event.data["staged"] in place of content. open_file(event, service=service) reads either kind into memory, up to max_bytes, and file_address(event, service=service) gives where a large one can be read a piece at a time. Only the hook that is being asked can open it, and it cannot be changed. Such a file can wait, so event.check is set and the hook may answer pending_hook(): it is asked again, a second later and then twice as long each time up to a minute, with the same event.id. How long it has in all is what the manifest says for the hook in maxSeconds, 30 unless it says otherwise and an hour at most; after that it has not answered. A hook that is told afterwards is told such a file was kept, and cannot open it.

The audit log

The gateway records every request to your service by itself. Record what your agents say and do, and an administrator can read a conversation back as it happened, with the tools that were called.

from firetail_finchly import create_audit

audit = create_audit(service=service)

# Per conversation, for the caller's tenant.
thread = audit.for_tenant(caller.tenant_id).conversation(
    conversation_id,  # yours to choose; left out, one is made
    user=caller.subject,
    agent_id=agent.id,
    agent_name=agent.name,
    model_id=model_id,
)

thread.user(message, turn=1)
thread.tool("search_documents", provider="docs", input=args, output=result, is_error=False, duration_ms=812, turn=2, seq=1)
thread.assistant(reply, turn=2)
thread.system("Run finished")

response.headers["x-conversation-id"] = thread.conversation_id
  • It never gets in the way. Each call returns at once and never raises. Rows are sent together a moment later, from another thread. What the platform will not take is dropped; on_error is told, if you give one.
  • Send x-conversation-id back on the response, and the gateway links the request to the conversation.
  • A conversation's id is 1 to 128 letters, digits and : _ . @ / -. Use one that means something where you have one: a thread in a channel, a run of a schedule.
  • user is the person the conversation is with. Take it from a verified identity. For a conversation no person began, say what did in initiated_by.
  • A tool's input and output are text, or anything JSON can hold. The platform takes out whatever is named like a secret, and keeps the first 32,768 characters of each. Leave them out for a tool whose arguments should not be kept.
  • Call audit.flush() when the service stops.

How a tenant's pages look

A tenant says what the platform is called for it, gives a logo and an accent colour, and the platform works out the rest. A page that uses the platform's kit links /_gateway/theme.css and needs nothing else. For what a stylesheet cannot reach (a message, a document, a page of your own), ask for the theme.

from firetail_finchly import create_theme

themes = create_theme(service=service)

theme = themes.for_tenant(caller.tenant_id).get()
theme.name             # "Acme"
theme.light["accent"]  # "#b4441c", as it can be read on a light page
theme.dark["accent"]   # the same accent, as it can be read on a dark one
theme.logo             # "/_gateway/theme/logo?v=…", or None

# The kit's own variables, for markup styled with its names.
style = ";".join(f"{name}:{value}" for name, value in theme.variables("light").items())
  • Any service may ask. The manifest asks for nothing, and nothing in a theme is secret.
  • It is kept for a minute for each tenant (cache_seconds), so asking with every message costs a call now and then. get(fresh=True) asks the platform whatever is kept. theme.version changes when anything of the theme does.
  • light and dark are whole palettes, each colour #rrggbb, by the platform's names (surfaceSunk, accentInk): the platform has already made the accent readable on each. theme.accent is what the tenant gave, or None.
  • A logo is a path on the address the tenant's people reach the platform at. Sent outside the platform, make it whole with that address. logo_dark is None where the one logo does for both.
  • mode is how the tenant's pages begin: system, light or dark.
  • A failure is theme_unavailable, with what the platform answered.

What every request carries

Every request this SDK makes to the platform says which SDK and which release is asking:

Header Value
x-platform-sdk firetail_finchly
x-platform-sdk-version This release, for example 0.0.6
x-platform-api-version The platform API version it speaks, v1

That covers fetching the gateway's issuer and keys, registering an instance key, registering an app, and every call to another service. On a call the headers reach the target service too, and a caller cannot replace them. service.headers() includes them, for use with another HTTP client.

Settings

Variable Required Meaning
PLATFORM_GATEWAY_URL yes The gateway's internal address
PLATFORM_MANIFEST_PATH no Manifest path in the container. Default /finchly/manifest.json
PLATFORM_APP_ADDRESS no Address the gateway should use to reach this service
PLATFORM_ENROLMENT_TOKEN no Token for self-registration
PLATFORM_SERVICE_CREDENTIAL no What a built-in service registers its instance key with

The enrolment token and the service credential are left out of the config's repr, so logging the config does not leak them.

Modules

The Python SDK may trail the Node SDK for modules that only Node services use.

Module What it does State
config Read and validate the platform settings Done
manifest Load the manifest and check what the SDK depends on Done
identity Verify x-platform-identity Done. Directory lookups (list_users, members_of) and require_* helpers are planned
app Register with the platform, serve /_platform/*, renew keys, fetch settings Self-registration and key renewal are done, through service. Serving /_platform/* and fetching settings are not
service Call other services through the gateway, as the service or for a user Done, for built-in services and for apps
db PostgreSQL: queries, transactions, advisory locks, migrations Done
blobs Objects, with conditional writes and addresses to hand on Done
queue Publish, lease, ack, retry, dead-letter Done
secrets Secrets, and encryption under the tenant's key Done
agents Publish, list and withdraw agents a service hosts Done
adapters Stand in for a provider of models: front a tenant's own AI gateway Done
hooks Be asked about what happens in the platform, and refuse it Done
models Ask the model a tenant chose, as it is written or whole; embeddings; prompts a tenant can change Done
audit Record conversations and tool calls in the tenant's audit log Done
theme How a tenant's pages look: its name, logo and colours, for what a stylesheet cannot reach Done
usage, notify, schedule, connectors Clients for platform services Planned
ui Shared header, footer and theme Not planned; Node only

The manifest check here is not the full schema. The platform runs the full check at registration and is the authority.

Changes

See CHANGELOG.md.

Metadata

Release files for firetail-finchly 0.0.19

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for firetail-finchly 0.0.19
File Size Uploaded Provenance Actions
firetail_finchly-0.0.19.tar.gz 89.1 kB With provenance Details for firetail_finchly-0.0.19.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for firetail-finchly 0.0.19
File Interpreter ABI Platform Actions
firetail_finchly-0.0.19-py3-none-any.whl Python 3 none any Details for firetail_finchly-0.0.19-py3-none-any.whl

Total release size: 173.8 kB

Release files / firetail_finchly-0.0.19.tar.gz

Download URL firetail_finchly-0.0.19.tar.gz
Size 89.1 kB
Tags Source
SHA-256 checksum
How to use checksums
44f0d8a4cc8af2af5ed4592074a1c32120e69b9c8026bcd2a50112142bea719f
BLAKE2b-256 checksum
How to use checksums
16cf27a4c7119c926fff32c025e502b39915ecddbad74bfcb7828a99d75b1dc8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 17, 2026.

Transparency log

Release files / firetail_finchly-0.0.19-py3-none-any.whl

Download URL firetail_finchly-0.0.19-py3-none-any.whl
Size 84.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
dc474ed4bd68d5f10ebec0bed694d5009879affa4cb1938ca9299e0b2177e56f
BLAKE2b-256 checksum
How to use checksums
67a3ade85909dcf2aa0b02bf2fc4e00d85ff1d5dde90fa62f8986528a65c563b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 17, 2026.

Transparency log

Security for firetail-finchly 0.0.19

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for firetail_finchly-0.0.19.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 17, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page