Skip to main content

gemini_proc_macros/
lib.rs

1use proc_macro::TokenStream;
2use quote::quote;
3use syn::{
4    parse_macro_input, Attribute, Data, DeriveInput, Fields, FnArg, ItemFn, Lit, Meta, Pat, Type,
5};
6
7/// Attribute macro to mark a function as callable by Gemini.
8///
9/// This macro generates a schema for the function and an `execute` method to call it
10/// with JSON arguments.
11///
12/// # Requirements
13/// - Function arguments must be owned types that implement `GeminiSchema` (e.g., `String`, `i32`, `bool`).
14/// - References are not supported.
15/// - The function can be `async` and can return a `Result` (the `Ok` value must implement `Serialize`).
16///
17/// # Example
18/// ```ignore
19/// #[gemini_function]
20/// /// Returns the current weather for a location.
21/// fn get_weather(location: String) -> String {
22///     format!("The weather in {} is sunny.", location)
23/// }
24/// ```
25#[proc_macro_attribute]
26pub fn gemini_function(_attr: TokenStream, item: TokenStream) -> TokenStream {
27    let mut input_fn = parse_macro_input!(item as ItemFn);
28    let fn_name = &input_fn.sig.ident;
29    let fn_description = extract_doc_comments(&input_fn.attrs);
30
31    let mut properties = Vec::new();
32    let mut required = Vec::new();
33    let mut param_names = Vec::new();
34    let mut param_types = Vec::new();
35
36    for arg in input_fn.sig.inputs.iter_mut() {
37        if let FnArg::Typed(pat_type) = arg {
38            if let Pat::Ident(pat_ident) = &*pat_type.pat {
39                let param_name = pat_ident.ident.clone();
40                let param_name_str = param_name.to_string();
41                let param_type = (*pat_type.ty).clone();
42                let param_desc = extract_doc_comments(&pat_type.attrs);
43
44                if has_reference(&param_type) {
45                    return syn::Error::new_spanned(
46                        &param_type,
47                        "references are not supported in gemini_function. Use owned types like String instead.",
48                    )
49                    .to_compile_error()
50                    .into();
51                }
52
53                // Remove doc attributes from the function signature so it compiles
54                pat_type.attrs.retain(|attr| !attr.path().is_ident("doc"));
55
56                let is_optional = is_option(&param_type);
57
58                properties.push(quote! {
59                    let mut schema = <#param_type as GeminiSchema>::gemini_schema();
60                    if !#param_desc.is_empty() {
61                        if let Some(obj) = schema.as_object_mut() {
62                            obj.insert("description".to_string(), serde_json::json!(#param_desc));
63                        }
64                    }
65                    props.insert(#param_name_str.to_string(), schema);
66                });
67
68                if !is_optional {
69                    required.push(param_name_str);
70                }
71
72                param_names.push(param_name);
73                param_types.push(param_type);
74            }
75        }
76    }
77
78    let fn_name_str = fn_name.to_string();
79    let is_async = input_fn.sig.asyncness.is_some();
80    let call_await = if is_async {
81        quote! { .await }
82    } else {
83        quote! {}
84    };
85
86    let is_result = match &input_fn.sig.output {
87        syn::ReturnType::Default => false,
88        syn::ReturnType::Type(_, ty) => {
89            let s = quote!(#ty).to_string();
90            s.contains("Result")
91        }
92    };
93
94    let result_handling = if is_result {
95        quote! {
96            match result {
97                Ok(v) => Ok(serde_json::json!(v)),
98                Err(e) => Err(e.to_string()),
99            }
100        }
101    } else {
102        quote! {
103            Ok(serde_json::json!(result))
104        }
105    };
106
107    let expanded = quote! {
108        #input_fn
109
110        #[allow(non_camel_case_types)]
111        pub struct #fn_name { }
112
113        impl GeminiSchema for #fn_name {
114            fn gemini_schema() -> serde_json::Value {
115                use serde_json::{json, Map};
116                let mut props = Map::new();
117                #(#properties)*
118
119                json!({
120                    "name": #fn_name_str,
121                    "description": #fn_description,
122                    "parameters": {
123                        "type": "OBJECT",
124                        "properties": props,
125                        "required": [#(#required),*]
126                    }
127                })
128            }
129        }
130
131        impl #fn_name {
132            pub async fn execute(args: serde_json::Value) -> Result<serde_json::Value, String> {
133                use serde::Deserialize;
134                #[derive(Deserialize)]
135                struct Args {
136                    #(#param_names: #param_types,)*
137                }
138                let args = Args::deserialize(&args).map_err(|e| e.to_string())?;
139                let result = #fn_name(#(args.#param_names),*) #call_await;
140                #result_handling
141            }
142        }
143    };
144
145    TokenStream::from(expanded)
146}
147
148/// Macro to execute function calls requested by Gemini and update the session history.
149///
150/// # Usage
151/// `execute_function_calls!(session, function1, function2, ...)`
152///
153/// # Returns
154/// A `Vec<Option<Result<serde_json::Value, String>>>` containing the results of each function call.
155/// The length of the vector matches the number of functions provided.
156/// - `Some(Ok(value))` if the function was called and succeeded.
157/// - `Some(Err(err))` if the function was called but failed.
158/// - `None` if the function was not called.
159///
160/// # Note
161/// The `session` is automatically updated with the `FunctionResponse` for successful calls.
162#[proc_macro]
163pub fn execute_function_calls(input: TokenStream) -> TokenStream {
164    use syn::parse::{Parse, ParseStream};
165    use syn::{Expr, Token};
166
167    struct ExecuteInput {
168        session: Expr,
169        _comma: Token![,],
170        functions: syn::punctuated::Punctuated<syn::Path, Token![,]>,
171    }
172
173    impl Parse for ExecuteInput {
174        fn parse(input: ParseStream) -> syn::Result<Self> {
175            Ok(ExecuteInput {
176                session: input.parse()?,
177                _comma: input.parse()?,
178                functions: input.parse_terminated(syn::Path::parse, Token![,])?,
179            })
180        }
181    }
182
183    let input = parse_macro_input!(input as ExecuteInput);
184    let session = &input.session;
185    let functions = &input.functions;
186    let num_funcs = functions.len();
187
188    let match_arms = functions.iter().enumerate().map(|(i, path)| {
189        let name_str = path.segments.last().unwrap().ident.to_string();
190        quote! {
191            #name_str => {
192                let args = call.args().clone().unwrap_or(gemini_client_api::serde_json::json!({}));
193                let fut: gemini_client_api::futures::future::BoxFuture<'static, (usize, String, Result<gemini_client_api::serde_json::Value, String>)> = Box::pin(async move {
194                    (#i, #name_str.to_string(), #path::execute(args).await)
195                });
196                futures.push(fut);
197            }
198        }
199    });
200
201    let expanded = quote! {
202        {
203            let mut results_array = vec![None; #num_funcs];
204            if let Some(chat) = #session.get_last_chat() {
205                let mut futures = Vec::new();
206                for part in chat.parts() {
207                    if let gemini_client_api::gemini::types::request::PartType::FunctionCall(call) = part.data() {
208                        match call.name().as_str() {
209                            #(#match_arms)*
210                            _ => {}
211                        }
212                    }
213                }
214                if !futures.is_empty() {
215                    let results = gemini_client_api::futures::future::join_all(futures).await;
216                    for (idx, name, res) in results {
217                        if let Ok(ref val) = res {
218                            if let Err(e) = #session.add_function_response(name.clone(), val.clone()) {
219                                results_array[idx] = Some(Err(format!(
220                                    "failed to add function response for `{}`: {}",
221                                    name, e
222                                )));
223                                continue;
224                            }
225                        }
226                        results_array[idx] = Some(res);
227                    }
228                }
229            }
230            results_array
231        }
232    };
233
234    TokenStream::from(expanded)
235}
236
237/// Attribute macro to derive the `GeminiSchema` trait for a struct or enum.
238///
239/// This allows the type to be used in structured output (`set_json_mode`) or as a parameter
240/// in a `gemini_function`.
241///
242/// # Requirements
243/// - For structs: only named fields are supported.
244/// - For enums: only unit variants (no data) are supported.
245/// - Field/variant types must also implement `GeminiSchema`.
246/// - Doc comments on fields and variants are extracted as descriptions in the schema.
247///
248/// # Example
249/// ```ignore
250/// #[gemini_schema]
251/// struct SearchResult {
252///     /// The title of the page.
253///     title: String,
254///     /// The URL of the page.
255///     url: String,
256/// }
257/// ```
258#[proc_macro_attribute]
259pub fn gemini_schema(_attr: TokenStream, item: TokenStream) -> TokenStream {
260    let input = parse_macro_input!(item as DeriveInput);
261    let name = &input.ident;
262    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
263    let description = extract_doc_comments(&input.attrs);
264
265    let expanded = match &input.data {
266        Data::Struct(data) => {
267            let mut properties = Vec::new();
268            let mut required = Vec::new();
269
270            match &data.fields {
271                Fields::Named(fields) => {
272                    for field in &fields.named {
273                        let field_name = field.ident.as_ref().unwrap();
274                        let field_name_str = field_name.to_string();
275                        let field_type = &field.ty;
276                        let field_desc = extract_doc_comments(&field.attrs);
277
278                        if has_reference(field_type) {
279                            return syn::Error::new_spanned(
280                                field_type,
281                                "references are not supported in gemini_schema. Use owned types instead.",
282                            )
283                            .to_compile_error()
284                            .into();
285                        }
286
287                        let is_optional = is_option(field_type);
288
289                        properties.push(quote! {
290                            let mut schema = <#field_type as GeminiSchema>::gemini_schema();
291                            if !#field_desc.is_empty() {
292                                if let Some(obj) = schema.as_object_mut() {
293                                    obj.insert("description".to_string(), serde_json::json!(#field_desc));
294                                }
295                            }
296                            props.insert(#field_name_str.to_string(), schema);
297                        });
298
299                        if !is_optional {
300                            required.push(field_name_str);
301                        }
302                    }
303                }
304                _ => panic!("gemini_schema only supports named fields in structs"),
305            }
306
307            quote! {
308                impl #impl_generics GeminiSchema for #name #ty_generics #where_clause {
309                    fn gemini_schema() -> serde_json::Value {
310                        use serde_json::{json, Map};
311                        let mut props = Map::new();
312                        #(#properties)*
313
314                        let mut schema = json!({
315                            "type": "OBJECT",
316                            "properties": props,
317                            "required": [#(#required),*]
318                        });
319
320                        if !#description.is_empty() {
321                            if let Some(obj) = schema.as_object_mut() {
322                                obj.insert("description".to_string(), json!(#description));
323                            }
324                        }
325                        schema
326                    }
327                }
328            }
329        }
330        Data::Enum(data) => {
331            let mut variants = Vec::new();
332            for variant in &data.variants {
333                if !matches!(variant.fields, Fields::Unit) {
334                    panic!("gemini_schema only supports unit variants in enums");
335                }
336                variants.push(variant.ident.to_string());
337            }
338
339            quote! {
340                impl #impl_generics GeminiSchema for #name #ty_generics #where_clause {
341                    fn gemini_schema() -> serde_json::Value {
342                        use serde_json::json;
343                        let mut schema = json!({
344                            "type": "STRING",
345                            "enum": [#(#variants),*]
346                        });
347
348                        if !#description.is_empty() {
349                            if let Some(obj) = schema.as_object_mut() {
350                                obj.insert("description".to_string(), json!(#description));
351                            }
352                        }
353                        schema
354                    }
355                }
356            }
357        }
358        _ => panic!("gemini_schema only supports structs and enums"),
359    };
360
361    let output = quote! {
362        #input
363        #expanded
364    };
365
366    TokenStream::from(output)
367}
368
369fn extract_doc_comments(attrs: &[Attribute]) -> String {
370    let mut doc_comments = Vec::new();
371    for attr in attrs {
372        if attr.path().is_ident("doc") {
373            if let Meta::NameValue(nv) = &attr.meta {
374                if let syn::Expr::Lit(expr_lit) = &nv.value {
375                    if let Lit::Str(lit_str) = &expr_lit.lit {
376                        doc_comments.push(lit_str.value().trim().to_string());
377                    }
378                }
379            }
380        }
381    }
382    doc_comments.join("\n")
383}
384
385fn is_option(ty: &Type) -> bool {
386    if let Type::Path(tp) = ty {
387        if let Some(seg) = tp.path.segments.last() {
388            return seg.ident == "Option";
389        }
390    }
391    false
392}
393
394fn has_reference(ty: &Type) -> bool {
395    match ty {
396        Type::Reference(_) => true,
397        Type::Path(tp) => {
398            for seg in &tp.path.segments {
399                if let syn::PathArguments::AngleBracketed(ab) = &seg.arguments {
400                    for arg in &ab.args {
401                        if let syn::GenericArgument::Type(inner) = arg {
402                            if has_reference(inner) {
403                                return true;
404                            }
405                        }
406                    }
407                }
408            }
409            false
410        }
411        _ => false,
412    }
413}