Skip to content

ReAct agent

warpra_prebuilt::create_react_agent builds a prebuilt ReAct agent: a model node and a tools node in a loop. It works with any nexura_core::ChatModel and any list of nexura_core::Tools.

use std::sync::Arc;
use warpra::RunConfig;
use warpra_prebuilt::{create_react_agent, AgentOptions};
async fn demo(model: Arc<dyn nexura_core::ChatModel>, tools: Vec<Arc<dyn nexura_core::Tool>>) -> Result<(), Box<dyn std::error::Error>> {
let agent = create_react_agent(model, tools, AgentOptions::new().prompt("You are helpful").interrupt_before_tools())?;
let out = agent.invoke(serde_json::json!({"messages": [{"role": "user", "content": "hi"}]}), RunConfig::thread("t1")).await?;
let _ = out;
Ok(())
}

The result is a Pregel, like any compiled graph. State is {"messages": [...]} with add_messages.

With SQLite checkpoints and human approval

Section titled “With SQLite checkpoints and human approval”

This is the react_agent example in the repository (cargo run -p warpra-prebuilt --example react_agent). The agent pauses before running tools. A second “process” opens the same SQLite file and resumes the thread. The models are scripted with FakeChatModel, so it runs offline.

use std::sync::Arc;
use nexura_core::{FnTool, Tool, ToolCall, ToolOutput, ToolSpec};
use nexura_llm::fake::{FakeChatModel, Response};
use warpra::RunConfig;
use warpra_checkpoint_sqlite::SqliteSaver;
use warpra_prebuilt::{create_react_agent, AgentOptions};
use serde_json::{json, Value};
fn weather_tool() -> Arc<dyn Tool> {
Arc::new(FnTool::new(
ToolSpec::new("weather", "Get the weather for a city", json!({"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]})),
|args, _ctx| async move { Ok(ToolOutput::text(format!("sunny in {}", args["city"].as_str().unwrap_or("?")))) },
))
}
fn last_text(state: &Value) -> String {
state["messages"].as_array().and_then(|m| m.last()).and_then(|m| m["content"].as_str()).unwrap_or_default().to_string()
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let dir = tempfile::tempdir()?;
let db = dir.path().join("agent.db");
let cfg = RunConfig::thread("trip-42");
// Process 1: the model asks for a tool call; the graph stops before executing it.
{
let saver = Arc::new(SqliteSaver::from_path(&db).await?);
let model = Arc::new(FakeChatModel::new(vec![Response::tool_calls(vec![ToolCall::new("c1", "weather", json!({"city": "Lisbon"}))])]));
let agent = create_react_agent(model, vec![weather_tool()], AgentOptions::new().prompt("You are a travel assistant").checkpointer(saver).interrupt_before_tools())?;
let out = agent.invoke(json!({"messages": [{"role": "user", "content": "Weather in Lisbon?"}]}), cfg.clone()).await?;
let pending = agent.get_state(&cfg, false).await?;
println!("paused; next nodes = {:?}; messages so far = {}", pending.next, out.value["messages"].as_array().map_or(0, Vec::len));
assert_eq!(pending.next, ["tools"]);
}
// Process 2: reopen the database, approve by resuming (input `()` continues from the checkpoint).
let saver = Arc::new(SqliteSaver::from_path(&db).await?);
let model = Arc::new(FakeChatModel::new(vec![Response::text("It is sunny in Lisbon.")]));
let agent = create_react_agent(model, vec![weather_tool()], AgentOptions::new().checkpointer(saver).interrupt_before_tools())?;
let out = agent.invoke((), cfg.clone()).await?;
println!("resumed; final answer: {}", last_text(&out.value));
Ok(())
}

Tools and models come from the Nexura crates in the same repository: nexura-core defines Tool and ChatModel, and nexura-llm has the scripted FakeChatModel.

Option Effect
prompt(str) / with_prompt(Prompt) System prompt: a string, a message or a function
response_format(ResponseFormat) Structured output step when the model stops calling tools, validated against the schema
pre_model_hook(hook) / post_model_hook(hook) Run before / after every model call. The pre hook can set llm_input_messages.
checkpointer(saver) Persist threads
store(store) Long-term store, reachable from hooks and from tools via injected_store()
interrupt_before_tools() Pause before the tools node for human review
interrupt_before([..]) / interrupt_after([..]) Static breakpoints on any node
version(AgentVersion::V2) Default: one Send per tool call. V1 runs all calls in one task.
name(str) Name on assistant messages and the graph
handle_tool_errors(HandleToolErrors) Error handling of the tools node

Nodes are agent and tools, plus pre_model_hook, post_model_hook and generate_structured_response when configured.

  • Chat history validation. An invalid history fails with INVALID_CHAT_HISTORY.
  • Step guard. When the remaining steps run out, the agent answers “Sorry, need more steps …”.
  • return_direct tools. Tools tagged with RETURN_DIRECT_TAG end the run with their result.
  • Approval. Tools that report requires_approval() raise an approval interrupt in the ToolNode.

When the run requests the messages stream mode, the agent node calls ChatModel::stream. It emits chunks {"role": "assistant", "chunk": true, "id", "content" | "tool_calls": [...]} through NodeCtx::stream_message, then emits the complete message with the same id. Without messages mode, or for models that cannot stream, it calls generate.

wrap_tool_call middleware, dynamic (callable) models, state_schema customisation and HumanInterrupt typed helpers. Several parent-command Sends are merged, but this is only unit-tested, with no end-to-end subgraph test.

Warpra is open source under Apache-2.0. Made by Liceron.