mofa_sdk/lib.rs
1//! MoFA API - Standard SDK for MoFA framework
2//!
3//! This crate provides a standardized API for the MoFA (Model-based Framework for Agents) framework.
4//!
5//! # Architecture Layers
6//!
7//! The SDK is organized into clear layers following microkernel architecture principles:
8//!
9//! ```text
10//! ┌─────────────────────────────────────────┐
11//! │ User Code │
12//! └─────────────────┬───────────────────────┘
13//! ↓
14//! ┌─────────────────────────────────────────┐
15//! │ SDK (Standard API Surface) │
16//! │ - kernel: Core abstractions │
17//! │ - runtime: Lifecycle management │
18//! │ - foundation: Business functionality │
19//! └─────────────────┬───────────────────────┘
20//! ```
21//!
22//! # Features
23//!
24//! - `dora` - Enable dora-rs runtime support for distributed dataflow
25//!
26//! For FFI bindings (Python, Kotlin, Swift, Java), use the `mofa-ffi` crate.
27//!
28//! # Quick Start
29//!
30//! ```toml
31//! mofa-sdk = "0.1"
32//! ```
33//!
34//! ```rust,ignore
35//! use mofa_sdk::kernel::{AgentInput, MoFAAgent};
36//! use mofa_sdk::runtime::run_agents;
37//!
38//! struct MyAgent;
39//!
40//! #[async_trait::async_trait]
41//! impl MoFAAgent for MyAgent {
42//! // implementation...
43//! }
44//!
45//! #[tokio::main]
46//! async fn main() -> anyhow::Result<()> {
47//! let outputs = run_agents(MyAgent, vec![AgentInput::text("Hello")]).await?;
48//! println!("{}", outputs[0].to_text());
49//! Ok(())
50//! }
51//! ```
52
53// =============================================================================
54// Kernel Layer - Core Abstractions
55// =============================================================================
56
57/// Core agent abstractions and extensions
58///
59/// This module provides the minimal core interfaces that all agents implement.
60/// Following microkernel principles, the core is kept minimal with optional
61/// extensions for additional capabilities.
62///
63/// # Core Trait
64///
65/// - `MoFAAgent`: The core agent interface (id, name, capabilities, execute, etc.)
66///
67/// # Extension Traits
68///
69/// - `AgentLifecycle`: pause, resume, interrupt
70/// - `AgentMessaging`: handle_message, handle_event
71/// - `AgentPluginSupport`: plugin management
72///
73/// # Example
74///
75/// ```rust,ignore
76/// use mofa_sdk::kernel::MoFAAgent;
77///
78/// #[async_trait::async_trait]
79/// impl MoFAAgent for MyAgent {
80/// fn id(&self) -> &str { "my-agent" }
81/// fn name(&self) -> &str { "My Agent" }
82/// // ... other methods
83/// }
84/// ```
85pub mod kernel {
86 //! Core abstractions and infrastructure from `mofa-kernel`.
87 //!
88 //! This module is a normalized, comprehensive facade over `mofa-kernel` with
89 //! structured submodules and curated top-level re-exports.
90
91 // ---------------------------------------------------------------------
92 // Structured submodules (full coverage)
93 // ---------------------------------------------------------------------
94 pub mod agent {
95 pub use mofa_kernel::agent::*;
96 }
97 pub mod message {
98 pub use mofa_kernel::message::*;
99 }
100 pub mod bus {
101 pub use mofa_kernel::bus::*;
102 }
103 pub mod plugin {
104 pub use mofa_kernel::plugin::*;
105 }
106 pub mod config {
107 pub use mofa_kernel::config::*;
108 }
109 pub mod core {
110 pub use mofa_kernel::core::*;
111 }
112 pub mod storage {
113 pub use mofa_kernel::storage::*;
114 }
115
116 // ---------------------------------------------------------------------
117 // Curated, commonly-used exports
118 // ---------------------------------------------------------------------
119 pub use mofa_kernel::agent::{
120 AgentCapabilities, AgentCapabilitiesBuilder, AgentContext, AgentError, AgentFactory,
121 AgentInput, AgentLifecycle, AgentMessage as CoreAgentMessage, AgentMessaging,
122 AgentMetadata, AgentOutput, AgentPluginSupport, AgentRequirements,
123 AgentRequirementsBuilder, AgentResult, AgentState, AgentStats, ChatCompletionRequest,
124 ChatCompletionResponse, ChatMessage, ContextConfig, CoordinationPattern, Coordinator,
125 DynAgent, ErrorCategory, ErrorContext, EventBuilder, EventBus, GlobalError, GlobalEvent,
126 GlobalMessage, GlobalResult, HealthStatus, InputType, InterruptResult, LLMProvider, Memory,
127 MemoryItem, MemoryStats, MemoryValue, Message, MessageContent, MessageMetadata,
128 MessageRole, MoFAAgent, OutputContent, OutputType, Reasoner, ReasoningResult,
129 ReasoningStep, ReasoningStepType, ReasoningStrategy, TokenUsage, Tool, ToolCall,
130 ToolDefinition, ToolDescriptor, ToolInput, ToolMetadata, ToolResult, ToolUsage,
131 execution_events, lifecycle, message_events, plugin_events, state_events,
132 };
133
134 // Core AgentConfig (runtime-level, lightweight)
135 pub use mofa_kernel::core::AgentConfig;
136
137 // Schema/config types for agent definitions
138 pub use mofa_kernel::agent::config::{
139 AgentConfig as AgentSchemaConfig, AgentType, ConfigFormat, ConfigLoader,
140 };
141
142 // Message-level events and task primitives (stream + scheduling included)
143 pub use mofa_kernel::message::{
144 AgentEvent, AgentMessage, SchedulingStatus, StreamControlCommand, StreamType, TaskPriority,
145 TaskRequest, TaskStatus,
146 };
147
148 // Bus
149 pub use mofa_kernel::bus::AgentBus;
150
151 // Plugin primitives
152 pub use mofa_kernel::plugin::{
153 AgentPlugin, HotReloadConfig, PluginContext, PluginEvent, PluginMetadata, PluginResult,
154 PluginState, PluginType, ReloadEvent, ReloadStrategy,
155 };
156
157 // Storage trait
158 pub use mofa_kernel::Storage;
159}
160
161// =============================================================================
162// Runtime Layer - Lifecycle and Execution
163// =============================================================================
164
165/// Agent lifecycle and execution management
166///
167/// This module provides runtime infrastructure for managing agent execution.
168///
169/// # Main Components
170///
171/// - `AgentBuilder`: Builder pattern for constructing agents
172/// - `SimpleRuntime`: Multi-agent coordination (non-dora)
173/// - `AgentRuntime`: Dora-rs integration (with `dora` feature)
174///
175/// # Example
176///
177/// ```rust,ignore
178/// use mofa_sdk::runtime::{AgentBuilder, SimpleRuntime};
179///
180/// let runtime = SimpleRuntime::new();
181/// runtime.register_agent(metadata, config, "worker").await?;
182/// ```
183pub mod runtime {
184 // Agent builder
185 pub use mofa_runtime::AgentBuilder;
186
187 // Simple runtime (non-dora)
188 pub use mofa_runtime::SimpleRuntime;
189
190 // Agent registry (runtime implementation)
191 pub use mofa_runtime::agent::{AgentFactory, AgentRegistry, RegistryStats};
192
193 // Agent runner (single-execution utilities)
194 pub use mofa_runtime::runner::{
195 AgentRunner, AgentRunnerBuilder, RunnerState, RunnerStats, run_agents,
196 };
197
198 pub use mofa_runtime::config::FrameworkConfig;
199
200 // Dora runtime (only available with dora feature)
201 #[cfg(feature = "dora")]
202 pub use mofa_runtime::{AgentRuntime, MoFARuntime};
203}
204
205// =============================================================================
206// Agent Layer - Foundation Agent Building Blocks
207// =============================================================================
208
209/// Agent building blocks and concrete implementations (foundation layer)
210pub mod agent {
211 pub use mofa_foundation::agent::*;
212}
213
214// =============================================================================
215// Prompt Layer - Prompt Composition & Management
216// =============================================================================
217
218/// Prompt templates, registries, and composition utilities
219pub mod prompt {
220 pub use mofa_foundation::prompt::*;
221}
222
223// =============================================================================
224// Coordination Layer - Task Coordination
225// =============================================================================
226
227/// Coordination strategies and schedulers (foundation layer)
228pub mod coordination {
229 pub use mofa_foundation::coordination::*;
230}
231
232// =============================================================================
233// Config Layer - Global Configuration
234// =============================================================================
235
236/// Global configuration facade (kernel + runtime + foundation)
237pub mod config {
238 /// Kernel config helpers and loaders
239 pub mod kernel {
240 pub use mofa_kernel::agent::config::*;
241 pub use mofa_kernel::config::*;
242 pub use mofa_kernel::core::AgentConfig as CoreAgentConfig;
243 }
244
245 /// Runtime config
246 pub mod runtime {
247 pub use mofa_runtime::config::*;
248 }
249
250 /// Foundation YAML config
251 pub mod foundation {
252 pub use mofa_foundation::config::*;
253 }
254
255 // Curated top-level re-exports
256 pub use mofa_foundation::config::{
257 AgentInfo, AgentYamlConfig, LLMYamlConfig, RuntimeConfig as YamlRuntimeConfig, ToolConfig,
258 };
259 pub use mofa_runtime::config::FrameworkConfig;
260}
261
262// =============================================================================
263// Foundation Layer - Business Functionality
264// =============================================================================
265
266/// Business functionality and concrete implementations
267///
268/// This module provides production-ready agent implementations and business logic.
269///
270/// # Modules
271///
272/// - `llm`: LLM integration (OpenAI, etc.)
273/// - `secretary`: Secretary agent pattern
274/// - `react`: ReAct (Reasoning + Acting) framework
275/// - `collaboration`: Multi-agent collaboration protocols
276/// - `persistence`: Database persistence
277pub mod foundation {
278 pub use super::agent;
279 pub use super::collaboration;
280 pub use super::config;
281 pub use super::coordination;
282 pub use super::llm;
283 pub use super::messaging;
284 pub use super::persistence;
285 pub use super::prompt;
286 pub use super::react;
287 pub use super::secretary;
288 pub use super::workflow;
289}
290
291// =============================================================================
292// Plugins (explicit module)
293// =============================================================================
294
295pub mod plugins {
296 pub use mofa_plugins::{
297 AgentPlugin,
298 AudioPlaybackConfig,
299 LLMPlugin,
300 LLMPluginConfig,
301 MemoryPlugin,
302 MemoryStorage,
303 MockTTSEngine,
304 // Kernel plugin primitives
305 PluginConfig,
306 PluginContext,
307 PluginEvent,
308 PluginManager,
309 PluginMetadata,
310 PluginResult,
311 PluginState,
312 PluginType,
313 RhaiPlugin,
314 RhaiPluginConfig,
315 RhaiPluginState,
316 StoragePlugin,
317 TTSCommand,
318 TTSEngine,
319 // TTS plugin types
320 TTSPlugin,
321 TTSPluginConfig,
322 TextToSpeechTool,
323 ToolCall,
324 ToolDefinition,
325 ToolExecutor,
326 ToolPlugin,
327 ToolPluginAdapter,
328 ToolResult,
329 VoiceInfo,
330 adapt_tool,
331 // TTS audio playback function
332 play_audio,
333 play_audio_async,
334 // Runtime plugin creation helpers
335 rhai_runtime,
336 tool,
337 tools,
338 wasm_runtime,
339 };
340
341 pub use mofa_kernel::PluginPriority;
342
343 // Re-export KokoroTTSWrapper when kokoro feature is enabled
344 #[cfg(feature = "kokoro")]
345 pub use mofa_plugins::KokoroTTS;
346
347 // Hot reload utilities
348 pub mod hot_reload {
349 pub use mofa_plugins::hot_reload::*;
350 }
351}
352
353// =============================================================================
354// Workflow (explicit module)
355// =============================================================================
356
357pub mod workflow {
358 //! Workflow orchestration module with LangGraph-inspired StateGraph API
359 //!
360 //! # StateGraph API (Recommended)
361 //!
362 //! The new StateGraph API provides a more intuitive way to build workflows:
363 //!
364 //! ```rust,ignore
365 //! use mofa_sdk::workflow::{StateGraphImpl, AppendReducer, OverwriteReducer, StateGraph, START, END};
366 //!
367 //! let graph = StateGraphImpl::<MyState>::new("my_workflow")
368 //! .add_reducer("messages", Box::new(AppendReducer))
369 //! .add_node("process", Box::new(ProcessNode))
370 //! .add_edge(START, "process")
371 //! .add_edge("process", END)
372 //! .compile()?;
373 //!
374 //! let result = graph.invoke(initial_state, None).await?;
375 //! ```
376 //!
377 //! # Legacy Workflow API
378 //!
379 //! The original WorkflowGraph API is still available for backward compatibility.
380
381 // Re-export kernel workflow types
382 pub use mofa_kernel::workflow::{
383 Command, CompiledGraph, ControlFlow, EdgeTarget, GraphConfig, GraphState, JsonState,
384 NodeFunc, Reducer, ReducerType, RemainingSteps, RuntimeContext, SendCommand, StateSchema,
385 StateUpdate, StreamEvent, StepResult, END, START,
386 };
387
388 // Re-export kernel StateGraph trait
389 pub use mofa_kernel::workflow::StateGraph;
390
391 // Foundation layer implementations
392 pub use mofa_foundation::workflow::{
393 // StateGraph implementation
394 CompiledGraphImpl, StateGraphImpl,
395 // Reducers
396 AppendReducer, ExtendReducer, FirstReducer, LastNReducer, LastReducer,
397 MergeReducer, OverwriteReducer, CustomReducer, create_reducer,
398 };
399
400 // Legacy workflow API
401 pub use mofa_foundation::workflow::{
402 ExecutionEvent, ExecutorConfig, WorkflowBuilder, WorkflowExecutor, WorkflowGraph,
403 WorkflowNode, WorkflowValue,
404 };
405
406 // DSL support
407 pub use mofa_foundation::workflow::dsl::{
408 AgentRef, DslError, DslResult, EdgeDefinition, LlmAgentConfig, LoopConditionDef,
409 NodeConfigDef, NodeDefinition, RetryPolicy, TaskExecutorDef, TimeoutConfig, TransformDef,
410 WorkflowConfig, WorkflowDefinition, WorkflowDslParser, WorkflowMetadata,
411 };
412}
413
414// =============================================================================
415// Prelude - Commonly Used Imports
416// =============================================================================
417
418/// Commonly used types for quick start
419pub mod prelude {
420 pub use crate::kernel::{
421 AgentCapabilities, AgentCapabilitiesBuilder, AgentContext, AgentError, AgentInput,
422 AgentMetadata, AgentOutput, AgentResult, AgentState, MoFAAgent,
423 };
424 pub use crate::runtime::{AgentBuilder, AgentRunner, SimpleRuntime, run_agents};
425 pub use async_trait::async_trait;
426}
427
428// Re-export dashboard module (only available with monitoring feature)
429#[cfg(feature = "monitoring")]
430pub mod dashboard {
431 pub use mofa_monitoring::*;
432}
433
434// Rhai scripting helpers (explicit module)
435pub mod rhai {
436 pub use mofa_extra::rhai::*;
437}
438
439mod llm_tools;
440
441// Re-export LLM module from mofa-foundation (always available)
442pub mod llm {
443 //! LLM (Large Language Model) integration module
444 //!
445 //! Provides LLM interaction capabilities for agents.
446 //!
447 //! # Quick Start
448 //!
449 //! ```rust,ignore
450 //! use mofa_sdk::llm::{LLMProvider, LLMClient, ChatMessage, ChatCompletionRequest};
451 //!
452 //! // Implement your LLM provider
453 //! struct MyProvider { /* ... */ }
454 //!
455 //! #[async_trait::async_trait]
456 //! impl LLMProvider for MyProvider {
457 //! fn name(&self) -> &str { "my-llm" }
458 //! async fn chat(&self, request: ChatCompletionRequest) -> LLMResult<ChatCompletionResponse> {
459 //! // Your implementation
460 //! }
461 //! }
462 //!
463 //! // Use the client
464 //! let client = LLMClient::new(Arc::new(MyProvider::new()));
465 //! let answer = client.ask("What is Rust?").await?;
466 //! ```
467
468 pub use crate::llm_tools::ToolPluginExecutor;
469 pub use mofa_foundation::llm::anthropic::{AnthropicConfig, AnthropicProvider};
470 pub use mofa_foundation::llm::google::{GeminiConfig, GeminiProvider};
471 pub use mofa_foundation::llm::openai::{OpenAIConfig, OpenAIProvider};
472 pub use mofa_foundation::llm::*;
473
474 /// 从环境变量创建 OpenAI 提供器
475 ///
476 /// 自动读取以下环境变量:
477 /// - OPENAI_API_KEY: API 密钥
478 /// - OPENAI_BASE_URL: 可选的 API 基础 URL
479 /// - OPENAI_MODEL: 可选的默认模型
480 ///
481 /// # 示例
482 ///
483 /// ```rust,ignore
484 /// use mofa_sdk::llm::openai_from_env;
485 ///
486 /// let provider = openai_from_env().unwrap();
487 /// ```
488 pub fn openai_from_env() -> Result<OpenAIProvider, crate::llm::LLMError> {
489 let api_key = std::env::var("OPENAI_API_KEY").map_err(|_| {
490 crate::llm::LLMError::ConfigError(
491 "OpenAI API key not found in environment variable OPENAI_API_KEY".to_string(),
492 )
493 })?;
494
495 let mut config = OpenAIConfig::new(api_key);
496
497 if let Ok(base_url) = std::env::var("OPENAI_BASE_URL") {
498 config = config.with_base_url(&base_url);
499 }
500
501 if let Ok(model) = std::env::var("OPENAI_MODEL") {
502 config = config.with_model(&model);
503 }
504
505 Ok(OpenAIProvider::with_config(config))
506 }
507}
508
509/// 从环境变量创建 Anthropic 提供器
510///
511/// 读取环境变量:
512/// - ANTHROPIC_API_KEY (必需)
513/// - ANTHROPIC_BASE_URL (可选)
514/// - ANTHROPIC_MODEL (可选)
515pub fn anthropic_from_env() -> Result<crate::llm::AnthropicProvider, crate::llm::LLMError> {
516 let api_key = std::env::var("ANTHROPIC_API_KEY").map_err(|_| {
517 crate::llm::LLMError::ConfigError(
518 "Anthropic API key not found in ANTHROPIC_API_KEY".to_string(),
519 )
520 })?;
521
522 let mut cfg = crate::llm::AnthropicConfig::new(api_key);
523 if let Ok(base_url) = std::env::var("ANTHROPIC_BASE_URL") {
524 cfg = cfg.with_base_url(base_url);
525 }
526 if let Ok(model) = std::env::var("ANTHROPIC_MODEL") {
527 cfg = cfg.with_model(model);
528 }
529
530 Ok(crate::llm::AnthropicProvider::with_config(cfg))
531}
532
533/// 从环境变量创建 Google Gemini 提供器
534///
535/// 读取环境变量:
536/// - GEMINI_API_KEY (必需)
537/// - GEMINI_BASE_URL (可选)
538/// - GEMINI_MODEL (可选)
539pub fn gemini_from_env() -> Result<crate::llm::GeminiProvider, crate::llm::LLMError> {
540 let api_key = std::env::var("GEMINI_API_KEY").map_err(|_| {
541 crate::llm::LLMError::ConfigError("Gemini API key not found in GEMINI_API_KEY".to_string())
542 })?;
543
544 let mut cfg = crate::llm::GeminiConfig::new(api_key);
545 if let Ok(base_url) = std::env::var("GEMINI_BASE_URL") {
546 cfg = cfg.with_base_url(base_url);
547 }
548 if let Ok(model) = std::env::var("GEMINI_MODEL") {
549 cfg = cfg.with_model(model);
550 }
551
552 Ok(crate::llm::GeminiProvider::with_config(cfg))
553}
554
555// Re-export Secretary module from mofa-foundation (always available)
556pub mod secretary {
557 //! 秘书Agent模式 - 基于事件循环的智能助手
558 //!
559 //! 秘书Agent是一个面向用户的智能助手,通过与LLM交互完成个人助理工作。
560 //! 设计为与长连接配合使用,实现持续的交互式服务。
561 //!
562 //! ## 工作循环(5阶段事件循环)
563 //!
564 //! 1. **接收想法** → 记录并生成TODO
565 //! 2. **澄清需求** → 与用户交互,转换为项目文档
566 //! 3. **调度分配** → 调用对应的执行Agent
567 //! 4. **监控反馈** → 推送关键决策给人类
568 //! 5. **验收汇报** → 更新TODO,生成报告
569 //!
570 //! # Quick Start
571 //!
572 //! ```rust,ignore
573 //! use mofa_sdk::secretary::{
574 //! AgentInfo, DefaultSecretaryBuilder, ChannelConnection, DefaultInput,
575 //! SecretaryOutput, TodoPriority,
576 //! };
577 //! use std::sync::Arc;
578 //!
579 //! #[tokio::main]
580 //! async fn main() -> anyhow::Result<()> {
581 //! // 1. 创建秘书Agent
582 //! let mut backend_agent = AgentInfo::new("backend_agent", "后端Agent");
583 //! backend_agent.capabilities = vec!["backend".to_string()];
584 //! backend_agent.current_load = 0;
585 //! backend_agent.available = true;
586 //! backend_agent.performance_score = 0.9;
587 //!
588 //! let secretary = DefaultSecretaryBuilder::new()
589 //! .with_id("my_secretary")
590 //! .with_name("项目秘书")
591 //! .with_auto_clarify(true)
592 //! .with_executor(backend_agent)
593 //! .build()
594 //! .await;
595 //!
596 //! // 2. 创建通道连接
597 //! let (conn, input_tx, mut output_rx) = ChannelConnection::new_pair(32);
598 //!
599 //! // 3. 启动事件循环
600 //! let handle = secretary.start(conn).await;
601 //!
602 //! // 4. 发送用户输入
603 //! input_tx.send(DefaultInput::Idea {
604 //! content: "开发一个REST API".to_string(),
605 //! priority: Some(TodoPriority::High),
606 //! metadata: None,
607 //! }).await?;
608 //!
609 //! // 5. 处理秘书输出
610 //! while let Some(output) = output_rx.recv().await {
611 //! match output {
612 //! SecretaryOutput::Acknowledgment { message } => {
613 //! info!("秘书: {}", message);
614 //! }
615 //! SecretaryOutput::DecisionRequired { decision } => {
616 //! info!("需要决策: {}", decision.description);
617 //! // 处理决策...
618 //! }
619 //! SecretaryOutput::Report { report } => {
620 //! info!("汇报: {}", report.content);
621 //! }
622 //! _ => {}
623 //! }
624 //! }
625 //!
626 //! handle.await??;
627 //! Ok(())
628 //! }
629 //! ```
630 //!
631 //! # 自定义LLM Provider
632 //!
633 //! ```rust,ignore
634 //! use mofa_sdk::secretary::{LLMProvider, ChatMessage};
635 //! use std::sync::Arc;
636 //!
637 //! struct MyLLMProvider {
638 //! api_key: String,
639 //! }
640 //!
641 //! #[async_trait::async_trait]
642 //! impl LLMProvider for MyLLMProvider {
643 //! fn name(&self) -> &str { "my-llm" }
644 //!
645 //! async fn chat(&self, messages: Vec<ChatMessage>) -> anyhow::Result<String> {
646 //! // 调用你的LLM API
647 //! Ok("LLM响应".to_string())
648 //! }
649 //! }
650 //!
651 //! // 使用自定义LLM
652 //! let llm = Arc::new(MyLLMProvider { api_key: "...".to_string() });
653 //! let secretary = DefaultSecretaryBuilder::new()
654 //! .with_llm(llm)
655 //! .build()
656 //! .await;
657 //! ```
658
659 pub use mofa_foundation::secretary::*;
660}
661
662// Re-export React module from mofa-foundation (always available)
663pub mod react {
664 //! ReAct (Reasoning + Acting) 框架
665 //!
666 //! ReAct 是一种将推理和行动相结合的智能代理架构。
667 //! 代理通过"思考-行动-观察"循环来解决问题。
668
669 pub use mofa_foundation::react::*;
670}
671
672// Re-export collaboration module from mofa-foundation (always available)
673pub mod collaboration {
674 //! 自适应协作协议模块
675 //!
676 //! 提供多 Agent 自适应协作的标准协议实现,支持根据任务描述动态切换协作模式。
677 //!
678 //! # 标准协议
679 //!
680 //! - `RequestResponseProtocol`: 请求-响应模式,适合数据处理任务
681 //! - `PublishSubscribeProtocol`: 发布-订阅模式,适合创意生成任务
682 //! - `ConsensusProtocol`: 共识机制模式,适合决策制定任务
683 //! - `DebateProtocol`: 辩论模式,适合审查任务
684 //! - `ParallelProtocol`: 并行模式,适合分析任务
685 //!
686 //! # 快速开始
687 //!
688 //! ```rust,ignore
689 //! use mofa_sdk::collaboration::{
690 //! RequestResponseProtocol, PublishSubscribeProtocol, ConsensusProtocol,
691 //! LLMDrivenCollaborationManager,
692 //! };
693 //! use std::sync::Arc;
694 //!
695 //! #[tokio::main]
696 //! async fn main() -> anyhow::Result<()> {
697 //! let manager = LLMDrivenCollaborationManager::new("agent_001");
698 //!
699 //! // 注册标准协议
700 //! manager.register_protocol(Arc::new(RequestResponseProtocol::new("agent_001"))).await?;
701 //! manager.register_protocol(Arc::new(PublishSubscribeProtocol::new("agent_001"))).await?;
702 //! manager.register_protocol(Arc::new(ConsensusProtocol::new("agent_001"))).await?;
703 //!
704 //! // 执行任务(使用自然语言描述,系统自动选择合适的协议)
705 //! let result = manager.execute_task(
706 //! "处理数据: [1, 2, 3]", // 任务描述
707 //! serde_json::json!({"data": [1, 2, 3]})
708 //! ).await?;
709 //!
710 //! println!("Result: {:?}", result);
711 //! Ok(())
712 //! }
713 //! ```
714
715 pub use mofa_foundation::collaboration::*;
716}
717
718// =============================================================================
719// Persistence module (re-export from mofa-foundation)
720// =============================================================================
721
722// Re-export Persistence module from mofa-foundation
723pub mod persistence {
724 pub use mofa_foundation::persistence::*;
725
726 /// 快速创建带 PostgreSQL 持久化的 LLM Agent
727 ///
728 /// 自动处理:
729 /// - 数据库连接(从 DATABASE_URL)
730 /// - OpenAI Provider(从 OPENAI_API_KEY)
731 /// - 持久化插件
732 /// - 自动生成 user_id、tenant_id、agent_id 和 session_id
733 ///
734 /// # 环境变量
735 /// - DATABASE_URL: PostgreSQL 连接字符串
736 /// - OPENAI_API_KEY: OpenAI API 密钥
737 /// - USER_ID: 用户 ID(可选)
738 /// - TENANT_ID: 租户 ID(可选)
739 /// - AGENT_ID: Agent ID(可选)
740 /// - SESSION_ID: 会话 ID(可选)
741 ///
742 /// # 示例
743 ///
744 /// ```rust,ignore
745 /// use mofa_sdk::persistence::quick_agent_with_postgres;
746 ///
747 /// #[tokio::main]
748 /// async fn main() -> mofa_sdk::llm::LLMResult<()> {
749 /// let agent = quick_agent_with_postgres("你是一个有用的助手")
750 /// .await?
751 /// .with_name("聊天助手")
752 /// .build_async()
753 /// .await;
754 /// Ok(())
755 /// }
756 /// ```
757 #[cfg(all(feature = "persistence-postgres"))]
758 pub async fn quick_agent_with_postgres(
759 system_prompt: &str,
760 ) -> Result<crate::llm::LLMAgentBuilder, crate::llm::LLMError> {
761 use std::sync::Arc;
762
763 // 1. 初始化数据库
764 let store_arc = PostgresStore::from_env().await.map_err(|e| {
765 crate::llm::LLMError::Other(format!("数据库连接失败: {}", e.to_string()))
766 })?;
767
768 // 2. 从环境变量获取或生成 IDs
769 let user_id = std::env::var("USER_ID")
770 .ok()
771 .and_then(|s| uuid::Uuid::parse_str(&s).ok())
772 .unwrap_or_else(uuid::Uuid::now_v7);
773
774 let tenant_id = std::env::var("TENANT_ID")
775 .ok()
776 .and_then(|s| uuid::Uuid::parse_str(&s).ok())
777 .unwrap_or_else(uuid::Uuid::now_v7);
778
779 let agent_id = std::env::var("AGENT_ID")
780 .ok()
781 .and_then(|s| uuid::Uuid::parse_str(&s).ok())
782 .unwrap_or_else(uuid::Uuid::now_v7);
783
784 let session_id = std::env::var("SESSION_ID")
785 .ok()
786 .and_then(|s| uuid::Uuid::parse_str(&s).ok())
787 .unwrap_or_else(uuid::Uuid::now_v7);
788
789 // 3. 创建持久化插件(直接使用 Arc<PostgresStore> 作为存储)
790 let plugin = PersistencePlugin::new(
791 "persistence-plugin",
792 store_arc.clone(),
793 store_arc,
794 user_id,
795 tenant_id,
796 agent_id,
797 session_id,
798 );
799
800 // 4. 返回预配置的 builder
801 Ok(crate::llm::LLMAgentBuilder::from_env()?
802 .with_system_prompt(system_prompt)
803 .with_plugin(plugin))
804 }
805
806 /// 快速创建带内存持久化的 LLM Agent
807 ///
808 /// 使用内存存储,适合测试和开发环境。
809 ///
810 /// # 环境变量
811 /// - OPENAI_API_KEY: OpenAI API 密钥
812 ///
813 /// # 示例
814 ///
815 /// ```rust,ignore
816 /// use mofa_sdk::persistence::quick_agent_with_memory;
817 ///
818 /// #[tokio::main]
819 /// async fn main() -> mofa_sdk::llm::LLMResult<()> {
820 /// let agent = quick_agent_with_memory("你是一个有用的助手")
821 /// .await?
822 /// .with_name("聊天助手")
823 /// .build_async()
824 /// .await;
825 /// Ok(())
826 /// }
827 /// ```
828 pub async fn quick_agent_with_memory(
829 system_prompt: &str,
830 ) -> Result<crate::llm::LLMAgentBuilder, crate::llm::LLMError> {
831 let store = InMemoryStore::new();
832
833 // 生成 IDs
834 let user_id = uuid::Uuid::now_v7();
835 let tenant_id = uuid::Uuid::now_v7();
836 let agent_id = uuid::Uuid::now_v7();
837 let session_id = uuid::Uuid::now_v7();
838
839 let plugin = PersistencePlugin::from_store(
840 "persistence-plugin",
841 store,
842 user_id,
843 tenant_id,
844 agent_id,
845 session_id,
846 );
847
848 Ok(crate::llm::LLMAgentBuilder::from_env()?
849 .with_system_prompt(system_prompt)
850 .with_plugin(plugin))
851 }
852}
853
854// =============================================================================
855// Messaging module (re-export from mofa-foundation)
856// =============================================================================
857
858// Re-export Messaging module from mofa-foundation
859pub mod messaging {
860 //! Generic message bus framework for decoupled agent architectures
861 //!
862 //! Provides:
863 //! - Generic message types with pub/sub patterns
864 //! - Inbound/outbound message separation
865 //! - Trait-based message contracts
866 //!
867 //! # Quick Start
868 //!
869 //! ```rust,ignore
870 //! use mofa_sdk::messaging::{MessageBus, SimpleInboundMessage, SimpleOutboundMessage};
871 //!
872 //! let bus = MessageBus::new(100);
873 //!
874 //! // Subscribe to inbound messages
875 //! let mut rx = bus.subscribe_inbound();
876 //!
877 //! // Publish a message
878 //! let msg = SimpleInboundMessage::new("telegram", "user", "chat", "Hello");
879 //! bus.publish_inbound(msg).await?;
880 //! ```
881
882 pub use mofa_foundation::messaging::*;
883}
884
885// =============================================================================
886// Dora-rs runtime support (enabled with `dora` feature)
887// =============================================================================
888
889#[cfg(feature = "dora")]
890pub mod dora {
891 //! Dora-rs adapter for distributed dataflow runtime
892 //!
893 //! This module provides MoFA framework integration with dora-rs, including:
894 //! - DoraNode wrapper: Agent lifecycle management
895 //! - DoraOperator wrapper: Plugin capability abstraction
896 //! - DoraDataflow wrapper: Multi-agent collaborative dataflow
897 //! - DoraChannel wrapper: Cross-agent communication channel
898 //! - DoraRuntime wrapper: Complete runtime support (embedded/distributed)
899 //!
900 //! # Example
901 //!
902 //! ```rust,ignore
903 //! use mofa_sdk::dora::{DoraRuntime, RuntimeConfig, run_dataflow};
904 //!
905 //! #[tokio::main]
906 //! async fn main() -> eyre::Result<()> {
907 //! // Quick run with helper function
908 //! let result = run_dataflow("dataflow.yml").await?;
909 //! info!("Dataflow {} completed", result.uuid);
910 //!
911 //! // Or use the builder pattern
912 //! let mut runtime = DoraRuntime::embedded("dataflow.yml");
913 //! let result = runtime.run().await?;
914 //! Ok(())
915 //! }
916 //! ```
917
918 // Re-export dora adapter types
919 pub use mofa_runtime::dora_adapter::*;
920
921 // Re-export dora-specific runtime types from mofa_runtime root
922 pub use mofa_runtime::{AgentBuilder, AgentRuntime, MoFARuntime};
923}
924
925// =============================================================================
926// Agent Skills - Progressive Disclosure Skills System
927// =============================================================================
928
929// Module declaration for skills (public)
930pub mod skills;
931
932// Public skills module with re-exports