poe_api_process 0.4.6

Poe API for 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
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
use crate::error::PoeError;
use crate::types::*;
use futures_util::Stream;
use futures_util::StreamExt;
use futures_util::future::join_all;
use reqwest::Client;
use reqwest::header::{ACCEPT, CACHE_CONTROL, CONTENT_TYPE, COOKIE, HeaderMap, HeaderValue};
use serde_json::Value;
use std::path::Path;
use std::pin::Pin;
use tokio_util::io::ReaderStream;
#[cfg(feature = "trace")]
use tracing::{debug, warn};

const POE_GQL_URL: &str = "https://poe.com/api/gql_POST";
const POE_GQL_MODEL_HASH: &str = "b24b2f2f6da147b3345eec1a433ed17b6e1332df97dea47622868f41078a40cc";
const POE_GQL_MODEL_REVISION: &str = "e2acc7025b43e08e88164ba8105273f37fbeaa26";

#[derive(Clone)]
pub struct PoeClient {
    client: Client,
    bot_name: String,
    access_key: String,
    poe_base_url: String,
    poe_file_upload_url: String,
}

impl PoeClient {
    pub fn new(
        bot_name: &str,
        access_key: &str,
        poe_base_url: &str,
        poe_file_upload_url: &str,
    ) -> Self {
        #[cfg(feature = "trace")]
        debug!("建立新的 PoeClient 實例,bot_name: {}", bot_name);

        // 處理 URL 末尾的斜線
        let normalized_base_url = if poe_base_url.ends_with('/') {
            poe_base_url.trim_end_matches('/').to_string()
        } else {
            poe_base_url.to_string()
        };

        let normalized_file_upload_url = if poe_file_upload_url.ends_with('/') {
            poe_file_upload_url.trim_end_matches('/').to_string()
        } else {
            poe_file_upload_url.to_string()
        };

        Self {
            client: Client::new(),
            bot_name: bot_name.to_string(),
            access_key: access_key.to_string(),
            poe_base_url: normalized_base_url,
            poe_file_upload_url: normalized_file_upload_url,
        }
    }

