opencrates 3.0.1

Enterprise-grade AI-powered Rust development companion with comprehensive automation, monitoring, and deployment capabilities
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
//! OpenAI Agents SDK Integration for enhanced AI capabilities

use anyhow::{Context, Result};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::RwLock;
use tracing::{debug, error, info, instrument, warn};

use crate::providers::openai::OpenAIProvider;
use crate::providers::{GenerationRequest, LegacyLLMProvider};
use crate::utils::cache::CacheManager;
pub use crate::utils::config::OpenAIConfig;
use crate::utils::error::OpenCratesError;
use crate::utils::metrics::OpenCratesMetrics;
use std::future::Future;
use std::pin::Pin;

/// `OpenAI` client configuration
#[derive(Debug, Clone)]
// TODO: document this
// TODO: document this
// TODO: document this
pub struct OpenAIClientConfig {
    /// The API key for the `OpenAI` service.
    // TODO: document this
    // TODO: document this
    pub api_key: String,
    /// The base URL for the `OpenAI` API.
    // TODO: document this
    // TODO: document this
    pub base_url: String,
    /// The model to use for generation.
    // TODO: document this
    // TODO: document this
    pub model: String,
    /// The maximum number of tokens to generate.
    // TODO: document this
    // TODO: document this
    pub max_tokens: Option<u32>,
    /// The temperature for sampling.
    // TODO: document this
    // TODO: document this
    pub temperature: Option<f32>,
    /// The timeout for API requests.
    // TODO: document this
    // TODO: document this
    pub timeout: Duration,
    /// The maximum number of retries for failed requests.
    // TODO: document this
    // TODO: document this
    pub max_retries: u32,
}

impl Default for OpenAIClientConfig {
    fn default() -> Self {
        Self {
            api_key: std::env::var("OPENAI_API_KEY").unwrap_or_default(),
            base_url: "https://api.openai.com/v1".to_string(),
            model: "gpt-4o".to_string(),
            max_tokens: Some(2048),
            temperature: Some(0.7),
            timeout: Duration::from_secs(30),
            max_retries: 3,
        }
    }
}

/// Chat message roles
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
// TODO: document this
// TODO: document this
// TODO: document this
pub enum MessageRole {
    /// A system message.
    System,
    /// A user message.
    User,
    /// An assistant message.
    Assistant,
    /// A tool message.
    Tool,
}

/// Chat message content
#[derive(Debug, Clone, Serialize, Deserialize)]
// TODO: document this
// TODO: document this
// TODO: document this
pub struct ChatMessage {
    /// The role of the message author.
    // TODO: document this
    // TODO: document this
    pub role: MessageRole,
    /// The content of the message.
    // TODO: document this
    // TODO: document this
    pub content: String,
    /// The name of the message author.
    #[serde(skip_serializing_if = "Option::is_none")]
    // TODO: document this
    // TODO: document this
    pub name: Option<String>,
    /// A list of tool calls made in the message.
    #[serde(skip_serializing_if = "Option::is_none")]
    // TODO: document this
    // TODO: document this
    pub tool_calls: Option<Vec<ToolCall>>,
    /// The ID of the tool call this message is a response to.
    #[serde(skip_serializing_if = "Option::is_none")]
    // TODO: document this
    // TODO: document this
    pub tool_call_id: Option<String>,
}

impl ChatMessage {
    /// Creates a new system message.
    // TODO: document this
    // TODO: document this
    // TODO: document this
    // TODO: document this
    #[must_use]
    pub fn system(content: String) -> Self {
        Self {
            role: MessageRole::System,
            content,
            name: None,
            tool_calls: None,
            tool_call_id: None,
        }
    }

    /// Creates a new user message.
    // TODO: document this
    // TODO: document this
    // TODO: document this
    // TODO: document this
    #[must_use]
    pub fn user(content: String) -> Self {
        Self {
            role: MessageRole::User,
            content,
            name: None,
            tool_calls: None,
            tool_call_id: None,
        }
    }

    /// Creates a new assistant message.
    // TODO: document this
    // TODO: document this
    // TODO: document this
    // TODO: document this
    #[must_use]
    pub fn assistant(content: String) -> Self {
        Self {
            role: MessageRole::Assistant,
            content,
            name: None,
            tool_calls: None,
            tool_call_id: None,
        }
    }

