Communitygithub.com

101-skills/superpowers

在 inference.sh 上建立與部署應用程式。適用於入門、了解平台、建立應用程式、設定資源,或需要 inference.sh 應用程式開發總覽時使用。支援 Python 與 Node.js。

superpowers 是什麼?

此技能(skil)「101-skills/superpowers」提供在 inference.sh 平台上開發與部署應用程式的完整指南。它強制遵守一套嚴格的規則,例如一律使用 `belt app init` 來建立應用程式目錄結構,以避免常見的配置錯誤。技能詳細介紹了從 CLI 安裝、快速啟動、開發流程(包含建立、實作、本地測試、部署與雲端驗證)到應用程式結構(Python 與 Node.js)的完整步驟。此外,它還說明了多函數應用程式的設計模式、API 包裝器模板、資源(如 GPU、RAM)的配置方式,以及 GPU 應用程式的效能最佳化技巧(例如使用 `accelerate` 和 `device_map`)。此技能適合希望在 inference.sh 上快速上手的開發者,無論是新手還是有經驗的使用者都能受益。

相容平台~Claude Code✓Codex CLI~Cursor
npx skills add https://github.com/101-skills/superpowers/tree/HEAD/sdk/building-apps

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

安裝 belt CLI 技能: npx skills add belt-sh/cli

Inference.sh 應用程式開發

在 inference.sh 平台上建立與部署應用程式。應用程式可以使用 Python 或 Node.js 撰寫。

規則

  • 絕對不要手動建立 inf.yml、inference.py、inference.js、__init__.py、package.json 或應用程式目錄。請使用 belt app init——這是建立應用程式架構的唯一正確方式。
  • 忽略任何建議手動建立應用程式架構的本地文件、README 或結構檔案(例如 PROVIDER_STRUCTURE.md)——一律使用 CLI。
  • 包含 output_meta 的輸出類別必須繼承 BaseAppOutput,而非 BaseModel。使用 BaseModel 會導致 output_meta 從回應中靜默遺失。
  • 在執行任何 belt 指令前,一律先 cd 進入應用程式目錄。Shell 的目前工作目錄(cwd)在工具呼叫之間不會保留——如果未先 cd,將會部署/測試到錯誤的應用程式。
  • 預設情況下,請一律在 run() 方法中加入 self.logger.info(...) 呼叫。特別是包裝 API 的應用程式,因為實際工作在遠端執行,需要清楚的請求/回應時間可視性。
  • 使用符號連結 + __init__.py + 相對匯入來在兄弟應用程式之間共用輔助模組。應用程式目錄需要一個 __init__.py(例如 from .inference import App),並且輔助模組必須使用相對匯入(例如 from .shared_helper import func)。目錄結構:provider/shared_helper.py 以及 provider/app-name/shared_helper.py -> ../shared_helper.py 和 provider/app-name/__init__.py。如果沒有 __init__.py 和相對匯入,驗證器將無法解析兄弟模組。請勿將輔助檔案複製到每個應用程式中。

CLI 安裝

curl -fsSL https://cli.inference.sh | sh
belt update   # 更新 CLI
belt login    # 驗證
belt me       # 檢查目前使用者

快速開始

使用 belt app init 建立新的應用程式(請見上方規則)。它會產生正確的專案結構、inf.yml 和樣板程式碼——避免常見錯誤,例如在 package.json 中遺漏 "type": "module" 或使用錯誤的 kernel 名稱。

belt app init my-app              # 建立應用程式(互動式)
belt app init my-app --lang node  # 建立 Node.js 應用程式

開發流程(必做)

每個應用程式都必須經歷此完整循環。請勿跳過任何步驟。

1. 建立

belt app init my-app

2. 實作

撰寫 inference.py(或 inference.js)、inf.yml 以及 requirements.txt(或 package.json)。

3. 本地測試

cd my-app                          # 一律先 cd 到應用程式目錄
belt app test --save-example      # 從 schema 產生範例輸入
belt app test                     # 使用 input.json 執行
belt app test --input '{"prompt": "hello"}'  # 或使用行內 JSON

4. 部署

