copilot_rs_macro/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
use std::collections::HashMap;
use std::str::FromStr;

use anyhow::Result;
use darling::{ast::NestedMeta, FromMeta};
use darling::{FromDeriveInput, FromField};
use maplit::hashmap;
use proc_macro::TokenStream;
use quote::quote;
use serde::{Deserialize, Serialize};
use syn::{parse_macro_input, DeriveInput, Ident};
use syn::{Expr, ItemFn, LitStr, Stmt};
#[proc_macro_attribute]
pub fn complete(attr: TokenStream, item: TokenStream) -> proc_macro::TokenStream {
    match common_simple(attr, item) {
        Ok(output) => output,
        Err(e) => TokenStream::from_str(e.to_string().as_str()).unwrap(),
    }
}
#[derive(Debug, FromMeta)]
struct MacroArgs {
    client: String,
    model: Option<String>,
    temperature: Option<f32>,
    max_tokens: Option<u32>,
    tools: Vec<LitStr>,
}

fn common_simple(attr: TokenStream, item: TokenStream) -> Result<TokenStream> {
    let attr_args = NestedMeta::parse_meta_list(attr.into())?;
    let args = MacroArgs::from_list(&attr_args).unwrap();

    let client = Ident::new(&args.client, proc_macro::Span::call_site().into());

    let mut item: ItemFn = syn::parse(item)?;

    let method_name = item.sig.ident.to_string();
    let mut is_async = item.sig.asyncness.is_some();
    let mut block = item.block;

    let new_chat_method = format!("chat_{}", method_name);

    if let Stmt::Expr(expr, _) = block.stmts.last_mut().unwrap() {
        if let Expr::Await(m) = expr {
            if let Expr::MethodCall(m) = m.base.as_mut() {
                let method = &m.method;
                if method == "async_chat" {
                    let ident = Ident::new(&new_chat_method, method.span());
                    m.method = ident;
                }
            }
        }
        if let Expr::MethodCall(m) = expr {
            let method = &m.method;
            if method == "chat" {
                let ident = Ident::new(&new_chat_method, method.span());
                m.method = ident;
                is_async = false;
            }
        }
    }

    // 更新函数体
    item.block = block;

    let new_chat_method_ident = Ident::new(&new_chat_method, proc_macro::Span::call_site().into());

    let new_chat_trait_name_ident = Ident::new(
        &format!("RealChat{}", uuid::Uuid::new_v4()).replace("-", ""),
        proc_macro::Span::call_site().into(),
    );

    if is_async {
        let trait_def = quote! {
            trait #new_chat_trait_name_ident {
                async fn #new_chat_method_ident(&self) -> String;
            }
        };
        let client_model = client;
        let impl_def = quote! {
            impl #new_chat_trait_name_ident for Vec<copilot_rs::PromptMessage> {
                async fn #new_chat_method_ident(&self) -> String {
                    let model = #client_model();
                    copilot_rs::async_chat(&model, &self).await
                }
            }
        };
        let expanded = quote! {
            #item

            #trait_def

            #impl_def
        };

        Ok(expanded.into())
    } else {
        let trait_def = quote! {
            trait #new_chat_trait_name_ident {
                fn #new_chat_method_ident(&self) -> String;
            }
        };
        let client_model = client;
        let model = args.model.clone().unwrap_or_default();
        let temperature = args.temperature.unwrap_or(0.7);
        let max_tokens = args.max_tokens.unwrap_or(1024);
        let idents_iter = args
            .tools
            .iter()
            .map(|v| Ident::new(v.value().as_str(), v.span()));

        let tools = {
            let tools = idents_iter.clone().collect::<Vec<_>>();
            quote! {
                vec![#(#tools::desc()),*]
            }
        };
        let functions = {
            let tools = idents_iter.clone().collect::<Vec<_>>();
            quote! {
                vec![#(#tools::inject),*]
            }
        };
        let keys = {
            let tools = idents_iter.clone().collect::<Vec<_>>();
            quote! {
                vec![#(#tools::key()),*]
            }
        };

        let impl_def = quote! {
            impl #new_chat_trait_name_ident for Vec<copilot_rs::PromptMessage> {
                fn #new_chat_method_ident(&self) -> String {
                    let client = #client_model();
                    let model = #model;
                    let temperature = #temperature;
                    let max_tokens = #max_tokens;
                    let r = #tools;
                    let f = #functions;
                    let k = #keys;
                    copilot_rs::chat(&client,&self,model,temperature, max_tokens,r,k,f)
                }
            }
        };
        let expanded = quote! {
            #item

            #trait_def

            #impl_def
        };

        Ok(expanded.into())
    }
}