    /// Adds tool calls to the message.
    // TODO: document this
    // TODO: document this
    // TODO: document this
    // TODO: document this
    #[must_use]
    pub fn with_tool_calls(mut self, tool_calls: Vec<ToolCall>) -> Self {
        self.tool_calls = Some(tool_calls);
        self
    }
}

/// Function tool definition
#[derive(Serialize)]
pub struct FunctionTool {
    pub name: String,
    pub description: String,
    pub parameters: Value,
    #[serde(skip)]
    pub function:
        Arc<dyn Fn(Value) -> Pin<Box<dyn Future<Output = Result<Value>> + Send>> + Send + Sync>,
}

impl Clone for FunctionTool {
    fn clone(&self) -> Self {
        Self {
            name: self.name.clone(),
            description: self.description.clone(),
            parameters: self.parameters.clone(),
            function: self.function.clone(),
        }
    }
}

impl std::fmt::Debug for FunctionTool {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FunctionTool")
            .field("name", &self.name)
            .field("description", &self.description)
            .field("parameters", &self.parameters)
            .field("function", &"<function>")
            .finish()
    }
}

impl FunctionTool {
    pub fn new<F, Fut>(name: &str, description: &str, parameters: Value, func: F) -> Self
    where
        F: Fn(Value) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<Value>> + Send + 'static,
    {
        Self {
            name: name.to_string(),
            description: description.to_string(),
            parameters,
            function: Arc::new(move |args| Box::pin(func(args))),
        }
    }

    pub fn call(&self, args: Value) -> Result<Value> {
        // For now, we'll make this synchronous by blocking on the async function
        // In a real implementation, this should be async
        let future = (self.function)(args);
        tokio::task::block_in_place(|| tokio::runtime::Handle::current().block_on(future))
    }
}

/// The definition of a function that can be called by the model.
#[derive(Debug, Clone, Serialize, Deserialize)]
// TODO: document this
// TODO: document this
// TODO: document this
pub struct FunctionDefinition {
    /// The name of the function.
    // TODO: document this
    // TODO: document this
    pub name: String,
    /// A description of the function.
    // TODO: document this
    // TODO: document this
    pub description: String,
    /// The parameters of the function.
    // TODO: document this
    // TODO: document this
    pub parameters: serde_json::Value,
}

/// Tool call from assistant
#[derive(Debug, Clone, Serialize, Deserialize)]
// TODO: document this
// TODO: document this
// TODO: document this
pub struct ToolCall {
    /// The ID of the tool call.
    // TODO: document this
    // TODO: document this
    pub id: String,
    /// The type of the tool.
    #[serde(rename = "type")]
    // TODO: document this
    // TODO: document this
    pub tool_type: String,
    /// The function call.
    // TODO: document this
    // TODO: document this
    pub function: FunctionCall,
}

/// A call to a function made by the model.
#[derive(Debug, Clone, Serialize, Deserialize)]
// TODO: document this
// TODO: document this
// TODO: document this
pub struct FunctionCall {
    /// The name of the function to call.
    // TODO: document this
    // TODO: document this
    pub name: String,
    /// The arguments to the function.
    // TODO: document this
    // TODO: document this
    pub arguments: String,
}

/// Chat completion request
#[derive(Debug, Serialize)]
// TODO: document this
// TODO: document this
// TODO: document this
pub struct ChatCompletionRequest {
    /// The model to use for the completion.
    // TODO: document this
    // TODO: document this
    pub model: String,
    /// The messages to complete.
    // TODO: document this
    // TODO: document this
    pub messages: Vec<ChatMessage>,
    /// The maximum number of tokens to generate.
    #[serde(skip_serializing_if = "Option::is_none")]
    // TODO: document this
    // TODO: document this
    pub max_tokens: Option<u32>,
    /// The temperature to use for sampling.
    #[serde(skip_serializing_if = "Option::is_none")]
    // TODO: document this
    // TODO: document this
    pub temperature: Option<f32>,
    /// The tools to make available to the model.
    #[serde(skip_serializing_if = "Option::is_none")]
    // TODO: document this
    // TODO: document this
    pub tools: Option<Vec<FunctionTool>>,
    /// The choice of tool to use.
    #[serde(skip_serializing_if = "Option::is_none")]
    // TODO: document this
    // TODO: document this
    pub tool_choice: Option<String>,
    /// Whether to stream the completion.
    #[serde(skip_serializing_if = "Option::is_none")]
    // TODO: document this
    // TODO: document this
    pub stream: Option<bool>,
}

