1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
use crate::streams::ByteStream;
use crate::{env::EnvBinding, send::SendFuture};
use crate::{Error, Result};
use serde::de::DeserializeOwned;
use serde::Serialize;
use wasm_bindgen::{JsCast, JsValue};
use wasm_bindgen_futures::JsFuture;
use web_sys::ReadableStream;
use worker_sys::Ai as AiSys;
/// Enables access to Workers AI functionality.
#[derive(Debug)]
pub struct Ai(AiSys);
impl Ai {
/// Execute a Workers AI operation using the specified model.
/// Various forms of the input are documented in the Workers
/// AI documentation.
pub async fn run<T: Serialize, U: DeserializeOwned>(
&self,
model: impl AsRef<str>,
input: T,
) -> Result<U> {
let fut = SendFuture::new(JsFuture::from(
self.0
.run(model.as_ref(), serde_wasm_bindgen::to_value(&input)?),
));
match fut.await {
Ok(output) => Ok(serde_wasm_bindgen::from_value(output)?),
Err(err) => Err(Error::from(err)),
}
}
/// Execute a Workers AI operation that returns binary data as a [`ByteStream`].
///
/// This method is designed for AI models that return raw bytes, such as:
/// - Image generation models (e.g., Stable Diffusion)
/// - Text-to-speech models
/// - Any other model that returns binary output
///
/// The returned [`ByteStream`] implements [`Stream`](futures_util::Stream) and can be:
/// - Streamed directly to a [`Response`] using [`Response::from_stream`]
/// - Collected into a `Vec<u8>` by iterating over the chunks
///
/// # Examples
///
/// ## Streaming directly to a response (recommended)
///
/// This approach is more memory-efficient as it doesn't buffer the entire
/// response in memory:
///
/// ```ignore
/// use worker::*;
/// use serde::Serialize;
///
/// #[derive(Serialize)]
/// struct ImageGenRequest {
/// prompt: String,
/// }
///
/// async fn generate_image(env: &Env) -> Result<Response> {
/// let ai = env.ai("AI")?;
/// let request = ImageGenRequest {
/// prompt: "a beautiful sunset".to_string(),
/// };
/// let stream = ai.run_bytes(
/// "@cf/stabilityai/stable-diffusion-xl-base-1.0",
/// &request
/// ).await?;
///
/// // Stream directly to the response
/// let mut response = Response::from_stream(stream)?;
/// response.headers_mut().set("Content-Type", "image/png")?;
/// Ok(response)
/// }
/// ```
///
/// ## Collecting into bytes
///
/// Use this approach if you need to inspect or modify the bytes before sending:
///
/// ```ignore
/// use worker::*;
/// use serde::Serialize;
/// use futures_util::StreamExt;
///
/// #[derive(Serialize)]
/// struct ImageGenRequest {
/// prompt: String,
/// }
///
/// async fn generate_image(env: &Env) -> Result<Response> {
/// let ai = env.ai("AI")?;
/// let request = ImageGenRequest {
/// prompt: "a beautiful sunset".to_string(),
/// };
/// let mut stream = ai.run_bytes(
/// "@cf/stabilityai/stable-diffusion-xl-base-1.0",
/// &request
/// ).await?;
///
/// // Collect all chunks into a Vec<u8>
/// let mut bytes = Vec::new();
/// while let Some(chunk) = stream.next().await {
/// bytes.extend_from_slice(&chunk?);
/// }
///
/// let mut response = Response::from_bytes(bytes)?;
/// response.headers_mut().set("Content-Type", "image/png")?;
/// Ok(response)
/// }
/// ```
pub async fn run_bytes<T: Serialize>(
&self,
model: impl AsRef<str>,
input: T,
) -> Result<ByteStream> {
let fut = SendFuture::new(JsFuture::from(
self.0
.run(model.as_ref(), serde_wasm_bindgen::to_value(&input)?),
));
match fut.await {
Ok(output) => {
if output.is_instance_of::<ReadableStream>() {
let stream = ReadableStream::unchecked_from_js(output);
Ok(ByteStream::from(stream))
} else {
Err(Error::RustError(
"AI model did not return binary data. Use run() for non-binary responses."
.into(),
))
}
}
Err(err) => Err(Error::from(err)),
}
}
}
unsafe impl Sync for Ai {}
unsafe impl Send for Ai {}
impl From<AiSys> for Ai {
fn from(inner: AiSys) -> Self {
Self(inner)
}
}
impl AsRef<JsValue> for Ai {
fn as_ref(&self) -> &JsValue {
&self.0
}
}
impl From<Ai> for JsValue {
fn from(database: Ai) -> Self {
JsValue::from(database.0)
}
}
impl JsCast for Ai {
fn instanceof(val: &JsValue) -> bool {
val.is_instance_of::<AiSys>()
}
fn unchecked_from_js(val: JsValue) -> Self {
Self(val.into())
}
fn unchecked_from_js_ref(val: &JsValue) -> &Self {
unsafe { &*(val as *const JsValue as *const Self) }
}
}
impl EnvBinding for Ai {
const TYPE_NAME: &'static str = "Ai";
fn get(val: JsValue) -> Result<Self> {
let obj = js_sys::Object::from(val);
if obj.constructor().name() == Self::TYPE_NAME {
Ok(obj.unchecked_into())
} else {
Err(format!(
"Binding cannot be cast to the type {} from {}",
Self::TYPE_NAME,
obj.constructor().name()
)
.into())
}
}
}