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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
//! Procedural macros for the rsai crate providing structured generation capabilities.
//!
//! This crate provides three main macros:
//!
//! - [`completion_schema`] - Automatically generates JSON schema for response types
//! - [`tool`](fn@tool) - Transforms Rust functions into callable tools with automatic schema generation
//! - [`toolset`] - Creates collections of tools
//!
//! # Quick Start
//!
//! ```rust
//! use rsai_macros::{completion_schema, tool, toolset};
//! use serde::{Deserialize, Serialize};
//!
//! #[completion_schema]
//! struct WeatherResponse {
//! city: String,
//! temperature: f64,
//! conditions: String,
//! }
//!
//! #[tool]
//! /// Get current weather for a city
//! /// city: The city to get weather for
//! /// unit: Temperature unit (celsius or fahrenheit)
//! fn get_weather(city: String, unit: Option<String>) -> String {
//! match unit.as_deref() {
//! Some("fahrenheit") => format!("Weather in {}: 72°F", city),
//! _ => format!("Weather in {}: 22°C", city),
//! }
//! }
//!
//! let tools = toolset![get_weather];
//! // Use with rsai::llm builder...
//! ```
use TokenStream;
use quote;
/// Attribute macro for types used with the `rsai::llm()::complete::<T>()` method.
///
/// This macro automatically adds the necessary derives and attributes to make a struct
/// suitable for structured responses. It ensures strict validation of
/// responses by rejecting unknown fields.
///
/// # What it does
///
/// - Adds `#[derive(serde::Deserialize, schemars::JsonSchema)]`
/// - Adds `#[serde(deny_unknown_fields)]` for strict local deserialization
/// - Adds `#[schemars(deny_unknown_fields)]` for strict schema generation
/// - Enables automatic JSON schema generation for LLM providers
///
/// # Example
///
/// ```rust
/// use rsai_macros::completion_schema;
/// use serde::Deserialize;
///
/// #[completion_schema]
/// struct WeatherResponse {
/// /// The city name
/// city: String,
/// /// Temperature in Celsius
/// temperature: f64,
/// /// Weather conditions
/// conditions: String,
/// /// Optional humidity percentage
/// humidity: Option<f64>,
/// }
/// ```
///
/// # Field Validation
///
/// The `deny_unknown_fields` attributes ensure that responses must exactly match
/// your struct definition. Any extra fields will cause a local deserialization
/// error and are also rejected in the generated JSON schema.
///
/// # Supported Types
///
/// All types that implement [`serde::Deserialize`] and [`schemars::JsonSchema`] are supported,
/// including:
/// - Primitive types ([`String`], [`i32`], [`f64`], [`bool`], etc.)
/// - Optionals ([`Option<T>`])
/// - Vectors ([`Vec<T>`])
/// - Nested structs and enums
/// - Custom types with appropriate trait implementations
/// Attribute macro for marking functions as tools that can be called by LLMs.
///
/// This macro generates the necessary boilerplate to make a function callable as a tool,
/// including automatic JSON schema generation, parameter parsing, and error handling.
/// It enables AI models to call your Rust functions safely and predictably.
///
/// # Syntax
///
/// The macro expects a specific docstring format:
///
/// ```rust
/// use rsai_macros::tool;
///
/// #[tool]
/// /// Function description (required - first line of docstring)
/// /// param: Parameter description (required for each parameter)
/// /// optional_param: Description for optional parameters (also required)
/// fn function_name(param: String, optional_param: Option<i32>) -> String {
/// // implementation
/// format!("param: {}, optional: {:?}", param, optional_param)
/// }
/// ```
///
/// # Examples
///
/// ## Basic Tool
///
/// ```rust
/// use rsai_macros::tool;
///
/// #[tool]
/// /// Get current weather for a city
/// /// city: The city to get weather for
/// /// unit: Temperature unit (celsius or fahrenheit)
/// fn get_weather(city: String, unit: Option<String>) -> String {
/// match unit.as_deref() {
/// Some("fahrenheit") => format!("Weather for {}: 72°F", city),
/// _ => format!("Weather for {}: 22°C", city),
/// }
/// }
/// ```
///
/// ## Async Tool
///
/// ```rust
/// use rsai_macros::tool;
///
/// #[tool]
/// /// Send an email to a recipient
/// /// to: Email address of the recipient
/// /// subject: Email subject line
/// /// body: Email body content
/// async fn send_email(to: String, subject: String, body: String) -> Result<String, String> {
/// // Simulate async email sending
/// tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
/// Ok(format!("Email sent to {}", to))
/// }
/// ```
///
/// # Parameter Validation
///
/// The macro performs comprehensive compile-time validation:
///
/// ✅ **Valid**: All parameters documented
/// ```rust
/// use rsai_macros::tool;
///
/// #[tool]
/// /// Get weather info
/// /// city: The city name
/// /// country: The country code
/// fn get_weather(city: String, country: String) -> String {
/// format!("Weather for {}, {}", city, country)
/// }
/// ```
///
/// ❌ **Invalid**: Missing parameter description
/// ```rust,compile_fail
/// #[tool]
/// /// Get weather info
/// /// city: The city name
/// fn get_weather(city: String, country: String) -> String {
/// // Compile error: Missing description for parameter 'country'
/// }
/// ```
///
/// # Type Mapping
///
/// Rust types are automatically mapped to JSON schema types:
///
/// | Rust Type | JSON Schema Type |
/// |-----------|------------------|
/// | `String`, `&str` | `string` |
/// | Integer types | `integer` |
/// | `f32`, `f64` | `number` |
/// | `bool` | `boolean` |
/// | `Vec<T>` | `array` |
/// | `Option<T>` | optional field containing `T` |
/// | Types implementing `serde::Deserialize` and `schemars::JsonSchema` | their generated schema |
/// Macro for creating a collection of tools from annotated [`tool`] functions.
///
/// This macro takes a comma-separated list of function names that have been
/// annotated with `#[tool]` and creates a `rsai::ToolSet` containing all of them.
/// It provides a convenient way to group related tools for AI agents.
///
/// # Syntax
///
/// ```rust,ignore
/// use rsai_macros::{tool, toolset};
///
/// // Assume these functions are defined with #[tool] attribute:
/// // #[tool] fn function_name1(param: String) -> String { ... }
/// // #[tool] fn function_name2(param: i32) -> i32 { ... }
/// // #[tool] fn function_name3(param: bool) -> bool { ... }
///
/// let tools = toolset![function_name1, function_name2, function_name3];
/// ```
///
/// # Requirements
///
/// All function names must correspond to functions that have the `#[tool]` attribute
/// applied. The macro will fail to compile if any function is not properly annotated.
///
/// # Examples
///
/// ## Single Tool
///
/// ```rust
/// use rsai_macros::{tool, toolset};
///
/// #[tool]
/// /// Get current weather for a city
/// /// city: The city to get weather for
/// fn get_weather(city: String) -> String {
/// format!("Weather for {}: 22°C", city)
/// }
///
/// let single_tool = toolset![get_weather];
/// assert_eq!(
/// single_tool
/// .tools()
/// .expect("toolset should contain the get_weather tool")
/// .len(),
/// 1
/// );
/// ```
///
/// ## Many Tools
///
/// ```rust
/// use rsai_macros::{tool, toolset};
///
/// #[tool]
/// /// Send an email
/// /// to: Recipient address
/// fn send_email(to: String) -> String {
/// format!("Email sent to {}", to)
/// }
///
/// #[tool]
/// /// Get user information
/// /// user_id: User identifier
/// fn get_user(user_id: String) -> String {
/// format!("User: {}", user_id)
/// }
///
/// #[tool]
/// /// Create a file
/// /// path: File path
/// /// content: File content
/// fn create_file(path: String, content: String) -> String {
/// format!("File created at {}", path)
/// }
///
/// let tools = toolset![send_email, get_user, create_file];
/// assert_eq!(
/// tools
/// .tools()
/// .expect("toolset should contain all registered tools")
/// .len(),
/// 3
/// );
/// ```
///
/// ## Tools With Shared Context
///
/// ```rust
/// use rsai::{Ctx, ToolSet, tool, toolset};
///
/// struct AppContext {
/// prefix: String,
/// }
///
/// impl AsRef<AppContext> for AppContext {
/// fn as_ref(&self) -> &AppContext {
/// self
/// }
/// }
///
/// #[tool]
/// /// Greet a user.
/// /// name: Name to greet.
/// fn greet(context: Ctx<&AppContext>, name: String) -> String {
/// format!("{} {name}", context.prefix)
/// }
///
/// let tools: ToolSet<AppContext> = toolset![AppContext => greet]
/// .with_context(AppContext { prefix: "Hello".to_string() })?;
/// # Ok::<(), rsai::LlmError>(())
/// ```
///
/// # Generated Code
///
/// The macro generates code that:
/// 1. Creates a new `rsai::ToolRegistry`
/// 2. Registers each tool function
/// 3. Builds the final `rsai::ToolSet`
///
/// ```rust,no_run
/// use rsai::ToolRegistry;
/// use std::sync::Arc;
///
/// {
/// let registry = ToolRegistry::new();
/// // Note: FunctionName1Tool and FunctionName2Tool would be created by the #[tool] macro
/// // registry.register(FunctionName1Tool);
/// // registry.register(FunctionName2Tool);
/// // The macro then creates the ToolSet from the registry
/// }
/// ```
///
/// # Error Handling
///
/// If any function name doesn't correspond to a `#[tool]`-annotated function,
/// compilation will fail with a clear error message indicating which function
/// is missing the tool annotation. Listing the same function twice is also a
/// compile-time error.