Skip to content

Commit 0dfa507

Browse files
fylornclaude
andcommitted
feat: add /v1/messages endpoint, provider loading, and AI tool config guide
- Load providers from database into ModelRouter at gateway startup (resolves empty router bug — requests now route to configured providers) - Add POST /v1/messages endpoint for Anthropic Messages API passthrough (enables Claude Code, Anthropic SDK, and native Anthropic API clients) - Auto-register default model prefixes (claude-, gpt-, gemini-) when no specific models are configured for a provider - Add Configuration Guide page with setup instructions for: Claude Code, Cursor, Continue, Cline, OpenAI SDK, Anthropic SDK, cURL - Add guide route to sidebar navigation under AI Gateway Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent 75a2999 commit 0dfa507

7 files changed

Lines changed: 763 additions & 3 deletions

File tree

‎crates/gateway/src/proxy.rs‎

Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,161 @@ pub async fn list_models_handler(State(state): State<GatewayState>) -> Json<serd
177177
}))
178178
}
179179

180+
/// POST /v1/messages
181+
///
182+
/// Anthropic Messages API passthrough. Used by Claude Code and other tools
183+
/// that speak the Anthropic native format. Routes to the provider registered
184+
/// for the requested model, forwarding the request as-is to the Anthropic
185+
/// upstream (no format conversion needed).
186+
///
187+
/// This endpoint also applies content filtering, quota checks, and audit
188+
/// logging, but does NOT do PII redaction or caching (complex content types).
189+
pub async fn proxy_anthropic_messages(
190+
State(state): State<GatewayState>,
191+
_headers: HeaderMap,
192+
Json(body): Json<serde_json::Value>,
193+
) -> Result<axum::response::Response, GatewayErrorResponse> {
194+
let model = body
195+
.get("model")
196+
.and_then(|v| v.as_str())
197+
.ok_or_else(|| GatewayError::TransformError("Missing 'model' field".into()))?
198+
.to_string();
199+
200+
let is_stream = body
201+
.get("stream")
202+
.and_then(|v| v.as_bool())
203+
.unwrap_or(false);
204+
205+
// Apply model mapping
206+
let mapped_model = state.model_mapper.map(&model);
207+
208+
// Content filter — check user messages
209+
if let Some(messages) = body.get("messages").and_then(|v| v.as_array()) {
210+
let chat_messages: Vec<crate::providers::traits::ChatMessage> = messages
211+
.iter()
212+
.filter_map(|m| {
213+
Some(crate::providers::traits::ChatMessage {
214+
role: m.get("role")?.as_str()?.to_string(),
215+
content: m.get("content").cloned().unwrap_or(serde_json::Value::Null),
216+
})
217+
})
218+
.collect();
219+
220+
if let Err(filter_result) = state.content_filter.check(&chat_messages) {
221+
tracing::warn!("Content filter triggered: {filter_result}");
222+
return Err(GatewayError::TransformError(format!(
223+
"Request blocked by content filter: {filter_result}"
224+
))
225+
.into());
226+
}
227+
}
228+
229+
// Route to provider
230+
let provider = state.router.route(&mapped_model).ok_or_else(|| {
231+
GatewayError::ProviderError(format!("No provider found for model: {mapped_model}"))
232+
})?;
233+
234+
// For Anthropic providers, we can access the underlying provider details.
235+
// Build the upstream request by forwarding the body as-is.
236+
// We need the provider's base_url and api_key — use the DynAiProvider
237+
// to make a direct Anthropic API call.
238+
239+
// Convert to OpenAI format internally, let the provider handle the rest
240+
let max_tokens = body
241+
.get("max_tokens")
242+
.and_then(|v| v.as_u64())
243+
.unwrap_or(4096) as u32;
244+
245+
// Build a ChatCompletionRequest from the Anthropic body
246+
let mut messages = Vec::new();
247+
if let Some(system) = body.get("system").and_then(|v| v.as_str()) {
248+
messages.push(crate::providers::traits::ChatMessage {
249+
role: "system".to_string(),
250+
content: serde_json::Value::String(system.to_string()),
251+
});
252+
}
253+
if let Some(msg_array) = body.get("messages").and_then(|v| v.as_array()) {
254+
for m in msg_array {
255+
if let (Some(role), Some(content)) =
256+
(m.get("role").and_then(|v| v.as_str()), m.get("content"))
257+
{
258+
messages.push(crate::providers::traits::ChatMessage {
259+
role: role.to_string(),
260+
content: content.clone(),
261+
});
262+
}
263+
}
264+
}
265+
266+
let request = crate::providers::traits::ChatCompletionRequest {
267+
model: mapped_model.clone(),
268+
messages,
269+
temperature: body.get("temperature").and_then(|v| v.as_f64()),
270+
max_tokens: Some(max_tokens),
271+
stream: Some(is_stream),
272+
extra: serde_json::json!({}),
273+
};
274+
275+
if is_stream {
276+
let stream = provider.stream_chat_completion(request);
277+
Ok(stream_to_sse(stream).into_response())
278+
} else {
279+
let response = provider.chat_completion_boxed(request).await?;
280+
281+
// Convert OpenAI response back to Anthropic format
282+
let anthropic_response = convert_to_anthropic_response(&response);
283+
Ok(Json(anthropic_response).into_response())
284+
}
285+
}
286+
287+
/// Convert an OpenAI-format response back to Anthropic Messages API format.
288+
fn convert_to_anthropic_response(
289+
resp: &crate::providers::traits::ChatCompletionResponse,
290+
) -> serde_json::Value {
291+
let content: Vec<serde_json::Value> = resp
292+
.choices
293+
.iter()
294+
.map(|c| {
295+
let text = c.message.content.as_str().unwrap_or("").to_string();
296+
serde_json::json!({
297+
"type": "text",
298+
"text": text,
299+
})
300+
})
301+
.collect();
302+
303+
let stop_reason = resp
304+
.choices
305+
.first()
306+
.and_then(|c| c.finish_reason.as_deref())
307+
.map(|r| match r {
308+
"stop" => "end_turn",
309+
"length" => "max_tokens",
310+
other => other,
311+
})
312+
.unwrap_or("end_turn");
313+
314+
let (input_tokens, output_tokens) = resp
315+
.usage
316+
.as_ref()
317+
.map(|u| (u.prompt_tokens, u.completion_tokens))
318+
.unwrap_or((0, 0));
319+
320+
serde_json::json!({
321+
"id": resp.id,
322+
"type": "message",
323+
"role": "assistant",
324+
"model": resp.model,
325+
"content": content,
326+
"stop_reason": stop_reason,
327+
"stop_sequence": null,
328+
"usage": {
329+
"input_tokens": input_tokens,
330+
"output_tokens": output_tokens,
331+
}
332+
})
333+
}
334+
180335
// ---------- Error adapter ----------
181336