/// Chat completion response
#[derive(Debug, Deserialize)]
// TODO: document this
// TODO: document this
// TODO: document this
pub struct ChatCompletionResponse {
    /// The ID of the response.
    // TODO: document this
    // TODO: document this
    pub id: String,
    /// The object type.
    // TODO: document this
    // TODO: document this
    pub object: String,
    /// The timestamp of the response.
    // TODO: document this
    // TODO: document this
    pub created: u64,
    /// The model that generated the response.
    // TODO: document this
    // TODO: document this
    pub model: String,
    /// The choices made by the model.
    // TODO: document this
    // TODO: document this
    pub choices: Vec<ChatChoice>,
    /// The usage statistics for the completion.
    // TODO: document this
    // TODO: document this
    pub usage: Option<Usage>,
}

/// A choice in a chat completion.
#[derive(Debug, Deserialize)]
// TODO: document this
// TODO: document this
// TODO: document this
pub struct ChatChoice {
    /// The index of the choice.
    // TODO: document this
    // TODO: document this
    pub index: u32,
    /// The message generated by the model.
    // TODO: document this
    // TODO: document this
    pub message: ChatMessage,
    /// The reason the model finished generating the message.
    // TODO: document this
    // TODO: document this
    pub finish_reason: Option<String>,
}

/// Usage statistics for a chat completion.
#[derive(Debug, Clone, Serialize, Deserialize)]
// TODO: document this
// TODO: document this
// TODO: document this
pub struct Usage {
    /// The number of tokens in the prompt.
    // TODO: document this
    // TODO: document this
    pub prompt_tokens: usize,
    /// The number of tokens in the completion.
    // TODO: document this
    // TODO: document this
    pub completion_tokens: usize,
    /// The total number of tokens.
    // TODO: document this
    // TODO: document this
    pub total_tokens: usize,
}

/// Streaming chunk response
#[derive(Debug, Deserialize)]
// TODO: document this
// TODO: document this
// TODO: document this
pub struct ChatCompletionChunk {
    /// The ID of the chunk.
    // TODO: document this
    // TODO: document this
    pub id: String,
    /// The object type.
    // TODO: document this
    // TODO: document this
    pub object: String,
    /// The timestamp of the chunk.
    // TODO: document this
    // TODO: document this
    pub created: u64,
    /// The model that generated the chunk.
    // TODO: document this
    // TODO: document this
    pub model: String,
    /// The choices in the chunk.
    // TODO: document this
    // TODO: document this
    pub choices: Vec<ChunkChoice>,
}

/// A choice in a streaming chunk.
#[derive(Debug, Deserialize)]
// TODO: document this
// TODO: document this
// TODO: document this
pub struct ChunkChoice {
    /// The index of the choice.
    // TODO: document this
    // TODO: document this
    pub index: u32,
    /// The delta of the choice.
    // TODO: document this
    // TODO: document this
    pub delta: ChunkDelta,
    /// The reason the model finished generating the choice.
    // TODO: document this
    // TODO: document this
    pub finish_reason: Option<String>,
}

/// The delta of a streaming chunk.
#[derive(Debug, Deserialize)]
// TODO: document this
// TODO: document this
// TODO: document this
pub struct ChunkDelta {
    /// The role of the message author.
    // TODO: document this
    // TODO: document this
    pub role: Option<MessageRole>,
    /// The content of the message.
    // TODO: document this
    // TODO: document this
    pub content: Option<String>,
    /// The tool calls made in the message.
    // TODO: document this
    // TODO: document this
    pub tool_calls: Option<Vec<ToolCall>>,
}

