YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
Llm api (#438)
Ezra Ellettef1c717f91a42
diff --git a/screenpipe-app-tauri/bun.lockb b/screenpipe-app-tauri/bun.lockbindex 72e259cf2..41776962d 100755Binary files a/screenpipe-app-tauri/bun.lockb and b/screenpipe-app-tauri/bun.lockb differdiff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.tomlindex ba20352e2..d0c0ee426 100644--- a/screenpipe-app-tauri/src-tauri/Cargo.toml+++ b/screenpipe-app-tauri/src-tauri/Cargo.toml@@ -74,7 +74,6 @@ axum = "0.6.0" # or your current versionserde = "1.0.160"-dirs = "5.0.1"@@ -89,6 +88,7 @@ tauri-plugin-updater = "2.0.0"cudart = []metal = []mkl = []+llm = []default = ["custom-protocol"]# DO NOT REMOVE!!diff --git a/screenpipe-core/Cargo.toml b/screenpipe-core/Cargo.tomlindex 02e5287f6..3d6ff7e24 100644--- a/screenpipe-core/Cargo.toml+++ b/screenpipe-core/Cargo.toml@@ -8,6 +8,7 @@ license = { workspace = true }edition = { workspace = true }[dependencies]+serde = { version = "1.0", features = ["derive"] }serde_json = "1.0"which = "6.0.1"log = "0.4.17"diff --git a/screenpipe-core/examples/llama.rs b/screenpipe-core/examples/llama.rsindex c9a5d47cc..f5363e66b 100644--- a/screenpipe-core/examples/llama.rs+++ b/screenpipe-core/examples/llama.rs@@ -1,14 +1,26 @@use anyhow::Result;-#[cfg(feature = "llm")]-use screenpipe_core::llama::LlamaInitConfig;-#[cfg(feature = "llm")]-use screenpipe_core::llama_stream_text;+#[cfg(feature = "llm")]fn main() -> Result<()> {- #[cfg(feature = "llm")]- llama_stream_text(LlamaInitConfig::default(), |text| {- println!("{}", text);- Ok(())+ use screenpipe_core::LLM;++ let llm = LLM::new(screenpipe_core::ModelName::Llama)?;++ let res = llm.chat(screenpipe_core::ChatRequest {+ messages: vec![screenpipe_core::ChatMessage {+ role: "user".to_string(),+ content: "What is the meaning of life?".to_string(),+ }],+ temperature: None,+ top_k: None,+ top_p: None,+ max_completion_tokens: None,+ seed: None,+ stream: false,})?;++ println!("{:?}", res.choices[0].message.content);++ println!("{:?}", res.usage.tokens_per_second);Ok(())}diff --git a/screenpipe-core/src/llama.rs b/screenpipe-core/src/llama.rsindex a6c8e90c4..b7e5e0ae0 100644--- a/screenpipe-core/src/llama.rs+++ b/screenpipe-core/src/llama.rs@@ -1,42 +1,50 @@#[cfg(feature = "llm")]mod llm_module {-use anyhow::{Error as E, Result};+ use std::path::PathBuf;use candle::{DType, Device, Tensor};use candle_nn::VarBuilder;use candle_transformers::generation::{LogitsProcessor, Sampling};- use hf_hub::{- api::sync::{Api, ApiBuilder},- Repo, RepoType,- };+ use hf_hub::{Repo, RepoType};use candle_transformers::models::llama as model;- use model::{Llama, LlamaConfig};+ use log::debug;+ use model::LlamaConfig;use tokenizers::Tokenizer;- use crate::{hub_load_safetensors, TokenOutputStream};+ use crate::{+ ChatMessage, ChatRequest, ChatResponse, ChatResponseChoice, ChatResponseUsage, Model,+ TokenOutputStream,+ };const EOS_TOKEN: &str = "</s>";- const DEFAULT_PROMPT: &str = "My favorite theorem is ";#[derive(Clone, Debug, Copy, PartialEq, Eq)]enum Which {- V1,- V2,- V3,- V31,- V3Instruct,- V31Instruct,- V32_1b,V32_1bInstruct,- V32_3b,- V32_3bInstruct,- Solar10_7B,- TinyLlama1_1BChat,}- #[derive(Debug)]+ impl Which {+ fn model_id(&self) -> String {+ match self {+ // Which::V1 => "Narsil/amall-7b".to_string(),+ // Which::V2 => "meta-llama/Llama-2-7b-hf".to_string(),+ // Which::V3 => "meta-llama/Meta-Llama-3-8B".to_string(),+ // Which::V3Instruct => "meta-llama/Meta-Llama-3-8B-Instruct".to_string(),+ // Which::V31 => "meta-llama/Meta-Llama-3.1-8B".to_string(),+ // Which::V31Instruct => "meta-llama/Meta-Llama-3.1-8B-Instruct".to_string(),+ // Which::V32_1b => "meta-llama/Llama-3.2-1B".to_string(),+ Which::V32_1bInstruct => "meta-llama/Llama-3.2-1B-Instruct".to_string(),+ // Which::V32_3b => "meta-llama/Llama-3.2-3B".to_string(),+ // Which::V32_3bInstruct => "meta-llama/Llama-3.2-3B-Instruct".to_string(),+ // Which::Solar10_7B => "upstage/SOLAR-10.7B-v1.0".to_string(),+ // Which::TinyLlama1_1BChat => "TinyLlama/TinyLlama-1.1B-Chat-v1.0".to_string(),+ }+ }+ }++ #[derive(Debug, Clone)]pub struct LlamaInitConfig {/// The temperature used to generate samples.temperature: f64,@@ -53,18 +61,8 @@ mod llm_module {/// The length of the sample to generate (in tokens).sample_len: usize,- /// Disable the key-value cache.- no_kv_cache: bool,-- /// The initial prompt.- prompt: Option<String>,-/// Use different dtype than f16- dtype: Option<String>,-- model_id: Option<String>,-- revision: Option<String>,+ dtype: DType,/// The model size to use.which: Which,@@ -82,168 +80,217 @@ mod llm_module {fn default() -> Self {Self {use_flash_attn: false,- prompt: None,temperature: 0.8,top_p: None,top_k: None,seed: 299792458,- sample_len: 10000,- which: Which::V32_3bInstruct,- model_id: None,- revision: None,+ sample_len: 1000,+ which: Which::V32_1bInstruct,repeat_penalty: 1.1,- repeat_last_n: 128,- no_kv_cache: false,- dtype: None,+ repeat_last_n: 64,+ dtype: DType::F16,}}}- pub fn llama_stream_text<F>(args: LlamaInitConfig, mut callback: F) -> Result<()>- where- F: FnMut(String) -> Result<()>,- {- let device = Device::new_metal(0).unwrap_or(Device::new_cuda(0).unwrap_or(Device::Cpu));-- let dtype = match args.dtype.as_deref() {- Some("f16") => DType::F16,- Some("bf16") => DType::BF16,- Some("f32") => DType::F32,- Some(dtype) => anyhow::bail!("Unsupported dtype {dtype}"),- None => DType::F16,- };- let (llama, tokenizer_filename, mut cache, config) = {- let api = Api::new()?;- let model_id = args.model_id.unwrap_or_else(|| match args.which {- Which::V1 => "Narsil/amall-7b".to_string(),- Which::V2 => "meta-llama/Llama-2-7b-hf".to_string(),- Which::V3 => "meta-llama/Meta-Llama-3-8B".to_string(),- Which::V3Instruct => "meta-llama/Meta-Llama-3-8B-Instruct".to_string(),- Which::V31 => "meta-llama/Meta-Llama-3.1-8B".to_string(),- Which::V31Instruct => "meta-llama/Meta-Llama-3.1-8B-Instruct".to_string(),- Which::V32_1b => "meta-llama/Llama-3.2-1B".to_string(),- Which::V32_1bInstruct => "meta-llama/Llama-3.2-1B-Instruct".to_string(),- Which::V32_3b => "meta-llama/Llama-3.2-3B".to_string(),- Which::V32_3bInstruct => "meta-llama/Llama-3.2-3B-Instruct".to_string(),- Which::Solar10_7B => "upstage/SOLAR-10.7B-v1.0".to_string(),- Which::TinyLlama1_1BChat => "TinyLlama/TinyLlama-1.1B-Chat-v1.0".to_string(),- });- println!("loading the model weights from {model_id}");- let revision = args.revision.unwrap_or("main".to_string());- let api = api.repo(Repo::with_revision(model_id, RepoType::Model, revision));-- let tokenizer_filename = api.get("tokenizer.json")?;- let config_filename = api.get("config.json")?;+ pub struct Llama {+ llama_config: candle_transformers::models::llama::Config,+ // device: Device,+ filenames: Vec<PathBuf>,+ tokenizer: Tokenizer,+ // llama: model::Llama,+ eos_token_id: Option<model::LlamaEosToks>,+ config: LlamaInitConfig,+ }++ impl Llama {+ pub fn new() -> Result<Self> {+ // let device = Device::new_metal(0).unwrap_or(Device::new_cuda(0).unwrap_or(Device::Cpu));+ let init_config = LlamaInitConfig::default();+ let api = hf_hub::api::sync::Api::new()?;++ let hf_api = api.repo(Repo::with_revision(+ init_config.which.model_id(),+ RepoType::Model,+ "main".to_string(),+ ));++ let tokenizer_filename = hf_api.get("tokenizer.json")?;+ let config_filename = hf_api.get("config.json")?;let config: LlamaConfig = serde_json::from_slice(&std::fs::read(config_filename)?)?;- let config = config.into_config(args.use_flash_attn);-- let filenames = match args.which {- Which::V1- | Which::V2- | Which::V3- | Which::V3Instruct- | Which::V31- | Which::V31Instruct- | Which::V32_3b- | Which::V32_3bInstruct- | Which::Solar10_7B => hub_load_safetensors(&api, "model.safetensors.index.json")?,- Which::V32_1b | Which::V32_1bInstruct | Which::TinyLlama1_1BChat => {- vec![api.get("model.safetensors")?]- }- };- let cache = model::Cache::new(!args.no_kv_cache, dtype, &config, &device)?;-- let vb = unsafe { VarBuilder::from_mmaped_safetensors(&filenames, dtype, &device)? };- (Llama::load(vb, &config)?, tokenizer_filename, cache, config)- };- let tokenizer = Tokenizer::from_file(tokenizer_filename).map_err(E::msg)?;- let eos_token_id = config.eos_token_id.or_else(|| {- tokenizer+ let llama_config = config.into_config(init_config.use_flash_attn);++ let filenames = vec![hf_api.get("model.safetensors")?];+ // let vb = unsafe {+ // VarBuilder::from_mmaped_safetensors(&filenames, init_config.dtype, &device)?+ // };++ let tokenizer = Tokenizer::from_file(tokenizer_filename).map_err(E::msg)?;++ // let llama = model::Llama::load(vb, &llama_config)?;++ let eos_token_id = tokenizer.token_to_id(EOS_TOKEN)- .map(model::LlamaEosToks::Single)- });- let prompt = args.prompt.as_ref().map_or(DEFAULT_PROMPT, |p| p.as_str());- let mut tokens = tokenizer- .encode(prompt, true)- .map_err(E::msg)?- .get_ids()- .to_vec();- let mut tokenizer = TokenOutputStream::new(tokenizer);-- println!("starting the inference loop");- print!("{prompt}");- let mut logits_processor = {- let temperature = args.temperature;+ .map(model::LlamaEosToks::Single);+ Ok(Self {+ llama_config,+ // device,+ filenames,+ eos_token_id,+ tokenizer,+ // llama,+ config: init_config,+ })+ }++ // TODO Implement+ pub fn llama_stream_text(&self) -> Result<()> {+ Ok(())+ }+ }++ impl Model for Llama {+ fn chat(&self, request: ChatRequest) -> Result<ChatResponse> {+ let device = Device::new_metal(0).unwrap_or(Device::new_cuda(0).unwrap_or(Device::Cpu));++ let vb = unsafe {+ VarBuilder::from_mmaped_safetensors(+ &self.filenames.clone(),+ self.config.dtype,+ &device,+ )?+ };++ let llama = model::Llama::load(vb, &self.llama_config)?;++ let sample_len = request+ .max_completion_tokens+ .unwrap_or(self.config.sample_len);+ let prompt = request+ .messages+ .iter()+ .map(|m| m.content.as_str())+ .collect::<Vec<&str>>()+ .join("\n\n");+ let mut cache =+ model::Cache::new(true, self.config.dtype, &self.llama_config, &device)?;++ let temperature = request.temperature.unwrap_or(self.config.temperature);+ let top_k = request.top_k.or(self.config.top_k);+ let top_p = request.top_p.or(self.config.top_p);+ let seed = request.seed.unwrap_or(self.config.seed);let sampling = if temperature <= 0. {Sampling::ArgMax} else {- match (args.top_k, args.top_p) {+ match (top_k, top_p) {(None, None) => Sampling::All { temperature },(Some(k), None) => Sampling::TopK { k, temperature },(None, Some(p)) => Sampling::TopP { p, temperature },(Some(k), Some(p)) => Sampling::TopKThenTopP { k, p, temperature },}};- LogitsProcessor::from_sampling(args.seed, sampling)- };-- let mut start_gen = std::time::Instant::now();- let mut index_pos = 0;- let mut token_generated = 0;- for index in 0..args.sample_len {- let (context_size, context_index) = if cache.use_kv_cache && index > 0 {- (1, index_pos)- } else {- (tokens.len(), 0)- };- if index == 1 {- start_gen = std::time::Instant::now()- }- let ctxt = &tokens[tokens.len().saturating_sub(context_size)..];- let input = Tensor::new(ctxt, &device)?.unsqueeze(0)?;- let logits = llama.forward(&input, context_index, &mut cache)?;- let logits = logits.squeeze(0)?;- let logits = if args.repeat_penalty == 1. {- logits- } else {- let start_at = tokens.len().saturating_sub(args.repeat_last_n);- candle_transformers::utils::apply_repeat_penalty(- &logits,- args.repeat_penalty,- &tokens[start_at..],- )?- };- index_pos += ctxt.len();+ let mut logits_processor = LogitsProcessor::from_sampling(seed, sampling);++ let prompt = prompt.as_str();+ let mut tokens = self+ .tokenizer+ .encode(prompt, true)+ .map_err(E::msg)?+ .get_ids()+ .to_vec();++ let prompt_tokens = tokens.len();++ let mut tokenizer = TokenOutputStream::new(self.tokenizer.clone());++ let mut output = String::new();+ let mut start_gen = std::time::Instant::now();++ let mut index_pos = 0;+ let mut token_generated = 0;- let next_token = logits_processor.sample(&logits)?;- token_generated += 1;- tokens.push(next_token);+ for index in 0..sample_len {+ let (context_size, context_index) = if cache.use_kv_cache && index > 0 {+ (1, index_pos)+ } else {+ (tokens.len(), 0)+ };+ if index == 1 {+ start_gen = std::time::Instant::now()+ }+ let ctxt = &tokens[tokens.len().saturating_sub(context_size)..];+ let input = Tensor::new(ctxt, &device)?.unsqueeze(0)?;+ let logits = llama.forward(&input, context_index, &mut cache)?;+ let logits = logits.squeeze(0)?;+ let logits = if self.config.repeat_penalty == 1. {+ logits+ } else {+ let start_at = tokens.len().saturating_sub(self.config.repeat_last_n);+ candle_transformers::utils::apply_repeat_penalty(+ &logits,+ self.config.repeat_penalty,+ &tokens[start_at..],+ )?+ };+ index_pos += ctxt.len();++ let next_token = logits_processor.sample(&logits)?;+ token_generated += 1;+ tokens.push(next_token);- match eos_token_id {- Some(model::LlamaEosToks::Single(eos_tok_id)) if next_token == eos_tok_id => {- break;+ // match eos_token_id {+ match self.eos_token_id {+ Some(model::LlamaEosToks::Single(eos_tok_id)) if next_token == eos_tok_id => {+ break;+ }+ Some(model::LlamaEosToks::Multiple(ref eos_ids))+ if eos_ids.contains(&next_token) =>+ {+ break;+ }+ _ => (),}- Some(model::LlamaEosToks::Multiple(ref eos_ids))- if eos_ids.contains(&next_token) =>- {- break;+ if let Some(t) = tokenizer.next_token(next_token)? {+ output.push_str(&t);}- _ => (),}- if let Some(t) = tokenizer.next_token(next_token)? {- print!("{t}");+ if let Some(rest) = tokenizer.decode_rest().map_err(E::msg)? {+ output.push_str(&rest);}+ let dt = start_gen.elapsed();+ tokenizer.clear();++ let tokens_per_second = (token_generated - 1) as f64 / dt.as_secs_f64();++ debug!(+ "Llama: {} tokens generated ({} token/s)",+ token_generated, tokens_per_second+ );++ Ok(ChatResponse {+ id: "123".to_string(),+ object: "chat.completion".to_string(),+ created: 1,+ model: "llama3.2-1B-Instruct".to_string(),+ system_fingerprint: "".to_string(),+ choices: vec![ChatResponseChoice {+ index: 0,+ message: ChatMessage {+ role: "assistant".to_string(),+ content: output,+ },+ logprobs: None,+ finish_reason: "stop".to_string(),+ }],+ usage: ChatResponseUsage {+ prompt_tokens: prompt_tokens as i64,+ completion_tokens: token_generated,+ total_tokens: token_generated,+ completion_tokens_details: serde_json::Value::Null,+ tokens_per_second: tokens_per_second,+ },+ })}- if let Some(rest) = tokenizer.decode_rest().map_err(E::msg)? {- print!("{rest}");- }- let dt = start_gen.elapsed();- println!(- "\n\n{} tokens generated ({} token/s)\n",- token_generated,- (token_generated - 1) as f64 / dt.as_secs_f64(),- );- Ok(())}}// Optionally, you can re-export the module contents if neededdiff --git a/screenpipe-core/src/llm.rs b/screenpipe-core/src/llm.rsindex 5e459d438..54df0fa98 100644--- a/screenpipe-core/src/llm.rs+++ b/screenpipe-core/src/llm.rs@@ -1,5 +1,80 @@#[cfg(feature = "llm")]mod llm_module {++ use serde::{Deserialize, Serialize};++ use crate::Llama;+ #[derive(Deserialize, Serialize, Clone, Debug)]+ pub struct ChatMessage {+ pub role: String,+ pub content: String,+ }++ #[derive(Deserialize, Serialize)]+ pub struct ChatResponseChoice {+ pub index: i64,+ pub message: ChatMessage,+ pub logprobs: Option<serde_json::Value>,+ pub finish_reason: String,+ }++ #[derive(Deserialize, Serialize)]+ pub struct ChatResponseUsage {+ pub prompt_tokens: i64,+ pub completion_tokens: i64,+ pub total_tokens: i64,+ pub completion_tokens_details: serde_json::Value,+ pub tokens_per_second: f64,+ }++ #[derive(Serialize, Deserialize)]+ pub struct ChatResponse {+ pub id: String,+ pub object: String,+ pub created: i64,+ pub model: String,+ pub system_fingerprint: String,+ pub choices: Vec<ChatResponseChoice>,+ pub usage: ChatResponseUsage,+ }++ #[derive(Deserialize, Clone, Debug)]+ pub struct ChatRequest {+ pub messages: Vec<ChatMessage>,+ #[serde(default)]+ pub stream: bool,+ pub max_completion_tokens: Option<usize>,+ pub temperature: Option<f64>,+ pub top_p: Option<f64>,+ pub top_k: Option<usize>,+ pub seed: Option<u64>,+ }++ pub trait Model {+ fn chat(&self, request: ChatRequest) -> anyhow::Result<ChatResponse>;+ }++ pub struct LLM {+ model: Llama,+ }++ pub enum ModelName {+ Llama,+ }++ impl LLM {+ pub fn new(model_name: ModelName) -> anyhow::Result<Self> {+ let model = match model_name {+ ModelName::Llama => Llama::new()?,+ };++ Ok(Self { model })+ }++ pub fn chat(&self, request: ChatRequest) -> anyhow::Result<ChatResponse> {+ self.model.chat(request)+ }+ }/// This is a wrapper around a tokenizer to ensure that tokens can be returned to the user in a/// streaming way rather than having to wait for the full decoding.pub struct TokenOutputStream {diff --git a/screenpipe-server/Cargo.toml b/screenpipe-server/Cargo.tomlindex e6886767b..262eca51a 100644--- a/screenpipe-server/Cargo.toml+++ b/screenpipe-server/Cargo.toml@@ -24,7 +24,12 @@ image = { workspace = true }chrono = { version = "0.4.31", features = ["serde"] }# Database-sqlx = { version = "0.7", features = ["sqlite", "runtime-tokio-native-tls", "chrono", "migrate"] }+sqlx = { version = "0.7", features = [+ "sqlite",+ "runtime-tokio-native-tls",+ "chrono",+ "migrate",+] }# Local Embeddings + STTcandle = { workspace = true }@@ -108,11 +113,8 @@ harness = falsedefault = ["pipes"]metal = ["candle/metal", "candle-nn/metal", "candle-transformers/metal"]cuda = ["candle/cuda", "candle-nn/cuda", "candle-transformers/cuda"]-pipes = [- "screenpipe-core/pipes",- "tempfile",- "url",-]+pipes = ["screenpipe-core/pipes", "tempfile", "url"]+llm = ["screenpipe-core/llm"][[bin]]@@ -121,4 +123,4 @@ path = "src/bin/screenpipe-server.rs"[package.metadata.cargo-machete]-ignored = ["tempfile", "url"]\ No newline at end of file+ignored = ["tempfile", "url"]diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rsindex faaf9f40f..43fa69aeb 100644--- a/screenpipe-server/src/bin/screenpipe-server.rs+++ b/screenpipe-server/src/bin/screenpipe-server.rs@@ -64,6 +64,7 @@ fn get_base_dir(custom_path: Option<String>) -> anyhow::Result<PathBuf> {#[tokio::main]async fn main() -> anyhow::Result<()> {+ debug!("starting screenpipe server");let cli = Cli::parse();let local_data_dir = get_base_dir(cli.data_dir)?;let local_data_dir_clone = local_data_dir.clone();@@ -347,6 +348,19 @@ async fn main() -> anyhow::Result<()> {};let local_data_dir_clone_2 = local_data_dir_clone.clone();+ #[cfg(feature = "llm")]+ debug!("LLM initializing");++ #[cfg(feature = "llm")]+ let llm = {+ match cli.enable_llm {+ true => Some(screenpipe_core::LLM::new(screenpipe_core::ModelName::Llama)?),+ false => None,+ }+ };++ #[cfg(feature = "llm")]+ debug!("LLM initialized");let api_plugin = |req: &axum::http::Request<axum::body::Body>| {if req.uri().path() == "/search" {@@ -362,6 +376,11 @@ async fn main() -> anyhow::Result<()> {pipe_manager.clone(),cli.disable_vision,cli.disable_audio,+ #[cfg(feature = "llm")]+ cli.enable_llm,+ #[cfg(feature = "llm")]+ llm,+);let mut pipe_futures = FuturesUnordered::new();@@ -417,6 +436,7 @@ async fn main() -> anyhow::Result<()> {);println!("│ debug mode │ {:<34} │", cli.debug);println!("│ telemetry │ {:<34} │", !cli.disable_telemetry);+ println!("│ local llm │ {:<34} │", cli.enable_llm);println!("│ use pii removal │ {:<34} │", cli.use_pii_removal);println!(diff --git a/screenpipe-server/src/cli.rs b/screenpipe-server/src/cli.rsindex 21a3288c5..d7c783aa8 100644--- a/screenpipe-server/src/cli.rs+++ b/screenpipe-server/src/cli.rs@@ -216,6 +216,10 @@ pub struct Cli {#[arg(long, default_value_t = false)]pub disable_telemetry: bool,+ /// Enable Local LLM API+ #[arg(long, default_value_t = false)]+ pub enable_llm: bool,+#[command(subcommand)]pub command: Option<Command>,diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rsindex 413d735e5..d0af8d943 100644--- a/screenpipe-server/src/server.rs+++ b/screenpipe-server/src/server.rs@@ -7,6 +7,10 @@ use axum::{};use crossbeam::queue::SegQueue;use futures::future::{try_join, try_join_all};+#[cfg(feature = "llm")]+use screenpipe_core::LLM;+#[cfg(feature = "llm")]+use screenpipe_core::{ChatRequest, ChatResponse};use screenpipe_vision::monitor::list_monitors;use crate::{@@ -46,6 +50,10 @@ pub struct AppState {pub pipe_manager: Arc<PipeManager>,pub vision_disabled: bool,pub audio_disabled: bool,+ #[cfg(feature = "llm")]+ pub llm_enabled: bool,+ #[cfg(feature = "llm")]+ pub llm: Option<LLM>,}// Update the SearchQuery struct@@ -692,9 +700,14 @@ pub struct Server {pipe_manager: Arc<PipeManager>,vision_disabled: bool,audio_disabled: bool,+ #[cfg(feature = "llm")]+ enable_llm: bool,+ #[cfg(feature = "llm")]+ llm: Option<LLM>,}impl Server {+ #[allow(clippy::too_many_arguments)]pub fn new(db: Arc<DatabaseManager>,addr: SocketAddr,@@ -704,6 +717,8 @@ impl Server {pipe_manager: Arc<PipeManager>,vision_disabled: bool,audio_disabled: bool,+ #[cfg(feature = "llm")] enable_llm: bool,+ #[cfg(feature = "llm")] llm: Option<LLM>,) -> Self {Server {db,@@ -714,6 +729,10 @@ impl Server {pipe_manager,vision_disabled,audio_disabled,+ #[cfg(feature = "llm")]+ enable_llm,+ #[cfg(feature = "llm")]+ llm,}}@@ -735,6 +754,10 @@ impl Server {pipe_manager: self.pipe_manager,vision_disabled: self.vision_disabled,audio_disabled: self.audio_disabled,+ #[cfg(feature = "llm")]+ llm_enabled: self.enable_llm,+ #[cfg(feature = "llm")]+ llm: self.llm,});let app = create_router()@@ -779,6 +802,40 @@ async fn merge_frames_handler(}}+#[cfg(feature = "llm")]+async fn llm_chat_handler(+ State(state): State<Arc<AppState>>,+ JsonResponse(payload): JsonResponse<ChatRequest>,+) -> Result<JsonResponse<ChatResponse>, (StatusCode, JsonResponse<Value>)> {+ if payload.stream {+ return Err((+ StatusCode::BAD_REQUEST,+ JsonResponse(json!({"error": "Stream not supported"})),+ ));+ }++ let llm = match &state.llm {+ Some(llm) => llm,+ None => {+ return Err((+ StatusCode::BAD_REQUEST,+ JsonResponse(json!({"error": "LLM is not enabled"})),+ ))+ }+ };++ match llm.chat(payload) {+ Ok(res) => Ok(JsonResponse(res)),+ Err(e) => {+ error!("Failed to chat: {}", e);+ Err((+ StatusCode::INTERNAL_SERVER_ERROR,+ JsonResponse(json!({"error": e.to_string()})),+ ))+ }+ }+}+#[derive(Deserialize)]struct RawSqlQuery {query: String,@@ -800,6 +857,7 @@ async fn execute_raw_sql(}}+#[cfg(not(feature = "llm"))]pub fn create_router() -> Router<Arc<AppState>> {Router::new().route("/search", get(search))@@ -820,6 +878,27 @@ pub fn create_router() -> Router<Arc<AppState>> {.route("/raw_sql", post(execute_raw_sql))}+#[cfg(feature = "llm")]+pub fn create_router() -> Router<Arc<AppState>> {+ Router::new()+ .route("/search", get(search))+ .route("/audio/list", get(api_list_audio_devices))+ .route("/vision/list", post(api_list_monitors))+ .route(+ "/tags/:content_type/:id",+ post(add_tags).delete(remove_tags),+ )+ .route("/pipes/info/:pipe_id", get(get_pipe_info_handler))+ .route("/pipes/list", get(list_pipes_handler))+ .route("/pipes/download", post(download_pipe_handler))+ .route("/pipes/enable", post(run_pipe_handler))+ .route("/pipes/disable", post(stop_pipe_handler))+ .route("/pipes/update", post(update_pipe_config_handler))+ .route("/experimental/frames/merge", post(merge_frames_handler))+ .route("/health", get(health_check))+ .route("/raw_sql", post(execute_raw_sql))+ .route("/llm/chat", post(llm_chat_handler))+}/*Curl commands for reference: