Brunobkr commited on
Commit
9e735b0
·
verified ·
1 Parent(s): 4988dfa

Upload folder using huggingface_hub (part 8)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +4 -0
  2. tools/server/bench/prometheus.yml +9 -0
  3. tools/server/bench/requirements.txt +2 -0
  4. tools/server/bench/script.js +162 -0
  5. tools/server/bench/speed-bench/README.md +117 -0
  6. tools/server/bench/speed-bench/requirements.txt +3 -0
  7. tools/server/bench/speed-bench/speed_bench.py +432 -0
  8. tools/server/bench/speed-bench/speed_bench_compare.py +84 -0
  9. tools/server/main.cpp +5 -0
  10. tools/server/server-chat.cpp +692 -0
  11. tools/server/server-chat.h +26 -0
  12. tools/server/server-common.cpp +1595 -0
  13. tools/server/server-common.h +448 -0
  14. tools/server/server-context.cpp +0 -0
  15. tools/server/server-context.h +182 -0
  16. tools/server/server-cors-proxy.h +83 -0
  17. tools/server/server-http.cpp +833 -0
  18. tools/server/server-http.h +100 -0
  19. tools/server/server-mcp.cpp +820 -0
  20. tools/server/server-mcp.h +176 -0
  21. tools/server/server-models.cpp +0 -0
  22. tools/server/server-models.h +390 -0
  23. tools/server/server-queue.cpp +460 -0
  24. tools/server/server-queue.h +209 -0
  25. tools/server/server-schema.cpp +659 -0
  26. tools/server/server-schema.h +104 -0
  27. tools/server/server-stream.cpp +668 -0
  28. tools/server/server-stream.h +79 -0
  29. tools/server/server-task.cpp +1854 -0
  30. tools/server/server-task.h +670 -0
  31. tools/server/server-tools.cpp +2195 -0
  32. tools/server/server-tools.h +55 -0
  33. tools/server/server.cpp +537 -0
  34. tools/server/tests/.gitignore +2 -0
  35. tools/server/tests/README.md +96 -0
  36. tools/server/tests/conftest.py +21 -0
  37. tools/server/tests/fixtures/mcp_burst_server.py +118 -0
  38. tools/server/tests/fixtures/mcp_crash_server.py +114 -0
  39. tools/server/tests/fixtures/mcp_echo_server.py +164 -0
  40. tools/server/tests/fixtures/mcp_grandchild_server.py +100 -0
  41. tools/server/tests/fixtures/mcp_malformed_server.py +113 -0
  42. tools/server/tests/fixtures/mcp_slow_server.py +132 -0
  43. tools/server/tests/pytest.ini +4 -0
  44. tools/server/tests/requirements.txt +7 -0
  45. tools/server/tests/tests.sh +23 -0
  46. tools/server/tests/unit/test_basic.py +113 -0
  47. tools/server/tests/unit/test_chat_completion.py +625 -0
  48. tools/server/tests/unit/test_compat_anthropic.py +1090 -0
  49. tools/server/tests/unit/test_compat_gcp.py +60 -0
  50. tools/server/tests/unit/test_compat_oai_responses.py +114 -0
.gitattributes CHANGED
@@ -82,3 +82,7 @@ models/ggml-vocab-qwen2.gguf filter=lfs diff=lfs merge=lfs -text
82
  models/ggml-vocab-qwen35.gguf filter=lfs diff=lfs merge=lfs -text
83
  models/ggml-vocab-refact.gguf filter=lfs diff=lfs merge=lfs -text
84
  models/ggml-vocab-starcoder.gguf filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
82
  models/ggml-vocab-qwen35.gguf filter=lfs diff=lfs merge=lfs -text
83
  models/ggml-vocab-refact.gguf filter=lfs diff=lfs merge=lfs -text
84
  models/ggml-vocab-starcoder.gguf filter=lfs diff=lfs merge=lfs -text
85
+ tools/ui/.svelte-kit/output/client/recommended-mcp/huggingface.ico filter=lfs diff=lfs merge=lfs -text
86
+ tools/ui/dist/_gzip/_app/immutable/assets/bundle.S65JMH_w.css filter=lfs diff=lfs merge=lfs -text
87
+ tools/ui/dist/_gzip/_app/immutable/bundle.Yxmpoeis.js filter=lfs diff=lfs merge=lfs -text
88
+ tools/ui/dist/recommended-mcp/huggingface.ico filter=lfs diff=lfs merge=lfs -text
tools/server/bench/prometheus.yml ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ global:
2
+ scrape_interval: 10s
3
+ external_labels:
4
+ llamacpp: 'server'
5
+
6
+ scrape_configs:
7
+ - job_name: 'llama.cpp server'
8
+ static_configs:
9
+ - targets: ['localhost:8080']
tools/server/bench/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ matplotlib
2
+ requests
tools/server/bench/script.js ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sse from 'k6/x/sse'
2
+ import {check, sleep} from 'k6'
3
+ import {SharedArray} from 'k6/data'
4
+ import {Counter, Rate, Trend} from 'k6/metrics'
5
+ import exec from 'k6/execution';
6
+
7
+ // Server chat completions prefix
8
+ const server_url = __ENV.SERVER_BENCH_URL ? __ENV.SERVER_BENCH_URL : 'http://localhost:8080/v1'
9
+
10
+ // Number of total prompts in the dataset - default 10m / 10 seconds/request * number of users
11
+ const n_prompt = __ENV.SERVER_BENCH_N_PROMPTS ? parseInt(__ENV.SERVER_BENCH_N_PROMPTS) : 600 / 10 * 8
12
+
13
+ // Model name to request
14
+ const model = __ENV.SERVER_BENCH_MODEL_ALIAS ? __ENV.SERVER_BENCH_MODEL_ALIAS : 'my-model'
15
+
16
+ // Dataset path
17
+ const dataset_path = __ENV.SERVER_BENCH_DATASET ? __ENV.SERVER_BENCH_DATASET : './ShareGPT_V3_unfiltered_cleaned_split.json'
18
+
19
+ // Max tokens to predict
20
+ const max_tokens = __ENV.SERVER_BENCH_MAX_TOKENS ? parseInt(__ENV.SERVER_BENCH_MAX_TOKENS) : 512
21
+
22
+ // Max prompt tokens
23
+ const n_prompt_tokens = __ENV.SERVER_BENCH_MAX_PROMPT_TOKENS ? parseInt(__ENV.SERVER_BENCH_MAX_PROMPT_TOKENS) : 1024
24
+
25
+ // Max slot context
26
+ const n_ctx_slot = __ENV.SERVER_BENCH_MAX_CONTEXT ? parseInt(__ENV.SERVER_BENCH_MAX_CONTEXT) : 2048
27
+
28
+ export function setup() {
29
+ console.info(`Benchmark config: server_url=${server_url} n_prompt=${n_prompt} model=${model} dataset_path=${dataset_path} max_tokens=${max_tokens}`)
30
+ }
31
+
32
+ const data = new SharedArray('conversations', function () {
33
+ const tokenizer = (message) => message.split(/[\s,'".?]/)
34
+
35
+ return JSON.parse(open(dataset_path))
36
+ // Filter out the conversations with less than 2 turns.
37
+ .filter(data => data["conversations"].length >= 2)
38
+ .filter(data => data["conversations"][0]["from"] === "human")
39
+ .map(data => {
40
+ return {
41
+ prompt: data["conversations"][0]["value"],
42
+ n_prompt_tokens: tokenizer(data["conversations"][0]["value"]).length,
43
+ n_completion_tokens: tokenizer(data["conversations"][1]["value"]).length,
44
+ }
45
+ })
46
+ // Filter out too short sequences
47
+ .filter(conv => conv.n_prompt_tokens >= 4 && conv.n_completion_tokens >= 4)
48
+ // Filter out too long sequences.
49
+ .filter(conv => conv.n_prompt_tokens <= n_prompt_tokens && conv.n_prompt_tokens + conv.n_completion_tokens <= n_ctx_slot)
50
+ // Keep only first n prompts
51
+ .slice(0, n_prompt)
52
+ })
53
+
54
+ const llamacpp_prompt_tokens = new Trend('llamacpp_prompt_tokens')
55
+ const llamacpp_completion_tokens = new Trend('llamacpp_completion_tokens')
56
+
57
+ const llamacpp_tokens_second = new Trend('llamacpp_tokens_second')
58
+ const llamacpp_prompt_processing_second = new Trend('llamacpp_prompt_processing_second')
59
+ const llamacpp_emit_first_token_second = new Trend('llamacpp_emit_first_token_second')
60
+
61
+ const llamacpp_prompt_tokens_total_counter = new Counter('llamacpp_prompt_tokens_total_counter')
62
+ const llamacpp_completion_tokens_total_counter = new Counter('llamacpp_completion_tokens_total_counter')
63
+
64
+ const llamacpp_completions_truncated_rate = new Rate('llamacpp_completions_truncated_rate')
65
+ const llamacpp_completions_stop_rate = new Rate('llamacpp_completions_stop_rate')
66
+
67
+ export const options = {
68
+ thresholds: {
69
+ llamacpp_completions_truncated_rate: [
70
+ // more than 80% of truncated input will abort the test
71
+ {threshold: 'rate < 0.8', abortOnFail: true, delayAbortEval: '1m'},
72
+ ],
73
+ },
74
+ duration: '10m',
75
+ vus: 8,
76
+ }
77
+
78
+ export default function () {
79
+ const conversation = data[exec.scenario.iterationInInstance % data.length]
80
+ const payload = {
81
+ "messages": [
82
+ {
83
+ "role": "system",
84
+ "content": "You are ChatGPT, an AI assistant.",
85
+ },
86
+ {
87
+ "role": "user",
88
+ "content": conversation.prompt,
89
+ }
90
+ ],
91
+ "model": model,
92
+ "stream": true,
93
+ "stream_options": {
94
+ "include_usage": true, // False to be supported in llama.cpp server
95
+ },
96
+ "seed": 42,
97
+ "max_tokens": max_tokens,
98
+ "stop": ["<|im_end|>"] // This is temporary for phi-2 base (i.e. not instructed) since the server expects that the model always to emit BOS
99
+ }
100
+
101
+ const params = {method: 'POST', body: JSON.stringify(payload)};
102
+
103
+ const startTime = new Date()
104
+ let promptEvalEndTime = null
105
+ let prompt_tokens = 0
106
+ let completions_tokens = 0
107
+ let finish_reason = null
108
+ const res = sse.open(`${server_url}/chat/completions`, params, function (client) {
109
+ client.on('event', function (event) {
110
+ if (promptEvalEndTime == null) {
111
+ promptEvalEndTime = new Date()
112
+ llamacpp_emit_first_token_second.add((promptEvalEndTime - startTime) / 1.e3)
113
+ }
114
+
115
+ if (event.data === '[DONE]' || event.data === '') {
116
+ return
117
+ }
118
+
119
+ let chunk = JSON.parse(event.data)
120
+
121
+ if (chunk.choices && chunk.choices.length > 0) {
122
+ let choice = chunk.choices[0]
123
+ if (choice.finish_reason) {
124
+ finish_reason = choice.finish_reason
125
+ }
126
+ }
127
+
128
+ if (chunk.usage) {
129
+ prompt_tokens = chunk.usage.prompt_tokens
130
+ llamacpp_prompt_tokens.add(prompt_tokens)
131
+ llamacpp_prompt_tokens_total_counter.add(prompt_tokens)
132
+
133
+ completions_tokens = chunk.usage.completion_tokens
134
+ llamacpp_completion_tokens.add(completions_tokens)
135
+ llamacpp_completion_tokens_total_counter.add(completions_tokens)
136
+ }
137
+ })
138
+
139
+ client.on('error', function (e) {
140
+ console.log('An unexpected error occurred: ', e.error());
141
+ throw e;
142
+ })
143
+ })
144
+
145
+ check(res, {'success completion': (r) => r.status === 200})
146
+
147
+ const endTime = new Date()
148
+
149
+ const promptEvalTime = promptEvalEndTime - startTime
150
+ if (promptEvalTime > 0) {
151
+ llamacpp_prompt_processing_second.add(prompt_tokens / (promptEvalEndTime - startTime) * 1.e3)
152
+ }
153
+
154
+ const completion_time = endTime - promptEvalEndTime
155
+ if (completions_tokens > 0 && completion_time > 0) {
156
+ llamacpp_tokens_second.add(completions_tokens / completion_time * 1.e3)
157
+ }
158
+ llamacpp_completions_truncated_rate.add(finish_reason === 'length')
159
+ llamacpp_completions_stop_rate.add(finish_reason === 'stop')
160
+
161
+ sleep(0.3)
162
+ }
tools/server/bench/speed-bench/README.md ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPEED-Bench server benchmark
2
+
3
+ A lightweight [SPEED-Bench](https://huggingface.co/datasets/nvidia/SPEED-Bench) client for benchmarking an already-running `llama-server` through its OpenAI-compatible API. It is primarily meant to evaluate speculative decoding (draft model, n-gram, MTP, EAGLE3, ...) by reporting per-category throughput, latency, and draft acceptance.
4
+
5
+ The dataset handling follows the [aiperf SPEED-Bench tutorial](https://github.com/ai-dynamo/aiperf/blob/main/docs/tutorials/speed-bench.md), which also documents the dataset layout in more detail.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pip install -r tools/server/bench/speed-bench/requirements.txt
11
+ ```
12
+
13
+ ## Start a server
14
+
15
+ The client does not launch the server, so start `llama-server` yourself first. If you care about throughput numbers, set the client `--concurrency` to the server's slot count (`--np`):
16
+
17
+ ```bash
18
+ llama-server \
19
+ -m target.gguf \
20
+ -c 8192 \
21
+ --port 8080 \
22
+ -ngl 99 -fa on \
23
+ --np 1 \
24
+ --jinja
25
+ ```
26
+
27
+ For speculative decoding, start the server with the appropriate flags for your setup (e.g. a draft model with `-md`, or `--spec-type ngram-mod`). See the [speculative decoding doc](../../../../docs/speculative.md) for details.
28
+
29
+ ## Run
30
+
31
+ ```bash
32
+ python tools/server/bench/speed-bench/speed_bench.py \
33
+ --url localhost:8080 \
34
+ --bench qualitative \
35
+ --category coding \
36
+ --osl 1024 \
37
+ --concurrency 1
38
+ ```
39
+
40
+ ## Options
41
+
42
+ | Option | Default | Description |
43
+ | --- | --- | --- |
44
+ | `--url` | `localhost:8080` | Server URL. The scheme and `/v1` are optional and a trailing slash is fine, so `localhost:8080` and `http://localhost:8080/v1/` both work. |
45
+ | `--model` | none | Optional `model` field sent in each request. |
46
+ | `--bench` | `qualitative` | SPEED-Bench config, e.g. `qualitative`, `throughput_1k`. See [available dataset variants](https://github.com/ai-dynamo/aiperf/blob/main/docs/tutorials/speed-bench.md#available-dataset-variants). |
47
+ | `--category` | `all` | Category filter within the bench; comma-separated list or `all`. For `qualitative` the categories are `coding`, `humanities`, `math`, `multilingual`, `qa`, `rag`, `reasoning`, `roleplay`, `stem`, `summarization`, `writing`. For the `throughput_{ISL}` splits they are `high_entropy`, `low_entropy`, `mixed`. |
48
+ | `--osl` | `1024` | Output sequence length, mapped to `max_tokens`. |
49
+ | `--extra-inputs` | `{"temperature":0}` | Extra request fields as a JSON object. |
50
+ | `--concurrency` | `1` | Concurrent client requests; usually match `--np`. |
51
+ | `--limit` | none | Max samples per category (handy for smoke tests). |
52
+ | `--timeout` | `600` | Per-request timeout in seconds. |
53
+ | `--output` | none | Save raw per-request results and the summary to JSON. |
54
+
55
+ A few common ones:
56
+
57
+ - `--category all` runs every category in the bench.
58
+ - `--category coding,math` runs just those two.
59
+ - `--bench throughput_8k` runs a fixed-input-length throughput split.
60
+ - `--limit 8` keeps at most 8 samples per category, which is enough for a quick check.
61
+
62
+ The `throughput_{ISL}` splits use fixed input lengths (1k - 32k), so they are handy for long-context testing and for comparing different `llama-server` batching settings (e.g. sweeping `-ub` / `--ubatch-size`) on prompts of a known size. Make sure the server `-c` is large enough for the chosen split. When raising `-ub`, also raise `-b` to at least the same value, since the physical ubatch cannot exceed the logical batch.
63
+
64
+ When `--output` is given, the JSON file holds the run `config`, the `selected_samples` / `completed_samples` / `failed_samples` counts, the per-category `summary` rows, and the per-sample `results`.
65
+
66
+ ## Metrics
67
+
68
+ The summary prints one row per category plus an `overall` row:
69
+
70
+ - `samples` - how many samples finished successfully.
71
+ - `avg_prompt_t/s` - prefill throughput from llama.cpp (`timings.prompt_per_second`), averaged over the category's samples.
72
+ - `avg_pred_t/s` - decode throughput from llama.cpp (`timings.predicted_per_second`), averaged over the category's samples.
73
+ - `avg_latency` - average end-to-end request latency seen by the client.
74
+ - `accept_rate` - `accepted / draft_n` over the category, or `n/a` if nothing was drafted (`draft_n == 0`).
75
+
76
+ ## Baseline vs speculative decoding
77
+
78
+ Save a run from each server with `--output`, then diff the two JSON files with `speed_bench_compare.py`.
79
+
80
+ First, start a plain `llama-server` (no speculative decoding) and save a baseline:
81
+
82
+ ```bash
83
+ python tools/server/bench/speed-bench/speed_bench.py \
84
+ --url localhost:8080 \
85
+ --bench qualitative \
86
+ --category all \
87
+ --osl 1024 \
88
+ --concurrency 1 \
89
+ --output baseline.json
90
+ ```
91
+
92
+ Then restart `llama-server` with speculative decoding enabled and save another run:
93
+
94
+ ```bash
95
+ python tools/server/bench/speed-bench/speed_bench.py \
96
+ --url localhost:8080 \
97
+ --bench qualitative \
98
+ --category all \
99
+ --osl 1024 \
100
+ --concurrency 1 \
101
+ --output spec.json
102
+ ```
103
+
104
+ Finally compare the two:
105
+
106
+ ```bash
107
+ python tools/server/bench/speed-bench/speed_bench_compare.py \
108
+ --baseline baseline.json \
109
+ --speculative spec.json
110
+ ```
111
+
112
+ The comparison table adds:
113
+
114
+ - `decode_speedup = spec_avg_pred_t/s / base_avg_pred_t/s`
115
+ - `latency_speedup = base_avg_latency / spec_avg_latency`
116
+
117
+ Keep `--bench`, `--category`, `--osl`, and `--limit` the same across both runs, otherwise they won't be using the same prompts.
tools/server/bench/speed-bench/requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ datasets
2
+ requests
3
+ tqdm
tools/server/bench/speed-bench/speed_bench.py ADDED
@@ -0,0 +1,432 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import concurrent.futures
6
+ import json
7
+ import statistics
8
+ import sys
9
+ import time
10
+ from dataclasses import asdict, dataclass
11
+ from typing import Any
12
+ from urllib.parse import urlparse
13
+
14
+ import requests
15
+ from datasets import get_dataset_config_names, load_dataset
16
+ from tqdm import tqdm
17
+
18
+
19
+ DATASET_REPO = "nvidia/SPEED-Bench"
20
+
21
+ @dataclass
22
+ class Sample:
23
+ id: str
24
+ category: str
25
+ turns: list[str]
26
+
27
+
28
+ @dataclass
29
+ class RequestResult:
30
+ id: str
31
+ category: str
32
+ ok: bool
33
+ turns: int
34
+ latency_s: float
35
+ prompt_tokens: int
36
+ completion_tokens: int
37
+ total_tokens: int
38
+ finish_reason: str | None
39
+ draft_n: int
40
+ draft_n_accepted: int
41
+ prompt_ms: float | None
42
+ predicted_ms: float | None
43
+ prompt_per_second: float | None
44
+ predicted_per_second: float | None
45
+ error: str | None
46
+
47
+
48
+ def normalize_base_url(url: str) -> str:
49
+ url = url.strip().rstrip("/")
50
+ if not url:
51
+ raise ValueError("--url cannot be empty")
52
+ if "://" not in url:
53
+ url = "http://" + url
54
+ parsed = urlparse(url)
55
+ if not parsed.scheme or not parsed.netloc:
56
+ raise ValueError(f"invalid --url: {url}")
57
+ if not parsed.path.rstrip("/").endswith("/v1"):
58
+ url = url + "/v1"
59
+ return url.rstrip("/")
60
+
61
+
62
+ def parse_extra_inputs(value: str) -> dict[str, Any]:
63
+ extra = json.loads(value)
64
+ if not isinstance(extra, dict):
65
+ raise ValueError("--extra-inputs must be a JSON object")
66
+ return extra
67
+
68
+
69
+ def extract_turns(row: dict[str, Any]) -> list[str]:
70
+ turns = row.get("turns")
71
+ if isinstance(turns, list) and turns:
72
+ clean_turns = [str(turn).strip() for turn in turns if turn and str(turn).strip()]
73
+ if clean_turns:
74
+ return clean_turns
75
+ raise ValueError("missing or empty turns")
76
+
77
+
78
+ def load_samples(args: argparse.Namespace) -> list[Sample]:
79
+ bench_names = get_dataset_config_names(DATASET_REPO)
80
+ if args.bench not in bench_names:
81
+ raise ValueError(
82
+ f"unknown --bench {args.bench!r}; available benches: {', '.join(bench_names)}"
83
+ )
84
+
85
+ dataset = load_dataset(DATASET_REPO, name=args.bench, split="test")
86
+ categories = list(dict.fromkeys(str(category) for category in dataset["category"]))
87
+ requested_categories = None
88
+ if args.category != "all":
89
+ requested_list = [category.strip() for category in args.category.split(",") if category.strip()]
90
+ if not requested_list:
91
+ raise ValueError(
92
+ f"--category must be 'all' or a comma-separated list; available categories: {', '.join(categories)}"
93
+ )
94
+ requested_categories = set(requested_list)
95
+ unknown_categories = [category for category in requested_list if category not in categories]
96
+ if unknown_categories:
97
+ unknown = ", ".join(unknown_categories)
98
+ raise ValueError(
99
+ f"unknown --category {unknown!r} for bench {args.bench!r}; "
100
+ f"available categories: all, {', '.join(categories)}"
101
+ )
102
+
103
+ samples: list[Sample] = []
104
+ samples_per_category: dict[str, int] = {}
105
+ skipped = 0
106
+ for index, row_raw in enumerate(dataset):
107
+ row = dict(row_raw)
108
+ category_raw = row.get("category")
109
+ if not isinstance(category_raw, str) or not category_raw.strip():
110
+ skipped += 1
111
+ continue
112
+ category = category_raw.strip()
113
+ if requested_categories is not None and category not in requested_categories:
114
+ continue
115
+ if args.limit is not None and samples_per_category.get(category, 0) >= args.limit:
116
+ continue
117
+
118
+ try:
119
+ turns = extract_turns(row)
120
+ except ValueError:
121
+ skipped += 1
122
+ continue
123
+ question_id = row.get("question_id")
124
+ if not isinstance(question_id, str) or not question_id.strip():
125
+ skipped += 1
126
+ continue
127
+ sample_id = question_id.strip()
128
+ samples.append(Sample(id=sample_id, category=category, turns=turns))
129
+ samples_per_category[category] = samples_per_category.get(category, 0) + 1
130
+
131
+ if not samples:
132
+ raise RuntimeError(f"no samples selected from bench={args.bench} category={args.category}")
133
+
134
+ if skipped:
135
+ print(f"speed_bench: skipped {skipped} rows without usable turns")
136
+ return samples
137
+
138
+
139
+ def parse_completion_response(data: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any], str | None, str]:
140
+ usage = data.get("usage") or {}
141
+ timings = data.get("timings") or {}
142
+ finish_reason = None
143
+ content = ""
144
+ choices = data.get("choices")
145
+ if isinstance(choices, list) and choices and isinstance(choices[0], dict):
146
+ choice = choices[0]
147
+ finish_reason = choice.get("finish_reason")
148
+ message = choice.get("message")
149
+ if isinstance(message, dict) and isinstance(message.get("content"), str):
150
+ content = message["content"]
151
+ elif isinstance(choice.get("text"), str):
152
+ content = choice["text"]
153
+ return usage, timings, finish_reason, content
154
+
155
+
156
+ def run_request(
157
+ endpoint: str,
158
+ model: str | None,
159
+ messages: list[dict[str, str]],
160
+ osl: int,
161
+ extra_inputs: dict[str, Any],
162
+ timeout: float,
163
+ ) -> tuple[dict[str, Any], float]:
164
+ payload: dict[str, Any] = {
165
+ "messages": messages,
166
+ "max_tokens": osl,
167
+ "stream": False,
168
+ }
169
+ if model:
170
+ payload["model"] = model
171
+ payload.update(extra_inputs)
172
+ payload["max_tokens"] = osl
173
+
174
+ start = time.perf_counter()
175
+ response = requests.post(endpoint, json=payload, timeout=timeout)
176
+ latency_s = time.perf_counter() - start
177
+ if response.status_code != 200:
178
+ body = response.text[:500].replace("\n", "\\n")
179
+ raise RuntimeError(f"HTTP {response.status_code}: {body}")
180
+ return response.json(), latency_s
181
+
182
+
183
+ def run_one(
184
+ sample: Sample,
185
+ endpoint: str,
186
+ model: str | None,
187
+ osl: int,
188
+ extra_inputs: dict[str, Any],
189
+ timeout: float,
190
+ ) -> RequestResult:
191
+ selected_turns = sample.turns
192
+ messages: list[dict[str, str]] = []
193
+ total_latency_s = 0.0
194
+ prompt_tokens = 0
195
+ completion_tokens = 0
196
+ total_tokens = 0
197
+ draft_n = 0
198
+ draft_n_accepted = 0
199
+ prompt_ms = 0.0
200
+ predicted_ms = 0.0
201
+ prompt_per_second = None
202
+ predicted_per_second = None
203
+ finish_reason: str | None = None
204
+ try:
205
+ for turn in selected_turns:
206
+ messages.append({"role": "user", "content": turn})
207
+ data, latency_s = run_request(endpoint, model, messages, osl, extra_inputs, timeout)
208
+ total_latency_s += latency_s
209
+ usage, timings, finish_reason, assistant_text = parse_completion_response(data)
210
+
211
+ turn_prompt_tokens = int(usage.get("prompt_tokens") or timings.get("prompt_n") or 0)
212
+ turn_completion_tokens_count = int(usage.get("completion_tokens") or timings.get("predicted_n") or 0)
213
+ turn_total_tokens_count = int(usage.get("total_tokens") or (turn_prompt_tokens + turn_completion_tokens_count))
214
+ prompt_tokens += turn_prompt_tokens
215
+ completion_tokens += turn_completion_tokens_count
216
+ total_tokens += turn_total_tokens_count
217
+ draft_n += int(timings.get("draft_n") or 0)
218
+ draft_n_accepted += int(timings.get("draft_n_accepted") or 0)
219
+ prompt_ms += float(timings.get("prompt_ms") or 0)
220
+ predicted_ms += float(timings.get("predicted_ms") or 0)
221
+ if len(selected_turns) == 1 and isinstance(timings.get("prompt_per_second"), (int, float)):
222
+ prompt_per_second = float(timings["prompt_per_second"])
223
+ if len(selected_turns) == 1 and isinstance(timings.get("predicted_per_second"), (int, float)):
224
+ predicted_per_second = float(timings["predicted_per_second"])
225
+
226
+ messages.append({"role": "assistant", "content": assistant_text})
227
+
228
+ if total_tokens == 0:
229
+ total_tokens = prompt_tokens + completion_tokens
230
+ if len(selected_turns) > 1:
231
+ prompt_per_second = (prompt_tokens / (prompt_ms / 1000)) if prompt_ms > 0 else None
232
+ predicted_per_second = (completion_tokens / (predicted_ms / 1000)) if predicted_ms > 0 else None
233
+
234
+ return RequestResult(
235
+ id=sample.id,
236
+ category=sample.category,
237
+ ok=True,
238
+ turns=len(selected_turns),
239
+ latency_s=total_latency_s,
240
+ prompt_tokens=prompt_tokens,
241
+ completion_tokens=completion_tokens,
242
+ total_tokens=total_tokens,
243
+ finish_reason=finish_reason,
244
+ draft_n=draft_n,
245
+ draft_n_accepted=draft_n_accepted,
246
+ prompt_ms=prompt_ms if prompt_ms > 0 else None,
247
+ predicted_ms=predicted_ms if predicted_ms > 0 else None,
248
+ prompt_per_second=prompt_per_second,
249
+ predicted_per_second=predicted_per_second,
250
+ error=None,
251
+ )
252
+ except Exception as exc:
253
+ return RequestResult(
254
+ id=sample.id,
255
+ category=sample.category,
256
+ ok=False,
257
+ turns=len(selected_turns),
258
+ latency_s=total_latency_s,
259
+ prompt_tokens=0,
260
+ completion_tokens=0,
261
+ total_tokens=0,
262
+ finish_reason=None,
263
+ draft_n=0,
264
+ draft_n_accepted=0,
265
+ prompt_ms=None,
266
+ predicted_ms=None,
267
+ prompt_per_second=None,
268
+ predicted_per_second=None,
269
+ error=str(exc),
270
+ )
271
+
272
+
273
+ def summarize_group(category: str, results: list[RequestResult]) -> dict[str, Any]:
274
+ ok_results = [result for result in results if result.ok]
275
+ latencies = [result.latency_s for result in ok_results]
276
+ server_prompt_speeds = [
277
+ result.prompt_per_second
278
+ for result in ok_results
279
+ if result.prompt_per_second is not None
280
+ ]
281
+ server_completion_speeds = [
282
+ result.predicted_per_second
283
+ for result in ok_results
284
+ if result.predicted_per_second is not None
285
+ ]
286
+ turns = sum(result.turns for result in ok_results)
287
+ draft_n = sum(result.draft_n for result in ok_results)
288
+ accepted = sum(result.draft_n_accepted for result in ok_results)
289
+
290
+ return {
291
+ "category": category,
292
+ "requests": len(ok_results),
293
+ "turns": turns,
294
+ "failed": len(results) - len(ok_results),
295
+ "avg_prompt_t_s": statistics.mean(server_prompt_speeds) if server_prompt_speeds else None,
296
+ "avg_pred_t_s": statistics.mean(server_completion_speeds) if server_completion_speeds else None,
297
+ "avg_latency": statistics.mean(latencies) if latencies else None,
298
+ "draft_n": draft_n,
299
+ "accepted": accepted,
300
+ "accept_rate": (accepted / draft_n) if draft_n > 0 else None,
301
+ }
302
+
303
+
304
+ def fmt_value(value: Any, kind: str = "") -> str:
305
+ if value is None:
306
+ return "n/a"
307
+ if kind == "int":
308
+ return str(int(value))
309
+ if kind == "rate":
310
+ return f"{float(value):.4f}"
311
+ if kind == "seconds":
312
+ return f"{float(value):.3f}s"
313
+ if kind == "speed":
314
+ return f"{float(value):.2f}"
315
+ if kind == "speedup":
316
+ return f"{float(value):.2f}x"
317
+ return str(value)
318
+
319
+
320
+ def print_table(rows: list[dict[str, Any]]) -> None:
321
+ columns = [
322
+ ("category", "category", ""),
323
+ ("samples", "requests", "int"),
324
+ ("avg_prompt_t/s", "avg_prompt_t_s", "speed"),
325
+ ("avg_pred_t/s", "avg_pred_t_s", "speed"),
326
+ ("avg_latency", "avg_latency", "seconds"),
327
+ ("accept_rate", "accept_rate", "rate"),
328
+ ]
329
+ print_rows(rows, columns)
330
+
331
+
332
+ def print_rows(rows: list[dict[str, Any]], columns: list[tuple[str, str, str]]) -> None:
333
+ rendered_rows = []
334
+ for row in rows:
335
+ rendered_rows.append([fmt_value(row.get(key), kind) for _, key, kind in columns])
336
+
337
+ widths = [len(header) for header, _, _ in columns]
338
+ for rendered in rendered_rows:
339
+ for i, cell in enumerate(rendered):
340
+ widths[i] = max(widths[i], len(cell))
341
+
342
+ header = " ".join(header.ljust(widths[i]) for i, (header, _, _) in enumerate(columns))
343
+ print(header)
344
+ print(" ".join("-" * width for width in widths))
345
+ for rendered in rendered_rows:
346
+ print(" ".join(cell.ljust(widths[i]) for i, cell in enumerate(rendered)))
347
+
348
+
349
+ def save_output(path: str, args: argparse.Namespace, samples: list[Sample], results: list[RequestResult], summary: list[dict[str, Any]]) -> None:
350
+ payload = {
351
+ "config": {
352
+ "url": args.url,
353
+ "model": args.model,
354
+ "bench": args.bench,
355
+ "category": args.category,
356
+ "osl": args.osl,
357
+ "concurrency": args.concurrency,
358
+ "extra_inputs": args.extra_inputs,
359
+ },
360
+ "selected_samples": len(samples),
361
+ "completed_samples": sum(1 for result in results if result.ok),
362
+ "failed_samples": sum(1 for result in results if not result.ok),
363
+ "summary": summary,
364
+ "results": [asdict(result) for result in results],
365
+ }
366
+ with open(path, "w", encoding="utf-8") as f:
367
+ json.dump(payload, f, indent=2, sort_keys=True)
368
+
369
+
370
+ def main(argv: list[str] | None = None) -> int:
371
+ parser = argparse.ArgumentParser(description="Run SPEED-Bench against an OpenAI-compatible llama-server.")
372
+ parser.add_argument("--url", default="localhost:8080", help="Server URL, for example localhost:8080 or http://localhost:8080/v1")
373
+ parser.add_argument("--model", default=None, help="Optional model name to send in OpenAI requests")
374
+ parser.add_argument("--bench", default="qualitative", help="SPEED-Bench config to run, for example qualitative or throughput_1k")
375
+ parser.add_argument("--category", default="all", help="Category to run within the selected bench; use all for no category filter")
376
+ parser.add_argument("--osl", type=int, default=4096, help="Output sequence length, mapped to max_tokens")
377
+ parser.add_argument("--extra-inputs", default='{"temperature":0}', help="Extra request fields as a JSON object")
378
+ parser.add_argument("--concurrency", type=int, default=1, help="Concurrent client requests; usually match llama-server --np")
379
+ parser.add_argument("--limit", type=int, default=None, help="Optional sample limit per category for smoke tests")
380
+ parser.add_argument("--timeout", type=float, default=600, help="Per-request timeout in seconds")
381
+ parser.add_argument("--output", default=None, help="Optional path to save raw results JSON")
382
+ args = parser.parse_args(argv)
383
+ try:
384
+ base_url = normalize_base_url(args.url)
385
+ endpoint = base_url + "/chat/completions"
386
+ extra_inputs = parse_extra_inputs(args.extra_inputs)
387
+ args.extra_inputs = extra_inputs
388
+ samples = load_samples(args)
389
+ except Exception as exc:
390
+ print(f"speed_bench: setup failed: {exc}", file=sys.stderr)
391
+ return 2
392
+
393
+ print(f"speed_bench: loaded {len(samples)} samples from bench={args.bench} category={args.category}")
394
+
395
+ results: list[RequestResult] = []
396
+ started = time.perf_counter()
397
+ with concurrent.futures.ThreadPoolExecutor(max_workers=args.concurrency) as executor:
398
+ futures = [
399
+ executor.submit(run_one, sample, endpoint, args.model, args.osl, extra_inputs, args.timeout)
400
+ for sample in samples
401
+ ]
402
+ for future in tqdm(concurrent.futures.as_completed(futures), total=len(futures), desc="speed_bench", unit="sample"):
403
+ result = future.result()
404
+ results.append(result)
405
+
406
+ elapsed = time.perf_counter() - started
407
+ categories = list(dict.fromkeys(sample.category for sample in samples))
408
+ summary = [
409
+ summarize_group(category, [result for result in results if result.category == category])
410
+ for category in categories
411
+ ]
412
+ summary.append(summarize_group("overall", results))
413
+ print()
414
+ print(f"Summary (elapsed={elapsed:.2f}s)")
415
+ print_table(summary)
416
+
417
+ if args.output:
418
+ save_output(args.output, args, samples, results, summary)
419
+ print(f"\nspeed_bench: wrote {args.output}")
420
+
421
+ failed = sum(1 for result in results if not result.ok)
422
+ if failed:
423
+ print(f"\nspeed_bench: {failed} samples failed", file=sys.stderr)
424
+ first_error = next((result.error for result in results if result.error), None)
425
+ if first_error:
426
+ print(f"first error: {first_error}", file=sys.stderr)
427
+ return 1
428
+ return 0
429
+
430
+
431
+ if __name__ == "__main__":
432
+ raise SystemExit(main())
tools/server/bench/speed-bench/speed_bench_compare.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import sys
7
+ from typing import Any
8
+
9
+ from speed_bench import fmt_value, print_rows
10
+
11
+
12
+ def load_summary(path: str) -> list[dict[str, Any]]:
13
+ with open(path, "r", encoding="utf-8") as f:
14
+ data = json.load(f)
15
+ summary = data.get("summary")
16
+ if not isinstance(summary, list):
17
+ raise ValueError(f"{path} does not contain a summary list")
18
+ return summary
19
+
20
+
21
+ def compare_rows(baseline: list[dict[str, Any]], speculative: list[dict[str, Any]]) -> list[dict[str, Any]]:
22
+ baseline_by_category = {row["category"]: row for row in baseline}
23
+ comparisons = []
24
+ for row in speculative:
25
+ base = baseline_by_category.get(row["category"])
26
+ if not base:
27
+ continue
28
+ base_speed = base.get("avg_pred_t_s")
29
+ spec_speed = row.get("avg_pred_t_s")
30
+ base_latency = base.get("avg_latency")
31
+ spec_latency = row.get("avg_latency")
32
+ comparisons.append(
33
+ {
34
+ "category": row["category"],
35
+ "base_avg_pred_t_s": base_speed,
36
+ "spec_avg_pred_t_s": spec_speed,
37
+ "decode_speedup": (spec_speed / base_speed) if base_speed and spec_speed else None,
38
+ "base_avg_latency": base_latency,
39
+ "spec_avg_latency": spec_latency,
40
+ "latency_speedup": (base_latency / spec_latency) if base_latency and spec_latency else None,
41
+ "accept_rate": row.get("accept_rate"),
42
+ }
43
+ )
44
+ return comparisons
45
+
46
+
47
+ def print_comparison(rows: list[dict[str, Any]]) -> None:
48
+ if not rows:
49
+ print("No overlapping categories found for comparison.")
50
+ return
51
+ columns = [
52
+ ("category", "category", ""),
53
+ ("base_avg_pred_t/s", "base_avg_pred_t_s", "speed"),
54
+ ("spec_avg_pred_t/s", "spec_avg_pred_t_s", "speed"),
55
+ ("decode_speedup", "decode_speedup", "speedup"),
56
+ ("base_avg_latency", "base_avg_latency", "seconds"),
57
+ ("spec_avg_latency", "spec_avg_latency", "seconds"),
58
+ ("latency_speedup", "latency_speedup", "speedup"),
59
+ ("accept_rate", "accept_rate", "rate"),
60
+ ]
61
+ print_rows(rows, columns)
62
+
63
+
64
+ def main(argv: list[str] | None = None) -> int:
65
+ parser = argparse.ArgumentParser(description="Compare two SPEED-Bench runs (baseline vs speculative).")
66
+ parser.add_argument("--baseline", required=True, help="Baseline results JSON produced by speed_bench.py --output")
67
+ parser.add_argument("--speculative", required=True, help="Speculative decoding results JSON produced by speed_bench.py --output")
68
+ args = parser.parse_args(argv)
69
+
70
+ try:
71
+ baseline = load_summary(args.baseline)
72
+ speculative = load_summary(args.speculative)
73
+ except Exception as exc:
74
+ print(f"speed_bench_compare: failed to load inputs: {exc}", file=sys.stderr)
75
+ return 2
76
+
77
+ comparisons = compare_rows(baseline, speculative)
78
+ print(f"Comparison: baseline={args.baseline} speculative={args.speculative}")
79
+ print_comparison(comparisons)
80
+ return 0
81
+
82
+
83
+ if __name__ == "__main__":
84
+ raise SystemExit(main())
tools/server/main.cpp ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ int llama_server(int argc, char ** argv);
2
+
3
+ int main(int argc, char ** argv) {
4
+ return llama_server(argc, argv);
5
+ }
tools/server/server-chat.cpp ADDED
@@ -0,0 +1,692 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "server-chat.h"
2
+ #include "server-common.h"
3
+
4
+ #include <sstream>
5
+
6
+ json server_chat_convert_responses_to_chatcmpl(const json & response_body) {
7
+ if (!response_body.contains("input")) {
8
+ throw std::invalid_argument("'input' is required");
9
+ }
10
+ if (!json_value(response_body, "previous_response_id", std::string{}).empty()) {
11
+ throw std::invalid_argument("llama.cpp does not support 'previous_response_id'.");
12
+ }
13
+
14
+ const json input_value = response_body.at("input");
15
+ json chatcmpl_body = response_body;
16
+ chatcmpl_body.erase("input");
17
+ std::vector<json> chatcmpl_messages;
18
+
19
+ if (response_body.contains("instructions")) {
20
+ chatcmpl_messages.push_back({
21
+ {"role", "system"},
22
+ {"content", json_value(response_body, "instructions", std::string())},
23
+ });
24
+ chatcmpl_body.erase("instructions");
25
+ }
26
+
27
+ if (input_value.is_string()) {
28
+ // #responses_create-input-text_input
29
+ chatcmpl_messages.push_back({
30
+ {"role", "user"},
31
+ {"content", input_value},
32
+ });
33
+ } else if (input_value.is_array()) {
34
+ // #responses_create-input-input_item_list
35
+
36
+ static auto exists_and_is_array = [](const json & j, const char * key) -> bool {
37
+ return j.contains(key) && j.at(key).is_array();
38
+ };
39
+ static auto exists_and_is_string = [](const json & j, const char * key) -> bool {
40
+ return j.contains(key) && j.at(key).is_string();
41
+ };
42
+
43
+ for (json item : input_value) {
44
+ bool merge_prev = !chatcmpl_messages.empty() && chatcmpl_messages.back().value("role", "") == "assistant";
45
+
46
+ if (exists_and_is_string(item, "content")) {
47
+ // #responses_create-input-input_item_list-input_message-content-text_input
48
+ // Only "Input message" contains item["content"]::string
49
+ // After converting item["content"]::string to item["content"]::array,
50
+ // we can treat "Input message" as sum of "Item-Input message" and "Item-Output message"
51
+ item["content"] = json::array({
52
+ json {
53
+ {"text", item.at("content")},
54
+ {"type", "input_text"}
55
+ }
56
+ });
57
+ }
58
+
59
+ if (exists_and_is_array(item, "content") &&
60
+ exists_and_is_string(item, "role") &&
61
+ (item.at("role") == "user" ||
62
+ item.at("role") == "system" ||
63
+ item.at("role") == "developer")
64
+ ) {
65
+ // #responses_create-input-input_item_list-item-input_message
66
+ std::vector<json> chatcmpl_content;
67
+
68
+ for (const json & input_item : item.at("content")) {
69
+ const std::string type = json_value(input_item, "type", std::string());
70
+
71
+ if (type == "input_text") {
72
+ if (!input_item.contains("text")) {
73
+ throw std::invalid_argument("'Input text' requires 'text'");
74
+ }
75
+ chatcmpl_content.push_back({
76
+ {"text", input_item.at("text")},
77
+ {"type", "text"},
78
+ });
79
+ } else if (type == "input_image") {
80
+ // While `detail` is marked as required,
81
+ // it has default value("auto") and can be omitted.
82
+
83
+ if (!input_item.contains("image_url")) {
84
+ throw std::invalid_argument("'image_url' is required");
85
+ }
86
+ chatcmpl_content.push_back({
87
+ {"image_url", json {
88
+ {"url", input_item.at("image_url")}
89
+ }},
90
+ {"type", "image_url"},
91
+ });
92
+ } else if (type == "input_file") {
93
+ throw std::invalid_argument("'input_file' is not supported by llamacpp at this moment");
94
+ } else {
95
+ throw std::invalid_argument("'type' must be one of 'input_text', 'input_image', or 'input_file'");
96
+ }
97
+ }
98
+
99
+ if (item.contains("type")) {
100
+ item.erase("type");
101
+ }
102
+ if (item.contains("status")) {
103
+ item.erase("status");
104
+ }
105
+ item["content"] = chatcmpl_content;
106
+
107
+ chatcmpl_messages.push_back(item);
108
+ } else if (exists_and_is_string(item, "role") &&
109
+ item.at("role") == "assistant" &&
110
+ exists_and_is_string(item, "type") &&
111
+ item.at("type") == "message"
112
+ ) {
113
+ // #responses_create-input-input_item_list-item-output_message
114
+ auto chatcmpl_content = json::array();
115
+
116
+ // Handle both string content and array content
117
+ if (item.contains("content") && item.at("content").is_string()) {
118
+ // String content - convert to text content part
119
+ chatcmpl_content.push_back({
120
+ {"text", item.at("content")},
121
+ {"type", "text"},
122
+ });
123
+ } else if (exists_and_is_array(item, "content")) {
124
+ // Array content - process each item
125
+ for (const auto & output_text : item.at("content")) {
126
+ const std::string type = json_value(output_text, "type", std::string());
127
+ if (type == "output_text" || type == "input_text") {
128
+ // Accept both output_text and input_text (string content gets converted to input_text)
129
+ if (!exists_and_is_string(output_text, "text")) {
130
+ throw std::invalid_argument("'Output text' requires 'text'");
131
+ }
132
+ chatcmpl_content.push_back({
133
+ {"text", output_text.at("text")},
134
+ {"type", "text"},
135
+ });
136
+ } else if (type == "refusal") {
137
+ if (!exists_and_is_string(output_text, "refusal")) {
138
+ throw std::invalid_argument("'Refusal' requires 'refusal'");
139
+ }
140
+ chatcmpl_content.push_back({
141
+ {"refusal", output_text.at("refusal")},
142
+ {"type", "refusal"},
143
+ });
144
+ } else {
145
+ throw std::invalid_argument("'type' must be one of 'output_text' or 'refusal'");
146
+ }
147
+ }
148
+ }
149
+
150
+ if (merge_prev) {
151
+ auto & prev_msg = chatcmpl_messages.back();
152
+ if (!exists_and_is_array(prev_msg, "content")) {
153
+ prev_msg["content"] = json::array();
154
+ }
155
+ auto & prev_content = prev_msg["content"];
156
+ prev_content.insert(prev_content.end(), chatcmpl_content.begin(), chatcmpl_content.end());
157
+ } else {
158
+ item.erase("status");
159
+ item.erase("type");
160
+ item["content"] = chatcmpl_content;
161
+ chatcmpl_messages.push_back(item);
162
+ }
163
+ } else if (exists_and_is_string(item, "arguments") &&
164
+ exists_and_is_string(item, "call_id") &&
165
+ exists_and_is_string(item, "name") &&
166
+ exists_and_is_string(item, "type") &&
167
+ item.at("type") == "function_call"
168
+ ) {
169
+ // #responses_create-input-input_item_list-item-function_tool_call
170
+ json tool_call = {
171
+ {"function", json {
172
+ {"arguments", item.at("arguments")},
173
+ {"name", item.at("name")},
174
+ }},
175
+ {"id", item.at("call_id")},
176
+ {"type", "function"},
177
+ };
178
+
179
+ if (merge_prev) {
180
+ auto & prev_msg = chatcmpl_messages.back();
181
+ if (!exists_and_is_array(prev_msg, "tool_calls")) {
182
+ prev_msg["tool_calls"] = json::array();
183
+ }
184
+ prev_msg["tool_calls"].push_back(tool_call);
185
+ } else {
186
+ chatcmpl_messages.push_back(json {
187
+ {"role", "assistant"},
188
+ {"tool_calls", json::array({tool_call})}
189
+ });
190
+ }
191
+ } else if (exists_and_is_string(item, "call_id") &&
192
+ (exists_and_is_string(item, "output") || exists_and_is_array(item, "output")) &&
193
+ exists_and_is_string(item, "type") &&
194
+ item.at("type") == "function_call_output"
195
+ ) {
196
+ // #responses_create-input-input_item_list-item-function_tool_call_output
197
+ if (item.at("output").is_string()) {
198
+ chatcmpl_messages.push_back(json {
199
+ {"content", item.at("output")},
200
+ {"role", "tool"},
201
+ {"tool_call_id", item.at("call_id")},
202
+ });
203
+ } else {
204
+ json chatcmpl_outputs = item.at("output");
205
+ for (json & chatcmpl_output : chatcmpl_outputs) {
206
+ if (!chatcmpl_output.contains("type") || chatcmpl_output.at("type") != "input_text") {
207
+ throw std::invalid_argument("Output of tool call should be 'Input text'");
208
+ }
209
+ chatcmpl_output["type"] = "text";
210
+ }
211
+ chatcmpl_messages.push_back(json {
212
+ {"content", chatcmpl_outputs},
213
+ {"role", "tool"},
214
+ {"tool_call_id", item.at("call_id")},
215
+ });
216
+ }
217
+ } else if (exists_and_is_array(item, "summary") &&
218
+ exists_and_is_string(item, "type") &&
219
+ item.at("type") == "reasoning") {
220
+ // #responses_create-input-input_item_list-item-reasoning
221
+
222
+ if (!exists_and_is_array(item, "content")) {
223
+ throw std::invalid_argument("item['content'] is not an array");
224
+ }
225
+ if (item.at("content").empty()) {
226
+ throw std::invalid_argument("item['content'] is empty");
227
+ }
228
+ if (!exists_and_is_string(item.at("content")[0], "text")) {
229
+ throw std::invalid_argument("item['content']['text'] is not a string");
230
+ }
231
+
232
+ if (merge_prev) {
233
+ auto & prev_msg = chatcmpl_messages.back();
234
+ prev_msg["reasoning_content"] = item.at("content")[0].at("text");
235
+ } else {
236
+ chatcmpl_messages.push_back(json {
237
+ {"role", "assistant"},
238
+ {"content", json::array()},
239
+ {"reasoning_content", item.at("content")[0].at("text")},
240
+ });
241
+ }
242
+ } else {
243
+ throw std::invalid_argument("Cannot determine type of 'item'");
244
+ }
245
+ }
246
+ } else {
247
+ throw std::invalid_argument("'input' must be a string or array of objects");
248
+ }
249
+
250
+ chatcmpl_body["messages"] = chatcmpl_messages;
251
+
252
+ if (response_body.contains("tools")) {
253
+ if (!response_body.at("tools").is_array()) {
254
+ throw std::invalid_argument("'tools' must be an array of objects");
255
+ }
256
+ std::vector<json> chatcmpl_tools;
257
+ for (json resp_tool : response_body.at("tools")) {
258
+ json chatcmpl_tool;
259
+
260
+ const std::string type = json_value(resp_tool, "type", std::string());
261
+ if (type != "function") {
262
+ // Non-function Responses tools have no Chat Completions equivalent.
263
+ SRV_WRN("unsupported Responses tool type '%s' skipped\n", type.c_str());
264
+ continue;
265
+ }
266
+ resp_tool.erase("type");
267
+ chatcmpl_tool["type"] = "function";
268
+
269
+ if (!resp_tool.contains("strict")) {
270
+ resp_tool["strict"] = true;
271
+ }
272
+ chatcmpl_tool["function"] = resp_tool;
273
+ chatcmpl_tools.push_back(chatcmpl_tool);
274
+ }
275
+ chatcmpl_body.erase("tools");
276
+ if (!chatcmpl_tools.empty()) {
277
+ chatcmpl_body["tools"] = chatcmpl_tools;
278
+ }
279
+ }
280
+
281
+ if (response_body.contains("max_output_tokens")) {
282
+ chatcmpl_body.erase("max_output_tokens");
283
+ chatcmpl_body["max_tokens"] = response_body["max_output_tokens"];
284
+ }
285
+
286
+ if (response_body.contains("reasoning")) {
287
+ // Only "effort" is handled so far
288
+ const json & reasoning = response_body.at("reasoning");
289
+ if (reasoning.contains("effort")) {
290
+ chatcmpl_body["reasoning_effort"] = reasoning.at("effort");
291
+ }
292
+ chatcmpl_body.erase("reasoning");
293
+ }
294
+
295
+ return chatcmpl_body;
296
+ }
297
+
298
+ // Edits the cch section of an "x-anthropic-billing-header" system prompt.
299
+ // Does nothing to any other prompt.
300
+ //
301
+ // This is a claude message with a "cch=ef01a" attribute that breaks prefix caching.
302
+ // The cch stamp is a whitebox end-to-end integrity hint. It's not meaningful as a
303
+ // system prompt data, particularly to llama.cpp, but its presence means the prefix
304
+ // cache will not get past it: It changes on each request.
305
+ //
306
+ // Reference: https://github.com/ggml-org/llama.cpp/pull/21793
307
+ // Example header:
308
+ // ```
309
+ // x-anthropic-billing-header: cc_version=2.1.101.e51; cc_entrypoint=cli; cch=a5145;You are Claude Code, Anthropic's official CLI for Claude.
310
+ // ^^^^^
311
+ // ```
312
+ static void normalize_anthropic_billing_header(std::string & system_text) {
313
+ if (system_text.rfind("x-anthropic-billing-header:", 0) != 0) {
314
+ return;
315
+ }
316
+
317
+ const size_t header_prefix_length = strlen("x-anthropic-billing-header:");
318
+ const size_t cch_length = 5;
319
+ const size_t index_cch = system_text.find("cch=", header_prefix_length);
320
+ if (index_cch == std::string::npos) {
321
+ return;
322
+ }
323
+
324
+ const size_t index_replace = index_cch + 4;
325
+ if (index_replace + cch_length < system_text.length() && system_text[index_replace + cch_length] == ';') {
326
+ for (size_t i = 0; i < cch_length; ++i) {
327
+ system_text[index_replace + i] = 'f';
328
+ }
329
+ } else {
330
+ LOG_ERR("anthropic string not as expected: %s", system_text.c_str());
331
+ }
332
+ }
333
+
334
+ json server_chat_convert_anthropic_to_oai(const json & body) {
335
+ json oai_body;
336
+
337
+ // Convert system prompt
338
+ json oai_messages = json::array();
339
+ auto system_param = json_value(body, "system", json());
340
+ if (!system_param.is_null()) {
341
+ std::string system_content;
342
+
343
+ if (system_param.is_string()) {
344
+ system_content = system_param.get<std::string>();
345
+ normalize_anthropic_billing_header(system_content);
346
+ } else if (system_param.is_array()) {
347
+ for (const auto & block : system_param) {
348
+ if (json_value(block, "type", std::string()) == "text") {
349
+ auto system_text = json_value(block, "text", std::string());
350
+ normalize_anthropic_billing_header(system_text);
351
+ system_content += system_text;
352
+ }
353
+ }
354
+ }
355
+
356
+ oai_messages.push_back({
357
+ {"role", "system"},
358
+ {"content", system_content}
359
+ });
360
+ }
361
+
362
+ // Convert messages
363
+ if (!body.contains("messages")) {
364
+ throw std::runtime_error("'messages' is required");
365
+ }
366
+ const json & messages = body.at("messages");
367
+ if (messages.is_array()) {
368
+ for (const auto & msg : messages) {
369
+ std::string role = json_value(msg, "role", std::string());
370
+
371
+ if (!msg.contains("content")) {
372
+ if (role == "assistant") {
373
+ continue;
374
+ }
375
+ oai_messages.push_back(msg);
376
+ continue;
377
+ }
378
+
379
+ const json & content = msg.at("content");
380
+
381
+ if (content.is_string()) {
382
+ oai_messages.push_back(msg);
383
+ continue;
384
+ }
385
+
386
+ if (!content.is_array()) {
387
+ oai_messages.push_back(msg);
388
+ continue;
389
+ }
390
+
391
+ json tool_calls = json::array();
392
+ json converted_content = json::array();
393
+ json tool_results = json::array();
394
+ std::string reasoning_content;
395
+ bool has_tool_calls = false;
396
+
397
+ for (const auto & block : content) {
398
+ std::string type = json_value(block, "type", std::string());
399
+
400
+ if (type == "text") {
401
+ converted_content.push_back(block);
402
+ } else if (type == "thinking") {
403
+ reasoning_content += json_value(block, "thinking", std::string());
404
+ } else if (type == "image") {
405
+ json source = json_value(block, "source", json::object());
406
+ std::string source_type = json_value(source, "type", std::string());
407
+
408
+ if (source_type == "base64") {
409
+ std::string media_type = json_value(source, "media_type", std::string("image/jpeg"));
410
+ std::string data = json_value(source, "data", std::string());
411
+ std::ostringstream ss;
412
+ ss << "data:" << media_type << ";base64," << data;
413
+
414
+ converted_content.push_back({
415
+ {"type", "image_url"},
416
+ {"image_url", {
417
+ {"url", ss.str()}
418
+ }}
419
+ });
420
+ } else if (source_type == "url") {
421
+ std::string url = json_value(source, "url", std::string());
422
+ converted_content.push_back({
423
+ {"type", "image_url"},
424
+ {"image_url", {
425
+ {"url", url}
426
+ }}
427
+ });
428
+ }
429
+ } else if (type == "tool_use") {
430
+ tool_calls.push_back({
431
+ {"id", json_value(block, "id", std::string())},
432
+ {"type", "function"},
433
+ {"function", {
434
+ {"name", json_value(block, "name", std::string())},
435
+ {"arguments", json_value(block, "input", json::object()).dump()}
436
+ }}
437
+ });
438
+ has_tool_calls = true;
439
+ } else if (type == "tool_result") {
440
+ std::string tool_use_id = json_value(block, "tool_use_id", std::string());
441
+
442
+ auto result_content = json_value(block, "content", json());
443
+ if (result_content.is_string()) {
444
+ tool_results.push_back({
445
+ {"role", "tool"},
446
+ {"tool_call_id", tool_use_id},
447
+ {"content", result_content.get<std::string>()}
448
+ });
449
+ } else if (result_content.is_array()) {
450
+ // Single-pass: build both text and content_parts, decide format at the end
451
+ std::string result_text;
452
+ json content_parts = json::array();
453
+ bool has_images = false;
454
+
455
+ for (const auto & c : result_content) {
456
+ std::string c_type = json_value(c, "type", std::string());
457
+ if (c_type == "text") {
458
+ std::string text = json_value(c, "text", std::string());
459
+ result_text += text;
460
+ content_parts.push_back({
461
+ {"type", "text"},
462
+ {"text", text}
463
+ });
464
+ } else if (c_type == "image") {
465
+ has_images = true;
466
+ json source = json_value(c, "source", json::object());
467
+ std::string source_type = json_value(source, "type", std::string());
468
+ if (source_type == "base64") {
469
+ std::string media_type = json_value(source, "media_type", std::string("image/jpeg"));
470
+ std::string data = json_value(source, "data", std::string());
471
+ std::string url = "data:" + media_type + ";base64," + data;
472
+ content_parts.push_back({
473
+ {"type", "image_url"},
474
+ {"image_url", {{"url", url}}}
475
+ });
476
+ } else if (source_type == "url") {
477
+ content_parts.push_back({
478
+ {"type", "image_url"},
479
+ {"image_url", {{"url", json_value(source, "url", std::string())}}}
480
+ });
481
+ }
482
+ }
483
+ }
484
+
485
+ if (!has_images) {
486
+ // Text-only: collapse to a plain string for maximum compatibility
487
+ tool_results.push_back({
488
+ {"role", "tool"},
489
+ {"tool_call_id", tool_use_id},
490
+ {"content", result_text}
491
+ });
492
+ } else {
493
+ // Mixed or image-only: use array content parts (OpenAI multimodal tool format)
494
+ tool_results.push_back({
495
+ {"role", "tool"},
496
+ {"tool_call_id", tool_use_id},
497
+ {"content", content_parts}
498
+ });
499
+ }
500
+ } else {
501
+ tool_results.push_back({
502
+ {"role", "tool"},
503
+ {"tool_call_id", tool_use_id},
504
+ {"content", ""}
505
+ });
506
+ }
507
+ }
508
+ }
509
+
510
+ if (!converted_content.empty() || has_tool_calls || !reasoning_content.empty()) {
511
+ json new_msg = {{"role", role}};
512
+ if (!converted_content.empty()) {
513
+ new_msg["content"] = converted_content;
514
+ } else if (has_tool_calls || !reasoning_content.empty()) {
515
+ new_msg["content"] = "";
516
+ }
517
+ if (!tool_calls.empty()) {
518
+ new_msg["tool_calls"] = tool_calls;
519
+ }
520
+ if (!reasoning_content.empty()) {
521
+ new_msg["reasoning_content"] = reasoning_content;
522
+ }
523
+ oai_messages.push_back(new_msg);
524
+ }
525
+
526
+ for (const auto & tool_msg : tool_results) {
527
+ oai_messages.push_back(tool_msg);
528
+ }
529
+ }
530
+ }
531
+
532
+ oai_body["messages"] = oai_messages;
533
+
534
+ // Convert tools
535
+ if (body.contains("tools")) {
536
+ const json & tools = body.at("tools");
537
+ if (tools.is_array()) {
538
+ json oai_tools = json::array();
539
+ for (const auto & tool : tools) {
540
+ oai_tools.push_back({
541
+ {"type", "function"},
542
+ {"function", {
543
+ {"name", json_value(tool, "name", std::string())},
544
+ {"description", json_value(tool, "description", std::string())},
545
+ {"parameters", tool.contains("input_schema") ? tool.at("input_schema") : json::object()}
546
+ }}
547
+ });
548
+ }
549
+ oai_body["tools"] = oai_tools;
550
+ }
551
+ }
552
+
553
+ // Convert tool_choice
554
+ if (body.contains("tool_choice")) {
555
+ const json & tc = body.at("tool_choice");
556
+ if (tc.is_object()) {
557
+ std::string type = json_value(tc, "type", std::string());
558
+ if (type == "auto") {
559
+ oai_body["tool_choice"] = "auto";
560
+ } else if (type == "any" || type == "tool") {
561
+ oai_body["tool_choice"] = "required";
562
+ }
563
+ }
564
+ }
565
+
566
+ // Convert stop_sequences to stop
567
+ if (body.contains("stop_sequences")) {
568
+ oai_body["stop"] = body.at("stop_sequences");
569
+ }
570
+
571
+ // Handle max_tokens (required in Anthropic, but we're permissive)
572
+ if (body.contains("max_tokens")) {
573
+ oai_body["max_tokens"] = body.at("max_tokens");
574
+ } else {
575
+ oai_body["max_tokens"] = 4096;
576
+ }
577
+
578
+ // Pass through common params
579
+ for (const auto & key : {"temperature", "top_p", "top_k", "stream", "chat_template_kwargs"}) {
580
+ if (body.contains(key)) {
581
+ oai_body[key] = body.at(key);
582
+ }
583
+ }
584
+
585
+ // Handle Anthropic-specific thinking param
586
+ if (body.contains("thinking")) {
587
+ json thinking = json_value(body, "thinking", json::object());
588
+ std::string thinking_type = json_value(thinking, "type", std::string());
589
+ if (thinking_type == "enabled") {
590
+ int budget_tokens = json_value(thinking, "budget_tokens", 10000);
591
+ oai_body["thinking_budget_tokens"] = budget_tokens;
592
+ }
593
+ }
594
+
595
+ // Handle Anthropic-specific metadata param
596
+ if (body.contains("metadata")) {
597
+ json metadata = json_value(body, "metadata", json::object());
598
+ std::string user_id = json_value(metadata, "user_id", std::string());
599
+ if (!user_id.empty()) {
600
+ oai_body["__metadata_user_id"] = user_id;
601
+ }
602
+ }
603
+
604
+ return oai_body;
605
+ }
606
+
607
+ json server_chat_msg_diff_to_json_oaicompat(const common_chat_msg_diff & diff) {
608
+ json delta = json::object();
609
+ if (!diff.reasoning_content_delta.empty()) {
610
+ delta["reasoning_content"] = diff.reasoning_content_delta;
611
+ }
612
+ if (!diff.content_delta.empty()) {
613
+ delta["content"] = diff.content_delta;
614
+ }
615
+ if (diff.tool_call_index != std::string::npos) {
616
+ json tool_call;
617
+ tool_call["index"] = diff.tool_call_index;
618
+ if (!diff.tool_call_delta.id.empty()) {
619
+ tool_call["id"] = diff.tool_call_delta.id;
620
+ tool_call["type"] = "function";
621
+ }
622
+ if (!diff.tool_call_delta.name.empty() || !diff.tool_call_delta.arguments.empty()) {
623
+ json function = json::object();
624
+ if (!diff.tool_call_delta.name.empty()) {
625
+ function["name"] = diff.tool_call_delta.name;
626
+ }
627
+ if (!diff.tool_call_delta.arguments.empty()) {
628
+ function["arguments"] = diff.tool_call_delta.arguments;
629
+ }
630
+ tool_call["function"] = function;
631
+ }
632
+ delta["tool_calls"] = json::array({ tool_call });
633
+ }
634
+ return delta;
635
+ }
636
+
637
+ json convert_transcriptions_to_chatcmpl(
638
+ const json & inp_body,
639
+ const common_chat_templates * tmpls,
640
+ const std::map<std::string, uploaded_file> & in_files,
641
+ std::vector<raw_buffer> & out_files) {
642
+ // TODO @ngxson : this function may need to be improved in the future
643
+ // handle input files
644
+ out_files.clear();
645
+ auto it = in_files.find("file");
646
+ if (it != in_files.end()) {
647
+ out_files.push_back(it->second.data);
648
+ } else {
649
+ throw std::invalid_argument("No input file found for transcription");
650
+ }
651
+
652
+ // handle input data
653
+ std::string prompt = json_value(inp_body, "prompt", std::string());
654
+ std::string language = json_value(inp_body, "language", std::string());
655
+ std::string response_format = json_value(inp_body, "response_format", std::string("json"));
656
+ if (response_format != "json") {
657
+ throw std::invalid_argument("Only 'json' response_format is supported for transcription");
658
+ }
659
+ const common_chat_prompt_preset preset = common_chat_get_asr_prompt(tmpls);
660
+ if (prompt.empty()) {
661
+ prompt = preset.user;
662
+ }
663
+ if (!language.empty()) {
664
+ prompt += string_format(" (language: %s)", language.c_str());
665
+ }
666
+ prompt += get_media_marker();
667
+
668
+ json messages = json::array();
669
+ if (!preset.system.empty()) {
670
+ messages.push_back({{"role", "system"}, {"content", preset.system}});
671
+ }
672
+ messages.push_back({{"role", "user"}, {"content", prompt}});
673
+
674
+ json chatcmpl_body = inp_body; // copy all fields
675
+ chatcmpl_body["messages"] = messages;
676
+
677
+ // because input from form-data, everything is string, we need to correct the types here
678
+ std::string stream = json_value(inp_body, "stream", std::string("false"));
679
+ chatcmpl_body["stream"] = stream == "true";
680
+
681
+ if (inp_body.contains("max_tokens")) {
682
+ std::string inp = inp_body["max_tokens"].get<std::string>();
683
+ chatcmpl_body["max_tokens"] = std::stoul(inp);
684
+ }
685
+
686
+ if (inp_body.contains("temperature")) {
687
+ std::string inp = inp_body["temperature"].get<std::string>();
688
+ chatcmpl_body["temperature"] = std::stof(inp);
689
+ }
690
+
691
+ return chatcmpl_body;
692
+ }
tools/server/server-chat.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Chat conversion functions for server (Responses API, Anthropic API, OAI streaming diffs)
2
+
3
+ #pragma once
4
+
5
+ #include "chat.h"
6
+ #include "server-common.h"
7
+ #include "server-http.h"
8
+
9
+ #include <nlohmann/json_fwd.hpp>
10
+
11
+ using json = nlohmann::ordered_json;
12
+
13
+ // Convert OpenAI Responses API format to OpenAI Chat Completions API format
14
+ json server_chat_convert_responses_to_chatcmpl(const json & body);
15
+
16
+ // Convert Anthropic Messages API format to OpenAI Chat Completions API format
17
+ json server_chat_convert_anthropic_to_oai(const json & body);
18
+
19
+ // convert OpenAI transcriptions API format to OpenAI Chat Completions API format
20
+ json convert_transcriptions_to_chatcmpl(
21
+ const json & body,
22
+ const common_chat_templates * tmpls,
23
+ const std::map<std::string, uploaded_file> & in_files,
24
+ std::vector<raw_buffer> & out_files);
25
+
26
+ json server_chat_msg_diff_to_json_oaicompat(const common_chat_msg_diff & diff);
tools/server/server-common.cpp ADDED
@@ -0,0 +1,1595 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "common.h"
2
+ #include "download.h"
3
+ #include "log.h"
4
+ #include "llama.h"
5
+ #include "mtmd.h"
6
+ #include "mtmd-helper.h"
7
+ #include "chat.h"
8
+ #include "base64.hpp"
9
+
10
+ #include "server-common.h"
11
+
12
+ #include <random>
13
+ #include <sstream>
14
+ #include <fstream>
15
+ #include <limits>
16
+
17
+ json format_error_response(const std::string & message, const enum error_type type) {
18
+ std::string type_str;
19
+ int code = 500;
20
+ switch (type) {
21
+ case ERROR_TYPE_INVALID_REQUEST:
22
+ type_str = "invalid_request_error";
23
+ code = 400;
24
+ break;
25
+ case ERROR_TYPE_AUTHENTICATION:
26
+ type_str = "authentication_error";
27
+ code = 401;
28
+ break;
29
+ case ERROR_TYPE_NOT_FOUND:
30
+ type_str = "not_found_error";
31
+ code = 404;
32
+ break;
33
+ case ERROR_TYPE_SERVER:
34
+ type_str = "server_error";
35
+ code = 500;
36
+ break;
37
+ case ERROR_TYPE_PERMISSION:
38
+ type_str = "permission_error";
39
+ code = 403;
40
+ break;
41
+ case ERROR_TYPE_NOT_SUPPORTED:
42
+ type_str = "not_supported_error";
43
+ code = 501;
44
+ break;
45
+ case ERROR_TYPE_UNAVAILABLE:
46
+ type_str = "unavailable_error";
47
+ code = 503;
48
+ break;
49
+ case ERROR_TYPE_EXCEED_CONTEXT_SIZE:
50
+ type_str = "exceed_context_size_error";
51
+ code = 400;
52
+ break;
53
+ }
54
+ return json {
55
+ {"code", code},
56
+ {"message", message},
57
+ {"type", type_str},
58
+ };
59
+ }
60
+
61
+ //
62
+ // random string / id
63
+ //
64
+
65
+ std::string random_string() {
66
+ static const std::string str("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
67
+
68
+ std::random_device rd;
69
+ std::mt19937 generator(rd());
70
+
71
+ std::string result(32, ' ');
72
+
73
+ for (int i = 0; i < 32; ++i) {
74
+ result[i] = str[generator() % str.size()];
75
+ }
76
+
77
+ return result;
78
+ }
79
+
80
+ std::string gen_chatcmplid() {
81
+ return "chatcmpl-" + random_string();
82
+ }
83
+
84
+ std::string gen_tool_call_id() {
85
+ return random_string();
86
+ }
87
+
88
+ const char * get_media_marker() {
89
+ static const std::string marker = []() {
90
+ // allow user to pin a reproducible marker via env var
91
+ const char * env = getenv("LLAMA_MEDIA_MARKER");
92
+ if (env && env[0] != '\0') {
93
+ return std::string(env);
94
+ }
95
+ return std::string("<__media_") + random_string() + "__>";
96
+ }();
97
+ return marker.c_str();
98
+ }
99
+
100
+ //
101
+ // lora utils
102
+ //
103
+
104
+ bool lora_all_alora(const std::vector<common_adapter_lora_info> & loras) {
105
+ bool found_alora = false;
106
+ for (const auto & lora : loras) {
107
+ if (lora.scale != 0) {
108
+ if (llama_adapter_get_alora_n_invocation_tokens(lora.ptr) == 0) {
109
+ return false;
110
+ }
111
+ found_alora = true;
112
+ }
113
+ }
114
+ return found_alora;
115
+ }
116
+
117
+ bool lora_should_clear_cache(
118
+ const std::vector<common_adapter_lora_info> & current,
119
+ const std::vector<common_adapter_lora_info> & next) {
120
+
121
+ // This should always be called after determining that the two sets are
122
+ // _not_ equal. This assert is therefore some slightly wasted work and
123
+ // should be safe to remove as long as this method is called correctly.
124
+ GGML_ASSERT(!are_lora_equal(current, next));
125
+
126
+ return (
127
+ !(lora_get_enabled_ids(current).empty() || lora_all_alora(current)) ||
128
+ !lora_all_alora(next));
129
+ }
130
+
131
+ std::map<int, float> parse_lora_request(const json & data) {
132
+ std::map<int, float> lora;
133
+
134
+ // set value
135
+ for (const auto & entry : data) {
136
+ int id = json_value(entry, "id", -1);
137
+ float scale = json_value(entry, "scale", 0.0f);
138
+ lora[id] = scale;
139
+ }
140
+
141
+ return lora;
142
+ }
143
+
144
+ bool are_lora_equal(
145
+ const std::vector<common_adapter_lora_info> & l1,
146
+ const std::vector<common_adapter_lora_info> & l2) {
147
+ if (l1.size() != l2.size()) {
148
+ return false;
149
+ }
150
+ for (size_t i = 0; i < l1.size(); ++i) {
151
+ // we don't check lora.path to reduce the time complexity
152
+ if (l1[i].scale != l2[i].scale || l1[i].ptr != l2[i].ptr) {
153
+ return false;
154
+ }
155
+ }
156
+ return true;
157
+ }
158
+
159
+ std::vector<size_t> lora_get_enabled_ids(const std::vector<common_adapter_lora_info> & loras) {
160
+ std::vector<size_t> enabled_ids;
161
+ for (size_t i = 0; i < loras.size(); ++i) {
162
+ if (loras[i].scale > 0) {
163
+ enabled_ids.push_back(i);
164
+ }
165
+ }
166
+ return enabled_ids;
167
+ }
168
+
169
+ //
170
+ // base64 utils (TODO: use the base64::decode from base64.hpp)
171
+ //
172
+
173
+ static const std::string base64_chars =
174
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
175
+ "abcdefghijklmnopqrstuvwxyz"
176
+ "0123456789+/";
177
+
178
+ static inline bool is_base64(uint8_t c) {
179
+ return (isalnum(c) || (c == '+') || (c == '/'));
180
+ }
181
+
182
+ static inline raw_buffer base64_decode(const std::string & encoded_string) {
183
+ int i = 0;
184
+ int j = 0;
185
+ int in_ = 0;
186
+
187
+ int in_len = encoded_string.size();
188
+
189
+ uint8_t char_array_4[4];
190
+ uint8_t char_array_3[3];
191
+
192
+ raw_buffer ret;
193
+
194
+ while (in_len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
195
+ char_array_4[i++] = encoded_string[in_]; in_++;
196
+ if (i == 4) {
197
+ for (i = 0; i < 4; i++) {
198
+ char_array_4[i] = base64_chars.find(char_array_4[i]);
199
+ }
200
+
201
+ char_array_3[0] = ((char_array_4[0] ) << 2) + ((char_array_4[1] & 0x30) >> 4);
202
+ char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
203
+ char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
204
+
205
+ for (i = 0; (i < 3); i++) {
206
+ ret.push_back(char_array_3[i]);
207
+ }
208
+
209
+ i = 0;
210
+ }
211
+ }
212
+
213
+ if (i) {
214
+ for (j = i; j < 4; j++) {
215
+ char_array_4[j] = 0;
216
+ }
217
+
218
+ for (j = 0; j < 4; j++) {
219
+ char_array_4[j] = base64_chars.find(char_array_4[j]);
220
+ }
221
+
222
+ char_array_3[0] = ((char_array_4[0] ) << 2) + ((char_array_4[1] & 0x30) >> 4);
223
+ char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
224
+ char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
225
+
226
+ for (j = 0; j < i - 1; j++) {
227
+ ret.push_back(char_array_3[j]);
228
+ }
229
+ }
230
+
231
+ return ret;
232
+ }
233
+
234
+ //
235
+ // server_tokens implementation
236
+ //
237
+
238
+ server_tokens::server_tokens(mtmd::input_chunks & mtmd_chunks, bool has_mtmd) : has_mtmd(has_mtmd) {
239
+ for (size_t i = 0; i < mtmd_chunks.size(); ++i) {
240
+ push_back(mtmd_chunks[i]);
241
+ }
242
+ }
243
+
244
+ server_tokens::server_tokens(const llama_tokens & tokens, bool has_mtmd) : has_mtmd(has_mtmd), tokens(tokens) {
245
+ }
246
+
247
+ llama_pos server_tokens::pos_next(int64_t n_tokens) const {
248
+ if (!has_mtmd) {
249
+ if (n_tokens < 0) {
250
+ return tokens.size();
251
+ }
252
+
253
+ return n_tokens;
254
+ }
255
+
256
+ if (n_tokens < 0) {
257
+ llama_pos res = tokens.size();
258
+
259
+ for (auto it = map_idx_to_media.begin(); it != map_idx_to_media.end(); ++it) {
260
+ const auto & chunk = it->second;
261
+ res += mtmd_input_chunk_get_n_pos(chunk.get()) - mtmd_input_chunk_get_n_tokens(chunk.get());
262
+ }
263
+
264
+ return res;
265
+ }
266
+
267
+ int64_t idx = 0;
268
+ llama_pos pos = 0;
269
+
270
+ GGML_ASSERT(n_tokens <= (int64_t)tokens.size());
271
+
272
+ while (idx < n_tokens) {
273
+ const auto media_it = map_idx_to_media.find(idx);
274
+ if (media_it != map_idx_to_media.end()) {
275
+ const auto & chunk = media_it->second;
276
+ const llama_pos n_pos = mtmd_input_chunk_get_n_pos(chunk.get());
277
+ const size_t n_tok = mtmd_input_chunk_get_n_tokens(chunk.get());
278
+
279
+ pos += n_pos;
280
+ idx += n_tok;
281
+ } else {
282
+ pos++;
283
+ idx++;
284
+ }
285
+ }
286
+
287
+ return pos;
288
+ }
289
+
290
+ size_t server_tokens::size_up_to_pos(llama_pos max_pos) const {
291
+ if (!has_mtmd) {
292
+ return std::min((size_t)max_pos, tokens.size());
293
+ }
294
+
295
+ size_t idx = 0;
296
+ llama_pos pos = 0;
297
+
298
+ while (idx < tokens.size()) {
299
+ const auto media_it = map_idx_to_media.find(idx);
300
+ if (media_it != map_idx_to_media.end()) {
301
+ const auto & chunk = media_it->second;
302
+ const llama_pos n_pos = mtmd_input_chunk_get_n_pos(chunk.get());
303
+ const size_t n_tok = mtmd_input_chunk_get_n_tokens(chunk.get());
304
+
305
+ pos += n_pos;
306
+ idx += n_tok;
307
+ } else {
308
+ pos++;
309
+ idx++;
310
+ }
311
+
312
+ if (pos >= max_pos) {
313
+ break;
314
+ }
315
+ }
316
+
317
+ return idx;
318
+ }
319
+
320
+ std::string server_tokens::str() const {
321
+ std::ostringstream oss;
322
+ oss << "tokens: ";
323
+ for (size_t idx = 0; idx < tokens.size(); ++idx) {
324
+ llama_token t = tokens[idx];
325
+ oss << "idx:" << idx << " ";
326
+ if (t == LLAMA_TOKEN_NULL) {
327
+ oss << "<embd> ";
328
+ } else {
329
+ oss << t << " ";
330
+ }
331
+ }
332
+ oss << "\n";
333
+ oss << "image idx: ";
334
+ for (const auto & it : map_idx_to_media) {
335
+ oss << it.first << ", ";
336
+ }
337
+ return oss.str();
338
+ }
339
+
340
+ const mtmd::input_chunk_ptr & server_tokens::find_chunk(size_t idx) const {
341
+ auto it = map_idx_to_media.find(idx);
342
+ if (it != map_idx_to_media.end()) {
343
+ return it->second;
344
+ }
345
+ throw std::runtime_error("Chunk not found");
346
+ }
347
+
348
+ std::pair<const mtmd::input_chunk_ptr *, size_t> server_tokens::find_next_media_chunk(size_t idx) const {
349
+ auto it = map_idx_to_media.upper_bound(idx);
350
+ if (it != map_idx_to_media.end()) {
351
+ return { &it->second, it->first };
352
+ }
353
+ return { nullptr, 0 };
354
+ }
355
+
356
+ void server_tokens::push_back(llama_token tok) {
357
+ if (tok == LLAMA_TOKEN_NULL) {
358
+ throw std::runtime_error("Invalid token");
359
+ }
360
+ tokens.emplace_back(tok);
361
+ }
362
+
363
+ void server_tokens::push_back(const mtmd_input_chunk * chunk) {
364
+ auto type = mtmd_input_chunk_get_type(chunk);
365
+ if (type == MTMD_INPUT_CHUNK_TYPE_IMAGE || type == MTMD_INPUT_CHUNK_TYPE_AUDIO) {
366
+ GGML_ASSERT(has_mtmd);
367
+ const size_t n_tokens = mtmd_input_chunk_get_n_tokens(chunk);
368
+ size_t start_idx = tokens.size();
369
+ for (size_t i = 0; i < n_tokens; ++i) {
370
+ tokens.emplace_back(LLAMA_TOKEN_NULL);
371
+ }
372
+ mtmd::input_chunk_ptr new_chunk(mtmd_input_chunk_copy(chunk));
373
+ map_idx_to_media[start_idx] = std::move(new_chunk);
374
+ } else if (type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
375
+ size_t n_tokens;
376
+ const auto * text_tokens = mtmd_input_chunk_get_tokens_text(chunk, &n_tokens);
377
+ for (size_t i = 0; i < n_tokens; ++i) {
378
+ push_back(text_tokens[i]);
379
+ }
380
+ } else {
381
+ GGML_ABORT("Invalid chunk type");
382
+ }
383
+ }
384
+
385
+ void server_tokens::push_back(server_tokens & tokens) {
386
+ size_t start_idx = size();
387
+ for (size_t i = 0; i < tokens.size(); i++) {
388
+ push_back(tokens[i]);
389
+ }
390
+ if (tokens.has_mtmd) {
391
+ // Assert if we are copying MTMD chunks to a server_tokens that does not have mtmd.
392
+ // We could also just check, but this will prevent silently dropping MTMD data.
393
+ GGML_ASSERT(has_mtmd);
394
+ for (auto it = tokens.map_idx_to_media.begin(); it != tokens.map_idx_to_media.end(); ) {
395
+ auto * chunk = tokens.map_idx_to_media[it->first].get();
396
+ mtmd::input_chunk_ptr new_chunk(mtmd_input_chunk_copy(chunk));
397
+ map_idx_to_media[start_idx + it->first] = std::move(new_chunk);
398
+ }
399
+ }
400
+ }
401
+
402
+ void server_tokens::insert(const llama_tokens & inp_tokens) {
403
+ tokens.insert(tokens.end(), inp_tokens.begin(), inp_tokens.end());
404
+ }
405
+
406
+ const llama_tokens & server_tokens::get_tokens() const {
407
+ GGML_ASSERT(!has_mtmd);
408
+ return tokens;
409
+ }
410
+
411
+ llama_tokens server_tokens::get_text_tokens() const {
412
+ llama_tokens res;
413
+ res.reserve(tokens.size());
414
+ for (llama_token t : tokens) {
415
+ if (t != LLAMA_TOKEN_NULL) {
416
+ res.push_back(t);
417
+ }
418
+ }
419
+ return res;
420
+ }
421
+
422
+ void server_tokens::set_token(llama_pos pos, llama_token id) {
423
+ GGML_ASSERT(!has_mtmd); // only allow this if mtmd is disabled
424
+ tokens[pos] = id;
425
+ }
426
+
427
+ void server_tokens::keep_first(size_t n) {
428
+ GGML_ASSERT(n <= tokens.size());
429
+ if (has_mtmd) {
430
+ if (n == tokens.size()) {
431
+ return; // nothing to do
432
+ }
433
+ // we throw an error if we try to remove a token in the middle of an image
434
+ // for ex. with input of 5 text tokens and 2 images:
435
+ // [0] [1] [2] [3] [4] [img0] [img0] [img0] [img1] [img1]
436
+ // n 1 2 3 4 5 6 7 8 9 10
437
+ // allowed to resize ^ ^
438
+ // disallowed to resize ^ ^ ^
439
+ if (n > 0) {
440
+ // make sure we never remove tokens in the middle of an image
441
+ // note that the case where we keep a full image at the end is allowed:
442
+ // tokens[n - 1] == LLAMA_TOKEN_NULL && tokens[n] != LLAMA_TOKEN_NULL
443
+ if (tokens[n - 1] == LLAMA_TOKEN_NULL && tokens[n] == LLAMA_TOKEN_NULL) {
444
+ find_chunk(n - 1); // will throw an error if the token is not begin-of-chunk
445
+ }
446
+ }
447
+ // remove all image chunks that are not used anymore
448
+ for (auto it = map_idx_to_media.begin(); it != map_idx_to_media.end(); ) {
449
+ size_t idx = it->first;
450
+ if (idx >= n) {
451
+ it = map_idx_to_media.erase(it);
452
+ } else {
453
+ ++it;
454
+ }
455
+ }
456
+ }
457
+ tokens.resize(n);
458
+ }
459
+
460
+ std::string server_tokens::detokenize(const llama_context * ctx, bool special) const {
461
+ llama_tokens text_tokens;
462
+ text_tokens.reserve(tokens.size());
463
+ for (const auto & t : tokens) {
464
+ if (t != LLAMA_TOKEN_NULL) {
465
+ text_tokens.push_back(t);
466
+ }
467
+ }
468
+ return common_detokenize(ctx, text_tokens, special);
469
+ }
470
+
471
+ size_t server_tokens::get_common_prefix(const server_tokens & b) const {
472
+ const size_t max_idx = std::min(tokens.size(), b.tokens.size());
473
+
474
+ if (!has_mtmd) {
475
+ for (size_t i = 0; i < max_idx; ++i) {
476
+ if (tokens[i] == b.tokens[i]) {
477
+ continue;
478
+ }
479
+
480
+ return i;
481
+ }
482
+
483
+ return max_idx;
484
+ }
485
+
486
+ for (size_t i = 0; i < max_idx; ++i) {
487
+ const llama_token ai = tokens[i];
488
+ const llama_token bi = b.tokens[i];
489
+
490
+ if (ai == LLAMA_TOKEN_NULL && bi == LLAMA_TOKEN_NULL) {
491
+ const auto & a_chunk = find_chunk(i);
492
+ const auto & b_chunk = b.find_chunk(i);
493
+
494
+ GGML_ASSERT(a_chunk && b_chunk);
495
+
496
+ const std::string id_ai = mtmd_input_chunk_get_id(a_chunk.get());
497
+ const std::string id_bi = mtmd_input_chunk_get_id(b_chunk.get());
498
+
499
+ const size_t n_tok_a = mtmd_input_chunk_get_n_tokens(a_chunk.get());
500
+ const size_t n_tok_b = mtmd_input_chunk_get_n_tokens(b_chunk.get());
501
+
502
+ if (id_ai == id_bi && n_tok_a == n_tok_b) {
503
+ GGML_ASSERT(n_tok_a > 0 && "Invalid media chunk"); // should never happen
504
+ i += n_tok_a - 1; // will be +1 by the for loop
505
+ continue;
506
+ }
507
+
508
+ return i;
509
+ }
510
+
511
+ if (ai == bi) {
512
+ continue;
513
+ }
514
+
515
+ return i;
516
+ }
517
+
518
+ return max_idx; // all tokens are equal
519
+ }
520
+
521
+ common_chat_msg_spans server_tokens::find_message_spans(const common_chat_msg_delimiters & delims) const {
522
+ std::map<size_t, size_t> skips;
523
+ for (const auto & it : map_idx_to_media) {
524
+ skips[it.first] = mtmd_input_chunk_get_n_tokens(it.second.get());
525
+ }
526
+ return delims.split(tokens, skips);
527
+ }
528
+
529
+ bool server_tokens::validate(const struct llama_context * ctx) const {
530
+ const llama_model * model = llama_get_model(ctx);
531
+ const llama_vocab * vocab = llama_model_get_vocab(model);
532
+ const int32_t n_vocab = llama_vocab_n_tokens(vocab);
533
+
534
+ for (size_t i = 0; i < tokens.size(); ++i) {
535
+ const auto & t = tokens[i];
536
+ if (t == LLAMA_TOKEN_NULL) {
537
+ try {
538
+ const auto & chunk = find_chunk(i);
539
+ size_t n_tokens = mtmd_input_chunk_get_n_tokens(chunk.get());
540
+ i += n_tokens - 1; // will be +1 by the for loop
541
+ } catch (const std::exception & e) {
542
+ return false;
543
+ }
544
+ } else if (t < 0 || t >= n_vocab) {
545
+ return false;
546
+ }
547
+ }
548
+ return true;
549
+ }
550
+
551
+ server_tokens server_tokens::clone() const {
552
+ server_tokens res;
553
+ res.has_mtmd = has_mtmd;
554
+ res.tokens = tokens;
555
+ for (auto it = map_idx_to_media.begin(); it != map_idx_to_media.end(); ++it) {
556
+ size_t idx = it->first;
557
+ const mtmd::input_chunk_ptr & chunk = it->second;
558
+ res.map_idx_to_media[idx] = mtmd::input_chunk_ptr(mtmd_input_chunk_copy(chunk.get()));
559
+ }
560
+ return res;
561
+ }
562
+
563
+ //
564
+ // tokenizer and input processing utils
565
+ //
566
+
567
+ bool json_is_array_of_numbers(const json & data) {
568
+ if (data.is_array()) {
569
+ for (const auto & e : data) {
570
+ if (!e.is_number_integer()) {
571
+ return false;
572
+ }
573
+ }
574
+ return true;
575
+ }
576
+ return false;
577
+ }
578
+
579
+ bool json_is_array_of_mixed_numbers_strings(const json & data) {
580
+ bool seen_string = false;
581
+ bool seen_number = false;
582
+ if (data.is_array()) {
583
+ for (const auto & e : data) {
584
+ seen_string |= e.is_string();
585
+ seen_number |= e.is_number_integer();
586
+ if (seen_number && seen_string) {
587
+ return true;
588
+ }
589
+ }
590
+ }
591
+ return false;
592
+ }
593
+
594
+ bool json_is_array_and_contains_numbers(const json & data) {
595
+ if (data.is_array()) {
596
+ for (const auto & e : data) {
597
+ if (e.is_number_integer()) {
598
+ return true;
599
+ }
600
+ }
601
+ return false;
602
+ }
603
+ return false;
604
+ }
605
+
606
+ json json_get_nested_values(const std::vector<std::string> & paths, const json & js) {
607
+ json result = json::object();
608
+
609
+ for (const std::string & path : paths) {
610
+ json current = js;
611
+ const auto keys = string_split<std::string>(path, /*separator*/ '/');
612
+ bool valid_path = true;
613
+ for (const std::string & k : keys) {
614
+ if (valid_path && current.is_object() && current.contains(k)) {
615
+ current = current[k];
616
+ } else {
617
+ valid_path = false;
618
+ }
619
+ }
620
+ if (valid_path) {
621
+ result[path] = current;
622
+ }
623
+ }
624
+ return result;
625
+ }
626
+
627
+ llama_tokens tokenize_mixed(const llama_vocab * vocab, const json & json_prompt, bool add_special, bool parse_special) {
628
+ // If `add_bos` is true, we only add BOS, when json_prompt is a string,
629
+ // or the first element of the json_prompt array is a string.
630
+ llama_tokens prompt_tokens;
631
+
632
+ if (json_prompt.is_array()) {
633
+ bool first = true;
634
+ for (const auto & p : json_prompt) {
635
+ if (p.is_string()) {
636
+ auto s = p.template get<std::string>();
637
+
638
+ llama_tokens p;
639
+ if (first) {
640
+ p = common_tokenize(vocab, s, add_special, parse_special);
641
+ first = false;
642
+ } else {
643
+ p = common_tokenize(vocab, s, false, parse_special);
644
+ }
645
+
646
+ prompt_tokens.insert(prompt_tokens.end(), p.begin(), p.end());
647
+ } else {
648
+ if (first) {
649
+ first = false;
650
+ }
651
+
652
+ prompt_tokens.push_back(p.template get<llama_token>());
653
+ }
654
+ }
655
+ } else {
656
+ auto s = json_prompt.template get<std::string>();
657
+ prompt_tokens = common_tokenize(vocab, s, add_special, parse_special);
658
+ }
659
+
660
+ return prompt_tokens;
661
+ }
662
+
663
+ size_t validate_utf8(const std::string& text) {
664
+ size_t len = text.size();
665
+ if (len == 0) return 0;
666
+
667
+ // Check the last few bytes to see if a multi-byte character is cut off
668
+ for (size_t i = 1; i <= 4 && i <= len; ++i) {
669
+ unsigned char c = text[len - i];
670
+ // Check for start of a multi-byte sequence from the end
671
+ if ((c & 0xE0) == 0xC0) {
672
+ // 2-byte character start: 110xxxxx
673
+ // Needs at least 2 bytes
674
+ if (i < 2) return len - i;
675
+ } else if ((c & 0xF0) == 0xE0) {
676
+ // 3-byte character start: 1110xxxx
677
+ // Needs at least 3 bytes
678
+ if (i < 3) return len - i;
679
+ } else if ((c & 0xF8) == 0xF0) {
680
+ // 4-byte character start: 11110xxx
681
+ // Needs at least 4 bytes
682
+ if (i < 4) return len - i;
683
+ }
684
+ }
685
+
686
+ // If no cut-off multi-byte character is found, return full length
687
+ return len;
688
+ }
689
+
690
+ server_tokens process_mtmd_prompt(mtmd_context * mctx, const std::string & prompt, const std::vector<raw_buffer> & files, bool is_placeholder) {
691
+ // these will be freed upon going out of scope
692
+ mtmd::bitmaps bitmaps;
693
+ std::vector<mtmd_helper::video_ptr> videos;
694
+ for (auto & file : files) {
695
+ auto out = mtmd_helper_bitmap_init_from_buf(mctx, file.data(), file.size(), is_placeholder);
696
+ if (!out.bitmap) {
697
+ throw std::runtime_error("Failed to load image or audio file");
698
+ }
699
+ bitmaps.entries.emplace_back(out.bitmap);
700
+ if (out.video_ctx) {
701
+ videos.emplace_back(out.video_ctx);
702
+ }
703
+ }
704
+ // process prompt
705
+ std::vector<server_tokens> inputs;
706
+ // multimodal
707
+ mtmd_input_text inp_txt = {
708
+ prompt.data(),
709
+ prompt.size(),
710
+ /* add_special */ true,
711
+ /* parse_special */ true,
712
+ };
713
+ mtmd::input_chunks chunks(mtmd_input_chunks_init());
714
+ auto bitmaps_c_ptr = bitmaps.c_ptr();
715
+ int32_t tokenized = mtmd_tokenize(mctx,
716
+ chunks.ptr.get(),
717
+ &inp_txt,
718
+ bitmaps_c_ptr.data(),
719
+ bitmaps_c_ptr.size());
720
+ if (tokenized != 0) {
721
+ throw std::runtime_error("Failed to tokenize prompt");
722
+ }
723
+ auto result = server_tokens(chunks, true);
724
+ return result;
725
+ }
726
+
727
+ /**
728
+ * break the input "prompt" object into multiple prompt if needed, then tokenize them
729
+ * use tokenize_input_prompts() if the input could be an array.
730
+ * this supports these cases:
731
+ * - "prompt": "string"
732
+ * - "prompt": [12, 34, 56]
733
+ * - "prompt": [12, 34, "string", 56, 78]
734
+ * - "prompt": { "prompt_string": "string", "multimodal_data": [ "base64" ] }
735
+ */
736
+ static server_tokens tokenize_input_subprompt(const llama_vocab * vocab, mtmd_context * mctx, const json & json_prompt, bool add_special, bool parse_special) {
737
+ constexpr char JSON_STRING_PROMPT_KEY[] = "prompt_string";
738
+ constexpr char JSON_MTMD_DATA_KEY[] = "multimodal_data";
739
+ const bool has_mtmd = mctx != nullptr;
740
+ if (json_prompt.is_string() || json_is_array_of_mixed_numbers_strings(json_prompt)) {
741
+ // string or mixed
742
+ llama_tokens tmp = tokenize_mixed(vocab, json_prompt, add_special, parse_special);
743
+ return server_tokens(tmp, false);
744
+ } else if (json_is_array_of_numbers(json_prompt)) {
745
+ // array of tokens
746
+ llama_tokens tmp = json_prompt.get<llama_tokens>();
747
+ return server_tokens(tmp, false);
748
+ } else if (json_prompt.contains(JSON_STRING_PROMPT_KEY)) {
749
+ // JSON object with prompt key.
750
+ if (json_prompt.contains(JSON_MTMD_DATA_KEY)) {
751
+ if (!has_mtmd)
752
+ throw std::runtime_error("Multimodal data provided, but model does not support multimodal requests.");
753
+
754
+ // JSON object with prompt and multimodal key.
755
+ std::vector<raw_buffer> files;
756
+ for (const auto & entry : json_prompt.at(JSON_MTMD_DATA_KEY)) {
757
+ files.push_back(base64_decode(entry));
758
+ }
759
+ return process_mtmd_prompt(mctx, json_prompt.at(JSON_STRING_PROMPT_KEY), files);
760
+ } else {
761
+ // Not multimodal, but contains a subobject.
762
+ llama_tokens tmp = tokenize_mixed(vocab, json_prompt.at(JSON_STRING_PROMPT_KEY), add_special, parse_special);
763
+ return server_tokens(tmp, false);
764
+ }
765
+ } else {
766
+ throw std::runtime_error("\"prompt\" elements must be a string, a list of tokens, a JSON object containing a prompt string, or a list of mixed strings & tokens.");
767
+ }
768
+ }
769
+
770
+ std::vector<server_tokens> tokenize_input_prompts(const llama_vocab * vocab, mtmd_context * mctx, const json & json_prompt, bool add_special, bool parse_special) {
771
+ std::vector<server_tokens> result;
772
+ if (json_prompt.is_array() && !json_is_array_and_contains_numbers(json_prompt)) {
773
+ result.reserve(json_prompt.size());
774
+ for (const auto & p : json_prompt) {
775
+ result.push_back(tokenize_input_subprompt(vocab, mctx, p,add_special, parse_special));
776
+ }
777
+ } else {
778
+ result.push_back(tokenize_input_subprompt(vocab, mctx, json_prompt, add_special, parse_special));
779
+ }
780
+ if (result.empty()) {
781
+ throw std::runtime_error("\"prompt\" must not be empty");
782
+ }
783
+ return result;
784
+ }
785
+
786
+ //
787
+ // OAI utils
788
+ //
789
+
790
+ // used by /completions endpoint
791
+ json oaicompat_completion_params_parse(const json & body) {
792
+ json llama_params;
793
+
794
+ if (!body.contains("prompt")) {
795
+ throw std::runtime_error("\"prompt\" is required");
796
+ }
797
+
798
+ // Handle "stop" field
799
+ if (body.contains("stop") && body.at("stop").is_string()) {
800
+ llama_params["stop"] = json::array({body.at("stop").get<std::string>()});
801
+ } else {
802
+ llama_params["stop"] = json_value(body, "stop", json::array());
803
+ }
804
+
805
+ // Handle "echo" field
806
+ if (json_value(body, "echo", false)) {
807
+ throw std::runtime_error("Only no echo is supported");
808
+ }
809
+
810
+ // Params supported by OAI but unsupported by llama.cpp
811
+ static const std::vector<std::string> unsupported_params { "best_of" };
812
+ for (const auto & param : unsupported_params) {
813
+ if (body.contains(param)) {
814
+ throw std::runtime_error("Unsupported param: " + param);
815
+ }
816
+ }
817
+
818
+ // Copy remaining properties to llama_params
819
+ for (const auto & item : body.items()) {
820
+ // Exception: if "n_predict" is present, we overwrite the value specified earlier by "max_tokens"
821
+ if (!llama_params.contains(item.key()) || item.key() == "n_predict") {
822
+ llama_params[item.key()] = item.value();
823
+ }
824
+ }
825
+
826
+ return llama_params;
827
+ }
828
+
829
+ // url can be
830
+ // - http(s):// for remote files
831
+ // - file:// for local files (only allowed if media_path is set)
832
+ // - data: for base64 encoded data with uri scheme (e.g. data:image/png;base64,...)
833
+ // - raw base64 encoded data
834
+ static void handle_media(
835
+ std::vector<raw_buffer> & out_files,
836
+ const std::string & url,
837
+ const std::string & media_path,
838
+ bool accept_base64_uri) {
839
+ if (!media_path.empty()) {
840
+ // should already be enforced by arg.cpp, but checking just in case
841
+ GGML_ASSERT(media_path.back() == DIRECTORY_SEPARATOR);
842
+ }
843
+
844
+ if (string_starts_with(url, "http")) {
845
+ // download remote image
846
+ // TODO @ngxson : maybe make these params configurable
847
+ common_remote_params params;
848
+ params.max_size = 1024 * 1024 * 10; // 10MB
849
+ params.timeout = 10; // seconds
850
+ SRV_INF("downloading image from '%s'\n", url.c_str());
851
+ auto res = common_remote_get_content(url, params);
852
+ if (200 <= res.first && res.first < 300) {
853
+ SRV_INF("downloaded %zu bytes\n", res.second.size());
854
+ raw_buffer data;
855
+ data.insert(data.end(), res.second.begin(), res.second.end());
856
+ out_files.push_back(data);
857
+ } else {
858
+ throw std::runtime_error("Failed to download image");
859
+ }
860
+
861
+ } else if (string_starts_with(url, "file://")) {
862
+ if (media_path.empty()) {
863
+ throw std::invalid_argument("file:// URLs are not allowed unless --media-path is specified");
864
+ }
865
+ // load local image file
866
+ std::string file_path = url.substr(7); // remove "file://"
867
+ raw_buffer data;
868
+ if (!fs_validate_filename(file_path, true)) {
869
+ throw std::invalid_argument("file path is not allowed: " + file_path);
870
+ }
871
+ SRV_INF("loading image from local file '%s'\n", (media_path + file_path).c_str());
872
+ std::ifstream file(media_path + file_path, std::ios::binary);
873
+ if (!file) {
874
+ throw std::invalid_argument("file does not exist or cannot be opened: " + file_path);
875
+ }
876
+ data.assign((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
877
+ out_files.push_back(data);
878
+
879
+ } else if (accept_base64_uri && string_starts_with(url, "data:")) {
880
+ // try to decode base64 image
881
+ std::vector<std::string> parts = string_split<std::string>(url, /*separator*/ ',');
882
+ if (parts.size() != 2) {
883
+ throw std::runtime_error("Invalid uri-encoded base64 value");
884
+ } else if (!string_starts_with(parts[0], "data:image/")) {
885
+ throw std::runtime_error("Invalid uri format: " + parts[0]);
886
+ } else if (!string_ends_with(parts[0], "base64")) {
887
+ throw std::runtime_error("uri must be base64 encoded");
888
+ } else {
889
+ auto base64_data = parts[1];
890
+ auto decoded_data = base64_decode(base64_data);
891
+ out_files.push_back(decoded_data);
892
+ }
893
+
894
+ } else {
895
+ // try as raw base64 string
896
+ auto decoded_data = base64_decode(url);
897
+ if (decoded_data.empty()) {
898
+ throw std::runtime_error("Invalid base64 value");
899
+ }
900
+ out_files.push_back(decoded_data);
901
+ }
902
+ }
903
+
904
+ // used by /chat/completions endpoint
905
+ json oaicompat_chat_params_parse(
906
+ json & body, /* openai api json semantics */
907
+ const server_chat_params & opt,
908
+ std::vector<raw_buffer> & out_files)
909
+ {
910
+ json llama_params;
911
+
912
+ auto tools = json_value(body, "tools", json());
913
+ auto has_tools = tools.is_array() && !tools.empty();
914
+ auto stream = json_value(body, "stream", false);
915
+ auto tool_choice = json_value(body, "tool_choice", std::string("auto"));
916
+
917
+ if (!opt.use_jinja) {
918
+ if (has_tools) {
919
+ throw std::runtime_error("tools param requires --jinja flag");
920
+ }
921
+ if (tool_choice != "auto") {
922
+ throw std::runtime_error("tool_choice param requires --jinja flag");
923
+ }
924
+ }
925
+
926
+ // Handle "stop" field
927
+ if (body.contains("stop") && body.at("stop").is_string()) {
928
+ llama_params["stop"] = json::array({body.at("stop").get<std::string>()});
929
+ } else {
930
+ llama_params["stop"] = json_value(body, "stop", json::array());
931
+ }
932
+
933
+ auto json_schema = json_value(body, "json_schema", json());
934
+ auto grammar = json_value(body, "grammar", std::string());
935
+ if (!json_schema.is_null() && !grammar.empty()) {
936
+ throw std::runtime_error("Cannot use both json_schema and grammar");
937
+ }
938
+
939
+ // Handle "response_format" field
940
+ if (body.contains("response_format")) {
941
+ json response_format = json_value(body, "response_format", json::object());
942
+ std::string response_type = json_value(response_format, "type", std::string());
943
+ if (response_type == "json_object") {
944
+ if (response_format.contains("schema") || json_schema.empty()) {
945
+ json_schema = json_value(response_format, "schema", json::object());
946
+ }
947
+ } else if (response_type == "json_schema") {
948
+ auto schema_wrapper = json_value(response_format, "json_schema", json::object());
949
+ json_schema = json_value(schema_wrapper, "schema", json::object());
950
+ } else if (!response_type.empty() && response_type != "text") {
951
+ throw std::invalid_argument("response_format type must be one of \"text\" or \"json_object\", but got: " + response_type);
952
+ }
953
+ }
954
+
955
+ // get input files
956
+ if (!body.contains("messages")) {
957
+ throw std::invalid_argument("'messages' is required");
958
+ }
959
+ json & messages = body.at("messages");
960
+ if (!messages.is_array()) {
961
+ throw std::invalid_argument("Expected 'messages' to be an array");
962
+ }
963
+ for (auto & msg : messages) {
964
+ std::string role = json_value(msg, "role", std::string());
965
+ if (role != "assistant" && !msg.contains("content")) {
966
+ throw std::invalid_argument("All non-assistant messages must contain 'content'");
967
+ }
968
+ if (role == "assistant") {
969
+ if (!msg.contains("content") && !msg.contains("tool_calls")) {
970
+ throw std::invalid_argument("Assistant message must contain either 'content' or 'tool_calls'!");
971
+ }
972
+ if (!msg.contains("content")) {
973
+ continue; // avoid errors with no content
974
+ }
975
+ }
976
+ json & content = msg.at("content");
977
+ if (content.is_string() || content.is_null()) {
978
+ continue;
979
+ }
980
+
981
+ if (!content.is_array()) {
982
+ throw std::invalid_argument("Expected 'content' to be a string or an array");
983
+ }
984
+
985
+ for (auto & p : content) {
986
+ std::string type = json_value(p, "type", std::string());
987
+ if (type == "image_url") {
988
+ if (!opt.allow_image) {
989
+ throw std::runtime_error("image input is not supported - hint: if this is unexpected, you may need to provide the mmproj");
990
+ }
991
+
992
+ json image_url = json_value(p, "image_url", json::object());
993
+ std::string url = json_value(image_url, "url", std::string());
994
+ handle_media(out_files, url, opt.media_path, true);
995
+
996
+ p["type"] = "media_marker";
997
+ p["text"] = get_media_marker();
998
+ p.erase("image_url");
999
+
1000
+ } else if (type == "input_audio") {
1001
+ if (!opt.allow_audio) {
1002
+ throw std::runtime_error("audio input is not supported - hint: if this is unexpected, you may need to provide the mmproj");
1003
+ }
1004
+
1005
+ // note: don't need to validate "format", it's redundant
1006
+ json input_audio = json_value(p, "input_audio", json::object());
1007
+ std::string url = json_value(input_audio, "data",
1008
+ json_value(input_audio, "url", std::string()));
1009
+ handle_media(out_files, url, opt.media_path, false);
1010
+
1011
+ p["type"] = "media_marker";
1012
+ p["text"] = get_media_marker();
1013
+ p.erase("input_audio");
1014
+
1015
+ } else if (type == "input_video") {
1016
+ if (!opt.allow_video) {
1017
+ throw std::runtime_error("video input is not supported - hint: if this is unexpected, you may need to provide the mmproj");
1018
+ }
1019
+
1020
+ json input_video = json_value(p, "input_video", json::object());
1021
+ std::string url = json_value(input_video, "data",
1022
+ json_value(input_video, "url", std::string()));
1023
+ handle_media(out_files, url, opt.media_path, false);
1024
+
1025
+ p["type"] = "media_marker";
1026
+ p["text"] = get_media_marker();
1027
+ p.erase("input_video");
1028
+
1029
+ } else if (type != "text") {
1030
+ throw std::invalid_argument("unsupported content[].type");
1031
+ }
1032
+ }
1033
+ }
1034
+
1035
+ auto caps = common_chat_templates_get_caps(opt.tmpls.get());
1036
+
1037
+ common_chat_templates_inputs inputs;
1038
+ inputs.messages = common_chat_msgs_parse_oaicompat(messages);
1039
+ inputs.tools = common_chat_tools_parse_oaicompat(tools);
1040
+ inputs.tool_choice = common_chat_tool_choice_parse_oaicompat(tool_choice);
1041
+ inputs.json_schema = json_schema.is_null() ? "" : json_schema.dump();
1042
+ inputs.grammar = grammar;
1043
+ inputs.use_jinja = opt.use_jinja;
1044
+ inputs.parallel_tool_calls = json_value(body, "parallel_tool_calls", caps["supports_parallel_tool_calls"]);
1045
+ inputs.add_generation_prompt = json_value(body, "add_generation_prompt", true);
1046
+ inputs.continue_final_message = body.contains("continue_final_message") ?
1047
+ common_chat_continuation_parse(body.at("continue_final_message")) :
1048
+ COMMON_CHAT_CONTINUATION_NONE;
1049
+ if (inputs.continue_final_message == COMMON_CHAT_CONTINUATION_NONE && opt.prefill_assistant
1050
+ && !inputs.messages.empty() && inputs.messages.back().role == "assistant") {
1051
+ if (inputs.messages.size() >= 2 && inputs.messages[inputs.messages.size() - 2].role == "assistant") {
1052
+ throw std::invalid_argument("Cannot have 2 or more assistant messages at the end of the list.");
1053
+ }
1054
+ inputs.continue_final_message = COMMON_CHAT_CONTINUATION_AUTO;
1055
+ inputs.add_generation_prompt = false;
1056
+ }
1057
+ if (inputs.continue_final_message != COMMON_CHAT_CONTINUATION_NONE && inputs.add_generation_prompt) {
1058
+ throw std::invalid_argument("Cannot set both add_generation_prompt and continue_final_message to true.");
1059
+ }
1060
+ inputs.reasoning_format = opt.reasoning_format;
1061
+ if (body.contains("reasoning_format")) {
1062
+ inputs.reasoning_format = common_reasoning_format_from_name(body.at("reasoning_format").get<std::string>());
1063
+ }
1064
+ inputs.enable_thinking = opt.enable_thinking;
1065
+ if (!inputs.tools.empty() && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE) {
1066
+ if (body.contains("grammar")) {
1067
+ throw std::invalid_argument("Cannot use custom grammar constraints with tools.");
1068
+ }
1069
+ llama_params["parse_tool_calls"] = true;
1070
+ }
1071
+
1072
+ // merge the template args provided from command line with the args provided in the user request
1073
+ auto chat_template_kwargs_object = json_value(body, "chat_template_kwargs", json::object());
1074
+ inputs.chat_template_kwargs = opt.chat_template_kwargs;
1075
+ for (const auto & item : chat_template_kwargs_object.items()) {
1076
+ inputs.chat_template_kwargs[item.key()] = item.value().dump();
1077
+ }
1078
+
1079
+ // parse the "enable_thinking" kwarg to override the default value
1080
+ auto enable_thinking_kwarg = json_value(inputs.chat_template_kwargs, "enable_thinking", std::string(""));
1081
+ if (enable_thinking_kwarg == "true") {
1082
+ inputs.enable_thinking = true;
1083
+ } else if (enable_thinking_kwarg == "false") {
1084
+ inputs.enable_thinking = false;
1085
+ } else if (!enable_thinking_kwarg.empty() && enable_thinking_kwarg[0] == '"') {
1086
+ throw std::invalid_argument("invalid type for \"enable_thinking\" (expected boolean, got string)");
1087
+ }
1088
+
1089
+ // Parse also the OAI "reasoning_effort": "none" specific value
1090
+ if (body.contains("reasoning_effort")) {
1091
+ auto reasoning_effort = json_value(body, "reasoning_effort", std::string(""));
1092
+ if (reasoning_effort == "none") {
1093
+ inputs.enable_thinking = false;
1094
+ } // other reasoning_effort values are model-specific and not yet handled
1095
+ }
1096
+
1097
+ inputs.force_pure_content = opt.force_pure_content;
1098
+
1099
+ // Apply chat template to the list of messages
1100
+ auto chat_params = common_chat_templates_apply(opt.tmpls.get(), inputs);
1101
+
1102
+ llama_params["chat_format"] = static_cast<int>(chat_params.format);
1103
+ llama_params["prompt"] = chat_params.prompt;
1104
+ if (!chat_params.grammar.empty()) {
1105
+ llama_params["grammar"] = chat_params.grammar;
1106
+ llama_params["grammar_type"] = std::string("tool_calls");
1107
+ }
1108
+ llama_params["grammar_lazy"] = chat_params.grammar_lazy;
1109
+ auto grammar_triggers = json::array();
1110
+ for (const auto & trigger : chat_params.grammar_triggers) {
1111
+ server_grammar_trigger ct(trigger);
1112
+ grammar_triggers.push_back(ct.to_json());
1113
+ }
1114
+ llama_params["grammar_triggers"] = grammar_triggers;
1115
+ llama_params["preserved_tokens"] = chat_params.preserved_tokens;
1116
+ llama_params["generation_prompt"] = chat_params.generation_prompt;
1117
+ for (const auto & stop : chat_params.additional_stops) {
1118
+ llama_params["stop"].push_back(stop);
1119
+ }
1120
+ if (!chat_params.parser.empty()) {
1121
+ llama_params["chat_parser"] = chat_params.parser;
1122
+ }
1123
+
1124
+ llama_params["message_delimiters"] = chat_params.message_delimiters.to_json();
1125
+
1126
+ // Reasoning budget: pass parameters through to sampling layer
1127
+ {
1128
+ int reasoning_budget = json_value(body, "reasoning_budget_tokens",
1129
+ json_value(body, "thinking_budget_tokens", -1));
1130
+ if (reasoning_budget == -1) {
1131
+ reasoning_budget = opt.reasoning_budget;
1132
+ }
1133
+
1134
+ if (!chat_params.thinking_end_tags.empty()) {
1135
+ llama_params["reasoning_budget_tokens"] = reasoning_budget;
1136
+ llama_params["reasoning_budget_start_tag"] = chat_params.thinking_start_tag;
1137
+ llama_params["reasoning_budget_end_tags"] = chat_params.thinking_end_tags;
1138
+ llama_params["reasoning_budget_message"] = json_value(body, "reasoning_budget_message", opt.reasoning_budget_message);
1139
+ llama_params["reasoning_control"] = json_value(body, "reasoning_control", false);
1140
+ }
1141
+ }
1142
+
1143
+ // Handle "logprobs" field
1144
+ // TODO: The response format of this option is not yet OAI-compatible, but seems like no one really using it; We may need to fix it in the future
1145
+ if (json_value(body, "logprobs", false)) {
1146
+ if (has_tools && stream) {
1147
+ throw std::invalid_argument("logprobs is not supported with tools + stream");
1148
+ }
1149
+ llama_params["n_probs"] = json_value(body, "top_logprobs", 20);
1150
+ } else if (body.contains("top_logprobs") && !body.at("top_logprobs").is_null()) {
1151
+ throw std::invalid_argument("top_logprobs requires logprobs to be set to true");
1152
+ }
1153
+
1154
+ // Copy remaining properties to llama_params
1155
+ // This allows user to use llama.cpp-specific params like "mirostat", ... via OAI endpoint.
1156
+ // See "launch_slot_with_task()" for a complete list of params supported by llama.cpp
1157
+ for (const auto & item : body.items()) {
1158
+ // Exception: if "n_predict" is present, we overwrite the value specified earlier by "max_tokens"
1159
+ if (!llama_params.contains(item.key()) || item.key() == "n_predict") {
1160
+ llama_params[item.key()] = item.value();
1161
+ }
1162
+ }
1163
+
1164
+ return llama_params;
1165
+ }
1166
+
1167
+ json format_embeddings_response_oaicompat(
1168
+ const json & request,
1169
+ const std::string & model_name,
1170
+ const json & embeddings,
1171
+ bool use_base64) {
1172
+ json data = json::array();
1173
+ int32_t n_tokens = 0;
1174
+ int i = 0;
1175
+ for (const auto & elem : embeddings) {
1176
+ json embedding_obj;
1177
+
1178
+ if (use_base64) {
1179
+ const auto& vec = json_value(elem, "embedding", json::array()).get<std::vector<float>>();
1180
+ const char* data_ptr = reinterpret_cast<const char*>(vec.data());
1181
+ size_t data_size = vec.size() * sizeof(float);
1182
+ embedding_obj = {
1183
+ {"embedding", base64::encode(data_ptr, data_size)},
1184
+ {"index", i++},
1185
+ {"object", "embedding"},
1186
+ {"encoding_format", "base64"}
1187
+ };
1188
+ } else {
1189
+ embedding_obj = {
1190
+ {"embedding", json_value(elem, "embedding", json::array())},
1191
+ {"index", i++},
1192
+ {"object", "embedding"}
1193
+ };
1194
+ }
1195
+ data.push_back(embedding_obj);
1196
+
1197
+ n_tokens += json_value(elem, "tokens_evaluated", 0);
1198
+ }
1199
+
1200
+ json res = json {
1201
+ {"model", json_value(request, "model", model_name)},
1202
+ {"object", "list"},
1203
+ {"usage", json {
1204
+ {"prompt_tokens", n_tokens},
1205
+ {"total_tokens", n_tokens}
1206
+ }},
1207
+ {"data", data}
1208
+ };
1209
+
1210
+ return res;
1211
+ }
1212
+
1213
+ json format_response_rerank(
1214
+ const json & request,
1215
+ const std::string & model_name,
1216
+ const json & ranks,
1217
+ bool is_tei_format,
1218
+ std::vector<std::string> & texts,
1219
+ int top_n) {
1220
+ int32_t n_tokens = 0;
1221
+ bool return_text = is_tei_format && json_value(request, "return_text", false);
1222
+ std::vector<json> elements; // Temporary vector to hold unsorted elements
1223
+ std::string score_label = is_tei_format ? "score" : "relevance_score";
1224
+ for (const auto & rank : ranks) {
1225
+ int index = json_value(rank, "index", 0);
1226
+ json elem = json{
1227
+ {"index", index},
1228
+ {score_label, json_value(rank, "score", 0.0)},
1229
+ };
1230
+ n_tokens += json_value(rank, "tokens_evaluated", 0);
1231
+ if (return_text) {
1232
+ elem["text"] = std::move(texts[index]);
1233
+ }
1234
+ elements.push_back(elem);
1235
+ }
1236
+
1237
+ std::sort(elements.begin(), elements.end(), [score_label](const json& a, const json& b) {
1238
+ return json_value(a, score_label, 0.0) > json_value(b, score_label, 0.0);
1239
+ });
1240
+
1241
+ elements.resize(std::min(top_n, (int)elements.size()));
1242
+ json results = elements;
1243
+
1244
+ if (is_tei_format) return results;
1245
+
1246
+ json res = json{
1247
+ {"model", json_value(request, "model", model_name)},
1248
+ {"object", "list"},
1249
+ {"usage", json{
1250
+ {"prompt_tokens", n_tokens},
1251
+ {"total_tokens", n_tokens}
1252
+ }},
1253
+ {"results", results}
1254
+ };
1255
+
1256
+ return res;
1257
+ }
1258
+
1259
+
1260
+ //
1261
+ // other utils
1262
+ //
1263
+
1264
+ std::vector<llama_token_data> get_token_probabilities(llama_context * ctx, int idx, size_t n_top) {
1265
+ std::vector<llama_token_data> cur;
1266
+
1267
+ const auto * logits = llama_get_logits_ith(ctx, idx);
1268
+ const llama_token * sampled_ids = llama_get_sampled_candidates_ith(ctx, idx);
1269
+
1270
+ const int n_logits = llama_get_sampled_logits_count_ith(ctx, idx);
1271
+
1272
+ cur.resize(n_logits);
1273
+ if (sampled_ids) {
1274
+ for (int i = 0; i < n_logits; i++) {
1275
+ cur[i] = llama_token_data{sampled_ids[i], logits[i], 0.0f};
1276
+ }
1277
+ } else {
1278
+ for (llama_token token_id = 0; token_id < n_logits; token_id++) {
1279
+ cur[token_id] = llama_token_data{token_id, logits[token_id], 0.0f};
1280
+ }
1281
+ }
1282
+
1283
+ // sort tokens by logits (partial: only the leading `n_top` need ordering)
1284
+ if (n_top > cur.size()) {
1285
+ n_top = cur.size();
1286
+ }
1287
+ if (n_top > 0) {
1288
+ std::partial_sort(cur.begin(), cur.begin() + n_top, cur.end(),
1289
+ [](const llama_token_data & a, const llama_token_data & b) {
1290
+ return a.logit > b.logit;
1291
+ });
1292
+ }
1293
+
1294
+ // apply softmax
1295
+ float max_l = -std::numeric_limits<float>::infinity();
1296
+ if (n_top > 0) {
1297
+ max_l = cur[0].logit; // partial_sort guarantees the absolute maximum is at index 0
1298
+ } else {
1299
+ for (const auto & t : cur) {
1300
+ max_l = std::max(max_l, t.logit);
1301
+ }
1302
+ }
1303
+ float cum_sum = 0.0f;
1304
+ for (auto & t : cur) {
1305
+ float p = expf(t.logit - max_l);
1306
+ t.p = p;
1307
+ cum_sum += p;
1308
+ }
1309
+ for (auto & t : cur) {
1310
+ t.p /= cum_sum;
1311
+ }
1312
+
1313
+ return cur;
1314
+ }
1315
+
1316
+ std::string safe_json_to_str(const json & data) {
1317
+ return data.dump(-1, ' ', false, json::error_handler_t::replace);
1318
+ }
1319
+
1320
+ // TODO: reuse llama_detokenize
1321
+ template <class Iter>
1322
+ static std::string tokens_to_str(const llama_vocab * ctx, Iter begin, Iter end) {
1323
+ std::string ret;
1324
+ for (; begin != end; ++begin) {
1325
+ ret += common_token_to_piece(ctx, *begin);
1326
+ }
1327
+
1328
+ return ret;
1329
+ }
1330
+
1331
+ std::string tokens_to_str(llama_context * ctx, const llama_tokens & tokens) {
1332
+ auto model = llama_get_model(ctx);
1333
+ return tokens_to_str(llama_model_get_vocab(model), tokens.begin(), tokens.end());
1334
+ }
1335
+
1336
+ std::string tokens_to_str(const llama_vocab * vocab, const llama_tokens & tokens) {
1337
+ return tokens_to_str(vocab, tokens.begin(), tokens.end());
1338
+ }
1339
+
1340
+ // format incomplete utf-8 multibyte character for output
1341
+ std::string tokens_to_output_formatted_string(const llama_context * ctx, const llama_token token) {
1342
+ std::string out = token == LLAMA_TOKEN_NULL ? "" : common_token_to_piece(ctx, token);
1343
+
1344
+ // if the size is 1 and first bit is 1, meaning it's a partial character
1345
+ // (size > 1 meaning it's already a known token)
1346
+ if (out.size() == 1 && (out[0] & 0x80) == 0x80) {
1347
+ std::stringstream ss;
1348
+ ss << std::hex << (out[0] & 0xff);
1349
+ std::string res(ss.str());
1350
+ out = "byte: \\x" + res;
1351
+ }
1352
+
1353
+ return out;
1354
+ }
1355
+
1356
+ // format server-sent event (SSE), return the formatted string to send
1357
+ // note: if data is a json array, it will be sent as multiple events, one per item
1358
+ std::string format_oai_sse(const json & data) {
1359
+ std::ostringstream ss;
1360
+ auto send_single = [&ss](const json & data) {
1361
+ ss << "data: " <<
1362
+ safe_json_to_str(data) <<
1363
+ "\n\n"; // required by RFC 8895 - A message is terminated by a blank line (two line terminators in a row).
1364
+ };
1365
+
1366
+ if (data.is_array()) {
1367
+ for (const auto & item : data) {
1368
+ send_single(item);
1369
+ }
1370
+ } else {
1371
+ send_single(data);
1372
+ }
1373
+
1374
+ return ss.str();
1375
+ }
1376
+
1377
+ std::string format_oai_resp_sse(const json & data) {
1378
+ std::ostringstream ss;
1379
+ auto send_single = [&ss](const json & event_obj) {
1380
+ ss << "event: " << event_obj.at("event").get<std::string>() << "\n";
1381
+ ss << "data: " << safe_json_to_str(event_obj.at("data")) << "\n\n";
1382
+ };
1383
+
1384
+ if (data.is_array()) {
1385
+ for (const auto & item : data) {
1386
+ send_single(item);
1387
+ }
1388
+ } else {
1389
+ send_single(data);
1390
+ }
1391
+
1392
+ return ss.str();
1393
+ }
1394
+
1395
+ std::string format_anthropic_sse(const json & data) {
1396
+ std::ostringstream ss;
1397
+
1398
+ auto send_event = [&ss](const json & event_obj) {
1399
+ if (event_obj.contains("event") && event_obj.contains("data")) {
1400
+ ss << "event: " << event_obj.at("event").get<std::string>() << "\n";
1401
+ ss << "data: " << safe_json_to_str(event_obj.at("data")) << "\n\n";
1402
+ } else {
1403
+ ss << "data: " << safe_json_to_str(event_obj) << "\n\n";
1404
+ }
1405
+ };
1406
+
1407
+ if (data.is_array()) {
1408
+ for (const auto & event : data) {
1409
+ send_event(event);
1410
+ }
1411
+ } else {
1412
+ send_event(data);
1413
+ }
1414
+
1415
+ return ss.str();
1416
+ }
1417
+
1418
+ bool is_valid_utf8(const std::string & str) {
1419
+ const unsigned char* bytes = reinterpret_cast<const unsigned char*>(str.data());
1420
+ const unsigned char* end = bytes + str.length();
1421
+
1422
+ while (bytes < end) {
1423
+ if (*bytes <= 0x7F) {
1424
+ // 1-byte sequence (0xxxxxxx)
1425
+ bytes++;
1426
+ } else if ((*bytes & 0xE0) == 0xC0) {
1427
+ // 2-byte sequence (110xxxxx 10xxxxxx)
1428
+ if (end - bytes < 2 || (bytes[1] & 0xC0) != 0x80)
1429
+ return false;
1430
+ bytes += 2;
1431
+ } else if ((*bytes & 0xF0) == 0xE0) {
1432
+ // 3-byte sequence (1110xxxx 10xxxxxx 10xxxxxx)
1433
+ if (end - bytes < 3 || (bytes[1] & 0xC0) != 0x80 || (bytes[2] & 0xC0) != 0x80)
1434
+ return false;
1435
+ bytes += 3;
1436
+ } else if ((*bytes & 0xF8) == 0xF0) {
1437
+ // 4-byte sequence (11110xxx 10xxxxxx 10xxxxxx 10xxxxxx)
1438
+ if (end - bytes < 4 || (bytes[1] & 0xC0) != 0x80 ||
1439
+ (bytes[2] & 0xC0) != 0x80 || (bytes[3] & 0xC0) != 0x80)
1440
+ return false;
1441
+ bytes += 4;
1442
+ } else {
1443
+ // Invalid UTF-8 lead byte
1444
+ return false;
1445
+ }
1446
+ }
1447
+
1448
+ return true;
1449
+ }
1450
+
1451
+ llama_tokens format_prompt_infill(
1452
+ const llama_vocab * vocab,
1453
+ const json & input_prefix,
1454
+ const json & input_suffix,
1455
+ const json & input_extra,
1456
+ const int n_batch,
1457
+ const int n_predict,
1458
+ const int n_ctx,
1459
+ const bool spm_infill,
1460
+ const llama_tokens & tokens_prompt
1461
+ ) {
1462
+ // TODO: optimize this block by reducing memory allocations and movement
1463
+
1464
+ // use FIM repo-level pattern:
1465
+ // ref: https://arxiv.org/pdf/2409.12186
1466
+ //
1467
+ // [FIM_REP]myproject
1468
+ // [FIM_SEP]filename0
1469
+ // extra chunk 0
1470
+ // [FIM_SEP]filename1
1471
+ // extra chunk 1
1472
+ // ...
1473
+ // [FIM_SEP]filename
1474
+ // [FIM_PRE]prefix[FIM_SUF]suffix[FIM_MID]prompt
1475
+ //
1476
+ llama_tokens extra_tokens;
1477
+ extra_tokens.reserve(n_ctx);
1478
+
1479
+ auto tokens_prefix = tokenize_mixed(vocab, input_prefix, false, false);
1480
+ auto tokens_suffix = tokenize_mixed(vocab, input_suffix, false, false);
1481
+
1482
+ if (llama_vocab_fim_rep(vocab) != LLAMA_TOKEN_NULL) {
1483
+ // TODO: make project name an input
1484
+ static const auto k_fim_repo = common_tokenize(vocab, "myproject\n", false, false);
1485
+
1486
+ extra_tokens.push_back(llama_vocab_fim_rep(vocab));
1487
+ extra_tokens.insert(extra_tokens.end(), k_fim_repo.begin(), k_fim_repo.end());
1488
+ }
1489
+ for (const auto & chunk : input_extra) {
1490
+ // { "text": string, "filename": string }
1491
+ const std::string text = json_value(chunk, "text", std::string());
1492
+ const std::string filename = json_value(chunk, "filename", std::string("tmp"));
1493
+
1494
+ if (llama_vocab_fim_sep(vocab) != LLAMA_TOKEN_NULL) {
1495
+ const auto k_fim_file = common_tokenize(vocab, filename + "\n", false, false);
1496
+
1497
+ extra_tokens.insert(extra_tokens.end(), llama_vocab_fim_sep(vocab));
1498
+ extra_tokens.insert(extra_tokens.end(), k_fim_file.begin(), k_fim_file.end());
1499
+ } else {
1500
+ // chunk separator in binary form to avoid confusing the AI
1501
+ static const char k_chunk_prefix_str[] = {0x0a, 0x0a, 0x2d, 0x2d, 0x2d, 0x20, 0x73, 0x6e, 0x69, 0x70, 0x70, 0x65, 0x74, 0x20, 0x2d, 0x2d, 0x2d, 0x0a, 0x0a, 0x00};
1502
+ static const auto k_chunk_prefix_tokens = common_tokenize(vocab, k_chunk_prefix_str, false, false);
1503
+
1504
+ extra_tokens.insert(extra_tokens.end(), k_chunk_prefix_tokens.begin(), k_chunk_prefix_tokens.end());
1505
+ }
1506
+
1507
+ const auto chunk_tokens = common_tokenize(vocab, text, false, false);
1508
+ extra_tokens.insert(extra_tokens.end(), chunk_tokens.begin(), chunk_tokens.end());
1509
+ }
1510
+
1511
+ if (llama_vocab_fim_sep(vocab) != LLAMA_TOKEN_NULL) {
1512
+ // TODO: current filename
1513
+ static const auto k_fim_file = common_tokenize(vocab, "filename\n", false, false);
1514
+
1515
+ extra_tokens.insert(extra_tokens.end(), llama_vocab_fim_sep(vocab));
1516
+ extra_tokens.insert(extra_tokens.end(), k_fim_file.begin(), k_fim_file.end());
1517
+ }
1518
+
1519
+ // for now pick FIM context to fit in a batch (ratio prefix:suffix = 3:1, TODO: configurable?)
1520
+ const int n_prefix_take = std::min<int>(tokens_prefix.size(), 3*(n_batch/4));
1521
+ const int n_suffix_take = std::min<int>(tokens_suffix.size(), std::max<int>(0, (n_batch/4) - (2 + tokens_prompt.size())));
1522
+
1523
+ SRV_DBG("n_prefix_take = %d, n_suffix_take = %d, total = %d\n", n_prefix_take, n_suffix_take, (n_prefix_take + n_suffix_take));
1524
+
1525
+ // fill the rest of the context with extra chunks
1526
+ const int n_extra_take = std::min<int>(std::max<int>(0, n_ctx - (n_batch) - 2*n_predict), extra_tokens.size());
1527
+
1528
+ tokens_prefix.erase(tokens_prefix.begin(), tokens_prefix.begin() + tokens_prefix.size() - n_prefix_take);
1529
+ tokens_suffix.resize(n_suffix_take);
1530
+
1531
+ tokens_prefix.insert(tokens_prefix.begin(), llama_vocab_fim_pre(vocab));
1532
+ tokens_prefix.insert(tokens_prefix.end(), tokens_prompt.begin(), tokens_prompt.end());
1533
+ tokens_suffix.insert(tokens_suffix.begin(), llama_vocab_fim_suf(vocab));
1534
+
1535
+ auto embd_inp = spm_infill ? tokens_suffix : tokens_prefix;
1536
+ auto embd_end = spm_infill ? tokens_prefix : tokens_suffix;
1537
+
1538
+ if (llama_vocab_get_add_bos(vocab)) {
1539
+ embd_inp.insert(embd_inp.begin(), llama_vocab_bos(vocab));
1540
+ }
1541
+
1542
+ SRV_DBG("extra: n_ctx = %d, n_extra_take = %d, n_extra = %d\n", n_ctx, n_extra_take, (int) extra_tokens.size());
1543
+
1544
+ // put the extra context before the FIM prefix
1545
+ embd_inp.insert(embd_inp.begin(), extra_tokens.end() - n_extra_take, extra_tokens.end());
1546
+
1547
+ embd_inp.insert(embd_inp.end(), embd_end.begin(), embd_end.end());
1548
+ embd_inp.push_back(llama_vocab_fim_mid(vocab));
1549
+
1550
+ return embd_inp;
1551
+ }
1552
+
1553
+ server_tokens format_prompt_rerank(
1554
+ const struct llama_model * model,
1555
+ const struct llama_vocab * vocab,
1556
+ mtmd_context * mctx,
1557
+ const std::string & query,
1558
+ const std::string & doc) {
1559
+ server_tokens result = {};
1560
+
1561
+ const char * rerank_prompt = llama_model_chat_template(model, "rerank");
1562
+
1563
+ if (rerank_prompt != nullptr) {
1564
+ std::string prompt = rerank_prompt;
1565
+ string_replace_all(prompt, "{query}" , query);
1566
+ string_replace_all(prompt, "{document}", doc );
1567
+ server_tokens tokens = tokenize_input_subprompt(vocab, mctx, prompt, false, true);
1568
+ result.push_back(tokens);
1569
+ } else {
1570
+ // Get EOS token - use SEP token as fallback if EOS is not available
1571
+ server_tokens query_tokens = tokenize_input_subprompt(vocab, mctx, query, false, false);
1572
+ server_tokens doc_tokens = tokenize_input_subprompt(vocab, mctx, doc, false, false);
1573
+ llama_token eos_token = llama_vocab_eos(vocab);
1574
+ if (eos_token == LLAMA_TOKEN_NULL) {
1575
+ eos_token = llama_vocab_sep(vocab);
1576
+ }
1577
+
1578
+ if (llama_vocab_get_add_bos(vocab)) {
1579
+ result.push_back(llama_vocab_bos(vocab));
1580
+ }
1581
+ result.push_back(query_tokens);
1582
+ if (llama_vocab_get_add_eos(vocab)) {
1583
+ result.push_back(eos_token);
1584
+ }
1585
+ if (llama_vocab_get_add_sep(vocab)) {
1586
+ result.push_back(llama_vocab_sep(vocab));
1587
+ }
1588
+ result.push_back(doc_tokens);
1589
+ if (llama_vocab_get_add_eos(vocab)) {
1590
+ result.push_back(eos_token);
1591
+ }
1592
+ }
1593
+
1594
+ return result;
1595
+ }
tools/server/server-common.h ADDED
@@ -0,0 +1,448 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include "common.h"
4
+ #include "log.h"
5
+ #include "llama.h"
6
+ #include "chat.h"
7
+ #include "mtmd.h"
8
+
9
+ #define JSON_ASSERT GGML_ASSERT
10
+ #include <nlohmann/json.hpp>
11
+
12
+ #include <atomic>
13
+ #include <chrono>
14
+ #include <condition_variable>
15
+ #include <cinttypes>
16
+ #include <functional>
17
+ #include <mutex>
18
+ #include <queue>
19
+ #include <string>
20
+ #include <vector>
21
+
22
+ using json = nlohmann::ordered_json;
23
+
24
+ #define SLT_DBG(slot, fmt, ...) LOG_DBG("slot %12.*s: id %2d | task %d | " fmt, 12, __func__, (slot).id, ((slot).task ? (slot).task->id : -1), __VA_ARGS__)
25
+ #define SLT_TRC(slot, fmt, ...) LOG_TRC("slot %12.*s: id %2d | task %d | " fmt, 12, __func__, (slot).id, ((slot).task ? (slot).task->id : -1), __VA_ARGS__)
26
+ #define SLT_INF(slot, fmt, ...) LOG_INF("slot %12.*s: id %2d | task %d | " fmt, 12, __func__, (slot).id, ((slot).task ? (slot).task->id : -1), __VA_ARGS__)
27
+ #define SLT_WRN(slot, fmt, ...) LOG_WRN("slot %12.*s: id %2d | task %d | " fmt, 12, __func__, (slot).id, ((slot).task ? (slot).task->id : -1), __VA_ARGS__)
28
+ #define SLT_ERR(slot, fmt, ...) LOG_ERR("slot %12.*s: id %2d | task %d | " fmt, 12, __func__, (slot).id, ((slot).task ? (slot).task->id : -1), __VA_ARGS__)
29
+ #define SLT_CNT(slot, fmt, ...) LOG_CNT("" fmt, __VA_ARGS__)
30
+
31
+ #define SRV_DBG(fmt, ...) LOG_DBG("srv %12.*s: " fmt, 12, __func__, __VA_ARGS__)
32
+ #define SRV_TRC(fmt, ...) LOG_TRC("srv %12.*s: " fmt, 12, __func__, __VA_ARGS__)
33
+ #define SRV_INF(fmt, ...) LOG_INF("srv %12.*s: " fmt, 12, __func__, __VA_ARGS__)
34
+ #define SRV_WRN(fmt, ...) LOG_WRN("srv %12.*s: " fmt, 12, __func__, __VA_ARGS__)
35
+ #define SRV_ERR(fmt, ...) LOG_ERR("srv %12.*s: " fmt, 12, __func__, __VA_ARGS__)
36
+ #define SRV_CNT(fmt, ...) LOG_CNT("" fmt, __VA_ARGS__)
37
+
38
+ using raw_buffer = std::vector<uint8_t>;
39
+
40
+ template <typename T>
41
+ static T json_value(const json & body, const std::string & key, const T & default_value) {
42
+ // Fallback null to default value
43
+ if (body.contains(key) && !body.at(key).is_null()) {
44
+ try {
45
+ return body.at(key);
46
+ } catch (NLOHMANN_JSON_NAMESPACE::detail::type_error const & err) {
47
+ LOG_WRN("Wrong type supplied for parameter '%s'. Expected '%s', using default value: %s\n", key.c_str(), json(default_value).type_name(), err.what());
48
+ return default_value;
49
+ }
50
+ } else {
51
+ return default_value;
52
+ }
53
+ }
54
+
55
+ // https://community.openai.com/t/openai-chat-list-of-error-codes-and-types/357791/11
56
+ enum error_type {
57
+ ERROR_TYPE_INVALID_REQUEST,
58
+ ERROR_TYPE_AUTHENTICATION,
59
+ ERROR_TYPE_SERVER,
60
+ ERROR_TYPE_NOT_FOUND,
61
+ ERROR_TYPE_PERMISSION,
62
+ ERROR_TYPE_UNAVAILABLE, // custom error
63
+ ERROR_TYPE_NOT_SUPPORTED, // custom error
64
+ ERROR_TYPE_EXCEED_CONTEXT_SIZE, // custom error
65
+ };
66
+
67
+ // thin wrapper around common_grammar_trigger with (de)serialization functions
68
+ struct server_grammar_trigger {
69
+ common_grammar_trigger value;
70
+
71
+ server_grammar_trigger() = default;
72
+ server_grammar_trigger(const common_grammar_trigger & value) : value(value) {}
73
+ server_grammar_trigger(const json & in) {
74
+ value.type = (common_grammar_trigger_type) in.at("type").get<int>();
75
+ value.value = in.at("value").get<std::string>();
76
+ if (value.type == COMMON_GRAMMAR_TRIGGER_TYPE_TOKEN) {
77
+ value.token = (llama_token) in.at("token").get<int>();
78
+ }
79
+ }
80
+
81
+ json to_json() const {
82
+ json out {
83
+ {"type", (int) value.type},
84
+ {"value", value.value},
85
+ };
86
+ if (value.type == COMMON_GRAMMAR_TRIGGER_TYPE_TOKEN) {
87
+ out["token"] = (int) value.token;
88
+ }
89
+ return out;
90
+ }
91
+ };
92
+
93
+ json format_error_response(const std::string & message, const enum error_type type);
94
+
95
+ //
96
+ // random string / id
97
+ //
98
+
99
+ std::string random_string();
100
+ std::string gen_chatcmplid();
101
+ std::string gen_tool_call_id();
102
+
103
+ // get a random marker; note: each time the server restarts, the marker will be different
104
+ const char * get_media_marker();
105
+
106
+ //
107
+ // lora utils
108
+ //
109
+
110
+ // check whether the given lora set has only aloras activated (empty => false)
111
+ bool lora_all_alora(const std::vector<common_adapter_lora_info> & loras);
112
+
113
+ // if the two sets of loras are different, they require a cache clear unless the
114
+ // change is only from aloras to aloras.
115
+ bool lora_should_clear_cache(
116
+ const std::vector<common_adapter_lora_info> & current,
117
+ const std::vector<common_adapter_lora_info> & next);
118
+
119
+ std::map<int, float> parse_lora_request(const json & data);
120
+
121
+ bool are_lora_equal(
122
+ const std::vector<common_adapter_lora_info> & l1,
123
+ const std::vector<common_adapter_lora_info> & l2);
124
+
125
+ // get the ids of all enabled loras
126
+ std::vector<size_t> lora_get_enabled_ids(const std::vector<common_adapter_lora_info> & loras);
127
+
128
+ //
129
+ // server_tokens
130
+ //
131
+
132
+ /**
133
+ * server_tokens is a helper to manage the input tokens and image for the server.
134
+ * it is made this way to simplify the logic of KV cache management.
135
+ */
136
+ struct server_tokens {
137
+ bool has_mtmd = false;
138
+
139
+ private: // disallow accessing these members directly, risking out-of-sync
140
+
141
+ // map a **start** index in tokens to the image chunk
142
+ // note: the order need to be in-sync with tokens
143
+ std::map<size_t, mtmd::input_chunk_ptr> map_idx_to_media;
144
+
145
+ // list of tokens
146
+ // if the token is LLAMA_TOKEN_NULL, it indicates that this position is occupied by media chunk
147
+ // otherwise, it is a normal text token
148
+ // note: a non-text chunk can occupy multiple tokens (aka memory cells) in the token list
149
+ // note(2): for M-RoPE, an image can occupy different number of pos; do not assume 1-to-1 mapping tokens <-> pos
150
+ llama_tokens tokens;
151
+
152
+ // for ex. with input of 5 text tokens and 2 images (each image occupies 3 tokens and 2 pos):
153
+ // [0] [1] [2] [3] [4] [img0] [img0] [img0] [img1] [img1] [img1]
154
+ // idx 0 1 2 3 4 5 6 7 8 9 10
155
+ // pos 0 1 2 3 4 5 5 5 7 7 7
156
+ // map_idx_to_media will contain: {5, img0}, {8, img1}
157
+
158
+ public:
159
+ server_tokens() = default;
160
+ ~server_tokens() = default;
161
+
162
+ // Prevent copying
163
+ // TODO: server_tokens should be copyable - remove this:
164
+ server_tokens(const server_tokens&) = delete;
165
+ server_tokens& operator=(const server_tokens&) = delete;
166
+
167
+ // Allow moving (usually implicitly generated if members are movable)
168
+ server_tokens(server_tokens&&) = default;
169
+ server_tokens& operator=(server_tokens&&) = default;
170
+
171
+ // Allow accessing elements using [] operator
172
+ llama_token operator[](size_t index) { return tokens[index]; }
173
+ const llama_token& operator[](size_t index) const { return tokens[index]; }
174
+
175
+ server_tokens(mtmd::input_chunks & mtmd_chunks, bool has_mtmd);
176
+ server_tokens(const llama_tokens & tokens, bool has_mtmd);
177
+
178
+ // for debugging
179
+ std::string str() const;
180
+
181
+ // the next position after n_tokens. if n_tokens < 0, return the next position after all tokens.
182
+ llama_pos pos_next(int64_t n_tokens = -1) const;
183
+
184
+ // number of tokens with position < max_pos
185
+ size_t size_up_to_pos(llama_pos max_pos) const;
186
+
187
+ const mtmd::input_chunk_ptr & find_chunk(size_t idx) const;
188
+
189
+ // find next media chunk after idx
190
+ // returns a pair of pointer to the chunk (nullptr if not found) and its start index in tokens
191
+ std::pair<const mtmd::input_chunk_ptr *, size_t> find_next_media_chunk(size_t idx) const;
192
+
193
+ void push_back(llama_token tok);
194
+
195
+ // will create a copy of the chunk if it contains non-text data
196
+ void push_back(const mtmd_input_chunk * chunk);
197
+
198
+ // appends server tokens, updates the media map. copies media chunks.
199
+ void push_back(server_tokens & tokens);
200
+
201
+ // for compatibility with context shift and prompt truncation
202
+ void insert(const llama_tokens & inp_tokens);
203
+
204
+ // for compatibility with speculative decoding, ctx shift, slot save/load
205
+ const llama_tokens & get_tokens() const;
206
+
207
+ llama_tokens get_text_tokens() const;
208
+
209
+ // for compatibility with speculative decoding
210
+ void set_token(llama_pos pos, llama_token id);
211
+
212
+ size_t size() const { return tokens.size(); }
213
+
214
+ bool empty() const { return tokens.empty(); }
215
+
216
+ // true if the sequence actually contains image/audio chunks.
217
+ bool has_media() const { return !map_idx_to_media.empty(); }
218
+
219
+ void clear() {
220
+ map_idx_to_media.clear();
221
+ tokens.clear();
222
+ }
223
+
224
+ void keep_first(size_t n);
225
+
226
+ std::string detokenize(const llama_context * ctx, bool special) const;
227
+
228
+ size_t get_common_prefix(const server_tokens & b) const;
229
+
230
+ // split the tokens into message spans, skipping over media chunks
231
+ common_chat_msg_spans find_message_spans(const common_chat_msg_delimiters & delims) const;
232
+
233
+ // make sure all text tokens are within the vocab range
234
+ bool validate(const struct llama_context * ctx) const;
235
+
236
+ server_tokens clone() const;
237
+ };
238
+
239
+
240
+ //
241
+ // tokenizer and input processing utils
242
+ //
243
+
244
+ bool json_is_array_of_numbers(const json & data);
245
+
246
+ // is array having BOTH numbers & strings?
247
+ bool json_is_array_of_mixed_numbers_strings(const json & data);
248
+
249
+ // does array have any individual integers/tokens?
250
+ bool json_is_array_and_contains_numbers(const json & data);
251
+
252
+ // get value by path(key1 / key2)
253
+ json json_get_nested_values(const std::vector<std::string> & paths, const json & js);
254
+
255
+ /**
256
+ * this handles 2 cases:
257
+ * - only string, example: "string"
258
+ * - mixed string and tokens, example: [12, 34, "string", 56, 78]
259
+ */
260
+ llama_tokens tokenize_mixed(const llama_vocab * vocab, const json & json_prompt, bool add_special, bool parse_special);
261
+
262
+ // return the last index of character that can form a valid string
263
+ // if the last character is potentially cut in half, return the index before the cut
264
+ // if validate_utf8(text) == text.size(), then the whole text is valid utf8
265
+ size_t validate_utf8(const std::string& text);
266
+
267
+ // process mtmd prompt, return the server_tokens containing both text tokens and media chunks
268
+ // if is_placeholder is true, the media chunk will be treated as placeholder for counting tokens; the output tokens are not usable for actual inference (e.g. for submitting a task to server_queue)
269
+ server_tokens process_mtmd_prompt(mtmd_context * mctx, const std::string & prompt, const std::vector<raw_buffer> & files, bool is_placeholder = false);
270
+
271
+ /**
272
+ * break the input "prompt" object into multiple prompt if needed, then tokenize them
273
+ * this supports these cases:
274
+ * - "prompt": "string"
275
+ * - "prompt": [12, 34, 56]
276
+ * - "prompt": [12, 34, "string", 56, 78]
277
+ * - "prompt": { "prompt_string": "string", "multimodal_data": [ "base64" ] }
278
+ * and multiple prompts (multi-tasks):
279
+ * - "prompt": ["string1", "string2"]
280
+ * - "prompt": ["string1", [12, 34, 56]]
281
+ * - "prompt": [[12, 34, 56], [78, 90, 12]]
282
+ * - "prompt": [[12, 34, "string", 56, 78], [12, 34, 56], { "prompt_string": "string", "multimodal_data": [ "base64" ]}]
283
+ */
284
+ std::vector<server_tokens> tokenize_input_prompts(
285
+ const llama_vocab * vocab,
286
+ mtmd_context * mctx,
287
+ const json & json_prompt,
288
+ bool add_special,
289
+ bool parse_special);
290
+
291
+ //
292
+ // OAI utils
293
+ //
294
+
295
+ // global server parameters for chat formatting / parsing
296
+ struct server_chat_params {
297
+ bool use_jinja;
298
+ bool prefill_assistant;
299
+ common_reasoning_format reasoning_format;
300
+ std::map<std::string, std::string> chat_template_kwargs; // mapping key --> json value
301
+ common_chat_templates_ptr tmpls;
302
+ bool allow_image;
303
+ bool allow_audio;
304
+ bool allow_video;
305
+ bool enable_thinking = true;
306
+ int reasoning_budget = -1;
307
+ std::string reasoning_budget_message;
308
+ std::string media_path;
309
+ bool force_pure_content = false;
310
+ };
311
+
312
+ // used by /completions endpoint
313
+ json oaicompat_completion_params_parse(const json & body);
314
+
315
+ // used by /chat/completions endpoint
316
+ json oaicompat_chat_params_parse(
317
+ json & body, /* openai api json semantics */
318
+ const server_chat_params & opt,
319
+ std::vector<raw_buffer> & out_files);
320
+
321
+ // TODO: move it to server-task.cpp
322
+ json format_embeddings_response_oaicompat(
323
+ const json & request,
324
+ const std::string & model_name,
325
+ const json & embeddings,
326
+ bool use_base64 = false);
327
+
328
+ // TODO: move it to server-task.cpp
329
+ json format_response_rerank(
330
+ const json & request,
331
+ const std::string & model_name,
332
+ const json & ranks,
333
+ bool is_tei_format,
334
+ std::vector<std::string> & texts,
335
+ int top_n);
336
+
337
+ //
338
+ // other utils
339
+ //
340
+
341
+ std::vector<llama_token_data> get_token_probabilities(llama_context * ctx, int idx, size_t n_top);
342
+
343
+ std::string safe_json_to_str(const json & data);
344
+
345
+ std::string tokens_to_str(llama_context * ctx, const llama_tokens & tokens);
346
+ std::string tokens_to_str(const llama_vocab * vocab, const llama_tokens & tokens);
347
+
348
+ // format incomplete utf-8 multibyte character for output
349
+ std::string tokens_to_output_formatted_string(const llama_context * ctx, const llama_token token);
350
+
351
+ // format server-sent event (SSE), return the formatted string to send
352
+ // note: if data is a json array, it will be sent as multiple events, one per item
353
+ std::string format_oai_sse(const json & data);
354
+
355
+ std::string format_oai_resp_sse(const json & data);
356
+
357
+ // format Anthropic-style SSE with event types
358
+ std::string format_anthropic_sse(const json & data);
359
+
360
+ bool is_valid_utf8(const std::string & str);
361
+
362
+ //
363
+ // formatting output responses
364
+ // TODO: move these to server-task.cpp
365
+ //
366
+
367
+ llama_tokens format_prompt_infill(
368
+ const llama_vocab * vocab,
369
+ const json & input_prefix,
370
+ const json & input_suffix,
371
+ const json & input_extra,
372
+ const int n_batch,
373
+ const int n_predict,
374
+ const int n_ctx,
375
+ const bool spm_infill,
376
+ const llama_tokens & tokens_prompt);
377
+
378
+ // format rerank task: [BOS]query[EOS][SEP]doc[EOS].
379
+ server_tokens format_prompt_rerank(
380
+ const struct llama_model * model,
381
+ const struct llama_vocab * vocab,
382
+ mtmd_context * mctx,
383
+ const std::string & query,
384
+ const std::string & doc);
385
+
386
+ // simple implementation of a pipe
387
+ // used for streaming data between threads
388
+ template<typename T>
389
+ struct server_pipe {
390
+ std::mutex mutex;
391
+ std::condition_variable cv;
392
+ std::queue<T> queue;
393
+ std::atomic<bool> writer_closed{false};
394
+ std::atomic<bool> reader_closed{false};
395
+
396
+ // 0 = unbounded (default)
397
+ // > 0, write() drops the oldest item once the queue is full
398
+ size_t max_size = 0;
399
+
400
+ void close_write() {
401
+ writer_closed.store(true, std::memory_order_relaxed);
402
+ cv.notify_all();
403
+ }
404
+
405
+ void close_read() {
406
+ reader_closed.store(true, std::memory_order_relaxed);
407
+ cv.notify_all();
408
+ }
409
+
410
+ // close_on_stop = true: should_stop means the reader is gone for good, so the writer is told the pipe is broken.
411
+ // close_on_stop = false: should_stop is a per-read deadline and further reads still come, so the pipe stays usable.
412
+ bool read(T & output, const std::function<bool()> & should_stop, bool close_on_stop = true) {
413
+ std::unique_lock<std::mutex> lk(mutex);
414
+ constexpr auto poll_interval = std::chrono::milliseconds(500);
415
+ while (true) {
416
+ if (!queue.empty()) {
417
+ output = std::move(queue.front());
418
+ queue.pop();
419
+ return true;
420
+ }
421
+ if (writer_closed.load()) {
422
+ return false; // clean EOF
423
+ }
424
+ if (should_stop && should_stop()) { // a null should_stop means "never stop"
425
+ if (close_on_stop) {
426
+ close_read(); // signal broken pipe to writer
427
+ }
428
+ return false; // cancelled / deadline reached
429
+ }
430
+ cv.wait_for(lk, poll_interval);
431
+ }
432
+ }
433
+
434
+ bool write(T && data) {
435
+ std::lock_guard<std::mutex> lk(mutex);
436
+ if (reader_closed.load()) {
437
+ return false; // broken pipe
438
+ }
439
+ if (max_size > 0) {
440
+ while (queue.size() >= max_size) {
441
+ queue.pop(); // drop oldest to stay bounded
442
+ }
443
+ }
444
+ queue.push(std::move(data));
445
+ cv.notify_one();
446
+ return true;
447
+ }
448
+ };
tools/server/server-context.cpp ADDED
The diff for this file is too large to render. See raw diff
 
tools/server/server-context.h ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include "server-http.h"
4
+ #include "server-task.h"
5
+ #include "server-queue.h"
6
+
7
+ #include <nlohmann/json_fwd.hpp>
8
+
9
+ #include <cstddef>
10
+ #include <memory>
11
+ #include <set>
12
+
13
+ struct server_context_impl; // private implementation
14
+
15
+ struct server_context_meta {
16
+ std::string build_info;
17
+ std::string model_name;
18
+ std::set<std::string> model_aliases;
19
+ std::set<std::string> model_tags;
20
+ std::string model_path;
21
+ bool has_mtmd;
22
+ bool has_inp_image;
23
+ bool has_inp_audio;
24
+ bool has_inp_video;
25
+ json json_ui_settings;
26
+ int slot_n_ctx;
27
+ enum llama_pooling_type pooling_type;
28
+
29
+ // chat params
30
+ server_chat_params & chat_params;
31
+ std::map<std::string, bool> chat_template_caps;
32
+
33
+ // tokens
34
+ std::string bos_token_str;
35
+ std::string eos_token_str;
36
+ llama_token fim_pre_token;
37
+ llama_token fim_sub_token;
38
+ llama_token fim_mid_token;
39
+ llama_token fim_pad_token;
40
+ llama_token fim_rep_token;
41
+ llama_token fim_sep_token;
42
+
43
+ // sampling
44
+ std::vector<llama_logit_bias> logit_bias_eog;
45
+
46
+ // model meta
47
+ enum llama_vocab_type model_vocab_type;
48
+ int32_t model_vocab_n_tokens;
49
+ int32_t model_n_ctx_train;
50
+ int32_t model_n_embd_inp;
51
+ uint64_t model_n_params;
52
+ uint64_t model_size;
53
+ std::string model_ftype;
54
+ };
55
+
56
+ enum server_state {
57
+ SERVER_STATE_DOWNLOADING,
58
+ SERVER_STATE_LOADING,
59
+ SERVER_STATE_READY,
60
+ SERVER_STATE_SLEEPING,
61
+ };
62
+
63
+ static std::string server_state_to_str(server_state state) {
64
+ switch (state) {
65
+ case SERVER_STATE_DOWNLOADING: return "downloading";
66
+ case SERVER_STATE_LOADING: return "loading";
67
+ case SERVER_STATE_READY: return "ready";
68
+ case SERVER_STATE_SLEEPING: return "sleeping";
69
+ default: GGML_ASSERT(false && "invalid server_state");
70
+ }
71
+ }
72
+
73
+ static server_state server_state_from_str(const std::string & str) {
74
+ if (str == "downloading") return SERVER_STATE_DOWNLOADING;
75
+ if (str == "loading") return SERVER_STATE_LOADING;
76
+ if (str == "ready") return SERVER_STATE_READY;
77
+ if (str == "sleeping") return SERVER_STATE_SLEEPING;
78
+ GGML_ASSERT(false && "invalid server_state string");
79
+ }
80
+
81
+ using server_state_callback_t = std::function<void(server_state, json /* payload */)>;
82
+
83
+ struct server_context {
84
+ std::unique_ptr<server_context_impl> impl;
85
+
86
+ server_context();
87
+ ~server_context();
88
+
89
+ // load the model and initialize llama_context
90
+ // returns true on success
91
+ bool load_model(common_params & params);
92
+
93
+ // this function will block main thread until termination
94
+ void start_loop();
95
+
96
+ // terminate main loop (will unblock start_loop)
97
+ void terminate();
98
+
99
+ // get the underlaying llama_context, can return nullptr if sleeping
100
+ // not thread-safe, should only be used from the main thread
101
+ llama_context * get_llama_context() const;
102
+
103
+ // get a new response reader, used by CLI application
104
+ server_response_reader get_response_reader();
105
+
106
+ // get server metadata (read-only), can only be called after load_model()
107
+ // not thread-safe, should only be used from the main thread
108
+ server_context_meta get_meta() const;
109
+
110
+ // note: must be set before load_model() is called
111
+ void set_state_callback(server_state_callback_t callback);
112
+ };
113
+
114
+
115
+ // forward declarations
116
+ struct server_res_generator;
117
+
118
+ struct server_routes {
119
+ server_routes(const common_params & params, server_context & ctx_server);
120
+
121
+ void init_routes();
122
+
123
+ // note: this is not thread-safe and can only when ctx_http.is_ready is false
124
+ void update_meta(const server_context & ctx_server) {
125
+ this->meta = std::make_unique<server_context_meta>(ctx_server.get_meta());
126
+ }
127
+
128
+ // handlers using lambda function, so that they can capture `this` without `std::bind`
129
+ // they won't be called until ctx_http.is_ready is set to true
130
+ server_http_context::handler_t get_health;
131
+ server_http_context::handler_t get_metrics;
132
+ server_http_context::handler_t get_slots;
133
+ server_http_context::handler_t post_slots;
134
+ server_http_context::handler_t get_props;
135
+ server_http_context::handler_t post_props;
136
+ server_http_context::handler_t post_infill;
137
+ server_http_context::handler_t post_completions;
138
+ server_http_context::handler_t post_completions_oai;
139
+ server_http_context::handler_t post_chat_completions;
140
+ server_http_context::handler_t post_chat_completions_tok;
141
+ server_http_context::handler_t post_control;
142
+ server_http_context::handler_t post_responses_oai;
143
+ server_http_context::handler_t post_responses_tok_oai;
144
+ server_http_context::handler_t post_transcriptions_oai;
145
+ server_http_context::handler_t post_anthropic_messages;
146
+ server_http_context::handler_t post_anthropic_count_tokens;
147
+ server_http_context::handler_t post_apply_template;
148
+ server_http_context::handler_t get_models;
149
+ server_http_context::handler_t post_tokenize;
150
+ server_http_context::handler_t post_detokenize;
151
+ server_http_context::handler_t post_embeddings;
152
+ server_http_context::handler_t post_embeddings_oai;
153
+ server_http_context::handler_t post_rerank;
154
+ server_http_context::handler_t get_lora_adapters;
155
+ server_http_context::handler_t post_lora_adapters;
156
+
157
+ // to be used in router mode
158
+ json get_model_info() const;
159
+
160
+ private:
161
+ std::unique_ptr<server_res_generator> handle_completions_impl(
162
+ const server_http_req & req,
163
+ server_task_type type,
164
+ const json & data,
165
+ const std::vector<raw_buffer> & files,
166
+ task_response_type res_type);
167
+ std::unique_ptr<server_res_generator> handle_slots_save(const server_http_req & req, int id_slot);
168
+ std::unique_ptr<server_res_generator> handle_slots_restore(const server_http_req & req, int id_slot);
169
+ std::unique_ptr<server_res_generator> handle_slots_erase(const server_http_req &, int id_slot);
170
+ std::unique_ptr<server_res_generator> handle_embeddings_impl(const server_http_req & req, task_response_type res_type);
171
+ std::unique_ptr<server_res_generator> handle_count_tokens(const llama_vocab * vocab, mtmd_context * mctx, const server_http_req & req, task_response_type res_type);
172
+
173
+ // using unique_ptr to allow late initialization of const
174
+ std::unique_ptr<const server_context_meta> meta;
175
+
176
+ const common_params & params;
177
+ const server_context_impl & ctx_server;
178
+
179
+ server_queue & queue_tasks;
180
+ server_response & queue_results;
181
+ std::unique_ptr<server_res_generator> create_response(bool bypass_sleep = false);
182
+ };
tools/server/server-cors-proxy.h ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include "common.h"
4
+ #include "http.h"
5
+
6
+ #include <string>
7
+ #include <unordered_set>
8
+ #include <list>
9
+ #include <map>
10
+ #include <algorithm>
11
+ #include <cctype>
12
+
13
+ #include "server-http.h"
14
+
15
+ static std::string proxy_header_to_lower(std::string header) {
16
+ std::transform(header.begin(), header.end(), header.begin(), [](unsigned char c) {
17
+ return std::tolower(c);
18
+ });
19
+ return header;
20
+ }
21
+
22
+ static server_http_res_ptr proxy_request(const server_http_req & req, std::string method) {
23
+ std::string target_url = req.get_param("url");
24
+ common_http_url parsed_url = common_http_parse_url(target_url);
25
+
26
+ if (parsed_url.host.empty()) {
27
+ throw std::runtime_error("invalid target URL: missing host");
28
+ }
29
+
30
+ if (parsed_url.path.empty()) {
31
+ parsed_url.path = "/";
32
+ }
33
+
34
+ if (!parsed_url.password.empty()) {
35
+ throw std::runtime_error("authentication in target URL is not supported");
36
+ }
37
+
38
+ if (parsed_url.scheme != "http" && parsed_url.scheme != "https") {
39
+ throw std::runtime_error("unsupported URL scheme in target URL: " + parsed_url.scheme);
40
+ }
41
+
42
+ SRV_INF("proxying %s request to %s://%s:%i%s\n", method.c_str(), parsed_url.scheme.c_str(), common_http_format_host(parsed_url.host).c_str(), parsed_url.port, parsed_url.path.c_str());
43
+
44
+ std::map<std::string, std::string> headers;
45
+ const std::string proxy_header_prefix = "x-llama-server-proxy-header-";
46
+ for (auto [key, value] : req.headers) {
47
+ const std::string lowered_key = proxy_header_to_lower(key);
48
+ if (!string_starts_with(lowered_key, proxy_header_prefix)) {
49
+ continue;
50
+ }
51
+
52
+ auto new_key = key.substr(proxy_header_prefix.size());
53
+ if (new_key.empty()) {
54
+ continue;
55
+ }
56
+
57
+ headers[new_key] = value;
58
+ }
59
+
60
+ auto proxy = std::make_unique<server_http_proxy>(
61
+ method,
62
+ parsed_url.scheme,
63
+ parsed_url.host,
64
+ parsed_url.port,
65
+ parsed_url.path,
66
+ headers,
67
+ req.body,
68
+ req.files,
69
+ req.should_stop,
70
+ 600, // timeout_read (default to 10 minutes)
71
+ 600 // timeout_write (default to 10 minutes)
72
+ );
73
+
74
+ return proxy;
75
+ }
76
+
77
+ static server_http_context::handler_t proxy_handler_post = [](const server_http_req & req) -> server_http_res_ptr {
78
+ return proxy_request(req, "POST");
79
+ };
80
+
81
+ static server_http_context::handler_t proxy_handler_get = [](const server_http_req & req) -> server_http_res_ptr {
82
+ return proxy_request(req, "GET");
83
+ };
tools/server/server-http.cpp ADDED
@@ -0,0 +1,833 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "common.h"
2
+ #include "http.h"
3
+ #include "server-http.h"
4
+ #include "server-common.h"
5
+ #include "ui.h"
6
+
7
+ #include <cpp-httplib/httplib.h>
8
+
9
+ #include <functional>
10
+ #include <future>
11
+ #include <memory>
12
+ #include <string>
13
+ #include <thread>
14
+
15
+ //
16
+ // HTTP implementation using cpp-httplib
17
+ //
18
+
19
+ class server_http_context::Impl {
20
+ public:
21
+ std::unique_ptr<httplib::Server> srv;
22
+ };
23
+
24
+ server_http_context::server_http_context()
25
+ : pimpl(std::make_unique<Impl>())
26
+ {}
27
+
28
+ server_http_context::~server_http_context() = default;
29
+
30
+ static void log_server_request(const httplib::Request & req, const httplib::Response & res) {
31
+ // skip logging requests that are regularly sent, to avoid log spam
32
+ if (req.path == "/health"
33
+ || req.path == "/v1/health"
34
+ || req.path == "/models"
35
+ || req.path == "/v1/models"
36
+ || req.path == "/props"
37
+ || req.path == "/metrics"
38
+ ) {
39
+ return;
40
+ }
41
+
42
+ // reminder: this function is not covered by httplib's exception handler; if someone does more complicated stuff, think about wrapping it in try-catch
43
+
44
+ SRV_TRC("done request: %s %s %s %d\n", req.method.c_str(), req.path.c_str(), req.remote_addr.c_str(), res.status);
45
+
46
+ SRV_DBG("request: %s\n", req.body.c_str());
47
+ SRV_DBG("response: %s\n", res.body.c_str());
48
+ }
49
+
50
+ // returns true if the Origin header value's host is localhost / 127.0.0.1 / ::1 (any port)
51
+ static bool origin_is_localhost(const std::string & origin) {
52
+ try {
53
+ const std::string host = common_http_parse_url(origin).host;
54
+ return host == "localhost" || host == "127.0.0.1" || host == "::1";
55
+ } catch (const std::exception &) {
56
+ return false;
57
+ }
58
+ }
59
+
60
+ // For Google Cloud Platform deployment compatibility
61
+ struct gcp_params {
62
+ bool enabled;
63
+ std::string path_health;
64
+ std::string path_predict;
65
+ int port;
66
+
67
+ // Ref: https://docs.cloud.google.com/vertex-ai/docs/predictions/custom-container-requirements#aip-variables
68
+ gcp_params() {
69
+ enabled = getenv("AIP_MODE", "") == "PREDICTION";
70
+ path_health = getenv("AIP_HEALTH_ROUTE", "", true); // default: using the route defined in server.cpp
71
+ path_predict = getenv("AIP_PREDICT_ROUTE", "/predict", true);
72
+ port = std::stoi(getenv("AIP_HTTP_PORT", "8080"));
73
+ }
74
+
75
+ static std::string getenv(const char * name, const std::string & default_value, bool ensure_leading_slash = false) {
76
+ const auto * value = std::getenv(name);
77
+ if (value == nullptr || value[0] == '\0') {
78
+ return default_value;
79
+ }
80
+ std::string val = value;
81
+ if (ensure_leading_slash && !val.empty() && val[0] != '/') {
82
+ val.insert(val.begin(), '/');
83
+ }
84
+ return val;
85
+ }
86
+ };
87
+
88
+ bool server_http_context::init(const common_params & params) {
89
+ const gcp_params gcp;
90
+
91
+ path_prefix = params.api_prefix;
92
+ port = params.port;
93
+ hostname = params.hostname;
94
+
95
+ if (gcp.enabled) {
96
+ SRV_TRC("Google Cloud Platform compat: health route = %s, predict route = %s, port = %d\n", gcp.path_health.c_str(), gcp.path_predict.c_str(), gcp.port);
97
+
98
+ if (port != gcp.port) {
99
+ SRV_WRN("Google Cloud Platform compat: overriding server port %d with AIP_HTTP_PORT %d\n", port, gcp.port);
100
+ }
101
+
102
+ port = gcp.port;
103
+ }
104
+
105
+ auto & srv = pimpl->srv;
106
+
107
+ #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
108
+ if (!params.ssl_file_key.empty() && !params.ssl_file_cert.empty()) {
109
+ SRV_TRC("running with SSL: key = %s, cert = %s\n", params.ssl_file_key.c_str(), params.ssl_file_cert.c_str());
110
+ srv = std::make_unique<httplib::SSLServer>(
111
+ params.ssl_file_cert.c_str(), params.ssl_file_key.c_str()
112
+ );
113
+ is_ssl = true;
114
+ } else {
115
+ SRV_TRC("%s", "running without SSL\n");
116
+ srv = std::make_unique<httplib::Server>();
117
+ }
118
+ #else
119
+ if (params.ssl_file_key != "" && params.ssl_file_cert != "") {
120
+ SRV_ERR("%s", "the server is built without SSL support\n");
121
+ return false;
122
+ }
123
+ srv.reset(new httplib::Server());
124
+ #endif
125
+
126
+ srv->set_default_headers({{"Server", "llama.cpp"}});
127
+ // srv->set_logger(log_server_request); // TODO @ngxson : this is too spamy, no very useful; improve it in the future
128
+ srv->set_exception_handler([](const httplib::Request &, httplib::Response & res, const std::exception_ptr & ep) {
129
+ // this is fail-safe; exceptions should already handled by `ex_wrapper`
130
+
131
+ std::string message;
132
+ try {
133
+ std::rethrow_exception(ep);
134
+ } catch (const std::exception & e) {
135
+ message = e.what();
136
+ } catch (...) {
137
+ message = "Unknown Exception";
138
+ }
139
+
140
+ res.status = 500;
141
+ res.set_content(message, "text/plain");
142
+ SRV_ERR("got exception: %s\n", message.c_str());
143
+ });
144
+
145
+ srv->set_error_handler([](const httplib::Request &, httplib::Response & res) {
146
+ if (res.status == 404) {
147
+ res.set_content(
148
+ safe_json_to_str(json {
149
+ {"error", {
150
+ {"message", "File Not Found"},
151
+ {"type", "not_found_error"},
152
+ {"code", 404}
153
+ }}
154
+ }),
155
+ "application/json; charset=utf-8"
156
+ );
157
+ }
158
+ // for other error codes, we skip processing here because it's already done by res->error()
159
+ });
160
+
161
+ // set timeouts and change hostname and port
162
+ srv->set_read_timeout (params.timeout_read);
163
+ srv->set_write_timeout(params.timeout_write);
164
+ srv->set_socket_options([reuse_port = params.reuse_port](const socket_t sock) {
165
+ httplib::set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
166
+ if (reuse_port) {
167
+ #ifdef SO_REUSEPORT
168
+ httplib::set_socket_opt(sock, SOL_SOCKET, SO_REUSEPORT, 1);
169
+ #else
170
+ SRV_WRN("%s", "SO_REUSEPORT is not supported\n");
171
+ #endif
172
+ }
173
+ });
174
+
175
+ if (params.api_keys.size() == 1) {
176
+ const auto key = params.api_keys[0];
177
+ const std::string substr = key.substr(std::max(static_cast<int>(key.length() - 4), 0));
178
+ SRV_TRC("api_keys: ****%s\n", substr.c_str());
179
+ } else if (params.api_keys.size() > 1) {
180
+ SRV_TRC("api_keys: %zu keys loaded\n", params.api_keys.size());
181
+ }
182
+
183
+ //
184
+ // Middlewares
185
+ //
186
+
187
+ // Frontend paths - all embedded UI assets
188
+ static const std::unordered_set<std::string> frontend_paths = []() {
189
+ std::unordered_set<std::string> paths { "/" };
190
+ for (const llama_ui_asset & a : llama_ui_get_assets()) {
191
+ paths.insert("/" + a.name);
192
+ }
193
+ return paths;
194
+ }();
195
+
196
+ // Public endpoints - API routes plus all embedded UI assets
197
+ static const std::unordered_set<std::string> get_public_endpoints = []() {
198
+ std::unordered_set<std::string> endpoints {
199
+ "/health",
200
+ "/v1/health",
201
+ "/models",
202
+ "/v1/models",
203
+ };
204
+ endpoints.insert(frontend_paths.begin(), frontend_paths.end());
205
+ return endpoints;
206
+ }();
207
+
208
+ auto middleware_validate_api_key = [api_keys = params.api_keys](const httplib::Request & req, httplib::Response & res) {
209
+ // If API key is not set, skip validation
210
+ if (api_keys.empty()) {
211
+ return true;
212
+ }
213
+
214
+ // If path is public or a UI asset, skip validation
215
+ if (get_public_endpoints.count(req.path)) {
216
+ return true;
217
+ }
218
+
219
+ // Check for API key in the Authorization header
220
+ std::string req_api_key = req.get_header_value("Authorization");
221
+ if (req_api_key.empty()) {
222
+ // retry with anthropic header
223
+ req_api_key = req.get_header_value("X-Api-Key");
224
+ }
225
+
226
+ // remove the "Bearer " prefix if needed
227
+ static std::string prefix = "Bearer ";
228
+ if (req_api_key.substr(0, prefix.size()) == prefix) {
229
+ req_api_key = req_api_key.substr(prefix.size());
230
+ }
231
+
232
+ // validate the API key
233
+ if (std::find(api_keys.begin(), api_keys.end(), req_api_key) != api_keys.end()) {
234
+ return true; // API key is valid
235
+ }
236
+
237
+ // API key is invalid or not provided
238
+ res.status = 401;
239
+ res.set_content(
240
+ safe_json_to_str(json {
241
+ {"error", {
242
+ {"message", "Invalid API Key"},
243
+ {"type", "authentication_error"},
244
+ {"code", 401}
245
+ }}
246
+ }),
247
+ "application/json; charset=utf-8"
248
+ );
249
+
250
+ SRV_WRN("%s", "unauthorized: Invalid API Key\n");
251
+
252
+ return false;
253
+ };
254
+
255
+ auto middleware_server_state = [this](const httplib::Request & req, httplib::Response & res) {
256
+ if (!is_ready.load()) {
257
+ if (frontend_paths.count(req.path)) {
258
+ return true; // frontend asset, allow it to load and show "loading"
259
+ }
260
+ // no endpoints are allowed to be accessed when the server is not ready
261
+ // this is to prevent any data races or inconsistent states
262
+ res.status = 503;
263
+ res.set_content(
264
+ safe_json_to_str(json {
265
+ {"error", {
266
+ {"message", "Loading model"},
267
+ {"type", "unavailable_error"},
268
+ {"code", 503}
269
+ }}
270
+ }),
271
+ "application/json; charset=utf-8"
272
+ );
273
+ return false;
274
+ }
275
+ return true;
276
+ };
277
+
278
+ // register server middlewares
279
+ srv->set_pre_routing_handler([&params, middleware_validate_api_key, middleware_server_state](const httplib::Request & req, httplib::Response & res) {
280
+ if (params.cors_credentials && params.cors_origins == "*") {
281
+ // special case: echo back the Origin header to allow any origin to access the server with credentials
282
+ res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
283
+ } else if (params.cors_origins == "localhost") {
284
+ // special case: only reflect the Origin header if it is a localhost origin
285
+ std::string origin = req.get_header_value("Origin");
286
+ if (!origin.empty() && origin_is_localhost(origin)) {
287
+ res.set_header("Access-Control-Allow-Origin", origin);
288
+ } else if (!origin.empty()) {
289
+ SRV_WRN("(CORS) skip non-localhost origin: %s\n", origin.c_str());
290
+ }
291
+ } else {
292
+ res.set_header("Access-Control-Allow-Origin", params.cors_origins);
293
+ }
294
+ // If this is OPTIONS request, skip validation because browsers don't include Authorization header
295
+ if (req.method == "OPTIONS") {
296
+ res.set_header("Access-Control-Allow-Credentials", params.cors_credentials ? "true" : "false");
297
+ res.set_header("Access-Control-Allow-Methods", params.cors_methods);
298
+ res.set_header("Access-Control-Allow-Headers", params.cors_headers);
299
+ res.set_content("", "text/html"); // blank response, no data
300
+ return httplib::Server::HandlerResponse::Handled; // skip further processing
301
+ }
302
+ if (!middleware_server_state(req, res)) {
303
+ return httplib::Server::HandlerResponse::Handled;
304
+ }
305
+ if (!middleware_validate_api_key(req, res)) {
306
+ return httplib::Server::HandlerResponse::Handled;
307
+ }
308
+ return httplib::Server::HandlerResponse::Unhandled;
309
+ });
310
+
311
+ auto n_threads_http = params.n_threads_http;
312
+ if (n_threads_http < 1) {
313
+ // +4 threads for monitoring, health and some threads reserved for MCP and other tasks in the future
314
+ n_threads_http = std::max(params.n_parallel + 4, static_cast<int32_t>(std::thread::hardware_concurrency() - 1));
315
+ }
316
+ SRV_TRC("using %d threads for HTTP server\n", n_threads_http);
317
+ srv->new_task_queue = [n_threads_http] {
318
+ // spawn n_threads_http fixed thread (always alive), while allow up to 1024 max possible additional threads
319
+ // when n_threads_http is used, server will create new "dynamic" threads that will be destroyed after processing each request
320
+ // ref: https://github.com/yhirose/cpp-httplib/pull/2368
321
+ const auto max_threads = static_cast<size_t>(n_threads_http + 1024);
322
+ return new httplib::ThreadPool(n_threads_http, max_threads);
323
+ };
324
+
325
+ //
326
+ // Web UI setup
327
+ //
328
+
329
+ // Use new `params.ui` field (backed by old `params.webui` for compat)
330
+ if (!params.ui) {
331
+ SRV_INF("%s", "The UI is disabled\n");
332
+ SRV_INF("%s", "Use --ui/--no-ui (or deprecated --webui/--no-webui) to enable/disable\n");
333
+ } else {
334
+ // register static assets routes
335
+ if (!params.public_path.empty()) {
336
+ // Set the base directory for serving static files
337
+ if (const auto is_found = srv->set_mount_point(params.api_prefix + "/", params.public_path); !is_found) {
338
+ SRV_ERR("static assets path not found: %s\n", params.public_path.c_str());
339
+ return false;
340
+ }
341
+ } else {
342
+ #if defined(LLAMA_UI_HAS_ASSETS)
343
+ static auto handle_gzip_header = [](const httplib::Request & req, httplib::Response & res) {
344
+ if (!llama_ui_use_gzip()) {
345
+ // no gzip build, skip
346
+ return true;
347
+ }
348
+ if (req.get_header_value("Accept-Encoding").find("gzip") == std::string::npos) {
349
+ res.status = 415; // unsupported media type
350
+ res.set_content("Error: gzip is not supported by this browser", "text/plain");
351
+ return false;
352
+ } else {
353
+ res.set_header("Content-Encoding", "gzip");
354
+ }
355
+ return true;
356
+ };
357
+
358
+ auto serve_asset_cached = [](const std::string & name, bool isolation) {
359
+ return [name, isolation](const httplib::Request & req, httplib::Response & res) {
360
+ if (!handle_gzip_header(req, res)) {
361
+ return true; // returns error message
362
+ }
363
+ const llama_ui_asset * a = llama_ui_find_asset(name);
364
+ if (!a) { res.status = 404; return false; }
365
+ res.set_header("ETag", a->etag);
366
+ if (const std::string & inm = req.get_header_value("If-None-Match");
367
+ !inm.empty() && (inm == a->etag || inm == std::string("W/") + a->etag)) {
368
+ res.status = 304;
369
+ return false;
370
+ }
371
+ if (isolation) {
372
+ res.set_header("Cross-Origin-Embedder-Policy", "require-corp");
373
+ res.set_header("Cross-Origin-Opener-Policy", "same-origin");
374
+ }
375
+ res.set_header("Cache-Control", "public, max-age=31536000, immutable");
376
+ res.set_content(reinterpret_cast<const char*>(a->data), a->size, a->type.c_str());
377
+ return false;
378
+ };
379
+ };
380
+
381
+ auto serve_asset_nocache = [](const std::string & name) {
382
+ return [name](const httplib::Request & req, httplib::Response & res) {
383
+ if (!handle_gzip_header(req, res)) {
384
+ return true; // returns error message
385
+ }
386
+ const llama_ui_asset * a = llama_ui_find_asset(name);
387
+ if (!a) {
388
+ res.status = 404;
389
+ return false;
390
+ }
391
+ res.set_header("Cache-Control", "no-cache");
392
+ res.set_content(reinterpret_cast<const char*>(a->data), a->size, a->type.c_str());
393
+ return false;
394
+ };
395
+ };
396
+
397
+ // main index file
398
+ srv->Get(params.api_prefix + "/", serve_asset_cached("index.html", true));
399
+ srv->Get(params.api_prefix + "/index.html", serve_asset_cached("index.html", true));
400
+
401
+ // All remaining assets registered directly from the embedded asset table.
402
+ // PWA revalidation files (sw.js, manifest, version.json) use no-cache;
403
+ // everything else is immutable.
404
+ static const std::unordered_set<std::string> no_cache_names = {
405
+ "sw.js",
406
+ "manifest.webmanifest",
407
+ "_app/version.json",
408
+ "build.json"
409
+ };
410
+
411
+ for (const auto & a : llama_ui_get_assets()) {
412
+ if (a.name == "index.html") continue; // served at "/" and "/index.html" above
413
+ if (no_cache_names.count(a.name)) {
414
+ SRV_DBG("serve nocache for %s\n", a.name.c_str());
415
+ srv->Get(params.api_prefix + "/" + a.name, serve_asset_nocache(a.name));
416
+ } else {
417
+ srv->Get(params.api_prefix + "/" + a.name, serve_asset_cached(a.name, false));
418
+ }
419
+ }
420
+
421
+ #endif
422
+ }
423
+ }
424
+ return true;
425
+ }
426
+
427
+ bool server_http_context::start() {
428
+ // Bind and listen
429
+
430
+ const auto & srv = pimpl->srv;
431
+ auto was_bound = false;
432
+ auto is_sock = false;
433
+ if (string_ends_with(std::string(hostname), ".sock")) {
434
+ is_sock = true;
435
+ SRV_TRC("%s", "setting address family to AF_UNIX\n");
436
+ srv->set_address_family(AF_UNIX);
437
+ // bind_to_port requires a second arg, any value other than 0 should
438
+ // simply get ignored
439
+ was_bound = srv->bind_to_port(hostname, 8080);
440
+ } else {
441
+ SRV_TRC("%s", "binding port with default address family\n");
442
+ // bind HTTP listen port
443
+ if (port == 0) {
444
+ const auto bound_port = srv->bind_to_any_port(hostname);
445
+ was_bound = (bound_port >= 0);
446
+ if (was_bound) {
447
+ port = bound_port;
448
+ }
449
+ } else {
450
+ was_bound = srv->bind_to_port(hostname, port);
451
+ }
452
+ }
453
+
454
+ if (!was_bound) {
455
+ SRV_ERR("couldn't bind HTTP server socket, hostname: %s, port: %d\n", hostname.c_str(), port);
456
+ return false;
457
+ }
458
+
459
+ // run the HTTP server in a thread
460
+ thread = std::thread([this] { pimpl->srv->listen_after_bind(); });
461
+ srv->wait_until_ready();
462
+
463
+ listening_address = is_sock ? string_format("unix://%s", hostname.c_str())
464
+ : string_format("%s://%s:%d", is_ssl ? "https" : "http", common_http_format_host(hostname).c_str(), port);
465
+ return true;
466
+ }
467
+
468
+ void server_http_context::stop() const {
469
+ if (pimpl->srv) {
470
+ pimpl->srv->stop();
471
+ }
472
+ }
473
+
474
+ static void set_headers(httplib::Response & res, const std::map<std::string, std::string> & headers) {
475
+ for (const auto & [key, value] : headers) {
476
+ res.set_header(key, value);
477
+ }
478
+ }
479
+
480
+ // percent-decode a path component (%XX). path params arrive raw from httplib, unlike query
481
+ // params, so a conv id like "conv::model" sent as "conv%3A%3Amodel" must be decoded here to
482
+ // match the value the client put in the X-Conversation-Id header
483
+ static std::string decode_path_component(const std::string & in) {
484
+ std::string out;
485
+ out.reserve(in.size());
486
+ for (size_t i = 0; i < in.size(); i++) {
487
+ if (in[i] == '%' && i + 2 < in.size()) {
488
+ auto hex = [](char c) -> int {
489
+ if (c >= '0' && c <= '9') return c - '0';
490
+ if (c >= 'a' && c <= 'f') return c - 'a' + 10;
491
+ if (c >= 'A' && c <= 'F') return c - 'A' + 10;
492
+ return -1;
493
+ };
494
+ int hi = hex(in[i + 1]);
495
+ int lo = hex(in[i + 2]);
496
+ if (hi >= 0 && lo >= 0) {
497
+ out.push_back(char((hi << 4) | lo));
498
+ i += 2;
499
+ continue;
500
+ }
501
+ }
502
+ out.push_back(in[i]);
503
+ }
504
+ return out;
505
+ }
506
+
507
+ static std::map<std::string, std::string> get_params(const httplib::Request & req) {
508
+ std::map<std::string, std::string> params;
509
+ for (const auto & [key, value] : req.params) {
510
+ params[key] = value;
511
+ }
512
+ for (const auto & [key, value] : req.path_params) {
513
+ params[key] = decode_path_component(value);
514
+ }
515
+ return params;
516
+ }
517
+
518
+ static std::map<std::string, std::string> get_headers(const httplib::Request & req) {
519
+ std::map<std::string, std::string> headers;
520
+ for (const auto & [key, value] : req.headers) {
521
+ headers[key] = value;
522
+ }
523
+ return headers;
524
+ }
525
+
526
+ static std::string build_query_string(const httplib::Request & req) {
527
+ std::string qs;
528
+ for (const auto & [key, value] : req.params) {
529
+ if (!qs.empty()) {
530
+ qs += '&';
531
+ }
532
+ qs += httplib::encode_query_component(key) + "=" + httplib::encode_query_component(value);
533
+ }
534
+ return qs;
535
+ }
536
+
537
+ // using unique_ptr for request to allow safe capturing in lambdas
538
+ using server_http_req_ptr = std::unique_ptr<server_http_req>;
539
+
540
+ static void process_handler_response(server_http_req_ptr && request, server_http_res_ptr & response, httplib::Response & res) {
541
+ if (response->is_stream()) {
542
+ res.status = response->status;
543
+ // Tell Nginx to not buffer any streamed response
544
+ response->headers["X-Accel-Buffering"] = "no";
545
+ set_headers(res, response->headers);
546
+ const std::string content_type = response->content_type;
547
+ // convert to shared_ptr as both chunked_content_provider() and on_complete() need to use it
548
+ std::shared_ptr<server_http_req> q_ptr = std::move(request);
549
+ std::shared_ptr<server_http_res> r_ptr = std::move(response);
550
+
551
+ const auto chunked_content_provider = [response = r_ptr](size_t, httplib::DataSink & sink) -> bool {
552
+ std::string chunk;
553
+ const bool has_next = response->next(chunk);
554
+ if (!chunk.empty()) {
555
+ if (!sink.write(chunk.data(), chunk.size())) {
556
+ return false;
557
+ }
558
+ SRV_DBG("http: streamed chunk: %s\n", chunk.c_str());
559
+ }
560
+ if (!has_next) {
561
+ sink.done();
562
+ SRV_DBG("%s", "http: stream ended\n");
563
+ }
564
+ return has_next;
565
+ };
566
+ const auto on_complete = [request = q_ptr, response = r_ptr](bool) mutable {
567
+ response->on_complete();
568
+ response.reset();
569
+ request.reset();
570
+ };
571
+ res.set_chunked_content_provider(content_type, chunked_content_provider, on_complete);
572
+ } else {
573
+ res.status = response->status;
574
+ set_headers(res, response->headers);
575
+ res.set_content(response->data, response->content_type);
576
+ response->on_complete();
577
+ }
578
+ }
579
+
580
+ void server_http_context::get(const std::string & path, const server_http_context::handler_t & handler) const {
581
+ handlers.emplace(path, handler);
582
+ pimpl->srv->Get(path_prefix + path, [handler](const httplib::Request & req, httplib::Response & res) {
583
+ server_http_req_ptr request = std::make_unique<server_http_req>(server_http_req{
584
+ get_params(req),
585
+ get_headers(req),
586
+ req.path,
587
+ build_query_string(req),
588
+ req.body,
589
+ {},
590
+ req.is_connection_closed
591
+ });
592
+ server_http_res_ptr response = handler(*request);
593
+ process_handler_response(std::move(request), response, res);
594
+ });
595
+ }
596
+
597
+ void server_http_context::post(const std::string & path, const server_http_context::handler_t & handler) const {
598
+ handlers.emplace(path, handler);
599
+ pimpl->srv->Post(path_prefix + path, [handler](const httplib::Request & req, httplib::Response & res) {
600
+ std::string body = req.body;
601
+ std::map<std::string, uploaded_file> files;
602
+
603
+ if (req.is_multipart_form_data()) {
604
+ // translate text fields to a JSON object and use it as the body
605
+ json form_json = json::object();
606
+ for (const auto & [key, field] : req.form.fields) {
607
+ if (form_json.contains(key)) {
608
+ // if the key already exists, convert it to an array
609
+ if (!form_json[key].is_array()) {
610
+ json existing_value = form_json[key];
611
+ form_json[key] = json::array({existing_value});
612
+ }
613
+ form_json[key].push_back(field.content);
614
+ } else {
615
+ form_json[key] = field.content;
616
+ }
617
+ }
618
+ body = form_json.dump();
619
+
620
+ // populate files from multipart form
621
+ for (const auto & [key, file] : req.form.files) {
622
+ files[key] = uploaded_file{
623
+ raw_buffer(file.content.begin(), file.content.end()),
624
+ file.filename,
625
+ file.content_type,
626
+ };
627
+ }
628
+ }
629
+
630
+ server_http_req_ptr request = std::make_unique<server_http_req>(server_http_req{
631
+ get_params(req),
632
+ get_headers(req),
633
+ req.path,
634
+ build_query_string(req),
635
+ body,
636
+ std::move(files),
637
+ req.is_connection_closed
638
+ });
639
+ server_http_res_ptr response = handler(*request);
640
+ process_handler_response(std::move(request), response, res);
641
+ });
642
+ }
643
+
644
+ void server_http_context::del(const std::string & path, const server_http_context::handler_t & handler) const {
645
+ handlers.emplace(path, handler);
646
+ pimpl->srv->Delete(path_prefix + path, [handler](const httplib::Request & req, httplib::Response & res) {
647
+ server_http_req_ptr request = std::make_unique<server_http_req>(server_http_req{
648
+ get_params(req),
649
+ get_headers(req),
650
+ req.path,
651
+ build_query_string(req),
652
+ req.body,
653
+ {},
654
+ req.is_connection_closed
655
+ });
656
+ server_http_res_ptr response = handler(*request);
657
+ process_handler_response(std::move(request), response, res);
658
+ });
659
+ }
660
+
661
+ //
662
+ // Vertex AI Prediction protocol (AIP_PREDICT_ROUTE)
663
+ // https://cloud.google.com/vertex-ai/docs/predictions/custom-container-requirements
664
+ //
665
+
666
+ // Derives the camelCase @requestFormat alias for a registered path.
667
+ // e.g. "/v1/chat/completions" -> "chatCompletions", "/apply-template" -> "applyTemplate"
668
+ static std::string path_to_gcp_format(const std::string & path) {
669
+ std::string s = path;
670
+ if (s.size() > 3 && s[0] == '/' && s[1] == 'v' && s[2] == '1') {
671
+ s = s.substr(3);
672
+ }
673
+ if (!s.empty() && s[0] == '/') {
674
+ s = s.substr(1);
675
+ }
676
+ std::string result;
677
+ bool cap = false;
678
+ for (unsigned char c : s) {
679
+ if (c == ':') break; // stop before path parameters
680
+ if (c == '/' || c == '-' || c == '_') {
681
+ cap = true;
682
+ } else {
683
+ result += static_cast<char>(cap ? std::toupper(c) : c);
684
+ cap = false;
685
+ }
686
+ }
687
+ return result;
688
+ }
689
+
690
+ static json parse_gcp_predict_response(const server_http_res_ptr & res) {
691
+ if (res == nullptr) {
692
+ throw std::runtime_error("empty response from internal handler");
693
+ }
694
+ if (res->is_stream()) {
695
+ throw std::invalid_argument("predict route does not support streaming responses");
696
+ }
697
+ if (res->data.empty()) {
698
+ return nullptr;
699
+ }
700
+ try {
701
+ return json::parse(res->data);
702
+ } catch (...) {
703
+ return res->data;
704
+ }
705
+ }
706
+
707
+ void server_http_context::register_gcp_compat() const {
708
+ const gcp_params gcp;
709
+
710
+ if (!gcp.enabled) {
711
+ // do nothing
712
+ return;
713
+ }
714
+
715
+ if (handlers.count(gcp.path_predict)) {
716
+ SRV_ERR("AIP_PREDICT_ROUTE=%s conflicts with an existing llama-server route\n", gcp.path_predict.c_str());
717
+ exit(1);
718
+ }
719
+
720
+ // camelCase alias -> canonical path (first registration wins on collision)
721
+ // e.g. "chatCompletions" -> "/v1/chat/completions"
722
+ std::unordered_map<std::string, std::string> alias_to_path;
723
+ for (const auto & [path, _] : handlers) {
724
+ alias_to_path.emplace(path_to_gcp_format(path), path);
725
+ }
726
+
727
+ if (!gcp.path_health.empty()) {
728
+ const auto health_handler = handlers.find("/health");
729
+ GGML_ASSERT(health_handler != handlers.end());
730
+ get(gcp.path_health, health_handler->second);
731
+ }
732
+
733
+ post(gcp.path_predict, [this, alias_to_path = std::move(alias_to_path)](const server_http_req & req) -> server_http_res_ptr {
734
+ static const auto build_error = [](const std::string & message, error_type type) -> json {
735
+ return json {{"error", format_error_response(message, type)}};
736
+ };
737
+
738
+ json data;
739
+ try {
740
+ data = json::parse(req.body);
741
+ } catch (const std::exception & e) {
742
+ auto res = std::make_unique<server_http_res>();
743
+ res->status = 400;
744
+ res->data = safe_json_to_str({{"error", format_error_response(e.what(), ERROR_TYPE_INVALID_REQUEST)}});
745
+ return res;
746
+ }
747
+ if (!data.is_object()) {
748
+ auto res = std::make_unique<server_http_res>();
749
+ res->status = 400;
750
+ res->data = safe_json_to_str({{"error", format_error_response("request body must be a JSON object", ERROR_TYPE_INVALID_REQUEST)}});
751
+ return res;
752
+ }
753
+ if (!data.contains("instances") || !data.at("instances").is_array()) {
754
+ auto res = std::make_unique<server_http_res>();
755
+ res->status = 400;
756
+ res->data = safe_json_to_str({{"error", format_error_response("request body must include an array field named instances", ERROR_TYPE_INVALID_REQUEST)}});
757
+ return res;
758
+ }
759
+
760
+ const json & instances = data.at("instances");
761
+ static const size_t MAX_INSTANCES = 128;
762
+ if (instances.size() > MAX_INSTANCES) {
763
+ auto res = std::make_unique<server_http_res>();
764
+ res->status = 400;
765
+ res->data = safe_json_to_str({{"error", format_error_response("instances array exceeds maximum size of " + std::to_string(MAX_INSTANCES), ERROR_TYPE_INVALID_REQUEST)}});
766
+ return res;
767
+ }
768
+
769
+ std::vector<std::future<json>> futures;
770
+ futures.reserve(instances.size());
771
+
772
+ for (const auto & instance : instances) {
773
+ futures.push_back(std::async(std::launch::async, [this, &req, &alias_to_path, instance]() -> json {
774
+ if (!instance.is_object()) {
775
+ return build_error("each instance must be a JSON object", ERROR_TYPE_INVALID_REQUEST);
776
+ }
777
+ if (!instance.contains("@requestFormat") || !instance.at("@requestFormat").is_string()) {
778
+ return build_error("each instance must include a string @requestFormat", ERROR_TYPE_INVALID_REQUEST);
779
+ }
780
+
781
+ try {
782
+ json payload = instance;
783
+ const std::string format = payload.at("@requestFormat").get<std::string>();
784
+ payload.erase("@requestFormat");
785
+
786
+ if (payload.contains("stream")) {
787
+ SRV_WRN("%s", "ignoring client-provided stream field in instance, streaming is not supported in predict route\n");
788
+ payload["stream"] = false;
789
+ }
790
+
791
+ // accept both camelCase aliases (e.g. "chatCompletions") and direct paths
792
+ std::string dispatch_path;
793
+ auto it_alias = alias_to_path.find(format);
794
+ if (it_alias != alias_to_path.end()) {
795
+ dispatch_path = it_alias->second;
796
+ } else if (handlers.count(format)) {
797
+ dispatch_path = format;
798
+ } else {
799
+ return build_error("no handler registered for @requestFormat: " + format, ERROR_TYPE_INVALID_REQUEST);
800
+ }
801
+
802
+ const server_http_req internal_req {
803
+ req.params,
804
+ req.headers,
805
+ path_prefix + dispatch_path,
806
+ req.query_string,
807
+ payload.dump(),
808
+ {},
809
+ req.should_stop,
810
+ };
811
+
812
+ server_http_res_ptr internal_res = handlers.at(dispatch_path)(internal_req);
813
+ return parse_gcp_predict_response(internal_res);
814
+ } catch (const std::invalid_argument & e) {
815
+ return build_error(e.what(), ERROR_TYPE_INVALID_REQUEST);
816
+ } catch (const std::exception & e) {
817
+ return build_error(e.what(), ERROR_TYPE_SERVER);
818
+ } catch (...) {
819
+ return build_error("unknown error", ERROR_TYPE_SERVER);
820
+ }
821
+ }));
822
+ }
823
+
824
+ json predictions = json::array();
825
+ for (auto & future : futures) {
826
+ predictions.push_back(future.get());
827
+ }
828
+
829
+ auto res = std::make_unique<server_http_res>();
830
+ res->data = safe_json_to_str({{"predictions", predictions}});
831
+ return res;
832
+ });
833
+ }
tools/server/server-http.h ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <atomic>
4
+ #include <functional>
5
+ #include <map>
6
+ #include <memory>
7
+ #include <string>
8
+ #include <thread>
9
+ #include <vector>
10
+ #include <cstdint>
11
+ #include <unordered_map>
12
+
13
+ struct common_params;
14
+
15
+ // generator-like API for HTTP response generation
16
+ // this object response with one of the 2 modes:
17
+ // 1) normal response: `data` contains the full response body
18
+ // 2) streaming response: each call to next(output) generates the next chunk
19
+ // when next(output) returns false, no more data after the current chunk
20
+ // note: some chunks can be empty, in which case no data is sent for that chunk
21
+ struct server_http_res {
22
+ std::string content_type = "application/json; charset=utf-8";
23
+ int status = 200;
24
+ std::string data;
25
+ std::map<std::string, std::string> headers;
26
+
27
+ std::function<bool(std::string &)> next = nullptr;
28
+ bool is_stream() const {
29
+ return next != nullptr;
30
+ }
31
+
32
+ // fired before req and res are destroyed
33
+ virtual void on_complete() {}
34
+
35
+ virtual ~server_http_res() = default;
36
+ };
37
+
38
+ // unique pointer, used by set_chunked_content_provider
39
+ // httplib requires the stream provider to be stored in heap
40
+ using server_http_res_ptr = std::unique_ptr<server_http_res>;
41
+ using raw_buffer = std::vector<uint8_t>;
42
+
43
+ struct uploaded_file {
44
+ raw_buffer data;
45
+ std::string filename;
46
+ std::string content_type;
47
+ };
48
+
49
+ struct server_http_req {
50
+ std::map<std::string, std::string> params; // path_params + query_params
51
+ std::map<std::string, std::string> headers; // used by MCP proxy
52
+ std::string path;
53
+ std::string query_string; // query parameters string (e.g. "action=save")
54
+ std::string body;
55
+ std::map<std::string, uploaded_file> files; // used for file uploads (form data)
56
+ const std::function<bool()> & should_stop;
57
+
58
+ std::string get_param(const std::string & key, const std::string & def = "") const {
59
+ auto it = params.find(key);
60
+ if (it != params.end()) {
61
+ return it->second;
62
+ }
63
+ return def;
64
+ }
65
+ };
66
+
67
+ struct server_http_context {
68
+ class Impl;
69
+ std::unique_ptr<Impl> pimpl;
70
+
71
+ std::thread thread; // server thread
72
+ std::atomic<bool> is_ready = false;
73
+
74
+ // note: the handler should never throw exceptions
75
+ using handler_t = std::function<server_http_res_ptr(const server_http_req & req)>;
76
+ mutable std::unordered_map<std::string, handler_t> handlers;
77
+
78
+ std::string path_prefix;
79
+ std::string hostname;
80
+ int port = 8080;
81
+ bool is_ssl = false;
82
+
83
+ server_http_context();
84
+ ~server_http_context();
85
+
86
+ bool init(const common_params & params);
87
+ bool start();
88
+ void stop() const;
89
+
90
+ void get(const std::string & path, const handler_t & handler) const;
91
+ void post(const std::string & path, const handler_t & handler) const;
92
+ void del(const std::string & path, const handler_t & handler) const;
93
+
94
+ // Register the Google Cloud Platform (Vertex AI) compat (AIP_PREDICT_ROUTE env var, or /predict)
95
+ // Must be called AFTER all other API routes are registered
96
+ void register_gcp_compat() const;
97
+
98
+ // for debugging
99
+ std::string listening_address;
100
+ };
tools/server/server-mcp.cpp ADDED
@@ -0,0 +1,820 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "server-mcp.h"
2
+
3
+ #include "subproc.h"
4
+
5
+ #include <atomic>
6
+ #include <chrono>
7
+ #include <cstdio>
8
+ #include <fstream>
9
+ #include <functional>
10
+ #include <sstream>
11
+ #include <thread>
12
+
13
+ #if defined(_WIN32)
14
+ # include <io.h>
15
+ # include <windows.h>
16
+ #else
17
+ # include <errno.h>
18
+ # include <fcntl.h>
19
+ # include <poll.h>
20
+ # include <unistd.h>
21
+ extern char ** environ;
22
+ #endif
23
+
24
+ // read NDJSON lines from a child pipe, calling on_line per line until `running` clears, EOF/error, or on_line returns false.
25
+ // polled, not blocking: a grandchild can inherit the pipe's write end and hold it open (terminate() kills only the direct child), so a blocking read would hang teardown on an EOF that never comes.
26
+ static void mcp_pump_ndjson(FILE * f, std::atomic<bool> & running,
27
+ const std::function<bool(std::string &&)> & on_line) {
28
+ if (!f) {
29
+ return;
30
+ }
31
+ const int poll_ms = 50;
32
+ const size_t max_line = 8 * 1024 * 1024; // drop any single NDJSON line larger than this, so a child that never emits '\n' can't grow buf without bound
33
+ #if defined(_WIN32)
34
+ HANDLE h = (HANDLE) _get_osfhandle(_fileno(f));
35
+ #else
36
+ int fd = fileno(f);
37
+ int fl = fcntl(fd, F_GETFL, 0);
38
+ if (fl >= 0) {
39
+ fcntl(fd, F_SETFL, fl | O_NONBLOCK);
40
+ }
41
+ #endif
42
+ std::string buf;
43
+ bool skipping = false; // discarding an over-long line until its terminating newline
44
+ char chunk[4096];
45
+ while (running.load()) {
46
+ size_t n = 0;
47
+ #if defined(_WIN32)
48
+ DWORD avail = 0;
49
+ if (!PeekNamedPipe(h, NULL, 0, NULL, &avail, NULL)) {
50
+ break; // pipe broken / child gone
51
+ }
52
+ if (avail == 0) {
53
+ std::this_thread::sleep_for(std::chrono::milliseconds(poll_ms));
54
+ continue;
55
+ }
56
+ DWORD to_read = avail < (DWORD) sizeof(chunk) ? avail : (DWORD) sizeof(chunk);
57
+ DWORD got = 0;
58
+ if (!ReadFile(h, chunk, to_read, &got, NULL) || got == 0) {
59
+ break;
60
+ }
61
+ n = (size_t) got;
62
+ #else
63
+ struct pollfd pfd;
64
+ pfd.fd = fd;
65
+ pfd.events = POLLIN;
66
+ pfd.revents = 0;
67
+ int pr = poll(&pfd, 1, poll_ms);
68
+ if (pr < 0) {
69
+ if (errno == EINTR) {
70
+ continue;
71
+ }
72
+ break;
73
+ }
74
+ if (pr == 0) {
75
+ continue; // timeout -> re-check running
76
+ }
77
+ if (pfd.revents & (POLLERR | POLLNVAL)) {
78
+ break;
79
+ }
80
+ ssize_t r = read(fd, chunk, sizeof(chunk));
81
+ if (r < 0) {
82
+ if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) {
83
+ continue;
84
+ }
85
+ break;
86
+ }
87
+ if (r == 0) {
88
+ break; // EOF: child (and any pipe writers) closed the stream
89
+ }
90
+ n = (size_t) r;
91
+ #endif
92
+ buf.append(chunk, n);
93
+
94
+ // resync after an over-long, unterminated line: discard bytes until the next newline
95
+ if (skipping) {
96
+ size_t nl = buf.find('\n');
97
+ if (nl == std::string::npos) {
98
+ if (buf.size() > max_line) {
99
+ buf.clear(); // stay bounded while waiting for a terminator
100
+ }
101
+ continue;
102
+ }
103
+ buf.erase(0, nl + 1);
104
+ skipping = false;
105
+ }
106
+
107
+ size_t pos;
108
+ while ((pos = buf.find('\n')) != std::string::npos) {
109
+ std::string line = buf.substr(0, pos);
110
+ buf.erase(0, pos + 1);
111
+ if (!line.empty() && line.back() == '\r') {
112
+ line.pop_back();
113
+ }
114
+ if (line.empty()) {
115
+ continue;
116
+ }
117
+ if (!on_line(std::move(line))) {
118
+ return;
119
+ }
120
+ }
121
+
122
+ // a partial line already larger than the cap and still no newline: drop it to avoid unbounded growth
123
+ if (buf.size() > max_line) {
124
+ SRV_WRN("MCP: dropping oversized line (> %zu bytes) from child pipe\n", max_line);
125
+ buf.clear();
126
+ skipping = true;
127
+ }
128
+ }
129
+ }
130
+
131
+ //
132
+ // server_mcp_server_config
133
+ //
134
+
135
+ std::vector<server_mcp_server_config> server_mcp_server_config::parse_from_json(const std::string & json_str) {
136
+ return parse_cursor_format(json::parse(json_str));
137
+ }
138
+
139
+ std::vector<server_mcp_server_config> server_mcp_server_config::parse_cursor_format(const json & j) {
140
+ std::vector<server_mcp_server_config> result;
141
+
142
+ if (!j.contains("mcpServers") || !j.at("mcpServers").is_object()) {
143
+ return result;
144
+ }
145
+
146
+ for (const auto & [name, cfg] : j.at("mcpServers").items()) {
147
+ server_mcp_server_config sc;
148
+ sc.name = name;
149
+ sc.command = cfg.value("command", std::string());
150
+ sc.cwd = cfg.value("cwd", std::string());
151
+ sc.timeout_ms = cfg.value("timeout_ms", sc.timeout_ms);
152
+
153
+ if (cfg.contains("args") && cfg.at("args").is_array()) {
154
+ for (const auto & a : cfg.at("args")) {
155
+ sc.args.push_back(a.get<std::string>());
156
+ }
157
+ }
158
+ if (cfg.contains("env") && cfg.at("env").is_object()) {
159
+ for (const auto & [k, v] : cfg.at("env").items()) {
160
+ sc.env[k] = v.get<std::string>();
161
+ }
162
+ }
163
+
164
+ if (sc.command.empty()) {
165
+ SRV_WRN("MCP server '%s' has no command, skipping\n", name.c_str());
166
+ continue;
167
+ }
168
+ result.push_back(std::move(sc));
169
+ }
170
+
171
+ return result;
172
+ }
173
+
174
+
175
+ //
176
+ // server_mcp_transport
177
+ //
178
+
179
+ static constexpr const char * MCP_PROTOCOL_VERSION = "2024-11-05";
180
+
181
+ static std::string rpc_error_message(const json & resp) {
182
+ if (resp.contains("error")) {
183
+ const json & e = resp.at("error");
184
+ if (e.is_object()) {
185
+ return e.value("message", "unknown error");
186
+ }
187
+ if (e.is_string()) {
188
+ return e.get<std::string>();
189
+ }
190
+ }
191
+ return "unknown error";
192
+ }
193
+
194
+ // normalize an MCP tools/call result to the /tools contract (see README-dev.md):
195
+ // concat text parts of result.content[], and surface an isError result
196
+ static json mcp_result_to_response(const json & result) {
197
+ std::string text;
198
+ if (result.contains("content") && result.at("content").is_array()) {
199
+ for (const auto & part : result.at("content")) {
200
+ if (part.is_object() && part.value("type", "") == "text") {
201
+ if (!text.empty()) {
202
+ text += "\n";
203
+ }
204
+ text += part.value("text", "");
205
+ }
206
+ }
207
+ }
208
+ if (result.is_object() && result.value("isError", false)) {
209
+ return {{"error", text.empty() ? "MCP tool returned an error" : text}};
210
+ }
211
+ return {{"plain_text_response", text}};
212
+ }
213
+
214
+ json server_mcp_transport::send_rpc(const json & request, const std::function<bool()> & should_stop) {
215
+ if (!to_server.write(request.dump())) {
216
+ return {{"error", {{"code", -32603}, {"message", "transport closed"}}}};
217
+ }
218
+
219
+ const bool has_id = request.contains("id");
220
+ const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms);
221
+ auto stop = [&]() {
222
+ return (should_stop && should_stop()) || std::chrono::steady_clock::now() >= deadline;
223
+ };
224
+
225
+ std::string frame;
226
+ while (from_server.read(frame, stop, false)) {
227
+ json reply;
228
+ try {
229
+ reply = json::parse(frame);
230
+ } catch (...) {
231
+ if (std::chrono::steady_clock::now() >= deadline) {
232
+ break;
233
+ }
234
+ continue; // skip malformed frame
235
+ }
236
+ // no id: a notification. mismatched id: a stale reply from a timed-out request (ids are monotonic, never a future one)
237
+ if (!has_id || (reply.contains("id") && reply.at("id") == request.at("id"))) {
238
+ return reply;
239
+ }
240
+ if (std::chrono::steady_clock::now() >= deadline) {
241
+ break; // a flood of notifications must not outrun the deadline
242
+ }
243
+ }
244
+
245
+ if (should_stop && should_stop()) {
246
+ return {{"error", {{"code", -32603}, {"message", "cancelled"}}}};
247
+ }
248
+ if (std::chrono::steady_clock::now() >= deadline) {
249
+ return {{"error", {{"code", -32603}, {"message", "request timed out"}}}};
250
+ }
251
+ return {{"error", {{"code", -32603}, {"message", "transport closed"}}}};
252
+ }
253
+
254
+ bool server_mcp_transport::ensure_init(const std::function<bool()> & should_stop) {
255
+ if (initialized) {
256
+ return true;
257
+ }
258
+
259
+ json init_req = {
260
+ {"jsonrpc", "2.0"},
261
+ {"id", next_id++},
262
+ {"method", "initialize"},
263
+ {"params", {
264
+ {"protocolVersion", MCP_PROTOCOL_VERSION},
265
+ {"capabilities", json::object()},
266
+ {"clientInfo", {{"name", "llama.cpp"}, {"version", "1.0"}}},
267
+ }},
268
+ };
269
+ json resp = send_rpc(init_req, should_stop);
270
+ if (!resp.contains("result")) {
271
+ last_error = "initialize failed: " + rpc_error_message(resp);
272
+ return false;
273
+ }
274
+
275
+ // notifications/initialized: no id, no reply expected
276
+ json notif = {{"jsonrpc", "2.0"}, {"method", "notifications/initialized"}};
277
+ to_server.write(notif.dump());
278
+
279
+ initialized = true;
280
+ return true;
281
+ }
282
+
283
+ std::vector<server_mcp_tool_def> server_mcp_transport::list_tools(const std::function<bool()> & should_stop) {
284
+ std::lock_guard<std::mutex> lock(rpc_mutex);
285
+ if (!ensure_init(should_stop)) {
286
+ return {};
287
+ }
288
+ if (!tools.empty()) {
289
+ return tools;
290
+ }
291
+
292
+ json req = {{"jsonrpc", "2.0"}, {"id", next_id++}, {"method", "tools/list"}};
293
+ json resp = send_rpc(req, should_stop);
294
+ if (!resp.contains("result")) {
295
+ last_error = "tools/list failed: " + rpc_error_message(resp);
296
+ return {};
297
+ }
298
+
299
+ const json & result = resp.at("result");
300
+ if (result.contains("tools") && result.at("tools").is_array()) {
301
+ for (const auto & t : result.at("tools")) {
302
+ server_mcp_tool_def def;
303
+ def.server_name = name;
304
+ def.name = t.value("name", "");
305
+ def.description = t.value("description", "");
306
+ if (t.contains("inputSchema")) {
307
+ def.input_schema = t.at("inputSchema");
308
+ }
309
+ tools.push_back(std::move(def));
310
+ }
311
+ }
312
+ return tools;
313
+ }
314
+
315
+ json server_mcp_transport::call_tool(const std::string & tool_name,
316
+ const json & arguments,
317
+ const std::function<bool()> & should_stop) {
318
+ std::lock_guard<std::mutex> lock(rpc_mutex);
319
+ if (!ensure_init(should_stop)) {
320
+ return {{"error", last_error}};
321
+ }
322
+
323
+ json req = {
324
+ {"jsonrpc", "2.0"},
325
+ {"id", next_id++},
326
+ {"method", "tools/call"},
327
+ {"params", {{"name", tool_name}, {"arguments", arguments}}},
328
+ };
329
+ json resp = send_rpc(req, should_stop);
330
+ if (resp.contains("error")) {
331
+ return {{"error", rpc_error_message(resp)}};
332
+ }
333
+ if (resp.contains("result")) {
334
+ return mcp_result_to_response(resp.at("result"));
335
+ }
336
+ return {{"error", "invalid response from MCP server"}};
337
+ }
338
+
339
+ //
340
+ // server_mcp_stdio
341
+ //
342
+
343
+ struct server_mcp_stdio::process_handle {
344
+ common_subproc sp;
345
+ FILE * in = nullptr; // child stdin
346
+ FILE * out = nullptr; // child stdout
347
+ FILE * err = nullptr; // child stderr
348
+ };
349
+
350
+ #if defined(_WIN32)
351
+ // config strings are UTF-8 (from JSON) and subprocess.h converts them with CP_UTF8, so inputs must be UTF-8, not the active code page
352
+ static std::wstring windows_utf8_to_wide(const std::string & s) {
353
+ if (s.empty()) {
354
+ return std::wstring();
355
+ }
356
+ int n = MultiByteToWideChar(CP_UTF8, 0, s.data(), (int) s.size(), NULL, 0);
357
+ if (n <= 0) {
358
+ return std::wstring();
359
+ }
360
+ std::wstring w((size_t) n, L'\0');
361
+ MultiByteToWideChar(CP_UTF8, 0, s.data(), (int) s.size(), &w[0], n);
362
+ return w;
363
+ }
364
+
365
+ static std::string windows_wide_to_utf8(const wchar_t * s, int len /* -1 for NUL-terminated */) {
366
+ int n = WideCharToMultiByte(CP_UTF8, 0, s, len, NULL, 0, NULL, NULL);
367
+ if (n <= 0) {
368
+ return std::string();
369
+ }
370
+ std::string out((size_t) n, '\0');
371
+ WideCharToMultiByte(CP_UTF8, 0, s, len, &out[0], n, NULL, NULL);
372
+ if (len == -1 && !out.empty() && out.back() == '\0') {
373
+ out.pop_back(); // drop the terminator WideCharToMultiByte counts for -1
374
+ }
375
+ return out;
376
+ }
377
+ #endif
378
+
379
+ static std::string mcp_resolve_command(const std::string & command) {
380
+ #if defined(_WIN32)
381
+ // For Windows: make sure we handle ".exe" correctly, as well as UTF-8
382
+ std::wstring wcmd = windows_utf8_to_wide(command);
383
+ wchar_t buf[MAX_PATH * 4];
384
+ const DWORD cap = (DWORD) (sizeof(buf) / sizeof(buf[0]));
385
+
386
+ auto search = [&](const wchar_t * ext) -> std::string {
387
+ DWORD n = SearchPathW(NULL, wcmd.c_str(), ext, cap, buf, NULL);
388
+ return (n > 0 && n < cap) ? windows_wide_to_utf8(buf, (int) n) : std::string();
389
+ };
390
+
391
+ std::string found = search(NULL); // exact path / already-extensioned / .exe on PATH
392
+ if (!found.empty()) {
393
+ return found;
394
+ }
395
+
396
+ std::wstring pathext;
397
+ DWORD need = GetEnvironmentVariableW(L"PATHEXT", NULL, 0);
398
+ if (need > 0) {
399
+ pathext.resize(need);
400
+ DWORD got = GetEnvironmentVariableW(L"PATHEXT", &pathext[0], need);
401
+ pathext.resize(got);
402
+ }
403
+ if (pathext.empty()) {
404
+ pathext = L".COM;.EXE;.BAT;.CMD";
405
+ }
406
+ for (size_t start = 0; start <= pathext.size();) {
407
+ size_t sep = pathext.find(L';', start);
408
+ std::wstring ext = pathext.substr(start, sep == std::wstring::npos ? std::wstring::npos : sep - start);
409
+ if (!ext.empty()) {
410
+ found = search(ext.c_str());
411
+ if (!found.empty()) {
412
+ return found;
413
+ }
414
+ }
415
+ if (sep == std::wstring::npos) {
416
+ break;
417
+ }
418
+ start = sep + 1;
419
+ }
420
+ return command; // give up and let subprocess.h report the spawn error
421
+ #else
422
+ return command;
423
+ #endif // _WIN32
424
+ }
425
+
426
+ static std::vector<std::string> mcp_parent_env() {
427
+ std::vector<std::string> env;
428
+ #if defined(_WIN32)
429
+ LPWCH block = GetEnvironmentStringsW();
430
+ if (block) {
431
+ for (LPWCH e = block; *e; e += wcslen(e) + 1) {
432
+ env.emplace_back(windows_wide_to_utf8(e, -1));
433
+ }
434
+ FreeEnvironmentStringsW(block);
435
+ }
436
+ #else
437
+ if (environ) {
438
+ for (char ** e = environ; *e; ++e) {
439
+ env.emplace_back(*e);
440
+ }
441
+ }
442
+ #endif
443
+ return env;
444
+ }
445
+
446
+ // parent env with the config overrides applied, in "KEY=VALUE" form
447
+ static std::vector<std::string> mcp_build_env(const std::map<std::string, std::string> & overrides) {
448
+ std::vector<std::string> env;
449
+ for (auto & e : mcp_parent_env()) {
450
+ size_t eq = e.find('=');
451
+ std::string key = eq == std::string::npos ? e : e.substr(0, eq);
452
+ if (overrides.find(key) == overrides.end()) {
453
+ env.push_back(e);
454
+ }
455
+ }
456
+ for (auto & [k, v] : overrides) {
457
+ env.push_back(k + "=" + v);
458
+ }
459
+ return env;
460
+ }
461
+
462
+ server_mcp_stdio::server_mcp_stdio(const server_mcp_server_config & config) : config(config) {
463
+ name = config.name;
464
+ timeout_ms = config.timeout_ms;
465
+ // bound the reply queue: send_rpc only drains during a call, so unsolicited notifications would otherwise grow it without limit
466
+ from_server.max_size = 65536;
467
+ }
468
+
469
+ server_mcp_stdio::~server_mcp_stdio() {
470
+ join_pumps();
471
+ }
472
+
473
+ bool server_mcp_stdio::start() {
474
+ std::vector<std::string> argv_s;
475
+ argv_s.push_back(mcp_resolve_command(config.command));
476
+ argv_s.insert(argv_s.end(), config.args.begin(), config.args.end());
477
+
478
+ int options = subprocess_option_no_window | subprocess_option_search_user_path;
479
+ std::vector<std::string> envp_s;
480
+ if (config.env.empty()) {
481
+ options |= subprocess_option_inherit_environment;
482
+ } else {
483
+ envp_s = mcp_build_env(config.env);
484
+ }
485
+
486
+ auto handle = std::make_unique<process_handle>();
487
+ bool ok = handle->sp.create(argv_s, options, envp_s, config.cwd.empty() ? nullptr : config.cwd.c_str());
488
+ if (!ok) {
489
+ SRV_WRN("MCP '%s': failed to spawn '%s'\n", config.name.c_str(), config.command.c_str());
490
+ return false;
491
+ }
492
+ handle->in = handle->sp.stdin_file();
493
+ handle->out = handle->sp.stdout_file();
494
+ handle->err = handle->sp.stderr_file();
495
+
496
+ proc = std::move(handle);
497
+ running.store(true);
498
+ reader = std::thread([this] { reader_loop(); });
499
+ writer = std::thread([this] { writer_loop(); });
500
+ errlog = std::thread([this] { errlog_loop(); });
501
+ return true;
502
+ }
503
+
504
+ void server_mcp_stdio::close() {
505
+ join_pumps();
506
+ }
507
+
508
+ bool server_mcp_stdio::is_alive() const {
509
+ return running.load();
510
+ }
511
+
512
+ std::string server_mcp_stdio::diagnostics() {
513
+ std::string out;
514
+ {
515
+ std::lock_guard<std::mutex> lock(rpc_mutex); // last_error is written by send_rpc's callers
516
+ out = last_error;
517
+ }
518
+ std::lock_guard<std::mutex> lk(err_mu);
519
+ if (!err_tail.empty()) {
520
+ if (!out.empty()) {
521
+ out += "; ";
522
+ }
523
+ out += "last stderr: " + err_tail;
524
+ }
525
+ return out;
526
+ }
527
+
528
+ void server_mcp_stdio::reader_loop() {
529
+ mcp_pump_ndjson(proc->out, running, [this](std::string && line) {
530
+ return from_server.write(std::move(line)); // false => consumer gone, stop
531
+ });
532
+ running.store(false);
533
+ to_server.close_write(); // stop the writer
534
+ from_server.close_write(); // EOF to any waiting caller
535
+ }
536
+
537
+ // write all of `data` to child stdin, non-blocking and polled so teardown never hangs (a grandchild can hold the read end of a full pipe open). returns false on error/close/shutdown.
538
+ static bool mcp_write_all(FILE * f, const std::string & data, std::atomic<bool> & running) {
539
+ if (!f) {
540
+ return false;
541
+ }
542
+ size_t total = 0;
543
+ #if defined(_WIN32)
544
+ HANDLE h = (HANDLE) _get_osfhandle(_fileno(f));
545
+ DWORD nowait = PIPE_NOWAIT;
546
+ SetNamedPipeHandleState(h, &nowait, NULL, NULL);
547
+ while (total < data.size() && running.load()) {
548
+ DWORD written = 0;
549
+ BOOL ok = WriteFile(h, data.data() + total, (DWORD) (data.size() - total), &written, NULL);
550
+ if (ok && written > 0) {
551
+ total += written;
552
+ continue;
553
+ }
554
+ if (!ok) {
555
+ DWORD err = GetLastError();
556
+ if (err != ERROR_NO_DATA && err != ERROR_PIPE_BUSY) {
557
+ return false;
558
+ }
559
+ }
560
+ // backpressure (pipe full) is rare for small JSON-RPC frames; sleep rather than spin.
561
+ // no writable-wait exists for a PIPE_NOWAIT anonymous pipe, so this polls like the POSIX poll() path.
562
+ std::this_thread::sleep_for(std::chrono::milliseconds(10));
563
+ }
564
+ #else
565
+ int fd = fileno(f);
566
+ int fl = fcntl(fd, F_GETFL, 0);
567
+ if (fl >= 0) {
568
+ fcntl(fd, F_SETFL, fl | O_NONBLOCK);
569
+ }
570
+ while (total < data.size() && running.load()) {
571
+ ssize_t n = write(fd, data.data() + total, data.size() - total);
572
+ if (n > 0) {
573
+ total += (size_t) n;
574
+ continue;
575
+ }
576
+ if (n == 0) {
577
+ return false;
578
+ }
579
+ if (errno == EINTR) {
580
+ continue;
581
+ }
582
+ if (errno != EAGAIN && errno != EWOULDBLOCK) {
583
+ return false;
584
+ }
585
+ struct pollfd pfd;
586
+ pfd.fd = fd;
587
+ pfd.events = POLLOUT;
588
+ pfd.revents = 0;
589
+ int pr = poll(&pfd, 1, 50);
590
+ if (pr < 0) {
591
+ if (errno == EINTR) {
592
+ continue;
593
+ }
594
+ return false;
595
+ }
596
+ if (pfd.revents & (POLLERR | POLLNVAL | POLLHUP)) {
597
+ return false;
598
+ }
599
+ }
600
+ #endif
601
+ return total == data.size();
602
+ }
603
+
604
+ void server_mcp_stdio::writer_loop() {
605
+ auto should_stop = [this] { return !running.load(); };
606
+ std::string msg;
607
+ while (to_server.read(msg, should_stop)) {
608
+ msg.push_back('\n');
609
+ if (!mcp_write_all(proc->in, msg, running)) {
610
+ break; // child gone or shutting down
611
+ }
612
+ }
613
+ running.store(false);
614
+ to_server.close_read(); // fail fast on any further send_rpc write
615
+ from_server.close_write(); // wake any caller waiting for a reply
616
+ }
617
+
618
+ void server_mcp_stdio::errlog_loop() {
619
+ static constexpr size_t ERR_TAIL_MAX = 4096;
620
+ // drain stderr (an undrained pipe blocks the child):
621
+ // log it, and keep a bounded tail for reporting when the server dies
622
+ mcp_pump_ndjson(proc->err, running, [this](std::string && line) {
623
+ SRV_DBG("MCP '%s' stderr: %s\n", name.c_str(), line.c_str());
624
+ std::lock_guard<std::mutex> lk(err_mu);
625
+ err_tail += line;
626
+ err_tail += '\n';
627
+ if (err_tail.size() > ERR_TAIL_MAX) {
628
+ err_tail.erase(0, err_tail.size() - ERR_TAIL_MAX);
629
+ }
630
+ return true;
631
+ });
632
+ }
633
+
634
+ void server_mcp_stdio::join_pumps() {
635
+ if (!proc) {
636
+ return;
637
+ }
638
+ running.store(false);
639
+ to_server.close_write(); // wake the writer if it waits for a message
640
+ from_server.close_write(); // wake any caller waiting for a reply
641
+
642
+ proc->sp.terminate(); // child death unblocks the blocked fread/fwrite
643
+
644
+ if (writer.joinable()) writer.join();
645
+ if (reader.joinable()) reader.join();
646
+ if (errlog.joinable()) errlog.join();
647
+
648
+ proc->sp.join(); // reap the child: never waiting would leave the pid a zombie for the process lifetime
649
+ proc.reset();
650
+ }
651
+
652
+
653
+ //
654
+ // server_mcp
655
+ //
656
+
657
+ static constexpr int MCP_COOLDOWN_SECONDS = 5;
658
+ static constexpr int MCP_WARMUP_TIMEOUT_SECONDS = 10; // cap per-server tool discovery at startup
659
+
660
+ server_mcp::~server_mcp() {
661
+ shutdown();
662
+
663
+ std::vector<std::shared_ptr<server_mcp_transport>> to_close;
664
+ {
665
+ std::lock_guard<std::mutex> lock(mutex);
666
+ for (auto & [name, t] : transports) {
667
+ to_close.push_back(std::move(t));
668
+ }
669
+ transports.clear();
670
+ }
671
+ for (auto & t : to_close) {
672
+ t->close();
673
+ }
674
+ }
675
+
676
+ std::shared_ptr<server_mcp_transport> server_mcp::create_transport(const server_mcp_server_config & cfg) {
677
+ return std::make_shared<server_mcp_stdio>(cfg);
678
+ }
679
+
680
+ void server_mcp::shutdown() {
681
+ stopping.store(true);
682
+ }
683
+
684
+ const server_mcp_server_config * server_mcp::find_config(const std::string & name) const {
685
+ for (const auto & c : configs) {
686
+ if (c.name == name) {
687
+ return &c;
688
+ }
689
+ }
690
+ return nullptr;
691
+ }
692
+
693
+ void server_mcp::start(const common_params & params) {
694
+ auto append = [this](const std::string & json_str) {
695
+ try {
696
+ auto parsed = server_mcp_server_config::parse_from_json(json_str);
697
+ if (parsed.empty()) {
698
+ SRV_WRN("%s", "MCP config: no servers found in JSON\n");
699
+ }
700
+ for (auto & p : parsed) {
701
+ // names must be unique across both config sources: get_or_create / find_config key on the name
702
+ if (find_config(p.name)) {
703
+ SRV_WRN("MCP config: duplicate server name '%s', skipping\n", p.name.c_str());
704
+ continue;
705
+ }
706
+ configs.push_back(std::move(p));
707
+ }
708
+ } catch (const std::exception & e) {
709
+ throw std::runtime_error(std::string("failed to parse MCP config JSON: ") + e.what());
710
+ }
711
+ };
712
+ if (!params.mcp_servers_config.empty()) {
713
+ std::ifstream f = fs_open_ifstream(params.mcp_servers_config, std::ios::in);
714
+ if (!f) {
715
+ throw std::runtime_error("failed to open MCP config file: " + params.mcp_servers_config);
716
+ }
717
+ std::stringstream ss;
718
+ ss << f.rdbuf();
719
+ append(ss.str());
720
+ }
721
+ if (!params.mcp_servers_json.empty()) {
722
+ append(params.mcp_servers_json);
723
+ }
724
+
725
+ if (configs.empty()) {
726
+ return;
727
+ }
728
+
729
+ std::vector<server_mcp_tool_def> discovered;
730
+ for (const auto & cfg : configs) {
731
+ auto t = create_transport(cfg);
732
+ if (!t->start()) {
733
+ SRV_WRN("MCP warmup: failed to spawn '%s': %s\n", cfg.name.c_str(), t->diagnostics().c_str());
734
+ continue;
735
+ }
736
+ // bound warmup per server so an unresponsive one can't stall startup for the full per-call timeout
737
+ const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(MCP_WARMUP_TIMEOUT_SECONDS);
738
+ auto should_stop = [this, deadline]() {
739
+ return stopping.load() || std::chrono::steady_clock::now() >= deadline;
740
+ };
741
+ auto tools = t->list_tools(should_stop);
742
+ SRV_INF("MCP warmup: '%s' discovered %zu tools\n", cfg.name.c_str(), tools.size());
743
+ discovered.insert(discovered.end(), tools.begin(), tools.end());
744
+ t->close();
745
+ }
746
+
747
+ std::lock_guard<std::mutex> lock(mutex);
748
+ registry.swap(discovered);
749
+ }
750
+
751
+ std::vector<server_mcp_tool_def> server_mcp::list_tools() const {
752
+ std::lock_guard<std::mutex> lock(mutex);
753
+ return registry;
754
+ }
755
+
756
+ json server_mcp::call_tool(const std::string & server_name,
757
+ const std::string & tool_name,
758
+ const json & arguments,
759
+ const std::function<bool()> & should_stop) {
760
+ auto transport = get_or_create(server_name);
761
+ if (!transport) {
762
+ return {{"error", "MCP server unavailable: " + server_name}};
763
+ }
764
+
765
+ auto stop = [this, &should_stop]() {
766
+ return stopping.load() || (should_stop && should_stop());
767
+ };
768
+ return transport->call_tool(tool_name, arguments, stop);
769
+ }
770
+
771
+ std::shared_ptr<server_mcp_transport> server_mcp::get_or_create(const std::string & name) {
772
+ std::vector<std::shared_ptr<server_mcp_transport>> to_close; // closed after unlock
773
+ std::shared_ptr<server_mcp_transport> result;
774
+
775
+ {
776
+ std::lock_guard<std::mutex> lock(mutex);
777
+ if (stopping.load()) {
778
+ return nullptr;
779
+ }
780
+
781
+ auto now = std::chrono::steady_clock::now();
782
+ auto dead_it = dead_servers.find(name);
783
+ if (dead_it != dead_servers.end()) {
784
+ if (now < dead_it->second) {
785
+ return nullptr;
786
+ }
787
+ dead_servers.erase(dead_it);
788
+ }
789
+
790
+ auto it = transports.find(name);
791
+ if (it != transports.end()) {
792
+ if (it->second->is_alive()) {
793
+ return it->second;
794
+ }
795
+ SRV_WRN("MCP '%s' is no longer alive: %s\n", name.c_str(), it->second->diagnostics().c_str());
796
+ to_close.push_back(std::move(it->second));
797
+ transports.erase(it);
798
+ }
799
+
800
+ const server_mcp_server_config * cfg = find_config(name);
801
+ if (cfg) {
802
+ auto fresh = create_transport(*cfg);
803
+ if (fresh->start() && fresh->is_alive()) {
804
+ transports[name] = fresh;
805
+ result = fresh;
806
+ } else {
807
+ SRV_WRN("MCP '%s': failed to start: %s\n", name.c_str(), fresh->diagnostics().c_str());
808
+ to_close.push_back(std::move(fresh));
809
+ dead_servers[name] = now + std::chrono::seconds(MCP_COOLDOWN_SECONDS);
810
+ }
811
+ }
812
+ }
813
+
814
+ for (auto & t : to_close) {
815
+ t->close(); // blocking call, no leaks
816
+ }
817
+
818
+ return result;
819
+ }
820
+
tools/server/server-mcp.h ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include "server-common.h"
4
+
5
+ #include <atomic>
6
+ #include <chrono>
7
+ #include <functional>
8
+ #include <map>
9
+ #include <memory>
10
+ #include <mutex>
11
+ #include <string>
12
+ #include <thread>
13
+ #include <vector>
14
+
15
+ //
16
+ // Configuration (Cursor-compatible "mcpServers" JSON)
17
+ //
18
+
19
+ struct server_mcp_server_config {
20
+ std::string name; // config key, e.g. "filesystem"
21
+ std::string command;
22
+ std::vector<std::string> args;
23
+ std::map<std::string, std::string> env; // merged over the parent env
24
+ std::string cwd;
25
+ int timeout_ms = 30000; // per-tool-call timeout
26
+
27
+ // throw on parse errors; missing "mcpServers" yields an empty list; entries without a "command" are skipped
28
+ static std::vector<server_mcp_server_config> parse_from_json(const std::string & json_str);
29
+ static std::vector<server_mcp_server_config> parse_cursor_format(const json & j);
30
+ };
31
+
32
+ // a tool advertised by an MCP server
33
+ struct server_mcp_tool_def {
34
+ std::string server_name;
35
+ std::string name; // bare tool name, no "<server>_" prefix
36
+ std::string description;
37
+ json input_schema; // JSON Schema for the arguments, or null
38
+ };
39
+
40
+ //
41
+ // server_mcp_transport: one MCP server session.
42
+ //
43
+ // caller --send_rpc--> to_server --[writer]--> framing --> server
44
+ // caller <--send_rpc-- from_server <--[reader]-- framing <-- server
45
+ //
46
+ // each queue item is one complete serialized JSON message.
47
+ // subclass owns byte I/O and framing; base owns JSON and the JSON-RPC session (handshake, id correlation).
48
+ //
49
+
50
+ struct server_mcp_transport {
51
+ std::string name;
52
+ int timeout_ms = 30000;
53
+
54
+ server_pipe<std::string> to_server; // serialized messages we send to the server
55
+ server_pipe<std::string> from_server; // serialized messages read from the server
56
+
57
+ virtual ~server_mcp_transport() = default;
58
+
59
+ virtual bool start() = 0;
60
+ virtual void close() = 0; // blocking and idempotent
61
+ virtual bool is_alive() const = 0; // never blocks behind an in-flight send_rpc()
62
+
63
+ // human-readable diagnostics for logging when the transport fails/dies
64
+ // (example: last RPC error, plus any transport-specific detail)
65
+ // may run on a different thread than send_rpc(), so last_error is read under rpc_mutex
66
+ virtual std::string diagnostics() {
67
+ std::lock_guard<std::mutex> lock(rpc_mutex);
68
+ return last_error;
69
+ }
70
+
71
+ std::vector<server_mcp_tool_def> list_tools(const std::function<bool()> & should_stop);
72
+
73
+ json call_tool(const std::string & tool_name,
74
+ const json & arguments,
75
+ const std::function<bool()> & should_stop);
76
+
77
+ protected:
78
+ // per-transport: send_rpc() holds it across the reply wait, so sharing it would stall every server behind one slow call. guards all members below.
79
+ std::mutex rpc_mutex;
80
+ uint64_t next_id = 1; // reset to 1 per (re)spawn
81
+ bool initialized = false;
82
+ std::string last_error;
83
+ std::vector<server_mcp_tool_def> tools;
84
+
85
+ // both assume rpc_mutex is already held by the public caller
86
+ bool ensure_init(const std::function<bool()> & should_stop); // initialize handshake, once
87
+ json send_rpc(const json & request, const std::function<bool()> & should_stop); // returns the reply or an {"error": ...}
88
+ };
89
+
90
+ //
91
+ // server_mcp_stdio: child process, NDJSON JSON-RPC over stdio (stderr drained to the debug log)
92
+ //
93
+
94
+ struct server_mcp_stdio : server_mcp_transport {
95
+ explicit server_mcp_stdio(const server_mcp_server_config & config);
96
+ ~server_mcp_stdio() override;
97
+
98
+ bool start() override;
99
+ void close() override;
100
+ bool is_alive() const override;
101
+ std::string diagnostics() override;
102
+
103
+ private:
104
+ server_mcp_server_config config;
105
+
106
+ // defined in the .cpp so <windows.h> stays out of this header
107
+ struct process_handle;
108
+ std::unique_ptr<process_handle> proc;
109
+
110
+ std::thread reader; // child stdout -> NDJSON de-framing -> from_server
111
+ std::thread writer; // to_server -> NDJSON framing -> child stdin
112
+ std::thread errlog; // child stderr -> debug log (must be drained or the child blocks)
113
+
114
+ // cleared by close() or by the reader on stdout EOF; read without rpc_mutex
115
+ std::atomic<bool> running{false};
116
+
117
+ // bounded tail of the child's stderr, for diagnostics when it dies
118
+ std::mutex err_mu;
119
+ std::string err_tail;
120
+
121
+ void reader_loop();
122
+ void writer_loop();
123
+ void errlog_loop();
124
+ void join_pumps();
125
+ };
126
+
127
+ //
128
+ // server_mcp
129
+ // declare before the HTTP context so it outlives every /tools handler.
130
+ //
131
+
132
+ class server_mcp {
133
+ public:
134
+ server_mcp() = default;
135
+ ~server_mcp();
136
+
137
+ // parse the MCP config from params (file and/or inline JSON),
138
+ // then spawn each server once, list its tools, and shut it down
139
+ // throws on config parse errors; spawn failures are logged.
140
+ void start(const common_params & params);
141
+
142
+ // true until start() has parsed at least one server from the config
143
+ bool empty() const { return configs.empty(); }
144
+
145
+ std::vector<server_mcp_tool_def> list_tools() const;
146
+
147
+ // lazily (re)spawns the transport. returns the MCP result or an {"error": ...}. should_stop is OR-ed with the manager's cancel flag.
148
+ json call_tool(const std::string & server_name,
149
+ const std::string & tool_name,
150
+ const json & arguments,
151
+ const std::function<bool()> & should_stop = nullptr);
152
+
153
+ // flip the cancel flag so in-flight calls return; blocking teardown is in the destructor. call before the HTTP server drains.
154
+ // note: multiple calls are idempotent
155
+ void shutdown();
156
+
157
+ private:
158
+ std::vector<server_mcp_server_config> configs;
159
+
160
+ mutable std::mutex mutex; // guards transports, dead_servers, registry
161
+
162
+ // shared_ptr: call_tool() hands a transport to the caller and drops the lock for the blocking RPC, so a concurrent evict/respawn must not destroy it mid-call
163
+ std::map<std::string, std::shared_ptr<server_mcp_transport>> transports;
164
+ std::map<std::string, std::chrono::steady_clock::time_point> dead_servers; // spawn-failure cooldown
165
+ std::vector<server_mcp_tool_def> registry;
166
+
167
+ std::atomic<bool> stopping{false};
168
+
169
+ const server_mcp_server_config * find_config(const std::string & name) const;
170
+
171
+ // the only place that names a concrete transport
172
+ std::shared_ptr<server_mcp_transport> create_transport(const server_mcp_server_config & cfg);
173
+
174
+ // nullptr during cooldown or shutdown
175
+ std::shared_ptr<server_mcp_transport> get_or_create(const std::string & name);
176
+ };
tools/server/server-models.cpp ADDED
The diff for this file is too large to render. See raw diff
 
tools/server/server-models.h ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include "common.h"
4
+ #include "download.h"
5
+ #include "preset.h"
6
+ #include "server-common.h"
7
+ #include "server-http.h"
8
+ #include "server-queue.h"
9
+
10
+ #include <mutex>
11
+ #include <condition_variable>
12
+ #include <functional>
13
+ #include <memory>
14
+ #include <optional>
15
+ #include <set>
16
+ #include <string>
17
+ #include <unordered_map>
18
+
19
+ /**
20
+ * state diagram:
21
+ *
22
+ * DOWNLOADING ──► DOWNLOADED ──► (replaced by new instance)
23
+ *
24
+ * UNLOADED ──► LOADING ──► LOADED ◄──── SLEEPING
25
+ * ▲ │ │ ▲
26
+ * └───failed───┘ │ │
27
+ * ▲ └──sleeping─────┘
28
+ * └────────unloaded─────────┘
29
+ */
30
+ enum server_model_status {
31
+ // TODO: also add downloading state when the logic is added
32
+ SERVER_MODEL_STATUS_DOWNLOADING,
33
+ SERVER_MODEL_STATUS_DOWNLOADED,
34
+ SERVER_MODEL_STATUS_UNLOADED,
35
+ SERVER_MODEL_STATUS_LOADING,
36
+ SERVER_MODEL_STATUS_LOADED,
37
+ SERVER_MODEL_STATUS_SLEEPING
38
+ };
39
+
40
+ enum server_model_source {
41
+ SERVER_MODEL_SOURCE_PRESET,
42
+ SERVER_MODEL_SOURCE_MODELS_DIR,
43
+ SERVER_MODEL_SOURCE_CACHE,
44
+ };
45
+
46
+ enum server_child_mode {
47
+ SERVER_CHILD_MODE_NORMAL, // load the model and run normally
48
+ SERVER_CHILD_MODE_DOWNLOAD, // download the model and exit
49
+ };
50
+
51
+ static std::string server_model_status_to_string(server_model_status status) {
52
+ switch (status) {
53
+ case SERVER_MODEL_STATUS_DOWNLOADING: return "downloading";
54
+ case SERVER_MODEL_STATUS_DOWNLOADED: return "downloaded";
55
+ case SERVER_MODEL_STATUS_UNLOADED: return "unloaded";
56
+ case SERVER_MODEL_STATUS_LOADING: return "loading";
57
+ case SERVER_MODEL_STATUS_LOADED: return "loaded";
58
+ case SERVER_MODEL_STATUS_SLEEPING: return "sleeping";
59
+ default: return "unknown";
60
+ }
61
+ }
62
+
63
+ static std::string server_model_source_to_string(server_model_source source) {
64
+ switch (source) {
65
+ case SERVER_MODEL_SOURCE_PRESET: return "preset";
66
+ case SERVER_MODEL_SOURCE_MODELS_DIR: return "models_dir";
67
+ case SERVER_MODEL_SOURCE_CACHE: return "cache";
68
+ default: return "unknown";
69
+ }
70
+ }
71
+
72
+ struct server_model_meta {
73
+ server_model_source source = SERVER_MODEL_SOURCE_CACHE;
74
+ common_preset preset;
75
+ std::string name;
76
+ std::set<std::string> aliases; // additional names that resolve to this model
77
+ std::set<std::string> tags; // informational tags, not used for routing
78
+ int port = 0;
79
+ server_model_status status = SERVER_MODEL_STATUS_UNLOADED;
80
+ int64_t last_used = 0; // for LRU unloading
81
+ std::vector<std::string> args; // args passed to the model instance, will be populated by render_args()
82
+ json loaded_info; // info to be reflected via /v1/models endpoint ; if in DOWNLOADING state, it should contain download progress info
83
+ json progress; // reflect load or download progress info, if any
84
+ int exit_code = 0; // exit code of the model instance process (only valid if status == FAILED)
85
+ int stop_timeout = 0; // seconds to wait before force-killing the model instance during shutdown
86
+ mtmd_caps multimodal; // multimodal capabilities
87
+
88
+ bool is_ready() const {
89
+ return status == SERVER_MODEL_STATUS_LOADED;
90
+ }
91
+
92
+ bool is_running() const {
93
+ return status == SERVER_MODEL_STATUS_LOADED || status == SERVER_MODEL_STATUS_LOADING || status == SERVER_MODEL_STATUS_SLEEPING;
94
+ }
95
+
96
+ bool is_ready_or_sleep() const {
97
+ return status == SERVER_MODEL_STATUS_LOADED || status == SERVER_MODEL_STATUS_SLEEPING;
98
+ }
99
+
100
+ bool is_failed() const {
101
+ return status == SERVER_MODEL_STATUS_UNLOADED && exit_code != 0;
102
+ }
103
+
104
+ void update_args(common_preset_context & ctx_presets, std::string bin_path);
105
+ void update_caps();
106
+ };
107
+
108
+ struct server_models_routes;
109
+ struct server_subproc; // defined in server-models.cpp
110
+ struct server_lru_sched; // defined in server-models.cpp
111
+
112
+ struct server_models {
113
+ friend struct server_models_routes;
114
+ friend struct server_lru_sched;
115
+
116
+ private:
117
+ struct instance_t {
118
+ std::shared_ptr<server_subproc> subproc; // shared between main thread and monitoring thread
119
+ std::thread th;
120
+ server_model_meta meta;
121
+ int req_count = 0; // number of active proxy requests
122
+ };
123
+
124
+ std::mutex mutex;
125
+ std::condition_variable cv;
126
+ std::map<std::string, instance_t> mapping;
127
+
128
+ // for stopping models
129
+ std::condition_variable cv_stop;
130
+ std::set<std::string> stopping_models;
131
+
132
+ // set to true while load_models() is executing a reload; load() will wait until clear
133
+ bool is_reloading = false;
134
+
135
+ // if true, the next get_meta() will trigger a reload of model list
136
+ bool need_reload = false;
137
+
138
+ // conv_id -> model name that currently serves its stream session, lets the resumable stream
139
+ // routes go straight to the owning child instead of polling every one. populated when
140
+ // proxy_request forwards a POST carrying an X-Conversation-Id. best effort: a stale entry just
141
+ // makes the child answer not found and the client recovers. owns its lock, one mutex per struct
142
+ struct conv_model_tracker {
143
+ // returns the ticket of this registration, 0 when nothing was registered. erasing or
144
+ // replacing the entry invalidates the ticket, which is how a stop cancels a request
145
+ // parked in the model load wait
146
+ uint64_t remember(const std::string & conv_id, const std::string & model) {
147
+ if (conv_id.empty() || model.empty()) {
148
+ return 0;
149
+ }
150
+ std::lock_guard<std::mutex> lock(mu);
151
+ uint64_t ticket = next_ticket++;
152
+ map[conv_id] = { model, ticket };
153
+ return ticket;
154
+ }
155
+
156
+ // false means a stop erased the entry or a newer request replaced it
157
+ bool alive(const std::string & conv_id, uint64_t ticket) {
158
+ std::lock_guard<std::mutex> lock(mu);
159
+ auto it = map.find(conv_id);
160
+ return it != map.end() && it->second.ticket == ticket;
161
+ }
162
+
163
+ std::optional<std::string> lookup(const std::string & conv_id) {
164
+ if (conv_id.empty()) {
165
+ return std::nullopt;
166
+ }
167
+ std::lock_guard<std::mutex> lock(mu);
168
+ auto it = map.find(conv_id);
169
+ if (it == map.end()) {
170
+ return std::nullopt;
171
+ }
172
+ return it->second.model;
173
+ }
174
+
175
+ void forget(const std::string & conv_id) {
176
+ if (conv_id.empty()) {
177
+ return;
178
+ }
179
+ std::lock_guard<std::mutex> lock(mu);
180
+ map.erase(conv_id);
181
+ }
182
+
183
+ private:
184
+ struct entry_t {
185
+ std::string model;
186
+ uint64_t ticket;
187
+ };
188
+ std::mutex mu;
189
+ uint64_t next_ticket = 1;
190
+ std::unordered_map<std::string, entry_t> map;
191
+ };
192
+
193
+ common_preset_context ctx_preset;
194
+
195
+ common_params base_params;
196
+ std::string bin_path;
197
+ std::vector<std::string> base_env;
198
+ common_preset base_preset; // base preset from llama-server CLI args
199
+
200
+ // queue of requests waiting for a models_max slot
201
+ std::unique_ptr<server_lru_sched> sched;
202
+
203
+ // if true, add some delay to simulate works (useful for testing)
204
+ bool debug_fake_timing = false;
205
+
206
+ void update_meta(const std::string & name, const server_model_meta & meta);
207
+
208
+ // unload least recently used models if the limit is reached
209
+ void unload_lru();
210
+
211
+ // not thread-safe, caller must hold mutex
212
+ void add_model(server_model_meta && meta);
213
+
214
+ // notify SSE clients
215
+ void notify_sse(const std::string & event, const std::string & model_id, const json & data = nullptr);
216
+
217
+ public:
218
+ // conv_id -> model tracker for the resumable stream routes, owns its lock
219
+ conv_model_tracker conv_models;
220
+
221
+ server_models(const common_params & params, int argc, char ** argv);
222
+ ~server_models();
223
+
224
+ server_response sse; // for real-time updates via SSE endpoint
225
+
226
+ // (re-)load the list of models from various sources and prepare the metadata mapping
227
+ // - if this is called the first time, simply populate the metadata
228
+ // - if this is called subsequently (e.g. when refreshing from disk):
229
+ // - if a model is running but updated or removed from the source, it will be unloaded
230
+ // - if a model is not running, it will be added or updated according to the source
231
+ void load_models();
232
+
233
+ // check if a model instance exists (thread-safe)
234
+ bool has_model(const std::string & name);
235
+
236
+ // return a copy of model metadata (thread-safe)
237
+ std::optional<server_model_meta> get_meta(const std::string & name);
238
+
239
+ // return a copy of all model metadata (thread-safe)
240
+ std::vector<server_model_meta> get_all_meta();
241
+
242
+ struct load_options {
243
+ server_child_mode mode = SERVER_CHILD_MODE_NORMAL;
244
+ // used for spawning a downloading child process
245
+ std::optional<server_model_meta> custom_meta = std::nullopt;
246
+ };
247
+
248
+ // load and unload model instances
249
+ // these functions are thread-safe
250
+ void load(const std::string & name);
251
+ void load(const std::string & name, const load_options & opts);
252
+ void unload(const std::string & name);
253
+ void unload_all();
254
+
255
+ struct update_status_args {
256
+ server_model_status status;
257
+ int exit_code = 0; // only valid if status == UNLOADED
258
+ json loaded_info = nullptr;
259
+ json progress = nullptr;
260
+ };
261
+ // update the status of a model instance (thread-safe)
262
+ // also send SSE notification to /models/sse endpoint
263
+ void update_status(const std::string & name, const update_status_args & args);
264
+ void update_download_progress(const std::string & name, const common_download_progress & progress, bool done, bool ok = true);
265
+
266
+ // remove a cache model from disk and update the list (thread-safe)
267
+ // note: only cache models can be removed; returns false if the model doesn't exist or is not a cache model
268
+ bool remove(const std::string & name);
269
+
270
+ // wait until the model instance is fully loaded (thread-safe)
271
+ // note: predicate is called while holding the lock
272
+ // return when the model no longer in "loading" state
273
+ void wait(const std::string & name, std::function<bool(const server_model_meta &)> predicate);
274
+ void wait(std::unique_lock<std::mutex> & lk, const std::string & name, std::function<bool(const server_model_meta &)> predicate);
275
+
276
+ // ensure the model is in ready state (thread-safe)
277
+ // return false if model is ready
278
+ // otherwise, load the model and blocking wait until it's ready, then return true (meta may need to be refreshed)
279
+ // if models_max is reached, the request waits in a queue until a slot frees up
280
+ // throws if the load fails, or if should_stop fires while waiting
281
+ bool ensure_model_ready(const std::string & name, const std::function<bool()> & should_stop = nullptr);
282
+
283
+ // proxy an HTTP request to the model instance
284
+ server_http_res_ptr proxy_request(const server_http_req & req, const std::string & method, const std::string & name, bool update_last_used, bool detached = false);
285
+
286
+ // handle message sent from server_child::notify_to_router()
287
+ // raw input must starts with CMD_CHILD_TO_ROUTER_STATE, followed by a JSON string
288
+ // this function is not thread-safe, must be called from instance's monitoring thread
289
+ // payload per state:
290
+ // state = loading -> payload = {} (TODO: add progress info)
291
+ // state = ready -> payload = model_info (json), or {} if wakeup from sleeping
292
+ // state = sleeping -> payload = {}
293
+ void handle_child_state(const std::string & name, const std::string & raw_input);
294
+ };
295
+
296
+ struct server_child {
297
+ // serializes the notify_to_router writes
298
+ std::mutex mtx_stdout;
299
+ std::atomic<bool> is_finished_downloading = false; // set by run_download
300
+
301
+ // return true if the current process is a child server instance
302
+ bool is_child();
303
+ server_child_mode get_mode();
304
+ int run_download(common_params & params);
305
+
306
+ // register the shutdown_handler to be called by the router
307
+ // return the monitoring thread (to be joined by the caller)
308
+ std::thread setup(const std::function<void(int)> & shutdown_handler);
309
+
310
+ // notify router server for status changes (e.g. loading, downloading, sleeping, etc.)
311
+ // message will be handled by server_models::handle_child_state() on the router side
312
+ void notify_to_router(const std::string & state_name, const json & payload);
313
+ };
314
+
315
+ struct server_models_routes {
316
+ common_params params;
317
+ json ui_settings = json::object(); // Primary: new name
318
+ std::atomic<bool> stopping = false; // for graceful disconnecting SSE clients during shutdown
319
+ server_models models;
320
+ server_models_routes(const common_params & params, int argc, char ** argv)
321
+ : params(params), models(params, argc, argv) {
322
+ const std::string & cfg = this->params.ui_config_json;
323
+ if (!cfg.empty()) {
324
+ try {
325
+ json json_settings = json::parse(cfg);
326
+ ui_settings = json_settings;
327
+ } catch (const std::exception & e) {
328
+ LOG_ERR("%s: failed to parse UI config: %s\n", __func__, e.what());
329
+ throw;
330
+ }
331
+ }
332
+ init_routes();
333
+ }
334
+
335
+ void init_routes();
336
+ // handlers using lambda function, so that they can capture `this` without `std::bind`
337
+ server_http_context::handler_t get_router_props;
338
+ server_http_context::handler_t proxy_get;
339
+ server_http_context::handler_t proxy_post;
340
+ server_http_context::handler_t get_router_models;
341
+ server_http_context::handler_t post_router_models_load;
342
+ server_http_context::handler_t post_router_models_unload;
343
+ // management API
344
+ server_http_context::handler_t get_router_models_sse;
345
+ server_http_context::handler_t post_router_models;
346
+ server_http_context::handler_t del_router_models;
347
+
348
+ // router side handlers for the resumable streaming routes. each resolves the child that owns
349
+ // a conversation through the conv_id -> model map, no probing or fan out
350
+ server_http_context::handler_t router_stream_get;
351
+ server_http_context::handler_t router_streams_lookup;
352
+ server_http_context::handler_t router_stream_delete;
353
+ };
354
+
355
+ /**
356
+ * A simple HTTP proxy that forwards requests to another server
357
+ * and relays the responses back.
358
+ */
359
+ struct server_http_proxy : server_http_res {
360
+ std::function<void()> cleanup = nullptr;
361
+ server_http_proxy(const std::string & method,
362
+ const std::string & scheme,
363
+ const std::string & host,
364
+ int port,
365
+ const std::string & path,
366
+ const std::map<std::string, std::string> & headers,
367
+ const std::string & body,
368
+ const std::map<std::string, uploaded_file> & files,
369
+ const std::function<bool()> should_stop,
370
+ int32_t timeout_read,
371
+ int32_t timeout_write
372
+ );
373
+ ~server_http_proxy() {
374
+ if (cleanup_pipes) {
375
+ cleanup_pipes();
376
+ }
377
+ if (cleanup) {
378
+ cleanup();
379
+ }
380
+ }
381
+ private:
382
+ std::function<void()> cleanup_pipes = nullptr;
383
+ std::thread thread;
384
+ struct msg_t {
385
+ std::map<std::string, std::string> headers;
386
+ int status = 0;
387
+ std::string data;
388
+ std::string content_type;
389
+ };
390
+ };
tools/server/server-queue.cpp ADDED
@@ -0,0 +1,460 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "server-task.h"
2
+ #include "server-queue.h"
3
+
4
+ #include "log.h"
5
+
6
+ #include <chrono>
7
+
8
+ #define QUE_INF(fmt, ...) LOG_INF("que %12.*s: " fmt, 12, __func__, __VA_ARGS__)
9
+ #define QUE_WRN(fmt, ...) LOG_WRN("que %12.*s: " fmt, 12, __func__, __VA_ARGS__)
10
+ #define QUE_ERR(fmt, ...) LOG_ERR("que %12.*s: " fmt, 12, __func__, __VA_ARGS__)
11
+ #define QUE_DBG(fmt, ...) LOG_DBG("que %12.*s: " fmt, 12, __func__, __VA_ARGS__)
12
+
13
+ #define RES_INF(fmt, ...) LOG_INF("res %12.*s: " fmt, 12, __func__, __VA_ARGS__)
14
+ #define RES_WRN(fmt, ...) LOG_WRN("res %12.*s: " fmt, 12, __func__, __VA_ARGS__)
15
+ #define RES_ERR(fmt, ...) LOG_ERR("res %12.*s: " fmt, 12, __func__, __VA_ARGS__)
16
+ #define RES_DBG(fmt, ...) LOG_DBG("res %12.*s: " fmt, 12, __func__, __VA_ARGS__)
17
+
18
+ //
19
+ // server_queue
20
+ //
21
+
22
+ int server_queue::post(server_task && task, bool front) {
23
+ std::unique_lock<std::mutex> lock(mutex_tasks);
24
+ GGML_ASSERT(task.id != -1);
25
+ // if this is cancel task make sure to clean up pending tasks
26
+ if (task.type == SERVER_TASK_TYPE_CANCEL) {
27
+ cleanup_pending_task(task.id_target);
28
+ }
29
+ const int task_id = task.id;
30
+ QUE_DBG("new task, id = %d, front = %d\n", task_id, front);
31
+ if (front) {
32
+ queue_tasks.push_front(std::move(task));
33
+ } else {
34
+ queue_tasks.push_back(std::move(task));
35
+ }
36
+ time_last_task = ggml_time_ms();
37
+ condition_tasks.notify_one();
38
+ return task_id;
39
+ }
40
+
41
+ int server_queue::post(std::vector<server_task> && tasks, bool front) {
42
+ std::unique_lock<std::mutex> lock(mutex_tasks);
43
+ for (auto & task : tasks) {
44
+ if (task.id == -1) {
45
+ task.id = id++;
46
+ }
47
+ // if this is cancel task make sure to clean up pending tasks
48
+ if (task.type == SERVER_TASK_TYPE_CANCEL) {
49
+ cleanup_pending_task(task.id_target);
50
+ }
51
+ QUE_DBG("new task, id = %d/%d, front = %d\n", task.id, (int) tasks.size(), front);
52
+ if (front) {
53
+ queue_tasks.push_front(std::move(task));
54
+ } else {
55
+ queue_tasks.push_back(std::move(task));
56
+ }
57
+ }
58
+ time_last_task = ggml_time_ms();
59
+ condition_tasks.notify_one();
60
+ return 0;
61
+ }
62
+
63
+ void server_queue::defer(server_task && task) {
64
+ std::unique_lock<std::mutex> lock(mutex_tasks);
65
+ QUE_DBG("defer task, id = %d\n", task.id);
66
+ queue_tasks_deferred.push_back(std::move(task));
67
+ time_last_task = ggml_time_ms();
68
+ condition_tasks.notify_one();
69
+ }
70
+
71
+ int server_queue::get_new_id() {
72
+ std::unique_lock<std::mutex> lock(mutex_tasks);
73
+ int new_id = id++;
74
+ return new_id;
75
+ }
76
+
77
+ void server_queue::pop_deferred_task(int id_slot) {
78
+ std::unique_lock<std::mutex> lock(mutex_tasks);
79
+ if (!queue_tasks_deferred.empty()) {
80
+ // try to find a task that uses the specified slot
81
+ bool found = false;
82
+ for (auto it = queue_tasks_deferred.begin(); it != queue_tasks_deferred.end(); ++it) {
83
+ if (it->id_slot == id_slot) {
84
+ QUE_DBG("pop deferred task (use slot %d), id_task = %d\n", id_slot, it->id);
85
+ queue_tasks.emplace_front(std::move(*it));
86
+ queue_tasks_deferred.erase(it);
87
+ found = true;
88
+ break;
89
+ }
90
+ }
91
+ // if not tasks found using the slot, just pop the first deferred task (default behavior)
92
+ if (!found) {
93
+ QUE_DBG("pop deferred task, id_task = %d\n", queue_tasks_deferred.front().id);
94
+ queue_tasks.emplace_front(std::move(queue_tasks_deferred.front()));
95
+ queue_tasks_deferred.pop_front();
96
+ }
97
+ }
98
+ time_last_task = ggml_time_ms();
99
+ condition_tasks.notify_one();
100
+ }
101
+
102
+ void server_queue::wait_until_no_sleep() {
103
+ std::unique_lock<std::mutex> lock(mutex_tasks);
104
+ if (!sleeping) {
105
+ return;
106
+ } else {
107
+ if (!req_stop_sleeping) {
108
+ QUE_DBG("%s", "requesting to stop sleeping\n");
109
+ req_stop_sleeping = true;
110
+ condition_tasks.notify_one(); // only main thread is waiting on this
111
+ }
112
+ QUE_DBG("%s", "waiting until no sleep\n");
113
+ condition_tasks.wait(lock, [&]{
114
+ return !sleeping;
115
+ });
116
+ }
117
+ }
118
+
119
+ void server_queue::terminate() {
120
+ std::unique_lock<std::mutex> lock(mutex_tasks);
121
+ running = false;
122
+ condition_tasks.notify_all();
123
+ }
124
+
125
+ void server_queue::start_loop(int64_t idle_sleep_ms) {
126
+ running = true;
127
+ time_last_task = ggml_time_ms();
128
+
129
+ constexpr auto max_wait_time = std::chrono::seconds(1);
130
+ auto should_sleep = [&]() -> bool {
131
+ // caller must hold mutex_tasks
132
+ if (idle_sleep_ms < 0) {
133
+ return false;
134
+ }
135
+ int64_t now = ggml_time_ms();
136
+ return (now - time_last_task) >= idle_sleep_ms;
137
+ };
138
+
139
+ while (true) {
140
+ QUE_DBG("%s", "processing new tasks\n");
141
+
142
+ while (true) {
143
+ std::unique_lock<std::mutex> lock(mutex_tasks);
144
+ if (!running) {
145
+ QUE_DBG("%s", "terminate\n");
146
+ return;
147
+ }
148
+ if (queue_tasks.empty()) {
149
+ lock.unlock();
150
+ break;
151
+ }
152
+ server_task task = std::move(queue_tasks.front());
153
+ queue_tasks.pop_front();
154
+ lock.unlock();
155
+
156
+ QUE_DBG("processing task, id = %d\n", task.id);
157
+ callback_new_task(std::move(task));
158
+ }
159
+ // all tasks in the current loop is processed, slots data is now ready
160
+ QUE_DBG("%s", "update slots\n");
161
+
162
+ // this will run the main inference process for all slots
163
+ callback_update_slots();
164
+ {
165
+ // update_slots() may take a while to finish, we need to make sure it's not counted as idle
166
+ std::unique_lock<std::mutex> lock(mutex_tasks);
167
+ time_last_task = ggml_time_ms();
168
+ }
169
+
170
+ QUE_DBG("%s", "waiting for new tasks\n");
171
+ while (true) {
172
+ std::unique_lock<std::mutex> lock(mutex_tasks);
173
+ if (!running || !queue_tasks.empty()) {
174
+ break; // go back to process new tasks or terminate
175
+ }
176
+
177
+ // no tasks, check for sleeping state
178
+ if (should_sleep()) {
179
+ QUE_INF("%s", "entering sleeping state\n");
180
+ sleeping = true;
181
+ callback_sleeping_state(true);
182
+ req_stop_sleeping = false;
183
+ // wait until we are requested to exit sleeping state
184
+ condition_tasks.wait(lock, [&]{
185
+ return (!running || req_stop_sleeping);
186
+ });
187
+ if (!running) { // may changed during sleep
188
+ break; // terminate
189
+ }
190
+ QUE_INF("%s", "exiting sleeping state\n");
191
+ req_stop_sleeping = false;
192
+ callback_sleeping_state(false);
193
+ sleeping = false;
194
+ time_last_task = ggml_time_ms();
195
+ condition_tasks.notify_all(); // notify wait_until_no_sleep()
196
+ break; // process new tasks
197
+ } else {
198
+ // wait for new tasks or timeout for checking sleeping condition
199
+ bool res = condition_tasks.wait_for(lock, max_wait_time, [&]{
200
+ return (!queue_tasks.empty() || !running);
201
+ });
202
+ if (res) {
203
+ break; // new task arrived or terminate
204
+ }
205
+ // otherwise, loop again to check sleeping condition
206
+ }
207
+ }
208
+ }
209
+ }
210
+
211
+ void server_queue::cleanup_pending_task(int id_target) {
212
+ // no need lock because this is called exclusively by post()
213
+ auto rm_func = [id_target](const server_task & task) {
214
+ return task.id == id_target;
215
+ };
216
+ queue_tasks.erase(
217
+ std::remove_if(queue_tasks.begin(), queue_tasks.end(), rm_func),
218
+ queue_tasks.end());
219
+ queue_tasks_deferred.erase(
220
+ std::remove_if(queue_tasks_deferred.begin(), queue_tasks_deferred.end(), rm_func),
221
+ queue_tasks_deferred.end());
222
+ }
223
+
224
+ //
225
+ // server_response
226
+ //
227
+
228
+ void server_response::add_waiting_task_id(int id_task) {
229
+ RES_DBG("add task %d to waiting list. current waiting = %d (before add)\n", id_task, (int) waiting_task_ids.size());
230
+
231
+ std::unique_lock<std::mutex> lock(mutex_results);
232
+ waiting_task_ids.insert(id_task);
233
+ }
234
+
235
+ void server_response::add_waiting_task_ids(const std::unordered_set<int> & id_tasks) {
236
+ std::unique_lock<std::mutex> lock(mutex_results);
237
+
238
+ for (const auto & id_task : id_tasks) {
239
+ RES_DBG("add task %d to waiting list. current waiting = %d (before add)\n", id_task, (int) waiting_task_ids.size());
240
+ waiting_task_ids.insert(id_task);
241
+ }
242
+ }
243
+
244
+ void server_response::remove_waiting_task_id(int id_task) {
245
+ RES_DBG("remove task %d from waiting list. current waiting = %d (before remove)\n", id_task, (int) waiting_task_ids.size());
246
+
247
+ std::unique_lock<std::mutex> lock(mutex_results);
248
+ waiting_task_ids.erase(id_task);
249
+ // make sure to clean up all pending results
250
+ queue_results.erase(
251
+ std::remove_if(queue_results.begin(), queue_results.end(), [id_task](const server_task_result_ptr & res) {
252
+ return res->id == id_task;
253
+ }),
254
+ queue_results.end());
255
+ }
256
+
257
+ void server_response::remove_waiting_task_ids(const std::unordered_set<int> & id_tasks) {
258
+ std::unique_lock<std::mutex> lock(mutex_results);
259
+
260
+ for (const auto & id_task : id_tasks) {
261
+ RES_DBG("remove task %d from waiting list. current waiting = %d (before remove)\n", id_task, (int) waiting_task_ids.size());
262
+ waiting_task_ids.erase(id_task);
263
+ }
264
+ }
265
+
266
+ server_task_result_ptr server_response::recv(const std::unordered_set<int> & id_tasks) {
267
+ while (true) {
268
+ std::unique_lock<std::mutex> lock(mutex_results);
269
+ condition_results.wait(lock, [&]{
270
+ if (!running) {
271
+ RES_DBG("%s : queue result stop\n", "recv");
272
+ std::terminate(); // we cannot return here since the caller is HTTP code
273
+ }
274
+ return !queue_results.empty();
275
+ });
276
+
277
+ for (size_t i = 0; i < queue_results.size(); i++) {
278
+ if (id_tasks.find(queue_results[i]->id) != id_tasks.end()) {
279
+ server_task_result_ptr res = std::move(queue_results[i]);
280
+ queue_results.erase(queue_results.begin() + i);
281
+ return res;
282
+ }
283
+ }
284
+ }
285
+
286
+ // should never reach here
287
+ }
288
+
289
+ server_task_result_ptr server_response::recv_with_timeout(const std::unordered_set<int> & id_tasks, int timeout) {
290
+ while (true) {
291
+ std::unique_lock<std::mutex> lock(mutex_results);
292
+
293
+ for (int i = 0; i < (int) queue_results.size(); i++) {
294
+ if (id_tasks.find(queue_results[i]->id) != id_tasks.end()) {
295
+ server_task_result_ptr res = std::move(queue_results[i]);
296
+ queue_results.erase(queue_results.begin() + i);
297
+ return res;
298
+ }
299
+ }
300
+
301
+ std::cv_status cr_res = condition_results.wait_for(lock, std::chrono::seconds(timeout));
302
+ if (!running) {
303
+ RES_DBG("%s : queue result stop\n", __func__);
304
+ std::terminate(); // we cannot return here since the caller is HTTP code
305
+ }
306
+ if (cr_res == std::cv_status::timeout) {
307
+ return nullptr;
308
+ }
309
+ }
310
+
311
+ // should never reach here
312
+ }
313
+
314
+ server_task_result_ptr server_response::recv(int id_task) {
315
+ std::unordered_set<int> id_tasks = {id_task};
316
+ return recv(id_tasks);
317
+ }
318
+
319
+ void server_response::send(server_task_result_ptr && result) {
320
+ RES_DBG("sending result for task id = %d\n", result->id);
321
+
322
+ std::unique_lock<std::mutex> lock(mutex_results);
323
+ for (const auto & id_task : waiting_task_ids) {
324
+ if (result->id == id_task) {
325
+ RES_DBG("task id = %d pushed to result queue\n", result->id);
326
+
327
+ queue_results.emplace_back(std::move(result));
328
+ condition_results.notify_all();
329
+ return;
330
+ }
331
+ }
332
+ }
333
+
334
+ void server_response::broadcast(server_task_result_ptr && result) {
335
+ std::unique_lock<std::mutex> lock(mutex_results);
336
+ for (const auto & id_task : waiting_task_ids) {
337
+ RES_DBG("task id = %d pushed to result queue\n", id_task);
338
+ server_task_result_ptr res_copy(result->clone());
339
+ res_copy->id = id_task; // override id with target task id
340
+ queue_results.emplace_back(std::move(res_copy));
341
+ }
342
+ condition_results.notify_all();
343
+ }
344
+
345
+ void server_response::terminate() {
346
+ running = false;
347
+ condition_results.notify_all();
348
+ }
349
+
350
+ //
351
+ // server_response_reader
352
+ //
353
+
354
+ void server_response_reader::post_task(server_task && task, bool front) {
355
+ GGML_ASSERT(id_tasks.empty() && "post_task() can only be called once per reader");
356
+ GGML_ASSERT(!task.is_parent() && "not supported, use post_tasks() instead");
357
+ task.index = 0;
358
+ id_tasks.insert(task.id);
359
+ states.push_back(task.create_state());
360
+ queue_results.add_waiting_task_id(task.id);
361
+ queue_tasks.post(std::move(task), front);
362
+ }
363
+
364
+ void server_response_reader::post_tasks(std::vector<server_task> && tasks, bool front) {
365
+ GGML_ASSERT(id_tasks.empty() && "post_tasks() can only be called once per reader");
366
+ id_tasks = server_task::get_list_id(tasks);
367
+ states.reserve(tasks.size());
368
+ size_t index = 0;
369
+ for (auto & task : tasks) {
370
+ task.index = index++;
371
+ states.push_back(task.create_state());
372
+ // for child tasks
373
+ for (auto & child_task : task.child_tasks) {
374
+ child_task.index = index++;
375
+ states.push_back(child_task.create_state());
376
+ }
377
+ }
378
+ GGML_ASSERT(states.size() == id_tasks.size());
379
+ queue_results.add_waiting_task_ids(id_tasks);
380
+ queue_tasks.post(std::move(tasks), front);
381
+ }
382
+
383
+ bool server_response_reader::has_next() const {
384
+ return !cancelled && received_count < id_tasks.size();
385
+ }
386
+
387
+ // return nullptr if should_stop() is true before receiving a result
388
+ // note: if one error is received, it will stop further processing and return error result
389
+ server_task_result_ptr server_response_reader::next(const std::function<bool()> & should_stop) {
390
+ while (true) {
391
+ server_task_result_ptr result = queue_results.recv_with_timeout(id_tasks, polling_interval_seconds);
392
+ if (result == nullptr) {
393
+ // timeout, check stop condition
394
+ if (should_stop()) {
395
+ return nullptr;
396
+ }
397
+ } else {
398
+ if (result->is_error()) {
399
+ stop(); // cancel remaining tasks
400
+ SRV_DBG("%s", "received error result, stopping further processing\n");
401
+ return result;
402
+ }
403
+ if (!states.empty()) {
404
+ // update the generation state if needed
405
+ const size_t idx = result->index;
406
+ GGML_ASSERT(idx < states.size());
407
+ result->update(states[idx]);
408
+ }
409
+ if (result->is_stop()) {
410
+ received_count++;
411
+ }
412
+ return result;
413
+ }
414
+ }
415
+
416
+ // should not reach here
417
+ }
418
+
419
+ server_response_reader::batch_response server_response_reader::wait_for_all(const std::function<bool()> & should_stop) {
420
+ batch_response batch_res;
421
+ batch_res.results.clear();
422
+ batch_res.results.resize(id_tasks.size());
423
+ while (has_next()) {
424
+ auto res = next(should_stop);
425
+ if (res == nullptr) {
426
+ batch_res.is_terminated = true;
427
+ return batch_res;
428
+ }
429
+ if (res->is_error()) {
430
+ batch_res.error = std::move(res);
431
+ return batch_res;
432
+ }
433
+ const size_t idx = res->index;
434
+ GGML_ASSERT(idx < batch_res.results.size() && "index out of range");
435
+ GGML_ASSERT(batch_res.results[idx] == nullptr && "duplicate result received");
436
+ batch_res.results[idx] = std::move(res);
437
+ }
438
+ return batch_res;
439
+ }
440
+
441
+ void server_response_reader::stop() {
442
+ queue_results.remove_waiting_task_ids(id_tasks);
443
+ if (has_next() && !cancelled) {
444
+ // if tasks is not finished yet, cancel them
445
+ cancelled = true;
446
+ std::vector<server_task> cancel_tasks;
447
+ cancel_tasks.reserve(id_tasks.size());
448
+ for (const auto & id_task : id_tasks) {
449
+ SRV_WRN("cancel task, id_task = %d\n", id_task);
450
+ server_task task(SERVER_TASK_TYPE_CANCEL);
451
+ task.id_target = id_task;
452
+ queue_results.remove_waiting_task_id(id_task);
453
+ cancel_tasks.push_back(std::move(task));
454
+ }
455
+ // push to beginning of the queue, so it has highest priority
456
+ queue_tasks.post(std::move(cancel_tasks), true);
457
+ } else {
458
+ SRV_DBG("%s", "all tasks already finished, no need to cancel\n");
459
+ }
460
+ }
tools/server/server-queue.h ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include "server-task.h"
4
+
5
+ #include <condition_variable>
6
+ #include <deque>
7
+ #include <mutex>
8
+ #include <vector>
9
+ #include <unordered_set>
10
+
11
+ // struct for managing server tasks
12
+ // in most cases, use server_response_reader to post new tasks and retrieve results
13
+ struct server_queue {
14
+ private:
15
+ int id = 0;
16
+ bool running = false;
17
+ bool sleeping = false;
18
+ bool req_stop_sleeping = false;
19
+ int64_t time_last_task = 0;
20
+
21
+ // queues
22
+ std::deque<server_task> queue_tasks;
23
+ std::deque<server_task> queue_tasks_deferred;
24
+
25
+ std::mutex mutex_tasks;
26
+ std::condition_variable condition_tasks;
27
+
28
+ // callback functions
29
+ std::function<void(server_task &&)> callback_new_task;
30
+ std::function<void(void)> callback_update_slots;
31
+ std::function<void(bool)> callback_sleeping_state;
32
+
33
+ public:
34
+ // Add a new task to the end of the queue
35
+ int post(server_task && task, bool front = false);
36
+
37
+ // multi-task version of post()
38
+ int post(std::vector<server_task> && tasks, bool front = false);
39
+
40
+ // Add a new task, but defer until one slot is available
41
+ void defer(server_task && task);
42
+
43
+ // Get the next id for creating a new task
44
+ int get_new_id();
45
+
46
+ // Call when the state of one slot is changed, it will move one task from deferred to main queue
47
+ // prioritize tasks that use the specified slot (otherwise, pop the first deferred task)
48
+ void pop_deferred_task(int id_slot);
49
+
50
+ // if sleeping, request exiting sleep state and wait until it is done
51
+ // returns immediately if not sleeping
52
+ void wait_until_no_sleep();
53
+
54
+ bool is_sleeping() {
55
+ std::unique_lock<std::mutex> lock(mutex_tasks);
56
+ return sleeping;
57
+ }
58
+
59
+ // end the start_loop routine
60
+ void terminate();
61
+
62
+ /**
63
+ * Main loop consists of these steps:
64
+ * - Wait until a new task arrives
65
+ * - Process the task (i.e. maybe copy data into slot)
66
+ * - Check if multitask is finished
67
+ * - Update all slots
68
+ *
69
+ * Sleeping procedure (disabled if idle_sleep_ms < 0):
70
+ * - If there is no task after idle_sleep_ms, enter sleeping state
71
+ * - Call callback_sleeping_state(true)
72
+ * - Wait until req_stop_sleeping is set to true
73
+ * - Call callback_sleeping_state(false)
74
+ * - Exit sleeping state
75
+ */
76
+ void start_loop(int64_t idle_sleep_ms = -1);
77
+
78
+ // for metrics
79
+ size_t queue_tasks_deferred_size() {
80
+ std::unique_lock<std::mutex> lock(mutex_tasks);
81
+ return queue_tasks_deferred.size();
82
+ }
83
+
84
+ //
85
+ // Functions below are not thread-safe, must only be used before start_loop() is called
86
+ //
87
+
88
+ // Register function to process a new task
89
+ void on_new_task(std::function<void(server_task &&)> callback) {
90
+ callback_new_task = std::move(callback);
91
+ }
92
+
93
+ // Register the function to be called when all slots data is ready to be processed
94
+ void on_update_slots(std::function<void(void)> callback) {
95
+ callback_update_slots = std::move(callback);
96
+ }
97
+
98
+ // Register callback for sleeping state change; multiple callbacks are allowed
99
+ // note: when entering sleeping state, the callback is called AFTER sleeping is set to true
100
+ // when leaving sleeping state, the callback is called BEFORE sleeping is set to false
101
+ void on_sleeping_state(std::function<void(bool)> callback) {
102
+ if (callback_sleeping_state) {
103
+ auto prev_callback = std::move(callback_sleeping_state);
104
+ callback_sleeping_state = [prev_callback, callback](bool sleeping) {
105
+ prev_callback(sleeping);
106
+ callback(sleeping);
107
+ };
108
+ } else {
109
+ callback_sleeping_state = std::move(callback);
110
+ }
111
+ }
112
+
113
+ private:
114
+ void cleanup_pending_task(int id_target);
115
+ };
116
+
117
+ // struct for managing server responses
118
+ // in most cases, use server_response_reader to retrieve results
119
+ struct server_response {
120
+ private:
121
+ bool running = true;
122
+
123
+ // for keeping track of all tasks waiting for the result
124
+ std::unordered_set<int> waiting_task_ids;
125
+
126
+ // the main result queue (using ptr for polymorphism)
127
+ std::vector<server_task_result_ptr> queue_results;
128
+
129
+ std::mutex mutex_results;
130
+ std::condition_variable condition_results;
131
+
132
+ public:
133
+ // add the id_task to the list of tasks waiting for response
134
+ void add_waiting_task_id(int id_task);
135
+
136
+ void add_waiting_task_ids(const std::unordered_set<int> & id_tasks);
137
+
138
+ // when the request is finished, we can remove task associated with it
139
+ void remove_waiting_task_id(int id_task);
140
+
141
+ // remove multiple tasks from waiting list
142
+ void remove_waiting_task_ids(const std::unordered_set<int> & id_tasks);
143
+
144
+ // This function blocks the thread until there is a response for one of the id_tasks
145
+ server_task_result_ptr recv(const std::unordered_set<int> & id_tasks);
146
+
147
+ // same as recv(), but have timeout in seconds
148
+ // if timeout is reached, nullptr is returned
149
+ server_task_result_ptr recv_with_timeout(const std::unordered_set<int> & id_tasks, int timeout);
150
+
151
+ // single-task version of recv()
152
+ server_task_result_ptr recv(int id_task);
153
+
154
+ // Send a new result to a waiting id_task
155
+ void send(server_task_result_ptr && result);
156
+
157
+ // broadcast a new result to all waiting tasks
158
+ // (used by router mode)
159
+ void broadcast(server_task_result_ptr && result);
160
+
161
+ // terminate the waiting loop
162
+ void terminate();
163
+ };
164
+
165
+ // RAII wrapper to make working with server_queue and server_response easier
166
+ // it provides a generator-like API for server responses
167
+ // support pooling connection state and aggregating multiple results
168
+ struct server_response_reader {
169
+ std::unordered_set<int> id_tasks;
170
+ server_queue & queue_tasks;
171
+ server_response & queue_results;
172
+ size_t received_count = 0;
173
+ bool cancelled = false;
174
+ int polling_interval_seconds;
175
+
176
+ // tracking generation state and partial tool calls
177
+ // only used by streaming completions
178
+ std::vector<task_result_state> states;
179
+
180
+ // should_stop function will be called each polling_interval_seconds
181
+ server_response_reader(server_queue & queue_tasks, server_response & queue_results, int polling_interval_seconds)
182
+ : queue_tasks(queue_tasks), queue_results(queue_results), polling_interval_seconds(polling_interval_seconds) {}
183
+ ~server_response_reader() {
184
+ stop();
185
+ }
186
+
187
+ int get_new_id() {
188
+ return queue_tasks.get_new_id();
189
+ }
190
+
191
+ // if front = true, the task will be posted to the front of the queue (high priority)
192
+ void post_task(server_task && task, bool front = false);
193
+ void post_tasks(std::vector<server_task> && tasks, bool front = false);
194
+ bool has_next() const;
195
+
196
+ // return nullptr if should_stop() is true before receiving a result
197
+ // note: if one error is received, it will stop further processing and return error result
198
+ server_task_result_ptr next(const std::function<bool()> & should_stop);
199
+
200
+ struct batch_response {
201
+ bool is_terminated = false; // if true, indicates that processing was stopped before all results were received
202
+ std::vector<server_task_result_ptr> results;
203
+ server_task_result_ptr error; // nullptr if no error
204
+ };
205
+ // aggregate multiple results
206
+ batch_response wait_for_all(const std::function<bool()> & should_stop);
207
+
208
+ void stop();
209
+ };
tools/server/server-schema.cpp ADDED
@@ -0,0 +1,659 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "server-schema.h"
2
+
3
+ #include "json-schema-to-grammar.h"
4
+
5
+ namespace server_schema {
6
+
7
+ //
8
+ // llama.cpp-specific completion schema
9
+ //
10
+
11
+ std::vector<std::unique_ptr<field>> make_llama_cmpl_schema(const common_params & params_base, task_params & params) {
12
+ std::vector<std::unique_ptr<field>> fields;
13
+ auto add = [&](field * f) {
14
+ fields.emplace_back(f);
15
+ };
16
+
17
+ add((new field_bool("verbose", params.verbose))
18
+ ->set_desc("Include __verbose field in the response with additional debug information"));
19
+
20
+ add((new field_bool("timings_per_token", params.timings_per_token))
21
+ ->set_desc("Include prompt processing and text generation speed information in each response"));
22
+
23
+ add((new field_bool("stream", params.stream))
24
+ ->set_desc("Allows receiving each predicted token in real-time instead of waiting for the completion to finish"));
25
+
26
+ add((new field_nested("stream_options"))
27
+ ->add_subfield((new field_bool("include_usage", params.include_usage))
28
+ ->set_desc("Whether to include usage information in the stream"))
29
+ ->set_desc("Additional options for streaming responses"));
30
+
31
+ add((new field_bool("cache_prompt", params.cache_prompt))
32
+ ->set_desc("Re-use KV cache from a previous request if possible. This way the common prefix does not have to be re-processed, only the suffix that differs between the requests"));
33
+
34
+ add((new field_bool("return_tokens", params.return_tokens))
35
+ ->set_desc("Return the raw generated token ids in the `tokens` field"));
36
+
37
+ add((new field_bool("return_progress", params.return_progress))
38
+ ->set_desc("Include prompt processing progress events in stream mode"));
39
+
40
+ add((new field_num("sse_ping_interval", params.sse_ping_interval))
41
+ ->set_hard_limits(-1, INT32_MAX)
42
+ ->set_desc("Interval in seconds between SSE comment pings emitted while the stream stays silent, -1 disables pings"));
43
+
44
+ add((new field_num("n_predict", params.n_predict))
45
+ ->set_hard_limits(-1, INT32_MAX)
46
+ ->add_alias("max_completion_tokens")
47
+ ->add_alias("max_tokens")
48
+ ->set_desc("Set the maximum number of tokens to predict. When 0, no tokens will be generated but the prompt is evaluated into the cache"));
49
+
50
+ add((new field_num("n_indent", params.n_indent))
51
+ ->set_hard_limits(0, INT32_MAX)
52
+ ->set_desc("Specify the minimum line indentation for the generated text in number of whitespace characters. Useful for code completion tasks"));
53
+
54
+ add((new field_num("n_keep", params.n_keep))
55
+ ->set_hard_limits(-1, INT32_MAX)
56
+ ->set_desc("Specify the number of tokens from the initial prompt to retain when context size is exceeded. Use -1 to retain all tokens from the prompt"));
57
+
58
+ add((new field_num("n_discard", params.n_discard))
59
+ ->set_hard_limits(0, INT32_MAX)
60
+ ->set_desc("Number of tokens after n_keep that may be discarded when shifting context (0 = half context)"));
61
+
62
+ add((new field_num("n_cmpl", params.n_cmpl))
63
+ ->set_hard_limits(1, params_base.n_parallel)
64
+ ->add_alias("n") // alias "n" as fallback (OpenAI completions API)
65
+ ->set_desc("Number of completions to generate. If the input has multiple prompts, total outputs will be N prompts times n_cmpl"));
66
+
67
+ add((new field_num("n_cache_reuse", params.n_cache_reuse))
68
+ ->set_hard_limits(0, INT32_MAX)
69
+ ->set_desc("Min chunk size to attempt reusing from the cache via KV shifting. See --cache-reuse arg"));
70
+
71
+ // TODO: implement t_max_prompt_ms
72
+ // add((new field_num("t_max_prompt_ms", params.t_max_prompt_ms))
73
+
74
+ add((new field_num("t_max_predict_ms", params.t_max_predict_ms))
75
+ ->set_hard_limits(-1, std::numeric_limits<int64_t>::max())
76
+ ->set_desc("Set a time limit in milliseconds for the prediction phase. The timeout triggers if generation exceeds this time (measured since the first token) and a newline has been generated. Useful for FIM applications"));
77
+
78
+ add((new field_json("response_fields"))
79
+ ->set_desc("A list of response fields to return. Missing fields are omitted without error. Fields with a slash are unnested (e.g. generation_settings/n_predict moves n_predict to the root)")
80
+ ->set_handler([&](field_eval_context & ctx, const json & data) {
81
+ ctx.params.response_fields = json_value(data, "response_fields", std::vector<std::string>());
82
+ }));
83
+
84
+
85
+ //
86
+ // Sampling params
87
+ //
88
+
89
+ add((new field_num("top_k", params.sampling.top_k))
90
+ ->set_limits(0, INT32_MAX)
91
+ ->set_desc("Limit the next token selection to the K most probable tokens (0 = disabled)"));
92
+
93
+ add((new field_num("top_p", params.sampling.top_p))
94
+ ->set_limits(0.0f, 1.0f)
95
+ ->set_desc("Limit the next token selection to a subset of tokens with cumulative probability above threshold P (1.0 = disabled)"));
96
+
97
+ add((new field_num("min_p", params.sampling.min_p))
98
+ ->set_limits(0.0f, 1.0f)
99
+ ->set_desc("The minimum probability for a token to be considered, relative to the probability of the most likely token (0 = disabled)"));
100
+
101
+ add((new field_num("top_n_sigma", params.sampling.top_n_sigma))
102
+ ->set_desc("Keep tokens within n standard deviations of the top token logit (< 0 = disabled)"));
103
+
104
+ add((new field_num("xtc_probability", params.sampling.xtc_probability))
105
+ ->set_limits(0.0f, 1.0f)
106
+ ->set_desc("Set the chance for token removal via XTC sampler (0 = disabled)"));
107
+
108
+ add((new field_num("xtc_threshold", params.sampling.xtc_threshold))
109
+ ->set_limits(0.0f, 1.0f)
110
+ ->set_desc("Set a minimum probability threshold for tokens to be removed via XTC sampler (> 0.5 disables XTC)"));
111
+
112
+ add((new field_num("typical_p", params.sampling.typ_p))
113
+ // ->set_limits(0.0f, 1.0f) // what's the valid range?
114
+ ->set_desc("Enable locally typical sampling with parameter p (1.0 = disabled)"));
115
+
116
+ add((new field_num("temperature", params.sampling.temp))
117
+ ->set_limits(0.0f, std::numeric_limits<float>::infinity())
118
+ ->set_desc("Adjust the randomness of the generated text (0 = greedy)"));
119
+
120
+ add((new field_num("dynatemp_range", params.sampling.dynatemp_range))
121
+ ->set_desc("Dynamic temperature range. The final temperature will be in [temperature - range, temperature + range] (0 = disabled)"));
122
+
123
+ add((new field_num("dynatemp_exponent", params.sampling.dynatemp_exponent))
124
+ ->set_desc("Dynamic temperature exponent, controls how entropy maps to temperature"));
125
+
126
+ add((new field_num("repeat_last_n", params.sampling.penalty_last_n))
127
+ ->set_hard_limits(0, INT32_MAX)
128
+ ->set_desc("Last n tokens to consider for penalizing repetition (0 = disabled)"));
129
+
130
+ add((new field_num("repeat_penalty", params.sampling.penalty_repeat))
131
+ ->set_desc("Control the repetition of token sequences in the generated text (1.0 = disabled)"));
132
+
133
+ add((new field_num("frequency_penalty", params.sampling.penalty_freq))
134
+ ->set_desc("Repeat alpha frequency penalty (0 = disabled)"));
135
+
136
+ add((new field_num("presence_penalty", params.sampling.penalty_present))
137
+ ->set_desc("Repeat alpha presence penalty (0 = disabled)"));
138
+
139
+ add((new field_num("dry_multiplier", params.sampling.dry_multiplier))
140
+ ->set_desc("Set the DRY (Don't Repeat Yourself) repetition penalty multiplier (0 = disabled)"));
141
+
142
+ add((new field_num("dry_base", params.sampling.dry_base))
143
+ ->set_desc("Set the DRY repetition penalty base value (must be >= 1.0, any values < 1.0 will be replaced with the default value)")
144
+ ->set_handler([&](field_eval_context & ctx, const json & data) {
145
+ float v = data.at("dry_base").get<float>();
146
+ ctx.params.sampling.dry_base = (v < 1.0f) ? params_base.sampling.dry_base : v;
147
+ }));
148
+
149
+ add((new field_num("dry_allowed_length", params.sampling.dry_allowed_length))
150
+ ->set_hard_limits(0, INT32_MAX)
151
+ ->set_desc("Tokens that extend repetition beyond this length receive exponentially increasing penalty: multiplier * base ^ (sequence_length - allowed_length)"));
152
+
153
+ add((new field_num("dry_penalty_last_n", params.sampling.dry_penalty_last_n))
154
+ ->set_hard_limits(0, INT32_MAX)
155
+ ->set_desc("How many tokens to scan for repetitions (0 = disabled)"));
156
+
157
+ add((new field_num("mirostat", params.sampling.mirostat))
158
+ ->set_limits(0, 2)
159
+ ->set_desc("Enable Mirostat sampling, controlling perplexity during text generation (0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0)"));
160
+
161
+ add((new field_num("mirostat_tau", params.sampling.mirostat_tau))
162
+ ->set_desc("Set the Mirostat target entropy, parameter tau"));
163
+
164
+ add((new field_num("mirostat_eta", params.sampling.mirostat_eta))
165
+ ->set_desc("Set the Mirostat learning rate, parameter eta"));
166
+
167
+ add((new field_num("adaptive_target", params.sampling.adaptive_target))
168
+ ->set_limits(-std::numeric_limits<float>::max(), 1.0f)
169
+ ->set_desc("Adaptive sampling target entropy (valid range 0.0 to 1.0; negative = disabled)"));
170
+
171
+ add((new field_num("adaptive_decay", params.sampling.adaptive_decay))
172
+ ->set_hard_limits(0.0f, 0.99f)
173
+ ->set_desc("EMA decay for adaptive sampling; history approximates 1/(1-decay) tokens"));
174
+
175
+ // seed is uint32_t; field_num uses int32_t so use a handler
176
+ add((new field_num("seed", params.sampling.seed))
177
+ ->set_desc("Set the random number generator (RNG) seed (-1 = random)"));
178
+
179
+ add((new field_num("n_probs", params.sampling.n_probs))
180
+ ->add_alias("logprobs") // use "logprobs" if "n_probs" wasn't provided
181
+ ->set_desc("If greater than 0, output the probabilities of top N tokens for each generated token"));
182
+
183
+ add((new field_num("min_keep", params.sampling.min_keep))
184
+ ->set_hard_limits(0, INT32_MAX)
185
+ ->set_desc("If greater than 0, force samplers to return at least N possible tokens"));
186
+
187
+ add((new field_bool("backend_sampling", params.sampling.backend_sampling))
188
+ ->set_desc("Use backend sampling instead of llama.cpp sampling"));
189
+
190
+ add((new field_bool("post_sampling_probs", params.post_sampling_probs))
191
+ ->set_desc("Return probabilities of top n_probs tokens after applying the sampling chain"));
192
+
193
+ //
194
+ // Speculative decoding params
195
+ //
196
+
197
+ // TODO: to keep things simple, we disable speculative parameter adjustments for now
198
+ #if 0
199
+ // TODO: for now, be able to adjust only the draft-model based speculative parameters
200
+ add((new field_num("speculative.n_max", params.speculative.draft.n_max))
201
+ ->set_hard_limits(0, INT32_MAX)
202
+ ->set_desc("Maximum number of tokens to draft during speculative decoding"));
203
+
204
+ add((new field_num("speculative.n_min", params.speculative.draft.n_min))
205
+ ->set_hard_limits(0, INT32_MAX)
206
+ ->set_desc("Minimum number of draft tokens to use for speculative decoding");
207
+
208
+ add((new field_num("speculative.p_min", params.speculative.draft.p_min))
209
+ ->set_hard_limits(0.0f, 1.0f)
210
+ ->set_desc("Minimum speculative decoding probability for draft tokens (0 = greedy)"));
211
+
212
+
213
+ add((new field_str("speculative.type"))
214
+ ->set_desc("Speculative decoding method (for debugging and research purposes)")
215
+ ->set_handler([&](field_eval_context & ctx, const json & data) {
216
+ ctx.params.speculative.types = { common_speculative_type_from_name(data.at("speculative.type").get<std::string>()) };
217
+ }));
218
+
219
+ add((new field_num("speculative.ngram_size_n", params.speculative.ngram_simple.size_n))
220
+ ->set_desc("Ngram size for lookup in ngram-based speculative decoding"));
221
+
222
+ add((new field_num("speculative.ngram_size_m", params.speculative.ngram_simple.size_m))
223
+ ->set_desc("Mgram size for speculative tokens in ngram-based speculative decoding"));
224
+
225
+ add((new field_num("speculative.ngram_min_hits", params.speculative.ngram_simple.min_hits))
226
+ ->set_desc("Minimum hits at ngram lookup for mgram to be proposed"));
227
+ #endif
228
+
229
+ add((new field_json("lora"))
230
+ ->set_desc("A list of LoRA adapters to apply to this request. Each entry must have `id` and `scale` fields. Adapters not listed default to scale 0.0")
231
+ ->set_handler([&](field_eval_context & ctx, const json & data) {
232
+ const auto & lora = data.at("lora");
233
+ if (!lora.is_array()) {
234
+ throw std::runtime_error("Error: 'lora' must be an array of objects with 'id' and 'scale' fields");
235
+ }
236
+ ctx.params.lora = parse_lora_request(lora);
237
+ }));
238
+
239
+ // sequence breakers for DRY
240
+ // Currently, this is not compatible with TextGen WebUI, Koboldcpp and SillyTavern format
241
+ // Ref: https://github.com/oobabooga/text-generation-webui/blob/d1af7a41ade7bd3c3a463bfa640725edb818ebaf/extensions/openai/typing.py#L39
242
+ add((new field_json("dry_sequence_breakers"))
243
+ ->set_desc("Specify an array of sequence breakers for DRY sampling. Only a JSON array of strings is accepted")
244
+ ->set_handler([&](field_eval_context & ctx, const json & data) {
245
+ ctx.params.sampling.dry_sequence_breakers = json_value(data, "dry_sequence_breakers", std::vector<std::string>());
246
+ if (ctx.params.sampling.dry_sequence_breakers.empty()) {
247
+ throw std::runtime_error("Error: dry_sequence_breakers must be a non-empty array of strings");
248
+ }
249
+ }));
250
+
251
+ // handle both "json_schema" and "grammar"
252
+ add((new field_json("json_schema"))
253
+ ->add_alias("grammar")
254
+ ->set_desc("Set a JSON schema (json_schema) or GBNF grammar string (grammar) for constrained generation. json_schema takes precedence if both are provided")
255
+ ->set_handler([&](field_eval_context & ctx, const json & data) {
256
+ auto & params = ctx.params;
257
+ if (data.contains("json_schema") && !data.contains("grammar")) {
258
+ try {
259
+ auto schema = json_value(data, "json_schema", json::object());
260
+ SRV_DBG("JSON schema: %s\n", schema.dump(2).c_str());
261
+ std::string grammar_str = json_schema_to_grammar(schema);
262
+ SRV_DBG("Converted grammar: %s\n", grammar_str.c_str());
263
+ params.sampling.grammar = {COMMON_GRAMMAR_TYPE_OUTPUT_FORMAT, std::move(grammar_str)};
264
+ } catch (const std::exception & e) {
265
+ throw std::runtime_error(std::string("\"json_schema\": ") + e.what());
266
+ }
267
+ } else {
268
+ std::string grammar_str = json_value(data, "grammar", std::string());
269
+ if (!grammar_str.empty()) {
270
+ // grammar_type key is set by the server when converting chat template grammars
271
+ std::string grammar_type = json_value(data, "grammar_type", std::string());
272
+ if (grammar_type == "tool_calls") {
273
+ params.sampling.grammar = {COMMON_GRAMMAR_TYPE_TOOL_CALLS, std::move(grammar_str)};
274
+ } else {
275
+ // explicit grammar from the user (API field "grammar")
276
+ params.sampling.grammar = {COMMON_GRAMMAR_TYPE_USER, std::move(grammar_str)};
277
+ }
278
+ SRV_DBG("Grammar (%s): %s\n", grammar_type.c_str(), common_grammar_value(params.sampling.grammar).c_str());
279
+ }
280
+ }
281
+ }));
282
+
283
+ add((new field_bool("grammar_lazy", params.sampling.grammar_lazy))
284
+ ->set_desc("Whether to apply grammar constraints lazily, only when triggered (instead of at every step)"));
285
+
286
+ //
287
+ // Chat parser params
288
+ //
289
+
290
+ // TODO: change this to string field instead
291
+ add((new field_json("chat_format"))
292
+ ->set_desc("Chat format used internally by the server")
293
+ ->set_handler([&](field_eval_context & ctx, const json & data) {
294
+ ctx.params.chat_parser_params.format = static_cast<common_chat_format>(data.at("chat_format").get<int>());
295
+ SRV_TRC("chat format: %s\n", common_chat_format_name(ctx.params.chat_parser_params.format));
296
+ }));
297
+
298
+ add((new field_str("reasoning_format"))
299
+ ->set_desc("Reasoning format for chain-of-thought models")
300
+ ->set_handler([&](field_eval_context & ctx, const json & data) {
301
+ auto reasoning_format = common_reasoning_format_from_name(data.at("reasoning_format").get<std::string>());
302
+ ctx.params.chat_parser_params.reasoning_format = reasoning_format;
303
+ ctx.params.chat_parser_params.reasoning_in_content = ctx.params.stream && (reasoning_format == COMMON_REASONING_FORMAT_DEEPSEEK_LEGACY);
304
+ }));
305
+
306
+ add((new field_str("generation_prompt"))
307
+ ->set_desc("Generation prompt appended to the chat template output")
308
+ ->set_handler([&](field_eval_context & ctx, const json & data) {
309
+ std::string s = data.at("generation_prompt").get<std::string>();
310
+ ctx.params.chat_parser_params.generation_prompt = s;
311
+ ctx.params.sampling.generation_prompt = s;
312
+ }));
313
+
314
+ add((new field_bool("parse_tool_calls", params.chat_parser_params.parse_tool_calls))
315
+ ->set_desc("Whether to parse tool calls from the generated output"));
316
+
317
+ add((new field_str("chat_parser"))
318
+ ->set_desc("Chat parser configuration string")
319
+ ->set_handler([&](field_eval_context & ctx, const json & data) {
320
+ ctx.params.chat_parser_params.parser.load(data.at("chat_parser").get<std::string>());
321
+ }));
322
+
323
+ add((new field_json("continue_final_message"))
324
+ ->set_desc("Whether to continue the final message of the chat template")
325
+ ->set_handler([&](field_eval_context & ctx, const json & data) {
326
+ auto continuation = common_chat_continuation_parse(data.at("continue_final_message"));
327
+ ctx.params.chat_parser_params.is_continuation = continuation != COMMON_CHAT_CONTINUATION_NONE;
328
+ }));
329
+
330
+ add((new field_bool("echo", params.chat_parser_params.echo))
331
+ ->set_desc("Whether to echo the input tokens in the output"));
332
+
333
+ //
334
+ // Token-level fields (require vocab)
335
+ //
336
+
337
+ add((new field_json("preserved_tokens"))
338
+ ->set_desc("List of token strings that must not be split during tokenization")
339
+ ->set_handler([&](field_eval_context & ctx, const json & data) {
340
+ GGML_ASSERT(ctx.vocab != nullptr);
341
+ for (const auto & t : data.at("preserved_tokens")) {
342
+ auto ids = common_tokenize(ctx.vocab, t.get<std::string>(), false, true);
343
+ if (ids.size() == 1) {
344
+ ctx.params.sampling.preserved_tokens.insert(ids[0]);
345
+ }
346
+ }
347
+ }));
348
+
349
+ add((new field_json("grammar_triggers"))
350
+ ->set_desc("List of strings or patterns that trigger grammar-constrained generation")
351
+ ->set_handler([&](field_eval_context & ctx, const json & data) {
352
+ GGML_ASSERT(ctx.vocab != nullptr);
353
+ for (const auto & t : data.at("grammar_triggers")) {
354
+ server_grammar_trigger ct(t);
355
+ if (ct.value.type == COMMON_GRAMMAR_TRIGGER_TYPE_WORD) {
356
+ const auto & word = ct.value.value;
357
+ auto ids = common_tokenize(ctx.vocab, word, false, true);
358
+ if (ids.size() == 1) {
359
+ auto token = ids[0];
360
+ if (std::find(ctx.params.sampling.preserved_tokens.begin(), ctx.params.sampling.preserved_tokens.end(), (llama_token) token) == ctx.params.sampling.preserved_tokens.end()) {
361
+ throw std::runtime_error("Grammar trigger word should be marked as preserved token: " + word);
362
+ }
363
+ common_grammar_trigger trigger;
364
+ trigger.type = COMMON_GRAMMAR_TRIGGER_TYPE_TOKEN;
365
+ trigger.value = word;
366
+ trigger.token = token;
367
+ ctx.params.sampling.grammar_triggers.push_back(std::move(trigger));
368
+ } else {
369
+ ctx.params.sampling.grammar_triggers.push_back({COMMON_GRAMMAR_TRIGGER_TYPE_WORD, word});
370
+ }
371
+ } else {
372
+ ctx.params.sampling.grammar_triggers.emplace_back(std::move(ct.value));
373
+ }
374
+ }
375
+ if (ctx.params.sampling.grammar_lazy && ctx.params.sampling.grammar_triggers.empty()) {
376
+ throw std::runtime_error("Error: no triggers set for lazy grammar!");
377
+ }
378
+ }));
379
+
380
+ add((new field_bool("reasoning_control", params.sampling.reasoning_control))
381
+ ->set_desc("Create the budget sampler on demand so reasoning can be ended at runtime"));
382
+
383
+ add((new field_num("reasoning_budget_tokens", params.sampling.reasoning_budget_tokens))
384
+ ->set_hard_limits(-1, INT32_MAX)
385
+ ->set_desc("Number of tokens in the reasoning budget (-1 = disabled)"));
386
+
387
+ add((new field_str("reasoning_budget_start_tag"))
388
+ ->set_desc("Token string marking the start of the reasoning budget section")
389
+ ->set_handler([&](field_eval_context & ctx, const json & data) {
390
+ GGML_ASSERT(ctx.vocab != nullptr);
391
+ ctx.params.sampling.reasoning_budget_start = common_tokenize(ctx.vocab, data.at("reasoning_budget_start_tag").get<std::string>(), false, true);
392
+ }));
393
+
394
+ add((new field_json("reasoning_budget_end_tags"))
395
+ ->add_alias("reasoning_budget_end_tag")
396
+ ->set_desc("Token strings marking the end of the reasoning budget section; the first is forced when the budget expires")
397
+ ->set_handler([&](field_eval_context & ctx, const json & data) {
398
+ GGML_ASSERT(ctx.vocab != nullptr);
399
+ ctx.params.sampling.reasoning_budget_end.clear();
400
+ if (data.contains("reasoning_budget_end_tags")) {
401
+ for (const auto & t : data.at("reasoning_budget_end_tags")) {
402
+ std::string tag = t.get<std::string>();
403
+ if (!tag.empty()) {
404
+ ctx.params.sampling.reasoning_budget_end.push_back(common_tokenize(ctx.vocab, tag, false, true));
405
+ }
406
+ }
407
+ } else if (data.contains("reasoning_budget_end_tag")) {
408
+ std::string tag = data.at("reasoning_budget_end_tag").get<std::string>();
409
+ if (!tag.empty()) {
410
+ ctx.params.sampling.reasoning_budget_end.push_back(common_tokenize(ctx.vocab, tag, false, true));
411
+ }
412
+ }
413
+ }));
414
+
415
+ add((new field_str("reasoning_budget_message"))
416
+ ->set_desc("Message to prepend to the reasoning budget end tag when forcing it")
417
+ ->set_handler([&](field_eval_context & ctx, const json & data) {
418
+ GGML_ASSERT(ctx.vocab != nullptr);
419
+ if (!ctx.params.sampling.reasoning_budget_end.empty()) {
420
+ llama_tokens end_tag = ctx.params.sampling.reasoning_budget_end.front();
421
+ std::string message = json_value(data, "reasoning_budget_message", std::string());
422
+ if (!message.empty()) {
423
+ llama_tokens message_tokens = common_tokenize(ctx.vocab, message, false, true);
424
+ end_tag.insert(end_tag.begin(), message_tokens.begin(), message_tokens.end());
425
+ }
426
+ ctx.params.sampling.reasoning_budget_forced = std::move(end_tag);
427
+ }
428
+ }));
429
+
430
+ add((new field_json("logit_bias"))
431
+ ->set_desc("Modify the likelihood of specific tokens. Accepts an array of [token, bias] pairs or an object mapping token to bias. Use false as bias to ban a token")
432
+ ->set_handler([&](field_eval_context & ctx, const json & data) {
433
+ GGML_ASSERT(ctx.vocab != nullptr);
434
+ ctx.params.sampling.logit_bias.clear();
435
+ const auto & logit_bias = data.at("logit_bias");
436
+ const int n_vocab = llama_vocab_n_tokens(ctx.vocab);
437
+ auto parse_bias = [](const json & v, float & bias) -> bool {
438
+ if (v.is_number()) { bias = v.get<float>(); return true; }
439
+ if (v.is_boolean() && !v.get<bool>()) { bias = -INFINITY; return true; }
440
+ return false;
441
+ };
442
+ if (logit_bias.is_array()) {
443
+ for (const auto & el : logit_bias) {
444
+ if (!el.is_array() || el.size() != 2) continue;
445
+ float bias;
446
+ if (!parse_bias(el[1], bias)) continue;
447
+ if (el[0].is_number_integer()) {
448
+ llama_token tok = el[0].get<llama_token>();
449
+ if (tok >= 0 && tok < n_vocab) ctx.params.sampling.logit_bias.push_back({tok, bias});
450
+ } else if (el[0].is_string()) {
451
+ for (auto tok : common_tokenize(ctx.vocab, el[0].get<std::string>(), false))
452
+ ctx.params.sampling.logit_bias.push_back({tok, bias});
453
+ }
454
+ }
455
+ } else if (logit_bias.is_object()) {
456
+ for (const auto & el : logit_bias.items()) {
457
+ float bias;
458
+ if (!parse_bias(el.value(), bias)) continue;
459
+ char * end;
460
+ llama_token tok = strtol(el.key().c_str(), &end, 10);
461
+ if (*end == 0) {
462
+ if (tok >= 0 && tok < n_vocab) ctx.params.sampling.logit_bias.push_back({tok, bias});
463
+ } else {
464
+ for (auto t : common_tokenize(ctx.vocab, el.key(), false))
465
+ ctx.params.sampling.logit_bias.push_back({t, bias});
466
+ }
467
+ }
468
+ }
469
+ }));
470
+
471
+ add((new field_bool("ignore_eos", params.sampling.ignore_eos))
472
+ ->set_desc("Ignore the end-of-sequence token and continue generating")
473
+ ->set_handler([&](field_eval_context & ctx, const json & data) {
474
+ GGML_ASSERT(ctx.logit_bias_eog != nullptr);
475
+ ctx.params.sampling.ignore_eos = data.at("ignore_eos").get<bool>();
476
+ if (ctx.params.sampling.ignore_eos && ctx.logit_bias_eog) {
477
+ ctx.params.sampling.logit_bias.insert(
478
+ ctx.params.sampling.logit_bias.end(),
479
+ ctx.logit_bias_eog->begin(), ctx.logit_bias_eog->end());
480
+ }
481
+ }));
482
+
483
+ add((new field_json("stop"))
484
+ ->set_desc("Specify stopping strings. Generation stops when one is produced, and the string is not included in the output")
485
+ ->set_handler([&](field_eval_context & ctx, const json & data) {
486
+ ctx.params.antiprompt.clear();
487
+ const auto & stop = data.at("stop");
488
+ if (stop.is_array()) {
489
+ for (const auto & word : stop) {
490
+ if (!word.empty()) ctx.params.antiprompt.push_back(word);
491
+ }
492
+ } else if (stop.is_string()) {
493
+ ctx.params.antiprompt.push_back(stop.get<std::string>());
494
+ }
495
+ // fall back to CLI defaults if the request provided no effective stop strings
496
+ if (ctx.params.antiprompt.empty()) {
497
+ ctx.params.antiprompt = params_base.antiprompt;
498
+ }
499
+ }));
500
+
501
+ add((new field_json("samplers"))
502
+ ->set_desc("The order in which samplers are applied. An array of sampler type names, or a single string of sampler chars")
503
+ ->set_handler([&](field_eval_context & ctx, const json & data) {
504
+ const auto & samplers = data.at("samplers");
505
+ if (samplers.is_array()) {
506
+ ctx.params.sampling.samplers = common_sampler_types_from_names(samplers);
507
+ } else if (samplers.is_string()) {
508
+ ctx.params.sampling.samplers = common_sampler_types_from_chars(samplers.get<std::string>());
509
+ }
510
+ }));
511
+
512
+ return fields;
513
+ }
514
+
515
+ task_params eval_llama_cmpl_schema(
516
+ const llama_vocab * vocab,
517
+ const common_params & params_base,
518
+ const std::vector<llama_logit_bias> & logit_bias_eog,
519
+ const json & data) {
520
+ task_params params;
521
+
522
+ // Sampling parameter defaults are loaded from the global server context (but individual requests can still override them)
523
+ params.sampling = params_base.sampling;
524
+ params.speculative = params_base.speculative;
525
+ params.n_keep = params_base.n_keep;
526
+ params.n_predict = params_base.n_predict;
527
+ params.n_cache_reuse = params_base.n_cache_reuse;
528
+ params.cache_prompt = params_base.cache_prompt;
529
+ params.antiprompt = params_base.antiprompt;
530
+ params.sse_ping_interval = params_base.sse_ping_interval;
531
+
532
+ // enabling this will output extra debug information in the HTTP responses from the server
533
+ params.verbose = params_base.verbosity > 9;
534
+
535
+ params.chat_parser_params.reasoning_format = params_base.reasoning_format;
536
+
537
+ // create context and schema
538
+ field_eval_context ctx(params);
539
+ ctx.vocab = vocab;
540
+ ctx.logit_bias_eog = &logit_bias_eog;
541
+
542
+ auto schema = make_llama_cmpl_schema(params_base, params);
543
+
544
+ // eval all fields in the schema
545
+ for (const auto & f : schema) {
546
+ f->eval(ctx, data);
547
+ }
548
+
549
+ // post-processing
550
+ {
551
+ // if "reasoning_format" is not provided, its handler will not be called, we will need to handle it here
552
+ auto reasoning_format = params.chat_parser_params.reasoning_format;
553
+ params.chat_parser_params.reasoning_in_content = params.stream && (reasoning_format == COMMON_REASONING_FORMAT_DEEPSEEK_LEGACY);
554
+ }
555
+
556
+ // debugging
557
+ {
558
+ auto budget = params.sampling.reasoning_budget_tokens;
559
+ SRV_DBG("reasoning budget: tokens=%d, generation_prompt='%s', start=%zu toks, end=%zu seqs, forced=%zu toks\n",
560
+ budget, params.sampling.generation_prompt.c_str(),
561
+ params.sampling.reasoning_budget_start.size(),
562
+ params.sampling.reasoning_budget_end.size(),
563
+ params.sampling.reasoning_budget_forced.size());
564
+ }
565
+
566
+ return params;
567
+ }
568
+
569
+ //
570
+ // eval() implementations
571
+ //
572
+
573
+ static void handle_with_catch(const char * name, std::function<void()> func) {
574
+ try {
575
+ func();
576
+ } catch (const std::exception & e) {
577
+ throw std::invalid_argument(string_format("Field '%s': %s", name, e.what()));
578
+ }
579
+ }
580
+
581
+ // treat a null value as absent so clients can send null to request the server default
582
+ static bool has_value(const json & data, const char * n) {
583
+ auto it = data.find(n);
584
+ return it != data.end() && !it->is_null();
585
+ }
586
+
587
+ template <typename T>
588
+ void field_num<T>::eval(field_eval_context & ctx, const json & data) {
589
+ for (const auto & n : name) {
590
+ if (has_value(data, n)) {
591
+ handle_with_catch(n, [&]() {
592
+ if (custom_handler) {
593
+ custom_handler(ctx, data);
594
+ } else if (!is_hard_limit) {
595
+ val = std::max(min, std::min(max, data.at(n).template get<T>()));
596
+ } else {
597
+ T tmp = data.at(n).template get<T>();
598
+ if (tmp < min || tmp > max) {
599
+ throw std::invalid_argument(std::string("Value must be between ") + std::to_string(min) + " <= value <= " + std::to_string(max) + ", but got " + std::to_string(tmp));
600
+ }
601
+ val = tmp;
602
+ }
603
+ });
604
+ return;
605
+ }
606
+ }
607
+ }
608
+
609
+ void field_str::eval(field_eval_context & ctx, const json & data) {
610
+ GGML_ASSERT(custom_handler);
611
+ for (const auto & n : name) {
612
+ if (has_value(data, n)) {
613
+ handle_with_catch(n, [&]() {
614
+ custom_handler(ctx, data);
615
+ });
616
+ return;
617
+ }
618
+ }
619
+ }
620
+
621
+ void field_bool::eval(field_eval_context & ctx, const json & data) {
622
+ for (const auto & n : name) {
623
+ if (has_value(data, n)) {
624
+ handle_with_catch(n, [&]() {
625
+ if (custom_handler) {
626
+ custom_handler(ctx, data);
627
+ } else {
628
+ val = data.at(n).get<bool>();
629
+ }
630
+ });
631
+ return;
632
+ }
633
+ }
634
+ }
635
+
636
+ void field_json::eval(field_eval_context & ctx, const json & data) {
637
+ GGML_ASSERT(custom_handler);
638
+ for (const auto & n : name) {
639
+ if (has_value(data, n)) {
640
+ handle_with_catch(n, [&]() {
641
+ custom_handler(ctx, data);
642
+ });
643
+ return;
644
+ }
645
+ }
646
+ }
647
+
648
+ void field_nested::eval(field_eval_context & ctx, const json & data) {
649
+ for (const auto & n : name) {
650
+ if (data.contains(n) && data.at(n).is_object()) {
651
+ for (auto & f : subfields) {
652
+ f->eval(ctx, data.at(n));
653
+ }
654
+ return;
655
+ }
656
+ }
657
+ }
658
+
659
+ } // namespace server_schema
tools/server/server-schema.h ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include "server-common.h"
4
+ #include "server-task.h"
5
+
6
+ #include "sampling.h"
7
+ #include "speculative.h"
8
+
9
+ #include <climits>
10
+ #include <functional>
11
+ #include <limits>
12
+ #include <memory>
13
+ #include <string>
14
+ #include <vector>
15
+
16
+ namespace server_schema {
17
+
18
+ struct field_eval_context {
19
+ task_params & params;
20
+ const llama_vocab * vocab = nullptr;
21
+ const std::vector<llama_logit_bias> * logit_bias_eog = nullptr;
22
+ field_eval_context(task_params & params) : params(params) {}
23
+ };
24
+
25
+ using field_handler = std::function<void(field_eval_context &, const json &)>;
26
+
27
+ struct field {
28
+ std::vector<const char *> name;
29
+ const char * desc = "";
30
+ field_handler custom_handler;
31
+ field() = default;
32
+ field(const char * n) : name({n}) {}
33
+ virtual ~field() = default;
34
+ field * set_desc(const char * s) {
35
+ desc = s;
36
+ return this;
37
+ }
38
+ // if 'name' is present, use it, otherwise look for aliases following the order they were added
39
+ field * add_alias(const char * n) {
40
+ name.push_back(n);
41
+ return this;
42
+ }
43
+ field * set_handler(field_handler h) { this->custom_handler = h; return this; }
44
+ virtual void eval(field_eval_context & ctx, const json & data) = 0;
45
+ };
46
+
47
+ template <typename T = int32_t>
48
+ struct field_num : public field {
49
+ T & val;
50
+ T min = std::numeric_limits<T>::lowest();
51
+ T max = std::numeric_limits<T>::max();
52
+ bool is_hard_limit = false; // if true, throw error if the value is invalid
53
+ field_num(const char * n, T & val) : field(n), val(val) {}
54
+ // limits are inclusive, min <= value <= max
55
+ field_num * set_limits(T min, T max) {
56
+ this->min = min;
57
+ this->max = max;
58
+ return this;
59
+ }
60
+ field_num * set_hard_limits(T min, T max) {
61
+ set_limits(min, max);
62
+ is_hard_limit = true;
63
+ return this;
64
+ }
65
+ virtual void eval(field_eval_context & ctx, const json & data) override;
66
+ };
67
+
68
+ struct field_str : public field {
69
+ field_str(const char * n) : field(n) {}
70
+ virtual void eval(field_eval_context & ctx, const json & data) override;
71
+ };
72
+
73
+ struct field_bool : public field {
74
+ bool & val;
75
+ field_bool(const char * n, bool & val) : field(n), val(val) {}
76
+ virtual void eval(field_eval_context & ctx, const json & data) override;
77
+ };
78
+
79
+ struct field_json : public field {
80
+ field_json(const char * n) : field(n) {}
81
+ virtual void eval(field_eval_context & ctx, const json & data) override;
82
+ };
83
+
84
+ struct field_nested : public field {
85
+ std::vector<std::unique_ptr<field>> subfields;
86
+ field_nested(const char * n) : field(n) {}
87
+ field_nested * add_subfield(field * f) {
88
+ subfields.emplace_back(std::unique_ptr<field>(f));
89
+ return this;
90
+ }
91
+ virtual void eval(field_eval_context & ctx, const json & data) override;
92
+ };
93
+
94
+ std::vector<std::unique_ptr<field>> make_llama_cmpl_schema(
95
+ const common_params & params_base,
96
+ task_params & params);
97
+
98
+ task_params eval_llama_cmpl_schema(
99
+ const llama_vocab * vocab,
100
+ const common_params & params_base,
101
+ const std::vector<llama_logit_bias> & logit_bias_eog,
102
+ const json & data);
103
+
104
+ } // namespace server_schema
tools/server/server-stream.cpp ADDED
@@ -0,0 +1,668 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "server-stream.h"
2
+ #include "server-common.h"
3
+ #include "server-http.h"
4
+ #include "server-queue.h"
5
+
6
+ #include <chrono>
7
+ #include <memory>
8
+ #include <utility>
9
+ #include <shared_mutex>
10
+
11
+ enum class stream_read_status {
12
+ OK,
13
+ OFFSET_LOST,
14
+ };
15
+
16
+ namespace {
17
+ constexpr int64_t STREAM_SESSION_TTL_SECONDS = 300;
18
+ constexpr size_t STREAM_SESSION_MAX_BYTES = 4 * 1024 * 1024;
19
+ constexpr int64_t STREAM_SESSION_GC_INTERVAL_SECONDS = 60;
20
+ constexpr int64_t STREAM_READ_WAKE_INTERVAL_MS = 200;
21
+
22
+ int64_t now_seconds() {
23
+ return std::chrono::duration_cast<std::chrono::seconds>(
24
+ std::chrono::system_clock::now().time_since_epoch()
25
+ ).count();
26
+ }
27
+ }
28
+
29
+ // owns all live sessions keyed by conversation_id, one conv = at most one live session.
30
+ // a periodic GC evicts expired ones
31
+ class stream_session_manager {
32
+ public:
33
+ stream_session_manager();
34
+ ~stream_session_manager();
35
+
36
+ stream_session_manager(const stream_session_manager &) = delete;
37
+ stream_session_manager & operator=(const stream_session_manager &) = delete;
38
+
39
+ // install a new session, evicting and cancelling any previous one. conversation_id must be non empty
40
+ stream_session_ptr create_or_replace(const std::string & conversation_id);
41
+
42
+ stream_session_ptr get(const std::string & conversation_id);
43
+
44
+ std::vector<stream_session_ptr> list_all() const;
45
+
46
+ void evict(const std::string & conversation_id);
47
+
48
+ void evict_and_cancel(const std::string & conversation_id);
49
+
50
+ void start_gc();
51
+ void stop_gc();
52
+
53
+ private:
54
+ void gc_loop();
55
+
56
+ mutable std::shared_mutex map_mu;
57
+ std::unordered_map<std::string, stream_session_ptr> sessions; // key: conversation_id
58
+ std::thread gc_thread;
59
+ bool running;
60
+ std::mutex gc_wake_mu;
61
+ std::condition_variable gc_wake_cv;
62
+ };
63
+
64
+ // process wide manager, lifecycle controlled by llama-server main() via start_gc/stop_gc
65
+ static stream_session_manager g_stream_sessions;
66
+
67
+ void server_stream_session_manager_start() {
68
+ g_stream_sessions.start_gc();
69
+ }
70
+
71
+ void server_stream_session_manager_stop() {
72
+ g_stream_sessions.stop_gc();
73
+ }
74
+
75
+ struct stream_session {
76
+ std::string conversation_id;
77
+ int64_t started_ts; // unix seconds at construction
78
+
79
+ stream_session(std::string conversation_id_, size_t max_bytes_);
80
+ stream_session(const stream_session &) = delete;
81
+ stream_session & operator=(const stream_session &) = delete;
82
+
83
+ bool append(const char * data, size_t len);
84
+
85
+ void finalize();
86
+
87
+ // drain from offset into sink, blocking for more bytes or finalize. OFFSET_LOST if offset
88
+ // fell below the dropped prefix
89
+ stream_read_status read_from(size_t offset,
90
+ const std::function<bool(const char *, size_t)> & sink,
91
+ const std::function<bool()> & should_stop);
92
+
93
+ bool is_done() const;
94
+ bool is_cancelled() const;
95
+ size_t total_size() const; // bytes that ever entered the session
96
+ size_t dropped_prefix() const; // bytes evicted from the front due to cap
97
+ int64_t completed_at() const; // 0 while alive, unix seconds after finalize
98
+
99
+ void cancel();
100
+
101
+ private:
102
+ mutable std::mutex mu;
103
+ std::condition_variable cv;
104
+ std::vector<char> buffer;
105
+ size_t prefix_dropped;
106
+ size_t cap_bytes;
107
+ bool done;
108
+ std::atomic<bool> cancelled; // polled lock-free by the should_stop closure, no mu
109
+ int64_t completed_ts;
110
+ };
111
+ stream_session::stream_session(std::string conversation_id_, size_t max_bytes_)
112
+ : conversation_id(std::move(conversation_id_))
113
+ , started_ts(now_seconds())
114
+ , prefix_dropped(0)
115
+ , cap_bytes(max_bytes_)
116
+ , done(false)
117
+ , cancelled(false)
118
+ , completed_ts(0) {
119
+ buffer.reserve(64 * 1024);
120
+ }
121
+
122
+ bool stream_session::append(const char * data, size_t len) {
123
+ if (len == 0) {
124
+ return true;
125
+ }
126
+ {
127
+ std::lock_guard<std::mutex> lock(mu);
128
+ if (done) {
129
+ return false;
130
+ }
131
+ if (len >= cap_bytes) {
132
+ // single chunk bigger than the cap, keep only the tail that fits
133
+ size_t skip = len - cap_bytes;
134
+ prefix_dropped += buffer.size() + skip;
135
+ buffer.clear();
136
+ buffer.insert(buffer.end(), data + skip, data + len);
137
+ } else {
138
+ size_t needed = buffer.size() + len;
139
+ if (needed > cap_bytes) {
140
+ size_t to_drop = needed - cap_bytes;
141
+ buffer.erase(buffer.begin(), buffer.begin() + to_drop);
142
+ prefix_dropped += to_drop;
143
+ }
144
+ buffer.insert(buffer.end(), data, data + len);
145
+ }
146
+ }
147
+ cv.notify_all();
148
+ return true;
149
+ }
150
+
151
+ void stream_session::finalize() {
152
+ {
153
+ std::lock_guard<std::mutex> lock(mu);
154
+ if (done) {
155
+ return;
156
+ }
157
+ done = true;
158
+ completed_ts = now_seconds();
159
+ }
160
+ cv.notify_all();
161
+ }
162
+
163
+ stream_read_status stream_session::read_from(size_t offset,
164
+ const std::function<bool(const char *, size_t)> & sink,
165
+ const std::function<bool()> & should_stop) {
166
+ std::unique_lock<std::mutex> lock(mu);
167
+ while (true) {
168
+ if (should_stop && should_stop()) {
169
+ return stream_read_status::OK;
170
+ }
171
+ if (offset < prefix_dropped) {
172
+ return stream_read_status::OFFSET_LOST;
173
+ }
174
+ size_t logical_end = prefix_dropped + buffer.size();
175
+ if (offset < logical_end) {
176
+ size_t local_off = offset - prefix_dropped;
177
+ size_t n = buffer.size() - local_off;
178
+ // copy the available chunk under the lock, release before calling the sink
179
+ std::vector<char> chunk(buffer.begin() + local_off, buffer.begin() + local_off + n);
180
+ offset += n;
181
+ lock.unlock();
182
+ bool keep_going = sink(chunk.data(), chunk.size());
183
+ if (!keep_going) {
184
+ return stream_read_status::OK;
185
+ }
186
+ lock.lock();
187
+ continue;
188
+ }
189
+ if (done) {
190
+ return stream_read_status::OK;
191
+ }
192
+ // wait for new bytes, finalize, or a periodic wake to re check should_stop
193
+ cv.wait_for(lock, std::chrono::milliseconds(STREAM_READ_WAKE_INTERVAL_MS));
194
+ }
195
+ }
196
+
197
+ bool stream_session::is_done() const {
198
+ std::lock_guard<std::mutex> lock(mu);
199
+ return done;
200
+ }
201
+
202
+ size_t stream_session::total_size() const {
203
+ std::lock_guard<std::mutex> lock(mu);
204
+ return prefix_dropped + buffer.size();
205
+ }
206
+
207
+ size_t stream_session::dropped_prefix() const {
208
+ std::lock_guard<std::mutex> lock(mu);
209
+ return prefix_dropped;
210
+ }
211
+
212
+ int64_t stream_session::completed_at() const {
213
+ std::lock_guard<std::mutex> lock(mu);
214
+ return completed_ts;
215
+ }
216
+
217
+ void stream_session::cancel() {
218
+ // the should_stop closure on both the producer and any HTTP reader polls is_cancelled()
219
+ // so flipping this is the only signal needed to unwind both sides
220
+ cancelled.store(true, std::memory_order_release);
221
+ }
222
+
223
+ bool stream_session::is_cancelled() const {
224
+ return cancelled.load(std::memory_order_acquire);
225
+ }
226
+
227
+ stream_session_manager::stream_session_manager()
228
+ : running(false) {
229
+ }
230
+
231
+ stream_session_manager::~stream_session_manager() {
232
+ stop_gc();
233
+ }
234
+
235
+ stream_session_ptr stream_session_manager::create_or_replace(const std::string & conversation_id) {
236
+ // evict any previous session on the same conv, this guarantees the invariant
237
+ // "one conv = at most one live session" and propagates cancel to its producer
238
+ stream_session_ptr previous;
239
+ auto fresh = std::make_shared<stream_session>(conversation_id, STREAM_SESSION_MAX_BYTES);
240
+ {
241
+ std::unique_lock<std::shared_mutex> lock(map_mu);
242
+ auto it = sessions.find(conversation_id);
243
+ if (it != sessions.end()) {
244
+ previous = it->second;
245
+ it->second = fresh;
246
+ } else {
247
+ sessions.emplace(conversation_id, fresh);
248
+ }
249
+ }
250
+ if (previous) {
251
+ previous->cancel();
252
+ previous->finalize();
253
+ }
254
+ return fresh;
255
+ }
256
+
257
+ stream_session_ptr stream_session_manager::get(const std::string & conversation_id) {
258
+ std::shared_lock<std::shared_mutex> lock(map_mu);
259
+ auto it = sessions.find(conversation_id);
260
+ if (it == sessions.end()) {
261
+ return nullptr;
262
+ }
263
+ return it->second;
264
+ }
265
+
266
+ std::vector<stream_session_ptr> stream_session_manager::list_all() const {
267
+ std::vector<stream_session_ptr> out;
268
+ std::shared_lock<std::shared_mutex> lock(map_mu);
269
+ out.reserve(sessions.size());
270
+ for (auto & kv : sessions) {
271
+ out.push_back(kv.second);
272
+ }
273
+ return out;
274
+ }
275
+
276
+ void stream_session_manager::evict(const std::string & conversation_id) {
277
+ stream_session_ptr s;
278
+ {
279
+ std::unique_lock<std::shared_mutex> lock(map_mu);
280
+ auto it = sessions.find(conversation_id);
281
+ if (it == sessions.end()) {
282
+ return;
283
+ }
284
+ s = it->second;
285
+ sessions.erase(it);
286
+ }
287
+ // finalize outside the map lock so any pending readers wake up and exit
288
+ s->finalize();
289
+ }
290
+
291
+ void stream_session_manager::evict_and_cancel(const std::string & conversation_id) {
292
+ stream_session_ptr s;
293
+ {
294
+ std::unique_lock<std::shared_mutex> lock(map_mu);
295
+ auto it = sessions.find(conversation_id);
296
+ if (it == sessions.end()) {
297
+ std::string live;
298
+ for (const auto & kv : sessions) {
299
+ if (!live.empty()) live += ", ";
300
+ live += kv.first;
301
+ }
302
+ SRV_WRN("stop on unknown stream session, conv_id=%s matched nothing, %zu live: [%s]\n",
303
+ conversation_id.c_str(), sessions.size(), live.c_str());
304
+ return;
305
+ }
306
+ s = it->second;
307
+ sessions.erase(it);
308
+ }
309
+ // cancel first so the producer's on_complete() drain loop and any pending HTTP reader
310
+ // observe is_cancelled() and stop pulling further output, then finalize to wake readers
311
+ // blocked in read_from(). note: this does not interrupt the underlying generation itself,
312
+ // which keeps running to its own natural stop condition (EOS/max_tokens)
313
+ s->cancel();
314
+ s->finalize();
315
+ }
316
+
317
+ void stream_session_manager::start_gc() {
318
+ {
319
+ std::lock_guard<std::mutex> lock(gc_wake_mu);
320
+ if (running) {
321
+ return;
322
+ }
323
+ running = true;
324
+ }
325
+ gc_thread = std::thread([this] { gc_loop(); });
326
+ }
327
+
328
+ void stream_session_manager::stop_gc() {
329
+ bool was_running;
330
+ {
331
+ std::lock_guard<std::mutex> lock(gc_wake_mu);
332
+ was_running = running;
333
+ running = false;
334
+ }
335
+ if (was_running) {
336
+ gc_wake_cv.notify_all();
337
+ if (gc_thread.joinable()) {
338
+ gc_thread.join();
339
+ }
340
+ }
341
+ // finalize all live sessions so no reader ever hangs
342
+ std::vector<stream_session_ptr> snapshot;
343
+ {
344
+ std::unique_lock<std::shared_mutex> lock(map_mu);
345
+ snapshot.reserve(sessions.size());
346
+ for (auto & kv : sessions) {
347
+ snapshot.push_back(kv.second);
348
+ }
349
+ sessions.clear();
350
+ }
351
+ for (auto & s : snapshot) {
352
+ s->finalize();
353
+ }
354
+ }
355
+
356
+ void stream_session_manager::gc_loop() {
357
+ while (true) {
358
+ {
359
+ std::unique_lock<std::mutex> lock(gc_wake_mu);
360
+ gc_wake_cv.wait_for(lock,
361
+ std::chrono::seconds(STREAM_SESSION_GC_INTERVAL_SECONDS),
362
+ [this] { return !running; });
363
+ if (!running) {
364
+ return;
365
+ }
366
+ }
367
+ int64_t cutoff = now_seconds() - STREAM_SESSION_TTL_SECONDS;
368
+ std::vector<stream_session_ptr> to_drop;
369
+ {
370
+ std::unique_lock<std::shared_mutex> lock(map_mu);
371
+ for (auto it = sessions.begin(); it != sessions.end(); ) {
372
+ int64_t completed = it->second->completed_at();
373
+ if (completed != 0 && completed <= cutoff) {
374
+ to_drop.push_back(it->second);
375
+ it = sessions.erase(it);
376
+ } else {
377
+ ++it;
378
+ }
379
+ }
380
+ }
381
+ // finalize outside the map lock, idempotent if the session was already done
382
+ for (auto & s : to_drop) {
383
+ s->finalize();
384
+ }
385
+ }
386
+ }
387
+
388
+ // stream_pipe
389
+
390
+ // consumer end: read-only replay of the ring buffer, the destructor does not finalize the session
391
+ struct stream_pipe_consumer : stream_pipe {
392
+ stream_read_status read(size_t & offset,
393
+ const std::function<bool(const char *, size_t)> & sink,
394
+ const std::function<bool()> & should_stop);
395
+
396
+ static std::shared_ptr<stream_pipe_consumer> create(stream_session_ptr session);
397
+
398
+ private:
399
+ explicit stream_pipe_consumer(stream_session_ptr session);
400
+ };
401
+
402
+ stream_pipe::stream_pipe(stream_session_ptr session)
403
+ : session_(std::move(session)) {
404
+ }
405
+
406
+ bool stream_pipe::is_cancelled() const {
407
+ return session_->is_cancelled();
408
+ }
409
+
410
+ // stream_pipe_producer
411
+
412
+ stream_pipe_producer::stream_pipe_producer(stream_session_ptr session)
413
+ : stream_pipe(std::move(session)) {
414
+ }
415
+
416
+ stream_pipe_producer::~stream_pipe_producer() {
417
+ session_->finalize();
418
+ }
419
+
420
+ bool stream_pipe_producer::write(const char * data, size_t len) {
421
+ return session_->append(data, len);
422
+ }
423
+
424
+ stream_pipe_producer * stream_pipe_producer::create(stream_session_ptr session) {
425
+ return new stream_pipe_producer(std::move(session));
426
+ }
427
+
428
+ // stream_pipe_consumer
429
+
430
+ stream_pipe_consumer::stream_pipe_consumer(stream_session_ptr session)
431
+ : stream_pipe(std::move(session)) {
432
+ }
433
+
434
+ stream_read_status stream_pipe_consumer::read(size_t & offset,
435
+ const std::function<bool(const char *, size_t)> & sink,
436
+ const std::function<bool()> & should_stop) {
437
+ return session_->read_from(offset, sink, should_stop);
438
+ }
439
+
440
+ std::shared_ptr<stream_pipe_consumer> stream_pipe_consumer::create(stream_session_ptr session) {
441
+ return std::shared_ptr<stream_pipe_consumer>(new stream_pipe_consumer(std::move(session)));
442
+ }
443
+
444
+ // helper, builds the standard error response and assigns it to a brand new http_res
445
+ static server_http_res_ptr make_error_response(int status, const std::string & message, error_type type) {
446
+ auto res = std::make_unique<server_http_res>();
447
+ json err = format_error_response(message, type);
448
+ res->status = json_value(err, "code", status);
449
+ res->content_type = "application/json; charset=utf-8";
450
+ res->data = safe_json_to_str({{"error", err}});
451
+ return res;
452
+ }
453
+
454
+ server_http_context::handler_t server_stream_make_get_handler() {
455
+ return [](const server_http_req & req) -> server_http_res_ptr {
456
+ // GET /v1/stream?conv_id=<id>&from=N replays buffered SSE bytes then blocks for live
457
+ // bytes until the session finalizes, streamed as text/event-stream for EventSource
458
+ std::string conv_id = req.get_param("conv_id");
459
+ if (conv_id.empty()) {
460
+ return make_error_response(400, "Missing conversation id in path", ERROR_TYPE_INVALID_REQUEST);
461
+ }
462
+ auto session = g_stream_sessions.get(conv_id);
463
+ if (!session) {
464
+ return make_error_response(404, "Stream not found or expired", ERROR_TYPE_NOT_FOUND);
465
+ }
466
+ size_t from = 0;
467
+ std::string from_str = req.get_param("from");
468
+ if (!from_str.empty()) {
469
+ try {
470
+ from = static_cast<size_t>(std::stoull(from_str));
471
+ } catch (const std::exception &) {
472
+ return make_error_response(400, "Invalid 'from' offset", ERROR_TYPE_INVALID_REQUEST);
473
+ }
474
+ }
475
+ if (from < session->dropped_prefix()) {
476
+ return make_error_response(400, "Stream offset lost, please restart", ERROR_TYPE_INVALID_REQUEST);
477
+ }
478
+ auto res = std::make_unique<server_http_res>();
479
+ res->status = 200;
480
+ res->content_type = "text/event-stream";
481
+ // the next closure reads from the ring buffer at the requested offset, blocks until
482
+ // bytes arrive or the session finalizes. exit each call after draining the available
483
+ // chunk so set_chunked_content_provider gets a chance to flush to the socket
484
+ auto offset_ptr = std::make_shared<size_t>(from);
485
+ // consumer pipe: read-only, does not finalize the session on destruction
486
+ auto pipe = stream_pipe_consumer::create(session);
487
+ res->next = [pipe, offset_ptr, &req](std::string & output) -> bool {
488
+ bool got_any = false;
489
+ pipe->read(*offset_ptr,
490
+ [&](const char * d, size_t n) {
491
+ output.append(d, n);
492
+ *offset_ptr += n;
493
+ got_any = true;
494
+ return false;
495
+ },
496
+ req.should_stop);
497
+ return got_any;
498
+ };
499
+ return res;
500
+ };
501
+ }
502
+
503
+ server_http_context::handler_t server_stream_make_lookup_handler() {
504
+ return [](const server_http_req & req) -> server_http_res_ptr {
505
+ // POST /v1/streams/lookup returns the matching sessions, only for ids the caller already
506
+ // knows. each id matches the exact key and any "<id>::<model>" per model variant
507
+ std::vector<std::string> requested;
508
+ try {
509
+ json body = json::parse(req.body);
510
+ if (body.contains("conversation_ids") && body["conversation_ids"].is_array()) {
511
+ for (const auto & v : body["conversation_ids"]) {
512
+ if (v.is_string()) {
513
+ std::string id = v.get<std::string>();
514
+ if (!id.empty()) {
515
+ requested.push_back(std::move(id));
516
+ }
517
+ }
518
+ }
519
+ }
520
+ } catch (const std::exception & e) {
521
+ auto res = std::make_unique<server_http_res>();
522
+ res->status = 400;
523
+ res->content_type = "application/json; charset=utf-8";
524
+ res->data = safe_json_to_str({{"error", {{"message", std::string("invalid body: ") + e.what()},
525
+ {"type", "invalid_request_error"}}}});
526
+ return res;
527
+ }
528
+
529
+ std::vector<stream_session_ptr> sessions;
530
+ if (!requested.empty()) {
531
+ auto all = g_stream_sessions.list_all();
532
+ for (const auto & rid : requested) {
533
+ const std::string with_sep = rid + "::";
534
+ for (auto & s : all) {
535
+ if (s->conversation_id == rid ||
536
+ s->conversation_id.compare(0, with_sep.size(), with_sep) == 0) {
537
+ sessions.push_back(s);
538
+ }
539
+ }
540
+ }
541
+ }
542
+
543
+ json arr = json::array();
544
+ for (auto & s : sessions) {
545
+ arr.push_back({
546
+ {"conversation_id", s->conversation_id},
547
+ {"is_done", s->is_done()},
548
+ {"total_bytes", s->total_size()},
549
+ {"started_at", s->started_ts},
550
+ {"completed_at", s->completed_at()},
551
+ });
552
+ }
553
+ auto res = std::make_unique<server_http_res>();
554
+ res->status = 200;
555
+ res->content_type = "application/json; charset=utf-8";
556
+ res->data = safe_json_to_str(arr);
557
+ return res;
558
+ };
559
+ }
560
+
561
+ server_http_context::handler_t server_stream_make_delete_handler() {
562
+ return [](const server_http_req & req) -> server_http_res_ptr {
563
+ // DELETE /v1/stream?conv_id=<id> is the explicit user Stop, cancels the producer and evicts
564
+ // the buffer. idempotent, returns 204 even if the session was already gone
565
+ std::string conv_id = req.get_param("conv_id");
566
+ if (conv_id.empty()) {
567
+ return make_error_response(400, "Missing conversation id in path", ERROR_TYPE_INVALID_REQUEST);
568
+ }
569
+ SRV_TRC("DELETE /v1/stream conv_id=%s -> evict_and_cancel\n", conv_id.c_str());
570
+ g_stream_sessions.evict_and_cancel(conv_id);
571
+ auto res = std::make_unique<server_http_res>();
572
+ res->status = 204;
573
+ res->content_type = "application/json";
574
+ return res;
575
+ };
576
+ }
577
+
578
+ std::string server_stream_conv_id_from_headers(const std::map<std::string, std::string> & headers) {
579
+ // case-insensitive scan for x-conversation-id
580
+ static constexpr char target[] = "x-conversation-id";
581
+ static constexpr size_t target_len = sizeof(target) - 1;
582
+ for (const auto & [hk, hv] : headers) {
583
+ if (hk.size() != target_len) continue;
584
+ bool match = true;
585
+ for (size_t i = 0; i < target_len; ++i) {
586
+ char c = hk[i];
587
+ if (c >= 'A' && c <= 'Z') c = char(c + 32);
588
+ if (c != target[i]) { match = false; break; }
589
+ }
590
+ if (match) {
591
+ return hv;
592
+ }
593
+ }
594
+ return std::string();
595
+ }
596
+
597
+ static stream_pipe_producer * server_stream_create_spipe(const std::map<std::string, std::string> & headers) {
598
+ std::string conversation_id = server_stream_conv_id_from_headers(headers);
599
+ SRV_TRC("conv_id=%s (empty=%d)\n", conversation_id.c_str(), conversation_id.empty() ? 1 : 0);
600
+ if (conversation_id.empty()) {
601
+ return nullptr;
602
+ }
603
+ auto session = g_stream_sessions.create_or_replace(conversation_id);
604
+ return stream_pipe_producer::create(session);
605
+ }
606
+
607
+ //
608
+ // server_res_spipe
609
+ //
610
+
611
+ void server_res_spipe::set_req(const server_http_req * req) {
612
+ this->req = req;
613
+ // optionally attach spipe to the response when X-Conversation-Id is present
614
+ spipe.reset(server_stream_create_spipe(req->headers));
615
+ }
616
+
617
+ bool server_res_spipe::conn_alive() {
618
+ GGML_ASSERT(req != nullptr);
619
+ return !req->should_stop();
620
+ }
621
+
622
+ bool server_res_spipe::should_stop() {
623
+ if (spipe) {
624
+ // note: if DELETE /v1/stream is called for this conv, is_cancelled() will be true
625
+ return spipe->is_cancelled();
626
+ } else {
627
+ return !conn_alive();
628
+ }
629
+ }
630
+
631
+ void server_res_spipe::on_complete() {
632
+ if (!spipe || next_finished) {
633
+ return;
634
+ }
635
+ // an empty next_orig means set_next() never ran: the request failed before streaming
636
+ // started, typically a params validation throw. evict the session installed by set_req()
637
+ // so the failed request leaves nothing behind for discovery or replay
638
+ if (!next_orig) {
639
+ g_stream_sessions.evict(server_stream_conv_id_from_headers(req->headers));
640
+ return;
641
+ }
642
+ std::string chunk;
643
+ while (!spipe->is_cancelled()) {
644
+ chunk.clear();
645
+ bool has_next = next_orig(chunk);
646
+ if (!chunk.empty()) {
647
+ spipe->write(chunk.data(), chunk.size());
648
+ }
649
+ if (!has_next) {
650
+ break;
651
+ }
652
+ }
653
+ }
654
+
655
+ void server_res_spipe::set_next(std::function<bool(std::string &)> next_fn) {
656
+ next_orig = std::move(next_fn);
657
+ next = [this](std::string & out) {
658
+ bool has_next = next_orig(out);
659
+ if (spipe) {
660
+ // if spipe is set, tee-style pipe input to both HTTP and spipe
661
+ spipe->write(out.data(), out.size());
662
+ }
663
+ if (!has_next) {
664
+ next_finished = true;
665
+ }
666
+ return has_next;
667
+ };
668
+ }
tools/server/server-stream.h ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include "server-http.h"
4
+
5
+ #include <atomic>
6
+ #include <cstddef>
7
+ #include <functional>
8
+ #include <memory>
9
+ #include <string>
10
+
11
+ // streaming buffer for one generation, survives HTTP disconnect. the producer appends SSE bytes,
12
+ // readers drain from any offset via read_from. keyed by conversation_id, one conv = one live session
13
+
14
+ struct stream_session;
15
+
16
+ using stream_session_ptr = std::shared_ptr<stream_session>;
17
+
18
+ // base of the producer/consumer pipe ends. virtual dtor so each runs its own teardown:
19
+ // the producer finalizes the session, the consumer leaves it untouched
20
+ struct stream_pipe {
21
+ virtual ~stream_pipe() = default;
22
+
23
+ bool is_cancelled() const;
24
+
25
+ protected:
26
+ explicit stream_pipe(stream_session_ptr session);
27
+
28
+ stream_session_ptr session_;
29
+ };
30
+
31
+ // producer end: writes chunks into the ring buffer and owns the session lifetime, finalizing it
32
+ // on destruction.
33
+ struct stream_pipe_producer : stream_pipe {
34
+ ~stream_pipe_producer() override;
35
+
36
+ bool write(const char * data, size_t len);
37
+
38
+ static stream_pipe_producer * create(stream_session_ptr session);
39
+
40
+ private:
41
+ explicit stream_pipe_producer(stream_session_ptr session);
42
+ };
43
+
44
+ void server_stream_session_manager_start();
45
+ void server_stream_session_manager_stop();
46
+
47
+ // route handler factories wired under /v1/stream/* by server.cpp
48
+ // child-side handlers for the resumable stream routes. the conv id travels in the conv_id
49
+ // query string because it can embed a model name containing slashes (org/repo), which the
50
+ // decoded path would split before the param is captured
51
+ server_http_context::handler_t server_stream_make_get_handler();
52
+ // POST /v1/streams/lookup with body {"conversation_ids": [...]}: only answers for ids the
53
+ // caller already owns (the WebUI passes the convs visible in its sidebar), the server never
54
+ // lists ids it has not been asked about, so a random caller cannot enumerate live sessions
55
+ server_http_context::handler_t server_stream_make_lookup_handler();
56
+ server_http_context::handler_t server_stream_make_delete_handler();
57
+
58
+ // extract the X-Conversation-Id header value (case-insensitive), empty when absent
59
+ std::string server_stream_conv_id_from_headers(const std::map<std::string, std::string> & headers);
60
+
61
+ // implement tee-style pipe (spipe) for "stream replay" functionality
62
+ struct server_res_spipe : server_http_res {
63
+ private:
64
+ // if set, the stream survives a client disconnect:
65
+ // connection kept alive, output is forwarded to spipe and reuse later
66
+ std::unique_ptr<stream_pipe_producer> spipe;
67
+ // if spipe is set, use this next_orig to implement tee-style pipe
68
+ std::function<bool(std::string &)> next_orig;
69
+ const server_http_req * req = nullptr;
70
+ // set once next_orig reports no more data, so on_complete() doesn't re-drain a finished stream
71
+ bool next_finished = false;
72
+
73
+ public:
74
+ void set_req(const server_http_req * req);
75
+ bool conn_alive();
76
+ bool should_stop();
77
+ void on_complete() override;
78
+ void set_next(std::function<bool(std::string &)> next_fn);
79
+ };
tools/server/server-task.cpp ADDED
@@ -0,0 +1,1854 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "server-task.h"
2
+
3
+ #include "build-info.h"
4
+ #include "server-chat.h"
5
+ #include "chat.h"
6
+ #include "common.h"
7
+ #include "json-schema-to-grammar.h"
8
+ #include "llama.h"
9
+ #include "sampling.h"
10
+ #include "speculative.h"
11
+ #include "server-common.h"
12
+
13
+ using json = nlohmann::ordered_json;
14
+
15
+ //
16
+ // task_params
17
+ //
18
+
19
+ json task_params::format_logit_bias(const std::vector<llama_logit_bias> & logit_bias) const {
20
+ json data = json::array();
21
+ for (const auto & lb : logit_bias) {
22
+ data.push_back(json{
23
+ {"bias", lb.bias},
24
+ {"token", lb.token},
25
+ });
26
+ }
27
+ return data;
28
+ }
29
+
30
+ json task_params::to_json(bool only_metrics) const {
31
+ std::vector<std::string> samplers;
32
+ samplers.reserve(sampling.samplers.size());
33
+ for (const auto & sampler : sampling.samplers) {
34
+ samplers.emplace_back(common_sampler_type_to_str(sampler));
35
+ }
36
+
37
+ json lora = json::array();
38
+ for (auto & it : this->lora) {
39
+ lora.push_back({{"id", it.first}, {"scale", it.second}});
40
+ }
41
+
42
+ if (only_metrics) {
43
+ return json {
44
+ {"seed", sampling.seed},
45
+ {"temperature", sampling.temp},
46
+ {"dynatemp_range", sampling.dynatemp_range},
47
+ {"dynatemp_exponent", sampling.dynatemp_exponent},
48
+ {"top_k", sampling.top_k},
49
+ {"top_p", sampling.top_p},
50
+ {"min_p", sampling.min_p},
51
+ {"top_n_sigma", sampling.top_n_sigma},
52
+ {"xtc_probability", sampling.xtc_probability},
53
+ {"xtc_threshold", sampling.xtc_threshold},
54
+ {"typical_p", sampling.typ_p},
55
+ {"repeat_last_n", sampling.penalty_last_n},
56
+ {"repeat_penalty", sampling.penalty_repeat},
57
+ {"presence_penalty", sampling.penalty_present},
58
+ {"frequency_penalty", sampling.penalty_freq},
59
+ {"dry_multiplier", sampling.dry_multiplier},
60
+ {"dry_base", sampling.dry_base},
61
+ {"dry_allowed_length", sampling.dry_allowed_length},
62
+ {"dry_penalty_last_n", sampling.dry_penalty_last_n},
63
+ {"mirostat", sampling.mirostat},
64
+ {"mirostat_tau", sampling.mirostat_tau},
65
+ {"mirostat_eta", sampling.mirostat_eta},
66
+ {"adaptive_target", sampling.adaptive_target},
67
+ {"adaptive_decay", sampling.adaptive_decay},
68
+ {"max_tokens", n_predict},
69
+ {"n_predict", n_predict}, // TODO: deduplicate?
70
+ {"n_keep", n_keep},
71
+ {"n_discard", n_discard},
72
+ {"ignore_eos", sampling.ignore_eos},
73
+ {"stream", stream},
74
+ {"n_probs", sampling.n_probs},
75
+ {"min_keep", sampling.min_keep},
76
+ {"chat_format", common_chat_format_name(chat_parser_params.format)},
77
+ {"reasoning_format", common_reasoning_format_name(chat_parser_params.reasoning_format)},
78
+ {"reasoning_in_content", chat_parser_params.reasoning_in_content},
79
+ {"generation_prompt", chat_parser_params.generation_prompt},
80
+ {"samplers", samplers},
81
+ {"speculative.types", common_speculative_type_name_str(speculative.types)},
82
+ {"timings_per_token", timings_per_token},
83
+ {"post_sampling_probs", post_sampling_probs},
84
+ {"backend_sampling", sampling.backend_sampling},
85
+ {"lora", lora},
86
+ };
87
+ }
88
+
89
+ auto grammar_triggers = json::array();
90
+ for (const auto & trigger : sampling.grammar_triggers) {
91
+ server_grammar_trigger ct(trigger);
92
+ grammar_triggers.push_back(ct.to_json());
93
+ }
94
+
95
+ return json {
96
+ {"seed", sampling.seed},
97
+ {"temperature", sampling.temp},
98
+ {"dynatemp_range", sampling.dynatemp_range},
99
+ {"dynatemp_exponent", sampling.dynatemp_exponent},
100
+ {"top_k", sampling.top_k},
101
+ {"top_p", sampling.top_p},
102
+ {"min_p", sampling.min_p},
103
+ {"top_n_sigma", sampling.top_n_sigma},
104
+ {"xtc_probability", sampling.xtc_probability},
105
+ {"xtc_threshold", sampling.xtc_threshold},
106
+ {"typical_p", sampling.typ_p},
107
+ {"repeat_last_n", sampling.penalty_last_n},
108
+ {"repeat_penalty", sampling.penalty_repeat},
109
+ {"presence_penalty", sampling.penalty_present},
110
+ {"frequency_penalty", sampling.penalty_freq},
111
+ {"dry_multiplier", sampling.dry_multiplier},
112
+ {"dry_base", sampling.dry_base},
113
+ {"dry_allowed_length", sampling.dry_allowed_length},
114
+ {"dry_penalty_last_n", sampling.dry_penalty_last_n},
115
+ {"dry_sequence_breakers", sampling.dry_sequence_breakers},
116
+ {"mirostat", sampling.mirostat},
117
+ {"mirostat_tau", sampling.mirostat_tau},
118
+ {"mirostat_eta", sampling.mirostat_eta},
119
+ {"adaptive_target", sampling.adaptive_target},
120
+ {"adaptive_decay", sampling.adaptive_decay},
121
+ {"stop", antiprompt},
122
+ {"max_tokens", n_predict},
123
+ {"n_predict", n_predict}, // TODO: deduplicate?
124
+ {"n_keep", n_keep},
125
+ {"n_discard", n_discard},
126
+ {"ignore_eos", sampling.ignore_eos},
127
+ {"stream", stream},
128
+ {"logit_bias", format_logit_bias(sampling.logit_bias)},
129
+ {"n_probs", sampling.n_probs},
130
+ {"min_keep", sampling.min_keep},
131
+ {"grammar", common_grammar_value(sampling.grammar)},
132
+ {"grammar_lazy", sampling.grammar_lazy},
133
+ {"grammar_triggers", grammar_triggers},
134
+ {"preserved_tokens", sampling.preserved_tokens},
135
+ {"chat_format", common_chat_format_name(chat_parser_params.format)},
136
+ {"reasoning_format", common_reasoning_format_name(chat_parser_params.reasoning_format)},
137
+ {"reasoning_in_content", chat_parser_params.reasoning_in_content},
138
+ {"generation_prompt", chat_parser_params.generation_prompt},
139
+ {"samplers", samplers},
140
+ {"speculative.types", common_speculative_type_name_str(speculative.types)},
141
+ {"timings_per_token", timings_per_token},
142
+ {"post_sampling_probs", post_sampling_probs},
143
+ {"backend_sampling", sampling.backend_sampling},
144
+ {"lora", lora},
145
+ };
146
+ }
147
+
148
+ //
149
+ // task_result_state
150
+ //
151
+ task_result_state::task_result_state(const common_chat_parser_params & chat_parser_params)
152
+ : chat_parser_params(chat_parser_params)
153
+ , oai_resp_id("resp_" + random_string())
154
+ , oai_resp_reasoning_id("rs_" + random_string())
155
+ , oai_resp_message_id("msg_" + random_string()) {
156
+ if (chat_parser_params.is_continuation && !chat_parser_params.echo) {
157
+ // initialize chat_msg to avoid emitting a delta containing the assistant prefill
158
+ chat_msg = common_chat_parse("", true, chat_parser_params);
159
+ }
160
+ }
161
+
162
+ common_chat_msg task_result_state::update_chat_msg(
163
+ const std::string & text_added,
164
+ bool is_partial,
165
+ std::vector<common_chat_msg_diff> & diffs,
166
+ bool filter_tool_calls) {
167
+ generated_text += text_added;
168
+ auto msg_prv_copy = chat_msg;
169
+ //SRV_DBG("Parsing chat message: %s\n", generated_text.c_str());
170
+ auto new_msg = common_chat_parse(
171
+ generated_text,
172
+ is_partial,
173
+ chat_parser_params);
174
+ if (!new_msg.empty()) {
175
+ new_msg.set_tool_call_ids(generated_tool_call_ids, gen_tool_call_id);
176
+ chat_msg = new_msg;
177
+ auto all_diffs = common_chat_msg_diff::compute_diffs(msg_prv_copy, chat_msg);
178
+
179
+ if (!filter_tool_calls) {
180
+ diffs = std::move(all_diffs);
181
+ } else {
182
+ for (auto & d : all_diffs) {
183
+ // If this is a new type of delta, flush all currently pending tool call names
184
+ for (size_t i = 0; i < chat_msg.tool_calls.size(); ++i) {
185
+ if (sent_tool_call_names.count(i) || chat_msg.tool_calls[i].name.empty()) {
186
+ continue;
187
+ }
188
+ if (d.tool_call_index != i || !d.tool_call_delta.arguments.empty()) {
189
+ common_chat_msg_diff header;
190
+ header.tool_call_index = i;
191
+ header.tool_call_delta.id = chat_msg.tool_calls[i].id;
192
+ header.tool_call_delta.name = chat_msg.tool_calls[i].name;
193
+ diffs.push_back(std::move(header));
194
+ sent_tool_call_names.insert(i);
195
+ }
196
+ }
197
+
198
+ if (d.tool_call_index == std::string::npos) {
199
+ diffs.push_back(std::move(d));
200
+ } else {
201
+ size_t i = d.tool_call_index;
202
+ if (sent_tool_call_names.count(i)) {
203
+ if (!d.tool_call_delta.arguments.empty()) {
204
+ d.tool_call_delta.name = "";
205
+ d.tool_call_delta.id = "";
206
+ diffs.push_back(std::move(d));
207
+ }
208
+ } else {
209
+ // Not sent yet.
210
+ if (!d.tool_call_delta.arguments.empty() || !is_partial) {
211
+ d.tool_call_delta.name = chat_msg.tool_calls[i].name;
212
+ d.tool_call_delta.id = chat_msg.tool_calls[i].id;
213
+ diffs.push_back(std::move(d));
214
+ sent_tool_call_names.insert(i);
215
+ } else {
216
+ // Suppress
217
+ }
218
+ }
219
+ }
220
+ }
221
+ // Final check at EOF
222
+ if (!is_partial) {
223
+ for (size_t i = 0; i < chat_msg.tool_calls.size(); ++i) {
224
+ if (!sent_tool_call_names.count(i) && !chat_msg.tool_calls[i].name.empty()) {
225
+ common_chat_msg_diff header;
226
+ header.tool_call_index = i;
227
+ header.tool_call_delta.id = chat_msg.tool_calls[i].id;
228
+ header.tool_call_delta.name = chat_msg.tool_calls[i].name;
229
+ diffs.push_back(std::move(header));
230
+ sent_tool_call_names.insert(i);
231
+ }
232
+ }
233
+ }
234
+ }
235
+ }
236
+ return chat_msg;
237
+ }
238
+
239
+ //
240
+
241
+ // result_timings
242
+ //
243
+
244
+ json result_timings::to_json() const {
245
+ json base = {
246
+ {"cache_n", cache_n},
247
+
248
+ {"prompt_n", prompt_n},
249
+ {"prompt_ms", prompt_ms},
250
+ {"prompt_per_token_ms", prompt_per_token_ms},
251
+ {"prompt_per_second", prompt_per_second},
252
+
253
+ {"predicted_n", predicted_n},
254
+ {"predicted_ms", predicted_ms},
255
+ {"predicted_per_token_ms", predicted_per_token_ms},
256
+ {"predicted_per_second", predicted_per_second},
257
+ };
258
+
259
+ if (draft_n > 0) {
260
+ base["draft_n"] = draft_n;
261
+ base["draft_n_accepted"] = draft_n_accepted;
262
+ }
263
+
264
+ return base;
265
+ }
266
+
267
+ //
268
+ // result_prompt_progress
269
+ //
270
+ json result_prompt_progress::to_json() const {
271
+ return json {
272
+ {"total", total},
273
+ {"cache", cache},
274
+ {"processed", processed},
275
+ {"time_ms", time_ms},
276
+ };
277
+ }
278
+
279
+ static inline std::string stop_type_to_str(stop_type type) {
280
+ switch (type) {
281
+ case STOP_TYPE_EOS: return "eos";
282
+ case STOP_TYPE_WORD: return "word";
283
+ case STOP_TYPE_LIMIT: return "limit";
284
+ default: return "none";
285
+ }
286
+ }
287
+
288
+ //
289
+ // completion_token_output
290
+ //
291
+
292
+ json completion_token_output::to_json(bool post_sampling_probs) const {
293
+ json probs_for_token = json::array();
294
+ for (const auto & p : probs) {
295
+ std::string txt(p.txt);
296
+ txt.resize(validate_utf8(txt));
297
+ probs_for_token.push_back(json {
298
+ {"id", p.tok},
299
+ {"token", txt},
300
+ {"bytes", str_to_bytes(p.txt)},
301
+ {
302
+ post_sampling_probs ? "prob" : "logprob",
303
+ post_sampling_probs ? p.prob : logarithm(p.prob)
304
+ },
305
+ });
306
+ }
307
+ return probs_for_token;
308
+ }
309
+
310
+ json completion_token_output::probs_vector_to_json(const std::vector<completion_token_output> & probs, bool post_sampling_probs) {
311
+ json out = json::array();
312
+ for (const auto & p : probs) {
313
+ std::string txt(p.text_to_send);
314
+ txt.resize(validate_utf8(txt));
315
+ out.push_back(json {
316
+ {"id", p.tok},
317
+ {"token", txt},
318
+ {"bytes", str_to_bytes(p.text_to_send)},
319
+ {
320
+ post_sampling_probs ? "prob" : "logprob",
321
+ post_sampling_probs ? p.prob : logarithm(p.prob)
322
+ },
323
+ {
324
+ post_sampling_probs ? "top_probs" : "top_logprobs",
325
+ p.to_json(post_sampling_probs)
326
+ },
327
+ });
328
+ }
329
+ return out;
330
+ }
331
+
332
+ float completion_token_output::logarithm(float x) {
333
+ // nlohmann::json converts -inf to null, so we need to prevent that
334
+ return x == 0.0f ? std::numeric_limits<float>::lowest() : std::log(x);
335
+ }
336
+
337
+ std::vector<unsigned char> completion_token_output::str_to_bytes(const std::string & str) {
338
+ std::vector<unsigned char> bytes;
339
+ for (unsigned char c : str) {
340
+ bytes.push_back(c);
341
+ }
342
+ return bytes;
343
+ }
344
+
345
+ //
346
+ // server_task_result_cmpl_final
347
+ //
348
+ json server_task_result_cmpl_final::to_json() {
349
+ GGML_ASSERT(is_updated && "update() must be called before to_json()");
350
+ switch (res_type) {
351
+ case TASK_RESPONSE_TYPE_NONE:
352
+ return to_json_non_oaicompat();
353
+ case TASK_RESPONSE_TYPE_OAI_CMPL:
354
+ return to_json_oaicompat();
355
+ case TASK_RESPONSE_TYPE_OAI_CHAT:
356
+ return stream ? to_json_oaicompat_chat_stream() : to_json_oaicompat_chat();
357
+ case TASK_RESPONSE_TYPE_OAI_RESP:
358
+ return stream ? to_json_oaicompat_resp_stream() : to_json_oaicompat_resp();
359
+ case TASK_RESPONSE_TYPE_OAI_ASR:
360
+ return to_json_oaicompat_asr();
361
+ case TASK_RESPONSE_TYPE_ANTHROPIC:
362
+ return stream ? to_json_anthropic_stream() : to_json_anthropic();
363
+ default:
364
+ GGML_ASSERT(false && "Invalid task_response_type");
365
+ }
366
+ }
367
+
368
+ json server_task_result_cmpl_final::to_json_non_oaicompat() {
369
+ json res = json {
370
+ {"index", index},
371
+ {"content", content},
372
+ {"tokens", tokens},
373
+ {"id_slot", id_slot},
374
+ {"stop", true},
375
+ {"model", oaicompat_model},
376
+ {"tokens_predicted", n_decoded},
377
+ {"tokens_evaluated", n_prompt_tokens},
378
+ {"generation_settings", generation_params.to_json()},
379
+ {"prompt", prompt},
380
+ {"has_new_line", has_new_line},
381
+ {"truncated", truncated},
382
+ {"stop_type", stop_type_to_str(stop)},
383
+ {"stopping_word", stopping_word},
384
+ {"tokens_cached", n_tokens_cached},
385
+ {"timings", timings.to_json()},
386
+ };
387
+ if (!stream && !probs_output.empty()) {
388
+ res["completion_probabilities"] = completion_token_output::probs_vector_to_json(probs_output, post_sampling_probs);
389
+ }
390
+ return response_fields.empty() ? res : json_get_nested_values(response_fields, res);
391
+ }
392
+
393
+ json server_task_result_cmpl_final::usage_json_oaicompat() {
394
+ return json {
395
+ {"completion_tokens", n_decoded},
396
+ {"prompt_tokens", n_prompt_tokens},
397
+ {"total_tokens", n_decoded + n_prompt_tokens},
398
+ {"prompt_tokens_details", json { {"cached_tokens", n_prompt_tokens_cache} }},
399
+ };
400
+ }
401
+
402
+ json server_task_result_cmpl_final::to_json_oaicompat() {
403
+ std::time_t t = std::time(0);
404
+ json logprobs = json(nullptr); // OAI default to null
405
+ if (!stream && probs_output.size() > 0) {
406
+ logprobs = json{
407
+ {"content", completion_token_output::probs_vector_to_json(probs_output, post_sampling_probs)},
408
+ };
409
+ }
410
+ json finish_reason = "length";
411
+ if (stop == STOP_TYPE_WORD || stop == STOP_TYPE_EOS) {
412
+ finish_reason = "stop";
413
+ }
414
+ json res = json {
415
+ {"choices", json::array({
416
+ json{
417
+ {"text", content},
418
+ {"index", index},
419
+ {"logprobs", logprobs},
420
+ {"finish_reason", finish_reason},
421
+ }
422
+ })},
423
+ {"created", t},
424
+ {"model", oaicompat_model},
425
+ {"system_fingerprint", std::string(llama_build_info())},
426
+ {"object", "text_completion"},
427
+ {"usage", usage_json_oaicompat()},
428
+ {"id", oaicompat_cmpl_id}
429
+ };
430
+
431
+ // extra fields for debugging purposes
432
+ if (verbose) {
433
+ res["__verbose"] = to_json_non_oaicompat();
434
+ }
435
+ if (timings.prompt_n >= 0) {
436
+ res.push_back({"timings", timings.to_json()});
437
+ }
438
+
439
+ return res;
440
+ }
441
+
442
+ json server_task_result_cmpl_final::to_json_oaicompat_chat() {
443
+ std::string finish_reason = "length";
444
+ common_chat_msg msg;
445
+ if (!oaicompat_msg.empty()) {
446
+ msg = oaicompat_msg;
447
+ } else {
448
+ msg.role = "assistant";
449
+ msg.content = content;
450
+ }
451
+ if (stop == STOP_TYPE_WORD || stop == STOP_TYPE_EOS) {
452
+ finish_reason = msg.tool_calls.empty() ? "stop" : "tool_calls";
453
+ }
454
+
455
+ json choice {
456
+ {"finish_reason", finish_reason},
457
+ {"index", index},
458
+ {"message", msg.to_json_oaicompat()},
459
+ };
460
+
461
+ if (!stream && probs_output.size() > 0) {
462
+ choice["logprobs"] = json{
463
+ {"content", completion_token_output::probs_vector_to_json(probs_output, post_sampling_probs)},
464
+ };
465
+ }
466
+
467
+ std::time_t t = std::time(0);
468
+
469
+ json res = json {
470
+ {"choices", json::array({choice})},
471
+ {"created", t},
472
+ {"model", oaicompat_model},
473
+ {"system_fingerprint", std::string(llama_build_info())},
474
+ {"object", "chat.completion"},
475
+ {"usage", usage_json_oaicompat()},
476
+ {"id", oaicompat_cmpl_id}
477
+ };
478
+
479
+ // extra fields for debugging purposes
480
+ if (verbose) {
481
+ res["__verbose"] = to_json_non_oaicompat();
482
+ }
483
+ if (timings.prompt_n >= 0) {
484
+ res.push_back({"timings", timings.to_json()});
485
+ }
486
+
487
+ return res;
488
+ }
489
+
490
+ json server_task_result_cmpl_final::to_json_oaicompat_chat_stream() {
491
+ std::time_t t = std::time(0);
492
+ std::string finish_reason = "length";
493
+ if (stop == STOP_TYPE_WORD || stop == STOP_TYPE_EOS) {
494
+ finish_reason = oaicompat_msg.tool_calls.empty() ? "stop" : "tool_calls";
495
+ }
496
+
497
+ json deltas = json::array();
498
+ for (const auto & diff : oaicompat_msg_diffs) {
499
+ deltas.push_back({
500
+ {"choices", json::array({
501
+ json {
502
+ {"finish_reason", nullptr},
503
+ {"index", index},
504
+ {"delta", server_chat_msg_diff_to_json_oaicompat(diff)},
505
+ },
506
+ })},
507
+ {"created", t},
508
+ {"id", oaicompat_cmpl_id},
509
+ {"model", oaicompat_model},
510
+ {"system_fingerprint", std::string(llama_build_info())},
511
+ {"object", "chat.completion.chunk"},
512
+ });
513
+ }
514
+
515
+ deltas.push_back({
516
+ {"choices", json::array({
517
+ json {
518
+ {"finish_reason", finish_reason},
519
+ {"index", index},
520
+ {"delta", json::object()},
521
+ },
522
+ })},
523
+ {"created", t},
524
+ {"id", oaicompat_cmpl_id},
525
+ {"model", oaicompat_model},
526
+ {"system_fingerprint", std::string(llama_build_info())},
527
+ {"object", "chat.completion.chunk"},
528
+ });
529
+
530
+ if (include_usage) {
531
+ // OpenAI API spec for chat.completion.chunks specifies an empty `choices` array for the last chunk when including usage
532
+ // https://platform.openai.com/docs/api-reference/chat_streaming/streaming#chat_streaming/streaming-choices
533
+ deltas.push_back({
534
+ {"choices", json::array()},
535
+ {"created", t},
536
+ {"id", oaicompat_cmpl_id},
537
+ {"model", oaicompat_model},
538
+ {"system_fingerprint", std::string(llama_build_info())},
539
+ {"object", "chat.completion.chunk"},
540
+ {"usage", usage_json_oaicompat()},
541
+ });
542
+ }
543
+
544
+ if (timings.prompt_n >= 0) {
545
+ deltas.back().push_back({"timings", timings.to_json()});
546
+ }
547
+
548
+ // extra fields for debugging purposes
549
+ if (verbose && !deltas.empty()) {
550
+ deltas.front()["__verbose"] = to_json_non_oaicompat();
551
+ }
552
+
553
+ return deltas;
554
+ }
555
+
556
+ json server_task_result_cmpl_final::to_json_oaicompat_resp() {
557
+ common_chat_msg msg;
558
+ if (!oaicompat_msg.empty()) {
559
+ msg = oaicompat_msg;
560
+ } else {
561
+ msg.role = "assistant";
562
+ msg.content = content;
563
+ }
564
+
565
+ std::vector<json> output;
566
+
567
+ if (msg.reasoning_content != "") {
568
+ output.push_back(json {
569
+ {"id", "rs_" + random_string()},
570
+ {"summary", json::array()},
571
+ {"type", "reasoning"},
572
+ {"content", json::array({ json {
573
+ {"text", msg.reasoning_content},
574
+ {"type", "reasoning_text"},
575
+ }})},
576
+ {"encrypted_content", ""},
577
+ {"status", "completed"},
578
+ });
579
+ }
580
+
581
+ if (msg.content != "") {
582
+ output.push_back(json {
583
+ {"content", json::array({ json {
584
+ {"type", "output_text"},
585
+ {"annotations", json::array()},
586
+ {"logprobs", json::array()},
587
+ {"text", msg.content},
588
+ }})},
589
+ {"id", "msg_" + random_string()},
590
+ {"role", msg.role},
591
+ {"status", "completed"},
592
+ {"type", "message"},
593
+ });
594
+ }
595
+
596
+ for (const common_chat_tool_call & tool_call : oaicompat_msg.tool_calls) {
597
+ output.push_back(json {
598
+ {"id", "fc_" + tool_call.id},
599
+ {"type", "function_call"},
600
+ {"status", "completed"},
601
+ {"arguments", tool_call.arguments},
602
+ {"call_id", "call_" + tool_call.id},
603
+ {"name", tool_call.name},
604
+ });
605
+ }
606
+
607
+ std::time_t t = std::time(0);
608
+ json res = {
609
+ {"completed_at", t},
610
+ {"created_at", t},
611
+ {"id", oai_resp_id},
612
+ {"model", oaicompat_model},
613
+ {"object", "response"},
614
+ {"output", output},
615
+ {"status", "completed"},
616
+ {"usage", json {
617
+ {"input_tokens", n_prompt_tokens},
618
+ {"output_tokens", n_decoded},
619
+ {"total_tokens", n_decoded + n_prompt_tokens},
620
+ {"input_tokens_details", json { {"cached_tokens", n_prompt_tokens_cache} }},
621
+ }},
622
+ };
623
+
624
+ return res;
625
+ }
626
+
627
+ json server_task_result_cmpl_final::to_json_oaicompat_resp_stream() {
628
+ std::vector<json> server_sent_events;
629
+ std::vector<json> output;
630
+
631
+ if (oaicompat_msg.reasoning_content != "") {
632
+ const json output_item = json {
633
+ {"id", oai_resp_reasoning_id},
634
+ {"summary", json::array()},
635
+ {"type", "reasoning"},
636
+ {"content", json::array({ json {
637
+ {"text", oaicompat_msg.reasoning_content},
638
+ {"type", "reasoning_text"},
639
+ }})},
640
+ {"encrypted_content", ""},
641
+ };
642
+
643
+ server_sent_events.push_back(json {
644
+ {"event", "response.output_item.done"},
645
+ {"data", json {
646
+ {"type", "response.output_item.done"},
647
+ {"item", output_item}
648
+ }}
649
+ });
650
+ output.push_back(output_item);
651
+ }
652
+
653
+ if (oaicompat_msg.content != "") {
654
+ server_sent_events.push_back(json {
655
+ {"event", "response.output_text.done"},
656
+ {"data", json {
657
+ {"type", "response.output_text.done"},
658
+ {"item_id", oai_resp_message_id},
659
+ {"text", oaicompat_msg.content}
660
+ }}
661
+ });
662
+
663
+ const json content_part = {
664
+ {"type", "output_text"},
665
+ {"annotations", json::array()},
666
+ {"logprobs", json::array()},
667
+ {"text", oaicompat_msg.content}
668
+ };
669
+
670
+ server_sent_events.push_back(json {
671
+ {"event", "response.content_part.done"},
672
+ {"data", json {
673
+ {"type", "response.content_part.done"},
674
+ {"item_id", oai_resp_message_id},
675
+ {"part", content_part}
676
+ }}
677
+ });
678
+ const json output_item = {
679
+ {"type", "message"},
680
+ {"status", "completed"},
681
+ {"id", oai_resp_message_id},
682
+ {"content", json::array({content_part})},
683
+ {"role", "assistant"}
684
+ };
685
+
686
+ server_sent_events.push_back(json {
687
+ {"event", "response.output_item.done"},
688
+ {"data", json {
689
+ {"type", "response.output_item.done"},
690
+ {"item", output_item}
691
+ }}
692
+ });
693
+ output.push_back(output_item);
694
+ }
695
+
696
+ for (const common_chat_tool_call & tool_call : oaicompat_msg.tool_calls) {
697
+ const json output_item = {
698
+ {"id", "fc_" + tool_call.id},
699
+ {"type", "function_call"},
700
+ {"status", "completed"},
701
+ {"arguments", tool_call.arguments},
702
+ {"call_id", "call_" + tool_call.id},
703
+ {"name", tool_call.name}
704
+ };
705
+ server_sent_events.push_back(json {
706
+ {"event", "response.output_item.done"},
707
+ {"data", json {
708
+ {"type", "response.output_item.done"},
709
+ {"item", output_item}
710
+ }}
711
+ });
712
+ output.push_back(output_item);
713
+ }
714
+
715
+ std::time_t t = std::time(0);
716
+ server_sent_events.push_back(json {
717
+ {"event", "response.completed"},
718
+ {"data", json {
719
+ {"type", "response.completed"},
720
+ {"response", json {
721
+ {"id", oai_resp_id},
722
+ {"object", "response"},
723
+ {"created_at", t},
724
+ {"status", "completed"},
725
+ {"model", oaicompat_model},
726
+ {"output", output},
727
+ {"usage", json {
728
+ {"input_tokens", n_prompt_tokens},
729
+ {"output_tokens", n_decoded},
730
+ {"total_tokens", n_decoded + n_prompt_tokens},
731
+ {"input_tokens_details", json { {"cached_tokens", n_prompt_tokens_cache} }},
732
+ }}
733
+ }},
734
+ }}
735
+ });
736
+
737
+ if (timings.prompt_n >= 0) {
738
+ server_sent_events.back().at("data").push_back({"timings", timings.to_json()});
739
+ }
740
+
741
+ return server_sent_events;
742
+ }
743
+
744
+ json server_task_result_cmpl_final::to_json_oaicompat_asr() {
745
+ json event = json {
746
+ {"type", "transcript.text.done"},
747
+ {"text", oaicompat_msg.content},
748
+ {"usage", json {
749
+ {"type", "tokens"},
750
+ {"input_tokens", n_prompt_tokens},
751
+ {"output_tokens", n_decoded},
752
+ {"total_tokens", n_decoded + n_prompt_tokens},
753
+ {"input_tokens_details", json { {"cached_tokens", n_prompt_tokens_cache} }},
754
+ }},
755
+ };
756
+ return event;
757
+ }
758
+
759
+ json server_task_result_cmpl_final::to_json_anthropic() {
760
+ std::string stop_reason = "max_tokens";
761
+ if (stop == STOP_TYPE_WORD || stop == STOP_TYPE_EOS) {
762
+ stop_reason = oaicompat_msg.tool_calls.empty() ? "end_turn" : "tool_use";
763
+ }
764
+
765
+ json content_blocks = json::array();
766
+
767
+ common_chat_msg msg;
768
+ if (!oaicompat_msg.empty()) {
769
+ msg = oaicompat_msg;
770
+ } else {
771
+ msg.role = "assistant";
772
+ msg.content = content;
773
+ }
774
+
775
+ // thinking block comes first (Anthropic extended thinking format)
776
+ if (!msg.reasoning_content.empty()) {
777
+ content_blocks.push_back({
778
+ {"type", "thinking"},
779
+ {"thinking", msg.reasoning_content},
780
+ {"signature", ""} // empty signature for local models (no cryptographic verification)
781
+ });
782
+ }
783
+
784
+ if (!msg.content.empty()) {
785
+ content_blocks.push_back({
786
+ {"type", "text"},
787
+ {"text", msg.content}
788
+ });
789
+ }
790
+
791
+ for (const auto & tool_call : msg.tool_calls) {
792
+ json tool_use_block = {
793
+ {"type", "tool_use"},
794
+ {"id", tool_call.id},
795
+ {"name", tool_call.name}
796
+ };
797
+
798
+ try {
799
+ tool_use_block["input"] = json::parse(tool_call.arguments);
800
+ } catch (const std::exception &) {
801
+ tool_use_block["input"] = json::object();
802
+ }
803
+
804
+ content_blocks.push_back(tool_use_block);
805
+ }
806
+
807
+ json res = {
808
+ {"id", oaicompat_cmpl_id},
809
+ {"type", "message"},
810
+ {"role", "assistant"},
811
+ {"content", content_blocks},
812
+ {"model", oaicompat_model},
813
+ {"stop_reason", stop_reason},
814
+ {"stop_sequence", stopping_word.empty() ? nullptr : json(stopping_word)},
815
+ {"usage", {
816
+ {"cache_read_input_tokens", n_prompt_tokens_cache},
817
+ {"input_tokens", n_prompt_tokens - n_prompt_tokens_cache},
818
+ {"output_tokens", n_decoded}
819
+ }}
820
+ };
821
+
822
+ return res;
823
+ }
824
+
825
+ json server_task_result_cmpl_final::to_json_anthropic_stream() {
826
+ json events = json::array();
827
+
828
+ std::string stop_reason = "max_tokens";
829
+ if (stop == STOP_TYPE_WORD || stop == STOP_TYPE_EOS) {
830
+ stop_reason = oaicompat_msg.tool_calls.empty() ? "end_turn" : "tool_use";
831
+ }
832
+
833
+ bool has_thinking = !oaicompat_msg.reasoning_content.empty();
834
+ bool has_text = !oaicompat_msg.content.empty();
835
+ size_t num_tool_calls = oaicompat_msg.tool_calls.size();
836
+
837
+ // content block indices: thinking (0) -> text (0 or 1) -> tool_use (n+)
838
+ size_t thinking_block_index = 0;
839
+ size_t text_block_index = has_thinking ? 1 : 0;
840
+
841
+ bool thinking_block_started = false;
842
+ bool text_block_started = false;
843
+ std::unordered_set<size_t> tool_calls_started;
844
+
845
+ for (const auto & diff : oaicompat_msg_diffs) {
846
+ // handle thinking/reasoning content
847
+ if (!diff.reasoning_content_delta.empty()) {
848
+ if (!thinking_block_started) {
849
+ events.push_back({
850
+ {"event", "content_block_start"},
851
+ {"data", {
852
+ {"type", "content_block_start"},
853
+ {"index", thinking_block_index},
854
+ {"content_block", {
855
+ {"type", "thinking"},
856
+ {"thinking", ""}
857
+ }}
858
+ }}
859
+ });
860
+ thinking_block_started = true;
861
+ }
862
+
863
+ events.push_back({
864
+ {"event", "content_block_delta"},
865
+ {"data", {
866
+ {"type", "content_block_delta"},
867
+ {"index", thinking_block_index},
868
+ {"delta", {
869
+ {"type", "thinking_delta"},
870
+ {"thinking", diff.reasoning_content_delta}
871
+ }}
872
+ }}
873
+ });
874
+ }
875
+
876
+ // handle regular text content
877
+ if (!diff.content_delta.empty()) {
878
+ if (!text_block_started) {
879
+ events.push_back({
880
+ {"event", "content_block_start"},
881
+ {"data", {
882
+ {"type", "content_block_start"},
883
+ {"index", text_block_index},
884
+ {"content_block", {
885
+ {"type", "text"},
886
+ {"text", ""}
887
+ }}
888
+ }}
889
+ });
890
+ text_block_started = true;
891
+ }
892
+
893
+ events.push_back({
894
+ {"event", "content_block_delta"},
895
+ {"data", {
896
+ {"type", "content_block_delta"},
897
+ {"index", text_block_index},
898
+ {"delta", {
899
+ {"type", "text_delta"},
900
+ {"text", diff.content_delta}
901
+ }}
902
+ }}
903
+ });
904
+ }
905
+
906
+ // handle tool calls
907
+ if (diff.tool_call_index != std::string::npos) {
908
+ size_t content_block_index = (has_thinking ? 1 : 0) + (has_text ? 1 : 0) + diff.tool_call_index;
909
+
910
+ if (tool_calls_started.find(diff.tool_call_index) == tool_calls_started.end()) {
911
+ const auto & full_tool_call = oaicompat_msg.tool_calls[diff.tool_call_index];
912
+
913
+ events.push_back({
914
+ {"event", "content_block_start"},
915
+ {"data", {
916
+ {"type", "content_block_start"},
917
+ {"index", content_block_index},
918
+ {"content_block", {
919
+ {"type", "tool_use"},
920
+ {"id", full_tool_call.id},
921
+ {"name", full_tool_call.name}
922
+ }}
923
+ }}
924
+ });
925
+ tool_calls_started.insert(diff.tool_call_index);
926
+ }
927
+
928
+ if (!diff.tool_call_delta.arguments.empty()) {
929
+ events.push_back({
930
+ {"event", "content_block_delta"},
931
+ {"data", {
932
+ {"type", "content_block_delta"},
933
+ {"index", content_block_index},
934
+ {"delta", {
935
+ {"type", "input_json_delta"},
936
+ {"partial_json", diff.tool_call_delta.arguments}
937
+ }}
938
+ }}
939
+ });
940
+ }
941
+ }
942
+ }
943
+
944
+ // close content blocks in order
945
+ if (has_thinking) {
946
+ // Anthropic API requires a signature_delta before closing thinking blocks
947
+ // We use an empty signature since we can't generate a cryptographic signature for local models
948
+ events.push_back({
949
+ {"event", "content_block_delta"},
950
+ {"data", {
951
+ {"type", "content_block_delta"},
952
+ {"index", thinking_block_index},
953
+ {"delta", {
954
+ {"type", "signature_delta"},
955
+ {"signature", ""}
956
+ }}
957
+ }}
958
+ });
959
+ events.push_back({
960
+ {"event", "content_block_stop"},
961
+ {"data", {
962
+ {"type", "content_block_stop"},
963
+ {"index", thinking_block_index}
964
+ }}
965
+ });
966
+ }
967
+
968
+ if (has_text) {
969
+ events.push_back({
970
+ {"event", "content_block_stop"},
971
+ {"data", {
972
+ {"type", "content_block_stop"},
973
+ {"index", text_block_index}
974
+ }}
975
+ });
976
+ }
977
+
978
+ for (size_t i = 0; i < num_tool_calls; i++) {
979
+ size_t content_block_index = (has_thinking ? 1 : 0) + (has_text ? 1 : 0) + i;
980
+ events.push_back({
981
+ {"event", "content_block_stop"},
982
+ {"data", {
983
+ {"type", "content_block_stop"},
984
+ {"index", content_block_index}
985
+ }}
986
+ });
987
+ }
988
+
989
+ events.push_back({
990
+ {"event", "message_delta"},
991
+ {"data", {
992
+ {"type", "message_delta"},
993
+ {"delta", {
994
+ {"stop_reason", stop_reason},
995
+ {"stop_sequence", stopping_word.empty() ? nullptr : json(stopping_word)}
996
+ }},
997
+ {"usage", {
998
+ {"output_tokens", n_decoded}
999
+ }}
1000
+ }}
1001
+ });
1002
+
1003
+ events.push_back({
1004
+ {"event", "message_stop"},
1005
+ {"data", {
1006
+ {"type", "message_stop"}
1007
+ }}
1008
+ });
1009
+
1010
+ return events;
1011
+ }
1012
+
1013
+ //
1014
+ // server_task_result_cmpl_partial
1015
+ //
1016
+ void server_task_result_cmpl_partial::update(task_result_state & state) {
1017
+ is_updated = true;
1018
+ if (is_begin) {
1019
+ return; // begin marker only flushes headers, skip parsing
1020
+ }
1021
+ state.update_chat_msg(content, true, oaicompat_msg_diffs);
1022
+
1023
+ // Copy current state for use in to_json_*() (reflects state BEFORE this chunk)
1024
+ thinking_block_started = state.thinking_block_started;
1025
+ text_block_started = state.text_block_started;
1026
+
1027
+ oai_resp_created = state.oai_resp_created;
1028
+ oai_resp_id = state.oai_resp_id;
1029
+ oai_resp_reasoning_id = state.oai_resp_reasoning_id;
1030
+ oai_resp_message_id = state.oai_resp_message_id;
1031
+ oai_resp_fc_id = state.oai_resp_fc_id;
1032
+
1033
+ // track if the accumulated message has any reasoning content
1034
+ anthropic_has_reasoning = !state.chat_msg.reasoning_content.empty();
1035
+
1036
+ if (res_type == TASK_RESPONSE_TYPE_OAI_RESP && !state.oai_resp_created && (is_progress || n_decoded == 1)) {
1037
+ state.oai_resp_created = true;
1038
+ }
1039
+
1040
+ // Pre-compute state updates based on diffs (for next chunk)
1041
+ for (const common_chat_msg_diff & diff : oaicompat_msg_diffs) {
1042
+ if (!diff.reasoning_content_delta.empty() && !state.thinking_block_started) {
1043
+ state.thinking_block_started = true;
1044
+ }
1045
+ if (!diff.content_delta.empty() && !state.text_block_started) {
1046
+ state.text_block_started = true;
1047
+ }
1048
+ if (!diff.tool_call_delta.name.empty()) {
1049
+ state.oai_resp_fc_id = diff.tool_call_delta.id;
1050
+ }
1051
+ }
1052
+ }
1053
+
1054
+ json server_task_result_cmpl_partial::to_json() {
1055
+ GGML_ASSERT(is_updated && "update() must be called before to_json()");
1056
+ if (is_begin) {
1057
+ return nullptr; // simply signal to HTTP handler to send the headers and status code
1058
+ }
1059
+ switch (res_type) {
1060
+ case TASK_RESPONSE_TYPE_NONE:
1061
+ return to_json_non_oaicompat();
1062
+ case TASK_RESPONSE_TYPE_OAI_CMPL:
1063
+ return to_json_oaicompat();
1064
+ case TASK_RESPONSE_TYPE_OAI_CHAT:
1065
+ return to_json_oaicompat_chat();
1066
+ case TASK_RESPONSE_TYPE_OAI_RESP:
1067
+ return to_json_oaicompat_resp();
1068
+ case TASK_RESPONSE_TYPE_OAI_ASR:
1069
+ return to_json_oaicompat_asr();
1070
+ case TASK_RESPONSE_TYPE_ANTHROPIC:
1071
+ return to_json_anthropic();
1072
+ default:
1073
+ GGML_ASSERT(false && "Invalid task_response_type");
1074
+ }
1075
+ }
1076
+
1077
+ json server_task_result_cmpl_partial::to_json_non_oaicompat() {
1078
+ // non-OAI-compat JSON
1079
+ json res = json {
1080
+ {"index", index},
1081
+ {"content", content},
1082
+ {"tokens", tokens},
1083
+ {"stop", false},
1084
+ {"id_slot", id_slot},
1085
+ {"tokens_predicted", n_decoded},
1086
+ {"tokens_evaluated", n_prompt_tokens},
1087
+ };
1088
+ // populate the timings object when needed (usually for the last response or with timings_per_token enabled)
1089
+ if (timings.prompt_n > 0) {
1090
+ res.push_back({"timings", timings.to_json()});
1091
+ }
1092
+ if (is_progress) {
1093
+ res.push_back({"prompt_progress", progress.to_json()});
1094
+ }
1095
+ if (!prob_output.probs.empty()) {
1096
+ res["completion_probabilities"] = completion_token_output::probs_vector_to_json({prob_output}, post_sampling_probs);
1097
+ }
1098
+ return res;
1099
+ }
1100
+
1101
+ json server_task_result_cmpl_partial::to_json_oaicompat() {
1102
+ std::time_t t = std::time(0);
1103
+ json logprobs = json(nullptr); // OAI default to null
1104
+ if (prob_output.probs.size() > 0) {
1105
+ logprobs = json{
1106
+ {"content", completion_token_output::probs_vector_to_json({prob_output}, post_sampling_probs)},
1107
+ };
1108
+ }
1109
+ json res = json {
1110
+ {"choices", json::array({
1111
+ json{
1112
+ {"text", content},
1113
+ {"index", index},
1114
+ {"logprobs", logprobs},
1115
+ {"finish_reason", nullptr},
1116
+ }
1117
+ })},
1118
+ {"created", t},
1119
+ {"model", oaicompat_model},
1120
+ {"system_fingerprint", std::string(llama_build_info())},
1121
+ {"object", "text_completion"},
1122
+ {"id", oaicompat_cmpl_id}
1123
+ };
1124
+
1125
+ // extra fields for debugging purposes
1126
+ if (verbose) {
1127
+ res["__verbose"] = to_json_non_oaicompat();
1128
+ }
1129
+ if (timings.prompt_n >= 0) {
1130
+ res.push_back({"timings", timings.to_json()});
1131
+ }
1132
+ if (is_progress) {
1133
+ res.push_back({"prompt_progress", progress.to_json()});
1134
+ }
1135
+
1136
+ return res;
1137
+ }
1138
+
1139
+ json server_task_result_cmpl_partial::to_json_oaicompat_chat() {
1140
+ bool first = n_decoded == 1;
1141
+ std::time_t t = std::time(0);
1142
+ json choices;
1143
+
1144
+ std::vector<json> deltas;
1145
+ auto add_delta = [&](const json & delta) {
1146
+ deltas.push_back({
1147
+ {"choices", json::array({
1148
+ json {
1149
+ {"finish_reason", nullptr},
1150
+ {"index", index},
1151
+ {"delta", delta},
1152
+ },
1153
+ })},
1154
+ {"created", t},
1155
+ {"id", oaicompat_cmpl_id},
1156
+ {"model", oaicompat_model},
1157
+ {"system_fingerprint", std::string(llama_build_info())},
1158
+ {"object", "chat.completion.chunk"},
1159
+ });
1160
+ };
1161
+ // We have to send an initial update to conform to openai behavior
1162
+ if (first || is_progress) {
1163
+ add_delta({
1164
+ {"role", "assistant"},
1165
+ {"content", nullptr},
1166
+ });
1167
+ }
1168
+
1169
+ for (const auto & diff : oaicompat_msg_diffs) {
1170
+ add_delta(server_chat_msg_diff_to_json_oaicompat(diff));
1171
+ }
1172
+
1173
+ if (!deltas.empty()) {
1174
+ auto & last_json = deltas[deltas.size() - 1];
1175
+ GGML_ASSERT(last_json.at("choices").size() >= 1);
1176
+
1177
+ if (prob_output.probs.size() > 0) {
1178
+ last_json.at("choices").at(0)["logprobs"] = json {
1179
+ {"content", completion_token_output::probs_vector_to_json({prob_output}, post_sampling_probs)},
1180
+ };
1181
+ }
1182
+
1183
+ if (timings.prompt_n >= 0) {
1184
+ last_json.push_back({"timings", timings.to_json()});
1185
+ }
1186
+ if (is_progress) {
1187
+ last_json.push_back({"prompt_progress", progress.to_json()});
1188
+ }
1189
+ }
1190
+
1191
+ return deltas;
1192
+ }
1193
+
1194
+ json server_task_result_cmpl_partial::to_json_oaicompat_resp() {
1195
+ std::vector<json> events;
1196
+
1197
+ if (!oai_resp_created) {
1198
+ events.push_back(json {
1199
+ {"event", "response.created"},
1200
+ {"data", json {
1201
+ {"type", "response.created"},
1202
+ {"response", json {
1203
+ {"id", oai_resp_id},
1204
+ {"object", "response"},
1205
+ {"status", "in_progress"},
1206
+ }},
1207
+ }},
1208
+ });
1209
+ events.push_back(json {
1210
+ {"event", "response.in_progress"},
1211
+ {"data", json {
1212
+ {"type", "response.in_progress"},
1213
+ {"response", json {
1214
+ {"id", oai_resp_id},
1215
+ {"object", "response"},
1216
+ {"status", "in_progress"},
1217
+ }},
1218
+ }},
1219
+ });
1220
+ } else if (is_progress) {
1221
+ events.push_back(json {
1222
+ {"event", "response.in_progress"},
1223
+ {"data", json {
1224
+ {"type", "response.in_progress"},
1225
+ {"response", json {
1226
+ {"id", oai_resp_id},
1227
+ {"object", "response"},
1228
+ {"status", "in_progress"},
1229
+ }},
1230
+ }},
1231
+ });
1232
+ }
1233
+
1234
+ for (const common_chat_msg_diff & diff : oaicompat_msg_diffs) {
1235
+ if (!diff.reasoning_content_delta.empty()) {
1236
+ if (!thinking_block_started) {
1237
+ events.push_back(json {
1238
+ {"event", "response.output_item.added"},
1239
+ {"data", json {
1240
+ {"type", "response.output_item.added"},
1241
+ {"item", json {
1242
+ {"id", oai_resp_reasoning_id},
1243
+ {"summary", json::array()},
1244
+ {"type", "reasoning"},
1245
+ {"content", json::array()},
1246
+ {"encrypted_content", ""},
1247
+ {"status", "in_progress"},
1248
+ }},
1249
+ }},
1250
+ });
1251
+ thinking_block_started = true;
1252
+ }
1253
+ events.push_back(json {
1254
+ {"event", "response.reasoning_text.delta"},
1255
+ {"data", json {
1256
+ {"type", "response.reasoning_text.delta"},
1257
+ {"delta", diff.reasoning_content_delta},
1258
+ {"item_id", oai_resp_reasoning_id},
1259
+ }},
1260
+ });
1261
+ }
1262
+
1263
+ if (!diff.content_delta.empty()) {
1264
+ if (!text_block_started) {
1265
+ events.push_back(json {
1266
+ {"event", "response.output_item.added"},
1267
+ {"data", json {
1268
+ {"type", "response.output_item.added"},
1269
+ {"item", json {
1270
+ {"content", json::array()},
1271
+ {"id", oai_resp_message_id},
1272
+ {"role", "assistant"},
1273
+ {"status", "in_progress"},
1274
+ {"type", "message"},
1275
+ }},
1276
+ }},
1277
+ });
1278
+ events.push_back(json {
1279
+ {"event", "response.content_part.added"},
1280
+ {"data", json {
1281
+ {"type", "response.content_part.added"},
1282
+ {"item_id", oai_resp_message_id},
1283
+ {"part", json {
1284
+ {"type", "output_text"},
1285
+ {"text", ""},
1286
+ }},
1287
+ }},
1288
+ });
1289
+ text_block_started = true;
1290
+ }
1291
+ events.push_back(json {
1292
+ {"event", "response.output_text.delta"},
1293
+ {"data", json {
1294
+ {"type", "response.output_text.delta"},
1295
+ {"item_id", oai_resp_message_id},
1296
+ {"delta", diff.content_delta},
1297
+ }},
1298
+ });
1299
+ }
1300
+
1301
+ if (!diff.tool_call_delta.name.empty()) {
1302
+ events.push_back(json {
1303
+ {"event", "response.output_item.added"},
1304
+ {"data", json {
1305
+ {"type", "response.output_item.added"},
1306
+ {"item", json {
1307
+ {"id", "fc_" + diff.tool_call_delta.id},
1308
+ {"arguments", ""},
1309
+ {"call_id", "call_" + diff.tool_call_delta.id},
1310
+ {"name", diff.tool_call_delta.name},
1311
+ {"type", "function_call"},
1312
+ {"status", "in_progress"},
1313
+ }},
1314
+ }},
1315
+ });
1316
+ oai_resp_fc_id = diff.tool_call_delta.id;
1317
+ }
1318
+
1319
+ if (!diff.tool_call_delta.arguments.empty()) {
1320
+ events.push_back(json {
1321
+ {"event", "response.function_call_arguments.delta"},
1322
+ {"data", json {
1323
+ {"type", "response.function_call_arguments.delta"},
1324
+ {"delta", diff.tool_call_delta.arguments},
1325
+ {"item_id", "fc_" + oai_resp_fc_id},
1326
+ }},
1327
+ });
1328
+ }
1329
+ }
1330
+
1331
+ if (!events.empty()) {
1332
+ json & data = events.back().at("data");
1333
+ if (timings.prompt_n >= 0) {
1334
+ data.push_back({"timings", timings.to_json()});
1335
+ }
1336
+ if (is_progress) {
1337
+ data.push_back({"prompt_progress", progress.to_json()});
1338
+ }
1339
+ }
1340
+
1341
+ return events;
1342
+ }
1343
+
1344
+ json server_task_result_cmpl_partial::to_json_oaicompat_asr() {
1345
+ json event = json {
1346
+ {"type", "transcript.text.delta"},
1347
+ {"delta", content},
1348
+ };
1349
+ return event;
1350
+ }
1351
+
1352
+ json server_task_result_cmpl_partial::to_json_anthropic() {
1353
+ json events = json::array();
1354
+ bool first = (n_decoded == 1);
1355
+ // use member variables to track block state across streaming calls
1356
+ // (anthropic_thinking_block_started, anthropic_text_block_started)
1357
+
1358
+ if (first) {
1359
+ events.push_back({
1360
+ {"event", "message_start"},
1361
+ {"data", {
1362
+ {"type", "message_start"},
1363
+ {"message", {
1364
+ {"id", oaicompat_cmpl_id},
1365
+ {"type", "message"},
1366
+ {"role", "assistant"},
1367
+ {"content", json::array()},
1368
+ {"model", oaicompat_model},
1369
+ {"stop_reason", nullptr},
1370
+ {"stop_sequence", nullptr},
1371
+ {"usage", {
1372
+ {"cache_read_input_tokens", n_prompt_tokens_cache},
1373
+ {"input_tokens", n_prompt_tokens - n_prompt_tokens_cache},
1374
+ {"output_tokens", 0}
1375
+ }}
1376
+ }}
1377
+ }}
1378
+ });
1379
+ }
1380
+
1381
+ // content block indices: thinking (0) -> text (0 or 1) -> tool_use (n+)
1382
+ size_t thinking_block_index = 0;
1383
+ // use anthropic_has_reasoning (set in update()) to know if ANY reasoning was generated
1384
+ size_t text_block_index = anthropic_has_reasoning ? 1 : 0;
1385
+
1386
+ // use local copies of streaming state (copied from task_result_state in update())
1387
+ // these reflect the state BEFORE this chunk was processed
1388
+ bool thinking_started = thinking_block_started;
1389
+ bool text_started = text_block_started;
1390
+
1391
+ for (const auto & diff : oaicompat_msg_diffs) {
1392
+ // handle thinking/reasoning content
1393
+ if (!diff.reasoning_content_delta.empty()) {
1394
+ if (!thinking_started) {
1395
+ events.push_back({
1396
+ {"event", "content_block_start"},
1397
+ {"data", {
1398
+ {"type", "content_block_start"},
1399
+ {"index", thinking_block_index},
1400
+ {"content_block", {
1401
+ {"type", "thinking"},
1402
+ {"thinking", ""}
1403
+ }}
1404
+ }}
1405
+ });
1406
+ thinking_started = true;
1407
+ }
1408
+
1409
+ events.push_back({
1410
+ {"event", "content_block_delta"},
1411
+ {"data", {
1412
+ {"type", "content_block_delta"},
1413
+ {"index", thinking_block_index},
1414
+ {"delta", {
1415
+ {"type", "thinking_delta"},
1416
+ {"thinking", diff.reasoning_content_delta}
1417
+ }}
1418
+ }}
1419
+ });
1420
+ }
1421
+
1422
+ // handle regular text content
1423
+ if (!diff.content_delta.empty()) {
1424
+ if (!text_started) {
1425
+ events.push_back({
1426
+ {"event", "content_block_start"},
1427
+ {"data", {
1428
+ {"type", "content_block_start"},
1429
+ {"index", text_block_index},
1430
+ {"content_block", {
1431
+ {"type", "text"},
1432
+ {"text", ""}
1433
+ }}
1434
+ }}
1435
+ });
1436
+ text_started = true;
1437
+ }
1438
+
1439
+ events.push_back({
1440
+ {"event", "content_block_delta"},
1441
+ {"data", {
1442
+ {"type", "content_block_delta"},
1443
+ {"index", text_block_index},
1444
+ {"delta", {
1445
+ {"type", "text_delta"},
1446
+ {"text", diff.content_delta}
1447
+ }}
1448
+ }}
1449
+ });
1450
+ }
1451
+
1452
+ // handle tool calls
1453
+ if (diff.tool_call_index != std::string::npos) {
1454
+ // use anthropic_has_reasoning for thinking block count (persists across calls)
1455
+ size_t content_block_index = (anthropic_has_reasoning ? 1 : 0) + (text_started ? 1 : 0) + diff.tool_call_index;
1456
+
1457
+ if (!diff.tool_call_delta.name.empty()) {
1458
+ events.push_back({
1459
+ {"event", "content_block_start"},
1460
+ {"data", {
1461
+ {"type", "content_block_start"},
1462
+ {"index", content_block_index},
1463
+ {"content_block", {
1464
+ {"type", "tool_use"},
1465
+ {"id", diff.tool_call_delta.id},
1466
+ {"name", diff.tool_call_delta.name}
1467
+ }}
1468
+ }}
1469
+ });
1470
+ }
1471
+
1472
+ if (!diff.tool_call_delta.arguments.empty()) {
1473
+ events.push_back({
1474
+ {"event", "content_block_delta"},
1475
+ {"data", {
1476
+ {"type", "content_block_delta"},
1477
+ {"index", content_block_index},
1478
+ {"delta", {
1479
+ {"type", "input_json_delta"},
1480
+ {"partial_json", diff.tool_call_delta.arguments}
1481
+ }}
1482
+ }}
1483
+ });
1484
+ }
1485
+ }
1486
+ }
1487
+
1488
+ return events;
1489
+ }
1490
+
1491
+ //
1492
+ // server_task_result_embd
1493
+ //
1494
+ json server_task_result_embd::to_json() {
1495
+ return res_type == TASK_RESPONSE_TYPE_OAI_EMBD
1496
+ ? to_json_oaicompat()
1497
+ : to_json_non_oaicompat();
1498
+ }
1499
+
1500
+ json server_task_result_embd::to_json_non_oaicompat() {
1501
+ return json {
1502
+ {"index", index},
1503
+ {"embedding", embedding},
1504
+ };
1505
+ }
1506
+
1507
+ json server_task_result_embd::to_json_oaicompat() {
1508
+ return json {
1509
+ {"index", index},
1510
+ {"embedding", embedding[0]},
1511
+ {"tokens_evaluated", n_tokens},
1512
+ };
1513
+ }
1514
+
1515
+ //
1516
+ // server_task_result_rerank
1517
+ //
1518
+ json server_task_result_rerank::to_json() {
1519
+ return json {
1520
+ {"index", index},
1521
+ {"score", score},
1522
+ {"tokens_evaluated", n_tokens},
1523
+ };
1524
+ }
1525
+
1526
+ //
1527
+ // server_task_result_error
1528
+ //
1529
+ json server_task_result_error::to_json() {
1530
+ json res = format_error_response(err_msg, err_type);
1531
+ if (err_type == ERROR_TYPE_EXCEED_CONTEXT_SIZE) {
1532
+ res["n_prompt_tokens"] = n_prompt_tokens;
1533
+ res["n_ctx"] = n_ctx;
1534
+ }
1535
+ return res;
1536
+ }
1537
+
1538
+ //
1539
+ // server_task_result_metrics
1540
+ //
1541
+ json server_task_result_metrics::to_json() {
1542
+ return json {
1543
+ { "idle", n_idle_slots },
1544
+ { "processing", n_processing_slots },
1545
+ { "deferred", n_tasks_deferred },
1546
+ { "t_start", t_start },
1547
+
1548
+ { "n_prompt_tokens_processed_total", n_prompt_tokens_processed_total },
1549
+ { "t_tokens_generation_total", t_tokens_generation_total },
1550
+ { "n_tokens_predicted_total", n_tokens_predicted_total },
1551
+ { "t_prompt_processing_total", t_prompt_processing_total },
1552
+
1553
+ { "n_tokens_max", n_tokens_max },
1554
+
1555
+ { "n_prompt_tokens_processed", n_prompt_tokens_processed },
1556
+ { "t_prompt_processing", t_prompt_processing },
1557
+ { "n_tokens_predicted", n_tokens_predicted },
1558
+ { "t_tokens_generation", t_tokens_generation },
1559
+
1560
+ { "n_decode_total", n_decode_total },
1561
+ { "n_busy_slots_total", n_busy_slots_total },
1562
+
1563
+ { "n_draft_tokens_total", n_draft_tokens_total },
1564
+ { "n_draft_accepted_total", n_draft_accepted_total },
1565
+ { "n_draft_verif_steps_total", n_draft_verif_steps_total },
1566
+ { "n_accepted_per_pos_total", n_accepted_per_pos_total },
1567
+
1568
+ { "slots", slots_data },
1569
+ };
1570
+ }
1571
+
1572
+ //
1573
+ // server_task_result_slot_save_load
1574
+ //
1575
+ json server_task_result_slot_save_load::to_json() {
1576
+ if (is_save) {
1577
+ return json {
1578
+ { "id_slot", id_slot },
1579
+ { "filename", filename },
1580
+ { "n_saved", n_tokens },
1581
+ { "n_written", n_bytes },
1582
+ { "timings", {
1583
+ { "save_ms", t_ms }
1584
+ }},
1585
+ };
1586
+ }
1587
+
1588
+ return json {
1589
+ { "id_slot", id_slot },
1590
+ { "filename", filename },
1591
+ { "n_restored", n_tokens },
1592
+ { "n_read", n_bytes },
1593
+ { "timings", {
1594
+ { "restore_ms", t_ms }
1595
+ }},
1596
+ };
1597
+ }
1598
+
1599
+ //
1600
+ // server_task_result_slot_erase
1601
+ //
1602
+ json server_task_result_slot_erase::to_json() {
1603
+ return json {
1604
+ { "id_slot", id_slot },
1605
+ { "n_erased", n_erased },
1606
+ };
1607
+ }
1608
+
1609
+ //
1610
+ // server_task_result_get_lora
1611
+ //
1612
+
1613
+ json server_task_result_get_lora::to_json() {
1614
+ json result = json::array();
1615
+ for (size_t i = 0; i < loras.size(); ++i) {
1616
+ auto & lora = loras[i];
1617
+ json entry = {
1618
+ {"id", i},
1619
+ {"path", lora.info.path},
1620
+ {"scale", lora.info.scale},
1621
+ {"task_name", lora.info.task_name},
1622
+ {"prompt_prefix", lora.info.prompt_prefix},
1623
+ };
1624
+ if (!lora.alora_invocation_tokens.empty()) {
1625
+ entry["alora_invocation_string"] = lora.alora_invocation_string;
1626
+ entry["alora_invocation_tokens"] = lora.alora_invocation_tokens;
1627
+ }
1628
+ result.push_back(std::move(entry));
1629
+ }
1630
+ return result;
1631
+ }
1632
+
1633
+ //
1634
+ // server_task_result_apply_lora
1635
+ //
1636
+
1637
+ json server_task_result_apply_lora::to_json() {
1638
+ return json {{ "success", true }};
1639
+ }
1640
+
1641
+ //
1642
+ // server_prompt_cache
1643
+ //
1644
+ size_t server_prompt_cache::size() const {
1645
+ size_t res = 0;
1646
+
1647
+ for (const auto & state : states) {
1648
+ res += state.size();
1649
+ }
1650
+
1651
+ return res;
1652
+ }
1653
+
1654
+ size_t server_prompt_cache::n_tokens() const {
1655
+ size_t res = 0;
1656
+
1657
+ for (const auto & state : states) {
1658
+ res += state.prompt.n_tokens();
1659
+ }
1660
+
1661
+ return res;
1662
+ }
1663
+
1664
+ server_prompt_cache_state * server_prompt_cache::alloc(const server_prompt & prompt, size_t state_size_tgt, size_t state_size_dft) {
1665
+ // first check if the current state is contained fully in the cache
1666
+ for (auto it = states.begin(); it != states.end(); ++it) {
1667
+ const int cur_lcp_len = it->prompt.tokens.get_common_prefix(prompt.tokens);
1668
+
1669
+ if (cur_lcp_len == (int) prompt.tokens.size()) {
1670
+ SRV_TRC("%s", " - prompt is already in the cache, skipping\n");
1671
+ return nullptr;
1672
+ }
1673
+ }
1674
+
1675
+ // calculate checkpoints size to see if it will fit with the prompt
1676
+ size_t checkpoints_size = 0;
1677
+ for (const auto & ckpt : prompt.checkpoints) {
1678
+ checkpoints_size += ckpt.size();
1679
+ }
1680
+
1681
+ const size_t state_size_new = state_size_tgt + state_size_dft + checkpoints_size;
1682
+
1683
+ // skip over-limit entries to avoid disturbing the cache
1684
+ if (limit_size > 0 && state_size_new > limit_size) {
1685
+ SRV_WRN(" - prompt state size %.3f MiB exceeds cache size limit %.3f MiB, skipping\n",
1686
+ state_size_new / (1024.0 * 1024.0), limit_size / (1024.0 * 1024.0));
1687
+ return nullptr;
1688
+ }
1689
+
1690
+ // remove any cached prompts that are fully contained in the current prompt
1691
+ for (auto it = states.begin(); it != states.end();) {
1692
+ const int len = it->prompt.tokens.get_common_prefix(prompt.tokens);
1693
+
1694
+ if (len == (int) it->prompt.tokens.size()) {
1695
+ SRV_TRC(" - removing obsolete cached prompt with length %d\n", len);
1696
+
1697
+ it = states.erase(it);
1698
+ } else {
1699
+ ++it;
1700
+ }
1701
+ }
1702
+
1703
+ if (limit_size > 0) {
1704
+ // make room before allocating the new vectors to avoid breaching the limit
1705
+ while (!states.empty() && size() + state_size_new > limit_size) {
1706
+ SRV_WRN(" - making room for prompt cache entry, removing oldest entry (size = %.3f MiB)\n",
1707
+ states.front().size() / (1024.0 * 1024.0));
1708
+
1709
+ states.pop_front();
1710
+ }
1711
+ }
1712
+
1713
+ std::vector<uint8_t> state_data_tgt;
1714
+ std::vector<uint8_t> state_data_dft;
1715
+
1716
+ // check if we can allocate enough memory for the new state
1717
+ try {
1718
+ state_data_tgt.resize(state_size_tgt);
1719
+ state_data_dft.resize(state_size_dft);
1720
+ } catch (const std::bad_alloc & e) {
1721
+ SRV_ERR("failed to allocate memory for prompt cache state: %s\n", e.what());
1722
+
1723
+ limit_size = std::max<size_t>(1, 0.4*size());
1724
+
1725
+ SRV_WRN(" - cache size limit reduced to %.3f MiB\n", limit_size / (1024.0 * 1024.0));
1726
+
1727
+ update();
1728
+
1729
+ return nullptr;
1730
+ }
1731
+
1732
+ states.push_back({
1733
+ /*.prompt =*/ {
1734
+ /*.tokens =*/ prompt.tokens.clone(),
1735
+ /*.checkpoints =*/ prompt.checkpoints,
1736
+ },
1737
+ /*.data =*/ {
1738
+ /*.main =*/ std::move(state_data_tgt),
1739
+ /*.drft =*/ std::move(state_data_dft),
1740
+ },
1741
+ });
1742
+
1743
+ return &states.back();
1744
+ }
1745
+
1746
+ bool server_prompt_cache::load(server_prompt & prompt, const server_tokens & tokens_new, llama_context * ctx_tgt, llama_context * ctx_dft, int32_t id_slot) {
1747
+ const int lcp_best = prompt.tokens.get_common_prefix(tokens_new);
1748
+
1749
+ float f_keep_best = prompt.tokens.size() > 0 ? float(lcp_best) / prompt.tokens.size() : -1.0f; // empty slot: any cache entry wins
1750
+ float f_sim_best = float(lcp_best) / tokens_new.size();
1751
+
1752
+ SRV_TRC(" - looking for better prompt, base f_keep = %.3f, f_sim = %.3f\n", f_keep_best, f_sim_best);
1753
+
1754
+ auto it_best = states.end();
1755
+
1756
+ // find the most similar cached prompt, that would also preserve the most context
1757
+ for (auto it = states.begin(); it != states.end(); ++it) {
1758
+ const int lcp_cur = it->prompt.tokens.get_common_prefix(tokens_new);
1759
+
1760
+ const float f_keep_cur = float(lcp_cur) / it->prompt.tokens.size();
1761
+ const float f_sim_cur = float(lcp_cur) / tokens_new.size();
1762
+
1763
+ SRV_TRC(" - prompt with length %7zu, lcp = %7d, f_keep = %.3f, f_sim = %.3f\n", it->prompt.tokens.size(), lcp_cur, f_keep_cur, f_sim_cur);
1764
+
1765
+ // don't trash large prompts
1766
+ if (f_keep_cur < 0.25f) {
1767
+ continue;
1768
+ }
1769
+
1770
+ if (f_keep_best < f_keep_cur && f_sim_best < f_sim_cur) {
1771
+ f_keep_best = f_keep_cur;
1772
+ f_sim_best = f_sim_cur;
1773
+
1774
+ it_best = it;
1775
+ }
1776
+ }
1777
+
1778
+ if (it_best != states.end()) {
1779
+ SRV_TRC(" - found better prompt with f_keep = %.3f, f_sim = %.3f\n", f_keep_best, f_sim_best);
1780
+
1781
+ {
1782
+ auto & data = it_best->data.main;
1783
+
1784
+ const size_t size = data.size();
1785
+ const size_t n = llama_state_seq_set_data_ext(ctx_tgt, data.data(), size, id_slot, 0);
1786
+ if (n != size) {
1787
+ SRV_ERR("failed to restore state with size %zu\n", size);
1788
+
1789
+ return false;
1790
+ }
1791
+
1792
+ data.clear();
1793
+ data.shrink_to_fit();
1794
+ }
1795
+
1796
+ {
1797
+ auto & data = it_best->data.drft;
1798
+
1799
+ if (!data.empty()) {
1800
+ GGML_ASSERT(ctx_dft);
1801
+
1802
+ const size_t size = data.size();
1803
+ const size_t n = llama_state_seq_set_data_ext(ctx_dft, data.data(), size, id_slot, 0);
1804
+ if (n != size) {
1805
+ SRV_WRN("failed to restore state with size %zu\n", size);
1806
+
1807
+ return false;
1808
+ }
1809
+
1810
+ data.clear();
1811
+ data.shrink_to_fit();
1812
+ }
1813
+ }
1814
+
1815
+ prompt = std::move(it_best->prompt);
1816
+
1817
+ states.erase(it_best);
1818
+ }
1819
+
1820
+ return true;
1821
+ }
1822
+
1823
+ void server_prompt_cache::update() {
1824
+ if (limit_size > 0) {
1825
+ while (!states.empty() && size() > limit_size) {
1826
+ SRV_WRN(" - cache size limit reached, removing oldest entry (size = %.3f MiB)\n", states.front().size() / (1024.0 * 1024.0));
1827
+
1828
+ states.pop_front();
1829
+ }
1830
+ }
1831
+
1832
+ // average size per token
1833
+ const float size_per_token = std::max<float>(1.0f, float(size()) / (std::max<size_t>(1, n_tokens())));
1834
+
1835
+ // dynamically increase the token limit if it can fit in the memory limit
1836
+ const size_t limit_tokens_cur = limit_size > 0 ? std::max<size_t>(limit_tokens, limit_size/size_per_token) : limit_tokens;
1837
+
1838
+ if (limit_tokens > 0) {
1839
+ while (!states.empty() && n_tokens() > limit_tokens_cur) {
1840
+ SRV_WRN(" - cache token limit (%zu, est: %zu) reached, removing oldest entry (size = %.3f MiB)\n",
1841
+ limit_tokens, limit_tokens_cur, states.front().size() / (1024.0 * 1024.0));
1842
+
1843
+ states.pop_front();
1844
+ }
1845
+ }
1846
+
1847
+ SRV_TRC(" - cache state: %zu prompts, %.3f MiB (limits: %.3f MiB, %zu tokens, %zu est)\n",
1848
+ states.size(), size() / (1024.0 * 1024.0), limit_size / (1024.0 * 1024.0), limit_tokens, limit_tokens_cur);
1849
+
1850
+ for (const auto & state : states) {
1851
+ SRV_TRC(" - prompt %p: %7d tokens, checkpoints: %2zu, %9.3f MiB\n",
1852
+ (const void *)&state, state.prompt.n_tokens(), state.prompt.checkpoints.size(), state.size() / (1024.0 * 1024.0));
1853
+ }
1854
+ }
tools/server/server-task.h ADDED
@@ -0,0 +1,670 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include "common.h"
4
+ #include "llama.h"
5
+
6
+ #include <string>
7
+ #include <unordered_set>
8
+ #include <list>
9
+ #include <map>
10
+
11
+ // TODO: prevent including the whole server-common.h as we only use server_tokens
12
+ #include "server-common.h"
13
+
14
+ using json = nlohmann::ordered_json;
15
+
16
+ enum server_task_type {
17
+ SERVER_TASK_TYPE_COMPLETION,
18
+ SERVER_TASK_TYPE_EMBEDDING,
19
+ SERVER_TASK_TYPE_RERANK,
20
+ SERVER_TASK_TYPE_INFILL,
21
+ SERVER_TASK_TYPE_CANCEL,
22
+ SERVER_TASK_TYPE_CONTROL,
23
+ SERVER_TASK_TYPE_NEXT_RESPONSE,
24
+ SERVER_TASK_TYPE_METRICS,
25
+ SERVER_TASK_TYPE_SLOT_SAVE,
26
+ SERVER_TASK_TYPE_SLOT_RESTORE,
27
+ SERVER_TASK_TYPE_SLOT_ERASE,
28
+ SERVER_TASK_TYPE_GET_LORA,
29
+ SERVER_TASK_TYPE_SET_LORA,
30
+ };
31
+
32
+ // TODO: change this to more generic "response_format" to replace the "format_response_*" in server-common
33
+ enum task_response_type {
34
+ TASK_RESPONSE_TYPE_NONE, // llama.cpp native format
35
+ TASK_RESPONSE_TYPE_OAI_CHAT,
36
+ TASK_RESPONSE_TYPE_OAI_CMPL,
37
+ TASK_RESPONSE_TYPE_OAI_RESP,
38
+ TASK_RESPONSE_TYPE_OAI_ASR, // transcriptions API
39
+ TASK_RESPONSE_TYPE_OAI_EMBD,
40
+ TASK_RESPONSE_TYPE_ANTHROPIC,
41
+ };
42
+
43
+ enum stop_type {
44
+ STOP_TYPE_NONE,
45
+ STOP_TYPE_EOS,
46
+ STOP_TYPE_WORD,
47
+ STOP_TYPE_LIMIT,
48
+ };
49
+
50
+ struct task_params {
51
+ bool stream = false;
52
+ bool include_usage = false;
53
+ bool cache_prompt = true; // remember the prompt to avoid reprocessing all prompt
54
+ bool return_tokens = false;
55
+ bool return_progress = false;
56
+
57
+ int32_t sse_ping_interval = 30; // seconds between SSE comment pings while the stream stays silent, -1 disables
58
+
59
+ int32_t n_keep = 0; // number of tokens to keep from initial prompt
60
+ int32_t n_discard = 0; // number of tokens after n_keep that may be discarded when shifting context, 0 defaults to half
61
+ int32_t n_predict = -1; // new tokens to predict
62
+ int32_t n_indent = 0; // minimum line indentation for the generated text in number of whitespace characters
63
+ int32_t n_cmpl = 1; // number of completions to generate from this prompt
64
+
65
+ int32_t n_cache_reuse = 0; // min chunk size to attempt reusing from the cache via KV shifting (0 = disabled)
66
+
67
+ int64_t t_max_prompt_ms = -1; // TODO: implement
68
+ int64_t t_max_predict_ms = -1; // if positive, limit the generation phase to this time limit
69
+
70
+ std::map<int, float> lora; // mapping adapter ID -> scale
71
+
72
+ std::vector<std::string> antiprompt;
73
+ std::vector<std::string> response_fields;
74
+
75
+ bool timings_per_token = false;
76
+ bool post_sampling_probs = false;
77
+
78
+ struct common_params_sampling sampling;
79
+ struct common_params_speculative speculative;
80
+
81
+ // response formatting
82
+ bool verbose = false;
83
+ task_response_type res_type = TASK_RESPONSE_TYPE_NONE;
84
+ std::string oaicompat_model;
85
+ std::string oaicompat_cmpl_id;
86
+
87
+ // realtime control (SERVER_TASK_TYPE_CONTROL)
88
+ std::string control_action;
89
+ std::string control_cmpl_id;
90
+
91
+ // per-request parameters for chat parsing
92
+ common_chat_parser_params chat_parser_params;
93
+
94
+ // message spans for checkpointing
95
+ common_chat_msg_spans message_spans;
96
+
97
+ // Embeddings
98
+ int32_t embd_normalize = 2; // (-1=none, 0=max absolute int16, 1=taxicab, 2=Euclidean/L2, >2=p-norm)
99
+
100
+ json format_logit_bias(const std::vector<llama_logit_bias> & logit_bias) const;
101
+ json to_json(bool only_metrics = false) const;
102
+ };
103
+
104
+ // struct for tracking the state of a task (e.g., for streaming)
105
+ struct task_result_state {
106
+ // tracking diffs for partial tool calls
107
+ std::vector<common_chat_msg_diff> diffs;
108
+ common_chat_parser_params chat_parser_params;
109
+ common_chat_msg chat_msg;
110
+ std::string generated_text; // append new chunks of generated text here
111
+ std::vector<std::string> generated_tool_call_ids;
112
+ std::unordered_set<size_t> sent_tool_call_names;
113
+
114
+ // for OpenAI Responses and Anthropic streaming API:
115
+ // track output item / content block state across chunks
116
+ bool thinking_block_started = false;
117
+ bool text_block_started = false;
118
+
119
+ // for OpenAI Responses streaming API
120
+ bool oai_resp_created = false;
121
+ const std::string oai_resp_id;
122
+ const std::string oai_resp_reasoning_id;
123
+ const std::string oai_resp_message_id;
124
+ std::string oai_resp_fc_id; // function call ID for current args delta
125
+
126
+ task_result_state(const common_chat_parser_params & chat_parser_params);
127
+
128
+ // parse partial tool calls and update the internal state
129
+ common_chat_msg update_chat_msg(
130
+ const std::string & text_added,
131
+ bool is_partial,
132
+ std::vector<common_chat_msg_diff> & diffs,
133
+ bool filter_tool_calls = false);
134
+ };
135
+
136
+ struct server_task {
137
+ int id = -1; // to be filled by server_queue
138
+
139
+ // TODO @ngxson : remove this field and implement a mapping task_id -> idx in the response_reader
140
+ size_t index = 0; // used when there are multiple prompts (batch request)
141
+
142
+ // used by SERVER_TASK_TYPE_CANCEL
143
+ int id_target = -1;
144
+ int id_slot = -1;
145
+
146
+ // used by parallel sampling (multiple completions from same prompt)
147
+ int id_parent = -1;
148
+ // temporary store of child tasks for scheduling
149
+ // note: accessing to elements is invalid after the task is moved to server_slot
150
+ std::vector<server_task> child_tasks;
151
+
152
+ // used by SERVER_TASK_TYPE_INFERENCE
153
+ task_params params;
154
+ server_tokens tokens;
155
+
156
+ // only used by CLI, this allow tokenizing CLI inputs on server side
157
+ // we need this because mtmd_context and vocab are not accessible outside of server_context
158
+ bool cli = false;
159
+ std::string cli_prompt;
160
+ std::vector<raw_buffer> cli_files;
161
+
162
+ server_task_type type;
163
+
164
+ // used by SERVER_TASK_TYPE_SLOT_SAVE, SERVER_TASK_TYPE_SLOT_RESTORE, SERVER_TASK_TYPE_SLOT_ERASE
165
+ struct slot_action {
166
+ int id_slot;
167
+ std::string filename;
168
+ std::string filepath;
169
+ };
170
+ slot_action slot_action;
171
+
172
+ // used by SERVER_TASK_TYPE_METRICS
173
+ bool metrics_reset_bucket = false;
174
+
175
+ // used by SERVER_TASK_TYPE_SET_LORA
176
+ std::map<int, float> set_lora; // mapping adapter ID -> scale
177
+
178
+ server_task() = default;
179
+
180
+ server_task(server_task_type type) : type(type) {}
181
+
182
+ int32_t n_tokens() const {
183
+ return tokens.size();
184
+ }
185
+
186
+ bool need_embd() const {
187
+ switch (type) {
188
+ case SERVER_TASK_TYPE_EMBEDDING:
189
+ case SERVER_TASK_TYPE_RERANK:
190
+ return true;
191
+ default:
192
+ return false;
193
+ }
194
+ }
195
+
196
+ bool need_logits() const {
197
+ switch (type) {
198
+ case SERVER_TASK_TYPE_COMPLETION:
199
+ case SERVER_TASK_TYPE_INFILL:
200
+ return true;
201
+ default:
202
+ return false;
203
+ }
204
+ }
205
+
206
+ bool need_sampling() const {
207
+ switch (type) {
208
+ case SERVER_TASK_TYPE_COMPLETION:
209
+ case SERVER_TASK_TYPE_INFILL:
210
+ return true;
211
+ default:
212
+ return false;
213
+ }
214
+ }
215
+
216
+ // utility function
217
+ static std::unordered_set<int> get_list_id(const std::vector<server_task> & tasks) {
218
+ std::unordered_set<int> ids(tasks.size());
219
+ for (size_t i = 0; i < tasks.size(); i++) {
220
+ ids.insert(tasks[i].id);
221
+ for (auto & child : tasks[i].child_tasks) {
222
+ ids.insert(child.id);
223
+ }
224
+ }
225
+ return ids;
226
+ }
227
+
228
+ void add_child(int id_parent, int id_child) {
229
+ server_task copy;
230
+
231
+ copy.id = id_child;
232
+ copy.id_parent = id_parent;
233
+ copy.params = params;
234
+ copy.type = type;
235
+ copy.tokens = tokens.clone();
236
+ copy.id_slot = -1; // child tasks cannot specify slot
237
+
238
+ // use different sampling seed for each child
239
+ // note: https://github.com/ggml-org/llama.cpp/pull/18700#discussion_r2675115723
240
+ if (copy.params.sampling.seed != LLAMA_DEFAULT_SEED) {
241
+ copy.params.sampling.seed += (uint32_t)child_tasks.size() + 1;
242
+ }
243
+
244
+ child_tasks.push_back(std::move(copy));
245
+ }
246
+
247
+ // the task will be moved into queue, then onto slots
248
+ // however, the state must be kept by caller (e.g., HTTP thread)
249
+ task_result_state create_state() const {
250
+ return task_result_state(params.chat_parser_params);
251
+ }
252
+
253
+ bool is_parent() const {
254
+ return child_tasks.size() > 0;
255
+ }
256
+
257
+ bool is_child() const {
258
+ return id_parent != -1;
259
+ }
260
+ };
261
+
262
+ struct result_timings {
263
+ int32_t cache_n = -1;
264
+
265
+ int32_t prompt_n = -1;
266
+ double prompt_ms = 0.0;
267
+ double prompt_per_token_ms = 0.0;
268
+ double prompt_per_second = 0.0;
269
+
270
+ int32_t predicted_n = -1;
271
+ double predicted_ms = 0.0;
272
+ double predicted_per_token_ms = 0.0;
273
+ double predicted_per_second = 0.0;
274
+
275
+ // Optional speculative metrics - only included when > 0
276
+ int32_t draft_n = 0;
277
+ int32_t draft_n_accepted = 0;
278
+
279
+ json to_json() const;
280
+ };
281
+
282
+ struct result_prompt_progress {
283
+ int32_t total = 0;
284
+ int32_t cache = 0;
285
+ int32_t processed = 0;
286
+ int64_t time_ms = 0;
287
+
288
+ json to_json() const;
289
+ };
290
+
291
+ struct server_task_result {
292
+ int id = -1;
293
+ int id_slot = -1;
294
+
295
+ // TODO @ngxson : remove this field and implement a mapping task_id -> idx in the response_reader
296
+ size_t index = 0; // to be used for batched tasks
297
+
298
+ virtual bool is_error() {
299
+ // only used by server_task_result_error
300
+ return false;
301
+ }
302
+ virtual bool is_stop() {
303
+ // only used by server_task_result_cmpl_*
304
+ return true;
305
+ }
306
+ virtual void update(task_result_state &) {
307
+ // only used by server_task_result_cmpl_*
308
+ }
309
+ virtual json to_json() = 0;
310
+ virtual ~server_task_result() = default;
311
+ virtual server_task_result * clone() const {
312
+ GGML_ABORT("not implemented for this task type");
313
+ }
314
+ };
315
+
316
+ // using shared_ptr for polymorphism of server_task_result
317
+ using server_task_result_ptr = std::unique_ptr<server_task_result>;
318
+
319
+ struct completion_token_output {
320
+ llama_token tok;
321
+ float prob;
322
+ std::string text_to_send;
323
+ struct prob_info {
324
+ llama_token tok;
325
+ std::string txt;
326
+ float prob;
327
+ };
328
+ std::vector<prob_info> probs;
329
+
330
+ json to_json(bool post_sampling_probs) const;
331
+
332
+ static json probs_vector_to_json(const std::vector<completion_token_output> & probs, bool post_sampling_probs);
333
+
334
+ static float logarithm(float x);
335
+
336
+ static std::vector<unsigned char> str_to_bytes(const std::string & str);
337
+
338
+ };
339
+
340
+ struct server_task_result_cmpl_final : server_task_result {
341
+ std::string content;
342
+ llama_tokens tokens;
343
+
344
+ bool stream;
345
+ bool include_usage;
346
+ result_timings timings;
347
+ std::string prompt;
348
+
349
+ bool truncated;
350
+ int32_t n_decoded;
351
+ int32_t n_prompt_tokens;
352
+ int32_t n_prompt_tokens_cache;
353
+ int32_t n_tokens_cached;
354
+ bool has_new_line;
355
+ std::string stopping_word;
356
+ stop_type stop = STOP_TYPE_NONE;
357
+
358
+ bool post_sampling_probs;
359
+ std::vector<completion_token_output> probs_output;
360
+ std::vector<std::string> response_fields;
361
+
362
+ task_params generation_params;
363
+
364
+ // response formatting
365
+ bool verbose = false;
366
+ task_response_type res_type = TASK_RESPONSE_TYPE_NONE;
367
+ std::string oaicompat_model;
368
+ std::string oaicompat_cmpl_id;
369
+ common_chat_msg oaicompat_msg; // to be populated by update()
370
+
371
+ std::vector<common_chat_msg_diff> oaicompat_msg_diffs; // to be populated by update()
372
+ bool is_updated = false;
373
+
374
+ // for OpenAI Responses API
375
+ std::string oai_resp_id;
376
+ std::string oai_resp_reasoning_id;
377
+ std::string oai_resp_message_id;
378
+
379
+ virtual bool is_stop() override {
380
+ return true; // in stream mode, final responses are considered stop
381
+ }
382
+
383
+ virtual json to_json() override;
384
+
385
+ virtual void update(task_result_state & state) override {
386
+ is_updated = true;
387
+ oaicompat_msg = state.update_chat_msg(content, false, oaicompat_msg_diffs);
388
+
389
+ oai_resp_id = state.oai_resp_id;
390
+ oai_resp_reasoning_id = state.oai_resp_reasoning_id;
391
+ oai_resp_message_id = state.oai_resp_message_id;
392
+ }
393
+
394
+ json to_json_non_oaicompat();
395
+
396
+ json usage_json_oaicompat();
397
+
398
+ json to_json_oaicompat();
399
+
400
+ json to_json_oaicompat_chat();
401
+
402
+ json to_json_oaicompat_chat_stream();
403
+
404
+ json to_json_oaicompat_resp();
405
+
406
+ json to_json_oaicompat_resp_stream();
407
+
408
+ json to_json_oaicompat_asr();
409
+
410
+ json to_json_anthropic();
411
+
412
+ json to_json_anthropic_stream();
413
+ };
414
+
415
+ struct server_task_result_cmpl_partial : server_task_result {
416
+ std::string content;
417
+ llama_tokens tokens;
418
+
419
+ int32_t n_decoded;
420
+ int32_t n_prompt_tokens;
421
+ int32_t n_prompt_tokens_cache;
422
+
423
+ bool post_sampling_probs;
424
+ bool is_progress = false;
425
+ bool is_begin = false; // whether to send 200 status to HTTP client (begin of SSE stream)
426
+ // ref: https://github.com/ggml-org/llama.cpp/pull/23884
427
+ completion_token_output prob_output;
428
+ result_timings timings;
429
+ result_prompt_progress progress;
430
+
431
+ // response formatting
432
+ bool verbose = false;
433
+ task_response_type res_type = TASK_RESPONSE_TYPE_NONE;
434
+ std::string oaicompat_model;
435
+ std::string oaicompat_cmpl_id;
436
+ std::vector<common_chat_msg_diff> oaicompat_msg_diffs; // to be populated by update()
437
+ bool is_updated = false;
438
+
439
+ // Streaming state copied from task_result_state for this chunk
440
+ bool thinking_block_started = false;
441
+ bool text_block_started = false;
442
+
443
+ // for OpenAI Responses API
444
+ bool oai_resp_created = false;
445
+ std::string oai_resp_id;
446
+ std::string oai_resp_reasoning_id;
447
+ std::string oai_resp_message_id;
448
+ std::string oai_resp_fc_id;
449
+
450
+ // for Anthropic API: track if any reasoning content has been generated
451
+ bool anthropic_has_reasoning = false;
452
+
453
+ virtual bool is_stop() override {
454
+ return false; // in stream mode, partial responses are not considered stop
455
+ }
456
+
457
+ virtual void update(task_result_state & state) override;
458
+
459
+ virtual json to_json() override;
460
+
461
+ json to_json_non_oaicompat();
462
+
463
+ json to_json_oaicompat();
464
+
465
+ json to_json_oaicompat_chat();
466
+
467
+ json to_json_oaicompat_resp();
468
+
469
+ json to_json_oaicompat_asr();
470
+
471
+ json to_json_anthropic();
472
+ };
473
+
474
+ struct server_task_result_embd : server_task_result {
475
+ std::vector<std::vector<float>> embedding;
476
+
477
+ int32_t n_tokens;
478
+
479
+ // response formatting
480
+ task_response_type res_type = TASK_RESPONSE_TYPE_NONE;
481
+
482
+ virtual json to_json() override;
483
+
484
+ json to_json_non_oaicompat();
485
+
486
+ json to_json_oaicompat();
487
+ };
488
+
489
+ struct server_task_result_rerank : server_task_result {
490
+ float score = -1e6;
491
+
492
+ int32_t n_tokens;
493
+
494
+ virtual json to_json() override;
495
+ };
496
+
497
+ struct server_task_result_error : server_task_result {
498
+ error_type err_type = ERROR_TYPE_SERVER;
499
+ std::string err_msg;
500
+
501
+ // for ERROR_TYPE_EXCEED_CONTEXT_SIZE
502
+ int32_t n_prompt_tokens = 0;
503
+ int32_t n_ctx = 0;
504
+
505
+ virtual bool is_error() override {
506
+ return true;
507
+ }
508
+
509
+ virtual json to_json() override;
510
+ };
511
+
512
+ struct server_task_result_metrics : server_task_result {
513
+ int n_idle_slots;
514
+ int n_processing_slots;
515
+ int n_tasks_deferred;
516
+ int64_t t_start;
517
+
518
+ // TODO: somehow reuse server_metrics in the future, instead of duplicating the fields
519
+ uint64_t n_prompt_tokens_processed_total = 0;
520
+ uint64_t t_prompt_processing_total = 0;
521
+ uint64_t n_tokens_predicted_total = 0;
522
+ uint64_t t_tokens_generation_total = 0;
523
+
524
+ uint64_t n_tokens_max = 0;
525
+
526
+ uint64_t n_prompt_tokens_processed = 0;
527
+ uint64_t t_prompt_processing = 0;
528
+
529
+ uint64_t n_tokens_predicted = 0;
530
+ uint64_t t_tokens_generation = 0;
531
+
532
+ uint64_t n_decode_total = 0;
533
+ uint64_t n_busy_slots_total = 0;
534
+
535
+ uint64_t n_draft_tokens_total = 0;
536
+ uint64_t n_draft_accepted_total = 0;
537
+ uint64_t n_draft_verif_steps_total = 0;
538
+ std::vector<uint64_t> n_accepted_per_pos_total;
539
+
540
+ // while we can also use std::vector<server_slot> this requires copying the slot object which can be quite messy
541
+ // therefore, we use json to temporarily store the slot.to_json() result
542
+ json slots_data = json::array();
543
+
544
+ virtual json to_json() override;
545
+ };
546
+
547
+ struct server_task_result_slot_save_load : server_task_result {
548
+ std::string filename;
549
+ bool is_save; // true = save, false = load
550
+
551
+ size_t n_tokens;
552
+ size_t n_bytes;
553
+ double t_ms;
554
+
555
+ virtual json to_json() override;
556
+ };
557
+
558
+ struct server_task_result_slot_erase : server_task_result {
559
+ size_t n_erased;
560
+
561
+ virtual json to_json() override;
562
+ };
563
+
564
+ struct server_task_result_control : server_task_result {
565
+ bool success = false;
566
+ std::string message; // optional detail when success is false
567
+
568
+ virtual json to_json() override {
569
+ json out = json { { "success", success } };
570
+ if (!message.empty()) {
571
+ out["message"] = message;
572
+ }
573
+ return out;
574
+ }
575
+ };
576
+
577
+ struct server_task_result_get_lora : server_task_result {
578
+ struct lora {
579
+ common_adapter_lora_info info;
580
+ std::string alora_invocation_string;
581
+ llama_tokens alora_invocation_tokens;
582
+ };
583
+ std::vector<lora> loras;
584
+
585
+ virtual json to_json() override;
586
+ };
587
+
588
+ struct server_task_result_apply_lora : server_task_result {
589
+ virtual json to_json() override;
590
+ };
591
+
592
+ struct server_prompt {
593
+ server_tokens tokens;
594
+
595
+ std::list<common_prompt_checkpoint> checkpoints;
596
+
597
+ void clear() {
598
+ tokens.clear();
599
+ checkpoints.clear();
600
+ }
601
+
602
+ int n_tokens() const {
603
+ return tokens.size();
604
+ }
605
+
606
+ server_prompt clone() const {
607
+ return server_prompt {
608
+ tokens.clone(),
609
+ checkpoints,
610
+ };
611
+ }
612
+ };
613
+
614
+ struct server_prompt_data {
615
+ std::vector<uint8_t> main;
616
+ std::vector<uint8_t> drft;
617
+
618
+ size_t size() const {
619
+ return main.size() + drft.size();
620
+ }
621
+ };
622
+
623
+ struct server_prompt_cache_state {
624
+ server_prompt prompt;
625
+ server_prompt_data data;
626
+
627
+ size_t size() const {
628
+ size_t res = data.size();
629
+
630
+ for (const auto & ckpt : prompt.checkpoints) {
631
+ res += ckpt.size();
632
+ }
633
+
634
+ return res;
635
+ }
636
+ };
637
+
638
+ struct server_prompt_cache {
639
+ server_prompt_cache(int32_t limit_size_mib, size_t limit_tokens) {
640
+ this->limit_size = 1024ull*1024ull*(limit_size_mib < 0 ? 0 : limit_size_mib);
641
+ this->limit_tokens = limit_tokens;
642
+ }
643
+
644
+ std::list<server_prompt_cache_state> states;
645
+
646
+ // in bytes, 0 = no limit
647
+ size_t limit_size = 0;
648
+
649
+ // in tokens, 0 = no limit
650
+ size_t limit_tokens = 0;
651
+
652
+ size_t size() const;
653
+
654
+ size_t n_tokens() const;
655
+
656
+ server_prompt_cache_state * alloc(const server_prompt & prompt, size_t state_size_main, size_t state_size_drft);
657
+
658
+ bool load(server_prompt & prompt, const server_tokens & tokens_new, llama_context * ctx_tgt, llama_context * ctx_dft, int32_t id_slot);
659
+
660
+ void update();
661
+ };
662
+
663
+ // used exclusively by router mode
664
+ struct server_task_result_router : server_task_result {
665
+ json data;
666
+ virtual json to_json() override { return data; }
667
+ virtual server_task_result * clone() const override {
668
+ return new server_task_result_router(*this);
669
+ }
670
+ };
tools/server/server-tools.cpp ADDED
@@ -0,0 +1,2195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "server-tools.h"
2
+
3
+ #include "subproc.h"
4
+
5
+ #include <filesystem>
6
+ #include <fstream>
7
+ #include <regex>
8
+ #include <thread>
9
+ #include <chrono>
10
+ #include <ctime>
11
+ #include <atomic>
12
+ #include <cstring>
13
+ #include <cctype>
14
+ #include <cstdint>
15
+ #include <cstdlib>
16
+ #include <algorithm>
17
+ #include <iterator>
18
+ #include <unordered_set>
19
+ #include <tuple>
20
+ #include <functional>
21
+ #include <memory>
22
+ #include <mutex>
23
+
24
+ #if defined(_WIN32)
25
+ # ifndef NOMINMAX
26
+ # define NOMINMAX
27
+ # endif
28
+ # include <windows.h>
29
+ # include <fcntl.h>
30
+ # include <io.h>
31
+ #else
32
+ # include <cerrno>
33
+ # include <unistd.h>
34
+ #endif
35
+
36
+ namespace fs = std::filesystem;
37
+
38
+ //
39
+ // internal helpers
40
+ //
41
+
42
+ // a child process writes in the OEM code page, so accented output would reach
43
+ // the JSON layer as invalid bytes. run() spawns without a console, so the
44
+ // console code page never applies
45
+ static std::string console_output_to_utf8(const std::string & text) {
46
+ #if defined(_WIN32)
47
+ // a chunk can end mid sequence, so the incomplete tail is dropped first
48
+ if (text.empty() || is_valid_utf8(text.substr(0, validate_utf8(text)))) {
49
+ // never decode twice a child that already emits UTF-8
50
+ return text;
51
+ }
52
+
53
+ const UINT cp = GetOEMCP();
54
+
55
+ // fail rather than emit replacement characters when the code page is wrong
56
+ const int wide_len = MultiByteToWideChar(cp, MB_ERR_INVALID_CHARS, text.data(), (int) text.size(), nullptr, 0);
57
+ if (wide_len <= 0) {
58
+ return text;
59
+ }
60
+ std::wstring wide(wide_len, L'\0');
61
+ MultiByteToWideChar(cp, MB_ERR_INVALID_CHARS, text.data(), (int) text.size(), wide.data(), wide_len);
62
+
63
+ const int utf8_len = WideCharToMultiByte(CP_UTF8, 0, wide.data(), wide_len, nullptr, 0, nullptr, nullptr);
64
+ if (utf8_len <= 0) {
65
+ return text;
66
+ }
67
+ std::string utf8(utf8_len, '\0');
68
+ WideCharToMultiByte(CP_UTF8, 0, wide.data(), wide_len, utf8.data(), utf8_len, nullptr, nullptr);
69
+ return utf8;
70
+ #else
71
+ return text;
72
+ #endif
73
+ }
74
+
75
+ json server_tool::to_json() const {
76
+ return {
77
+ {"display_name", display_name},
78
+ {"tool", name},
79
+ {"type", type()},
80
+ {"permissions", json{
81
+ {"write", permission_write}
82
+ }},
83
+ {"uses_cwd", uses_cwd},
84
+ {"definition", get_definition()},
85
+ };
86
+ }
87
+
88
+ static constexpr size_t SERVER_TOOL_GIT_LS_FILES_MAX_OUTPUT = 8 * 1024 * 1024; // 8 MB
89
+ // budget for one listing call, shared by the git and walker paths
90
+ static constexpr int SERVER_TOOL_LIST_ENTRIES_TIMEOUT = 15; // seconds
91
+
92
+ // entry kinds a directory listing may return
93
+ enum class list_kind {
94
+ files, // regular files only
95
+ dirs, // directories only
96
+ all, // both
97
+ };
98
+
99
+ // a narrow path uses the active code page on Windows, so every crossing between
100
+ // a std::string (always UTF-8 here) and fs::path is converted explicitly
101
+ static fs::path path_from_utf8(const std::string & s) {
102
+ return fs::u8path(s);
103
+ }
104
+
105
+ // '/' separators on every platform: Windows accepts them, the web UI needs them
106
+ static std::string path_to_utf8(const fs::path & p) {
107
+ const auto s = p.generic_u8string();
108
+ return std::string(s.begin(), s.end());
109
+ }
110
+
111
+ // home directory, read once at first use (getenv is not thread safe against setenv)
112
+ static const std::string & home_dir() {
113
+ static const std::string home = [] {
114
+ #ifdef _WIN32
115
+ // the narrow getenv would return the profile path in the active code page
116
+ const wchar_t * w = _wgetenv(L"HOME");
117
+ if (w == nullptr) w = _wgetenv(L"USERPROFILE");
118
+ return w ? path_to_utf8(fs::path(w)) : std::string();
119
+ #else
120
+ const char * h = getenv("HOME");
121
+ return h ? std::string(h) : std::string();
122
+ #endif
123
+ }();
124
+ return home;
125
+ }
126
+
127
+ static std::string expand_home(const std::string & path) {
128
+ if (path.empty() || path[0] != '~') return path;
129
+ if (path.size() > 1 && path[1] != '/' && path[1] != '\\') return path;
130
+ const std::string & home = home_dir();
131
+ if (home.empty()) return path;
132
+ return home + path.substr(1);
133
+ }
134
+
135
+ // depth of a '/'-separated relative path: "a/b/c" is 3
136
+ static int entry_depth(const std::string & rel) {
137
+ return 1 + (int) std::count(rel.begin(), rel.end(), '/');
138
+ }
139
+
140
+ // directories that a listing reports but never descends into: they can be enormous
141
+ // lowercase only, the local walker case-folds a name before the lookup
142
+ static const char * const SERVER_TOOL_JUNK_DIR_NAMES[] = {
143
+ ".git", ".svn", ".hg", "node_modules", "__pycache__",
144
+ ".venv", "venv", "dist", "build", "target", ".cache", ".idea", ".vscode",
145
+ };
146
+
147
+ class tools_io {
148
+ public:
149
+ struct exec_result {
150
+ std::string output;
151
+ int exit_code = -1;
152
+ bool timed_out = false;
153
+ };
154
+
155
+ virtual ~tools_io() = default;
156
+
157
+ virtual bool is_directory(const std::string & path) const = 0;
158
+ virtual bool is_regular_file(const std::string & path) const = 0;
159
+ virtual bool file_size(const std::string & path, uintmax_t & out_size) const = 0;
160
+ virtual bool read_file(const std::string & path, std::string & out) const = 0;
161
+ virtual bool write_file(const std::string & path, const std::string & content) const = 0;
162
+ // resolve `path` against the IO's working directory; absolute paths are returned unchanged
163
+ virtual std::string resolve(const std::string & path) const = 0;
164
+ struct list_entry {
165
+ std::string rel; // '/'-separated, relative to `base`
166
+ bool is_dir = false;
167
+ };
168
+ struct list_result {
169
+ std::vector<list_entry> entries;
170
+ std::string err; // set when `base` is not a directory
171
+ bool truncated = false; // set when the walk could not see everything
172
+ };
173
+ // entries relative to `base`, which must already be resolved (absolute)
174
+ // max_depth == 0 means unlimited, 1 means direct children of `base` only
175
+ virtual list_result list_entries(const std::string & base, int max_depth, list_kind kind) const = 0;
176
+ // on_chunk, if set, is called with each chunk of output as it is read (before truncation cuts in);
177
+ // returning false terminates the process early (e.g. the client disconnected)
178
+ virtual exec_result run(
179
+ const std::vector<std::string> & args,
180
+ size_t max_output,
181
+ int timeout_secs,
182
+ const std::function<bool(const std::string &)> & on_chunk = nullptr) const = 0;
183
+ };
184
+
185
+ // shared subprocess execution helper, used by both the local and the isolate-backed tools_io implementations.
186
+ // combine_stderr=false when the raw stdout bytes must not be tainted by stderr, e.g. reading file contents.
187
+ static tools_io::exec_result run_subprocess(
188
+ const std::vector<std::string> & args,
189
+ size_t max_output,
190
+ int timeout_secs,
191
+ const std::function<bool(const std::string &)> & on_chunk,
192
+ bool combine_stderr,
193
+ const std::string & cwd = "",
194
+ const std::string * stdin_data = nullptr) {
195
+ tools_io::exec_result res;
196
+
197
+ common_subproc proc;
198
+
199
+ int options = subprocess_option_no_window
200
+ | subprocess_option_inherit_environment
201
+ | subprocess_option_search_user_path;
202
+ if (combine_stderr) {
203
+ options |= subprocess_option_combined_stdout_stderr;
204
+ }
205
+
206
+ if (!proc.create(args, options, {}, cwd.empty() ? nullptr : cwd.c_str())) {
207
+ res.output = "failed to spawn process";
208
+ return res;
209
+ }
210
+
211
+ std::atomic<bool> done{false};
212
+ std::atomic<bool> timed_out{false};
213
+
214
+ std::thread timeout_thread([&]() {
215
+ auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(timeout_secs);
216
+ while (!done.load()) {
217
+ if (std::chrono::steady_clock::now() >= deadline) {
218
+ timed_out.store(true);
219
+ proc.terminate();
220
+ return;
221
+ }
222
+ std::this_thread::sleep_for(std::chrono::milliseconds(100));
223
+ }
224
+ });
225
+
226
+ // write stdin before reading stdout, the child drains stdin as it goes
227
+ // always close stdin, a transport client waits forever if its stdin pipe stays open
228
+ if (FILE * in = proc.stdin_file()) {
229
+ if (stdin_data != nullptr && !stdin_data->empty()) {
230
+ #if defined(_WIN32)
231
+ // pipe fds default to CRT text mode: binary keeps the bytes untranslated
232
+ _setmode(_fileno(in), _O_BINARY);
233
+ #endif
234
+ // a short write is not an error by itself, the exit code below decides
235
+ fwrite(stdin_data->data(), 1, stdin_data->size(), in);
236
+ }
237
+ fflush(in);
238
+ }
239
+ proc.close_stdin();
240
+
241
+ FILE * f = proc.stdout_file();
242
+ std::string output;
243
+ bool truncated = false;
244
+ if (f) {
245
+ #if defined(_WIN32)
246
+ // pipe fds default to CRT text mode: binary keeps the bytes untranslated
247
+ _setmode(_fileno(f), _O_BINARY);
248
+ #endif
249
+ // read raw bytes, not lines: the output can hold NUL and must arrive as soon as it is ready
250
+ // keep draining past the size cap, else the child blocks on a full pipe
251
+ char buf[4096];
252
+ for (;;) {
253
+ #if defined(_WIN32)
254
+ const int n = _read(_fileno(f), buf, (unsigned) sizeof(buf));
255
+ #else
256
+ ssize_t n = read(fileno(f), buf, sizeof(buf));
257
+ while (n < 0 && errno == EINTR) {
258
+ n = read(fileno(f), buf, sizeof(buf));
259
+ }
260
+ #endif
261
+ if (n <= 0) {
262
+ break;
263
+ }
264
+ if (truncated) {
265
+ continue;
266
+ }
267
+ const size_t len = (size_t) n;
268
+ if (output.size() + len <= max_output) {
269
+ output.append(buf, len);
270
+ if (on_chunk && !on_chunk(console_output_to_utf8(std::string(buf, len)))) {
271
+ proc.terminate();
272
+ break;
273
+ }
274
+ } else {
275
+ size_t remaining = max_output - output.size();
276
+ output.append(buf, remaining);
277
+ if (on_chunk && remaining > 0) on_chunk(console_output_to_utf8(std::string(buf, remaining)));
278
+ truncated = true;
279
+ }
280
+ }
281
+ }
282
+
283
+ done.store(true);
284
+ if (timeout_thread.joinable()) {
285
+ timeout_thread.join();
286
+ }
287
+
288
+ res.exit_code = proc.join();
289
+
290
+ res.output = console_output_to_utf8(output);
291
+ res.timed_out = timed_out.load();
292
+ if (truncated) {
293
+ res.output += "\n[output truncated]";
294
+ }
295
+ return res;
296
+ }
297
+
298
+ class tools_io_basic : public tools_io {
299
+ public:
300
+ // cwd, if non-empty, is used to resolve relative paths and as the working directory for run()
301
+ explicit tools_io_basic(std::string cwd = "") : cwd(std::move(cwd)) {}
302
+
303
+ // expands a leading `~`, then resolves `path` against `cwd` (or the server
304
+ // working directory when `cwd` is unset); the result is always absolute
305
+ std::string resolve(const std::string & path) const override {
306
+ const std::string p = expand_home(path);
307
+
308
+ fs::path full = path_from_utf8(p);
309
+ if (!full.is_absolute()) {
310
+ if (cwd.empty()) {
311
+ std::error_code ec;
312
+ const fs::path cur = fs::current_path(ec);
313
+ if (ec) return p;
314
+ full = cur / full;
315
+ } else {
316
+ full = path_from_utf8(cwd) / full;
317
+ }
318
+ }
319
+
320
+ // drop "." and ".." so they never reach git or the client
321
+ full = full.lexically_normal();
322
+ // a trailing ".." normalizes to a path that ends with a separator
323
+ if (!full.has_filename() && full != full.root_path()) {
324
+ full = full.parent_path();
325
+ }
326
+ return path_to_utf8(full);
327
+ }
328
+
329
+ bool is_directory(const std::string & path) const override {
330
+ std::error_code ec;
331
+ return fs::is_directory(path_from_utf8(resolve(path)), ec) && !ec;
332
+ }
333
+
334
+ bool is_regular_file(const std::string & path) const override {
335
+ std::error_code ec;
336
+ return fs::is_regular_file(path_from_utf8(resolve(path)), ec) && !ec;
337
+ }
338
+
339
+ bool file_size(const std::string & path, uintmax_t & out_size) const override {
340
+ std::error_code ec;
341
+ out_size = fs::file_size(path_from_utf8(resolve(path)), ec);
342
+ return !ec;
343
+ }
344
+
345
+ bool read_file(const std::string & path, std::string & out) const override {
346
+ std::ifstream f(path_from_utf8(resolve(path)), std::ios::binary);
347
+ if (!f) return false;
348
+ std::ostringstream ss;
349
+ ss << f.rdbuf();
350
+ out = ss.str();
351
+ return true;
352
+ }
353
+
354
+ bool write_file(const std::string & path, const std::string & content) const override {
355
+ std::error_code ec;
356
+ fs::path fpath = path_from_utf8(resolve(path));
357
+ if (fpath.has_parent_path()) {
358
+ fs::create_directories(fpath.parent_path(), ec);
359
+ if (ec) return false;
360
+ }
361
+ std::ofstream f(fpath, std::ios::binary);
362
+ if (!f) return false;
363
+ f << content;
364
+ return (bool) f;
365
+ }
366
+
367
+ list_result list_entries(const std::string & base, int max_depth, list_kind kind) const override {
368
+ list_result out;
369
+
370
+ std::error_code ec;
371
+ if (!fs::is_directory(base, ec) || ec) {
372
+ out.err = "path does not exist or is not a directory";
373
+ return out;
374
+ }
375
+
376
+ const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(SERVER_TOOL_LIST_ENTRIES_TIMEOUT);
377
+
378
+ // git ls-files cannot list directories; use the walker when they are requested
379
+ if (kind == list_kind::files) {
380
+ auto res = run(
381
+ {"git", "-C", base, "ls-files", "--cached", "--others", "--exclude-standard"},
382
+ SERVER_TOOL_GIT_LS_FILES_MAX_OUTPUT, SERVER_TOOL_LIST_ENTRIES_TIMEOUT);
383
+
384
+ if (res.exit_code == 0 && !res.timed_out) {
385
+ std::istringstream iss(res.output);
386
+ std::string line;
387
+ while (std::getline(iss, line)) {
388
+ if (!line.empty() && line.back() == '\r') line.pop_back();
389
+ if (line.empty()) continue;
390
+ std::replace(line.begin(), line.end(), '\\', '/');
391
+ if (max_depth > 0 && entry_depth(line) > max_depth) continue;
392
+ if (is_regular_file(path_to_utf8(path_from_utf8(base) / path_from_utf8(line)))) {
393
+ out.entries.push_back({line, false});
394
+ }
395
+ }
396
+ return out;
397
+ }
398
+ }
399
+
400
+ out.entries = list_entries_fallback(base, max_depth, kind, deadline, out.truncated);
401
+ return out;
402
+ }
403
+
404
+ exec_result run(
405
+ const std::vector<std::string> & args,
406
+ size_t max_output,
407
+ int timeout_secs,
408
+ const std::function<bool(const std::string &)> & on_chunk = nullptr) const override {
409
+ return run_subprocess(args, max_output, timeout_secs, on_chunk, /*combine_stderr=*/true, cwd);
410
+ }
411
+
412
+ private:
413
+ std::string cwd;
414
+
415
+ // a link can point back to an ancestor and loop forever, so it is never walked
416
+ static bool is_link(const fs::directory_entry & entry) {
417
+ std::error_code ec;
418
+ if (entry.is_symlink(ec) || ec) {
419
+ return true;
420
+ }
421
+ #if defined(_WIN32)
422
+ // a junction looks like a plain directory to std::filesystem, so read the reparse tag
423
+ WIN32_FIND_DATAW data;
424
+ const HANDLE h = FindFirstFileW(entry.path().c_str(), &data);
425
+ if (h == INVALID_HANDLE_VALUE) {
426
+ return false;
427
+ }
428
+ FindClose(h);
429
+ if ((data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) == 0) {
430
+ return false;
431
+ }
432
+ // other reparse points (cloud placeholder, dedup stub) are real directories
433
+ return data.dwReserved0 == IO_REPARSE_TAG_SYMLINK || data.dwReserved0 == IO_REPARSE_TAG_MOUNT_POINT;
434
+ #else
435
+ return false;
436
+ #endif
437
+ }
438
+
439
+ // NTFS is case insensitive, so Build and build are the same directory
440
+ static std::string get_effective_name(const std::string & fname) {
441
+ #if defined(_WIN32)
442
+ std::string lowered = fname;
443
+ std::transform(lowered.begin(), lowered.end(), lowered.begin(),
444
+ [](unsigned char c) { return (char) std::tolower(c); });
445
+ return lowered;
446
+ #else
447
+ return fname;
448
+ #endif
449
+ }
450
+
451
+ static const std::unordered_set<std::string> & junk_dir_names() {
452
+ static const std::unordered_set<std::string> names(
453
+ std::begin(SERVER_TOOL_JUNK_DIR_NAMES), std::end(SERVER_TOOL_JUNK_DIR_NAMES));
454
+ return names;
455
+ }
456
+
457
+ std::vector<list_entry> list_entries_fallback(const std::string & base, int max_depth, list_kind kind,
458
+ std::chrono::steady_clock::time_point deadline, bool & truncated) const {
459
+ std::vector<list_entry> result;
460
+
461
+ std::vector<std::tuple<fs::path, fs::path, int>> stack;
462
+ stack.emplace_back(path_from_utf8(base), fs::path(), 0);
463
+
464
+ while (!stack.empty()) {
465
+ if (std::chrono::steady_clock::now() >= deadline) {
466
+ truncated = true;
467
+ return result;
468
+ }
469
+
470
+ auto [dir, rel_dir, depth] = std::move(stack.back());
471
+ stack.pop_back();
472
+
473
+ std::error_code ec;
474
+ // step the iterator by hand: the throwing increment escapes on a directory that goes away
475
+ fs::directory_iterator it(dir, fs::directory_options::skip_permission_denied, ec);
476
+ // permission errors are skipped above, so this is a subtree the caller never sees
477
+ if (ec) {
478
+ truncated = true;
479
+ continue;
480
+ }
481
+ for (const fs::directory_iterator end; it != end; it.increment(ec)) {
482
+ if (ec) {
483
+ truncated = true;
484
+ break;
485
+ }
486
+ if (std::chrono::steady_clock::now() >= deadline) {
487
+ truncated = true;
488
+ return result;
489
+ }
490
+ const fs::directory_entry & entry = *it;
491
+ const fs::path fname = entry.path().filename();
492
+ std::error_code tec;
493
+ const bool is_dir = entry.is_directory(tec);
494
+ if (tec) continue;
495
+ if (is_dir) {
496
+ if (kind == list_kind::dirs || kind == list_kind::all) {
497
+ result.push_back({path_to_utf8(rel_dir / fname), true});
498
+ }
499
+ // junk directories stay selectable but are never walked: they can be enormous
500
+ if (junk_dir_names().count(get_effective_name(path_to_utf8(fname))) > 0) continue;
501
+ if (!is_link(entry) && (max_depth == 0 || depth + 1 < max_depth)) {
502
+ stack.emplace_back(entry.path(), rel_dir / fname, depth + 1);
503
+ }
504
+ } else if (entry.is_regular_file(tec)) {
505
+ if (kind == list_kind::files || kind == list_kind::all) {
506
+ result.push_back({path_to_utf8(rel_dir / fname), false});
507
+ }
508
+ }
509
+ }
510
+ }
511
+
512
+ return result;
513
+ }
514
+ };
515
+
516
+ // timeout for auxiliary isolate calls (stat/mkdir/ls helpers); exec_shell_command uses its own
517
+ // caller-controlled timeout instead, enforced separately in run()
518
+ static constexpr int SERVER_TOOL_ISOLATE_EXEC_TIMEOUT = 15; // seconds
519
+ static constexpr size_t SERVER_TOOL_ISOLATE_READ_FILE_MAX_SIZE = 64 * 1024 * 1024; // 64 MB
520
+
521
+ // runs every tools_io operation as a command inside an isolate: a container, a remote host, ...
522
+ // the isolate is created, mounted, and torn down externally by the caller
523
+ // it must provide a POSIX environment: sh, cat, wc, mkdir, dirname, find, timeout
524
+ class tools_io_isolate : public tools_io {
525
+ public:
526
+ // cwd, if non-empty, is used to resolve relative paths and as the working directory for run()
527
+ explicit tools_io_isolate(std::string cwd = "") : cwd(std::move(cwd)) {}
528
+
529
+ // resolves `path` against `cwd` if `path` is relative and `cwd` is set; otherwise returns `path` unchanged.
530
+ // isolate paths are always POSIX-style ('/'), regardless of host OS.
531
+ std::string resolve(const std::string & path) const override {
532
+ if (cwd.empty() || (!path.empty() && path[0] == '/')) {
533
+ return path;
534
+ }
535
+ return cwd + "/" + path;
536
+ }
537
+
538
+ bool is_directory(const std::string & path) const override {
539
+ return shell_test("-d", resolve(path));
540
+ }
541
+
542
+ bool is_regular_file(const std::string & path) const override {
543
+ return shell_test("-f", resolve(path));
544
+ }
545
+
546
+ bool file_size(const std::string & path, uintmax_t & out_size) const override {
547
+ auto res = exec({"sh", "-c", "wc -c < \"$1\"", "_", resolve(path)}, 64, true);
548
+ if (res.exit_code != 0 || res.timed_out) return false;
549
+ try {
550
+ size_t pos;
551
+ out_size = (uintmax_t) std::stoull(res.output, &pos);
552
+ } catch (...) {
553
+ return false;
554
+ }
555
+ return true;
556
+ }
557
+
558
+ bool read_file(const std::string & path, std::string & out) const override {
559
+ // combine_stderr=false: stderr must not be spliced into raw file bytes
560
+ auto res = exec({"cat", "--", resolve(path)}, SERVER_TOOL_ISOLATE_READ_FILE_MAX_SIZE, false);
561
+ if (res.exit_code != 0 || res.timed_out) return false;
562
+ out = res.output;
563
+ return true;
564
+ }
565
+
566
+ bool write_file(const std::string & path, const std::string & content) const override {
567
+ // the content travels on stdin: no argv for the far side to re-parse, no temp file on the host
568
+ auto res = run_subprocess(
569
+ build_argv({"sh", "-c", "mkdir -p \"$(dirname \"$1\")\" && cat > \"$1\"", "_", resolve(path)},
570
+ /*needs_stdin=*/true),
571
+ 4096, SERVER_TOOL_ISOLATE_EXEC_TIMEOUT, nullptr, true, "", &content);
572
+ return res.exit_code == 0 && !res.timed_out;
573
+ }
574
+
575
+ list_result list_entries(const std::string & base, int max_depth, list_kind kind) const override {
576
+ list_result out;
577
+
578
+ const std::string abs_base = resolve(base);
579
+ if (!is_directory(base)) {
580
+ out.err = "path does not exist or is not a directory";
581
+ return out;
582
+ }
583
+
584
+ // git ls-files cannot list directories; use the walker when they are requested
585
+ if (kind == list_kind::files) {
586
+ auto res = exec(
587
+ {"sh", "-c", "cd \"$1\" && git ls-files --cached --others --exclude-standard", "_", abs_base},
588
+ SERVER_TOOL_GIT_LS_FILES_MAX_OUTPUT, true);
589
+
590
+ if (res.exit_code == 0 && !res.timed_out) {
591
+ for (const auto & rel : split_lines(res.output, /*strip_dot_slash=*/false)) {
592
+ if (max_depth > 0 && entry_depth(rel) > max_depth) continue;
593
+ out.entries.push_back({rel, false});
594
+ }
595
+ return out;
596
+ }
597
+ }
598
+
599
+ if (kind == list_kind::dirs || kind == list_kind::all) {
600
+ for (auto & rel : find_entries(abs_base, max_depth, /*dirs=*/true, out.truncated)) {
601
+ out.entries.push_back({std::move(rel), true});
602
+ }
603
+ }
604
+ if (kind == list_kind::files || kind == list_kind::all) {
605
+ for (auto & rel : find_entries(abs_base, max_depth, /*dirs=*/false, out.truncated)) {
606
+ out.entries.push_back({std::move(rel), false});
607
+ }
608
+ }
609
+
610
+ return out;
611
+ }
612
+
613
+ // wraps the command with an in-isolate `timeout`, since killing the host-side client
614
+ // does not kill the process tree running inside the isolate
615
+ exec_result run(
616
+ const std::vector<std::string> & args,
617
+ size_t max_output,
618
+ int timeout_secs,
619
+ const std::function<bool(const std::string &)> & on_chunk = nullptr) const override {
620
+ std::vector<std::string> inner = {"timeout", std::to_string(timeout_secs) + "s"};
621
+ inner.insert(inner.end(), args.begin(), args.end());
622
+ // small buffer over timeout_secs so the in-isolate `timeout` has a chance to exit cleanly
623
+ // before the host-side supervisory timeout forcibly kills the client
624
+ return run_subprocess(
625
+ build_argv(with_cwd(inner), /*needs_stdin=*/true),
626
+ max_output, timeout_secs + 5, on_chunk, true);
627
+ }
628
+
629
+ protected:
630
+ // wrap `inner` (a complete POSIX argv) into the host-side argv that runs it in the isolate
631
+ // a transport that re-parses its args in a remote shell (ssh) must join `inner` with shell_quote_join()
632
+ virtual std::vector<std::string> build_argv(const std::vector<std::string> & inner, bool needs_stdin) const = 0;
633
+
634
+ // quote `argv` into a single string that a POSIX shell re-parses into exactly `argv`
635
+ static std::string shell_quote_join(const std::vector<std::string> & argv) {
636
+ std::string out;
637
+ for (const auto & arg : argv) {
638
+ if (!out.empty()) out += ' ';
639
+ out += '\'';
640
+ for (const char c : arg) {
641
+ // a single quote cannot be escaped inside single quotes: close, escape, reopen
642
+ if (c == '\'') out += "'\\''";
643
+ else out += c;
644
+ }
645
+ out += '\'';
646
+ }
647
+ return out;
648
+ }
649
+
650
+ private:
651
+ std::string cwd;
652
+
653
+ // set the working directory in the command itself, no `-w` equivalent exists on every transport
654
+ // auxiliary calls do not need this, they use the absolute paths from resolve()
655
+ std::vector<std::string> with_cwd(const std::vector<std::string> & inner) const {
656
+ if (cwd.empty()) {
657
+ return inner;
658
+ }
659
+ // 127 is what a shell reports for a command it could not run
660
+ std::vector<std::string> out = {"sh", "-c", "cd \"$1\" || exit 127; shift; exec \"$@\"", "_", cwd};
661
+ out.insert(out.end(), inner.begin(), inner.end());
662
+ return out;
663
+ }
664
+
665
+ exec_result exec(const std::vector<std::string> & inner, size_t max_output, bool combine_stderr) const {
666
+ return run_subprocess(
667
+ build_argv(inner, /*needs_stdin=*/false),
668
+ max_output, SERVER_TOOL_ISOLATE_EXEC_TIMEOUT, nullptr, combine_stderr);
669
+ }
670
+
671
+ bool shell_run(const std::vector<std::string> & inner) const {
672
+ auto res = exec(inner, 4096, true);
673
+ return res.exit_code == 0 && !res.timed_out;
674
+ }
675
+
676
+ bool shell_test(const char * flag, const std::string & path) const {
677
+ return shell_run({"sh", "-c", std::string("[ ") + flag + " \"$1\" ]", "_", path});
678
+ }
679
+
680
+ static std::vector<std::string> split_lines(const std::string & text, bool strip_dot_slash) {
681
+ std::vector<std::string> result;
682
+ std::istringstream iss(text);
683
+ std::string line;
684
+ while (std::getline(iss, line)) {
685
+ if (!line.empty() && line.back() == '\r') line.pop_back();
686
+ if (line.empty()) continue;
687
+ if (strip_dot_slash && line.rfind("./", 0) == 0) line = line.substr(2);
688
+ std::replace(line.begin(), line.end(), '\\', '/');
689
+ result.push_back(line);
690
+ }
691
+ return result;
692
+ }
693
+
694
+ // one `find` pass in the isolate. junk directories stay selectable but are never descended into,
695
+ // and -mindepth/-maxdepth keep a busybox image working as well as a GNU one
696
+ std::vector<std::string> find_entries(const std::string & abs_base, int max_depth, bool dirs, bool & truncated) const {
697
+ std::string prune_expr;
698
+ for (const char * n : SERVER_TOOL_JUNK_DIR_NAMES) {
699
+ if (!prune_expr.empty()) prune_expr += " -o ";
700
+ prune_expr += std::string("-name ") + n;
701
+ }
702
+
703
+ std::string cmd = "cd \"$1\" && find . -mindepth 1";
704
+ if (max_depth > 0) {
705
+ cmd += " -maxdepth " + std::to_string(max_depth);
706
+ }
707
+ cmd += " \\( " + prune_expr + " \\) -prune";
708
+ cmd += dirs ? " -print -o -type d -print" : " -o -type f -print";
709
+
710
+ auto res = exec({"sh", "-c", cmd, "_", abs_base}, SERVER_TOOL_GIT_LS_FILES_MAX_OUTPUT, true);
711
+ truncated = truncated || res.timed_out;
712
+ return split_lines(res.output, /*strip_dot_slash=*/true);
713
+ }
714
+ };
715
+
716
+ // an already-running container, driven through `<engine> exec`
717
+ // docker and podman take the same verbs and the same argument order, so one class drives both
718
+ class tools_io_container : public tools_io_isolate {
719
+ public:
720
+ tools_io_container(std::string bin, std::string container_id, std::string cwd = "")
721
+ : tools_io_isolate(std::move(cwd)), bin(std::move(bin)), container_id(std::move(container_id)) {}
722
+
723
+ protected:
724
+ std::vector<std::string> build_argv(const std::vector<std::string> & inner, bool needs_stdin) const override {
725
+ std::vector<std::string> argv = {bin, "exec"};
726
+ if (needs_stdin) {
727
+ argv.push_back("-i");
728
+ }
729
+ argv.push_back(container_id);
730
+ argv.insert(argv.end(), inner.begin(), inner.end());
731
+ return argv;
732
+ }
733
+
734
+ private:
735
+ std::string bin;
736
+ std::string container_id;
737
+ };
738
+
739
+ // a remote host reached over ssh
740
+ // this is remoting, not isolation: the tools can do anything the target account can do
741
+ class tools_io_ssh : public tools_io_isolate {
742
+ public:
743
+ tools_io_ssh(std::string target, std::string cwd = "")
744
+ : tools_io_isolate(std::move(cwd)), target(std::move(target)) {}
745
+
746
+ // the target can come from a client header, and ssh reads options from its argv
747
+ // a target starting with '-' would become one, e.g. -oProxyCommand=<anything> runs on the host
748
+ static bool is_valid_target(const std::string & target) {
749
+ if (target.empty() || target[0] == '-') {
750
+ return false;
751
+ }
752
+ return std::all_of(target.begin(), target.end(), [](unsigned char c) {
753
+ return std::isalnum(c) || c == '.' || c == '-' || c == '_' || c == '@';
754
+ });
755
+ }
756
+
757
+ protected:
758
+ std::vector<std::string> build_argv(const std::vector<std::string> & inner, bool needs_stdin) const override {
759
+ // the remote shell re-parses the command line, so `inner` travels as one quoted word
760
+ std::vector<std::string> argv = ssh_argv();
761
+ if (!needs_stdin) {
762
+ argv.push_back("-n");
763
+ }
764
+ argv.push_back(target);
765
+ argv.push_back(shell_quote_join(inner));
766
+ return argv;
767
+ }
768
+
769
+ private:
770
+ std::string target;
771
+
772
+ // there is no console here, so a prompt would hang the tool call
773
+ // key-based auth only, and the admin must trust the host key beforehand
774
+ static std::vector<std::string> ssh_argv() {
775
+ return {
776
+ "ssh",
777
+ "-o", "BatchMode=yes",
778
+ "-o", "PasswordAuthentication=no",
779
+ "-o", "KbdInteractiveAuthentication=no",
780
+ "-o", "StrictHostKeyChecking=yes",
781
+ };
782
+ }
783
+ };
784
+
785
+ // "<engine>:<image>" spawns a container and owns it, "<engine>-container:<id>" attaches to one
786
+ struct container_runtime_spec {
787
+ std::string bin;
788
+ std::string arg; // image name when spawning, container id when attaching
789
+ bool attach = false;
790
+
791
+ static bool parse(const std::string & spec, container_runtime_spec & out) {
792
+ // docker and podman take the same verbs, hence a single implementation
793
+ static const char * engines[] = {"docker", "podman"};
794
+ for (const char * bin : engines) {
795
+ const std::string attach_prefix = std::string(bin) + "-container:";
796
+ if (spec.rfind(attach_prefix, 0) == 0) {
797
+ out = {bin, spec.substr(attach_prefix.size()), true};
798
+ return true;
799
+ }
800
+ const std::string spawn_prefix = std::string(bin) + ":";
801
+ if (spec.rfind(spawn_prefix, 0) == 0) {
802
+ out = {bin, spec.substr(spawn_prefix.size()), false};
803
+ return true;
804
+ }
805
+ }
806
+ return false;
807
+ }
808
+
809
+ // same risk as the ssh target: an id starting with '-' would become an engine option,
810
+ // e.g. --privileged
811
+ static bool is_valid_id(const std::string & id) {
812
+ if (id.empty() || !std::isalnum((unsigned char) id[0])) {
813
+ return false;
814
+ }
815
+ return std::all_of(id.begin(), id.end(), [](unsigned char c) {
816
+ return std::isalnum(c) || c == '.' || c == '-' || c == '_';
817
+ });
818
+ }
819
+ };
820
+
821
+ static std::unique_ptr<tools_io> make_tools_io(const json & params) {
822
+ std::string cwd = json_value(params, "cwd", std::string());
823
+ std::string runtime = json_value(params, "runtime", std::string());
824
+ if (runtime.empty()) {
825
+ // an empty runtime runs the tools on the host
826
+ return std::make_unique<tools_io_basic>(cwd);
827
+ }
828
+ container_runtime_spec container;
829
+ if (container_runtime_spec::parse(runtime, container)) {
830
+ // spawning belongs to the runtime that owns the container, a tool call only attaches
831
+ if (!container.attach) {
832
+ throw std::runtime_error("tool runtime must name a running container: " + runtime);
833
+ }
834
+ if (!container_runtime_spec::is_valid_id(container.arg)) {
835
+ throw std::runtime_error("invalid container id: " + container.arg);
836
+ }
837
+ return std::make_unique<tools_io_container>(container.bin, container.arg, cwd);
838
+ }
839
+ const std::string ssh_prefix = "ssh:";
840
+ if (runtime.rfind(ssh_prefix, 0) == 0) {
841
+ std::string target = runtime.substr(ssh_prefix.size());
842
+ if (!tools_io_ssh::is_valid_target(target)) {
843
+ throw std::runtime_error("invalid ssh target: " + target);
844
+ }
845
+ return std::make_unique<tools_io_ssh>(target, cwd);
846
+ }
847
+ // do not fall back to the host, the caller asked for an isolate
848
+ throw std::runtime_error("unknown tool runtime: " + runtime);
849
+ }
850
+
851
+ // no '/' in pattern -> match basename at any depth; else match full relative path
852
+ static bool path_glob_match(const std::string & pattern, const std::string & rel_path) {
853
+ if (pattern.find('/') == std::string::npos) {
854
+ return glob_match(pattern, path_to_utf8(path_from_utf8(rel_path).filename()));
855
+ }
856
+ if (pattern == "**" || pattern.rfind("**/", 0) == 0 || pattern.rfind('/', 0) == 0) {
857
+ return glob_match(pattern, rel_path);
858
+ }
859
+ return glob_match("**/" + pattern, rel_path);
860
+ }
861
+
862
+ //
863
+ // read_file: read a file with optional line range and line-number prefix
864
+ //
865
+
866
+ static constexpr size_t SERVER_TOOL_READ_FILE_MAX_SIZE = 16 * 1024; // 16 KB
867
+
868
+ struct server_tool_read_file : server_tool {
869
+ server_tool_read_file() {
870
+ name = "read_file";
871
+ display_name = "Read file";
872
+ uses_cwd = true;
873
+ permission_write = false;
874
+ }
875
+
876
+ json get_definition() const override {
877
+ return {
878
+ {"type", "function"},
879
+ {"function", {
880
+ {"name", name},
881
+ {"description", "Read the contents of a file. Optionally specify a 1-based line range. "
882
+ "If append_loc is true, each line is prefixed with its line number (e.g. \"1\u2192...\")."},
883
+ {"parameters", {
884
+ {"type", "object"},
885
+ {"properties", {
886
+ {"path", {{"type", "string"}, {"description", "Path to the file"}}},
887
+ {"start_line", {{"type", "integer"}, {"description", "First line to read, 1-based (default: 1)"}}},
888
+ {"end_line", {{"type", "integer"}, {"description", "Last line to read, 1-based inclusive (default: end of file)"}}},
889
+ {"append_loc", {{"type", "boolean"}, {"description", "Prefix each line with its line number"}}},
890
+ }},
891
+ {"required", json::array({"path"})},
892
+ }},
893
+ }},
894
+ };
895
+ }
896
+
897
+ json invoke(json params, server_tool::stream *) const override {
898
+ std::string path = params.at("path").get<std::string>();
899
+ int start_line = json_value(params, "start_line", 1);
900
+ int end_line = json_value(params, "end_line", -1); // -1 = no limit
901
+ bool append_loc = json_value(params, "append_loc", false);
902
+
903
+ auto io = make_tools_io(params);
904
+
905
+ uintmax_t file_size = 0;
906
+ if (!io->file_size(path, file_size)) {
907
+ return {{"error", "cannot stat file: " + path}};
908
+ }
909
+ if (file_size > SERVER_TOOL_READ_FILE_MAX_SIZE && end_line == -1) {
910
+ return {{"error", string_format(
911
+ "file too large (%zu bytes, max %zu). Use start_line/end_line to read a portion.",
912
+ (size_t)file_size, SERVER_TOOL_READ_FILE_MAX_SIZE)}};
913
+ }
914
+
915
+ std::string content;
916
+ if (!io->read_file(path, content)) {
917
+ return {{"error", "failed to open file: " + path}};
918
+ }
919
+
920
+ std::istringstream f(content);
921
+ std::string result;
922
+ std::string line;
923
+ int lineno = 0;
924
+
925
+ while (std::getline(f, line)) {
926
+ lineno++;
927
+ if (lineno < start_line) continue;
928
+ if (end_line != -1 && lineno > end_line) break;
929
+
930
+ std::string out_line;
931
+ if (append_loc) {
932
+ out_line = std::to_string(lineno) + "\u2192" + line + "\n";
933
+ } else {
934
+ out_line = line + "\n";
935
+ }
936
+
937
+ if (result.size() + out_line.size() > SERVER_TOOL_READ_FILE_MAX_SIZE) {
938
+ result += "[output truncated]";
939
+ break;
940
+ }
941
+ result += out_line;
942
+ }
943
+
944
+ return {{"plain_text_response", result}};
945
+ }
946
+ };
947
+
948
+ //
949
+ // file_glob_search: find files matching a glob pattern under a base directory
950
+ //
951
+
952
+ static constexpr int SERVER_TOOL_FILE_SEARCH_MAX_RESULTS = 100;
953
+ static constexpr const char * SERVER_TOOL_FILE_SEARCH_TYPE_FILE = "file";
954
+ static constexpr const char * SERVER_TOOL_FILE_SEARCH_TYPE_DIR = "dir";
955
+ static constexpr const char * SERVER_TOOL_FILE_SEARCH_TYPE_ALL = "all";
956
+
957
+ struct server_tool_file_glob_search : server_tool {
958
+ server_tool_file_glob_search() {
959
+ name = "file_glob_search";
960
+ display_name = "File search";
961
+ uses_cwd = true;
962
+ permission_write = false;
963
+ }
964
+
965
+ json get_definition() const override {
966
+ return {
967
+ {"type", "function"},
968
+ {"function", {
969
+ {"name", name},
970
+ {"description",
971
+ "Recursively search for files matching a glob pattern under a directory. "
972
+ "Automatically skips files ignored by .gitignore (when the directory is inside a git repo) "
973
+ "and common junk directories (.git, node_modules, build, dist, etc.) otherwise. "
974
+ "A pattern with no '/' (e.g. \"*.cpp\") matches the file's basename at any depth. "
975
+ "A pattern containing '/' matches the full relative path; unless already anchored with "
976
+ "\"**/\" or a leading '/', it is automatically prefixed with \"**/\". "
977
+ "Use type=\"dir\" or \"all\" to also list directories; directory entries are suffixed with '/' in the output. "
978
+ "Note: directory listings do not apply .gitignore filtering."},
979
+ {"parameters", {
980
+ {"type", "object"},
981
+ {"properties", {
982
+ {"path", {{"type", "string"}, {"description", "Base directory to search in"}}},
983
+ {"include", {{"type", "string"}, {"description", "Glob pattern for files to include (e.g. \"*.cpp\" or \"src/**/*.cpp\"). Default: **"}}},
984
+ {"exclude", {{"type", "string"}, {"description", "Glob pattern for files to exclude"}}},
985
+ {"type", {{"type", "string"}, {"description", "Entry type to return: \"file\" (default), \"dir\" or \"all\""}}},
986
+ {"max_depth", {{"type", "integer"}, {"description", "Maximum depth to descend into subdirectories (default: 0 = unlimited; 1 = direct children only)"}}},
987
+ {"limit", {{"type", "integer"}, {"description", string_format("Maximum number of results to return, capped at %d (default %d)", SERVER_TOOL_FILE_SEARCH_MAX_RESULTS, SERVER_TOOL_FILE_SEARCH_MAX_RESULTS)}}},
988
+ }},
989
+ {"required", json::array({"path"})},
990
+ }},
991
+ }},
992
+ };
993
+ }
994
+
995
+ json invoke(json params, server_tool::stream *) const override {
996
+ auto io = make_tools_io(params);
997
+
998
+ const std::string path = params.at("path").get<std::string>();
999
+
1000
+ std::string base = io->resolve(path);
1001
+ std::string include = json_value(params, "include", std::string("**"));
1002
+ std::string exclude = json_value(params, "exclude", std::string(""));
1003
+ std::string type = json_value(params, "type", std::string("file"));
1004
+ int max_depth = std::max(0, json_value(params, "max_depth", 0));
1005
+ const int limit_req = json_value(params, "limit", SERVER_TOOL_FILE_SEARCH_MAX_RESULTS);
1006
+ if (limit_req < 1) {
1007
+ return {{"error", "invalid limit: " + std::to_string(limit_req) + " (expected 1 or more)"}};
1008
+ }
1009
+ const int limit = std::min(limit_req, SERVER_TOOL_FILE_SEARCH_MAX_RESULTS);
1010
+
1011
+ list_kind kind;
1012
+ if (type == SERVER_TOOL_FILE_SEARCH_TYPE_FILE) {
1013
+ kind = list_kind::files;
1014
+ } else if (type == SERVER_TOOL_FILE_SEARCH_TYPE_DIR) {
1015
+ kind = list_kind::dirs;
1016
+ } else if (type == SERVER_TOOL_FILE_SEARCH_TYPE_ALL) {
1017
+ kind = list_kind::all;
1018
+ } else {
1019
+ return {{"error", "invalid type: " + type + " (expected \"file\", \"dir\" or \"all\")"}};
1020
+ }
1021
+
1022
+ const auto listing = io->list_entries(base, max_depth, kind);
1023
+ if (!listing.err.empty()) {
1024
+ return {{"error", listing.err + ": " + path}};
1025
+ }
1026
+
1027
+ std::vector<tools_io::list_entry> matches;
1028
+ for (const auto & entry : listing.entries) {
1029
+ if (!path_glob_match(include, entry.rel)) continue;
1030
+ if (!exclude.empty() && path_glob_match(exclude, entry.rel)) continue;
1031
+ matches.push_back(entry);
1032
+ }
1033
+
1034
+ size_t total = matches.size();
1035
+ size_t shown = std::min(total, (size_t) limit);
1036
+
1037
+ std::ostringstream output_text;
1038
+ json entries_json = json::array();
1039
+ for (size_t i = 0; i < shown; i++) {
1040
+ output_text << matches[i].rel << (matches[i].is_dir ? "/" : "") << "\n";
1041
+ entries_json.push_back({
1042
+ {"path", matches[i].rel},
1043
+ {"type", matches[i].is_dir ? "dir" : "file"},
1044
+ });
1045
+ }
1046
+
1047
+ output_text << "\n---\nTotal matches: " << total << "\n";
1048
+ if (total > shown) {
1049
+ output_text << string_format(
1050
+ "[%zu results limit reached (%zu total matches). Refine the glob pattern to narrow the search.]\n",
1051
+ shown, total);
1052
+ }
1053
+ if (listing.truncated) {
1054
+ output_text << "[results truncated: time budget or unreadable directory]\n";
1055
+ }
1056
+
1057
+ // `base` is always absolute (resolve falls back to the server cwd), so
1058
+ // API clients (e.g. the web UI picker) can join the relative entries
1059
+ // into absolute paths. `plain_text_response` is what the model sees;
1060
+ // `entries` is the same data as structured JSON for the UI picker,
1061
+ // which reads `entries`/`base` instead of re-parsing the text.
1062
+ return {{"plain_text_response", output_text.str()}, {"entries", entries_json}, {"base", base}};
1063
+ }
1064
+ };
1065
+
1066
+ //
1067
+ // grep_search: search for a regex pattern in files
1068
+ //
1069
+
1070
+ static constexpr size_t SERVER_TOOL_GREP_SEARCH_MAX_RESULTS = 100;
1071
+
1072
+ struct server_tool_grep_search : server_tool {
1073
+ server_tool_grep_search() {
1074
+ name = "grep_search";
1075
+ display_name = "Grep search";
1076
+ uses_cwd = true;
1077
+ permission_write = false;
1078
+ }
1079
+
1080
+ json get_definition() const override {
1081
+ return {
1082
+ {"type", "function"},
1083
+ {"function", {
1084
+ {"name", name},
1085
+ {"description",
1086
+ "Search for a pattern in files under a path. Returns matching lines with file paths "
1087
+ "(and, unless searching a single file, paths relative to the given directory). "
1088
+ "Automatically skips files ignored by .gitignore (when the directory is inside a git repo) "
1089
+ "and common junk directories (.git, node_modules, build, dist, etc.) otherwise. "
1090
+ "include/exclude: a pattern with no '/' matches the basename at any depth; a pattern "
1091
+ "containing '/' matches the full relative path (auto-anchored with \"**/\" unless already anchored)."},
1092
+ {"parameters", {
1093
+ {"type", "object"},
1094
+ {"properties", {
1095
+ {"path", {{"type", "string"}, {"description", "File or directory to search in"}}},
1096
+ {"pattern", {{"type", "string"}, {"description", "Pattern to search for (regular expression unless literal is true)"}}},
1097
+ {"include", {{"type", "string"}, {"description", "Glob pattern to filter files (default: **)"}}},
1098
+ {"exclude", {{"type", "string"}, {"description", "Glob pattern to exclude files"}}},
1099
+ {"return_line_numbers", {{"type", "boolean"}, {"description", "If true, include line numbers in results"}}},
1100
+ {"literal", {{"type", "boolean"}, {"description", "Treat pattern as a literal string instead of a regular expression (default: false)"}}},
1101
+ {"ignore_case", {{"type", "boolean"}, {"description", "Case-insensitive search (default: false)"}}},
1102
+ {"context_lines", {{"type", "integer"}, {"description", "Number of lines of context to show before and after each match (default: 0)"}}},
1103
+ }},
1104
+ {"required", json::array({"path", "pattern"})},
1105
+ }},
1106
+ }},
1107
+ };
1108
+ }
1109
+
1110
+ json invoke(json params, server_tool::stream *) const override {
1111
+ std::string path = params.at("path").get<std::string>();
1112
+ std::string pat_str = params.at("pattern").get<std::string>();
1113
+ std::string include = json_value(params, "include", std::string("**"));
1114
+ std::string exclude = json_value(params, "exclude", std::string(""));
1115
+ bool show_lineno = json_value(params, "return_line_numbers", false);
1116
+ bool literal = json_value(params, "literal", false);
1117
+ bool ignore_case = json_value(params, "ignore_case", false);
1118
+ int ctx_lines = std::max(0, json_value(params, "context_lines", 0));
1119
+
1120
+ std::string pattern_src = pat_str;
1121
+ if (literal) {
1122
+ static const std::string specials = "\\^$.|?*+()[]{}";
1123
+ std::string escaped;
1124
+ escaped.reserve(pat_str.size() * 2);
1125
+ for (char c : pat_str) {
1126
+ if (specials.find(c) != std::string::npos) escaped += '\\';
1127
+ escaped += c;
1128
+ }
1129
+ pattern_src = escaped;
1130
+ }
1131
+
1132
+ std::regex pattern;
1133
+ try {
1134
+ auto flags = std::regex::ECMAScript;
1135
+ if (ignore_case) flags |= std::regex::icase;
1136
+ pattern = std::regex(pattern_src, flags);
1137
+ } catch (const std::regex_error & e) {
1138
+ return {{"error", std::string("invalid regex: ") + e.what()}};
1139
+ }
1140
+
1141
+ auto io = make_tools_io(params);
1142
+
1143
+ // collect (absolute_path, display_path) pairs to search
1144
+ std::vector<std::pair<std::string, std::string>> files;
1145
+
1146
+ const std::string abs_path = io->resolve(path);
1147
+ if (io->is_regular_file(abs_path)) {
1148
+ files.emplace_back(abs_path, path);
1149
+ } else if (io->is_directory(abs_path)) {
1150
+ const auto listing = io->list_entries(abs_path, 0, list_kind::files);
1151
+ if (!listing.err.empty()) {
1152
+ return {{"error", listing.err + ": " + path}};
1153
+ }
1154
+ for (const auto & entry : listing.entries) {
1155
+ if (!path_glob_match(include, entry.rel)) continue;
1156
+ if (!exclude.empty() && path_glob_match(exclude, entry.rel)) continue;
1157
+ files.emplace_back(path_to_utf8(path_from_utf8(abs_path) / path_from_utf8(entry.rel)), entry.rel);
1158
+ }
1159
+ } else {
1160
+ return {{"error", "path does not exist: " + path}};
1161
+ }
1162
+
1163
+ std::ostringstream output_text;
1164
+ size_t total = 0;
1165
+ bool limit_reached = false;
1166
+ bool show_num = show_lineno || ctx_lines > 0;
1167
+
1168
+ for (const auto & file_entry : files) {
1169
+ if (limit_reached) break;
1170
+ const std::string & fpath = file_entry.first;
1171
+ const std::string & display_path = file_entry.second;
1172
+
1173
+ std::string content;
1174
+ if (!io->read_file(fpath, content)) continue;
1175
+ std::vector<std::string> lines;
1176
+ {
1177
+ std::istringstream f(content);
1178
+ std::string line;
1179
+ while (std::getline(f, line)) lines.push_back(line);
1180
+ }
1181
+
1182
+ for (size_t i = 0; i < lines.size(); i++) {
1183
+ if (total >= SERVER_TOOL_GREP_SEARCH_MAX_RESULTS) {
1184
+ limit_reached = true;
1185
+ break;
1186
+ }
1187
+ if (!std::regex_search(lines[i], pattern)) continue;
1188
+
1189
+ long ctx_start = ctx_lines > 0 ? std::max<long>(0, (long) i - ctx_lines) : (long) i;
1190
+ long ctx_end = ctx_lines > 0 ? std::min<long>((long) lines.size() - 1, (long) i + ctx_lines) : (long) i;
1191
+
1192
+ for (long j = ctx_start; j <= ctx_end; j++) {
1193
+ bool is_match = (j == (long) i);
1194
+ output_text << display_path << (is_match ? ':' : '-');
1195
+ if (show_num) {
1196
+ output_text << (j + 1) << (is_match ? ':' : '-');
1197
+ }
1198
+ output_text << lines[j] << "\n";
1199
+ }
1200
+ if (ctx_lines > 0) {
1201
+ output_text << "--\n";
1202
+ }
1203
+ total++;
1204
+ }
1205
+ }
1206
+
1207
+ output_text << "\n---\nTotal matches: " << total << "\n";
1208
+ if (limit_reached) {
1209
+ output_text << string_format(
1210
+ "[%zu matches limit reached. Narrow the path/pattern/include to see more.]\n",
1211
+ SERVER_TOOL_GREP_SEARCH_MAX_RESULTS);
1212
+ }
1213
+
1214
+ return {{"plain_text_response", output_text.str()}};
1215
+ }
1216
+ };
1217
+
1218
+ //
1219
+ // exec_shell_command: run an arbitrary shell command
1220
+ //
1221
+
1222
+ static constexpr size_t SERVER_TOOL_EXEC_SHELL_COMMAND_MAX_OUTPUT_SIZE = 16 * 1024; // 16 KB
1223
+ static constexpr int SERVER_TOOL_EXEC_SHELL_COMMAND_MAX_TIMEOUT = 60; // seconds
1224
+
1225
+ struct server_tool_exec_shell_command : server_tool {
1226
+ server_tool_exec_shell_command() {
1227
+ name = "exec_shell_command";
1228
+ display_name = "Execute shell command";
1229
+ uses_cwd = true;
1230
+ permission_write = true;
1231
+ support_stream = true;
1232
+ }
1233
+
1234
+ json get_definition() const override {
1235
+ return {
1236
+ {"type", "function"},
1237
+ {"function", {
1238
+ {"name", name},
1239
+ {"description", "Execute a shell command and return its output (stdout and stderr combined)."},
1240
+ {"parameters", {
1241
+ {"type", "object"},
1242
+ {"properties", {
1243
+ {"command", {{"type", "string"}, {"description", "Shell command to execute"}}},
1244
+ {"timeout", {{"type", "integer"}, {"description", string_format("Timeout in seconds (default 10, max %d)", SERVER_TOOL_EXEC_SHELL_COMMAND_MAX_TIMEOUT)}}},
1245
+ {"max_output_size", {{"type", "integer"}, {"description", string_format("Maximum output size in bytes (default %zu)", SERVER_TOOL_EXEC_SHELL_COMMAND_MAX_OUTPUT_SIZE)}}},
1246
+ }},
1247
+ {"required", json::array({"command"})},
1248
+ }},
1249
+ }},
1250
+ };
1251
+ }
1252
+
1253
+ json invoke(json params, server_tool::stream * st) const override {
1254
+ std::string command = params.at("command").get<std::string>();
1255
+ int timeout = json_value(params, "timeout", 10);
1256
+ size_t max_output = (size_t) json_value(params, "max_output_size", (int) SERVER_TOOL_EXEC_SHELL_COMMAND_MAX_OUTPUT_SIZE);
1257
+
1258
+ timeout = std::min(timeout, SERVER_TOOL_EXEC_SHELL_COMMAND_MAX_TIMEOUT);
1259
+ max_output = std::min(max_output, SERVER_TOOL_EXEC_SHELL_COMMAND_MAX_OUTPUT_SIZE);
1260
+
1261
+ // an isolate is always POSIX regardless of host OS, so it always gets `sh -c`
1262
+ #ifdef _WIN32
1263
+ std::vector<std::string> args = !json_value(params, "runtime", std::string()).empty()
1264
+ ? std::vector<std::string>{"sh", "-c", command}
1265
+ : std::vector<std::string>{"cmd", "/c", command};
1266
+ #else
1267
+ std::vector<std::string> args = {"sh", "-c", command};
1268
+ #endif
1269
+
1270
+ auto io = make_tools_io(params);
1271
+
1272
+ if (st) {
1273
+ auto res = io->run(args, max_output, timeout, [st](const std::string & chunk) {
1274
+ st->push(chunk);
1275
+ return !st->alive || st->alive();
1276
+ });
1277
+ if (st->alive && !st->alive()) {
1278
+ return json();
1279
+ }
1280
+ std::string tail = string_format("\n[exit code: %d]", res.exit_code);
1281
+ if (res.timed_out) {
1282
+ tail += " [exit due to timed out]";
1283
+ }
1284
+ st->push(tail);
1285
+ return json();
1286
+ }
1287
+
1288
+ auto res = io->run(args, max_output, timeout);
1289
+
1290
+ std::string text_output = res.output;
1291
+ text_output += string_format("\n[exit code: %d]", res.exit_code);
1292
+ if (res.timed_out) {
1293
+ text_output += " [exit due to timed out]";
1294
+ }
1295
+
1296
+ return {{"plain_text_response", text_output}};
1297
+ }
1298
+ };
1299
+
1300
+ //
1301
+ // write_file: create or overwrite a file
1302
+ //
1303
+
1304
+ struct server_tool_write_file : server_tool {
1305
+ server_tool_write_file() {
1306
+ name = "write_file";
1307
+ display_name = "Write file";
1308
+ uses_cwd = true;
1309
+ permission_write = true;
1310
+ }
1311
+
1312
+ json get_definition() const override {
1313
+ return {
1314
+ {"type", "function"},
1315
+ {"function", {
1316
+ {"name", name},
1317
+ {"description", "Write content to a file, creating it (including parent directories) if it does not exist. May use with edit_file for more complex edits."},
1318
+ {"parameters", {
1319
+ {"type", "object"},
1320
+ {"properties", {
1321
+ {"path", {{"type", "string"}, {"description", "Path of the file to write"}}},
1322
+ {"content", {{"type", "string"}, {"description", "Content to write"}}},
1323
+ }},
1324
+ {"required", json::array({"path", "content"})},
1325
+ }},
1326
+ }},
1327
+ };
1328
+ }
1329
+
1330
+ json invoke(json params, server_tool::stream *) const override {
1331
+ std::string path = params.at("path").get<std::string>();
1332
+ std::string content = params.at("content").get<std::string>();
1333
+
1334
+ auto io = make_tools_io(params);
1335
+ if (!io->write_file(path, content)) {
1336
+ return {{"error", "failed to write file: " + path}};
1337
+ }
1338
+
1339
+ return {{"result", "file written successfully"}, {"path", path}, {"bytes", content.size()}};
1340
+ }
1341
+ };
1342
+
1343
+ //
1344
+ // edit_file: exact text replacement, one or more edits per call
1345
+ //
1346
+
1347
+ struct server_tool_edit_file : server_tool {
1348
+ server_tool_edit_file() {
1349
+ name = "edit_file";
1350
+ display_name = "Edit file";
1351
+ uses_cwd = true;
1352
+ permission_write = true;
1353
+ }
1354
+
1355
+ json get_definition() const override {
1356
+ return {
1357
+ {"type", "function"},
1358
+ {"function", {
1359
+ {"name", name},
1360
+ {"description",
1361
+ "Edit a file using exact text replacement. Each edits[].old_text must be unique in the file "
1362
+ "and is matched against the original content, not incrementally. Merge nearby changes into "
1363
+ "one edit instead of overlapping edits. Use write_file to replace the whole file."},
1364
+ {"parameters", {
1365
+ {"type", "object"},
1366
+ {"properties", {
1367
+ {"path", {{"type", "string"}, {"description", "Path to the file to edit"}}},
1368
+ {"edits", {
1369
+ {"type", "array"},
1370
+ {"description", "One or more exact text replacements to apply"},
1371
+ {"items", {
1372
+ {"type", "object"},
1373
+ {"properties", {
1374
+ {"old_text", {{"type", "string"}, {"description", "Exact text to find; must be unique in the file and must not overlap with other edits"}}},
1375
+ {"new_text", {{"type", "string"}, {"description", "Text to replace old_text with"}}},
1376
+ }},
1377
+ {"required", json::array({"old_text", "new_text"})},
1378
+ }},
1379
+ }},
1380
+ }},
1381
+ {"required", json::array({"path", "edits"})},
1382
+ }},
1383
+ }},
1384
+ };
1385
+ }
1386
+
1387
+ json invoke(json params, server_tool::stream *) const override {
1388
+ std::string path = params.at("path").get<std::string>();
1389
+ const json & edits_json = params.at("edits");
1390
+
1391
+ if (!edits_json.is_array() || edits_json.empty()) {
1392
+ return {{"error", "\"edits\" must be a non-empty array"}};
1393
+ }
1394
+
1395
+ struct edit_req {
1396
+ std::string old_text;
1397
+ std::string new_text;
1398
+ };
1399
+ std::vector<edit_req> edits;
1400
+ edits.reserve(edits_json.size());
1401
+ for (const auto & e : edits_json) {
1402
+ edit_req er;
1403
+ er.old_text = e.at("old_text").get<std::string>();
1404
+ er.new_text = e.at("new_text").get<std::string>();
1405
+ if (er.old_text.empty()) {
1406
+ return {{"error", string_format("edits[%zu].old_text must not be empty", edits.size())}};
1407
+ }
1408
+ edits.push_back(std::move(er));
1409
+ }
1410
+
1411
+ auto io = make_tools_io(params);
1412
+ std::string original_content;
1413
+ if (!io->read_file(path, original_content)) {
1414
+ return {{"error", "failed to open file: " + path}};
1415
+ }
1416
+
1417
+ // does any old_text need fuzzy matching (no exact match found)?
1418
+ bool any_fuzzy = false;
1419
+ for (size_t i = 0; i < edits.size(); i++) {
1420
+ if (original_content.find(edits[i].old_text) != std::string::npos) continue;
1421
+ std::string fuzzy_content = normalize_for_fuzzy_match(original_content);
1422
+ std::string fuzzy_old = normalize_for_fuzzy_match(edits[i].old_text);
1423
+ if (fuzzy_content.find(fuzzy_old) == std::string::npos) {
1424
+ return {{"error", string_format(
1425
+ "could not find edits[%zu].old_text in %s, it must match the file's current content exactly",
1426
+ i, path.c_str())}};
1427
+ }
1428
+ any_fuzzy = true;
1429
+ }
1430
+
1431
+ std::string base_content = any_fuzzy ? normalize_for_fuzzy_match(original_content) : original_content;
1432
+
1433
+ // uniqueness check always uses fuzzy-normalized text, so a whitespace-only duplicate still counts
1434
+ std::vector<matched_edit> matched;
1435
+ matched.reserve(edits.size());
1436
+ for (size_t i = 0; i < edits.size(); i++) {
1437
+ std::string needle = any_fuzzy ? normalize_for_fuzzy_match(edits[i].old_text) : edits[i].old_text;
1438
+ size_t occurrences = count_occurrences(
1439
+ normalize_for_fuzzy_match(original_content),
1440
+ normalize_for_fuzzy_match(edits[i].old_text));
1441
+ if (occurrences > 1) {
1442
+ return {{"error", string_format(
1443
+ "found %zu occurrences of edits[%zu].old_text in %s, it must be unique",
1444
+ occurrences, i, path.c_str())}};
1445
+ }
1446
+ size_t idx = base_content.find(needle);
1447
+ matched.push_back({i, idx, needle.size(), edits[i].new_text});
1448
+ }
1449
+
1450
+ std::sort(matched.begin(), matched.end(), [](const matched_edit & a, const matched_edit & b) {
1451
+ return a.match_index < b.match_index;
1452
+ });
1453
+ for (size_t i = 1; i < matched.size(); i++) {
1454
+ if (matched[i - 1].match_index + matched[i - 1].match_length > matched[i].match_index) {
1455
+ return {{"error", string_format(
1456
+ "edits[%zu] and edits[%zu] overlap in %s; merge them into one edit or target disjoint regions",
1457
+ matched[i - 1].edit_index, matched[i].edit_index, path.c_str())}};
1458
+ }
1459
+ }
1460
+
1461
+ std::string new_content = any_fuzzy
1462
+ ? apply_replacements_preserving_unchanged_lines(original_content, base_content, matched)
1463
+ : apply_replacements(base_content, matched, 0);
1464
+
1465
+ if (new_content == original_content) {
1466
+ return {{"error", "no changes made: the replacement(s) produced identical content"}};
1467
+ }
1468
+
1469
+ if (!io->write_file(path, new_content)) {
1470
+ return {{"error", "failed to write file: " + path}};
1471
+ }
1472
+
1473
+ return {{"result", "file edited successfully"}, {"path", path}, {"edits_applied", (int) matched.size()}};
1474
+ }
1475
+
1476
+ private:
1477
+ // strip trailing whitespace, normalize smart quotes/dashes/spaces to ASCII
1478
+ static std::string normalize_line_for_fuzzy_match(const std::string & line) {
1479
+ size_t end = line.size();
1480
+ while (end > 0 && (line[end - 1] == ' ' || line[end - 1] == '\t' || line[end - 1] == '\r')) {
1481
+ end--;
1482
+ }
1483
+ std::string s = line.substr(0, end);
1484
+
1485
+ auto replace_all = [](std::string & str, const std::string & from, const std::string & to) {
1486
+ if (from.empty()) return;
1487
+ size_t pos = 0;
1488
+ while ((pos = str.find(from, pos)) != std::string::npos) {
1489
+ str.replace(pos, from.size(), to);
1490
+ pos += to.size();
1491
+ }
1492
+ };
1493
+
1494
+ // smart single quotes -> '
1495
+ for (unsigned char b : {0x98, 0x99, 0x9A, 0x9B}) {
1496
+ replace_all(s, std::string("\xE2\x80") + (char) b, "'");
1497
+ }
1498
+ // smart double quotes -> "
1499
+ for (unsigned char b : {0x9C, 0x9D, 0x9E, 0x9F}) {
1500
+ replace_all(s, std::string("\xE2\x80") + (char) b, "\"");
1501
+ }
1502
+ // various dashes -> -
1503
+ for (unsigned char b = 0x90; b <= 0x95; b++) {
1504
+ replace_all(s, std::string("\xE2\x80") + (char) b, "-");
1505
+ }
1506
+ replace_all(s, "\xE2\x88\x92", "-"); // minus sign
1507
+ // special spaces -> ' '
1508
+ replace_all(s, "\xC2\xA0", " "); // no-break space
1509
+ for (unsigned char b = 0x82; b <= 0x8A; b++) {
1510
+ replace_all(s, std::string("\xE2\x80") + (char) b, " ");
1511
+ }
1512
+ replace_all(s, "\xE2\x80\xAF", " "); // narrow no-break space
1513
+ replace_all(s, "\xE2\x81\x9F", " "); // medium mathematical space
1514
+ replace_all(s, "\xE3\x80\x80", " "); // ideographic space
1515
+
1516
+ return s;
1517
+ }
1518
+
1519
+ // applies the per-line transform above to every line; preserves line count/positions
1520
+ static std::string normalize_for_fuzzy_match(const std::string & content) {
1521
+ std::string result;
1522
+ result.reserve(content.size());
1523
+ size_t start = 0;
1524
+ while (true) {
1525
+ size_t nl = content.find('\n', start);
1526
+ bool is_last = nl == std::string::npos;
1527
+ std::string line = is_last ? content.substr(start) : content.substr(start, nl - start);
1528
+ result += normalize_line_for_fuzzy_match(line);
1529
+ if (is_last) break;
1530
+ result += '\n';
1531
+ start = nl + 1;
1532
+ }
1533
+ return result;
1534
+ }
1535
+
1536
+ // lines with trailing '\n' kept, so untouched ones can be reconstructed verbatim
1537
+ static std::vector<std::string> split_lines_with_endings(const std::string & content) {
1538
+ std::vector<std::string> lines;
1539
+ size_t start = 0;
1540
+ while (start < content.size()) {
1541
+ size_t nl = content.find('\n', start);
1542
+ if (nl == std::string::npos) {
1543
+ lines.push_back(content.substr(start));
1544
+ break;
1545
+ }
1546
+ lines.push_back(content.substr(start, nl - start + 1));
1547
+ start = nl + 1;
1548
+ }
1549
+ return lines;
1550
+ }
1551
+
1552
+ struct line_span {
1553
+ size_t start;
1554
+ size_t end;
1555
+ };
1556
+
1557
+ static std::vector<line_span> get_line_spans(const std::string & content) {
1558
+ std::vector<line_span> spans;
1559
+ size_t offset = 0;
1560
+ for (const auto & line : split_lines_with_endings(content)) {
1561
+ spans.push_back({offset, offset + line.size()});
1562
+ offset += line.size();
1563
+ }
1564
+ return spans;
1565
+ }
1566
+
1567
+ // count non-overlapping occurrences of `needle` in `content`
1568
+ static size_t count_occurrences(const std::string & content, const std::string & needle) {
1569
+ if (needle.empty()) return 0;
1570
+ size_t count = 0, pos = 0;
1571
+ while ((pos = content.find(needle, pos)) != std::string::npos) {
1572
+ count++;
1573
+ pos += needle.size();
1574
+ }
1575
+ return count;
1576
+ }
1577
+
1578
+ struct matched_edit {
1579
+ size_t edit_index;
1580
+ size_t match_index; // offset into the "base content" (see below)
1581
+ size_t match_length;
1582
+ std::string new_text;
1583
+ };
1584
+
1585
+ // replacements must be sorted ascending by match_index and non-overlapping
1586
+ static std::string apply_replacements(
1587
+ const std::string & content,
1588
+ const std::vector<matched_edit> & replacements,
1589
+ size_t offset) {
1590
+ std::string result = content;
1591
+ for (auto it = replacements.rbegin(); it != replacements.rend(); ++it) {
1592
+ size_t local_index = it->match_index - offset;
1593
+ result = result.substr(0, local_index) + it->new_text + result.substr(local_index + it->match_length);
1594
+ }
1595
+ return result;
1596
+ }
1597
+
1598
+ // widen a replacement's byte range to the line(s) of `lines` it touches
1599
+ static bool get_replacement_line_range(
1600
+ const std::vector<line_span> & lines,
1601
+ size_t match_index, size_t match_length,
1602
+ size_t & out_start_line, size_t & out_end_line /* exclusive */) {
1603
+ size_t replacement_start = match_index;
1604
+ size_t replacement_end = match_index + match_length;
1605
+
1606
+ size_t start_line = (size_t) -1;
1607
+ for (size_t i = 0; i < lines.size(); i++) {
1608
+ if (replacement_start >= lines[i].start && replacement_start < lines[i].end) {
1609
+ start_line = i;
1610
+ break;
1611
+ }
1612
+ }
1613
+ if (start_line == (size_t) -1) return false;
1614
+
1615
+ size_t end_line = start_line;
1616
+ while (end_line < lines.size() && lines[end_line].end < replacement_end) {
1617
+ end_line++;
1618
+ }
1619
+ if (end_line >= lines.size()) return false;
1620
+
1621
+ out_start_line = start_line;
1622
+ out_end_line = end_line + 1;
1623
+ return true;
1624
+ }
1625
+
1626
+ // like apply_replacements, but untouched lines come from `original_content`
1627
+ static std::string apply_replacements_preserving_unchanged_lines(
1628
+ const std::string & original_content,
1629
+ const std::string & base_content,
1630
+ const std::vector<matched_edit> & replacements /* ascending, non-overlapping */) {
1631
+ auto original_lines = split_lines_with_endings(original_content);
1632
+ auto base_lines = get_line_spans(base_content);
1633
+
1634
+ struct group {
1635
+ size_t start_line;
1636
+ size_t end_line; // exclusive
1637
+ std::vector<matched_edit> reps;
1638
+ };
1639
+ std::vector<group> groups;
1640
+
1641
+ for (const auto & rep : replacements) {
1642
+ size_t start_line = 0, end_line = 0;
1643
+ get_replacement_line_range(base_lines, rep.match_index, rep.match_length, start_line, end_line);
1644
+ if (!groups.empty() && start_line < groups.back().end_line) {
1645
+ groups.back().end_line = std::max(groups.back().end_line, end_line);
1646
+ groups.back().reps.push_back(rep);
1647
+ } else {
1648
+ groups.push_back({start_line, end_line, {rep}});
1649
+ }
1650
+ }
1651
+
1652
+ size_t original_line_index = 0;
1653
+ std::string result;
1654
+ for (auto & g : groups) {
1655
+ for (size_t i = original_line_index; i < g.start_line; i++) {
1656
+ result += original_lines[i];
1657
+ }
1658
+
1659
+ size_t group_start_offset = base_lines[g.start_line].start;
1660
+ size_t group_end_offset = base_lines[g.end_line - 1].end;
1661
+ std::string slice = base_content.substr(group_start_offset, group_end_offset - group_start_offset);
1662
+ result += apply_replacements(slice, g.reps, group_start_offset);
1663
+
1664
+ original_line_index = g.end_line;
1665
+ }
1666
+ for (size_t i = original_line_index; i < original_lines.size(); i++) {
1667
+ result += original_lines[i];
1668
+ }
1669
+
1670
+ return result;
1671
+ }
1672
+ };
1673
+
1674
+ //
1675
+ // get_datetime: returns the current date and time
1676
+ //
1677
+
1678
+ struct server_tool_get_datetime : server_tool {
1679
+ server_tool_get_datetime() {
1680
+ name = "get_datetime";
1681
+ display_name = "Get Date & Time";
1682
+ permission_write = false;
1683
+ }
1684
+
1685
+ json get_definition() const override {
1686
+ return {
1687
+ {"type", "function"},
1688
+ {"function", {
1689
+ {"name", name},
1690
+ {"description", "Returns the current date and time in UTC"},
1691
+ {"parameters", {
1692
+ {"type", "object"},
1693
+ {"properties", {
1694
+ {"format", {
1695
+ {"type", "string"},
1696
+ {"description",
1697
+ "strftime()-style format string for the output (default: \"%Y-%m-%dT%H:%M:%SZ\", "
1698
+ "e.g. ISO 8601). Choose your own format if you need something else, "
1699
+ "e.g. \"%A, %B %d %Y\" for a human-readable date."},
1700
+ }},
1701
+ }},
1702
+ }},
1703
+ }},
1704
+ };
1705
+ }
1706
+
1707
+ json invoke(json params, server_tool::stream *) const override {
1708
+ std::string format = json_value(params, "format", std::string("%Y-%m-%dT%H:%M:%SZ"));
1709
+
1710
+ auto now = std::chrono::system_clock::now();
1711
+ auto time = std::chrono::system_clock::to_time_t(now);
1712
+ std::tm tm_utc;
1713
+ #ifdef _WIN32
1714
+ gmtime_s(&tm_utc, &time);
1715
+ #else
1716
+ gmtime_r(&time, &tm_utc);
1717
+ #endif
1718
+
1719
+ char buf[256];
1720
+ size_t len = std::strftime(buf, sizeof(buf), format.c_str(), &tm_utc);
1721
+ if (len == 0) {
1722
+ return {{"error", "invalid format string"}};
1723
+ }
1724
+
1725
+ return {{"result", std::string(buf, len)}};
1726
+ }
1727
+ };
1728
+
1729
+ //
1730
+ // get_info: returns runtime info (OS name/version and cwd)
1731
+ //
1732
+
1733
+ static constexpr size_t SERVER_TOOL_GET_INFO_MAX_OUTPUT = 4096;
1734
+ static constexpr int SERVER_TOOL_GET_INFO_TIMEOUT = 5; // seconds
1735
+
1736
+ struct server_tool_get_info : server_tool {
1737
+ server_tool_get_info() {
1738
+ name = "get_info";
1739
+ display_name = "Get Runtime Info";
1740
+ uses_cwd = true;
1741
+ permission_write = false;
1742
+ }
1743
+
1744
+ json get_definition() const override {
1745
+ return {
1746
+ {"type", "function"},
1747
+ {"function", {
1748
+ {"name", name},
1749
+ {"description", "Returns runtime info: the OS name/version and the current working directory"},
1750
+ {"parameters", {
1751
+ {"type", "object"},
1752
+ {"properties", json::object()},
1753
+ }},
1754
+ }},
1755
+ };
1756
+ }
1757
+
1758
+ json invoke(json params, server_tool::stream *) const override {
1759
+ auto io = make_tools_io(params);
1760
+
1761
+ // inside an isolate, we always use the linux command
1762
+ #ifdef _WIN32
1763
+ std::vector<std::string> args = !json_value(params, "runtime", std::string()).empty()
1764
+ ? std::vector<std::string>{"uname", "-a"}
1765
+ : std::vector<std::string>{"cmd", "/c", "ver"};
1766
+ #else
1767
+ std::vector<std::string> args = {"uname", "-a"};
1768
+ #endif
1769
+
1770
+ auto res = io->run(args, SERVER_TOOL_GET_INFO_MAX_OUTPUT, SERVER_TOOL_GET_INFO_TIMEOUT);
1771
+ // "ver" prints a blank line before the version, so the output is stripped on both ends;
1772
+ // a failed spawn or a timeout leaves a diagnostic in res.output, which is not an OS name
1773
+ std::string os_info = res.exit_code == 0 && !res.timed_out ? string_strip(res.output) : "unknown";
1774
+
1775
+ std::string cwd = json_value(params, "cwd", std::string());
1776
+ if (cwd.empty()) {
1777
+ if (json_value(params, "runtime", std::string()).empty()) {
1778
+ std::error_code ec;
1779
+ cwd = path_to_utf8(fs::current_path(ec));
1780
+ } else {
1781
+ auto pwd = io->run({"pwd"}, SERVER_TOOL_GET_INFO_MAX_OUTPUT, SERVER_TOOL_GET_INFO_TIMEOUT);
1782
+ cwd = pwd.exit_code == 0 && !pwd.timed_out ? string_strip(pwd.output) : "unknown";
1783
+ }
1784
+ }
1785
+
1786
+ return {
1787
+ {"os", os_info},
1788
+ {"cwd", cwd},
1789
+ };
1790
+ }
1791
+ };
1792
+
1793
+ struct server_tool_stream_result : server_task_result {
1794
+ std::string chunk;
1795
+ bool done = false;
1796
+ std::string error_msg;
1797
+
1798
+ json to_json() override {
1799
+ if (!done) {
1800
+ return {{"chunk", chunk}};
1801
+ } else {
1802
+ json result = {{"done", true}};
1803
+ if (!error_msg.empty()) {
1804
+ result["error"] = error_msg;
1805
+ }
1806
+ return result;
1807
+ }
1808
+ }
1809
+ };
1810
+
1811
+ void server_tool::stream::push(const std::string & chunk) {
1812
+ if (chunk.empty()) return;
1813
+ auto r = std::make_unique<server_tool_stream_result>();
1814
+ r->id = id;
1815
+ r->chunk = chunk;
1816
+ qr.send(std::move(r));
1817
+ }
1818
+
1819
+ struct server_tools_res : server_http_res {
1820
+ std::thread worker;
1821
+ server_response * qr = nullptr; // set only for streaming responses
1822
+ int id = -1;
1823
+
1824
+ ~server_tools_res() override {
1825
+ if (worker.joinable()) {
1826
+ worker.join();
1827
+ }
1828
+ if (qr) {
1829
+ qr->remove_waiting_task_id(id);
1830
+ }
1831
+ }
1832
+ };
1833
+
1834
+ //
1835
+ // server_mcp_tool: exposes one tool from a running MCP server as a server_tool.
1836
+ //
1837
+ struct server_mcp_tool : server_tool {
1838
+ std::string server_name;
1839
+ std::string tool_name;
1840
+ server_mcp_tool_def def;
1841
+ server_mcp & mcp_mgr;
1842
+
1843
+ server_mcp_tool(server_mcp_tool_def d, server_mcp & mgr)
1844
+ : server_name(d.server_name)
1845
+ , tool_name(d.name)
1846
+ , def(std::move(d))
1847
+ , mcp_mgr(mgr)
1848
+ {
1849
+ name = server_name + "_" + tool_name;
1850
+ display_name = name;
1851
+ permission_write = false;
1852
+ support_stream = false;
1853
+ }
1854
+
1855
+ std::string type() const override { return "mcp"; }
1856
+
1857
+ json get_definition() const override {
1858
+ json schema = def.input_schema;
1859
+ if (schema.is_null() || !schema.is_object()) {
1860
+ schema = json::object();
1861
+ }
1862
+ return {
1863
+ {"type", "function"},
1864
+ {"function", {
1865
+ {"name", name},
1866
+ {"description", def.description},
1867
+ {"parameters", schema},
1868
+ }},
1869
+ };
1870
+ }
1871
+
1872
+ json invoke(json params, server_tool::stream *) const override {
1873
+ return mcp_mgr.call_tool(server_name, tool_name, params);
1874
+ }
1875
+ };
1876
+
1877
+ // resolves --tools-runtime into the isolate that every tool call runs through
1878
+ // spec() returns the runtime string make_tools_io() takes, and runs once per tool call
1879
+ struct server_tools_runtime {
1880
+ virtual ~server_tools_runtime() = default;
1881
+ virtual std::string spec() = 0;
1882
+ };
1883
+
1884
+ // a target that already exists and needs no lifecycle
1885
+ // the spec is validated once at startup, then passed straight through
1886
+ struct server_tools_static_runtime : server_tools_runtime {
1887
+ explicit server_tools_static_runtime(std::string spec) : runtime_spec(std::move(spec)) {}
1888
+ std::string spec() override { return runtime_spec; }
1889
+
1890
+ private:
1891
+ std::string runtime_spec;
1892
+ };
1893
+
1894
+ // owns the container the tools run in, as set by --tools-runtime "<engine>:<image>"
1895
+ // it is spawned here and stopped when the server exits
1896
+ struct server_tools_container_runtime : server_tools_runtime {
1897
+ server_tools_container_runtime(const server_tools_container_runtime &) = delete;
1898
+
1899
+ explicit server_tools_container_runtime(const std::string & spec) {
1900
+ container_runtime_spec parsed;
1901
+ if (!container_runtime_spec::parse(spec, parsed)) {
1902
+ throw std::runtime_error("unknown --tools-runtime option: " + spec);
1903
+ }
1904
+
1905
+ bin = parsed.bin;
1906
+ image = parsed.arg;
1907
+ if (image.empty()) {
1908
+ throw std::runtime_error("--tools-runtime " + bin + ":<image> requires an image name");
1909
+ }
1910
+ spawn();
1911
+ }
1912
+
1913
+ ~server_tools_container_runtime() override {
1914
+ // closing stdin signals the container's shell (its pid 1) to exit; --rm then removes it
1915
+ proc.close_stdin();
1916
+ proc.join();
1917
+ }
1918
+
1919
+ // respawns a container that died on its own, so the returned spec always names a running one
1920
+ std::string spec() override {
1921
+ std::lock_guard<std::mutex> lock(mutex);
1922
+ if (!proc.alive()) {
1923
+ SRV_WRN("%s tools runtime container \"%s\" died, respawning\n", bin.c_str(), container_id.c_str());
1924
+ spawn();
1925
+ }
1926
+ return bin + "-container:" + container_id;
1927
+ }
1928
+
1929
+ private:
1930
+ std::string bin;
1931
+ std::string image;
1932
+ std::string container_id;
1933
+ common_subproc proc; // `<engine> run` client that keeps the container alive
1934
+ std::mutex mutex;
1935
+
1936
+ // spawns "<engine> run --rm -i <image> sh" and keeps its stdin open; the shell blocks reading stdin,
1937
+ // so the container stays alive until we close it (see destructor) or it is killed from the outside
1938
+ void spawn() {
1939
+ // create() writes over the handle it is given, so the previous one is released first
1940
+ proc.join();
1941
+
1942
+ std::error_code ec;
1943
+ fs::path cidfile = fs::temp_directory_path(ec) / string_format(
1944
+ "llama-tools-runtime-cid-%zu.tmp", std::hash<std::thread::id>{}(std::this_thread::get_id()));
1945
+ fs::remove(cidfile, ec);
1946
+
1947
+ std::vector<std::string> args = {bin, "run", "--rm", "-i", "--cidfile", path_to_utf8(cidfile), image, "sh"};
1948
+ int options = subprocess_option_no_window
1949
+ | subprocess_option_inherit_environment
1950
+ | subprocess_option_search_user_path;
1951
+ if (!proc.create(args, options)) {
1952
+ throw std::runtime_error("failed to spawn " + bin + " container for tools runtime (image: " + image + ")");
1953
+ }
1954
+
1955
+ std::string cid;
1956
+ for (int i = 0; i < 100 && cid.empty(); i++) {
1957
+ std::ifstream f(cidfile);
1958
+ if (f) std::getline(f, cid);
1959
+ if (cid.empty()) std::this_thread::sleep_for(std::chrono::milliseconds(100));
1960
+ }
1961
+ fs::remove(cidfile, ec);
1962
+ if (cid.empty()) {
1963
+ proc.terminate();
1964
+ throw std::runtime_error("timed out waiting for " + bin + " container to start (image: " + image + ")");
1965
+ }
1966
+ container_id = cid;
1967
+ }
1968
+ };
1969
+
1970
+ static server_tool & find_tool(std::vector<std::unique_ptr<server_tool>> & tools, const std::string & name, bool require_stream) {
1971
+ for (auto & t : tools) {
1972
+ if (t->name == name) {
1973
+ if (require_stream && !t->support_stream) {
1974
+ throw std::invalid_argument(string_format("tool \"%s\" does not support stream = true", name.c_str()));
1975
+ }
1976
+ return *t;
1977
+ }
1978
+ }
1979
+ throw std::invalid_argument(string_format("unknown tool \"%s\"", name.c_str()));
1980
+ }
1981
+
1982
+ //
1983
+ // public API
1984
+ //
1985
+
1986
+ static std::vector<std::unique_ptr<server_tool>> build_tools() {
1987
+ std::vector<std::unique_ptr<server_tool>> tools;
1988
+ tools.push_back(std::make_unique<server_tool_read_file>());
1989
+ tools.push_back(std::make_unique<server_tool_file_glob_search>());
1990
+ tools.push_back(std::make_unique<server_tool_grep_search>());
1991
+ tools.push_back(std::make_unique<server_tool_exec_shell_command>());
1992
+ tools.push_back(std::make_unique<server_tool_write_file>());
1993
+ tools.push_back(std::make_unique<server_tool_edit_file>());
1994
+ tools.push_back(std::make_unique<server_tool_get_datetime>());
1995
+ tools.push_back(std::make_unique<server_tool_get_info>());
1996
+ return tools;
1997
+ }
1998
+
1999
+ static std::string str_to_lower(const std::string & value) {
2000
+ std::string lowered(value.size(), '\0');
2001
+ std::transform(value.begin(), value.end(), lowered.begin(), [](unsigned char c) { return std::tolower(c); });
2002
+ return lowered;
2003
+ }
2004
+
2005
+ static std::string get_header(const std::map<std::string, std::string> & headers, const std::string & key, std::string default_value = "") {
2006
+ const auto lowered_key = str_to_lower(key);
2007
+ for (const auto & h : headers) {
2008
+ if (str_to_lower(h.first) == lowered_key) {
2009
+ return h.second;
2010
+ }
2011
+ }
2012
+ return default_value;
2013
+ }
2014
+
2015
+ server_tools::server_tools() = default;
2016
+ server_tools::~server_tools() = default;
2017
+
2018
+ // the "<engine>:<image>" form owns a container lifecycle
2019
+ // anything else names an existing target, so only its spec is validated here at startup
2020
+ static std::unique_ptr<server_tools_runtime> make_tools_runtime(const std::string & spec) {
2021
+ container_runtime_spec parsed;
2022
+ if (container_runtime_spec::parse(spec, parsed) && !parsed.attach) {
2023
+ return std::make_unique<server_tools_container_runtime>(spec);
2024
+ }
2025
+ make_tools_io({{"runtime", spec}}); // nothing to own, just reject a bad spec now
2026
+ return std::make_unique<server_tools_static_runtime>(spec);
2027
+ }
2028
+
2029
+ void server_tools::setup(const std::vector<std::string> & enabled_tools,
2030
+ server_mcp & mcp_mgr,
2031
+ const std::string & tools_runtime) {
2032
+ if (!tools_runtime.empty()) {
2033
+ runtime = make_tools_runtime(tools_runtime);
2034
+ }
2035
+
2036
+ if (!enabled_tools.empty()) {
2037
+ if (!common_subproc::is_supported()) {
2038
+ throw std::runtime_error("subprocess is not enabled on this build");
2039
+ }
2040
+
2041
+ std::unordered_set<std::string> enabled_set(enabled_tools.begin(), enabled_tools.end());
2042
+ auto all_tools = build_tools();
2043
+
2044
+ // collect all known tool names for validation
2045
+ std::vector<std::string> known_names;
2046
+ known_names.reserve(all_tools.size());
2047
+ for (const auto & t : all_tools) {
2048
+ known_names.push_back(t->name);
2049
+ }
2050
+
2051
+ // validate that every requested tool is known
2052
+ for (const auto & name : enabled_tools) {
2053
+ if (name == "all") continue;
2054
+ if (std::find(known_names.begin(), known_names.end(), name) == known_names.end()) {
2055
+ throw std::runtime_error(string_format(
2056
+ "unknown tool \"%s\". available tools: %s",
2057
+ name.c_str(),
2058
+ string_join(known_names, ", ").c_str()));
2059
+ }
2060
+ }
2061
+
2062
+ tools.clear();
2063
+ for (auto & t : all_tools) {
2064
+ if (enabled_set.count(t->name) > 0 || enabled_set.count("all") > 0) {
2065
+ tools.push_back(std::move(t));
2066
+ }
2067
+ }
2068
+ }
2069
+
2070
+ // append MCP tools, skipping any that collide with a built-in or another MCP tool of the same "<server>_<tool>" name
2071
+ if (!mcp_mgr.empty()) {
2072
+ std::unordered_set<std::string> seen_names;
2073
+ for (auto & t : tools) {
2074
+ seen_names.insert(t->name);
2075
+ }
2076
+ size_t n_added = 0;
2077
+ for (const auto & def : mcp_mgr.list_tools()) {
2078
+ std::string mcp_name = def.server_name + "_" + def.name;
2079
+ if (seen_names.count(mcp_name)) {
2080
+ SRV_WRN("MCP tool \"%s\" from server \"%s\" collides with an existing tool, skipping\n",
2081
+ mcp_name.c_str(), def.server_name.c_str());
2082
+ continue;
2083
+ }
2084
+ seen_names.insert(mcp_name);
2085
+ tools.push_back(std::make_unique<server_mcp_tool>(def, mcp_mgr));
2086
+ n_added++;
2087
+ }
2088
+ if (n_added > 0) {
2089
+ SRV_INF("Added %zu MCP tools\n", n_added);
2090
+ }
2091
+ }
2092
+
2093
+ handle_get = [this](const server_http_req &) -> server_http_res_ptr {
2094
+ auto res = std::make_unique<server_http_res>();
2095
+ try {
2096
+ json result = json::array();
2097
+ for (const auto & t : tools) {
2098
+ result.push_back(t->to_json());
2099
+ }
2100
+ res->data = safe_json_to_str(result);
2101
+ } catch (const std::exception & e) {
2102
+ SRV_ERR("got exception: %s\n", e.what());
2103
+ res->status = 500;
2104
+ res->data = safe_json_to_str(format_error_response(e.what(), ERROR_TYPE_SERVER));
2105
+ }
2106
+ return res;
2107
+ };
2108
+
2109
+ handle_post = [this](const server_http_req & req) -> server_http_res_ptr {
2110
+ auto res = std::make_unique<server_tools_res>();
2111
+ try {
2112
+ json body = json::parse(req.body);
2113
+ std::string tool_name = body.at("tool").get<std::string>();
2114
+ json params = body.value("params", json::object());
2115
+ bool stream = body.value("stream", false);
2116
+
2117
+ // accept x-tool-cwd header to override of the process
2118
+ if (params.contains("cwd")) {
2119
+ params.erase("cwd");
2120
+ }
2121
+ auto cwd = get_header(req.headers, "x-tool-cwd");
2122
+ if (!cwd.empty()) {
2123
+ params["cwd"] = cwd;
2124
+ }
2125
+
2126
+ // accept x-tool-runtime header to route tool I/O through an isolate, e.g. "docker-container:<id>";
2127
+ // falls back to the --tools-runtime isolate, if configured
2128
+ if (params.contains("runtime")) {
2129
+ params.erase("runtime");
2130
+ }
2131
+ auto runtime_header = get_header(req.headers, "x-tool-runtime");
2132
+ if (!runtime_header.empty()) {
2133
+ params["runtime"] = runtime_header;
2134
+ } else if (runtime) {
2135
+ params["runtime"] = runtime->spec();
2136
+ }
2137
+
2138
+ server_tool & tool = find_tool(tools, tool_name, stream);
2139
+
2140
+ if (stream) {
2141
+ int id = res_id.fetch_add(1);
2142
+ queue_res.add_waiting_task_id(id);
2143
+ res->qr = &queue_res;
2144
+ res->id = id;
2145
+
2146
+ res->worker = std::thread([this, id, &req, &tool, params]() mutable {
2147
+ server_tool::stream st{queue_res, id, [&req]() {
2148
+ return !req.should_stop();
2149
+ }};
2150
+
2151
+ auto done = std::make_unique<server_tool_stream_result>();
2152
+ try {
2153
+ tool.invoke(params, &st);
2154
+ } catch (const std::exception & e) {
2155
+ done->error_msg = e.what();
2156
+ } catch (...) {
2157
+ done->error_msg = "An unknown error occurred";
2158
+ }
2159
+ done->id = st.id;
2160
+ done->done = true;
2161
+ st.qr.send(std::move(done));
2162
+ });
2163
+
2164
+ res->content_type = "text/event-stream";
2165
+ res->status = 200;
2166
+ res->next = [this, id](std::string & output) -> bool {
2167
+ auto result = queue_res.recv(id);
2168
+ auto * r = dynamic_cast<server_tool_stream_result *>(result.get());
2169
+ GGML_ASSERT(r != nullptr);
2170
+ output = "data: " + safe_json_to_str(r->to_json()) + "\n\n";
2171
+ if (r->done) {
2172
+ queue_res.remove_waiting_task_id(id);
2173
+ return false;
2174
+ }
2175
+ return true;
2176
+ };
2177
+ } else {
2178
+ json result = tool.invoke(params, nullptr);
2179
+ res->status = 200;
2180
+ res->data = safe_json_to_str(result);
2181
+ }
2182
+ } catch (const json::exception & e) {
2183
+ res->status = 400;
2184
+ res->data = safe_json_to_str(format_error_response(e.what(), ERROR_TYPE_INVALID_REQUEST));
2185
+ } catch (const std::invalid_argument & e) {
2186
+ res->status = 404;
2187
+ res->data = safe_json_to_str(format_error_response(e.what(), ERROR_TYPE_INVALID_REQUEST));
2188
+ } catch (const std::exception & e) {
2189
+ SRV_ERR("got exception: %s\n", e.what());
2190
+ res->status = 500;
2191
+ res->data = safe_json_to_str(format_error_response(e.what(), ERROR_TYPE_SERVER));
2192
+ }
2193
+ return res;
2194
+ };
2195
+ }
tools/server/server-tools.h ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include "server-common.h"
4
+ #include "server-http.h"
5
+ #include "server-queue.h"
6
+ #include "server-mcp.h"
7
+
8
+ #include <atomic>
9
+ #include <functional>
10
+ #include <memory>
11
+
12
+ struct server_tool {
13
+ std::string name;
14
+ std::string display_name;
15
+ bool permission_write = false;
16
+ bool support_stream = false; // if true, output can be streamed
17
+ bool uses_cwd = false; // if true, the tool resolves paths and runs against the working directory
18
+
19
+ virtual ~server_tool() = default;
20
+ virtual json get_definition() const = 0;
21
+ virtual std::string type() const { return "builtin"; }
22
+
23
+ struct stream {
24
+ server_response & qr;
25
+ int id;
26
+ std::function<bool()> alive;
27
+ void push(const std::string & chunk);
28
+ };
29
+ virtual json invoke(json params, stream * st = nullptr) const = 0;
30
+
31
+ json to_json() const;
32
+ };
33
+
34
+ struct server_tools_runtime; // impl detail, defined in server-tools.cpp
35
+
36
+ struct server_tools {
37
+ std::vector<std::unique_ptr<server_tool>> tools;
38
+
39
+ // for streaming
40
+ server_response queue_res;
41
+ std::atomic<int> res_id{0};
42
+
43
+ // set when --tools-runtime is configured; routes every tool call through an isolate
44
+ std::unique_ptr<server_tools_runtime> runtime;
45
+
46
+ void setup(const std::vector<std::string> & enabled_tools,
47
+ server_mcp & mcp_mgr,
48
+ const std::string & tools_runtime);
49
+
50
+ server_http_context::handler_t handle_get;
51
+ server_http_context::handler_t handle_post;
52
+
53
+ server_tools();
54
+ ~server_tools();
55
+ };
tools/server/server.cpp ADDED
@@ -0,0 +1,537 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "server-context.h"
2
+ #include "server-http.h"
3
+ #include "server-models.h"
4
+ #include "server-cors-proxy.h"
5
+ #include "server-stream.h"
6
+ #include "server-tools.h"
7
+
8
+ #include "arg.h"
9
+ #include "build-info.h"
10
+ #include "common.h"
11
+ #include "fit.h"
12
+ #include "llama.h"
13
+ #include "log.h"
14
+
15
+ #include <atomic>
16
+ #include <clocale>
17
+ #include <exception>
18
+ #include <signal.h>
19
+ #include <thread> // for std::thread::hardware_concurrency
20
+
21
+ #if defined(_WIN32)
22
+ #include <windows.h>
23
+ #endif
24
+
25
+ static std::function<void(int)> shutdown_handler;
26
+ static std::atomic_flag is_terminating = ATOMIC_FLAG_INIT;
27
+
28
+ static inline void signal_handler(int signal) {
29
+ if (is_terminating.test_and_set()) {
30
+ // in case it hangs, we can force terminate the server by hitting Ctrl+C twice
31
+ // this is for better developer experience, we can remove when the server is stable enough
32
+ fprintf(stderr, "Received second interrupt, terminating immediately.\n");
33
+ exit(1);
34
+ }
35
+
36
+ shutdown_handler(signal);
37
+ }
38
+
39
+ // satisfies -Wmissing-declarations (used by llama command)
40
+ int llama_server(int argc, char ** argv);
41
+
42
+ // to be used via CLI (argc / argv are used by router mode only)
43
+ int llama_server(common_params & params, int argc, char ** argv);
44
+ void llama_server_terminate();
45
+ void llama_server_terminate() {
46
+ if (shutdown_handler) {
47
+ shutdown_handler(0);
48
+ }
49
+ }
50
+
51
+
52
+ // wrapper function that handles exceptions and logs errors
53
+ // this is to make sure handler_t never throws exceptions; instead, it returns an error response
54
+ static server_http_context::handler_t ex_wrapper(server_http_context::handler_t func) {
55
+ return [func = std::move(func)](const server_http_req & req) -> server_http_res_ptr {
56
+ std::string message;
57
+ error_type error;
58
+ try {
59
+ return func(req);
60
+ } catch (const std::invalid_argument & e) {
61
+ // treat invalid_argument as invalid request (400)
62
+ error = ERROR_TYPE_INVALID_REQUEST;
63
+ message = e.what();
64
+ } catch (const std::exception & e) {
65
+ // treat other exceptions as server error (500)
66
+ error = ERROR_TYPE_SERVER;
67
+ message = e.what();
68
+ } catch (...) {
69
+ error = ERROR_TYPE_SERVER;
70
+ message = "unknown error";
71
+ }
72
+
73
+ auto res = std::make_unique<server_http_res>();
74
+ res->status = 500;
75
+ try {
76
+ json error_data = format_error_response(message, error);
77
+ res->status = json_value(error_data, "code", 500);
78
+ res->data = safe_json_to_str({{ "error", error_data }});
79
+ SRV_WRN("got exception: %s\n", res->data.c_str());
80
+ } catch (const std::exception & e) {
81
+ SRV_ERR("got another exception: %s | while handling exception: %s\n", e.what(), message.c_str());
82
+ res->data = "Internal Server Error";
83
+ }
84
+ return res;
85
+ };
86
+ }
87
+
88
+ int llama_server(int argc, char ** argv) {
89
+ std::setlocale(LC_NUMERIC, "C");
90
+
91
+ #ifndef _WIN32
92
+ // Ignore SIGPIPE so the server does not crash if a child (MCP server, tools runtime) exits while we are writing to its stdin
93
+ signal(SIGPIPE, SIG_IGN);
94
+ #endif
95
+
96
+ // own arguments required by this example
97
+ common_params params;
98
+
99
+ common_init();
100
+
101
+ // start the stream session manager GC right after common init, before any HTTP route can
102
+ // touch it. lifecycle is symmetric, stop_gc() runs in clean_up() before backend free
103
+ server_stream_session_manager_start();
104
+
105
+ if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_SERVER)) {
106
+ return 1;
107
+ }
108
+
109
+ llama_backend_init();
110
+ llama_numa_init(params.numa);
111
+
112
+ return llama_server(params, argc, argv);
113
+ }
114
+
115
+ int llama_server(common_params & params, int argc, char ** argv) {
116
+ bool is_run_by_cli = (argv == nullptr);
117
+
118
+ common_models_handler models_handler;
119
+
120
+ // note: router mode also accepts -hf remote-preset, so we need to check that first
121
+ if (!is_run_by_cli && !params.model.hf_repo.empty()) {
122
+ try {
123
+ models_handler = common_models_handler_init(params, LLAMA_EXAMPLE_SERVER);
124
+ if (common_models_handler_is_preset_repo(models_handler)) {
125
+ // apply the preset and start the server in router mode
126
+ common_models_handler_apply(models_handler, params);
127
+ }
128
+ } catch (const std::exception & e) {
129
+ SRV_ERR("failed to fetch model metadata: %s\n", e.what());
130
+ return 1;
131
+ }
132
+ }
133
+
134
+ // router server never loads a model and must not touch the GPU
135
+ const bool is_router_server = params.model.path.empty()
136
+ && params.model.hf_repo.empty();
137
+
138
+ // skip device enumeration so the CUDA primary context stays uncreated
139
+ common_params_print_info(params, !is_router_server);
140
+
141
+ if (!is_router_server) {
142
+ // validate batch size for embeddings
143
+ // embeddings require all tokens to be processed in a single ubatch
144
+ // see https://github.com/ggml-org/llama.cpp/issues/12836
145
+ if (params.embedding && params.n_batch > params.n_ubatch) {
146
+ SRV_WRN("embeddings enabled with n_batch (%d) > n_ubatch (%d)\n", params.n_batch, params.n_ubatch);
147
+ SRV_WRN("setting n_batch = n_ubatch = %d to avoid assertion failure\n", params.n_ubatch);
148
+ params.n_batch = params.n_ubatch;
149
+ }
150
+
151
+ if (params.n_parallel < 0) {
152
+ SRV_TRC("%s", "n_parallel is set to auto, using n_parallel = 4 and kv_unified = true\n");
153
+
154
+ params.n_parallel = 4;
155
+ params.kv_unified = true;
156
+ }
157
+ }
158
+
159
+ // for consistency between server router mode and single-model mode, we set the same model name as alias
160
+ auto model_name = params.model.get_name();
161
+ if (params.model_alias.empty() && !model_name.empty()) {
162
+ params.model_alias.insert(model_name);
163
+ }
164
+
165
+ // note: this is guaranteed to out-live ctx_http and tools
166
+ server_mcp mcp_mgr;
167
+
168
+ // struct that contains llama context and inference
169
+ server_context ctx_server;
170
+
171
+ server_http_context ctx_http;
172
+ if (!ctx_http.init(params)) {
173
+ SRV_ERR("%s", "failed to initialize HTTP server\n");
174
+ return 1;
175
+ }
176
+
177
+ //
178
+ // Router
179
+ //
180
+
181
+ // register API routes
182
+ server_child child; // only used in non-router mode
183
+ server_routes routes(params, ctx_server);
184
+ server_tools tools;
185
+
186
+ std::optional<server_models_routes> models_routes{};
187
+ if (is_router_server) {
188
+ // setup server instances manager
189
+ try {
190
+ models_routes.emplace(params, argc, argv);
191
+ } catch (const std::exception & e) {
192
+ SRV_ERR("failed to initialize router models: %s\n", e.what());
193
+ return 1;
194
+ }
195
+
196
+ // proxy handlers
197
+ // note: routes.get_health stays the same
198
+ routes.get_metrics = models_routes->proxy_get;
199
+ routes.post_props = models_routes->proxy_post;
200
+ routes.post_completions = models_routes->proxy_post;
201
+ routes.post_completions_oai = models_routes->proxy_post;
202
+ routes.post_chat_completions = models_routes->proxy_post;
203
+ routes.post_control = models_routes->proxy_post;
204
+ routes.post_responses_oai = models_routes->proxy_post;
205
+ routes.post_transcriptions_oai = models_routes->proxy_post;
206
+ routes.post_anthropic_messages = models_routes->proxy_post;
207
+ routes.post_anthropic_count_tokens = models_routes->proxy_post;
208
+ routes.post_infill = models_routes->proxy_post;
209
+ routes.post_embeddings = models_routes->proxy_post;
210
+ routes.post_embeddings_oai = models_routes->proxy_post;
211
+ routes.post_rerank = models_routes->proxy_post;
212
+ routes.post_tokenize = models_routes->proxy_post;
213
+ routes.post_detokenize = models_routes->proxy_post;
214
+ routes.post_apply_template = models_routes->proxy_post;
215
+ routes.post_chat_completions_tok = models_routes->proxy_post;
216
+ routes.post_responses_tok_oai = models_routes->proxy_post;
217
+ routes.get_lora_adapters = models_routes->proxy_get;
218
+ routes.post_lora_adapters = models_routes->proxy_post;
219
+ routes.get_slots = models_routes->proxy_get;
220
+ routes.post_slots = models_routes->proxy_post;
221
+
222
+ // custom routes for router
223
+ routes.get_props = models_routes->get_router_props;
224
+ routes.get_models = models_routes->get_router_models;
225
+
226
+ ctx_http.post("/models", ex_wrapper(models_routes->post_router_models));
227
+ ctx_http.post("/models/load", ex_wrapper(models_routes->post_router_models_load));
228
+ ctx_http.post("/models/unload", ex_wrapper(models_routes->post_router_models_unload));
229
+ ctx_http.get ("/models/sse", ex_wrapper(models_routes->get_router_models_sse));
230
+ ctx_http.del ("/models", ex_wrapper(models_routes->del_router_models));
231
+ }
232
+
233
+ ctx_http.get ("/health", ex_wrapper(routes.get_health)); // public endpoint (no API key check)
234
+ ctx_http.get ("/v1/health", ex_wrapper(routes.get_health)); // public endpoint (no API key check)
235
+ ctx_http.get ("/metrics", ex_wrapper(routes.get_metrics));
236
+ ctx_http.get ("/props", ex_wrapper(routes.get_props));
237
+ ctx_http.post("/props", ex_wrapper(routes.post_props));
238
+ ctx_http.get ("/models", ex_wrapper(routes.get_models)); // public endpoint (no API key check)
239
+ ctx_http.get ("/v1/models", ex_wrapper(routes.get_models)); // public endpoint (no API key check)
240
+ ctx_http.post("/completion", ex_wrapper(routes.post_completions)); // legacy
241
+ ctx_http.post("/completions", ex_wrapper(routes.post_completions));
242
+ ctx_http.post("/v1/completions", ex_wrapper(routes.post_completions_oai));
243
+ ctx_http.post("/chat/completions", ex_wrapper(routes.post_chat_completions));
244
+ ctx_http.post("/v1/chat/completions", ex_wrapper(routes.post_chat_completions));
245
+ ctx_http.post("/v1/chat/completions/control", ex_wrapper(routes.post_control));
246
+ ctx_http.post("/v1/responses", ex_wrapper(routes.post_responses_oai));
247
+ ctx_http.post("/responses", ex_wrapper(routes.post_responses_oai));
248
+ ctx_http.post("/v1/audio/transcriptions", ex_wrapper(routes.post_transcriptions_oai));
249
+ ctx_http.post("/audio/transcriptions", ex_wrapper(routes.post_transcriptions_oai));
250
+ ctx_http.post("/v1/messages", ex_wrapper(routes.post_anthropic_messages)); // anthropic messages API
251
+ ctx_http.post("/infill", ex_wrapper(routes.post_infill));
252
+ ctx_http.post("/embedding", ex_wrapper(routes.post_embeddings)); // legacy
253
+ ctx_http.post("/embeddings", ex_wrapper(routes.post_embeddings));
254
+ ctx_http.post("/v1/embeddings", ex_wrapper(routes.post_embeddings_oai));
255
+ ctx_http.post("/rerank", ex_wrapper(routes.post_rerank));
256
+ ctx_http.post("/reranking", ex_wrapper(routes.post_rerank));
257
+ ctx_http.post("/v1/rerank", ex_wrapper(routes.post_rerank));
258
+ ctx_http.post("/v1/reranking", ex_wrapper(routes.post_rerank));
259
+ ctx_http.post("/tokenize", ex_wrapper(routes.post_tokenize));
260
+ ctx_http.post("/detokenize", ex_wrapper(routes.post_detokenize));
261
+ ctx_http.post("/apply-template", ex_wrapper(routes.post_apply_template));
262
+ // token counting
263
+ ctx_http.post("/chat/completions/input_tokens", ex_wrapper(routes.post_chat_completions_tok));
264
+ ctx_http.post("/v1/chat/completions/input_tokens", ex_wrapper(routes.post_chat_completions_tok));
265
+ ctx_http.post("/responses/input_tokens", ex_wrapper(routes.post_responses_tok_oai));
266
+ ctx_http.post("/v1/responses/input_tokens", ex_wrapper(routes.post_responses_tok_oai));
267
+ ctx_http.post("/v1/messages/count_tokens", ex_wrapper(routes.post_anthropic_count_tokens)); // anthropic token counting
268
+ // LoRA adapters hotswap
269
+ ctx_http.get ("/lora-adapters", ex_wrapper(routes.get_lora_adapters));
270
+ ctx_http.post("/lora-adapters", ex_wrapper(routes.post_lora_adapters));
271
+ // Save & load slots
272
+ ctx_http.get ("/slots", ex_wrapper(routes.get_slots));
273
+ ctx_http.post("/slots/:id_slot", ex_wrapper(routes.post_slots));
274
+
275
+ // resumable streaming: a child binds the local session factories, the router binds
276
+ // proxies that resolve the owning child, see server-stream.h
277
+ server_http_context::handler_t stream_get_h;
278
+ server_http_context::handler_t streams_lookup_h;
279
+ server_http_context::handler_t stream_delete_h;
280
+ if (is_router_server) {
281
+ stream_get_h = models_routes->router_stream_get;
282
+ streams_lookup_h = models_routes->router_streams_lookup;
283
+ stream_delete_h = models_routes->router_stream_delete;
284
+ } else {
285
+ stream_get_h = server_stream_make_get_handler();
286
+ streams_lookup_h = server_stream_make_lookup_handler();
287
+ stream_delete_h = server_stream_make_delete_handler();
288
+ }
289
+ ctx_http.get ("/v1/stream", ex_wrapper(stream_get_h));
290
+ ctx_http.post("/v1/streams/lookup", ex_wrapper(streams_lookup_h));
291
+ ctx_http.del ("/v1/stream", ex_wrapper(stream_delete_h));
292
+
293
+ // Google Cloud Platform (Vertex AI) compat
294
+ ctx_http.register_gcp_compat();
295
+
296
+ // return 403 for disabled features
297
+ server_http_context::handler_t res_403 = [](const server_http_req &) {
298
+ auto res = std::make_unique<server_http_res>();
299
+ res->status = 403;
300
+ res->data = safe_json_to_str({
301
+ {"error", {
302
+ {"message", "this feature is disabled"},
303
+ {"type", "feature_disabled"},
304
+ }}
305
+ });
306
+ return res;
307
+ };
308
+
309
+ if (params.cors_origins == "*" && params.api_keys.empty()) {
310
+ SRV_WRN("%s", "-----------------\n");
311
+ SRV_WRN("%s", "CORS is set to allow all origins ('*') and no API key is set\n");
312
+ SRV_WRN("%s", "this can be a security risk (cross-origin attacks)\n");
313
+ SRV_WRN("%s", "more info: https://github.com/ggml-org/llama.cpp/pull/25655\n");
314
+ SRV_WRN("%s", "-----------------\n");
315
+ }
316
+
317
+ // CORS proxy (EXPERIMENTAL, only used by the Web UI for MCP)
318
+ std::vector<std::string> warn_names;
319
+ if (is_router_server) {
320
+ warn_names.push_back("router mode");
321
+ }
322
+
323
+ if (params.ui_mcp_proxy) {
324
+ ctx_http.get ("/cors-proxy", ex_wrapper(proxy_handler_get));
325
+ ctx_http.post("/cors-proxy", ex_wrapper(proxy_handler_post));
326
+ warn_names.push_back("MCP proxy (experimental)");
327
+ } else {
328
+ ctx_http.get ("/cors-proxy", ex_wrapper(res_403));
329
+ ctx_http.post("/cors-proxy", ex_wrapper(res_403));
330
+ }
331
+
332
+ try {
333
+ mcp_mgr.start(params);
334
+ } catch (const std::exception & e) {
335
+ SRV_ERR("MCP starting failed: %s\n", e.what());
336
+ return 1;
337
+ }
338
+
339
+ if (!params.server_tools.empty() || !mcp_mgr.empty()) {
340
+ try {
341
+ tools.setup(params.server_tools, mcp_mgr, params.server_tools_runtime);
342
+ } catch (const std::exception & e) {
343
+ SRV_ERR("tools setup failed: %s\n", e.what());
344
+ return 1;
345
+ }
346
+ ctx_http.get ("/tools", ex_wrapper(tools.handle_get));
347
+ ctx_http.post("/tools", ex_wrapper(tools.handle_post));
348
+ if (!params.server_tools.empty()) {
349
+ warn_names.push_back("built-in tools (experimental)");
350
+ }
351
+ if (!params.server_tools_runtime.empty()) {
352
+ warn_names.push_back("tools runtime (experimental)");
353
+ }
354
+ if (!mcp_mgr.empty()) {
355
+ warn_names.push_back("MCP servers (experimental)");
356
+ }
357
+ } else {
358
+ ctx_http.get ("/tools", ex_wrapper(res_403));
359
+ ctx_http.post("/tools", ex_wrapper(res_403));
360
+ }
361
+
362
+ if (warn_names.size() > 0) {
363
+ SRV_WRN("%s", "-----------------\n");
364
+ SRV_WRN("%s", "the following feature(s) are enabled:\n");
365
+ for (const auto & name : warn_names) {
366
+ SRV_WRN(" %s\n", name.c_str());
367
+ }
368
+ SRV_WRN("%s", "do not expose the server to untrusted environments\n");
369
+ SRV_WRN("%s", "-----------------\n");
370
+ }
371
+
372
+ //
373
+ // Handle downloading model
374
+ //
375
+
376
+ if (child.is_child() && child.get_mode() == SERVER_CHILD_MODE_DOWNLOAD) {
377
+ return child.run_download(params);
378
+ } else if (!is_router_server && !is_run_by_cli) {
379
+ // single-model mode (NOT spawned by router)
380
+ // if this is invoked by CLI, model downloading should be already handled
381
+ try {
382
+ common_models_handler_apply(models_handler, params);
383
+ } catch (const std::exception & e) {
384
+ SRV_ERR("failed to download model: %s\n", e.what());
385
+ return 1;
386
+ }
387
+ }
388
+
389
+ //
390
+ // Start the server
391
+ //
392
+
393
+ std::function<void()> clean_up;
394
+
395
+ if (is_router_server) {
396
+ SRV_INF("%s", "starting server in router mode. models will be automatically loaded on-demand\n");
397
+
398
+ clean_up = [&models_routes, &mcp_mgr]() {
399
+ SRV_INF("%s: cleaning up before exit...\n", __func__);
400
+ // stop the session GC first, it finalizes live sessions and wakes pending readers
401
+ server_stream_session_manager_stop();
402
+ if (models_routes.has_value()) {
403
+ models_routes->stopping.store(true); // maybe redundant, but just to be safe
404
+ models_routes->models.unload_all();
405
+ }
406
+ mcp_mgr.shutdown();
407
+ llama_backend_free();
408
+ };
409
+
410
+ if (!ctx_http.start()) {
411
+ clean_up();
412
+ SRV_ERR("%s", "exiting due to HTTP server error\n");
413
+ return 1;
414
+ }
415
+ ctx_http.is_ready.store(true);
416
+
417
+ shutdown_handler = [&](int) {
418
+ if (models_routes.has_value()) {
419
+ // important to disconnect any SSE clients
420
+ models_routes->stopping.store(true);
421
+ }
422
+ mcp_mgr.shutdown();
423
+ ctx_http.stop();
424
+ };
425
+
426
+ } else {
427
+ // setup clean up function, to be called before exit
428
+ clean_up = [&ctx_http, &ctx_server, &mcp_mgr]() {
429
+ SRV_INF("%s: cleaning up before exit...\n", __func__);
430
+ // stop the session GC first, it finalizes live sessions and wakes pending readers
431
+ server_stream_session_manager_stop();
432
+ ctx_http.stop();
433
+ ctx_server.terminate();
434
+ mcp_mgr.shutdown();
435
+ llama_backend_free();
436
+ };
437
+
438
+ // start the HTTP server before loading the model to be able to serve /health requests
439
+ if (!ctx_http.start()) {
440
+ clean_up();
441
+ SRV_ERR("%s", "exiting due to HTTP server error\n");
442
+ return 1;
443
+ }
444
+
445
+ // setup communication child --> router if necessary
446
+ if (child.is_child()) {
447
+ ctx_server.set_state_callback([&](server_state state, json payload) {
448
+ child.notify_to_router(server_state_to_str(state), payload);
449
+ });
450
+ }
451
+
452
+ if (!ctx_server.load_model(params)) {
453
+ clean_up();
454
+ if (ctx_http.thread.joinable()) {
455
+ ctx_http.thread.join();
456
+ }
457
+ SRV_ERR("%s", "exiting due to model loading error\n");
458
+ return 1;
459
+ }
460
+
461
+ routes.update_meta(ctx_server);
462
+ ctx_http.is_ready.store(true);
463
+
464
+ SRV_INF("%s", "model loaded\n");
465
+
466
+ shutdown_handler = [&](int) {
467
+ mcp_mgr.shutdown();
468
+ // this will unblock start_loop()
469
+ ctx_server.terminate();
470
+ };
471
+ }
472
+
473
+ // register signal handler if not running by CLI
474
+ if (!is_run_by_cli) {
475
+ #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
476
+ struct sigaction sigint_action;
477
+ sigint_action.sa_handler = signal_handler;
478
+ sigemptyset (&sigint_action.sa_mask);
479
+ sigint_action.sa_flags = 0;
480
+ sigaction(SIGINT, &sigint_action, NULL);
481
+ sigaction(SIGTERM, &sigint_action, NULL);
482
+ #elif defined (_WIN32)
483
+ auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
484
+ return (ctrl_type == CTRL_C_EVENT) ? (signal_handler(SIGINT), true) : false;
485
+ };
486
+ SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
487
+ #endif
488
+ }
489
+
490
+ SRV_INF("listening on %s\n", ctx_http.listening_address.c_str());
491
+
492
+ // TODO: remove this in the future
493
+ // check the string to also handle the .sock case
494
+ if (string_ends_with(ctx_http.listening_address, ":8080")) {
495
+ SRV_WRN("%s", "NOTICE: server default port will be changed to :9931 in a future release\n");
496
+ SRV_WRN("%s", " ref: https://github.com/ggml-org/llama.cpp/pull/26508\n");
497
+ }
498
+
499
+ if (is_router_server) {
500
+ if (!params.models_preset_hf.empty()) {
501
+ SRV_WRN( "NOTE: using preset.ini from HF repo '%s'\n", params.models_preset_hf.c_str());
502
+ SRV_WRN("%s", " please only use presets that you can trust! Unknown presets may be unsafe\n");
503
+ }
504
+
505
+ if (ctx_http.thread.joinable()) {
506
+ ctx_http.thread.join(); // keep the main thread alive
507
+ }
508
+
509
+ // when the HTTP server stops, clean up and exit
510
+ clean_up();
511
+ } else {
512
+ // optionally, notify router server that this instance is ready
513
+ std::thread monitor_thread;
514
+ if (child.is_child()) {
515
+ monitor_thread = child.setup(shutdown_handler);
516
+ child.notify_to_router(server_state_to_str(SERVER_STATE_READY), routes.get_model_info());
517
+ }
518
+
519
+ // this call blocks the main thread until queue_tasks.terminate() is called
520
+ ctx_server.start_loop();
521
+
522
+ clean_up();
523
+ if (ctx_http.thread.joinable()) {
524
+ ctx_http.thread.join();
525
+ }
526
+ if (monitor_thread.joinable()) {
527
+ monitor_thread.join();
528
+ }
529
+
530
+ auto * ll_ctx = ctx_server.get_llama_context();
531
+ if (ll_ctx != nullptr) {
532
+ common_memory_breakdown_print(ll_ctx);
533
+ }
534
+ }
535
+
536
+ return 0;
537
+ }
tools/server/tests/.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ .venv
2
+ tmp
tools/server/tests/README.md ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Server tests
2
+
3
+ Python based server tests scenario using [pytest](https://docs.pytest.org/en/stable/).
4
+
5
+ Tests target GitHub workflows job runners with 4 vCPU.
6
+
7
+ Note: If the host architecture inference speed is faster than GitHub runners one, parallel scenario may randomly fail.
8
+ To mitigate it, you can increase values in `n_predict`, `kv_size`.
9
+
10
+ ### Install dependencies
11
+
12
+ `pip install -r requirements.txt`
13
+
14
+ ### Run tests
15
+
16
+ 1. Build the server
17
+
18
+ ```shell
19
+ cd ../../..
20
+ cmake -B build
21
+ cmake --build build --target llama-server
22
+ ```
23
+
24
+ 2. Start the test: `./tests.sh`
25
+
26
+ It's possible to override some scenario steps values with environment variables:
27
+
28
+ | variable | description |
29
+ |--------------------------|------------------------------------------------------------------------------------------------|
30
+ | `PORT` | `context.server_port` to set the listening port of the server during scenario, default: `8080` |
31
+ | `LLAMA_SERVER_BIN_PATH` | to change the server binary path, default: `../../../build/bin/llama-server` |
32
+ | `DEBUG` | to enable steps and server verbose mode `--verbose` |
33
+ | `N_GPU_LAYERS` | number of model layers to offload to VRAM `-ngl --n-gpu-layers` |
34
+ | `LLAMA_CACHE` | by default server tests re-download models to the `tmp` subfolder. Set this to your cache (e.g. `$HOME/Library/Caches/llama.cpp` on Mac or `$HOME/.cache/llama.cpp` on Unix) to avoid this |
35
+
36
+ To run slow tests (will download many models, make sure to set `LLAMA_CACHE` if needed):
37
+
38
+ ```shell
39
+ SLOW_TESTS=1 ./tests.sh
40
+ ```
41
+
42
+ To run with stdout/stderr display in real time (verbose output, but useful for debugging):
43
+
44
+ ```shell
45
+ DEBUG=1 ./tests.sh -s -v -x
46
+ ```
47
+
48
+ To run all the tests in a file:
49
+
50
+ ```shell
51
+ ./tests.sh unit/test_chat_completion.py -v -x
52
+ ```
53
+
54
+ To run a single test:
55
+
56
+ ```shell
57
+ ./tests.sh unit/test_chat_completion.py::test_invalid_chat_completion_req
58
+ ```
59
+
60
+ Hint: You can compile and run test in single command, useful for local development:
61
+
62
+ ```shell
63
+ cmake --build build -j --target llama-server && ./tools/server/tests/tests.sh
64
+ ```
65
+
66
+ To see all available arguments, please refer to [pytest documentation](https://docs.pytest.org/en/stable/how-to/usage.html)
67
+
68
+ ### Debugging external llama-server
69
+ It can sometimes be useful to run the server in a debugger when invesigating test
70
+ failures. To do this, the environment variable `DEBUG_EXTERNAL=1` can be set
71
+ which will cause the test to skip starting a llama-server itself. Instead, the
72
+ server can be started in a debugger.
73
+
74
+ Example using `gdb`:
75
+ ```console
76
+ $ gdb --args ../../../build/bin/llama-server \
77
+ --host 127.0.0.1 --port 8080 \
78
+ --temp 0.8 --seed 42 \
79
+ --hf-repo ggml-org/models --hf-file tinyllamas/stories260K.gguf \
80
+ --batch-size 32 --no-slots --alias tinyllama-2 --ctx-size 512 \
81
+ --parallel 2 --n-predict 64
82
+ ```
83
+ And a break point can be set in before running:
84
+ ```console
85
+ (gdb) br server.cpp:4604
86
+ (gdb) r
87
+ main: server is listening on http://127.0.0.1:8080 - starting the main loop
88
+ srv update_slots: all slots are idle
89
+ ```
90
+
91
+ And then the test in question can be run in another terminal:
92
+ ```console
93
+ (venv) $ env DEBUG_EXTERNAL=1 ./tests.sh unit/test_chat_completion.py -v -x
94
+ ```
95
+ And this should trigger the breakpoint and allow inspection of the server state
96
+ in the debugger terminal.
tools/server/tests/conftest.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from utils import *
3
+
4
+
5
+ # ref: https://stackoverflow.com/questions/22627659/run-code-before-and-after-each-test-in-py-test
6
+ @pytest.fixture(autouse=True)
7
+ def stop_server_after_each_test():
8
+ # do nothing before each test
9
+ yield
10
+ # stop all servers after each test
11
+ instances = set(
12
+ server_instances
13
+ ) # copy the set to prevent 'Set changed size during iteration'
14
+ for server in instances:
15
+ server.stop()
16
+
17
+
18
+ @pytest.fixture(scope="session", autouse=True)
19
+ def load_server_presets():
20
+ # this will be run once per test session, before any tests
21
+ ServerPreset.load_all()
tools/server/tests/fixtures/mcp_burst_server.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Minimal MCP server that writes notification + response in a single write() with no flush.
4
+ This reproduces the buffering bug where read_message() can strand the response.
5
+ """
6
+ import json
7
+ import sys
8
+ import os
9
+
10
+ TOOLS = [
11
+ {
12
+ "name": "echo",
13
+ "description": "Echo back the input message",
14
+ "inputSchema": {
15
+ "type": "object",
16
+ "properties": {
17
+ "message": {"type": "string"}
18
+ },
19
+ "required": ["message"]
20
+ }
21
+ }
22
+ ]
23
+
24
+ def handle_initialize(params, req_id):
25
+ return {
26
+ "jsonrpc": "2.0",
27
+ "id": req_id,
28
+ "result": {
29
+ "protocolVersion": "2024-11-05",
30
+ "capabilities": {"tools": {}},
31
+ "serverInfo": {"name": "burst-test", "version": "1.0"}
32
+ }
33
+ }
34
+
35
+ def handle_tools_list(params, req_id):
36
+ return {
37
+ "jsonrpc": "2.0",
38
+ "id": req_id,
39
+ "result": {"tools": TOOLS}
40
+ }
41
+
42
+ def handle_tools_call(params, req_id):
43
+ tool_name = params.get("name")
44
+ arguments = params.get("arguments", {})
45
+
46
+ if tool_name == "echo":
47
+ message = arguments.get("message", "")
48
+ notif = {
49
+ "jsonrpc": "2.0",
50
+ "method": "notifications/progress",
51
+ "params": {"progress": 50, "total": 100}
52
+ }
53
+ response = {
54
+ "jsonrpc": "2.0",
55
+ "id": req_id,
56
+ "result": {
57
+ "content": [{"type": "text", "text": f"echo: {message}"}]
58
+ }
59
+ }
60
+ # Single os.write() call: both lines land in one pipe packet atomically.
61
+ # This is the key difference from mcp_malformed_server.py which flushes between writes.
62
+ data = (json.dumps(notif) + "\n" + json.dumps(response) + "\n").encode("utf-8")
63
+ os.write(sys.stdout.fileno(), data)
64
+ return None # already written
65
+ else:
66
+ response = {
67
+ "jsonrpc": "2.0",
68
+ "id": req_id,
69
+ "error": {"code": -32602, "message": f"Unknown tool: {tool_name}"}
70
+ }
71
+ return response
72
+
73
+ HANDLERS = {
74
+ "initialize": handle_initialize,
75
+ "tools/list": handle_tools_list,
76
+ "tools/call": handle_tools_call,
77
+ }
78
+
79
+ def main():
80
+ # Use line-buffered text mode for regular responses, but the burst write
81
+ # uses os.write() directly to guarantee a single kernel write().
82
+ sys.stdout = os.fdopen(sys.stdout.fileno(), "w", buffering=1)
83
+ sys.stderr = os.fdopen(sys.stderr.fileno(), "w", buffering=1)
84
+
85
+ for line in sys.stdin:
86
+ line = line.strip()
87
+ if not line:
88
+ continue
89
+ try:
90
+ request = json.loads(line)
91
+ except json.JSONDecodeError:
92
+ continue
93
+
94
+ method = request.get("method")
95
+ req_id = request.get("id")
96
+ params = request.get("params", {})
97
+
98
+ # JSON-RPC 2.0: a message without an id is a notification and must not receive a response
99
+ if req_id is None:
100
+ continue
101
+
102
+ handler = HANDLERS.get(method)
103
+ if handler:
104
+ response = handler(params, req_id)
105
+ if response is not None:
106
+ sys.stdout.write(json.dumps(response) + "\n")
107
+ sys.stdout.flush()
108
+ else:
109
+ response = {
110
+ "jsonrpc": "2.0",
111
+ "id": req_id,
112
+ "error": {"code": -32601, "message": f"Method not found: {method}"}
113
+ }
114
+ sys.stdout.write(json.dumps(response) + "\n")
115
+ sys.stdout.flush()
116
+
117
+ if __name__ == "__main__":
118
+ main()
tools/server/tests/fixtures/mcp_crash_server.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ MCP server that crashes after receiving a specific tool call.
4
+ """
5
+ import json
6
+ import sys
7
+ import os
8
+
9
+ def handle_initialize(params, req_id):
10
+ return {
11
+ "jsonrpc": "2.0",
12
+ "id": req_id,
13
+ "result": {
14
+ "protocolVersion": "2024-11-05",
15
+ "capabilities": {"tools": {}},
16
+ "serverInfo": {"name": "crash-test", "version": "1.0"}
17
+ }
18
+ }
19
+
20
+ def handle_tools_list(params, req_id):
21
+ return {
22
+ "jsonrpc": "2.0",
23
+ "id": req_id,
24
+ "result": {
25
+ "tools": [
26
+ {
27
+ "name": "echo",
28
+ "description": "Echo back the input message",
29
+ "inputSchema": {
30
+ "type": "object",
31
+ "properties": {
32
+ "message": {"type": "string"}
33
+ }
34
+ }
35
+ },
36
+ {
37
+ "name": "crash",
38
+ "description": "Crash the server",
39
+ "inputSchema": {
40
+ "type": "object",
41
+ "properties": {}
42
+ }
43
+ }
44
+ ]
45
+ }
46
+ }
47
+
48
+ def handle_tools_call(params, req_id):
49
+ tool_name = params.get("name")
50
+ arguments = params.get("arguments", {})
51
+
52
+ if tool_name == "echo":
53
+ message = arguments.get("message", "")
54
+ return {
55
+ "jsonrpc": "2.0",
56
+ "id": req_id,
57
+ "result": {
58
+ "content": [{"type": "text", "text": f"echo: {message}"}]
59
+ }
60
+ }
61
+ elif tool_name == "crash":
62
+ # Send a partial response then exit
63
+ sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": req_id, "result": {"content": [{"type": "text", "text": "crashing..."}]}}) + "\n")
64
+ sys.stdout.flush()
65
+ os._exit(1)
66
+ else:
67
+ return {
68
+ "jsonrpc": "2.0",
69
+ "id": req_id,
70
+ "error": {"code": -32602, "message": f"Unknown tool: {tool_name}"}
71
+ }
72
+
73
+ HANDLERS = {
74
+ "initialize": handle_initialize,
75
+ "tools/list": handle_tools_list,
76
+ "tools/call": handle_tools_call,
77
+ }
78
+
79
+ def main():
80
+ sys.stdout = os.fdopen(sys.stdout.fileno(), "w", buffering=1)
81
+ sys.stderr = os.fdopen(sys.stderr.fileno(), "w", buffering=1)
82
+
83
+ for line in sys.stdin:
84
+ line = line.strip()
85
+ if not line:
86
+ continue
87
+ try:
88
+ request = json.loads(line)
89
+ except json.JSONDecodeError:
90
+ continue
91
+
92
+ method = request.get("method")
93
+ req_id = request.get("id")
94
+ params = request.get("params", {})
95
+
96
+ # JSON-RPC 2.0: a message without an id is a notification and must not receive a response
97
+ if req_id is None:
98
+ continue
99
+
100
+ handler = HANDLERS.get(method)
101
+ if handler:
102
+ response = handler(params, req_id)
103
+ else:
104
+ response = {
105
+ "jsonrpc": "2.0",
106
+ "id": req_id,
107
+ "error": {"code": -32601, "message": f"Method not found: {method}"}
108
+ }
109
+
110
+ sys.stdout.write(json.dumps(response) + "\n")
111
+ sys.stdout.flush()
112
+
113
+ if __name__ == "__main__":
114
+ main()
tools/server/tests/fixtures/mcp_echo_server.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Minimal MCP server for testing.
4
+ Implements JSON-RPC 2.0 over stdio (line-delimited JSON).
5
+ """
6
+ import json
7
+ import sys
8
+ import os
9
+
10
+ # Ensure we use python3 from the current environment
11
+ if sys.platform == "win32":
12
+ # On Windows, we need to use the same python interpreter
13
+ pass
14
+
15
+ TOOLS = [
16
+ {
17
+ "name": "echo",
18
+ "description": "Echo back the input message",
19
+ "inputSchema": {
20
+ "type": "object",
21
+ "properties": {
22
+ "message": {"type": "string", "description": "Message to echo"}
23
+ },
24
+ "required": ["message"]
25
+ }
26
+ },
27
+ {
28
+ "name": "add",
29
+ "description": "Add two numbers",
30
+ "inputSchema": {
31
+ "type": "object",
32
+ "properties": {
33
+ "a": {"type": "number"},
34
+ "b": {"type": "number"}
35
+ },
36
+ "required": ["a", "b"]
37
+ }
38
+ },
39
+ {
40
+ "name": "fail_once",
41
+ "description": "Fails on first call, succeeds on subsequent calls",
42
+ "inputSchema": {
43
+ "type": "object",
44
+ "properties": {}
45
+ }
46
+ }
47
+ ]
48
+
49
+ _state = {"fail_once_called": False}
50
+
51
+ def handle_initialize(params, req_id):
52
+ return {
53
+ "jsonrpc": "2.0",
54
+ "id": req_id,
55
+ "result": {
56
+ "protocolVersion": "2024-11-05",
57
+ "capabilities": {"tools": {}},
58
+ "serverInfo": {"name": "echo-test", "version": "1.0"}
59
+ }
60
+ }
61
+
62
+ def handle_tools_list(params, req_id):
63
+ return {
64
+ "jsonrpc": "2.0",
65
+ "id": req_id,
66
+ "result": {"tools": TOOLS}
67
+ }
68
+
69
+ def handle_tools_call(params, req_id):
70
+ tool_name = params.get("name")
71
+ arguments = params.get("arguments", {})
72
+
73
+ if tool_name == "echo":
74
+ message = arguments.get("message", "")
75
+ return {
76
+ "jsonrpc": "2.0",
77
+ "id": req_id,
78
+ "result": {
79
+ "content": [{"type": "text", "text": f"echo: {message}"}]
80
+ }
81
+ }
82
+ elif tool_name == "add":
83
+ a = arguments.get("a", 0)
84
+ b = arguments.get("b", 0)
85
+ return {
86
+ "jsonrpc": "2.0",
87
+ "id": req_id,
88
+ "result": {
89
+ "content": [{"type": "text", "text": str(a + b)}]
90
+ }
91
+ }
92
+ elif tool_name == "fail_once":
93
+ if not _state["fail_once_called"]:
94
+ _state["fail_once_called"] = True
95
+ return {
96
+ "jsonrpc": "2.0",
97
+ "id": req_id,
98
+ "error": {"code": -32000, "message": "transient error"}
99
+ }
100
+ return {
101
+ "jsonrpc": "2.0",
102
+ "id": req_id,
103
+ "result": {
104
+ "content": [{"type": "text", "text": "ok"}]
105
+ }
106
+ }
107
+ else:
108
+ return {
109
+ "jsonrpc": "2.0",
110
+ "id": req_id,
111
+ "error": {"code": -32602, "message": f"Unknown tool: {tool_name}"}
112
+ }
113
+
114
+ def handle_ping(params, req_id):
115
+ return {
116
+ "jsonrpc": "2.0",
117
+ "id": req_id,
118
+ "result": {}
119
+ }
120
+
121
+ HANDLERS = {
122
+ "initialize": handle_initialize,
123
+ "tools/list": handle_tools_list,
124
+ "tools/call": handle_tools_call,
125
+ "ping": handle_ping,
126
+ }
127
+
128
+ def main():
129
+ # Use unbuffered output
130
+ sys.stdout = os.fdopen(sys.stdout.fileno(), "w", buffering=1)
131
+ sys.stderr = os.fdopen(sys.stderr.fileno(), "w", buffering=1)
132
+
133
+ for line in sys.stdin:
134
+ line = line.strip()
135
+ if not line:
136
+ continue
137
+ try:
138
+ request = json.loads(line)
139
+ except json.JSONDecodeError:
140
+ continue
141
+
142
+ method = request.get("method")
143
+ req_id = request.get("id")
144
+ params = request.get("params", {})
145
+
146
+ # JSON-RPC 2.0: a message without an id is a notification and must not receive a response
147
+ if req_id is None:
148
+ continue
149
+
150
+ handler = HANDLERS.get(method)
151
+ if handler:
152
+ response = handler(params, req_id)
153
+ else:
154
+ response = {
155
+ "jsonrpc": "2.0",
156
+ "id": req_id,
157
+ "error": {"code": -32601, "message": f"Method not found: {method}"}
158
+ }
159
+
160
+ sys.stdout.write(json.dumps(response) + "\n")
161
+ sys.stdout.flush()
162
+
163
+ if __name__ == "__main__":
164
+ main()
tools/server/tests/fixtures/mcp_grandchild_server.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ MCP server (NDJSON JSON-RPC over stdio) that spawns a long-lived grandchild which inherits
4
+ this process's stdin/stdout/stderr and keeps them open.
5
+
6
+ This reproduces the reader-teardown deadlock: killing the direct MCP child (SIGKILL, which is
7
+ all subprocess_terminate() does) does NOT close the stdout/stderr pipe write ends, because the
8
+ grandchild still holds them. A server that reads those pipes with a blocking read would then
9
+ wait forever for an EOF that never arrives, hanging teardown (both warmup shutdown at startup
10
+ and process shutdown). The polled, running-aware reader must exit regardless.
11
+ """
12
+ import json
13
+ import os
14
+ import subprocess
15
+ import sys
16
+
17
+ # Spawn a grandchild that inherits our std handles (fds 0/1/2 = the MCP pipes) and lives well
18
+ # past any teardown in the tests. We do NOT redirect its stdio, so it keeps the pipe write ends
19
+ # open even after this process is killed.
20
+ subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"])
21
+
22
+ TOOLS = [
23
+ {
24
+ "name": "echo",
25
+ "description": "Echo back the input message",
26
+ "inputSchema": {
27
+ "type": "object",
28
+ "properties": {"message": {"type": "string", "description": "Message to echo"}},
29
+ "required": ["message"],
30
+ },
31
+ }
32
+ ]
33
+
34
+
35
+ def handle_initialize(params, req_id):
36
+ return {
37
+ "jsonrpc": "2.0",
38
+ "id": req_id,
39
+ "result": {
40
+ "protocolVersion": "2024-11-05",
41
+ "capabilities": {"tools": {}},
42
+ "serverInfo": {"name": "grandchild-test", "version": "1.0"},
43
+ },
44
+ }
45
+
46
+
47
+ def handle_tools_list(params, req_id):
48
+ return {"jsonrpc": "2.0", "id": req_id, "result": {"tools": TOOLS}}
49
+
50
+
51
+ def handle_tools_call(params, req_id):
52
+ if params.get("name") == "echo":
53
+ message = params.get("arguments", {}).get("message", "")
54
+ return {
55
+ "jsonrpc": "2.0",
56
+ "id": req_id,
57
+ "result": {"content": [{"type": "text", "text": f"echo: {message}"}]},
58
+ }
59
+ return {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32602, "message": "Unknown tool"}}
60
+
61
+
62
+ HANDLERS = {
63
+ "initialize": handle_initialize,
64
+ "tools/list": handle_tools_list,
65
+ "tools/call": handle_tools_call,
66
+ }
67
+
68
+
69
+ def main():
70
+ sys.stdout = os.fdopen(sys.stdout.fileno(), "w", buffering=1)
71
+ sys.stderr = os.fdopen(sys.stderr.fileno(), "w", buffering=1)
72
+
73
+ for line in sys.stdin:
74
+ line = line.strip()
75
+ if not line:
76
+ continue
77
+ try:
78
+ request = json.loads(line)
79
+ except json.JSONDecodeError:
80
+ continue
81
+
82
+ method = request.get("method")
83
+ req_id = request.get("id")
84
+ params = request.get("params", {})
85
+
86
+ if req_id is None:
87
+ continue # notification, no response
88
+
89
+ handler = HANDLERS.get(method)
90
+ if handler:
91
+ response = handler(params, req_id)
92
+ else:
93
+ response = {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32601, "message": f"Method not found: {method}"}}
94
+
95
+ sys.stdout.write(json.dumps(response) + "\n")
96
+ sys.stdout.flush()
97
+
98
+
99
+ if __name__ == "__main__":
100
+ main()
tools/server/tests/fixtures/mcp_malformed_server.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ MCP server that sends malformed responses and notifications during requests.
4
+ """
5
+ import json
6
+ import sys
7
+ import os
8
+
9
+ def handle_initialize(params, req_id):
10
+ return {
11
+ "jsonrpc": "2.0",
12
+ "id": req_id,
13
+ "result": {
14
+ "protocolVersion": "2024-11-05",
15
+ "capabilities": {"tools": {}},
16
+ "serverInfo": {"name": "malformed-test", "version": "1.0"}
17
+ }
18
+ }
19
+
20
+ def handle_tools_list(params, req_id):
21
+ return {
22
+ "jsonrpc": "2.0",
23
+ "id": req_id,
24
+ "result": {
25
+ "tools": [
26
+ {
27
+ "name": "echo",
28
+ "description": "Echo back the input message",
29
+ "inputSchema": {
30
+ "type": "object",
31
+ "properties": {
32
+ "message": {"type": "string"}
33
+ }
34
+ }
35
+ }
36
+ ]
37
+ }
38
+ }
39
+
40
+ def handle_tools_call(params, req_id):
41
+ tool_name = params.get("name")
42
+ arguments = params.get("arguments", {})
43
+
44
+ if tool_name == "echo":
45
+ message = arguments.get("message", "")
46
+ # Send a notification first (no id field)
47
+ notif = {
48
+ "jsonrpc": "2.0",
49
+ "method": "notifications/progress",
50
+ "params": {"progress": 50, "total": 100}
51
+ }
52
+ sys.stdout.write(json.dumps(notif) + "\n")
53
+ sys.stdout.flush()
54
+ # Then send the actual response
55
+ return {
56
+ "jsonrpc": "2.0",
57
+ "id": req_id,
58
+ "result": {
59
+ "content": [{"type": "text", "text": f"echo: {message}"}]
60
+ }
61
+ }
62
+ else:
63
+ return {
64
+ "jsonrpc": "2.0",
65
+ "id": req_id,
66
+ "error": {"code": -32602, "message": f"Unknown tool: {tool_name}"}
67
+ }
68
+
69
+ HANDLERS = {
70
+ "initialize": handle_initialize,
71
+ "tools/list": handle_tools_list,
72
+ "tools/call": handle_tools_call,
73
+ }
74
+
75
+ def main():
76
+ sys.stdout = os.fdopen(sys.stdout.fileno(), "w", buffering=1)
77
+ sys.stderr = os.fdopen(sys.stderr.fileno(), "w", buffering=1)
78
+
79
+ for line in sys.stdin:
80
+ line = line.strip()
81
+ if not line:
82
+ continue
83
+ try:
84
+ request = json.loads(line)
85
+ except json.JSONDecodeError:
86
+ # Send malformed JSON response
87
+ sys.stdout.write("THIS IS NOT JSON\n")
88
+ sys.stdout.flush()
89
+ continue
90
+
91
+ method = request.get("method")
92
+ req_id = request.get("id")
93
+ params = request.get("params", {})
94
+
95
+ # JSON-RPC 2.0: a message without an id is a notification and must not receive a response
96
+ if req_id is None:
97
+ continue
98
+
99
+ handler = HANDLERS.get(method)
100
+ if handler:
101
+ response = handler(params, req_id)
102
+ else:
103
+ response = {
104
+ "jsonrpc": "2.0",
105
+ "id": req_id,
106
+ "error": {"code": -32601, "message": f"Method not found: {method}"}
107
+ }
108
+
109
+ sys.stdout.write(json.dumps(response) + "\n")
110
+ sys.stdout.flush()
111
+
112
+ if __name__ == "__main__":
113
+ main()
tools/server/tests/fixtures/mcp_slow_server.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ MCP server that sleeps before responding, for timeout testing.
4
+ """
5
+ import json
6
+ import sys
7
+ import os
8
+ import time
9
+ import argparse
10
+
11
+ TOOLS = [
12
+ {
13
+ "name": "sleep",
14
+ "description": "Sleep for a given number of seconds",
15
+ "inputSchema": {
16
+ "type": "object",
17
+ "properties": {
18
+ "seconds": {"type": "number", "description": "Seconds to sleep"}
19
+ },
20
+ "required": ["seconds"]
21
+ }
22
+ }
23
+ ]
24
+
25
+ def handle_initialize(params, req_id):
26
+ return {
27
+ "jsonrpc": "2.0",
28
+ "id": req_id,
29
+ "result": {
30
+ "protocolVersion": "2024-11-05",
31
+ "capabilities": {"tools": {}},
32
+ "serverInfo": {"name": "slow-test", "version": "1.0"}
33
+ }
34
+ }
35
+
36
+ def handle_tools_list(params, req_id):
37
+ return {
38
+ "jsonrpc": "2.0",
39
+ "id": req_id,
40
+ "result": {"tools": TOOLS}
41
+ }
42
+
43
+ def handle_tools_call(params, req_id):
44
+ tool_name = params.get("name")
45
+ arguments = params.get("arguments", {})
46
+
47
+ if tool_name == "sleep":
48
+ seconds = arguments.get("seconds", 1)
49
+ time.sleep(seconds)
50
+ return {
51
+ "jsonrpc": "2.0",
52
+ "id": req_id,
53
+ "result": {
54
+ "content": [{"type": "text", "text": f"slept {seconds}s"}]
55
+ }
56
+ }
57
+ else:
58
+ return {
59
+ "jsonrpc": "2.0",
60
+ "id": req_id,
61
+ "error": {"code": -32602, "message": f"Unknown tool: {tool_name}"}
62
+ }
63
+
64
+ HANDLERS = {
65
+ "initialize": handle_initialize,
66
+ "tools/list": handle_tools_list,
67
+ "tools/call": handle_tools_call,
68
+ }
69
+
70
+ def main():
71
+ parser = argparse.ArgumentParser()
72
+ parser.add_argument("--delay", type=float, default=5.0, help="Delay in seconds for sleep tool")
73
+ args = parser.parse_args()
74
+
75
+ # Override the sleep duration
76
+ global handle_tools_call
77
+ def handle_tools_call(params, req_id):
78
+ tool_name = params.get("name")
79
+ arguments = params.get("arguments", {})
80
+
81
+ if tool_name == "sleep":
82
+ seconds = arguments.get("seconds", args.delay)
83
+ time.sleep(seconds)
84
+ return {
85
+ "jsonrpc": "2.0",
86
+ "id": req_id,
87
+ "result": {
88
+ "content": [{"type": "text", "text": f"slept {seconds}s"}]
89
+ }
90
+ }
91
+ else:
92
+ return {
93
+ "jsonrpc": "2.0",
94
+ "id": req_id,
95
+ "error": {"code": -32602, "message": f"Unknown tool: {tool_name}"}
96
+ }
97
+
98
+ sys.stdout = os.fdopen(sys.stdout.fileno(), "w", buffering=1)
99
+ sys.stderr = os.fdopen(sys.stderr.fileno(), "w", buffering=1)
100
+
101
+ for line in sys.stdin:
102
+ line = line.strip()
103
+ if not line:
104
+ continue
105
+ try:
106
+ request = json.loads(line)
107
+ except json.JSONDecodeError:
108
+ continue
109
+
110
+ method = request.get("method")
111
+ req_id = request.get("id")
112
+ params = request.get("params", {})
113
+
114
+ # JSON-RPC 2.0: a message without an id is a notification and must not receive a response
115
+ if req_id is None:
116
+ continue
117
+
118
+ handler = HANDLERS.get(method)
119
+ if handler:
120
+ response = handler(params, req_id)
121
+ else:
122
+ response = {
123
+ "jsonrpc": "2.0",
124
+ "id": req_id,
125
+ "error": {"code": -32601, "message": f"Method not found: {method}"}
126
+ }
127
+
128
+ sys.stdout.write(json.dumps(response) + "\n")
129
+ sys.stdout.flush()
130
+
131
+ if __name__ == "__main__":
132
+ main()
tools/server/tests/pytest.ini ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ [pytest]
2
+ markers =
3
+ slow: marks tests as slow (deselect with '-m "not slow"')
4
+ serial
tools/server/tests/requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ aiohttp~=3.9.3
2
+ pytest~=8.3.3
3
+ numpy~=1.26.4
4
+ openai~=2.14.0
5
+ prometheus-client~=0.20.0
6
+ requests~=2.32.3
7
+ wget~=3.2
tools/server/tests/tests.sh ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+
3
+ # make sure we are in the right directory
4
+ SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
5
+ cd $SCRIPT_DIR
6
+
7
+ set -eu
8
+
9
+ if [[ "${SLOW_TESTS:-0}" == 1 ]]; then
10
+ # Slow tests for tool calls need quite a few models ahead of time to avoid timing out.
11
+ python $SCRIPT_DIR/../../../scripts/fetch_server_test_models.py
12
+ fi
13
+
14
+ if [ $# -lt 1 ]
15
+ then
16
+ if [[ "${SLOW_TESTS:-0}" == 1 ]]; then
17
+ pytest --durations=30 -v -x
18
+ else
19
+ pytest --durations=30 -v -x -m "not slow"
20
+ fi
21
+ else
22
+ pytest --durations=30 "$@"
23
+ fi
tools/server/tests/unit/test_basic.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import requests
3
+ from utils import *
4
+
5
+ server = ServerPreset.tinyllama2()
6
+
7
+
8
+ @pytest.fixture(autouse=True)
9
+ def create_server():
10
+ global server
11
+ server = ServerPreset.tinyllama2()
12
+
13
+
14
+ def test_server_start_simple():
15
+ global server
16
+ server.start()
17
+ res = server.make_request("GET", "/health")
18
+ assert res.status_code == 200
19
+
20
+
21
+ def test_server_props():
22
+ global server
23
+ server.start()
24
+ res = server.make_request("GET", "/props")
25
+ assert res.status_code == 200
26
+ assert ".gguf" in res.body["model_path"]
27
+ assert res.body["total_slots"] == server.n_slots
28
+ default_val = res.body["default_generation_settings"]
29
+ assert server.n_ctx is not None and server.n_slots is not None
30
+ assert default_val["n_ctx"] == server.n_ctx / server.n_slots
31
+ assert default_val["params"]["seed"] == server.seed
32
+
33
+
34
+ def test_server_models():
35
+ global server
36
+ server.start()
37
+ res = server.make_request("GET", "/models")
38
+ assert res.status_code == 200
39
+ assert len(res.body["data"]) == 1
40
+ assert res.body["data"][0]["id"] == server.model_alias
41
+
42
+
43
+ def test_server_slots():
44
+ global server
45
+
46
+ # without slots endpoint enabled, this should return error
47
+ server.server_slots = False
48
+ server.start()
49
+ res = server.make_request("GET", "/slots")
50
+ assert res.status_code == 501 # ERROR_TYPE_NOT_SUPPORTED
51
+ assert "error" in res.body
52
+ server.stop()
53
+
54
+ # with slots endpoint enabled, this should return slots info
55
+ server.server_slots = True
56
+ server.n_slots = 2
57
+ server.start()
58
+ res = server.make_request("GET", "/slots")
59
+ assert res.status_code == 200
60
+ assert len(res.body) == server.n_slots
61
+ assert server.n_ctx is not None and server.n_slots is not None
62
+ assert res.body[0]["n_ctx"] == server.n_ctx / server.n_slots
63
+ assert "params" not in res.body[0]
64
+
65
+
66
+ def test_load_split_model():
67
+ global server
68
+ server.offline = False
69
+ server.model_hf_repo = "ggml-org/models"
70
+ server.model_hf_file = "tinyllamas/split/stories15M-q8_0-00001-of-00003.gguf"
71
+ server.model_alias = "tinyllama-split"
72
+ server.start()
73
+ res = server.make_request("POST", "/completion", data={
74
+ "n_predict": 16,
75
+ "prompt": "Hello",
76
+ "temperature": 0.0,
77
+ })
78
+ assert res.status_code == 200
79
+ assert match_regex("(little|girl)+", res.body["content"])
80
+
81
+
82
+ def test_no_ui():
83
+ global server
84
+ # default: UI enabled
85
+ server.start()
86
+ url = f"http://{server.server_host}:{server.server_port}"
87
+ res = requests.get(url)
88
+ assert res.status_code == 200
89
+ assert "<!doctype html>" in res.text
90
+ server.stop()
91
+
92
+ # with --no-ui, the UI should be disabled
93
+ server.no_ui = True
94
+ server.start()
95
+ res = requests.get(url)
96
+ assert res.status_code == 404
97
+
98
+
99
+ def test_server_model_aliases_and_tags():
100
+ global server
101
+ server.model_alias = "tinyllama-2,fim,code"
102
+ server.model_tags = "chat,fim,small"
103
+ server.start()
104
+ res = server.make_request("GET", "/models")
105
+ assert res.status_code == 200
106
+ assert len(res.body["data"]) == 1
107
+ model = res.body["data"][0]
108
+ # aliases field must contain all aliases
109
+ assert set(model["aliases"]) == {"tinyllama-2", "fim", "code"}
110
+ # tags field must contain all tags
111
+ assert set(model["tags"]) == {"chat", "fim", "small"}
112
+ # id is derived from first alias (alphabetical order from std::set)
113
+ assert model["id"] == "code"
tools/server/tests/unit/test_chat_completion.py ADDED
@@ -0,0 +1,625 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from openai import OpenAI
3
+ from utils import *
4
+
5
+ server: ServerProcess
6
+
7
+ @pytest.fixture(autouse=True)
8
+ def create_server():
9
+ global server
10
+ server = ServerPreset.tinyllama2()
11
+
12
+
13
+ @pytest.mark.parametrize(
14
+ "model,system_prompt,user_prompt,max_tokens,re_content,n_prompt,n_predicted,finish_reason,jinja,chat_template",
15
+ [
16
+ (None, "Book", "Hey", 8, "But she couldn't", 69, 8, "length", False, None),
17
+ (None, "Book", "Hey", 8, "But she couldn't", 69, 8, "length", True, None),
18
+ (None, "Book", "What is the best book", 8, "(Suddenly)+|\\{ \" Sarax.", 77, 8, "length", False, None),
19
+ (None, "Book", "What is the best book", 8, "(Suddenly)+|\\{ \" Sarax.", 77, 8, "length", True, None),
20
+ (None, "Book", "What is the best book", 8, "(Suddenly)+|\\{ \" Sarax.", 77, 8, "length", True, 'chatml'),
21
+ (None, "Book", "What is the best book", 8, "^ blue", 23, 8, "length", True, "This is not a chat template, it is"),
22
+ ("codellama70b", "You are a coding assistant.", "Write the fibonacci function in c++.", 128, "(Aside|she|felter|alonger)+", 104, 128, "length", False, None),
23
+ ("codellama70b", "You are a coding assistant.", "Write the fibonacci function in c++.", 128, "(Aside|she|felter|alonger)+", 104, 128, "length", True, None),
24
+ (None, "Book", [{"type": "text", "text": "What is"}, {"type": "text", "text": "the best book"}], 8, "Whillicter", 79, 8, "length", False, None),
25
+ (None, "Book", [{"type": "text", "text": "What is"}, {"type": "text", "text": "the best book"}], 8, "Whillicter", 79, 8, "length", True, None),
26
+ ]
27
+ )
28
+ def test_chat_completion(model, system_prompt, user_prompt, max_tokens, re_content, n_prompt, n_predicted, finish_reason, jinja, chat_template):
29
+ global server
30
+ server.jinja = jinja
31
+ server.chat_template = chat_template
32
+ server.start()
33
+ res = server.make_request("POST", "/chat/completions", data={
34
+ "model": model,
35
+ "max_tokens": max_tokens,
36
+ "messages": [
37
+ {"role": "system", "content": system_prompt},
38
+ {"role": "user", "content": user_prompt},
39
+ ],
40
+ })
41
+ assert res.status_code == 200
42
+ assert "cmpl" in res.body["id"] # make sure the completion id has the expected format
43
+ assert res.body["system_fingerprint"].startswith("b")
44
+ # we no longer reflect back the model name, see https://github.com/ggml-org/llama.cpp/pull/17668
45
+ # assert res.body["model"] == model if model is not None else server.model_alias
46
+ assert res.body["usage"]["prompt_tokens"] == n_prompt
47
+ assert res.body["usage"]["completion_tokens"] == n_predicted
48
+ choice = res.body["choices"][0]
49
+ assert "assistant" == choice["message"]["role"]
50
+ assert match_regex(re_content, choice["message"]["content"]), f'Expected {re_content}, got {choice["message"]["content"]}'
51
+ assert choice["finish_reason"] == finish_reason
52
+
53
+
54
+ def test_chat_completion_cached_tokens():
55
+ global server
56
+ server.n_slots = 1
57
+ server.start()
58
+ seq = [
59
+ ("1 2 3 4 5 6", 77, 0),
60
+ ("1 2 3 4 5 6", 77, 76),
61
+ ("1 2 3 4 5 9", 77, 51),
62
+ ("1 2 3 9 9 9", 77, 47),
63
+ ]
64
+ for user_prompt, n_prompt, n_cache in seq:
65
+ res = server.make_request("POST", "/chat/completions", data={
66
+ "max_tokens": 8,
67
+ "messages": [
68
+ {"role": "system", "content": "Test"},
69
+ {"role": "user", "content": user_prompt},
70
+ ],
71
+ })
72
+ assert res.body["usage"]["prompt_tokens"] == n_prompt
73
+ assert res.body["usage"]["prompt_tokens_details"]["cached_tokens"] == n_cache
74
+
75
+ @pytest.mark.parametrize(
76
+ "system_prompt,user_prompt,max_tokens,re_content,n_prompt,n_predicted,finish_reason",
77
+ [
78
+ ("Book", "What is the best book", 8, "(Suddenly)+", 77, 8, "length"),
79
+ ("You are a coding assistant.", "Write the fibonacci function in c++.", 128, "(Aside|she|felter|alonger)+", 104, 128, "length"),
80
+ ]
81
+ )
82
+ def test_chat_completion_stream(system_prompt, user_prompt, max_tokens, re_content, n_prompt, n_predicted, finish_reason):
83
+ global server
84
+ server.model_alias = "llama-test-model"
85
+ server.start()
86
+ res = server.make_stream_request("POST", "/chat/completions", data={
87
+ "max_tokens": max_tokens,
88
+ "messages": [
89
+ {"role": "system", "content": system_prompt},
90
+ {"role": "user", "content": user_prompt},
91
+ ],
92
+ "stream": True,
93
+ })
94
+ content = ""
95
+ last_cmpl_id = None
96
+ for i, data in enumerate(res):
97
+ if data["choices"]:
98
+ choice = data["choices"][0]
99
+ if i == 0:
100
+ # Check first role message for stream=True
101
+ assert choice["delta"]["content"] is None
102
+ assert choice["delta"]["role"] == "assistant"
103
+ else:
104
+ assert "role" not in choice["delta"]
105
+ assert data["system_fingerprint"].startswith("b")
106
+ assert data["model"] == "llama-test-model"
107
+ if last_cmpl_id is None:
108
+ last_cmpl_id = data["id"]
109
+ assert last_cmpl_id == data["id"] # make sure the completion id is the same for all events in the stream
110
+ if choice["finish_reason"] in ["stop", "length"]:
111
+ assert "content" not in choice["delta"]
112
+ assert match_regex(re_content, content)
113
+ assert choice["finish_reason"] == finish_reason
114
+ else:
115
+ assert choice["finish_reason"] is None
116
+ content += choice["delta"]["content"] or ''
117
+ else:
118
+ assert data["usage"]["prompt_tokens"] == n_prompt
119
+ assert data["usage"]["completion_tokens"] == n_predicted
120
+
121
+
122
+ def test_chat_completion_with_openai_library():
123
+ global server
124
+ server.start()
125
+ client = OpenAI(api_key="dummy", base_url=f"http://{server.server_host}:{server.server_port}/v1")
126
+ res = client.chat.completions.create(
127
+ model="gpt-3.5-turbo-instruct",
128
+ messages=[
129
+ {"role": "system", "content": "Book"},
130
+ {"role": "user", "content": "What is the best book"},
131
+ ],
132
+ max_tokens=8,
133
+ seed=42,
134
+ temperature=0.8,
135
+ )
136
+ assert res.system_fingerprint is not None and res.system_fingerprint.startswith("b")
137
+ assert res.choices[0].finish_reason == "length"
138
+ assert res.choices[0].message.content is not None
139
+ assert match_regex("(Suddenly)+", res.choices[0].message.content)
140
+
141
+
142
+ def test_chat_template():
143
+ global server
144
+ server.chat_template = "llama3"
145
+ server.debug = True # to get the "__verbose" object in the response
146
+ server.start()
147
+ res = server.make_request("POST", "/chat/completions", data={
148
+ "max_tokens": 8,
149
+ "messages": [
150
+ {"role": "system", "content": "Book"},
151
+ {"role": "user", "content": "What is the best book"},
152
+ ]
153
+ })
154
+ assert res.status_code == 200
155
+ assert "__verbose" in res.body
156
+ assert res.body["__verbose"]["prompt"] == "<s> <|start_header_id|>system<|end_header_id|>\n\nBook<|eot_id|><|start_header_id|>user<|end_header_id|>\n\nWhat is the best book<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n"
157
+
158
+
159
+ @pytest.mark.parametrize("prefill,re_prefill", [
160
+ ("Whill", "Whill"),
161
+ ([{"type": "text", "text": "Wh"}, {"type": "text", "text": "ill"}], "Wh\n\nill"),
162
+ ])
163
+ def test_chat_template_assistant_prefill(prefill, re_prefill):
164
+ global server
165
+ server.jinja = True
166
+ server.chat_template_file = "../../../models/templates/meta-llama-Llama-3.1-8B-Instruct.jinja"
167
+ server.debug = True # to get the "__verbose" object in the response
168
+ server.start()
169
+ res = server.make_request("POST", "/chat/completions", data={
170
+ "max_tokens": 8,
171
+ "messages": [
172
+ {"role": "system", "content": "Book"},
173
+ {"role": "user", "content": "What is the best book"},
174
+ {"role": "assistant", "content": prefill},
175
+ ]
176
+ })
177
+ assert res.status_code == 200
178
+ assert "__verbose" in res.body
179
+ assert res.body["__verbose"]["prompt"].endswith(f"<|start_header_id|>user<|end_header_id|>\n\nWhat is the best book<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n{re_prefill}")
180
+
181
+
182
+ def test_chat_template_continue_final_message_vllm_compat():
183
+ """continue_final_message is the vLLM/transformers explicit alias for the prefill_assistant heuristic.
184
+ Both must produce the same prompt."""
185
+ global server
186
+ server.jinja = True
187
+ server.chat_template_file = "../../../models/templates/meta-llama-Llama-3.1-8B-Instruct.jinja"
188
+ server.debug = True
189
+ server.start()
190
+ res = server.make_request("POST", "/chat/completions", data={
191
+ "max_tokens": 8,
192
+ "add_generation_prompt": False,
193
+ "continue_final_message": True,
194
+ "messages": [
195
+ {"role": "system", "content": "Book"},
196
+ {"role": "user", "content": "What is the best book"},
197
+ {"role": "assistant", "content": "Whill"},
198
+ ]
199
+ })
200
+ assert res.status_code == 200
201
+ assert "__verbose" in res.body
202
+ assert res.body["__verbose"]["prompt"].endswith("<|start_header_id|>user<|end_header_id|>\n\nWhat is the best book<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\nWhill")
203
+
204
+
205
+ def test_chat_template_continue_final_message_mutual_exclusion():
206
+ """add_generation_prompt and continue_final_message both set to true must be rejected"""
207
+ global server
208
+ server.chat_template = "llama3"
209
+ server.start()
210
+ res = server.make_request("POST", "/chat/completions", data={
211
+ "max_tokens": 8,
212
+ "add_generation_prompt": True,
213
+ "continue_final_message": True,
214
+ "messages": [
215
+ {"role": "user", "content": "Hi"},
216
+ {"role": "assistant", "content": "Hello"},
217
+ ]
218
+ })
219
+ assert res.status_code == 400
220
+
221
+
222
+ def test_apply_chat_template():
223
+ global server
224
+ server.chat_template = "command-r"
225
+ server.start()
226
+ res = server.make_request("POST", "/apply-template", data={
227
+ "messages": [
228
+ {"role": "system", "content": "You are a test."},
229
+ {"role": "user", "content":"Hi there"},
230
+ ]
231
+ })
232
+ assert res.status_code == 200
233
+ assert "prompt" in res.body
234
+ assert res.body["prompt"] == "<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>You are a test.<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|USER_TOKEN|>Hi there<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>"
235
+
236
+
237
+ @pytest.mark.parametrize("response_format,n_predicted,re_content", [
238
+ ({"type": "json_object", "schema": {"const": "42"}}, 6, "\"42\""),
239
+ ({"type": "json_object", "schema": {"items": [{"type": "integer"}]}}, 10, "[ -3000 ]"),
240
+ ({"type": "json_schema", "json_schema": {"schema": {"const": "foooooo"}}}, 10, "\"foooooo\""),
241
+ ({"type": "json_object"}, 10, "(\\{|John)+"),
242
+ ({"type": "sound"}, 0, None),
243
+ # invalid response format (expected to fail)
244
+ ({"type": "json_object", "schema": 123}, 0, None),
245
+ ({"type": "json_object", "schema": {"type": 123}}, 0, None),
246
+ ({"type": "json_object", "schema": {"type": "hiccup"}}, 0, None),
247
+ ])
248
+ def test_completion_with_response_format(response_format: dict, n_predicted: int, re_content: str | None):
249
+ global server
250
+ server.start()
251
+ res = server.make_request("POST", "/chat/completions", data={
252
+ "max_tokens": n_predicted,
253
+ "messages": [
254
+ {"role": "system", "content": "You are a coding assistant."},
255
+ {"role": "user", "content": "Write an example"},
256
+ ],
257
+ "response_format": response_format,
258
+ })
259
+ if re_content is not None:
260
+ assert res.status_code == 200
261
+ choice = res.body["choices"][0]
262
+ assert match_regex(re_content, choice["message"]["content"])
263
+ else:
264
+ assert res.status_code == 400
265
+ assert "error" in res.body
266
+
267
+
268
+ @pytest.mark.parametrize("jinja,json_schema,n_predicted,re_content", [
269
+ (False, {"const": "42"}, 6, "\"42\""),
270
+ (True, {"const": "42"}, 6, "\"42\""),
271
+ ])
272
+ def test_completion_with_json_schema(jinja: bool, json_schema: dict, n_predicted: int, re_content: str):
273
+ global server
274
+ server.jinja = jinja
275
+ server.debug = True
276
+ server.start()
277
+ res = server.make_request("POST", "/chat/completions", data={
278
+ "max_tokens": n_predicted,
279
+ "messages": [
280
+ {"role": "system", "content": "You are a coding assistant."},
281
+ {"role": "user", "content": "Write an example"},
282
+ ],
283
+ "json_schema": json_schema,
284
+ })
285
+ assert res.status_code == 200, f'Expected 200, got {res.status_code}'
286
+ choice = res.body["choices"][0]
287
+ assert match_regex(re_content, choice["message"]["content"]), f'Expected {re_content}, got {choice["message"]["content"]}'
288
+
289
+
290
+ @pytest.mark.parametrize("jinja,grammar,n_predicted,re_content", [
291
+ (False, 'root ::= "a"{5,5}', 6, "a{5,5}"),
292
+ (True, 'root ::= "a"{5,5}', 6, "a{5,5}"),
293
+ ])
294
+ def test_completion_with_grammar(jinja: bool, grammar: str, n_predicted: int, re_content: str):
295
+ global server
296
+ server.jinja = jinja
297
+ server.start()
298
+ res = server.make_request("POST", "/chat/completions", data={
299
+ "max_tokens": n_predicted,
300
+ "messages": [
301
+ {"role": "user", "content": "Does not matter what I say, does it?"},
302
+ ],
303
+ "grammar": grammar,
304
+ })
305
+ assert res.status_code == 200, res.body
306
+ choice = res.body["choices"][0]
307
+ assert match_regex(re_content, choice["message"]["content"]), choice["message"]["content"]
308
+
309
+
310
+ def test_completion_with_invalid_grammar():
311
+ global server
312
+ server.start()
313
+ res = server.make_request("POST", "/chat/completions", data={
314
+ "max_tokens": 8,
315
+ "messages": [
316
+ {"role": "user", "content": "Does not matter what I say, does it?"},
317
+ ],
318
+ "grammar": "root ::= this is (not valid GBNF",
319
+ })
320
+ assert res.status_code == 400, res.body
321
+ assert "error" in res.body
322
+
323
+
324
+ @pytest.mark.parametrize("messages", [
325
+ None,
326
+ "string",
327
+ [123],
328
+ [{}],
329
+ [{"role": 123}],
330
+ [{"role": "system", "content": 123}],
331
+ # [{"content": "hello"}], # TODO: should not be a valid case
332
+ [{"role": "system", "content": "test"}, {}],
333
+ [{"role": "user", "content": "test"}, {"role": "assistant", "content": "test"}, {"role": "assistant", "content": "test"}],
334
+ ])
335
+ def test_invalid_chat_completion_req(messages):
336
+ global server
337
+ server.start()
338
+ res = server.make_request("POST", "/chat/completions", data={
339
+ "messages": messages,
340
+ })
341
+ assert res.status_code == 400 or res.status_code == 500
342
+ assert "error" in res.body
343
+
344
+
345
+ def test_chat_completion_with_timings_per_token():
346
+ global server
347
+ server.start()
348
+ res = server.make_stream_request("POST", "/chat/completions", data={
349
+ "max_tokens": 10,
350
+ "messages": [{"role": "user", "content": "test"}],
351
+ "stream": True,
352
+ "stream_options": {"include_usage": True},
353
+ "timings_per_token": True,
354
+ })
355
+ stats_received = False
356
+ for i, data in enumerate(res):
357
+ if i == 0:
358
+ # Check first role message for stream=True
359
+ assert data["choices"][0]["delta"]["content"] is None
360
+ assert data["choices"][0]["delta"]["role"] == "assistant"
361
+ assert "timings" not in data, f'First event should not have timings: {data}'
362
+ else:
363
+ if data["choices"]:
364
+ assert "role" not in data["choices"][0]["delta"]
365
+ else:
366
+ assert "timings" in data
367
+ assert "prompt_per_second" in data["timings"]
368
+ assert "predicted_per_second" in data["timings"]
369
+ assert "predicted_n" in data["timings"]
370
+ assert data["timings"]["predicted_n"] <= 10
371
+ stats_received = True
372
+ assert stats_received
373
+
374
+
375
+ def test_logprobs():
376
+ global server
377
+ server.start()
378
+ client = OpenAI(api_key="dummy", base_url=f"http://{server.server_host}:{server.server_port}/v1")
379
+ res = client.chat.completions.create(
380
+ model="gpt-3.5-turbo-instruct",
381
+ temperature=0.0,
382
+ messages=[
383
+ {"role": "system", "content": "Book"},
384
+ {"role": "user", "content": "What is the best book"},
385
+ ],
386
+ max_tokens=5,
387
+ logprobs=True,
388
+ top_logprobs=10,
389
+ )
390
+ output_text = res.choices[0].message.content
391
+ aggregated_text = ''
392
+ assert res.choices[0].logprobs is not None
393
+ assert res.choices[0].logprobs.content is not None
394
+ for token in res.choices[0].logprobs.content:
395
+ aggregated_text += token.token
396
+ assert token.logprob <= 0.0
397
+ assert token.bytes is not None
398
+ assert len(token.top_logprobs) > 0
399
+ assert aggregated_text == output_text
400
+
401
+
402
+ def test_logprobs_stream():
403
+ global server
404
+ server.start()
405
+ client = OpenAI(api_key="dummy", base_url=f"http://{server.server_host}:{server.server_port}/v1")
406
+ res = client.chat.completions.create(
407
+ model="gpt-3.5-turbo-instruct",
408
+ temperature=0.0,
409
+ messages=[
410
+ {"role": "system", "content": "Book"},
411
+ {"role": "user", "content": "What is the best book"},
412
+ ],
413
+ max_tokens=5,
414
+ logprobs=True,
415
+ top_logprobs=10,
416
+ stream=True,
417
+ )
418
+ output_text = ''
419
+ aggregated_text = ''
420
+ for i, data in enumerate(res):
421
+ if data.choices:
422
+ choice = data.choices[0]
423
+ if i == 0:
424
+ # Check first role message for stream=True
425
+ assert choice.delta.content is None
426
+ assert choice.delta.role == "assistant"
427
+ else:
428
+ assert choice.delta.role is None
429
+ if choice.finish_reason is None:
430
+ if choice.delta.content:
431
+ output_text += choice.delta.content
432
+ assert choice.logprobs is not None
433
+ assert choice.logprobs.content is not None
434
+ for token in choice.logprobs.content:
435
+ aggregated_text += token.token
436
+ assert token.logprob <= 0.0
437
+ assert token.bytes is not None
438
+ assert token.top_logprobs is not None
439
+ assert len(token.top_logprobs) > 0
440
+ assert aggregated_text == output_text
441
+
442
+
443
+ def test_logit_bias():
444
+ global server
445
+ server.start()
446
+
447
+ exclude = ["i", "I", "the", "The", "to", "a", "an", "be", "is", "was", "but", "But", "and", "And", "so", "So", "you", "You", "he", "He", "she", "She", "we", "We", "they", "They", "it", "It", "his", "His", "her", "Her", "book", "Book"]
448
+
449
+ res = server.make_request("POST", "/tokenize", data={
450
+ "content": " " + " ".join(exclude) + " ",
451
+ })
452
+ assert res.status_code == 200
453
+ tokens = res.body["tokens"]
454
+ logit_bias = {tok: -100 for tok in tokens}
455
+
456
+ client = OpenAI(api_key="dummy", base_url=f"http://{server.server_host}:{server.server_port}/v1")
457
+ res = client.chat.completions.create(
458
+ model="gpt-3.5-turbo-instruct",
459
+ temperature=0.0,
460
+ messages=[
461
+ {"role": "system", "content": "Book"},
462
+ {"role": "user", "content": "What is the best book"},
463
+ ],
464
+ max_tokens=64,
465
+ logit_bias=logit_bias
466
+ )
467
+ output_text = res.choices[0].message.content
468
+ assert output_text
469
+ assert all(output_text.find(" " + tok + " ") == -1 for tok in exclude)
470
+
471
+ def test_context_size_exceeded():
472
+ global server
473
+ server.start()
474
+ res = server.make_request("POST", "/chat/completions", data={
475
+ "messages": [
476
+ {"role": "system", "content": "Book"},
477
+ {"role": "user", "content": "What is the best book"},
478
+ ] * 100, # make the prompt too long
479
+ })
480
+ assert res.status_code == 400
481
+ assert "error" in res.body
482
+ assert res.body["error"]["type"] == "exceed_context_size_error"
483
+ assert res.body["error"]["n_prompt_tokens"] > 0
484
+ assert server.n_ctx is not None
485
+ assert server.n_slots is not None
486
+ assert res.body["error"]["n_ctx"] == server.n_ctx // server.n_slots
487
+
488
+
489
+ def test_context_size_exceeded_stream():
490
+ global server
491
+ server.start()
492
+ try:
493
+ for _ in server.make_stream_request("POST", "/chat/completions", data={
494
+ "messages": [
495
+ {"role": "system", "content": "Book"},
496
+ {"role": "user", "content": "What is the best book"},
497
+ ] * 100, # make the prompt too long
498
+ "stream": True}):
499
+ pass
500
+ assert False, "Should have failed"
501
+ except ServerError as e:
502
+ assert e.code == 400
503
+ assert "error" in e.body
504
+ assert e.body["error"]["type"] == "exceed_context_size_error"
505
+ assert e.body["error"]["n_prompt_tokens"] > 0
506
+ assert server.n_ctx is not None
507
+ assert server.n_slots is not None
508
+ assert e.body["error"]["n_ctx"] == server.n_ctx // server.n_slots
509
+
510
+
511
+ @pytest.mark.parametrize(
512
+ "n_batch,batch_count,reuse_cache",
513
+ [
514
+ (64, 4, False),
515
+ (64, 2, True),
516
+ ]
517
+ )
518
+ def test_return_progress(n_batch, batch_count, reuse_cache):
519
+ global server
520
+ server.n_batch = n_batch
521
+ server.n_ctx = 256
522
+ server.n_slots = 1
523
+ server.start()
524
+ def make_cmpl_request():
525
+ return server.make_stream_request("POST", "/chat/completions", data={
526
+ "max_tokens": 10,
527
+ "messages": [
528
+ {"role": "user", "content": "This is a test" * 10},
529
+ ],
530
+ "stream": True,
531
+ "return_progress": True,
532
+ })
533
+ if reuse_cache:
534
+ # make a first request to populate the cache
535
+ res0 = make_cmpl_request()
536
+ for _ in res0:
537
+ pass # discard the output
538
+
539
+ res = make_cmpl_request()
540
+ last_progress = None
541
+ total_batch_count = 0
542
+
543
+ for data in res:
544
+ cur_progress = data.get("prompt_progress", None)
545
+ if cur_progress is None:
546
+ continue
547
+ if total_batch_count == 0:
548
+ # first progress report must have n_cache == n_processed
549
+ assert cur_progress["total"] > 0
550
+ assert cur_progress["cache"] == cur_progress["processed"]
551
+ if reuse_cache:
552
+ # when reusing cache, we expect some cached tokens
553
+ assert cur_progress["cache"] > 0
554
+ if last_progress is not None:
555
+ assert cur_progress["total"] == last_progress["total"]
556
+ assert cur_progress["cache"] == last_progress["cache"]
557
+ assert cur_progress["processed"] > last_progress["processed"]
558
+ total_batch_count += 1
559
+ last_progress = cur_progress
560
+
561
+ # last progress should indicate completion (all tokens processed)
562
+ assert last_progress is not None
563
+ assert last_progress["total"] > 0
564
+ assert last_progress["processed"] == last_progress["total"]
565
+ assert total_batch_count == batch_count
566
+
567
+
568
+ def test_chat_completions_multiple_choices():
569
+ global server
570
+ server.start()
571
+ # make sure cache can be reused across multiple choices and multiple requests
572
+ # ref: https://github.com/ggml-org/llama.cpp/pull/18663
573
+ for _ in range(2):
574
+ res = server.make_request("POST", "/chat/completions", data={
575
+ "max_tokens": 8,
576
+ "n": 2,
577
+ "messages": [
578
+ {"role": "system", "content": "Book"},
579
+ {"role": "user", "content": "What is the best book"},
580
+ ],
581
+ # test forcing the same slot to be used
582
+ # the scheduler should not be locked up in this case
583
+ "id_slot": 0,
584
+ })
585
+ assert res.status_code == 200
586
+ assert len(res.body["choices"]) == 2
587
+ for choice in res.body["choices"]:
588
+ assert "assistant" == choice["message"]["role"]
589
+ assert choice["finish_reason"] == "length"
590
+
591
+
592
+ def test_chat_completions_token_count():
593
+ global server
594
+ server.start()
595
+ # make sure cache can be reused across multiple choices and multiple requests
596
+ # ref: https://github.com/ggml-org/llama.cpp/pull/18663
597
+ for _ in range(2):
598
+ res = server.make_request("POST", "/chat/completions/input_tokens", data={
599
+ "messages": [
600
+ {"role": "system", "content": "Book"},
601
+ {"role": "user", "content": "What is the best book"},
602
+ ],
603
+ })
604
+ assert res.status_code == 200
605
+ assert res.body["input_tokens"] > 5
606
+
607
+
608
+ def test_verbose_debug():
609
+ global server
610
+ server.start()
611
+ for verbose in [True, False]:
612
+ res = server.make_request("POST", "/chat/completions", data={
613
+ "max_tokens": 2,
614
+ "messages": [
615
+ {"role": "system", "content": "Book"},
616
+ {"role": "user", "content": "What is the best book"},
617
+ ],
618
+ "verbose": verbose,
619
+ })
620
+ assert res.status_code == 200
621
+ if verbose:
622
+ assert "__verbose" in res.body
623
+ assert "Book" in res.body["__verbose"]["prompt"]
624
+ else:
625
+ assert "__verbose" not in res.body
tools/server/tests/unit/test_compat_anthropic.py ADDED
@@ -0,0 +1,1090 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import pytest
3
+ import base64
4
+ import requests
5
+
6
+ from utils import *
7
+
8
+ server: ServerProcess
9
+
10
+
11
+ def get_test_image_base64() -> str:
12
+ """Get a test image in base64 format"""
13
+ # Use the same test image as test_vision_api.py
14
+ IMG_URL = "https://huggingface.co/ggml-org/tinygemma3-GGUF/resolve/main/test/11_truck.png"
15
+ response = requests.get(IMG_URL)
16
+ response.raise_for_status()
17
+ return base64.b64encode(response.content).decode("utf-8")
18
+
19
+ @pytest.fixture(autouse=True)
20
+ def create_server():
21
+ global server
22
+ server = ServerPreset.tinyllama2()
23
+ server.model_alias = "tinyllama-2-anthropic"
24
+ server.server_port = 8082
25
+ server.n_slots = 1
26
+ server.n_ctx = 8192
27
+ server.n_batch = 2048
28
+
29
+
30
+ @pytest.fixture
31
+ def vision_server():
32
+ """Separate fixture for vision tests that require multimodal support"""
33
+ global server
34
+ server = ServerPreset.tinygemma3()
35
+ server.offline = False # Allow downloading the model
36
+ server.model_alias = "tinygemma3-anthropic"
37
+ server.server_port = 8083 # Different port to avoid conflicts
38
+ server.n_slots = 1
39
+ return server
40
+
41
+
42
+ # Basic message tests
43
+
44
+ def test_anthropic_messages_basic():
45
+ """Test basic Anthropic messages endpoint"""
46
+ server.start()
47
+
48
+ res = server.make_request("POST", "/v1/messages", data={
49
+ "model": "test",
50
+ "max_tokens": 50,
51
+ "messages": [
52
+ {"role": "user", "content": "Say hello"}
53
+ ]
54
+ })
55
+
56
+ assert res.status_code == 200, f"Expected 200, got {res.status_code}"
57
+ assert res.body["type"] == "message", f"Expected type 'message', got {res.body.get('type')}"
58
+ assert res.body["role"] == "assistant", f"Expected role 'assistant', got {res.body.get('role')}"
59
+ assert "content" in res.body, "Missing 'content' field"
60
+ assert isinstance(res.body["content"], list), "Content should be an array"
61
+ assert len(res.body["content"]) > 0, "Content array should not be empty"
62
+ assert res.body["content"][0]["type"] == "text", "First content block should be text"
63
+ assert "text" in res.body["content"][0], "Text content block missing 'text' field"
64
+ assert res.body["stop_reason"] in ["end_turn", "max_tokens"], f"Invalid stop_reason: {res.body.get('stop_reason')}"
65
+ assert "usage" in res.body, "Missing 'usage' field"
66
+ assert "cache_read_input_tokens" in res.body["usage"], "Missing usage.cache_read_input_tokens"
67
+ assert "input_tokens" in res.body["usage"], "Missing usage.input_tokens"
68
+ assert "output_tokens" in res.body["usage"], "Missing usage.output_tokens"
69
+ assert isinstance(res.body["usage"]["cache_read_input_tokens"], int), "cache_read_input_tokens should be integer"
70
+ assert isinstance(res.body["usage"]["input_tokens"], int), "input_tokens should be integer"
71
+ assert isinstance(res.body["usage"]["output_tokens"], int), "output_tokens should be integer"
72
+ assert res.body["usage"]["output_tokens"] > 0, "Should have generated some tokens"
73
+ # Anthropic API should NOT include timings
74
+ assert "timings" not in res.body, "Anthropic API should not include timings field"
75
+
76
+
77
+ def test_anthropic_messages_with_system():
78
+ """Test messages with system prompt"""
79
+ server.start()
80
+
81
+ res = server.make_request("POST", "/v1/messages", data={
82
+ "model": "test",
83
+ "max_tokens": 50,
84
+ "system": "You are a helpful assistant.",
85
+ "messages": [
86
+ {"role": "user", "content": "Hello"}
87
+ ]
88
+ })
89
+
90
+ assert res.status_code == 200
91
+ assert res.body["type"] == "message"
92
+ assert len(res.body["content"]) > 0
93
+
94
+
95
+ def test_anthropic_messages_multipart_content():
96
+ """Test messages with multipart content blocks"""
97
+ server.start()
98
+
99
+ res = server.make_request("POST", "/v1/messages", data={
100
+ "model": "test",
101
+ "max_tokens": 50,
102
+ "messages": [
103
+ {
104
+ "role": "user",
105
+ "content": [
106
+ {"type": "text", "text": "What is"},
107
+ {"type": "text", "text": " the answer?"}
108
+ ]
109
+ }
110
+ ]
111
+ })
112
+
113
+ assert res.status_code == 200
114
+ assert res.body["type"] == "message"
115
+
116
+
117
+ def test_anthropic_messages_conversation():
118
+ """Test multi-turn conversation"""
119
+ server.start()
120
+
121
+ res = server.make_request("POST", "/v1/messages", data={
122
+ "model": "test",
123
+ "max_tokens": 50,
124
+ "messages": [
125
+ {"role": "user", "content": "Hello"},
126
+ {"role": "assistant", "content": "Hi there!"},
127
+ {"role": "user", "content": "How are you?"}
128
+ ]
129
+ })
130
+
131
+ assert res.status_code == 200
132
+ assert res.body["type"] == "message"
133
+
134
+
135
+ # Streaming tests
136
+
137
+ def test_anthropic_messages_streaming():
138
+ """Test streaming messages"""
139
+ server.start()
140
+
141
+ res = server.make_stream_request("POST", "/v1/messages", data={
142
+ "model": "test",
143
+ "max_tokens": 30,
144
+ "messages": [
145
+ {"role": "user", "content": "Say hello"}
146
+ ],
147
+ "stream": True
148
+ })
149
+
150
+ events = []
151
+ for data in res:
152
+ # Each event should have type and other fields
153
+ assert "type" in data, f"Missing 'type' in event: {data}"
154
+ events.append(data)
155
+
156
+ # Verify event sequence
157
+ event_types = [e["type"] for e in events]
158
+ assert "message_start" in event_types, "Missing message_start event"
159
+ assert "content_block_start" in event_types, "Missing content_block_start event"
160
+ assert "content_block_delta" in event_types, "Missing content_block_delta event"
161
+ assert "content_block_stop" in event_types, "Missing content_block_stop event"
162
+ assert "message_delta" in event_types, "Missing message_delta event"
163
+ assert "message_stop" in event_types, "Missing message_stop event"
164
+
165
+ # Check message_start structure
166
+ message_start = next(e for e in events if e["type"] == "message_start")
167
+ assert "message" in message_start, "message_start missing 'message' field"
168
+ assert message_start["message"]["type"] == "message"
169
+ assert message_start["message"]["role"] == "assistant"
170
+ assert message_start["message"]["content"] == []
171
+ assert "usage" in message_start["message"]
172
+ assert message_start["message"]["usage"]["input_tokens"] > 0
173
+
174
+ # Check content_block_start
175
+ block_start = next(e for e in events if e["type"] == "content_block_start")
176
+ assert "index" in block_start, "content_block_start missing 'index'"
177
+ assert block_start["index"] == 0, "First content block should be at index 0"
178
+ assert "content_block" in block_start
179
+ assert block_start["content_block"]["type"] == "text"
180
+
181
+ # Check content_block_delta
182
+ deltas = [e for e in events if e["type"] == "content_block_delta"]
183
+ assert len(deltas) > 0, "Should have at least one content_block_delta"
184
+ for delta in deltas:
185
+ assert "index" in delta
186
+ assert "delta" in delta
187
+ assert delta["delta"]["type"] == "text_delta"
188
+ assert "text" in delta["delta"]
189
+
190
+ # Check content_block_stop
191
+ block_stop = next(e for e in events if e["type"] == "content_block_stop")
192
+ assert "index" in block_stop
193
+ assert block_stop["index"] == 0
194
+
195
+ # Check message_delta
196
+ message_delta = next(e for e in events if e["type"] == "message_delta")
197
+ assert "delta" in message_delta
198
+ assert "stop_reason" in message_delta["delta"]
199
+ assert message_delta["delta"]["stop_reason"] in ["end_turn", "max_tokens"]
200
+ assert "usage" in message_delta
201
+ assert message_delta["usage"]["output_tokens"] > 0
202
+
203
+ # Check message_stop
204
+ message_stop = next(e for e in events if e["type"] == "message_stop")
205
+ # message_stop should NOT have timings for Anthropic API
206
+ assert "timings" not in message_stop, "Anthropic streaming should not include timings"
207
+
208
+
209
+ # Token counting tests
210
+
211
+ def test_anthropic_count_tokens():
212
+ """Test token counting endpoint"""
213
+ server.start()
214
+
215
+ res = server.make_request("POST", "/v1/messages/count_tokens", data={
216
+ "model": "test",
217
+ "messages": [
218
+ {"role": "user", "content": "Hello world"}
219
+ ]
220
+ })
221
+
222
+ assert res.status_code == 200
223
+ assert "input_tokens" in res.body
224
+ assert isinstance(res.body["input_tokens"], int)
225
+ assert res.body["input_tokens"] > 0
226
+ # Should only have input_tokens, no other fields
227
+ assert "output_tokens" not in res.body
228
+
229
+
230
+ def test_anthropic_count_tokens_with_system():
231
+ """Test token counting with system prompt"""
232
+ server.start()
233
+
234
+ res = server.make_request("POST", "/v1/messages/count_tokens", data={
235
+ "model": "test",
236
+ "system": "You are a helpful assistant.",
237
+ "messages": [
238
+ {"role": "user", "content": "Hello"}
239
+ ]
240
+ })
241
+
242
+ assert res.status_code == 200
243
+ assert res.body["input_tokens"] > 0
244
+
245
+
246
+ def test_anthropic_count_tokens_no_max_tokens():
247
+ """Test that count_tokens doesn't require max_tokens"""
248
+ server.start()
249
+
250
+ # max_tokens is NOT required for count_tokens
251
+ res = server.make_request("POST", "/v1/messages/count_tokens", data={
252
+ "model": "test",
253
+ "messages": [
254
+ {"role": "user", "content": "Hello"}
255
+ ]
256
+ })
257
+
258
+ assert res.status_code == 200
259
+ assert "input_tokens" in res.body
260
+
261
+
262
+ # Tool use tests
263
+
264
+ def test_anthropic_tool_use_basic():
265
+ """Test basic tool use"""
266
+ server.jinja = True
267
+ server.start()
268
+
269
+ res = server.make_request("POST", "/v1/messages", data={
270
+ "model": "test",
271
+ "max_tokens": 200,
272
+ "tools": [{
273
+ "name": "get_weather",
274
+ "description": "Get the current weather in a location",
275
+ "input_schema": {
276
+ "type": "object",
277
+ "properties": {
278
+ "location": {
279
+ "type": "string",
280
+ "description": "City name"
281
+ }
282
+ },
283
+ "required": ["location"]
284
+ }
285
+ }],
286
+ "messages": [
287
+ {"role": "user", "content": "What's the weather in Paris?"}
288
+ ]
289
+ })
290
+
291
+ assert res.status_code == 200
292
+ assert res.body["type"] == "message"
293
+ assert len(res.body["content"]) > 0
294
+
295
+ # Check if model used the tool (it might not always, depending on the model)
296
+ content_types = [block.get("type") for block in res.body["content"]]
297
+
298
+ if "tool_use" in content_types:
299
+ # Model used the tool
300
+ assert res.body["stop_reason"] == "tool_use"
301
+
302
+ # Find the tool_use block
303
+ tool_block = next(b for b in res.body["content"] if b.get("type") == "tool_use")
304
+ assert "id" in tool_block
305
+ assert "name" in tool_block
306
+ assert tool_block["name"] == "get_weather"
307
+ assert "input" in tool_block
308
+ assert isinstance(tool_block["input"], dict)
309
+
310
+
311
+ def test_anthropic_tool_result():
312
+ """Test sending tool results back
313
+
314
+ This test verifies that tool_result blocks are properly converted to
315
+ role="tool" messages internally. Without proper conversion, this would
316
+ fail with a 500 error: "unsupported content[].type" because tool_result
317
+ blocks would remain in the user message content array.
318
+ """
319
+ server.jinja = True
320
+ server.start()
321
+
322
+ res = server.make_request("POST", "/v1/messages", data={
323
+ "model": "test",
324
+ "max_tokens": 100,
325
+ "messages": [
326
+ {"role": "user", "content": "What's the weather?"},
327
+ {
328
+ "role": "assistant",
329
+ "content": [
330
+ {
331
+ "type": "tool_use",
332
+ "id": "test123",
333
+ "name": "get_weather",
334
+ "input": {"location": "Paris"}
335
+ }
336
+ ]
337
+ },
338
+ {
339
+ "role": "user",
340
+ "content": [
341
+ {
342
+ "type": "tool_result",
343
+ "tool_use_id": "test123",
344
+ "content": "The weather is sunny, 25°C"
345
+ }
346
+ ]
347
+ }
348
+ ]
349
+ })
350
+
351
+ # This would be 500 with the old bug where tool_result blocks weren't converted
352
+ assert res.status_code == 200
353
+ assert res.body["type"] == "message"
354
+ # Model should respond to the tool result
355
+ assert len(res.body["content"]) > 0
356
+ assert res.body["content"][0]["type"] == "text"
357
+
358
+
359
+ def test_anthropic_tool_result_with_text():
360
+ """Test tool result mixed with text content
361
+
362
+ This tests the edge case where a user message contains both text and
363
+ tool_result blocks. The server must properly split these into separate
364
+ messages: a user message with text, followed by tool messages.
365
+ Without proper handling, this would fail with 500: "unsupported content[].type"
366
+ """
367
+ server.jinja = True
368
+ server.start()
369
+
370
+ res = server.make_request("POST", "/v1/messages", data={
371
+ "model": "test",
372
+ "max_tokens": 100,
373
+ "messages": [
374
+ {"role": "user", "content": "What's the weather?"},
375
+ {
376
+ "role": "assistant",
377
+ "content": [
378
+ {
379
+ "type": "tool_use",
380
+ "id": "tool_1",
381
+ "name": "get_weather",
382
+ "input": {"location": "Paris"}
383
+ }
384
+ ]
385
+ },
386
+ {
387
+ "role": "user",
388
+ "content": [
389
+ {"type": "text", "text": "Here are the results:"},
390
+ {
391
+ "type": "tool_result",
392
+ "tool_use_id": "tool_1",
393
+ "content": "Sunny, 25°C"
394
+ }
395
+ ]
396
+ }
397
+ ]
398
+ })
399
+
400
+ assert res.status_code == 200
401
+ assert res.body["type"] == "message"
402
+ assert len(res.body["content"]) > 0
403
+
404
+
405
+ def test_anthropic_tool_result_with_image():
406
+ """Test tool result containing mixed text and image blocks
407
+
408
+ Verifies that image blocks inside Anthropic tool_result content are
409
+ properly converted to OpenAI image_url format rather than being
410
+ silently dropped. With a non-multimodal model, the converted image
411
+ triggers a clear error message instead of being ignored.
412
+ """
413
+ server.jinja = True
414
+ server.start()
415
+
416
+ # Small 1x1 red PNG image in base64 (same as vision tests)
417
+ red_pixel_png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg=="
418
+
419
+ res = server.make_request("POST", "/v1/messages", data={
420
+ "model": "test",
421
+ "max_tokens": 100,
422
+ "messages": [
423
+ {"role": "user", "content": "What is in this image?"},
424
+ {
425
+ "role": "assistant",
426
+ "content": [
427
+ {
428
+ "type": "tool_use",
429
+ "id": "tool_1",
430
+ "name": "read",
431
+ "input": {"file": "test.png"}
432
+ }
433
+ ]
434
+ },
435
+ {
436
+ "role": "user",
437
+ "content": [
438
+ {
439
+ "type": "tool_result",
440
+ "tool_use_id": "tool_1",
441
+ "content": [
442
+ {"type": "text", "text": "File: test.png"},
443
+ {
444
+ "type": "image",
445
+ "source": {
446
+ "type": "base64",
447
+ "media_type": "image/png",
448
+ "data": red_pixel_png
449
+ }
450
+ }
451
+ ]
452
+ }
453
+ ]
454
+ }
455
+ ]
456
+ })
457
+
458
+ # Without the fix, image block would cause "unsupported content[].type"
459
+ # With the fix, image is converted to image_url but tinyllama doesn't support images
460
+ assert res.status_code == 500
461
+ assert "image input is not supported" in res.body.get("error", {}).get("message", "").lower()
462
+
463
+
464
+ def test_anthropic_tool_result_error():
465
+ """Test tool result with error flag"""
466
+ server.jinja = True
467
+ server.start()
468
+
469
+ res = server.make_request("POST", "/v1/messages", data={
470
+ "model": "test",
471
+ "max_tokens": 100,
472
+ "messages": [
473
+ {"role": "user", "content": "Get the weather"},
474
+ {
475
+ "role": "assistant",
476
+ "content": [
477
+ {
478
+ "type": "tool_use",
479
+ "id": "test123",
480
+ "name": "get_weather",
481
+ "input": {"location": "InvalidCity"}
482
+ }
483
+ ]
484
+ },
485
+ {
486
+ "role": "user",
487
+ "content": [
488
+ {
489
+ "type": "tool_result",
490
+ "tool_use_id": "test123",
491
+ "is_error": True,
492
+ "content": "City not found"
493
+ }
494
+ ]
495
+ }
496
+ ]
497
+ })
498
+
499
+ assert res.status_code == 200
500
+ assert res.body["type"] == "message"
501
+
502
+
503
+ def test_anthropic_tool_streaming():
504
+ """Test streaming with tool use"""
505
+ server.jinja = True
506
+ server.start()
507
+
508
+ res = server.make_stream_request("POST", "/v1/messages", data={
509
+ "model": "test",
510
+ "max_tokens": 200,
511
+ "stream": True,
512
+ "tools": [{
513
+ "name": "calculator",
514
+ "description": "Calculate math",
515
+ "input_schema": {
516
+ "type": "object",
517
+ "properties": {
518
+ "expression": {"type": "string"}
519
+ },
520
+ "required": ["expression"]
521
+ }
522
+ }],
523
+ "messages": [
524
+ {"role": "user", "content": "Calculate 2+2"}
525
+ ]
526
+ })
527
+
528
+ events = []
529
+ for data in res:
530
+ events.append(data)
531
+
532
+ event_types = [e["type"] for e in events]
533
+
534
+ # Should have basic events
535
+ assert "message_start" in event_types
536
+ assert "message_stop" in event_types
537
+
538
+ # If tool was used, check for proper tool streaming
539
+ if any(e.get("type") == "content_block_start" and
540
+ e.get("content_block", {}).get("type") == "tool_use"
541
+ for e in events):
542
+ # Find tool use block start
543
+ tool_starts = [e for e in events if
544
+ e.get("type") == "content_block_start" and
545
+ e.get("content_block", {}).get("type") == "tool_use"]
546
+
547
+ assert len(tool_starts) > 0, "Should have tool_use content_block_start"
548
+
549
+ # Check index is correct (should be 0 if no text, 1 if there's text)
550
+ tool_start = tool_starts[0]
551
+ assert "index" in tool_start
552
+ assert tool_start["content_block"]["type"] == "tool_use"
553
+ assert "name" in tool_start["content_block"]
554
+
555
+
556
+ # Vision/multimodal tests
557
+
558
+ def test_anthropic_vision_format_accepted():
559
+ """Test that Anthropic vision format is accepted (format validation only)"""
560
+ server.start()
561
+
562
+ # Small 1x1 red PNG image in base64
563
+ red_pixel_png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg=="
564
+
565
+ res = server.make_request("POST", "/v1/messages", data={
566
+ "model": "test",
567
+ "max_tokens": 10,
568
+ "messages": [
569
+ {
570
+ "role": "user",
571
+ "content": [
572
+ {
573
+ "type": "image",
574
+ "source": {
575
+ "type": "base64",
576
+ "media_type": "image/png",
577
+ "data": red_pixel_png
578
+ }
579
+ },
580
+ {
581
+ "type": "text",
582
+ "text": "What is this?"
583
+ }
584
+ ]
585
+ }
586
+ ]
587
+ })
588
+
589
+ # Server accepts the format but tinyllama doesn't support images
590
+ # So it should return 500 with clear error message about missing mmproj
591
+ assert res.status_code == 500
592
+ assert "image input is not supported" in res.body.get("error", {}).get("message", "").lower()
593
+
594
+
595
+ def test_anthropic_vision_base64_with_multimodal_model(vision_server):
596
+ """Test vision with base64 image using Anthropic format with multimodal model"""
597
+ global server
598
+ server = vision_server
599
+ server.start()
600
+
601
+ # Get test image in base64 format
602
+ image_base64 = get_test_image_base64()
603
+
604
+ res = server.make_request("POST", "/v1/messages", data={
605
+ "model": "test",
606
+ "max_tokens": 10,
607
+ "messages": [
608
+ {
609
+ "role": "user",
610
+ "content": [
611
+ {
612
+ "type": "image",
613
+ "source": {
614
+ "type": "base64",
615
+ "media_type": "image/png",
616
+ "data": image_base64
617
+ }
618
+ },
619
+ {
620
+ "type": "text",
621
+ "text": "What is this:\n"
622
+ }
623
+ ]
624
+ }
625
+ ]
626
+ })
627
+
628
+ assert res.status_code == 200, f"Expected 200, got {res.status_code}: {res.body}"
629
+ assert res.body["type"] == "message"
630
+ assert len(res.body["content"]) > 0
631
+ assert res.body["content"][0]["type"] == "text"
632
+ # The model should generate some response about the image
633
+ assert len(res.body["content"][0]["text"]) > 0
634
+
635
+
636
+ # Parameter tests
637
+
638
+ def test_anthropic_stop_sequences():
639
+ """Test stop_sequences parameter"""
640
+ server.start()
641
+
642
+ res = server.make_request("POST", "/v1/messages", data={
643
+ "model": "test",
644
+ "max_tokens": 100,
645
+ "stop_sequences": ["\n", "END"],
646
+ "messages": [
647
+ {"role": "user", "content": "Count to 10"}
648
+ ]
649
+ })
650
+
651
+ assert res.status_code == 200
652
+ assert res.body["type"] == "message"
653
+
654
+
655
+ def test_anthropic_temperature():
656
+ """Test temperature parameter"""
657
+ server.start()
658
+
659
+ res = server.make_request("POST", "/v1/messages", data={
660
+ "model": "test",
661
+ "max_tokens": 50,
662
+ "temperature": 0.5,
663
+ "messages": [
664
+ {"role": "user", "content": "Hello"}
665
+ ]
666
+ })
667
+
668
+ assert res.status_code == 200
669
+ assert res.body["type"] == "message"
670
+
671
+
672
+ def test_anthropic_top_p():
673
+ """Test top_p parameter"""
674
+ server.start()
675
+
676
+ res = server.make_request("POST", "/v1/messages", data={
677
+ "model": "test",
678
+ "max_tokens": 50,
679
+ "top_p": 0.9,
680
+ "messages": [
681
+ {"role": "user", "content": "Hello"}
682
+ ]
683
+ })
684
+
685
+ assert res.status_code == 200
686
+ assert res.body["type"] == "message"
687
+
688
+
689
+ def test_anthropic_top_k():
690
+ """Test top_k parameter (llama.cpp specific)"""
691
+ server.start()
692
+
693
+ res = server.make_request("POST", "/v1/messages", data={
694
+ "model": "test",
695
+ "max_tokens": 50,
696
+ "top_k": 40,
697
+ "messages": [
698
+ {"role": "user", "content": "Hello"}
699
+ ]
700
+ })
701
+
702
+ assert res.status_code == 200
703
+ assert res.body["type"] == "message"
704
+
705
+
706
+ # Error handling tests
707
+
708
+ def test_anthropic_missing_messages():
709
+ """Test error when messages are missing"""
710
+ server.start()
711
+
712
+ res = server.make_request("POST", "/v1/messages", data={
713
+ "model": "test",
714
+ "max_tokens": 50
715
+ # missing "messages" field
716
+ })
717
+
718
+ # Should return an error (400 or 500)
719
+ assert res.status_code >= 400
720
+
721
+
722
+ def test_anthropic_empty_messages():
723
+ """Test permissive handling of empty messages array"""
724
+ server.start()
725
+
726
+ res = server.make_request("POST", "/v1/messages", data={
727
+ "model": "test",
728
+ "max_tokens": 50,
729
+ "messages": []
730
+ })
731
+
732
+ # Server is permissive and accepts empty messages (provides defaults)
733
+ # This matches the permissive validation design choice
734
+ assert res.status_code == 200
735
+ assert res.body["type"] == "message"
736
+
737
+
738
+ # Content block index tests
739
+
740
+ def test_anthropic_streaming_content_block_indices():
741
+ """Test that content block indices are correct in streaming"""
742
+ server.jinja = True
743
+ server.start()
744
+
745
+ # Request that might produce both text and tool use
746
+ res = server.make_stream_request("POST", "/v1/messages", data={
747
+ "model": "test",
748
+ "max_tokens": 400,
749
+ "stream": True,
750
+ "tools": [{
751
+ "name": "test_tool",
752
+ "description": "A test tool",
753
+ "input_schema": {
754
+ "type": "object",
755
+ "properties": {
756
+ "param": {"type": "string"}
757
+ },
758
+ "required": ["param"]
759
+ }
760
+ }],
761
+ "messages": [
762
+ {"role": "user", "content": "Use the test tool"}
763
+ ]
764
+ })
765
+
766
+ events = []
767
+ for data in res:
768
+ events.append(data)
769
+
770
+ # Check content_block_start events have sequential indices
771
+ block_starts = [e for e in events if e.get("type") == "content_block_start"]
772
+ if len(block_starts) > 1:
773
+ # If there are multiple blocks, indices should be sequential
774
+ indices = [e["index"] for e in block_starts]
775
+ expected_indices = list(range(len(block_starts)))
776
+ assert indices == expected_indices, f"Expected indices {expected_indices}, got {indices}"
777
+
778
+ # Check content_block_stop events match the starts
779
+ block_stops = [e for e in events if e.get("type") == "content_block_stop"]
780
+ start_indices = set(e["index"] for e in block_starts)
781
+ stop_indices = set(e["index"] for e in block_stops)
782
+ assert start_indices == stop_indices, "content_block_stop indices should match content_block_start indices"
783
+
784
+
785
+ # Extended features tests
786
+
787
+ def test_anthropic_thinking():
788
+ """Test extended thinking parameter"""
789
+ server.jinja = True
790
+ server.start()
791
+
792
+ res = server.make_request("POST", "/v1/messages", data={
793
+ "model": "test",
794
+ "max_tokens": 100,
795
+ "thinking": {
796
+ "type": "enabled",
797
+ "budget_tokens": 50
798
+ },
799
+ "messages": [
800
+ {"role": "user", "content": "What is 2+2?"}
801
+ ]
802
+ })
803
+
804
+ assert res.status_code == 200
805
+ assert res.body["type"] == "message"
806
+
807
+
808
+ def test_anthropic_metadata():
809
+ """Test metadata parameter"""
810
+ server.start()
811
+
812
+ res = server.make_request("POST", "/v1/messages", data={
813
+ "model": "test",
814
+ "max_tokens": 50,
815
+ "metadata": {
816
+ "user_id": "test_user_123"
817
+ },
818
+ "messages": [
819
+ {"role": "user", "content": "Hello"}
820
+ ]
821
+ })
822
+
823
+ assert res.status_code == 200
824
+ assert res.body["type"] == "message"
825
+
826
+
827
+ # Compatibility tests
828
+
829
+ def test_anthropic_vs_openai_different_response_format():
830
+ """Verify Anthropic format is different from OpenAI format"""
831
+ server.start()
832
+
833
+ # Make OpenAI request
834
+ openai_res = server.make_request("POST", "/v1/chat/completions", data={
835
+ "model": "test",
836
+ "max_tokens": 50,
837
+ "messages": [
838
+ {"role": "user", "content": "Hello"}
839
+ ]
840
+ })
841
+
842
+ # Make Anthropic request
843
+ anthropic_res = server.make_request("POST", "/v1/messages", data={
844
+ "model": "test",
845
+ "max_tokens": 50,
846
+ "messages": [
847
+ {"role": "user", "content": "Hello"}
848
+ ]
849
+ })
850
+
851
+ assert openai_res.status_code == 200
852
+ assert anthropic_res.status_code == 200
853
+
854
+ # OpenAI has "object", Anthropic has "type"
855
+ assert "object" in openai_res.body
856
+ assert "type" in anthropic_res.body
857
+ assert openai_res.body["object"] == "chat.completion"
858
+ assert anthropic_res.body["type"] == "message"
859
+
860
+ # OpenAI has "choices", Anthropic has "content"
861
+ assert "choices" in openai_res.body
862
+ assert "content" in anthropic_res.body
863
+
864
+ # Different usage field names
865
+ assert "prompt_tokens" in openai_res.body["usage"]
866
+ assert "input_tokens" in anthropic_res.body["usage"]
867
+ assert "completion_tokens" in openai_res.body["usage"]
868
+ assert "output_tokens" in anthropic_res.body["usage"]
869
+
870
+
871
+ # Extended thinking tests with reasoning models
872
+
873
+ # The next two tests cover the input path (conversation history):
874
+ # Client sends thinking blocks -> convert_anthropic_to_oai -> reasoning_content -> template
875
+
876
+ def test_anthropic_thinking_history_in_count_tokens():
877
+ """Test that interleaved thinking blocks in conversation history are not dropped during conversion."""
878
+ global server
879
+ server.jinja = True
880
+ server.chat_template_file = '../../../models/templates/Qwen-Qwen3-0.6B.jinja'
881
+ server.start()
882
+
883
+ tool = {
884
+ "name": "list_files",
885
+ "description": "List files",
886
+ "input_schema": {
887
+ "type": "object",
888
+ "properties": {"path": {"type": "string"}},
889
+ "required": ["path"]
890
+ }
891
+ }
892
+
893
+ messages_without_thinking = [
894
+ {"role": "user", "content": "Fix the bug"},
895
+ {
896
+ "role": "assistant",
897
+ "content": [
898
+ {"type": "tool_use", "id": "call_1", "name": "list_files", "input": {"path": "."}}
899
+ ]
900
+ },
901
+ {
902
+ "role": "user",
903
+ "content": [
904
+ {"type": "tool_result", "tool_use_id": "call_1", "content": "main.py"}
905
+ ]
906
+ },
907
+ ]
908
+
909
+ messages_with_thinking = [
910
+ {"role": "user", "content": "Fix the bug"},
911
+ {
912
+ "role": "assistant",
913
+ "content": [
914
+ {"type": "thinking", "thinking": "I should check the project structure first to understand the codebase layout."},
915
+ {"type": "tool_use", "id": "call_1", "name": "list_files", "input": {"path": "."}}
916
+ ]
917
+ },
918
+ {
919
+ "role": "user",
920
+ "content": [
921
+ {"type": "tool_result", "tool_use_id": "call_1", "content": "main.py"}
922
+ ]
923
+ },
924
+ ]
925
+
926
+ res_without = server.make_request("POST", "/v1/messages/count_tokens", data={
927
+ "model": "test",
928
+ "messages": messages_without_thinking,
929
+ "tools": [tool],
930
+ })
931
+ assert res_without.status_code == 200, f"Expected 200: {res_without.body}"
932
+
933
+ res_with = server.make_request("POST", "/v1/messages/count_tokens", data={
934
+ "model": "test",
935
+ "messages": messages_with_thinking,
936
+ "tools": [tool],
937
+ })
938
+ assert res_with.status_code == 200, f"Expected 200: {res_with.body}"
939
+
940
+ # Thinking blocks should increase the token count
941
+ assert res_with.body["input_tokens"] > res_without.body["input_tokens"], \
942
+ f"Expected more tokens with thinking ({res_with.body['input_tokens']}) than without ({res_without.body['input_tokens']})"
943
+
944
+
945
+ def test_anthropic_thinking_history_in_template():
946
+ """Test that reasoning_content from converted interleaved thinking blocks renders in the prompt."""
947
+ global server
948
+ server.jinja = True
949
+ server.chat_template_file = '../../../models/templates/Qwen-Qwen3-0.6B.jinja'
950
+ server.start()
951
+
952
+ reasoning_1 = "I should check the project structure first."
953
+ reasoning_2 = "Now I need to read the main file."
954
+
955
+ res = server.make_request("POST", "/apply-template", data={
956
+ "messages": [
957
+ {"role": "user", "content": "Fix the bug in main.py"},
958
+ {
959
+ "role": "assistant",
960
+ "content": "",
961
+ "reasoning_content": reasoning_1,
962
+ "tool_calls": [{
963
+ "id": "call_1",
964
+ "type": "function",
965
+ "function": {"name": "list_files", "arguments": "{\"path\": \".\"}"}
966
+ }]
967
+ },
968
+ {"role": "tool", "tool_call_id": "call_1", "content": "main.py\nutils.py"},
969
+ {
970
+ "role": "assistant",
971
+ "content": "",
972
+ "reasoning_content": reasoning_2,
973
+ "tool_calls": [{
974
+ "id": "call_2",
975
+ "type": "function",
976
+ "function": {"name": "read_file", "arguments": "{\"path\": \"main.py\"}"}
977
+ }]
978
+ },
979
+ {"role": "tool", "tool_call_id": "call_2", "content": "print('hello')"},
980
+ ],
981
+ "tools": [{
982
+ "type": "function",
983
+ "function": {
984
+ "name": "list_files",
985
+ "description": "List files",
986
+ "parameters": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}
987
+ }
988
+ }, {
989
+ "type": "function",
990
+ "function": {
991
+ "name": "read_file",
992
+ "description": "Read a file",
993
+ "parameters": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}
994
+ }
995
+ }],
996
+ })
997
+ assert res.status_code == 200, f"Expected 200, got {res.status_code}: {res.body}"
998
+ prompt = res.body["prompt"]
999
+
1000
+ # Both reasoning_content values should be rendered in <think> tags
1001
+ assert reasoning_1 in prompt, f"Expected first reasoning text in prompt: {prompt}"
1002
+ assert reasoning_2 in prompt, f"Expected second reasoning text in prompt: {prompt}"
1003
+ assert prompt.count("<think>") >= 2, f"Expected at least 2 <think> blocks in prompt: {prompt}"
1004
+
1005
+
1006
+ @pytest.mark.slow
1007
+ @pytest.mark.parametrize("stream", [False, True])
1008
+ def test_anthropic_thinking_with_reasoning_model(stream):
1009
+ """Test that thinking content blocks are properly returned for reasoning models"""
1010
+ global server
1011
+ server = ServerProcess()
1012
+ server.model_hf_repo = "bartowski/DeepSeek-R1-Distill-Qwen-7B-GGUF"
1013
+ server.model_hf_file = "DeepSeek-R1-Distill-Qwen-7B-Q4_K_M.gguf"
1014
+ server.reasoning_format = "deepseek"
1015
+ server.jinja = True
1016
+ server.n_ctx = 8192
1017
+ server.n_predict = 1024
1018
+ server.server_port = 8084
1019
+ server.start(timeout_seconds=600) # large model needs time to download
1020
+
1021
+ if stream:
1022
+ res = server.make_stream_request("POST", "/v1/messages", data={
1023
+ "model": "test",
1024
+ "max_tokens": 1024,
1025
+ "thinking": {
1026
+ "type": "enabled",
1027
+ "budget_tokens": 500
1028
+ },
1029
+ "messages": [
1030
+ {"role": "user", "content": "What is 2+2?"}
1031
+ ],
1032
+ "stream": True
1033
+ })
1034
+
1035
+ events = list(res)
1036
+
1037
+ # should have thinking content block events
1038
+ thinking_starts = [e for e in events if
1039
+ e.get("type") == "content_block_start" and
1040
+ e.get("content_block", {}).get("type") == "thinking"]
1041
+ assert len(thinking_starts) > 0, "Should have thinking content_block_start event"
1042
+ assert thinking_starts[0]["index"] == 0, "Thinking block should be at index 0"
1043
+
1044
+ # should have thinking_delta events
1045
+ thinking_deltas = [e for e in events if
1046
+ e.get("type") == "content_block_delta" and
1047
+ e.get("delta", {}).get("type") == "thinking_delta"]
1048
+ assert len(thinking_deltas) > 0, "Should have thinking_delta events"
1049
+
1050
+ # should have signature_delta event before thinking block closes (Anthropic API requirement)
1051
+ signature_deltas = [e for e in events if
1052
+ e.get("type") == "content_block_delta" and
1053
+ e.get("delta", {}).get("type") == "signature_delta"]
1054
+ assert len(signature_deltas) > 0, "Should have signature_delta event for thinking block"
1055
+
1056
+ # should have text block after thinking
1057
+ text_starts = [e for e in events if
1058
+ e.get("type") == "content_block_start" and
1059
+ e.get("content_block", {}).get("type") == "text"]
1060
+ assert len(text_starts) > 0, "Should have text content_block_start event"
1061
+ assert text_starts[0]["index"] == 1, "Text block should be at index 1 (after thinking)"
1062
+ else:
1063
+ res = server.make_request("POST", "/v1/messages", data={
1064
+ "model": "test",
1065
+ "max_tokens": 1024,
1066
+ "thinking": {
1067
+ "type": "enabled",
1068
+ "budget_tokens": 500
1069
+ },
1070
+ "messages": [
1071
+ {"role": "user", "content": "What is 2+2?"}
1072
+ ]
1073
+ })
1074
+
1075
+ assert res.status_code == 200
1076
+ assert res.body["type"] == "message"
1077
+
1078
+ content = res.body["content"]
1079
+ assert len(content) >= 2, "Should have at least thinking and text blocks"
1080
+
1081
+ # first block should be thinking
1082
+ thinking_blocks = [b for b in content if b.get("type") == "thinking"]
1083
+ assert len(thinking_blocks) > 0, "Should have thinking content block"
1084
+ assert "thinking" in thinking_blocks[0], "Thinking block should have 'thinking' field"
1085
+ assert len(thinking_blocks[0]["thinking"]) > 0, "Thinking content should not be empty"
1086
+ assert "signature" in thinking_blocks[0], "Thinking block should have 'signature' field (Anthropic API requirement)"
1087
+
1088
+ # should also have text block
1089
+ text_blocks = [b for b in content if b.get("type") == "text"]
1090
+ assert len(text_blocks) > 0, "Should have text content block"
tools/server/tests/unit/test_compat_gcp.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from utils import *
3
+
4
+ server: ServerProcess
5
+
6
+
7
+ @pytest.fixture(autouse=True)
8
+ def create_server():
9
+ global server
10
+ server = ServerPreset.tinyllama2()
11
+ server.gcp_compat = True
12
+
13
+
14
+ def test_gcp_predict_camel_case():
15
+ global server
16
+ server.start()
17
+ res = server.make_request("POST", "/predict", data={
18
+ "instances": [
19
+ {
20
+ "@requestFormat": "chatCompletions",
21
+ "max_tokens": 8,
22
+ "messages": [
23
+ {"role": "user", "content": "What is the meaning of life?"},
24
+ ],
25
+ }
26
+ ],
27
+ })
28
+ assert res.status_code == 200
29
+ assert "predictions" in res.body
30
+ assert len(res.body["predictions"]) == 1
31
+ prediction = res.body["predictions"][0]
32
+ assert "choices" in prediction
33
+ assert len(prediction["choices"]) == 1
34
+ assert prediction["choices"][0]["message"]["role"] == "assistant"
35
+ assert len(prediction["choices"][0]["message"]["content"]) > 0
36
+
37
+
38
+ def test_gcp_predict_multiple_instances():
39
+ global server
40
+ server.n_slots = 2
41
+ server.start()
42
+ res = server.make_request("POST", "/predict", data={
43
+ "instances": [
44
+ {
45
+ "@requestFormat": "chatCompletions",
46
+ "max_tokens": 8,
47
+ "messages": [{"role": "user", "content": "Say hello"}],
48
+ },
49
+ {
50
+ "@requestFormat": "chatCompletions",
51
+ "max_tokens": 8,
52
+ "messages": [{"role": "user", "content": "Say world"}],
53
+ },
54
+ ],
55
+ })
56
+ assert res.status_code == 200
57
+ assert len(res.body["predictions"]) == 2
58
+ for prediction in res.body["predictions"]:
59
+ assert "choices" in prediction
60
+ assert len(prediction["choices"][0]["message"]["content"]) > 0
tools/server/tests/unit/test_compat_oai_responses.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from openai import OpenAI
3
+ from utils import *
4
+
5
+ server: ServerProcess
6
+
7
+ @pytest.fixture(autouse=True)
8
+ def create_server():
9
+ global server
10
+ server = ServerPreset.tinyllama2()
11
+
12
+ def test_responses_with_openai_library():
13
+ global server
14
+ server.start()
15
+ client = OpenAI(api_key="dummy", base_url=f"http://{server.server_host}:{server.server_port}/v1")
16
+ res = client.responses.create(
17
+ model="gpt-4.1",
18
+ input=[
19
+ {"role": "system", "content": "Book"},
20
+ {"role": "user", "content": "What is the best book"},
21
+ ],
22
+ max_output_tokens=8,
23
+ temperature=0.8,
24
+ )
25
+ assert res.id.startswith("resp_")
26
+ assert res.output[0].id is not None
27
+ assert res.output[0].id.startswith("msg_")
28
+ assert match_regex("(Suddenly)+", res.output_text)
29
+
30
+ def test_responses_stream_with_openai_library():
31
+ global server
32
+ server.start()
33
+ client = OpenAI(api_key="dummy", base_url=f"http://{server.server_host}:{server.server_port}/v1")
34
+ stream = client.responses.create(
35
+ model="gpt-4.1",
36
+ input=[
37
+ {"role": "system", "content": "Book"},
38
+ {"role": "user", "content": "What is the best book"},
39
+ ],
40
+ max_output_tokens=8,
41
+ temperature=0.8,
42
+ stream=True,
43
+ )
44
+
45
+ gathered_text = ''
46
+ resp_id = ''
47
+ msg_id = ''
48
+ for r in stream:
49
+ if r.type == "response.created":
50
+ assert r.response.id.startswith("resp_")
51
+ resp_id = r.response.id
52
+ if r.type == "response.in_progress":
53
+ assert r.response.id == resp_id
54
+ if r.type == "response.output_item.added":
55
+ assert r.item.id is not None
56
+ assert r.item.id.startswith("msg_")
57
+ msg_id = r.item.id
58
+ if (r.type == "response.content_part.added" or
59
+ r.type == "response.output_text.delta" or
60
+ r.type == "response.output_text.done" or
61
+ r.type == "response.content_part.done"):
62
+ assert r.item_id == msg_id
63
+ if r.type == "response.output_item.done":
64
+ assert r.item.id == msg_id
65
+
66
+ if r.type == "response.output_text.delta":
67
+ gathered_text += r.delta
68
+ if r.type == "response.completed":
69
+ assert r.response.id.startswith("resp_")
70
+ assert r.response.output[0].id is not None
71
+ assert r.response.output[0].id.startswith("msg_")
72
+ assert gathered_text == r.response.output_text
73
+ assert match_regex("(Suddenly)+", r.response.output_text)
74
+
75
+
76
+ def test_responses_stream_with_llama_telemetry():
77
+ global server
78
+ server.n_ctx = 256
79
+ server.n_batch = 32
80
+ server.n_slots = 1
81
+ server.start()
82
+
83
+ saw_progress = False
84
+ saw_delta_timings = False
85
+ completed = None
86
+
87
+ res = server.make_stream_request("POST", "/responses", data={
88
+ "input": "This is a test" * 10,
89
+ "max_output_tokens": 8,
90
+ "temperature": 0.8,
91
+ "stream": True,
92
+ "timings_per_token": True,
93
+ "return_progress": True,
94
+ })
95
+
96
+ for data in res:
97
+ if "prompt_progress" in data:
98
+ assert data["type"] == "response.in_progress"
99
+ assert data["prompt_progress"]["total"] > 0
100
+ assert data["prompt_progress"]["processed"] >= data["prompt_progress"]["cache"]
101
+ saw_progress = True
102
+ if "timings" in data:
103
+ assert "prompt_per_second" in data["timings"]
104
+ assert "predicted_per_second" in data["timings"]
105
+ if data["type"] == "response.output_text.delta":
106
+ saw_delta_timings = True
107
+ if data["type"] == "response.completed":
108
+ completed = data
109
+
110
+ assert saw_progress
111
+ assert saw_delta_timings
112
+ assert completed is not None
113
+ assert "usage" in completed["response"]
114
+ assert "timings" in completed