causa-provider 0.1.2

Causa — a minimal context kernel for Rust agents (facts, ports, adapters)
Documentation
//! Quickstart — one turn, one local tool, one real provider round-trip.
//!
//! This example lives in `causa-provider` (not `causa-runtime`) for one
//! reason: the dependency direction. The runtime must never depend on
//! the edge adapters it drives, so an example that wires *both* sides
//! belongs to the adapter crate — which dev-depends on the runtime for
//! exactly this kind of demonstration. In your own host, start with the
//! `causa` facade or compose the layer crates directly.
//!
//! ```text
//! ANTHROPIC_API_KEY=sk-ant-... cargo run --example quickstart -p causa-provider
//! ```
//!
//! The shape is the whole framework: fill the kernel's ports (a
//! `ModelGateway` adapter from `causa-provider`, a local `Tool`), hand
//! them to the execution stack, and drive one turn. The driver loops
//! model rounds and tool dispatch until the model ends the turn.

use async_trait::async_trait;
use causa_kernel::{
    CallControl, CancellationToken, Context, ContextBlock, GenerationOptions, ModelRef, Role, Tool,
    ToolCallContext, ToolDefinition, ToolOutput, ToolResultPayload, ToolResultStatus, TurnId,
};
use causa_provider::AnthropicMessagesGateway;
use causa_runtime::{
    ToolExecutor, ToolExecutorOptions, TurnResult, TurnRunOptions, TurnRunner, new_block_id,
};

use std::sync::Arc;

/// A local Rust tool the model may call — one `ToolDefinition` for the
/// surface, one `execute` for the effect.
struct WordCount;

#[async_trait]
impl Tool for WordCount {
    fn definition(&self) -> ToolDefinition {
        ToolDefinition::new(
            "word_count",
            "Count whitespace-separated words in a text.",
            serde_json::json!({
                "type": "object",
                "properties": { "text": { "type": "string" } },
                "required": ["text"]
            }),
        )
    }

    async fn execute(
        &self,
        ctx: &ToolCallContext,
        _control: &CallControl,
        _store: Option<&dyn causa_kernel::ArtifactStore>,
    ) -> ToolResultPayload {
        let text = ctx
            .input
            .arguments
            .get("text")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        let count = text.split_whitespace().count();
        ToolResultPayload::new(
            ctx.call_block_id,
            ToolResultStatus::Succeeded,
            ToolOutput::new(serde_json::json!({ "words": count })),
        )
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let api_key = std::env::var("ANTHROPIC_API_KEY")
        .map_err(|_| "set ANTHROPIC_API_KEY to run this example against the real API")?;

    // Ports out, driver in: the executor holds the tools, the gateway
    // adapter talks to the provider, the runner loops the turn.
    let executor = Arc::new(ToolExecutor::new(
        vec![Arc::new(WordCount)],
        ToolExecutorOptions::default(),
    )?);
    // Media: inject the host's asset table so fact-level
    // media references resolve to inline payloads at render time. The
    // table is prefetched before the turn; misses degrade to a
    // deterministic text placeholder.
    let asset_table: std::collections::HashMap<String, causa_provider::MediaPayload> =
        std::collections::HashMap::new();
    let gateway = Arc::new(
        AnthropicMessagesGateway::new(api_key)
            .with_media_resolver(std::sync::Arc::new(asset_table)),
    );
    let runner = TurnRunner::new(gateway, executor.clone());

    let context = Context::from_blocks(vec![ContextBlock::text(
        new_block_id(),
        Role::User,
        "How many words are in \"the quick brown fox jumps over the lazy dog\"? Use the word_count tool, then answer with just the number.",
    )])?;
    // Anthropic requires an output limit; the gateway sends no default.
    let options = TurnRunOptions::new(ModelRef::new("claude-sonnet-4-5"))
        .with_generation(GenerationOptions::default().with_max_tokens(1024));

    let outcome = runner
        .run(
            TurnId::new("quickstart"),
            context,
            options,
            CallControl::new(CancellationToken::new(), None),
        )
        .await;
    match outcome.result {
        TurnResult::Completed { final_output } => {
            println!("answer: {}", final_output.response.text());
        }
        TurnResult::Interrupted { cause } => {
            return Err(format!("turn interrupted: {cause:?}").into());
        }
    }
    println!("retained blocks: {}", outcome.context.blocks().len());
    Ok(())
}