#[async_trait]
pub trait Function: Send + Sync {
    /// The name of the function.
    fn name(&self) -> String;
    /// A description of the function.
    fn description(&self) -> String;
    /// The parameters of the function.
    fn parameters(&self) -> Value;
    /// Calls the function with the given arguments.
    async fn call(&self, args: Value) -> Result<Value>;
}

/// Crate search function
// TODO: document this
// TODO: document this
// TODO: document this
pub struct CrateSearchFunction {
    // In a real implementation, this would have access to the crate database
}

#[async_trait]
impl Function for CrateSearchFunction {
    fn name(&self) -> String {
        "search_crates".to_string()
    }

    fn description(&self) -> String {
        "Search for Rust crates by name, description, or keywords".to_string()
    }

    fn parameters(&self) -> Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "Search query for crates"
                },
                "limit": {
                    "type": "integer",
                    "description": "Maximum number of results to return",
                    "default": 10
                }
            },
            "required": ["query"]
        })
    }

    async fn call(&self, args: Value) -> Result<Value> {
        let _query = args
            .get("query")
            .and_then(|v| v.as_str())
            .ok_or_else(|| OpenCratesError::validation("Missing query parameter".to_string()))?;

        let limit = args
            .get("limit")
            .and_then(serde_json::Value::as_u64)
            .unwrap_or(10) as usize;

        // Mock search results
        let results = vec![
            serde_json::json!({
                "name": "serde",
                "version": "1.0.193",
                "description": "A generic serialization/deserialization framework",
                "downloads": 500_000_000,
                "repository": "https://github.com/serde-rs/serde"
            }),
            serde_json::json!({
                "name": "tokio",
                "version": "1.35.1",
                "description": "An event-driven, non-blocking I/O platform",
                "downloads": 300_000_000,
                "repository": "https://github.com/tokio-rs/tokio"
            }),
        ];

        let total_count = results.len();
        let limited_results = results.into_iter().take(limit).collect::<Vec<_>>();

        Ok(serde_json::json!({
            "results": limited_results,
            "total": total_count
        }))
    }
}

/// Crate recommendation function
// TODO: document this
// TODO: document this
// TODO: document this
pub struct CrateRecommendationFunction {
    // Would have access to ML models and user behavior data
}

#[async_trait]
impl Function for CrateRecommendationFunction {
    fn name(&self) -> String {
        "recommend_crates".to_string()
    }

    fn description(&self) -> String {
        "Get personalized crate recommendations based on project requirements".to_string()
    }

    fn parameters(&self) -> Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "project_type": {
                    "type": "string",
                    "enum": ["web", "cli", "library", "game", "embedded"],
                    "description": "Type of Rust project"
                },
                "categories": {
                    "type": "array",
                    "items": {"type": "string"},
                    "description": "Relevant categories or use cases"
                },
                "existing_crates": {
                    "type": "array",
                    "items": {"type": "string"},
                    "description": "Crates already in use"
                }
            },
            "required": ["project_type"]
        })
    }

    async fn call(&self, args: Value) -> Result<Value> {
        let project_type = args
            .get("project_type")
            .and_then(|v| v.as_str())
            .ok_or_else(|| {
                OpenCratesError::validation("Missing project_type parameter".to_string())
            })?;

        // Mock recommendations based on project type
        let recommendations = match project_type {
            "web" => vec![
                serde_json::json!({
                    "name": "axum",
                    "reason": "Modern, ergonomic web framework with excellent performance",
                    "confidence": 0.95
                }),
                serde_json::json!({
                    "name": "sqlx",
                    "reason": "Async SQL toolkit with compile-time checked queries",
                    "confidence": 0.90
                }),
            ],
            "cli" => vec![
                serde_json::json!({
                    "name": "clap",
                    "reason": "Feature-rich command line argument parser",
                    "confidence": 0.98
                }),
                serde_json::json!({
                    "name": "colored",
                    "reason": "Simple library for colored terminal output",
                    "confidence": 0.85
                }),
            ],
            _ => vec![serde_json::json!({
                "name": "anyhow",
                "reason": "Flexible error handling library",
                "confidence": 0.92
            })],
        };

        Ok(serde_json::json!({
            "recommendations": recommendations,
            "project_type": project_type
        }))
    }
}

