spin_factor_llm/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
mod host;
pub mod spin;

use std::collections::{HashMap, HashSet};
use std::sync::Arc;

use async_trait::async_trait;
use spin_factors::{
    ConfigureAppContext, Factor, PrepareContext, RuntimeFactors, SelfInstanceBuilder,
};
use spin_locked_app::MetadataKey;
use spin_world::v1::llm::{self as v1};
use spin_world::v2::llm::{self as v2};
use tokio::sync::Mutex;

pub const ALLOWED_MODELS_KEY: MetadataKey<Vec<String>> = MetadataKey::new("ai_models");

/// The factor for LLMs.
pub struct LlmFactor {
    default_engine_creator: Box<dyn LlmEngineCreator>,
}

impl LlmFactor {
    /// Creates a new LLM factor with the given default engine creator.
    ///
    /// The default engine creator is used to create the engine if no runtime configuration is provided.
    pub fn new<F: LlmEngineCreator + 'static>(default_engine_creator: F) -> Self {
        Self {
            default_engine_creator: Box::new(default_engine_creator),
        }
    }
}

impl Factor for LlmFactor {
    type RuntimeConfig = RuntimeConfig;
    type AppState = AppState;
    type InstanceBuilder = InstanceState;

    fn init<T: Send + 'static>(
        &mut self,
        mut ctx: spin_factors::InitContext<T, Self>,
    ) -> anyhow::Result<()> {
        ctx.link_bindings(spin_world::v1::llm::add_to_linker)?;
        ctx.link_bindings(spin_world::v2::llm::add_to_linker)?;
        Ok(())
    }

    fn configure_app<T: RuntimeFactors>(
        &self,
        mut ctx: ConfigureAppContext<T, Self>,
    ) -> anyhow::Result<Self::AppState> {
        let component_allowed_models = ctx
            .app()
            .components()
            .map(|component| {
                Ok((
                    component.id().to_string(),
                    component
                        .get_metadata(ALLOWED_MODELS_KEY)?
                        .unwrap_or_default()
                        .into_iter()
                        .collect::<HashSet<_>>()
                        .into(),
                ))
            })
            .collect::<anyhow::Result<_>>()?;
        let engine = ctx
            .take_runtime_config()
            .map(|c| c.engine)
            .unwrap_or_else(|| self.default_engine_creator.create());
        Ok(AppState {
            engine,
            component_allowed_models,
        })
    }

    fn prepare<T: RuntimeFactors>(
        &self,
        ctx: PrepareContext<T, Self>,
    ) -> anyhow::Result<Self::InstanceBuilder> {
        let allowed_models = ctx
            .app_state()
            .component_allowed_models
            .get(ctx.app_component().id())
            .cloned()
            .unwrap_or_default();
        let engine = ctx.app_state().engine.clone();

        Ok(InstanceState {
            engine,
            allowed_models,
        })
    }
}

/// The application state for the LLM factor.
pub struct AppState {
    engine: Arc<Mutex<dyn LlmEngine>>,
    component_allowed_models: HashMap<String, Arc<HashSet<String>>>,
}

/// The instance state for the LLM factor.
pub struct InstanceState {
    engine: Arc<Mutex<dyn LlmEngine>>,
    pub allowed_models: Arc<HashSet<String>>,
}

/// The runtime configuration for the LLM factor.
pub struct RuntimeConfig {
    engine: Arc<Mutex<dyn LlmEngine>>,
}

impl SelfInstanceBuilder for InstanceState {}

/// The interface for a language model engine.
#[async_trait]
pub trait LlmEngine: Send + Sync {
    async fn infer(
        &mut self,
        model: v1::InferencingModel,
        prompt: String,
        params: v2::InferencingParams,
    ) -> Result<v2::InferencingResult, v2::Error>;

    async fn generate_embeddings(
        &mut self,
        model: v2::EmbeddingModel,
        data: Vec<String>,
    ) -> Result<v2::EmbeddingsResult, v2::Error>;

    /// A human-readable summary of the given engine's configuration
    ///
    /// Example: "local model"
    fn summary(&self) -> Option<String> {
        None
    }
}

/// A creator for an LLM engine.
pub trait LlmEngineCreator: Send + Sync {
    fn create(&self) -> Arc<Mutex<dyn LlmEngine>>;
}

impl<F> LlmEngineCreator for F
where
    F: Fn() -> Arc<Mutex<dyn LlmEngine>> + Send + Sync,
{
    fn create(&self) -> Arc<Mutex<dyn LlmEngine>> {
        self()
    }
}