| 1 | use sqlx::PgPool; |
| 2 | use utopia_core::models::LlmSettings; |
| 3 | use utopia_core::AppResult; |
| 4 | use uuid::Uuid; |
| 5 | |
| 6 | pub async fn get(pool: &PgPool, workspace_id: Uuid) -> AppResult<Option<LlmSettings>> { |
| 7 | let row = sqlx::query_as("SELECT * FROM llm_settings WHERE workspace_id = $1") |
| 8 | .bind(workspace_id) |
| 9 | .fetch_optional(pool) |
| 10 | .await?; |
| 11 | Ok(row) |
| 12 | } |
| 13 | |
| 14 | /// 任取一个配了对话模型的工作区设置。给端点探针用:端点地址是部署共用的, |
| 15 | /// 从哪个工作区的配置读到的都是同一个地方,而探针没有"当前工作区"这个上下文。 |
| 16 | pub async fn any_with_chat(pool: &PgPool) -> AppResult<Option<LlmSettings>> { |
| 17 | let row = sqlx::query_as( |
| 18 | "SELECT * FROM llm_settings |
| 19 | WHERE chat_base_url IS NOT NULL AND chat_model IS NOT NULL |
| 20 | ORDER BY workspace_id LIMIT 1", |
| 21 | ) |
| 22 | .fetch_optional(pool) |
| 23 | .await?; |
| 24 | Ok(row) |
| 25 | } |
| 26 | |
| 27 | /// upsert;api_key 传 None 表示保留旧值(前端不回传密钥)。 |
| 28 | #[allow(clippy::too_many_arguments)] |
| 29 | pub async fn upsert( |
| 30 | pool: &PgPool, |
| 31 | workspace_id: Uuid, |
| 32 | chat_base_url: Option<&str>, |
| 33 | chat_api_key: Option<&str>, |
| 34 | chat_model: Option<&str>, |
| 35 | embed_base_url: Option<&str>, |
| 36 | embed_api_key: Option<&str>, |
| 37 | embed_model: Option<&str>, |
| 38 | embed_dim: Option<i32>, |
| 39 | ) -> AppResult<LlmSettings> { |
| 40 | let row = sqlx::query_as( |
| 41 | "INSERT INTO llm_settings |
| 42 | (workspace_id, chat_base_url, chat_api_key, chat_model, |
| 43 | embed_base_url, embed_api_key, embed_model, embed_dim, updated_at) |
| 44 | VALUES ($1, $2, $3, $4, $5, $6, $7, $8, now()) |
| 45 | ON CONFLICT (workspace_id) DO UPDATE SET |
| 46 | chat_base_url = EXCLUDED.chat_base_url, |
| 47 | chat_api_key = COALESCE(EXCLUDED.chat_api_key, llm_settings.chat_api_key), |
| 48 | chat_model = EXCLUDED.chat_model, |
| 49 | embed_base_url = EXCLUDED.embed_base_url, |
| 50 | embed_api_key = COALESCE(EXCLUDED.embed_api_key, llm_settings.embed_api_key), |
| 51 | embed_model = EXCLUDED.embed_model, |
| 52 | embed_dim = EXCLUDED.embed_dim, |
| 53 | updated_at = now() |
| 54 | RETURNING *", |
| 55 | ) |
| 56 | .bind(workspace_id) |
| 57 | .bind(chat_base_url) |
| 58 | .bind(chat_api_key) |
| 59 | .bind(chat_model) |
| 60 | .bind(embed_base_url) |
| 61 | .bind(embed_api_key) |
| 62 | .bind(embed_model) |
| 63 | .bind(embed_dim) |
| 64 | .fetch_one(pool) |
| 65 | .await?; |
| 66 | Ok(row) |
| 67 | } |