### Quick Example: Running an AgentLoop Source: https://github.com/secbear/neuron/blob/main/docs/book/src/guides/loop.md Demonstrates the basic setup and execution of an AgentLoop with a provider, context strategy, and tools. It shows how to build the agent, run a text-based query, and print the results including response, turns, and token usage. ```rust use neuron_context::SlidingWindowStrategy; use neuron_loop::AgentLoop; use neuron_tool::ToolRegistry; use neuron_types::ToolContext; let provider = Anthropic::from_env()?; let context = SlidingWindowStrategy::new(20, 100_000); let mut tools = ToolRegistry::new(); tools.register(MySearchTool); tools.register(MyCalculateTool); let mut agent = AgentLoop::builder(provider, context) .tools(tools) .system_prompt("You are a helpful research assistant.") .max_turns(15) .parallel_tool_execution(true) .build(); let ctx = ToolContext::default(); let result = agent.run_text("Find the population of Tokyo", &ctx).await?; println!("Response: {}", result.response); println!("Turns: {}, Tokens: {} in / {} out", result.turns, result.usage.input_tokens, result.usage.output_tokens); ``` -------------------------------- ### Quick Start: Building an AI Agent with Neuron Source: https://github.com/secbear/neuron/blob/main/neuron/README.md A basic example of how to initialize and run an AI agent using the Neuron library. It sets up an Anthropic provider, a sliding window context strategy, and a tool registry, then executes a simple text prompt. ```rust use neuron::prelude::*; use neuron::anthropic::Anthropic; #[tokio::main] async fn main() -> Result<(), Box> { let provider = Anthropic::new("your-api-key").model("claude-sonnet-4-20250514"); let context = SlidingWindowStrategy::new(10, 100_000); let tools = ToolRegistry::new(); let mut agent = AgentLoop::builder(provider, context) .system_prompt("You are a helpful assistant.") .max_turns(10) .tools(tools) .build(); let ctx = ToolContext { cwd: std::env::current_dir()?, session_id: "demo".into(), environment: Default::default(), cancellation_token: Default::default(), progress_reporter: None, }; let result = agent.run_text("Hello!", &ctx).await?; println!("{}", result.response); Ok(()) } ``` -------------------------------- ### Full Production Agent Composition Example (Rust) Source: https://github.com/secbear/neuron/blob/main/llms.txt Composes sessions, guardrails, and `TracingHook` for a full production-ready agent setup. This example integrates multiple advanced features. ```rust /* Sessions + guardrails + TracingHook composed https://github.com/secbear/neuron/blob/main/neuron-runtime/examples/full_production.rs */ // Placeholder for actual code content fn main() { println!("Full production example"); } ``` -------------------------------- ### Rust: Durable Production Agent Composition Example Source: https://github.com/secbear/neuron/blob/main/docs/plans/2026-02-21-rust-agent-blocks-design.md Presents a comprehensive setup for a production-ready agent, integrating durable execution via Temporal, custom tools, a composite context strategy, and guardrails. It also demonstrates step-by-step execution control for framework authors. ```rust use neuron_types::*; use neuron_provider_anthropic::Anthropic; use neuron_tool::ToolRegistry; use neuron_context::CompositeStrategy; use neuron_loop::AgentLoop; use neuron_runtime::*; let provider = Anthropic::new(api_key).model("claude-sonnet-4-20250514"); let tools = /* ... */; let context = /* ... */; // Durable execution via Temporal let durability = TemporalDurableContext::connect("localhost:7233", "agent-tasks").await?; let mut agent = AgentLoop::new(provider, tools, context) .system_prompt("You are a production agent.") .max_turns(100) .with_durability(durability) .with_guardrail(NoSecretsGuardrail::new()); // Step-by-step execution for framework authors let mut steps = agent.run_step("Deploy the new feature"); while let Some(turn) = steps.next().await { match turn { TurnResult::ToolsExecuted { calls, .. } => { for call in &calls { println!("[tool: {}]", call.name); } } TurnResult::FinalResponse(result) => { println!("{}", result.response); break; } _ => {} } } ``` -------------------------------- ### Bash Commit Example Source: https://github.com/secbear/neuron/blob/main/docs/plans/2026-02-22-quick-wins.md An example of a Git commit command used to stage and commit documentation changes. This specific commit message reflects simplifications made to the Quick Start section, including the use of `from_env()` and `ToolContext::default()`. ```bash git add README.md git commit -m "docs: simplify Quick Start with from_env(), Message::user(), ToolContext::default()" ``` -------------------------------- ### Rust: Minimal Agent Composition Example Source: https://github.com/secbear/neuron/blob/main/docs/plans/2026-02-21-rust-agent-blocks-design.md Demonstrates the creation of a minimal Neuron agent using three core blocks: a provider (Anthropic), a tool registry, and a context strategy (SlidingWindowStrategy). This example shows how to initialize an `AgentLoop` and run a simple query. ```rust use neuron_types::*; use neuron_provider_anthropic::Anthropic; use neuron_loop::AgentLoop; let provider = Anthropic::new(api_key).model("claude-sonnet-4-20250514"); let context = neuron_context::SlidingWindowStrategy::new(100_000); let mut agent = AgentLoop::new(provider, neuron_tool::ToolRegistry::new(), context) .system_prompt("You are a helpful assistant."); let result = agent.run("What is the capital of France?").await?; println!("{}", result.response); ``` -------------------------------- ### Agent Loop Execution Example (Rust) Source: https://github.com/secbear/neuron/blob/main/llms.txt Demonstrates step-by-step agent loop execution using a mock provider. This example is helpful for understanding the internal workings of the agent's decision-making process. ```rust /* Step-by-step loop execution with mock provider https://github.com/secbear/neuron/blob/main/neuron-loop/examples/agent_loop.rs */ // Placeholder for actual code content fn main() { println!("Agent loop example"); } ``` -------------------------------- ### Anthropic Provider Basic Usage Example (Rust) Source: https://github.com/secbear/neuron/blob/main/llms.txt Demonstrates the direct usage of the Anthropic provider for interacting with Anthropic's language models. This serves as a starting point for integrating Anthropic. ```rust /* Direct provider usage https://github.com/secbear/neuron/blob/main/neuron-provider-anthropic/examples/basic.rs */ // Placeholder for actual code content fn main() { println!("Anthropic provider example"); } ``` -------------------------------- ### Rust: Coding Agent with MCP Tools Example Source: https://github.com/secbear/neuron/blob/main/docs/plans/2026-02-21-rust-agent-blocks-design.md Illustrates a more complex agent setup for coding tasks, incorporating multiple MCP (Meta-Cognitive Programming) tools like file reading, editing, and bash execution. It also shows how to integrate external tools discovered via MCP and apply per-tool middleware. ```rust use neuron_types::*; use neuron_provider_anthropic::Anthropic; use neuron_tool::ToolRegistry; use neuron_mcp::McpClient; use neuron_context::CompositeStrategy; use neuron_loop::AgentLoop; let provider = Anthropic::new(api_key).model("claude-sonnet-4-20250514"); let mut tools = ToolRegistry::new(); tools.register(my_tools::ReadFile); tools.register(my_tools::EditFile); tools.register(my_tools::Bash); // MCP tools integrate seamlessly let github = McpClient::connect_stdio("npx", &["@mcp/server-github"]).await?; for tool in github.discover_tools().await? { tools.register_dyn(tool); } // Per-tool middleware tools.add_tool_middleware("bash", my_middleware::PermissionRequired); let context = CompositeStrategy::new(vec![ Box::new(neuron_context::ToolResultClearingStrategy::new(10)), Box::new(neuron_context::SummarizationStrategy::new( Anthropic::new(api_key).model("claude-haiku-4-5-20251001"), 20, )), ]); let mut agent = AgentLoop::new(provider, tools, context) .system_prompt("You are a coding assistant.") .max_turns(50); let result = agent.run("Fix the bug in src/main.rs").await?; ``` -------------------------------- ### OpenAI Provider Basic Usage Example (Rust) Source: https://github.com/secbear/neuron/blob/main/llms.txt Illustrates the direct usage of the OpenAI provider for interacting with OpenAI's language models. This is a fundamental example for OpenAI integration. ```rust /* Direct provider usage https://github.com/secbear/neuron/blob/main/neuron-provider-openai/examples/basic.rs */ // Placeholder for actual code content fn main() { println!("OpenAI provider example"); } ``` -------------------------------- ### Full Agent Loop Example (Rust) Source: https://github.com/secbear/neuron/blob/main/llms.txt Demonstrates an end-to-end agent loop with integrated tools and context management. This example showcases the core agent functionality. ```rust /* Full agent loop with tools and context https://github.com/secbear/neuron/blob/main/neuron/examples/full_agent.rs */ // Placeholder for actual code content fn main() { println!("Full agent example"); } ``` -------------------------------- ### Quick Start: Running an AI Agent with Anthropic Provider Source: https://github.com/secbear/neuron/blob/main/README.md This example demonstrates how to initialize and run a basic AI agent using the neuron library. It utilizes the Anthropic provider and a sliding window context strategy. The agent is configured with a system prompt and then used to process a simple text input, printing the response. Ensure the ANTHROPIC_API_KEY environment variable is set. ```rust use neuron::prelude::*; use neuron::anthropic::Anthropic; #[tokio::main] async fn main() -> Result<(), Box> { let provider = Anthropic::from_env()?; let context = SlidingWindowStrategy::new(10, 100_000); let mut agent = AgentLoop::builder(provider, context) .system_prompt("You are a helpful assistant.") .build(); let result = agent.run_text("Hello!", &ToolContext::default()).await?; println!("{}", result.response); Ok(()) } ``` -------------------------------- ### Session Management with FileStorage Example (Rust) Source: https://github.com/secbear/neuron/blob/main/llms.txt Demonstrates creating, saving, and loading agent sessions using `FileSessionStorage`. This is essential for persistent agent states. ```rust /* Create, save, load sessions with FileSessionStorage https://github.com/secbear/neuron/blob/main/neuron-runtime/examples/sessions.rs */ // Placeholder for actual code content fn main() { println!("Session management example"); } ``` -------------------------------- ### Testing Agents with Mock Providers Example (Rust) Source: https://github.com/secbear/neuron/blob/main/llms.txt Illustrates patterns for unit testing agents using mock providers. This example is essential for building reliable and maintainable agent systems. ```rust /* Mock provider patterns for unit testing agents https://github.com/secbear/neuron/blob/main/neuron/examples/testing_agents.rs */ // Placeholder for actual code content fn main() { println!("Testing agents example"); } ``` -------------------------------- ### Parallel Tool Execution Example (Rust) Source: https://github.com/secbear/neuron/blob/main/llms.txt Demonstrates concurrent tool execution using `join_all`. This allows multiple tools to be run in parallel, improving efficiency for independent tasks. ```rust /* Concurrent tool execution via join_all https://github.com/secbear/neuron/blob/main/neuron-loop/examples/parallel_tools.rs */ // Placeholder for actual code content fn main() { println!("Parallel tools example"); } ``` -------------------------------- ### Server-Side Context Management Example (Rust) Source: https://github.com/secbear/neuron/blob/main/llms.txt Illustrates server-side context management and compaction strategies, specifically with the Anthropic provider. This optimizes context handling on the server. ```rust /* Server-side compaction https://github.com/secbear/neuron/blob/main/neuron-provider-anthropic/examples/context_management.rs */ // Placeholder for actual code content fn main() { println!("Context management example"); } ``` -------------------------------- ### Context Compaction Example (Rust) Source: https://github.com/secbear/neuron/blob/main/llms.txt Illustrates the sliding window strategy for context compaction in a growing conversation. This helps manage memory usage and focus on relevant information. ```rust /* Sliding window strategy on a growing conversation https://github.com/secbear/neuron/blob/main/neuron-context/examples/compaction.rs */ // Placeholder for actual code content fn main() { println!("Context compaction example"); } ``` -------------------------------- ### Tool Middleware Example (Rust) Source: https://github.com/secbear/neuron/blob/main/llms.txt Shows how to implement middleware for tool calls, specifically focusing on logging and authentication. This allows for centralized control over tool interactions. ```rust /* Logging and auth middleware on tool calls https://github.com/secbear/neuron/blob/main/neuron-tool/examples/middleware.rs */ // Placeholder for actual code content fn main() { println!("Tool middleware example"); } ``` -------------------------------- ### Streaming Token Output Example (Rust) Source: https://github.com/secbear/neuron/blob/main/llms.txt Demonstrates how to handle streaming token output from a provider, such as Anthropic. This allows for real-time display of model responses. ```rust /* Streaming token output https://github.com/secbear/neuron/blob/main/neuron-provider-anthropic/examples/streaming.rs */ // Placeholder for actual code content fn main() { println!("Streaming example"); } ``` -------------------------------- ### Multi-Turn Conversation Loop Example (Rust) Source: https://github.com/secbear/neuron/blob/main/llms.txt Shows how to manage multi-turn conversations using a mock provider. This example is useful for testing conversational flows without external dependencies. ```rust /* Multi-turn conversation with mock provider https://github.com/secbear/neuron/blob/main/neuron-loop/examples/multi_turn.rs */ // Placeholder for actual code content fn main() { println!("Multi-turn loop example"); } ``` -------------------------------- ### Ollama Provider Basic Usage Example (Rust) Source: https://github.com/secbear/neuron/blob/main/llms.txt Shows the direct usage of the Ollama provider for interacting with local Ollama models. This example is useful for developers running models locally. ```rust /* Direct provider usage https://github.com/secbear/neuron/blob/main/neuron-provider-ollama/examples/basic.rs */ // Placeholder for actual code content fn main() { println!("Ollama provider example"); } ``` -------------------------------- ### Multi-Provider Request Example (Rust) Source: https://github.com/secbear/neuron/blob/main/llms.txt Shows how to send the same request to multiple providers, such as Anthropic and OpenAI, simultaneously. This allows for comparing responses or using the best available model. ```rust /* Same request to Anthropic and OpenAI https://github.com/secbear/neuron/blob/main/neuron/examples/multi_provider.rs */ // Placeholder for actual code content fn main() { println!("Multi-provider example"); } ``` -------------------------------- ### Quick Example: Anthropic Provider Usage in Rust Source: https://github.com/secbear/neuron/blob/main/docs/book/src/guides/providers.md Demonstrates how to instantiate and use the Anthropic provider to send a completion request and print the response. It requires the `neuron-provider-anthropic` and `neuron-types` crates and uses `tokio` for asynchronous operations. The example shows setting up the provider from environment variables and constructing a basic completion request. ```rust use neuron_provider_anthropic::Anthropic; use neuron_types::{CompletionRequest, Message, Provider}; #[tokio::main] async fn main() -> Result<(), Box> { let provider = Anthropic::from_env()?; let request = CompletionRequest { messages: vec![Message::user("What is Rust?")], max_tokens: Some(256), ..Default::default() }; let response = provider.complete(request).await?; println!("{}", response.message.content[0]); // ContentBlock::Text(...) println!("Tokens: {} in, {} out", response.usage.input_tokens, response.usage.output_tokens); Ok(()) } ``` -------------------------------- ### Structured Output with JSON Schema Example (Rust) Source: https://github.com/secbear/neuron/blob/main/llms.txt Demonstrates how to obtain structured responses constrained by JSON Schema from language models. This ensures predictable and usable output formats. ```rust /* JSON Schema-constrained responses https://github.com/secbear/neuron/blob/main/neuron/examples/structured_output.rs */ // Placeholder for actual code content fn main() { println!("Structured output example"); } ``` -------------------------------- ### TracingHook Output Example (Rust) Source: https://github.com/secbear/neuron/blob/main/llms.txt Illustrates how to generate structured tracing output from hook events using `TracingHook`. This is valuable for debugging and monitoring agent behavior. ```rust /* Structured tracing output from hook events https://github.com/secbear/neuron/blob/main/neuron-runtime/examples/tracing_hook.rs */ // Placeholder for actual code content fn main() { println!("TracingHook example"); } ``` -------------------------------- ### Custom Tool Definition and Execution Example (Rust) Source: https://github.com/secbear/neuron/blob/main/llms.txt Illustrates how to define, register, and execute custom tools within the Neuron framework, including the use of middleware for enhanced functionality. ```rust /* Define, register, and execute tools with middleware https://github.com/secbear/neuron/blob/main/neuron-tool/examples/custom_tool.rs */ // Placeholder for actual code content fn main() { println!("Custom tool example"); } ``` -------------------------------- ### Derive Tool Macro Example (Rust) Source: https://github.com/secbear/neuron/blob/main/llms.txt Demonstrates the use of the `#[neuron_tool]` procedural macro for defining tools, including custom types and automatic registration with the tool registry. ```rust /* `#[neuron_tool]` proc-macro with custom types and registry https://github.com/secbear/neuron/blob/main/neuron-tool/examples/derive_tool.rs */ // Placeholder for actual code content fn main() { println!("Derive tool macro example"); } ``` -------------------------------- ### Guardrails for Input/Output Safety Example (Rust) Source: https://github.com/secbear/neuron/blob/main/llms.txt Shows how to implement input and output safety checks using guardrails. This ensures that agent interactions adhere to defined constraints and policies. ```rust /* Input/output safety checks https://github.com/secbear/neuron/blob/main/neuron-runtime/examples/guardrails.rs */ // Placeholder for actual code content fn main() { println!("Guardrails example"); } ``` -------------------------------- ### Agent Loop Cancellation Example (Rust) Source: https://github.com/secbear/neuron/blob/main/llms.txt Shows how to cooperatively stop the agent loop using `CancellationToken`. This is crucial for graceful shutdown and managing long-running processes. ```rust /* CancellationToken stops the agent loop cooperatively https://github.com/secbear/neuron/blob/main/neuron-loop/examples/cancellation.rs */ // Placeholder for actual code content fn main() { println!("Cancellation example"); } ``` -------------------------------- ### Local Durable Context Example (Rust) Source: https://github.com/secbear/neuron/blob/main/llms.txt Shows the passthrough durable context for local development scenarios using `LocalDurableContext`. This simplifies local testing and development workflows. ```rust /* Passthrough durable context for local development https://github.com/secbear/neuron/blob/main/neuron-runtime/examples/local_durable.rs */ // Placeholder for actual code content fn main() { println!("LocalDurableContext example"); } ``` -------------------------------- ### Markdown Summary for mdBook Source: https://github.com/secbear/neuron/blob/main/docs/plans/2026-02-22-path-to-10-implementation.md This Markdown file defines the structure and navigation for the mdBook documentation site. It includes a main summary, sections for Getting Started, Guides, and Architecture, with links to individual pages within each section. ```markdown # Summary [Introduction](introduction.md) # Getting Started - [Installation](getting-started/installation.md) - [Quickstart](getting-started/quickstart.md) - [Core Concepts](getting-started/concepts.md) # Guides - [Tools](guides/tools.md) - [Context Management](guides/context.md) - [Providers](guides/providers.md) - [The Agent Loop](guides/loop.md) - [MCP Integration](guides/mcp.md) - [Runtime](guides/runtime.md) - [Embeddings](guides/embeddings.md) - [Testing Agents](guides/testing.md) # Architecture - [Design Decisions](architecture/design-decisions.md) - [Dependency Graph](architecture/dependency-graph.md) - [Comparison](architecture/comparison.md) ``` -------------------------------- ### Generate Text Embeddings with OpenAI Provider Source: https://github.com/secbear/neuron/blob/main/docs/book/src/guides/embeddings.md Demonstrates how to use the `OpenAi` client from `neuron-provider-openai` to generate text embeddings. It shows the setup of the client, the structure of an `EmbeddingRequest`, and how to process the `EmbeddingResponse`. This example requires the `tokio` runtime. ```rust use neuron_provider_openai::OpenAi; use neuron_types::{EmbeddingProvider, EmbeddingRequest}; #[tokio::main] async fn main() -> Result<(), Box> { let client = OpenAi::from_env()?; let response = client.embed(EmbeddingRequest { model: "text-embedding-3-small".to_string(), input: vec![ "Rust is a systems programming language.".to_string(), "Python is great for scripting.".to_string(), ], dimensions: None, ..Default::default() }).await?; println!("Got {} embeddings", response.embeddings.len()); println!("First vector has {} dimensions", response.embeddings[0].len()); println!("Tokens used: {}", response.usage.total_tokens); Ok(()) } ``` -------------------------------- ### Build and Run AI Agent with Neuron in Rust Source: https://github.com/secbear/neuron/blob/main/docs/book/src/getting-started/quickstart.md This Rust code snippet demonstrates the core functionality of the Neuron library for building an AI agent. It includes defining a custom tool for fetching weather information, setting up an Anthropic AI provider, registering the tool, configuring a context strategy, and running the agent loop to process user messages and execute tools. ```rust use neuron::prelude::*; use neuron_provider_anthropic::Anthropic; use neuron_tool::ToolRegistry; use neuron_loop::AgentLoop; use neuron_context::SlidingWindowStrategy; use neuron_types::*; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; // 1. Define a tool struct GetWeather; impl Tool for GetWeather { const NAME: &'static str = "get_weather"; type Args = WeatherArgs; type Output = String; type Error = std::io::Error; fn definition(&self) -> ToolDefinition { ToolDefinition { name: "get_weather".to_string(), title: None, description: "Get the current weather for a city".to_string(), input_schema: schemars::schema_for!(WeatherArgs).into(), output_schema: None, annotations: None, cache_control: None, } } async fn call(&self, args: WeatherArgs, _ctx: &ToolContext) -> Result { Ok(format!("Weather in {}: 72°F, sunny", args.city)) } } #[derive(Debug, Deserialize, JsonSchema)] struct WeatherArgs { /// The city to get weather for city: String, } #[tokio::main] async fn main() -> Result<(), Box> { // 2. Set up a provider let provider = Anthropic::from_env()?; // 3. Register tools let mut tools = ToolRegistry::new(); tools.register(GetWeather); // 4. Create the context strategy let context = SlidingWindowStrategy::new(10, 100_000); // 5. Build and run the agent loop let mut agent = AgentLoop::builder(provider, context) .tools(tools) .system_prompt("You are a helpful weather assistant.") .max_turns(5) .build(); let ctx = ToolContext::default(); let result = agent.run(Message::user("What's the weather in San Francisco?"), &ctx).await?; println!("{}", result.response); Ok(()) } ``` -------------------------------- ### Update Rustdoc Examples from ignore to no_run Source: https://github.com/secbear/neuron/blob/main/docs/plans/2026-02-22-quick-wins.md This task involves changing Rust documentation examples within trait implementations from `ignore` fences to `no_run` fences. The `no_run` attribute allows rustdoc to compile the examples, verifying their correctness without executing them at runtime. This is particularly useful for examples that contain `todo!()` or other code that would panic if run. ```rust /// ```no_run /// ``` ``` -------------------------------- ### Agent Loop Execution Example (Rust) Source: https://github.com/secbear/neuron/blob/main/neuron/tests/HUMAN.md Demonstrates the creation and execution of an AgentLoop with Anthropic provider, a CalculateTool, and a SlidingWindowStrategy. It shows the internal loop logic for handling tool use and generating a final response. ```rust use agent_blocks::*; use agent_blocks::provider::anthropic::AnthropicProvider; use agent_blocks::tool::{CalculateTool, ToolRegistry}; use agent_blocks::context::SlidingWindowStrategy; // ... (setup code for provider, tools, context, config) ... let provider = AnthropicProvider::new(anthropic_key, "claude-haiku-4-5-20251001".to_string()); let mut tools = ToolRegistry::new(); tools.register(CalculateTool); let context = SlidingWindowStrategy::new(10, 100_000); let config = LoopConfig { system_prompt: "You are a math assistant. Use the calculate tool for any arithmetic.".to_string(), max_turns: 5, }; let mut agent = AgentLoop::new(provider, tools, context, config); let user_msg = "What is 99 * 101? Use the calculate tool."; let ctx = agent_blocks::context::Context::new(); let result = agent.run(user_msg, &ctx).await; // Assertions on the result assert!(result.turns >= 2); assert!(result.response.contains("9999") || result.response.contains("9,999")); assert!(result.usage.total_tokens > 0); ``` -------------------------------- ### Neuron Umbrella Crate Dependency Example Source: https://github.com/secbear/neuron/blob/main/docs/book/src/architecture/dependency-graph.md Example of how to include the Neuron umbrella crate in your project's dependencies, using feature flags to enable specific provider crates like 'anthropic' and 'openai'. This allows for selective inclusion of functionalities. ```toml [dependencies] neuron = { version = "0.2", features = ["anthropic", "openai"] } ``` -------------------------------- ### Commit Changes for Rustdoc Example Update Source: https://github.com/secbear/neuron/blob/main/docs/plans/2026-02-22-quick-wins.md This bash script shows the Git commands to commit the changes made to update Rust documentation examples from `ignore` to `no_run` fences. It adds the modified `neuron-types/src/traits.rs` file and creates a commit with a `docs` scope. ```bash git add neuron-types/src/traits.rs git commit -m "docs(types): change trait examples from ignore to no_run" ``` -------------------------------- ### Implement Provider Trait for LLM Completion Source: https://github.com/secbear/neuron/blob/main/neuron-types/README.md Illustrates the skeleton implementation of the `Provider` trait for handling LLM completions. This example uses native async Rust without `#[async_trait]` and defines `complete` and `complete_stream` methods. Note that this is an abstract example and would require actual API calls in a real implementation. ```rust use neuron_types::*; use std::future::Future; struct MyProvider { /* ... */ } impl Provider for MyProvider { fn complete(&self, request: CompletionRequest) -> impl Future> + Send { async { todo!() } } fn complete_stream(&self, request: CompletionRequest) -> impl Future> + Send { async { todo!() } } } ``` -------------------------------- ### Commit Initialization of neuron-provider-anthropic Source: https://github.com/secbear/neuron/blob/main/docs/plans/2026-02-21-implementation-plan.md Commits the initialization of the 'neuron-provider-anthropic' crate, marking the start of its development. ```bash feat(neuron-provider-anthropic): initialize crate ``` -------------------------------- ### Install neuron-context Crate Source: https://github.com/secbear/neuron/blob/main/neuron-context/README.md Adds the neuron-context crate to your project's dependencies using Cargo. ```sh cargo add neuron-context ``` -------------------------------- ### Rust OpenAI Completions Example Source: https://github.com/secbear/neuron/blob/main/neuron-provider-openai/README.md Demonstrates how to use the OpenAi client to perform text completions using the OpenAI API. It shows setting up the provider, defining a completion request with messages and system prompts, and processing the response. Requires the 'neuron-types' and 'tokio' crates. ```rust use neuron_provider_openai::OpenAi; use neuron_types::{CompletionRequest, ContentBlock, Message, Provider, Role, SystemPrompt}; #[tokio::main] async fn main() -> Result<(), Box> { let provider = OpenAi::new("sk-...") .model("gpt-4o") .organization("org-..."); let request = CompletionRequest { messages: vec![Message { role: Role::User, content: vec![ContentBlock::Text("Explain Rust's ownership model.".into())], }], system: Some(SystemPrompt::Text("You are a helpful assistant.".into())), max_tokens: Some(1024), ..Default::default() }; let response = provider.complete(request).await?; for block in &response.message.content { println!("{block:?}"); } Ok(()) } ``` -------------------------------- ### Install neuron-provider-anthropic Source: https://github.com/secbear/neuron/blob/main/neuron-provider-anthropic/README.md Adds the neuron-provider-anthropic crate to your project's dependencies using Cargo. ```sh cargo add neuron-provider-anthropic ``` -------------------------------- ### CompositeStrategy Initialization Source: https://github.com/secbear/neuron/blob/main/docs/book/src/guides/context.md Shows how to create a `CompositeStrategy` by chaining multiple strategies. Strategies are boxed and applied in order, with token count re-estimation after each step. This example prioritizes cheaper strategies like clearing tool results before dropping messages. ```rust use neuron_context::{ CompositeStrategy, SlidingWindowStrategy, ToolResultClearingStrategy, strategies::BoxedStrategy, }; let strategy = CompositeStrategy::new(vec![ // First: clear old tool results (cheap, often sufficient) BoxedStrategy::new(ToolResultClearingStrategy::new(2, 100_000)), // Second: drop old messages if still over budget BoxedStrategy::new(SlidingWindowStrategy::new(10, 100_000)), ], 100_000); ``` -------------------------------- ### Embeddings with OpenAI Example (Rust) Source: https://github.com/secbear/neuron/blob/main/llms.txt Illustrates the `EmbeddingProvider` with OpenAI, including calculating cosine similarity. This is useful for tasks involving semantic search and vector embeddings. ```rust /* EmbeddingProvider with OpenAI, cosine similarity https://github.com/secbear/neuron/blob/main/neuron-provider-openai/examples/embeddings.rs */ // Placeholder for actual code content fn main() { println!("Embeddings example"); } ``` -------------------------------- ### MCP Client and Tool Bridging Example (Rust) Source: https://github.com/secbear/neuron/blob/main/llms.txt Illustrates how to connect to an MCP server, discover available tools, and bridge them for use within the Neuron framework. This is key for distributed agent systems. ```rust /* Connect to MCP server, discover and bridge tools https://github.com/secbear/neuron/blob/main/neuron-mcp/examples/mcp_client.rs */ // Placeholder for actual code content fn main() { println!("MCP client example"); } ``` -------------------------------- ### Quick Example: Persisting and Loading Sessions with FileSessionStorage Source: https://github.com/secbear/neuron/blob/main/docs/book/src/guides/runtime.md Demonstrates the basic usage of FileSessionStorage to persist a session to disk and then load it back. This is useful for maintaining conversation history across application restarts. ```rust use std::path::PathBuf; use neuron_runtime::* use neuron_types::Message; #[tokio::main] async fn main() -> Result<(), Box> { // Persist sessions to disk let storage = FileSessionStorage::new(PathBuf::from("./sessions")); let mut session = Session::new("s-1", PathBuf::from(".")); session.messages.push(Message::user("Hello")); storage.save(&session).await?; // Load it back later let loaded = storage.load("s-1").await?; println!("{} messages", loaded.messages.len()); Ok(()) } ``` -------------------------------- ### Connect and Register MCP Tools via Stdio Source: https://github.com/secbear/neuron/blob/main/docs/book/src/guides/mcp.md This example demonstrates connecting to an MCP server using stdio, discovering available tools, and registering them with a ToolRegistry. It requires the `neuron-mcp` and `neuron-tool` crates. The input is a `StdioConfig` defining how to spawn the MCP server process. ```rust use std::sync::Arc; use neuron_mcp::{McpClient, McpToolBridge, StdioConfig}; use neuron_tool::ToolRegistry; #[tokio::main] async fn main() -> Result<(), Box> { // Connect to an MCP server via stdio let client = Arc::new(McpClient::connect_stdio(StdioConfig { command: "npx".to_string(), args: vec!["-y".to_string(), "@modelcontextprotocol/server-filesystem".to_string(), "/tmp".to_string()], env: vec![], }).await?); // Discover tools and register them let tools = McpToolBridge::discover(&client).await?; let mut registry = ToolRegistry::new(); for tool in tools { registry.register_dyn(tool); } Ok(()) } ```