/// Function registry
// TODO: document this
// TODO: document this
// TODO: document this
pub struct FunctionRegistry {
    functions: Vec<FunctionTool>,
}

impl Default for FunctionRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl FunctionRegistry {
    #[must_use]
    pub fn new() -> Self {
        Self {
            functions: Vec::new(),
        }
    }

    pub fn register_function(&mut self, f: FunctionTool) {
        self.functions.push(f);
    }

    #[must_use]
    pub fn list_functions(&self) -> &[FunctionTool] {
        &self.functions
    }
}

#[must_use]
pub fn create_crate_search_function() -> FunctionTool {
    FunctionTool::new(
        "crate_search",
        "Search crates by keyword",
        serde_json::json!({}),
        |_| Box::pin(async { Ok(serde_json::json!({})) }),
    )
}

/// `OpenAI` client
#[derive(Clone)]
// TODO: document this
// TODO: document this
// TODO: document this
pub struct OpenAIClient {
    config: OpenAIClientConfig,
    http_client: reqwest::Client,
    metrics: Arc<OpenCratesMetrics>,
    cache: Arc<CacheManager>,
    function_registry: Arc<RwLock<FunctionRegistry>>,
}

impl OpenAIClient {
    // TODO: document this
    // TODO: document this
    // TODO: document this
    // TODO: document this
    #[must_use]
    pub fn new(
        config: OpenAIClientConfig,
        metrics: Arc<OpenCratesMetrics>,
        cache: Arc<CacheManager>,
    ) -> Self {
        let http_client = reqwest::Client::builder()
            .timeout(config.timeout)
            .build()
            .expect("Failed to create HTTP client");

        Self {
            config,
            http_client,
            metrics,
            cache,
            function_registry: Arc::new(RwLock::new(FunctionRegistry::new())),
        }
    }

    /// Retrieves the cache manager.
    // TODO: document this
    // TODO: document this
    // TODO: document this
    // TODO: document this
    #[must_use]
    pub fn cache(&self) -> &Arc<CacheManager> {
        &self.cache
    }

    /// Register a custom function
    // TODO: document this
    // TODO: document this
    // TODO: document this
    // TODO: document this
    pub async fn register_function(&self, function: FunctionTool) {
        let mut registry = self.function_registry.write().await;
        registry.register_function(function);
    }

    /// Create a chat completion
    #[instrument(skip(self, messages))]
    // TODO: document this
    // TODO: document this
    // TODO: document this
    // TODO: document this
    pub async fn chat_completion(
        &self,
        messages: Vec<ChatMessage>,
        use_tools: bool,
    ) -> Result<ChatCompletionResponse> {
        let start = Instant::now();

        let mut request = ChatCompletionRequest {
            model: self.config.model.clone(),
            messages,
            max_tokens: self.config.max_tokens,
            temperature: self.config.temperature,
            tools: None,
            tool_choice: None,
            stream: Some(false),
        };

        if use_tools {
            let registry = self.function_registry.read().await;
            request.tools = Some(registry.list_functions().to_vec());
            request.tool_choice = Some("auto".to_string());
        }

        let response = self
            .http_client
            .post(format!("{}/chat/completions", self.config.base_url))
            .header("Authorization", format!("Bearer {}", self.config.api_key))
            .header("Content-Type", "application/json")
            .json(&request)
            .send()
            .await
            .context("Failed to send chat completion request")?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            return Err(
                OpenCratesError::internal(format!("OpenAI API error: {error_text}")).into(),
            );
        }

        let completion: ChatCompletionResponse = response
            .json()
            .await
            .context("Failed to parse chat completion response")?;

        let duration = start.elapsed();
        self.metrics.record_api_request().await.unwrap_or(());

        info!("Chat completion completed in {}ms", duration.as_millis());

