Skip to main content

gproxy_protocol/adapt/generate/resources/
chat.rs

1use super::*;
2use crate::wire::{DeclaredFields, openai::chat as h};
3
4impl<R: ResourceAccess> GenerationResources<'_, R> {
5    pub async fn chat(
6        &self,
7        input: h::GenerateContentRequestBody,
8    ) -> Result<h::GenerateContentRequestBody, TransformError> {
9        let mut input = input.into_declared();
10        let mut budget = self.budget();
11        for message in &mut input.messages {
12            if let h::ChatMessage::User(message) = message
13                && let h::UserContent::Parts(parts) = &mut message.content
14            {
15                for part in parts {
16                    match part {
17                        h::UserContentPart::Image(part)
18                            if !part.image_url.url.starts_with("data:") =>
19                        {
20                            let media = budget
21                                .read(ResourceReference::Url(part.image_url.url.clone()), true)
22                                .await?;
23                            part.image_url.url = media.data_uri();
24                        }
25                        h::UserContentPart::File(part) if part.file.file_id.is_some() => {
26                            if part.file.file_data.is_some() {
27                                return Err(TransformError::shape(
28                                    "file",
29                                    "ambiguous inline data and native ID",
30                                ));
31                            }
32                            let media = budget
33                                .read(
34                                    ResourceReference::Id(
35                                        part.file.file_id.clone().expect("matched"),
36                                    ),
37                                    false,
38                                )
39                                .await?;
40                            part.file.file_data = Some(media.data_uri());
41                            part.file.file_id = None;
42                            if part.file.filename.is_none() {
43                                part.file.filename = media.filename;
44                            }
45                        }
46                        _ => {}
47                    }
48                }
49            }
50        }
51        Ok(input)
52    }
53}