|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD-style license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +"""OpenAI-compatible request/response schemas for the ExecuTorch LLM server. |
| 8 | +
|
| 9 | +This is the Python view of the contract defined in ``extension/llm/server/spec``. |
| 10 | +Any language server must serialize to the same shapes; the conformance suite in |
| 11 | +``extension/llm/server/conformance`` validates them. |
| 12 | +""" |
| 13 | + |
| 14 | +import time |
| 15 | +import uuid |
| 16 | +from typing import Any, Literal, Optional, Union |
| 17 | + |
| 18 | +from pydantic import BaseModel, Field |
| 19 | + |
| 20 | + |
| 21 | +def _new_id(prefix: str) -> str: |
| 22 | + return f"{prefix}-{uuid.uuid4().hex}" |
| 23 | + |
| 24 | + |
| 25 | +class FunctionCall(BaseModel): |
| 26 | + name: Optional[str] = None |
| 27 | + arguments: Optional[str] = None |
| 28 | + |
| 29 | + |
| 30 | +class ToolCall(BaseModel): |
| 31 | + index: Optional[int] = None |
| 32 | + id: Optional[str] = None |
| 33 | + type: Literal["function"] = "function" |
| 34 | + function: FunctionCall |
| 35 | + |
| 36 | + |
| 37 | +class ChatMessage(BaseModel): |
| 38 | + role: str |
| 39 | + content: Optional[Union[str, list[dict[str, Any]]]] = None |
| 40 | + name: Optional[str] = None |
| 41 | + tool_calls: Optional[list[ToolCall]] = None |
| 42 | + tool_call_id: Optional[str] = None |
| 43 | + |
| 44 | + |
| 45 | +class StreamOptions(BaseModel): |
| 46 | + include_usage: bool = False |
| 47 | + |
| 48 | + |
| 49 | +class ChatCompletionRequest(BaseModel): |
| 50 | + model: Optional[str] = None |
| 51 | + messages: list[ChatMessage] |
| 52 | + stream: bool = False |
| 53 | + stream_options: Optional[StreamOptions] = None |
| 54 | + temperature: Optional[float] = None |
| 55 | + top_p: Optional[float] = None |
| 56 | + max_tokens: Optional[int] = None |
| 57 | + max_completion_tokens: Optional[int] = None |
| 58 | + stop: Optional[Union[str, list[str]]] = None |
| 59 | + n: int = 1 |
| 60 | + seed: Optional[int] = None |
| 61 | + # Sampling knobs that change generation output. We don't plumb these, so they |
| 62 | + # are modeled (not dropped) in order to be rejected with a clear error rather |
| 63 | + # than silently ignored — see serving_chat's unsupported-parameter check. |
| 64 | + frequency_penalty: Optional[float] = None |
| 65 | + presence_penalty: Optional[float] = None |
| 66 | + top_k: Optional[int] = None |
| 67 | + logit_bias: Optional[dict[str, float]] = None |
| 68 | + # Output-contract fields: modeled (not dropped) so we reject the ones we |
| 69 | + # can't honor rather than returning an output that violates what was asked. |
| 70 | + response_format: Optional[dict[str, Any]] = None |
| 71 | + logprobs: Optional[bool] = None |
| 72 | + top_logprobs: Optional[int] = None |
| 73 | + parallel_tool_calls: Optional[bool] = None |
| 74 | + # Per-request chat-template controls, e.g. {"enable_thinking": false} for Qwen3. |
| 75 | + chat_template_kwargs: Optional[dict[str, Any]] = None |
| 76 | + # Accepted now so the contract is stable; parsing/enforcement land in M2/M5. |
| 77 | + tools: Optional[list[dict[str, Any]]] = None |
| 78 | + tool_choice: Optional[Union[str, dict[str, Any]]] = None |
| 79 | + reasoning_effort: Optional[str] = None |
| 80 | + |
| 81 | + def resolved_max_tokens(self) -> int: |
| 82 | + # `is not None` (not `or`): an explicit 0 must not be treated as unset. |
| 83 | + # Callers validate positivity; -1 means "unset / auto". |
| 84 | + if self.max_completion_tokens is not None: |
| 85 | + return self.max_completion_tokens |
| 86 | + if self.max_tokens is not None: |
| 87 | + return self.max_tokens |
| 88 | + return -1 |
| 89 | + |
| 90 | + |
| 91 | +class Usage(BaseModel): |
| 92 | + prompt_tokens: int = 0 |
| 93 | + completion_tokens: int = 0 |
| 94 | + total_tokens: int = 0 |
| 95 | + |
| 96 | + |
| 97 | +class ResponseMessage(BaseModel): |
| 98 | + role: str = "assistant" |
| 99 | + content: Optional[str] = None |
| 100 | + tool_calls: Optional[list[ToolCall]] = None |
| 101 | + |
| 102 | + |
| 103 | +class Choice(BaseModel): |
| 104 | + index: int = 0 |
| 105 | + message: ResponseMessage |
| 106 | + finish_reason: Optional[str] = None |
| 107 | + |
| 108 | + |
| 109 | +class ChatCompletionResponse(BaseModel): |
| 110 | + id: str = Field(default_factory=lambda: _new_id("chatcmpl")) |
| 111 | + object: Literal["chat.completion"] = "chat.completion" |
| 112 | + created: int = Field(default_factory=lambda: int(time.time())) |
| 113 | + model: str |
| 114 | + choices: list[Choice] |
| 115 | + usage: Usage = Field(default_factory=Usage) |
| 116 | + |
| 117 | + |
| 118 | +class DeltaMessage(BaseModel): |
| 119 | + role: Optional[str] = None |
| 120 | + content: Optional[str] = None |
| 121 | + tool_calls: Optional[list[ToolCall]] = None |
| 122 | + |
| 123 | + |
| 124 | +class ChunkChoice(BaseModel): |
| 125 | + index: int = 0 |
| 126 | + delta: DeltaMessage |
| 127 | + finish_reason: Optional[str] = None |
| 128 | + |
| 129 | + |
| 130 | +class ChatCompletionChunk(BaseModel): |
| 131 | + id: str |
| 132 | + object: Literal["chat.completion.chunk"] = "chat.completion.chunk" |
| 133 | + created: int = Field(default_factory=lambda: int(time.time())) |
| 134 | + model: str |
| 135 | + choices: list[ChunkChoice] |
| 136 | + usage: Optional[Usage] = None |
| 137 | + |
| 138 | + |
| 139 | +class ModelCard(BaseModel): |
| 140 | + id: str |
| 141 | + object: Literal["model"] = "model" |
| 142 | + created: int = Field(default_factory=lambda: int(time.time())) |
| 143 | + owned_by: str = "executorch" |
| 144 | + |
| 145 | + |
| 146 | +class ModelList(BaseModel): |
| 147 | + object: Literal["list"] = "list" |
| 148 | + data: list[ModelCard] |
0 commit comments