tokitai/lib.rs
1//! # Tokitai
2//!
3//! **AI Tool Integration System with Compile-time Tool Definitions**
4//!
5//! Tokitai is a zero-runtime-dependency procedural macro library that transforms your Rust methods
6//! into AI-callable tools with a single `#[tool]` attribute. All tool definitions are generated at
7//! compile time, ensuring type errors are caught before runtime.
8//!
9//! ## π― Key Features
10//!
11//! - **Zero Runtime Intrusion** - The macro itself has no runtime dependencies
12//! - **Compile-time Type Safety** - Tool definitions generated at compile time, parameter type errors exposed during compilation
13//! - **Single Attribute** - Just `#[tool]`, no need for multiple tags
14//! - **Optional Runtime** - Control dependencies via features, supports async-free environments
15//! - **Vendor Neutral** - Works with any AI/LLM provider (Ollama, OpenAI, Anthropic, etc.)
16
17#![allow(unexpected_cfgs)]
18
19//! ## π Quick Start
20//!
21//! ### 1. Add Dependencies
22//!
23//! ```toml
24//! [dependencies]
25//! tokitai = "0.3.3"
26//! ```
27//!
28//! That's it! All required dependencies (serde, serde_json, thiserror) are included automatically.
29//!
30//! ### 2. Define Your Tools
31//!
32//! ```rust,ignore
33//! use tokitai::tool;
34//!
35//! pub struct Calculator;
36//!
37//! #[tool]
38//! impl Calculator {
39//! /// Add two numbers together
40//! pub fn add(&self, a: i32, b: i32) -> i32 {
41//! a + b
42//! }
43//!
44//! /// Calculate SHA256 hash of a string
45//! pub fn sha256(&self, input: String) -> String {
46//! // Your implementation...
47//! format!("hash of {}", input)
48//! }
49//! }
50//! ```
51//!
52//! ### 3. Get Tool Definitions (Send to AI)
53//!
54//! ```rust,ignore
55//! // Compile-time generated tool definitions
56//! let tools = Calculator::tool_definitions();
57//!
58//! // Convert to JSON and send to AI
59//! let tools_json = serde_json::to_string_pretty(tools)?;
60//! println!("{}", tools_json);
61//! ```
62//!
63//! Output:
64//!
65//! ```json
66//! [
67//! {
68//! "name": "add",
69//! "description": "Add two numbers together",
70//! "input_schema": "{\"type\":\"object\",\"properties\":{\"a\":{\"type\":\"integer\"},\"b\":{\"type\":\"integer\"}},\"required\":[\"a\",\"b\"]}"
71//! },
72//! {
73//! "name": "sha256",
74//! "description": "Calculate SHA256 hash of a string",
75//! "input_schema": "{\"type\":\"object\",\"properties\":{\"input\":{\"type\":\"string\"}},\"required\":[\"input\"]}"
76//! }
77//! ]
78//! ```
79//!
80//! ### 4. Handle AI Calls
81//!
82//! ```rust,ignore
83//! use tokitai::json;
84//!
85//! let calc = Calculator;
86//!
87//! // AI decides to call a tool
88//! let call_request = json!({
89//! "name": "add",
90//! "arguments": {"a": 10, "b": 20}
91//! });
92//!
93//! // Execute the tool
94//! let result = calc.call_tool(
95//! call_request["name"].as_str().unwrap(),
96//! &call_request["arguments"]
97//! )?;
98//!
99//! println!("Result: {}", result); // 30
100//! ```
101//!
102//! ## π¦ Crate Structure
103//!
104//! Tokitai is organized as a workspace with three crates:
105//!
106//! | Crate | Description |
107//! |-------|-------------|
108//! | [`tokitai`](https://crates.io/crates/tokitai) | Main crate with runtime support (this crate) |
109//! | [`tokitai-core`](https://crates.io/crates/tokitai-core) | Core types and traits (zero dependencies) |
110//! | [`tokitai-macros`](https://crates.io/crates/tokitai-macros) | Procedural macros (compile-time code generation) |
111//!
112//! ## π§ How It Works
113//!
114//! ```text
115//! +---------------+ Tool Definitions +---------------+
116//! | Your Code | ----------------------> | AI Service |
117//! | #[tool] | | (Ollama, |
118//! +---------------+ | OpenAI, |
119//! ^ | etc.) |
120//! | Execution Result +---------------+
121//! | |
122//! | | Call Request
123//! | v
124//! +---------------+ +---------------+
125//! | Rust Method | <------ call_tool ------ | JSON Call |
126//! | (Local) | | {"name":..} |
127//! +---------------+ +---------------+
128//! ```
129//!
130//! 1. **Define Rust methods** β Implement your business logic
131//! 2. **Send to AI** β AI knows what tools are available
132//! 3. **Receive call request** β AI returns "I want to call a tool"
133//! 4. **Execute and return** β Run Rust code locally
134//!
135//! ## π οΈ Features
136//!
137//! | Feature | Description |
138//! |---------|-------------|
139//! | `default` | Enables full runtime support |
140//! | `runtime` | Basic runtime support (async, error handling) |
141//! | `mcp` | MCP protocol support (requires `runtime`) |
142//!
143//! ### Minimal Dependencies (Compile-time Only)
144//!
145//! If you only need compile-time tool definitions without runtime support:
146//!
147//! ```toml
148//! [dependencies]
149//! tokitai = { version = "0.3", default-features = false }
150//! ```
151//!
152//! Note: Runtime features (call_tool, etc.) require serde/serde_json which are included by default.
153//!
154//! ## π API Overview
155//!
156//! ### Re-exported Core Types
157//!
158//! - [`ToolDefinition`] - Tool definition with name, description, and input schema
159//! - [`ToolError`] - Tool invocation error type
160//! - [`ToolErrorKind`] - Error classification
161//! - [`ParamType`] - JSON Schema type enumeration
162//! - [`ToolProvider`] - Trait for tool providers (auto-implemented by `#[tool]`)
163//! - [`json!`] - Macro for creating JSON values (from serde_json)
164//! - [`Value`], [`Map`] - JSON value types (from serde_json)
165//!
166//! ### Runtime Types
167//!
168//! - [`AiToolError`] - Enhanced error type for runtime
169//!
170//! ### Macro
171//!
172//! - [`tool`] - Attribute macro for marking tool implementations
173//!
174//! ## π Type Mapping
175//!
176//! Rust types are automatically mapped to JSON Schema types:
177//!
178//! | Rust Type | JSON Schema Type |
179//! |-----------|------------------|
180//! | `String`, `&str` | `string` |
181//! | `i8`, `i16`, `i32`, `i64`, `u8`, `u16`, `u32`, `u64` | `integer` |
182//! | `f32`, `f64` | `number` |
183//! | `bool` | `boolean` |
184//! | `Vec<T>` | `array` |
185//! | Custom structs | `object` |
186//!
187//! ## π Examples
188//!
189//! See the [examples directory](https://github.com/silverenternal/tokitai/tree/main/examples) for more:
190//!
191//! - `basic_usage.rs` - Basic usage example
192//! - `ollama_integration.rs` - Ollama AI integration with SHA256 tool
193//! - `multi_tool_chat.rs` - Multi-toolεδ½ chatbot
194//!
195//! ## βοΈ Requirements
196//!
197//! - **Rust Version**: 1.70+
198//! - **Edition**: 2021
199//!
200//! ## π License
201//!
202//! Licensed under either of:
203//!
204//! - Apache License, Version 2.0 ([LICENSE-APACHE](https://github.com/silverenternal/tokitai/blob/main/LICENSE))
205//! - MIT License ([LICENSE-MIT](https://github.com/silverenternal/tokitai/blob/main/LICENSE))
206//!
207//! at your option.
208//!
209//! ## π€ Contributing
210//!
211//! Unless you explicitly state otherwise, any contribution intentionally submitted
212//! for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be
213//! dual licensed as above, without any additional terms or conditions.
214//!
215//! ## See Also
216//!
217//! - [`tokitai-core`](https://crates.io/crates/tokitai-core) - Core types and traits
218//! - [`tokitai-macros`](https://crates.io/crates/tokitai-macros) - Procedural macros
219
220// Re-export core types (always available)
221pub use tokitai_core::{ParamType, ToolCaller, ToolDefinition, ToolError, ToolErrorKind, ToolProvider};
222
223// Re-export serde_json for convenience (users don't need to add extra dependency)
224pub use serde_json::{json, Map, Value};
225
226// Re-export config types (when serde feature is enabled)
227#[cfg(feature = "serde")]
228pub use tokitai_core::{ToolConfig, ToolConfigRegistry, GLOBAL_CONFIG_REGISTRY};
229
230// Runtime module (always available)
231pub mod error;
232
233#[cfg(feature = "mcp")]
234pub mod mcp;
235
236// Export runtime types
237pub use error::AiToolError;
238
239#[cfg(feature = "mcp")]
240pub use mcp::*;
241
242// Re-export macros
243pub use tokitai_macros::{
244 config, param_tool, tool, tool_default, tool_desc, tool_example, tool_max, tool_max_items,
245 tool_max_length, tool_min, tool_min_items, tool_min_length, tool_multiple_of, tool_pattern,
246 tool_required, tool_transform, tool_type, tool_validate,
247};
248
249/// Library version
250pub const VERSION: &str = env!("CARGO_PKG_VERSION");