From c67d8af42da086e6d23c889922a10316f820c592 Mon Sep 17 00:00:00 2001 From: Valentin Haudiquet Date: Wed, 2 Dec 2026 19:23:28 +0100 Subject: [PATCH] api: let the openai provider pin chat or responses The openai kind already accepts a base URL, and the registry already takes an explicit API choice, but the app always passed none. An OpenAI-compatible server therefore had to answer chat completions. The add-provider dialog now shows an API type for the openai kind: automatic, chat completions, or responses. Automatic keeps the old route rule, Responses at OpenAI itself and chat completions at a base URL; an explicit choice pins either. A separate provider kind would store the same fields and need the same adapter wiring. --- specs/rhema-together.md | 9 ++- src/api/settings.rs | 123 +++++++++++++++++++++++++++---------- src/db.rs | 2 + src/models.rs | 3 + src/room/agent.rs | 12 ++-- web/app/pages/settings.vue | 23 ++++++- web/app/types.ts | 2 + 7 files changed, 135 insertions(+), 39 deletions(-) diff --git a/specs/rhema-together.md b/specs/rhema-together.md index 8c5346f..9ac8bb3 100644 --- a/specs/rhema-together.md +++ b/specs/rhema-together.md @@ -618,9 +618,12 @@ One SQLite file in WAL mode. ``` accounts(id, handle, display_name, email, password_hash, created_at) auth_sessions(token_hash, account_id, created_at, expires_at, last_seen) -provider_configs(id, account_id, name, kind, model, base_url, key_ciphertext) +provider_configs(id, account_id, name, kind, model, base_url, api, + key_ciphertext) -- model is an optional default kept for existing rows; rooms carry -- the model that turns use + -- api is chat or responses for the openai kind; unset follows the + -- route: Responses at OpenAI, chat completions at a base URL sandbox_targets(id, account_id, name, host, user, port, key_ciphertext, workspace_root, host_key, created_at) rooms(id, name, owner_id, workspace, cwd, sandbox_target_id, @@ -764,7 +767,9 @@ This repository, as committed: output, price, and vision from the adapter and models.dev. A custom id is always accepted. The add-provider dialog asks for a kind and key, or runs a sign-in for GitHub Copilot, ChatGPT, and Mistral Vibe. - The room chooses the model. + An OpenAI provider also takes a base URL and an explicit chat + completions or responses API, so one kind reaches OpenAI itself and + any compatible server. The room chooses the model. - One conversation per room, a `@rhema` mention starts a turn, human messages are stamped with their author's name, and only the `message` tool puts agent text in the room. diff --git a/src/api/settings.rs b/src/api/settings.rs index 2f590cb..977f7c0 100644 --- a/src/api/settings.rs +++ b/src/api/settings.rs @@ -42,7 +42,7 @@ pub const FLOW_KINDS: &[&str] = &["copilot", "chatgpt", "mistral-vibe"]; pub async fn list_providers(user: AuthUser, State(state): State) -> AppResult> { let conn = state.db.conn(); let mut stmt = conn.prepare( - "SELECT id, name, kind, model, base_url FROM provider_configs + "SELECT id, name, kind, model, base_url, api FROM provider_configs WHERE account_id = ?1 ORDER BY created_at ASC", )?; let rows = stmt.query_map(rusqlite::params![user.user.id], |row| { @@ -52,6 +52,7 @@ pub async fn list_providers(user: AuthUser, State(state): State) -> AppR kind: row.get(2)?, model: row.get(3)?, base_url: row.get(4)?, + api: row.get(5)?, }) })?; let configs = rows.collect::, _>>()?; @@ -72,6 +73,9 @@ pub struct CreateProvider { pub model: String, #[serde(default)] pub base_url: Option, + /// `chat` or `responses`; only the openai kind reads it. + #[serde(default)] + pub api: Option, #[serde(default)] pub api_key: String, } @@ -107,42 +111,74 @@ pub async fn create_provider( if body.kind != "llama-cpp" && body.api_key.trim().is_empty() { return Err(AppError::bad_request("an api key is required")); } + let api = api_choice(&body.kind, body.api)?; let id = insert_provider( &state, &user.user.id, - name, - &body.kind, - &model, - base_url.as_deref(), - body.api_key.trim(), + ProviderDraft { + name, + kind: &body.kind, + model: &model, + base_url: base_url.as_deref(), + api: api.as_deref(), + api_key: body.api_key.trim(), + }, )?; Ok(Json(json!({ "id": id }))) } -/// Seals and stores one provider row. The callers validate the kind -/// and credential first; this only owns the encryption and the insert. +/// The stored API choice, normalized. Blank means automatic, which the +/// registry reads from the route. Only the openai kind has the choice. +fn api_choice(kind: &str, api: Option) -> AppResult> { + let api = api + .map(|value| value.trim().to_ascii_lowercase()) + .filter(|value| !value.is_empty()); + let Some(api) = api else { + return Ok(None); + }; + if !matches!(api.as_str(), "chat" | "responses") { + return Err(AppError::bad_request("api must be chat or responses")); + } + if kind != "openai" { + return Err(AppError::bad_request( + "the api choice only applies to the openai kind", + )); + } + Ok(Some(api)) +} + +/// One provider row before it is sealed and stored. The callers +/// validate the kind and credential first. +struct ProviderDraft<'a> { + name: &'a str, + kind: &'a str, + model: &'a str, + base_url: Option<&'a str>, + api: Option<&'a str>, + api_key: &'a str, +} + +/// Seals and stores one provider row; this only owns the encryption +/// and the insert. fn insert_provider( state: &Shared, account_id: &str, - name: &str, - kind: &str, - model: &str, - base_url: Option<&str>, - api_key: &str, + draft: ProviderDraft<'_>, ) -> AppResult { - let sealed = state.secrets.seal_str(api_key)?; + let sealed = state.secrets.seal_str(draft.api_key)?; let id = random_id(12); state.db.conn().execute( - "INSERT INTO provider_configs (id, account_id, name, kind, model, base_url, + "INSERT INTO provider_configs (id, account_id, name, kind, model, base_url, api, api_key_ciphertext, created_at) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", rusqlite::params![ id, account_id, - name, - kind, - model, - base_url, + draft.name, + draft.kind, + draft.model, + draft.base_url, + draft.api, sealed, crate::util::now_ms() ], @@ -202,11 +238,14 @@ pub async fn start_provider_login( insert_provider( &complete_state, &account_id, - &provider_name, - &provider_kind, - "", - None, - token.trim(), + ProviderDraft { + name: &provider_name, + kind: &provider_kind, + model: "", + base_url: None, + api: None, + api_key: token.trim(), + }, ) .map_err(|err| err.message) }); @@ -251,11 +290,11 @@ pub async fn list_provider_models( State(state): State, Path(id): Path, ) -> AppResult> { - let (kind, model, base_url, ciphertext) = state + let (kind, model, base_url, api, ciphertext) = state .db .conn() .query_row( - "SELECT kind, model, base_url, api_key_ciphertext FROM provider_configs + "SELECT kind, model, base_url, api, api_key_ciphertext FROM provider_configs WHERE id = ?1 AND account_id = ?2", rusqlite::params![id, user.user.id], |row| { @@ -263,7 +302,8 @@ pub async fn list_provider_models( row.get::<_, String>(0)?, row.get::<_, String>(1)?, row.get::<_, Option>(2)?, - row.get::<_, String>(3)?, + row.get::<_, Option>(3)?, + row.get::<_, String>(4)?, )) }, ) @@ -275,9 +315,14 @@ pub async fn list_provider_models( let llama_url = (kind == "llama-cpp") .then_some(base_url.as_deref()) .flatten(); - let built = - rhema_provider_registry::build(&kind, Some(&key), llama_url, base_url.as_deref(), None) - .map_err(|err| AppError::bad_request(format!("provider: {err}")))?; + let built = rhema_provider_registry::build( + &kind, + Some(&key), + llama_url, + base_url.as_deref(), + api.as_deref(), + ) + .map_err(|err| AppError::bad_request(format!("provider: {err}")))?; let models = tokio::time::timeout(Duration::from_secs(30), built.listing.list_models()) .await .map_err(|_| { @@ -581,4 +626,20 @@ mod tests { fn a_keyed_kind_has_no_login_flow() { assert!(login_flow("anthropic").is_none()); } + + #[test] + fn the_openai_api_choice_is_normalized() { + assert_eq!(api_choice("openai", None).unwrap(), None); + assert_eq!(api_choice("openai", Some(" ".into())).unwrap(), None); + assert_eq!( + api_choice("openai", Some(" Responses ".into())).unwrap(), + Some("responses".into()) + ); + assert_eq!( + api_choice("openai", Some("chat".into())).unwrap(), + Some("chat".into()) + ); + assert!(api_choice("openai", Some("completions".into())).is_err()); + assert!(api_choice("anthropic", Some("chat".into())).is_err()); + } } diff --git a/src/db.rs b/src/db.rs index eb80c20..aea22ee 100644 --- a/src/db.rs +++ b/src/db.rs @@ -34,6 +34,7 @@ impl Db { "thinking_effort", "TEXT NOT NULL DEFAULT 'default'", )?; + ensure_column(&conn, "provider_configs", "api", "TEXT")?; Ok(Self { conn: Arc::new(Mutex::new(conn)), }) @@ -115,6 +116,7 @@ CREATE TABLE IF NOT EXISTS provider_configs ( kind TEXT NOT NULL, model TEXT NOT NULL, base_url TEXT, + api TEXT, api_key_ciphertext TEXT NOT NULL, created_at INTEGER NOT NULL ) STRICT; diff --git a/src/models.rs b/src/models.rs index ce05e29..4ad6fa0 100644 --- a/src/models.rs +++ b/src/models.rs @@ -122,6 +122,9 @@ pub struct ProviderConfig { pub kind: String, pub model: String, pub base_url: Option, + /// `chat` or `responses` for the openai kind; `None` follows the + /// route: Responses at OpenAI, chat completions at a base URL. + pub api: Option, } /// A sandbox target without its private key. diff --git a/src/room/agent.rs b/src/room/agent.rs index b3b720d..91a2f6a 100644 --- a/src/room/agent.rs +++ b/src/room/agent.rs @@ -46,6 +46,8 @@ pub struct TurnConfig { pub struct ProviderRow { pub kind: String, pub base_url: Option, + /// `chat` or `responses`; only the openai kind reads it. + pub api: Option, pub api_key_ciphertext: String, } @@ -101,15 +103,16 @@ pub fn load_turn_config(state: &Shared, room_id: &str) -> AppResult provider_id.ok_or_else(|| AppError::bad_request("room has no provider configured"))?; let target_id = target_id.ok_or_else(|| AppError::bad_request("room has no sandbox configured"))?; - let (kind, provider_model, base_url, key) = conn.query_row( - "SELECT kind, model, base_url, api_key_ciphertext FROM provider_configs WHERE id = ?1", + let (kind, provider_model, base_url, api, key) = conn.query_row( + "SELECT kind, model, base_url, api, api_key_ciphertext FROM provider_configs WHERE id = ?1", rusqlite::params![provider_id], |row| { Ok(( row.get::<_, String>(0)?, row.get::<_, String>(1)?, row.get::<_, Option>(2)?, - row.get::<_, String>(3)?, + row.get::<_, Option>(3)?, + row.get::<_, String>(4)?, )) }, )?; @@ -162,6 +165,7 @@ pub fn load_turn_config(state: &Shared, room_id: &str) -> AppResult provider: ProviderRow { kind, base_url, + api, api_key_ciphertext: key, }, target, @@ -336,7 +340,7 @@ pub fn build_agent( Some(&api_key), llama_url, config.provider.base_url.as_deref(), - None, + config.provider.api.as_deref(), ) .map_err(|err| AppError::bad_request(format!("provider: {err}")))?; let message_tool: Arc = diff --git a/web/app/pages/settings.vue b/web/app/pages/settings.vue index 9944074..200ed28 100644 --- a/web/app/pages/settings.vue +++ b/web/app/pages/settings.vue @@ -23,7 +23,7 @@ const api = useApi() const KIND_LABELS: Record = { anthropic: 'Anthropic', - openai: 'OpenAI', + openai: 'OpenAI / compatible', openrouter: 'OpenRouter', google: 'Google Gemini', deepseek: 'DeepSeek', @@ -46,10 +46,12 @@ const loadError = ref('') const providerName = ref('') const providerKind = ref('anthropic') const providerBaseUrl = ref('') +const providerApi = ref('') const providerKey = ref('') const providerBusy = ref(false) const providerError = ref('') const llama = computed(() => providerKind.value === 'llama-cpp') +const openai = computed(() => providerKind.value === 'openai') const flowKind = computed(() => flowKinds.value.includes(providerKind.value)) const kindName = computed(() => KIND_LABELS[providerKind.value] ?? providerKind.value) @@ -319,11 +321,13 @@ async function addProvider() { kind: providerKind.value, } if (providerBaseUrl.value.trim()) body.base_url = providerBaseUrl.value.trim() + if (openai.value && providerApi.value) body.api = providerApi.value if (!llama.value) body.api_key = providerKey.value try { await api.post('/provider-configs', body) providerName.value = '' providerBaseUrl.value = '' + providerApi.value = '' providerKey.value = '' await loadLists() providerDialog.value = false @@ -446,7 +450,7 @@ async function copyKey(target: SandboxTarget) {
{{ provider.name }}
- {{ kindLabel(provider.kind) }} + {{ kindLabel(provider.kind) }}
@@ -510,6 +514,21 @@ async function copyKey(target: SandboxTarget) { :required="llama" > The address of the llama.cpp server. + + Leave empty for OpenAI, or point at any OpenAI-compatible server. + +
+ +
+ + + + Automatic uses Responses at OpenAI and chat completions when a base URL points elsewhere. +
diff --git a/web/app/types.ts b/web/app/types.ts index 2c5be68..8fe4ac6 100644 --- a/web/app/types.ts +++ b/web/app/types.ts @@ -159,6 +159,7 @@ export interface ProviderConfig { kind: string model: string base_url: string | null + api: string | null } export interface ProviderListResponse { @@ -215,6 +216,7 @@ export interface CreateProviderBody { kind: string model?: string base_url?: string | null + api?: string | null api_key?: string }