Komponen
Apa Itu Komponen?
Section titled “Apa Itu 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
Jenis Komponen
Section titled “Jenis Komponen”| Type | Purpose | Example |
|---|---|---|
| Node | Langkah pemrosesan flow | Pemanggil LLM, renderer template |
| Provider | Jembatan layanan eksternal | Telegram, Slack, SendGrid |
| Tool | Implementasi tool MCP | Query database, panggilan API |
| Operator | Transformasi pesan | Penanganan tombol, rendering card |
Membuat Komponen
Section titled “Membuat Komponen”Setup Proyek
Section titled “Setup Proyek”Gunakan CLI authoring komponen:
# Create new component projectgreentic-component new my-processor
cd my-processorIni akan menghasilkan:
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 = trueAntarmuka WIT
Section titled “Antarmuka WIT”Definisikan antarmuka komponen Anda:
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;}Implementasi
Section titled “Implementasi”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
Pola Komponen Lanjutan
Section titled “Pola Komponen Lanjutan”Operasi Async
Section titled “Operasi Async”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, } }}Manajemen State
Section titled “Manajemen State”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, } }}Penanganan Error
Section titled “Penanganan Error”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, }) }}Komponen Bawaan
Section titled “Komponen Bawaan”Greentic menyediakan beberapa komponen bawaan:
component-llm-openai
Section titled “component-llm-openai”Panggil LLM yang kompatibel dengan OpenAI:
- id: analyze type: llm config: model: "gpt-4" system_prompt: "You are a helpful assistant." prompt: "{{message}}"component-templates
Section titled “component-templates”Render template Handlebars:
- id: format type: template config: template: "Hello, {{name}}! Your order #{{order_id}} is ready."component-script-rhai
Section titled “component-script-rhai”Eksekusi script 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”Render dan validasi Adaptive Card:
- id: show_card type: adaptive-card config: card: "cards/welcome.json" data: user_name: "{{user_name}}"Menguji Komponen
Section titled “Menguji Komponen”Unit Test
Section titled “Unit Test”#[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")); }}Integration Test
Section titled “Integration Test”# Run with test harnessgreentic-component test ./my-processor
# Test with sample inputecho '{"message": "test"}' | greentic-component run ./my-processor.wasmPraktik Terbaik Komponen
Section titled “Praktik Terbaik Komponen”- Jaga fokus komponen - Satu tanggung jawab
- Tangani semua error - Jangan pernah panic di produksi
- Minimalkan dependensi - Binary WASM lebih kecil
- Gunakan tipe yang kuat - Manfaatkan WIT untuk type safety
- Dokumentasikan antarmuka - Definisi WIT yang jelas
- Uji secara menyeluruh - Unit test dan integration test
- Optimalkan ukuran - Gunakan LTO dan optimasi ukuran
Debugging Komponen
Section titled “Debugging Komponen”Inspeksi WASM
Section titled “Inspeksi WASM”# Inspect component exportswasm-tools component wit ./my-processor.wasm
# Validate componentwasm-tools validate ./my-processor.wasmLogging
Section titled “Logging”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 }}Langkah Berikutnya
Section titled “Langkah Berikutnya”- Providers - Bangun komponen provider
- MCP Tools - Buat komponen tool MCP
- WIT Interfaces Reference - Spesifikasi WIT lengkap