    pub async fn stream_request(
        &self,
        #[cfg(feature = "xml")] mut request: ChatRequest,
        #[cfg(not(feature = "xml"))] request: ChatRequest,
    ) -> Result<Pin<Box<dyn Stream<Item = Result<ChatResponse, PoeError>> + Send>>, PoeError> {
        #[cfg(feature = "trace")]
        debug!("開始串流請求,bot_name: {}", self.bot_name);

        // 當啟用 xml feature 時,自動將工具轉換為 XML 格式
        #[cfg(feature = "xml")]
        {
            if request.tools.is_some() {
                #[cfg(feature = "trace")]
                debug!("檢測到 xml feature 啟用,自動將工具轉換為 XML 格式");

                // 使用 xml 模塊中的方法
                request.append_tools_as_xml();
                request.tools = None; // 清除原始工具定義
            }

            // 如果有工具結果,也需要轉換為 XML 格式並清除原始數據
            if request.tool_results.is_some() {
                #[cfg(feature = "trace")]
                debug!("檢測到 xml feature 啟用,自動將工具結果轉換為 XML 格式");

                // 將工具結果轉換為 XML 格式並附加到訊息末尾
                request.append_tool_results_as_xml();

                // 清除原始的工具調用和結果,因為已經轉換為 XML 格式
                request.tool_calls = None;
                request.tool_results = None;
            }
        }

        let url = format!("{}/bot/{}", self.poe_base_url, self.bot_name);
        #[cfg(feature = "trace")]
        debug!("發送請求至 URL: {}", url);

        #[cfg(feature = "trace")]
        debug!(
            "🔍 發送的完整請求體: {}",
            serde_json::to_string_pretty(&request).unwrap_or_else(|_| "無法序列化".to_string())
        );

        let response = self
            .client
            .post(&url)
            .header(ACCEPT, "text/event-stream")
            .header(CACHE_CONTROL, "no-store")
            .header("Authorization", format!("Bearer {}", self.access_key))
            .header(CONTENT_TYPE, "application/json")
            .json(&request)
            .send()
            .await?;

        if !response.status().is_success() {
            let status = response.status();
            #[cfg(feature = "trace")]
            warn!("API 請求失敗,狀態碼: {}", status);
            return Err(PoeError::BotError(format!("API 回應狀態碼: {}", status)));
        }

        #[cfg(feature = "trace")]
        debug!("成功接收到串流回應");

        let mut static_buffer = String::new();
        let mut current_event: Option<ChatEventType> = None;
        let mut is_collecting_data = false;
        // 用於累積 tool_calls 的狀態
        let mut accumulated_tool_calls: Vec<PartialToolCall> = Vec::new();
        let mut tool_calls_complete = false;

        // XML 工具調用緩衝和檢測狀態
        #[cfg(feature = "xml")]
        let mut xml_text_buffer = String::new();
        #[cfg(feature = "xml")]
        let mut xml_detection_active = false;
        #[cfg(feature = "xml")]
        let available_tools = request.tools.clone().unwrap_or_default();

        let stream = response
            .bytes_stream()
            .map(move |result| {
                result.map_err(PoeError::from).map(|chunk| {
                    let chunk_str = String::from_utf8_lossy(&chunk);
                    #[cfg(feature = "trace")]
                    debug!("處理串流塊,大小: {} 字節", chunk.len());

                    let mut events = Vec::new();
                    // 將新的塊添加到靜態緩衝區
                    static_buffer.push_str(&chunk_str);

                    // 尋找完整的消息
                    while let Some(newline_pos) = static_buffer.find('\n') {
                        let line = static_buffer[..newline_pos].trim().to_string();
                        static_buffer = static_buffer[newline_pos + 1..].to_string();

                        if line.is_empty() {
                            // 重置當前事件狀態,準備處理下一個事件
                            current_event = None;
                            is_collecting_data = false;
                            continue;
                        }

                        if line == ": ping" {
                            #[cfg(feature = "trace")]
                            debug!("收到 ping 訊號");
                            continue;
                        }

                        if line.starts_with("event: ") {
                            let event_name = line.trim_start_matches("event: ").trim();
                            #[cfg(feature = "trace")]
                            debug!("解析事件類型: {}", event_name);

                            let event_type = match event_name {
                                "text" => ChatEventType::Text,
                                "replace_response" => ChatEventType::ReplaceResponse,
                                "json" => ChatEventType::Json,
                                "file" => ChatEventType::File,
                                "done" => ChatEventType::Done,
                                "error" => ChatEventType::Error,
                                _ => {
                                    #[cfg(feature = "trace")]
                                    warn!("收到未知事件類型: {}", event_name);
                                    continue;
                                }
                            };

                            current_event = Some(event_type);
                            is_collecting_data = false;
                            continue;
                        }

                        if line.starts_with("data: ") {
                            let data = line.trim_start_matches("data: ").trim();
                            #[cfg(feature = "trace")]
                            debug!(
                                "收到事件數據: {}",
                                if data.len() > 100 { &data[..100] } else { data }
                            );

                            if let Some(ref event_type) = current_event {
                                match event_type {
                                    ChatEventType::Text | ChatEventType::ReplaceResponse => {
                                        if let Ok(json) = serde_json::from_str::<Value>(data) {
                                            if let Some(text) = json.get("text").and_then(Value::as_str) {
                                                #[cfg(feature = "trace")]
                                                debug!("解析到文本數據,長度: {}", text.len());

                                                // XML 工具調用檢測和緩衝邏輯
                                                #[cfg(feature = "xml")]
                                                {
                                                    // 基於實際工具定義的智能檢測
                                                    let should_start_xml_detection = !xml_detection_active && (
                                                        text.contains("<tool_call>") ||
                                                        text.contains("<invoke") ||
                                                        // 檢查是否包含任何已定義的工具名稱標籤
                                                        available_tools.iter().any(|tool|
                                                            text.contains(&format!("<{}>", tool.function.name))
                                                        )
                                                    );
                                                    if should_start_xml_detection {
                                                        xml_detection_active = true;
                                                        xml_text_buffer.clear();
                                                        #[cfg(feature = "trace")]
                                                        debug!("檢測到已定義工具的 XML 調用,開始 XML 緩衝 | 清空緩衝區重新開始");
                                                    }
                                                    if xml_detection_active {
                                                        xml_text_buffer.push_str(text);
                                                        #[cfg(feature = "trace")]
                                                        debug!("XML 模式:文本已添加到緩衝區 | 長度: {}", xml_text_buffer.len());
                                                        // 檢查是否有完整的工具調用
                                                        let message = ChatMessage {
                                                            role: "assistant".to_string(),
                                                            content: xml_text_buffer.clone(),
                                                            attachments: None,
                                                            content_type: "text/plain".to_string(),
                                                        };
                                                        // 使用工具定義來檢測和解析
                                                        if message.contains_xml_tool_calls_with_tools(&available_tools) {
                                                            let tool_calls = message.extract_xml_tool_calls_with_tools(&available_tools);
                                                            if !tool_calls.is_empty() {
                                                                #[cfg(feature = "trace")]
                                                                debug!("檢測到完整的 XML 工具調用,轉換為標準格式,數量: {}", tool_calls.len());
                                                                // 發送工具調用事件
                                                                events.push(Ok(ChatResponse {
                                                                    event: ChatEventType::Json,
                                                                    data: Some(ChatResponseData::ToolCalls(tool_calls)),
                                                                }));
                                                                // 移除 XML 部分並發送剩餘文本
                                                                let clean_text = Self::remove_xml_tool_calls(&xml_text_buffer);
                                                                if !clean_text.trim().is_empty() {
                                                                    events.push(Ok(ChatResponse {
                                                                        event: event_type.clone(),
                                                                        data: Some(ChatResponseData::Text {
                                                                            text: clean_text,
                                                                        }),
                                                                    }));
                                                                }
                                                                // 重置 XML 緩衝狀態
                                                                xml_text_buffer.clear();
                                                                xml_detection_active = false;
                                                            } else {
                                                                // 沒有完整的工具調用,繼續緩衝
                                                                #[cfg(feature = "trace")]
                                                                debug!("XML 工具調用尚未完整,繼續緩衝");
                                                            }
                                                        } else {
                                                            // 檢查是否應該釋放緩衝區
                                                            let should_release = xml_text_buffer.contains('\n') &&
                                                                 xml_text_buffer.len() > 200 &&
                                                                 !available_tools.iter().any(|tool|
                                                                     xml_text_buffer.contains(&format!("<{}>", tool.function.name)) ||
                                                                     xml_text_buffer.contains(&format!("</{}>", tool.function.name))
                                                                 ) &&
                                                                 !xml_text_buffer.contains("<tool_call>") &&
                                                                 !xml_text_buffer.contains("<invoke");
                                                            if should_release {
                                                                #[cfg(feature = "trace")]
                                                                debug!("XML 緩衝區過大或不包含工具調用,發送為普通文本");
                                                                // 發送緩衝的文本
                                                                events.push(Ok(ChatResponse {
                                                                    event: event_type.clone(),
                                                                    data: Some(ChatResponseData::Text {
                                                                        text: xml_text_buffer.clone(),
                                                                    }),
                                                                }));
                                                                // 重置緩衝狀態
                                                                xml_text_buffer.clear();
                                                                xml_detection_active = false;
                                                            } else {
                                                                // 繼續緩衝
                                                                #[cfg(feature = "trace")]
                                                                debug!("繼續緩衝 XML 文本,當前長度: {}", xml_text_buffer.len());
                                                            }
                                                        }
                                                    } else {
                                                        // 沒有檢測到 XML,直接發送文本
                                                        events.push(Ok(ChatResponse {
                                                            event: event_type.clone(),
                                                            data: Some(ChatResponseData::Text {
                                                                text: text.to_string(),
                                                            }),
                                                        }));
                                                    }
                                                }

                                                #[cfg(not(feature = "xml"))]
                                                {
                                                    events.push(Ok(ChatResponse {
                                                        event: event_type.clone(),
                                                        data: Some(ChatResponseData::Text {
                                                            text: text.to_string(),
                                                        }),
                                                    }));
                                                }
                                            }
                                        } else {
                                            #[cfg(feature = "trace")]
                                            debug!("JSON 解析失敗,可能是不完整的數據,等待更多數據");
                                            is_collecting_data = true;
                                        }
                                    }
                                    ChatEventType::File => {
                                        if let Ok(file_data) = serde_json::from_str::<FileData>(data) {
                                            #[cfg(feature = "trace")]
                                            debug!("解析到文件數據: {}", file_data.name);
                                            events.push(Ok(ChatResponse {
                                                event: ChatEventType::File,
                                                data: Some(ChatResponseData::File(file_data)),
                                            }));
                                        } else {
                                            #[cfg(feature = "trace")]
                                            debug!("文件數據 JSON 解析失敗,可能是不完整的數據,等待更多數據");
                                            is_collecting_data = true;
                                        }
                                    }
                                    ChatEventType::Json => {
                                        if let Ok(json) = serde_json::from_str::<Value>(data) {
                                            #[cfg(feature = "trace")]
                                            debug!("解析到 JSON 事件數據");
                                            // 檢查是否有 finish_reason: "tool_calls",表示工具調用完成
                                            let finish_reason = json
                                                .get("choices")
                                                .and_then(|choices| choices.get(0))
                                                .and_then(|choice| choice.get("finish_reason"))
                                                .and_then(Value::as_str);

                                            if finish_reason == Some("tool_calls") {
                                                #[cfg(feature = "trace")]
                                                debug!("檢測到工具調用完成標誌");
                                                tool_calls_complete = true;
                                            }

                                            // 檢查是否包含 tool_calls delta
                                            let tool_calls_delta = json
                                                .get("choices")
                                                .and_then(|choices| choices.get(0))
                                                .and_then(|choice| choice.get("delta"))
                                                .and_then(|delta| delta.get("tool_calls"));

                                            if let Some(tool_calls_array) = tool_calls_delta {
                                                #[cfg(feature = "trace")]
                                                debug!("檢測到工具調用 delta");
                                                // 處理每個工具調用的 delta
                                                if let Some(tool_calls) = tool_calls_array.as_array() {
                                                    for tool_call_delta in tool_calls {
                                                        let index = tool_call_delta
                                                            .get("index")
                                                            .and_then(Value::as_u64)
                                                            .unwrap_or(0)
                                                            as usize;

                                                        // 確保 accumulated_tool_calls 有足夠的元素
                                                        while accumulated_tool_calls.len() <= index {
                                                            accumulated_tool_calls.push(PartialToolCall::default());
                                                        }

                                                        // 更新 id 和 type
                                                        if let Some(id) = tool_call_delta
                                                            .get("id")
                                                            .and_then(Value::as_str)
                                                        {
                                                            accumulated_tool_calls[index].id = id.to_string();
                                                        }

                                                        if let Some(type_str) = tool_call_delta
                                                            .get("type")
                                                            .and_then(Value::as_str)
                                                        {
                                                            accumulated_tool_calls[index].r#type = type_str.to_string();
                                                        }

                                                        // 更新 function 相關欄位
                                                        if let Some(function) = tool_call_delta.get("function") {
                                                            if let Some(name) = function
                                                                .get("name")
                                                                .and_then(Value::as_str)
                                                            {
                                                                accumulated_tool_calls[index].function_name = name.to_string();
                                                            }

                                                            if let Some(args) = function
                                                                .get("arguments")
                                                                .and_then(Value::as_str)
                                                            {
                                                                accumulated_tool_calls[index].function_arguments.push_str(args);
                                                            }
                                                        }
                                                    }
                                                }
                                            } else if !tool_calls_complete {
                                                // 如果沒有 tool_calls delta 且工具調用尚未完成,
                                                // 則按一般 JSON 處理
                                                events.push(Ok(ChatResponse {
                                                    event: ChatEventType::Json,
                                                    data: Some(ChatResponseData::Text {
                                                        text: data.to_string(),
                                                    }),
                                                }));
                                            }
                                        } else {
                                            #[cfg(feature = "trace")]
                                            debug!("JSON 事件解析失敗,可能是不完整的數據");
                                            is_collecting_data = true;
                                        }
                                    }
                                    ChatEventType::Done => {
                                        #[cfg(feature = "trace")]
                                        debug!("收到完成事件");
                                        // 處理任何剩餘的 XML 緩衝內容
                                        #[cfg(feature = "xml")]
                                        {
                                            if xml_detection_active && !xml_text_buffer.trim().is_empty() {
                                                #[cfg(feature = "trace")]
                                                debug!("處理剩餘的 XML 緩衝內容,長度: {}", xml_text_buffer.len());
                                                let message = ChatMessage {
                                                    role: "assistant".to_string(),
                                                    content: xml_text_buffer.clone(),
                                                    attachments: None,
                                                    content_type: "text/plain".to_string(),
                                                };
                                                // 使用工具定義來檢測和解析
                                                if message.contains_xml_tool_calls_with_tools(&available_tools) {
                                                    let tool_calls = message.extract_xml_tool_calls_with_tools(&available_tools);
                                                    if !tool_calls.is_empty() {
                                                        #[cfg(feature = "trace")]
                                                        debug!("在完成事件中檢測到 XML 工具調用,數量: {}", tool_calls.len());
                                                        // 發送工具調用事件
                                                        events.push(Ok(ChatResponse {
                                                            event: ChatEventType::Json,
                                                            data: Some(ChatResponseData::ToolCalls(tool_calls)),
                                                        }));
                                                        // 發送清理後的文本(如果有)
                                                        let clean_text = Self::remove_xml_tool_calls(&xml_text_buffer);
                                                        if !clean_text.trim().is_empty() {
                                                            events.push(Ok(ChatResponse {
                                                                event: ChatEventType::Text,
                                                                data: Some(ChatResponseData::Text {
                                                                    text: clean_text,
                                                                }),
                                                            }));
                                                        }
                                                    } else {
                                                        // 發送為普通文本
                                                        events.push(Ok(ChatResponse {
                                                            event: ChatEventType::Text,
                                                            data: Some(ChatResponseData::Text {
                                                                text: xml_text_buffer.clone(),
                                                            }),
                                                        }));
                                                    }
                                                } else {
                                                    // 發送為普通文本
                                                    events.push(Ok(ChatResponse {
                                                        event: ChatEventType::Text,
                                                        data: Some(ChatResponseData::Text {
                                                            text: xml_text_buffer.clone(),
                                                        }),
                                                    }));
                                                }
                                                // 清理緩衝狀態
                                                xml_text_buffer.clear();
                                                xml_detection_active = false;
                                            }
                                        }
                                        events.push(Ok(ChatResponse {
                                            event: ChatEventType::Done,
                                            data: Some(ChatResponseData::Empty),
                                        }));
                                        current_event = None;
                                    }
                                    ChatEventType::Error => {
                                        if let Ok(json) = serde_json::from_str::<Value>(data) {
                                            let text = json
                                                .get("text")
                                                .and_then(Value::as_str)
                                                .unwrap_or("未知錯誤");
                                            let allow_retry = json
                                                .get("allow_retry")
                                                .and_then(Value::as_bool)
                                                .unwrap_or(false);

                                            #[cfg(feature = "trace")]
                                            warn!("收到錯誤事件: {}, 可重試: {}", text, allow_retry);

                                            events.push(Ok(ChatResponse {
                                                event: ChatEventType::Error,
                                                data: Some(ChatResponseData::Error {
                                                    text: text.to_string(),
                                                    allow_retry,
                                                }),
                                            }));
                                        } else {
                                            #[cfg(feature = "trace")]
                                            warn!("無法解析錯誤事件數據: {}", data);
                                        }
                                        current_event = None;
                                    }
                                }
                            } else {
                                #[cfg(feature = "trace")]
                                debug!("收到數據但沒有當前事件類型");
                            }
                        } else if is_collecting_data {
                            // 嘗試解析累積的 JSON
                            #[cfg(feature = "trace")]
                            debug!("嘗試解析未完整的 JSON 數據: {}", line);

                            if let Some(ref event_type) = current_event {
                                match event_type {
                                    ChatEventType::Text | ChatEventType::ReplaceResponse => {
                                        if let Ok(json) = serde_json::from_str::<Value>(&line) {
                                            if let Some(text) = json.get("text").and_then(Value::as_str) {
                                                #[cfg(feature = "trace")]
                                                debug!("成功解析到累積的 JSON 文本,長度: {}", text.len());

                                                events.push(Ok(ChatResponse {
                                                    event: event_type.clone(),
                                                    data: Some(ChatResponseData::Text {
                                                        text: text.to_string(),
                                                    }),
                                                }));
                                                is_collecting_data = false;
                                                current_event = None;
                                            }
                                        }
                                    }
                                    ChatEventType::File => {
                                        if let Ok(file_data) = serde_json::from_str::<FileData>(&line) {
                                            #[cfg(feature = "trace")]
                                            debug!("成功解析到累積的文件數據: {}", file_data.name);

                                            events.push(Ok(ChatResponse {
                                                event: ChatEventType::File,
                                                data: Some(ChatResponseData::File(file_data)),
                                            }));
                                            is_collecting_data = false;
                                            current_event = None;
                                        }
                                    }
                                    ChatEventType::Json => {
                                        if let Ok(json) = serde_json::from_str::<Value>(&line) {
                                            #[cfg(feature = "trace")]
                                            debug!("成功解析到累積的 JSON 事件數據");

                                            // 檢查是否有 finish_reason: "tool_calls"
                                            let finish_reason = json
                                                .get("choices")
                                                .and_then(|choices| choices.get(0))
                                                .and_then(|choice| choice.get("finish_reason"))
                                                .and_then(Value::as_str);

                                            if finish_reason == Some("tool_calls") {
                                                #[cfg(feature = "trace")]
                                                debug!("檢測到工具調用完成標誌");
                                                tool_calls_complete = true;
                                            }

                                            // 檢查是否包含 tool_calls delta
                                            let tool_calls_delta = json
                                                .get("choices")
                                                .and_then(|choices| choices.get(0))
                                                .and_then(|choice| choice.get("delta"))
                                                .and_then(|delta| delta.get("tool_calls"));

                                            if let Some(tool_calls_array) = tool_calls_delta {
                                                #[cfg(feature = "trace")]
                                                debug!("檢測到工具調用 delta");

                                                // 處理每個工具調用的 delta
                                                if let Some(tool_calls) = tool_calls_array.as_array() {
                                                    for tool_call_delta in tool_calls {
                                                        let index = tool_call_delta
                                                            .get("index")
                                                            .and_then(Value::as_u64)
                                                            .unwrap_or(0)
                                                            as usize;

                                                        // 確保 accumulated_tool_calls 有足夠的元素
                                                        while accumulated_tool_calls.len() <= index {
                                                            accumulated_tool_calls.push(PartialToolCall::default());
                                                        }

                                                        // 更新 id 和 type
                                                        if let Some(id) = tool_call_delta
                                                            .get("id")
                                                            .and_then(Value::as_str)
                                                        {
                                                            accumulated_tool_calls[index].id = id.to_string();
                                                        }

                                                        if let Some(type_str) = tool_call_delta
                                                            .get("type")
                                                            .and_then(Value::as_str)
                                                        {
                                                            accumulated_tool_calls[index].r#type = type_str.to_string();
                                                        }

                                                        // 更新 function 相關欄位
                                                        if let Some(function) = tool_call_delta.get("function") {
                                                            if let Some(name) = function
                                                                .get("name")
                                                                .and_then(Value::as_str)
                                                            {
                                                                accumulated_tool_calls[index].function_name = name.to_string();
                                                            }

                                                            if let Some(args) = function
                                                                .get("arguments")
                                                                .and_then(Value::as_str)
                                                            {
                                                                accumulated_tool_calls[index].function_arguments.push_str(args);
                                                            }
                                                        }
                                                    }
                                                }

                                                // 如果工具調用完成,則創建並發送 ChatResponse
                                                if tool_calls_complete && !accumulated_tool_calls.is_empty() {
                                                    let complete_tool_calls = accumulated_tool_calls
                                                        .iter()
                                                        .filter(|tc| {
                                                            !tc.id.is_empty() && !tc.function_name.is_empty()
                                                        })
                                                        .map(|tc| ChatToolCall {
                                                            id: tc.id.clone(),
                                                            r#type: tc.r#type.clone(),
                                                            function: FunctionCall {
                                                                name: tc.function_name.clone(),
                                                                arguments: tc.function_arguments.clone(),
                                                            },
                                                        })
                                                        .collect::<Vec<ChatToolCall>>();

                                                    if !complete_tool_calls.is_empty() {
                                                        #[cfg(feature = "trace")]
                                                        debug!("發送完整的工具調用,數量: {}", complete_tool_calls.len());

                                                        events.push(Ok(ChatResponse {
                                                            event: ChatEventType::Json,
                                                            data: Some(ChatResponseData::ToolCalls(complete_tool_calls)),
                                                        }));

                                                        // 重置累積狀態
                                                        accumulated_tool_calls.clear();
                                                        tool_calls_complete = false;
                                                    }
                                                }
                                            } else {
                                                // 如果沒有 tool_calls delta,則按一般 JSON 處理
                                                events.push(Ok(ChatResponse {
                                                    event: ChatEventType::Json,
                                                    data: Some(ChatResponseData::Text {
                                                        text: line.to_string(),
                                                    }),
                                                }));
                                            }

                                            is_collecting_data = false;
                                            current_event = None;
                                        }
                                    }
                                    ChatEventType::Done | ChatEventType::Error => {
                                        // 這些事件類型不應該有累積的數據
                                        is_collecting_data = false;
                                    }
                                }
                            }
                        }
                    }

                    // 在處理完 chunk 中的所有行之後,檢查是否需要發送最終的 tool_calls 事件
                    if tool_calls_complete && !accumulated_tool_calls.is_empty() {
                        let complete_tool_calls = accumulated_tool_calls
                            .iter()
                            .filter(|tc| !tc.id.is_empty() && !tc.function_name.is_empty())
                            .map(|tc| ChatToolCall {
                                id: tc.id.clone(),
                                r#type: tc.r#type.clone(),
                                function: FunctionCall {
                                    name: tc.function_name.clone(),
                                    arguments: tc.function_arguments.clone(),
                                },
                            })
                            .collect::<Vec<ChatToolCall>>();

                        if !complete_tool_calls.is_empty() {
                            #[cfg(feature = "trace")]
                            debug!("發送最終的完整工具調用,數量: {}", complete_tool_calls.len());

                            events.push(Ok(ChatResponse {
                                event: ChatEventType::Json,
                                data: Some(ChatResponseData::ToolCalls(complete_tool_calls)),
                            }));

                            // 重置狀態
                            accumulated_tool_calls.clear();
                            tool_calls_complete = false;
                        }
                    }

                    events
                })
            })
            .flat_map(|result| {
                futures_util::stream::iter(match result {
                    Ok(events) => events,
                    Err(e) => {
                        #[cfg(feature = "trace")]
                        warn!("串流處理錯誤: {}", e);
                        vec![Err(e)]
                    }
                })
            });

        Ok(Box::pin(stream))
    }

