MolyKit 스킬은(는) 무엇을 하나요?
Makepad과 MolyKit을 사용하여 크로스 플랫폼 AI 채팅 인터페이스를 구축하기 위한 모범 사례입니다. MolyKit은 크로스 플랫폼 AI 채팅 애플리케이션을 위한 툴킷입니다.
소스 코드베이스: /Users/zhangalex/Work/Projects/FW/robius/moly/moly-kit
사용 시기
다음과 같은 경우 이 스킬을 사용하세요:
- Makepad로 AI 채팅 인터페이스 구축
- OpenAI 또는 기타 LLM API 통합
- 네이티브 및 WASM을 위한 크로스 플랫폼 비동기 구현
- 채팅 위젯(메시지, 프롬프트, 아바타) 생성
- SSE 스트리밍 응답 처리
- 키워드: molykit, moly-kit, ai chat, bot client, openai makepad, chat widget, sse streaming
개요
MolyKit은 다음을 제공합니다:
- 크로스 플랫폼 비동기 유틸리티 (PlatformSend, spawn(), ThreadToken)
- 바로 사용 가능한 채팅 위젯 (Chat, Messages, PromptInput, Avatar)
- AI 제공자 통합을 위한 BotClient 트레이트
- SSE 스트리밍을 지원하는 OpenAI 호환 클라이언트
- 메시지, 봇 및 도구 호출을 위한 프로토콜 타입
- MCP (모델 컨텍스트 프로토콜) 지원
크로스 플랫폼 비동기 패턴
PlatformSend - 네이티브에서만 전송 가능
/// 네이티브 플랫폼에서만 Send를 의미하며 WASM에서는 아님
/// - 네이티브: Send를 구현하는 타입에 의해 구현됨
/// - WASM: 모든 타입에 의해 구현됨
pub trait PlatformSend: PlatformSendInner {}
/// 크로스 플랫폼 사용을 위한 박스형 퓨처 타입
pub type BoxPlatformSendFuture<'a, T> = Pin<Box<dyn PlatformSendFuture<Output = T> + 'a>>;
/// 크로스 플랫폼 사용을 위한 박스형 스트림 타입
pub type BoxPlatformSendStream<'a, T> = Pin<Box<dyn PlatformSendStream<Item = T> + 'a>>;
플랫폼에 구애받지 않는 생성(Spawning)
/// 퓨처를 독립적으로 실행합니다.
/// - 네이티브에서는 tokio 사용 (Send 필요)
/// - WASM에서는 wasm-bindgen-futures 사용 (Send 불필요)
pub fn spawn(fut: impl PlatformSendFuture<Output = ()> + 'static);
// 사용법
spawn(async move {
let result = fetch_data().await;
Cx::post_action(DataReady(result));
SignalToUI::set_ui_signal();
});
AbortOnDropHandle을 사용한 작업 취소
/// 드롭될 때 퓨처를 중단하는 핸들
pub struct AbortOnDropHandle(AbortHandle);
// 사용법 - 위젯이 드롭되면 작업 취소됨
#[rust]
task_handle: Option<AbortOnDropHandle>,
fn start_task(&mut self) {
let (future, handle) = abort_on_drop(async move {
// 비동기 작업...
});
self.task_handle = Some(handle);
spawn(async move { let _ = future.await; });
}
WASM에서 Non-Send 타입을 위한 ThreadToken
/// Non-Send 값을 스레드 로컬에 저장하고 토큰을 통해 접근
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;
}
// 사용법 - Send 경계를 넘어 사용하기 위해 non-Send 타입 래핑
let token = ThreadToken::new(non_send_value);
spawn(async move {
token.peek(|value| {
// 값 사용...
});
});
BotClient 트레이트
AI 제공자 통합 구현
pub trait BotClient: Send {
/// 스트리밍 응답으로 메시지 전송
fn send(
&mut self,
bot_id: &BotId,
messages: &[Message],
tools: &[Tool],
) -> BoxPlatformSendStream<'static, ClientResult<MessageContent>>;
/// 사용 가능한 봇/모델 가져오기
fn bots(&self) -> BoxPlatformSendFuture<'static, ClientResult<Vec<Bot>>>;
/// 전달을 위한 복제
fn clone_box(&self) -> Box<dyn BotClient>;
}
// 사용법
let client = OpenAIClient::new("https://api.openai.com/v1".into());
client.set_key("sk-...")?;
let context = BotContext::from(client);
BotContext - 공유 가능한 래퍼
/// 동기 UI 접근을 위해 로드된 봇과 함께 공유 가능한 래퍼
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>;
}
// 사용법
let mut context = BotContext::from(client);
spawn(async move {
if let Err(errors) = context.load().await.into_result() {
// 오류 처리
}
Cx::post_action(BotsLoaded);
});
프로토콜 타입
메시지 구조체
pub struct Message {
pub from: EntityId, // User, System, Bot(BotId), App
pub metadata: MessageMetadata,
pub content: MessageContent,
}
pub struct MessageContent {
pub text: String, // 주요 내용 (마크다운)
pub reasoning: String, // AI 추론/사고
pub citations: Vec<String>, // 출처 URL
pub attachments: Vec<Attachment>,
pub tool_calls: Vec<ToolCall>,
pub tool_results: Vec<ToolResult>,
}
pub struct MessageMetadata {
pub is_writing: bool, // 아직 스트리밍 중
pub created_at: DateTime<Utc>,
}
봇 식별
/// 전역 고유 봇 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-local id
pub fn provider(&self) -> &str; // provider domain
}
// 예제: BotId::new("gpt-4", "api.openai.com")
// -> "5;[email protected]"
위젯 패턴
Slot 위젯 - 런타임 콘텐츠 교체
live_design! {
pub Slot = {{Slot}} {
width: Fill, height: Fit,
slot = <View> {} // 기본 콘텐츠
}
}
// 사용법 - 런타임에 콘텐츠 교체
let mut slot = widget.slot(id!(content));
if let Some(custom) = client.content_widget(cx, ...) {
slot.replace(custom);
} else {
slot.restore(); // 기본값으로 복원
slot.default().as_standard_message_content().set_content(cx, &content);
}
Avatar 위젯 - 텍스트/이미지 전환
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 위젯
#[derive(Live, Widget)]
pub struct PromptInput {
#[deref] deref: CommandTextInput,
#[live] pub send_icon: LiveValue,
#[live] pub stop_icon: LiveValue,
#[rust] pub task: Task, // Send 또는 Stop
#[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 위젯 - 대화 보기
#[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;
}
비동기-UI를 위한 UiRunner 패턴
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 스트리밍
/// SSE 바이트 스트림을 메시지 스트림으로 파싱
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]>,
{
// "\n\n"로 분할, "data:" 콘텐츠 추출
// 주석 및 [DONE] 메시지 필터링
}
// 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)
}
모범 사례
- 크로스 플랫폼을 위해 PlatformSend 사용: 네이티브와 WASM에서 동일한 코드 작동
- tokio::spawn 대신 spawn() 사용: 플랫폼에 구애받지 않는 작업 생성
- AbortOnDropHandle 사용: 위젯 드롭 시 작업 취소
- WASM에서 non-Send를 위해 ThreadToken 사용: 토큰 접근을 통한 스레드 로컬 저장소
- 사용자 정의 콘텐츠를 위해 Slot 사용: BotClient가 사용자 정의 위젯을 제공할 수 있도록 함
- read()/write() 패턴 사용: WidgetRef를 통한 안전한 빌림 접근
- UiRunner::defer_with_redraw 사용: 비동기 컨텍스트에서 위젯 업데이트
- ClientResult 부분 성공 처리: 값과 오류를 모두 가질 수 있음
참조 파일
llms.txt- 전체 MolyKit API 참조