hanzo-server-core 0.6.1

Hanzo Engine - fast, flexible LLM inference engine written in Rust.
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
//! ## Chat Completions functionality and route handler.

use std::{
    collections::HashMap, io::Cursor, ops::Deref, pin::Pin, sync::Arc, task::Poll, time::Duration,
};

use anyhow::{Context, Result};
use axum::{
    extract::{Json, State},
    http::{self},
    response::{
        sse::{Event, KeepAlive, KeepAliveStream},
        IntoResponse, Sse,
    },
    Extension,
};
use base64::{engine::general_purpose::STANDARD, Engine};
use either::Either;
use hanzo_engine::{
    AgentPermission, AgentToolApprovalHandler, AgentToolApprovalNotifier, AgenticToolCallData,
    AgenticToolCallPhase, AgenticToolCallRecord, ChatCompletionChunkResponse,
    ChatCompletionResponse, Constraint, Hanzo, ModelCategory, NormalRequest, ReasoningEffort,
    Request, RequestMessage, Response, SamplingParams,
};
use image::DynamicImage;
use indexmap::IndexMap;
use itertools::Itertools;
use serde_json::{json, Value};
use tokio::sync::mpsc::{Receiver, Sender};

use crate::{
    completion_core::{
        convert_stop_tokens, get_dry_sampling_params, handle_completion_error,
        BaseCompletionResponder,
    },
    handler_core::{
        create_response_channel, send_request_with_model, BaseJsonModelError, ErrorToResponse,
        JsonError, ModelErrorMessage,
    },
    hanzo_server_router_builder::AgenticDefaults,
    openai::{
        ChatCompletionRequest, Grammar, JsonSchemaResponseFormat, MessageInnerContent,
        ResponseFormat,
    },
    streaming::{base_create_streamer, get_keep_alive_interval, BaseStreamer, DoneState},
    types::{ExtractedHanzoState, OnChunkCallback, OnDoneCallback, SharedHanzoState},
    util::{parse_audio_url, parse_image_url, sanitize_error_message, validate_model_name},
    video::parse_video_url,
};

/// A callback function that processes streaming response chunks before they are sent to the client.
///
/// This hook allows modification of each chunk in the streaming response, enabling features like
/// content filtering, transformation, or logging. The callback receives a chunk and must return
/// a (potentially modified) chunk.
///
/// ### Examples
///
/// ```no_run
/// use hanzo_server_core::chat_completion::ChatCompletionOnChunkCallback;
///
/// let on_chunk: ChatCompletionOnChunkCallback = Box::new(|mut chunk| {
///     // Log the chunk or modify its content
///     println!("Processing chunk: {:?}", chunk);
///     chunk
/// });
/// ```
/// Max files surfaced on a single chat completion response body. Additional files
/// produced by the agentic loop are still reachable via `GET /v1/files/{id}` but
/// are not embedded in the response JSON to keep the body bounded.
const MAX_FILES_PER_RESPONSE: usize = 64;

pub type ChatCompletionOnChunkCallback = OnChunkCallback<ChatCompletionChunkResponse>;

/// A callback function that is executed when the streaming response completes.
///
/// This hook receives all chunks that were streamed during the response, allowing for
/// post-processing, analytics, or cleanup operations after the stream finishes.
///
/// ### Examples
///
/// ```no_run
/// use hanzo_server_core::chat_completion::ChatCompletionOnDoneCallback;
///
/// let on_done: ChatCompletionOnDoneCallback = Box::new(|chunks| {
///     println!("Stream completed with {} chunks", chunks.len());
///     // Process all chunks for analytics
/// });
/// ```
pub type ChatCompletionOnDoneCallback = OnDoneCallback<ChatCompletionChunkResponse>;

/// A streaming response handler.
///
/// It processes incoming response chunks from a model and converts them
/// into Server-Sent Events (SSE) format for real-time streaming to clients.
pub type ChatCompletionStreamer = BaseStreamer<
    ChatCompletionChunkResponse,
    ChatCompletionOnChunkCallback,
    ChatCompletionOnDoneCallback,
>;

fn encode_agentic_tool_images(images: &[DynamicImage]) -> Vec<String> {
    images
        .iter()
        .filter_map(|image| {
            let mut buffer = Vec::new();
            match image.write_to(&mut Cursor::new(&mut buffer), image::ImageFormat::Png) {
                Ok(()) => Some(STANDARD.encode(buffer)),
                Err(e) => {
                    tracing::warn!("failed to encode agentic tool image: {e}");
                    None
                }
            }
        })
        .collect()
}

pub(crate) fn serialize_agentic_progress(
    round: usize,
    tool_name: &str,
    phase: &AgenticToolCallPhase,
) -> Value {
    let (phase_str, data) = match phase {
        AgenticToolCallPhase::Calling(data) => ("calling", serialize_agentic_data(data)),
        AgenticToolCallPhase::Complete(data) => ("complete", serialize_agentic_data(data)),
    };
    json!({
        "type": "agentic_tool_call_progress",
        "round": round,
        "tool_name": tool_name,
        "phase": phase_str,
        "data": data,
    })
}

