Skip to main content

gemini_proc_macros/
lib.rs

1use proc_macro::TokenStream;
2use quote::quote;
3use syn::{
4    Attribute, Data, DeriveInput, Fields, FnArg, ItemFn, Lit, Meta, Pat, Type, parse_macro_input,
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, with a custom callback for results.
149///
150/// # Usage
151/// `execute_function_calls_with_callback!(session, callback, function1, function2, ...)`
152///
153/// The `callback` should be a closure or function that takes `Result<serde_json::Value, String>`
154/// and returns `serde_json::Value`.
155///
156/// # Returns
157/// A `Vec<Option<Result<serde_json::Value, String>>>` containing the results of each function call.
158/// - `Some(Ok(value))` if the function was called and succeeded.
159/// - `Some(Err(err))` if the function was called but failed.
160/// - `None` if the function was not called.
161///
162/// # Note
163/// The `session` is automatically updated with the `FunctionResponse`.
164/// The `callback` is invoked with the result of the function execution (whether `Ok` or `Err`)
165/// and its return value is used to update the session.
166#[proc_macro]
167pub fn execute_function_calls_with_callback(input: TokenStream) -> TokenStream {
168    use syn::parse::{Parse, ParseStream};
169    use syn::{Expr, Token};
170
171    struct ExecuteWithCallbackInput {
172        session: Expr,
173        _comma1: Token![,],
174        callback: Expr,
175        _comma2: Token![,],
176        functions: syn::punctuated::Punctuated<syn::Path, Token![,]>,
177    }
178
179    impl Parse for ExecuteWithCallbackInput {
180        fn parse(input: ParseStream) -> syn::Result<Self> {
181            Ok(ExecuteWithCallbackInput {
182                session: input.parse()?,
183                _comma1: input.parse()?,
184                callback: input.parse()?,
185                _comma2: input.parse()?,
186                functions: input.parse_terminated(syn::Path::parse, Token![,])?,
187            })
188        }
189    }
190
191    let input = parse_macro_input!(input as ExecuteWithCallbackInput);
192    generate_execute_logic(&input.session, &input.callback, &input.functions)
193}
194
195/// Attribute macro to derive the `GeminiSchema` trait for a struct or enum.
196///
197/// This allows the type to be used in structured output (`set_json_mode`) or as a parameter
198/// in a `gemini_function`.
199///
200/// # Requirements
201/// - For structs: only named fields are supported.
202/// - For enums: only unit variants (no data) are supported.
203/// - Field/variant types must also implement `GeminiSchema`.
204/// - Doc comments on fields and variants are extracted as descriptions in the schema.
205///
206/// # Example
207/// ```ignore
208/// #[gemini_schema]
209/// struct SearchResult {
210///     /// The title of the page.
211///     title: String,
212///     /// The URL of the page.
213///     url: String,
214/// }
215/// ```
216#[proc_macro_attribute]
217pub fn gemini_schema(_attr: TokenStream, item: TokenStream) -> TokenStream {
218    let input = parse_macro_input!(item as DeriveInput);
219    let name = &input.ident;
220    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
221    let description = extract_doc_comments(&input.attrs);
222
223    let expanded = match &input.data {
224        Data::Struct(data) => {
225            let mut properties = Vec::new();
226            let mut required = Vec::new();
227
228            match &data.fields {
229                Fields::Named(fields) => {
230                    for field in &fields.named {
231                        let field_name = field.ident.as_ref().unwrap();
232                        let field_name_str = field_name.to_string();
233                        let field_type = &field.ty;
234                        let field_desc = extract_doc_comments(&field.attrs);
235
236                        if has_reference(field_type) {
237                            return syn::Error::new_spanned(
238                                field_type,
239                                "references are not supported in gemini_schema. Use owned types instead.",
240                            )
241                            .to_compile_error()
242                            .into();
243                        }
244
245                        let is_optional = is_option(field_type);
246
247                        properties.push(quote! {
248                            let mut schema = <#field_type as GeminiSchema>::gemini_schema();
249                            if !#field_desc.is_empty() {
250                                if let Some(obj) = schema.as_object_mut() {
251                                    obj.insert("description".to_string(), serde_json::json!(#field_desc));
252                                }
253                            }
254                            props.insert(#field_name_str.to_string(), schema);
255                        });
256
257                        if !is_optional {
258                            required.push(field_name_str);
259                        }
260                    }
261                }
262                _ => panic!("gemini_schema only supports named fields in structs"),
263            }
264
265            quote! {
266                impl #impl_generics GeminiSchema for #name #ty_generics #where_clause {
267                    fn gemini_schema() -> serde_json::Value {
268                        use serde_json::{json, Map};
269                        let mut props = Map::new();
270                        #(#properties)*
271
272                        let mut schema = json!({
273                            "type": "OBJECT",
274                            "properties": props,
275                            "required": [#(#required),*]
276                        });
277
278                        if !#description.is_empty() {
279                            if let Some(obj) = schema.as_object_mut() {
280                                obj.insert("description".to_string(), json!(#description));
281                            }
282                        }
283                        schema
284                    }
285                }
286            }
287        }
288        Data::Enum(data) => {
289            let mut variants = Vec::new();
290            for variant in &data.variants {
291                if !matches!(variant.fields, Fields::Unit) {
292                    panic!("gemini_schema only supports unit variants in enums");
293                }
294                variants.push(variant.ident.to_string());
295            }
296
297            quote! {
298                impl #impl_generics GeminiSchema for #name #ty_generics #where_clause {
299                    fn gemini_schema() -> serde_json::Value {
300                        use serde_json::json;
301                        let mut schema = json!({
302                            "type": "STRING",
303                            "enum": [#(#variants),*]
304                        });
305
306                        if !#description.is_empty() {
307                            if let Some(obj) = schema.as_object_mut() {
308                                obj.insert("description".to_string(), json!(#description));
309                            }
310                        }
311                        schema
312                    }
313                }
314            }
315        }
316        _ => panic!("gemini_schema only supports structs and enums"),
317    };
318
319    let output = quote! {
320        #input
321        #expanded
322    };
323
324    TokenStream::from(output)
325}
326
327fn extract_doc_comments(attrs: &[Attribute]) -> String {
328    let mut doc_comments = Vec::new();
329    for attr in attrs {
330        if attr.path().is_ident("doc") {
331            if let Meta::NameValue(nv) = &attr.meta {
332                if let syn::Expr::Lit(expr_lit) = &nv.value {
333                    if let Lit::Str(lit_str) = &expr_lit.lit {
334                        doc_comments.push(lit_str.value().trim().to_string());
335                    }
336                }
337            }
338        }
339    }
340    doc_comments.join("\n")
341}
342
343fn is_option(ty: &Type) -> bool {
344    if let Type::Path(tp) = ty {
345        if let Some(seg) = tp.path.segments.last() {
346            return seg.ident == "Option";
347        }
348    }
349    false
350}
351
352fn has_reference(ty: &Type) -> bool {
353    match ty {
354        Type::Reference(_) => true,
355        Type::Path(tp) => {
356            for seg in &tp.path.segments {
357                if let syn::PathArguments::AngleBracketed(ab) = &seg.arguments {
358                    for arg in &ab.args {
359                        if let syn::GenericArgument::Type(inner) = arg {
360                            if has_reference(inner) {
361                                return true;
362                            }
363                        }
364                    }
365                }
366            }
367            false
368        }
369        _ => false,
370    }
371}
372
373/// Macro to execute function calls requested by Gemini and update the session history.
374///
375/// # Usage
376/// `execute_function_calls!(session, function1, function2, ...)`
377///
378/// # Returns
379/// A `Vec<Option<Result<serde_json::Value, String>>>` containing the results of each function call.
380/// The length of the vector matches the number of functions provided.
381/// - `Some(Ok(value))` if the function was called and succeeded.
382/// - `Some(Err(err))` if the function was called but failed.
383/// - `None` if the function was not called.
384///
385/// # Note
386/// The `session` is automatically updated with the `FunctionResponse` for successful calls.
387/// If a function call fails, the error is converted to a JSON object `{"Error": error_message}`
388/// and sent to the session as the function response.
389#[proc_macro]
390pub fn execute_function_calls(input: TokenStream) -> TokenStream {
391    use syn::parse::{Parse, ParseStream};
392    use syn::{Expr, Token};
393
394    struct ExecuteInput {
395        session: Expr,
396        _comma: Token![,],
397        functions: syn::punctuated::Punctuated<syn::Path, Token![,]>,
398    }
399
400    impl Parse for ExecuteInput {
401        fn parse(input: ParseStream) -> syn::Result<Self> {
402            Ok(ExecuteInput {
403                session: input.parse()?,
404                _comma: input.parse()?,
405                functions: input.parse_terminated(syn::Path::parse, Token![,])?,
406            })
407        }
408    }
409
410    let input = parse_macro_input!(input as ExecuteInput);
411    let callback: Expr = syn::parse_quote! {
412        |result: Result<gemini_client_api::serde_json::Value, String>| {
413            match result {
414                Ok(value) => value,
415                Err(e) => gemini_client_api::serde_json::json!({"Error": e}),
416            }
417        }
418    };
419
420    generate_execute_logic(&input.session, &callback, &input.functions)
421}
422
423fn generate_execute_logic(
424    session: &syn::Expr,
425    callback: &syn::Expr,
426    functions: &syn::punctuated::Punctuated<syn::Path, syn::Token![,]>,
427) -> TokenStream {
428    let num_funcs = functions.len();
429
430    let match_arms = functions.iter().enumerate().map(|(i, path)| {
431        let name_str = path.segments.last().unwrap().ident.to_string();
432        quote! {
433            #name_str => {
434                let args = call.args().clone().unwrap_or(gemini_client_api::serde_json::json!({}));
435                let fut: gemini_client_api::futures::future::BoxFuture<'static, (usize, String, Result<gemini_client_api::serde_json::Value, String>)> = Box::pin(async move {
436                    (#i, #name_str.to_string(), #path::execute(args).await)
437                });
438                futures.push(fut);
439            }
440        }
441    });
442
443    let expanded = quote! {
444        {
445            let mut results_array = vec![None; #num_funcs];
446            // Define callback here to ensure it's available
447            let mut result_callback = #callback;
448
449            if let Some(chat) = #session.get_last_chat() {
450                let mut futures = Vec::new();
451                for part in chat.parts() {
452                    if let gemini_client_api::gemini::types::request::PartType::FunctionCall(call) = part.data() {
453                        match call.name().as_str() {
454                            #(#match_arms)*
455                            _ => {}
456                        }
457                    }
458                }
459                if !futures.is_empty() {
460                    let results = gemini_client_api::futures::future::join_all(futures).await;
461                    for (idx, name, res) in results {
462                        // Invoke callback regardless of success or failure
463                        let val_to_add = result_callback(res.clone());
464
465                        if let Err(e) = #session.add_function_response(name.clone(), val_to_add) {
466                             results_array[idx] = Some(Err(format!(
467                                "failed to add function response for `{}`: {}",
468                                name, e
469                            )));
470                            continue;
471                        }
472                        results_array[idx] = Some(res);
473                    }
474                }
475            }
476            results_array
477        }
478    };
479
480    TokenStream::from(expanded)
481}