@ondeinference / ed Mirror · read-only
Fork 0

Read-only mirror of github.com/ondeinference/ed.

Mirrored from https://github.com/ondeinference/ed.git

Synced Nov 23, 01:00 UTC

main
rs 134 lines 4.37 KB
Raw
1 //! Ed in the browser.
2 //!
3 //! [`WebChat`] wraps one [`Ed`] and is meant to live in a Web Worker: loading
4 //! the model and every token's forward pass block the thread they run on. The
5 //! page talks to it through `www/worker.js`.
6 //!
7 //! Each method returns a `Promise` and holds its own `Rc<Ed>`, because
8 //! wasm-bindgen would otherwise borrow `&self` across the whole await and a
9 //! second call (a `reset` while a reply streams) would panic.
10
11 use std::rc::Rc;
12
13 use ed_agent::{Ed, GgufModelConfig};
14 use js_sys::{Function, Promise};
15 use wasm_bindgen::prelude::*;
16 use wasm_bindgen_futures::future_to_promise;
17
18 /// The model this example runs: the catalogue's smallest (about 380 MB). The
19 /// preset comes from onde, so no model name is written here.
20 fn model() -> GgufModelConfig {
21 GgufModelConfig::qwen25_0_5b()
22 }
23
24 fn to_js_error(e: impl std::fmt::Display) -> JsValue {
25 JsValue::from_str(&e.to_string())
26 }
27
28 fn number(n: u64) -> JsValue {
29 JsValue::from_f64(n as f64)
30 }
31
32 #[wasm_bindgen]
33 pub struct WebChat {
34 ed: Rc<Ed>,
35 }
36
37 impl Default for WebChat {
38 fn default() -> Self {
39 Self::new()
40 }
41 }
42
43 #[wasm_bindgen]
44 impl WebChat {
45 #[wasm_bindgen(constructor)]
46 pub fn new() -> WebChat {
47 console_error_panic_hook::set_once();
48 WebChat {
49 ed: Rc::new(Ed::new()),
50 }
51 }
52
53 /// Display name and size of the model, for the first-run card.
54 pub fn model_label(&self) -> String {
55 let config = model();
56 format!("{}, {}", config.display_name, config.approx_memory)
57 }
58
59 /// Resolves to whether the model is already in the browser cache.
60 pub fn is_cached(&self) -> Promise {
61 future_to_promise(async move {
62 Ok(JsValue::from_bool(
63 onde::web_store::is_cached(&model()).await,
64 ))
65 })
66 }
67
68 /// Download the model into the browser cache. `on_progress(received, total)`
69 /// gets byte counts; `total` is `null` when the server hides the length.
70 pub fn download(&self, on_progress: Function) -> Promise {
71 future_to_promise(async move {
72 onde::web_store::download_model(&model(), |received, total| {
73 let total = total.map_or(JsValue::NULL, number);
74 let _ = on_progress.call2(&JsValue::NULL, &number(received), &total);
75 })
76 .await
77 .map_err(to_js_error)?;
78 Ok(JsValue::UNDEFINED)
79 })
80 }
81
82 /// Remove the downloaded model from the browser cache.
83 pub fn delete_cached(&self) -> Promise {
84 future_to_promise(async move {
85 let removed = onde::web_store::delete_model(&model())
86 .await
87 .map_err(to_js_error)?;
88 Ok(JsValue::from_bool(removed))
89 })
90 }
91
92 /// Load the model into memory (downloading it first if it isn't cached).
93 /// Resolves to the load time in seconds.
94 pub fn load(&self, system_prompt: Option<String>) -> Promise {
95 let ed = self.ed.clone();
96 future_to_promise(async move {
97 let took = ed
98 .load(model(), system_prompt, None)
99 .await
100 .map_err(to_js_error)?;
101 Ok(JsValue::from_f64(took.as_secs_f64()))
102 })
103 }
104
105 /// Send one message. `on_delta(text)` is called for each piece as it is
106 /// generated; the promise resolves with the whole reply.
107 pub fn send(&self, message: String, on_delta: Function) -> Promise {
108 let ed = self.ed.clone();
109 future_to_promise(async move {
110 let mut stream = ed.stream(message).await.map_err(to_js_error)?;
111 let mut reply = String::new();
112 while let Some(piece) = stream.next().await {
113 let piece = piece.map_err(to_js_error)?;
114 reply.push_str(&piece);
115 let _ = on_delta.call1(&JsValue::NULL, &JsValue::from_str(&piece));
116 }
117 Ok(JsValue::from_str(&reply))
118 })
119 }
120
121 /// Forget the conversation. Resolves to how many messages were dropped.
122 pub fn reset(&self) -> Promise {
123 let ed = self.ed.clone();
124 future_to_promise(async move { Ok(number(ed.clear_history().await as u64)) })
125 }
126
127 /// Engine status, model name and history length.
128 pub fn info(&self) -> Promise {
129 let ed = self.ed.clone();
130 future_to_promise(async move {
131 serde_wasm_bindgen::to_value(&ed.info().await).map_err(to_js_error)
132 })
133 }
134 }