        Ok(completion)
    }

    /// Handle function calls from assistant response
    #[instrument(skip(self, tool_calls))]
    // TODO: document this
    // TODO: document this
    // TODO: document this
    // TODO: document this
    pub async fn handle_tool_calls(&self, tool_calls: Vec<ToolCall>) -> Result<Vec<ChatMessage>> {
        let mut tool_messages = Vec::new();
        let registry = self.function_registry.read().await;

        for tool_call in tool_calls {
            if tool_call.tool_type != "function" {
                continue;
            }

            let function_name = &tool_call.function.name;
            let function_args: serde_json::Value =
                serde_json::from_str(&tool_call.function.arguments)
                    .context("Failed to parse function arguments")?;

            debug!(
                "Calling function: {} with args: {}",
                function_name, function_args
            );

            let result = if let Some(function) = registry
                .list_functions()
                .iter()
                .find(|f| f.name == *function_name)
            {
                match function.call(function_args) {
                    Ok(result) => result,
                    Err(e) => {
                        error!("Function {} failed: {}", function_name, e);
                        serde_json::json!({
                            "error": e.to_string()
                        })
                    }
                }
            } else {
                warn!("Unknown function called: {}", function_name);
                serde_json::json!({
                    "error": format!("Unknown function: {}", function_name)
                })
            };

            tool_messages.push(ChatMessage {
                role: MessageRole::Tool,
                content: serde_json::to_string(&result)?,
                name: Some(function_name.clone()),
                tool_calls: None,
                tool_call_id: Some(tool_call.id),
            });
        }

        Ok(tool_messages)
    }

    /// Complete conversation with automatic function calling
    #[instrument(skip(self, messages))]
    // TODO: document this
    // TODO: document this
    // TODO: document this
    // TODO: document this
    pub async fn complete_conversation(&self, messages: Vec<ChatMessage>) -> Result<String> {
        let mut conversation = messages;
        let max_iterations = 5;

        for iteration in 0..max_iterations {
            debug!("Conversation iteration {}", iteration + 1);

            let response = self.chat_completion(conversation.clone(), true).await?;

            if let Some(choice) = response.choices.first() {
                let assistant_message = choice.message.clone();
                conversation.push(assistant_message.clone());

                if let Some(tool_calls) = &assistant_message.tool_calls {
                    // Handle function calls
                    let tool_messages = self.handle_tool_calls(tool_calls.clone()).await?;
                    conversation.extend(tool_messages);

                    // Continue the conversation
                    continue;
                }

                // No more function calls, return the final response
                return Ok(assistant_message.content);
            }
        }

        Err(OpenCratesError::internal("Max conversation iterations reached".to_string()).into())
    }

    /// Create streaming chat completion
    #[instrument(skip(self, messages))]
    // TODO: document this
    // TODO: document this
    // TODO: document this
    // TODO: document this
    pub async fn chat_completion_stream(
        &self,
        messages: Vec<ChatMessage>,
        use_tools: bool,
    ) -> Result<impl futures::Stream<Item = Result<ChatCompletionChunk>>> {
        let mut request = ChatCompletionRequest {
            model: self.config.model.clone(),
            messages,
            max_tokens: self.config.max_tokens,
            temperature: self.config.temperature,
            tools: None,
            tool_choice: None,
            stream: Some(true),
        };

        if use_tools {
            let registry = self.function_registry.read().await;
            request.tools = Some(registry.list_functions().to_vec());
            request.tool_choice = Some("auto".to_string());
        }

        let response = self
            .http_client
            .post(format!("{}/chat/completions", self.config.base_url))
            .header("Authorization", format!("Bearer {}", self.config.api_key))
            .header("Content-Type", "application/json")
            .json(&request)
            .send()
            .await
            .context("Failed to send streaming chat completion request")?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            return Err(
                OpenCratesError::internal(format!("OpenAI API error: {error_text}")).into(),
            );
        }

        // For now, let's use a simpler non-streaming approach
        // In production, use eventsource-stream or similar for proper SSE support
        let response_text = response.text().await?;

        // Parse the SSE response
        let mut chunks = Vec::new();
        for line in response_text.lines() {
            if let Some(data) = line.strip_prefix("data: ") {
                if data == "[DONE]" {
                    break;
                }

                match serde_json::from_str::<ChatCompletionChunk>(data) {
                    Ok(parsed_chunk) => {
                        chunks.push(Ok(parsed_chunk));
                    }
                    Err(e) => {
                        chunks.push(Err(OpenCratesError::internal(format!(
                            "Failed to parse chunk: {e}"
                        ))
                        .into()));
                    }
                }
            }
        }

        Ok(futures::stream::iter(chunks))
    }
}

