Rust Requires Chilkat v11.2.0+
Rust
AI: Simple Stateless Streaming Response
See more AI Examples
Shows a simple stateless query and receives the response in streaming mode.Chilkat Rust Downloads
// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
let ai = chilkat::Ai::new();
// The provider can be "openai", "google", "claude", "deepseek", "xai", or "perplexity".
// Support for additional providers will be added in future versions of Chilkat.
ai.set_provider("openai");
// Use your provider's API key.
ai.set_api_key("MY_API_KEY");
// Choose a model.
ai.set_model("gpt-5.6-terra");
// Indicate streaming mode is to be used.
ai.set_streaming(true);
// Add a text input.
let _ = ai.input_add_text("Write a detailed story about a turtle who decides to run a bakery. Describe the setting, the kinds of pastries, how the turtle feels, and include at least three paragraphs.");
// Ask the AI for text output.
if ai.ask("text").is_err() {
println!("{}", ai.last_error_text());
return;
}
let sb_event_name = chilkat::StringBuilder::new();
let sb_delta = chilkat::StringBuilder::new();
let sb_full_response = chilkat::StringBuilder::new();
let mut finished = false;
let abort_flag = false;
let max_wait_ms = 5000;
while !finished {
let result = ai.poll_ai(abort_flag);
if result == 1 {
// We have output waiting. It should be instantly available. The maxWaitMs is just-in-case.
if ai.next_ai_event(max_wait_ms, &sb_event_name, &sb_delta).is_err() {
println!("{}", ai.last_error_text());
return;
}
// Some AI providers send many "empty" events. Just ignore them.
if !sb_event_name.contents_equal("empty", true) {
// Log the non-empty events.
println!("{}", sb_event_name.get_as_string().unwrap_or_default());
// The delta contains the new output. This could be emitted to a display or the terminal
// as real-time output.
if sb_event_name.contents_equal("delta", true) {
println!("{}", sb_delta.get_as_string().unwrap_or_default());
// Accumulate the delta's so we can show the full response later.
let _ = sb_full_response.append_sb(&sb_delta);
} else {
// A streaming AI response is always terminated by a single "null_terminator" event.
finished = sb_event_name.contents_equal("null_terminator", true);
}
}
} else {
if result == 0 {
// Nothing is immediately available. Sleep for 1/10 of a second before polling again.
ai.sleep_ms(100);
} else {
// Something failed..
println!("{}", ai.last_error_text());
finished = true;
}
}
}
// Show the accumulated (full) response.
println!("----");
println!("{}", sb_full_response.get_as_string().unwrap_or_default());
// -------------------------------------------------------------
// The response is in markdown format.
// Also see Markdown to HTML Conversion Examples.
// -------------------------------------------------------------