Skip to content

About

No description, website, or topics provided.

Resources

Stars

8 stars

Watchers

2 watching

Forks

Repository files navigation

FlyMy.AI

FlyMy.AI - the Agentic Cloud.

ᕦ[▀̿_▀̿]ᕤ ⚡ ◢▆[◉◡◉]▆◣ ⚡ o=[•_•]=o ⚡ ╾━[⊙▂⊙]━╼ ⚡ ¬[°□°]¬ ⚡ 凸[¬_¬]凸 ⚡ <|¤_¤|> ⚡ ʕ[•ᴥ•]ʔ ⚡ ╚[ʘᗜʘ]╝ ⚡ d[-_-]b ⚡ q[◔౪◔]p ⚡ \[T_T]/ ⚡ ✧[◕‿◕]✧ ⚡ =^.^=

FlyMy.AI is the Agentic Cloud - Agents. Models. Serverless.

Ship autonomous AI workers that plan, call tools (MCP), and deliver results - not just chat. Access any model through a unified API, or deploy your own custom models on serverless GPUs. One platform, pay per use, production-ready in minutes.

  • Agents: build autonomous workers that plan, execute tools, and return structured results - then freeze a good run into a reusable, deterministic instruction you call as an API.
  • Models: run any model through one unified API (image, video, audio, LLMs) in sync or async mode.
  • Serverless: deploy your own custom models on autoscaling GPUs.
  • MCP tools: plug in any MCP - web search, browsers, files, external APIs.

Agents tie everything together; Models and Serverless also work standalone - pick what you need and plug the rest in later.

Website

For more information, visit FlyMy.AI, read the docs, or join us on Discord.

Getting Started

This is the Python client for FlyMy.AI. Build and run agents, call any model, and drive serverless endpoints from Python - in sync or async mode.

Requirements

  • Python 3.8+

Installation

Install the FlyMyAI client using pip:

pip install flymyai

Authentication

Before using the client, you need to have your API key, username, and project name. In order to get credentials, you have to sign up on flymy.ai and get your personal data on the profile.

📚 Core documentation: docs.flymy.ai - full guides for agents, inference, and MCP tools.

Agents

Autonomous agents plan, call tools (MCP), and return structured results. Declare an input_schema to make an agent reusable with runtime {{ variables }}, then freeze a good run into a Markdown instruction you can re-run as an API.

import asyncio
from flymyai import AsyncAgentClient

async def main():
    async with AsyncAgentClient(api_key="fly-secret-key") as client:
        # 1. Attach a tool (browse the full catalog with client.tools.available())
        tool = await client.tools.create(mcp_tool="tavily")

        # 2. Create a reusable agent. {{ variables }} require an input_schema.
        agent = await client.agents.create(
            name="News Brief",
            goal="Find the biggest news about {{ topic }} on {{ date }}. Return a one-line headline.",
            tools=[tool.id],
            input_schema={
                "type": "object",
                "properties": {"topic": {"type": "string"}, "date": {"type": "string"}},
                "required": ["topic", "date"],
            },
        )

        # 3. Run with variables; stream progress; get the structured result
        run = await client.runs.create(
            agent_id=agent.id,
            idempotency_key="news-brief-tesla-2026-05-21-v1",
            variables={"topic": "Tesla", "date": "2026-05-21"},
        )
        async for event in client.runs.stream_events(run.id):
            print(f"[{event.type}] {event.message}")
        result = await client.runs.wait(run.id)
        print(result.output)

        # 4. Chat: append a follow-up message and continue the same run (the key makes
        #    a retry after a lost answer return the first answer, not a second message)
        await client.runs.append_message(
            run.id,
            text="Make it punchier.",
            idempotency_key="news-brief-tesla-2026-05-21-v1:punchier",
        )
        await client.runs.wait(run.id)

        # 5. Freeze into a reusable instruction, re-run with fresh variables - your API
        compilation = await client.agents.compile_from_run(run.id)
        later = await client.compilations.run_instruction_and_wait(
            compilation.id,
            idempotency_key="news-brief-bitcoin-2026-05-19-v1",
            variables={"topic": "Bitcoin", "date": "2026-05-19"},
        )
        print(later.output)

asyncio.run(main())

Browse one agent's saved versions without loading every instruction:

page = client.compilations.list_versions(agent_id, limit=20)
for version in page.results:
    print(version.id, version.name, version.is_live)
# Read older versions only when needed; the cursor is scoped and expires in 24h.
if page.next_cursor:
    older = client.compilations.list_versions(agent_id, cursor=page.next_cursor)
# Open a selected version explicitly.
# selected = client.compilations.get(version_id)

list_versions returns a SavedVersionPage with summary metadata, never full instructions, code, schemas or results. It fetches one page, defaults to 20 rows and accepts at most 50, within a 64 KiB JSON response. The async client exposes the same method with await. compilations.list() retains its full-data contract.

Other agent methods: client.tools.available() / provide_config() / call(), client.runs.get() / list() / cancel(), client.agents.update() / suggest_schema(), client.compilations.update() (edit a frozen instruction in place). To keep history, save an edit as a new version with client.compilations.save_instruction(execution_id=..., instruction_md=...), test it with run_instruction(compilation_id), then set_live(compilation_id); run_live(agent_id, idempotency_key=...) and the agent's schedule run the live version, get_live(agent_id) reads it, and set_live on an older version rolls back. A version keeps the model, effort, web search, tools and skills it was saved with (Compilation.pins; model and effort on each list_versions row), so its runs never pick up later edits of the agent; pins is None only for an older version, which runs on the agent's current settings. When client.agents.update() changes one of these settings on an agent with a live version, the live version stays as it is and the answer's new_version names a new version with the new settings that is not live: test it with run_instruction(new_version.id, ...), then set_live(new_version.id). A synchronous AgentClient with the same method names (no await) is also available. Full reference: docs.flymy.ai/agents.

What a run used and costs

client.runs.prices(run_id) lists every tool call and model answer of a run with its price in USD (Decimal). A row with settled=True shows what was charged; before the charge (within about 10 minutes of the call) it shows the estimate the charge will use. billing_settled turns true when the run has ended and everything is charged. llm_usage rows split the prompt into fresh and cached tokens, and reasoning_tokens explain part of output_tokens. A helper started by the agent is its own run; a trigger event names its run in execution_public_id.

