Skip to main content

Crate polaris_ai

Crate polaris_ai 

Source
Expand description

A modular framework for building AI agents in Rust.

Polaris is an ECS-inspired runtime for composing AI agents as directed graphs of systems. It provides layered abstractions — from low-level dependency-injected systems, through graph-based execution, up to session management and HTTP serving.

§Why Polaris

Building performant AI agents is a design problem. The bottleneck is not compute, APIs, or infrastructure — it is discovering how an agent should behave for a given use case, and being able to change that behavior quickly when it turns out to be wrong.

Polaris provides composable primitives without prescribing how they should be assembled. There is no default execution loop. Agent behavior is constructed from small, replaceable parts, and the framework imposes no opinion on the result.

§Architecture

Polaris is organized into three layers. Lower layers are fixed primitives; upper layers are swappable.

LayerNameModulesScope
1System FrameworksystemSystems, resources, plugins, server
2Graph Executiongraph, agentDirected-graph model, agent trait
3Pluginstools, models, plugins, sessions, app, shellLLM providers, tools, HTTP, sessions

Layer 1 provides the ECS-inspired primitives: systems as pure async functions, resources as shared state, dependency injection via typed parameters, plugins as the unit of composition, and the Server runtime.

Layer 2 defines how agents are structured: a directed graph of nodes (computation, control flow) connected by edges (sequential, conditional, parallel, looping). The Agent trait packages a behavior pattern as a reusable graph builder.

Layer 3 delivers every optional capability through plugins: LLM providers, tool registries, session management, HTTP serving, and more. Every component is replaceable.

§Quick Start

use polaris_ai::prelude::*;
use polaris_ai::system::system;
use polaris_ai::system::server::Server;
use polaris_ai::plugins::MinimalPlugins;
use polaris_ai::graph::GraphExecutor;

#[system]
async fn greet() -> String {
    "Hello from Polaris!".to_string()
}

let mut server = Server::new();
server.add_plugins(MinimalPlugins.build());
server.finish().await;

let graph = {
    let mut g = Graph::new();
    g.add_system(greet);
    g
};

let mut ctx = server.create_context();
let executor = GraphExecutor::new();
let result = executor.execute(&graph, &mut ctx, None, None).await?;
let output = result.output::<String>();

§Core Concepts

§Systems and Resources

A system is a pure async function that declares its dependencies as typed parameters. The #[system] macro generates the boilerplate:

#[system]
async fn reason(llm: Res<LlmClient>, memory: Res<Memory>) -> ReasoningResult {
    // Access resources, produce output
    ReasoningResult { action: "search".into() }
}

Resources are how agents get capabilities. An LLM provider, a tool registry, a memory backend — each exists as a resource in the SystemContext:

ParameterResolutionAccessUse for
Res<T>Hierarchy (local → parent → global)ImmutableConfig, registries, per-request input
ResMut<T>Current context onlyExclusiveAccumulated state (conversation history)
Out<T>Previous system outputImmutableSystem-to-system data handoff
ErrOut<T>Error-edge outputImmutableError context in handler subgraphs

§Graphs

Agent logic is expressed as a directed graph of systems and control flow:

let mut graph = Graph::new();
graph
    .add_system(reason)
    .add_conditional_branch::<ReasoningResult, _, _, _>(
        "needs_tool",
        |r| r.needs_tool,
        |g| { g.add_system(execute_tool); },
        |g| { g.add_system(respond); },
    );

Node types: System, Decision, Switch, Parallel, Loop, Scope. Edge types: Sequential, Conditional, Parallel, LoopBack, Error, Timeout.

The graph’s full topology is inspectable, validated before execution, and restructured by rewiring edges. See the graph module for the full API.

§Plugins

Every capability is delivered through plugins registered at startup:

let mut server = Server::new();
server
    .add_plugins(DefaultPlugins::new().build())
    .add_plugins(ToolsPlugin)
    .add_plugins(SessionsPlugin::new(Arc::new(InMemoryStore::new())));

Plugins have a lifecycle: build()ready()update()cleanup(). Dependencies are declared and resolved automatically. See the system module for the Plugin trait and the plugins module for built-in plugin groups.

§Data Flow Patterns

Choosing the right parameter type is critical for correct data flow:

PatternUseAvoid
Step A’s result feeds step BOut<T> — A returns T, B declares Out<T>ResMut<SharedState> with Option fields
Immutable per-request inputRes<T> via ctx.insert(T) in setup closureResMut<WorkingState> with .input.clone()
Accumulated state (history, counters)ResMut<T> — local resourceOut<T> — outputs are per-system
Shared server-wide configRes<T> — global resourceResMut<T> — compile error on globals
Error context in handlerErrOut<CaughtError>Custom ResMut<LastError>

§Data Lifetimes

Data lives…Mechanism
Server lifetimeGlobalResource + Res<T>
Session lifetimeLocalResource inserted at session creation
Single turnLocalResource inserted in process_turn_with
Between two systemsReturn value + Out<T>
Error handler subgraphErrOut<CaughtError>

§Common Integration Patterns