    pub async fn send_tool_results(
        &self,
        original_request: ChatRequest,
        tool_calls: Vec<ChatToolCall>,
        tool_results: Vec<ChatToolResult>,
    ) -> Result<Pin<Box<dyn Stream<Item = Result<ChatResponse, PoeError>> + Send>>, PoeError> {
        #[cfg(feature = "trace")]
        debug!("發送工具調用結果,bot_name: {}", self.bot_name);

        // 創建包含工具結果的新請求
        let mut request = original_request;

        // 當啟用 xml feature 時,將工具結果以 XML 格式附加到訊息末尾
        #[cfg(feature = "xml")]
        {
            #[cfg(feature = "trace")]
            debug!("檢測到 xml feature 啟用,將工具結果轉換為 XML 格式並附加到訊息末尾");

            // 先設置工具調用和結果,以便 XML 轉換方法可以訪問
            request.tool_calls = Some(tool_calls);
            request.tool_results = Some(tool_results);

            // 將工具結果轉換為 XML 格式並附加到訊息末尾
            request.append_tool_results_as_xml();

            // 清除原始的工具調用和結果,因為已經轉換為 XML 格式
            request.tool_calls = None;
            request.tool_results = None;

            #[cfg(feature = "trace")]
            debug!(
                "🔧 工具結果 XML 轉換完成,檢查訊息內容: {}",
                request
                    .query
                    .iter()
                    .map(|msg| format!("角色: {}, 內容長度: {}", msg.role, msg.content.len()))
                    .collect::<Vec<_>>()
                    .join("; ")
            );
        }

        // 當未啟用 xml feature 時,使用原有的 JSON API 方式
        #[cfg(not(feature = "xml"))]
        {
            request.tool_calls = Some(tool_calls);
            request.tool_results = Some(tool_results);
        }

        #[cfg(feature = "trace")]
        debug!(
            "發送工具結果請求結構: {}",
            serde_json::to_string_pretty(&request).unwrap_or_else(|_| "無法序列化請求".to_string())
        );

        // 發送請求並處理響應(stream_request 會自動處理 XML feature)
        self.stream_request(request).await
    }

