Skip to content

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

refactor(inference): move openai-compatible http surface upstream

Steven Enamakel6ecc95805043
diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.toml
index eef5a85036..36664b2985 100644
--- a/crates/openhuman-core/Cargo.toml
+++ b/crates/openhuman-core/Cargo.toml
@@ -611,9 +611,9 @@ default = ["media", "skills", "flows", "mcp", "channels", "http-server", "schedu
#
# `web_chat`'s event payload types (`WebChannelEvent`, `TurnUsagePayload`, …)
# stay compiled in BOTH builds, since ~10 always-on domains construct them.
-# Likewise `inference::http::types` and `EXTERNAL_OPENAI_COMPAT_PROVIDER` stay
+# Likewise `EXTERNAL_OPENAI_COMPAT_PROVIDER` stays
# compiled for the server's auth policy.
-http-server = ["dep:axum"]
+http-server = ["dep:axum", "tinyinference-llm/server-http"]
# The public inference gate is retained for host feature compatibility.
# Native permission probes execute through the TinyComputer module.
inference = ["modules"]
diff --git a/crates/openhuman-core/src/inference/http/backend.rs b/crates/openhuman-core/src/inference/http/backend.rs
new file mode 100644
index 0000000000..499bab57d9
--- /dev/null
+++ b/crates/openhuman-core/src/inference/http/backend.rs
@@ -0,0 +1,155 @@
+//! Host [`ChatBackend`] for the OpenAI-compatible `/v1` endpoint.
+//!
+//! The generic handlers (wire types, SSE framing, error envelope) live in
+//! `tinyinference_llm::providers::openai::server_http`. This adapter only
+//! resolves a request's `model` against OpenHuman's `Config` and the provider
+//! factory, and lists the configured models.
+//!
+//! ## Provider routing
+//!
+//! - `"ollama:<model>"` or a bare model name -> local Ollama
+//! - `"<slug>:<model>"` -> cloud provider entry by slug
+//! - `"openhuman"` -> OpenHuman backend (session JWT)
+
+use async_trait::async_trait;
+use tinyinference_llm::providers::openai::server_http::{
+ strip_temperature_suffix, BackendFailure, ChatBackend, ListedModel, ResolvedChat,
+};
+use tracing::{debug, warn};
+
+use crate::config::Config;
+
+const LOG_PREFIX: &str = "[inference::http]";
+
+/// Resolves `/v1` requests against the loaded OpenHuman [`Config`].
+pub(super) struct HostChatBackend;
+
+/// Bare model names (no `:`, not the `openhuman` sentinel) are local Ollama models.
+pub(super) fn provider_string_for(model: &str) -> String {
+ if model.contains(':') || model == "openhuman" {
+ model.to_string()
+ } else {
+ format!("ollama:{model}")
+ }
+}
+
+#[async_trait]
+impl ChatBackend for HostChatBackend {
+ async fn resolve(
+ &self,
+ model: &str,
+ temperature: Option<f64>,
+ ) -> Result<ResolvedChat, BackendFailure> {
+ let config = Config::load_or_init().await.map_err(|e| {
+ warn!("{LOG_PREFIX} resolve: config load failed: {e}");
+ BackendFailure::internal(format!("config load failed: {e}"))
+ })?;
+ let provider_string = provider_string_for(model);
+ let raw = temperature.unwrap_or(config.default_temperature);
+ let (chat_model, model_id) =
+ crate::inference::provider::create_chat_model_from_string_with_model_id(
+ "agentic",
+ &provider_string,
+ &config,
+ raw,
+ )
+ .map_err(|e| {
+ warn!("{LOG_PREFIX} resolve: provider build failed: {e}");
+ BackendFailure::invalid_request(format!("provider error: {e}"))
+ })?;
+
+ // Reasoning models reject `temperature`; the provider layer omits it on
+ // the wire, so only log the drop here.
+ let suppressed = tinyinference_llm::model::effective_temperature(
+ &model_id,
+ Some(raw),
+ None,
+ &config.temperature_unsupported_models,
+ );
+ if suppressed.is_none() && temperature.is_some() {
+ warn!(
+ model = %model_id,
+ requested_temperature = raw,
+ "{LOG_PREFIX} dropping caller-supplied temperature — model is on temperature_unsupported_models list"
+ );
+ }
+ Ok(ResolvedChat {
+ chat_model,
+ model_id,
+ temperature: raw,
+ })
+ }
+
+ async fn list_models(&self) -> Result<Vec<ListedModel>, BackendFailure> {
+ let config = Config::load_or_init().await.map_err(|e| {
+ warn!("{LOG_PREFIX} models: config load failed: {e}");
+ BackendFailure::internal(format!("config load failed: {e}"))
+ })?;
+ let models = configured_models(&config);
+ debug!(model_count = models.len(), "{LOG_PREFIX} models: ok");
+ Ok(models)
+ }
+}
+
+/// Every model the config advertises (duplicates are removed upstream).
+pub(super) fn configured_models(config: &Config) -> Vec<ListedModel> {
+ let mut out = Vec::new();
+ let mut push = |id: String, owned_by: &str| out.push(ListedModel::new(id, owned_by));
+
+ // Stable managed-router sentinel: OpenHuman keeps selecting the effective
+ // upstream model from the current routing config.
+ push("openhuman".to_string(), "openhuman");
+
+ if let Some(default_model) = config
+ .default_model
+ .as_deref()
+ .map(str::trim)
+ .filter(|model| !model.is_empty())
+ {
+ push(strip_temperature_suffix(default_model).to_string(), "openhuman");
+ }
+
+ for cp in &config.cloud_providers {
+ if let Some(ref model) = cp.default_model {
+ push(
+ format!("{}:{}", cp.slug, strip_temperature_suffix(model)),
+ &cp.slug,
+ );
+ }
+ }
+
+ if !config.local_ai.chat_model_id.is_empty() {
+ push(format!("ollama:{}", config.local_ai.chat_model_id), "ollama");
+ }
+
+ for provider_string in [
+ config.chat_provider.as_deref(),
+ config.reasoning_provider.as_deref(),
+ config.agentic_provider.as_deref(),
+ config.coding_provider.as_deref(),
+ config.vision_provider.as_deref(),
+ config.memory_provider.as_deref(),
+ config.embeddings_provider.as_deref(),
+ ]
+ .into_iter()
+ .flatten()
+ .map(str::trim)
+ .filter(|value| !value.is_empty() && *value != "cloud" && *value != "openhuman")
+ {
+ if let Some(model) = provider_string.strip_prefix("ollama:") {
+ push(
+ format!("ollama:{}", strip_temperature_suffix(model)),
+ "ollama",
+ );
+ } else if let Some((slug, model)) = provider_string.split_once(':') {
+ if slug != "openhuman" {
+ push(format!("{slug}:{}", strip_temperature_suffix(model)), slug);
+ }
+ }
+ }
+ out
+}
+
+#[cfg(test)]
+#[path = "backend_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/inference/http/backend_tests.rs b/crates/openhuman-core/src/inference/http/backend_tests.rs
new file mode 100644
index 0000000000..e84591ab42
--- /dev/null
+++ b/crates/openhuman-core/src/inference/http/backend_tests.rs
@@ -0,0 +1,22 @@
+use super::*;
+
+#[test]
+fn bare_model_names_route_to_ollama() {
+ assert_eq!(provider_string_for("llama3"), "ollama:llama3");
+ assert_eq!(provider_string_for("ollama:llama3"), "ollama:llama3");
+ assert_eq!(provider_string_for("acme:gpt-4o"), "acme:gpt-4o");
+ assert_eq!(provider_string_for("openhuman"), "openhuman");
+}
+
+#[test]
+fn configured_models_lists_sentinel_and_strips_temperature_suffix() {
+ let mut config = Config::default();
+ config.default_model = Some("[email protected]".to_string());
+ config.chat_provider = Some("acme:claude@1".to_string());
+ config.local_ai.chat_model_id = "qwen".to_string();
+ let ids: Vec<String> = configured_models(&config).into_iter().map(|m| m.id).collect();
+ assert_eq!(ids[0], "openhuman");
+ assert!(ids.contains(&"gpt-4o".to_string()));
+ assert!(ids.contains(&"acme:claude".to_string()));
+ assert!(ids.contains(&"ollama:qwen".to_string()));
+}
diff --git a/crates/openhuman-core/src/inference/http/http_tests.rs b/crates/openhuman-core/src/inference/http/http_tests.rs
deleted file mode 100644
index a290826595..0000000000
--- a/crates/openhuman-core/src/inference/http/http_tests.rs
+++ /dev/null
@@ -1,48 +0,0 @@
-//! Unit tests for the OpenAI-compatible `/v1` handler helpers. Route and
-//! auth-layer tests live with the router in `openhuman-rpc`
-//! (`server/http/inference_route_tests.rs`).
-
-use crate::inference::http::server::strip_temperature_suffix;
-
-#[test]
-fn strip_temperature_suffix_only_removes_numeric_suffixes() {
- assert_eq!(strip_temperature_suffix("[email protected]"), "gpt-4o");
- assert_eq!(strip_temperature_suffix("llama3.1:8b@1"), "llama3.1:8b");
- assert_eq!(strip_temperature_suffix("gpt@beta"), "gpt@beta");
-}
-
-/// Asserts that `ChatCompletionRequest` parses `max_completion_tokens` and respects
-/// fallback precedence over `max_tokens` (Refs #5498).
-#[test]
-fn test_chat_completion_request_deserializes_max_completion_tokens() {
- use crate::inference::http::types::ChatCompletionRequest;
-
- let json_both = serde_json::json!({
- "model": "gpt-5",
- "messages": [{ "role": "user", "content": "hello" }],
- "max_tokens": 100,
- "max_completion_tokens": 200
- });
- let parsed: ChatCompletionRequest = serde_json::from_value(json_both).unwrap();
- assert_eq!(parsed.max_tokens, Some(100));
- assert_eq!(parsed.max_completion_tokens, Some(200));
- assert_eq!(
- parsed.max_completion_tokens.or(parsed.max_tokens),
- Some(200)
- );
-
- let json_legacy = serde_json::json!({
- "model": "gpt-4o",
- "messages": [{ "role": "user", "content": "hello" }],
- "max_tokens": 150
- });
- let parsed_legacy: ChatCompletionRequest = serde_json::from_value(json_legacy).unwrap();
- assert_eq!(parsed_legacy.max_tokens, Some(150));
- assert_eq!(parsed_legacy.max_completion_tokens, None);
- assert_eq!(
- parsed_legacy
- .max_completion_tokens
- .or(parsed_legacy.max_tokens),
- Some(150)
- );
-}
diff --git a/crates/openhuman-core/src/inference/http/mod.rs b/crates/openhuman-core/src/inference/http/mod.rs
index f3be178fd8..006610fa0e 100644
--- a/crates/openhuman-core/src/inference/http/mod.rs
+++ b/crates/openhuman-core/src/inference/http/mod.rs
@@ -1,10 +1,12 @@
//! OpenAI-compatible HTTP endpoint at `/v1/chat/completions` and `/v1/models`.
//!
-//! ## Mounting
-//!
-//! The router is mounted by `crates/openhuman-rpc/src/server/http/mod.rs`:
+//! The wire types and handlers live upstream in
+//! `tinyinference_llm::providers::openai::server_http` (feature `server-http`).
+//! OpenHuman keeps the host side: [`backend::HostChatBackend`] resolves models
+//! against `Config`, and the router is mounted by
+//! `crates/openhuman-rpc/src/server/http/mod.rs`:
//! ```ignore
-//! .nest("/v1", crate::inference::http::router())
+//! .nest("/v1", crate::core_host::inference::http::router())
//! ```
//! It inherits the core bearer-token auth middleware, but `/v1/*` also accepts
//! a stable user-managed external API key so local harnesses can treat
@@ -18,14 +20,18 @@
/// secret encrypted at rest and scoped to the active user workspace.
pub const EXTERNAL_OPENAI_COMPAT_PROVIDER: &str = "external-openai-compat";
-// The `/v1/*` axum router lives here and is exclusive to the `http-server`
-// feature (#5048). CARVE-OUT: `EXTERNAL_OPENAI_COMPAT_PROVIDER` (above) and
-// `types` stay UNGATED — `core::auth` consumes the provider id (and its inert
-// request/response types are dep-free) in ALL builds, so only the axum
-// `server`/`router` surface is gated.
+// The axum surface is exclusive to the `http-server` feature (#5048).
+// `EXTERNAL_OPENAI_COMPAT_PROVIDER` stays ungated: `core::auth` reads it in all builds.
#[cfg(feature = "http-server")]
-pub mod server;
-pub mod types;
+mod backend;
+/// Build the `/v1` axum sub-router over the host [`backend::HostChatBackend`].
#[cfg(feature = "http-server")]
-pub use server::router;
+pub fn router<S>() -> axum::Router<S>
+where
+ S: Clone + Send + Sync + 'static,
+{
+ tinyinference_llm::providers::openai::server_http::router(std::sync::Arc::new(
+ backend::HostChatBackend,
+ ))
+}
diff --git a/crates/openhuman-core/src/inference/http/server.rs b/crates/openhuman-core/src/inference/http/server.rs
deleted file mode 100644
index c92c283c50..0000000000
--- a/crates/openhuman-core/src/inference/http/server.rs
+++ /dev/null
@@ -1,397 +0,0 @@
-//! OpenAI-compatible HTTP handlers for `/v1/chat/completions` and `/v1/models`.
-//!
-//! ## Mounting
-//!
-//! The router returned by [`router()`] is merged into the core axum server
-//! in `crates/openhuman-rpc/src/server/http/mod.rs` via `.nest("/v1", inference::http::router())`.
-//! It reuses the same bearer-token auth middleware that guards `/rpc`.
-//!
-//! ## Authentication
-//!
-//! All routes accept `Authorization: Bearer <token>`, but the token may be
-//! either:
-//! - the per-launch `OPENHUMAN_CORE_TOKEN` used by the desktop shell, or
-//! - a stable user-managed external API key stored under
-//! `EXTERNAL_OPENAI_COMPAT_PROVIDER` for local harnesses.
-//!
-//! Missing or wrong tokens get a `401 Unauthorized` from the shared middleware.
-//!
-//! ## Provider routing
-//!
-//! The `model` field in the request selects the provider:
-//! - `"ollama:<model>"` or a bare model name → local Ollama
-//! - `"<slug>:<model>"` → cloud provider entry by slug
-//! - everything else → OpenHuman backend (session JWT)
-
-use axum::http::StatusCode;
-use axum::response::sse::{Event, KeepAlive, Sse};
-use axum::response::{IntoResponse, Response};
-use axum::routing::{get, post};
-use axum::{extract::State, Json, Router};
-use futures_util::stream::{self, StreamExt};
-use serde_json::json;
-use std::collections::HashSet;
-use std::sync::atomic::{AtomicBool, Ordering};
-use std::sync::Arc;
-use tinyinference_llm::message::Message;
-use tinyinference_llm::model::{ModelRequest, ModelStreamItem};
-use tracing::{debug, warn};
-
-use super::types::{
- ChatCompletionChoice, ChatCompletionChunk, ChatCompletionChunkChoice, ChatCompletionDelta,
- ChatCompletionMessage, ChatCompletionRequest, ChatCompletionResponse, ChatCompletionUsage,
- ModelObject, ModelsResponse,
-};
-use crate::config::Config;
-use crate::core::types::AppState;
-
-const LOG_PREFIX: &str = "[inference::http]";
-
-/// Build the `/v1` axum sub-router.
-pub fn router() -> Router<AppState> {
- Router::new()
- .route("/chat/completions", post(chat_completions_handler))
- .route("/models", get(models_handler))
-}
-
-/// `POST /v1/chat/completions`
-///
-/// Accepts an OpenAI-compatible request body. Routes through the unified
-/// `Provider` trait — local (Ollama) for `ollama:*` model names, cloud otherwise.
-async fn chat_completions_handler(
- State(_state): State<AppState>,
- Json(req): Json<ChatCompletionRequest>,
-) -> Response {
- debug!(
- model = %req.model,
- stream = req.stream,
- message_count = req.messages.len(),
- "{LOG_PREFIX} chat_completions: start"
- );
-
- let config = match Config::load_or_init().await {
- Ok(c) => c,
- Err(e) => {
- warn!("{LOG_PREFIX} chat_completions: config load failed: {e}");
- return (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(json!({ "error": { "message": format!("config load failed: {e}"), "type": "internal_error" }})),
- )
- .into_response();
- }
- };
-
- // Build provider string from model name.
- // If the model already looks like a provider string, use it directly.
- // Otherwise treat a bare model name as an Ollama model.
- let provider_string = if req.model.starts_with("ollama:")
- || req.model.contains(':')
- || req.model == "openhuman"
- {
- req.model.clone()
- } else {
- // Bare model name (no colon) — route to Ollama local runtime.
- format!("ollama:{}", req.model)
- };
-
- let (chat_model, model_id) =
- match crate::inference::provider::create_chat_model_from_string_with_model_id(
- "agentic",
- &provider_string,
- &config,
- req.temperature.unwrap_or(config.default_temperature),
- ) {
- Ok(pair) => pair,
- Err(e) => {
- warn!("{LOG_PREFIX} chat_completions: provider build failed: {e}");
- return (
- StatusCode::BAD_REQUEST,
- Json(json!({ "error": { "message": format!("provider error: {e}"), "type": "invalid_request_error" }})),
- )
- .into_response();
- }
- };
-
- // Map the OpenAI-compatible wire messages directly into crate messages.
- let messages: Vec<Message> = req
- .messages
- .iter()
- .map(|message| match message.role.as_str() {
- "system" => Message::system(&message.content),
- "assistant" => Message::assistant(&message.content),
- "tool" => Message::tool("external-tool-call", &message.content),
- _ => Message::user(&message.content),
- })
- .collect();
-
- // If the caller supplied a temperature but the model is on the unsupported
- // list, log a warning and drop it — sending temperature to o1/o3/o4/gpt-5
- // reasoning models causes an API error. The provider layer applies the same
- // check on the outbound body, so this is belt-and-suspenders for logging.
- let temperature = {
- let raw = req.temperature.unwrap_or(config.default_temperature);
- let suppressed = tinyinference_llm::model::effective_temperature(
- &model_id,
- Some(raw),
- None,
- &config.temperature_unsupported_models,
- );
- if suppressed.is_none() && req.temperature.is_some() {
- tracing::warn!(
- model = %model_id,
- requested_temperature = req.temperature.unwrap_or(0.0),
- "{LOG_PREFIX} dropping caller-supplied temperature — model is on temperature_unsupported_models list"
- );
- }
- raw // the Provider layer handles omission; we pass the value through
- };
- let completion_id = format!("chatcmpl-{}", uuid::Uuid::new_v4());
- let created = chrono::Utc::now().timestamp();
- let model_name = req.model.clone();
- let mut model_request = ModelRequest::new(messages)
- .with_model(model_id.clone())
- .with_temperature(temperature);
- if let Some(tokens) = req.max_completion_tokens.or(req.max_tokens) {
- model_request = model_request.with_max_tokens(tokens);
- }
-
- if req.stream {
- let model_stream = match chat_model.stream(&(), model_request).await {
- Ok(stream) => stream,
- Err(e) => {
- warn!(error = %e, model = %model_id, "{LOG_PREFIX} chat_completions: stream start failed");
- return (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(json!({ "error": { "message": format!("inference error: {e}"), "type": "internal_error" }})),
- )
- .into_response();
- }
- };
-
- let cid = completion_id.clone();
- let model_clone = model_name.clone();
- let first_delta = Arc::new(AtomicBool::new(true));
- let event_stream = model_stream
- .filter_map(move |item| {
- let cid = cid.clone();
- let model_clone = model_clone.clone();
- let first_delta = Arc::clone(&first_delta);
- async move {
- let (content, finish_reason) = match item {
- ModelStreamItem::MessageDelta(delta) if !delta.text.is_empty() => {
- (Some(delta.text), None)
- }
- ModelStreamItem::Completed(_) => (None, Some("stop")),
- ModelStreamItem::Failed(message) => {
- let body = json!({"error": {"message": message, "type": "stream_error"}});
- return Some(Ok::<Event, std::convert::Infallible>(
- Event::default().data(body.to_string()),
- ));
- }
- ModelStreamItem::ProviderFailed(error) => {
- let body = json!({"error": {"message": error.message, "type": "stream_error"}});
- return Some(Ok::<Event, std::convert::Infallible>(
- Event::default().data(body.to_string()),
- ));
- }
- _ => return None,
- };
- let role = first_delta
- .swap(false, Ordering::Relaxed)
- .then(|| "assistant".to_string());
- let sse_chunk = ChatCompletionChunk {
- id: cid,
- object: "chat.completion.chunk",
- created,
- model: model_clone,
- choices: vec![ChatCompletionChunkChoice {
- index: 0,
- delta: ChatCompletionDelta {
- role,
- content,
- },
- finish_reason,
- }],
- };
- let data =
- serde_json::to_string(&sse_chunk).unwrap_or_else(|_| "{}".to_string());
- Some(Ok::<Event, std::convert::Infallible>(
- Event::default().data(data),
- ))
- }
- })
- .chain(stream::once(async {
- Ok::<Event, std::convert::Infallible>(Event::default().data("[DONE]"))
- }));
-
- debug!("{LOG_PREFIX} chat_completions: streaming response started");
- return Sse::new(event_stream)
- .keep_alive(KeepAlive::default())
- .into_response();
- }
-
- match chat_model.invoke(&(), model_request).await {
- Ok(model_response) => {
- debug!("{LOG_PREFIX} chat_completions: non-streaming ok");
- let usage = model_response.usage.unwrap_or_default();
- let response = ChatCompletionResponse {
- id: completion_id,
- object: "chat.completion",
- created,
- model: model_name,
- choices: vec![ChatCompletionChoice {
- index: 0,
- message: ChatCompletionMessage {
- role: "assistant".to_string(),
- content: model_response.text(),
- },
- finish_reason: "stop",
- }],
- usage: ChatCompletionUsage {
- prompt_tokens: usage.input_tokens,
- completion_tokens: usage.output_tokens,
- total_tokens: usage.total_tokens,
- },
- };
- (StatusCode::OK, Json(response)).into_response()
- }
- Err(e) => {
- warn!("{LOG_PREFIX} chat_completions: inference failed: {e}");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(json!({ "error": { "message": format!("inference error: {e}"), "type": "internal_error" }})),
- )
- .into_response()
- }
- }
-}
-
-/// `GET /v1/models`
-///
-/// Lists all configured models (local Ollama + cloud providers).
-async fn models_handler(State(_state): State<AppState>) -> Response {
- debug!("{LOG_PREFIX} models: start");
-
- let config = match Config::load_or_init().await {
- Ok(c) => c,
- Err(e) => {
- warn!("{LOG_PREFIX} models: config load failed: {e}");
- return (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(json!({ "error": { "message": format!("config load failed: {e}") }})),
- )
- .into_response();
- }
- };
-
- let created = chrono::Utc::now().timestamp();
- let mut data: Vec<ModelObject> = Vec::new();
- let mut seen: HashSet<String> = HashSet::new();
-
- let mut push_model = |id: String, owned_by: String| {
- if seen.insert(id.clone()) {
- data.push(ModelObject {
- id,
- object: "model",
- created,
- owned_by,
- });
- }
- };
-
- // Stable managed-router sentinel for callers that want OpenHuman to keep
- // selecting the effective upstream model based on the current routing config.
- push_model("openhuman".to_string(), "openhuman".to_string());
-
- if let Some(default_model) = config
- .default_model
- .as_deref()
- .map(str::trim)
- .filter(|model| !model.is_empty())
- {
- push_model(
- strip_temperature_suffix(default_model).to_string(),
- "openhuman".to_string(),
- );
- }
-
- // Cloud provider default models
- for cp in &config.cloud_providers {
- if let Some(ref model) = cp.default_model {
- push_model(
- format!("{}:{}", cp.slug, strip_temperature_suffix(model)),
- cp.slug.clone(),
- );
- }
- }
-
- // Configured local chat model (Ollama)
- if !config.local_ai.chat_model_id.is_empty() {
- push_model(
- format!("ollama:{}", config.local_ai.chat_model_id),
- "ollama".to_string(),
- );
- }
-
- for provider_string in [
- config.chat_provider.as_deref(),
- config.reasoning_provider.as_deref(),
- config.agentic_provider.as_deref(),
- config.coding_provider.as_deref(),
- config.vision_provider.as_deref(),
- config.memory_provider.as_deref(),
- config.embeddings_provider.as_deref(),
- ]
- .into_iter()
- .flatten()
- .map(str::trim)
- .filter(|value| !value.is_empty() && *value != "cloud")
- {
- if provider_string == "openhuman" {
- continue;
- }
-
- if let Some(model) = provider_string.strip_prefix("ollama:") {
- push_model(
- format!("ollama:{}", strip_temperature_suffix(model)),
- "ollama".to_string(),
- );
- continue;
- }
-
- if let Some((slug, model)) = provider_string.split_once(':') {
- if slug != "openhuman" {
- push_model(
- format!("{}:{}", slug, strip_temperature_suffix(model)),
- slug.to_string(),
- );
- }
- }
- }
-
- debug!(model_count = data.len(), "{LOG_PREFIX} models: ok");
- (
- StatusCode::OK,
- Json(ModelsResponse {
- object: "list",
- data,
- }),
- )
- .into_response()
-}
-
-pub(crate) fn strip_temperature_suffix(model: &str) -> &str {
- let trimmed = model.trim();
- let Some((head, tail)) = trimmed.rsplit_once('@') else {
- return trimmed;
- };
- if tail.parse::<f64>().is_ok() {
- head.trim()
- } else {
- trimmed
- }
-}
-
-#[cfg(test)]
-#[path = "http_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/inference/http/types.rs b/crates/openhuman-core/src/inference/http/types.rs
deleted file mode 100644
index 206e046986..0000000000
--- a/crates/openhuman-core/src/inference/http/types.rs
+++ /dev/null
@@ -1,102 +0,0 @@
-//! OpenAI-compatible HTTP request / response types.
-
-use serde::{Deserialize, Serialize};
-
-// ── Chat Completions ──────────────────────────────────────────────────────────
-
-/// Request payload for OpenAI-compatible chat completions (`POST /v1/chat/completions`).
-#[derive(Debug, Deserialize)]
-pub struct ChatCompletionRequest {
- /// Identifier of the model to query.
- pub model: String,
- /// List of input messages in conversation order.
- pub messages: Vec<ChatCompletionMessage>,
- /// Whether to stream back partial progress via SSE chunks.
- #[serde(default)]
- pub stream: bool,
- /// Sampling temperature between 0.0 and 2.0.
- #[serde(default)]
- pub temperature: Option<f64>,
- /// Legacy maximum tokens limit (superseded by `max_completion_tokens`).
- #[serde(default)]
- pub max_tokens: Option<u32>,
- /// Maximum number of output tokens for newer OpenAI / reasoning models (#5498).
- #[serde(default)]
- pub max_completion_tokens: Option<u32>,
- /// Optional tool definitions (ignored if the provider doesn't support them).
- #[serde(default)]
- pub tools: Option<serde_json::Value>,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct ChatCompletionMessage {
- pub role: String,
- pub content: String,
-}
-
-#[derive(Debug, Serialize)]
-pub struct ChatCompletionResponse {
- pub id: String,
- pub object: &'static str,
- pub created: i64,
- pub model: String,
- pub choices: Vec<ChatCompletionChoice>,
- pub usage: ChatCompletionUsage,
-}
-
-#[derive(Debug, Serialize)]
-pub struct ChatCompletionChoice {
- pub index: u32,
- pub message: ChatCompletionMessage,
- pub finish_reason: &'static str,
-}
-
-#[derive(Debug, Serialize)]
-pub struct ChatCompletionUsage {
- pub prompt_tokens: u64,
- pub completion_tokens: u64,
- pub total_tokens: u64,
-}
-
-// ── Streaming (SSE) ───────────────────────────────────────────────────────────
-
-#[derive(Debug, Serialize)]
-pub struct ChatCompletionChunk {
- pub id: String,
- pub object: &'static str,
- pub created: i64,
- pub model: String,
- pub choices: Vec<ChatCompletionChunkChoice>,
-}
-
-#[derive(Debug, Serialize)]
-pub struct ChatCompletionChunkChoice {
- pub index: u32,
- pub delta: ChatCompletionDelta,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub finish_reason: Option<&'static str>,
-}
-
-#[derive(Debug, Serialize)]
-pub struct ChatCompletionDelta {
- #[serde(skip_serializing_if = "Option::is_none")]
- pub role: Option<String>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub content: Option<String>,
-}
-
-// ── Models ────────────────────────────────────────────────────────────────────
-
-#[derive(Debug, Serialize)]
-pub struct ModelsResponse {
- pub object: &'static str,
- pub data: Vec<ModelObject>,
-}
-
-#[derive(Debug, Serialize)]
-pub struct ModelObject {
- pub id: String,
- pub object: &'static str,
- pub created: i64,
- pub owned_by: String,
-}