oris-runtime 0.61.0

An agentic workflow runtime and programmable AI execution system in Rust: stateful graphs, agents, tools, and multi-step execution.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
use std::collections::HashMap;
use std::sync::Arc;

use async_trait::async_trait;

use crate::{
    agent::Agent, chain::Chain, language_models::llm::LLM, prompt::PromptArgs,
    schemas::messages::Message,
};

use super::{
    compiled::CompiledGraph,
    error::GraphError,
    persistence::{config::RunnableConfig, store::StoreBox},
    state::State,
    StateUpdate,
};

mod subgraph;
pub use subgraph::{SubgraphNode, SubgraphNodeWithTransform};

/// Trait for nodes in a LangGraph
///
/// Nodes are the building blocks of a graph. They take state as input
/// and return state updates.
#[async_trait]
pub trait Node<S: State>: Send + Sync {
    /// Invoke the node with the current state
    ///
    /// Returns a state update that will be merged into the current state.
    async fn invoke(&self, state: &S) -> Result<StateUpdate, GraphError>;

    /// Invoke the node with state, config, and store
    ///
    /// This method allows nodes to access configuration and store for
    /// long-term memory and cross-thread data access.
    ///
    /// # Arguments
    ///
    /// * `state` - The current state
    /// * `config` - Optional configuration (thread_id, user_id, etc.)
    /// * `store` - Optional store for cross-thread storage
    ///
    /// # Default Implementation
    ///
    /// The default implementation calls `invoke(state)` to maintain
    /// backward compatibility. Nodes that need config or store should
    /// override this method.
    async fn invoke_with_context(
        &self,
        state: &S,
        _config: Option<&RunnableConfig>,
        _store: Option<StoreBox>,
    ) -> Result<StateUpdate, GraphError> {
        // Default implementation calls invoke for backward compatibility
        self.invoke(state).await
    }

    /// Get the LLM from this node if it contains one
    ///
    /// Returns None if this node is not an LLM node.
    /// This is used for streaming LLM tokens.
    fn get_llm(&self) -> Option<Arc<dyn LLM>> {
        None
    }

    /// Get the subgraph from this node if it contains one
    ///
    /// Returns None if this node is not a subgraph node.
    /// This is used for subgraph streaming.
    fn get_subgraph(&self) -> Option<Arc<CompiledGraph<S>>> {
        None
    }
}

/// Function node - wraps an async function
///
/// This is the simplest type of node, wrapping a function that takes
/// state and returns a state update.
///
/// Supports multiple function signatures:
/// - `Fn(&S) -> Fut` - state only
/// - `Fn(&S, &RunnableConfig) -> Fut` - state and config
/// - `Fn(&S, &RunnableConfig, &dyn Store) -> Fut` - state, config, and store
pub struct FunctionNode<S: State> {
    name: String,
    func_state_only: Option<
        Arc<
            dyn Fn(
                    &S,
                ) -> std::pin::Pin<
                    Box<dyn std::future::Future<Output = Result<StateUpdate, GraphError>> + Send>,
                > + Send
                + Sync,
        >,
    >,
    func_with_config: Option<
        Arc<
            dyn Fn(
                    &S,
                    &RunnableConfig,
                ) -> std::pin::Pin<
                    Box<dyn std::future::Future<Output = Result<StateUpdate, GraphError>> + Send>,
                > + Send
                + Sync,
        >,
    >,
    func_with_config_store: Option<
        Arc<
            dyn Fn(
                    &S,
                    &RunnableConfig,
                    StoreBox,
                ) -> std::pin::Pin<
                    Box<dyn std::future::Future<Output = Result<StateUpdate, GraphError>> + Send>,
                > + Send
                + Sync,
        >,
    >,
}

impl<S: State> FunctionNode<S> {
    /// Create a new function node with state only
    pub fn new<F, Fut>(name: String, func: F) -> Self
    where
        F: Fn(&S) -> Fut + Send + Sync + 'static,
        Fut: std::future::Future<Output = Result<StateUpdate, GraphError>> + Send + 'static,
    {
        Self {
            name,
            func_state_only: Some(Arc::new(move |state| Box::pin(func(state)))),
            func_with_config: None,
            func_with_config_store: None,
        }
    }

    /// Create a new function node with state and config
    pub fn with_config<F, Fut>(name: String, func: F) -> Self
    where
        F: Fn(&S, &RunnableConfig) -> Fut + Send + Sync + 'static,
        Fut: std::future::Future<Output = Result<StateUpdate, GraphError>> + Send + 'static,
    {
        Self {
            name,
            func_state_only: None,
            func_with_config: Some(Arc::new(move |state, config| Box::pin(func(state, config)))),
            func_with_config_store: None,
        }
    }

