Skip to main content

larastvel_core/ai/
provider.rs

1use std::fmt::Debug;
2use std::pin::Pin;
3
4use async_trait::async_trait;
5use futures_util::Stream;
6
7use super::image::{ImageOptions, ImageResponse};
8use super::media::AudioOptions;
9use super::messages::{ChatOptions, ChatResponse, EmbeddingOptions, Message};
10use super::moderation::ModerationResponse;
11use super::rerank::{RerankOptions, RerankResponse};
12
13/// An error raised by an AI provider.
14#[derive(Debug, thiserror::Error)]
15pub enum ProviderError {
16    #[error("AI provider error: {0}")]
17    Request(String),
18    #[error("AI provider returned HTTP {0}: {1}")]
19    Status(u16, String),
20    #[error("AI provider returned an invalid response: {0}")]
21    InvalidResponse(String),
22    #[error(
23        "No API key configured. Set `ai.api_key` in config/ai.toml or the {0} environment variable."
24    )]
25    MissingApiKey(String),
26    #[error("No AI provider configured. Set `ai.provider` in config/ai.toml.")]
27    NoProvider,
28    #[error("Unsupported AI provider: {0}")]
29    UnsupportedProvider(String),
30    #[error("The configured AI provider does not support {0}")]
31    Unsupported(String),
32}
33
34/// A stream of incremental text chunks from a streaming chat completion.
35pub type ChatStream = Pin<Box<dyn Stream<Item = Result<String, ProviderError>> + Send>>;
36
37/// A unified AI provider, mirroring the Laravel AI SDK's provider
38/// abstraction. Providers implement chat completions (text and streaming)
39/// and embeddings; the framework keeps a consistent interface regardless of
40/// the underlying vendor.
41#[async_trait]
42pub trait AiProvider: Send + Sync + Debug {
43    /// The provider's name (e.g. `openai`, `anthropic`, `fake`).
44    fn name(&self) -> &str;
45
46    /// Complete a chat conversation.
47    async fn chat(
48        &self,
49        messages: &[Message],
50        options: &ChatOptions,
51    ) -> Result<ChatResponse, ProviderError>;
52
53    /// Stream a chat completion, yielding incremental text chunks.
54    async fn chat_stream(
55        &self,
56        messages: &[Message],
57        options: &ChatOptions,
58    ) -> Result<ChatStream, ProviderError>;
59
60    /// Embed a single text input into a vector.
61    async fn embed(
62        &self,
63        input: &str,
64        options: &EmbeddingOptions,
65    ) -> Result<Vec<f32>, ProviderError>;
66
67    /// Embed multiple text inputs into vectors.
68    async fn embed_many(
69        &self,
70        inputs: &[String],
71        options: &EmbeddingOptions,
72    ) -> Result<Vec<Vec<f32>>, ProviderError>;
73
74    /// Generate an image from a text prompt. Defaults to an "unsupported"
75    /// error so providers without image support stay valid.
76    async fn image_create(
77        &self,
78        _prompt: &str,
79        _options: &ImageOptions,
80    ) -> Result<ImageResponse, ProviderError> {
81        Err(ProviderError::Unsupported("image generation".into()))
82    }
83
84    /// Edit an image with a text prompt. Defaults to "unsupported".
85    async fn image_edit(
86        &self,
87        _image: &super::media::Media,
88        _prompt: &str,
89        _options: &ImageOptions,
90    ) -> Result<ImageResponse, ProviderError> {
91        Err(ProviderError::Unsupported("image editing".into()))
92    }
93
94    /// Create a variation of an image. Defaults to "unsupported".
95    async fn image_variation(
96        &self,
97        _image: &super::media::Media,
98        _options: &ImageOptions,
99    ) -> Result<ImageResponse, ProviderError> {
100        Err(ProviderError::Unsupported("image variations".into()))
101    }
102
103    /// Synthesize speech from text, returning audio bytes. Defaults to
104    /// "unsupported".
105    async fn tts(&self, _text: &str, _options: &AudioOptions) -> Result<Vec<u8>, ProviderError> {
106        Err(ProviderError::Unsupported("text-to-speech".into()))
107    }
108
109    /// Transcribe speech to text. Defaults to "unsupported".
110    async fn stt(
111        &self,
112        _audio: &super::media::Media,
113        _options: &AudioOptions,
114    ) -> Result<String, ProviderError> {
115        Err(ProviderError::Unsupported("speech-to-text".into()))
116    }
117
118    /// Moderate content, flagging policy violations. Defaults to
119    /// "unsupported".
120    async fn moderate(&self, _content: &str) -> Result<ModerationResponse, ProviderError> {
121        Err(ProviderError::Unsupported("moderation".into()))
122    }
123
124    /// Rerank documents by relevance to a query. Defaults to
125    /// "unsupported".
126    async fn rerank(
127        &self,
128        _query: &str,
129        _documents: &[String],
130        _options: &RerankOptions,
131    ) -> Result<RerankResponse, ProviderError> {
132        Err(ProviderError::Unsupported("reranking".into()))
133    }
134}