fn serialize_agentic_data(data: &AgenticToolCallData) -> Value {
    match data {
        AgenticToolCallData::CodeExecution {
            code,
            stdout,
            stderr,
            exception,
            images,
            video_frames,
            video_frame_count,
            working_directory,
            execution_time_ms,
        } => {
            let mut v = json!({"tool_type": "code_execution"});
            if let Some(c) = code {
                v["code"] = json!(c);
            }
            if let Some(s) = stdout {
                v["stdout"] = json!(s);
            }
            if let Some(s) = stderr {
                v["stderr"] = json!(s);
            }
            if let Some(e) = exception {
                v["exception"] = json!(e);
            }
            if !images.is_empty() {
                v["images_base64"] = json!(encode_agentic_tool_images(images));
            }
            if !video_frames.is_empty() {
                v["video_frames_base64"] = json!(encode_agentic_tool_images(video_frames));
            }
            if let Some(n) = video_frame_count {
                v["video_frame_count"] = json!(n);
            }
            if let Some(d) = working_directory {
                v["working_directory"] = json!(d);
            }
            if let Some(ms) = execution_time_ms {
                v["execution_time_ms"] = json!(ms);
            }
            v
        }
        AgenticToolCallData::WebSearch {
            query,
            results_count,
            sources,
        } => {
            let mut v = json!({"tool_type": "web_search"});
            if let Some(q) = query {
                v["query"] = json!(q);
            }
            if let Some(n) = results_count {
                v["results_count"] = json!(n);
            }
            if !sources.is_empty() {
                v["sources"] = json!(sources);
            }
            v
        }
        AgenticToolCallData::Custom { arguments, content } => {
            let mut v = json!({"tool_type": "custom"});
            if !arguments.is_empty() {
                v["arguments"] = json!(arguments);
            }
            if !content.is_empty() {
                v["content"] = json!(content);
            }
            v
        }
    }
}

/// Arguments string from a Calling-phase `AgenticToolCallData`.
fn extract_arguments(data: &AgenticToolCallData) -> String {
    match data {
        AgenticToolCallData::CodeExecution {
            code: Some(code), ..
        } => serde_json::json!({"code": code}).to_string(),
        AgenticToolCallData::WebSearch {
            query: Some(query), ..
        } => serde_json::json!({"query": query}).to_string(),
        AgenticToolCallData::Custom { arguments, .. } => arguments.clone(),
        _ => String::new(),
    }
}

/// Fold progress events into `AgenticToolCallRecord` for non-streaming responses. `pending_args` keeps Calling-phase args keyed by (round, tool_name).
fn record_agentic_progress(
    records: &mut Vec<AgenticToolCallRecord>,
    pending_args: &mut HashMap<(usize, String), String>,
    round: usize,
    tool_name: &str,
    phase: &AgenticToolCallPhase,
) {
    match phase {
        AgenticToolCallPhase::Calling(data) => {
            pending_args.insert((round, tool_name.to_string()), extract_arguments(data));
        }
        AgenticToolCallPhase::Complete(data) => {
            let arguments = pending_args
                .remove(&(round, tool_name.to_string()))
                .unwrap_or_default();

            let (result_content, result_images_base64) = match data {
                AgenticToolCallData::CodeExecution {
                    stdout,
                    stderr,
                    exception,
                    images,
                    ..
                } => {
                    let mut content_parts = Vec::new();
                    if let Some(s) = stdout {
                        content_parts.push(format!("stdout: {s}"));
                    }
                    if let Some(s) = stderr {
                        content_parts.push(format!("stderr: {s}"));
                    }
                    if let Some(e) = exception {
                        content_parts.push(format!("exception: {e}"));
                    }
                    (content_parts.join("\n"), encode_agentic_tool_images(images))
                }
                AgenticToolCallData::WebSearch {
                    results_count,
                    sources,
                    ..
                } => {
                    let mut parts = Vec::new();
                    if let Some(n) = results_count {
                        parts.push(format!("{n} results"));
                    }
                    if !sources.is_empty() {
                        parts.push(format!("sources: {}", sources.join(", ")));
                    }
                    let msg = parts.join("\n");
                    (msg, vec![])
                }
                AgenticToolCallData::Custom { content, .. } => (content.clone(), vec![]),
            };
            records.push(AgenticToolCallRecord {
                round,
                name: tool_name.to_string(),
                arguments,
                result_content,
                result_images_base64,
                file_ids: Vec::new(),
            });
        }
    }
}

fn attach_agentic_tool_calls(
    mut response: ChatCompletionResponse,
    records: Vec<AgenticToolCallRecord>,
) -> ChatCompletionResponse {
    if !records.is_empty() {
        response.agentic_tool_calls = Some(records);
    }
    response
}