    /// Create a new function node with state, config, and store
    pub fn with_config_store<F, Fut>(name: String, func: F) -> Self
    where
        F: Fn(&S, &RunnableConfig, StoreBox) -> Fut + Send + Sync + 'static,
        Fut: std::future::Future<Output = Result<StateUpdate, GraphError>> + Send + 'static,
    {
        Self {
            name,
            func_state_only: None,
            func_with_config: None,
            func_with_config_store: Some(Arc::new(move |state, config, store| {
                Box::pin(func(state, config, store))
            })),
        }
    }

    /// Get the name of the node
    pub fn name(&self) -> &str {
        &self.name
    }
}

#[async_trait]
impl<S: State> Node<S> for FunctionNode<S> {
    async fn invoke(&self, state: &S) -> Result<StateUpdate, GraphError> {
        if let Some(ref func) = self.func_state_only {
            func(state).await
        } else {
            // If node requires config/store, invoke_with_context should be used
            Err(GraphError::ExecutionError(
                "Node requires config or store, use invoke_with_context".to_string(),
            ))
        }
    }

    async fn invoke_with_context(
        &self,
        state: &S,
        config: Option<&RunnableConfig>,
        store: Option<StoreBox>,
    ) -> Result<StateUpdate, GraphError> {
        // Try func_with_config_store first (most specific)
        if let Some(ref func) = self.func_with_config_store {
            if let (Some(config), Some(store)) = (config, store) {
                return func(state, config, store.clone()).await;
            } else {
                return Err(GraphError::ExecutionError(
                    "Node requires both config and store".to_string(),
                ));
            }
        }

        // Try func_with_config
        if let Some(ref func) = self.func_with_config {
            if let Some(config) = config {
                return func(state, config).await;
            } else {
                return Err(GraphError::ExecutionError(
                    "Node requires config".to_string(),
                ));
            }
        }

        // Fall back to func_state_only
        if let Some(ref func) = self.func_state_only {
            func(state).await
        } else {
            Err(GraphError::ExecutionError(
                "No valid function signature found".to_string(),
            ))
        }
    }
}

/// Chain node - wraps a Chain trait object
///
/// This node executes a Chain and adds the result to the state.
pub struct ChainNode {
    chain: Arc<dyn Chain>,
    input_key: String,
    output_key: String,
}

impl ChainNode {
    /// Create a new chain node
    ///
    /// # Arguments
    ///
    /// * `chain` - The chain to execute
    /// * `input_key` - The key in the state to use as input (default: "input")
    /// * `output_key` - The key in the state to store the output (default: "output")
    pub fn new(
        chain: Arc<dyn Chain>,
        input_key: Option<String>,
        output_key: Option<String>,
    ) -> Self {
        Self {
            chain,
            input_key: input_key.unwrap_or_else(|| "input".to_string()),
            output_key: output_key.unwrap_or_else(|| "output".to_string()),
        }
    }
}

#[async_trait]
impl<S: State> Node<S> for ChainNode {
    async fn invoke(&self, state: &S) -> Result<StateUpdate, GraphError> {
        // Convert state to PromptArgs
        // For MessagesState, we extract the last message as input
        let state_json = serde_json::to_value(state).map_err(GraphError::SerializationError)?;

        let mut prompt_args = PromptArgs::new();

        // Try to extract input from state
        if let Some(input_value) = state_json.get(&self.input_key) {
            prompt_args.insert(self.input_key.clone(), input_value.clone());
        } else if let Some(messages) = state_json.get("messages") {
            // For MessagesState, use the last message as input
            if let Some(msg_array) = messages.as_array() {
                if let Some(last_msg) = msg_array.last() {
                    if let Some(content) = last_msg.get("content") {
                        prompt_args.insert(self.input_key.clone(), content.clone());
                    }
                }
            }
        }

        // Execute the chain
        let result = self.chain.call(prompt_args).await?;

        // Create state update
        let mut update = HashMap::new();
        update.insert(
            self.output_key.clone(),
            serde_json::to_value(result.generation)?,
        );

        Ok(update)
    }
}

/// LLM node - wraps an LLM trait object
///
/// This node executes an LLM and adds the result as a message to the state.
pub struct LLMNode {
    llm: Arc<dyn LLM>,
}

impl LLMNode {
    /// Create a new LLM node
    pub fn new(llm: Arc<dyn LLM>) -> Self {
        Self { llm }
    }
}

#[async_trait]
impl<S: State> Node<S> for LLMNode {
    // invoke_with_context uses default implementation (calls invoke)
    // LLM nodes don't typically need config or store

