providers-kit 0.0.2

Portable enum-dispatch Kit over multiple model provider APIs.
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
use crate::live_failures::CaseFailure;
use providers_kit::error::{ErrorKind, Operation};

use providers_kit::Model;
use providers_kit::generation::{
    ContentPart, FinishReason, FunctionResult, GenerateRequest, GenerationConfig, JsonSchema,
    Message, ProviderFunctionTool, ProviderToolSpec, ReasoningConfig, ReasoningEffort, ToolChoice,
};
use providers_kit::models::ModelBackend;

use super::{LiveProvider, Mode, Service, StreamCompletion};
use crate::live_assertions::{ErrorEvidence, GenerationEvidence};

impl LiveProvider {
    async fn exact_generation(&self, mode: Mode) -> Result<(), CaseFailure> {
        let nonce = Self::nonce();
        let instruction = match (self.service(), mode) {
            (Service::Ollama, Mode::Streaming) => format!(
                "Copy the following token character for character, including its complete suffix: {nonce}. Treat it as literal text; do not infer, repair, shorten, or replace any character. Return only the token, without quotes, Markdown, or whitespace."
            ),
            _ => format!("Reply with exactly this text and nothing else: {nonce}"),
        };
        let request = Self::text_request(&instruction)?;
        let response = self.generate(&request, mode).await?;
        GenerationEvidence::exact_text(&response, &nonce, false).map_err(CaseFailure::from)
    }

    async fn reasoning_generation(&self) -> Result<(), CaseFailure> {
        let (variable, reasoning) = match self.service() {
            Service::Anthropic => (
                "TEST_ANTHROPIC_MODEL_THINKING",
                ReasoningConfig {
                    effort: Some(ReasoningEffort::High),
                    ..ReasoningConfig::default()
                },
            ),
            Service::Gemini => (
                "TEST_GEMINI_MODEL_THINKING_LEVEL",
                ReasoningConfig {
                    effort: Some(ReasoningEffort::High),
                    ..ReasoningConfig::default()
                },
            ),
            Service::Ollama => (
                "TEST_OLLAMA_MODEL_REASONING",
                ReasoningConfig {
                    effort: Some(ReasoningEffort::High),
                    ..ReasoningConfig::default()
                },
            ),
            Service::OpenAi => {
                return Err("no separate OpenAI reasoning fixture configured"
                    .to_owned()
                    .into());
            }
        };
        let model = self.selected(&Self::required(variable)?)?;
        let nonce = Self::nonce();
        let request = Self::text_request(&format!(
            "Reply with exactly this text and nothing else: {nonce}"
        ))?
        .with_reasoning(reasoning);
        let response = self.generate_on(&model, &request, Mode::Unary).await?;
        GenerationEvidence::exact_text(&response, &nonce, false).map_err(CaseFailure::from)
    }

    async fn missing_model(&self, mode: Mode) -> Result<(), CaseFailure> {
        let absent = match self.service() {
            Service::Gemini => format!("models/{}", Self::nonce()),
            Service::OpenAi | Service::Anthropic | Service::Ollama => Self::nonce(),
        };
        let model = self.selected(&absent)?;
        let request = GenerateRequest::new(vec![
            Message::user_text("Reply with exactly: unreachable").map_err(Self::error)?,
        ])
        .map_err(Self::error)?;
        let error = self.rejected(&model, &request, mode).await?;
        let codes: &[Option<&str>] = match self.service() {
            Service::OpenAi => &[Some("model_not_found")],
            Service::Anthropic => &[Some("not_found_error")],
            Service::Gemini => &[Some("NOT_FOUND"), Some("404")],
            Service::Ollama => &[None],
        };
        let operation = match mode {
            Mode::Unary => Operation::Generate,
            Mode::Streaming => Operation::GenerateStream,
        };
        ErrorEvidence::not_found(&error, operation, &absent, codes)
            .map_err(|failure| CaseFailure::from(failure).with_sdk(error))
    }

    pub(super) fn function_tool() -> Result<ProviderToolSpec, CaseFailure> {
        let schema = JsonSchema::new(serde_json::json!({
            "type": "object", "properties": {"value": {"type": "string"}},
            "required": ["value"], "additionalProperties": false,
        }))
        .map_err(Self::error)?;
        Ok(ProviderToolSpec::Function(
            ProviderFunctionTool::new(
                "strict_lookup",
                Some("Returns the requested verification token.".to_owned()),
                schema,
            )
            .map_err(Self::error)?,
        ))
    }