    /// 上傳本地檔案
    pub async fn upload_local_file(
        &self,
        file_path: &str,
        mime_type: Option<&str>,
    ) -> Result<FileUploadResponse, PoeError> {
        #[cfg(feature = "trace")]
        debug!(
            "開始上傳本地檔案: {} | MIME 類型: {:?}",
            file_path, mime_type
        );
        // 檢查檔案是否存在
        let path = Path::new(file_path);
        if !path.exists() {
            #[cfg(feature = "trace")]
            warn!("檔案不存在: {}", file_path);
            return Err(PoeError::FileNotFound(file_path.to_string()));
        }

        // 簡化 MIME 類型處理:如果有提供 mime_type 就使用,否則使用預設值
        let content_type = mime_type.unwrap_or("application/octet-stream").to_string();

        #[cfg(feature = "trace")]
        debug!("使用 MIME 類型: {}", content_type);

        // 建立 multipart 表單
        let file = tokio::fs::File::open(path).await.map_err(|e| {
            #[cfg(feature = "trace")]
            warn!("無法開啟檔案: {}", e);
            PoeError::FileReadError(e)
        })?;

        let file_part =
            reqwest::multipart::Part::stream(reqwest::Body::wrap_stream(ReaderStream::new(file)))
                .file_name(
                    path.file_name()
                        .and_then(|name| name.to_str())
                        .unwrap_or("file")
                        .to_string(),
                )
                .mime_str(&content_type)
                .map_err(|e| {
                    #[cfg(feature = "trace")]
                    warn!("設置 MIME 類型失敗: {}", e);
                    PoeError::FileUploadFailed(format!("設置 MIME 類型失敗: {}", e))
                })?;

        let form = reqwest::multipart::Form::new().part("file", file_part);

        // 發送請求
        self.send_upload_request(form).await
    }