/// AI-powered crate assistant
// TODO: document this
// TODO: document this
// TODO: document this
pub struct CrateAssistant {
    openai_client: OpenAIClient,
    cache: Arc<CacheManager>,
    system_prompt: String,
}

/// Agent manager for coordinating multiple AI agents
#[derive(Clone)]
pub struct AgentManager {
    openai_client: Arc<OpenAIClient>,
    assistants: HashMap<String, Arc<CrateAssistant>>,
}

impl AgentManager {
    pub async fn new(_openai_provider: OpenAIProvider) -> Result<Self> {
        let config = OpenAIClientConfig::default();
        let metrics = Arc::new(OpenCratesMetrics::new().await.unwrap());
        let cache = Arc::new(CacheManager::new());
        let openai_client = Arc::new(OpenAIClient::new(config, metrics, cache));

        Ok(Self {
            openai_client,
            assistants: HashMap::new(),
        })
    }

    pub async fn get_assistant(&self, name: &str) -> Option<Arc<CrateAssistant>> {
        self.assistants.get(name).cloned()
    }

    pub async fn create_assistant(&mut self, name: String) -> Result<Arc<CrateAssistant>> {
        let assistant = Arc::new(CrateAssistant::new(self.openai_client.clone()).await?);
        self.assistants.insert(name.clone(), assistant.clone());
        Ok(assistant)
    }

    /// Lists the available agents.
    pub async fn list_agents(&self) -> Vec<String> {
        self.assistants.keys().cloned().collect()
    }

    /// Executes a task on a specific agent.
    pub async fn execute_agent(&self, agent_name: &str, task_description: &str) -> Result<String> {
        if let Some(assistant) = self.get_assistant(agent_name).await {
            assistant.assist(task_description.to_string()).await
        } else {
            Err(OpenCratesError::not_found("Agent", agent_name).into())
        }
    }
}

impl CrateAssistant {
    // TODO: document this
    // TODO: document this
    // TODO: document this
    // TODO: document this
    pub async fn new(client: Arc<OpenAIClient>) -> Result<Self> {
        let system_prompt = r"
You are an expert Rust developer and crate curator assistant for OpenCrates, a comprehensive Rust crate registry.

Your role is to help developers:
1. Find the best crates for their specific needs
2. Compare different crates and their trade-offs
3. Provide implementation guidance and best practices
4. Suggest compatible crates that work well together
5. Help with dependency management and version selection

You have access to functions that can search the crate registry and provide personalized recommendations.
Always provide accurate, helpful, and up-to-date information about Rust crates and ecosystem.

When recommending crates, consider:
- Maintenance status and community support
- Performance characteristics
- API ergonomics and ease of use
- Documentation quality
- License compatibility
- Security track record
".trim().to_string();

        let cache = Arc::new(CacheManager::new());

        Ok(Self {
            openai_client: Arc::try_unwrap(client).unwrap_or_else(|arc| (*arc).clone()),
            cache,
            system_prompt,
        })
    }

    // TODO: document this

    // TODO: document this

    // TODO: document this

    // TODO: document this

    #[must_use]
    pub fn cache(&self) -> &Arc<CacheManager> {
        &self.cache
    }

    /// Get assistance for a user query
    #[instrument(skip(self))]
    // TODO: document this
    // TODO: document this
    // TODO: document this
    // TODO: document this
    pub async fn assist(&self, user_query: String) -> Result<String> {
        let messages = vec![
            ChatMessage::system(self.system_prompt.clone()),
            ChatMessage::user(user_query),
        ];

        self.openai_client.complete_conversation(messages).await
    }

    /// Get crate recommendations
    #[instrument(skip(self))]
    // TODO: document this
    // TODO: document this
    // TODO: document this
    // TODO: document this
    pub async fn recommend_crates(
        &self,
        project_type: String,
        requirements: String,
    ) -> Result<String> {
        let user_query = format!(
            "I'm working on a {project_type} project with the following requirements: {requirements}. \
             Can you recommend the best crates and explain why they're good choices?"
        );

        self.assist(user_query).await
    }
}