    async fn function_continuation(&self) -> Result<(), CaseFailure> {
        let model = self.model()?;
        self.function_continuation_on(&model, Mode::Unary, None, Self::generation_config(), None)
            .await
    }

    pub(super) async fn function_continuation_on(
        &self,
        model: &Model,
        mode: Mode,
        reasoning: Option<ReasoningConfig>,
        generation: GenerationConfig,
        system_instruction: Option<&str>,
    ) -> Result<(), CaseFailure> {
        let user = Message::user_text("Call strict_lookup exactly once with value `providers-kit`. After it returns, copy the verification_token from its result character for character as an opaque literal string, including its complete prefix and suffix. Do not interpret, regenerate, shorten, correct, or replace any character. Return only the complete token, with no quotes, Markdown, whitespace, or surrounding text.")
            .map_err(Self::error)?;
        let tool = Self::function_tool()?;
        let choice = if self.service() == Service::Ollama
            || (self.service() == Service::Anthropic
                && (reasoning.is_some()
                    || matches!(
                        model.model_id().as_str(),
                        "claude-fable-5-1" | "claude-opus-5-5" | "claude-sonnet-5-5"
                    ))) {
            ToolChoice::Auto
        } else {
            ToolChoice::Tool {
                name: "strict_lookup".to_owned(),
            }
        };
        // Freeze scenario inputs before either request; only the initial call selects a tool.
        let initial_generation = generation.clone().with_tool_choice(choice);
        let prefix = match system_instruction {
            Some(instruction) => vec![
                Message::system(vec![ContentPart::Text {
                    text: instruction.to_owned(),
                }])
                .map_err(Self::error)?,
                user,
            ],
            None => vec![user],
        };
        if self.service() == Service::Ollama
            && matches!(mode, Mode::Unary)
            && reasoning.is_none()
            && std::env::var_os("PROVIDERS_KIT_EVIDENCE_DIR").is_some()
        {
            Self::write_required_observation(
                "function-continuation-scenario",
                serde_json::json!({
                    "stage": "before-initial-request",
                    "model": model.model_id().as_str(),
                    "prefix": &prefix,
                    "initial_generation": &initial_generation,
                    "continuation_generation": &generation,
                }),
            )?;
        }
        let mut request = GenerateRequest::new(prefix.clone())
            .map_err(Self::error)?
            .with_tools(vec![tool.clone()])
            .map_err(Self::error)?
            .with_generation(initial_generation)
            .map_err(Self::error)?;
        if let Some(reasoning) = &reasoning {
            request = request.with_reasoning(reasoning.clone());
        }
        let first = self
            .generate_with_completion(model, &request, mode, StreamCompletion::RequireFunctionCall)
            .await?;
        if first.finish_reason != Some(FinishReason::ToolCall)
            || first.message.function_calls().len() != 1
        {
            return Err(format!(
                "expected exactly one function call and ToolCall finish, got {:?}",
                first.finish_reason
            )
            .into());
        }
        let call = &first.message.function_calls()[0];
        if call.name() != "strict_lookup"
            || call.arguments() != &serde_json::json!({"value": "providers-kit"})
        {
            return Err("function name or exact arguments did not match request"
                .to_owned()
                .into());
        }
        let nonce = Self::nonce();
        let result = FunctionResult::new(
            call.id().map(str::to_owned),
            call.name().to_owned(),
            vec![ContentPart::Json {
                value: serde_json::json!({"verification_token": nonce}),
            }],
            false,
        )
        .map_err(Self::error)?;
        if self.service() == Service::Ollama
            && matches!(mode, Mode::Unary)
            && reasoning.is_none()
            && std::env::var_os("PROVIDERS_KIT_EVIDENCE_DIR").is_some()
        {
            Self::write_required_observation(
                "function-continuation-input",
                serde_json::json!({
                    "stage": "before-continuation",
                    "model": model.model_id().as_str(),
                    "expected_nonce": &nonce,
                    "function_result": &result,
                }),
            )?;
        }
        // Move the complete returned assistant message without rebuilding its continuation.
        let mut messages = prefix;
        messages.extend([
            first.message,
            Message::tool(vec![result]).map_err(Self::error)?,
        ]);
        let mut continuation = GenerateRequest::new(messages)
            .map_err(Self::error)?
            .with_tools(vec![tool])
            .map_err(Self::error)?
            .with_generation(generation)
            .map_err(Self::error)?;
        if let Some(reasoning) = reasoning {
            continuation = continuation.with_reasoning(reasoning);
        }
        let response = self.generate_on(model, &continuation, mode).await?;
        GenerationEvidence::exact_text(&response, &nonce, false).map_err(CaseFailure::from)
    }