    /// 上傳遠端檔案 (通過URL)
    pub async fn upload_remote_file(
        &self,
        download_url: &str,
    ) -> Result<FileUploadResponse, PoeError> {
        #[cfg(feature = "trace")]
        debug!("開始上傳遠端檔案: {}", download_url);

        // 檢查URL格式
        url::Url::parse(download_url)?;

        // 建立 multipart 表單
        let form = reqwest::multipart::Form::new().text("download_url", download_url.to_string());

        // 發送請求
        self.send_upload_request(form).await
    }

    /// 批量上傳檔案 (接受混合的本地和遠端檔案)
    pub async fn upload_files_batch(
        &self,
        files: Vec<FileUploadRequest>,
    ) -> Result<Vec<FileUploadResponse>, PoeError> {
        #[cfg(feature = "trace")]
        debug!("開始批量上傳檔案,數量: {}", files.len());

        if files.is_empty() {
            return Ok(Vec::new());
        }

        // 為每個檔案創建上傳任務
        let mut upload_tasks = Vec::with_capacity(files.len());

        for file_request in files {
            let task = match file_request {
                FileUploadRequest::LocalFile { file, mime_type } => {
                    let client = self.clone();
                    let file_path = file.clone();
                    tokio::spawn(async move {
                        client
                            .upload_local_file(&file_path, mime_type.as_deref())
                            .await
                    })
                }
                FileUploadRequest::RemoteFile { download_url } => {
                    let client = self.clone();
                    let url = download_url.clone();
                    tokio::spawn(async move { client.upload_remote_file(&url).await })
                }
            };
            upload_tasks.push(task);
        }

        // 等待所有上傳任務完成
        let results = join_all(upload_tasks).await;

        // 收集結果
        let mut upload_responses = Vec::with_capacity(results.len());

        for task_result in results.into_iter() {
            match task_result {
                Ok(upload_result) => match upload_result {
                    Ok(response) => {
                        #[cfg(feature = "trace")]
                        debug!("檔案上傳成功: {}", response.attachment_url);
                        upload_responses.push(response);
                    }
                    Err(e) => {
                        #[cfg(feature = "trace")]
                        warn!("檔案上傳失敗: {}", e);
                        return Err(e);
                    }
                },
                Err(e) => {
                    #[cfg(feature = "trace")]
                    warn!("檔案上傳任務失敗: {}", e);
                    return Err(PoeError::FileUploadFailed(format!("上傳任務失敗: {}", e)));
                }
            }
        }

        #[cfg(feature = "trace")]
        debug!("批量上傳全部成功,共 {} 個檔案", upload_responses.len());

        Ok(upload_responses)
    }