/// Fill each record's `file_ids` from files whose `source.round` and `source.tool` match.
fn stamp_file_ids(records: &mut [AgenticToolCallRecord], files: &[hanzo_engine::File]) {
    for r in records.iter_mut() {
        let matched: Vec<String> = files
            .iter()
            .filter(|f| f.source.round == r.round && f.source.tool == r.name)
            .map(|f| f.id.clone())
            .collect();
        if !matched.is_empty() {
            r.file_ids = matched;
        }
    }
}

impl futures::Stream for ChatCompletionStreamer {
    type Item = Result<Event, axum::Error>;

    /// Polls the stream for the next Server-Sent Event.
    ///
    /// This method implements the core streaming logic:
    /// 1. Handles stream completion by sending `[DONE]` and executing callbacks
    /// 2. Processes incoming model responses and converts them to SSE events
    /// 3. Applies chunk modifications if a callback is provided
    /// 4. Stores chunks if completion callback is configured
    fn poll_next(
        mut self: Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> Poll<Option<Self::Item>> {
        match self.done_state {
            DoneState::SendingDone => {
                // https://platform.openai.com/docs/api-reference/completions/create
                // If true, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a data: [DONE] message.
                self.done_state = DoneState::Done;
                return Poll::Ready(Some(Ok(Event::default().data("[DONE]"))));
            }
            DoneState::Done => {
                if let Some(on_done) = &self.on_done {
                    on_done(&self.chunks);
                }
                return Poll::Ready(None);
            }
            DoneState::Running => (),
        }

        match self.rx.poll_recv(cx) {
            Poll::Ready(Some(resp)) => match resp {
                Response::ModelError(msg, _) => {
                    Hanzo::maybe_log_error(self.state.clone(), &ModelErrorMessage(msg.to_string()));
                    // Done now, just need to send the [DONE]
                    self.done_state = DoneState::SendingDone;
                    Poll::Ready(Some(Ok(Event::default().data(msg))))
                }
                Response::ValidationError(e) => {
                    self.done_state = DoneState::SendingDone;
                    Poll::Ready(Some(Ok(
                        Event::default().data(sanitize_error_message(e.as_ref()))
                    )))
                }
                Response::InternalError(e) => {
                    Hanzo::maybe_log_error(self.state.clone(), &*e);
                    self.done_state = DoneState::SendingDone;
                    Poll::Ready(Some(Ok(
                        Event::default().data(sanitize_error_message(e.as_ref()))
                    )))
                }
                Response::Chunk(mut response) => {
                    if response.choices.iter().all(|x| x.finish_reason.is_some()) {
                        self.done_state = DoneState::SendingDone;
                    }
                    // Done now, just need to send the [DONE]
                    Hanzo::maybe_log_response(self.state.clone(), &response);

                    if let Some(on_chunk) = &self.on_chunk {
                        response = on_chunk(response);
                    }

                    if self.store_chunks {
                        self.chunks.push(response.clone());
                    }

                    Poll::Ready(Some(Event::default().json_data(response)))
                }
                Response::AgenticToolCallProgress {
                    round,
                    tool_name,
                    phase,
                } => {
                    let payload = serialize_agentic_progress(round, &tool_name, &phase);
                    Poll::Ready(Some(
                        Event::default()
                            .event("agentic_tool_call_progress")
                            .json_data(payload),
                    ))
                }
                Response::AgenticToolApprovalRequired {
                    approval_id,
                    session_id,
                    round,
                    tool,
                    arguments,
                } => {
                    let payload = json!({
                        "type": "agentic_tool_approval_required",
                        "approval_id": approval_id,
                        "session_id": session_id,
                        "round": round,
                        "tool": tool,
                        "arguments": arguments,
                    });
                    Poll::Ready(Some(
                        Event::default()
                            .event("agentic_tool_approval_required")
                            .json_data(payload),
                    ))
                }
                Response::File(file) => Poll::Ready(Some(
                    Event::default().event("file_produced").json_data(file),
                )),
                Response::Done(_) => unreachable!(),
                Response::CompletionDone(_) => unreachable!(),
                Response::CompletionModelError(_, _) => unreachable!(),
                Response::CompletionChunk(_) => unreachable!(),
                Response::ImageGeneration(_) => unreachable!(),
                Response::Speech { .. } => unreachable!(),
                Response::Raw { .. } => unreachable!(),
                Response::Embeddings { .. } => unreachable!(),
            },
            Poll::Ready(None) => Poll::Ready(None),
            Poll::Pending => Poll::Pending,
        }
    }
}

/// Represents different types of chat completion responses.
pub type ChatCompletionResponder =
    BaseCompletionResponder<ChatCompletionResponse, KeepAliveStream<ChatCompletionStreamer>>;

type JsonModelError = BaseJsonModelError<ChatCompletionResponse>;
impl ErrorToResponse for JsonModelError {}

impl IntoResponse for ChatCompletionResponder {
    /// Converts the chat completion responder into an HTTP response.
    fn into_response(self) -> axum::response::Response {
        match self {
            ChatCompletionResponder::Sse(s) => s.into_response(),
            ChatCompletionResponder::Json(s) => Json(s).into_response(),
            ChatCompletionResponder::InternalError(e) => {
                JsonError::new(sanitize_error_message(e.as_ref()))
                    .to_response(http::StatusCode::INTERNAL_SERVER_ERROR)
            }
            ChatCompletionResponder::ValidationError(e) => {
                JsonError::new(sanitize_error_message(e.as_ref()))
                    .to_response(http::StatusCode::UNPROCESSABLE_ENTITY)
            }
            ChatCompletionResponder::ModelError(msg, response) => {
                JsonModelError::new(msg, response)
                    .to_response(http::StatusCode::INTERNAL_SERVER_ERROR)
            }
        }
    }
}

/// Parse reasoning_effort string to ReasoningEffort enum
fn parse_reasoning_effort(effort: &Option<String>) -> Option<ReasoningEffort> {
    effort
        .as_ref()
        .and_then(|e| match e.to_lowercase().as_str() {
            "low" => Some(ReasoningEffort::Low),
            "medium" => Some(ReasoningEffort::Medium),
            "high" => Some(ReasoningEffort::High),
            _ => None,
        })
}

/// Parses and validates a chat completion request.
///
/// This function transforms an OpenAI-compatible chat completion request into the
/// request format used by hanzo.
pub async fn parse_request(
    oairequest: ChatCompletionRequest,
    state: SharedHanzoState,
    tx: Sender<Response>,
    tool_dispatch_url: Option<String>,
    agent_approval_handler: Option<AgentToolApprovalHandler>,
    agent_approval_notifier: Option<Arc<AgentToolApprovalNotifier>>,
) -> Result<(Request, bool)> {
    let repr = serde_json::to_string(&oairequest)
        .context("Failed to serialize chat completion request for logging")?;
    Hanzo::maybe_log_request(state.clone(), repr);

    // Validate that the requested model matches the loaded model
    validate_model_name(&oairequest.model, state.clone())?;

    // Parse reasoning effort for Harmony-format models
    let reasoning_effort = parse_reasoning_effort(&oairequest.reasoning_effort);

    let stop_toks = convert_stop_tokens(oairequest.stop_seqs);

    let messages = match oairequest.messages {
        Either::Left(req_messages) => {
            let mut messages = Vec::new();
            let mut image_urls = Vec::new();
            let mut audio_urls = Vec::new();
            let mut video_urls = Vec::new();
            for message in req_messages {
                let content = match message.content.as_deref() {
                    Some(content) => content.clone(),
                    None => {
                        // Handle tool call
                        let calls = message
                            .tool_calls
                            .as_ref()
                            .context(
                                "No content was provided, expected tool calls to be provided.",
                            )?
                            .iter()
                            .map(|call| &call.function)
                            .collect::<Vec<_>>();

                        Either::Left(serde_json::to_string(&calls)?)
                    }
                };

                match &content {
                    Either::Left(content) => {
                        let mut message_map: IndexMap<
                            String,
                            Either<String, Vec<IndexMap<String, Value>>>,
                        > = IndexMap::new();
                        message_map.insert("role".to_string(), Either::Left(message.role.clone()));
                        message_map.insert("content".to_string(), Either::Left(content.clone()));

                        // Add tool_calls for assistant messages that have them
                        if let Some(ref tool_calls) = message.tool_calls {
                            // Convert tool_calls to Vec<IndexMap<String, Value>> for Jinja template
                            let tool_calls_vec: Vec<IndexMap<String, Value>> = tool_calls
                                .iter()
                                .map(|tc| {
                                    let mut tc_map = IndexMap::new();
                                    // Use provided ID or fallback to function name
                                    let id =
                                        tc.id.clone().unwrap_or_else(|| tc.function.name.clone());
                                    tc_map.insert("id".to_string(), Value::String(id));
                                    tc_map.insert(
                                        "type".to_string(),
                                        Value::String("function".to_string()),
                                    );
                                    let mut function_map = serde_json::Map::new();
                                    function_map.insert(
                                        "name".to_string(),
                                        Value::String(tc.function.name.clone()),
                                    );
                                    function_map.insert(
                                        "arguments".to_string(),
                                        Value::String(tc.function.arguments.clone()),
                                    );
                                    tc_map.insert(
                                        "function".to_string(),
                                        Value::Object(function_map),
                                    );
                                    tc_map
                                })
                                .collect();
                            message_map
                                .insert("tool_calls".to_string(), Either::Right(tool_calls_vec));
                        }

                        // Add tool_call_id for tool messages
                        if let Some(ref tool_call_id) = message.tool_call_id {
                            message_map.insert(
                                "tool_call_id".to_string(),
                                Either::Left(tool_call_id.clone()),
                            );
                        }

                        // Add name for tool messages
                        if let Some(ref name) = message.name {
                            message_map.insert("name".to_string(), Either::Left(name.clone()));
                        }

                        messages.push(message_map);
                    }
                    Either::Right(image_messages) => {
                        // If there is only one message, it is possible a text message
                        // found when rig is used as client. In this case, we need to check if
                        // the message is a text message or an image message.
                        if image_messages.len() == 1 {
                            if !image_messages[0].contains_key("text") {
                                anyhow::bail!("Expected `text` key in input message.");
                            }
                            let content = match image_messages[0]["text"].deref() {
                                Either::Left(left) => left.to_string(),
                                Either::Right(right) => format!("{right:?}"),
                            };
                            let mut message_map: IndexMap<
                                String,
                                Either<String, Vec<IndexMap<String, Value>>>,
                            > = IndexMap::new();
                            message_map.insert("role".to_string(), Either::Left(message.role));
                            message_map.insert("content".to_string(), Either::Left(content));
                            messages.push(message_map);
                            continue;
                        }
                        if message.role != "user" {
                            anyhow::bail!(
                                "Role for an image message must be `user`, but it is {}",
                                message.role
                            );
                        }

                        enum ContentPart {
                            Text { text: String },
                            Image { image_url: String },
                            Audio { audio_url: String },
                            Video { video_url: String },
                        }

                        let mut items = Vec::new();
                        for image_message in image_messages {
                            match image_message.get("type") {
                                Some(MessageInnerContent(Either::Left(x))) if x == "text" => {
                                    items.push(ContentPart::Text {
                                        text: image_message
                                            .get("text").as_ref()
                                            .context("Text sub-content must have `text` key.")?.as_ref()
                                            .left().context("Text sub-content `text` key must be a string.")?.clone(),
                                    });
                                }
                                Some(MessageInnerContent(Either::Left(x))) if x == "image_url" => {
                                    items.push(ContentPart::Image {
                                        image_url: image_message
                                            .get("image_url")
                                            .as_ref()
                                            .context("Image sub-content must have `image_url` key.")?
                                            .as_ref()
                                            .right()
                                            .context("Image sub-content `image_url` key must be an object.")?
                                            .get("url")
                                            .context("Image sub-content `image_url` object must have a `url` key.")?
                                            .clone(),
                                    });
                                }
                                Some(MessageInnerContent(Either::Left(x))) if x == "audio_url" => {
                                    items.push(ContentPart::Audio {
                                        audio_url: image_message
                                            .get("audio_url")
                                            .as_ref()
                                            .context("Audio sub-content must have `audio_url` key.")?
                                            .as_ref()
                                            .right()
                                            .context("Audio sub-content `audio_url` key must be an object.")?
                                            .get("url")
                                            .context("Audio sub-content `audio_url` object must have a `url` key.")?
                                            .clone(),
                                    });
                                }
                                Some(MessageInnerContent(Either::Left(x))) if x == "video_url" => {
                                    items.push(ContentPart::Video {
                                        video_url: image_message
                                            .get("video_url")
                                            .as_ref()
                                            .context("Video sub-content must have `video_url` key.")?
                                            .as_ref()
                                            .right()
                                            .context("Video sub-content `video_url` key must be an object.")?
                                            .get("url")
                                            .context("Video sub-content `video_url` object must have a `url` key.")?
                                            .clone(),
                                    });
                                }
                                _ => anyhow::bail!("Expected array content sub-content to be of format {{`type`: `text`, `text`: ...}} and {{`type`: `url`, `image_url`: {{`url`: ...}}}}")
                            }
                        }

                        let text_content = items
                            .iter()
                            .filter_map(|item| match item {
                                ContentPart::Text { text } => Some(text),
                                _ => None,
                            })
                            .join(" ");
                        let image_urls_iter = items
                            .iter()
                            .filter_map(|item| match item {
                                ContentPart::Image { image_url } => Some(image_url.clone()),
                                _ => None,
                            })
                            .collect::<Vec<_>>();

                        let audio_urls_iter = items
                            .iter()
                            .filter_map(|item| match item {
                                ContentPart::Audio { audio_url } => Some(audio_url.clone()),
                                _ => None,
                            })
                            .collect::<Vec<_>>();

                        let video_urls_iter = items
                            .iter()
                            .filter_map(|item| match item {
                                ContentPart::Video { video_url } => Some(video_url.clone()),
                                _ => None,
                            })
                            .collect::<Vec<_>>();

                        // Apply prefixer to text content if this is a multimodal model with images/audio/video
                        // This matches the behavior of interactive mode which auto-inserts media tokens
                        let text_content = if !image_urls_iter.is_empty()
                            || !audio_urls_iter.is_empty()
                            || !video_urls_iter.is_empty()
                        {
                            if let Ok(ModelCategory::Multimodal { prefixer }) =
                                state.get_model_category(None)
                            {
                                let mut prefixed = text_content;

                                // Apply image prefixer
                                if !image_urls_iter.is_empty() {
                                    let start_idx = image_urls.len();
                                    let image_indices: Vec<usize> =
                                        (start_idx..start_idx + image_urls_iter.len()).collect();
                                    prefixed = prefixer.prefix_image(image_indices, &prefixed);
                                }

                                // Apply audio prefixer
                                if !audio_urls_iter.is_empty() {
                                    let start_idx = audio_urls.len();
                                    let audio_indices: Vec<usize> =
                                        (start_idx..start_idx + audio_urls_iter.len()).collect();
                                    prefixed = prefixer.prefix_audio(audio_indices, &prefixed);
                                }

                                // Apply video prefixer
                                if !video_urls_iter.is_empty() {
                                    let start_idx = video_urls.len();
                                    let video_indices: Vec<usize> =
                                        (start_idx..start_idx + video_urls_iter.len()).collect();
                                    prefixed = prefixer.prefix_video(video_indices, &prefixed);
                                }

                                prefixed
                            } else {
                                text_content
                            }
                        } else {
                            text_content
                        };

                        let mut message_map: IndexMap<
                            String,
                            Either<String, Vec<IndexMap<String, Value>>>,
                        > = IndexMap::new();
                        message_map.insert("role".to_string(), Either::Left(message.role));

                        let mut content_map: Vec<IndexMap<String, Value>> = Vec::new();
                        for _ in &image_urls_iter {
                            let mut content_image_map = IndexMap::new();
                            content_image_map
                                .insert("type".to_string(), Value::String("image".to_string()));
                            content_map.push(content_image_map);
                        }
                        for _ in &audio_urls_iter {
                            let mut content_audio_map = IndexMap::new();
                            content_audio_map
                                .insert("type".to_string(), Value::String("audio".to_string()));
                            content_map.push(content_audio_map);
                        }
                        for _ in &video_urls_iter {
                            let mut content_video_map = IndexMap::new();
                            content_video_map
                                .insert("type".to_string(), Value::String("video".to_string()));
                            content_map.push(content_video_map);
                        }
                        {
                            let mut content_text_map = IndexMap::new();
                            content_text_map
                                .insert("type".to_string(), Value::String("text".to_string()));
                            content_text_map
                                .insert("text".to_string(), Value::String(text_content));
                            content_map.push(content_text_map);
                        }

                        message_map.insert("content".to_string(), Either::Right(content_map));
                        messages.push(message_map);
                        image_urls.extend(image_urls_iter);
                        audio_urls.extend(audio_urls_iter);
                        video_urls.extend(video_urls_iter);
                    }
                }
            }
            if !image_urls.is_empty() || !audio_urls.is_empty() || !video_urls.is_empty() {
                // Parse images
                let mut images = Vec::new();
                for url_unparsed in image_urls {
                    let image = parse_image_url(&url_unparsed)
                        .await
                        .context(format!("Failed to parse image resource: {url_unparsed}"))?;
                    images.push(image);
                }

                // Parse audios
                let mut audios = Vec::new();
                for url_unparsed in audio_urls {
                    let audio = parse_audio_url(&url_unparsed)
                        .await
                        .context(format!("Failed to parse audio resource: {url_unparsed}"))?;
                    audios.push(audio);
                }

                // Parse videos
                let mut videos = Vec::new();
                for url_unparsed in video_urls {
                    let video = parse_video_url(&url_unparsed, None)
                        .await
                        .context(format!("Failed to parse video resource: {url_unparsed}"))?;
                    videos.push(video);
                }

                RequestMessage::MultimodalChat {
                    messages,
                    images,
                    audios,
                    videos,
                    enable_thinking: oairequest.enable_thinking,
                    reasoning_effort,
                }
            } else {
                RequestMessage::Chat {
                    messages,
                    enable_thinking: oairequest.enable_thinking,
                    reasoning_effort,
                }
            }
        }
        Either::Right(prompt) => {
            let mut messages = Vec::new();
            let mut message_map: IndexMap<String, Either<String, Vec<IndexMap<String, Value>>>> =
                IndexMap::new();
            message_map.insert("role".to_string(), Either::Left("user".to_string()));
            message_map.insert("content".to_string(), Either::Left(prompt));
            messages.push(message_map);
            RequestMessage::Chat {
                messages,
                enable_thinking: oairequest.enable_thinking,
                reasoning_effort,
            }
        }
    };

    let dry_params = get_dry_sampling_params(
        oairequest.dry_multiplier,
        oairequest.dry_sequence_breakers,
        oairequest.dry_base,
        oairequest.dry_allowed_length,
    )?;

    let is_streaming = oairequest.stream.unwrap_or(false);

    if oairequest.grammar.is_some() && oairequest.response_format.is_some() {
        anyhow::bail!("Request `grammar` and `response_format` were both provided but are mutually exclusive.")
    }

    let constraint = match oairequest.grammar {
        Some(Grammar::Regex(regex)) => Constraint::Regex(regex),
        Some(Grammar::Lark(lark)) => Constraint::Lark(lark),
        Some(Grammar::JsonSchema(schema)) => Constraint::JsonSchema(schema),
        Some(Grammar::Llguidance(llguidance)) => Constraint::Llguidance(llguidance),
        None => match oairequest.response_format {
            Some(ResponseFormat::JsonSchema {
                json_schema: JsonSchemaResponseFormat { name: _, schema },
            }) => Constraint::JsonSchema(schema),
            Some(ResponseFormat::Text) => Constraint::None,
            None => Constraint::None,
        },
    };

    Ok((
        Request::Normal(Box::new(NormalRequest {
            id: state.next_request_id(),
            messages,
            sampling_params: SamplingParams {
                temperature: oairequest.temperature,
                top_k: oairequest.top_k,
                top_p: oairequest.top_p,
                min_p: oairequest.min_p,
                top_n_logprobs: oairequest.top_logprobs.unwrap_or(1),
                frequency_penalty: oairequest.frequency_penalty,
                presence_penalty: oairequest.presence_penalty,
                repetition_penalty: oairequest.repetition_penalty,
                max_len: oairequest.max_tokens,
                stop_toks,
                logits_bias: oairequest.logit_bias,
                n_choices: oairequest.n_choices,
                dry_params,
            },
            response: tx,
            return_logprobs: oairequest.logprobs,
            is_streaming,
            suffix: None,
            constraint,
            tool_choice: oairequest.tool_choice,
            tools: oairequest.tools,
            logits_processors: None,
            return_raw_logits: false,
            web_search_options: oairequest.web_search_options,
            enable_code_execution: oairequest.enable_code_execution,
            code_execution_permission: oairequest.code_execution_permission,
            code_execution_approval_notifier: None,
            agent_permission: oairequest.agent_permission,
            agent_approval_handler,
            agent_approval_notifier,
            session_id: oairequest.session_id,
            files: oairequest.files,
            max_tool_rounds: oairequest.max_tool_rounds,
            tool_dispatch_url,
            model_id: if oairequest.model == "default" {
                None
            } else {
                Some(oairequest.model.clone())
            },
            truncate_sequence: oairequest.truncate_sequence.unwrap_or(false),
        })),
        is_streaming,
    ))
}

/// OpenAI-compatible chat completions endpoint handler.
#[utoipa::path(
    post,
    tag = "Mistral.rs",
    path = "/v1/chat/completions",
    request_body = ChatCompletionRequest,
    responses((status = 200, description = "Chat completions"))
)]
pub async fn chatcompletions(
    State(state): ExtractedHanzoState,
    Extension(agentic_defaults): Extension<AgenticDefaults>,
    Json(mut oairequest): Json<ChatCompletionRequest>,
) -> ChatCompletionResponder {
    let (tx, mut rx) = create_response_channel(None);

    // Apply server-level default for max_tool_rounds (per-request value takes priority)
    oairequest.max_tool_rounds = oairequest
        .max_tool_rounds
        .or(agentic_defaults.max_tool_rounds);

    let request_permission = oairequest
        .agent_permission
        .or_else(|| oairequest.code_execution_permission.map(Into::into));
    oairequest.agent_permission = match (agentic_defaults.agent_permission, request_permission) {
        (Some(server_permission), Some(request_permission)) => {
            Some(server_permission.strictest(request_permission))
        }
        (Some(server_permission), None) => Some(server_permission),
        (None, permission) => permission,
    };
    oairequest.code_execution_permission = None;

    let is_streaming = oairequest.stream.unwrap_or(false);
    if matches!(oairequest.agent_permission, Some(AgentPermission::Ask)) && !is_streaming {
        return ChatCompletionResponder::ValidationError(Box::new(JsonError::new(
            "agent_permission \"ask\" requires stream=true over HTTP; approve or deny emitted requests with POST /v1/agent/approvals/{approval_id}.".to_string(),
        )));
    }

    let agent_approval_handler = matches!(oairequest.agent_permission, Some(AgentPermission::Ask))
        .then(|| AgentToolApprovalHandler::from_async(agentic_defaults.approval_broker.callback()));
    let agent_approval_notifier =
        if is_streaming && matches!(oairequest.agent_permission, Some(AgentPermission::Ask)) {
            Some(agentic_defaults.approval_broker.notifier(tx.clone()))
        } else {
            None
        };

    // Extract model_id for routing before parsing
    let model_id = if oairequest.model == "default" {
        None
    } else {
        Some(oairequest.model.clone())
    };

    // tool_dispatch_url is server-level only (not settable per-request via HTTP API) for security
    let (request, is_streaming) = match parse_request(
        oairequest,
        state.clone(),
        tx,
        agentic_defaults.tool_dispatch_url,
        agent_approval_handler,
        agent_approval_notifier,
    )
    .await
    {
        Ok(x) => x,
        Err(e) => return handle_error(state, e.into()),
    };

    if let Err(e) = send_request_with_model(&state, request, model_id.as_deref()).await {
        return handle_error(state, e.into());
    }

    if is_streaming {
        ChatCompletionResponder::Sse(create_streamer(rx, state, None, None))
    } else {
        process_non_streaming_response(&mut rx, state).await
    }
}

