| 163 | } |
| 164 | |
| 165 | pub(crate) fn convert_messages(&self, messages: &[Message]) -> Vec<serde_json::Value> { |
| 166 | messages |
| 167 | .iter() |
| 168 | .map(|msg| { |
| 169 | let content: serde_json::Value = if msg.content.len() == 1 { |
| 170 | match &msg.content[0] { |
| 171 | ContentBlock::Text { text } => serde_json::json!(text), |
| 172 | ContentBlock::ToolResult { |
| 173 | tool_use_id, |
| 174 | content, |
| 175 | .. |
| 176 | } => { |
| 177 | let content_str = match content { |
| 178 | ToolResultContentField::Text(s) => s.clone(), |
| 179 | ToolResultContentField::Blocks(blocks) => blocks |
| 180 | .iter() |
| 181 | .filter_map(|b| { |
| 182 | if let ToolResultContent::Text { text } = b { |
| 183 | Some(text.clone()) |
| 184 | } else { |
| 185 | None |
| 186 | } |
| 187 | }) |
| 188 | .collect::<Vec<_>>() |
| 189 | .join("\n"), |
| 190 | }; |
| 191 | return serde_json::json!({ |
| 192 | "role": "tool", |
| 193 | "tool_call_id": tool_use_id, |
| 194 | "content": content_str, |
| 195 | }); |
| 196 | } |
| 197 | _ => serde_json::json!(""), |
| 198 | } |
| 199 | } else { |
| 200 | serde_json::json!(msg |
| 201 | .content |
| 202 | .iter() |
| 203 | .map(|block| { |
| 204 | match block { |
| 205 | ContentBlock::Text { text } => serde_json::json!({ |
| 206 | "type": "text", |
| 207 | "text": text, |
| 208 | }), |
| 209 | ContentBlock::Image { source } => serde_json::json!({ |
| 210 | "type": "image_url", |
| 211 | "image_url": { |
| 212 | "url": format!( |
| 213 | "data:{};base64,{}", |
| 214 | source.media_type, source.data |
| 215 | ), |
| 216 | } |
| 217 | }), |
| 218 | ContentBlock::ToolUse { id, name, input } => serde_json::json!({ |
| 219 | "type": "function", |
| 220 | "id": id, |
| 221 | "function": { |
| 222 | "name": name, |