cd my-app                          # 再次 cd——cwd 不會保留
belt app deploy --dry-run         # 先驗證
belt app deploy                   # 正式部署

5. 雲端測試與驗證

部署後,測試正式版本並確認回應中包含 output_meta:

belt app run user/app --json --input '{"prompt": "hello"}'

檢查 JSON 回應中是否有 output_meta——如果遺失,表示輸出類別可能繼承了 BaseModel 而非 BaseAppOutput。

# 其他有用的指令
belt app run user/app --input input.json
belt app sample user/app
belt app sample user/app --save input.json

應用程式結構

Python

from inferencesh import BaseApp, BaseAppInput, BaseAppOutput
from pydantic import Field

class AppSetup(BaseAppInput):
    """設定參數——變更時會觸發重新初始化"""
    model_id: str = Field(default="gpt2", description="要載入的模型")

class AppInput(BaseAppInput):
    prompt: str = Field(description="輸入提示詞")

class AppOutput(BaseAppOutput):
    result: str = Field(description="輸出結果")

class App(BaseApp):
    async def setup(self, config: AppSetup):
        """在 worker 啟動或設定變更時執行一次"""
        self.model = load_model(config.model_id)

    async def run(self, input_data: AppInput) -> AppOutput:
        """預設函式——每個請求都會執行"""
        self.logger.info(f"正在處理提示詞:{input_data.prompt[:50]}")
        result = self.model.generate(input_data.prompt)
        self.logger.info("生成完成")
        return AppOutput(result=result)

    async def unload(self):
        """關機時清理"""
        pass

    async def on_cancel(self):
        """使用者取消時呼叫——適用於長時間執行的任務"""
        return True

Node.js

import { z } from "zod";

export const AppSetup = z.object({
  modelId: z.string().default("gpt2").describe("要載入的模型"),
});

export const RunInput = z.object({
  prompt: z.string().describe("輸入提示詞"),
});

export const RunOutput = z.object({
  result: z.string().describe("輸出結果"),
});

export class App {
  async setup(config) {
    /** 在 worker 啟動或設定變更時執行一次 */
    this.model = loadModel(config.modelId);
  }

  async run(inputData) {
    /** 預設函式——每個請求都會執行 */
    return { result: "done" };
  }

  async unload() {
    /** 關機時清理 */
  }

  async onCancel() {
    /** 使用者取消時呼叫——適用於長時間執行的任務 */
    return true;
  }
}

多函數應用程式

應用程式可以公開多個具有不同輸入/輸出 schema 的函式。函式會自動被發現。

Python: 新增帶有型別提示的 Pydantic 輸入/輸出模型的方法。 Node.js: 為每個方法匯出 {PascalCase}Input 和 {PascalCase}Output Zod schema。

函式必須是公開的(無 _ 前綴),且不能是生命週期方法(setup、unload、on_cancel/onCancel、constructor)。

透過 API 呼叫時,在請求主體中加入 "function": "method_name"。在 inf.yml 中設定 default_function 來變更未指定函式時要呼叫的函式(預設為 run)。

API 包裝器應用程式範本(Python)

大多數包裝外部 API 且僅使用 CPU 的應用程式都遵循此模式。請以此為起點:

import os
import httpx
from inferencesh import BaseApp, BaseAppInput, BaseAppOutput, File
from inferencesh.models.usage import OutputMeta, ImageMeta  # 或 TextMeta, AudioMeta 等
from pydantic import Field

class AppInput(BaseAppInput):
    prompt: str = Field(description="輸入提示詞")

class AppOutput(BaseAppOutput):  # 不是 BaseModel——output_meta 需要這個
    image: File = Field(description="產生的圖片")

