| 87 | } |
| 88 | |
| 89 | async fn chat_stream(&self, request: ChatRequest) -> Result<StreamResult, ProviderError> { |
| 90 | let mut stream_request = request; |
| 91 | stream_request.stream = Some(true); |
| 92 | |
| 93 | let response = self |
| 94 | .client |
| 95 | .post(DEEPSEEK_API_URL) |
| 96 | .header("Authorization", format!("Bearer {}", self.api_key)) |
| 97 | .header("Content-Type", "application/json") |
| 98 | .header("Accept", "text/event-stream") |
| 99 | .json(&stream_request) |
| 100 | .send() |
| 101 | .await |
| 102 | .map_err(|e| ProviderError::NetworkError(e.to_string()))?; |
| 103 | |
| 104 | if !response.status().is_success() { |
| 105 | let status = response.status(); |
| 106 | let body = response.text().await.unwrap_or_default(); |
| 107 | return Err(ProviderError::ApiError(format!("{}: {}", status, body))); |
| 108 | } |
| 109 | |
| 110 | let stream = response |
| 111 | .bytes_stream() |
| 112 | .map(|chunk_result| match chunk_result { |
| 113 | Ok(bytes) => { |
| 114 | let text = String::from_utf8_lossy(&bytes); |
| 115 | for line in text.lines() { |
| 116 | if line.starts_with("data: ") { |
| 117 | let data = &line[6..]; |
| 118 | if let Some(event) = crate::stream::parse_openai_sse(data) { |
| 119 | return Ok(event); |
| 120 | } |
| 121 | } |
| 122 | } |
| 123 | Ok(StreamEvent::TextDelta(String::new())) |
| 124 | } |
| 125 | Err(e) => Err(ProviderError::StreamError(e.to_string())), |
| 126 | }); |
| 127 | |
| 128 | Ok(Box::pin(stream)) |
| 129 | } |
| 130 | } |