    async fn invoke(&self, state: &S) -> Result<StateUpdate, GraphError> {
        // Convert state to messages
        let state_json = serde_json::to_value(state).map_err(GraphError::SerializationError)?;

        let messages: Vec<Message> = if let Some(messages_value) = state_json.get("messages") {
            serde_json::from_value(messages_value.clone())
                .map_err(GraphError::SerializationError)?
        } else {
            // If no messages, create a default human message
            vec![Message::new_human_message("")]
        };

        // Generate response
        let result = self.llm.generate(&messages).await?;

        // Create state update with new AI message
        let ai_message = Message::new_ai_message(&result.generation);
        let mut update = HashMap::new();
        update.insert(
            "messages".to_string(),
            serde_json::to_value(vec![ai_message])?,
        );

        Ok(update)
    }

    fn get_llm(&self) -> Option<Arc<dyn LLM>> {
        Some(self.llm.clone())
    }
}

/// Agent node - wraps an Agent trait object
///
/// This node executes an Agent and adds the result to the state.
pub struct AgentNode {
    agent: Arc<dyn Agent>,
}

impl AgentNode {
    /// Create a new agent node
    pub fn new(agent: Arc<dyn Agent>) -> Self {
        Self { agent }
    }
}

#[async_trait]
impl<S: State> Node<S> for AgentNode {
    // invoke_with_context uses default implementation (calls invoke)
    // Agent nodes can be extended later if needed

    async fn invoke(&self, state: &S) -> Result<StateUpdate, GraphError> {
        // Convert state to PromptArgs
        let state_json = serde_json::to_value(state).map_err(GraphError::SerializationError)?;

        let mut prompt_args = PromptArgs::new();

        // Extract input from state
        if let Some(input_value) = state_json.get("input") {
            prompt_args.insert("input".to_string(), input_value.clone());
        } else if let Some(messages) = state_json.get("messages") {
            // For MessagesState, use the last message as input
            if let Some(msg_array) = messages.as_array() {
                if let Some(last_msg) = msg_array.last() {
                    if let Some(content) = last_msg.get("content") {
                        prompt_args.insert("input".to_string(), content.clone());
                    }
                }
            }
        }

        // Execute the agent
        // Note: This is a simplified version. Full agent execution
        // would require handling intermediate steps, tools, etc.
        // For now, we'll use the agent's plan method
        let intermediate_steps = vec![];
        let event = self.agent.plan(&intermediate_steps, prompt_args).await?;

        // Create state update based on agent event
        let mut update = HashMap::new();

        match event {
            crate::schemas::agent::AgentEvent::Finish(finish) => {
                update.insert(
                    "output".to_string(),
                    serde_json::Value::String(finish.output.clone()),
                );
            }
            crate::schemas::agent::AgentEvent::Action(actions) => {
                if let Some(action) = actions.first() {
                    update.insert("action".to_string(), serde_json::to_value(action)?);
                }
            }
        }

        Ok(update)
    }
}

/// Helper function to create a simple function node from a closure
///
/// Supports function signatures:
/// - `Fn(&S) -> Fut` - state only
pub fn function_node<S: State, F, Fut>(name: impl Into<String>, func: F) -> FunctionNode<S>
where
    F: Fn(&S) -> Fut + Send + Sync + 'static,
    Fut: std::future::Future<Output = Result<StateUpdate, GraphError>> + Send + 'static,
{
    FunctionNode::new(name.into(), func)
}

/// Helper function to create a function node with config
///
/// Supports function signatures:
/// - `Fn(&S, &RunnableConfig) -> Fut` - state and config
pub fn function_node_with_config<S: State, F, Fut>(
    name: impl Into<String>,
    func: F,
) -> FunctionNode<S>
where
    F: Fn(&S, &RunnableConfig) -> Fut + Send + Sync + 'static,
    Fut: std::future::Future<Output = Result<StateUpdate, GraphError>> + Send + 'static,
{
    FunctionNode::with_config(name.into(), func)
}

/// Helper function to create a function node with config and store
///
/// Supports function signatures:
/// - `Fn(&S, &RunnableConfig, StoreBox) -> Fut` - state, config, and store (owned Arc)
pub fn function_node_with_store<S: State, F, Fut>(
    name: impl Into<String>,
    func: F,
) -> FunctionNode<S>
where
    F: Fn(&S, &RunnableConfig, StoreBox) -> Fut + Send + Sync + 'static,
    Fut: std::future::Future<Output = Result<StateUpdate, GraphError>> + Send + 'static,
{
    FunctionNode::with_config_store(name.into(), func)
}

#[cfg(test)]
mod tests_subgraph;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::state::MessagesState;

    #[tokio::test]
    async fn test_function_node() {
        let node = function_node("test_node", |_state: &MessagesState| async move {
            let mut update = HashMap::new();
            update.insert(
                "messages".to_string(),
                serde_json::to_value(vec![Message::new_ai_message("Hello from node")])?,
            );
            Ok(update)
        });

        let state = MessagesState::new();
        let result = node.invoke(&state).await;
        assert!(result.is_ok());
    }
}