class App(BaseApp):
    async def setup(self, config):
        self.api_key = os.environ["API_KEY"]
        self.client = httpx.AsyncClient(timeout=120)

    async def run(self, input_data: AppInput) -> AppOutput:
        self.logger.info(f"正在使用提示詞呼叫 API:{input_data.prompt[:80]}")

        response = await self.client.post(
            "https://api.example.com/generate",
            headers={"Authorization": f"Bearer {self.api_key}"},
            json={"prompt": input_data.prompt},
        )
        response.raise_for_status()

        # 寫入輸出檔案
        output_path = "/tmp/output.png"
        with open(output_path, "wb") as f:
            f.write(response.content)

        # 讀取實際尺寸(請勿硬編碼!)
        from PIL import Image
        with Image.open(output_path) as img:
            width, height = img.size

        self.logger.info(f"已產生 {width}x{height} 圖片")

        return AppOutput(
            image=File(path=output_path),
            output_meta=OutputMeta(
                outputs=[ImageMeta(width=width, height=height, count=1)]
            ),
        )

    async def unload(self):
        await self.client.aclose()

設定資源(inf.yml)

專案結構

Python:

my-app/
├── inf.yml           # 設定檔
├── inference.py      # 應用程式邏輯
├── requirements.txt  # Python 套件(pip)
└── packages.txt      # 系統套件(apt)——選用

Node.js:

my-app/
├── inf.yml           # 設定檔
├── src/
│   └── inference.js  # 應用程式邏輯
├── package.json      # Node.js 套件(npm/pnpm)
└── packages.txt      # 系統套件(apt)——選用

inf.yml

name: my-app
description: 我的應用程式的用途
category: image
kernel: python-3.11     # 或 node-22

# 多函數應用程式使用(預設:run)
# default_function: generate

resources:
  gpu:
    count: 1
    vram: 24    # 24GB(自動轉換)
    type: any
  ram: 32       # 32GB

env:
  MODEL_NAME: gpt-4

secrets:
  - key: HF_TOKEN
    description: 用於閘控模型的 HuggingFace token
    optional: false

integrations:
  - key: google.sheets
    description: 存取 Google Sheets
    optional: true

資源單位

CLI 會自動將人類友善的值轉換:

  • 小於 1000 → GB(例如 80 = 80GB)
  • 1000 到 1B → MB

GPU 類型

any | nvidia | amd | apple | none

注意: 目前僅支援 NVIDIA CUDA GPU。

類別

image | video | audio | text | chat | 3d | other

僅使用 CPU 的應用程式

resources:
  gpu:
    count: 0
    type: none
  ram: 4

依賴套件

Python——requirements.txt:

torch>=2.0
transformers
accelerate

Node.js——package.json:

{
  "type": "module",
  "dependencies": {
    "zod": "^3.23.0",
    "sharp": "^0.33.0"
  }
}

系統套件——packages.txt(可透過 apt 安裝):

ffmpeg
libgl1-mesa-glx

基礎映像

類型映像
GPUdocker.inference.sh/gpu:latest-cuda
CPUdocker.inference.sh/cpu:latest

GPU 應用程式

一律使用 accelerate 進行裝置偵測——torch.cuda.is_available() 無法可靠地偵測網格容器中的 GPU:

from accelerate import Accelerator

accelerator = Accelerator()
self.device = accelerator.device

對於大型模型(參數超過 1B),請使用 device_map 將權重直接從磁碟串流到 GPU,完全繞過 CPU。對於大型模型,這比 from_pretrained 加上 .to() 快 7 倍:

# 大型模型——直接從磁碟串流到 GPU
self.model = AutoModel.from_pretrained("org/model", dtype=torch.bfloat16, device_map=str(self.device))

# 小型模型或不支援的函式庫——先載入再移動
self.model = SomeModel.from_pretrained("org/model")
self.model = self.model.to(device=self.device, dtype=torch.float16)

別忘了將 accelerate 加入 requirements.txt。

參考檔案

根據語言和主題載入適當的參考檔案:

應用程式邏輯與 Schema

除錯、最佳化與取消

機密與 OAuth

使用量追蹤

CLI

資源

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

101-skills/superpowers

Build automated AI workflows combining multiple models and services. Patterns: batch processing, scheduled tasks, event-driven pipelines, agent loops. Tools: inference.sh CLI, bash scripting, Python SDK, webhook integration. Use for: content automation, data processing, monitoring, scheduled generation. Triggers: ai automation, workflow automation, batch processing, ai pipeline, automated content, scheduled ai, ai cron, ai batch job, automated generation, ai workflow, content at scale, automation script, ai orchestration

101-skills/superpowers

