Communitygithub.com

101-skills/superpowers (inference.sh 应用开发)

在 inference.sh 平台上构建和部署应用。适用于入门、了解平台、创建应用、配置资源或需要 overview 的场景。支持 Python 和 Node.js。

superpowers (inference.sh 应用开发) 是什么?

该 AI 代理技能提供了在 inference.sh 平台上构建和部署应用的完整指南。它支持 Python 和 Node.js 两种语言,并严格规定必须使用 `belt app init` 命令行工具进行项目脚手架搭建,避免手动创建文件和目录。技能详细介绍了从项目初始化、本地测试、部署到云端验证的完整开发流程,并提供了 Python 和 Node.js 的代码模板。此外,它还涵盖了多函数应用、API 封装应用模式、资源(GPU/内存)配置、环境变量与密钥管理、GPU 应用优化(如使用 `accelerate` 检测设备)等重要主题。该技能旨在帮助开发者在 inference.sh 平台上高效、规范地开发可扩展的 AI 应用。

兼容平台~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 的当前工作目录不会在工具调用之间持久化——如果忘记先 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——如果缺失,说明输出类可能继承了 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):
        """在工作进程启动或配置更改时运行一次"""
        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) {
    /** 在工作进程启动或配置更改时运行一次 */
    this.model = loadModel(config.modelId);
  }

  async run(inputData) {
    /** 默认函数——每个请求运行一次 */
    return { result: "done" };
  }

  async unload() {
    /** 关闭时清理 */
  }

  async onCancel() {
    /** 用户取消时调用——用于长时间运行的任务 */
    return true;
  }
}

多函数应用

应用可以暴露多个具有不同输入/输出模式的函数。函数会被自动发现。

Python: 添加带有类型提示的 Pydantic 输入/输出模型的方法。 Node.js: 为每个方法导出 {PascalName}Input 和 {PascalName}Output Zod 模式。

函数必须是公开的(无 _ 前缀)且不能是生命周期方法(setup、unload、on_cancel/onCancel、constructor)。

通过 API 调用时,在请求体中指定 "function": "method_name"。在 inf.yml 中设置 default_function 来更改未指定函数时的默认行为(默认为 run)。

API 封装应用模板(Python)

大多数仅使用 CPU 且封装外部 API 的应用遵循以下模式。可以将其作为起点:

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

对于大型模型(>10亿参数),请使用 device_map 将权重直接从磁盘流式传输到 GPU,完全跳过 CPU。对于大型模型,这比 from_pretrained + .to() 快 7 倍:

# 大型模型——直接从磁盘到 GPU 流式传输
self.model = AutoModel.from_pretrained("org/model", dtype=torch.bfloat16, device_map=str(self.device))

# 小型模型或不支持 device_map 的库——加载后再移动
self.model = SomeModel.from_pretrained("org/model")
self.model = self.model.to(device=self.device, dtype=torch.float16)

记得将 accelerate 添加到 requirements.txt。

参考文件

根据语言和主题加载相应的参考文件:

应用逻辑与模式

调试、优化与取消

Secret 与 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.

相关技能