Lewati ke konten

Komponen

Component adalah building block WebAssembly (WASM) portabel yang mengimplementasikan antarmuka Greentic WIT. Komponen bersifat:

  • Sandboxed - Dieksekusi dalam environment WASM yang terisolasi
  • Portable - Berjalan di platform apa pun dengan Wasmtime
  • Composable - Dapat digabungkan untuk membangun workflow yang kompleks
  • Language-agnostic - Dapat ditulis dalam Rust, Go, atau bahasa lain yang kompatibel dengan WASM
TypePurposeExample
NodeLangkah pemrosesan flowPemanggil LLM, renderer template
ProviderJembatan layanan eksternalTelegram, Slack, SendGrid
ToolImplementasi tool MCPQuery database, panggilan API
OperatorTransformasi pesanPenanganan tombol, rendering card

Gunakan CLI authoring komponen:

Terminal window
# Create new component project
greentic-component new my-processor
cd my-processor

Ini akan menghasilkan:

my-processor/
├── Cargo.toml
├── src/
│ └── lib.rs
├── wit/
│ └── component.wit
└── build.sh
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 = true

Definisikan antarmuka komponen Anda:

wit/component.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;
}
src/lib.rs
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);
target/wasm32-wasip2/release/my_processor.wasm
# Build for WASM target
cargo build --target wasm32-wasip2 --release

Komponen dapat menjalankan operasi async menggunakan antarmuka 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,
}
}
}

Akses state session di dalam komponen:

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,
}
}
}

Gunakan tipe Result untuk penanganan error:

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,
})
}
}

Greentic menyediakan beberapa komponen bawaan:

Panggil LLM yang kompatibel dengan OpenAI:

- id: analyze
type: llm
config:
model: "gpt-4"
system_prompt: "You are a helpful assistant."
prompt: "{{message}}"

Render template Handlebars:

- id: format
type: template
config:
template: "Hello, {{name}}! Your order #{{order_id}} is ready."

Eksekusi script Rhai:

- id: calculate
type: script
config:
script: |
let total = 0;
for item in items {
total += item.price * item.quantity;
}
total

Render dan validasi Adaptive Card:

- id: show_card
type: adaptive-card
config:
card: "cards/welcome.json"
data:
user_name: "{{user_name}}"
src/lib.rs
#[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"));
}
}
Terminal window
# Run with test harness
greentic-component test ./my-processor
# Test with sample input
echo '{"message": "test"}' | greentic-component run ./my-processor.wasm
  1. Jaga fokus komponen - Satu tanggung jawab
  2. Tangani semua error - Jangan pernah panic di produksi
  3. Minimalkan dependensi - Binary WASM lebih kecil
  4. Gunakan tipe yang kuat - Manfaatkan WIT untuk type safety
  5. Dokumentasikan antarmuka - Definisi WIT yang jelas
  6. Uji secara menyeluruh - Unit test dan integration test
  7. Optimalkan ukuran - Gunakan LTO dan optimasi ukuran
Terminal window
# Inspect component exports
wasm-tools component wit ./my-processor.wasm
# Validate component
wasm-tools validate ./my-processor.wasm

Gunakan antarmuka logging 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
}
}