-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathmain.rs
More file actions
1814 lines (1627 loc) · 96.3 KB
/
Copy pathmain.rs
File metadata and controls
1814 lines (1627 loc) · 96.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Dora MaaS Client - Model-as-a-Service client for Dora dataflows
//!
//! This node provides cloud AI integration for Dora applications, serving as a
//! drop-in replacement for local LLM nodes. It features:
//!
//! - Multi-provider support (OpenAI, Gemini, etc.)
//! - Real-time streaming with SSE
//! - Intelligent text segmentation for TTS
//! - Session-based conversation management
//! - Event-driven architecture without threading
//!
//! # Architecture
//!
//! The client operates as a Dora node, processing events in a single async loop:
//! 1. Receives text input events from ASR or other nodes
//! 2. Routes requests to configured cloud providers
//! 3. Streams responses through the segmenter
//! 4. Emits segmented text for TTS processing
use std::collections::{BTreeMap, HashMap};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use dora_node_api::{
DoraNode, Event, Parameter,
arrow::array::{AsArray, StringArray, Array},
dora_core::config::DataId,
};
use eyre::{Context, Result};
use outfox_openai::spec::{
ChatCompletionMessageToolCall, ChatCompletionRequestAssistantMessage,
ChatCompletionRequestAssistantMessageContent, ChatCompletionRequestMessage,
ChatCompletionRequestSystemMessage, ChatCompletionRequestToolMessage,
ChatCompletionRequestUserMessage, ChatCompletionRequestUserMessageContent, ChatCompletionTool,
ChatCompletionToolType, CreateChatCompletionRequest, FunctionObject, PartibleTextContent,
};
use serde_json::json;
use tokio::sync::Mutex as AsyncMutex;
use tokio_util::sync::CancellationToken;
mod client;
mod config;
mod segmenter;
mod streaming;
mod tool;
use config::{Config, load_anchor_context, format_anchor_context};
use segmenter::StreamSegmenter;
use tool::ToolSet;
// Import CancellationReason from streaming module
use crate::streaming::CancellationReason;
// Helper function to send log messages
fn send_log(node: &mut DoraNode, level: &str, message: &str) -> Result<()> {
let log_data = json!({
"node": "maas-client",
"level": level,
"message": message,
"timestamp": chrono::Utc::now().timestamp()
});
node.send_output(
DataId::from("log".to_string()),
Default::default(),
StringArray::from(vec![log_data.to_string().as_str()]),
)
.context("Failed to send log output")?;
Ok(())
}
/// Manages active request cancellation tokens
struct RequestCancellationManager {
/// Active tokens by request_id
active_tokens: Arc<AsyncMutex<HashMap<String, CancellationToken>>>,
/// Session mapping for tokens (session_id -> Vec<request_id>)
session_requests: Arc<AsyncMutex<HashMap<String, Vec<String>>>>,
}
impl RequestCancellationManager {
fn new() -> Self {
Self {
active_tokens: Arc::new(AsyncMutex::new(HashMap::new())),
session_requests: Arc::new(AsyncMutex::new(HashMap::new())),
}
}
/// Create a new cancellation token for a request
async fn create_token(
&self,
request_id: String,
session_id: String,
) -> CancellationToken {
let token = CancellationToken::new();
// Store token
let mut tokens = self.active_tokens.lock().await;
tokens.insert(request_id.clone(), token.clone());
drop(tokens);
// Track session -> request mapping
let mut sessions = self.session_requests.lock().await;
sessions
.entry(session_id)
.or_insert_with(Vec::new)
.push(request_id);
token
}
/// Cancel a specific request by ID
async fn cancel_request(&self, request_id: &str) -> bool {
let mut tokens = self.active_tokens.lock().await;
if let Some(token) = tokens.remove(request_id) {
token.cancel();
eprintln!("[CANCELLATION] Cancelled request: {}", request_id);
true
} else {
eprintln!("[CANCELLATION] Request not found: {}", request_id);
false
}
}
/// Cancel all requests for a session
async fn cancel_session(&self, session_id: &str) -> usize {
let mut sessions = self.session_requests.lock().await;
let request_ids = sessions.remove(session_id).unwrap_or_default();
drop(sessions);
let mut cancelled_count = 0;
for request_id in request_ids {
if self.cancel_request(&request_id).await {
cancelled_count += 1;
}
}
// Only show cancellation message if there were actual requests to cancel
if cancelled_count > 0 {
eprintln!("[CANCELLATION] Cancelled {} requests for session: {}", cancelled_count, session_id);
} else {
// During startup, show a more informative message
if session_id == "default" {
eprintln!("[INFO] node ready - starting dataflow");
} else {
eprintln!("[INFO] {} ready - no active requests to cancel", session_id);
}
}
cancelled_count
}
/// Clean up completed request
async fn cleanup_request(&self, request_id: &str, session_id: &str) {
let mut tokens = self.active_tokens.lock().await;
tokens.remove(request_id);
drop(tokens);
let mut sessions = self.session_requests.lock().await;
if let Some(request_ids) = sessions.get_mut(session_id) {
request_ids.retain(|id| id != request_id);
if request_ids.is_empty() {
sessions.remove(session_id);
}
}
}
}
struct ChatSession {
messages: Vec<ChatCompletionRequestMessage>,
total_tokens: usize,
tool_set: Option<Arc<Mutex<ToolSet>>>,
}
impl ChatSession {
fn new(system_prompt: String, anchor_context: Option<String>) -> Self {
// Combine system prompt with anchor context if provided
let combined_prompt = if let Some(context) = anchor_context {
format!("{}\n\n{}", context, system_prompt)
} else {
system_prompt
};
let system_message =
ChatCompletionRequestMessage::System(ChatCompletionRequestSystemMessage {
content: PartibleTextContent::Text(combined_prompt),
name: None,
});
Self {
messages: vec![system_message],
total_tokens: 0,
tool_set: None, // Will be set separately
}
}
fn set_tool_set(&mut self, tool_set: Arc<Mutex<ToolSet>>) {
self.tool_set = Some(tool_set);
}
fn has_tools(&self) -> bool {
self.tool_set
.as_ref()
.and_then(|ts| ts.lock().ok())
.map(|ts| ts.has_tools())
.unwrap_or(false)
}
fn get_tool_definitions(&self) -> Option<Vec<ChatCompletionTool>> {
self.tool_set
.as_ref()
.and_then(|ts| ts.lock().ok())
.map(|ts| {
ts.tools()
.iter()
.map(|tool| ChatCompletionTool {
kind: ChatCompletionToolType::Function,
function: FunctionObject {
name: tool.name(),
description: Some(tool.description()),
parameters: Some(tool.parameters()),
strict: None,
},
})
.collect()
})
}
fn add_user_message(&mut self, content: String) {
let message = ChatCompletionRequestMessage::User(ChatCompletionRequestUserMessage {
content: ChatCompletionRequestUserMessageContent::Text(content),
name: None,
});
self.messages.push(message);
}
fn add_assistant_message(&mut self, content: String) {
let message =
ChatCompletionRequestMessage::Assistant(ChatCompletionRequestAssistantMessage {
content: Some(ChatCompletionRequestAssistantMessageContent::Text(content)),
name: None,
tool_calls: None,
audio: None,
refusal: None,
});
self.messages.push(message);
}
fn add_assistant_message_with_tools(
&mut self,
content: String,
tool_calls: Vec<ChatCompletionMessageToolCall>,
) {
let message =
ChatCompletionRequestMessage::Assistant(ChatCompletionRequestAssistantMessage {
content: if content.is_empty() {
None
} else {
Some(ChatCompletionRequestAssistantMessageContent::Text(content))
},
name: None,
tool_calls: Some(tool_calls),
audio: None,
refusal: None,
});
self.messages.push(message);
}
fn add_tool_message(&mut self, tool_call_id: String, content: String) {
let message = ChatCompletionRequestMessage::Tool(ChatCompletionRequestToolMessage {
content: PartibleTextContent::Text(content),
tool_call_id,
});
self.messages.push(message);
}
fn manage_history(&mut self, max_exchanges: usize) {
// Collect indices where each logical turn starts (i.e., user messages)
let turn_start_indices: Vec<usize> = self
.messages
.iter()
.enumerate()
.skip(1)
.filter_map(|(i, msg) | {
if matches!(msg, ChatCompletionRequestMessage::User(_)) {
Some(i)
} else {
None
}
})
.collect();
// If within limit already, do nothing
if turn_start_indices.len() <= max_exchanges {
return;
}
// Dropping (turn_start_indices.len() - max_exchanges) oldest turns
let turns_to_drop = turn_start_indices.len() - max_exchanges;
// Everything from index 1 up to (but not including) that index gets removed.
let first_keep_index = turn_start_indices[turns_to_drop];
// drain(1..first_keep_index) removes old turns while keeping system prompt.
self.messages.drain(1..first_keep_index);
}
}
/// Load and format anchor context for a given configuration
fn load_anchor_context_for_session(config: &Config) -> Option<String> {
if let Some(ref context_path) = config.anchor_context {
match load_anchor_context(context_path) {
Ok(context_content) => {
let formatted = format_anchor_context(&context_content);
eprintln!("✅ Loaded anchor context from: {}", context_path);
Some(formatted)
}
Err(e) => {
eprintln!("⚠️ Warning: Failed to load anchor context from '{}': {}", context_path, e);
eprintln!("⚠️ Proceeding without anchor context");
None
}
}
} else {
None
}
}
#[tokio::main]
async fn main() -> Result<()> {
// Check if running as dynamic node with --name argument
let args: Vec<String> = std::env::args().collect();
let node_id = if args.len() > 2 && args[1] == "--name" {
Some(args[2].clone())
} else {
None
};
// Load configuration
let config = Config::load().context("Failed to load configuration")?;
// Log level is available for future use
let _log_level = &config.log_level;
// Load anchor context if configured
let anchor_context = load_anchor_context_for_session(&config);
// Initialize MCP tools if enabled
let tool_set = if config.enable_tools {
match config.init_tool_set().await {
Ok(Some(ts)) => {
let tool_count = ts.tools().len();
Some(Arc::new(Mutex::new(ts)))
}
Ok(None) => None,
Err(e) => {
eprintln!("Warning: Failed to initialize MCP tools: {}", e);
None
}
}
} else {
None
};
// Create provider clients
let clients = config.create_clients();
// Initialize cancellation manager if enabled
let cancellation_manager = Arc::new(RequestCancellationManager::new());
// Initialize Dora node - use node_id if provided (dynamic node), otherwise from env
let (mut node, events) = if let Some(id) = node_id {
match DoraNode::init_from_node_id(dora_node_api::dora_core::config::NodeId::from(
id.clone(),
)) {
Ok((n, e)) => (n, e),
Err(e) => {
eprintln!("❌ Failed to initialize dynamic node '{}': {:?}", id, e);
return Err(e.into());
}
}
} else {
match DoraNode::init_from_env() {
Ok((n, e)) => (n, e),
Err(e) => {
eprintln!("❌ Failed to initialize node from environment: {:?}", e);
return Err(e.into());
}
}
};
// Send initialization logs
send_log(&mut node, "INFO", "MaaS Client initialized")?;
send_log(
&mut node,
"INFO",
&format!("Model: {}", config.default_model),
)?;
send_log(
&mut node,
"INFO",
&format!("Providers: {}", config.providers.len()),
)?;
// Session storage
let mut sessions: HashMap<String, ChatSession> = HashMap::new();
// Process events
let events = futures::executor::block_on_stream(events);
for event in events {
match event {
Event::Input { id, data, metadata } => {
// Extract session ID from metadata
let session_id = metadata
.parameters
.get("session_id")
.and_then(|p| match p {
Parameter::String(s) => Some(s.clone()),
_ => None,
})
.unwrap_or_else(|| "default".to_string());
// debug!("Received input '{}' for session '{}'", id, session_id);
match id.as_str() {
"text" | "text_to_audio" => {
// Extract text from input
let text_array = data.as_string::<i32>();
let user_text = text_array
.iter()
.filter_map(|s| s)
.collect::<Vec<_>>()
.join(" ");
send_log(&mut node, "INFO", &format!("Received input: \"{}\"", user_text))?;
if user_text.is_empty() {
send_log(&mut node, "WARNING", "Received empty text input")?;
continue;
}
// Get or create session
let session = sessions.entry(session_id.clone()).or_insert_with(|| {
let mut session = ChatSession::new(config.system_prompt.clone(), anchor_context.clone());
if let Some(ref ts) = tool_set {
session.set_tool_set(ts.clone());
}
session
});
let role = metadata
.parameters
.get("role")
.and_then(|p| match p {
Parameter::String(s) => Some(s.as_str()),
_ => None,
});
if matches!(role, Some("assistant")) {
send_log(
&mut node,
"DEBUG",
&format!("Caching assistant context: {}", user_text),
)?;
session.add_assistant_message(user_text.clone());
session.manage_history(config.max_history_exchanges);
continue;
}
send_log(&mut node, "INFO", &format!("Processing: {}", user_text))?;
// Add user message
session.add_user_message(user_text.clone());
// Manage history
session.manage_history(config.max_history_exchanges);
// Process the conversation with automatic tool handling
// FIX: Added loop to handle tool calls without waiting for user input
// When the LLM calls a tool, we execute it and immediately send the results
// back to get the final response, instead of waiting for the next user message
let mut continue_conversation = true;
while continue_conversation {
continue_conversation = false; // Default to not continuing unless we have tool calls
// Route to appropriate provider
let (provider_id, model_name) =
config.route_model(&config.default_model).ok_or_else(|| {
eyre::eyre!(
"No route found for model: {}",
config.default_model
)
})?;
// Create chat completion request with the mapped model name
let mut request = CreateChatCompletionRequest::new(
model_name.clone(), // Use the mapped model name, not the config model ID
session.messages.clone(),
);
// Add tool definitions if available
if config.enable_tools {
if config.enable_local_mcp && session.has_tools() {
// Use local MCP tools
request.tools = session.get_tool_definitions();
send_log(
&mut node,
"DEBUG",
&format!(
"Added {} local MCP tool definitions",
request.tools.as_ref().map(|t| t.len()).unwrap_or(0)
),
)?;
} else if !config.enable_local_mcp {
// Pass through tools from client metadata
if let Some(tools_param) = metadata.parameters.get("tools") {
// Parse tools from metadata (expecting JSON array)
if let Parameter::String(tools_json) = tools_param {
if let Ok(tools) =
serde_json::from_str::<Vec<ChatCompletionTool>>(
tools_json,
)
{
request.tools = Some(tools.clone());
send_log(
&mut node,
"DEBUG",
&format!(
"Added {} client-provided tool definitions",
tools.len()
),
)?;
}
}
}
}
}
request.stream = config.enable_streaming;
request.temperature = Some(0.7);
let client = clients.get(&provider_id).ok_or_else(|| {
eyre::eyre!("No client found for provider: {}", provider_id)
})?;
send_log(
&mut node,
"DEBUG",
&format!(
"Routing to provider '{}' with model '{}'",
provider_id, model_name
),
)?;
// Send "processing" status when starting API call
node.send_output(
DataId::from("status".to_string()),
Default::default(),
StringArray::from(vec!["processing"]),
)
.context("Failed to send status output")?;
// Make API call - use streaming if enabled
if config.enable_streaming.unwrap_or(false) {
// Streaming mode
send_log(&mut node, "DEBUG", "Using streaming mode")?;
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<String>();
let mut has_sent_segment = false;
let mut segment_index: u32 = 0;
// Start streaming in background with cancellation support
let client_clone = client.clone();
let request_clone = request.clone();
let request_id = uuid::Uuid::new_v4().to_string();
let session_id_clone = session_id.clone();
let metadata_clone = metadata.parameters.clone();
let cancellation_manager_clone = cancellation_manager.clone();
// Create cancellation token if enabled
let cancellation_token = if config.enable_cancellation {
Some(cancellation_manager.create_token(
request_id.clone(),
session_id.clone(),
).await)
} else {
None
};
let stream_handle = tokio::spawn(async move {
let result = if let Some(token) = cancellation_token {
// Use cancellation-aware streaming
client_clone.complete_streaming_with_cancellation(
request_clone,
tx,
token,
Duration::from_secs(config.stream_timeout_secs),
).await
} else {
// Use regular streaming
client_clone.complete_streaming(request_clone, tx).await
};
// Clean up token after completion
if config.enable_cancellation {
cancellation_manager_clone
.cleanup_request(&request_id, &session_id_clone)
.await;
}
result
});
// Use segmenter to buffer chunks into meaningful segments
let mut segmenter = StreamSegmenter::new(10); // Max 10 words without punctuation
let mut accumulated = String::new();
let mut chunk_count = 0;
let mut segment_count = 0;
while let Some(chunk) = rx.recv().await {
chunk_count += 1;
// Add chunk to segmenter and check if we have a segment ready
if let Some(segment) = segmenter.add_chunk(&chunk) {
accumulated.push_str(&segment);
segment_count += 1;
// Send the meaningful segment with metadata passthrough
let mut segment_metadata = metadata.parameters.clone();
segment_metadata.insert(
"session_status".to_string(),
Parameter::String(
if !has_sent_segment {
"started".to_string()
} else {
"ongoing".to_string()
},
),
);
segment_metadata.insert(
"segment_index".to_string(),
Parameter::String(segment_index.to_string()),
);
node.send_output(
DataId::from("text".to_string()),
segment_metadata,
StringArray::from(vec![segment.as_str()]),
)
.context("Failed to send text segment")?;
has_sent_segment = true;
segment_index += 1;
}
}
// Flush any remaining buffered content
if let Some(final_segment) = segmenter.flush() {
accumulated.push_str(&final_segment);
segment_count += 1;
let mut segment_metadata = metadata.parameters.clone();
segment_metadata.insert(
"session_status".to_string(),
Parameter::String(
if !has_sent_segment {
"started".to_string()
} else {
"ongoing".to_string()
},
),
);
segment_metadata.insert(
"segment_index".to_string(),
Parameter::String(segment_index.to_string()),
);
node.send_output(
DataId::from("text".to_string()),
segment_metadata,
StringArray::from(vec![final_segment.as_str()]),
)
.context("Failed to send final segment")?;
has_sent_segment = true;
segment_index += 1;
send_log(
&mut node,
"DEBUG",
&format!(
"Sent final segment {} ({} chars)",
segment_count,
final_segment.len()
),
)?;
}
// Wait for streaming to complete
match stream_handle.await {
Ok(Ok((final_text, tool_calls))) => {
send_log(
&mut node,
"INFO",
&format!(
"Streaming complete: {} chars in {} segments (from {} chunks)",
final_text.len(),
segment_count,
chunk_count
),
)?;
// Send "complete" status
node.send_output(
DataId::from("status".to_string()),
Default::default(),
StringArray::from(vec!["complete"]),
)
.context("Failed to send status output")?;
// FIX: Handle tool calls from streaming response
// When the LLM returns tool calls, we either execute them locally (enable_local_mcp=true)
// or pass them back to the client (enable_local_mcp=false)
if let Some(tool_calls) = tool_calls {
send_log(
&mut node,
"INFO",
&format!(
"Received {} tool calls",
tool_calls.len()
),
)?;
// Add assistant message with tool calls first
session.add_assistant_message_with_tools(
final_text.clone(),
tool_calls.clone(),
);
if config.enable_local_mcp {
// Execute tool calls locally
send_log(
&mut node,
"INFO",
"Executing tool calls locally",
)?;
// Execute tool calls and collect results
let mut tool_results = Vec::new();
if let Some(ref tool_set) = session.tool_set {
for tool_call in &tool_calls {
send_log(
&mut node,
"DEBUG",
&format!(
"Calling tool: {} with args: {}",
tool_call.function.name,
tool_call.function.arguments
),
)?;
// Get the tool from the tool set
let tool = {
let tool_set_guard =
tool_set.lock().unwrap();
tool_set_guard
.get_tool(&tool_call.function.name)
};
let result = if let Some(tool) = tool {
// Parse arguments
let args: serde_json::Value =
serde_json::from_str(
&tool_call.function.arguments,
)
.unwrap_or(serde_json::Value::Null);
// Execute the tool
match tool.call(args).await {
Ok(result) => {
let content = if let Some(
contents,
) =
result.content
{
contents
.iter()
.filter_map(|c| {
c.as_text()
})
.map(|t| t.text.clone())
.collect::<Vec<_>>()
.join("\n")
} else {
"Tool executed successfully"
.to_string()
};
send_log(
&mut node,
"DEBUG",
&format!(
"Tool result: {}",
content
),
)?;
content
}
Err(e) => {
send_log(
&mut node,
"ERROR",
&format!(
"Tool execution failed: {}",
e
),
)?;
format!("Error: {}", e)
}
}
} else {
let msg = format!(
"Tool '{}' not found",
tool_call.function.name
);
send_log(&mut node, "ERROR", &msg)?;
msg
};
// Collect the result to add later
tool_results
.push((tool_call.id.clone(), result));
}
}
// Add all tool results to session
for (tool_call_id, result) in tool_results {
session.add_tool_message(tool_call_id, result);
}
// After tool execution, immediately make another request to get the final response
// Don't wait for user input - we need to send the tool results back to the LLM
send_log(
&mut node,
"DEBUG",
"Sending tool results back to LLM for final response",
)?;
// Set flag to continue the conversation with tool results
continue_conversation = true;
} else {
// Pass tool calls back to client
send_log(
&mut node,
"INFO",
"Passing tool calls to client",
)?;
// Serialize tool calls and send to client
let tool_calls_json =
serde_json::to_string(&tool_calls)?;
node.send_output(
DataId::from("tool_calls".to_string()),
Default::default(),
StringArray::from(vec![
tool_calls_json.as_str(),
]),
)
.context("Failed to send tool calls")?;
// Don't continue conversation - wait for tool results from client
continue_conversation = false;
}
} else {
// No tool calls, just add the text message
session.add_assistant_message(final_text.clone());
}
}
Ok(Err(e)) => {
let error_msg = format!("{}", e);
send_log(
&mut node,
"ERROR",
&format!("Streaming error: {}", error_msg),
)?;
// Classify error type and set appropriate session_status
let status = if error_msg.contains("cancelled") || error_msg.contains("cancelled by user") {
"cancelled"
} else if error_msg.contains("timed out") {
"timeout"
} else {
"error"
};
// Use same classification for session_status
let session_status = if error_msg.contains("cancelled") || error_msg.contains("cancelled by user") {
"cancelled"
} else if error_msg.contains("timed out") {
"timeout"
} else {
"error"
};
// Send status
node.send_output(
DataId::from("status".to_string()),
Default::default(),
StringArray::from(vec![status]),
)
.context("Failed to send status output")?;
let mut error_metadata = metadata.parameters.clone();
error_metadata.insert(
"session_status".to_string(),
Parameter::String(session_status.to_string()),
);
error_metadata.insert(
"error_type".to_string(),
Parameter::String(status.to_string()),
);
error_metadata.insert(
"error_message".to_string(),
Parameter::String(error_msg),
);
node.send_output(
DataId::from("text".to_string()),
error_metadata,
StringArray::from(vec![
format!("Error: {}", e).as_str(),
]),
)
.context("Failed to send error")?;
}
Err(e) => {
let error_msg = format!("{}", e);
send_log(
&mut node,
"ERROR",
&format!("Task error: {}", error_msg),
)?;
// Classify error type for task errors
let error_type = if error_msg.contains("cancelled") || error_msg.contains("cancelled by user") {
"cancelled"
} else if error_msg.contains("timed out") {
"timeout"
} else {
"error"
};
// Send error status
node.send_output(
DataId::from("status".to_string()),
Default::default(),
StringArray::from(vec![format!("{}: {}", error_type, e)]),
)
.context("Failed to send status output")?;
let mut error_metadata = metadata.parameters.clone();
error_metadata.insert(
"session_status".to_string(),
Parameter::String(error_type.to_string()),
);
error_metadata.insert(
"error_type".to_string(),
Parameter::String(error_type.to_string()),
);
error_metadata.insert(
"error_message".to_string(),
Parameter::String(error_msg),
);
node.send_output(
DataId::from("text".to_string()),
error_metadata,
StringArray::from(vec![format!("Error: {}", e).as_str()]),
)
.context("Failed to send error output")?;
}
}
if has_sent_segment {
let mut end_metadata = metadata.parameters.clone();
end_metadata.insert(
"session_status".to_string(),
Parameter::String("ended".to_string()),
);
end_metadata.insert(
"segment_index".to_string(),
Parameter::String(segment_index.to_string()),
);
node.send_output(
DataId::from("text".to_string()),
end_metadata,
StringArray::from(vec![""]),
)
.context("Failed to send session end marker")?;
}
} else {
// Non-streaming mode
match client.complete(request).await {
Ok(response) => {
if let Some(choice) = response.choices.first() {
let content = match &choice.message {
outfox_openai::spec::ChatCompletionResponseMessage { content, .. } => {
content.clone().unwrap_or_default()
}