serving-and-clients
Serve BentoML services locally over HTTP or gRPC and call endpoints with Python clients, curl/OpenAPI, streaming, websocket clients, and operational serve flags.
- License 许可
- Apache-2.0
- 最近更新
- 2026-09-03
- Stars
- ★ 351
- Forks
- 27
01 前言 Front Matter
- name
- serving-and-clients
- license
- Apache 2.0
- metadata
- { "disco-role": "operating" }
- description
- Serve BentoML services locally over HTTP or gRPC and call endpoints with Python clients, curl/OpenAPI, streaming, websocket clients, and operational serve flags.
- disable-model-invocation
- true
02 资源文件 5
- 参考文档references/cli-reference.md4.0 KB
- 参考文档references/client-reference.md4.0 KB
- 参考文档references/troubleshooting.md4.0 KB
- 脚本scripts/inspect_service_client.py4.4 KB
- 脚本scripts/serve_command_builder.py3.4 KB
03 SKILL.md 正文
BentoML Serving And Clients
Use this sub-skill when the user needs to run a BentoML service locally, choose HTTP versus gRPC serving, call service endpoints from Python or curl, inspect endpoint schemas, or debug client/serve failures. For defining @bentoml.service and @bentoml.api, use ../service-authoring/SKILL.md. For bentoml build, containerization, and Bento packaging, use ../packaging-and-containerization/SKILL.md. For metrics, logs, tracing, scaling, and runtime resource configuration, use ../observability-and-operations/SKILL.md. For BentoCloud deployments and cloud endpoints, use ../cli-and-cloud/SKILL.md.
Local Serving
- Start HTTP serving with
bentoml serve SERVICE_TARGET, whereSERVICE_TARGETis an import target such asservice.py:Summarization, a local Bento tag such asfraud_detector:latest, or a Bento directory. - Prefer explicit source serving commands during development:
bentoml serve service.py:ServiceClass --working-dir . --development --reload --port 3000. - Production mode is the CLI default; use
--developmentfor local iteration because it uses one API worker and, with--reload, restarts on code/model-store changes. - Set
--working-dirwhenever the service module is not in the current shell directory; this prevents import target failures caused by the wrongsys.path. - Use
--host,--port,--api-workers,--backlog,--timeout, and SSL flags for local server behavior; environment variablesBENTOML_HOST,BENTOML_PORT,BENTOML_API_WORKERS, andBENTOML_TIMEOUTcan also supply values. - Use
bentoml serve-grpc SERVICE_TARGETonly when the caller needs gRPC; it is hidden in the CLI but implemented, supports reflection/channelz flags, and may require installing BentoML with gRPC dependencies.
See references/cli-reference.md and the bundled dry-run helper scripts/serve_command_builder.py for safe command construction.
HTTP Client Calls
- Use
bentoml.SyncHTTPClient(url, token=None, timeout=30, server_ready_timeout=None)for blocking Python calls andbentoml.AsyncHTTPClient(...)for async code. - Prefer context managers so connections close cleanly:
with bentoml.SyncHTTPClient("http://localhost:3000") as client:orasync with bentoml.AsyncHTTPClient("http://localhost:3000") as client:. - Client methods are created from the server’s
/schema.json; callclient.<endpoint>(...)when the endpoint name is a valid Python attribute orclient.call("endpoint_name", ...)when it is dynamic. - Match arguments to the service API signature. Normal structured inputs use keyword arguments such as
client.summarize(text="..."); root-input APIs require exactly one positional argument. - Set
server_ready_timeoutwhen connecting while a server is booting, and useclient.is_ready()to check/readyzbefore sending expensive calls. - For authenticated endpoints, pass
token="..."; if omitted, the client readsBENTO_CLOUD_API_KEYand sendsAuthorization: Bearer <token>when available.
See references/client-reference.md and scripts/inspect_service_client.py for schema inspection without starting a server.
Curl, OpenAPI, And Schema
- The local UI is available from the server root, the client schema is at
/schema.json, readiness is at/readyz, and OpenAPI JSON is exposed under the docs route asdocs.json. - For JSON APIs, send
POST /<route>withContent-Type: application/json; the hello-world endpoint shape iscurl -X POST http://localhost:3000/summarize -H 'Content-Type: application/json' -d '{"text":"..."}'. - If the API uses root input, the raw request body may be a scalar, bytes/text, or a serialized JSON value rather than an object with named fields.
- For files, the Python client switches to multipart when the schema contains file fields; with curl, mirror the schema’s content type and multipart field names.
- For endpoint-name confusion, inspect
/schema.jsonfirst; API method names, customroute=...values, and visible HTTP paths can differ.
Streaming And WebSockets
- A BentoML API that returns a Python generator or async generator is exposed as a streaming HTTP response; the Sync client returns an iterator and the Async client returns an async iterator for stream outputs.
- Iterate streaming results instead of forcing a single response value:
for chunk in client.generate(prompt="..."):orasync for chunk in await client.generate(prompt="..."):depending on the async method’s return. - WebSocket endpoints are mounted through FastAPI/ASGI apps, usually with
@bentoml.asgi_app(app, path="/chat"); the BentoML Python HTTP clients do not support WebSockets. - Use a WebSocket library such as
websocketsand connect to the mounted path plus websocket route, for examplews://localhost:3000/chat/ws. - Keep service-authoring details for ASGI mounting in
../service-authoring/SKILL.md; this sub-skill focuses on calling and debugging the running server.
gRPC Serving
- Use
bentoml serve-grpc SERVICE_TARGET --port 3000 --host 0.0.0.0for local gRPC serving when the environment includes gRPC support. - gRPC serving exposes BentoML’s generated service protocol and health service; tests use
grpc.health.v1.Health/Checkand generated BentoML stubs. - Useful gRPC flags include
--enable-reflection,--enable-channelz,--max-concurrent-streams,--protocol-version v1|v1alpha1,--api-workers,--backlog, and SSL cert/key/CA options. - On Windows, production gRPC serving has limitations around
SO_REUSEPORT; use--developmentfor local testing or containerize on Linux for production-like behavior.
Helper Scripts
scripts/serve_command_builder.pybuilds shell-safebentoml serveorbentoml serve-grpccommands and never starts a server unless a user copies the output.scripts/inspect_service_client.pyrequires an explicit URL, checks/readyzand/schema.json, and prints endpoint routes, input/output schemas, streaming flags, and task flags.- Keep all script examples self-contained and avoid pointing runtime guidance at source-repo docs, tests, or local checkout paths.
Troubleshooting Checklist
- Import target fails: use
module.py:ClassNameormodule:svc, pass--working-dir, and confirm the module imports from that directory. - Port conflict: change
--port, clear the process occupying the port, or use a separate HTTP and gRPC port. - Readiness timeout: increase
server_ready_timeout, check/readyz, and verify expensive model loading or startup hooks are not failing. - Wrong endpoint name: fetch
/schema.json, then call the route’snamewithclient.call(name, ...)or the generated method. - Request schema error: compare your kwargs to the endpoint input schema; root inputs take one positional argument and reject keyword arguments.
- Auth token error: pass
token=explicitly or setBENTO_CLOUD_API_KEY; verify the endpoint actually expects BentoCloud-style bearer auth. - Missing gRPC support: install the gRPC extra/dependencies before using
serve-grpcor generated gRPC clients. - Async lifecycle leak: use
async with bentoml.AsyncHTTPClient(...)or callawait client.close().
For deeper failure mapping, see references/troubleshooting.md.
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).