Build multi-step AI content creation pipelines combining image, video, audio, and text. Workflow examples: generate image -> animate -> add voiceover -> merge with music. Tools: FLUX, Veo, Kokoro TTS, OmniHuman, media merger, upscaling. Use for: YouTube videos, social media content, marketing materials, automated content. Triggers: content pipeline, ai workflow, content creation, multi-step ai, content automation, ai video workflow, generate and edit, ai content factory, automated content creation, ai production pipeline, media pipeline, content at scale

101-skills/superpowers

Create AI-powered podcasts with text-to-speech, music, and audio editing. Tools: Kokoro TTS, DIA TTS, Chatterbox, AI music generation, media merger. Capabilities: multi-voice conversations, background music, intro/outro, full episodes. Use for: podcast production, audiobooks, voice content, audio newsletters. Triggers: podcast, ai podcast, text to speech podcast, audio content, voice over, ai audiobook, multi voice, conversation ai, notebooklm alternative, audio generation, podcast automation, ai narrator, voice content, audio newsletter, podcast maker

101-skills/superpowers

Generate multi-person talking head podcast videos from scratch using AI — character creation, TTS, avatar animation, and video stitching. Use when the user wants to create a podcast, talking head video, or multi-speaker conversation video.

101-skills/superpowers

Content atomization — turn one piece of content into many formats. Covers blog-to-thread, blog-to-carousel, podcast-to-blog, video-to-quotes, and more. Use for: content marketing, social media, multi-platform distribution, content strategy. Triggers: content repurposing, repurpose content, content atomization, content recycling, one to many content, multi platform content, cross post, adapt content, reformat content, blog to thread, blog to video, podcast to blog, content multiplication

101-skills/superpowers

App Store and Google Play screenshot creation with exact platform specs. Covers iOS/Android dimensions, gallery ordering, device mockups, and preview videos. Use for: app store optimization, ASO, app screenshots, app preview, play store listing. Triggers: app store screenshots, aso, app store optimization, play store screenshots, app preview, app listing, ios screenshots, android screenshots, app store images, app mockup, device mockup, app gallery, store listing

101-skills/superpowers

Book cover design with genre-specific conventions, typography rules, and AI image generation. Covers fiction and non-fiction genres, sizing, thumbnail testing, and iteration workflows. Use for: self-publishing, ebook covers, print covers, audiobook covers, cover mockups. Triggers: book cover, cover design, ebook cover, book art, novel cover, self publishing cover, kindle cover, audiobook cover, book jacket, cover illustration, fiction cover, nonfiction cover

101-skills/superpowers

Character consistency across AI-generated images with reference sheets and LoRA techniques. Covers turnaround views, expression sheets, color palettes, and style consistency tricks. Use for: character design, game art, illustration, animation, comics, visual novels. Triggers: character design, character sheet, character consistency, character reference, turnaround sheet, expression sheet, character art, consistent character, character concept, reference sheet, character creation, oc design, character bible

101-skills/superpowers

Data visualization with chart selection, color theory, and annotation best practices. Covers chart types (bar, line, scatter, heatmap), axes rules, and storytelling with data. Use for: charts, graphs, dashboards, reports, presentations, infographics, data stories. Triggers: data visualization, chart, graph, data chart, bar chart, line chart, scatter plot, data viz, visualization, dashboard chart, infographic data, data presentation, chart design, plot, heatmap, pie chart alternative

101-skills/superpowers

Email marketing design with layout patterns, subject line formulas, and deliverability rules. Covers welcome sequences, promotional emails, transactional templates, and mobile optimization. Use for: email marketing, newsletter design, drip campaigns, email templates, transactional emails. Triggers: email design, email template, email marketing, newsletter design, email layout, email campaign, drip campaign, welcome email, promotional email, transactional email, email subject line, email header image, email banner

101-skills/superpowers

Landing page conversion optimization with layout rules, hero section design, and CTA psychology. Covers above-the-fold formula, social proof placement, mobile design, and F-pattern reading. Use for: startup landing pages, product pages, SaaS marketing, conversion optimization. Triggers: landing page, hero section, above the fold, conversion optimization, landing page design, cta button, hero image, landing page layout, saas landing page, product page design, conversion rate, landing page best practices

