mofa-sdk 0.1.0

MoFA SDK - Modular Framework for Agents. A standard development toolkit for building AI agents with Rust
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
# MoFA SDK

MoFA (Modular Framework for Agents) SDK - A standard development toolkit for building AI agents with Rust.

## Architecture

```
mofa-sdk (标准 API 层 - SDK)
├── mofa-kernel (微内核核心)
├── mofa-runtime (运行时)
├── mofa-foundation (业务逻辑)
└── mofa-plugins (插件系统)
```

## Public Modules

- `kernel`: core abstractions from `mofa-kernel`
- `runtime`: lifecycle and execution runtime
- `agent`: foundation agent building blocks
- `llm`: LLM integration and helpers
- `plugins`: plugin system and adapters
- `workflow`: workflow engine and DSL
- `persistence`: persistence stores and plugins
- `messaging`: message bus and contracts
- `secretary`: secretary agent pattern
- `collaboration`: multi-agent collaboration protocols
- `coordination`: scheduling and coordination utilities
- `prompt`: prompt templates and composition
- `config`: global config facade (kernel/runtime/foundation)
- `skills`: progressive disclosure skills system
- `prelude`: common imports for quick start

## Installation

Add this to your `Cargo.toml`:

```toml
[dependencies]
mofa-sdk = "0.1"
```

### Optional Features

```toml
# With LLM support (OpenAI, Ollama, Azure)
mofa-sdk = { version = "0.1", features = ["openai"] }

# With dora-rs runtime support (distributed dataflow)
mofa-sdk = { version = "0.1", features = ["dora"] }

# With UniFFI bindings (Python, Kotlin, Swift, Java)
mofa-sdk = { version = "0.1", features = ["uniffi"] }

# With PyO3 Python bindings
mofa-sdk = { version = "0.1", features = ["python"] }

# Full features
mofa-sdk = { version = "0.1", features = ["openai", "uniffi", "dora"] }
```

## Quick Start

### Basic Agent

```rust
use mofa_sdk::kernel::{
    AgentCapabilities, AgentCapabilitiesBuilder, AgentContext, AgentInput, AgentOutput,
    AgentResult, AgentState, MoFAAgent,
};
use mofa_sdk::runtime::run_agents;
use async_trait::async_trait;

struct MyAgent {
    id: String,
    name: String,
    caps: AgentCapabilities,
    state: AgentState,
}

impl MyAgent {
    fn new(id: &str, name: &str) -> Self {
        Self {
            id: id.to_string(),
            name: name.to_string(),
            caps: AgentCapabilitiesBuilder::new().build(),
            state: AgentState::Created,
        }
    }
}

#[async_trait]
impl MoFAAgent for MyAgent {
    fn id(&self) -> &str { &self.id }
    fn name(&self) -> &str { &self.name }
    fn capabilities(&self) -> &AgentCapabilities { &self.caps }

    async fn initialize(&mut self, _ctx: &AgentContext) -> AgentResult<()> {
        self.state = AgentState::Ready;
        Ok(())
    }

    async fn execute(&mut self, _input: AgentInput, _ctx: &AgentContext) -> AgentResult<AgentOutput> {
        Ok(AgentOutput::text("Hello from MyAgent"))
    }

    async fn shutdown(&mut self) -> AgentResult<()> {
        self.state = AgentState::Shutdown;
        Ok(())
    }

    fn state(&self) -> AgentState { self.state.clone() }
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let agent = MyAgent::new("agent-001", "MyAgent");
    let outputs = run_agents(agent, vec![AgentInput::text("Hello")]).await?;
    println!("{}", outputs[0].to_text());
    Ok(())
}
```

### Batch Execution

```rust
use mofa_sdk::kernel::AgentInput;
use mofa_sdk::runtime::run_agents;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let agent = MyAgent::new("agent-002", "BatchAgent");
    let inputs = vec![
        AgentInput::text("task-1"),
        AgentInput::text("task-2"),
    ];
    let outputs = run_agents(agent, inputs).await?;
    for output in outputs {
        println!("{}", output.to_text());
    }
    Ok(())
}
```

### LLM Agent (Recommended)

Use the built-in LLMAgent for quick LLM interactions:

