zeph-llm 0.22.4

LLM provider abstraction with Ollama, Claude, OpenAI, and Candle backends
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
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Wiremock fixture helpers for LLM provider tests.
//!
//! Each helper returns a [`wiremock::ResponseTemplate`] that mimics a real
//! provider response.  Pair them with a [`wiremock::MockServer`] to intercept
//! HTTP calls made by [`ClaudeProvider`], [`OpenAiProvider`], or the
//! compatible-endpoint provider.

use std::fmt::Write as _;
use wiremock::ResponseTemplate;

/// Syntactically-valid current Claude model ID for tests that need *some*
/// model string but do not assert on model freshness. Update in one place.
pub const TEST_CLAUDE_MODEL: &str = "claude-sonnet-5";

// ---------------------------------------------------------------------------
// OpenAI-compatible response shapes
// ---------------------------------------------------------------------------

/// Non-streaming `OpenAI` chat completion response.
///
/// Compatible with `OpenAiProvider` and `CompatibleProvider`.
#[must_use]
pub fn openai_chat_response(content: &str) -> ResponseTemplate {
    let body = serde_json::json!({
        "id": "chatcmpl-test",
        "object": "chat.completion",
        "model": "gpt-4o",
        "choices": [{
            "index": 0,
            "message": {
                "role": "assistant",
                "content": content
            },
            "finish_reason": "stop"
        }],
        "usage": {
            "prompt_tokens": 10,
            "completion_tokens": 5,
            "total_tokens": 15
        }
    });
    ResponseTemplate::new(200).set_body_json(body)
}

/// `OpenAI` 429 rate-limit response.
#[must_use]
pub fn openai_rate_limit_response() -> ResponseTemplate {
    let body = serde_json::json!({
        "error": {
            "message": "Rate limit exceeded",
            "type": "requests",
            "code": "rate_limit_exceeded"
        }
    });
    ResponseTemplate::new(429).set_body_json(body)
}

/// `OpenAI` 401 auth-error response.
#[must_use]
pub fn openai_auth_error_response() -> ResponseTemplate {
    let body = serde_json::json!({
        "error": {
            "message": "Incorrect API key",
            "type": "invalid_request_error",
            "code": "invalid_api_key"
        }
    });
    ResponseTemplate::new(401).set_body_json(body)
}

/// `OpenAI` 500 server-error response.
#[must_use]
pub fn openai_server_error_response() -> ResponseTemplate {
    ResponseTemplate::new(500).set_body_string("Internal Server Error")
}

/// SSE streaming response for OpenAI-compatible endpoints.
///
/// Encodes `chunks` as `data: {...}\n\n` events followed by `data: [DONE]\n\n`.
#[must_use]
pub fn openai_sse_stream_response(chunks: &[&str]) -> ResponseTemplate {
    let mut body = String::new();
    for chunk in chunks {
        let event = serde_json::json!({
            "id": "chatcmpl-test",
            "object": "chat.completion.chunk",
            "choices": [{
                "index": 0,
                "delta": { "content": chunk },
                "finish_reason": null
            }]
        });
        let _ = write!(body, "data: {event}\n\n");
    }
    let stop_event = serde_json::json!({
        "id": "chatcmpl-test",
        "object": "chat.completion.chunk",
        "choices": [{
            "index": 0,
            "delta": {},
            "finish_reason": "stop"
        }]
    });
    let _ = write!(body, "data: {stop_event}\n\n");
    body.push_str("data: [DONE]\n\n");
    ResponseTemplate::new(200)
        .insert_header("content-type", "text/event-stream")
        .set_body_string(body)
}

// ---------------------------------------------------------------------------
// Claude (Anthropic) response shapes
// ---------------------------------------------------------------------------

/// Non-streaming Anthropic Messages API response.
#[must_use]
pub fn claude_messages_response(content: &str) -> ResponseTemplate {
    let body = serde_json::json!({
        "id": "msg_test",
        "type": "message",
        "role": "assistant",
        "model": TEST_CLAUDE_MODEL,
        "content": [{
            "type": "text",
            "text": content
        }],
        "stop_reason": "end_turn",
        "usage": {
            "input_tokens": 10,
            "output_tokens": 5,
            "cache_creation_input_tokens": 0,
            "cache_read_input_tokens": 0
        }
    });
    ResponseTemplate::new(200).set_body_json(body)
}