GoalPatternEntry point
Run one-shot agentsessions.run_oneshot(&agent_type, |ctx| { ... })sessions
Multi-turn with cleanupsessions.scoped_session(&agent_type, |ctx| { ... })sessions
Execute agent from HTTPDeferredStateSessionsAPIHttpIOProviderapp
Register HTTP routesserver.api::<HttpRouter>().add_routes(router)app
Add tools for LLM#[tool] macro + ToolRegistrytools
Add model providerImplement LlmProvider + register via pluginmodels
Handle system errorsFallible system + error edge + ErrOut<CaughtError>graph
Schedule plugin updatestick_schedules() + server.tick::<S>()system

§Crate Organisation

ModuleCratePurpose
systempolaris_systemECS-inspired systems, resources, and plugins
graphpolaris_graphDirected-graph execution primitives
agentpolaris_agentAgent trait for reusable behavior patterns
toolspolaris_toolsTool framework for LLM-callable functions
modelspolaris_models / polaris_model_providersModel registry and provider implementations
pluginspolaris_core_pluginsCore infrastructure plugins (time, tracing, persistence)
sessionspolaris_sessionsSession management and orchestration
shellpolaris_shellShell command execution with permission model
apppolaris_appHTTP server runtime with plugin integration

§Exploration Map

If you want to find…Start here
System primitives, resources, and plugin lifecyclesystem
Graph nodes, edges, execution, hooks, and middlewaregraph
LLM providers and provider pluginsmodels
Core infrastructure plugins and observabilityplugins
Session lifecycle, persistence, and HTTP session routessessions
Feature-gated exports and which module owns themFeature Export Map

§Feature Flags

All features are opt-in (none enabled by default). Features that originate from a sub-crate and would otherwise be ambiguous at the top level are prefixed with the sub-crate’s short name (e.g. sessions-http). Features that are already unambiguous keep their original name (e.g. anthropic).

§Model Providers

FeatureExported itemFind it under
anthropicmodels::AnthropicPluginmodels
openaimodels::OpenAiPluginmodels
bedrockmodels::BedrockPluginmodels

§Observability

FeatureExported itemEffect
graph-tracingNo new public typeExtends plugins::TracingPlugin with graph-execution spans
models-tracingNo new public typeExtends plugins::TracingPlugin to decorate model providers
tools-tracingNo new public typeExtends plugins::TracingPlugin to decorate tools
otelplugins::OpenTelemetryPluginAdds OTLP export via the tracing subscriber

§Tokenization

FeatureExported itemEffect
tiktokenmodels::tokenizer::TiktokenCounter and models::tokenizer::EncodingFamilyEnables tiktoken-backed counting and models::TokenizerPlugin::default

§Sessions

FeatureExported itemFind it under
sessions-httpsessions::HttpPlugin and sessions::httpsessions

§Feature Coverage Map

Use this table when the question is “what does feature X expose, modify, or wire up at runtime?”

FeatureAdds public itemsAlso changesRuntime surface
anthropicmodels::anthropic, models::AnthropicPluginMakes the anthropic/... provider family available through models::ModelRegistry once registeredmodels::AnthropicPlugin registers the Anthropic provider
openaimodels::openai, models::OpenAiPluginMakes the openai/... provider family available through models::ModelRegistry once registeredmodels::OpenAiPlugin registers the OpenAI provider
bedrockmodels::bedrock, models::BedrockPluginMakes the bedrock/... provider family available through models::ModelRegistry once registeredmodels::BedrockPlugin registers the Bedrock provider
graph-tracingNo new public itemExtends plugins::TracingPlugin only; no separate GraphTracingPlugin existsplugins::TracingPlugin registers graph middleware through graph::MiddlewareAPI
models-tracingNo new public itemExtends plugins::TracingPlugin onlyplugins::TracingPlugin decorates the global models::ModelRegistry
tools-tracingNo new public itemExtends plugins::TracingPlugin onlyplugins::TracingPlugin decorates the global tools::ToolRegistry
otelplugins::OpenTelemetryPluginIntegrates with the existing plugins::TracingPlugin / plugins::TracingLayersApi surfaceplugins::OpenTelemetryPlugin pushes an OTLP export layer into the tracing subscriber
tiktokenmodels::tokenizer::TiktokenCounter, models::tokenizer::EncodingFamilyAdds Default for models::TokenizerPlugin and changes what models::TokenizerPlugin::default buildsmodels::TokenizerPlugin::default registers a global models::Tokenizer backed by models::tokenizer::TiktokenCounter
sessions-httpsessions::http, sessions::HttpPlugin, sessions::http::modelsAdds request/response model types and HTTP-facing session APIs under sessionssessions::HttpPlugin registers routes through app::HttpRouter and depends on app::AppPlugin + sessions::SessionsPlugin

Modules§

agent
Agent trait for defining reusable behavior patterns.
app
HTTP server runtime with plugin-based route composition.
graph
Directed-graph execution primitives for agent behavior.
models
Model registry and LLM provider implementations.
plugins
Core infrastructure plugins for the Polaris runtime.
prelude
Re-export all common types for easy access.
sessions
Session management and agent orchestration.
shell
Shell command execution with a layered permission model.
system
ECS-inspired systems, resources, plugins, and the server runtime.
tools
Tool framework for LLM-callable functions.