service-authoring
Author BentoML services and APIs with the current class-based SDK, including service decorators, API/task endpoints, IO specs, batching, dependencies, lifecycle hooks, ASGI/Gradio/WebSocket/streaming integrations, GPU/runtime hints, and service-loading checks.
- License 许可
- Apache-2.0
- 最近更新
- 2026-09-03
- Stars
- ★ 351
- Forks
- 27
01 前言 Front Matter
- name
- service-authoring
- license
- Apache 2.0
- metadata
- { "disco-role": "operating" }
- description
- Author BentoML services and APIs with the current class-based SDK, including service decorators, API/task endpoints, IO specs, batching, dependencies, lifecycle hooks, ASGI/Gradio/WebSocket/streaming integrations, GPU/runtime hints, and service-loading checks.
- disable-model-invocation
- true
02 资源文件 5
- 参考文档references/api-reference.md6.1 KB
- 参考文档references/troubleshooting.md5.4 KB
- 参考文档references/workflows.md4.5 KB
- 脚本scripts/create_minimal_service.py3.8 KB
- 脚本scripts/validate_service_target.py5.7 KB
03 SKILL.md 正文
BentoML Service Authoring
Use this sub-skill when creating or debugging service.py and other BentoML service modules. It focuses on Python SDK authoring, not Bento packaging, model-store import mechanics, client usage, observability, cloud deployment, or CLI operations.
Route The Work
- For service class structure, endpoint decorators, IO annotations, batching, service dependencies, hooks, ASGI/Gradio/WebSocket/streaming, and local import checks, stay here.
- For
bentoml build, Bento image/container settings,bentofile.yaml, include/exclude rules, or containerization, use../packaging-and-containerization/SKILL.md. - For
bentoml serve,SyncHTTPClient,AsyncHTTPClient, HTTP calls, and server flags, use../serving-and-clients/SKILL.md. - For framework-specific model saving/loading, Model Store tags, and import APIs, use
../model-management/SKILL.md. - For metrics, tracing, logging, scaling, config overrides, and operations, use
../observability-and-operations/SKILL.md. - For
bentoml deploy, BentoCloud resources, secrets, and deployment config, use../cli-and-cloud/SKILL.md.
Authoring Checklist
- Put the service in an importable module, usually
service.py, and assign the decorated class at module scope. - Decorate a class with
@bentoml.serviceor@bentoml.service(...); default service name is the class name. - Keep heavyweight framework imports in
__init__, lifecycle hooks, orwith bentoml.importing():if they may be absent during tooling/import-only phases. - Define public endpoints with
@bentoml.apior@bentoml.api(...); use@bentoml.taskonly for asynchronous task-queue endpoints. - Add precise type hints or explicit
input_spec=/output_spec=so BentoML can infer request/response schemas. - Validate importability before serving or building with
scripts/validate_service_target.py --target service:MyService --working-dir ..
Minimal Pattern
from __future__ import annotations
import bentoml
@bentoml.service(name="text_tools", path_prefix="/v1")
class TextTools:
@bentoml.api(route="/echo", name="echo")
def echo(self, text: str) -> str:
return text
@bentoml.api(batchable=True, max_batch_size=32, max_latency_ms=1000)
def summarize(self, texts: list[str]) -> list[str]:
return [text[:80] for text in texts]
Generate a fuller starter service with:
python skills/bentoml/sub-skills/service-authoring/scripts/create_minimal_service.py --output service.py --class-name TextTools
Key Decisions
@bentoml.service(...)acceptsname,image,description,path_prefix,envs,labels,cmd,service_class, and service config kwargs such asresources,workers,traffic,metrics, andlogging.path_prefix="/v1"applies to BentoML API routes, mounted ASGI apps, and health endpoints such as/v1/livezand/v1/readyz.@bentoml.api(...)and@bentoml.task(...)shareroute,name,input_spec,output_spec,batchable,batch_dim,max_batch_size, andmax_latency_ms; task endpoints must not return a stream.- For batchable APIs, accept one batched argument plus optional
bentoml.Context, return the matching batched structure, and setbatch_dim=(input_dim, output_dim)when input and output split axes differ. - Use
bentoml.depends(OtherService)for service composition; call blocking dependency APIs through.to_asyncfrom async endpoints. - Use
bentoml.images.Image(...).python_packages(...)andenvs=[...]as service-level runtime hints, but route full packaging decisions to packaging guidance.
Advanced Integrations
- Lifecycle: use
@bentoml.on_deploymentfor once-before-workers setup,@bentoml.on_startupfor per-worker startup,@bentoml.on_shutdownfor cleanup, and__is_alive__/__is_ready__for health checks. - ASGI: create a FastAPI/Starlette/Quart app, mount it with
@bentoml.asgi_app(app, path="/app"), and usebentoml.get_current_service()or class-routeselfto access service state. - Gradio: create a Gradio
Interface/Blocksand mount with@bentoml.gradio.mount_gradio_app(blocks, path="/ui"); includefastapiandgradioin the runtime environment. - WebSocket: mount a FastAPI app with
@app.websocket(...); BentoML Python clients do not handle WebSocket endpoints, so author a direct WebSocket client for tests or consumers. - Streaming: return a
Generator[...]orAsyncGenerator[...]from@bentoml.api; BentoML defaults stream media type totext/event-streamwhen no explicit media type is inferred. - GPU/runtime hints: put
resources={"gpu": 1}orresources={"gpu": 2}on the service and select framework devices in__init__; usebentoml.server_context.worker_indexwhen mapping multiple workers to devices.
References
references/api-reference.mdfor decorator signatures, route/schema choices, IO validators, and lifecycle/API patterns.references/workflows.mdfor common recipes: minimal services, batching, tasks, composition, ASGI/Gradio/WebSocket/streaming, and validation loops.references/troubleshooting.mdfor import target errors, missing runtime dependencies, invalid specs, batching mismatch, optional dependency gaps, service init side effects, and async task misuse.scripts/create_minimal_service.pyto generate a safe starter service without relying on repository examples.scripts/validate_service_target.pyto import a user service target from a chosen working directory and inspect APIs/tasks/routes without serving it.
04 同仓库更多 Skills
passnet-triton-opt
Make a single PassNet Triton kernel fast AND numerically faithful: performance model (when a replacement can win at all), block/grid/warp tuning, autotune policy, launch overhead, and per-op numeric recipes to pass the dtype baseline tolerances. Use when a pass matches and is correct but speedup below expected, or when correctness fails by small numeric margins.
passnet-solve
END-TO-END playbook for solving one PassNet sample: analyze the computation graphs, decide the optimization strategy (what to fuse, what to replace, what to leave alone), drive the iteration loop, and maximize the sample score. This is the ENTRY skill — invoke it first for any PassNet optimization task; it tells you when to use passnet-pattern-fusion, passnet-triton-opt and passnet-feedback.
passnet-skill
PassNet GPU kernel optimization via compiler passes. Design and implement Triton-based optimization passes, create pass files under ./pass_dir/, self-evaluate with pass_evaluator, and iterate to maximize GPU speedup.
passnet-pattern-fusion
Author PassNet pass files: write patterns that actually MATCH the FX graph, pick fusion regions (which ops to absorb into one Triton kernel), and structure multi-pass submissions with the mandatory shared-dispatch architecture. Use when creating or fixing pattern()/replacement_args()/replacement_func() files, when a pass "failed to match", or when deciding how to fuse multiple kernels/ops.
passnet-orchestrate
Round/batch planning and decision support for PassNet graph optimization. Use for multi-sample triage, worker allocation, eval-budget policy, and post-eval keep/revert decisions. For solving one concrete sample end to end, use passnet-solve as the entry skill; consult this skill only when you need broader planning or a specific decision gate.
passnet-feedback
Fast, deterministic feedback for PassNet work: pre-flight pattern/match verification WITHOUT burning a GPU evaluation, per-node bottleneck analysis of a sample's graphs, and eval-log parsing into per-variant status + estimated score + failure classification. Use BEFORE every GPU evaluation (check_pattern), at the START of a sample (analyze_graph), and AFTER every evaluation (parse_eval_log).