/// Non-streaming Anthropic Messages API response containing a single `tool_use` block.
///
/// Compatible with `ClaudeProvider::chat_with_tools`, `chat_with_tools_stream` (non-streaming
/// send path), and `chat_typed`.
#[must_use]
pub fn claude_tool_use_response(
    tool_name: &str,
    tool_id: &str,
    input: &serde_json::Value,
) -> ResponseTemplate {
    let body = serde_json::json!({
        "id": "msg_test",
        "type": "message",
        "role": "assistant",
        "model": TEST_CLAUDE_MODEL,
        "content": [{
            "type": "tool_use",
            "id": tool_id,
            "name": tool_name,
            "input": input
        }],
        "stop_reason": "tool_use",
        "usage": {
            "input_tokens": 10,
            "output_tokens": 5,
            "cache_creation_input_tokens": 0,
            "cache_read_input_tokens": 0
        }
    });
    ResponseTemplate::new(200).set_body_json(body)
}

/// Claude 429 rate-limit / 529 overload response.
#[must_use]
pub fn claude_overload_response(status: u16) -> ResponseTemplate {
    let body = serde_json::json!({
        "type": "error",
        "error": {
            "type": "overloaded_error",
            "message": "Overloaded"
        }
    });
    ResponseTemplate::new(status).set_body_json(body)
}

/// Claude streaming SSE response.
///
/// Encodes `chunks` as Anthropic `content_block_delta` events.
#[must_use]
pub fn claude_sse_stream_response(chunks: &[&str]) -> ResponseTemplate {
    let mut body = String::new();

    body.push_str(
        "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_test\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[],\"model\":\"claude-sonnet-5\",\"stop_reason\":null,\"stop_sequence\":null,\"usage\":{\"input_tokens\":10,\"output_tokens\":0}}}\n\n",
    );
    body.push_str(
        "event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n",
    );

    for chunk in chunks {
        let escaped = chunk.replace('\\', "\\\\").replace('"', "\\\"");
        let _ = write!(
            body,
            "event: content_block_delta\ndata: {{\"type\":\"content_block_delta\",\"index\":0,\"delta\":{{\"type\":\"text_delta\",\"text\":\"{escaped}\"}}}}\n\n"
        );
    }

    body.push_str(
        "event: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":0}\n\n",
    );
    body.push_str(
        "event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\",\"stop_sequence\":null},\"usage\":{\"output_tokens\":5}}\n\n",
    );
    body.push_str("event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n");

    ResponseTemplate::new(200)
        .insert_header("content-type", "text/event-stream")
        .set_body_string(body)
}

/// Claude streaming SSE response containing a single `tool_use` block.
///
/// Encodes `input_json` (already-serialized JSON) as one `input_json_delta` event.
/// Compatible with `ClaudeProvider::chat_with_tools_stream`.
#[must_use]
pub fn claude_tool_use_sse_response(
    tool_id: &str,
    tool_name: &str,
    input_json: &str,
) -> ResponseTemplate {
    let mut body = String::new();

    body.push_str(
        "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_test\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[],\"model\":\"claude-sonnet-5\",\"stop_reason\":null,\"stop_sequence\":null,\"usage\":{\"input_tokens\":10,\"output_tokens\":0}}}\n\n",
    );
    let _ = write!(
        body,
        "event: content_block_start\ndata: {{\"type\":\"content_block_start\",\"index\":0,\"content_block\":{{\"type\":\"tool_use\",\"id\":\"{tool_id}\",\"name\":\"{tool_name}\",\"input\":{{}}}}}}\n\n"
    );
    let escaped = input_json.replace('\\', "\\\\").replace('"', "\\\"");
    let _ = write!(
        body,
        "event: content_block_delta\ndata: {{\"type\":\"content_block_delta\",\"index\":0,\"delta\":{{\"type\":\"input_json_delta\",\"partial_json\":\"{escaped}\"}}}}\n\n"
    );
    body.push_str(
        "event: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":0}\n\n",
    );
    body.push_str(
        "event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"tool_use\",\"stop_sequence\":null},\"usage\":{\"output_tokens\":5}}\n\n",
    );
    body.push_str("event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n");

    ResponseTemplate::new(200)
        .insert_header("content-type", "text/event-stream")
        .set_body_string(body)
}

// ---------------------------------------------------------------------------
// Ollama-compatible response shapes (HTTP API)
// ---------------------------------------------------------------------------