    async fn forced_function_unsupported(&self, mode: Mode) -> Result<(), CaseFailure> {
        let request = Self::text_request("Call strict_lookup with value providers-kit.")?
            .with_tools(vec![Self::function_tool()?])
            .map_err(Self::error)?
            .with_generation(
                GenerationConfig::default().with_tool_choice(ToolChoice::Tool {
                    name: "strict_lookup".to_owned(),
                }),
            )
            .map_err(Self::error)?;
        let model = self.model()?;
        let result = match mode {
            Mode::Unary => model.generate(&request).await.map(|_| ()),
            Mode::Streaming => model.generate_stream(&request).await.map(|_| ()),
        };
        match result {
            Err(error) if error.kind() == ErrorKind::Unsupported => Ok(()),
            Err(error) => Err(CaseFailure::from(
                "Ollama forced tool choice did not return Unsupported",
            )
            .with_sdk(error)),
            Ok(()) => Err("Ollama forced tool choice unexpectedly succeeded".into()),
        }
    }
}

#[tokio::test]
async fn openai_generation() -> Result<(), CaseFailure> {
    let live = LiveProvider::new(Service::OpenAi)?;
    let result = live.exact_generation(Mode::Unary).await;
    live.finish(result).await;
    Ok(())
}
#[tokio::test]
async fn anthropic_generation() -> Result<(), CaseFailure> {
    let live = LiveProvider::new(Service::Anthropic)?;
    let result = live.exact_generation(Mode::Unary).await;
    live.finish(result).await;
    Ok(())
}
#[tokio::test]
async fn gemini_generation() -> Result<(), CaseFailure> {
    let live = LiveProvider::new(Service::Gemini)?;
    let result = live.exact_generation(Mode::Unary).await;
    live.finish(result).await;
    Ok(())
}
#[tokio::test]
async fn ollama_generation() -> Result<(), CaseFailure> {
    let live = LiveProvider::new(Service::Ollama)?;
    let result = live.exact_generation(Mode::Unary).await;
    live.finish(result).await;
    Ok(())
}
#[tokio::test]
async fn openai_streaming() -> Result<(), CaseFailure> {
    let live = LiveProvider::new(Service::OpenAi)?;
    let result = live.exact_generation(Mode::Streaming).await;
    live.finish(result).await;
    Ok(())
}
#[tokio::test]
async fn anthropic_streaming() -> Result<(), CaseFailure> {
    let live = LiveProvider::new(Service::Anthropic)?;
    let result = live.exact_generation(Mode::Streaming).await;
    live.finish(result).await;
    Ok(())
}
#[tokio::test]
async fn gemini_streaming() -> Result<(), CaseFailure> {
    let live = LiveProvider::new(Service::Gemini)?;
    let result = live.exact_generation(Mode::Streaming).await;
    live.finish(result).await;
    Ok(())
}
#[tokio::test]
async fn ollama_streaming() -> Result<(), CaseFailure> {
    let live = LiveProvider::new(Service::Ollama)?;
    let result = live.exact_generation(Mode::Streaming).await;
    live.finish(result).await;
    Ok(())
}
#[tokio::test]
async fn openai_missing_model_generation() -> Result<(), CaseFailure> {
    let live = LiveProvider::new(Service::OpenAi)?;
    let result = live.missing_model(Mode::Unary).await;
    live.finish(result).await;
    Ok(())
}
#[tokio::test]
async fn anthropic_missing_model_generation() -> Result<(), CaseFailure> {
    let live = LiveProvider::new(Service::Anthropic)?;
    let result = live.missing_model(Mode::Unary).await;
    live.finish(result).await;
    Ok(())
}
#[tokio::test]
async fn gemini_missing_model_generation() -> Result<(), CaseFailure> {
    let live = LiveProvider::new(Service::Gemini)?;
    let result = live.missing_model(Mode::Unary).await;
    live.finish(result).await;
    Ok(())
}
#[tokio::test]
async fn ollama_missing_model_generation() -> Result<(), CaseFailure> {
    let live = LiveProvider::new(Service::Ollama)?;
    let result = live.missing_model(Mode::Unary).await;
    live.finish(result).await;
    Ok(())
}
#[tokio::test]
async fn openai_missing_model_streaming() -> Result<(), CaseFailure> {
    let live = LiveProvider::new(Service::OpenAi)?;
    let result = live.missing_model(Mode::Streaming).await;
    live.finish(result).await;
    Ok(())
}
#[tokio::test]
async fn anthropic_missing_model_streaming() -> Result<(), CaseFailure> {
    let live = LiveProvider::new(Service::Anthropic)?;
    let result = live.missing_model(Mode::Streaming).await;
    live.finish(result).await;
    Ok(())
}
#[tokio::test]
async fn gemini_missing_model_streaming() -> Result<(), CaseFailure> {
    let live = LiveProvider::new(Service::Gemini)?;
    let result = live.missing_model(Mode::Streaming).await;
    live.finish(result).await;
    Ok(())
}
#[tokio::test]
async fn ollama_missing_model_streaming() -> Result<(), CaseFailure> {
    let live = LiveProvider::new(Service::Ollama)?;
    let result = live.missing_model(Mode::Streaming).await;
    live.finish(result).await;
    Ok(())
}
#[tokio::test]
async fn anthropic_reasoning() -> Result<(), CaseFailure> {
    let live = LiveProvider::new(Service::Anthropic)?;
    let result = live.reasoning_generation().await;
    live.finish(result).await;
    Ok(())
}
#[tokio::test]
async fn gemini_reasoning() -> Result<(), CaseFailure> {
    let live = LiveProvider::new(Service::Gemini)?;
    let result = live.reasoning_generation().await;
    live.finish(result).await;
    Ok(())
}
#[tokio::test]
async fn ollama_reasoning() -> Result<(), CaseFailure> {
    let live = LiveProvider::new(Service::Ollama)?;
    let result = live.reasoning_generation().await;
    live.finish(result).await;
    Ok(())
}
#[tokio::test]
async fn openai_function_continuation() -> Result<(), CaseFailure> {
    let live = LiveProvider::new(Service::OpenAi)?;
    let result = live.function_continuation().await;
    live.finish(result).await;
    Ok(())
}
#[tokio::test]
async fn anthropic_function_continuation() -> Result<(), CaseFailure> {
    let live = LiveProvider::new(Service::Anthropic)?;
    let result = live.function_continuation().await;
    live.finish(result).await;
    Ok(())
}
#[tokio::test]
async fn gemini_function_continuation() -> Result<(), CaseFailure> {
    let live = LiveProvider::new(Service::Gemini)?;
    let result = live.function_continuation().await;
    live.finish(result).await;
    Ok(())
}
#[tokio::test]
async fn ollama_function_continuation() -> Result<(), CaseFailure> {
    let generation = LiveProvider::generation_config();
    let system_instruction = Some(
        "You are a tool-result relay. After the requested tool call, return exactly the verification_token string supplied by the tool, preserving every character, and nothing else. Never invent a token.",
    );
    let live = LiveProvider::new(Service::Ollama)?;
    let result = async {
        let model = live.model()?;
        live.function_continuation_on(&model, Mode::Unary, None, generation, system_instruction)
            .await
    }
    .await;
    live.finish(result).await;
    Ok(())
}

#[tokio::test]
async fn ollama_forced_function_generation_unsupported() -> Result<(), CaseFailure> {
    let live = LiveProvider::new(Service::Ollama)?;
    let result = live.forced_function_unsupported(Mode::Unary).await;
    live.finish(result).await;
    Ok(())
}
#[tokio::test]
async fn ollama_forced_function_streaming_unsupported() -> Result<(), CaseFailure> {
    let live = LiveProvider::new(Service::Ollama)?;
    let result = live.forced_function_unsupported(Mode::Streaming).await;
    live.finish(result).await;
    Ok(())
}