generate_enum_info!() { /* proc-macro */ }
Expand description
A procedural macro to generate information about an enum.
This macro generates code that uses the EnumDescriptor
and VariantDescriptors
traits to extract information about an enum, including its name, variant names,
and their corresponding token counts. Additionally, it uses the FunctionArgument
trait
to fetch the argument description. All this information is serialized into JSON.
The macro returns a tuple containing the JSON and the total token count.
Usage
The generated code will look like this:
{
use serde_json::Value;
let mut total_tokens = 0;
let (arg_desc, arg_count) = <MyEnum as ::openai_func_enums::FunctionArgument>::argument_description_with_token_count();
total_tokens += arg_count;
// When this is consumed by the function that creates the overall function,
// we are going to be requiring all the arguments, which means we will repeat
// their names in the "required" part of openai's function schema. So we will
// count the tokens associated with this enum name twice here.
let enum_name = <MyEnum as EnumDescriptor>::name_with_token_count();
total_tokens += enum_name.1;
total_tokens += enum_name.1;
let enum_variants = <MyEnum as VariantDescriptors>::variant_names_with_token_counts();
total_tokens += enum_variants.iter().map(|(_, token_count)| *token_count).sum::<usize>();
let json_enum = serde_json::json!({
enum_name.0: {
"type": "string",
"enum": enum_variants.iter().map(|(name, _)| name.clone()).collect::<Vec<_>>(),
"description": arg_desc,
}
});
total_tokens += 11;
(json_enum, total_tokens)
}
Note: It is assumed that the enum implements the EnumDescriptor
and VariantDescriptors
traits.
The actual token count is computed during compile time using these traits’ methods.