|
| 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 | +"""Language-neutral OpenAI-contract conformance tests. |
| 8 | +
|
| 9 | +Runs against any base URL (ExecuTorch, llama.cpp, mlx-lm, ...) so every server |
| 10 | +implementation is validated against one shared spec. Point it at a running |
| 11 | +server: |
| 12 | +
|
| 13 | + OPENAI_BASE_URL=http://127.0.0.1:8000/v1 pytest test_openai_contract.py |
| 14 | +
|
| 15 | +Skips automatically if no server is reachable. |
| 16 | +""" |
| 17 | + |
| 18 | +import json |
| 19 | +import os |
| 20 | +import urllib.error |
| 21 | +import urllib.request |
| 22 | + |
| 23 | +import pytest |
| 24 | + |
| 25 | +BASE_URL = os.environ.get("OPENAI_BASE_URL", "http://127.0.0.1:8000/v1").rstrip("/") |
| 26 | +MODEL = os.environ.get("OPENAI_MODEL", "executorch") |
| 27 | + |
| 28 | + |
| 29 | +def _post(path: str, body: dict, stream: bool = False): |
| 30 | + req = urllib.request.Request( |
| 31 | + f"{BASE_URL}{path}", |
| 32 | + data=json.dumps(body).encode(), |
| 33 | + headers={"Content-Type": "application/json"}, |
| 34 | + method="POST", |
| 35 | + ) |
| 36 | + return urllib.request.urlopen(req, timeout=120) |
| 37 | + |
| 38 | + |
| 39 | +def _server_up() -> bool: |
| 40 | + try: |
| 41 | + urllib.request.urlopen(f"{BASE_URL}/models", timeout=5) |
| 42 | + return True |
| 43 | + except Exception: |
| 44 | + return False |
| 45 | + |
| 46 | + |
| 47 | +pytestmark = pytest.mark.skipif( |
| 48 | + not _server_up(), reason="no OpenAI server at OPENAI_BASE_URL" |
| 49 | +) |
| 50 | + |
| 51 | + |
| 52 | +def test_models_listing(): |
| 53 | + with urllib.request.urlopen(f"{BASE_URL}/models", timeout=10) as r: |
| 54 | + data = json.loads(r.read()) |
| 55 | + assert data["object"] == "list" |
| 56 | + assert any("id" in m for m in data["data"]) |
| 57 | + |
| 58 | + |
| 59 | +def test_chat_completion_nonstreaming(): |
| 60 | + body = { |
| 61 | + "model": MODEL, |
| 62 | + "messages": [{"role": "user", "content": "Say hello in one word."}], |
| 63 | + "max_tokens": 16, |
| 64 | + "temperature": 0.0, |
| 65 | + } |
| 66 | + with _post("/chat/completions", body) as r: |
| 67 | + data = json.loads(r.read()) |
| 68 | + assert data["object"] == "chat.completion" |
| 69 | + assert data["choices"][0]["message"]["role"] == "assistant" |
| 70 | + assert isinstance(data["choices"][0]["message"]["content"], str) |
| 71 | + assert data["choices"][0]["finish_reason"] is not None |
| 72 | + |
| 73 | + |
| 74 | +def test_chat_completion_streaming(): |
| 75 | + body = { |
| 76 | + "model": MODEL, |
| 77 | + "messages": [{"role": "user", "content": "Count to three."}], |
| 78 | + "max_tokens": 32, |
| 79 | + "stream": True, |
| 80 | + } |
| 81 | + saw_role = saw_content = saw_done = False |
| 82 | + with _post("/chat/completions", body, stream=True) as r: |
| 83 | + for raw in r: |
| 84 | + line = raw.decode().strip() |
| 85 | + if not line.startswith("data:"): |
| 86 | + continue |
| 87 | + payload = line[len("data:") :].strip() |
| 88 | + if payload == "[DONE]": |
| 89 | + saw_done = True |
| 90 | + break |
| 91 | + chunk = json.loads(payload) |
| 92 | + assert chunk["object"] == "chat.completion.chunk" |
| 93 | + delta = chunk["choices"][0]["delta"] |
| 94 | + saw_role = saw_role or delta.get("role") == "assistant" |
| 95 | + saw_content = saw_content or bool(delta.get("content")) |
| 96 | + assert saw_role and saw_content and saw_done |
| 97 | + |
| 98 | + |
| 99 | +def test_multibyte_streaming_integrity(): |
| 100 | + # Byte-level BPE can split a multi-byte character across tokens; the stream |
| 101 | + # must reassemble it, not abort with a UTF-8 decode error. |
| 102 | + body = { |
| 103 | + "model": MODEL, |
| 104 | + "messages": [ |
| 105 | + {"role": "user", "content": "Reply with exactly: 你好世界 🌍 café"} |
| 106 | + ], |
| 107 | + "max_tokens": 32, |
| 108 | + "temperature": 0.0, |
| 109 | + "stream": True, |
| 110 | + } |
| 111 | + content, saw_done, saw_error = "", False, False |
| 112 | + with _post("/chat/completions", body, stream=True) as r: |
| 113 | + for raw in r: |
| 114 | + line = raw.decode().strip() |
| 115 | + if not line.startswith("data:"): |
| 116 | + continue |
| 117 | + payload = line[len("data:") :].strip() |
| 118 | + if payload == "[DONE]": |
| 119 | + saw_done = True |
| 120 | + break |
| 121 | + chunk = json.loads(payload) |
| 122 | + if "error" in chunk: |
| 123 | + saw_error = True |
| 124 | + content += ( |
| 125 | + chunk["choices"][0]["delta"].get("content", "") |
| 126 | + if chunk.get("choices") |
| 127 | + else "" |
| 128 | + ) |
| 129 | + assert saw_done and not saw_error |
| 130 | + assert isinstance(content, str) and content # reassembled, valid UTF-8 |
| 131 | + |
| 132 | + |
| 133 | +def test_usage_chunk_in_stream(): |
| 134 | + body = { |
| 135 | + "model": MODEL, |
| 136 | + "messages": [{"role": "user", "content": "Say hi."}], |
| 137 | + "max_tokens": 16, |
| 138 | + "stream": True, |
| 139 | + "stream_options": {"include_usage": True}, |
| 140 | + } |
| 141 | + usage = None |
| 142 | + with _post("/chat/completions", body, stream=True) as r: |
| 143 | + for raw in r: |
| 144 | + line = raw.decode().strip() |
| 145 | + if not line.startswith("data:"): |
| 146 | + continue |
| 147 | + payload = line[len("data:") :].strip() |
| 148 | + if payload == "[DONE]": |
| 149 | + break |
| 150 | + chunk = json.loads(payload) |
| 151 | + if chunk.get("usage"): |
| 152 | + usage = chunk["usage"] |
| 153 | + assert usage is not None, "no usage chunk emitted with include_usage" |
| 154 | + assert usage["prompt_tokens"] > 0 and usage["completion_tokens"] > 0 |
| 155 | + assert usage["total_tokens"] == usage["prompt_tokens"] + usage["completion_tokens"] |
| 156 | + |
| 157 | + |
| 158 | +WEATHER_TOOL = { |
| 159 | + "type": "function", |
| 160 | + "function": { |
| 161 | + "name": "get_weather", |
| 162 | + "description": "Get the current weather for a city.", |
| 163 | + "parameters": { |
| 164 | + "type": "object", |
| 165 | + "properties": {"city": {"type": "string"}}, |
| 166 | + "required": ["city"], |
| 167 | + }, |
| 168 | + }, |
| 169 | +} |
| 170 | + |
| 171 | + |
| 172 | +def test_tool_call_response_shape(): |
| 173 | + body = { |
| 174 | + "model": MODEL, |
| 175 | + "messages": [ |
| 176 | + {"role": "user", "content": "What is the weather in Paris? Use the tool."} |
| 177 | + ], |
| 178 | + "tools": [WEATHER_TOOL], |
| 179 | + "max_tokens": 128, |
| 180 | + "temperature": 0.0, |
| 181 | + } |
| 182 | + with _post("/chat/completions", body) as r: |
| 183 | + data = json.loads(r.read()) |
| 184 | + calls = data["choices"][0]["message"].get("tool_calls") |
| 185 | + assert calls, "expected tool_calls in response" |
| 186 | + tc = calls[0] |
| 187 | + assert tc["type"] == "function" |
| 188 | + assert tc["id"] |
| 189 | + assert tc["function"]["name"] == "get_weather" |
| 190 | + json.loads(tc["function"]["arguments"]) # arguments is a JSON string |
| 191 | + assert data["choices"][0]["finish_reason"] == "tool_calls" |
| 192 | + |
| 193 | + |
| 194 | +def test_error_body_shape(): |
| 195 | + # Over-long prompt -> structured 400 (OpenAI error envelope), not a 500/drop. |
| 196 | + body = { |
| 197 | + "model": MODEL, |
| 198 | + "messages": [{"role": "user", "content": "word " * 40000}], |
| 199 | + "max_tokens": 8, |
| 200 | + } |
| 201 | + try: |
| 202 | + _post("/chat/completions", body) |
| 203 | + raise AssertionError("expected an HTTP error for over-long prompt") |
| 204 | + except urllib.error.HTTPError as e: |
| 205 | + assert 400 <= e.code < 500 |
| 206 | + err = json.loads(e.read())["error"] |
| 207 | + assert err["message"] and err["type"] |
0 commit comments