Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

refactor(inference): remove openrouter provider and update catalog logic

Steven Enamakelc10ed7464550
diff --git a/crates/openhuman-core/src/inference/provider/models/local_runtime.rs b/crates/openhuman-core/src/inference/provider/models/local_runtime.rs
index 5a17533a5e..624b76badf 100644
--- a/crates/openhuman-core/src/inference/provider/models/local_runtime.rs
+++ b/crates/openhuman-core/src/inference/provider/models/local_runtime.rs
@@ -26,22 +26,18 @@ pub fn synthesize_local_runtime_entry(
) -> Option<crate::config::schema::cloud_providers::CloudProviderCreds> {
use crate::config::schema::cloud_providers::{AuthStyle, CloudProviderCreds};
- let endpoint = match slug {
- // Ollama's OpenAI-compatible surface at `<base>/v1/models` returns
- // the same `{"data": [...]}` shape the existing parser handles, so
- // we route through that rather than the native `/api/tags`.
- "ollama" => {
- let base = tinyinference_local::ollama::ollama_base_url_from_override(
- config.local_ai.base_url.as_deref(),
- );
- format!("{}/v1", base.trim_end_matches('/'))
- }
- // `lm_studio_base_url` already ends in `/v1`.
+ let runtime_base = match slug {
+ "ollama" => tinyinference_local::ollama::ollama_base_url_from_override(
+ config.local_ai.base_url.as_deref(),
+ ),
"lmstudio" => {
tinyinference_local::lm_studio::lm_studio_base_url(config.local_ai.base_url.as_deref())
}
_ => return None,
};
+ let endpoint = tinyinference_local::provider::local_runtime_models_endpoint(slug, &runtime_base)?
+ .strip_suffix("/models")?
+ .to_string();
Some(CloudProviderCreds {
id: format!("synthetic_local_{slug}"),
diff --git a/crates/openhuman-core/src/inference/provider/models/mod.rs b/crates/openhuman-core/src/inference/provider/models/mod.rs
index 9cdbddb2e1..4051840c3c 100644
--- a/crates/openhuman-core/src/inference/provider/models/mod.rs
+++ b/crates/openhuman-core/src/inference/provider/models/mod.rs
@@ -2,7 +2,6 @@
pub mod catalog_listing;
pub(crate) mod local_runtime;
-mod openrouter;
#[cfg(test)]
#[path = "mod_tests.rs"]
diff --git a/crates/openhuman-core/src/inference/provider/models/openrouter.rs b/crates/openhuman-core/src/inference/provider/models/openrouter.rs
deleted file mode 100644
index 018cd61d04..0000000000
--- a/crates/openhuman-core/src/inference/provider/models/openrouter.rs
+++ /dev/null
@@ -1,65 +0,0 @@
-//! OpenRouter detection and API-key validation.
-
-use tinyinference_core::sanitize::sanitize_api_error;
-
-pub(super) async fn validate_openrouter_api_key(
- client: &reqwest::Client,
- base: &str,
- api_key: &str,
-) -> Result<(), String> {
- if api_key.is_empty() {
- return Err("OpenRouter API key is required before enabling the provider".to_string());
- }
-
- let key_url = format!("{}/key", base);
- log::debug!("[providers][list_models] validating OpenRouter API key");
- let response = client
- .get(&key_url)
- .header("Authorization", format!("Bearer {api_key}"))
- .send()
- .await
- .map_err(|e| format!("[providers][list_models] OpenRouter key validation failed: {e}"))?;
-
- let status = response.status();
- let text = response.text().await.unwrap_or_default();
- if !status.is_success() {
- let sanitized = sanitize_api_error(&text);
- let truncated = crate::util::truncate_with_ellipsis(&sanitized, 300);
- log::debug!(
- "[providers][list_models] OpenRouter key validation failed status={} body={}",
- status.as_u16(),
- truncated
- );
- return Err(format!(
- "OpenRouter key validation returned {}: {}",
- status.as_u16(),
- truncated
- ));
- }
-
- if let Ok(body) = serde_json::from_str::<serde_json::Value>(&text) {
- if let Some(err_field) = body.get("error") {
- let msg = err_field
- .as_str()
- .map(|s| s.to_string())
- .or_else(|| {
- err_field
- .get("message")
- .and_then(|m| m.as_str())
- .map(|s| s.to_string())
- })
- .unwrap_or_else(|| err_field.to_string());
- let sanitized = sanitize_api_error(&msg);
- log::debug!(
- "[providers][list_models] OpenRouter key validation returned error payload={}",
- sanitized
- );
- return Err(format!(
- "OpenRouter key validation returned error payload: {}",
- sanitized
- ));
- }
- }
-
- Ok(())
-}
diff --git a/crates/openhuman-tinyhumans/src/inference/managed_catalog.rs b/crates/openhuman-tinyhumans/src/inference/managed_catalog.rs
index 5b9478951a..b6e01ffe19 100644
--- a/crates/openhuman-tinyhumans/src/inference/managed_catalog.rs
+++ b/crates/openhuman-tinyhumans/src/inference/managed_catalog.rs
@@ -18,7 +18,7 @@ use openhuman_embed::__host::security::credentials::session_support::{
};
use openhuman_embed::__host::util::url::join_url;
use std::sync::Arc;
-use tinyinference_llm::catalog::{append_query_param, parse_models_response};
+use tinyinference_llm::catalog::{append_query_param, list_models as fetch_models};
use tinyinference_llm::model::discover::DiscoveryRequest;
use crate::backend::headers::attribution_headers;
@@ -64,16 +64,8 @@ fn catalog_url(config: &Config) -> String {
/// Whether a non-2xx from the listing reads as "signed out": a 401 on a request
/// that actually carried the app session token. A 401 without one describes the
/// request, not the session.
-pub(super) fn managed_401_means_signed_out(status: u16, session_attached: bool) -> bool {
- status == 401 && session_attached
-}
-
-fn truncate(text: &str, max_chars: usize) -> String {
- if text.chars().count() <= max_chars {
- return text.to_string();
- }
- let cut: String = text.chars().take(max_chars).collect();
- format!("{cut}...")
+pub(super) fn managed_401_means_signed_out(status: Option<u16>, session_attached: bool) -> bool {
+ status == Some(401) && session_attached
}
/// What authenticates a listing request: the live session token, or the
@@ -141,11 +133,20 @@ pub(super) async fn list_models(
// request that carried only a provider key describes that key, not the
// session.
let session_attached = attach && session_token;
- let mut request = client.get(&url);
+ let mut discovery = DiscoveryRequest::new(
+ format!("{}/openai/v1", effective_api_url(&config.api_url).trim_end_matches('/')),
+ String::new(),
+ )
+ .with_listing_url(url.clone())
+ .with_single_model_probe(false);
if attach {
- request = request.header("Authorization", format!("Bearer {token}"));
+ discovery = discovery.with_header("Authorization", format!("Bearer {token}"));
if let Ok(headers) = attribution_headers() {
- request = request.headers(headers);
+ for (name, value) in headers.iter() {
+ if let Ok(value) = value.to_str() {
+ discovery = discovery.with_header(name.as_str(), value);
+ }
+ }
}
} else {
log::warn!(
@@ -153,55 +154,16 @@ pub(super) async fn list_models(
);
}
- let response = request
- .send()
- .await
- .map_err(|e| format!("[providers][list_models] HTTP request failed: {e}"))?;
- let status = response.status();
- if !status.is_success() {
- if managed_401_means_signed_out(status.as_u16(), session_attached) {
+ let models = match fetch_models(&client, discovery).await {
+ Ok(models) => models,
+ Err(error) if managed_401_means_signed_out(error.http_status(), session_attached) => {
log::info!(
"[tinyhumans][inference] managed catalog unavailable: backend rejected the session token (401)"
);
return empty_catalog("session not accepted");
}
- let body = response.text().await.unwrap_or_default();
- let sanitized = tinyinference_core::sanitize::sanitize_api_error(&body);
- return Err(format!(
- "provider returned {}: {}",
- status.as_u16(),
- truncate(&sanitized, 300)
- ));
- }
-
- let raw_body = response
- .text()
- .await
- .map_err(|e| format!("[providers][list_models] failed to read response body: {e}"))?;
- let body: serde_json::Value = serde_json::from_str(&raw_body).map_err(|e| {
- let snippet = truncate(
- &tinyinference_core::sanitize::sanitize_api_error(&raw_body),
- 300,
- );
- format!("[providers][list_models] failed to parse JSON: {e} (body: {snippet})")
- })?;
- if let Some(err_field) = body.get("error") {
- let msg = err_field
- .as_str()
- .map(str::to_string)
- .or_else(|| {
- err_field
- .get("message")
- .and_then(|m| m.as_str())
- .map(str::to_string)
- })
- .unwrap_or_else(|| err_field.to_string());
- return Err(format!(
- "provider returned error payload: {}",
- tinyinference_core::sanitize::sanitize_api_error(&msg)
- ));
- }
- let models = parse_models_response(&body).map_err(|error| error.to_string())?;
+ Err(error) => return Err(error.to_string()),
+ };
log::info!(
"[tinyhumans][inference] managed catalog fetched {} models",
models.len()
diff --git a/crates/openhuman-tinyhumans/src/inference/managed_catalog_tests.rs b/crates/openhuman-tinyhumans/src/inference/managed_catalog_tests.rs
index 89cac0c621..05880553a2 100644
--- a/crates/openhuman-tinyhumans/src/inference/managed_catalog_tests.rs
+++ b/crates/openhuman-tinyhumans/src/inference/managed_catalog_tests.rs
@@ -1,22 +1,66 @@
use super::*;
+use axum::{
+ http::{HeaderMap, StatusCode},
+ routing::get,
+ Router,
+};
+use openhuman_embed::__host::security::credentials::{AuthService, APP_SESSION_PROVIDER};
+use std::sync::{Arc, Mutex};
+use tempfile::TempDir;
+
+async fn catalog_server(status: StatusCode, body: &'static str) -> (String, Arc<Mutex<Vec<Option<String>>>>) {
+ let authorization = Arc::new(Mutex::new(Vec::new()));
+ let captured = Arc::clone(&authorization);
+ let app = Router::new().route(
+ "/openai/v1/models",
+ get(move |headers: HeaderMap| {
+ let captured = Arc::clone(&captured);
+ async move {
+ captured.lock().unwrap().push(
+ headers
+ .get(axum::http::header::AUTHORIZATION)
+ .and_then(|value| value.to_str().ok())
+ .map(str::to_owned),
+ );
+ (status, body)
+ }
+ }),
+ );
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+ (format!("http://{address}"), authorization)
+}
+
+fn catalog_config(tmp: &TempDir, base_url: &str) -> Config {
+ crate::hosted::test_support::config(tmp, base_url)
+}
+
+fn without_session(config: &Config) {
+ crate::hosted::test_support::store_session(config, "fixture-session-to-remove");
+ AuthService::from_config(config)
+ .remove_profile(APP_SESSION_PROVIDER, "default")
+ .expect("remove fixture session");
+}
#[test]
fn a_managed_401_on_an_attached_session_reads_as_signed_out() {
- assert!(managed_401_means_signed_out(401, true));
+ assert!(managed_401_means_signed_out(Some(401), true));
+ assert!(!managed_401_means_signed_out(None, true));
}
/// A 401 on a request that never carried the session token describes the
/// request (a misconfigured URL), not the session, so the error surfaces.
#[test]
fn a_401_without_an_attached_session_still_surfaces() {
- assert!(!managed_401_means_signed_out(401, false));
+ assert!(!managed_401_means_signed_out(Some(401), false));
}
#[test]
fn other_statuses_still_surface_the_error() {
for status in [400, 403, 404, 429, 500, 503] {
assert!(
- !managed_401_means_signed_out(status, true),
+ !managed_401_means_signed_out(Some(status), true),
"managed {status}"
);
}
@@ -54,12 +98,6 @@ fn limits_request_lists_the_catalog_keyed_by_the_inference_base() {
.is_some_and(|url| url.ends_with("/openai/v1/models?catalog=openrouter")));
}
-#[test]
-fn truncate_caps_long_text_with_an_ellipsis() {
- assert_eq!(truncate("abc", 5), "abc");
- assert_eq!(truncate("abcdef", 3), "abc...");
-}
-
#[test]
fn a_live_session_wins_over_the_provider_key() {
assert_eq!(
@@ -93,3 +131,78 @@ fn with_neither_credential_the_catalog_is_empty() {
ListingAuth::Empty("session expired")
);
}
+
+#[tokio::test]
+async fn managed_catalog_treats_http_401_as_signed_out_only_for_an_attached_session() {
+ let (base_url, authorization) =
+ catalog_server(StatusCode::UNAUTHORIZED, "session token rejected").await;
+ let tmp = TempDir::new().unwrap();
+ let config = catalog_config(&tmp, &base_url);
+ crate::hosted::test_support::store_session(&config, "fixture-live-session");
+
+ let result = list_models(
+ &config,
+ CatalogRequest {
+ provider_key: String::new(),
+ client: reqwest::Client::new(),
+ },
+ )
+ .await
+ .expect("a rejected attached session degrades to an empty catalog");
+
+ assert_eq!(result.value["models"], serde_json::json!([]));
+ assert_eq!(
+ authorization.lock().unwrap().as_slice(),
+ [Some("Bearer fixture-live-session".to_string())]
+ );
+}
+
+#[tokio::test]
+async fn managed_catalog_keeps_provider_key_401_as_a_provider_error() {
+ let (base_url, authorization) =
+ catalog_server(StatusCode::UNAUTHORIZED, "provider key rejected").await;
+ let tmp = TempDir::new().unwrap();
+ let config = catalog_config(&tmp, &base_url);
+ without_session(&config);
+
+ let error = list_models(
+ &config,
+ CatalogRequest {
+ provider_key: "fixture-provider-key".into(),
+ client: reqwest::Client::new(),
+ },
+ )
+ .await
+ .expect_err("a 401 for a provider key remains actionable");
+
+ assert!(error.contains("provider returned 401"), "{error}");
+ assert_eq!(
+ authorization.lock().unwrap().as_slice(),
+ [Some("Bearer fixture-provider-key".to_string())]
+ );
+}
+
+#[tokio::test]
+async fn managed_catalog_does_not_infer_http_status_from_error_payload_text() {
+ let (base_url, _authorization) = catalog_server(
+ StatusCode::OK,
+ r#"{"error":"401 session expired"}"#,
+ )
+ .await;
+ let tmp = TempDir::new().unwrap();
+ let config = catalog_config(&tmp, &base_url);
+ crate::hosted::test_support::store_session(&config, "fixture-live-session");
+
+ let error = list_models(
+ &config,
+ CatalogRequest {
+ provider_key: String::new(),
+ client: reqwest::Client::new(),
+ },
+ )
+ .await
+ .expect_err("a successful error envelope is not an HTTP 401");
+
+ assert!(error.contains("provider returned error payload"), "{error}");
+ assert!(error.contains("401 session expired"), "{error}");
+}