price = client.runs.prices(run.id)
print(price.total_price, price.billing_settled)
for row in price.llm_usage:
    print(row.model, row.purpose, row.total_input_tokens, row.output_tokens, row.price)

# your newest runs, or the runs you name (up to 200)
spent = sum(p.total_price for p in client.runs.list_prices(limit=50))
both = client.runs.list_prices(ids=[run.id, other_run.id])

Adding funds and sending feedback

A call the balance cannot cover raises InsufficientBalanceError before anything runs. When the answer names them, shortfall_usd is how much the balance is short and top_up_url the page where the account owner adds funds (the web app's finances page, with no amount filled in). client.billing.create_top_up_link(amount_usd) makes a one-time payment link for whole US dollars (an int, no cents) within the account's limits (InvalidAmountError names minimum_usd and maximum_usd). Show checkout_url to the owner; nothing is charged until they pay. Too many links in an hour raise RateLimitedError with retry_after_seconds; its response_body names top_up_url too.

client.feedback.send(message, category=..., execution_id=..., tool=..., client=...) tells the FlyMyAI team about a real problem: a call or run that failed in a way you cannot fix, a wrong result, something missing from the catalog, a charge that looks wrong or misleading docs. category is one of FEEDBACK_CATEGORIES. The same message within 10 minutes is not sent again (deduplicated=True); too much feedback raises FeedbackRateLimitedError with retry_after_seconds. Never put secrets or personal data in a message.

from flymyai import InsufficientBalanceError

try:
    run = client.agents.run(agent.id, idempotency_key="nightly-report-42")
except InsufficientBalanceError as error:
    if error.top_up_url:
        print("Add funds:", error.top_up_url)
    else:
        # whole dollars: at least the shortfall rounded up, and the account minimum
        link = client.billing.create_top_up_link(10)
        print("Add funds:", link.checkout_url)

client.feedback.send(
    "The weekly report run stopped at the Sheets step twice with a timeout.",
    category="bug",
    execution_id="abc-defg-hij",
)

Both clients have these methods (await them on AsyncAgentClient); neither takes an idempotency key.

Webhooks: events to your own endpoint

client.webhooks sends platform events to a public https:// endpoint of yours, as Composio's webhooks do. The first event is connection.expired: a connected account stopped accepting FlyMyAI's access, its owner got an email, and data names the connection, its reconnect_url and the agents that use it (once a day per connection). client.webhooks.list().event_types lists every event type with its description.

Each event is one POST of {"id", "type", "created_at", "schema", "data"}, signed the Standard Webhooks way (webhook-id, webhook-timestamp, webhook-signature). The signing secret (whsec_...) is in the answer of create and rotate_secret only; store it where your receiver reads it. verify_webhook(body, headers, secret) checks a delivery (the raw body, before you parse it) and returns its event, or raises WebhookSignatureError (answer 400). event.id is the same on every retry, so use it to skip a repeat. Answer 2xx quickly: network errors, 408, 429 and 5xx are retried for about two hours, any other answer ends the delivery as failed.

created = client.webhooks.create(
    "https://example.com/flymyai/events",
    events=["connection.expired"],
    description="Reconnect alerts",
    idempotency_key="webhook-reconnect-alerts",
)
secret = created.secret  # shown once
client.webhooks.send_test(created.webhook.id)  # one webhook.test event
for delivery in client.webhooks.list_deliveries(created.webhook.id):
    print(delivery.event_type, delivery.status, delivery.last_status_code)
from flymyai import WebhookSignatureError, verify_webhook

def receive(body: bytes, headers) -> int:
    try:
        event = verify_webhook(body, headers, WEBHOOK_SECRET)
    except WebhookSignatureError:
        return 400
    if event.type == "connection.expired":
        tell_the_user(event.data["connection"]["name"], event.data["reconnect_url"])
    return 204

update(webhook_id, url=..., events=..., description=..., is_active=False) changes or pauses a webhook, delete(webhook_id) removes it, rotate_secret(webhook_id) replaces the secret at once. Writes take an optional idempotency_key; a replayed create or rotate_secret answers with secret=None. A refused URL, event or field raises InvalidWebhookError (field names it); an account has at most 10 webhooks (WebhookLimitError). Both clients have these methods.

Limits for automatic subagents

Ordinary client.agents.run(...) calls use the same delegation runtime as chat. Pass message="..." to send the first user request atomically with the start; client.runs.create(...) and both async methods accept it too. Keep the same message, variables and idempotency_key when retrying the same logical run. By default a run's helpers have no USD cap and no count limit. Pass subagent_limits={"cap_usd": "3", "max_children": 6, "max_parallel": 3} alongside the required idempotency_key to pin owner limits for a new run. None for cap_usd or max_children means no limit and cap_usd=0 disables helpers. The cap covers subagents and their tools; lead charges remain separate. The server validates limits before starting work and rejects a changed request under a reused idempotency key.

Sync and async clients support this option. Owner client.compilations.run_instruction(...) and run_instruction_and_wait(...) accept it too; omission inherits the frozen source run's limits. Scheduled runs inherit those limits automatically. Embedded customer calls cannot override owner limits. Owner run responses expose the effective subagent_limits.

Personal connection first

A new user starts in one implicit personal space. The first connection of a toolkit is the obvious default connection. Give that direct connection to the same agent and run it without naming projects, groups, slots, principals, revisions, or mappings.

import time
import webbrowser

from flymyai import AgentClient, McpAccessMode

with AgentClient(api_key="fly-secret-key") as client:
    # Omitting alias keeps the first personal Gmail connection on `default`.
    gmail = client.tools.create(mcp_tool="gmail")

    # Gmail setup is hosted. Open the returned URL, finish OAuth, then wait for
    # the same connection row to become ready before assigning it or running.
    if not gmail.is_configured:
        if gmail.redirect_url:
            webbrowser.open(gmail.redirect_url)
            input("Finish Gmail authorization, then press Enter: ")
        elif gmail.next_configuration_step:
            raise RuntimeError(
                "This connector needs an answer. Inspect "
                "gmail.next_configuration_step and call "
                "client.tools.provide_config(gmail.id, user_response=...)."
            )
        deadline = time.monotonic() + 300
        while time.monotonic() < deadline:
            gmail = client.tools.get(gmail.id)
            if gmail.is_configured:
                break
            time.sleep(2)
        else:
            raise TimeoutError("Gmail authorization did not become ready in 5 minutes.")

    agent = client.agents.create(
        name="Personal inbox helper",
        goal="Summarize my unread mail.",
        tools=[gmail.id],
        mcp_access_mode=McpAccessMode.LEGACY,
    )
    run = client.agents.run(
        agent.id,
        idempotency_key="personal-inbox-summary-v1",
    )

legacy here is the explicit compatibility projection for direct personal connections. The response also exposes agent.mcp_access_mode; old server responses that omit it parse as McpAccessMode.LEGACY. This simple path uses the same exact connection row as the controls below, so it can grow without rebuilding the agent or reconnecting the account.

Advanced connection access

Open the advanced model only when the same agent needs a second account of one toolkit, reusable sharing, group access, separate clients or environments, or explicit policy and mapping control.

from flymyai import (
    AgentClient,
    McpAccessMode,
    McpResourceSetManagementMode,
    McpResourceSetMemberInput,
    McpResourceType,
)

with AgentClient(api_key="fly-secret-key") as client:
    support = client.tools.create(mcp_tool="gmail", alias="support_mail")
    sales = client.tools.create(mcp_tool="gmail", alias="sales_mail")

    resource_set = client.mcp_resource_sets.create(
        name="Mail operations",
        management_mode=McpResourceSetManagementMode.FLYMYAI,
    )
    resource_set = client.mcp_resource_sets.replace_members(
        resource_set.id,
        expected_revision=resource_set.revision,
        members=[
            McpResourceSetMemberInput(
                resource_type=McpResourceType.USER_MCP_TOOL,
                resource_id=support.public_id,
                slot="support_read",
                allowed_actions=["GMAIL_SEARCH_EMAILS"],
            ),
            McpResourceSetMemberInput(
                resource_type=McpResourceType.USER_MCP_TOOL,
                resource_id=support.public_id,
                slot="support_send",
                allowed_actions=["GMAIL_SEND_EMAIL"],
            ),
            McpResourceSetMemberInput(
                resource_type=McpResourceType.USER_MCP_TOOL,
                resource_id=sales.public_id,
                slot="sales_mailbox",
            ),
        ],
    )
    agent = client.agents.create(
        name="Mail operations",
        goal="Work in the mailbox selected for this request.",
        mcp_resource_set_ids=[resource_set.id],
        mcp_access_mode=McpAccessMode.SCOPED,
    )

    # Metadata writes use the revision that this editor originally loaded.
    resource_set = client.mcp_resource_sets.update(
        resource_set.id,
        expected_revision=resource_set.revision,
        description="Support and sales mailboxes",
    )

Aliases and slots accept 1 to 64 and 1 to 128 characters respectively, using only ASCII letters, digits, underscores, and hyphens. They are labels, not authority. Select resources with stable public UUIDs. client.tools.list() follows bounded cursor pages and can filter by exact mcp_tool or alias. Metadata update() uses PATCH, complete metadata replace() uses PUT, and member replacement uses replace_members(); all three require expected_revision.

client.mcp_resource_sets.list() and client.agent_groups.list() follow the backend's compact cursor envelope across pages. They reject malformed or repeated cursors and stop at fixed page and row safety limits. A bounded plain array remains accepted for compatibility with an older server during rollout. Resource-set list rows are McpResourceSetSummary values with member_count and no nested members. Use client.mcp_resource_sets.get(id) for one bounded full set or client.mcp_resource_sets.list_members(id) to traverse a large membership collection. Sync and async clients expose the same contract.

Member identity is the exact (resource_type, resource_id, slot) tuple. The same resource UUID may therefore appear in several different slots, as the support connection does above, and every slot keeps its own allowed_actions ceiling. Repeating the same tuple is invalid. Members pooled inside one slot must use the same action ceiling.

Returning a scoped agent to personal legacy access is intentionally a safe multi-request workflow. First remove the agent from every group while preserving each group's other agents and resource sets, then clear its direct resource-set grants. Only after every cleanup request succeeds, switch the mode in a separate PATCH:

for group in client.agent_groups.list():
    if agent.id in group.agent_ids:
        client.agent_groups.replace_assignments(
            group.id,
            agent_ids=[item for item in group.agent_ids if item != agent.id],
            resource_set_ids=group.resource_set_ids,
        )

client.agents.update(agent.id, mcp_resource_set_ids=[])
client.agents.update(agent.id, mcp_access_mode=McpAccessMode.LEGACY)

If any cleanup request fails, do not send the final mode PATCH. The agent then remains fail-closed in scoped mode. The SDK deliberately does not hide these independent writes in a convenience helper: automatic rollback could restore stale grants or overwrite another editor's group assignment.

An owner project uses management_mode=McpResourceSetManagementMode.FLYMYAI and omits principal_id. A customer-managed named mapping uses the exact typed principal UUID. The complete embedded flow below obtains that principal with access.principal_for_external_user(customer_id), creates the mapping with principal_id=principal.id, installs exact connection UUID members, and runs with the returned mapping revision.

The deprecated external_principal_id field is not an accepted SDK argument. For a FlyMyAI-managed deployment run, omit both resource_set_id and connections so saved bindings apply. Send resource_set_id only for a customer-managed named mapping, or connections for a one-off explicit mapping. The last two are mutually exclusive.

AgentClient and AsyncAgentClient call the Agents REST API. They expose Python methods such as client.agents.create(), client.mcp_resource_sets.replace_members(), and client.deployments.run(). The Agents MCP gateway is a separate assistant surface with its own discovered tool names. Do not translate a REST SDK method into an invented MCP-only lifecycle call, and do not treat an MCP tool name as a Python method.

First messages and instruction files

For an ordinary owner run, client.agents.run(agent_id, message="Build the report", idempotency_key="report-job-42") stores the first user message before execution. The same option exists on async clients and client.runs.create. Its value is part of the idempotent request, so a changed message requires a new logical job.

Create an agent from uploaded instructions with client.agents.create(name="Report worker", user_prompt_source={"agent_file_id": 123}). Use user_prompt_source instead of goal; exact artifact references are also accepted. The backend pins and attaches the instruction file for later runs. Large files stay accessible by reference independently of their model preview. Inside agent code, flymy.iter_payload(source) is the command SDK's streaming reader; it is separate from this owner REST client.

An agent's preview

agent.preview says what the agent does in one or two sentences (at most 280 characters); it is shown where people copy the agent - its public page and its project link. FlyMyAI writes it after each freeze. Your own text is pinned (agent.preview_pinned) and stays through later freezes:

client.agents.update(agent_id, preview="Scores each creator's posts and sends a daily digest.")
client.agents.update(agent_id, preview="")  # hand it back to FlyMyAI

client.agents.create(..., preview="...") and the async clients take it too. It is in flymyai 1.2.0rc18 and later; an older SDK drops the field on read.

Embedded customer agents

An embedded deployment publishes one immutable frozen version while each customer authorizes their own MCP accounts. Hosted authorization links must be created by your trusted application backend because the FlyMyAI API key must never be sent to the customer browser.

client.deployments.access() is read-only and never creates a principal. It can inspect the published requirements. The first mutating customer bootstrap is client.deployments.create_connection_link(), which calls REST POST /api/v1/agents/deployments/{deployment_id}/connect-session/ with the stable external_user_id and one exact required slot.

Complete synchronous flow for a customer-managed named mapping:

import os
import time
import webbrowser

from flymyai import (
    AgentClient,
    McpResourceSetManagementMode,
    McpResourceSetMemberInput,
    McpResourceType,
)

customer_id = os.environ["PRODUCT_CUSTOMER_ID"]  # Stable, non-secret product ID
agent_id = os.environ["FLYMYAI_AGENT_ID"]
accepted_run_id = int(os.environ["FLYMYAI_ACCEPTED_RUN_ID"])

with AgentClient(api_key="fly-secret-key") as client:
    # compile_from_run freezes and polls until compilation has finished.
    compilation = client.agents.compile_from_run(accepted_run_id)
    version = next(
        item
        for item in client.versions.list(agent_id=agent_id)
        if item.source_compilation == compilation.id
    )

    deployment = client.deployments.create(
        agent_id=agent_id,
        version_id=version.id,
        name="Production",
    )
    manifest = client.deployments.access(deployment.id)  # Read-only.
    preflight = client.deployments.preflight(
        deployment.id,
        publish_mode="embedded",
        version_id=version.id,
    )
    if not preflight.ready:
        raise RuntimeError("Deployment preflight is not ready.")
    deployment = client.deployments.publish(
        deployment.id,
        publish_mode="embedded",
        version_id=version.id,
    )

    # Each POST is the mutating principal/bootstrap step for one exact slot.
    sessions = [
        client.deployments.create_connection_link(
            deployment.id,
            external_user_id=customer_id,
            slot=requirement.slot,
        )
        for requirement in manifest.requirements
        if requirement.connection_required
    ]
    for session in sessions:
        webbrowser.open(session.redirect_url)
    if sessions:
        input("Finish every customer authorization, then press Enter: ")

    # Poll the filtered access projection. The typed helpers fail closed until
    # one exact principal and active connection IDs exist for every slot.
    deadline = time.monotonic() + 300
    while True:
        access = client.deployments.access(
            deployment.id,
            external_user_id=customer_id,
        )
        try:
            principal = access.principal_for_external_user(customer_id)
            ready_by_slot = {
                requirement.slot: access.ready_connection_ids_for_slot(
                    principal_id=principal.id,
                    slot=requirement.slot,
                )
                for requirement in access.requirements
                if requirement.connection_required
            }
            break
        except ValueError:
            if time.monotonic() >= deadline:
                raise TimeoutError("Customer connections did not become ready.")
            time.sleep(2)

    customer_mapping = client.mcp_resource_sets.create(
        name=f"{customer_id} connections",
        management_mode=McpResourceSetManagementMode.CUSTOMER,
        principal_id=principal.id,
    )
    customer_mapping = client.mcp_resource_sets.replace_members(
        customer_mapping.id,
        expected_revision=customer_mapping.revision,
        members=[
            McpResourceSetMemberInput(
                resource_type=McpResourceType.INTEGRATION_CONNECTION,
                resource_id=connection_id,
                slot=requirement.slot,
                allowed_actions=requirement.exact_actions,
            )
            for requirement in access.requirements
            if requirement.connection_required
            for connection_id in ready_by_slot[requirement.slot]
        ],
    )
    result = client.deployments.run_and_wait(
        deployment.id,
        variables={"topic": "Q3 pipeline"},
        external_user_id=customer_id,
        resource_set_id=customer_mapping.id,
        resource_set_revision=customer_mapping.revision,
        idempotency_key=f"{customer_id}-q3-pipeline-v1",
    )

AsyncAgentClient exposes the same typed lifecycle. Await the network methods; principal_for_external_user() and ready_connection_ids_for_slot() remain ordinary local model helpers.

The access request must include the exact external_user_id; do not select a principal or connection by display name, email, alias, provider account ID, or row order. McpResourceSets.list() supports query, authority_type, and principal_id; AgentGroups.list() supports query. These filters remain on every compact-cursor page.

client.deployments.run() and run_and_wait() call the stable deployment endpoint, so callers need the deployment UUID but never need a compilation ID. Normally a run uses the saved customer bindings. To choose among several authorized accounts for one run, pass connections={"sender_inbox": "8335876a-ee78-45db-9d49-0ae148bd0158"} or a list of up to 25 connection UUIDs for a multi-connection slot. Provider account IDs and aliases are not accepted in this mapping. Customer file attachments are not enabled for embedded runs in this beta. Wait for every hosted authorization callback to complete before starting the customer's first run.

The legacy client.compilations.run_instruction() and run_instruction_and_wait() methods remain available for compilation-scoped owner runs. Deprecated client.compilations.run() and its async counterpart fail locally before HTTP because that legacy endpoint has no caller-owned replay contract.

Every agents.run(), runs.create(), tools.call(), compilations.run_instruction(), and deployments.run() call, including their wait helpers and async variants, requires a caller-owned idempotency_key. It must be non-blank and no longer than 255 characters and contain no control or non-printable characters. The SDK forwards the exact value as Idempotency-Key and never generates one for the caller. Reuse a key only for an identical retry; choose a new key for a new logical execution. This is an intentional compatibility break for keyless effect calls because a lost response must not create a second execution that repeats external writes.

Native models: MiniMax-H3

client.model_proxy runs native models on the agents host. MiniMax-H3 makes one video with stereo audio from a prompt and your own files. It is not the older flymyai/minimax-h3-t2v and flymyai/minimax-h3-i2v endpoints, and it does not run from text alone. A model is usable only after the backend publishes its route.

from flymyai.agents import AgentClient

with AgentClient(api_key="fly-secret-key") as client:
    # Find the model, by its profile or with endpoint_id="owner/name".
    page = client.model_proxy.catalog(limit=100)
    h3 = next(row for row in page.items if row.profile == "broker.h3-ref2va.v1")

    # Store your file. This takes a path, bytes or a stream.
    photo = client.model_proxy.upload_file(
        "photo.png", idempotency_key="photo-upload-1"
    )

    # Save the key, revision and inputs before create(), and the operation id after it.
    created = client.model_proxy.create(
        h3.contract_revision,
        {
            "prompt": "the photo comes alive",
            "conditions": [{"type": "image", "artifact": photo.artifact}],
            "duration_seconds": 5,
            "aspect_ratio": "9:16",
        },
        idempotency_key="photo-video-1",
    )

    result = client.model_proxy.wait(
        created.operation.operation_id,
        contract_revision=h3.contract_revision,
        timeout=3600,
        poll_interval=5,
        max_polls=720,
        on_update=lambda operation: print(operation.status, operation.reason),
    )
    if result.status == "succeeded":
        print(result.output["video"]["url"])

Input. {prompt, conditions, duration_seconds?, aspect_ratio?, seed?}. prompt is 1 to 16000 characters. conditions is 1 to 12 {"type": "image" | "audio", "artifact": ...} in order, at most 9 images and 3 audio. duration_seconds is 5 or 10, aspect_ratio is 16:9, 9:16, 1:1, 4:3, 3:4 or 21:9, and seed is 0 to 2147483647. The SDK sends your input whole: the bounds are the backend's, and a refusal names its code in ModelProxyError.refusal_code, such as h3_references. That request started nothing.

Files. artifact is the exact reference of your own file. Pass it unchanged. A file id or URL is refused, and it is None when no reference can be built. No agent is needed. After a lost reply, call upload_file again with the same idempotency_key and file: it returns the same reference. media_type decides the kind of the reference, so it must be the file's real image/ or audio/ type; it defaults from the filename. One upload holds at most 96 MiB.

Waiting. An operation with no capacity stays queued: waiting_for_capacity is true, error_code is h3_capacity_not_ready, h3_model_busy, ds_capacity_not_ready or ds_model_busy, and reason says it plainly. This is the model starting, not a failure. A cold start takes about 15 minutes for H3 and up to 50 for DeepSeek, and nothing is sent or charged meanwhile. Call wait or get on the same operation id and never call create for it again. A wait that ends earlier raises ModelProxyError with the same operation_id and what it last read in last_status, waiting_code and reason.

The ends. rejected with one of those codes or proxy_deadline means the model did not start in time: the wait ran out with no charge. failed with model_lease_deleted or model_http_<status> means no result and no charge. reason says so on each.

Neural Network Inference

Run any model on the platform with flymyai.async_run (async) or flymyai.run (sync).

Image generation - Nano Banana 🍌

import asyncio
import base64
import flymyai

async def main():
    response = await flymyai.async_run(
        apikey="fly-secret-key",
        model="flymyai/nano-banana",
        payload={"prompt": "a cute cat astronaut floating in a neon nebula, studio lighting"},
    )
    with open("nano_banana.jpg", "wb") as f:
        f.write(base64.b64decode(response.output_data["image"][0]))

asyncio.run(main())

Video generation - Veo 3.1 Fast

import asyncio
import flymyai

async def main():
    response = await flymyai.async_run(
        apikey="fly-secret-key",
        model="flymyai/veo31-fast-generate",
        payload={"prompt": "a red sports car driving along a coastal road at sunset, cinematic"},
    )
    print(response.output_data["video"][0])  # public URL to the generated .mp4

asyncio.run(main())

Parallel generation

Fire many requests concurrently with asyncio.gather:

import asyncio
import base64
import flymyai

PROMPTS = ["a neon city at night", "a serene mountain lake at dawn", "a retro robot barista"]

async def main():
    results = await asyncio.gather(*[
        flymyai.async_run(
            apikey="fly-secret-key",
            model="flymyai/nano-banana",
            payload={"prompt": p},
        )
        for p in PROMPTS
    ])
    for i, r in enumerate(results):
        with open(f"img_{i}.jpg", "wb") as f:
            f.write(base64.b64decode(r.output_data["image"][0]))

asyncio.run(main())

Retries and broken streams

The prediction clients send a request again the way the official OpenAI and Anthropic SDKs do (since 1.2.0rc28):

  • Only before the answer started: when the connection failed, was reset or timed out before a response arrived (up to FMA_RECONNECT_RETRIES, default 3), or when the response's status allows it (FLYMYAI_MAX_RETRIES or max_retries, default 2 attempts): 408, 409, 429 and every status from 500.
  • The server decides when it says so: x-should-retry: true|false wins over the status, and a JSON error body with "retry_safe": false stops it.
  • The wait honours retry-after-ms / retry-after up to two minutes, otherwise exponential backoff from 0.5 s to 8 s with jitter.
  • A stream that has delivered an event is never sent again: the model may still be running, and a second run would repeat the answer and its cost. A broken connection raises FlyMyAIStreamInterrupted and an error event inside the stream raises FlyMyAIStreamError; both carry prediction_id (when the stream announced it) and events_received, and both are FlyMyAIPredictExceptions.
  • predict_async_task sends one Idempotency-Key on every attempt (yours via idempotency_key=, or one made for the call), so a submit sent again after a lost answer replays the first job instead of starting a second paid one.
import flymyai
from flymyai import FlyMyAIStreamInterrupted

client = flymyai.client(apikey="fly-secret-key", model="flymyai/llama-v3-8b")
text = []
try:
    for chunk in client.stream({"prompt": "a haiku about the sea"}):
        text.append(chunk.output_data["output"][0])
except FlyMyAIStreamInterrupted as error:
    # Part of the answer arrived; retry the whole call yourself if a second run is fine.
    print(f"cut after {error.events_received} events of {error.prediction_id}")

Reading a saved tool response

When a tool call returns a memory_key, read one UTF-8 page at a time. Use the same owner client. For a result from a run, also pass its execution_id. The synchronous and asynchronous clients use the same arguments.

offset = 0
while True:
    page = client.tools.read_tool_response(memory_key, offset=offset, limit=6000)
    consume(page.chunk)
    if page.is_complete:
        break
    offset = page.next_offset

Custom MCP servers and OAuth

client.mcp_servers adds an MCP server by URL - a service that is not in the catalog, or a provider's own MCP endpoint - and calls it. auth_type is none, api_key, bearer_token, basic or oauth. With oauth FlyMyAI discovers the server's authorization and registers itself where the provider allows it; authorize returns a link a person opens to approve, and then the server is connected.

import webbrowser

from flymyai import AgentClient
from flymyai.agents import McpServerOAuthError

with AgentClient(api_key="fly-secret-key") as client:
    server = client.mcp_servers.create(
        name="Linear", url="https://mcp.linear.app/mcp", auth_type="oauth"
    )
    try:
        authorization = client.mcp_servers.authorize(server.id)
    except McpServerOAuthError as error:
        if error.code != "oauth_client_required":
            raise
        # No automatic registration (Slack's MCP is like this): register
        # error.redirect_uri in your own OAuth app, save its client ID and
        # secret on the server, then authorize again.
        client.mcp_servers.update(
            server.id, oauth_client_id="...", oauth_client_secret="..."
        )
        authorization = client.mcp_servers.authorize(server.id)
    webbrowser.open(authorization.authorize_url)  # works once, 15 minutes

    # After the approval: status "connected", the tools in discovered_tools.
    server = client.mcp_servers.get(server.id)
    if server.status == "connected":
        client.mcp_servers.call(
            server.id, "list_issues", {"first": 5}, idempotency_key="issues-1"
        )

server.oauth (owner only) says authorized, reconnect_required (authorize again), issuer, scopes, client and redirect_uri; tokens and the client secret never come back. disconnect forgets the grant.

Personal MCP sharing

The optional AgentClient.shares and AsyncAgentClient.shares clients manage email invitations, exact-connection grants, device tokens and revocation. A recipient must verify the addressed email and explicitly pass accept_billing=True when accepting. FlyMy execution charges use the recipient's wallet, without owner-wallet fallback. Provider charges remain with the connected account; existing team MCP calls continue using the team wallet.

Personal sharing is live on FlyMy.AI production (backend and Agents MCP) since 2026-09-25; see the sharing guide. Self-hosted deployments keep it behind the independent MCP_PERSONAL_SHARING_ENABLED gate, off by default. Existing inference clients and resource-set/agent contracts remain available.

Frontend artifacts

AgentClient.artifacts and AsyncAgentClient.artifacts manage frontend artifacts (flymy.artifact.v1): a small web page, a presentation or a mini game with immutable versions. Share it by link (with or without its sources) or with people by name to view or edit, and clone anyone's shared artifact into your own copy. Artifacts are on for every account; client.artifacts.status() returns your limits. They are in the 1.2.0 pre-releases: pip install 'flymyai>=1.2.0rc12' (a plain pip install flymyai gets 1.1.0, which has no client.artifacts).

from flymyai import AgentClient
from flymyai.agents import artifact_file, artifact_files_from_directory

client = AgentClient(api_key="fly-...")

# a folder (a built site, a game, a page copied from a Claude artifact)
made = client.artifacts.create(
    name="Pod racer",
    files=artifact_files_from_directory("./pod-racer"),
    visibility="link",
    idempotency_key="pod-racer-create-1",
)
racer = made.artifact
print(racer.share_url)

# a new version on top of the latest; the other files are kept
client.artifacts.publish(
    racer.id,
    base_version=racer.latest_version,
    files=[artifact_file("js/app.js", "speed = 2")],
    message="Faster pods",
    idempotency_key="pod-racer-v2",
)

# invite a teammate to publish versions too ("view" lets them read and clone);
# they accept first, and nothing is shared with them until then
invited = client.artifacts.add_member(racer.id, "teammate@example.com", role="edit")
print(invited.member.status)  # pending

# on the teammate's side: what waits for them, and their answer
for invitation in client.artifacts.invitations().results:
    client.artifacts.accept_invitation(invitation.id)
shared_with_me = client.artifacts.list(scope="shared")

# your own copy of someone's artifact shared with sources
copy = client.artifacts.clone(
    share_link="https://app.flymy.ai/artifacts/s/<handle>",
    idempotency_key="clone-1",
)

Sharing by name never tells anyone who an email or a username belongs to: an email answers the same whether an account has it, the owner sees each person as they typed them (invited_as) with status pending or accepted, and a member sees only which row is theirs (you). remove_member(artifact_id, member.id) stops sharing with an invited or accepted person; a member removes their own row to leave.

Start from a standard type

client.artifacts.types() lists the standard types: a presentation, a game, a landing page, a report, a dashboard and a gallery. create(type=...) makes version 1 from that type's template, so files (laid over the template) and name (default: the type's default_name) are optional. Each template keeps its content in one file, edit (slides.md, site.json, game.config.js, ...), and its README.md says how to change it.

