Advanced Start
Advanced Start is built from runnable Rust examples. The story below follows the same source files that appear under Examples, so code changes start in src/examples/rust/.
Rust Typed Generation
Start with a typed contract: the model receives named inputs and Ax parses named outputs.
Runs a small typed generation program against OpenAI.
- Level:
beginner - Run:
npm run example -- rust src/examples/rust/generation/basic_generation.rs - Source: src/examples/rust/generation/basic_generation.rs
- More in this group: Generation examples
use axllm::{ax, AxResult, OpenAICompatibleClient};
use serde_json::json;
use std::env;
fn openai_client() -> AxResult<OpenAICompatibleClient> {
let api_key = env::var("OPENAI_API_KEY").or_else(|_| env::var("OPENAI_APIKEY")).map_err(|_| axllm::AxError::runtime("Set OPENAI_API_KEY or OPENAI_APIKEY to run this example."))?;
let model = env::var("AX_OPENAI_MODEL").unwrap_or_else(|_| "gpt-5.4-mini".to_string());
Ok(OpenAICompatibleClient::new(api_key, model).with_model_config(json!({"temperature": 0})))
}
fn main() -> AxResult<()> {
let mut client = openai_client()?;
let mut program = ax("question:string -> answer:string")?;
let output = program.forward(&mut client, json!({"question": "In one sentence, explain Ax as a language-agnostic LLM programming library."}))?;
println!("{}", serde_json::to_string_pretty(&output)?);
Ok(())
}Rust Grounded Support Agent
Move to an agent when the model needs a runtime loop and a final typed answer.
Answers a support question grounded in a handbook that is kept out of the model prompt via contextFields.
- Level:
beginner - Run:
npm run example -- rust src/examples/rust/short-agents/basic_agent.rs - Source: src/examples/rust/short-agents/basic_agent.rs
- More in this group: Agents examples
use axllm::runtime::quickjs::QuickJsCodeRuntime;
use axllm::{agent_with_options, AxResult, OpenAICompatibleClient};
use serde_json::json;
use std::env;
fn openai_client() -> AxResult<OpenAICompatibleClient> {
let api_key = env::var("OPENAI_API_KEY")
.or_else(|_| env::var("OPENAI_APIKEY"))
.map_err(|_| {
axllm::AxError::runtime("Set OPENAI_API_KEY or OPENAI_APIKEY to run this example.")
})?;
let model = env::var("AX_OPENAI_MODEL").unwrap_or_else(|_| "gpt-5.4-mini".to_string());
Ok(OpenAICompatibleClient::new(api_key, model).with_model_config(json!({"temperature": 0})))
}
fn main() -> AxResult<()> {
let mut client = openai_client()?;
// The handbook can be arbitrarily large. Listing it in `contextFields` keeps
// it in the agent's runtime so it never inflates the model prompt -- the agent
// reads it through code, not through tokens.
let handbook = r#"
# Acme Cloud -- Support Handbook
## Billing
- Invoices are issued on the 1st of each month and are due net-15.
- Plan downgrades take effect at the END of the current billing cycle, not immediately.
- Refunds are issued to the original payment method within 5 business days.
## Access
- Seats can be added by any workspace Owner under Settings -> Members.
- SSO (SAML) is available on Enterprise; SCIM provisioning is Owner-only.
## Incidents
- Status and uptime are published at status.acme.example.
- Sev-1 incidents page the on-call within 5 minutes; updates post every 30 minutes.
## Data
- Exports are available in CSV and JSON from Settings -> Data.
- Deleted workspaces are recoverable for 30 days, then permanently purged.
"#;
// `with_runtime` attaches the embedded JS engine so the agent loop can run.
let mut assistant = agent_with_options(
"question:string, handbook:string -> answer:string, citations:string[] \"Handbook sections the answer relies on\"",
json!({"contextFields": ["handbook"], "runtime": {"language": "JavaScript"}}),
)?
.with_runtime(Box::new(QuickJsCodeRuntime::new()))?;
let output = assistant.forward_with_options(
&mut client,
json!({
"question": "A customer downgraded their plan today. When does it take effect, and can they get a refund for the current cycle?",
"handbook": handbook,
}),
json!({"max_actor_steps": 12}),
)?;
println!("{}", serde_json::to_string_pretty(&output)?);
Ok(())
}Rust Sequential Flow
Use a flow when the application should own the order of multi-step work.
Runs a two-step Ax flow against OpenAI.
- Level:
beginner - Run:
npm run example -- rust src/examples/rust/flows/sequential_flow.rs - Source: src/examples/rust/flows/sequential_flow.rs
- More in this group: Flows examples
use axllm::{ax, flow, AxResult, OpenAICompatibleClient};
use serde_json::json;
use std::env;
fn openai_client() -> AxResult<OpenAICompatibleClient> {
let api_key = env::var("OPENAI_API_KEY").or_else(|_| env::var("OPENAI_APIKEY")).map_err(|_| axllm::AxError::runtime("Set OPENAI_API_KEY or OPENAI_APIKEY to run this example."))?;
let model = env::var("AX_OPENAI_MODEL").unwrap_or_else(|_| "gpt-5.4-mini".to_string());
Ok(OpenAICompatibleClient::new(api_key, model).with_model_config(json!({"temperature": 0})))
}
fn main() -> AxResult<()> {
let mut client = openai_client()?;
let step = ax("documentText:string -> summaryText:string")?;
let mut program = axllm::flow("examples.sequentialFlow").execute("step", step).returns(json!({"step": "step"}));
let output = program.forward(&mut client, json!({"documentText": "Ax gives developers signatures, provider clients, agents, flows, tracing, and optimization."}))?;
println!("{}", serde_json::to_string_pretty(&output)?);
Ok(())
}Rust Text To Speech
Add audio when the same provider-backed contract should accept or produce speech.
Generates speech audio through OpenAI.
- Level:
beginner - Run:
npm run example -- rust src/examples/rust/audio/speech_audio.rs - Source: src/examples/rust/audio/speech_audio.rs
- More in this group: Audio examples
use axllm::{ax, AxAIClient, AxResult, OpenAICompatibleClient};
use serde_json::json;
use std::{env, fs};
fn openai_client() -> AxResult<OpenAICompatibleClient> {
let api_key = env::var("OPENAI_API_KEY").or_else(|_| env::var("OPENAI_APIKEY")).map_err(|_| axllm::AxError::runtime("Set OPENAI_API_KEY or OPENAI_APIKEY to run this example."))?;
let model = env::var("AX_OPENAI_MODEL").unwrap_or_else(|_| "gpt-5.4-mini".to_string());
Ok(OpenAICompatibleClient::new(api_key, model).with_model_config(json!({"temperature": 0})))
}
fn main() -> AxResult<()> {
let mut client = openai_client()?;
let speech = client.speak(json!({"text": "Ax turns LLM prompts into typed programs.", "voice": "alloy", "format": "mp3"}))?;
let audio_len = speech["audio"].as_str().unwrap_or("").len();
println!("{}", serde_json::to_string_pretty(&json!({"format": speech["format"].clone(), "audioBytesBase64": audio_len}))?);
Ok(())
}Rust AxGen Optimization
Close the loop by measuring examples and applying optimizer artifacts to the program.
Runs a baseline OpenAI prediction and applies an optimizer artifact.
- Level:
beginner - Run:
npm run example -- rust src/examples/rust/optimization/axgen_optimization.rs - Source: src/examples/rust/optimization/axgen_optimization.rs
- More in this group: Optimization examples
use axllm::{ax, AxResult, OpenAICompatibleClient, OptimizerEngine};
use serde_json::{json, Value};
use std::env;
struct ExampleOptimizer;
impl OptimizerEngine for ExampleOptimizer {
fn optimize(&mut self, _request: Value, _evaluator: &mut dyn FnMut(Value) -> AxResult<Value>) -> AxResult<Value> {
Ok(json!({"componentMap": {"priority::instruction": "Classify operational risk. Use high for production-impacting urgency."}, "metadata": {"source": "axgen"}}))
}
}
fn openai_client() -> AxResult<OpenAICompatibleClient> {
let api_key = env::var("OPENAI_API_KEY").or_else(|_| env::var("OPENAI_APIKEY")).map_err(|_| axllm::AxError::runtime("Set OPENAI_API_KEY or OPENAI_APIKEY to run this example."))?;
let model = env::var("AX_OPENAI_MODEL").unwrap_or_else(|_| "gpt-5.4-mini".to_string());
Ok(OpenAICompatibleClient::new(api_key, model).with_model_config(json!({"temperature": 0})))
}
fn main() -> AxResult<()> {
let mut client = openai_client()?;
let mut program = ax("emailText:string -> priority:class \"high, normal, low\", rationale:string")?;
let baseline = program.forward(&mut client, json!({"emailText": "Production checkout is failing for enterprise customers."}))?;
let mut optimizer = ExampleOptimizer;
let artifact = optimizer.optimize(json!({"candidate": "priority"}), &mut |_candidate| Ok(json!({"score": 1.0})))?;
println!("{}", serde_json::to_string_pretty(&json!({"baseline": baseline, "artifact": artifact}))?);
Ok(())
}