-
Notifications
You must be signed in to change notification settings - Fork 348
Expand file tree
/
Copy pathmodel.rs
More file actions
4731 lines (4294 loc) · 179 KB
/
Copy pathmodel.rs
File metadata and controls
4731 lines (4294 loc) · 179 KB
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
//! SpacebotModel: Custom CompletionModel implementation that routes through LlmManager.
use crate::config::{ApiType, ProviderConfig};
use crate::llm::manager::LlmManager;
use crate::llm::routing::{
self, MAX_FALLBACK_ATTEMPTS, MAX_RETRIES_PER_MODEL, RETRY_BASE_DELAY_MS, RoutingConfig,
};
use futures::StreamExt as _;
use rig::completion::{self, CompletionError, CompletionModel, CompletionRequest, GetTokenUsage};
use rig::message::{
AssistantContent, DocumentSourceKind, Image, Message, MimeType, ReasoningContent, Text,
ToolCall, ToolFunction, UserContent,
};
use rig::one_or_many::OneOrMany;
use rig::providers::openai::responses_api::Output as OpenAiResponsesOutput;
use rig::providers::openai::responses_api::streaming::{
ItemChunkKind as OpenAiResponsesItemChunkKind,
ResponseChunkKind as OpenAiResponsesResponseChunkKind,
StreamingCompletionChunk as OpenAiResponsesStreamingCompletionChunk,
StreamingItemDoneOutput as OpenAiResponsesStreamingItemDoneOutput,
};
use rig::streaming::{RawStreamingChoice, RawStreamingToolCall, StreamingCompletionResponse};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::sync::Arc;
use tokio::sync::Mutex;
const STREAM_REQUEST_TIMEOUT_SECS: u64 = 30 * 60;
/// Raw provider response. Wraps the JSON so Rig can carry it through.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RawResponse {
pub body: serde_json::Value,
}
/// Streaming response wrapper for token usage and raw provider payload.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RawStreamingResponse {
pub body: serde_json::Value,
pub usage: Option<completion::Usage>,
}
impl GetTokenUsage for RawStreamingResponse {
fn token_usage(&self) -> Option<completion::Usage> {
self.usage
}
}
/// Custom completion model that routes through LlmManager.
///
/// Optionally holds a RoutingConfig for fallback behavior. When present,
/// completion() will try fallback models on retriable errors.
#[derive(Clone)]
pub struct SpacebotModel {
llm_manager: Arc<LlmManager>,
model_name: String,
provider: String,
full_model_name: String,
routing: Option<RoutingConfig>,
agent_id: Option<String>,
process_type: Option<String>,
worker_type: Option<String>,
usage_accumulator: Option<Arc<Mutex<crate::llm::usage::UsageAccumulator>>>,
}
impl SpacebotModel {
pub fn provider(&self) -> &str {
&self.provider
}
pub fn model_name(&self) -> &str {
&self.model_name
}
pub fn full_model_name(&self) -> &str {
&self.full_model_name
}
/// Attach routing config for fallback behavior.
pub fn with_routing(mut self, routing: RoutingConfig) -> Self {
self.routing = Some(routing);
self
}
/// Attach agent context for per-agent metric labels.
pub fn with_context(
mut self,
agent_id: impl Into<String>,
process_type: impl Into<String>,
) -> Self {
self.agent_id = Some(agent_id.into());
self.process_type = Some(process_type.into());
self
}
/// Attach a worker type label for metrics (e.g. "builtin", "opencode").
pub fn with_worker_type(mut self, worker_type: impl Into<String>) -> Self {
self.worker_type = Some(worker_type.into());
self
}
/// Attach a shared usage accumulator for token tracking.
pub fn with_accumulator(
mut self,
accumulator: Arc<Mutex<crate::llm::usage::UsageAccumulator>>,
) -> Self {
self.usage_accumulator = Some(accumulator);
self
}
async fn provider_config_for_current_model(&self) -> Result<ProviderConfig, CompletionError> {
let provider_id = self
.full_model_name
.split_once('/')
.map(|(provider, _)| provider)
.unwrap_or("anthropic");
match provider_id {
"anthropic" => self
.llm_manager
.get_anthropic_provider()
.await
.map_err(|error| CompletionError::ProviderError(error.to_string())),
"openai" => self
.llm_manager
.get_openai_provider()
.await
.map_err(|error| CompletionError::ProviderError(error.to_string())),
"openai-chatgpt" => self
.llm_manager
.get_openai_chatgpt_provider()
.await
.map_err(|error| CompletionError::ProviderError(error.to_string())),
"github-copilot" => self
.llm_manager
.get_github_copilot_provider()
.await
.map_err(|error| CompletionError::ProviderError(error.to_string())),
_ => self
.llm_manager
.get_provider(provider_id)
.map_err(|error| CompletionError::ProviderError(error.to_string())),
}
}
/// Direct call to the provider (no fallback logic).
async fn attempt_completion(
&self,
request: CompletionRequest,
) -> Result<completion::CompletionResponse<RawResponse>, CompletionError> {
let provider_config = self.provider_config_for_current_model().await?;
match provider_config.api_type {
ApiType::Anthropic => self.call_anthropic(request, &provider_config).await,
ApiType::OpenAiCompletions => self.call_openai(request, &provider_config).await,
ApiType::OpenAiChatCompletions => {
let endpoint = format!(
"{}/chat/completions",
provider_config.base_url.trim_end_matches('/')
);
let display_name = provider_config
.name
.as_deref()
.unwrap_or("OpenAI-compatible provider");
let headers: Vec<(&str, &str)> = provider_config
.extra_headers
.iter()
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect();
self.call_openai_compatible_with_optional_auth(
request,
display_name,
&endpoint,
Some(provider_config.api_key.clone()),
&headers,
)
.await
}
ApiType::Azure => {
// Azure OpenAI Service requires a specific endpoint structure.
// Supported domain: *.openai.azure.com (HTTPS only)
let base_url = provider_config.base_url.trim_end_matches('/');
// Validate HTTPS scheme
if !base_url.starts_with("https://") {
return Err(CompletionError::ProviderError(format!(
"Invalid Azure endpoint. Azure OpenAI Service requires HTTPS.\n\
\n\
Detected: {}\n\
\n\
The endpoint must use https:// (e.g., https://<resource-name>.openai.azure.com)",
base_url
)));
}
// Validate that the endpoint is actually an Azure OpenAI endpoint
if !base_url.ends_with(".openai.azure.com") {
return Err(CompletionError::ProviderError(format!(
"Invalid Azure endpoint. Azure OpenAI Service requires a base_url ending in '.openai.azure.com'.\n\
\n\
Detected: {}\n\
\n\
If you are using Azure AI Foundry (hosting Anthropic, Llama, Mistral, etc.) or other Azure-hosted models,\n\
use the standard OpenAI-compatible provider instead:\n\
- Set api_type = \"openai_chat_completions\"\n\
- Point base_url directly to your endpoint (e.g., https://<resource>.services.ai.azure.com)\n\
- Omit the 'deployment' and 'api_version' fields\n\
\n\
For Azure OpenAI Service, the endpoint must follow this pattern:\n\
https://<resource-name>.openai.azure.com",
base_url
)));
}
let resource = base_url
.trim_start_matches("https://")
.trim_end_matches(".openai.azure.com");
let deployment = provider_config
.deployment
.as_ref()
.ok_or_else(|| CompletionError::ProviderError(
"Azure deployment name is required. Example: 'gpt-4o', 'gpt-35-turbo', etc.\n\
This is the deployment name you created in the Azure Portal for your OpenAI model."
.to_string()
))?;
let api_version = provider_config.api_version.as_ref().ok_or_else(|| {
CompletionError::ProviderError(
"Azure API version is required. Example: '2024-12-01-preview'\n\
Find available API versions in the Azure OpenAI documentation."
.to_string(),
)
})?;
let endpoint = format!(
"https://{}.openai.azure.com/openai/deployments/{}/chat/completions?api-version={}",
resource, deployment, api_version
);
let display_name = provider_config.name.as_deref().unwrap_or("Azure OpenAI");
// Azure uses "api-key" header instead of Authorization
let headers: Vec<(&str, &str)> =
vec![("api-key", provider_config.api_key.as_str())];
self.call_openai_compatible_with_optional_auth(
request,
display_name,
&endpoint,
None, // No Bearer token needed
&headers,
)
.await
}
ApiType::KiloGateway => {
let endpoint = format!(
"{}/chat/completions",
provider_config.base_url.trim_end_matches('/')
);
self.call_openai_compatible_with_optional_auth(
request,
"Kilo Gateway",
&endpoint,
Some(provider_config.api_key.clone()),
&[
("HTTP-Referer", "https://github.com/spacedriveapp/spacebot"),
("X-Title", "spacebot"),
],
)
.await
}
ApiType::OpenAiResponses => self.call_openai_responses(request, &provider_config).await,
ApiType::Gemini => {
self.call_openai_compatible(request, "Google Gemini", &provider_config)
.await
}
}
}
/// Try a model with retries and exponential backoff on transient errors.
///
/// Returns `Ok(response)` on success, or `Err((last_error, was_rate_limit))`
/// after exhausting retries. `was_rate_limit` indicates the final failure was
/// a 429/rate-limit (as opposed to a timeout or server error), so the caller
/// can decide whether to record cooldown.
async fn attempt_with_retries(
&self,
model_name: &str,
request: &CompletionRequest,
) -> Result<completion::CompletionResponse<RawResponse>, (CompletionError, bool)> {
let model = if model_name == self.full_model_name {
self.clone()
} else {
SpacebotModel::make(&self.llm_manager, model_name)
};
let mut last_error = None;
for attempt in 0..MAX_RETRIES_PER_MODEL {
if attempt > 0 {
let delay_ms = RETRY_BASE_DELAY_MS * 2u64.pow((attempt - 1) as u32);
tracing::debug!(
model = %model_name,
attempt = attempt + 1,
delay_ms,
"retrying after backoff"
);
tokio::time::sleep(std::time::Duration::from_millis(delay_ms)).await;
}
match model.attempt_completion(request.clone()).await {
Ok(response) => return Ok(response),
Err(error) => {
let error_str = error.to_string();
if !routing::is_retriable_error(&error_str) {
// Non-retriable (auth error, bad request, etc) — bail immediately
return Err((error, false));
}
tracing::warn!(
model = %model_name,
attempt = attempt + 1,
%error,
"retriable error"
);
last_error = Some(error_str);
}
}
}
let error_str = last_error.unwrap_or_default();
let was_rate_limit = routing::is_rate_limit_error(&error_str);
Err((
CompletionError::ProviderError(format!(
"{model_name} failed after {MAX_RETRIES_PER_MODEL} attempts: {error_str}"
)),
was_rate_limit,
))
}
}
impl CompletionModel for SpacebotModel {
type Response = RawResponse;
type StreamingResponse = RawStreamingResponse;
type Client = Arc<LlmManager>;
fn make(client: &Self::Client, model: impl Into<String>) -> Self {
let full_name = model.into();
// OpenRouter model names have the form "openrouter/provider/model",
// so split on the first "/" only and keep the rest as the model name.
let (provider, model_name) = if let Some(rest) = full_name.strip_prefix("openrouter/") {
("openrouter".to_string(), rest.to_string())
} else if let Some((p, m)) = full_name.split_once('/') {
(p.to_string(), m.to_string())
} else {
("anthropic".to_string(), full_name.clone())
};
let full_model_name = format!("{provider}/{model_name}");
Self {
llm_manager: client.clone(),
model_name,
provider,
full_model_name,
routing: None,
agent_id: None,
process_type: None,
worker_type: None,
usage_accumulator: None,
}
}
async fn completion(
&self,
request: CompletionRequest,
) -> Result<completion::CompletionResponse<RawResponse>, CompletionError> {
#[cfg(feature = "metrics")]
let start = std::time::Instant::now();
let result = async move {
let Some(routing) = &self.routing else {
// No routing config — just call the model directly, no fallback/retry
return self.attempt_completion(request).await;
};
let cooldown = routing.rate_limit_cooldown_secs;
let fallbacks = routing.get_fallbacks(&self.full_model_name);
let mut last_error: Option<CompletionError> = None;
// Try the primary model (with retries) unless it's in rate-limit cooldown
// and we have fallbacks to try instead.
let primary_rate_limited = self
.llm_manager
.is_rate_limited(&self.full_model_name, cooldown)
.await;
let skip_primary = primary_rate_limited && !fallbacks.is_empty();
if skip_primary {
tracing::debug!(
model = %self.full_model_name,
"primary model in rate-limit cooldown, skipping to fallbacks"
);
} else {
match self
.attempt_with_retries(&self.full_model_name, &request)
.await
{
Ok(response) => return Ok(response),
Err((error, was_rate_limit)) => {
if was_rate_limit {
self.llm_manager
.record_rate_limit(&self.full_model_name)
.await;
}
if fallbacks.is_empty() {
// No fallbacks — this is the final error
return Err(error);
}
tracing::warn!(
model = %self.full_model_name,
"primary model exhausted retries, trying fallbacks"
);
last_error = Some(error);
}
}
}
// Try fallback chain, each with their own retry loop
for (index, fallback_name) in fallbacks.iter().take(MAX_FALLBACK_ATTEMPTS).enumerate() {
if self
.llm_manager
.is_rate_limited(fallback_name, cooldown)
.await
{
tracing::debug!(
fallback = %fallback_name,
"fallback model in cooldown, skipping"
);
continue;
}
match self.attempt_with_retries(fallback_name, &request).await {
Ok(response) => {
tracing::info!(
original = %self.full_model_name,
fallback = %fallback_name,
attempt = index + 1,
"fallback model succeeded"
);
return Ok(response);
}
Err((error, was_rate_limit)) => {
if was_rate_limit {
self.llm_manager.record_rate_limit(fallback_name).await;
}
tracing::warn!(
fallback = %fallback_name,
"fallback model exhausted retries, continuing chain"
);
last_error = Some(error);
}
}
}
Err(last_error.unwrap_or_else(|| {
CompletionError::ProviderError("all models in fallback chain failed".into())
}))
}
.await;
#[cfg(feature = "metrics")]
{
let elapsed = start.elapsed().as_secs_f64();
let agent_label = self.agent_id.as_deref().unwrap_or("unknown");
let tier_label = self.process_type.as_deref().unwrap_or("unknown");
let worker_label = match self.worker_type.as_deref() {
Some(worker_type) => worker_type,
None if tier_label == "worker" => "unknown",
None => "",
};
let metrics = crate::telemetry::Metrics::global();
metrics
.llm_requests_total
.with_label_values(&[agent_label, &self.full_model_name, tier_label, worker_label])
.inc();
metrics
.llm_request_duration_seconds
.with_label_values(&[agent_label, &self.full_model_name, tier_label, worker_label])
.observe(elapsed);
if let Ok(ref response) = result {
let usage = &response.usage;
if usage.input_tokens > 0 || usage.output_tokens > 0 {
metrics
.llm_tokens_total
.with_label_values(&[
agent_label,
&self.full_model_name,
tier_label,
"input",
worker_label,
])
.inc_by(usage.input_tokens);
metrics
.llm_tokens_total
.with_label_values(&[
agent_label,
&self.full_model_name,
tier_label,
"output",
worker_label,
])
.inc_by(usage.output_tokens);
if usage.cached_input_tokens > 0 {
metrics
.llm_tokens_total
.with_label_values(&[
agent_label,
&self.full_model_name,
tier_label,
"cached_input",
worker_label,
])
.inc_by(usage.cached_input_tokens);
}
let cost = crate::llm::pricing::estimate_cost(
&self.full_model_name,
usage.input_tokens,
usage.output_tokens,
usage.cached_input_tokens,
);
if cost > 0.0 {
metrics
.llm_estimated_cost_dollars
.with_label_values(&[
agent_label,
&self.full_model_name,
tier_label,
worker_label,
])
.inc_by(cost);
// Track per-worker cost separately when this is a worker process.
if tier_label == "worker" {
metrics
.worker_cost_dollars
.with_label_values(&[agent_label, worker_label])
.inc_by(cost);
}
}
}
}
if let Err(ref error) = result {
let error_type = match error {
rig::completion::CompletionError::ProviderError(msg) => {
if msg.contains("rate") || msg.contains("429") {
"rate_limit"
} else if msg.contains("timeout") {
"timeout"
} else if msg.contains("context") || msg.contains("too long") {
"context_overflow"
} else {
"provider_error"
}
}
_ => "other",
};
metrics
.process_errors_total
.with_label_values(&[agent_label, tier_label, error_type, worker_label])
.inc();
if error_type == "context_overflow" {
metrics
.context_overflow_total
.with_label_values(&[agent_label, tier_label])
.inc();
}
}
}
// Record usage in the accumulator (if attached).
if let Some(ref accumulator) = self.usage_accumulator
&& let Ok(ref response) = result
{
let body = &response.raw_response.body;
let extended = if self.provider == "anthropic" {
crate::llm::usage::ExtendedUsage::from_anthropic_body(body)
} else {
crate::llm::usage::ExtendedUsage::from_openai_body(body)
};
let cost =
crate::llm::pricing::estimate_cost_extended(&self.full_model_name, &extended);
accumulator
.lock()
.await
.add(extended, &self.full_model_name, &self.provider, cost);
}
result
}
async fn stream(
&self,
request: CompletionRequest,
) -> Result<StreamingCompletionResponse<RawStreamingResponse>, CompletionError> {
let provider_config = self.provider_config_for_current_model().await?;
match provider_config.api_type {
ApiType::OpenAiCompletions => self.stream_openai(request, &provider_config).await,
ApiType::OpenAiChatCompletions => {
let endpoint = format!(
"{}/chat/completions",
provider_config.base_url.trim_end_matches('/')
);
let display_name = provider_config
.name
.as_deref()
.unwrap_or("OpenAI-compatible provider");
let headers: Vec<(&str, &str)> = provider_config
.extra_headers
.iter()
.map(|(key, value)| (key.as_str(), value.as_str()))
.collect();
self.stream_openai_compatible_with_optional_auth(
request,
display_name,
&endpoint,
Some(provider_config.api_key.clone()),
&headers,
)
.await
}
ApiType::Azure => {
// Azure OpenAI Service requires a specific endpoint structure.
// Supported domain: *.openai.azure.com (HTTPS only)
let base_url = provider_config.base_url.trim_end_matches('/');
// Validate HTTPS scheme
if !base_url.starts_with("https://") {
return Err(CompletionError::ProviderError(format!(
"Invalid Azure endpoint. Azure OpenAI Service requires HTTPS.\n\
\n\
Detected: {}\n\
\n\
The endpoint must use https:// (e.g., https://<resource-name>.openai.azure.com)",
base_url
)));
}
// Validate that the endpoint is actually an Azure OpenAI endpoint
if !base_url.ends_with(".openai.azure.com") {
return Err(CompletionError::ProviderError(format!(
"Invalid Azure endpoint. Azure OpenAI Service requires a base_url ending in '.openai.azure.com'.\n\
\n\
Detected: {}\n\
\n\
If you are using Azure AI Foundry (hosting Anthropic, Llama, Mistral, etc.) or other Azure-hosted models,\n\
use the standard OpenAI-compatible provider instead:\n\
- Set api_type = \"openai_chat_completions\"\n\
- Point base_url directly to your endpoint (e.g., https://<resource>.services.ai.azure.com)\n\
- Omit the 'deployment' and 'api_version' fields\n\
\n\
For Azure OpenAI Service, the endpoint must follow this pattern:\n\
https://<resource-name>.openai.azure.com",
base_url
)));
}
let resource = base_url
.trim_start_matches("https://")
.trim_end_matches(".openai.azure.com");
let deployment = provider_config
.deployment
.as_ref()
.ok_or_else(|| CompletionError::ProviderError(
"Azure deployment name is required. Example: 'gpt-4o', 'gpt-35-turbo', etc.\n\
This is the deployment name you created in the Azure Portal for your OpenAI model."
.to_string()
))?;
let api_version = provider_config.api_version.as_ref().ok_or_else(|| {
CompletionError::ProviderError(
"Azure API version is required. Example: '2024-12-01-preview'\n\
Find available API versions in the Azure OpenAI documentation."
.to_string(),
)
})?;
let endpoint = format!(
"https://{}.openai.azure.com/openai/deployments/{}/chat/completions?api-version={}",
resource, deployment, api_version
);
let display_name = provider_config.name.as_deref().unwrap_or("Azure OpenAI");
let headers: Vec<(&str, &str)> =
vec![("api-key", provider_config.api_key.as_str())];
self.stream_openai_compatible_with_optional_auth(
request,
display_name,
&endpoint,
None,
&headers,
)
.await
}
ApiType::KiloGateway => {
let endpoint = format!(
"{}/chat/completions",
provider_config.base_url.trim_end_matches('/')
);
self.stream_openai_compatible_with_optional_auth(
request,
"Kilo Gateway",
&endpoint,
Some(provider_config.api_key.clone()),
&[
("HTTP-Referer", "https://github.com/spacedriveapp/spacebot"),
("X-Title", "spacebot"),
],
)
.await
}
ApiType::Gemini => {
self.stream_openai_compatible(request, "Google Gemini", &provider_config)
.await
}
ApiType::Anthropic => {
let response = self.attempt_completion(request).await?;
Ok(stream_from_completion_response(response))
}
ApiType::OpenAiResponses => {
self.stream_openai_responses(request, &provider_config)
.await
}
}
}
}
impl SpacebotModel {
async fn call_anthropic(
&self,
request: CompletionRequest,
provider_config: &ProviderConfig,
) -> Result<completion::CompletionResponse<RawResponse>, CompletionError> {
let api_key = provider_config.api_key.as_str();
let effort = self
.routing
.as_ref()
.map(|r| r.thinking_effort_for_model(&self.model_name))
.unwrap_or("auto");
let anthropic_request = crate::llm::anthropic::build_anthropic_request(
self.llm_manager.http_client(),
api_key,
&provider_config.base_url,
&self.model_name,
&request,
effort,
provider_config.use_bearer_auth,
);
let is_oauth =
anthropic_request.auth_path == crate::llm::anthropic::AnthropicAuthPath::OAuthToken;
let original_tools = anthropic_request.original_tools;
let response = anthropic_request
.builder
.send()
.await
.map_err(|e| CompletionError::ProviderError(e.to_string()))?;
let status = response.status();
let response_text = response.text().await.map_err(|e| {
CompletionError::ProviderError(format!("failed to read response body: {e}"))
})?;
let response_body: serde_json::Value =
serde_json::from_str(&response_text).map_err(|e| {
CompletionError::ProviderError(format!(
"Anthropic response ({status}) is not valid JSON: {e}\nBody: {}",
truncate_body(&response_text)
))
})?;
if !status.is_success() {
let message = response_body["error"]["message"]
.as_str()
.unwrap_or("unknown error");
return Err(CompletionError::ProviderError(format!(
"Anthropic API error ({status}): {message}"
)));
}
let mut completion = parse_anthropic_response(response_body)?;
// Reverse-map tool names when using OAuth (Claude Code canonical → original)
if is_oauth && !original_tools.is_empty() {
reverse_map_tool_names(&mut completion, &original_tools);
}
Ok(completion)
}
async fn call_openai(
&self,
request: CompletionRequest,
provider_config: &ProviderConfig,
) -> Result<completion::CompletionResponse<RawResponse>, CompletionError> {
let stream = self.stream_openai(request, provider_config).await?;
collect_streaming_completion_response(stream).await
}
async fn stream_openai(
&self,
request: CompletionRequest,
provider_config: &ProviderConfig,
) -> Result<StreamingCompletionResponse<RawStreamingResponse>, CompletionError> {
let api_key = provider_config.api_key.as_str();
let provider_label = provider_config
.name
.as_deref()
.filter(|name| !name.trim().is_empty())
.map(ToOwned::to_owned)
.unwrap_or_else(|| provider_display_name(&self.provider));
let mut messages = Vec::new();
if let Some(preamble) = &request.preamble {
let preamble = crate::prompts::strip_system_prompt_cache_boundary(preamble);
messages.push(serde_json::json!({
"role": "system",
"content": preamble,
}));
}
messages.extend(convert_messages_to_openai(&request.chat_history));
let api_model_name = self.remap_model_name_for_api();
let mut body = serde_json::json!({
"model": api_model_name,
"messages": messages,
});
if let Some(max_tokens) = request.max_tokens {
body["max_tokens"] = serde_json::json!(max_tokens);
}
if let Some(temperature) = request.temperature {
body["temperature"] = serde_json::json!(temperature);
}
if !request.tools.is_empty() {
let tools: Vec<serde_json::Value> = request
.tools
.iter()
.map(|t| {
serde_json::json!({
"type": "function",
"function": {
"name": t.name,
"description": t.description,
"parameters": t.parameters,
}
})
})
.collect();
body["tools"] = serde_json::json!(tools);
}
let chat_completions_url = format!(
"{}/v1/chat/completions",
provider_config.base_url.trim_end_matches('/')
);
let openai_account_id = if self.provider == "openai-chatgpt" {
self.llm_manager.get_openai_account_id().await
} else {
None
};
let http_client = self.llm_manager.http_client().clone();
let auth_header = format!("Bearer {api_key}");
let extra_headers = provider_config.extra_headers.clone();
let is_kimi_endpoint = chat_completions_url.contains("kimi.com")
|| chat_completions_url.contains("moonshot.ai");
self.stream_openai_chat_request(
move |request_body| {
let mut request_builder = http_client
.post(&chat_completions_url)
.header("authorization", auth_header.clone())
.header("content-type", "application/json");
if let Some(account_id) = openai_account_id.as_deref() {
request_builder = request_builder.header("chatgpt-account-id", account_id);
}
if is_kimi_endpoint {
request_builder = request_builder.header("user-agent", "KimiCLI/1.3");
}
for (key, value) in &extra_headers {
request_builder = request_builder.header(key, value);
}
request_builder.json(request_body)
},
body,
&provider_label,
)
.await
}
async fn call_openai_responses(
&self,
request: CompletionRequest,
provider_config: &ProviderConfig,
) -> Result<completion::CompletionResponse<RawResponse>, CompletionError> {
let base_url = provider_config.base_url.trim_end_matches('/');
let is_chatgpt_codex = self.provider == "openai-chatgpt";
let responses_url = if is_chatgpt_codex {
format!("{base_url}/responses")
} else {
format!("{base_url}/v1/responses")
};
let api_key = provider_config.api_key.as_str();
let provider_label = provider_config
.name
.as_deref()
.filter(|name| !name.trim().is_empty())
.map(ToOwned::to_owned)
.unwrap_or_else(|| provider_display_name(&self.provider));
let input = convert_messages_to_openai_responses(&request.chat_history);
let api_model_name = self.remap_model_name_for_api();
let mut body = serde_json::json!({
"model": api_model_name,
"input": input,
});
if let Some(preamble) = &request.preamble {
let preamble = crate::prompts::strip_system_prompt_cache_boundary(preamble);
body["instructions"] = serde_json::json!(preamble);
} else if is_chatgpt_codex {
body["instructions"] = serde_json::json!(
"You are Spacebot. Follow instructions exactly and respond concisely."
);
}
if !is_chatgpt_codex && let Some(max_tokens) = request.max_tokens {
body["max_output_tokens"] = serde_json::json!(max_tokens);
}
if !is_chatgpt_codex && let Some(temperature) = request.temperature {
body["temperature"] = serde_json::json!(temperature);
}
if is_chatgpt_codex {
body["store"] = serde_json::json!(false);
body["stream"] = serde_json::json!(true);
}
if !request.tools.is_empty() {
let tools: Vec<serde_json::Value> = request
.tools
.iter()
.map(|tool_definition| {
serde_json::json!({
"type": "function",
"name": tool_definition.name,
"description": tool_definition.description,
"parameters": tool_definition.parameters,
})
})
.collect();
body["tools"] = serde_json::json!(tools);
}
let openai_account_id = if self.provider == "openai-chatgpt" {
self.llm_manager.get_openai_account_id().await
} else {
None
};
let mut request_builder = self
.llm_manager
.http_client()
.post(&responses_url)
.header("authorization", format!("Bearer {api_key}"))
.header("content-type", "application/json");
if let Some(account_id) = openai_account_id {
request_builder = request_builder.header("ChatGPT-Account-Id", account_id);
}