causa-provider 0.0.3

Causa — a minimal context kernel for Rust agents (facts, ports, adapters)
Documentation
//! Protocol rendering, full-response parsing and authentication.

use causa_kernel::{ModelInvokeError, ModelOutput, ModelRequest};
use causa_protocol::translation::anthropic::{parse_anthropic_response, render_anthropic_messages};
use causa_protocol::translation::media::MediaSet;
use causa_protocol::translation::openai_chat::{
    parse_openai_chat_response, render_openai_chat_messages,
};
use causa_protocol::translation::openai_responses::{
    parse_openai_responses_output, render_openai_responses_input,
};
use causa_protocol::translation::render_options::{
    AnthropicRenderOptions, ChatRenderOptions, ResponsesRenderOptions,
};
use serde_json::Value;

/// Protocol-specific rendering, parsing, and auth decoration for a kernel gateway.
///
/// The per-protocol quirks (endpoint, path, header shape, render/parse)
/// are isolated here so the transport loop is written once. `media` is
/// the resolution table the gateway built from its injected resolver —
/// the config passes it through to the pure renderer.
pub trait KernelGatewayConfig: Clone + Send + Sync + std::fmt::Debug + Default {
    /// Wire protocol used by the pure streaming decoder.
    const PROTOCOL: causa_protocol::Protocol;
    /// Render a kernel request and its resolved media into a wire request body.
    /// Rejection prevents the gateway from sending an HTTP request.
    fn render(&self, request: &ModelRequest, media: &MediaSet) -> Result<Value, ModelInvokeError>;
    /// Parse a successful wire response into the kernel's model output.
    fn parse(&self, value: &Value) -> Result<ModelOutput, ModelInvokeError>;
    /// Add protocol-specific authentication and version headers to a request.
    fn decorate_request(
        &self,
        builder: reqwest::RequestBuilder,
        api_key: &str,
    ) -> reqwest::RequestBuilder;
    /// Full endpoint URL used unless the host overrides it.
    const DEFAULT_ENDPOINT: &'static str;
    /// Protocol path appended by [`crate::KernelHttpGateway::with_base_url`].
    /// It has no version segment; the base URL supplies one.
    const PATH: &'static str;
    /// Provider label used in transport errors and tracing spans.
    const PROVIDER: &'static str;
}

/// Anthropic Messages gateway config: the `anthropic-version` header, the
/// render options of that protocol, and the extra `anthropic-beta` values.
/// Stored in `config: C` so the generic struct holds all protocol state
/// uniformly. The setters live on [`crate::KernelHttpGateway`].
#[derive(Debug, Clone)]
pub struct AnthropicGatewayConfig {
    pub(super) anthropic_version: String,
    pub(super) render_options: AnthropicRenderOptions,
    /// Extra `anthropic-beta` values, sent as one comma-separated header.
    pub(super) beta: Vec<String>,
}

impl Default for AnthropicGatewayConfig {
    fn default() -> Self {
        Self {
            anthropic_version: "2023-06-01".into(),
            render_options: AnthropicRenderOptions::default(),
            beta: Vec::new(),
        }
    }
}

impl KernelGatewayConfig for AnthropicGatewayConfig {
    const PROTOCOL: causa_protocol::Protocol = causa_protocol::Protocol::AnthropicMessages;
    fn render(&self, request: &ModelRequest, media: &MediaSet) -> Result<Value, ModelInvokeError> {
        render_anthropic_messages(
            &request.frame,
            media,
            &request.tool_surface,
            &request.generation,
            &request.model,
            request.cache,
            &self.render_options,
        )
    }

    fn parse(&self, value: &Value) -> Result<ModelOutput, ModelInvokeError> {
        parse_anthropic_response(value)
    }

    fn decorate_request(
        &self,
        builder: reqwest::RequestBuilder,
        api_key: &str,
    ) -> reqwest::RequestBuilder {
        let builder = builder
            .header("x-api-key", api_key)
            .header("anthropic-version", &self.anthropic_version);
        if self.beta.is_empty() {
            builder
        } else {
            // One comma-separated header, exactly the values the host listed;
            // no model table decides headers.
            builder.header("anthropic-beta", self.beta.join(","))
        }
    }

    const DEFAULT_ENDPOINT: &'static str = "https://api.anthropic.com/v1/messages";
    const PATH: &'static str = "/messages";
    const PROVIDER: &'static str = "anthropic";
}

/// OpenAI Chat Completions gateway config: the Chat-only render options.
#[derive(Debug, Clone, Default)]
pub struct OpenAiChatGatewayConfig {
    pub(super) render_options: ChatRenderOptions,
}

impl KernelGatewayConfig for OpenAiChatGatewayConfig {
    const PROTOCOL: causa_protocol::Protocol = causa_protocol::Protocol::OpenAiChatCompletions;
    fn render(&self, request: &ModelRequest, media: &MediaSet) -> Result<Value, ModelInvokeError> {
        render_openai_chat_messages(
            &request.frame,
            media,
            &request.tool_surface,
            &request.generation,
            &request.model,
            request.cache,
            &self.render_options,
        )
    }

    fn parse(&self, value: &Value) -> Result<ModelOutput, ModelInvokeError> {
        parse_openai_chat_response(value)
    }

    fn decorate_request(
        &self,
        builder: reqwest::RequestBuilder,
        api_key: &str,
    ) -> reqwest::RequestBuilder {
        builder.bearer_auth(api_key)
    }

    const DEFAULT_ENDPOINT: &'static str = "https://api.openai.com/v1/chat/completions";
    const PATH: &'static str = "/chat/completions";
    const PROVIDER: &'static str = "openai";
}

/// OpenAI Responses gateway config: the Responses-only render options.
#[derive(Debug, Clone, Default)]
pub struct OpenAiResponsesGatewayConfig {
    pub(super) render_options: ResponsesRenderOptions,
}

impl KernelGatewayConfig for OpenAiResponsesGatewayConfig {
    const PROTOCOL: causa_protocol::Protocol = causa_protocol::Protocol::OpenAiResponses;
    fn render(&self, request: &ModelRequest, media: &MediaSet) -> Result<Value, ModelInvokeError> {
        render_openai_responses_input(
            &request.frame,
            media,
            &request.tool_surface,
            &request.generation,
            &request.model,
            request.cache,
            &self.render_options,
        )
    }

    fn parse(&self, value: &Value) -> Result<ModelOutput, ModelInvokeError> {
        parse_openai_responses_output(value)
    }

    fn decorate_request(
        &self,
        builder: reqwest::RequestBuilder,
        api_key: &str,
    ) -> reqwest::RequestBuilder {
        builder.bearer_auth(api_key)
    }

    const DEFAULT_ENDPOINT: &'static str = "https://api.openai.com/v1/responses";
    const PATH: &'static str = "/responses";
    const PROVIDER: &'static str = "openai";
}