for kind in client.artifacts.types():
    print(kind.key, kind.edit, "-", kind.example_change)

game = client.artifacts.create(type="game", idempotency_key="harvest-create-1")
print(game.artifact.type, game.artifact.owner_url)

Change it: a new version next to the live one

People change an artifact by pasting its link into their assistant with the change right after it: <link> add these things to the artifact: <change>. get() opens the link - a share link https://app.flymy.ai/artifacts/s/<handle> (a query string is fine) or its handle as share_link, the artifact's own page https://app.flymy.ai/artifacts/<id> as either argument - and next says what the caller may do:

  • Owner or editor: publish with publish=False. The live version stays and the new one is saved next to it, so both are kept; version.page_url (the app page at ?v=<n>) shows it. Make it live only when the person asks to update the current version: update(live_version=...), or publish=True. base_version may be the live version, so a saved draft above it stays a draft.
  • Anyone else: clone() makes their own copy (when the sources are shared); change the copy. The original stays as it is.
art = client.artifacts.get(share_link="https://app.flymy.ai/artifacts/s/<handle>")
print(art.role, art.next)
if art.role in ("owner", "editor"):
    config = client.artifacts.read_file(
        art.id, version=art.live_version, path="game.config.js"
    )
    v2 = client.artifacts.publish(
        art.id,
        base_version=art.live_version,
        files=[artifact_file("game.config.js", config.content.replace("crow", "boar"))],
        publish=False,  # the live version stays
        message="Other enemies",
        idempotency_key="harvest-v2-other-enemies",
    )
    print(v2.version.version, v2.version.page_url)
    # only when they asked to "update current version":
    # client.artifacts.update(art.id, live_version=v2.version.version)