/// Handle route / generation errors and logging them.
pub fn handle_error(
    state: SharedHanzoState,
    e: Box<dyn std::error::Error + Send + Sync + 'static>,
) -> ChatCompletionResponder {
    handle_completion_error(state, e)
}

/// Creates a SSE streamer for chat completions with optional callbacks.
pub fn create_streamer(
    rx: Receiver<Response>,
    state: SharedHanzoState,
    on_chunk: Option<ChatCompletionOnChunkCallback>,
    on_done: Option<ChatCompletionOnDoneCallback>,
) -> Sse<KeepAliveStream<ChatCompletionStreamer>> {
    let streamer = base_create_streamer(rx, state, on_chunk, on_done);
    let keep_alive_interval = get_keep_alive_interval();

    Sse::new(streamer)
        .keep_alive(KeepAlive::new().interval(Duration::from_millis(keep_alive_interval)))
}

/// Process non-streaming chat completion responses.
pub async fn process_non_streaming_response(
    rx: &mut Receiver<Response>,
    state: SharedHanzoState,
) -> ChatCompletionResponder {
    let mut tool_call_records = Vec::new();
    let mut pending_args = std::collections::HashMap::new();
    let mut files: Vec<hanzo_engine::File> = Vec::new();

    loop {
        match rx.recv().await {
            Some(Response::AgenticToolCallProgress {
                round,
                tool_name,
                phase,
            }) => record_agentic_progress(
                &mut tool_call_records,
                &mut pending_args,
                round,
                &tool_name,
                &phase,
            ),
            Some(Response::AgenticToolApprovalRequired { .. }) => {
                return ChatCompletionResponder::ValidationError(Box::new(JsonError::new(
                    "code execution approval requires a streaming HTTP request.".to_string(),
                )));
            }
            Some(Response::File(file)) => {
                if files.len() < MAX_FILES_PER_RESPONSE {
                    files.push(file);
                } else {
                    tracing::warn!(
                        "MAX_FILES_PER_RESPONSE ({MAX_FILES_PER_RESPONSE}) reached; remaining files are fetchable via /v1/files/{{id}}",
                    );
                }
            }
            Some(Response::Done(response)) => {
                if !files.is_empty() {
                    stamp_file_ids(&mut tool_call_records, &files);
                }
                let mut response = attach_agentic_tool_calls(response, tool_call_records);
                if !files.is_empty() {
                    response.files = Some(files);
                }
                return match_responses(state, Response::Done(response));
            }
            Some(Response::ModelError(msg, response)) => {
                if !files.is_empty() {
                    stamp_file_ids(&mut tool_call_records, &files);
                }
                let mut response = attach_agentic_tool_calls(response, tool_call_records);
                if !files.is_empty() {
                    response.files = Some(files);
                }
                return match_responses(state, Response::ModelError(msg, response));
            }
            Some(response) => return match_responses(state, response),
            None => {
                let error = anyhow::Error::msg("No response received from the model.");
                return handle_error(state, error.into());
            }
        }
    }
}