    /// 發送檔案上傳請求 (內部方法)
    async fn send_upload_request(
        &self,
        form: reqwest::multipart::Form,
    ) -> Result<FileUploadResponse, PoeError> {
        #[cfg(feature = "trace")]
        debug!("發送檔案上傳請求至 {}", self.poe_file_upload_url);

        let response = self
            .client
            .post(&self.poe_file_upload_url)
            // 檔案上傳端點需要純 API key,不添加 Bearer 前綴
            .header("Authorization", self.access_key.clone())
            .multipart(form)
            .send()
            .await
            .map_err(|e| {
                #[cfg(feature = "trace")]
                warn!("檔案上傳請求失敗: {}", e);
                PoeError::RequestFailed(e)
            })?;

        if !response.status().is_success() {
            let status = response.status();
            let text = response
                .text()
                .await
                .unwrap_or_else(|_| "無法讀取回應內容".to_string());

            #[cfg(feature = "trace")]
            warn!("檔案上傳API回應錯誤 - 狀態碼: {}, 內容: {}", status, text);

            return Err(PoeError::FileUploadFailed(format!(
                "上傳失敗 - 狀態碼: {}, 內容: {}",
                status, text
            )));
        }

        #[cfg(feature = "trace")]
        debug!("成功接收到檔案上傳回應");

        let response_text = response.text().await.map_err(|e| {
            #[cfg(feature = "trace")]
            warn!("讀取檔案上傳回應內容失敗: {}", e);
            PoeError::RequestFailed(e)
        })?;

        #[cfg(feature = "trace")]
        debug!("檔案上傳回應內容: {}", response_text);

        let upload_response: FileUploadResponse =
            serde_json::from_str(&response_text).map_err(|e| {
                #[cfg(feature = "trace")]
                warn!("解析檔案上傳回應失敗: {}", e);
                PoeError::JsonParseFailed(e)
            })?;

        #[cfg(feature = "trace")]
        debug!("檔案上傳成功,附件URL: {}", upload_response.attachment_url);

        Ok(upload_response)
    }

