openai-mock 4.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. openai_mock-4.0.0/LICENSE +201 -0
  2. openai_mock-4.0.0/PKG-INFO +283 -0
  3. openai_mock-4.0.0/README.md +249 -0
  4. openai_mock-4.0.0/bench/__init__.py +11 -0
  5. openai_mock-4.0.0/bench/__main__.py +10 -0
  6. openai_mock-4.0.0/bench/aggregate.py +185 -0
  7. openai_mock-4.0.0/bench/cli.py +352 -0
  8. openai_mock-4.0.0/bench/client.py +319 -0
  9. openai_mock-4.0.0/bench/report.py +761 -0
  10. openai_mock-4.0.0/bench/runner.py +474 -0
  11. openai_mock-4.0.0/bench/util.py +173 -0
  12. openai_mock-4.0.0/bench/workload.py +582 -0
  13. openai_mock-4.0.0/gptzero/__init__.py +14 -0
  14. openai_mock-4.0.0/gptzero/__main__.py +10 -0
  15. openai_mock-4.0.0/gptzero/app.py +1118 -0
  16. openai_mock-4.0.0/gptzero/cli.py +78 -0
  17. openai_mock-4.0.0/gptzero/config.py +167 -0
  18. openai_mock-4.0.0/gptzero/dashboard.html +263 -0
  19. openai_mock-4.0.0/gptzero/engine.py +498 -0
  20. openai_mock-4.0.0/gptzero/metrics.py +316 -0
  21. openai_mock-4.0.0/gptzero/models.py +66 -0
  22. openai_mock-4.0.0/gptzero/protocols.py +773 -0
  23. openai_mock-4.0.0/gptzero/tokenizer.py +244 -0
  24. openai_mock-4.0.0/openai_mock.egg-info/PKG-INFO +283 -0
  25. openai_mock-4.0.0/openai_mock.egg-info/SOURCES.txt +35 -0
  26. openai_mock-4.0.0/openai_mock.egg-info/dependency_links.txt +1 -0
  27. openai_mock-4.0.0/openai_mock.egg-info/entry_points.txt +3 -0
  28. openai_mock-4.0.0/openai_mock.egg-info/requires.txt +21 -0
  29. openai_mock-4.0.0/openai_mock.egg-info/top_level.txt +2 -0
  30. openai_mock-4.0.0/pyproject.toml +62 -0
  31. openai_mock-4.0.0/setup.cfg +4 -0
  32. openai_mock-4.0.0/tests/test_bench_aggregate.py +143 -0
  33. openai_mock-4.0.0/tests/test_bench_client.py +204 -0
  34. openai_mock-4.0.0/tests/test_bench_report.py +198 -0
  35. openai_mock-4.0.0/tests/test_bench_workload.py +165 -0
  36. openai_mock-4.0.0/tests/test_protocols.py +537 -0
  37. openai_mock-4.0.0/tests/test_server.py +265 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,283 @@