/// Matches and processes different types of model responses into appropriate chat completion responses.
pub fn match_responses(state: SharedHanzoState, response: Response) -> ChatCompletionResponder {
    match response {
        Response::InternalError(e) => {
            Hanzo::maybe_log_error(state, &*e);
            ChatCompletionResponder::InternalError(e)
        }
        Response::ModelError(msg, response) => {
            Hanzo::maybe_log_error(state.clone(), &ModelErrorMessage(msg.to_string()));
            Hanzo::maybe_log_response(state, &response);
            ChatCompletionResponder::ModelError(msg, response)
        }
        Response::ValidationError(e) => ChatCompletionResponder::ValidationError(e),
        Response::Done(response) => {
            Hanzo::maybe_log_response(state, &response);
            ChatCompletionResponder::Json(response)
        }
        Response::Chunk(_) => unreachable!(),
        Response::CompletionDone(_) => unreachable!(),
        Response::CompletionModelError(_, _) => unreachable!(),
        Response::CompletionChunk(_) => unreachable!(),
        Response::ImageGeneration(_) => unreachable!(),
        Response::Speech { .. } => unreachable!(),
        Response::Raw { .. } => unreachable!(),
        Response::Embeddings { .. } => unreachable!(),
        Response::AgenticToolCallProgress { .. } => unreachable!(),
        Response::AgenticToolApprovalRequired { .. } => unreachable!(),
        Response::File(_) => unreachable!(),
    }
}