| 1 | //! 从工作区设置构造 LLM 客户端,以及按模型的并发闸门。 |
| 2 | |
| 3 | use std::collections::HashMap; |
| 4 | use std::sync::Arc; |
| 5 | |
| 6 | use tokio::sync::{OwnedSemaphorePermit, Semaphore}; |
| 7 | use utopia_core::models::LlmSettings; |
| 8 | use utopia_llm::LlmClient; |
| 9 | |
| 10 | use crate::state::AppState; |
| 11 | |
| 12 | pub fn chat_client(s: &LlmSettings) -> Option<LlmClient> { |
| 13 | if !s.chat_ready() { |
| 14 | return None; |
| 15 | } |
| 16 | Some(LlmClient::new( |
| 17 | s.chat_base_url.as_deref()?, |
| 18 | s.chat_api_key.as_deref(), |
| 19 | s.chat_model.as_deref()?, |
| 20 | )) |
| 21 | } |
| 22 | |
| 23 | pub fn embed_client(s: &LlmSettings) -> Option<LlmClient> { |
| 24 | if !s.embed_ready() { |
| 25 | return None; |
| 26 | } |
| 27 | Some(LlmClient::new( |
| 28 | s.embed_base_url.as_deref()?, |
| 29 | s.embed_api_key.as_deref(), |
| 30 | s.embed_model.as_deref()?, |
| 31 | )) |
| 32 | } |
| 33 | |
| 34 | /// 按模型的信号量注册表。限额变了就换一把新的——旧的在飞许可自然跑完, |
| 35 | /// 换的瞬间可能短暂超出新限额,可接受;换来的是"改完即时生效"而不必做 |
| 36 | /// 缓存失效,也不必和 tokio Semaphore 不能缩容的限制搏斗。 |
| 37 | #[derive(Default)] |
| 38 | pub struct ModelGates { |
| 39 | inner: std::sync::Mutex<HashMap<String, (usize, Arc<Semaphore>)>>, |
| 40 | } |
| 41 | |
| 42 | impl ModelGates { |
| 43 | fn gate(&self, key: &str, limit: usize) -> Arc<Semaphore> { |
| 44 | let mut m = self.inner.lock().unwrap(); |
| 45 | match m.get(key) { |
| 46 | Some((n, sem)) if *n == limit => sem.clone(), |
| 47 | _ => { |
| 48 | let sem = Arc::new(Semaphore::new(limit)); |
| 49 | m.insert(key.to_string(), (limit, sem.clone())); |
| 50 | sem |
| 51 | } |
| 52 | } |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | /// 后台任务调模型前取一张许可,持有到调用结束。 |
| 57 | /// |
| 58 | /// **只给后台任务用**(抽取、裁决、摄入嵌入、本体建议)。用户的对话与检索 |
| 59 | /// 不走这里——让人打字等在十个后台抽取后面,产品就成了坏的;真正会打爆 |
| 60 | /// 供应商速率限制的也从来不是一个人在打字。 |
| 61 | /// |
| 62 | /// 限额读不到(表还没建、库暂时不可达)时**放行**:并发限制是保护措施, |
| 63 | /// 不该因为读不到配置而把整条流水线卡死。 |
| 64 | pub async fn acquire( |
| 65 | state: &AppState, |
| 66 | base_url: &str, |
| 67 | model: &str, |
| 68 | ) -> Option<OwnedSemaphorePermit> { |
| 69 | let limit = utopia_store::model_limits::limit_for(&state.pool, base_url, model) |
| 70 | .await |
| 71 | .ok()?; |
| 72 | let key = format!("{base_url}|{model}"); |
| 73 | state |
| 74 | .model_gates |
| 75 | .gate(&key, limit) |
| 76 | .acquire_owned() |
| 77 | .await |
| 78 | .ok() |
| 79 | } |
| 80 | |
| 81 | /// `acquire` 的便捷形式:直接从工作区设置取 chat 模型的身份。 |
| 82 | pub async fn acquire_chat(state: &AppState, s: &LlmSettings) -> Option<OwnedSemaphorePermit> { |
| 83 | let (base, model) = (s.chat_base_url.as_deref()?, s.chat_model.as_deref()?); |
| 84 | acquire(state, base, model).await |
| 85 | } |
| 86 | |
| 87 | /// `acquire` 的便捷形式:embedding 模型。 |
| 88 | pub async fn acquire_embed(state: &AppState, s: &LlmSettings) -> Option<OwnedSemaphorePermit> { |
| 89 | let (base, model) = (s.embed_base_url.as_deref()?, s.embed_model.as_deref()?); |
| 90 | acquire(state, base, model).await |
| 91 | } |