diff options
Diffstat (limited to 'src/provider.rs')
| -rw-r--r-- | src/provider.rs | 128 |
1 files changed, 101 insertions, 27 deletions
diff --git a/src/provider.rs b/src/provider.rs index 16c9013..b45282e 100644 --- a/src/provider.rs +++ b/src/provider.rs | |||
| @@ -115,6 +115,23 @@ impl SseDecoder { | |||
| 115 | self.buf.drain(..start); | 115 | self.buf.drain(..start); |
| 116 | out | 116 | out |
| 117 | } | 117 | } |
| 118 | |||
| 119 | /// Anything left when the connection closes without a final newline. | ||
| 120 | pub fn finish(&mut self) -> Vec<String> { | ||
| 121 | let mut out = Vec::new(); | ||
| 122 | if !self.buf.is_empty() { | ||
| 123 | let mut line = &self.buf[..]; | ||
| 124 | if line.last() == Some(&b'\r') { | ||
| 125 | line = &line[..line.len() - 1]; | ||
| 126 | } | ||
| 127 | if let Some(payload) = line.strip_prefix(b"data:") { | ||
| 128 | let payload = payload.strip_prefix(b" ").unwrap_or(payload); | ||
| 129 | out.push(String::from_utf8_lossy(payload).into_owned()); | ||
| 130 | } | ||
| 131 | self.buf.clear(); | ||
| 132 | } | ||
| 133 | out | ||
| 134 | } | ||
| 118 | } | 135 | } |
| 119 | 136 | ||
| 120 | const MAX_ATTEMPTS: usize = 4; | 137 | const MAX_ATTEMPTS: usize = 4; |
| @@ -290,9 +307,12 @@ pub fn chat( | |||
| 290 | let mut decoder = SseDecoder::new(); | 307 | let mut decoder = SseDecoder::new(); |
| 291 | let mut buf = [0u8; 8192]; | 308 | let mut buf = [0u8; 8192]; |
| 292 | let mut reader = resp.body_mut().as_reader(); | 309 | let mut reader = resp.body_mut().as_reader(); |
| 310 | let mut calls: std::collections::BTreeMap<usize, ToolCall> = std::collections::BTreeMap::new(); | ||
| 311 | let mut completed = false; | ||
| 293 | let mut done = false; | 312 | let mut done = false; |
| 313 | let mut dropped = 0usize; | ||
| 294 | 314 | ||
| 295 | while !done { | 315 | loop { |
| 296 | // Blocking reads mean an abort is only noticed when bytes arrive or the | 316 | // Blocking reads mean an abort is only noticed when bytes arrive or the |
| 297 | // per-read timeout fires. Good enough: the model streams constantly. | 317 | // per-read timeout fires. Good enough: the model streams constantly. |
| 298 | if cancel.load(Ordering::Relaxed) { | 318 | if cancel.load(Ordering::Relaxed) { |
| @@ -304,31 +324,83 @@ pub fn chat( | |||
| 304 | Err(e) => return Err(Error::Transport(e.to_string())), | 324 | Err(e) => return Err(Error::Transport(e.to_string())), |
| 305 | }; | 325 | }; |
| 306 | for data in decoder.feed(&buf[..n]) { | 326 | for data in decoder.feed(&buf[..n]) { |
| 307 | if data.is_empty() { | 327 | if handle_event(&data, &mut outcome, &mut calls, &mut completed, &mut dropped, sink) { |
| 308 | continue; | ||
| 309 | } | ||
| 310 | if data.trim() == "[DONE]" { | ||
| 311 | done = true; | 328 | done = true; |
| 312 | break; | 329 | break; |
| 313 | } | 330 | } |
| 314 | let chunk: Chunk = match serde_json::from_str(&data) { | 331 | } |
| 315 | Ok(c) => c, | 332 | if done { |
| 316 | // A malformed frame is dropped rather than killing the turn. | 333 | break; |
| 317 | Err(_) => continue, | 334 | } |
| 318 | }; | 335 | } |
| 319 | apply_chunk(&chunk, &mut outcome, sink); | 336 | |
| 337 | // A final `data:` frame with no trailing newline is legitimate. | ||
| 338 | if !done { | ||
| 339 | for data in decoder.finish() { | ||
| 340 | if handle_event(&data, &mut outcome, &mut calls, &mut completed, &mut dropped, sink) { | ||
| 341 | break; | ||
| 342 | } | ||
| 320 | } | 343 | } |
| 321 | } | 344 | } |
| 322 | 345 | ||
| 346 | outcome.tool_calls = calls.into_values().collect(); | ||
| 323 | if outcome.usage.as_ref().is_some_and(|u| u.is_null()) { | 347 | if outcome.usage.as_ref().is_some_and(|u| u.is_null()) { |
| 324 | outcome.usage = None; | 348 | outcome.usage = None; |
| 325 | } | 349 | } |
| 326 | 350 | ||
| 351 | if dropped > 0 { | ||
| 352 | eprintln!("agent686: ignored {dropped} malformed stream frame(s)"); | ||
| 353 | } | ||
| 354 | |||
| 355 | // A connection that closes early, or a 200 that is not SSE at all, must not | ||
| 356 | // be recorded as a complete answer. | ||
| 357 | if !completed { | ||
| 358 | return Err(Error::Transport(format!( | ||
| 359 | "stream ended before completion ({} bytes of text, {} tool call(s)); \ | ||
| 360 | the turn was not recorded as answered", | ||
| 361 | outcome.content.len(), | ||
| 362 | outcome.tool_calls.len() | ||
| 363 | ))); | ||
| 364 | } | ||
| 365 | |||
| 327 | sink.done(&outcome, started.elapsed()); | 366 | sink.done(&outcome, started.elapsed()); |
| 328 | Ok(outcome) | 367 | Ok(outcome) |
| 329 | } | 368 | } |
| 330 | 369 | ||
| 331 | fn apply_chunk(chunk: &Chunk, outcome: &mut Outcome, sink: &mut dyn Sink) { | 370 | fn handle_event( |
| 371 | data: &str, | ||
| 372 | outcome: &mut Outcome, | ||
| 373 | calls: &mut std::collections::BTreeMap<usize, ToolCall>, | ||
| 374 | completed: &mut bool, | ||
| 375 | dropped: &mut usize, | ||
| 376 | sink: &mut dyn Sink, | ||
| 377 | ) -> bool { | ||
| 378 | if data.is_empty() { | ||
| 379 | return false; | ||
| 380 | } | ||
| 381 | if data.trim() == "[DONE]" { | ||
| 382 | *completed = true; | ||
| 383 | return true; | ||
| 384 | } | ||
| 385 | match serde_json::from_str::<Chunk>(data) { | ||
| 386 | Ok(chunk) => { | ||
| 387 | if chunk.choices.iter().any(|choice| choice.finish_reason.is_some()) { | ||
| 388 | *completed = true; | ||
| 389 | } | ||
| 390 | apply_chunk(&chunk, outcome, calls, sink); | ||
| 391 | } | ||
| 392 | // Counted and reported rather than silently swallowed. | ||
| 393 | Err(_) => *dropped += 1, | ||
| 394 | } | ||
| 395 | false | ||
| 396 | } | ||
| 397 | |||
| 398 | fn apply_chunk( | ||
| 399 | chunk: &Chunk, | ||
| 400 | outcome: &mut Outcome, | ||
| 401 | calls: &mut std::collections::BTreeMap<usize, ToolCall>, | ||
| 402 | sink: &mut dyn Sink, | ||
| 403 | ) { | ||
| 332 | if let Some(usage) = &chunk.usage { | 404 | if let Some(usage) = &chunk.usage { |
| 333 | outcome.usage = Some(usage.clone()); | 405 | outcome.usage = Some(usage.clone()); |
| 334 | } | 406 | } |
| @@ -345,9 +417,9 @@ fn apply_chunk(chunk: &Chunk, outcome: &mut Outcome, sink: &mut dyn Sink) { | |||
| 345 | sink.text(t); | 417 | sink.text(t); |
| 346 | } | 418 | } |
| 347 | } | 419 | } |
| 348 | if let Some(calls) = &choice.delta.tool_calls { | 420 | if let Some(deltas) = &choice.delta.tool_calls { |
| 349 | for call in calls { | 421 | for delta in deltas { |
| 350 | accumulate_tool_call(&mut outcome.tool_calls, call); | 422 | accumulate_tool_call(calls, delta); |
| 351 | } | 423 | } |
| 352 | } | 424 | } |
| 353 | if let Some(finish) = &choice.finish_reason { | 425 | if let Some(finish) = &choice.finish_reason { |
| @@ -357,18 +429,19 @@ fn apply_chunk(chunk: &Chunk, outcome: &mut Outcome, sink: &mut dyn Sink) { | |||
| 357 | } | 429 | } |
| 358 | 430 | ||
| 359 | /// Tool call deltas arrive split across chunks and are keyed by `index`: the | 431 | /// Tool call deltas arrive split across chunks and are keyed by `index`: the |
| 360 | /// name and id usually come once, the arguments a fragment at a time. | 432 | /// name and id usually come once, the arguments a fragment at a time. A map |
| 361 | fn accumulate_tool_call(calls: &mut Vec<ToolCall>, delta: &ToolCallDelta) { | 433 | /// keyed by index means a missing or non-contiguous index cannot invent an |
| 362 | while calls.len() <= delta.index { | 434 | /// empty call or shift the others. |
| 363 | let index = calls.len(); | 435 | fn accumulate_tool_call( |
| 364 | calls.push(ToolCall { | 436 | calls: &mut std::collections::BTreeMap<usize, ToolCall>, |
| 365 | index, | 437 | delta: &ToolCallDelta, |
| 366 | id: String::new(), | 438 | ) { |
| 367 | name: String::new(), | 439 | let call = calls.entry(delta.index).or_insert_with(|| ToolCall { |
| 368 | arguments: String::new(), | 440 | index: delta.index, |
| 369 | }); | 441 | id: String::new(), |
| 370 | } | 442 | name: String::new(), |
| 371 | let call = &mut calls[delta.index]; | 443 | arguments: String::new(), |
| 444 | }); | ||
| 372 | if let Some(id) = &delta.id { | 445 | if let Some(id) = &delta.id { |
| 373 | call.id.push_str(id); | 446 | call.id.push_str(id); |
| 374 | } | 447 | } |
| @@ -434,6 +507,7 @@ struct Delta { | |||
| 434 | 507 | ||
| 435 | #[derive(Debug, Deserialize)] | 508 | #[derive(Debug, Deserialize)] |
| 436 | struct ToolCallDelta { | 509 | struct ToolCallDelta { |
| 510 | #[serde(default)] | ||
| 437 | index: usize, | 511 | index: usize, |
| 438 | #[serde(default)] | 512 | #[serde(default)] |
| 439 | id: Option<String>, | 513 | id: Option<String>, |