    /// 獲取 v1/models API 的模型列表 (需要 access_key)
    pub async fn get_v1_model_list(&self) -> Result<ModelResponse, PoeError> {
        #[cfg(feature = "trace")]
        debug!("開始獲取 v1/models 模型列表");

        let url = format!("{}/v1/models", self.poe_base_url);
        #[cfg(feature = "trace")]
        debug!("發送 v1/models 請求至 URL: {}", url);

        let response = self
            .client
            .get(&url)
            .header("Authorization", format!("Bearer {}", self.access_key))
            .header("Content-Type", "application/json")
            .send()
            .await
            .map_err(|e| {
                #[cfg(feature = "trace")]
                warn!("發送 v1/models 請求失敗: {}", e);
                PoeError::RequestFailed(e)
            })?;

        if !response.status().is_success() {
            let status = response.status();
            let text = response
                .text()
                .await
                .unwrap_or_else(|_| "無法讀取回應內容".to_string());

            #[cfg(feature = "trace")]
            warn!(
                "v1/models API 回應錯誤 - 狀態碼: {}, 內容: {}",
                status, text
            );

            return Err(PoeError::BotError(format!(
                "v1/models API 回應錯誤 - 狀態碼: {}, 內容: {}",
                status, text
            )));
        }

        #[cfg(feature = "trace")]
        debug!("成功接收到 v1/models 回應");

        let response_text = response.text().await.map_err(|e| {
            #[cfg(feature = "trace")]
            warn!("讀取 v1/models 回應內容失敗: {}", e);
            PoeError::RequestFailed(e)
        })?;

        #[cfg(feature = "trace")]
        debug!("v1/models 回應內容: {}", response_text);

        let json_data: Value = serde_json::from_str(&response_text).map_err(|e| {
            #[cfg(feature = "trace")]
            warn!("解析 v1/models 回應失敗: {}", e);
            PoeError::JsonParseFailed(e)
        })?;

        let mut model_list = Vec::new();

        if let Some(data_array) = json_data.get("data").and_then(Value::as_array) {
            #[cfg(feature = "trace")]
            debug!("找到 {} 個模型", data_array.len());

            for model_data in data_array {
                if let (Some(id), Some(object), Some(created), Some(owned_by)) = (
                    model_data.get("id").and_then(Value::as_str),
                    model_data.get("object").and_then(Value::as_str),
                    model_data.get("created").and_then(Value::as_i64),
                    model_data.get("owned_by").and_then(Value::as_str),
                ) {
                    model_list.push(ModelInfo {
                        id: id.to_string(),
                        object: object.to_string(),
                        created,
                        owned_by: owned_by.to_string(),
                    });
                }
            }
        } else {
            #[cfg(feature = "trace")]
            warn!("無法從 v1/models 回應中取得模型列表");
            return Err(PoeError::BotError(
                "無法從 v1/models 回應中取得模型列表".to_string(),
            ));
        }

        if model_list.is_empty() {
            #[cfg(feature = "trace")]
            warn!("取得的模型列表為空");
            return Err(PoeError::BotError("取得的模型列表為空".to_string()));
        }

        #[cfg(feature = "trace")]
        debug!("成功解析 {} 個模型", model_list.len());

        Ok(ModelResponse { data: model_list })
    }

    /// 從文本中移除 XML 工具調用部分
    #[cfg(feature = "xml")]
    pub fn remove_xml_tool_calls(text: &str) -> String {
        // 創建一個臨時的 ChatMessage 來檢測工具調用
        let message = ChatMessage {
            role: "assistant".to_string(),
            content: text.to_string(),
            attachments: None,
            content_type: "text/plain".to_string(),
        };

        // 如果沒有檢測到工具調用,直接返回原文本
        if !message.contains_xml_tool_calls() {
            return text.to_string();
        }

        // 提取工具調用以了解需要移除哪些部分
        let tool_calls = message.extract_xml_tool_calls();
        if tool_calls.is_empty() {
            return text.to_string();
        }

        let mut result = text.to_string();

        // 移除 <tool_call>...</tool_call> 標籤
        while let Some(start) = result.find("<tool_call>") {
            if let Some(end) = result[start..].find("</tool_call>") {
                let end_pos = start + end + "</tool_call>".len();
                result.replace_range(start..end_pos, "");
            } else {
                break;
            }
        }

        // 根據檢測到的工具調用移除對應的工具標籤
        for tool_call in &tool_calls {
            let tool_name = &tool_call.function.name;
            let start_pattern = format!("<{}>", tool_name);
            let end_pattern = format!("</{}>", tool_name);

            while let Some(start) = result.find(&start_pattern) {
                if let Some(end) = result[start..].find(&end_pattern) {
                    let end_pos = start + end + end_pattern.len();
                    result.replace_range(start..end_pos, "");
                } else {
                    break;
                }
            }
        }

        // 移除 <invoke> 標籤(如果存在)
        while let Some(start) = result.find("<invoke") {
            if let Some(end) = result[start..].find("</invoke>") {
                let end_pos = start + end + "</invoke>".len();
                result.replace_range(start..end_pos, "");
            } else {
                break;
            }
        }

        // 清理多餘的空行
        result
            .lines()
            .filter(|line| !line.trim().is_empty())
            .collect::<Vec<_>>()
            .join("\n")
    }
}

