Parse `OpenAI` response to `GraphBit` response
(&self, response: OpenAiResponse)
| 120 | |
| 121 | /// Parse `OpenAI` response to `GraphBit` response |
| 122 | fn parse_response(&self, response: OpenAiResponse) -> GraphBitResult<LlmResponse> { |
| 123 | let choice = response |
| 124 | .choices |
| 125 | .into_iter() |
| 126 | .next() |
| 127 | .ok_or_else(|| GraphBitError::llm_provider("openai", "No choices in response"))?; |
| 128 | |
| 129 | let mut content = choice.message.content; |
| 130 | if content.trim().is_empty() |
| 131 | && !choice |
| 132 | .message |
| 133 | .tool_calls |
| 134 | .as_ref() |
| 135 | .unwrap_or(&vec![]) |
| 136 | .is_empty() |
| 137 | { |
| 138 | content = "I'll help you with that using the available tools.".to_string(); |
| 139 | } |
| 140 | let tool_calls = choice |
| 141 | .message |
| 142 | .tool_calls |
| 143 | .unwrap_or_default() |
| 144 | .into_iter() |
| 145 | .map(|tc| { |
| 146 | // Production-grade argument parsing with error handling |
| 147 | let parameters = if tc.function.arguments.trim().is_empty() { |
| 148 | serde_json::Value::Object(serde_json::Map::new()) |
| 149 | } else { |
| 150 | match serde_json::from_str(&tc.function.arguments) { |
| 151 | Ok(params) => params, |
| 152 | Err(e) => { |
| 153 | tracing::warn!( |
| 154 | "Failed to parse tool call arguments for {}: {e}. Arguments: '{}'", |
| 155 | tc.function.name, |
| 156 | tc.function.arguments |
| 157 | ); |
| 158 | // Try to create a simple object with the raw arguments |
| 159 | serde_json::json!({ "raw_arguments": tc.function.arguments }) |
| 160 | } |
| 161 | } |
| 162 | }; |
| 163 | |
| 164 | LlmToolCall { |
| 165 | id: tc.id, |
| 166 | name: tc.function.name, |
| 167 | parameters, |
| 168 | } |
| 169 | }) |
| 170 | .collect(); |
| 171 | |
| 172 | let finish_reason = parse_finish_reason(choice.finish_reason.as_deref()); |
| 173 | |
| 174 | let usage = LlmUsage::new( |
| 175 | response.usage.prompt_tokens, |
| 176 | response.usage.completion_tokens, |
| 177 | ); |
| 178 | |
| 179 | Ok(LlmResponse::new(content, &self.model) |
no test coverage detected