openai-specs
Build and debug LitServe OpenAI-compatible chat completions and embeddings endpoints with OpenAISpec and OpenAIEmbeddingSpec.
- License 许可
- Apache-2.0
- 最近更新
- 2026-09-03
- Stars
- ★ 351
- Forks
- 27
01 前言 Front Matter
- name
- openai-specs
- license
- Apache 2.0
- metadata
- { "disco-role": "operating" }
- description
- Build and debug LitServe OpenAI-compatible chat completions and embeddings endpoints with OpenAISpec and OpenAIEmbeddingSpec.
- disable-model-invocation
- true
02 资源文件 5
- 参考文档references/api-reference.md10.1 KB
- 参考文档references/troubleshooting.md9.9 KB
- 参考文档references/workflows.md10.3 KB
- 脚本scripts/openai_chat_server.py6.1 KB
- 脚本scripts/openai_embedding_server.py3.8 KB
03 SKILL.md 正文
LitServe OpenAI-Compatible Specs
Use this sub-skill when the user wants a LitServe server that looks like the
OpenAI API, including /v1/chat/completions, /v1/embeddings, streaming chat,
tool calls, response_format, image/audio chat messages, or embedding response
shape debugging.
For the underlying LitServe server model, LitAPI lifecycle, LitServer.run,
ports, process settings, auth, middleware, and non-OpenAI routes, first load the
root LitServe router at ../../SKILL.md and the server basics sub-skill at
../server-basics/SKILL.md.
Do not use this sub-skill for MCP tool exposure, GPU/Torch benchmark paths, or throughput benchmark harnesses.
Router
- Chat completions: use
OpenAISpecfor/v1/chat/completions.- Implement
LitAPI.predictas a generator, even when clients send non-streaming requests. - Return simple text by yielding strings, or return richer messages by yielding
dicts or
ChatMessage-compatible objects withrole,content,tool_calls, and optional token usage keys. - If you override
encode_response, it must also be a generator in sync mode.
- Implement
- Async chat completions: set
enable_async=Trueon theLitAPIand makepredictan async generator.decode_requestmay be sync or async; overriddenencode_responsemust yield from either a sync generator or async generator. - Streaming chat: keep the server implementation generator-based. The client
request field
stream=Trueselects SSE chunks;stream=Falsereturns one JSONchat.completionresponse assembled from the same generated messages. - Tool calls: yield a chat message with
tool_calls=[...]; keepfunction.argumentsas a JSON string. - Structured JSON output: read
response_formatfrom the request/context and yield JSON text yourself. LitServe accepts OpenAI-styletext,json_object, andjson_schemarequest shapes, but it does not synthesize or validate model JSON for you. - Image and audio inputs: accept
messages[*].contentas either text or a list of content items. Image items useimage_url; audio items useinput_audiowithformatlimited towavormp3. - Embeddings: use
OpenAIEmbeddingSpecfor/v1/embeddings.predictandencode_responsemust return values, not generators.- Return
{"embeddings": <list-of-vectors>}from customencode_response, plus optionalprompt_tokensandtotal_tokens. - Client-side batching (a request with multiple input items) is allowed only when server dynamic batching is not also enabled.
- OpenAI SDK compatibility: keep the default spec paths. A custom
api_pathregisters the endpoint, but the OpenAI Python SDK only targets the default/v1/chat/completionsand/v1/embeddingspaths throughbase_url="http://host:port/v1".
Minimal implementation patterns
Chat completions:
import litserve as ls
from litserve import OpenAISpec
class ChatAPI(ls.LitAPI):
def predict(self, request):
# request is a ChatCompletionRequest
yield "This is a generated output"
if __name__ == "__main__":
api = ChatAPI(spec=OpenAISpec())
server = ls.LitServer(api)
server.run(port=8000)
Embeddings:
import litserve as ls
from litserve import OpenAIEmbeddingSpec
class EmbeddingAPI(ls.LitAPI):
def predict(self, inputs):
n = len(inputs) if isinstance(inputs, list) else 1
return [[0.0, 1.0, 0.5] for _ in range(n)]
def encode_response(self, output):
return {"embeddings": output}
if __name__ == "__main__":
api = EmbeddingAPI(spec=OpenAIEmbeddingSpec())
server = ls.LitServer(api)
server.run(port=8000)
Bundled runnable examples:
scripts/openai_chat_server.py— chat completions server with streaming, usage, tool-call,response_format, image, and audio request handling hooks.scripts/openai_embedding_server.py— deterministic embeddings server with OpenAI-compatible response shape and optional usage accounting.
References
references/api-reference.md— request/response models, endpoint paths, response assembly rules, validation contracts, and import paths.references/workflows.md— implementation recipes for chat, streaming, tool calls, JSON response format, multimodal messages, embeddings, batching, and OpenAI SDK clients.references/troubleshooting.md— failure matrix for generator validation, async mode, malformed outputs, embedding response rejection, multimodal payload errors, batching conflicts, and custom path warnings.
Handoff checklist for future agents
Before claiming an OpenAI-compatible LitServe endpoint is ready:
- Confirm the correct spec is attached:
OpenAISpec()for chat orOpenAIEmbeddingSpec()for embeddings. - Confirm the route is the spec default unless the user intentionally chose raw HTTP over OpenAI SDK compatibility.
- For chat, confirm
predictis generator-based and any customencode_responseis generator-based. - For async chat, confirm
enable_async=Trueandpredictis an async generator. - For embeddings, confirm no generator/yield is used and the response includes
an
embeddingskey with one vector per requested input item. - Exercise both SDK-style clients and direct HTTP only within the user's target environment; do not rely on repository checkout paths at runtime.
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).