Communitygithub.com

101-skills/superpowers

Inference.shプラットフォーム上でアプリケーションを構築・デプロイします。入門、プラットフォームの理解、アプリ作成、リソース設定、inference.shアプリ開発の概要が必要なときに使用します。PythonとNode.jsの両方をサポートします。

superpowers とは?

このスキルは、inference.shプラットフォーム上でアプリケーションを構築・デプロイするための包括的なガイドです。開発者はbelt CLIを使用してアプリを初期化し、開発ワークフロー(スキャフォールディング、実装、テスト、デプロイ、クラウド検証)を順に実行することで、迅速にアプリを公開できます。PythonとNode.jsの両方をサポートしており、GPUリソースの設定、環境変数やシークレットの管理、複数機能を持つアプリの作成など、実践的なパターンを提供します。また、APIラッパーアプリのテンプレートや、大規模モデル向けの最適化テクニック(accelerateによるデバイス検出、device_mapによる効率的なモデル読み込み)も解説されています。referenceファイルにより、言語ごとの詳細な実装パターン、デバッグ、最適化、OAuth、使用量トラッキングなどのトピックをカバーしています。

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

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

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 を含む出力クラスは、BaseModel ではなく BaseAppOutput を拡張しなければなりません。BaseModel を使用すると、output_meta がレスポンスから静かに削除されます。
  • 任意の belt コマンドを実行する前に、必ずアプリディレクトリに cd してください。シェルのカレントワーキングディレクトリ(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" の欠落や誤ったカーネル名などのよくある間違いを防ぎます。

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      # スキーマからサンプル入力を生成
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 を確認します — 欠落している場合、出力クラスが BaseAppOutput ではなく BaseModel を拡張している可能性があります。

# その他の便利なコマンド
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):
        """ワーカー起動時または設定変更時に1回実行"""
        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) {
    /** ワーカー起動時または設定変更時に1回実行 */
    this.model = loadModel(config.modelId);
  }

  async run(inputData) {
    /** デフォルト関数 — 各リクエストに対して実行 */
    return { result: "done" };
  }

  async unload() {
    /** シャットダウン時のクリーンアップ */
  }

  async onCancel() {
    /** ユーザーがキャンセルしたときに呼び出される — 長時間タスク用 */
    return true;
  }
}

複数機能アプリ

アプリは異なる入出力スキーマを持つ複数の関数を公開できます。関数は自動検出されます。

Python: 型ヒント付きのPydantic入出力モデルを持つメソッドを追加します。 Node.js: 各メソッドに対して {パスカル名}Input および {パスカル名}Output のZodスキーマをエクスポートします。

関数はパブリック(_ プレフィックスなし)であり、ライフサイクルメソッド(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トークン
    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 に追加することを忘れないでください。

リファレンスファイル

言語とトピックに基づいて適切なリファレンスファイルを読み込んでください:

アプロジックとスキーマ

デバッグ、最適化、キャンセル

  • references/python-patterns.md — Python: CUDAデバッグ、デバイス検出、モデル読み込み、メモリクリーンアップ、混合精度、キャンセル
  • references/node-patterns.md — Node.js: ESM/importデバッグ、ストリーミング、メモリ管理、並行処理、キャンセル

シークレットとOAuth

使用量トラッキング

CLI

  • references/cli.md — 完全な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.

関連スキル