Skip to main content

runtime_adapter/
runtime_adapter.rs

1use axllm::{agent, AxCodeRuntime, AxCodeSession, AxResult, RuntimeEnvelope};
2use serde_json::{json, Value};
3
4struct DemoSession {
5    globals: Value,
6    closed: bool,
7}
8
9impl AxCodeSession for DemoSession {
10    fn execute(&mut self, code: &str, _options: Value) -> AxResult<RuntimeEnvelope> {
11        if code == "timeout()" {
12            return Ok(RuntimeEnvelope::timeout("demo timeout"));
13        }
14        self.globals["answer"] = json!("runtime final");
15        Ok(RuntimeEnvelope::final_payload(
16            json!({"answer": self.globals["answer"]}),
17        ))
18    }
19
20    fn snapshot_globals(&mut self, _options: Value) -> AxResult<Value> {
21        Ok(json!({"version": 1, "bindings": self.globals, "closed": self.closed}))
22    }
23
24    fn patch_globals(&mut self, snapshot: Value, _options: Value) -> AxResult<Value> {
25        self.globals = snapshot
26            .get("bindings")
27            .cloned()
28            .unwrap_or_else(|| json!({}));
29        self.snapshot_globals(json!({}))
30    }
31
32    fn close(&mut self) -> AxResult<Value> {
33        self.closed = true;
34        Ok(json!({"closed": true}))
35    }
36}
37
38struct DemoRuntime;
39
40impl AxCodeRuntime for DemoRuntime {
41    fn language(&self) -> &str {
42        "Rust"
43    }
44
45    fn create_session(
46        &mut self,
47        globals: Value,
48        _options: Value,
49    ) -> AxResult<Box<dyn AxCodeSession>> {
50        Ok(Box::new(DemoSession {
51            globals,
52            closed: false,
53        }))
54    }
55}
56
57fn main() -> AxResult<()> {
58    let mut runtime = DemoRuntime;
59    let mut runner = agent("question:string -> answer:string")?;
60    let step = runner.execute_actor_step(
61        &mut runtime,
62        "final()",
63        json!({"question": "adapter"}),
64        json!({}),
65    )?;
66    let snapshot = runner.export_session_state()?;
67    let timeout = runner.execute_actor_step(
68        &mut runtime,
69        "timeout()",
70        json!({"question": "adapter"}),
71        json!({}),
72    )?;
73    let closed = runner.close_runtime_session()?;
74    println!(
75        "{}",
76        serde_json::to_string_pretty(&json!({
77            "stepKind": step.payload["kind"],
78            "snapshotAnswer": snapshot["bindings"]["answer"],
79            "timeoutCategory": timeout.payload["error_category"],
80            "closed": closed
81        }))?
82    );
83    Ok(())
84}