llmp 0.1.0

Measures how well a local LLM setup uses its model: a recording proxy and a prompt-reuse analysis
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
use std::collections::{BTreeMap, BTreeSet};
use std::time::Duration;

use bytes::Bytes;
use http_body_util::{BodyExt, Full};
use hyper::client::conn::http1::{self, SendRequest};
use hyper::{Method, Request, Uri, header};
use hyper_util::rt::TokioIo;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use tokio::net::TcpStream;

use crate::hash;
use crate::normalize::{self, Api};
use crate::record::{self, Record, TokenCounts};

const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
const REQUEST_TIMEOUT: Duration = Duration::from_secs(60);

#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct TokenizeResult {
    pub counted: u64,
    pub warnings: Vec<String>,
}

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Kind {
    Message,
    Tool,
}

struct Text {
    kind: Kind,
    hash: String,
    text: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Flavor {
    LlamaCpp,
    Ollama,
}

#[derive(Debug)]
struct Endpoint {
    socket: String,
    authority: String,
    base: String,
}

pub fn enrich(records: &mut [Record], server: &str) -> TokenizeResult {
    let mut result = TokenizeResult::default();
    let endpoint = match Endpoint::parse(server) {
        Ok(endpoint) => endpoint,
        Err(warning) => {
            result.warnings.push(warning);
            return result;
        }
    };
    let (texts, models, digest_records) = collect(records);
    if digest_records > 0 {
        result.warnings.push(format!(
            "{digest_records} records were recorded in digest mode and have no text to tokenize"
        ));
    }
    if models.len() > 1 {
        result.warnings.push(format!(
            "the recording uses {} models; every text was counted with the tokenizer of the model {server} serves",
            models.len()
        ));
    }
    if texts.is_empty() {
        return result;
    }
    let model = models.into_iter().next().unwrap_or_default();
    let run =
        std::thread::scope(|scope| scope.spawn(|| count_all(&endpoint, &model, &texts)).join());
    let (counts, warnings) = run.unwrap_or_else(|_| {
        (
            BTreeMap::new(),
            vec!["the tokenize thread panicked".to_string()],
        )
    });
    result.warnings.extend(warnings);
    result.counted = counts.len() as u64;
    apply(records, &counts);
    result
}

impl Endpoint {
    fn parse(server: &str) -> Result<Endpoint, String> {
        let uri: Uri = server
            .parse()
            .map_err(|e| format!("--tokenize {server}: not a URL: {e}"))?;
        match uri.scheme_str() {
            Some("http") => {}
            Some(other) => {
                return Err(format!(
                    "--tokenize {server}: only http:// is supported, not {other}://"
                ));
            }
            None => return Err(format!("--tokenize {server}: the URL needs http://")),
        }
        let authority = uri
            .authority()
            .ok_or_else(|| format!("--tokenize {server}: the URL has no host"))?;
        let port = authority.port_u16().unwrap_or(80);
        Ok(Endpoint {
            socket: format!("{}:{port}", authority.host()),
            authority: authority.to_string(),
            base: uri.path().trim_end_matches('/').to_string(),
        })
    }
}

fn collect(records: &[Record]) -> (Vec<Text>, BTreeSet<String>, usize) {
    let mut texts = Vec::new();
    let mut seen = BTreeSet::new();
    let mut models = BTreeSet::new();
    let mut digest_records = 0;
    for record in records {
        let api = normalize::detect_api(&record.request.path);
        if api == Api::Other {
            continue;
        }
        if record.request.digest.is_some() {
            digest_records += 1;
            continue;
        }
        let Some(body) = &record.request.body else {
            continue;
        };
        let Some(digest) = record::request_digest(api, body) else {
            continue;
        };
        if let Some(model) = digest.model {
            models.insert(model);
        }
        let known = record.tokens.as_ref();
        let messages = body.get("messages").and_then(Value::as_array);
        for (message, value) in digest.messages.iter().zip(messages.into_iter().flatten()) {
            let counted = known.is_some_and(|t| t.messages.contains_key(&message.hash));
            if !counted && seen.insert((Kind::Message, message.hash.clone())) {
                texts.push(Text {
                    kind: Kind::Message,
                    hash: message.hash.clone(),
                    text: record::message_text(value),
                });
            }
        }
        let tools = body.get("tools").and_then(Value::as_array);
        for (tool, value) in digest.tools.iter().zip(tools.into_iter().flatten()) {
            let counted = known.is_some_and(|t| t.tools.contains_key(&tool.hash));
            if !counted && seen.insert((Kind::Tool, tool.hash.clone())) {
                texts.push(Text {
                    kind: Kind::Tool,
                    hash: tool.hash.clone(),
                    text: hash::canonical_json(value),
                });
            }
        }
    }
    (texts, models, digest_records)
}

fn apply(records: &mut [Record], counts: &Counts) {
    if counts.is_empty() {
        return;
    }
    for record in records.iter_mut() {
        let api = normalize::detect_api(&record.request.path);
        let Some(digest) = record
            .request
            .body
            .as_ref()
            .filter(|_| api != Api::Other)
            .and_then(|body| record::request_digest(api, body))
        else {
            continue;
        };
        let mut added = TokenCounts::default();
        for message in &digest.messages {
            if let Some(&n) = counts.get(&(Kind::Message, message.hash.clone())) {
                added.messages.insert(message.hash.clone(), n);
            }
        }
        for tool in &digest.tools {
            if let Some(&n) = counts.get(&(Kind::Tool, tool.hash.clone())) {
                added.tools.insert(tool.hash.clone(), n);
            }
        }
        if added.messages.is_empty() && added.tools.is_empty() {
            continue;
        }
        let tokens = record.tokens.get_or_insert_with(TokenCounts::default);
        tokens.messages.extend(added.messages);
        tokens.tools.extend(added.tools);
    }
}

type Counts = BTreeMap<(Kind, String), u32>;

fn count_all(endpoint: &Endpoint, model: &str, texts: &[Text]) -> (Counts, Vec<String>) {
    let runtime = match tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
    {
        Ok(runtime) => runtime,
        Err(e) => {
            return (
                Counts::new(),
                vec![format!("cannot start the tokenize runtime: {e}")],
            );
        }
    };
    runtime.block_on(async {
        let mut counts = Counts::new();
        let mut warnings = Vec::new();
        let mut client = Client {
            endpoint,
            sender: None,
        };
        let mut flavor = None;
        let mut failed = 0u64;
        for text in texts {
            let key = (text.kind, text.hash.clone());
            if text.text.is_empty() {
                counts.insert(key, 0);
                continue;
            }
            let flavor = match flavor {
                Some(flavor) => flavor,
                None => match detect(&mut client, model, &text.text).await {
                    Ok((detected, n)) => {
                        flavor = Some(detected);
                        counts.insert(key, n);
                        continue;
                    }
                    Err(warning) => {
                        warnings.push(warning);
                        return (counts, warnings);
                    }
                },
            };
            match count(&mut client, flavor, model, &text.text).await {
                Ok(Some(n)) => {
                    counts.insert(key, n);
                }
                Ok(None) => failed += 1,
                Err(warning) => {
                    warnings.push(format!(
                        "{warning}; {} texts were not counted",
                        texts.len() - counts.len()
                    ));
                    return (counts, warnings);
                }
            }
        }
        if failed > 0 {
            warnings.push(format!(
                "{failed} texts could not be tokenized and keep their estimate"
            ));
        }
        (counts, warnings)
    })
}

async fn detect(client: &mut Client<'_>, model: &str, text: &str) -> Result<(Flavor, u32), String> {
    let socket = client.endpoint.socket.clone();
    let mut statuses = Vec::new();
    for flavor in [Flavor::LlamaCpp, Flavor::Ollama] {
        let (path, body) = request(client.endpoint, flavor, model, text);
        let (status, reply) = client.post(&path, &body).await.map_err(|e| {
            format!("cannot reach the tokenize endpoint at {socket}: {e}; estimates are kept")
        })?;
        if let Some(n) = tokens(status, &reply) {
            return Ok((flavor, n));
        }
        statuses.push(format!("{path} answered {status}"));
    }
    Err(format!(
        "no tokenize endpoint at {socket} ({}); estimates are kept",
        statuses.join(", ")
    ))
}

async fn count(
    client: &mut Client<'_>,
    flavor: Flavor,
    model: &str,
    text: &str,
) -> Result<Option<u32>, String> {
    let (path, body) = request(client.endpoint, flavor, model, text);
    let (status, reply) = client.post(&path, &body).await.map_err(|e| {
        format!(
            "lost the tokenize endpoint at {}: {e}",
            client.endpoint.socket
        )
    })?;
    Ok(tokens(status, &reply))
}

fn request(endpoint: &Endpoint, flavor: Flavor, model: &str, text: &str) -> (String, Value) {
    match flavor {
        Flavor::LlamaCpp => (
            format!("{}/tokenize", endpoint.base),
            json!({ "content": text, "add_special": false }),
        ),
        Flavor::Ollama => (
            format!("{}/api/tokenize", endpoint.base),
            json!({ "model": model, "text": text }),
        ),
    }
}

fn tokens(status: u16, reply: &Value) -> Option<u32> {
    if !(200..300).contains(&status) {
        return None;
    }
    let tokens = reply.get("tokens")?.as_array()?;
    u32::try_from(tokens.len()).ok()
}

struct Client<'a> {
    endpoint: &'a Endpoint,
    sender: Option<SendRequest<Full<Bytes>>>,
}