versions is None for a link viewer when the author shared only the page; with sources shared, link viewers see every saved version, not only the live one. An unchanged publish answers no_change and names the version that already holds those files. app_url is the app page for the owner and the people it is shared with by name. A file that looks like a secret is refused (secret_file: env files, version control, keys and certificates; secret_in_file: a private key or another service's token inside a text file), and a request body is at most 40 MB.

Writes that create something take a caller-owned idempotency_key: 1-255 printable ASCII characters, spaces inside allowed but no leading or trailing spaces; reuse it only to retry the identical call. A version published on a base_version that is neither the latest nor the live version raises ArtifactStaleBaseVersionError with latest_version and live_version. These are the v1 methods and they stay: a breaking change would arrive as new methods next to them, never in place.

Projects

AgentClient.projects and AsyncAgentClient.projects read and run your projects (flymy.project.v1): an app applied from one flymy.yaml (its pages, agents, servers, storage and budgets), a page published on its own, a fleet (a lead agent and the agents it starts) or a frontend artifact. A project is its config: creating, stopping and starting it are a plan and an apply of that config, and each leaves a release.

Both projects.plan and projects.create accept optional brief, model and effort. A brief queues the first task before the project agent's first model turn; creation returns made.agent and made.chat. Preview starts nothing. Send the same fields at both steps and reuse the idempotency key when retrying creation. The brief is limited to 65,536 UTF-8 bytes and needs a positive balance. Pick the model from the current agent model catalog. Pick effort from that model's current effort_options; omit it when the list is empty. The backend saves it before the first execution. Use the same fields in preview and creation. Omitted or None effort is left out of the request, preserving the existing default and request identity; the backend also treats blank text as default and normalizes explicit text to lowercase. An explicit level without a model binds the current project default model to the plan. Changing that selection requires a new plan, and a changed nonempty effort under the same creation key is refused. This option needs the backend effort contract before SDK publication.

from flymyai import AgentClient

client = AgentClient(api_key="fly-...")

for project in client.projects.list().projects:
    print(project.id, project.status)

# a plan creates nothing: show its price, then create exactly that plan
plan = client.projects.plan(name="paint-arena", budget={"per_day_usd": "5"})
print(plan.plan["usd_per_hour"], plan.plan["changes"])
made = client.projects.create(
    name="paint-arena",
    budget={"per_day_usd": "5"},
    plan_token=plan.plan_token,
    idempotency_key="paint-arena-create-1",
)

# stop it (its servers stop and the rest of their holds is refunded), start it again
client.projects.stop("app:me/paint-arena", idempotency_key="paint-arena-stop-1")
start = client.projects.start("app:me/paint-arena")  # the plan, nothing changes
print(start.plan["usd_per_hour"])
client.projects.start(
    "app:me/paint-arena",
    plan_token=start.plan_token,
    idempotency_key="paint-arena-start-1",
)

journal = client.projects.errors("app:me/paint-arena", limit=20)

# the project agent (created on first use) runs on the platform's top model; pick
# another from GET /api/v1/agents/llm-models/ - it stays the agent's model
agent = client.projects.agent("app:me/paint-arena", model="gpt-6-luna")
print(agent.agent, agent.model)

# rename it, change its budget (None removes a period, a period left out stays) and
# delete it: each is a release of its flymy.yaml, answered once per key
client.projects.rename(
    "app:me/paint-arena", title="Paint Arena", idempotency_key="paint-arena-title-1"
)
edit = client.projects.set_budget(
    "app:me/paint-arena",
    {"per_day_usd": "10", "per_week_usd": None},
    idempotency_key="paint-arena-budget-1",
)
print(edit.budget["day"]["left_usd"], edit.release)  # release is None when unchanged
gone = client.projects.delete("app:me/paint-arena", idempotency_key="paint-arena-del-1")
print(gone.deleted)  # removed (no history) or archived

rename, set_budget and delete (flymy.project-edit.v1) change a project after it is created. A rename sets an app's metadata.title, the name it lists under, while its id keeps its name; a page on its own takes the title as its name. A budget change sets billing.budgets.project: money spent and held stays, and only the caps change. A deletion removes a project with no history for good, and its name is free again. A project with history is archived instead: it stops as stop does, its agents are archived and it leaves the lists, while its runs, ledger entries, releases, storages and name stay. Before anything changes, a change can be refused with 409 busy (a release is applying) or project_stopped (start it first). A fleet without a named AgentTeam takes its title from its lead (agents.update); a named AgentTeam keeps its own title and has no rename endpoint. An artifact changes through client.artifacts. These project kinds are refused before a request.

Change an app by applying its flymy.yaml again with AgentClient.apps: plan shows what it would create, change or stop and its price, and apply applies exactly that plan as a release.

import time

from flymyai.agents import artifact_files_from_directory

files = artifact_files_from_directory("./paint-arena")  # flymy.yaml at the root
plan = client.apps.plan(files=files)
print(plan.changes, plan.usd_per_hour)  # show the user before applying
release = client.apps.apply(
    files=files, plan_token=plan.plan_token, idempotency_key="paint-arena-apply-2"
)
while client.apps.status(release.release).status == "applying":
    time.sleep(5)

client.apps.files("me/paint-arena") reads the applied template back; plan and apply also take app="me/paint-arena" with overrides to replace some files and keep the rest.

An app's secrets: (a Stripe key, a session signing key) reach only its rented servers, as env: {STRIPE_KEY: ${secrets.STRIPE_KEY}}. Set the values with client.apps.secrets, before the first plan (it asks for the ones a server uses, needs_secret). A value goes in and never comes out: list shows names, set, version, who uses them and an authenticated input_url. set is for trusted owner code only: read the value from your own environment or secret store. Never put a secret into an assistant prompt, transcript or tool arguments. An assistant can give the owner client.apps.secrets.list("me/shop").input_url to enter it in the write-only web form, or call generate without anyone seeing the value.

import os

client.apps.secrets.set("me/shop", "STRIPE_KEY", os.environ["STRIPE_KEY"])
client.apps.secrets.generate("me/shop", "SESSION_KEY")  # made once by the platform
for secret in client.apps.secrets.list("me/shop").secrets:
    print(secret.name, secret.set, secret.version, secret.used_by)

A new value reaches a server at its next start. delete removes a value; generate makes a new one only for a secret without a value.

get, errors, templates and agent (the project's own agent, created on first use) complete the projects set. A fleet (fleet:<lead agent id>) and a frontend artifact (artifact:<artifact id>) are read with get and errors; they have no project agent and are not stopped or started (an artifact changes through client.artifacts).

Advanced agent helpers

Draft an input_schema from a prompt

import asyncio
from flymyai import AsyncAgentClient

async def main():
    async with AsyncAgentClient(api_key="fly-secret-key") as client:
        suggestion = await client.agents.suggest_schema(
            user_prompt="Summarize {{ url }} in {{ n_sentences }} sentences.",
            generate_descriptions=True,
        )
        print(suggestion.input_schema)
        print(suggestion.input_description)

asyncio.run(main())

Handle invalid variables

When variables don't match the agent's input_schema, the server returns HTTP 400 and the client raises VariablesValidationError:

from flymyai import VariablesValidationError

try:
    await client.agents.run(
        agent.id,
        idempotency_key="validate-agent-input-v1",
        variables={},
    )
except VariablesValidationError as err:
    print(err.messages)      # ["'url' is a required property", ...]
    print(err.field_errors)  # {"url": "'url' is a required property"}

Draft schemas from a finished run

# Infer schemas from a completed run's chat + tool trace
# (also persists them onto the source agent).
suggestion = await client.runs.suggest_schema(
    run.id,
    inputs_prompt="A URL and a sentence count",
    outputs_prompt="A short summary",
)

Webhook triggers v1

AgentClient.triggers_v1 and AsyncAgentClient.triggers_v1 manage signed webhooks for the owner's Live frozen agent version. Methods: list, get, create, update, pause, activate, delete, events.

import secrets
from uuid import uuid4

operation_key = str(uuid4())  # Persist for retries of this logical create.
secret = secrets.token_urlsafe(32)  # Store securely in the sender, never log it.
trigger = client.triggers_v1.create(
    agent_id,
    secret=secret,
    idempotency_key=operation_key,
)
events = client.triggers_v1.events(trigger.uuid)

The API never returns the signing secret. Every SDK write requires a stable idempotency_key; keep the identical key and arguments after a lost response. config replaces the previous config, while omitted fields stay unchanged. An empty signing secret is rejected. Paused deliveries are acknowledged and discarded. Deleting a webhook removes its receipts; already admitted runs continue. execution_public_id in a receipt can be passed to client.runs.get. Acceptance/admission is not agent completion. Native subscriptions use the additional catalog/subscribe methods below. See Webhook Triggers v1 for the exact HMAC format, limits and versioned REST contract. The namespace is in flymyai 1.2.0rc15 and later (released 2026-10-16 with the backend, the Agents MCP triggers_v1_* tools and the app's Webhooks panel); older packages do not have it, so require flymyai>=1.2.0rc15. tests/test_triggers.py pins the v1 methods, arguments and answer fields (V1_METHODS); keep them when a v2 is added.

Native Granola and Telegram subscriptions

Discover events with triggers_v1_catalog (SDK: client.triggers_v1.catalog()). Create a binding with triggers_v1_subscribe, an exact owned connection_id, agent_id, events and a persistent operation_key. In the SDK use .subscribe(agent_id, connection_id, events=[...], idempotency_key=...). Granola requires scopes=["personal"], ["public"], both, or exactly ["workspace"] for a workspace key; optional folder_ids include subfolders. Telegram accepts optional chat_ids and actor_ids. Both sync and async SDK clients support it.

A 201 creates a binding; inspect source.status until registration is ready. conflict preserves an existing provider registration; unknown must be reconciled before another registration attempt. One bot webhook feeds its agent subscriptions. Native records have kind: mcp_event, webhook_url: null and a secret-free source. The run receives trigger.webhook containing provider, type, provider_event_id, connection_id and the original provider object in data. Use the existing list/get/update/pause/activate/delete/events calls. Native secrets and event/chat/actor filters cannot be changed through update. Pausing discards events for that binding; deleting the final binding starts removal of only the owned provider webhook. Provider credentials are never returned.

See the full event and method matrix. Private approvals use an authenticated reply to the current review; reaction events require administrator rights and are not reliable for private bot chats. Native personal Telegram listening and polling are separate, unimplemented transports. Payment/callback events still need their own deadline-aware handler.

About

No description, website, or topics provided.

Resources

Stars

8 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages