Skip to content

Commit c5865a0

Browse files
fylornclaude
andcommitted
feat: add /v1/responses endpoint for OpenAI Responses API
- Add POST /v1/responses proxy handler with input/instructions parsing, content filtering, and response format conversion - Supports both string and message array input formats - Converts responses to OpenAI Responses API output format - Update configuration guide page to show /v1/responses in supported endpoints - Add i18n keys for the new endpoint (en + zh) Gateway now supports three API formats: - /v1/chat/completions (OpenAI Chat, used by Cursor/Continue/Cline) - /v1/messages (Anthropic Messages, used by Claude Code) - /v1/responses (OpenAI Responses, new 2025 format) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent 0dfa507 commit c5865a0

5 files changed

Lines changed: 159 additions & 0 deletions

File tree

‎crates/gateway/src/proxy.rs‎

Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -332,6 +332,156 @@ fn convert_to_anthropic_response(
332332
})
333333
}
334334

335+
/// POST /v1/responses
336+
///
337+
/// OpenAI Responses API (new format, 2025+). Supports tool use, multi-turn,
338+
/// and structured outputs natively. AgentBastion proxies this by converting
339+
/// to internal ChatCompletionRequest format, routing through the same
340+
/// provider pipeline, then converting the response back.
341+
///
342+
/// For providers that support the Responses API natively (OpenAI), this
343+
/// could be a direct passthrough in the future.
344+
pub async fn proxy_responses(
345+
State(state): State<GatewayState>,
346+
_headers: HeaderMap,
347+
Json(body): Json<serde_json::Value>,
348+
) -> Result<axum::response::Response, GatewayErrorResponse> {
349+
let model = body
350+
.get("model")
351+
.and_then(|v| v.as_str())
352+
.ok_or_else(|| GatewayError::TransformError("Missing 'model' field".into()))?
353+
.to_string();
354+
355+
let is_stream = body
356+
.get("stream")
357+
.and_then(|v| v.as_bool())
358+
.unwrap_or(false);
359+
360+
let mapped_model = state.model_mapper.map(&model);
361+
362+
// Extract messages from the "input" field (Responses API format)
363+
// Input can be a string or an array of messages
364+
let mut messages = Vec::new();
365+
366+
if let Some(instructions) = body.get("instructions").and_then(|v| v.as_str()) {
367+
messages.push(crate::providers::traits::ChatMessage {
368+
role: "system".to_string(),
369+
content: serde_json::Value::String(instructions.to_string()),
370+
});
371+
}
372+
373+
match body.get("input") {
374+
Some(serde_json::Value::String(s)) => {
375+
messages.push(crate::providers::traits::ChatMessage {
376+
role: "user".to_string(),
377+
content: serde_json::Value::String(s.clone()),
378+
});
379+
}
380+
Some(serde_json::Value::Array(arr)) => {
381+
for item in arr {
382+
// Each item can be a message object or a string
383+
if let Some(s) = item.as_str() {
384+
messages.push(crate::providers::traits::ChatMessage {
385+
role: "user".to_string(),
386+
content: serde_json::Value::String(s.to_string()),
387+
});
388+
} else if let (Some(role), Some(content)) = (
389+
item.get("role").and_then(|v| v.as_str()),
390+
item.get("content"),
391+
) {
392+
messages.push(crate::providers::traits::ChatMessage {
393+
role: role.to_string(),
394+
content: content.clone(),
395+
});
396+
}
397+
}
398+
}
399+
_ => {
400+
return Err(
401+
GatewayError::TransformError("Missing or invalid 'input' field".into()).into(),
402+
);
403+
}
404+
}
405+
406+
// Content filter
407+
if let Err(filter_result) = state.content_filter.check(&messages) {
408+
tracing::warn!("Content filter triggered: {filter_result}");
409+
return Err(GatewayError::TransformError(format!(
410+
"Request blocked by content filter: {filter_result}"
411+
))
412+
.into());
413+
}
414+
415+
let max_tokens = body
416+
.get("max_output_tokens")
417+
.and_then(|v| v.as_u64())
418+
.unwrap_or(4096) as u32;
419+
420+
let request = crate::providers::traits::ChatCompletionRequest {
421+
model: mapped_model.clone(),
422+
messages,
423+
temperature: body.get("temperature").and_then(|v| v.as_f64()),
424+
max_tokens: Some(max_tokens),
425+
stream: Some(is_stream),
426+
extra: serde_json::json!({}),
427+
};
428+
429+
// Route to provider
430+
let provider = state.router.route(&mapped_model).ok_or_else(|| {
431+
GatewayError::ProviderError(format!("No provider found for model: {mapped_model}"))
432+
})?;
433+
434+
if is_stream {
435+
let stream = provider.stream_chat_completion(request);
436+
Ok(stream_to_sse(stream).into_response())
437+
} else {
438+
let response = provider.chat_completion_boxed(request).await?;
439+
let responses_format = convert_to_responses_format(&response);
440+
Ok(Json(responses_format).into_response())
441+
}
442+
}
443+
444+
/// Convert an internal ChatCompletionResponse to OpenAI Responses API format.
445+
fn convert_to_responses_format(
446+
resp: &crate::providers::traits::ChatCompletionResponse,
447+
) -> serde_json::Value {
448+
let mut output = Vec::new();
449+
450+
for choice in &resp.choices {
451+
let text = choice.message.content.as_str().unwrap_or("").to_string();
452+
output.push(serde_json::json!({
453+
"type": "message",
454+
"id": format!("msg_{}", uuid::Uuid::new_v4()),
455+
"status": "completed",
456+
"role": "assistant",
457+
"content": [{
458+
"type": "output_text",
459+
"text": text,
460+
}],
461+
}));
462+
}
463+
464+
let (input_tokens, output_tokens) = resp
465+
.usage
466+
.as_ref()
467+
.map(|u| (u.prompt_tokens, u.completion_tokens))
468+
.unwrap_or((0, 0));
469+
470+
serde_json::json!({
471+
"id": resp.id,
472+
"object": "response",
473+
"created_at": resp.created,
474+
"status": "completed",
475+
"model": resp.model,
476+
"output": output,
477+
"usage": {
478+
"input_tokens": input_tokens,
479+
"output_tokens": output_tokens,
480+
"total_tokens": input_tokens + output_tokens,
481+
}
482+
})
483+
}
484+
335485
// ---------- Error adapter ----------
336486

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

‎crates/server/src/app.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,7 @@ pub async fn create_gateway_app(
143143
"/v1/messages",
144144
post(gateway_proxy::proxy_anthropic_messages),
145145
)
146+
.route("/v1/responses", post(gateway_proxy::proxy_responses))
146147
.route("/v1/models", get(gateway_proxy::list_models_handler))
147148
.layer(axum::middleware::from_fn_with_state(
148149
state.clone(),

‎web/src/i18n/en.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -422,6 +422,7 @@
422422
"supportedEndpoints": "Supported Endpoints",
423423
"openaiEndpoint": "OpenAI-compatible: /v1/chat/completions",
424424
"anthropicEndpoint": "Anthropic Messages: /v1/messages",
425+
"responsesEndpoint": "OpenAI Responses (new): /v1/responses",
425426
"modelsEndpoint": "List models: /v1/models"
426427
},
427428
"notFound": {

‎web/src/i18n/zh.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -422,6 +422,7 @@
422422
"supportedEndpoints": "支持的端点",
423423
"openaiEndpoint": "OpenAI 兼容:/v1/chat/completions",
424424
"anthropicEndpoint": "Anthropic Messages:/v1/messages",
425+
"responsesEndpoint": "OpenAI Responses(新版):/v1/responses",
425426
"modelsEndpoint": "模型列表:/v1/models"
426427
},
427428
"notFound": {

‎web/src/routes/gateway/guide.tsx‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -395,6 +395,12 @@ export function GuidePage() {
395395
</Badge>
396396
{t('guide.anthropicEndpoint')}
397397
</p>
398+
<p>
399+
<Badge variant="outline" className="mr-2 font-mono text-xs">
400+
POST
401+
</Badge>
402+
{t('guide.responsesEndpoint')}
403+
</p>
398404
<p>
399405
<Badge variant="outline" className="mr-2 font-mono text-xs">
400406
GET

0 commit comments

Comments
 (0)