rig/providers/openai/completion/
streaming.rs1use std::collections::HashMap;
2
3use async_stream::stream;
4use futures::StreamExt;
5use http::Request;
6use serde::{Deserialize, Serialize};
7use serde_json::json;
8use tracing::{Level, enabled, info_span};
9use tracing_futures::Instrument;
10
11use crate::completion::{CompletionError, CompletionRequest, GetTokenUsage};
12use crate::http_client::HttpClientExt;
13use crate::http_client::sse::{Event, GenericEventSource};
14use crate::json_utils::{self, merge};
15use crate::message::{ToolCall, ToolFunction};
16use crate::providers::openai::completion::{self, CompletionModel, OpenAIRequestParams, Usage};
17use crate::streaming::{self, RawStreamingChoice};
18
19#[derive(Deserialize, Debug)]
23pub(crate) struct StreamingFunction {
24 pub(crate) name: Option<String>,
25 pub(crate) arguments: Option<String>,
26}
27
28#[derive(Deserialize, Debug)]
29pub(crate) struct StreamingToolCall {
30 pub(crate) index: usize,
31 pub(crate) id: Option<String>,
32 pub(crate) function: StreamingFunction,
33}
34
35#[derive(Deserialize, Debug)]
36struct StreamingDelta {
37 #[serde(default)]
38 content: Option<String>,
39 #[serde(default, deserialize_with = "json_utils::null_or_vec")]
40 tool_calls: Vec<StreamingToolCall>,
41}
42
43#[derive(Deserialize, Debug, PartialEq)]
44#[serde(rename_all = "snake_case")]
45pub enum FinishReason {
46 ToolCalls,
47 Stop,
48 ContentFilter,
49 Length,
50 #[serde(untagged)]
51 Other(String), }
53
54#[derive(Deserialize, Debug)]
55struct StreamingChoice {
56 delta: StreamingDelta,
57 finish_reason: Option<FinishReason>,
58}
59
60#[derive(Deserialize, Debug)]
61struct StreamingCompletionChunk {
62 choices: Vec<StreamingChoice>,
63 usage: Option<Usage>,
64}
65
66#[derive(Clone, Serialize, Deserialize)]
67pub struct StreamingCompletionResponse {
68 pub usage: Usage,
69}
70
71impl GetTokenUsage for StreamingCompletionResponse {
72 fn token_usage(&self) -> Option<crate::completion::Usage> {
73 let mut usage = crate::completion::Usage::new();
74 usage.input_tokens = self.usage.prompt_tokens as u64;
75 usage.output_tokens = self.usage.total_tokens as u64 - self.usage.prompt_tokens as u64;
76 usage.total_tokens = self.usage.total_tokens as u64;
77 Some(usage)
78 }
79}
80
81impl<T> CompletionModel<T>
82where
83 T: HttpClientExt + Clone + 'static,
84{
85 pub(crate) async fn stream(
86 &self,
87 completion_request: CompletionRequest,
88 ) -> Result<streaming::StreamingCompletionResponse<StreamingCompletionResponse>, CompletionError>
89 {
90 let request = super::CompletionRequest::try_from(OpenAIRequestParams {
91 model: self.model.clone(),
92 request: completion_request,
93 strict_tools: self.strict_tools,
94 tool_result_array_content: self.tool_result_array_content,
95 })?;
96 let request_messages = serde_json::to_string(&request.messages)
97 .expect("Converting to JSON from a Rust struct shouldn't fail");
98 let mut request_as_json = serde_json::to_value(request).expect("this should never fail");
99
100 request_as_json = merge(
101 request_as_json,
102 json!({"stream": true, "stream_options": {"include_usage": true}}),
103 );
104
105 if enabled!(Level::TRACE) {
106 tracing::trace!(
107 target: "rig::completions",
108 "OpenAI Chat Completions streaming completion request: {}",
109 serde_json::to_string_pretty(&request_as_json)?
110 );
111 }
112
113 let req_body = serde_json::to_vec(&request_as_json)?;
114
115 let req = self
116 .client
117 .post("/chat/completions")?
118 .body(req_body)
119 .map_err(|e| CompletionError::HttpError(e.into()))?;
120
121 let span = if tracing::Span::current().is_disabled() {
122 info_span!(
123 target: "rig::completions",
124 "chat",
125 gen_ai.operation.name = "chat",
126 gen_ai.provider.name = "openai",
127 gen_ai.request.model = self.model,
128 gen_ai.response.id = tracing::field::Empty,
129 gen_ai.response.model = self.model,
130 gen_ai.usage.output_tokens = tracing::field::Empty,
131 gen_ai.usage.input_tokens = tracing::field::Empty,
132 gen_ai.input.messages = request_messages,
133 gen_ai.output.messages = tracing::field::Empty,
134 )
135 } else {
136 tracing::Span::current()
137 };
138
139 let client = self.client.clone();
140
141 tracing::Instrument::instrument(send_compatible_streaming_request(client, req), span).await
142 }
143}
144
145pub async fn send_compatible_streaming_request<T>(
146 http_client: T,
147 req: Request<Vec<u8>>,
148) -> Result<streaming::StreamingCompletionResponse<StreamingCompletionResponse>, CompletionError>
149where
150 T: HttpClientExt + Clone + 'static,
151{
152 let span = tracing::Span::current();
153 let mut event_source = GenericEventSource::new(http_client, req);
155
156 let stream = stream! {
157 let span = tracing::Span::current();
158
159 let mut tool_calls: HashMap<usize, ToolCall> = HashMap::new();
161 let mut text_content = String::new();
162 let mut final_tool_calls: Vec<completion::ToolCall> = Vec::new();
163 let mut final_usage = None;
164
165 while let Some(event_result) = event_source.next().await {
166 match event_result {
167 Ok(Event::Open) => {
168 tracing::trace!("SSE connection opened");
169 continue;
170 }
171
172 Ok(Event::Message(message)) => {
173 if message.data.trim().is_empty() || message.data == "[DONE]" {
174 continue;
175 }
176
177 let data = match serde_json::from_str::<StreamingCompletionChunk>(&message.data) {
178 Ok(data) => data,
179 Err(error) => {
180 tracing::error!(?error, message = message.data, "Failed to parse SSE message");
181 continue;
182 }
183 };
184
185 let Some(choice) = data.choices.first() else {
187 tracing::debug!("There is no choice");
188 continue;
189 };
190 let delta = &choice.delta;
191
192 if !delta.tool_calls.is_empty() {
193 for tool_call in &delta.tool_calls {
194 let index = tool_call.index;
195
196 let existing_tool_call = tool_calls.entry(index).or_insert_with(|| ToolCall {
198 id: String::new(),
199 call_id: None,
200 function: ToolFunction {
201 name: String::new(),
202 arguments: serde_json::Value::Null,
203 },
204 signature: None,
205 additional_params: None,
206 });
207
208 if let Some(id) = &tool_call.id && !id.is_empty() {
210 existing_tool_call.id = id.clone();
211 }
212
213 if let Some(name) = &tool_call.function.name && !name.is_empty() {
214 existing_tool_call.function.name = name.clone();
215 }
216
217 if let Some(chunk) = &tool_call.function.arguments {
218 let current_args = match &existing_tool_call.function.arguments {
220 serde_json::Value::Null => String::new(),
221 serde_json::Value::String(s) => s.clone(),
222 v => v.to_string(),
223 };
224
225 let combined = format!("{current_args}{chunk}");
227
228 if combined.trim_start().starts_with('{') && combined.trim_end().ends_with('}') {
230 match serde_json::from_str(&combined) {
231 Ok(parsed) => existing_tool_call.function.arguments = parsed,
232 Err(_) => existing_tool_call.function.arguments = serde_json::Value::String(combined),
233 }
234 } else {
235 existing_tool_call.function.arguments = serde_json::Value::String(combined);
236 }
237
238 yield Ok(streaming::RawStreamingChoice::ToolCallDelta {
240 id: existing_tool_call.id.clone(),
241 delta: chunk.clone(),
242 });
243 }
244 }
245 }
246
247 if let Some(content) = &delta.content && !content.is_empty() {
249 text_content += content;
250 yield Ok(streaming::RawStreamingChoice::Message(content.clone()));
251 }
252
253 if let Some(usage) = data.usage {
255 final_usage = Some(usage);
256 }
257
258 if let Some(finish_reason) = &choice.finish_reason && *finish_reason == FinishReason::ToolCalls {
260 for (_idx, tool_call) in tool_calls.into_iter() {
261 final_tool_calls.push(completion::ToolCall {
262 id: tool_call.id.clone(),
263 r#type: completion::ToolType::Function,
264 function: completion::Function {
265 name: tool_call.function.name.clone(),
266 arguments: tool_call.function.arguments.clone(),
267 },
268 });
269 yield Ok(streaming::RawStreamingChoice::ToolCall(
270 streaming::RawStreamingToolCall::new(
271 tool_call.id,
272 tool_call.function.name,
273 tool_call.function.arguments,
274 )
275 ));
276 }
277 tool_calls = HashMap::new();
278 }
279 }
280 Err(crate::http_client::Error::StreamEnded) => {
281 break;
282 }
283 Err(error) => {
284 tracing::error!(?error, "SSE error");
285 yield Err(CompletionError::ProviderError(error.to_string()));
286 break;
287 }
288 }
289 }
290
291
292 event_source.close();
294
295 for (_idx, tool_call) in tool_calls.into_iter() {
297 yield Ok(streaming::RawStreamingChoice::ToolCall(
298 streaming::RawStreamingToolCall::new(
299 tool_call.id,
300 tool_call.function.name,
301 tool_call.function.arguments,
302 )
303 ));
304 }
305
306 let final_usage = final_usage.unwrap_or_default();
307 if !span.is_disabled() {
308 span.record("gen_ai.usage.input_tokens", final_usage.prompt_tokens);
309 span.record("gen_ai.usage.output_tokens", final_usage.total_tokens - final_usage.prompt_tokens);
310 }
311
312 yield Ok(RawStreamingChoice::FinalResponse(StreamingCompletionResponse {
313 usage: final_usage
314 }));
315 }.instrument(span);
316
317 Ok(streaming::StreamingCompletionResponse::stream(Box::pin(
318 stream,
319 )))
320}
321
322#[cfg(test)]
323mod tests {
324 use super::*;
325
326 #[test]
327 fn test_streaming_function_deserialization() {
328 let json = r#"{"name": "get_weather", "arguments": "{\"location\":\"Paris\"}"}"#;
329 let function: StreamingFunction = serde_json::from_str(json).unwrap();
330 assert_eq!(function.name, Some("get_weather".to_string()));
331 assert_eq!(
332 function.arguments.as_ref().unwrap(),
333 r#"{"location":"Paris"}"#
334 );
335 }
336
337 #[test]
338 fn test_streaming_tool_call_deserialization() {
339 let json = r#"{
340 "index": 0,
341 "id": "call_abc123",
342 "function": {
343 "name": "get_weather",
344 "arguments": "{\"city\":\"London\"}"
345 }
346 }"#;
347 let tool_call: StreamingToolCall = serde_json::from_str(json).unwrap();
348 assert_eq!(tool_call.index, 0);
349 assert_eq!(tool_call.id, Some("call_abc123".to_string()));
350 assert_eq!(tool_call.function.name, Some("get_weather".to_string()));
351 }
352
353 #[test]
354 fn test_streaming_tool_call_partial_deserialization() {
355 let json = r#"{
357 "index": 0,
358 "id": null,
359 "function": {
360 "name": null,
361 "arguments": "Paris"
362 }
363 }"#;
364 let tool_call: StreamingToolCall = serde_json::from_str(json).unwrap();
365 assert_eq!(tool_call.index, 0);
366 assert!(tool_call.id.is_none());
367 assert!(tool_call.function.name.is_none());
368 assert_eq!(tool_call.function.arguments.as_ref().unwrap(), "Paris");
369 }
370
371 #[test]
372 fn test_streaming_delta_with_tool_calls() {
373 let json = r#"{
374 "content": null,
375 "tool_calls": [{
376 "index": 0,
377 "id": "call_xyz",
378 "function": {
379 "name": "search",
380 "arguments": ""
381 }
382 }]
383 }"#;
384 let delta: StreamingDelta = serde_json::from_str(json).unwrap();
385 assert!(delta.content.is_none());
386 assert_eq!(delta.tool_calls.len(), 1);
387 assert_eq!(delta.tool_calls[0].id, Some("call_xyz".to_string()));
388 }
389
390 #[test]
391 fn test_streaming_chunk_deserialization() {
392 let json = r#"{
393 "choices": [{
394 "delta": {
395 "content": "Hello",
396 "tool_calls": []
397 }
398 }],
399 "usage": {
400 "prompt_tokens": 10,
401 "completion_tokens": 5,
402 "total_tokens": 15
403 }
404 }"#;
405 let chunk: StreamingCompletionChunk = serde_json::from_str(json).unwrap();
406 assert_eq!(chunk.choices.len(), 1);
407 assert_eq!(chunk.choices[0].delta.content, Some("Hello".to_string()));
408 assert!(chunk.usage.is_some());
409 }
410
411 #[test]
412 fn test_streaming_chunk_with_multiple_tool_call_deltas() {
413 let json_start = r#"{
415 "choices": [{
416 "delta": {
417 "content": null,
418 "tool_calls": [{
419 "index": 0,
420 "id": "call_123",
421 "function": {
422 "name": "get_weather",
423 "arguments": ""
424 }
425 }]
426 }
427 }],
428 "usage": null
429 }"#;
430
431 let json_chunk1 = r#"{
432 "choices": [{
433 "delta": {
434 "content": null,
435 "tool_calls": [{
436 "index": 0,
437 "id": null,
438 "function": {
439 "name": null,
440 "arguments": "{\"loc"
441 }
442 }]
443 }
444 }],
445 "usage": null
446 }"#;
447
448 let json_chunk2 = r#"{
449 "choices": [{
450 "delta": {
451 "content": null,
452 "tool_calls": [{
453 "index": 0,
454 "id": null,
455 "function": {
456 "name": null,
457 "arguments": "ation\":\"NYC\"}"
458 }
459 }]
460 }
461 }],
462 "usage": null
463 }"#;
464
465 let start_chunk: StreamingCompletionChunk = serde_json::from_str(json_start).unwrap();
467 assert_eq!(start_chunk.choices[0].delta.tool_calls.len(), 1);
468 assert_eq!(
469 start_chunk.choices[0].delta.tool_calls[0]
470 .function
471 .name
472 .as_ref()
473 .unwrap(),
474 "get_weather"
475 );
476
477 let chunk1: StreamingCompletionChunk = serde_json::from_str(json_chunk1).unwrap();
478 assert_eq!(chunk1.choices[0].delta.tool_calls.len(), 1);
479 assert_eq!(
480 chunk1.choices[0].delta.tool_calls[0]
481 .function
482 .arguments
483 .as_ref()
484 .unwrap(),
485 "{\"loc"
486 );
487
488 let chunk2: StreamingCompletionChunk = serde_json::from_str(json_chunk2).unwrap();
489 assert_eq!(chunk2.choices[0].delta.tool_calls.len(), 1);
490 assert_eq!(
491 chunk2.choices[0].delta.tool_calls[0]
492 .function
493 .arguments
494 .as_ref()
495 .unwrap(),
496 "ation\":\"NYC\"}"
497 );
498 }
499}