| 175 | } |
| 176 | |
| 177 | pub fn parse_openai_sse(data: &str) -> Option<StreamEvent> { |
| 178 | if data == "[DONE]" { |
| 179 | return Some(StreamEvent::Done); |
| 180 | } |
| 181 | |
| 182 | let event: OpenAISSEvent = serde_json::from_str(data).ok()?; |
| 183 | |
| 184 | for choice in event.choices { |
| 185 | if let Some(delta) = &choice.delta { |
| 186 | if let Some(content) = &delta.content { |
| 187 | if !content.is_empty() { |
| 188 | return Some(StreamEvent::TextDelta(content.clone())); |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | if let Some(tool_calls) = &delta.tool_calls { |
| 193 | for tc in tool_calls { |
| 194 | if let Some(func) = &tc.function { |
| 195 | if let Some(name) = &func.name { |
| 196 | return Some(StreamEvent::ToolCallStart { |
| 197 | id: openai_tool_call_id(tc), |
| 198 | name: name.clone(), |
| 199 | }); |
| 200 | } |
| 201 | if let Some(args) = &func.arguments { |
| 202 | if !args.is_empty() { |
| 203 | return Some(StreamEvent::ToolCallDelta { |
| 204 | id: openai_tool_call_id(tc), |
| 205 | input: args.clone(), |
| 206 | }); |
| 207 | } |
| 208 | } |
| 209 | } |
| 210 | } |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | if let Some(reason) = &choice.finish_reason { |
| 215 | if reason == "tool_calls" { |
| 216 | return Some(StreamEvent::Done); |
| 217 | } |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | if let Some(usage) = event.usage { |
| 222 | return Some(StreamEvent::Usage { |
| 223 | prompt_tokens: usage.prompt_tokens, |
| 224 | completion_tokens: usage.completion_tokens, |
| 225 | }); |
| 226 | } |
| 227 | |
| 228 | None |
| 229 | } |
| 230 | |
| 231 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 232 | pub struct AnthropicEvent { |