Skip to main content

Build AI agents in Python with the FleetQ API

FleetQ has a plain REST API, so you can drive agents, budgets and human approvals from a Python script. The examples below use requests. There is no SDK to install: it is plain HTTP and JSON, so the same calls work from any language.

The base URL is https://<your-host>/api/v1: your Cloud address or your own self-hosted server.

1. Get an API token

Create a token in Team settings, in the API tokens section. With an existing token you can also create one over the API with POST /api/v1/team/tokens. The response holds the plain-text token once; store it somewhere safe. Send it on every request as Authorization: Bearer <token>.

import os
import requests

BASE = "https://fleetq.net/api/v1"  # or your self-hosted host
session = requests.Session()
session.headers.update({
    "Authorization": f"Bearer {os.environ['FLEETQ_TOKEN']}",
    "Accept": "application/json",
})

# Optional: create another token for this script (returns 201)
r = session.post(f"{BASE}/team/tokens", json={"name": "python-scripts"})
r.raise_for_status()
new_token = r.json()["data"]["token"]

2. Talk to an agent

Send a message with POST /api/v1/agents/{agent}/chat (limited to 60 requests a minute). The agent must have the chat protocol enabled. Required fields: msg_id (a new UUID), session_id (a UUID you keep for the whole conversation), timestamp (ISO 8601), from, to and content. response_url and metadata are optional.

The reply is asynchronous. The call returns 202 with ack, message_id and status: "accepted". When the agent finishes, FleetQ POSTs its answer as JSON (content, in_reply_to, session_id) to your response_url.

import uuid
from datetime import datetime, timezone

agent_id = "YOUR-AGENT-UUID"
conversation = str(uuid.uuid4())  # reuse for follow-up messages

r = session.post(f"{BASE}/agents/{agent_id}/chat", json={
    "msg_id": str(uuid.uuid4()),
    "session_id": conversation,
    "timestamp": datetime.now(timezone.utc).isoformat(),
    "from": "python-script",
    "to": agent_id,
    "content": "Summarise yesterday's support tickets.",
    "response_url": "https://example.com/fleetq/reply",  # receives the answer
})
assert r.status_code == 202
print(r.json()["status"])  # "accepted"

3. Start a governed run

A run with a budget and approvals is an experiment. POST /api/v1/experiments takes title, thesis, track (one of growth, retention, revenue, engagement, debug, workflow, web_build), budget_cap_credits and an optional workflow_id. It returns 201.

A new experiment starts as draft and does not run by itself. Start it with POST /api/v1/experiments/{id}/transition; from draft you can move to scoring, planning or executing. Then poll GET /api/v1/experiments/{id} for its status.

import time

r = session.post(f"{BASE}/experiments", json={
    "title": "Weekly churn report",
    "thesis": "Find accounts at risk and draft a retention email for each.",
    "track": "retention",
    "budget_cap_credits": 500,
})
r.raise_for_status()  # 201
experiment_id = r.json()["data"]["id"]

# Draft experiments wait until you start them
session.post(f"{BASE}/experiments/{experiment_id}/transition",
             json={"status": "scoring"}).raise_for_status()

def status():
    data = session.get(f"{BASE}/experiments/{experiment_id}").json()["data"]
    return data["status"], data

STOP = {"awaiting_approval", "paused", "completed", "killed", "discarded", "expired"}

current, data = status()
while current not in STOP and not current.endswith("_failed"):
    time.sleep(10)
    current, data = status()

4. Approvals

When the status is awaiting_approval, a person has to decide. List the pending approvals for the run with GET /api/v1/approvals?filter[status]=pending&filter[experiment_id]=<id>. Approve with POST /api/v1/approvals/{id}/approve (optional notes) or reject with POST /api/v1/approvals/{id}/reject (reason is required, notes optional).

if current == "awaiting_approval":
    pending = session.get(f"{BASE}/approvals", params={
        "filter[status]": "pending",
        "filter[experiment_id]": experiment_id,
    }).json()["data"]

    for approval in pending:
        approval_id = approval["id"]
        ok = input(f"Approve {approval_id}? [y/N] ") == "y"
        if ok:
            session.post(f"{BASE}/approvals/{approval_id}/approve",
                         json={"notes": "Looks good"}).raise_for_status()
        else:
            session.post(f"{BASE}/approvals/{approval_id}/reject",
                         json={"reason": "Wrong audience"}).raise_for_status()

5. Cost and budget pause

GET /api/v1/experiments/{id}/cost returns what the run has spent. If spend goes over the budget, FleetQ pauses the run automatically: the status becomes paused, paused_from_status holds the step it stopped at, and you can compare budget_spent_credits with budget_cap_credits. After you raise the budget, continue with POST /api/v1/experiments/{id}/resume.

cost = session.get(f"{BASE}/experiments/{experiment_id}/cost").json()
print(cost)

current, data = status()
if current == "paused":
    print("Paused at", data["paused_from_status"],
          "spent", data["budget_spent_credits"], "of", data["budget_cap_credits"])
    # raise the budget first, then:
    session.post(f"{BASE}/experiments/{experiment_id}/resume").raise_for_status()

Prefer httpx? Use httpx.Client(headers=...) in place of requests.Session(); the URLs, JSON bodies and responses are the same, and httpx.AsyncClient works for async code.

Cloud or your own server

The same API runs in the Cloud and on a self-hosted install. To run it yourself, read the self-hosting guide.

Star the repository on GitHub, or start free in the Cloud: https://fleetq.net.