```rust
use mofa_sdk::llm::LLMAgentBuilder;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    // Create from environment (OPENAI_API_KEY)
    let agent = LLMAgentBuilder::from_env()?
        .with_id("my-agent")
        .with_system_prompt("You are a helpful assistant.")
        .build();

    // Simple Q&A
    let response = agent.ask("What is Rust?").await?;
    info!("{}", response);

    // Multi-turn chat
    let r1 = agent.chat("My name is Alice.").await?;
    let r2 = agent.chat("What's my name?").await?;  // Remembers context

    Ok(())
}
```

### Load Agent from Configuration File

```rust
use mofa_sdk::llm::agent_from_config;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    // Load from agent.yml
    let agent = agent_from_config("agent.yml")?;

    let response = agent.ask("Hello!").await?;
    info!("{}", response);

    Ok(())
}
```

### With Dora Runtime

```rust
use mofa_sdk::dora::{DoraRuntime, run_dataflow};

#[tokio::main]
async fn main() -> eyre::Result<()> {
    // Quick run a dataflow
    let result = run_dataflow("dataflow.yml").await?;
    info!("Dataflow {} completed", result.uuid);
    Ok(())
}
```

## Cross-Language Bindings (UniFFI)

MoFA provides cross-language bindings via UniFFI for Python, Kotlin, Swift, Java, and Go.

### Building with UniFFI

```bash
# Build with UniFFI and OpenAI features
cargo build --release --features "uniffi,openai" -p mofa-sdk
```

### Generating Bindings

Use the provided script:

```bash
cd crates/mofa-sdk

# Generate all bindings (Python, Kotlin, Swift, Java)
./generate-bindings.sh all

# Generate specific language
./generate-bindings.sh python
./generate-bindings.sh kotlin
./generate-bindings.sh swift
./generate-bindings.sh java
```

For Go bindings (requires separate tool):

```bash
cd crates/mofa-sdk/bindings/go

# Install uniffi-bindgen-go first
cargo install uniffi-bindgen-go --git https://github.com/NordSecurity/uniffi-bindgen-go

# Generate Go bindings
./generate-go.sh
```

### Python Quick Start

```bash
cd examples/python_bindings
export OPENAI_API_KEY=your-key-here
python 01_llm_agent.py
```

```python
from mofa import LLMAgentBuilder, MoFaError
import os

# Create an agent using the builder pattern
builder = LLMAgentBuilder.create()
builder = builder.set_id("my-agent")
builder = builder.set_name("Python Agent")
builder = builder.set_system_prompt("You are a helpful assistant.")
builder = builder.set_openai_provider(
    os.environ["OPENAI_API_KEY"],
    base_url=os.environ.get("OPENAI_BASE_URL"),
    model=os.environ.get("OPENAI_MODEL", "gpt-3.5-turbo")
)

agent = builder.build()

# Simple Q&A
response = agent.ask("What is Python?")
print(response)

# Multi-turn chat
r1 = agent.chat("My name is Alice.")
r2 = agent.chat("What's my name?")  # Remembers context

# Get history
history = agent.get_history()
agent.clear_history()
```

### Java Quick Start

```bash
cd examples/java_bindings
export OPENAI_API_KEY=your-key-here
mvn compile exec:java
```

```java
import com.mofa.*;

// Create an agent using the builder pattern
LLMAgentBuilder builder = UniFFI.INSTANCE.newLlmAgentBuilder();
builder = builder.setId("my-agent");
builder = builder.setName("Java Agent");
builder = builder.setSystemPrompt("You are a helpful assistant.");
builder = builder.setOpenaiProvider(
    System.getenv("OPENAI_API_KEY"),
    System.getenv("OPENAI_BASE_URL"),
    System.getenv().getOrDefault("OPENAI_MODEL", "gpt-3.5-turbo")
);

LLMAgent agent = builder.build();

// Simple Q&A
String response = agent.ask("What is Java?");
System.out.println(response);

// Multi-turn chat
String r1 = agent.chat("My name is Bob.");
String r2 = agent.chat("What's my name?");

// Get history
List<ChatMessage> history = agent.getHistory();
agent.clearHistory();
```

### Go Quick Start

```bash
cd examples/go_bindings
../crates/mofa-sdk/bindings/go/generate-go.sh
export OPENAI_API_KEY=your-key-here
go run 01_llm_agent.go
```

