1use std::collections::HashMap;
6
7use crate::completion::{CompletionResponse, Usage};
8use crate::error::ProviderError;
9use crate::message::ReasoningContent;
10use crate::operation::{
11 CallFragment, Completion, Finish, IfMalformed, ReasoningPart, Seal, TextPart,
12};
13use crate::wire::{Decoder, Flow, Out, WireEvent};
14
15pub const MOCK_PROVIDER: &str = "mock";
17
18pub fn mock_final(usage: Usage) -> Finish {
20 Finish {
21 usage,
22 ..Finish::default()
23 }
24}
25
26fn fixture_additional_params(
30 value: serde_json::Value,
31) -> Result<Option<crate::message::AdditionalParams>, ProviderError> {
32 crate::message::AdditionalParams::try_from_value(value).map_err(|other| {
33 ProviderError::Provider(format!(
34 "mock stream fixture `additional_params` must be a JSON object, got: {other}"
35 ))
36 })
37}
38
39pub fn mock_final_with_total_tokens(total_tokens: u64) -> Finish {
41 mock_final(Usage {
42 total_tokens: Some(total_tokens),
43 ..Default::default()
44 })
45}
46
47#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
49pub enum MockStreamEvent {
50 Text(String),
52 TextStart {
54 id: String,
55 additional_params: Option<serde_json::Value>,
56 },
57 TextAdditionalParams(serde_json::Value),
59 ToolCall {
61 id: String,
62 name: String,
63 arguments: serde_json::Value,
64 call_id: Option<String>,
65 },
66 ToolCallNameDelta { id: String, name: String },
68 ToolCallArgumentsDelta { id: String, arguments: String },
70 ToolCallEnd { id: String },
73 Reasoning {
75 id: String,
76 content: ReasoningContent,
77 },
78 ReasoningDelta { id: String, reasoning: String },
80 MessageId(String),
82 Unknown(serde_json::Value),
84 RequestId(String),
89 FinalResponse(Finish),
91 Error(MockError),
93}
94
95use super::completion::MockError;
96
97fn fixture_provider_id(id: &str) -> Option<&str> {
102 let unnamed = ["reasoning-", "block-", "output-", "tool-", "text-"]
103 .iter()
104 .any(|namespace| {
105 id.strip_prefix(namespace)
106 .is_some_and(|rest| rest.parse::<u64>().is_ok())
107 });
108 (!id.is_empty() && !unnamed).then_some(id)
109}
110
111impl MockStreamEvent {
112 pub fn text(text: impl Into<String>) -> Self {
114 Self::Text(text.into())
115 }
116
117 pub fn text_start(id: impl Into<String>, additional_params: Option<serde_json::Value>) -> Self {
119 Self::TextStart {
120 id: id.into(),
121 additional_params,
122 }
123 }
124
125 pub fn text_additional_params(additional_params: serde_json::Value) -> Self {
127 Self::TextAdditionalParams(additional_params)
128 }
129
130 pub fn tool_call(
132 id: impl Into<String>,
133 name: impl Into<String>,
134 arguments: serde_json::Value,
135 ) -> Self {
136 Self::ToolCall {
137 id: id.into(),
138 name: name.into(),
139 arguments,
140 call_id: None,
141 }
142 }
143
144 pub fn with_call_id(mut self, call_id: impl Into<String>) -> Self {
146 if let Self::ToolCall { call_id: id, .. } = &mut self {
147 *id = Some(call_id.into());
148 }
149 self
150 }
151
152 pub fn tool_call_name_delta(id: impl Into<String>, name: impl Into<String>) -> Self {
154 Self::ToolCallNameDelta {
155 id: id.into(),
156 name: name.into(),
157 }
158 }
159
160 pub fn tool_call_arguments_delta(id: impl Into<String>, arguments: impl Into<String>) -> Self {
162 Self::ToolCallArgumentsDelta {
163 id: id.into(),
164 arguments: arguments.into(),
165 }
166 }
167
168 pub fn tool_call_end(id: impl Into<String>) -> Self {
170 Self::ToolCallEnd { id: id.into() }
171 }
172
173 pub fn reasoning(reasoning: impl Into<String>) -> Self {
177 Self::Reasoning {
178 id: "reasoning-0".to_string(),
179 content: ReasoningContent::Text {
180 text: reasoning.into(),
181 signature: None,
182 },
183 }
184 }
185
186 pub fn with_reasoning_id(mut self, reasoning_id: impl Into<String>) -> Self {
188 if let Self::Reasoning { id, .. } = &mut self {
189 *id = reasoning_id.into();
190 }
191 self
192 }
193
194 pub fn reasoning_delta(reasoning: impl Into<String>) -> Self {
198 Self::reasoning_delta_with_id("reasoning-0", reasoning)
199 }
200
201 pub fn reasoning_delta_with_id(id: impl Into<String>, reasoning: impl Into<String>) -> Self {
203 Self::ReasoningDelta {
204 id: id.into(),
205 reasoning: reasoning.into(),
206 }
207 }
208
209 pub fn message_id(id: impl Into<String>) -> Self {
211 Self::MessageId(id.into())
212 }
213
214 pub fn unknown(value: serde_json::Value) -> Self {
216 Self::Unknown(value)
217 }
218
219 pub fn final_response(usage: Usage) -> Self {
221 Self::FinalResponse(mock_final(usage))
222 }
223
224 pub fn final_response_with_default_usage() -> Self {
226 Self::FinalResponse(mock_final(Usage::default()))
227 }
228
229 pub fn final_response_with_total_tokens(total_tokens: u64) -> Self {
231 Self::FinalResponse(mock_final_with_total_tokens(total_tokens))
232 }
233
234 pub fn error(message: impl Into<String>) -> Self {
236 Self::Error(MockError::provider(message))
237 }
238}
239
240#[derive(Clone, Debug)]
242pub enum MockFrame {
243 Event(MockStreamEvent),
245 Response(Box<CompletionResponse>),
247}
248
249#[derive(Default)]
252pub struct MockDecoder<'id> {
253 text: Option<TextPart<'id>>,
255 reasoning: Vec<(String, ReasoningPart<'id>)>,
257 calls: HashMap<String, usize>,
259 next_call: usize,
260}
261
262impl<'id> MockDecoder<'id> {
263 fn close_text(&mut self, out: &mut Out<'id, Completion>) {
264 if let Some(part) = self.text.take() {
265 out.close_text(part);
266 }
267 }
268
269 fn call_index(&mut self, id: &str) -> usize {
270 if let Some(index) = self.calls.get(id) {
271 return *index;
272 }
273 let index = self.next_call;
274 self.next_call += 1;
275 if !id.is_empty() {
276 self.calls.insert(id.to_owned(), index);
277 }
278 index
279 }
280
281 fn event(
282 &mut self,
283 event: MockStreamEvent,
284 mut out: Out<'id, Completion>,
285 ) -> Result<Flow, ProviderError> {
286 match event {
287 MockStreamEvent::Text(text) => {
288 let part = self.text.get_or_insert_with(|| out.text());
289 out.push_text(part, &text);
290 }
291 MockStreamEvent::TextStart {
292 id: _,
293 additional_params,
294 } => {
295 self.close_text(&mut out);
296 let part = out.text();
297 if let Some(params) = additional_params
298 .map(fixture_additional_params)
299 .transpose()?
300 .flatten()
301 {
302 out.text_params(&part, params);
303 }
304 self.text = Some(part);
305 }
306 MockStreamEvent::TextAdditionalParams(additional_params) => {
307 let Some(params) = fixture_additional_params(additional_params)? else {
310 return Err(ProviderError::Provider(
311 "mock stream fixture `TextAdditionalParams` carries no data — \
312 drop the event instead"
313 .to_string(),
314 ));
315 };
316 let part = self.text.get_or_insert_with(|| out.text());
317 out.text_params(part, params);
318 }
319 MockStreamEvent::ToolCall {
320 id,
321 name,
322 arguments,
323 call_id,
324 } => {
325 self.close_text(&mut out);
326 let index = match self.calls.remove(&id) {
331 Some(index) => index,
332 None => self.call_index(""),
333 };
334 let wire_id = fixture_provider_id(&id);
335 out.call_fragment(
336 index,
337 CallFragment {
338 id: call_id.as_deref().or(wire_id),
339 item_id: call_id.as_ref().and(wire_id),
340 name: Some(name.as_str()),
341 ..CallFragment::default()
342 },
343 )?;
344 out.announce_pending(index, arguments);
345 out.close_pending(index, IfMalformed::Fail)?;
346 }
347 MockStreamEvent::ToolCallNameDelta { id, name } => {
348 self.close_text(&mut out);
349 let index = self.call_index(&id);
350 out.call_fragment(
351 index,
352 CallFragment {
353 id: fixture_provider_id(&id),
354 name: Some(name.as_str()),
355 ..CallFragment::default()
356 },
357 )?;
358 }
359 MockStreamEvent::ToolCallArgumentsDelta { id, arguments } => {
360 self.close_text(&mut out);
361 let index = self.call_index(&id);
362 out.call_fragment(
363 index,
364 CallFragment {
365 id: fixture_provider_id(&id),
366 arguments: Some(arguments.as_str()),
367 ..CallFragment::default()
368 },
369 )?;
370 }
371 MockStreamEvent::ToolCallEnd { id } => {
372 let index = self.call_index(&id);
373 self.calls.remove(&id);
374 out.close_pending(index, IfMalformed::Fail)?;
375 }
376 MockStreamEvent::Reasoning { id, content } => {
377 self.close_text(&mut out);
378 let reasoning = crate::message::Reasoning {
379 id: fixture_provider_id(&id).map(str::to_owned),
380 content: vec![content],
381 };
382 match self.reasoning.iter().position(|(open, _)| *open == id) {
385 Some(at) => {
386 let (_, part) = self.reasoning.remove(at);
387 out.close_reasoning(
388 part,
389 Seal {
390 id: reasoning.id.clone(),
391 restated: Some(reasoning),
392 ..Seal::default()
393 },
394 );
395 }
396 None => out.reasoning_block(reasoning),
397 }
398 }
399 MockStreamEvent::ReasoningDelta { id, reasoning } => {
400 self.close_text(&mut out);
401 let at = match self.reasoning.iter().position(|(open, _)| *open == id) {
402 Some(at) => at,
403 None => {
404 self.reasoning.push((id, out.reasoning()));
405 self.reasoning.len() - 1
406 }
407 };
408 if let Some((_, part)) = self.reasoning.get(at) {
409 out.push_reasoning(part, &reasoning);
410 }
411 }
412 MockStreamEvent::MessageId(id) => out.message_id(id),
413 MockStreamEvent::Unknown(value) => out.unknown(value.into()),
414 MockStreamEvent::RequestId(_) => {}
415 MockStreamEvent::FinalResponse(finish) => {
416 self.close_text(&mut out);
417 for (id, part) in std::mem::take(&mut self.reasoning) {
418 out.close_reasoning(
419 part,
420 Seal {
421 id: fixture_provider_id(&id).map(str::to_owned),
422 ..Seal::default()
423 },
424 );
425 }
426 out.raw(serde_json::to_value(&finish)?);
428 return Ok(out.end(finish));
429 }
430 MockStreamEvent::Error(error) => return Err(error.into_completion_error()),
431 }
432 Ok(Flow::More)
433 }
434
435 fn response(
436 &mut self,
437 response: CompletionResponse,
438 mut out: Out<'id, Completion>,
439 ) -> Result<Flow, ProviderError> {
440 for content in response.choice.iter().cloned() {
441 out.content(content)?;
442 }
443 if let Some(message_id) = response.message_id.clone() {
444 out.message_id(message_id);
445 }
446 out.raw(response.raw.clone());
447 Ok(out.end(Finish {
448 usage: response.usage,
449 reason: response.finish_reason(),
450 message_id: None,
451 response_id: response.response_id.clone(),
452 model: response.model.clone(),
453 }))
454 }
455}
456
457impl<'id> Decoder<'id, Completion, MockFrame> for MockDecoder<'id> {
458 type Event = MockFrame;
459
460 fn classify(&self, frame: MockFrame) -> WireEvent<MockFrame> {
461 WireEvent::Known(frame)
462 }
463
464 fn decode(
465 &mut self,
466 frame: MockFrame,
467 out: Out<'id, Completion>,
468 ) -> Result<Flow, ProviderError> {
469 match frame {
470 MockFrame::Event(event) => self.event(event, out),
471 MockFrame::Response(response) => self.response(*response, out),
472 }
473 }
474}