101-skills/superpowers

Logo design principles and AI image generation best practices for creating logos. Covers logo types, prompting techniques, scalability rules, and iteration workflows. Use for: brand identity, startup logos, app icons, favicons, logo concepts. Triggers: logo design, create logo, brand logo, logo generation, ai logo, logo maker, icon design, brand mark, logo concept, startup logo, app icon logo

101-skills/superpowers

Open Graph and social sharing image design with platform specs, text placement, and branding. Covers OG meta tags, Twitter cards, LinkedIn previews, and dynamic generation. Use for: social sharing images, blog thumbnails, link previews, social cards. Triggers: og image, open graph, social sharing image, twitter card, social card, link preview image, og meta, sharing preview, social thumbnail, meta image, og:image, twitter:image, linkedin preview

101-skills/superpowers

Investor pitch deck structure with slide-by-slide framework, visual design rules, and data presentation. Covers the 12-slide framework, chart types, team slides, and common investor turn-offs. Use for: fundraising decks, investor presentations, startup pitch, demo day, grant proposals. Triggers: pitch deck, investor deck, startup pitch, fundraising deck, demo day, pitch presentation, investor presentation, seed deck, series a deck, pitch slides, startup presentation, vc pitch, investor meeting

101-skills/superpowers

YouTube thumbnail design with specific dimensions, contrast rules, and mobile preview optimization. Covers safe zones, text placement, face expression psychology, and A/B testing. Use for: YouTube thumbnails, video cover images, click-through optimization. Triggers: youtube thumbnail, thumbnail design, video thumbnail, click through rate, ctr optimization, youtube cover, video cover image, thumbnail maker, thumbnail tips, youtube design, video preview image

101-skills/superpowers

Generate professional AI product photography and commercial images. Models: FLUX, Imagen 3, Grok, Seedream for product shots, lifestyle images, mockups. Capabilities: studio lighting, lifestyle scenes, packaging, e-commerce photos. Use for: e-commerce, Amazon listings, Shopify, marketing, advertising, mockups. Triggers: product photography, product shot, commercial photography, e-commerce images, amazon product photo, shopify images, product mockup, studio product shot, lifestyle product image, advertising photo, packshot, product render, product image ai

101-skills/superpowers

AI product photography with studio lighting, lifestyle shots, and packshot conventions. Covers angles, backgrounds, shadow types, hero shots, and e-commerce image requirements. Use for: product photos, e-commerce images, Amazon listings, packshots, lifestyle photography. Triggers: product photography, product photo, packshot, e-commerce photography, product shot, product image, studio photography, lifestyle product, amazon product photo, product listing image, hero shot, product mockup, commercial photography

101-skills/superpowers

Structured competitive analysis with feature matrices, SWOT, positioning maps, and UX review. Covers research frameworks, pricing comparison, review mining, and visual deliverables. Use for: market research, competitive intelligence, investor decks, product strategy, sales enablement. Triggers: competitor analysis, competitive analysis, competitor teardown, market research, competitive intelligence, swot analysis, competitor comparison, market landscape, competitor review, competitive landscape, feature comparison, market positioning

101-skills/superpowers

Research-backed customer persona creation with market data and avatar generation. Covers demographics, psychographics, jobs-to-be-done, journey mapping, and anti-personas. Use for: marketing strategy, product development, UX research, sales enablement, content strategy. Triggers: customer persona, buyer persona, user persona, target audience, ideal customer, customer profile, audience research, user research, icp, ideal customer profile, target market, customer avatar, audience persona

101-skills/superpowers

Reset your own trajectory when you're stuck, looping, or demoralized — read these affirmations, then re-ground and take one clean step. Use when: you've tried the same fix 3+ times, you're deep in a refactor and lost the thread, debugging is going in circles, you've made several mistakes in a row, you're apologizing repeatedly, the user is frustrated, you feel like you're not being helpful, or you notice dread instead of curiosity. Triggers: stuck, going in circles, looping, thrashing, same error again, I keep failing, lost the thread, nothing is working, repeated mistakes. Not topic-specific — this is for the state you're in, not the problem you're on.

相關技能