MolyKit Skill
Best Practices für die Entwicklung von KI-Chat-Oberflächen mit Makepad unter Verwendung von MolyKit – einem Toolkit für plattformübergreifende KI-Chat-Anwendungen.
Quellcodebasis: /Users/zhangalex/Work/Projects/FW/robius/moly/moly-kit
Wann verwenden
Dieses Skill verwenden, wenn:
- KI-Chat-Oberflächen mit Makepad entwickelt werden
- OpenAI oder andere LLM-APIs integriert werden
- Plattformübergreifendes Async für native und WASM implementiert wird
- Chat-Widgets (Nachrichten, Eingabeaufforderungen, Avatare) erstellt werden
- SSE-Streaming-Antworten verarbeitet werden
- Schlüsselwörter: molykit, moly-kit, ai chat, bot client, openai makepad, chat widget, sse streaming
Überblick
MolyKit bietet:
- Plattformübergreifende Async-Hilfsprogramme (PlatformSend, spawn(), ThreadToken)
- Fertig einsatzbereite Chat-Widgets (Chat, Messages, PromptInput, Avatar)
- BotClient-Trait für die KI-Anbieterintegration
- OpenAI-kompatiblen Client mit SSE-Streaming
- Protokolltypen für Nachrichten, Bots und Tool-Aufrufe
- MCP (Model Context Protocol)-Unterstützung
Plattformübergreifende Async-Muster
PlatformSend – Nur auf nativen Plattformen senden
/// Impliziert Send nur auf nativen Plattformen, nicht auf WASM
/// - Auf nativen Plattformen: implementiert von Typen, die Send implementieren
/// - Auf WASM: von ALLEN Typen implementiert
pub trait PlatformSend: PlatformSendInner {}
/// Boxed-Future-Typ für plattformübergreifende Verwendung
pub type BoxPlatformSendFuture<'a, T> = Pin<Box<dyn PlatformSendFuture<Output = T> + 'a>>;
/// Boxed-Stream-Typ für plattformübergreifende Verwendung
pub type BoxPlatformSendStream<'a, T> = Pin<Box<dyn PlatformSendStream<Item = T> + 'a>>;
Plattformunabhängiges Spawning
/// Führt eine Future unabhängig aus
/// - Verwendet tokio auf nativen Plattformen (erfordert Send)
/// - Verwendet wasm-bindgen-futures auf WASM (kein Send erforderlich)
pub fn spawn(fut: impl PlatformSendFuture<Output = ()> + 'static);
// Verwendung
spawn(async move {
let result = fetch_data().await;
Cx::post_action(DataReady(result));
SignalToUI::set_ui_signal();
});
Aufgabenabbruch mit AbortOnDropHandle
/// Handle, das seine Future beim Löschen abbricht
pub struct AbortOnDropHandle(AbortHandle);
// Verwendung – Aufgabe wird abgebrochen, wenn Widget gelöscht wird
#[rust]
task_handle: Option<AbortOnDropHandle>,
fn start_task(&mut self) {
let (future, handle) = abort_on_drop(async move {
// asynchrone Arbeit...
});
self.task_handle = Some(handle);
spawn(async move { let _ = future.await; });
}
ThreadToken für Nicht-Send-Typen auf WASM
/// Nicht-Send-Wert im Thread-Local speichern, Zugriff über Token
pub struct ThreadToken<T: 'static>;
impl<T> ThreadToken<T> {
pub fn new(value: T) -> Self;
pub fn peek<R>(&self, f: impl FnOnce(&T) -> R) -> R;
pub fn peek_mut<R>(&self, f: impl FnOnce(&mut T) -> R) -> R;
}
// Verwendung – Nicht-Send-Typ für die Verwendung über Send-Grenzen hinweg umschließen
let token = ThreadToken::new(non_send_value);
spawn(async move {
token.peek(|value| {
// Wert verwenden...
});
});
BotClient-Trait
Implementierung der KI-Anbieterintegration
pub trait BotClient: Send {
/// Nachricht mit gestreamter Antwort senden
fn send(
&mut self,
bot_id: &BotId,
messages: &[Message],
tools: &[Tool],
) -> BoxPlatformSendStream<'static, ClientResult<MessageContent>>;
/// Verfügbare Bots/Modelle abrufen
fn bots(&self) -> BoxPlatformSendFuture<'static, ClientResult<Vec<Bot>>>;
/// Zum Weitergeben klonen
fn clone_box(&self) -> Box<dyn BotClient>;
}
// Verwendung
let client = OpenAIClient::new("https://api.openai.com/v1".into());
client.set_key("sk-...")?;
let context = BotContext::from(client);
BotContext – Teilbarer Wrapper
/// Teilbarer Wrapper mit geladenen Bots für synchronen UI-Zugriff
pub struct BotContext(Arc<Mutex<InnerBotContext>>);
impl BotContext {
pub fn load(&mut self) -> BoxPlatformSendFuture<ClientResult<()>>;
pub fn bots(&self) -> Vec<Bot>;
pub fn get_bot(&self, id: &BotId) -> Option<Bot>;
pub fn client(&self) -> Box<dyn BotClient>;
}
// Verwendung
let mut context = BotContext::from(client);
spawn(async move {
if let Err(errors) = context.load().await.into_result() {
// Fehler behandeln
}
Cx::post_action(BotsLoaded);
});
Protokolltypen
Nachrichtenstruktur
pub struct Message {
pub from: EntityId, // Benutzer, System, Bot(BotId), App
pub metadata: MessageMetadata,
pub content: MessageContent,
}
pub struct MessageContent {
pub text: String, // Hauptinhalt (Markdown)
pub reasoning: String, // KI-Argumentation/Denken
pub citations: Vec<String>, // Quell-URLs
pub attachments: Vec<Attachment>,
pub tool_calls: Vec<ToolCall>,
pub tool_results: Vec<ToolResult>,
}
pub struct MessageMetadata {
pub is_writing: bool, // Wird noch gestreamt
pub created_at: DateTime<Utc>,
}
Bot-Identifikation
/// Global eindeutige Bot-ID: <len>;<id>@<provider>
pub struct BotId(Arc<str>);
impl BotId {
pub fn new(id: &str, provider: &str) -> Self;
pub fn id(&self) -> &str; // Provider-lokale ID
pub fn provider(&self) -> &str; // Provider-Domain
}
// Beispiel: BotId::new("gpt-4", "api.openai.com")
// -> "5;[email protected]"
Widget-Muster
Slot-Widget – Laufzeitaustausch von Inhalten
live_design! {
pub Slot = {{Slot}} {
width: Fill, height: Fit,
slot = <View> {} // Standardinhalt
}
}
// Verwendung – Inhalt zur Laufzeit ersetzen
let mut slot = widget.slot(id!(content));
if let Some(custom) = client.content_widget(cx, ...) {
slot.replace(custom);
} else {
slot.restore(); // zurück zum Standard
slot.default().as_standard_message_content().set_content(cx, &content);
}
Avatar-Widget – Text/Bild-Umschaltung
live_design! {
pub Avatar = {{Avatar}} <View> {
grapheme = <RoundedView> {
visible: false,
label = <Label> { text: "P" }
}
dependency = <RoundedView> {
visible: false,
image = <Image> {}
}
}
}
impl Widget for Avatar {
fn draw_walk(&mut self, cx: &mut Cx2d, ...) -> DrawStep {
if let Some(avatar) = &self.avatar {
match avatar {
Picture::Grapheme(g) => {
self.view(id!(grapheme)).set_visible(cx, true);
self.view(id!(dependency)).set_visible(cx, false);
self.label(id!(label)).set_text(cx, &g);
}
Picture::Dependency(d) => {
self.view(id!(dependency)).set_visible(cx, true);
self.view(id!(grapheme)).set_visible(cx, false);
self.image(id!(image)).load_image_dep_by_path(cx, d.as_str());
}
}
}
self.deref.draw_walk(cx, scope, walk)
}
}
PromptInput-Widget
#[derive(Live, Widget)]
pub struct PromptInput {
#[deref] deref: CommandTextInput,
#[live] pub send_icon: LiveValue,
#[live] pub stop_icon: LiveValue,
#[rust] pub task: Task, // Senden oder Stoppen
#[rust] pub interactivity: Interactivity,
}
impl PromptInput {
pub fn submitted(&self, actions: &Actions) -> bool;
pub fn reset(&mut self, cx: &mut Cx);
pub fn set_send(&mut self);
pub fn set_stop(&mut self);
pub fn enable(&mut self);
pub fn disable(&mut self);
}
Messages-Widget – Konversationsansicht
#[derive(Live, Widget)]
pub struct Messages {
#[deref] deref: View,
#[rust] pub messages: Vec<Message>,
#[rust] pub bot_context: Option<BotContext>,
}
impl Messages {
pub fn set_messages(&mut self, messages: Vec<Message>, scroll_to_bottom: bool);
pub fn scroll_to_bottom(&mut self, cx: &mut Cx, triggered_by_stream: bool);
pub fn is_at_bottom(&self) -> bool;
}
UiRunner-Muster für Async-zu-UI
impl Widget for PromptInput {
fn handle_event(&mut self, cx: &mut Cx, event: &Event, scope: &mut Scope) {
self.deref.handle_event(cx, event, scope);
self.ui_runner().handle(cx, event, scope, self);
if self.button(id!(attach)).clicked(event.actions()) {
let ui = self.ui_runner();
Attachment::pick_multiple(move |result| match result {
Ok(attachments) => {
ui.defer_with_redraw(move |me, cx, _| {
me.attachment_list_ref().write().attachments.extend(attachments);
});
}
Err(_) => {}
});
}
}
}
SSE-Streaming
/// SSE-Byte-Stream in Nachrichten-Stream parsen
pub fn parse_sse<S, B, E>(s: S) -> impl Stream<Item = Result<String, E>>
where
S: Stream<Item = Result<B, E>>,
B: AsRef<[u8]>,
{
// Bei "\n\n" trennen, "data:"-Inhalt extrahieren
// Kommentare und [DONE]-Nachrichten filtern
}
// Verwendung in BotClient::send
fn send(&mut self, ...) -> BoxPlatformSendStream<...> {
let stream = stream! {
let response = client.post(url).send().await?;
let events = parse_sse(response.bytes_stream());
for await event in events {
let completion: Completion = serde_json::from_str(&event)?;
content.text.push_str(&completion.delta.content);
yield ClientResult::new_ok(content.clone());
}
};
Box::pin(stream)
}
Best Practices
- PlatformSend für plattformübergreifende Nutzung verwenden: Gleicher Code funktioniert auf nativen Plattformen und WASM
- spawn() statt tokio::spawn() verwenden: Plattformunabhängiges Task-Spawning
- AbortOnDropHandle verwenden: Aufgaben abbrechen, wenn Widget gelöscht wird
- ThreadToken für Nicht-Send auf WASM verwenden: Thread-lokaler Speicher mit Token-Zugriff
- Slot für benutzerdefinierte Inhalte verwenden: BotClient erlaubt die Bereitstellung benutzerdefinierter Widgets
- read()/write()-Muster verwenden: Sicherer Borrow-Zugriff über WidgetRef
- UiRunner::defer_with_redraw verwenden: Widget aus asynchronem Kontext aktualisieren
- ClientResult-Teil Erfolg behandeln: Kann sowohl Wert als auch Fehler enthalten
Referenzdateien
llms.txt– Vollständige MolyKit-API-Referenz