pub async fn get_model_list(language_code: Option<&str>) -> Result<ModelResponse, PoeError> {
    #[cfg(feature = "trace")]
    debug!("開始獲取模型列表,語言代碼: {:?}", language_code);

    let client = Client::builder()
        .user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
        .build()
        .map_err(|e| {
            #[cfg(feature = "trace")]
            warn!("建立 HTTP 客戶端失敗: {}", e);
            PoeError::BotError(e.to_string())
        })?;

    let payload = serde_json::json!({
        "queryName": "ExploreBotsListPaginationQuery",
        "variables": {
            "categoryName": "defaultCategory",
            "count": 150
        },
        "extensions": {
            "hash": POE_GQL_MODEL_HASH
        }
    });

    #[cfg(feature = "trace")]
    debug!("準備 GraphQL 請求載荷,使用 hash: {}", POE_GQL_MODEL_HASH);

    let mut headers = HeaderMap::new();
    headers.insert("Content-Type", HeaderValue::from_static("application/json"));
    headers.insert("Accept", HeaderValue::from_static("*/*"));
    headers.insert(
        "Accept-Language",
        HeaderValue::from_static("zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7"),
    );
    headers.insert("Origin", HeaderValue::from_static("https://poe.com"));
    headers.insert("Referer", HeaderValue::from_static("https://poe.com"));
    headers.insert("Sec-Fetch-Dest", HeaderValue::from_static("empty"));
    headers.insert("Sec-Fetch-Mode", HeaderValue::from_static("cors"));
    headers.insert("Sec-Fetch-Site", HeaderValue::from_static("same-origin"));
    headers.insert(
        "poe-revision",
        HeaderValue::from_static(POE_GQL_MODEL_REVISION),
    );
    headers.insert("poegraphql", HeaderValue::from_static("1"));

    if let Some(code) = language_code {
        let cookie_value = format!("Poe-Language-Code={}; p-b=1", code);
        #[cfg(feature = "trace")]
        debug!("設置語言 Cookie: {}", cookie_value);

        headers.insert(
            COOKIE,
            HeaderValue::from_str(&cookie_value).map_err(|e| {
                #[cfg(feature = "trace")]
                warn!("設置 Cookie 失敗: {}", e);
                PoeError::BotError(e.to_string())
            })?,
        );
    }

    #[cfg(feature = "trace")]
    debug!("發送 GraphQL 請求至 {}", POE_GQL_URL);

    let response = client
        .post(POE_GQL_URL)
        .headers(headers)
        .json(&payload)
        .send()
        .await
        .map_err(|e| {
            #[cfg(feature = "trace")]
            warn!("發送 GraphQL 請求失敗: {}", e);
            PoeError::RequestFailed(e)
        })?;

    if !response.status().is_success() {
        let status = response.status();
        let text = response
            .text()
            .await
            .unwrap_or_else(|_| "無法讀取回應內容".to_string());

        #[cfg(feature = "trace")]
        warn!("GraphQL API 回應錯誤 - 狀態碼: {}, 內容: {}", status, text);

        return Err(PoeError::BotError(format!(
            "API 回應錯誤 - 狀態碼: {}, 內容: {}",
            status, text
        )));
    }

    #[cfg(feature = "trace")]
    debug!("成功接收到 GraphQL 回應");

    let json_value = response.text().await.map_err(|e| {
        #[cfg(feature = "trace")]
        warn!("讀取 GraphQL 回應內容失敗: {}", e);
        PoeError::RequestFailed(e)
    })?;

    let data: Value = serde_json::from_str(&json_value).map_err(|e| {
        #[cfg(feature = "trace")]
        warn!("解析 GraphQL 回應 JSON 失敗: {}", e);
        PoeError::JsonParseFailed(e)
    })?;

    let mut model_list = Vec::with_capacity(150);

    if let Some(edges) = data["data"]["exploreBotsConnection"]["edges"].as_array() {
        #[cfg(feature = "trace")]
        debug!("找到 {} 個模型節點", edges.len());

        for edge in edges {
            if let Some(handle) = edge["node"]["handle"].as_str() {
                #[cfg(feature = "trace")]
                debug!("解析模型 ID: {}", handle);

                model_list.push(ModelInfo {
                    id: handle.to_string(),
                    object: "model".to_string(),
                    created: 0,
                    owned_by: "poe".to_string(),
                });
            } else {
                #[cfg(feature = "trace")]
                debug!("模型節點中找不到 handle 欄位");
            }
        }
    } else {
        #[cfg(feature = "trace")]
        warn!("無法從回應中取得模型列表節點");
        return Err(PoeError::BotError("無法從回應中取得模型列表".to_string()));
    }

    if model_list.is_empty() {
        #[cfg(feature = "trace")]
        warn!("取得的模型列表為空");
        return Err(PoeError::BotError("取得的模型列表為空".to_string()));
    }

    #[cfg(feature = "trace")]
    debug!("成功解析 {} 個模型", model_list.len());

    Ok(ModelResponse { data: model_list })
}