Components
什么是 Component?
Section titled “什么是 Component?”Component 是一个可移植的 WebAssembly (WASM) 构建单元,实现了 Greentic 的 WIT 接口。Components 具有以下特性:
- Sandboxed - 在隔离的 WASM 环境中执行
- Portable - 可在任何带有 Wasmtime 的平台上运行
- Composable - 可组合构建复杂工作流
- Language-agnostic - 可使用 Rust、Go 或任何兼容 WASM 的语言编写
Component 类型
Section titled “Component 类型”| 类型 | 用途 | 示例 |
|---|---|---|
| Node | Flow 处理步骤 | LLM 调用器、模板渲染器 |
| Provider | 外部服务桥接 | Telegram、Slack、SendGrid |
| Tool | MCP tool 实现 | 数据库查询、API 调用 |
| Operator | 消息转换 | 按钮处理、卡片渲染 |
创建一个 Component
Section titled “创建一个 Component”使用组件编写 CLI:
# Create new component projectgreentic-component new my-processor
cd my-processor这会生成:
my-processor/├── Cargo.toml├── src/│ └── lib.rs├── wit/│ └── component.wit└── build.shCargo.toml
Section titled “Cargo.toml”[package]name = "my-processor"version = "0.1.0"edition = "2024"
[lib]crate-type = ["cdylib"]
[dependencies]wit-bindgen = "0.53"serde = { version = "1.0", features = ["derive"] }serde_json = "1.0"
[profile.release]opt-level = "s"lto = trueWIT 接口
Section titled “WIT 接口”定义你的组件接口:
package greentic:my-processor;
interface types { record input { message: string, context: option<string>, }
record output { result: string, success: bool, }}
world processor { import types;
export process: func(input: types.input) -> types.output;}use wit_bindgen::generate;
generate!({ world: "processor", path: "wit",});
struct MyProcessor;
impl Guest for MyProcessor { fn process(input: Input) -> Output { // Your processing logic here let result = format!("Processed: {}", input.message);
Output { result, success: true, } }}
export!(MyProcessor);# Build for WASM targetcargo build --target wasm32-wasip2 --release
高级 Component 模式
Section titled “高级 Component 模式”Components 可以使用 WASI 接口执行异步操作:
use wit_bindgen::generate;
generate!({ world: "async-processor", path: "wit", async: true,});
impl Guest for AsyncProcessor { async fn process(input: Input) -> Output { // Async HTTP call let response = http_fetch(&input.url).await;
Output { result: response.body, success: response.status == 200, } }}在 components 中访问 session state:
impl Guest for StatefulProcessor { fn process(input: Input, state: &mut State) -> Output { // Read from state let counter = state.get("counter").unwrap_or(0);
// Update state state.set("counter", counter + 1);
Output { result: format!("Processed {} times", counter + 1), success: true, } }}使用 Result 类型进行错误处理:
impl Guest for SafeProcessor { fn process(input: Input) -> Result<Output, Error> { if input.message.is_empty() { return Err(Error::InvalidInput("Message cannot be empty".into())); }
Ok(Output { result: process_message(&input.message)?, success: true, }) }}内置 Components
Section titled “内置 Components”Greentic 提供了多个内置 components:
component-llm-openai
Section titled “component-llm-openai”调用兼容 OpenAI 的 LLM:
- id: analyze type: llm config: model: "gpt-4" system_prompt: "You are a helpful assistant." prompt: "{{message}}"component-templates
Section titled “component-templates”渲染 Handlebars 模板:
- id: format type: template config: template: "Hello, {{name}}! Your order #{{order_id}} is ready."component-script-rhai
Section titled “component-script-rhai”执行 Rhai 脚本:
- id: calculate type: script config: script: | let total = 0; for item in items { total += item.price * item.quantity; } totalcomponent-adaptive-card
Section titled “component-adaptive-card”渲染并校验 Adaptive Cards:
- id: show_card type: adaptive-card config: card: "cards/welcome.json" data: user_name: "{{user_name}}"测试 Components
Section titled “测试 Components”#[cfg(test)]mod tests { use super::*;
#[test] fn test_process() { let input = Input { message: "Hello".into(), context: None, };
let output = MyProcessor::process(input);
assert!(output.success); assert!(output.result.contains("Processed")); }}# Run with test harnessgreentic-component test ./my-processor
# Test with sample inputecho '{"message": "test"}' | greentic-component run ./my-processor.wasmComponent 最佳实践
Section titled “Component 最佳实践”- 保持组件聚焦 - 单一职责
- 处理所有错误 - 生产环境中绝不要 panic
- 尽量减少依赖 - 减小 WASM 二进制体积
- 使用强类型 - 利用 WIT 保证类型安全
- 记录接口文档 - 保持 WIT 定义清晰
- 充分测试 - 包含单元测试和集成测试
- 优化体积 - 使用 LTO 和体积优化
调试 Components
Section titled “调试 Components”WASM 检查
Section titled “WASM 检查”# Inspect component exportswasm-tools component wit ./my-processor.wasm
# Validate componentwasm-tools validate ./my-processor.wasm使用 WASI 日志接口:
use greentic_interfaces::log;
impl Guest for DebugProcessor { fn process(input: Input) -> Output { log::debug(&format!("Processing: {:?}", input));
// ... processing ...
log::info("Processing complete"); output }}- Providers - 构建 provider components
- MCP Tools - 创建 MCP tool components
- WIT Interfaces Reference - 完整 WIT 规范