/// Ollama `/api/chat` non-streaming response.
///
/// `OllamaProvider`'s `chat`/`chat_stream`/`chat_with_tools` post directly via `reqwest`
/// (see `ollama::send_chat_request`, #6491) so this fixture exercises the same wire path a
/// real Ollama server would receive a request on, not just the compatible-endpoint path.
#[must_use]
pub fn ollama_chat_response(content: &str) -> ResponseTemplate {
    let body = serde_json::json!({
        "model": "llama3",
        "created_at": "2024-01-01T00:00:00Z",
        "message": {
            "role": "assistant",
            "content": content
        },
        "done": true,
        "total_duration": 1_000_000,
        "load_duration": 100_000,
        "prompt_eval_count": 10,
        "eval_count": 5
    });
    ResponseTemplate::new(200).set_body_json(body)
}

/// Ollama 500 error response.
#[must_use]
pub fn ollama_server_error_response() -> ResponseTemplate {
    ResponseTemplate::new(500).set_body_string("model not found")
}

/// Ollama 429 rate-limit response, with `Retry-After: 0` so retry tests run fast.
#[must_use]
pub fn ollama_rate_limit_response() -> ResponseTemplate {
    ResponseTemplate::new(429)
        .insert_header("retry-after", "0")
        .set_body_json(serde_json::json!({ "error": "rate limit exceeded" }))
}

/// Ollama 503 service-unavailable response, with `Retry-After: 0` so retry tests run fast.
#[must_use]
pub fn ollama_unavailable_response() -> ResponseTemplate {
    ResponseTemplate::new(503)
        .insert_header("retry-after", "0")
        .set_body_json(serde_json::json!({ "error": "server overloaded" }))
}

/// Ollama 400 context-length-exceeded response (not retried by `send_with_retry`).
#[must_use]
pub fn ollama_context_length_response() -> ResponseTemplate {
    ResponseTemplate::new(400)
        .set_body_json(serde_json::json!({ "error": "context length exceeded for this model" }))
}

#[cfg(test)]
mod tests {
    use super::*;
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer};

    // ResponseTemplate does not expose its body, so we verify fixtures via a
    // real MockServer round-trip using reqwest.

    #[tokio::test]
    async fn openai_chat_response_is_200() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/chat/completions"))
            .respond_with(openai_chat_response("hello"))
            .mount(&server)
            .await;
        let resp = reqwest::Client::new()
            .post(format!("{}/v1/chat/completions", server.uri()))
            .send()
            .await
            .unwrap();
        assert_eq!(resp.status(), 200);
        let body: serde_json::Value = resp.json().await.unwrap();
        assert_eq!(body["choices"][0]["message"]["content"], "hello");
    }

    #[tokio::test]
    async fn claude_messages_response_shape() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/messages"))
            .respond_with(claude_messages_response("world"))
            .mount(&server)
            .await;
        let resp = reqwest::Client::new()
            .post(format!("{}/v1/messages", server.uri()))
            .send()
            .await
            .unwrap();
        assert_eq!(resp.status(), 200);
        let body: serde_json::Value = resp.json().await.unwrap();
        assert_eq!(body["content"][0]["text"], "world");
        assert_eq!(body["role"], "assistant");
    }

    #[tokio::test]
    async fn openai_sse_contains_done_sentinel() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/stream"))
            .respond_with(openai_sse_stream_response(&["chunk1", "chunk2"]))
            .mount(&server)
            .await;
        let raw = reqwest::Client::new()
            .post(format!("{}/stream", server.uri()))
            .send()
            .await
            .unwrap()
            .text()
            .await
            .unwrap();
        assert!(raw.contains("chunk1"));
        assert!(raw.contains("chunk2"));
        assert!(raw.contains("[DONE]"));
    }

    #[tokio::test]
    async fn claude_sse_contains_chunks() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/stream"))
            .respond_with(claude_sse_stream_response(&["part1", "part2"]))
            .mount(&server)
            .await;
        let raw = reqwest::Client::new()
            .post(format!("{}/stream", server.uri()))
            .send()
            .await
            .unwrap()
            .text()
            .await
            .unwrap();
        assert!(raw.contains("part1"));
        assert!(raw.contains("part2"));
        assert!(raw.contains("message_stop"));
    }

    #[tokio::test]
    async fn ollama_response_shape() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/api/chat"))
            .respond_with(ollama_chat_response("ok"))
            .mount(&server)
            .await;
        let resp = reqwest::Client::new()
            .post(format!("{}/api/chat", server.uri()))
            .send()
            .await
            .unwrap();
        assert_eq!(resp.status(), 200);
        let body: serde_json::Value = resp.json().await.unwrap();
        assert_eq!(body["message"]["content"], "ok");
        assert_eq!(body["done"], true);
    }
}