| 171 | } |
| 172 | |
| 173 | async fn chat_stream(&self, request: ChatRequest) -> Result<StreamResult, ProviderError> { |
| 174 | let url = self.build_url(&request.model, true); |
| 175 | |
| 176 | let mut stream_request = request; |
| 177 | stream_request.stream = Some(true); |
| 178 | let request_body = Self::build_request_body(&stream_request)?; |
| 179 | |
| 180 | let response = self |
| 181 | .client |
| 182 | .post(&url) |
| 183 | .header("api-key", &self.config.api_key) |
| 184 | .header("Content-Type", "application/json") |
| 185 | .header("Accept", "text/event-stream") |
| 186 | .json(&request_body) |
| 187 | .send() |
| 188 | .await |
| 189 | .map_err(|e| ProviderError::NetworkError(e.to_string()))?; |
| 190 | |
| 191 | if !response.status().is_success() { |
| 192 | let status = response.status(); |
| 193 | let body = response.text().await.unwrap_or_default(); |
| 194 | return Err(ProviderError::ApiError(format!("{}: {}", status, body))); |
| 195 | } |
| 196 | |
| 197 | let stream = response |
| 198 | .bytes_stream() |
| 199 | .map(move |chunk_result| match chunk_result { |
| 200 | Ok(bytes) => { |
| 201 | let text = String::from_utf8_lossy(&bytes); |
| 202 | for line in text.lines() { |
| 203 | if line.starts_with("data: ") { |
| 204 | let data = &line[6..]; |
| 205 | if let Some(event) = crate::stream::parse_openai_sse(data) { |
| 206 | return Ok(event); |
| 207 | } |
| 208 | } |
| 209 | } |
| 210 | Ok(StreamEvent::TextDelta(String::new())) |
| 211 | } |
| 212 | Err(e) => Err(ProviderError::StreamError(e.to_string())), |
| 213 | }); |
| 214 | |
| 215 | Ok(Box::pin(stream)) |
| 216 | } |
| 217 | } |
| 218 | |
| 219 | fn openai_reasoning_effort(model_id: &str, variant: Option<&str>) -> Option<&'static str> { |