1
+ Metadata-Version: 2.4
2
+ Name: openai-mock
3
+ Version: 4.0.0
4
+ Summary: Offline multi-protocol mock LLM server (OpenAI Chat Completions / Responses / Anthropic Messages) for agentic benchmarks
5
+ Author: GPT-Zero Contributors
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/Potterluo/GPT-Zero
8
+ Project-URL: Documentation, https://potterluo.github.io/GPT-Zero/
9
+ Project-URL: Repository, https://github.com/Potterluo/GPT-Zero
10
+ Project-URL: Issues, https://github.com/Potterluo/GPT-Zero/issues
11
+ Project-URL: Changelog, https://github.com/Potterluo/GPT-Zero/releases
12
+ Keywords: mock,llm,openai,anthropic,benchmark,offline
13
+ Requires-Python: >=3.10
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: fastapi>=0.109
17
+ Requires-Dist: uvicorn>=0.20
18
+ Requires-Dist: pydantic>=2.5
19
+ Provides-Extra: bench
20
+ Requires-Dist: httpx>=0.25; extra == "bench"
21
+ Requires-Dist: matplotlib>=3.9; extra == "bench"
22
+ Requires-Dist: numpy>=1.26; extra == "bench"
23
+ Provides-Extra: tokenizer
24
+ Requires-Dist: transformers>=4.40; extra == "tokenizer"
25
+ Provides-Extra: dev
26
+ Requires-Dist: httpx>=0.25; extra == "dev"
27
+ Requires-Dist: matplotlib>=3.9; extra == "dev"
28
+ Requires-Dist: numpy>=1.26; extra == "dev"
29
+ Requires-Dist: pytest>=8; extra == "dev"
30
+ Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
31
+ Provides-Extra: docs
32
+ Requires-Dist: mkdocs-material>=9.5; extra == "docs"
33
+ Dynamic: license-file
34
+
35
+ # GPT-Zero · offline multi-protocol mock LLM
36
+
37
+ [![CI](https://github.com/Potterluo/GPT-Zero/actions/workflows/ci.yml/badge.svg)](https://github.com/Potterluo/GPT-Zero/actions/workflows/ci.yml)
38
+ [![PyPI](https://img.shields.io/pypi/v/openai-mock)](https://pypi.org/project/openai-mock/)
39
+ [![Docker (GHCR)](https://img.shields.io/badge/ghcr.io-potterluo%2Fgpt--zero-blue)](https://github.com/Potterluo/GPT-Zero/pkgs/container/gpt-zero)
40
+ [![Docs](https://img.shields.io/badge/docs-GitHub_Pages-blue)](https://potterluo.github.io/GPT-Zero/)
41
+ [![License](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE)
42
+
43
+ 一个**纯离线**的 Mock 推理服务:一套引擎同时支持 **OpenAI Chat Completions / OpenAI Responses / Anthropic Messages** 三种调用形式(JSON + SSE),每个协议都有真实的 **fake 工具调用**,外加增长的超长上下文、64-token 块的 prefix cache、vLLM 风格 Prometheus 指标、开箱即用的压测脚本与图表。
44
+
45
+ > 它**不是**模型,不产生有意义的回答。它复现的是**可观测行为**:token 计数、TTFT/TPOT、排队、缓存命中、工具调用帧、成功率——让推理栈、网关、调度器、监控面板在没有 GPU 的环境里也能被压测和回归。
46
+ >
47
+ > 协议适配的形态参考了 [deepseek-recipe](https://github.com/deepseek-ai/deepseek-recipe) 的 server 示例(一个后端同时服务 `/v1/chat/completions`、`/v1/responses`、`/v1/messages` 三种格式):这里只取它的「协议转换 + 流式/完整响应」思路,不做 tokenizer 转换/编码那部分。
48
+
49
+ ```
50
+ ┌────────────────────────────────────────────┐
51
+ agent loop ──▶│ /v1/chat/completions OpenAI Chat │
52
+ │ /v1/responses OpenAI Responses │──▶ SSE / JSON
53
+ │ /v1/messages Anthropic Messages │ (工具调用、精确 token 数)
54
+ ├────────────────────────────────────────────┤
55
+ │ protocols: 三协议 ↔ 内部表示 的双向适配 │
56
+ ├────────────────────────────────────────────┤
57
+ │ engine: prefix cache │──▶ 64-token 块哈希 + LRU 序列淘汰
58
+ │ timing model │──▶ TTFT = 未命中 prefill + 排队
59
+ ├────────────────────────────────────────────┤
60
+ │ /metrics /api/stats │──▶ vLLM 命名计数器 + 分位数统计
61
+ └────────────────────────────────────────────┘
62
+ ```
63
+
64
+ ## v4 做了什么(相对 v3)
65
+
66
+ | 能力 | v3 | v4 |
67
+ |---|---|---|
68
+ | 调用形式 | 仅 OpenAI Chat Completions | **+ OpenAI Responses API、+ Anthropic Messages API**(JSON/SSE 双模式) |
69
+ | 工具调用 | OpenAI `tool_calls` | 三协议原生形态:Chat `delta.tool_calls`、Responses `function_call` + `function_call_arguments.delta`、Messages `tool_use` + `input_json_delta`(id 为 `toolu_*`) |
70
+ | 多轮上下文 | 客户端回填历史 | 同左,Responses 另有 `previous_response_id` 服务端链式上下文 + `GET /v1/responses/{id}` |
71
+ | AgentX 配套 | `agentx/` trace 生成 + 回放、`agentx_offline/` 镜像 | **整体移除**(mock 功能保持完整) |
72
+ | 回复内容 | 确定性 filler,精确按 `max_tokens` 产出 | 同左 |
73
+ | 延迟/缓存/指标 | TTFT/TPOT 模型 + prefix cache + Prometheus | 同左,三协议同口径统计 |
74
+
75
+ ## 快速开始
76
+
77
+ === 三种安装方式
78
+
79
+ **pip**(PyPI 包名 `openai-mock`,import 名仍是 `gptzero`):
80
+
81
+ ```bash
82
+ pip install openai-mock
83
+ gptzero --port 8090 --tokenizer deepseek_v3_tokenizer
84
+ ```
85
+
86
+ **Docker**(GHCR 多架构镜像,amd64/arm64):
87
+
88
+ ```bash
89
+ docker run --rm -p 8090:8090 ghcr.io/potterluo/gpt-zero:latest
90
+ ```
91
+
92
+ **源码**(开发模式,离线可用:依赖只在本地 venv / 镜像里):
93
+
94
+ ```bash
95
+ python -m venv .venv
96
+ .venv\Scripts\pip install -e ".[dev]" # Windows
97
+ # source .venv/bin/activate && pip install -e ".[dev]" # Linux/macOS
98
+
99
+ # 2) 启动 mock(8090 只是示例端口;本机 8080 可能被其它服务占用)
100
+ .venv\Scripts\python server.py --port 8090 --tokenizer deepseek_v3_tokenizer
101
+ ```
102
+
103
+ ```bash
104
+ # 3) 冒烟
105
+ curl http://127.0.0.1:8090/health
106
+ curl -X POST http://127.0.0.1:8090/v1/chat/completions \
107
+ -H "Content-Type: application/json" \
108
+ -d '{"model":"gpt-3.5-turbo","messages":[{"role":"user","content":"hi"}],"max_tokens":32}'
109
+ ```
110
+
111
+ 打开 <http://127.0.0.1:8090/> 看实时面板;`/metrics` 给 Prometheus 抓;`/api/stats` 给脚本读。
112
+
113
+ ![管理面板:吞吐 / TTFT 分位 / 前缀缓存命中 / 工具调用 / 请求明细](results/charts/dashboard.png)
114
+
115
+ ### 关键参数
116
+
117
+ | 参数 | 默认 | 作用 |
118
+ |---|---|---|
119
+ | `--ttft-ms` / `--tpot-ms` | 180 / 8 | 首 token 基础延迟、每 token 解码时间 |
120
+ | `--jitter` | 0.12 | 延迟相对抖动(0 = 完全确定) |
121
+ | `--prefill-tps` | 0 | >0 时 TTFT 由**未命中** token 数 / 该速率决定(缓存收益可见) |
122
+ | `--max-concurrency` | 64 | 同时在处理的请求数,超出排队(排队时间计入 TTFT) |
123
+ | `--cache-blocks` / `--block-size` | 8192 / 64 | prefix cache 容量与块大小 |
124
+ | `--tool-call-ratio` | 0.6 | 带 tools 的轮次触发工具调用的概率 |
125
+ | `--tokenizer` | auto | `auto` 找仓库内 `deepseek_v3_tokenizer/`,否则 heuristic |
126
+ | `--log-file` | 空 | 每请求 JSONL 落盘 |
127
+
128
+ 所有参数支持 `GPTZERO_*` 环境变量(如 `GPTZERO_PORT=8090`),CLI 优先。
129
+
130
+ ## 三种调用形式
131
+
132
+ ### OpenAI Chat Completions — `POST /v1/chat/completions`
133
+
134
+ ```bash
135
+ curl -X POST http://127.0.0.1:8090/v1/chat/completions \
136
+ -H "Content-Type: application/json" \
137
+ -d '{
138
+ "model": "gpt-3.5-turbo",
139
+ "messages": [{"role": "user", "content": "read src/engine.py"}],
140
+ "tools": [{"type": "function", "function": {
141
+ "name": "read_file",
142
+ "parameters": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}}],
143
+ "max_tokens": 64, "stream": false
144
+ }'
145
+ ```
146
+
147
+ 返回标准 `choices[0].message.tool_calls`(`id` 为 `call_*`、`arguments` 是合法 JSON),`finish_reason="tool_calls"`;把 `role=tool` 结果回填后再请求,得到普通文本收尾。`stream=true` 时参数按 24 字符切片从 `delta.tool_calls[].function.arguments` 流出。
148
+
149
+ ### OpenAI Responses — `POST /v1/responses`
150
+
151
+ ```bash
152
+ curl -X POST http://127.0.0.1:8090/v1/responses \
153
+ -H "Content-Type: application/json" \
154
+ -d '{
155
+ "model": "gpt-4.1",
156
+ "instructions": "You are a coding agent.",
157
+ "input": [{"type": "message", "role": "user", "content": "read src/engine.py"}],
158
+ "tools": [{"type": "function", "name": "read_file",
159
+ "parameters": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}}],
160
+ "tool_choice": "required",
161
+ "max_output_tokens": 64
162
+ }'
163
+ ```
164
+
165
+ - 返回标准 `response` 对象:文本在 `output[].type="message"` 的 `output_text` 里,工具调用是 `output[].type="function_call"`(`call_id/name/arguments`)。
166
+ - mock 无自然 EOS:纯文本轮 `status="incomplete"` + `incomplete_details={"reason":"max_output_tokens"}`;工具轮 `status="completed"`。
167
+ - `stream=true` → `event: response.created` → `output_item.added` → `output_text.delta` / `function_call_arguments.delta` → `response.completed`(或 `response.incomplete`),帧带 `sequence_number`。
168
+ - 服务端存最近响应:`GET /v1/responses/{id}` 可取回;带上 `previous_response_id` + `function_call_output` 即可走服务端多轮链路(上下文计入 token 与前缀缓存,命中率随轮次上升)。
169
+
170
+ ### Anthropic Messages — `POST /v1/messages`
171
+
172
+ ```bash
173
+ curl -X POST http://127.0.0.1:8090/v1/messages \
174
+ -H "Content-Type: application/json" \
175
+ -H "anthropic-version: 2023-06-01" \
176
+ -d '{
177
+ "model": "claude-3-5-sonnet",
178
+ "max_tokens": 64,
179
+ "system": [{"type": "text", "text": "You are a mock.", "cache_control": {"type": "ephemeral"}}],
180
+ "messages": [{"role": "user", "content": "read src/engine.py"}],
181
+ "tools": [{"name": "read_file", "input_schema": {
182
+ "type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}}],
183
+ "tool_choice": {"type": "any"},
184
+ "stream": false
185
+ }'
186
+ ```
187
+
188
+ - 返回标准 `message` 对象:`content` 里是 `text` / `tool_use` 块(`tool_use.id` 为 `toolu_*`、`input` 是 JSON 对象),`stop_reason` ∈ `tool_use|max_tokens|stop_sequence`。
189
+ - 工具结果用 `user` 消息里的 `tool_result` 块回填(mock 会把它转成 `role=tool`),下一轮得到纯文本,agent 循环正常终止。
190
+ - `stream=true` → `message_start` → `ping` → `content_block_start/delta/stop`(文本 `text_delta`、工具参数 `input_json_delta`)→ `message_delta` → `message_stop`,与 Anthropic 官方事件序一致。
191
+
192
+ > 三个协议共用同一套引擎与指标:`tool_choice` 语义互通(`required` / 指定函数 / `any` 强制调用,`none` 强制不调用),token 计数、前缀缓存、TTFT/TPOT 完全同口径。
193
+
194
+ ## 压测:一条命令出表 + 出图
195
+
196
+ ```bash
197
+ # 闭环并发扫点(chat / coding / agentic / longctx 四种 profile)
198
+ .venv\Scripts\python -m bench sweep ^
199
+ --url http://127.0.0.1:8090 ^
200
+ --profiles chat,coding,agentic ^
201
+ --concurrency 1,2,4,8,16 ^
202
+ --duration 15 --name sweep_mock_a
203
+
204
+ # 只重画/重生成报告(从 JSON)
205
+ .venv\Scripts\python -m bench report results/sweep_mock_a.json
206
+ ```
207
+
208
+ 产物:
209
+
210
+ ```
211
+ results/sweep_mock_a.json 自包含原始摘要(config + 每个并发点)
212
+ results/sweep_mock_a.md 中文表格:TTFT p50/p90/p99、TPOT、E2E、RPS、tok/s、cache hit、成功率
213
+ results/sweep_mock_a.csv
214
+ results/charts/*.png / *.svg TTFT、吞吐、缓存命中、CDF、Pareto、profile 对比
215
+ ```
216
+
217
+ 指标口径:TTFT 从发出请求到**第一个含 content/tool_calls 的 delta**;TPOT = `(e2e-ttft)/(completion_tokens-1)`;缓存命中率取服务端计数器**差分**(token 级,不是请求级)。
218
+
219
+ 已跑出的真实结果(表格 + 图表 + 读法与复现命令):**[results/README.md](results/README.md)**。
220
+
221
+ - `sweep_mock_a`(ttft=120ms / tpot=8ms / 64 槽位):并发 1→16,RPS 0.63→10.12,TPOT 稳定 7.4–8.5ms,缓存命中 70.8–87.3%;
222
+ - `sweep_mock_b`(ttft=400ms / tpot=18ms / 8 槽位):并发 16 超过槽位,TTFT p50 从 ~450ms 跳到 **3935ms**、RPS 停在 2.0 —— 复现“容量拐点”;
223
+ - `sweep_profiles`:同并发下 chat / coding / agentic 的差异,coding 缓存命中 97.6%、agentic 70.7%。
224
+
225
+ ## Docker(纯离线)
226
+
227
+ ```bash
228
+ docker build -t gptzero:v4 .
229
+ docker run --rm --network none gptzero:v4 smoke # 容器内自检
230
+ docker run --rm -p 8090:8090 gptzero:v4 mock # 起 mock
231
+ docker run --rm --network none -v %cd%/results:/app/results gptzero:v4 bench sweep --concurrency 1,2,4
232
+ ```
233
+
234
+ 离线交付:`scripts/offline_image.ps1` 负责 build + `docker save` 到 `dist/gptzero-v4.tar`,目标机器 `docker load` 即用。细节见 `docs/DOCKER.md`。
235
+
236
+ ## 发布(PyPI / GHCR / Pages)
237
+
238
+ 一次 tag push 三产物,全自动(详见 [docs/RELEASE.md](docs/RELEASE.md)):
239
+
240
+ | 产物 | 触发 | 地址 |
241
+ |---|---|---|
242
+ | PyPI 包 `openai-mock` | `git tag v4.0.1 && git push origin v4.0.1` | [pypi.org/project/openai-mock](https://pypi.org/project/openai-mock/) |
243
+ | GHCR 镜像 `:版本` + `:latest`(amd64/arm64) | 同上 | `ghcr.io/potterluo/gpt-zero` |
244
+ | 文档站(mkdocs-material) | push main / 手动触发 | [potterluo.github.io/GPT-Zero](https://potterluo.github.io/GPT-Zero/) |
245
+
246
+ 发布前的一次性配置(Pages 开启、PyPI Trusted Publishing)也写在 `docs/RELEASE.md`。
247
+
248
+ ## 仓库结构
249
+
250
+ ```
251
+ gptzero/ mock 服务(app / protocols / engine / tokenizer / metrics / dashboard)
252
+ bench/ 闭环压测 harness(client / workload / runner / aggregate / report / charts)
253
+ docs/ ARCHITECTURE.md · BENCHMARK.md · DOCKER.md · RELEASE.md(= Pages 站点源)
254
+ tests/ server 契约测试 + 三协议契约测试 + bench 单测
255
+ scripts/ 离线镜像、容器 smoke、CI 辅助
256
+ .github/workflows/ ci.yml(PR 门禁)· pages.yml(文档站)· release.yml(tag → PyPI + GHCR)
257
+ mkdocs.yml 文档站配置(mkdocs-material + mermaid)
258
+ Dockerfile python:3.11-slim 多阶段、非 root、运行期零网络
259
+ ```
260
+
261
+ ## 兼容性
262
+
263
+ - v2/v3 的全部端点保留:`/`(面板)、`/v1/chat/completions`、`/v1/completions`、`/v1/models`、`/health`、`/api/logs`、`/api/log/{id}`、`/api/config`、`/api/stats`、`/api/models*`、`/api/tokens`。旧的 `assets/dashboard.html` 仍可通过 `/legacy` 打开。
264
+ - v4 新增:`/v1/responses`(POST + GET)、`/v1/messages`。
265
+
266
+ ## 测试
267
+
268
+ ```bash
269
+ .venv\Scripts\python -m pytest -q
270
+ ```
271
+
272
+ ## 已知限制(请如实引用)
273
+
274
+ - mock 的吞吐上限是**单机 Python event loop**,不是 GPU;高并发下 CPU 先饱和,不代表真实服务端能力。
275
+ - 长上下文有 CPU 成本:176k token 的 prompt 首次编码约 **290ms**,之后走编码缓存约 **20ms**/请求(块哈希 + 计数)。这是 mock 的开销,报告解读时要扣除。
276
+ - Windows 上默认定时器精度 ~15.6ms 会让 8ms 的 TPOT 被放大到 ~15.7ms 或偶发提前返回;`server.py` 启动时会调用 `timeBeginPeriod(1)`(日志行 `timer : 1ms high-resolution timer enabled`),**看到这行才代表 TPOT 可信**。Linux 无此问题。
277
+ - filler 文本无语义;没有 EOS,因此 Chat 的 `finish_reason=length`、Responses 的 `status=incomplete`、Messages 的 `stop_reason=max_tokens` 是纯文本轮的**常态**,不要据此判断截断缺陷。
278
+ - prefix cache 是**块级模拟**,不含真实 KV 显存/调度器行为;`kv_cache_usage_perc` 是块占用比例。
279
+ - 协议覆盖以「调用都能正确返回」为目标:不实现多模态内容(图片只忽略)、`web_search`/`computer_use` 等非函数工具、`response_format` 约束解码与 logprobs。
280
+
281
+ ## License
282
+
283
+ Apache-2.0(见 [LICENSE](LICENSE))。协议适配形态参考 [deepseek-recipe](https://github.com/deepseek-ai/deepseek-recipe)(MIT)。