lumos_macro 0.1.4

Procedural macros for the Lumosai agent framework
Documentation
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
# Lumos Macro

Lumos Macro是Lumosai框架的一部分,提供了一系列过程宏,用于简化Lumosai框架中工具、代理和LLM适配器的定义和使用。

## 特性

### 基础宏
- `#[tool]`:简化工具定义,自动生成Tool trait实现
- `#[agent]`:定义代理及其工具,自动处理工具注册
- `#[derive(LlmAdapter)]`:为自定义LLM适配器生成默认实现
- `lumos_execute_tool!`:快速执行工具的宏

### 受Mastra API启发的DSL宏
- `workflow!`:工作流定义DSL,支持步骤、条件和代理集成
- `rag_pipeline!`:RAG管道DSL,简化文档处理、嵌入和向量检索
- `eval_suite!`:评估框架DSL,用于定义指标、测试用例和报告格式
- `mcp_client!`:MCP客户端配置DSL,简化外部工具集成
- `agent!`:代理定义DSL,简化代理创建和配置
- `tools!`:工具集合DSL,一次性定义多个工具
- `lumos!`:应用级配置DSL,一次性配置整个应用

## 安装

将下面的依赖添加到项目的Cargo.toml文件中:

```toml
[dependencies]
lumosai_core = { version = "0.1.0", features = ["macros"] }
```

核心的`macros`特性会自动包含`lumos_macro`库。

## 使用示例

### 工具定义 (使用#[tool]宏)

```rust
use lumosai_core::{Error, Result};
use serde_json::{Value, json};
use lumos_macro::tool;

#[tool(
    name = "calculator",
    description = "执行基本的数学运算"
)]
fn calculator(
    #[parameter(
        name = "operation",
        description = "要执行的操作: add, subtract, multiply, divide",
        r#type = "string", 
        required = true
    )]
    operation: String,
    
    #[parameter(
        name = "a",
        description = "第一个数字",
        r#type = "number",
        required = true
    )]
    a: f64,
    
    #[parameter(
        name = "b",
        description = "第二个数字",
        r#type = "number",
        required = true
    )]
    b: f64,
) -> Result<Value> {
    let result = match operation.as_str() {
        "add" => a + b,
        "subtract" => a - b,
        "multiply" => a * b,
        "divide" => {
            if b == 0.0 {
                return Err(Error::InvalidInput("Cannot divide by zero".to_string()));
            }
            a / b
        },
        _ => return Err(Error::InvalidInput(format!("Unknown operation: {}", operation))),
    };
    
    Ok(json!({ "result": result }))
}
```

宏展开后,会生成一个返回`Box<dyn Tool>`的函数,可以直接用于工具注册。

### 代理定义 (使用agent!宏)

```rust
use std::sync::Arc;
use lumosai_core::llm::LlmProvider;
use lumos_macro::agent;

#[agent(
    name = "math_agent",
    instructions = "你是一个能够执行数学计算的助手。",
    model = "gpt-4"
)]
struct MathAgent {
    #[tool]
    calculator: calculator,
    
    #[tool]
    unit_converter: unit_converter,
}
```

宏展开后,会生成一个名为`create_mathagent`的函数,接受`Arc<dyn LlmProvider>`参数,返回配置好的代理实例。

### LLM适配器 (使用#[derive(LlmAdapter)]宏)

```rust
use async_trait::async_trait;
use lumosai_core::{Result, Message, Role, Error};
use lumosai_core::llm::{LlmProvider, LlmOptions};
use lumos_macro::LlmAdapter;

#[derive(LlmAdapter)]
struct CustomLlmAdapter {
    api_key: String,
    model: String,
}

impl CustomLlmAdapter {
    fn new(api_key: String, model: String) -> Self {
        Self { api_key, model }
    }
}

#[async_trait]
impl LlmProvider for CustomLlmAdapter {
    async fn generate_with_messages(&self, messages: &[Message], options: &LlmOptions) -> Result<String> {
        // 实现自定义的消息生成逻辑
        Ok("这是一个模拟的LLM响应".to_string())
    }
}
```

宏展开后,会为`LlmProvider` trait的其他方法提供默认实现,你只需要实现`generate_with_messages`方法即可。

### 快速执行工具 (使用lumos_execute_tool!宏)

```rust
use lumos_macro::lumos_execute_tool;

async fn main() -> Result<()> {
    let result = lumos_execute_tool! {
        tool: calculator,
        params: {
            "operation": "add",
            "a": 10.5,
            "b": 20.3
        }
    };
    
    println!("结果: {}", result);
    Ok(())
}
```

## 新增DSL宏

### 工作流定义 (使用workflow!宏)

```rust
use lumos_macro::workflow;
use lumosai_core::agent::Agent;

let content_workflow = workflow! {
    name: "content_creation",
    description: "创建高质量的内容",
    steps: {
        {
            name: "research",
            agent: researcher,
            instructions: "进行深入的主题研究",
        },
        {
            name: "writing",
            agent: writer,
            instructions: "将研究结果整理成文章",
            when: { completed("research") },
        },
        {
            name: "review",
            agent: reviewer,
            instructions: "检查文章质量和准确性",
            when: { completed("writing") },
        }
    }
};

// 执行工作流
let result = content_workflow.execute(input_data).await?;
```

### RAG管道 (使用rag_pipeline!宏)