impl Client<'_> {
    async fn post(&mut self, path: &str, body: &Value) -> Result<(u16, Value), String> {
        let bytes = Bytes::from(body.to_string());
        for attempt in 0..2 {
            let reused = self.sender.as_ref().is_some_and(|s| !s.is_closed());
            if !reused {
                self.sender = Some(self.connect().await?);
            }
            let Some(sender) = self.sender.as_mut() else {
                return Err("no connection".into());
            };
            let request = Request::builder()
                .method(Method::POST)
                .uri(path)
                .header(header::HOST, &self.endpoint.authority)
                .header(header::CONTENT_TYPE, "application/json")
                .body(Full::new(bytes.clone()))
                .map_err(|e| e.to_string())?;
            let sent = async {
                sender.ready().await?;
                let response = sender.send_request(request).await?;
                let status = response.status().as_u16();
                let body = response.into_body().collect().await?.to_bytes();
                Ok::<_, hyper::Error>((status, body))
            };
            match tokio::time::timeout(REQUEST_TIMEOUT, sent).await {
                Ok(Ok((status, body))) => {
                    let reply = serde_json::from_slice(&body).unwrap_or(Value::Null);
                    return Ok((status, reply));
                }
                Ok(Err(e)) => {
                    self.sender = None;
                    if reused && attempt == 0 {
                        continue;
                    }
                    return Err(e.to_string());
                }
                Err(_) => {
                    self.sender = None;
                    return Err(format!("no answer within {} s", REQUEST_TIMEOUT.as_secs()));
                }
            }
        }
        Err("connection closed".into())
    }

    async fn connect(&self) -> Result<SendRequest<Full<Bytes>>, String> {
        let stream =
            tokio::time::timeout(CONNECT_TIMEOUT, TcpStream::connect(&self.endpoint.socket))
                .await
                .map_err(|_| format!("connecting took more than {} s", CONNECT_TIMEOUT.as_secs()))?
                .map_err(|e| e.to_string())?;
        let _ = stream.set_nodelay(true);
        let (sender, conn) = http1::handshake(TokioIo::new(stream))
            .await
            .map_err(|e| e.to_string())?;
        tokio::spawn(async move {
            let _ = conn.await;
        });
        Ok(sender)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn endpoint_urls() {
        let e = Endpoint::parse("http://127.0.0.1:8080").unwrap();
        assert_eq!(
            (e.socket.as_str(), e.authority.as_str(), e.base.as_str()),
            ("127.0.0.1:8080", "127.0.0.1:8080", "")
        );
        let e = Endpoint::parse("http://localhost/llama/").unwrap();
        assert_eq!(
            (e.socket.as_str(), e.base.as_str()),
            ("localhost:80", "/llama")
        );
        assert!(
            Endpoint::parse("https://example.com")
                .unwrap_err()
                .contains("only http://")
        );
        assert!(Endpoint::parse("127.0.0.1:8080").is_err());
        assert!(Endpoint::parse("not a url").is_err());
    }

    #[test]
    fn token_replies() {
        assert_eq!(tokens(200, &json!({"tokens": [1, 2, 3]})), Some(3));
        assert_eq!(tokens(200, &json!({"tokens": []})), Some(0));
        assert_eq!(tokens(404, &json!({"tokens": [1]})), None);
        assert_eq!(tokens(200, &json!({"error": "x"})), None);
        assert_eq!(tokens(200, &Value::Null), None);
    }
}