### Start background sweep task Source: https://docs.rs/juncture/0.3.1/juncture/prelude/store/struct.MemoryStore.html?search= Shows how to initialize a MemoryStore with TTL configuration and start a background task for periodic cleanup. ```rust use juncture_core::store::{MemoryStore, TTLConfig}; use std::{time::Duration, sync::Arc}; let store = Arc::new(MemoryStore::new().with_ttl_config(TTLConfig { default_ttl: Some(Duration::from_secs(300)), refresh_on_read: true, ..Default::default() })); // Start background sweep task let _sweep_handle = store.start_sweep_task(); // Store continues to work, sweep task runs in background // The task will run until _sweep_handle is dropped or aborted ``` -------------------------------- ### Set Entry Point Source: https://docs.rs/juncture/0.3.1/juncture/graph/struct.StateGraph.html Defines the starting node for the graph, equivalent to adding an edge from the START node. ```rust graph.set_entry_point("start_node"); ``` -------------------------------- ### Command Initialization Examples Source: https://docs.rs/juncture/0.3.1/juncture/command/struct.Command.html?search= Basic imports for utilizing Command functionality in a project. ```rust use juncture_core::Command; use serde_json::json; ``` -------------------------------- ### Initialize LlmSummarizer Source: https://docs.rs/juncture/0.3.1/juncture/memory/struct.LlmSummarizer.html?search= Example showing how to instantiate an LlmSummarizer with a ChatOpenAI model. ```rust use juncture::memory::LlmSummarizer; use juncture::llm::ChatOpenAI; use std::sync::Arc; let model = ChatOpenAI::new("sk-..."); let summarizer = LlmSummarizer::new(model, 500); ``` -------------------------------- ### Initialize CircuitBreakerConfig Source: https://docs.rs/juncture/0.3.1/juncture/graph/struct.CircuitBreakerConfig.html Example of creating a new configuration instance. ```rust use juncture_core::graph::CircuitBreakerConfig; use std::time::Duration; let config = CircuitBreakerConfig::new(5, Duration::from_secs(30)); assert_eq!(config.failure_threshold, 5); ``` -------------------------------- ### Compile a graph with configuration Source: https://docs.rs/juncture/0.3.1/juncture/graph/struct.CompileConfig.html Example showing how to instantiate CompileConfig and use it to compile a graph. ```rust use juncture_core::graph::CompileConfig; let config = CompileConfig { interrupt_before: vec!["human_review".into()], interrupt_after: vec!["llm_call".into()], }; let compiled = graph.compile_with_config(config)?; ``` -------------------------------- ### Configure ResourceLimits Source: https://docs.rs/juncture/0.3.1/juncture/config/struct.ResourceLimits.html?search=std%3A%3Avec Example showing how to instantiate ResourceLimits and set the maximum state size in bytes. ```rust use juncture_core::config::ResourceLimits; let limits = ResourceLimits::new() .with_max_state_size_bytes(10 * 1024 * 1024); // 10 MB ``` -------------------------------- ### Converting to AgentEntry Source: https://docs.rs/juncture/0.3.1/juncture/prebuilt/trait.IntoAgentEntry.html Example showing how to convert a CompiledGraph into an AgentEntry. ```rust use juncture::prebuilt::{IntoAgentEntry, AgentEntry}; use juncture::prebuilt::MessagesState; let graph: CompiledGraph = create_react_agent(...)?; let entry: AgentEntry = graph.into_agent_entry(); ``` -------------------------------- ### Example Usage of create_react_agent_with_config Source: https://docs.rs/juncture/0.3.1/juncture/prebuilt/fn.create_react_agent_with_config.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates initializing a ReAct agent with a mock model and custom system message configuration. ```rust use juncture::llm::MockChatModel; use juncture::prebuilt::{create_react_agent_with_config, ReactAgentConfig}; use juncture::tools::Tool; let model = MockChatModel::new("gpt-4").with_response("Hello!"); let tools: Vec> = vec![]; let config = ReactAgentConfig { system_message: Some("You are a helpful assistant.".to_string()), ..Default::default() }; let graph = create_react_agent_with_config(model, tools, config)?; ``` -------------------------------- ### Example Usage of create_agent_with_config Source: https://docs.rs/juncture/0.3.1/juncture/prebuilt/fn.create_agent_with_config.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates initializing a ReAct agent with a mock model and a custom system message configuration. ```rust use juncture::llm::MockChatModel; use juncture::prebuilt::{create_agent_with_config, ReactAgentConfig}; use juncture::tools::Tool; let model = MockChatModel::new("gpt-4").with_response("Hello!"); let tools: Vec> = vec![]; let config = ReactAgentConfig { system_message: Some("You are a helpful assistant.".to_string()), ..Default::default() }; let graph = create_agent_with_config(model, tools, config)?; ``` -------------------------------- ### RunnableConfig Usage Source: https://docs.rs/juncture/0.3.1/juncture/prelude/struct.RunnableConfig.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Example of initializing a RunnableConfig with custom resource limits. ```APIDOC ## RunnableConfig Initialization ### Description Initializes a new `RunnableConfig` instance and applies resource limits such as maximum state size. ### Example ```rust use juncture_core::config::{RunnableConfig, ResourceLimits}; let limits = ResourceLimits::new() .with_max_state_size_bytes(10 * 1024 * 1024); let config = RunnableConfig::new() .with_resource_limits(limits); ``` ``` -------------------------------- ### Implement StatefulTool with ToolRuntime Source: https://docs.rs/juncture/0.3.1/juncture/tools/struct.ToolRuntime.html Example demonstrating how to access state, configuration, and the store within a tool's invocation method. ```rust use juncture::tools::{StatefulTool, ToolRuntime}; use juncture_core::{State, RunnableConfig}; use async_trait::async_trait; struct MyStatefulTool; #[async_trait] impl StatefulTool for MyStatefulTool { async fn invoke_with_runtime( &self, input: serde_json::Value, runtime: &ToolRuntime, ) -> Result { // Access state let state = &runtime.state; let config = runtime.config(); // Access store if available if let Some(store) = runtime.store() { let item = store.get("namespace", "key").await?; } Ok("Result".to_string()) } } ``` -------------------------------- ### START Source: https://docs.rs/juncture/0.3.1/juncture/prelude/constant.START.html The START constant is a sentinel value used to define the virtual start node when configuring entry points in a StateGraph. ```APIDOC ## Constant: START ### Description Sentinel constant for graph entry point. This is used as the virtual start node when setting entry points via `super::StateGraph::set_entry_point`. ### Signature `pub const START: &'static str;` ``` -------------------------------- ### Implementing a Context-Aware Stateful Tool Source: https://docs.rs/juncture/0.3.1/juncture/tools/trait.StatefulTool.html Example implementation of a tool that utilizes the ToolRuntime to access persistent storage and configuration. ```rust use juncture::tools::{StatefulTool, ToolRuntime, ToolError}; use juncture_core::State; use async_trait::async_trait; use serde_json::json; struct ContextAwareSearchTool; #[async_trait] impl StatefulTool for ContextAwareSearchTool { async fn invoke_with_runtime( &self, input: serde_json::Value, runtime: &ToolRuntime, ) -> Result { // Access the persistent store for cross-thread memory if let Some(store) = runtime.store() { let _item = store.get("namespace", "key").await .map_err(|e| ToolError::execution_failed(e.to_string()))?; } Ok(format!("Searched with config: {:?}", runtime.config())) } fn name(&self) -> &'static str { "context_aware_search" } fn description(&self) -> &'static str { "Searches using graph state context" } fn schema(&self) -> serde_json::Value { json!({"type": "object"}) } } ``` -------------------------------- ### SyncAsyncFuture Usage Examples Source: https://docs.rs/juncture/0.3.1/juncture/enum.SyncAsyncFuture.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates creating and awaiting both synchronous and asynchronous results using SyncAsyncFuture. ```rust use juncture_core::pregel::types::SyncAsyncFuture; // Synchronous (cache hit) let ready = SyncAsyncFuture::ready(42); assert!(ready.is_ready()); assert_eq!(ready.result().await?, 42); // Asynchronous (needs computation) let pending = SyncAsyncFuture::pending(async { Ok(99) }); assert!(!pending.is_ready()); assert_eq!(pending.result().await?, 99); ``` -------------------------------- ### Streaming Graph Execution Example Source: https://docs.rs/juncture/0.3.1/juncture/graph/struct.StreamHandle.html Demonstrates how to initiate a streaming graph execution and process the resulting events. ```rust use juncture_core::{StateGraph, State, StreamMode}; use futures::StreamExt; let handle = compiled.stream(initial_state, &config, StreamMode::Values).await?; println!("run_id = {}", handle.run_id()); let mut stream = handle.stream; while let Some(result) = stream.next().await { // process events } ``` -------------------------------- ### Using ValidationNode Source: https://docs.rs/juncture/0.3.1/juncture/tools/struct.ValidationNode.html?search= Example demonstrating how to initialize a ValidationNode with token limits and a custom validation closure. ```rust use juncture::tools::ValidationNode; use juncture_core::state::messages::Message; let validator = ValidationNode::new() .with_max_tokens(100_000) .with_validator(|messages| { // Custom validation logic if messages.len() > 1000 { return Err(ToolError::validation_failed(vec!["Too many messages".to_string()])); } Ok(()) }); validator.validate(&messages)?; ``` -------------------------------- ### Example Search Queries Source: https://docs.rs/juncture/0.3.1/juncture/enum.Content.html?search= Common search patterns for finding types, functions, or trait implementations in the documentation. ```text std::vec ``` ```text u32 -> bool ``` ```text Option, (T -> U) -> Option ``` -------------------------------- ### Initialize MemoryStore with TTLConfig Source: https://docs.rs/juncture/0.3.1/juncture/prelude/store/struct.TTLConfig.html Example of configuring a MemoryStore instance with custom TTL settings using the builder pattern. ```rust use juncture_core::store::{MemoryStore, TTLConfig}; use std::time::Duration; let store = MemoryStore::new().with_ttl_config(TTLConfig { default_ttl: Some(Duration::from_secs(300)), refresh_on_read: true, ..Default::default() }); ``` -------------------------------- ### Initialize and Populate TriggerTable Source: https://docs.rs/juncture/0.3.1/juncture/edge/struct.TriggerTable.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Example showing how to create a new TriggerTable and add an outgoing edge mapping. ```rust use juncture_core::edge::{TriggerTable, CompiledEdge, TriggerSource}; use std::collections::HashMap; let mut trigger_table = TriggerTable::::new(); trigger_table.outgoing.insert( "node_a".to_string(), vec![CompiledEdge::Fixed { target: "node_b".to_string() }], ); ``` -------------------------------- ### Create a Send target Source: https://docs.rs/juncture/0.3.1/juncture/prelude/send/struct.Send.html?search= Example of initializing a Send target with a custom state implementation. ```rust use juncture_core::{Send, State, command::SendTarget}; use serde_json::json; struct MyState; impl State for MyState { type Update = MyStateUpdate; } struct MyStateUpdate; // Create a send target with custom state let send = Send { node: "worker".to_string(), state: MyState { /* ... */ }, }; ``` -------------------------------- ### Implement LlmMiddleware Source: https://docs.rs/juncture/0.3.1/juncture/llm/trait.LlmMiddleware.html Example implementation of the LlmMiddleware trait using the async_trait macro. ```rust use juncture::llm::LlmMiddleware; use juncture::llm::{CallOptions, LlmError, Message}; use async_trait::async_trait; struct UppercaseMiddleware; #[async_trait] impl LlmMiddleware for UppercaseMiddleware { async fn pre_invoke( &self, _messages: &mut Vec, _options: &mut CallOptions, ) -> Result<(), LlmError> { // Implementation here Ok(()) } } ``` -------------------------------- ### Executing a superstep Source: https://docs.rs/juncture/0.3.1/juncture/fn.execute_superstep.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Example usage of the execute_superstep function, demonstrating how to initialize policies and invoke the runner. ```rust use juncture_core::pregel::runner::execute_superstep; use juncture_core::interrupt::Scratchpad; use tokio_util::sync::CancellationToken; let retry_policies = std::collections::HashMap::new(); let timeout_policies = std::collections::HashMap::new(); let (result, _interrupt_rx) = execute_superstep( &pending_tasks, &state, &nodes, &config, &token, None::>, &pending_interrupts, &scratchpad, &std::collections::HashMap::new(), &retry_policies, &timeout_policies, &std::collections::HashMap::new(), // fallback_map 0, // step ).await?; ``` -------------------------------- ### set_entry_point Source: https://docs.rs/juncture/0.3.1/juncture/graph/struct.StateGraph.html?search= Sets the entry point for the graph, equivalent to adding an edge from the START node. ```APIDOC ## pub fn set_entry_point(&mut self, node: impl Into) ### Description Sets the entry point for the graph. This is equivalent to `add_edge(START, node)`. ### Parameters - **node** (impl Into) - The name of the node to set as the entry point. ``` -------------------------------- ### Demonstrating potential panic with Instant arithmetic Source: https://docs.rs/juncture/0.3.1/juncture/prelude/time/struct.Instant.html This example shows an arithmetic operation on an Instant that may panic on certain operating systems like macOS due to underlying system limitations. ```rust use std::time::{Instant, Duration}; let now = Instant::now(); let days_per_10_millennia = 365_2425; let solar_seconds_per_day = 60 * 60 * 24; let millennium_in_solar_seconds = 31_556_952_000; assert_eq!(millennium_in_solar_seconds, days_per_10_millennia * solar_seconds_per_day / 10); let duration = Duration::new(millennium_in_solar_seconds, 0); println!("{:?}", now + duration); ``` -------------------------------- ### Example Usage of compute_next_tasks Source: https://docs.rs/juncture/0.3.1/juncture/fn.compute_next_tasks.html Demonstrates how to invoke the function with the required parameters to retrieve the next set of tasks. ```rust use juncture_core::pregel::scheduler::compute_next_tasks; use juncture_core::pregel::types::{TaskOutput, SuperstepResult}; use std::time::Duration; let next_tasks = compute_next_tasks(&completed_tasks, &trigger_table, &state)?; ``` -------------------------------- ### Initialize Runtime Source: https://docs.rs/juncture/0.3.1/juncture/prelude/runtime/struct.Runtime.html Demonstrates creating a Runtime instance with default settings or a custom context. ```rust use juncture_core::Runtime; use std::sync::Arc; // Simple runtime with no context let runtime = Runtime::<()>::new(); // Runtime with custom context struct MyContext { user_id: String } let runtime = Runtime::with_context(MyContext { user_id: "123".to_string() }); ``` -------------------------------- ### Define the START constant Source: https://docs.rs/juncture/0.3.1/juncture/constant.START.html This constant represents the virtual start node for graph entry points. ```rust pub const START: &'static str; ``` -------------------------------- ### CheckpointNamespace Usage Example Source: https://docs.rs/juncture/0.3.1/juncture/checkpoint/struct.CheckpointNamespace.html Demonstrates creating a root namespace and appending child segments to build a hierarchical path. ```rust use juncture_core::checkpoint::CheckpointNamespace; let root_ns = CheckpointNamespace::root(); let child_ns = root_ns.child("review", "550e8400-e29b-41d4-a716-446655440000"); let grandchild_ns = child_ns.child("detail", "6ba7b810-9dad-11d1-80b4-00c04fd430c8"); assert_eq!(root_ns.as_str(), ""); assert_eq!(child_ns.as_str(), "|review:550e8400-e29b-41d4-a716-446655440000"); assert_eq!(grandchild_ns.as_str(), "|review:550e8400-e29b-41d4-a716-446655440000|detail:6ba7b810-9dad-11d1-80b4-00c04fd430c8"); ``` -------------------------------- ### Create a Fixed Edge Source: https://docs.rs/juncture/0.3.1/juncture/edge/enum.Edge.html Example of initializing a Fixed edge that routes between two nodes. ```rust use juncture_core::{edge::Edge, State, Node}; use std::sync::Arc; struct MyState; impl State for MyState { type Update = MyStateUpdate; } struct MyStateUpdate; // Fixed edge: routes from "node_a" to "node_b" let fixed = Edge::::Fixed { from: "node_a".to_string(), to: "node_b".to_string(), }; ``` -------------------------------- ### get Source: https://docs.rs/juncture/0.3.1/juncture/prelude/state/struct.CowState.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Retrieves a read-only reference to the current state. ```APIDOC ## pub fn get(&self) -> &S ### Description Get current state (read-only). ``` -------------------------------- ### get Source: https://docs.rs/juncture/0.3.1/juncture/prelude/state/channel/struct.DeltaChannel.html?search= Retrieves the current value stored in the channel. ```APIDOC ## fn get(&self) -> &T ### Description Get the current value. ``` -------------------------------- ### Initialize ChatOpenAI Client Source: https://docs.rs/juncture/0.3.1/juncture/llm/struct.ChatOpenAI.html Shows how to create a new client instance using an API key or environment variables. ```rust use juncture::llm::ChatOpenAI; let model = ChatOpenAI::new("sk-...")?; ``` ```rust use juncture::llm::ChatOpenAI; let model = ChatOpenAI::from_env()?; ``` -------------------------------- ### Arc::weak_count Source: https://docs.rs/juncture/0.3.1/juncture/prelude/prebuilt/type.ModelSelector.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Gets the number of Weak pointers to this allocation. ```APIDOC ## pub fn weak_count(this: &Arc) -> usize ### Description Gets the number of `Weak` pointers to this allocation. Note that another thread can change the weak count at any time. ``` -------------------------------- ### WebFetchTool::new Source: https://docs.rs/juncture/0.3.1/juncture/tools/builtin/struct.WebFetchTool.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a new instance of WebFetchTool with default settings (15s timeout, 500KB max size). ```APIDOC ### pub const fn new() -> Self Creates a new `WebFetchTool` with default settings. ``` -------------------------------- ### Initialize and Query PricingTable Source: https://docs.rs/juncture/0.3.1/juncture/llm/struct.PricingTable.html Demonstrates creating a default pricing table and retrieving input/output pricing for a specific model. ```rust use juncture::llm::PricingTable; let pricing = PricingTable::default(); if let Some((input_price, output_price)) = pricing.get("claude-3-opus-20240229") { // Use pricing information let _ = (input_price, output_price); } ``` -------------------------------- ### Configure initial backoff Source: https://docs.rs/juncture/0.3.1/juncture/llm/struct.RetryingModel.html Sets the starting duration for exponential backoff. ```rust use juncture::llm::{MockChatModel, RetryingModel}; use std::time::Duration; let base_model = MockChatModel::new("gpt-4"); let model = RetryingModel::new(base_model) .initial_backoff(Duration::from_secs(2)); ``` -------------------------------- ### NodeFnUpdateWithRuntime Usage Example Source: https://docs.rs/juncture/0.3.1/juncture/node/struct.NodeFnUpdateWithRuntime.html?search= Demonstrates defining an async node function that utilizes Runtime for dependency injection. ```rust use juncture_core::{IntoNode, State, Runtime}; use juncture_core::node::NodeFnUpdateWithRuntime; struct MyContext; struct MyState; impl State for MyState { type Update = MyStateUpdate; } async fn my_node(state: MyState, runtime: Runtime) -> Result { Ok(MyStateUpdate) } ``` -------------------------------- ### fn get(&self) -> &T Source: https://docs.rs/juncture/0.3.1/juncture/prelude/trait.Channel.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Retrieves the current value stored in the channel. ```APIDOC ### fn get(&self) -> &T Returns a reference to the current value. ``` -------------------------------- ### Runtime::new Source: https://docs.rs/juncture/0.3.1/juncture/func/struct.Runtime.html?search=std%3A%3Avec Creates a new runtime instance with minimal configuration. ```APIDOC ## pub fn new() -> Runtime ### Description Creates a new runtime with minimal configuration. ### Returns - **Runtime** - A new instance of the Runtime. ``` -------------------------------- ### get Source: https://docs.rs/juncture/0.3.1/juncture/prelude/store/trait.Store.html Retrieves an item from the store based on the provided namespace and key. ```APIDOC ## fn get(namespace: &str, key: &str) ### Description Retrieves an item from the store. Returns the item if found, or None if it does not exist. ### Parameters - **namespace** (str) - Required - Namespace path - **key** (str) - Required - Item key within namespace ``` -------------------------------- ### BudgetTracker::new Source: https://docs.rs/juncture/0.3.1/juncture/prelude/pregel/struct.BudgetTracker.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a new instance of BudgetTracker with the provided configuration. ```APIDOC ## pub fn new(config: BudgetConfig) -> BudgetTracker ### Description Initializes a new budget tracker with the specified configuration settings. ### Parameters - **config** (BudgetConfig) - Required - The configuration object defining limits for tokens, duration, etc. ``` -------------------------------- ### Arc::strong_count Source: https://docs.rs/juncture/0.3.1/juncture/prelude/prebuilt/type.ModelSelector.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Gets the number of strong (Arc) pointers to this allocation. ```APIDOC ## pub fn strong_count(this: &Arc) -> usize ### Description Gets the number of strong (`Arc`) pointers to this allocation. Note that another thread can change the strong count at any time. ``` -------------------------------- ### Measure elapsed time with Instant Source: https://docs.rs/juncture/0.3.1/juncture/prelude/time/struct.Instant.html Demonstrates capturing a starting point with Instant::now() and calculating the elapsed duration after a sleep period. ```rust use std::time::{Duration, Instant}; use std::thread::sleep; fn main() { let now = Instant::now(); // we sleep for 2 seconds sleep(Duration::new(2, 0)); // it prints '2' println!("{}", now.elapsed().as_secs()); } ``` -------------------------------- ### as_ref Source: https://docs.rs/juncture/0.3.1/juncture/prelude/llm/type.BoxStream.html?search=u32+-%3E+bool Gets a shared reference to the pinned value this Pin points to. ```APIDOC ## pub fn as_ref(&self) -> Pin<&::Target> ### Description Gets a shared reference to the pinned value this `Pin` points to. This is a safe way to go from `&Pin>` to `Pin<&T>`. ### Parameters - **self** (&self) - The Pin instance. ``` -------------------------------- ### Basic usage of compile_entrypoint Source: https://docs.rs/juncture/0.3.1/juncture/fn.compile_entrypoint.html Demonstrates wrapping an async workflow function into an executable graph with a memory-based checkpointer. ```rust use juncture_core::func::compile_entrypoint; use juncture_core::checkpoint::MemorySaver; use juncture_core::state::CowState; use juncture_core::runtime::Runtime as CoreRuntime; use juncture_core::JunctureError; async fn my_workflow( state: CowState, runtime: &CoreRuntime, ) -> Result { Ok(MyStateUpdate::default()) } let graph = compile_entrypoint::( my_workflow, Some(Arc::new(MemorySaver::new())) )?; let result = graph.invoke(input, &config).await?; ``` -------------------------------- ### Get tracker length Source: https://docs.rs/juncture/0.3.1/juncture/pregel/struct.FieldVersionTracker.html Returns the total number of fields being tracked. ```rust use juncture_core::pregel::scheduler::FieldVersionTracker; let tracker = FieldVersionTracker::new(5); assert_eq!(tracker.len(), 5); ``` -------------------------------- ### Calculate Cost with Assertion Source: https://docs.rs/juncture/0.3.1/juncture/llm/trait.ModelPricing.html Example demonstrating cost calculation with specific token counts and an assertion for the expected result. ```rust use juncture::llm::{ModelPricing, TokenUsage}; let model = MyModel; let usage = TokenUsage { input_tokens: 1_000_000, output_tokens: 500_000, total_tokens: 1_500_000, }; let cost = model.cost_for_usage(&usage); // Cost = (1M * $3.0) + (0.5M * $15.0) = $10.50 assert_eq!(cost, 10.50); ``` -------------------------------- ### WebFetchTool Configuration Methods Source: https://docs.rs/juncture/0.3.1/juncture/tools/builtin/struct.WebFetchTool.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Methods for initializing and configuring the WebFetchTool instance. ```rust pub const fn new() -> Self ``` ```rust pub const fn with_timeout(self, secs: u64) -> Self ``` ```rust pub const fn with_max_size(self, bytes: usize) -> Self ``` -------------------------------- ### Register Callback Handler Source: https://docs.rs/juncture/0.3.1/juncture/observability/trait.GraphLifecycleCallback.html Example of injecting a GraphLifecycleCallback implementation into a RunnableConfig. ```rust use std::sync::Arc; use juncture_core::observability::GraphLifecycleCallback; use juncture_core::config::RunnableConfig; let handler: Arc = /* ... */; let config = RunnableConfig::new() .with_callback_handler(handler); ``` -------------------------------- ### Initialize RunnableConfig with Resource Limits Source: https://docs.rs/juncture/0.3.1/juncture/config/struct.RunnableConfig.html?search=u32+-%3E+bool Demonstrates how to create a new RunnableConfig instance and apply custom resource limits. ```rust use juncture_core::config::{RunnableConfig, ResourceLimits}; let limits = ResourceLimits::new() .with_max_state_size_bytes(10 * 1024 * 1024); let config = RunnableConfig::new() .with_resource_limits(limits); ``` -------------------------------- ### WebFetchTool Methods Source: https://docs.rs/juncture/0.3.1/juncture/tools/builtin/struct.WebFetchTool.html?search=u32+-%3E+bool Methods for initializing and configuring the WebFetchTool instance. ```APIDOC ## pub const fn new() -> Self ### Description Creates a new `WebFetchTool` instance with default settings (15s timeout, 500KB max size). ## pub const fn with_timeout(self, secs: u64) -> Self ### Description Configures the request timeout in seconds. ## pub const fn with_max_size(self, bytes: usize) -> Self ### Description Sets the maximum response size in bytes for the fetch operation. ``` -------------------------------- ### Initialize LlmFactExtractor Source: https://docs.rs/juncture/0.3.1/juncture/memory/struct.LlmFactExtractor.html?search= Example showing how to instantiate an LlmFactExtractor with a ChatOpenAI model. ```rust use juncture::memory::LlmFactExtractor; use juncture::llm::ChatOpenAI; let model = ChatOpenAI::new("sk-..."); let extractor = LlmFactExtractor::new(model); ``` -------------------------------- ### Implementing a Custom Tool Source: https://docs.rs/juncture/0.3.1/juncture/tools/trait.Tool.html Example of implementing the Tool trait for a struct, including the required schema and asynchronous invocation logic. ```rust use async_trait::async_trait; use juncture::tools::{Tool, ToolError}; use serde_json::json; struct Calculator; #[async_trait] impl Tool for Calculator { fn name(&self) -> &str { "calculator" } fn description(&self) -> &str { "Performs basic arithmetic operations" } fn schema(&self) -> serde_json::Value { json!({ "type": "object", "properties": { "operation": { "type": "string", "enum": ["add", "subtract", "multiply", "divide"], }, "a": {"type": "number"}, "b": {"type": "number"}, }, "required": ["operation", "a", "b"], }) } async fn invoke(&self, input: serde_json::Value) -> Result { // Parse and execute the calculation Ok("42".to_string()) } } ``` -------------------------------- ### Initialize a MemorySaver Source: https://docs.rs/juncture/0.3.1/juncture/checkpoint/trait.CheckpointSaver.html Example of initializing a MemorySaver implementation of the CheckpointSaver trait. ```rust use juncture_core::CheckpointSaver; use juncture_checkpoint::MemorySaver; let saver = MemorySaver::new(); // Use saver as a CheckpointSaver trait object... ``` -------------------------------- ### Initialize BudgetTracker Source: https://docs.rs/juncture/0.3.1/juncture/pregel/struct.BudgetTracker.html?search= Create a new instance of BudgetTracker using a BudgetConfig configuration. ```rust use juncture_core::pregel::budget::{BudgetTracker, BudgetConfig}; use std::time::Duration; let config = BudgetConfig::new() .with_max_tokens(1000) .with_max_duration(Duration::from_secs(60)); let tracker = BudgetTracker::new(config); ``` -------------------------------- ### Runtime::new Source: https://docs.rs/juncture/0.3.1/juncture/prelude/runtime/struct.Runtime.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a new runtime instance with minimal configuration. Requires the context type C to implement Default. ```APIDOC ## Runtime::new ### Description Creates a new runtime with minimal configuration. ### Signature `pub fn new() -> Runtime where C: Default` ``` -------------------------------- ### ToolRuntime::emit_tool_started Source: https://docs.rs/juncture/0.3.1/juncture/prelude/struct.ToolRuntime.html?search=std%3A%3Avec Emits a lifecycle event indicating that a tool has started execution. ```APIDOC ## ToolRuntime::emit_tool_started ### Description Sends a ToolsEvent::ToolStarted through the tools event channel if configured. ### Parameters - **tool_name** (&str) - Name of the tool being started - **node** (&str) - Node name where the tool is executing - **input** (Value) - Tool input as JSON value ``` -------------------------------- ### MemoryStore::start_sweep_task Source: https://docs.rs/juncture/0.3.1/juncture/prelude/store/struct.MemoryStore.html Starts a background task for periodic cleanup of expired items. ```APIDOC ## pub fn start_sweep_task(self: Arc) -> JoinHandle<()> ### Description Start the background sweep task for periodic expired item cleanup. The task runs periodically based on the sweep_interval defined in the TTL configuration. ``` -------------------------------- ### as_mut Source: https://docs.rs/juncture/0.3.1/juncture/prelude/llm/type.BoxStream.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Gets a mutable reference to the pinned value this Pin points to. ```APIDOC ## pub fn as_mut(&mut self) -> Pin<&mut ::Target> ### Description Gets a mutable reference to the pinned value this Pin points to. This method is useful when doing multiple calls to functions that consume the pinning pointer. ``` -------------------------------- ### Compiling with task configuration Source: https://docs.rs/juncture/0.3.1/juncture/fn.compile_entrypoint.html Shows how to use compile_entrypoint_with_config to apply retry policies and timeouts to a workflow. ```rust use juncture_core::func::compile_entrypoint_with_config; use juncture_core::config::TaskConfig; use juncture_core::graph::{RetryPolicy, NodeMetadata}; use std::time::Duration; let retry_policy = RetryPolicy::max_attempts(3); let task_config = TaskConfig { retry_policy: Some(retry_policy.clone()), cache_policy: None, timeout: Some(Duration::from_secs(30)), name: Some("my_workflow".to_string()), }; let graph = compile_entrypoint_with_config( my_workflow, &task_config, Some(Arc::new(MemorySaver::new())) )?; ``` -------------------------------- ### Get Current State Source: https://docs.rs/juncture/0.3.1/juncture/client/struct.GraphClient.html?search= Retrieves the current state snapshot for a specific thread. ```rust pub async fn get_state( &self, thread_id: &str, ) -> Result, ClientError> where T: for<'de> Deserialize<'de>, ``` -------------------------------- ### Initialize and use a TopicChannel Source: https://docs.rs/juncture/0.3.1/juncture/prelude/state/channel/struct.TopicChannel.html Demonstrates creating a TopicChannel, publishing messages via update, retrieving them, and clearing the channel state. ```rust use juncture_core::state::channel::{Channel, TopicChannel}; let mut channel: TopicChannel = TopicChannel::new(); // Publish messages. `TopicChannel` implements `Channel>`, so // `update` takes `Vec>` (one batch per publisher). channel.update(vec![vec!["hello".to_string()]]); channel.update(vec![vec!["world".to_string()]]); // Get all accumulated messages let messages = channel.get(); assert_eq!(messages.len(), 2); assert_eq!(messages[0], "hello"); assert_eq!(messages[1], "world"); // Consume (clear) for the next superstep drop(messages); assert!(channel.consume()); assert!(channel.get().is_empty()); ``` -------------------------------- ### Synchronous and Asynchronous Invocation Source: https://docs.rs/juncture/0.3.1/juncture/prelude/struct.CompiledGraph.html?search=u32+-%3E+bool Examples of invoking the compiled graph synchronously and asynchronously. ```rust let output = compiled.invoke(initial_state, &config)?; let final_state = output.value; ``` ```rust let output = compiled.invoke_async(initial_state, &config).await?; let final_state = output.value; ``` -------------------------------- ### Using InMemoryAgentRegistry Source: https://docs.rs/juncture/0.3.1/juncture/prebuilt/trait.AgentRegistry.html Demonstrates basic usage of the InMemoryAgentRegistry implementation, including registration, retrieval, and listing. ```rust use juncture::prebuilt::{AgentRegistry, InMemoryAgentRegistry, AgentEntry}; let mut registry = InMemoryAgentRegistry::new(); registry.register("researcher".to_string(), agent_entry); if let Some(entry) = registry.get("researcher") { let description = entry.description(); assert_eq!(description, "Researches topics"); } let agents = registry.list(); assert!(agents.contains(&"researcher".to_string())); ``` -------------------------------- ### Create ChatAnthropic Client Source: https://docs.rs/juncture/0.3.1/juncture/llm/struct.ChatAnthropic.html?search= Shows initialization methods using a direct API key or environment variables. ```rust use juncture::llm::ChatAnthropic; let model = ChatAnthropic::new("sk-ant-...")?; ``` ```rust use juncture::llm::ChatAnthropic; let model = ChatAnthropic::from_env()?; ``` -------------------------------- ### RetryingModel Configuration Methods Source: https://docs.rs/juncture/0.3.1/juncture/llm/struct.RetryingModel.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Examples of configuring the RetryingModel using its builder-style methods. ```rust use juncture::llm::{ChatModel, MockChatModel, RetryingModel}; let base_model = MockChatModel::new("gpt-4"); let model = RetryingModel::new(base_model); ``` ```rust use juncture::llm::{MockChatModel, RetryingModel}; use std::time::Duration; let base_model = MockChatModel::new("gpt-4"); let model = RetryingModel::new(base_model) .max_retries(5); ``` ```rust use juncture::llm::{MockChatModel, RetryingModel}; use std::time::Duration; let base_model = MockChatModel::new("gpt-4"); let model = RetryingModel::new(base_model) .initial_backoff(Duration::from_secs(2)); ``` ```rust use juncture::llm::{MockChatModel, RetryingModel}; use std::time::Duration; let base_model = MockChatModel::new("gpt-4"); let model = RetryingModel::new(base_model) .max_backoff(Duration::from_secs(60)); ``` ```rust use juncture::llm::{MockChatModel, RetryingModel}; let base_model = MockChatModel::new("gpt-4"); let model = RetryingModel::new(base_model) .respect_retry_after(false); ``` -------------------------------- ### BudgetConfig Implementation Methods Source: https://docs.rs/juncture/0.3.1/juncture/pregel/struct.BudgetConfig.html?search=std%3A%3Avec Methods for creating and configuring a BudgetConfig instance. ```rust pub fn new() -> BudgetConfig ``` ```rust pub const fn with_max_tokens(self, tokens: u64) -> BudgetConfig ``` ```rust pub const fn with_max_cost_usd(self, cost: f64) -> BudgetConfig ``` ```rust pub const fn with_max_duration(self, duration: Duration) -> BudgetConfig ``` ```rust pub const fn with_max_steps(self, steps: usize) -> BudgetConfig ``` ```rust pub const fn has_limits(&self) -> bool ``` -------------------------------- ### RunControl::request_drain Source: https://docs.rs/juncture/0.3.1/juncture/pregel/struct.RunControl.html Signals the system to finish current tasks but not start new ones. ```APIDOC ## pub fn request_drain(&self) ### Description Request drain (finish current tasks but don’t start new ones). This is thread-safe and can be called from any thread. ### Signature `pub fn request_drain(&self)` ``` -------------------------------- ### Create a ReAct Agent in Rust Source: https://docs.rs/juncture/0.3.1/juncture/prebuilt/index.html Demonstrates initializing a ReAct agent using default settings or custom configuration with ReactAgentConfig. ```rust use juncture::llm::{ChatModel, MockChatModel}; use juncture::prebuilt::{create_react_agent, MessagesState, ReactAgentConfig}; use juncture::tools::Tool; let model = MockChatModel::new("gpt-4").with_response("Done!"); let tools: Vec> = vec![]; // Basic usage let agent = create_react_agent(model, tools)?; // With configuration let model = MockChatModel::new("gpt-4").with_response("Done!"); let config = ReactAgentConfig { system_message: Some("You are a helpful assistant.".to_string()), ..Default::default() }; let agent = create_react_agent_with_config(model, tools, config)?; ``` -------------------------------- ### Get field versions as slice Source: https://docs.rs/juncture/0.3.1/juncture/pregel/struct.FieldVersionTracker.html An alias for the versions() method to retrieve all field versions. ```rust use juncture_core::pregel::scheduler::FieldVersionTracker; let tracker = FieldVersionTracker::new(3); assert_eq!(tracker.as_slice(), &[0, 0, 0]); ``` -------------------------------- ### Get a field version Source: https://docs.rs/juncture/0.3.1/juncture/pregel/struct.FieldVersionTracker.html Retrieves the current version number for a specific field index. ```rust use juncture_core::pregel::scheduler::FieldVersionTracker; let mut tracker = FieldVersionTracker::new(3); tracker.bump(0); assert_eq!(tracker.get(0), 1); ``` -------------------------------- ### Get Graph Client Source: https://docs.rs/juncture/0.3.1/juncture/client/struct.JunctureClient.html Obtain a client instance for a specific graph using its identifier. ```rust pub fn graph(&self, graph_id: &str) -> GraphClient ``` -------------------------------- ### Runtime::from_entrypoint_config Source: https://docs.rs/juncture/0.3.1/juncture/func/struct.Runtime.html?search=std%3A%3Avec Creates a runtime from an entrypoint configuration. ```APIDOC ## pub fn from_entrypoint_config(config: &EntrypointConfig) -> Runtime ### Description Creates a runtime from an entrypoint configuration. ### Parameters - **config** (&EntrypointConfig) - The configuration object for the entrypoint. ### Returns - **Runtime** - A configured runtime instance. ``` -------------------------------- ### Example Usage of schedule_error_handlers_filtered Source: https://docs.rs/juncture/0.3.1/juncture/pregel/fn.schedule_fallback_tasks.html Demonstrates how to use schedule_error_handlers_filtered to retrieve and iterate over recovery tasks. ```rust use juncture_core::pregel::scheduler::schedule_error_handlers_filtered; let recovery_tasks = schedule_error_handlers_filtered(&task_outputs, &nodes, &error_handler_map, &std::collections::HashSet::new()); for task in recovery_tasks { // Execute error handler task in next superstep } ``` -------------------------------- ### Basic entrypoint attribute usage Source: https://docs.rs/juncture/0.3.1/juncture/attr.entrypoint.html?search=u32+-%3E+bool The standard syntax for applying the entrypoint attribute. ```rust #[entrypoint] ``` -------------------------------- ### Example usage of consume_triggered_channels Source: https://docs.rs/juncture/0.3.1/juncture/pregel/fn.consume_triggered_channels.html Demonstrates how to invoke the function with a list of triggered channel indices. ```rust use juncture_core::pregel::scheduler::consume_triggered_channels; let triggered_channels = vec![0, 2]; // channels 0 and 2 were triggered consume_triggered_channels(&mut state, &triggered_channels); ``` -------------------------------- ### Runtime Methods Source: https://docs.rs/juncture/0.3.1/juncture/func/struct.Runtime.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Methods for initializing and configuring the Runtime instance. ```APIDOC ## Runtime::new ### Description Creates a new runtime with minimal configuration. ## Runtime::from_core ### Description Creates a functional runtime from a core runtime. This extracts functional-API-specific context from the core runtime, allowing entrypoint functions to access features like previous values. ## Runtime::from_entrypoint_config ### Description Creates a runtime from an entrypoint configuration. ## Runtime::with_previous ### Description Sets the previous execution value for the runtime. ## Runtime::with_checkpointer ### Description Sets the checkpointer for state persistence. ## Runtime::with_store ### Description Sets the persistent key-value store for the runtime. ## Runtime::with_core ### Description Sets the underlying core runtime. ``` -------------------------------- ### Injecting MetricsCollector into RunnableConfig Source: https://docs.rs/juncture/0.3.1/juncture/observability/trait.MetricsCollector.html Example showing how to attach a MetricsCollector implementation to a RunnableConfig instance. ```rust use std::sync::Arc; use juncture_core::observability::MetricsCollector; use juncture_core::config::RunnableConfig; let collector: Arc = /* ... */; let config = RunnableConfig::new() .with_metrics_collector(collector); ``` -------------------------------- ### Applying Writes Example Source: https://docs.rs/juncture/0.3.1/juncture/fn.apply_writes.html Basic usage of apply_writes to update state with task outputs. ```rust use juncture_core::pregel::scheduler::{apply_writes, FieldVersionTracker}; use std::collections::HashMap; let mut state = MyState::default(); let mut tracker = FieldVersionTracker::new(3); let node_registration = HashMap::new(); let changed = apply_writes(&mut state, &task_outputs, &mut tracker, &node_registration)?; ``` -------------------------------- ### RunnableConfig::new Source: https://docs.rs/juncture/0.3.1/juncture/config/struct.RunnableConfig.html?search=u32+-%3E+bool Creates a new instance of RunnableConfig. ```APIDOC ## RunnableConfig::new ### Description Creates a new instance of the `RunnableConfig` structure. ### Signature `pub fn new() -> RunnableConfig` ### Example ```rust use juncture_core::config::RunnableConfig; let config = RunnableConfig::new(); ``` ``` -------------------------------- ### Scratchpad::new Source: https://docs.rs/juncture/0.3.1/juncture/interrupt/struct.Scratchpad.html?search= Creates a new empty scratchpad instance. ```APIDOC ### pub fn new() -> Scratchpad Creates a new empty scratchpad. ``` -------------------------------- ### Get Failure Count Source: https://docs.rs/juncture/0.3.1/juncture/llm/struct.CircuitBreaker.html Retrieve the number of consecutive failures currently tracked by the circuit breaker. ```rust use juncture::llm::{CircuitBreaker, CircuitBreakerConfig}; let breaker = CircuitBreaker::new(CircuitBreakerConfig::default()); assert_eq!(breaker.failure_count(), 0); ``` -------------------------------- ### Get State History Source: https://docs.rs/juncture/0.3.1/juncture/client/struct.GraphClient.html?search= Retrieves a history of state snapshots for a given thread, with an optional limit. ```rust pub async fn get_state_history( &self, thread_id: &str, limit: Option, ) -> Result>, ClientError> where T: for<'de> Deserialize<'de>, ``` -------------------------------- ### Creating MetricsMiddleware Source: https://docs.rs/juncture/0.3.1/juncture/llm/struct.MetricsMiddleware.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initializes a new instance of the middleware with zeroed counters. ```rust use juncture::llm::MetricsMiddleware; let middleware = MetricsMiddleware::new(); ``` -------------------------------- ### Invoke a graph using PregelProtocol Source: https://docs.rs/juncture/0.3.1/juncture/pregel/trait.PregelProtocol.html Example usage of the invoke method on a graph implementing the PregelProtocol. ```rust use juncture_core::pregel::protocol::PregelProtocol; let result = graph.invoke(state, &config).await?; ``` -------------------------------- ### MemoryStore::new Source: https://docs.rs/juncture/0.3.1/juncture/prelude/store/struct.MemoryStore.html Creates a new instance of the MemoryStore. ```APIDOC ## pub fn new() -> MemoryStore ### Description Creates a new in-memory store instance. ``` -------------------------------- ### Usage Example for check_replace_conflicts Source: https://docs.rs/juncture/0.3.1/juncture/pregel/fn.check_replace_conflicts.html Demonstrates how to invoke the function with a list of field indices that utilize the ReplaceReducer. ```rust use juncture_core::pregel::scheduler::check_replace_conflicts; let replace_fields = vec![0, 2]; // fields 0 and 2 use ReplaceReducer check_replace_conflicts(&superstep_result, &replace_fields)?; ``` -------------------------------- ### Initialize PathMap from collections Source: https://docs.rs/juncture/0.3.1/juncture/edge/struct.PathMap.html Demonstrates creating a PathMap instance using a HashMap or a slice of key-value pairs. ```rust use juncture_core::edge::PathMap; use std::collections::HashMap; // From HashMap let mut map = HashMap::new(); map.insert("approve".to_string(), "publish".to_string()); map.insert("reject".to_string(), "archive".to_string()); let path_map = PathMap::from(map); // From slice let path_map = PathMap::from(&[("approve", "publish"), ("reject", "archive")][..]); ``` -------------------------------- ### FuncRuntime Initialization and Configuration Source: https://docs.rs/juncture/0.3.1/juncture/struct.FuncRuntime.html?search=std%3A%3Avec Methods for creating and configuring a FuncRuntime instance. ```APIDOC ## Runtime::new() ### Description Creates a new runtime with minimal configuration. ## Runtime::from_core(core: &Runtime) ### Description Creates a functional runtime from a core runtime, extracting context such as previous execution values. ## Runtime::from_entrypoint_config(config: &EntrypointConfig) ### Description Creates a runtime from an existing entrypoint configuration. ## Runtime::with_previous(self, previous: Value) ### Description Sets the previous execution return value for the runtime. ## Runtime::with_checkpointer(self, checkpointer: Arc) ### Description Sets the checkpointer for state persistence. ## Runtime::with_store(self, store: Arc) ### Description Sets the cross-thread persistent key-value store. ## Runtime::with_core(self, core: Runtime) ### Description Sets the underlying core runtime. ``` -------------------------------- ### Executing an Operation with Retry Source: https://docs.rs/juncture/0.3.1/juncture/graph/fn.execute_with_retry.html?search= Basic usage example demonstrating how to invoke execute_with_retry with a default policy. ```rust use juncture_core::graph::builder::{RetryPolicy, execute_with_retry}; let policy = RetryPolicy::default(); let result = execute_with_retry( "my_node", &policy, |state, config| my_node.call(state, config), state, &config, ).await?; ``` -------------------------------- ### Initialize ChatAnthropic with API key Source: https://docs.rs/juncture/0.3.1/juncture/llm/struct.ChatAnthropic.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Create a new client instance using a provided API key string. ```rust use juncture::llm::ChatAnthropic; let model = ChatAnthropic::new("sk-ant-...")?; ``` -------------------------------- ### Initialize AgentMiddlewareChain Source: https://docs.rs/juncture/0.3.1/juncture/prebuilt/agent_middleware/struct.AgentMiddlewareChain.html?search=u32+-%3E+bool Create a new chain and register middleware using the builder pattern. ```rust use juncture::prebuilt::middleware::{ AgentMiddlewareChain, LoopDetectionMiddleware, ToolErrorHandlingMiddleware, }; let chain = AgentMiddlewareChain::new() .with(LoopDetectionMiddleware::new(3)) .with(ToolErrorHandlingMiddleware::new()); ``` -------------------------------- ### Runtime Configuration Methods Source: https://docs.rs/juncture/0.3.1/juncture/func/struct.Runtime.html?search=std%3A%3Avec Fluent methods for configuring the Runtime instance. ```APIDOC ## Configuration Methods ### with_previous(self, previous: Value) -> Runtime Sets the previous execution value. ### with_checkpointer(self, checkpointer: Arc) -> Runtime Sets the checkpointer for state persistence. ### with_store(self, store: Arc) -> Runtime Sets the cross-thread persistent key-value store. ### with_core(self, core: Runtime) -> Runtime Sets the underlying core runtime. ``` -------------------------------- ### Emit Tool Started Event Source: https://docs.rs/juncture/0.3.1/juncture/prelude/struct.ToolRuntime.html?search=std%3A%3Avec Sends a ToolStarted lifecycle event through the configured tools event channel. ```rust pub fn emit_tool_started(&self, tool_name: &str, node: &str, input: Value) ``` -------------------------------- ### Initialize and Invoke ChatAnthropic Source: https://docs.rs/juncture/0.3.1/juncture/llm/struct.ChatAnthropic.html?search= Demonstrates creating a client from environment variables and invoking it with a message. ```rust use juncture::llm::{ChatModel, ChatAnthropic}; use juncture::Message; #[tokio::main] async fn main() -> Result<(), Box> { let model = ChatAnthropic::from_env()?; let messages = vec![Message::human("Hello!")]; let response = model.invoke(&messages, None).await?; Ok(()) } ``` -------------------------------- ### Get mutable reference to Arc Source: https://docs.rs/juncture/0.3.1/juncture/prelude/prebuilt/type.ModelSelector.html Retrieves a mutable reference if no other pointers exist, otherwise returns None. ```rust use std::sync::Arc; let mut x = Arc::new(3); *Arc::get_mut(&mut x).unwrap() = 4; assert_eq!(*x, 4); let _y = Arc::clone(&x); assert!(Arc::get_mut(&mut x).is_none()); ``` -------------------------------- ### Using the store in Runtime Source: https://docs.rs/juncture/0.3.1/juncture/func/struct.Runtime.html Shows how to interact with the persistent key-value store available within the functional runtime. ```rust use juncture_core::func::Runtime; async fn workflow_with_store( state: CowState, runtime: &CoreRuntime, ) -> Result { let func_runtime = Runtime::from_core(runtime); if let Some(store) = &func_runtime.store { store.put("key", serde_json::json!("value")).await?; } Ok(MyStateUpdate::default()) } ``` -------------------------------- ### Configure TimeoutPolicy instance Source: https://docs.rs/juncture/0.3.1/juncture/pregel/struct.TimeoutPolicy.html Example of creating a default TimeoutPolicy and setting a specific run timeout duration. ```rust use juncture_core::pregel::context::TimeoutPolicy; use std::time::Duration; let policy = TimeoutPolicy::default() .with_run_timeout(Duration::from_secs(60)); ``` -------------------------------- ### Initialize and use InterruptContext Source: https://docs.rs/juncture/0.3.1/juncture/interrupt/struct.InterruptContext.html Demonstrates creating a new InterruptContext with resume values and a channel, then retrieving the next interrupt index. ```rust use juncture_core::interrupt::InterruptContext; use serde_json::json; let mut context = InterruptContext::new( vec![Some(json!("human_input"))], tokio::sync::mpsc::unbounded_channel(), ); // Get next interrupt index (increments counter) let index = context.next_index(); ``` -------------------------------- ### AgentNode Initialization Methods Source: https://docs.rs/juncture/0.3.1/juncture/prebuilt/struct.AgentNode.html Constructors for creating an AgentNode instance with or without a system prompt. ```rust pub fn new(model: M) -> Self ``` ```rust pub fn with_prompt(model: M, prompt: PromptSource) -> Self ``` -------------------------------- ### Implement Summarizer for LlmSummarizer Source: https://docs.rs/juncture/0.3.1/juncture/memory/trait.Summarizer.html Example of implementing the Summarizer trait for an LLM-based summarizer using a generic ChatModel. ```rust impl Summarizer for LlmSummarizer ``` -------------------------------- ### Creating a new LoggingMiddleware instance Source: https://docs.rs/juncture/0.3.1/juncture/llm/struct.LoggingMiddleware.html Initialize a default logging middleware instance. ```rust use juncture::llm::LoggingMiddleware; let middleware = LoggingMiddleware::new(); ```