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
use std::pin::Pin;
use crate::OpenAiAdapter;
use crate::api_v1::ChatCompletionRequest;
use crate::api_v1::FinishReason;
use artificial_core::error::{ArtificialError, Result};
use artificial_core::generic::{GenericFunctionCall, GenericFunctionCallIntent, StreamEvent};
use artificial_core::provider::StreamingEventsProvider;
use artificial_core::provider::{ChatCompleteParameters, StreamingChatProvider};
use futures_core::stream::Stream;
use std::collections::HashMap;
impl StreamingChatProvider for OpenAiAdapter {
type Delta<'s>
= Pin<Box<dyn Stream<Item = Result<String>> + Send + 's>>
where
Self: 's;
fn chat_complete_stream<'p, M>(&self, params: ChatCompleteParameters<M>) -> Self::Delta<'p>
where
M: Into<Self::Message> + Send + Sync + 'p,
{
let client = self.client.clone();
Box::pin(async_stream::try_stream! {
use futures_util::StreamExt;
let request: ChatCompletionRequest = params.try_into()?;
let stream = client.chat_completion_stream(request);
futures_util::pin_mut!(stream);
while let Some(chunk) = stream.next().await {
let chunk = chunk.map_err(ArtificialError::from)?;
for choice in chunk.choices {
if let Some(text) = choice.delta.content {
yield text;
}
}
}
})
}
}
impl StreamingEventsProvider for OpenAiAdapter {
type EventStream<'s>
= Pin<Box<dyn Stream<Item = Result<StreamEvent>> + Send + 's>>
where
Self: 's;
fn chat_complete_events_stream<'p, M>(
&self,
params: ChatCompleteParameters<M>,
) -> Self::EventStream<'p>
where
M: Into<Self::Message> + Send + Sync + 'p,
{
let client = self.client.clone();
Box::pin(async_stream::try_stream! {
use futures_util::StreamExt;
let request: ChatCompletionRequest = params.try_into()?;
// Track tool-call argument fragments and first-seen id/name per tool index.
let mut tool_args: HashMap<usize, String> = HashMap::new();
let mut tool_seen: HashMap<usize, (Option<String>, Option<String>)> = HashMap::new();
let stream = client.chat_completion_stream(request);
futures_util::pin_mut!(stream);
while let Some(chunk) = stream.next().await {
let chunk = chunk.map_err(ArtificialError::from)?;
for choice in chunk.choices {
// Process only the first choice to match current non-streaming behavior.
if choice.index != 0 { continue; }
// Text deltas
if let Some(delta) = choice.delta.content
&& !delta.is_empty() {
yield StreamEvent::TextDelta(delta);
}
// Tool-call deltas
if let Some(tool_calls) = choice.delta.tool_calls {
for tc in tool_calls {
let entry = tool_seen.entry(tc.index).or_insert((None, None));
if let Some(id) = tc.id.clone() {
if entry.0.is_none() {
entry.0 = Some(id.clone());
yield StreamEvent::ToolCallStart {
index: tc.index,
id: Some(id),
name: entry.1.clone(),
};
} else {
entry.0 = Some(id);
}
}
if let Some(func) = tc.function {
if let Some(name) = func.name {
if entry.1.is_none() {
entry.1 = Some(name.clone());
yield StreamEvent::ToolCallStart {
index: tc.index,
id: entry.0.clone(),
name: Some(name),
};
} else {
entry.1 = Some(name);
}
}
if let Some(arguments) = func.arguments {
let buf = tool_args.entry(tc.index).or_default();
buf.push_str(&arguments);
if !arguments.is_empty() {
yield StreamEvent::ToolCallArgumentsDelta {
index: tc.index,
arguments_fragment: arguments,
};
}
}
}
}
}
// Finish conditions
if let Some(reason) = choice.finish_reason {
match reason {
FinishReason::ToolCalls => {
// Finalize tool calls by parsing accumulated argument buffers.
for (index, buf) in tool_args.iter() {
let (id_opt, name_opt) = tool_seen
.get(index)
.cloned()
.unwrap_or((None, None));
let name = name_opt.unwrap_or_else(|| "tool".to_string());
let args_json: serde_json::Value = serde_json::from_str(buf)
.map_err(|e| ArtificialError::Invalid(format!("invalid tool arguments JSON: {e}")))?;
let intent = GenericFunctionCallIntent {
id: id_opt.unwrap_or_else(|| format!("toolcall-{index}")),
function: GenericFunctionCall { name, arguments: args_json },
};
yield StreamEvent::ToolCallComplete { index: *index, intent };
}
yield StreamEvent::MessageEnd;
return;
}
FinishReason::Stop | FinishReason::Length | FinishReason::ContentFilter => {
yield StreamEvent::MessageEnd;
return;
}
}
}
}
}
})
}
}