```rust
use lumos_macro::rag_pipeline;
use lumosai_core::rag::DocumentSource;

let kb = rag_pipeline! {
    name: "knowledge_base",
    
    source: DocumentSource::from_directory("./docs"),
    
    pipeline: {
        chunk: {
            chunk_size: 1000,
            chunk_overlap: 200,
            separator: "\n",
            strategy: "recursive"
        },
        
        embed: {
            model: "text-embedding-3-small",
            dimensions: 1536,
            max_retries: 3
        },
        
        store: {
            db: "pgvector",
            collection: "embeddings",
            connection_string: env!("DATABASE_URL")
        }
    },
    
    query_pipeline: {
        rerank: true,
        top_k: 5,
        filter: r#"{ "type": { "$in": ["article", "faq"] } }"#
    }
};

// 执行查询
let results = kb.query("如何使用RAG?").await?;
```

### 评估套件 (使用eval_suite!宏)

```rust
use lumos_macro::eval_suite;
use lumosai_core::eval::{AccuracyMetric, RelevanceMetric, CompletenessMetric};

let suite = eval_suite! {
    name: "agent_performance",
    
    metrics: {
        accuracy: AccuracyMetric::new(0.8),
        relevance: RelevanceMetric::new(0.7),
        completeness: CompletenessMetric::new(0.6)
    },
    
    test_cases: {
        basic_queries: "./tests/basic_queries.json",
        complex_queries: "./tests/complex_queries.json"
    },
    
    reporting: {
        format: "html",
        output: "./reports/eval_results.html"
    }
};

// 运行评估
let results = suite.run(agent).await?;
```

### MCP客户端 (使用mcp_client!宏)

```rust
use lumos_macro::mcp_client;

let client = mcp_client! {
    discovery: {
        endpoints: ["https://tools.example.com/mcp", "https://api.mcp.run"],
        auto_register: true
    },
    
    tools: {
        data_analysis: {
            enabled: true,
            auth: {
                type: "api_key",
                key_env: "DATA_ANALYSIS_API_KEY"
            }
        },
        image_processing: {
            enabled: true,
            rate_limit: 100
        }
    }
};

// 获取可用的MCP工具
let tools = client.get_available_tools().await?;
```

### 代理定义 (使用agent!宏)

```rust
use lumos_macro::agent;

let agent = agent! {
    name: "research_assistant",
    instructions: "你是一个专业的研究助手,擅长收集和整理信息。",
    
    llm: {
        provider: openai_adapter,
        model: "gpt-4"
    },
    
    memory: {
        store_type: "buffer",
        capacity: 10
    },
    
    tools: {
        search_tool,
        calculator_tool: { precision: 2 },
        web_browser: { javascript: true, screenshots: true }
    }
};

// 使用代理处理请求
let response = agent.run("帮我查找关于量子计算的最新研究").await?;
```

### 工具集合定义 (使用tools!宏)

```rust
use lumos_macro::tools;

tools! {
    {
        name: "calculator",
        description: "执行基本的数学运算",
        parameters: {
            {
                name: "operation",
                description: "要执行的操作: add, subtract, multiply, divide",
                type: "string",
                required: true
            },
            {
                name: "a",
                description: "第一个数字",
                type: "number",
                required: true
            },
            {
                name: "b",
                description: "第二个数字",
                type: "number",
                required: true
            }
        },
        handler: |params| async move {
            let operation = params.get("operation").unwrap().as_str().unwrap();
            let a = params.get("a").unwrap().as_f64().unwrap();
            let b = params.get("b").unwrap().as_f64().unwrap();
            
            let result = match operation {
                "add" => a + b,
                "subtract" => a - b,
                "multiply" => a * b,
                "divide" => a / b,
                _ => return Err(Error::InvalidInput("Unknown operation".into()))
            };
            
            Ok(json!({ "result": result }))
        }
    },
    {
        name: "weather",
        description: "获取指定城市的天气信息",
        parameters: {
            {
                name: "city",
                description: "城市名称",
                type: "string",
                required: true
            }
        },
        handler: get_weather_data
    }
}

// 使用工具
let result = calculator().execute(params, &options).await?;
let weather = weather().execute(params, &options).await?;
```

### 应用级配置 (使用lumos!宏)

```rust
use lumos_macro::lumos;

let app = lumos! {
    name: "stock_assistant",
    description: "一个能够提供股票信息的AI助手",
    
    agents: {
        stockAgent
    },
    
    tools: {
        stockPriceTool,
        stockInfoTool
    },
    
    rags: {
        stockKnowledgeBase
    },
    
    workflows: {
        stockAnalysisWorkflow
    },
    
    mcp_endpoints: vec!["https://api.example.com/mcp"]
};

// 使用应用处理请求
let response = app.run("查询苹果公司股票价格").await?;
```

## 与Mastra API的比较

Lumos宏的设计受到了Mastra API的启发,提供了类似的声明式API,但专为Rust语言和Lumosai框架量身定制。相比于Mastra的JavaScript API,Lumos宏利用了Rust的强类型系统和编译时检查,以提供更安全和高效的代码。

新增的DSL宏直接受到Mastra的工作流、RAG、评估和MCP功能的启发,提供了相似的声明式语法,但保持了Rust语言的特性和安全性。

## 贡献

欢迎贡献代码、报告问题或提出新功能建议。在提交PR前,请确保通过所有测试并遵循项目的代码风格。

## 许可证

MIT