api: let the openai provider pin chat or responses
ci / checks (push) Successful in 54s
ci / test (push) Successful in 1m0s
ci / chart (push) Successful in 5s
ci / web (push) Successful in 17s
ci / docker (push) Successful in 1m49s
ci / publish-edge-image (push) Successful in 9s
ci / publish-edge-chart (push) Successful in 3s

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.
This commit is contained in:
vhaudiquet committed 2026-12-02 19:23:28 +01:00
1 parent 1289f5f0c2
commit c67d8af42d
7 files changed
+135 -39

No files matched your search

+7 -2
View File
@@ -618,9 +618,12 @@ One SQLite file in WAL mode.
``` ```
accounts(id, handle, display_name, email, password_hash, created_at) accounts(id, handle, display_name, email, password_hash, created_at)
auth_sessions(token_hash, account_id, created_at, expires_at, last_seen) 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 -- model is an optional default kept for existing rows; rooms carry
-- the model that turns use -- 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, sandbox_targets(id, account_id, name, host, user, port, key_ciphertext,
workspace_root, host_key, created_at) workspace_root, host_key, created_at)
rooms(id, name, owner_id, workspace, cwd, sandbox_target_id, 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 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 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. 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 - One conversation per room, a `@rhema` mention starts a turn, human
messages are stamped with their author's name, and only the `message` messages are stamped with their author's name, and only the `message`
tool puts agent text in the room. tool puts agent text in the room.
+92 -31
View File
@@ -42,7 +42,7 @@ pub const FLOW_KINDS: &[&str] = &["copilot", "chatgpt", "mistral-vibe"];
pub async fn list_providers(user: AuthUser, State(state): State<Shared>) -> AppResult<Json<Value>> { pub async fn list_providers(user: AuthUser, State(state): State<Shared>) -> AppResult<Json<Value>> {
let conn = state.db.conn(); let conn = state.db.conn();
let mut stmt = conn.prepare( 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", WHERE account_id = ?1 ORDER BY created_at ASC",
)?; )?;
let rows = stmt.query_map(rusqlite::params![user.user.id], |row| { 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<Shared>) -> AppR
kind: row.get(2)?, kind: row.get(2)?,
model: row.get(3)?, model: row.get(3)?,
base_url: row.get(4)?, base_url: row.get(4)?,
api: row.get(5)?,
}) })
})?; })?;
let configs = rows.collect::<Result<Vec<_>, _>>()?; let configs = rows.collect::<Result<Vec<_>, _>>()?;
@@ -72,6 +73,9 @@ pub struct CreateProvider {
pub model: String, pub model: String,
#[serde(default)] #[serde(default)]
pub base_url: Option<String>, pub base_url: Option<String>,
/// `chat` or `responses`; only the openai kind reads it.
#[serde(default)]
pub api: Option<String>,
#[serde(default)] #[serde(default)]
pub api_key: String, pub api_key: String,
} }
@@ -107,42 +111,74 @@ pub async fn create_provider(
if body.kind != "llama-cpp" && body.api_key.trim().is_empty() { if body.kind != "llama-cpp" && body.api_key.trim().is_empty() {
return Err(AppError::bad_request("an api key is required")); return Err(AppError::bad_request("an api key is required"));
} }
let api = api_choice(&body.kind, body.api)?;
let id = insert_provider( let id = insert_provider(
&state, &state,
&user.user.id, &user.user.id,
name, ProviderDraft {
&body.kind, name,
&model, kind: &body.kind,
base_url.as_deref(), model: &model,
body.api_key.trim(), base_url: base_url.as_deref(),
api: api.as_deref(),
api_key: body.api_key.trim(),
},
)?; )?;
Ok(Json(json!({ "id": id }))) Ok(Json(json!({ "id": id })))
} }
/// Seals and stores one provider row. The callers validate the kind /// The stored API choice, normalized. Blank means automatic, which the
/// and credential first; this only owns the encryption and the insert. /// registry reads from the route. Only the openai kind has the choice.
fn api_choice(kind: &str, api: Option<String>) -> AppResult<Option<String>> {
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( fn insert_provider(
state: &Shared, state: &Shared,
account_id: &str, account_id: &str,
name: &str, draft: ProviderDraft<'_>,
kind: &str,
model: &str,
base_url: Option<&str>,
api_key: &str,
) -> AppResult<String> { ) -> AppResult<String> {
let sealed = state.secrets.seal_str(api_key)?; let sealed = state.secrets.seal_str(draft.api_key)?;
let id = random_id(12); let id = random_id(12);
state.db.conn().execute( 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) 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![ rusqlite::params![
id, id,
account_id, account_id,
name, draft.name,
kind, draft.kind,
model, draft.model,
base_url, draft.base_url,
draft.api,
sealed, sealed,
crate::util::now_ms() crate::util::now_ms()
], ],
@@ -202,11 +238,14 @@ pub async fn start_provider_login(
insert_provider( insert_provider(
&complete_state, &complete_state,
&account_id, &account_id,
&provider_name, ProviderDraft {
&provider_kind, name: &provider_name,
"", kind: &provider_kind,
None, model: "",
token.trim(), base_url: None,
api: None,
api_key: token.trim(),
},
) )
.map_err(|err| err.message) .map_err(|err| err.message)
}); });
@@ -251,11 +290,11 @@ pub async fn list_provider_models(
State(state): State<Shared>, State(state): State<Shared>,
Path(id): Path<String>, Path(id): Path<String>,
) -> AppResult<Json<Value>> { ) -> AppResult<Json<Value>> {
let (kind, model, base_url, ciphertext) = state let (kind, model, base_url, api, ciphertext) = state
.db .db
.conn() .conn()
.query_row( .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", WHERE id = ?1 AND account_id = ?2",
rusqlite::params![id, user.user.id], rusqlite::params![id, user.user.id],
|row| { |row| {
@@ -263,7 +302,8 @@ pub async fn list_provider_models(
row.get::<_, String>(0)?, row.get::<_, String>(0)?,
row.get::<_, String>(1)?, row.get::<_, String>(1)?,
row.get::<_, Option<String>>(2)?, row.get::<_, Option<String>>(2)?,
row.get::<_, String>(3)?, row.get::<_, Option<String>>(3)?,
row.get::<_, String>(4)?,
)) ))
}, },
) )
@@ -275,9 +315,14 @@ pub async fn list_provider_models(
let llama_url = (kind == "llama-cpp") let llama_url = (kind == "llama-cpp")
.then_some(base_url.as_deref()) .then_some(base_url.as_deref())
.flatten(); .flatten();
let built = let built = rhema_provider_registry::build(
rhema_provider_registry::build(&kind, Some(&key), llama_url, base_url.as_deref(), None) &kind,
.map_err(|err| AppError::bad_request(format!("provider: {err}")))?; 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()) let models = tokio::time::timeout(Duration::from_secs(30), built.listing.list_models())
.await .await
.map_err(|_| { .map_err(|_| {
@@ -581,4 +626,20 @@ mod tests {
fn a_keyed_kind_has_no_login_flow() { fn a_keyed_kind_has_no_login_flow() {
assert!(login_flow("anthropic").is_none()); 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());
}
} }
+2
View File
@@ -34,6 +34,7 @@ impl Db {
"thinking_effort", "thinking_effort",
"TEXT NOT NULL DEFAULT 'default'", "TEXT NOT NULL DEFAULT 'default'",
)?; )?;
ensure_column(&conn, "provider_configs", "api", "TEXT")?;
Ok(Self { Ok(Self {
conn: Arc::new(Mutex::new(conn)), conn: Arc::new(Mutex::new(conn)),
}) })
@@ -115,6 +116,7 @@ CREATE TABLE IF NOT EXISTS provider_configs (
kind TEXT NOT NULL, kind TEXT NOT NULL,
model TEXT NOT NULL, model TEXT NOT NULL,
base_url TEXT, base_url TEXT,
api TEXT,
api_key_ciphertext TEXT NOT NULL, api_key_ciphertext TEXT NOT NULL,
created_at INTEGER NOT NULL created_at INTEGER NOT NULL
) STRICT; ) STRICT;
+3
View File
@@ -122,6 +122,9 @@ pub struct ProviderConfig {
pub kind: String, pub kind: String,
pub model: String, pub model: String,
pub base_url: Option<String>, pub base_url: Option<String>,
/// `chat` or `responses` for the openai kind; `None` follows the
/// route: Responses at OpenAI, chat completions at a base URL.
pub api: Option<String>,
} }
/// A sandbox target without its private key. /// A sandbox target without its private key.
+8 -4
View File
@@ -46,6 +46,8 @@ pub struct TurnConfig {
pub struct ProviderRow { pub struct ProviderRow {
pub kind: String, pub kind: String,
pub base_url: Option<String>, pub base_url: Option<String>,
/// `chat` or `responses`; only the openai kind reads it.
pub api: Option<String>,
pub api_key_ciphertext: String, pub api_key_ciphertext: String,
} }
@@ -101,15 +103,16 @@ pub fn load_turn_config(state: &Shared, room_id: &str) -> AppResult<TurnConfig>
provider_id.ok_or_else(|| AppError::bad_request("room has no provider configured"))?; provider_id.ok_or_else(|| AppError::bad_request("room has no provider configured"))?;
let target_id = let target_id =
target_id.ok_or_else(|| AppError::bad_request("room has no sandbox configured"))?; target_id.ok_or_else(|| AppError::bad_request("room has no sandbox configured"))?;
let (kind, provider_model, base_url, key) = conn.query_row( let (kind, provider_model, base_url, api, key) = conn.query_row(
"SELECT kind, model, base_url, api_key_ciphertext FROM provider_configs WHERE id = ?1", "SELECT kind, model, base_url, api, api_key_ciphertext FROM provider_configs WHERE id = ?1",
rusqlite::params![provider_id], rusqlite::params![provider_id],
|row| { |row| {
Ok(( Ok((
row.get::<_, String>(0)?, row.get::<_, String>(0)?,
row.get::<_, String>(1)?, row.get::<_, String>(1)?,
row.get::<_, Option<String>>(2)?, row.get::<_, Option<String>>(2)?,
row.get::<_, String>(3)?, row.get::<_, Option<String>>(3)?,
row.get::<_, String>(4)?,
)) ))
}, },
)?; )?;
@@ -162,6 +165,7 @@ pub fn load_turn_config(state: &Shared, room_id: &str) -> AppResult<TurnConfig>
provider: ProviderRow { provider: ProviderRow {
kind, kind,
base_url, base_url,
api,
api_key_ciphertext: key, api_key_ciphertext: key,
}, },
target, target,
@@ -336,7 +340,7 @@ pub fn build_agent(
Some(&api_key), Some(&api_key),
llama_url, llama_url,
config.provider.base_url.as_deref(), config.provider.base_url.as_deref(),
None, config.provider.api.as_deref(),
) )
.map_err(|err| AppError::bad_request(format!("provider: {err}")))?; .map_err(|err| AppError::bad_request(format!("provider: {err}")))?;
let message_tool: Arc<dyn ToolResolver> = let message_tool: Arc<dyn ToolResolver> =
+21 -2
View File
@@ -23,7 +23,7 @@ const api = useApi()
const KIND_LABELS: Record<string, string> = { const KIND_LABELS: Record<string, string> = {
anthropic: 'Anthropic', anthropic: 'Anthropic',
openai: 'OpenAI', openai: 'OpenAI / compatible',
openrouter: 'OpenRouter', openrouter: 'OpenRouter',
google: 'Google Gemini', google: 'Google Gemini',
deepseek: 'DeepSeek', deepseek: 'DeepSeek',
@@ -46,10 +46,12 @@ const loadError = ref('')
const providerName = ref('') const providerName = ref('')
const providerKind = ref('anthropic') const providerKind = ref('anthropic')
const providerBaseUrl = ref('') const providerBaseUrl = ref('')
const providerApi = ref('')
const providerKey = ref('') const providerKey = ref('')
const providerBusy = ref(false) const providerBusy = ref(false)
const providerError = ref('') const providerError = ref('')
const llama = computed(() => providerKind.value === 'llama-cpp') const llama = computed(() => providerKind.value === 'llama-cpp')
const openai = computed(() => providerKind.value === 'openai')
const flowKind = computed(() => flowKinds.value.includes(providerKind.value)) const flowKind = computed(() => flowKinds.value.includes(providerKind.value))
const kindName = computed(() => KIND_LABELS[providerKind.value] ?? providerKind.value) const kindName = computed(() => KIND_LABELS[providerKind.value] ?? providerKind.value)
@@ -319,11 +321,13 @@ async function addProvider() {
kind: providerKind.value, kind: providerKind.value,
} }
if (providerBaseUrl.value.trim()) body.base_url = providerBaseUrl.value.trim() 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 if (!llama.value) body.api_key = providerKey.value
try { try {
await api.post<IdResponse>('/provider-configs', body) await api.post<IdResponse>('/provider-configs', body)
providerName.value = '' providerName.value = ''
providerBaseUrl.value = '' providerBaseUrl.value = ''
providerApi.value = ''
providerKey.value = '' providerKey.value = ''
await loadLists() await loadLists()
providerDialog.value = false providerDialog.value = false
@@ -446,7 +450,7 @@ async function copyKey(target: SandboxTarget) {
<div class="settings-row-main"> <div class="settings-row-main">
<div class="settings-row-title">{{ provider.name }}</div> <div class="settings-row-title">{{ provider.name }}</div>
<div class="settings-row-detail"> <div class="settings-row-detail">
{{ kindLabel(provider.kind) }}<template v-if="provider.base_url">, {{ provider.base_url }}</template> {{ kindLabel(provider.kind) }}<template v-if="provider.api">, {{ provider.api }} API</template><template v-if="provider.base_url">, {{ provider.base_url }}</template>
</div> </div>
</div> </div>
<div class="settings-row-actions"> <div class="settings-row-actions">
@@ -510,6 +514,21 @@ async function copyKey(target: SandboxTarget) {
:required="llama" :required="llama"
> >
<span v-if="llama" class="hint">The address of the llama.cpp server.</span> <span v-if="llama" class="hint">The address of the llama.cpp server.</span>
<span v-else-if="openai" class="hint">
Leave empty for OpenAI, or point at any OpenAI-compatible server.
</span>
</div>
<div v-if="openai" class="field">
<label class="field-label" for="provider-api">API type</label>
<select id="provider-api" v-model="providerApi" class="select">
<option value="">Automatic</option>
<option value="chat">Chat completions</option>
<option value="responses">Responses</option>
</select>
<span class="hint">
Automatic uses Responses at OpenAI and chat completions when a base URL points elsewhere.
</span>
</div> </div>
<div v-if="!flowKind && !llama" class="field"> <div v-if="!flowKind && !llama" class="field">
+2
View File
@@ -159,6 +159,7 @@ export interface ProviderConfig {
kind: string kind: string
model: string model: string
base_url: string | null base_url: string | null
api: string | null
} }
export interface ProviderListResponse { export interface ProviderListResponse {
@@ -215,6 +216,7 @@ export interface CreateProviderBody {
kind: string kind: string
model?: string model?: string
base_url?: string | null base_url?: string | null
api?: string | null
api_key?: string api_key?: string
} }