```go
package main

import (
    "fmt"
    "os"
    mofa "mofa-sdk/bindings/go"
)

func main() {
    // Create an agent using the builder pattern
    builder := mofa.NewLlmAgentBuilder()
    builder.SetId("my-agent")
    builder.SetName("Go Agent")
    builder.SetSystemPrompt("You are a helpful assistant.")
    builder.SetOpenaiProvider(
        os.Getenv("OPENAI_API_KEY"),
        os.Getenv("OPENAI_BASE_URL"),
        os.Getenv("OPENAI_MODEL"),
    )

    agent, _ := builder.Build()

    // Simple Q&A
    answer, _ := agent.Ask("What is Go?")
    fmt.Println(answer)

    // Multi-turn chat
    agent.Chat("My name is Charlie.")
    agent.Chat("What's my name?")

    // Get history
    history := agent.GetHistory()
    agent.ClearHistory()
}
```

### Kotlin Quick Start

```kotlin
import org.mofa.*

// Create an agent using the builder pattern
val builder = UniFFI.newLlmAgentBuilder()
builder.setId("my-agent")
builder.setName("Kotlin Agent")
builder.setSystemPrompt("You are a helpful assistant.")
builder.setOpenaiProvider(
    apiKey = System.getenv("OPENAI_API_KEY"),
    baseUrl = System.getenv("OPENAI_BASE_URL"),
    model = System.getenv("OPENAI_MODEL") ?: "gpt-3.5-turbo"
)

val agent = builder.build()

// Simple Q&A
val response = agent.ask("What is Kotlin?")
println(response)

// Multi-turn chat
val r1 = agent.chat("My name is Diana.")
val r2 = agent.chat("What's my name?")
```

### Swift Quick Start

```swift
import MoFA

// Create an agent using the builder pattern
let builder = try UniFFI.newLlmAgentBuilder()
try builder.setId("my-agent")
try builder.setName("Swift Agent")
try builder.setSystemPrompt("You are a helpful assistant.")
try builder.setOpenaiProvider(
    apiKey: ProcessInfo.processInfo.environment["OPENAI_API_KEY"]!,
    baseUrl: ProcessInfo.processInfo.environment["OPENAI_BASE_URL"],
    model: ProcessInfo.processInfo.environment["OPENAI_MODEL"]
)

let agent = try builder.build()

// Simple Q&A
let response = try agent.ask(question: "What is Swift?")
print(response)

// Multi-turn chat
let r1 = try agent.chat(message: "My name is Eve.")
let r2 = try agent.chat(message: "What's my name?")
```

### Available Functions (All Languages)

| Function | Description |
|----------|-------------|
| `get_version()` | Get SDK version string |
| `is_dora_available()` | Check if Dora runtime support is enabled |
| `new_llm_agent_builder()` | Create a new LLMAgentBuilder instance |

### LLMAgentBuilder Methods

| Method | Description |
|--------|-------------|
| `set_id(id)` | Set agent ID |
| `set_name(name)` | Set agent name |
| `set_system_prompt(prompt)` | Set system prompt |
| `set_temperature(temp)` | Set temperature (0.0-1.0) |
| `set_max_tokens(tokens)` | Set max tokens for response |
| `set_session_id(id)` | Set session ID |
| `set_user_id(id)` | Set user ID |
| `set_tenant_id(id)` | Set tenant ID |
| `set_context_window_size(size)` | Set context window size in rounds |
| `set_openai_provider(key, url, model)` | Configure OpenAI provider |
| `build()` | Build the LLMAgent instance |

### LLMAgent Methods

| Method | Description |
|--------|-------------|
| `agent_id()` | Get agent ID |
| `name()` | Get agent name |
| `ask(question)` | Simple Q&A (no context retention) |
| `chat(message)` | Multi-turn chat (with context retention) |
| `clear_history()` | Clear conversation history |
| `get_history()` | Get conversation history |

## Features

| Feature | Description |
|---------|-------------|
| `openai` | Enable LLM support (OpenAI, Ollama, Azure, Compatible) |
| `dora` | Enable dora-rs runtime for distributed dataflow |
| `uniffi` | Enable UniFFI bindings for cross-language support |
| `python` | Enable PyO3 Python native bindings |

## Configuration File Format (agent.yml)

```yaml
agent:
  id: "my-agent-001"
  name: "My LLM Agent"
  description: "A helpful assistant"

llm:
  provider: openai  # openai, ollama, azure, compatible
  model: gpt-4o
  api_key: ${OPENAI_API_KEY}  # Environment variable reference
  temperature: 0.7
  max_tokens: 4096
  system_prompt: |
    You are a helpful AI assistant.
```

## Documentation

- [API Documentation]https://docs.rs/mofa-sdk
- [GitHub Repository]https://github.com/mofa-org/mofa

## License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.