xz-provider 0.5.0

LLM 服务提供者抽象层 — 统一的 LLM 服务提供者接口
Documentation
pub mod openai_chat;
pub use openai_chat::OpenAiChatAdapter;

/// Shared OpenAI wire encode/decode helpers (chat + responses).
pub(crate) mod openai_wire;

use std::fmt::Debug;

use serde::{Deserialize, Serialize};
use serde_json::Value;

pub mod openai_responses;

use crate::error::ProviderError;
use crate::types::{CompletionRequest, CompletionResponse, StreamEvent};

#[cfg(feature = "anthropic")]
pub mod anthropic;

/// Authentication method for a provider.
///
/// Represents the various ways providers authenticate API requests.
/// The [`ProtocolAdapter::build_auth_headers`] method converts this
/// into the appropriate HTTP headers.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum AuthMethod {
    /// No authentication required (e.g., local providers).
    None,
    /// Bearer token authentication (used by OpenAI, Anthropic, etc.).
    Bearer {
        /// The bearer token value (api key).
        token: String,
    },
    /// Custom API key header authentication.
    ApiKey {
        /// The HTTP header name for the API key (e.g., "x-api-key").
        header_name: String,
        /// The API key value.
        key: String,
    },
}

/// A protocol adapter translates between the unified request/response types
/// and a specific provider's API protocol.
///
/// This trait is object-safe so it can be used as `&dyn ProtocolAdapter`
/// or `Box<dyn ProtocolAdapter>`. That means:
/// - No async methods
/// - No generic type parameters
/// - No `impl Trait` return types
///
/// Each variant represents a different API protocol:
/// - OpenAI Chat Completions (`/v1/chat/completions`)
/// - OpenAI Responses (`/v1/responses`)
/// - Anthropic Messages (`/v1/messages`)
/// - Ollama (`/api/chat`)
///
/// # Examples
///
/// ```rust
/// use xz_provider::protocol::{ProtocolAdapter, AuthMethod};
/// use xz_provider::ProviderError;
///
/// # #[derive(Debug)]
/// # struct DummyAdapter;
/// # impl ProtocolAdapter for DummyAdapter {
/// #     fn endpoint_path(&self) -> &str { "/v1/test" }
/// #     fn build_request_body(&self, _: &xz_provider::CompletionRequest, _: bool) -> Result<serde_json::Value, ProviderError> {
/// #         Ok(serde_json::json!({}))
/// #     }
/// #     fn build_auth_headers(&self, _: &AuthMethod) -> Vec<(String, String)> { vec![] }
/// #     fn parse_response(&self, _: &serde_json::Value) -> Result<xz_provider::CompletionResponse, ProviderError> {
/// #         Err(ProviderError::Format("not implemented".to_owned()))
/// #     }
/// #     fn parse_sse_event(&self, _: &str) -> Result<Option<xz_provider::StreamEvent>, ProviderError> {
/// #         Ok(None)
/// #     }
/// #     fn protocol_name(&self) -> &str { "test" }
/// # }
/// let adapter: &dyn ProtocolAdapter = &DummyAdapter;
/// assert_eq!(adapter.protocol_name(), "test");
/// ```
pub trait ProtocolAdapter: Debug + Send + Sync {
    /// Returns the API endpoint path for this protocol (e.g., `/v1/chat/completions`).
    ///
    /// The caller appends this to the provider's base URL.
    fn endpoint_path(&self) -> &str;

    /// Builds the JSON request body for a completion request.
    ///
    /// When `stream` is `true`, the body should include the
    /// protocol-appropriate streaming flag (e.g., `"stream": true` for
    /// OpenAI, no change for Anthropic which uses SSE headers instead).
    fn build_request_body(
        &self,
        request: &CompletionRequest,
        stream: bool,
    ) -> Result<Value, ProviderError>;

    /// Converts an [`AuthMethod`] into the appropriate HTTP auth headers.
    ///
    /// For `AuthMethod::None`, returns an empty vector.
    /// For `AuthMethod::Bearer`, returns a single `Authorization: Bearer ...` header.
    /// For `AuthMethod::ApiKey`, returns a single header with the specified name and value.
    fn build_auth_headers(&self, auth: &AuthMethod) -> Vec<(String, String)>;

    /// Parses a complete (non-streaming) JSON response body into a
    /// [`CompletionResponse`].
    fn parse_response(&self, body: &Value) -> Result<CompletionResponse, ProviderError>;

    /// Parses the data portion of a single SSE event into a [`StreamEvent`].
    ///
    /// Returns `Ok(None)` when the event is ignorable (e.g., a heartbeat).
    /// The input `data` string is the content after the `data: ` prefix,
    /// already trimmed.
    fn parse_sse_event(&self, data: &str) -> Result<Option<StreamEvent>, ProviderError>;

    /// Returns the human-readable name of this protocol for logging and metrics.
    fn protocol_name(&self) -> &str;
}