pub struct Ai(/* private fields */);Expand description
Enables access to Workers AI functionality.
Implementations§
Source§impl Ai
impl Ai
Sourcepub async fn run<T: Serialize, U: DeserializeOwned>(
&self,
model: impl AsRef<str>,
input: T,
) -> Result<U>
pub async fn run<T: Serialize, U: DeserializeOwned>( &self, model: impl AsRef<str>, input: T, ) -> Result<U>
Execute a Workers AI operation using the specified model. Various forms of the input are documented in the Workers AI documentation.
Sourcepub async fn run_bytes<T: Serialize>(
&self,
model: impl AsRef<str>,
input: T,
) -> Result<ByteStream>
pub async fn run_bytes<T: Serialize>( &self, model: impl AsRef<str>, input: T, ) -> Result<ByteStream>
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 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:
ⓘ
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:
ⓘ
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)
}Trait Implementations§
Source§impl EnvBinding for Ai
impl EnvBinding for Ai
Source§impl JsCast for Ai
impl JsCast for Ai
Source§fn instanceof(val: &JsValue) -> bool
fn instanceof(val: &JsValue) -> bool
Performs a dynamic
instanceof check to see whether the JsValue
provided is an instance of this type. Read moreSource§fn unchecked_from_js(val: JsValue) -> Self
fn unchecked_from_js(val: JsValue) -> Self
Source§fn unchecked_from_js_ref(val: &JsValue) -> &Self
fn unchecked_from_js_ref(val: &JsValue) -> &Self
Source§fn has_type<T>(&self) -> boolwhere
T: JsCast,
fn has_type<T>(&self) -> boolwhere
T: JsCast,
Test whether this JS value has a type
T. Read moreSource§fn dyn_into<T>(self) -> Result<T, Self>where
T: JsCast,
fn dyn_into<T>(self) -> Result<T, Self>where
T: JsCast,
Performs a dynamic cast (checked at runtime) of this value into the
target type
T. Read moreSource§fn dyn_ref<T>(&self) -> Option<&T>where
T: JsCast,
fn dyn_ref<T>(&self) -> Option<&T>where
T: JsCast,
Performs a dynamic cast (checked at runtime) of this value into the
target type
T. Read moreSource§fn unchecked_into<T>(self) -> Twhere
T: JsCast,
fn unchecked_into<T>(self) -> Twhere
T: JsCast,
Performs a zero-cost unchecked cast into the specified type. Read more
Source§fn unchecked_ref<T>(&self) -> &Twhere
T: JsCast,
fn unchecked_ref<T>(&self) -> &Twhere
T: JsCast,
Performs a zero-cost unchecked cast into a reference to the specified
type. Read more
impl Send for Ai
impl Sync for Ai
Auto Trait Implementations§
impl Freeze for Ai
impl RefUnwindSafe for Ai
impl Unpin for Ai
impl UnsafeUnpin for Ai
impl UnwindSafe for Ai
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more