gemini_genai_rs/embed/
mod.rs1use serde::{Deserialize, Serialize};
6
7use crate::client::Client;
8use crate::client::http::HttpError;
9use crate::protocol::types::{Content, ModelId};
10use crate::transport::auth::ServiceEndpoint;
11
12#[derive(Debug, Clone)]
14pub struct EmbedContentConfig {
15 pub content: Content,
17 pub task_type: Option<TaskType>,
19 pub title: Option<String>,
21 pub output_dimensionality: Option<u32>,
23}
24
25impl EmbedContentConfig {
26 pub fn from_text(text: impl Into<String>) -> Self {
28 Self {
29 content: Content::user(text),
30 task_type: None,
31 title: None,
32 output_dimensionality: None,
33 }
34 }
35
36 pub fn task_type(mut self, task_type: TaskType) -> Self {
38 self.task_type = Some(task_type);
39 self
40 }
41
42 pub fn title(mut self, title: impl Into<String>) -> Self {
44 self.title = Some(title.into());
45 self
46 }
47
48 pub fn output_dimensionality(mut self, dim: u32) -> Self {
50 self.output_dimensionality = Some(dim);
51 self
52 }
53}
54
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
57#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
58pub enum TaskType {
59 RetrievalQuery,
61 RetrievalDocument,
63 SemanticSimilarity,
65 Classification,
67 Clustering,
69 QuestionAnswering,
71 FactVerification,
73}
74
75#[derive(Debug, Clone, Serialize, Deserialize)]
77#[serde(rename_all = "camelCase")]
78pub struct EmbedContentResponse {
79 pub embedding: ContentEmbedding,
81}
82
83#[derive(Debug, Clone, Serialize, Deserialize)]
85#[serde(rename_all = "camelCase")]
86pub struct ContentEmbedding {
87 pub values: Vec<f32>,
89}
90
91#[derive(Debug, thiserror::Error)]
93pub enum EmbedError {
94 #[error(transparent)]
95 Http(#[from] HttpError),
97 #[error("Failed to parse response: {0}")]
98 Parse(#[from] serde_json::Error),
100 #[error("Failed to serialize request: {0}")]
101 Serialize(#[source] serde_json::Error),
103 #[error("Auth error: {0}")]
104 Auth(#[from] crate::session::AuthError),
106}
107
108impl Client {
109 pub async fn embed_content(
111 &self,
112 text: impl Into<String>,
113 ) -> Result<EmbedContentResponse, EmbedError> {
114 self.embed_content_with(EmbedContentConfig::from_text(text), None)
115 .await
116 }
117
118 pub async fn embed_content_with(
120 &self,
121 config: EmbedContentConfig,
122 model: Option<&ModelId>,
123 ) -> Result<EmbedContentResponse, EmbedError> {
124 let model = model.unwrap_or(self.default_model());
125 let url = self.rest_url_for(ServiceEndpoint::EmbedContent, model);
126 let headers = self.auth_headers().await?;
127
128 let mut body = serde_json::json!({
129 "content": config.content,
130 });
131
132 if let Some(task_type) = config.task_type {
133 body["taskType"] = serde_json::to_value(task_type).map_err(EmbedError::Serialize)?;
134 }
135 if let Some(title) = config.title {
136 body["title"] = serde_json::Value::String(title);
137 }
138 if let Some(dim) = config.output_dimensionality {
139 body["outputDimensionality"] = serde_json::json!(dim);
140 }
141
142 let json = self.http_client().post_json(&url, headers, &body).await?;
143 Ok(serde_json::from_value(json)?)
144 }
145}
146
147#[cfg(test)]
148mod tests {
149 use super::*;
150
151 #[test]
152 fn parse_embed_response() {
153 let json = serde_json::json!({
154 "embedding": {
155 "values": [0.1, 0.2, 0.3, 0.4]
156 }
157 });
158 let resp: EmbedContentResponse = serde_json::from_value(json).unwrap();
159 assert_eq!(resp.embedding.values.len(), 4);
160 assert!((resp.embedding.values[0] - 0.1).abs() < f32::EPSILON);
161 }
162
163 #[test]
164 fn embed_config_builder() {
165 let config = EmbedContentConfig::from_text("Hello")
166 .task_type(TaskType::RetrievalQuery)
167 .output_dimensionality(256);
168 assert_eq!(config.task_type, Some(TaskType::RetrievalQuery));
169 assert_eq!(config.output_dimensionality, Some(256));
170 }
171}