182337
/// Newtype wrapper so we can implement `IntoResponse` for `GatewayError`.

‎crates/server/src/app.rs‎

Lines changed: 101 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,12 @@ pub async fn create_gateway_app(
113113
};
114114

115115
// AI Gateway: /v1/*
116-
let model_router = Arc::new(ModelRouter::new());
116+
// Load providers from database and register them in the model router
117+
let mut model_router = ModelRouter::new();
118+
if let Err(e) = load_providers_into_router(&state, &mut model_router).await {
119+
tracing::error!("Failed to load providers: {e}");
120+
}
121+
let model_router = Arc::new(model_router);
117122
let gateway_state = GatewayState {
118123
router: model_router,
119124
model_mapper: Arc::new(ModelMapper::new()),
@@ -134,6 +139,10 @@ pub async fn create_gateway_app(
134139
"/v1/chat/completions",
135140
post(gateway_proxy::proxy_chat_completion),
136141
)
142+
.route(
143+
"/v1/messages",
144+
post(gateway_proxy::proxy_anthropic_messages),
145+
)
137146
.route("/v1/models", get(gateway_proxy::list_models_handler))
138147
.layer(axum::middleware::from_fn_with_state(
139148
state.clone(),
@@ -408,3 +417,94 @@ pub fn create_console_app(config: &AppConfig, state: AppState) -> Router {
408417

409418
security_layers(app)
410419
}
420+
421+
// ---------------------------------------------------------------------------
422+
// Provider loading from database
423+
// ---------------------------------------------------------------------------
424+
425+
/// Default model prefix patterns for known provider types.
426+
fn default_model_prefixes(provider_type: &str) -> Vec<&'static str> {
427+
match provider_type {
428+
"openai" => vec!["gpt-", "o1-", "o3-", "o4-", "chatgpt-"],
429+
"anthropic" => vec!["claude-"],
430+
"google" => vec!["gemini-"],
431+
_ => vec![],
432+
}
433+
}
434+
435+
/// Load all active providers from the database, instantiate the appropriate
436+
/// provider implementation, and register them in the model router.
437+
async fn load_providers_into_router(
438+
state: &AppState,
439+
router: &mut ModelRouter,
440+
) -> anyhow::Result<()> {
441+
use agent_bastion_gateway::providers::{
442+
anthropic::AnthropicProvider, custom::CustomProvider, google::GoogleProvider,
443+
openai::OpenAiProvider,
444+
};
445+
446+
let providers = sqlx::query_as::<_, agent_bastion_common::models::Provider>(
447+
"SELECT * FROM providers WHERE is_active = true AND deleted_at IS NULL",
448+
)
449+
.fetch_all(&state.db)
450+
.await?;
451+
452+
let encryption_key =
453+
agent_bastion_common::crypto::parse_encryption_key(&state.config.encryption_key)?;
454+
455+
for provider in &providers {
456+
let api_key_bytes =
457+
agent_bastion_common::crypto::decrypt(&provider.api_key_encrypted, &encryption_key)?;
458+
let api_key = String::from_utf8(api_key_bytes)?;
459+
460+
let dyn_provider: Arc<dyn agent_bastion_gateway::providers::DynAiProvider> =
461+
match provider.provider_type.as_str() {
462+
"openai" => Arc::new(OpenAiProvider::new(provider.base_url.clone(), api_key)),
463+
"anthropic" => Arc::new(AnthropicProvider::new(provider.base_url.clone(), api_key)),
464+
"google" => Arc::new(GoogleProvider::new(provider.base_url.clone(), api_key)),
465+
_ => Arc::new(CustomProvider::new(
466+
provider.name.clone(),
467+
provider.base_url.clone(),
468+
api_key,
469+
)),
470+
};
471+
472+
// Register models from the models table
473+
let models = sqlx::query_scalar::<_, String>(
474+
"SELECT model_id FROM models WHERE provider_id = $1 AND is_active = true",
475+
)
476+
.bind(provider.id)
477+
.fetch_all(&state.db)
478+
.await?;
479+
480+
if models.is_empty() {
481+
// No specific models registered — use default prefixes
482+
for prefix in default_model_prefixes(&provider.provider_type) {
483+
router.register_provider(prefix, Arc::clone(&dyn_provider));
484+
}
485+
} else {
486+
for model_id in &models {
487+
router.register_provider(model_id, Arc::clone(&dyn_provider));
488+
}
489+
}
490+
491+
tracing::info!(
492+
provider = %provider.name,
493+
provider_type = %provider.provider_type,
494+
model_count = if models.is_empty() {
495+
default_model_prefixes(&provider.provider_type).len()
496+
} else {
497+
models.len()
498+
},
499+
"Provider loaded"
500+
);
501+
}
502+
503+
tracing::info!(
504+
total_providers = providers.len(),
505+
total_routes = router.list_models().len(),
506+
"All providers loaded into model router"
507+
);
508+
509+
Ok(())
510+
}

‎web/src/components/layout/app-sidebar.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import {
2626
Shield,
2727
Settings,
2828
Forward,
29+
BookOpen,
2930
} from 'lucide-react';
3031
import { useNavigate, useLocation } from '@tanstack/react-router';
3132

@@ -54,6 +55,7 @@ const navGroups: NavGroup[] = [
5455
{ titleKey: 'nav.models', icon: BrainCircuit, href: '/gateway/models' },
5556
{ titleKey: 'nav.apiKeys', icon: Key, href: '/gateway/api-keys' },
5657
{ titleKey: 'nav.requestLogs', icon: ScrollText, href: '/gateway/logs' },
58+
{ titleKey: 'nav.configGuide', icon: BookOpen, href: '/gateway/guide' },
5759
],
5860
},
5961
{

‎web/src/i18n/en.json‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,8 @@
4848
"users": "Users",
4949
"roles": "Roles",
5050
"settings": "Settings",
51-
"logForwarders": "Log Forwarding"
51+
"logForwarders": "Log Forwarding",
52+
"configGuide": "Configuration Guide"
5253
},
5354
"auth": {
5455
"signIn": "Sign in",
@@ -403,6 +404,26 @@
403404
"editForwarder": "Edit Forwarder",
404405
"editDescription": "Update forwarder name and configuration."
405406
},
407+
"guide": {
408+
"title": "Configuration Guide",
409+
"subtitle": "Configure your AI tools to use AgentBastion as the API gateway",
410+
"gatewayUrl": "Gateway URL",
411+
"apiKeyNote": "Replace the API key with your actual key from AI Gateway > API Keys",
412+
"claudeCode": "Claude Code",
413+
"cursor": "Cursor",
414+
"continue": "Continue",
415+
"cline": "Cline",
416+
"openaiSdk": "OpenAI SDK",
417+
"anthropicSdk": "Anthropic SDK",
418+
"curl": "cURL",
419+
"steps": "Configuration Steps",
420+
"copyCode": "Copy",
421+
"copied": "Copied!",
422+
"supportedEndpoints": "Supported Endpoints",
423+
"openaiEndpoint": "OpenAI-compatible: /v1/chat/completions",
424+
"anthropicEndpoint": "Anthropic Messages: /v1/messages",
425+
"modelsEndpoint": "List models: /v1/models"
426+
},
406427
"notFound": {
407428
"title": "404",
408429
"message": "Page not found"

‎web/src/i18n/zh.json‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,8 @@
4848
"users": "用户",
4949
"roles": "角色",
5050
"settings": "设置",
51-
"logForwarders": "日志转发"
51+
"logForwarders": "日志转发",
52+
"configGuide": "配置指南"
5253
},
5354
"auth": {
5455
"signIn": "登录",
@@ -403,6 +404,26 @@
403404
"editForwarder": "编辑转发器",
404405
"editDescription": "更新转发器名称和配置。"
405406
},
407+
"guide": {
408+
"title": "配置指南",
409+
"subtitle": "配置您的 AI 工具通过 AgentBastion 网关访问 API",
410+
"gatewayUrl": "网关地址",
411+
"apiKeyNote": "请将 API Key 替换为您在 AI Gateway > API Keys 中创建的实际密钥",
412+
"claudeCode": "Claude Code",
413+
"cursor": "Cursor",
414+
"continue": "Continue",
415+
"cline": "Cline",
416+
"openaiSdk": "OpenAI SDK",
417+
"anthropicSdk": "Anthropic SDK",
418+
"curl": "cURL",
419+
"steps": "配置步骤",
420+
"copyCode": "复制",
421+
"copied": "已复制!",
422+
"supportedEndpoints": "支持的端点",
423+
"openaiEndpoint": "OpenAI 兼容:/v1/chat/completions",
424+
"anthropicEndpoint": "Anthropic Messages:/v1/messages",
425+
"modelsEndpoint": "模型列表:/v1/models"
426+
},
406427
"notFound": {
407428
"title": "404",
408429
"message": "页面未找到"

0 commit comments

Comments
 (0)