#[derive(FromDeriveInput, Debug)]
#[darling(attributes(property), forward_attrs(allow, deny))]
struct FunctionToolOptions {
    ident: Ident,
    data: darling::ast::Data<(), FunctionToolProperties>,
    #[darling(default)]
    desc: String,
}

#[derive(Debug, FromField)]
#[darling(attributes(property), forward_attrs(allow, deny))]
struct FunctionToolProperties {
    ident: Option<Ident>,
    ty: syn::Type,
    desc: String,
    #[darling(default)]
    choices: Vec<LitStr>,
}

#[proc_macro_derive(FunctionTool, attributes(property))]
pub fn derive_function_tool(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);

    let parsed = FunctionToolOptions::from_derive_input(&input).unwrap();

    let struct_name = &parsed.ident;
    let struct_desc = parsed.desc;

    let properties = parsed
        .data
        .take_struct()
        .map(|v| v.fields)
        .map(|v| {
            v.iter().fold(HashMap::new(), |mut acc, field| {
                let name = field
                    .ident
                    .as_ref()
                    .map(|v| v.to_string())
                    .unwrap_or_default();
                let ty = match &field.ty {
                    syn::Type::Path(p) => p
                        .path
                        .segments
                        .first()
                        .map(|seg| seg.ident.to_string())
                        .unwrap_or_else(|| "unknown".to_string()),
                    _ => "unknown".to_string(),
                };
                let mut prop = Property::default();
                prop.r#type = ty;
                prop.description = field.desc.clone();
                prop.choices = if field.choices.is_empty() {
                    None
                } else {
                    Some(field.choices.iter().map(|v| v.value()).collect())
                };
                acc.insert(name, prop);
                acc
            })
        })
        .unwrap_or_default();
    let required = properties
        .iter()
        .filter(|(_k, v)| v.choices.is_none())
        .map(|(k, _v)| k.clone())
        .collect();
    let struct_str = struct_name.to_string();
    let desc_impl = ToolImpl::Function {
        name: struct_str.clone(),
        description: struct_desc,
        parameters: Parameters {
            r#type: default_type(),
            properties,
            required,
        },
    };

    let json = serde_json::to_string(&desc_impl).unwrap();

    let ret = quote! {
        impl FunctionTool for #struct_name {
            fn key() -> String {
                #struct_str.to_string()
            }
            fn desc() -> String {
                #json.to_string()

            }
            fn inject(args: std::collections::HashMap<String, serde_json::Value>) -> String {
                let args = serde_json::to_string(&args).unwrap();
                let c : #struct_name = serde_json::from_str(&args).unwrap();
                c.exec()
            }
        }
    };
    ret.into()
}

#[derive(Debug, Deserialize, Serialize)]
#[serde(tag = "type", content = "function")]
enum ToolImpl {
    #[serde(rename = "function")]
    Function {
        name: String,
        description: String,
        parameters: Parameters,
    },
}

#[derive(Debug, Deserialize, Serialize)]
struct Parameters {
    #[serde(default = "default_type")]
    r#type: String,
    properties: HashMap<String, Property>,
    required: Vec<String>,
}
const DEFAULT_TYPE: &str = "object";

fn default_type() -> String {
    DEFAULT_TYPE.to_string()
}

#[derive(Debug, Deserialize, Serialize, Default)]
struct Property {
    r#type: String,
    #[serde(rename = "enum", skip_serializing_if = "Option::is_none")]
    choices: Option<Vec<String>>,
    description: String,
}