mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-26 16:01:13 +00:00
refactor(gateway)!: isolate Chat conversion from native protocols
Route native requests only to providers that support their wire protocol. Convert Chat Completions directly to Responses, Messages or GenAI while preserving the shared request lifecycle and native continuation ownership. Remove provider-side cross-protocol adaptation outside compat modules and update protocol, provider, routing and delivery regression coverage. Validation: workspace fmt and strict Clippy; 4,741 tests passed, none skipped. Live-tested native Codex, AGY and Grok harnesses plus Chat JSON/SSE and tools. BREAKING CHANGE: Built-in cross-protocol conversion is available only through Chat Completions. Native callers must use a matching provider protocol. Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
@@ -17,7 +17,7 @@
|
||||
</div>
|
||||
|
||||
> [!NOTE]
|
||||
> 生成请求支持 [OpenAI Responses](docs/api.md#responses-请求与传输)、[Chat Completions](docs/api.md#chat-completions-请求) 和 [Anthropic Messages](docs/api.md#messages-请求) 三种协议
|
||||
> 原生生成支持 [OpenAI Responses](docs/api.md#responses-请求与传输)、[Anthropic Messages](docs/api.md#messages-请求) 和 [GenAI](docs/api.md#antigravity-客户端原生生成);[Chat Completions](docs/api.md#chat-completions-请求) 直接转换到所选账号协议,其他跨协议转换不内置
|
||||
|
||||
## 快速预览
|
||||
|
||||
|
||||
Generated
+2
@@ -1950,7 +1950,9 @@ dependencies = [
|
||||
"memchr",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"thiserror",
|
||||
"url",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
|
||||
@@ -159,7 +159,6 @@ async fn model_responses(
|
||||
middleware_body,
|
||||
},
|
||||
Some(authorization),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
Ok(plugin_response(response))
|
||||
|
||||
@@ -1,320 +1,158 @@
|
||||
//! Chat 出口持有协议投影缓冲 提交与资源回收始终委托原受管正文
|
||||
//! Chat 出口只编码已转换的错误,不另建正文或提交状态机
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use axum::body::to_bytes;
|
||||
use bytes::Bytes;
|
||||
use futures::future::BoxFuture;
|
||||
use gateway_core::{
|
||||
engine::middleware::{
|
||||
MiddlewareBody, MiddlewareError, MiddlewareFrame, MiddlewareFraming, MiddlewareHeader,
|
||||
MiddlewareResponse,
|
||||
},
|
||||
error::{GatewayError, GatewayErrorKind},
|
||||
};
|
||||
use gateway_protocol::openai::sse::{DONE_SSE_FRAME, SseEvent, SseEventDecoder, sse_frame_is_done};
|
||||
use gateway_core::event::{GatewayEvent, ProviderEvent};
|
||||
use gateway_protocol::openai::sse::{parse_sse_events, sse_frame_is_done};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::client_error::ProtocolErrorBody;
|
||||
use crate::data_plane::middleware::error_response;
|
||||
|
||||
use super::response::{ChatIdentity, ChatStreamEncoder, project_response};
|
||||
|
||||
pub(super) fn project_middleware_response(
|
||||
response: MiddlewareResponse,
|
||||
identity: ChatIdentity,
|
||||
streaming: bool,
|
||||
include_usage: bool,
|
||||
) -> MiddlewareResponse {
|
||||
if !(200..300).contains(&response.status_code()) {
|
||||
return response;
|
||||
}
|
||||
let (protocol, status, mut headers, body, envelope) = response.into_parts();
|
||||
// 投影改变正文长度和表示形式 不继承 Responses 的实体长度或编码
|
||||
headers.retain(|header| {
|
||||
!["content-length", "content-type", "content-encoding"]
|
||||
.iter()
|
||||
.any(|name| header.name().eq_ignore_ascii_case(name))
|
||||
});
|
||||
headers.push(MiddlewareHeader::new(
|
||||
"content-type",
|
||||
Bytes::from_static(if streaming {
|
||||
b"text/event-stream"
|
||||
} else {
|
||||
b"application/json"
|
||||
}),
|
||||
));
|
||||
let projection = if streaming {
|
||||
Projection::Stream(Box::new(StreamProjection {
|
||||
encoder: ChatStreamEncoder::new(identity, include_usage),
|
||||
decoder: SseEventDecoder::default(),
|
||||
done_received: false,
|
||||
}))
|
||||
} else {
|
||||
Projection::Json(identity)
|
||||
};
|
||||
let mut response = MiddlewareResponse::new(
|
||||
protocol,
|
||||
status,
|
||||
headers,
|
||||
Box::new(ChatBody {
|
||||
inner: Some(body),
|
||||
projection,
|
||||
pending: VecDeque::new(),
|
||||
committed: false,
|
||||
finished: false,
|
||||
}),
|
||||
);
|
||||
if let Some(envelope) = envelope {
|
||||
response = response.with_envelope(envelope);
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
pub(super) fn chat_error_frame(data: &Value) -> Bytes {
|
||||
pub(in crate::data_plane) fn chat_error_frame(data: &Value) -> Bytes {
|
||||
let error = data
|
||||
.pointer("/response/error")
|
||||
.or_else(|| data.get("error"));
|
||||
.or_else(|| data.get("error"))
|
||||
.unwrap_or(data);
|
||||
Bytes::from(format!("data: {}\n\n", serde_json::json!({"error": error})))
|
||||
}
|
||||
|
||||
enum Projection {
|
||||
Json(ChatIdentity),
|
||||
Stream(Box<StreamProjection>),
|
||||
}
|
||||
|
||||
impl Projection {
|
||||
fn terminal_seen(&self) -> bool {
|
||||
matches!(self, Self::Stream(stream) if stream.terminal_seen())
|
||||
pub(in crate::data_plane) fn validate_response(bytes: &[u8]) -> Result<(), ()> {
|
||||
let value: Value = serde_json::from_slice(bytes).map_err(|_| ())?;
|
||||
if value.get("object").and_then(Value::as_str) != Some("chat.completion")
|
||||
|| value.get("id").and_then(Value::as_str).is_none()
|
||||
|| !value
|
||||
.get("choices")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|choices| {
|
||||
choices.len() == 1
|
||||
&& choices[0].get("message").is_some_and(Value::is_object)
|
||||
&& choices[0]
|
||||
.get("finish_reason")
|
||||
.is_some_and(Value::is_string)
|
||||
})
|
||||
{
|
||||
return Err(());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct StreamProjection {
|
||||
encoder: ChatStreamEncoder,
|
||||
decoder: SseEventDecoder,
|
||||
done_received: bool,
|
||||
/// finish 与 usage 必须随原生 Completed 交付,避免终结失败后已向客户端报成功
|
||||
#[derive(Default)]
|
||||
pub(in crate::data_plane) struct ChatEncoder {
|
||||
terminal: Vec<Bytes>,
|
||||
pub(in crate::data_plane) completed: bool,
|
||||
pub(in crate::data_plane) failed: bool,
|
||||
}
|
||||
|
||||
impl StreamProjection {
|
||||
fn terminal_seen(&self) -> bool {
|
||||
self.encoder.is_completed() || self.encoder.has_wire_failure()
|
||||
}
|
||||
|
||||
fn project(&mut self, events: Vec<SseEvent>) -> Result<Vec<Bytes>, MiddlewareError> {
|
||||
impl ChatEncoder {
|
||||
pub(in crate::data_plane) fn push(&mut self, event: &ProviderEvent) -> Vec<Bytes> {
|
||||
let mut output = Vec::new();
|
||||
for event in events {
|
||||
if self.done_received {
|
||||
return Err(invalid_response());
|
||||
}
|
||||
let data = serde_json::from_str(&event.data).map_err(|_| invalid_response())?;
|
||||
// codec 区分辅助事件与终态后的业务输出 交付层不再维护一份事件分类
|
||||
output.extend(
|
||||
self.encoder
|
||||
.push_event(event.event.as_deref(), &data)
|
||||
.map_err(projection_error)?,
|
||||
);
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
}
|
||||
|
||||
struct ChatBody {
|
||||
inner: Option<Box<dyn MiddlewareBody>>,
|
||||
projection: Projection,
|
||||
pending: VecDeque<MiddlewareFrame>,
|
||||
committed: bool,
|
||||
finished: bool,
|
||||
}
|
||||
|
||||
impl ChatBody {
|
||||
async fn read_one(&mut self) -> Result<(), MiddlewareError> {
|
||||
let inner = self.inner.as_mut().ok_or(MiddlewareError::InvalidState)?;
|
||||
let Some(frame) = inner.next_frame().await? else {
|
||||
if let Projection::Stream(stream) = &mut self.projection {
|
||||
let events = stream.decoder.finish().map_err(|_| invalid_response())?;
|
||||
let frames = stream.project(events)?;
|
||||
if !frames.is_empty() || !stream.done_received || !inner.is_finalized() {
|
||||
return Err(invalid_response());
|
||||
}
|
||||
self.pending.push_back(done_frame());
|
||||
}
|
||||
self.finished = true;
|
||||
return Ok(());
|
||||
};
|
||||
let transformed = frame.transformed();
|
||||
let (bytes, framing, terminal, envelope) = frame.into_parts();
|
||||
let output = match &mut self.projection {
|
||||
Projection::Json(identity) => {
|
||||
if framing != MiddlewareFraming::JsonDocument || !terminal {
|
||||
return Err(invalid_response());
|
||||
}
|
||||
let value = serde_json::from_slice(&bytes).map_err(|_| invalid_response())?;
|
||||
let value = project_response(&value, identity).map_err(projection_error)?;
|
||||
vec![MiddlewareFrame::new(
|
||||
Bytes::from(serde_json::to_vec(&value).map_err(|_| invalid_response())?),
|
||||
MiddlewareFraming::JsonDocument,
|
||||
true,
|
||||
)]
|
||||
}
|
||||
Projection::Stream(stream) => {
|
||||
if framing != MiddlewareFraming::SseEvent {
|
||||
return Err(invalid_response());
|
||||
}
|
||||
let events = stream
|
||||
.decoder
|
||||
.push(&bytes)
|
||||
.map_err(|_| invalid_response())?;
|
||||
let output = stream.project(events)?;
|
||||
// 共用 SSE 解码器只返回业务事件 DONE 由受管正文的控制帧单独确认
|
||||
if std::str::from_utf8(&bytes).is_ok_and(sse_frame_is_done) {
|
||||
if stream.done_received || !stream.terminal_seen() {
|
||||
return Err(invalid_response());
|
||||
}
|
||||
stream.done_received = true;
|
||||
}
|
||||
if terminal && !stream.done_received {
|
||||
return Err(invalid_response());
|
||||
}
|
||||
output
|
||||
.into_iter()
|
||||
.map(|bytes| MiddlewareFrame::new(bytes, MiddlewareFraming::SseEvent, false))
|
||||
.collect()
|
||||
}
|
||||
};
|
||||
let mut output: VecDeque<_> = output
|
||||
.into_iter()
|
||||
.map(|frame| frame.with_transformed(transformed))
|
||||
.collect();
|
||||
if let Some(envelope) = envelope
|
||||
&& let Some(last) = output.pop_back()
|
||||
if let Some(wire) = event
|
||||
.wire_event()
|
||||
.filter(|wire| wire.protocol() == gateway_protocol::chat_completions::CHAT_PROTOCOL)
|
||||
{
|
||||
output.push_back(last.with_envelope(envelope));
|
||||
}
|
||||
self.pending.extend(output);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn verify_terminal(&mut self) -> Result<(), MiddlewareError> {
|
||||
while !self.finished {
|
||||
self.read_one().await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn fail_stream(&mut self, error: MiddlewareError) {
|
||||
self.pending.clear();
|
||||
if let Some(inner) = self.inner.take() {
|
||||
inner.close().await;
|
||||
}
|
||||
let response = error_response(error);
|
||||
let bytes = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
let value = serde_json::from_slice(&bytes).unwrap_or_else(|_| {
|
||||
serde_json::json!({"error": {
|
||||
"type": "server_error", "code": "invalid_upstream_response",
|
||||
"message": "The gateway could not deliver the Chat response."
|
||||
}})
|
||||
});
|
||||
self.pending.push_back(MiddlewareFrame::new(
|
||||
chat_error_frame(&value),
|
||||
MiddlewareFraming::SseEvent,
|
||||
false,
|
||||
));
|
||||
self.pending.push_back(done_frame());
|
||||
self.finished = true;
|
||||
}
|
||||
}
|
||||
|
||||
impl MiddlewareBody for ChatBody {
|
||||
fn next_frame(&mut self) -> BoxFuture<'_, Result<Option<MiddlewareFrame>, MiddlewareError>> {
|
||||
Box::pin(async move {
|
||||
while self.pending.is_empty() && !self.finished {
|
||||
let result = match self.read_one().await {
|
||||
Ok(()) if self.committed && self.projection.terminal_seen() => {
|
||||
self.verify_terminal().await
|
||||
}
|
||||
result => result,
|
||||
};
|
||||
if let Err(error) = result {
|
||||
if !self.committed {
|
||||
return Err(error);
|
||||
}
|
||||
self.fail_stream(error).await;
|
||||
self.failed |= wire.data().get("error").is_some_and(Value::is_object);
|
||||
let bytes = wire.raw_sse_frame().cloned().or_else(|| {
|
||||
wire.has_json_data()
|
||||
.then(|| Bytes::from(format!("data: {}\n\n", wire.data())))
|
||||
});
|
||||
if let Some(bytes) = bytes {
|
||||
if wire
|
||||
.data()
|
||||
.pointer("/choices/0/finish_reason")
|
||||
.is_some_and(Value::is_string)
|
||||
|| wire
|
||||
.data()
|
||||
.get("choices")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(Vec::is_empty)
|
||||
{
|
||||
self.terminal.push(bytes);
|
||||
} else {
|
||||
output.push(bytes);
|
||||
}
|
||||
}
|
||||
Ok(self.pending.pop_front())
|
||||
})
|
||||
}
|
||||
if event
|
||||
.canonical_facts()
|
||||
.iter()
|
||||
.any(|fact| matches!(fact, GatewayEvent::Completed(_)))
|
||||
{
|
||||
self.completed = true;
|
||||
output.append(&mut self.terminal);
|
||||
}
|
||||
output
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(in crate::data_plane) struct ChatDeliveryValidator {
|
||||
id: Option<String>,
|
||||
finished: bool,
|
||||
done: bool,
|
||||
}
|
||||
|
||||
impl ChatDeliveryValidator {
|
||||
pub(in crate::data_plane) fn response_id(&self) -> Option<&str> {
|
||||
self.id.as_deref()
|
||||
}
|
||||
|
||||
fn commit_downstream(
|
||||
&mut self,
|
||||
client_status_code: Option<u16>,
|
||||
) -> BoxFuture<'_, Result<(), MiddlewareError>> {
|
||||
Box::pin(async move {
|
||||
self.inner
|
||||
.as_mut()
|
||||
.ok_or(MiddlewareError::InvalidState)?
|
||||
.commit_downstream(client_status_code)
|
||||
.await?;
|
||||
self.committed = true;
|
||||
// HTTP 尚未发送首帧 即使首批已经包含 finish 或 usage 也先确认原会话完成结算
|
||||
if self.projection.terminal_seen()
|
||||
&& let Err(error) = self.verify_terminal().await
|
||||
{
|
||||
// 原会话已提交 不能把已记录的 200 改成另一 HTTP 状态
|
||||
// 首个 Chat 帧为 role 或 error 成功终态仍在 pending 内可安全撤回
|
||||
self.fail_stream(error).await;
|
||||
pub(in crate::data_plane) fn validate_frame(&mut self, bytes: &[u8]) -> Result<(), ()> {
|
||||
if self.done {
|
||||
return Err(());
|
||||
}
|
||||
let text = std::str::from_utf8(bytes).map_err(|_| ())?;
|
||||
if sse_frame_is_done(text) {
|
||||
if !self.finished {
|
||||
return Err(());
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
self.done = true;
|
||||
return Ok(());
|
||||
}
|
||||
for event in parse_sse_events(text).map_err(|_| ())? {
|
||||
let value: Value = serde_json::from_str(&event.data).map_err(|_| ())?;
|
||||
if value.get("error").is_some_and(Value::is_object) {
|
||||
self.finished = true;
|
||||
continue;
|
||||
}
|
||||
if value.get("object").and_then(Value::as_str) != Some("chat.completion.chunk") {
|
||||
return Err(());
|
||||
}
|
||||
let id = value.get("id").and_then(Value::as_str).ok_or(())?;
|
||||
// 首帧必须留有提交锚点,终态不能替代被中间件移除的首个业务帧
|
||||
if self.id.is_none()
|
||||
&& value
|
||||
.pointer("/choices/0/finish_reason")
|
||||
.is_some_and(Value::is_string)
|
||||
{
|
||||
return Err(());
|
||||
}
|
||||
if self.id.as_deref().is_some_and(|expected| expected != id) {
|
||||
return Err(());
|
||||
}
|
||||
self.id.get_or_insert_with(|| id.to_owned());
|
||||
let choices = value.get("choices").and_then(Value::as_array).ok_or(())?;
|
||||
if choices.is_empty() {
|
||||
if !self.finished || !value.get("usage").is_some_and(Value::is_object) {
|
||||
return Err(());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if self.finished
|
||||
|| choices.len() != 1
|
||||
|| choices[0].get("index").and_then(Value::as_u64) != Some(0)
|
||||
{
|
||||
return Err(());
|
||||
}
|
||||
self.finished = choices[0]
|
||||
.get("finish_reason")
|
||||
.is_some_and(Value::is_string);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn record_client_status(&mut self, status: u16) -> BoxFuture<'_, Result<(), MiddlewareError>> {
|
||||
match self.inner.as_mut() {
|
||||
Some(inner) => inner.record_client_status(status),
|
||||
None => Box::pin(async { Ok(()) }),
|
||||
pub(in crate::data_plane) fn finish_delivery(&self) -> Result<(), ()> {
|
||||
if self.finished && self.done {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(())
|
||||
}
|
||||
}
|
||||
|
||||
fn is_finalized(&self) -> bool {
|
||||
self.inner.as_ref().is_none_or(|inner| inner.is_finalized())
|
||||
}
|
||||
|
||||
fn close(mut self: Box<Self>) -> BoxFuture<'static, ()> {
|
||||
let inner = self.inner.take();
|
||||
Box::pin(async move {
|
||||
if let Some(inner) = inner {
|
||||
inner.close().await;
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn projection_error(error: ProtocolErrorBody) -> MiddlewareError {
|
||||
MiddlewareError::Gateway(
|
||||
GatewayError::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"The gateway could not project the upstream response to Chat Completions.",
|
||||
)
|
||||
.with_client_code(error.error.code),
|
||||
)
|
||||
}
|
||||
|
||||
fn invalid_response() -> MiddlewareError {
|
||||
MiddlewareError::Gateway(
|
||||
GatewayError::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"The gateway could not deliver the Chat response.",
|
||||
)
|
||||
.with_client_code("invalid_upstream_response"),
|
||||
)
|
||||
}
|
||||
|
||||
fn done_frame() -> MiddlewareFrame {
|
||||
MiddlewareFrame::new(
|
||||
Bytes::from_static(DONE_SSE_FRAME.as_bytes()),
|
||||
MiddlewareFraming::SseEvent,
|
||||
true,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
//! Chat HTTP 入口只规范化协议 共用 Responses 的执行与交付链路
|
||||
//! Chat HTTP 入口保留原始协议,由目标 Provider 直接转换
|
||||
|
||||
use std::{net::SocketAddr, time::SystemTime};
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use axum::{
|
||||
body::Bytes,
|
||||
extract::{Extension, State, connect_info::ConnectInfo},
|
||||
http::{HeaderMap, StatusCode, header::CONTENT_ENCODING},
|
||||
http::{
|
||||
HeaderMap, StatusCode,
|
||||
header::{CONTENT_ENCODING, CONTENT_LENGTH},
|
||||
},
|
||||
response::Response,
|
||||
};
|
||||
use gateway_core::operation::{GenerateRequest, Operation, ProtocolPayload};
|
||||
use gateway_protocol::chat_completions::{self, CHAT_PROTOCOL};
|
||||
|
||||
use crate::ApiState;
|
||||
use crate::data_plane::{
|
||||
@@ -15,24 +20,17 @@ use crate::data_plane::{
|
||||
body::{RequestDecodeError, decompress_request_body},
|
||||
error::{gateway_error_response, protocol_error_response},
|
||||
generation::{
|
||||
DecodedGenerationRequest, GenerationEndpoint, GenerationHttpRequest, HttpResponseAdapter,
|
||||
execute_prepared_generation,
|
||||
ContinuationIntent, DecodedGenerationRequest, GenerationEndpoint, GenerationHttpRequest,
|
||||
GenerationRequestMetadata, execute_prepared_generation,
|
||||
},
|
||||
responses::decode_request_with_headers,
|
||||
router::CHAT_COMPLETIONS_PATH,
|
||||
};
|
||||
|
||||
use super::{
|
||||
delivery::{chat_error_frame, project_middleware_response},
|
||||
request::convert_request,
|
||||
response::ChatIdentity,
|
||||
responses::OpenAiRequestHeaders,
|
||||
};
|
||||
|
||||
pub(in crate::data_plane) async fn chat_completions(
|
||||
State(state): State<ApiState>,
|
||||
connect_info: Option<Extension<ConnectInfo<SocketAddr>>>,
|
||||
ingress_id: Option<Extension<tower_http::request_id::RequestId>>,
|
||||
headers: HeaderMap,
|
||||
mut headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> Response {
|
||||
let service = state.data_plane().clone();
|
||||
@@ -40,12 +38,17 @@ pub(in crate::data_plane) async fn chat_completions(
|
||||
Ok(client) => client,
|
||||
Err(error) => return client_access_error_response(error),
|
||||
};
|
||||
let (decoded, middleware_body, include_usage) = match decode_request(
|
||||
&body,
|
||||
&headers,
|
||||
client.snapshot().responses_max_decompressed_body_bytes(),
|
||||
) {
|
||||
Ok(request) => request,
|
||||
let maximum = client.snapshot().responses_max_decompressed_body_bytes();
|
||||
let body = match decompress_request_body(&body, &headers, maximum) {
|
||||
Ok(body) => Bytes::copy_from_slice(&body),
|
||||
Err(error) => {
|
||||
return protocol_error_response(StatusCode::BAD_REQUEST, error.protocol_body());
|
||||
}
|
||||
};
|
||||
headers.remove(CONTENT_ENCODING);
|
||||
headers.remove(CONTENT_LENGTH);
|
||||
let decoded = match decode_request(&body, &headers, maximum) {
|
||||
Ok(decoded) => decoded,
|
||||
Err(error) => {
|
||||
return protocol_error_response(StatusCode::BAD_REQUEST, error.protocol_body());
|
||||
}
|
||||
@@ -54,22 +57,6 @@ pub(in crate::data_plane) async fn chat_completions(
|
||||
Ok(prepared) => prepared,
|
||||
Err(error) => return gateway_error_response(&error),
|
||||
};
|
||||
let identity = ChatIdentity {
|
||||
id: format!("chatcmpl-{}", prepared.request_id().as_str()),
|
||||
created: SystemTime::now()
|
||||
.duration_since(SystemTime::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs(),
|
||||
model: decoded.metadata().requested_model().to_owned(),
|
||||
};
|
||||
let streaming = decoded.metadata().stream();
|
||||
let adapter = HttpResponseAdapter {
|
||||
endpoint: CHAT_COMPLETIONS_PATH,
|
||||
wrap: Box::new(move |response| {
|
||||
project_middleware_response(response, identity, streaming, include_usage)
|
||||
}),
|
||||
stream_error: chat_error_frame,
|
||||
};
|
||||
execute_prepared_generation(
|
||||
service,
|
||||
prepared,
|
||||
@@ -77,26 +64,70 @@ pub(in crate::data_plane) async fn chat_completions(
|
||||
peer_address: connect_info.map(|Extension(ConnectInfo(address))| address),
|
||||
ingress_id,
|
||||
headers,
|
||||
input: GenerationEndpoint::Responses.input(decoded),
|
||||
middleware_body,
|
||||
input: GenerationEndpoint::Chat.input(decoded),
|
||||
middleware_body: body,
|
||||
},
|
||||
None,
|
||||
Some(adapter),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
fn decode_request(
|
||||
pub(in crate::data_plane) fn decode_request(
|
||||
body: &[u8],
|
||||
headers: &HeaderMap,
|
||||
maximum_body_bytes: usize,
|
||||
) -> Result<(DecodedGenerationRequest, Bytes, bool), RequestDecodeError> {
|
||||
let body = decompress_request_body(body, headers, maximum_body_bytes)?;
|
||||
let converted = convert_request(&body)?;
|
||||
let body =
|
||||
serde_json::to_vec(&converted.body).map_err(|_| RequestDecodeError::MalformedJson)?;
|
||||
let mut decoded_headers = headers.clone();
|
||||
decoded_headers.remove(CONTENT_ENCODING);
|
||||
let decoded = decode_request_with_headers(&body, &decoded_headers, maximum_body_bytes)?;
|
||||
Ok((decoded, Bytes::from(body), converted.include_usage))
|
||||
maximum: usize,
|
||||
) -> Result<DecodedGenerationRequest, RequestDecodeError> {
|
||||
let body = decompress_request_body(body, headers, maximum)?;
|
||||
let parsed = chat_completions::parse_request(&body).map_err(decode_error)?;
|
||||
let model = parsed
|
||||
.body
|
||||
.get("model")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.unwrap_or_default()
|
||||
.to_owned();
|
||||
let stream = parsed
|
||||
.body
|
||||
.get("stream")
|
||||
.and_then(serde_json::Value::as_bool)
|
||||
.unwrap_or(false);
|
||||
let payload = ProtocolPayload::from_json_bytes(CHAT_PROTOCOL, Bytes::copy_from_slice(&body))
|
||||
.map_err(|_| RequestDecodeError::CanonicalContract {
|
||||
field: "chat request".to_owned(),
|
||||
})?
|
||||
.with_context(OpenAiRequestHeaders::from_headers(headers).session_context());
|
||||
Ok(DecodedGenerationRequest {
|
||||
operation: Operation::Generate(GenerateRequest::from_protocol_payload(payload)),
|
||||
metadata: GenerationRequestMetadata {
|
||||
requested_model: model,
|
||||
stream,
|
||||
store: false,
|
||||
continuation: ContinuationIntent::None,
|
||||
client_ip: None,
|
||||
user_agent: None,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
fn decode_error(error: chat_completions::ChatError) -> RequestDecodeError {
|
||||
use chat_completions::ChatError;
|
||||
match error {
|
||||
ChatError::MalformedJson => RequestDecodeError::MalformedJson,
|
||||
ChatError::ExpectedObject => RequestDecodeError::ExpectedObject,
|
||||
ChatError::MissingField { field } => RequestDecodeError::MissingField { field },
|
||||
ChatError::InvalidType { field, expected } => {
|
||||
RequestDecodeError::InvalidType { field, expected }
|
||||
}
|
||||
ChatError::EmptyField { field } => RequestDecodeError::EmptyField { field },
|
||||
ChatError::InvalidValue { field } => RequestDecodeError::InvalidValue { field },
|
||||
ChatError::UnknownField { field } => RequestDecodeError::UnknownField { field },
|
||||
ChatError::UnsupportedField { field } => RequestDecodeError::UnsupportedField { field },
|
||||
ChatError::UnsupportedCombination { field, other } => {
|
||||
RequestDecodeError::UnsupportedCombination { field, other }
|
||||
}
|
||||
ChatError::InvalidResponse | ChatError::IncompleteStream => {
|
||||
RequestDecodeError::CanonicalContract {
|
||||
field: "chat request".to_owned(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//! Chat Completions 与 Responses 之间的 API 协议适配
|
||||
//! Chat 原始协议入口与交付,目标协议转换由选定的 Provider 装配
|
||||
|
||||
mod delivery;
|
||||
pub(in crate::data_plane) mod delivery;
|
||||
mod http;
|
||||
mod request;
|
||||
mod response;
|
||||
|
||||
pub(in crate::data_plane) use delivery::chat_error_frame;
|
||||
pub(super) use http::chat_completions;
|
||||
pub(in crate::data_plane) use http::decode_request;
|
||||
|
||||
@@ -217,7 +217,6 @@ async fn generate(
|
||||
middleware_body: body,
|
||||
},
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -34,7 +34,6 @@ use gateway_core::event::{ProviderEvent, ProviderResponseHeader};
|
||||
use gateway_core::lifecycle::{CancellationToken, ConnectionGuard};
|
||||
use gateway_protocol::openai::OPENAI_PROTOCOL;
|
||||
use gateway_protocol::openai::sse::response_failed_sse_event_with_id;
|
||||
use serde_json::Value;
|
||||
use tokio::time::Instant;
|
||||
|
||||
use crate::data_plane::error::{
|
||||
@@ -69,19 +68,12 @@ pub(crate) struct GenerationHttpRequest {
|
||||
pub middleware_body: Bytes,
|
||||
}
|
||||
|
||||
/// 下游协议只投影出口字节 执行会话和计量仍归原 owner
|
||||
pub(crate) struct HttpResponseAdapter {
|
||||
pub endpoint: &'static str,
|
||||
pub wrap: Box<dyn FnOnce(MiddlewareResponse) -> MiddlewareResponse + Send>,
|
||||
pub stream_error: fn(&Value) -> Bytes,
|
||||
}
|
||||
|
||||
impl GenerationEndpoint {
|
||||
fn expected_http_body(self, stream: bool) -> ExpectedBody {
|
||||
if stream {
|
||||
// 原生 GenAI 客户端会将网关插入的 SSE 注释解析为无效帧
|
||||
ExpectedBody::Sse {
|
||||
keep_alive: matches!(self, Self::Responses | Self::Messages),
|
||||
keep_alive: matches!(self, Self::Chat | Self::Responses | Self::Messages),
|
||||
}
|
||||
} else {
|
||||
ExpectedBody::SingleJson
|
||||
@@ -94,7 +86,6 @@ pub(crate) async fn execute_prepared_generation(
|
||||
prepared: PreparedRootExecution,
|
||||
request: GenerationHttpRequest,
|
||||
authorization: Option<Arc<dyn ResponseAuthorization>>,
|
||||
adapter: Option<HttpResponseAdapter>,
|
||||
) -> Response {
|
||||
let GenerationHttpRequest {
|
||||
peer_address,
|
||||
@@ -128,13 +119,8 @@ pub(crate) async fn execute_prepared_generation(
|
||||
// 中间件正文已经由入口按上限解压;传输编码和旧长度不能与改写后的正文混用
|
||||
middleware_headers.remove(CONTENT_ENCODING);
|
||||
middleware_headers.remove(CONTENT_LENGTH);
|
||||
let endpoint = adapter
|
||||
.as_ref()
|
||||
.map_or(protocol.path(), |adapter| adapter.endpoint);
|
||||
let stream_error = adapter
|
||||
.as_ref()
|
||||
.map(|adapter| adapter.stream_error)
|
||||
.or_else(|| protocol.stream_error_encoder());
|
||||
let endpoint = protocol.path();
|
||||
let stream_error = protocol.stream_error_encoder();
|
||||
let input = RequestInput {
|
||||
endpoint: endpoint.to_owned(),
|
||||
protocol: protocol.wire().to_owned(),
|
||||
@@ -231,10 +217,6 @@ pub(crate) async fn execute_prepared_generation(
|
||||
};
|
||||
let response =
|
||||
validated_middleware_response(response, validation, stream, protocol);
|
||||
let response = match adapter {
|
||||
Some(adapter) => (adapter.wrap)(response),
|
||||
None => response,
|
||||
};
|
||||
into_http_response(response, expected, protocol.wire()).await
|
||||
}
|
||||
Err(error) => error_response(error),
|
||||
@@ -245,7 +227,10 @@ pub(crate) async fn execute_prepared_generation(
|
||||
response,
|
||||
keepalive,
|
||||
stream_error,
|
||||
protocol == GenerationEndpoint::Responses,
|
||||
matches!(
|
||||
protocol,
|
||||
GenerationEndpoint::Responses | GenerationEndpoint::Chat
|
||||
),
|
||||
)
|
||||
.await
|
||||
} else {
|
||||
@@ -1014,6 +999,25 @@ impl MiddlewareBody for StreamingExecutionBody {
|
||||
.map_err(MiddlewareError::Engine)?;
|
||||
self.committed = true;
|
||||
self.batch_pending = false;
|
||||
if self.protocol == GenerationEndpoint::Chat && self.awaiting_terminal_eof {
|
||||
match self.verify_terminal_eof().await {
|
||||
Ok(()) => {
|
||||
self.pending.push_back(done_frame(self.protocol));
|
||||
self.output_finished = true;
|
||||
}
|
||||
Err(error) => {
|
||||
self.pending.clear();
|
||||
let error = match error {
|
||||
MiddlewareError::Engine(error) => gateway_error_from_engine(&error),
|
||||
_ => GatewayError::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"The Chat response could not be finalized.",
|
||||
),
|
||||
};
|
||||
self.push_stream_error(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
@@ -6,9 +6,7 @@ mod request;
|
||||
mod response;
|
||||
mod validation;
|
||||
|
||||
pub(crate) use http::{
|
||||
GenerationHttpRequest, HttpResponseAdapter, ResponseAuthorization, execute_prepared_generation,
|
||||
};
|
||||
pub(crate) use http::{GenerationHttpRequest, ResponseAuthorization, execute_prepared_generation};
|
||||
pub use request::{ContinuationIntent, DecodedGenerationRequest, GenerationRequestMetadata};
|
||||
|
||||
use axum::http::HeaderMap;
|
||||
@@ -18,6 +16,7 @@ use gateway_protocol::openai::OPENAI_PROTOCOL;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum GenerationEndpoint {
|
||||
Chat,
|
||||
Responses,
|
||||
Messages,
|
||||
MessageTokenCount,
|
||||
@@ -36,6 +35,7 @@ impl GenerationEndpoint {
|
||||
|
||||
pub(crate) const fn wire(self) -> &'static str {
|
||||
match self {
|
||||
Self::Chat => gateway_protocol::chat_completions::CHAT_PROTOCOL,
|
||||
Self::Responses => OPENAI_PROTOCOL,
|
||||
Self::GenAi | Self::GenAiTokenCount => gateway_protocol::genai::GENAI_PROTOCOL,
|
||||
Self::Messages | Self::MessageTokenCount => ANTHROPIC_PROTOCOL,
|
||||
@@ -44,6 +44,7 @@ impl GenerationEndpoint {
|
||||
|
||||
pub(crate) const fn path(self) -> &'static str {
|
||||
match self {
|
||||
Self::Chat => super::router::CHAT_COMPLETIONS_PATH,
|
||||
Self::Responses => super::router::RESPONSES_PATH,
|
||||
Self::GenAi | Self::GenAiTokenCount => super::genai::MODEL_ACTION_PATH,
|
||||
Self::Messages => super::router::MESSAGES_PATH,
|
||||
@@ -53,7 +54,7 @@ impl GenerationEndpoint {
|
||||
|
||||
pub(crate) const fn operation(self) -> OperationKind {
|
||||
match self {
|
||||
Self::Responses | Self::Messages | Self::GenAi => OperationKind::Generate,
|
||||
Self::Chat | Self::Responses | Self::Messages | Self::GenAi => OperationKind::Generate,
|
||||
Self::MessageTokenCount | Self::GenAiTokenCount => OperationKind::CountTokens,
|
||||
}
|
||||
}
|
||||
@@ -74,6 +75,17 @@ impl GenerationInput {
|
||||
) -> Result<DecodedGenerationRequest, gateway_core::engine::middleware::MiddlewareError> {
|
||||
use gateway_core::engine::middleware::MiddlewareError;
|
||||
match self.endpoint {
|
||||
GenerationEndpoint::Chat => {
|
||||
super::chat_completions::decode_request(body, headers, maximum).map_err(|error| {
|
||||
MiddlewareError::Gateway(
|
||||
gateway_core::error::GatewayError::new(
|
||||
gateway_core::error::GatewayErrorKind::InvalidRequest,
|
||||
"The Chat request is invalid.",
|
||||
)
|
||||
.with_source(error),
|
||||
)
|
||||
})
|
||||
}
|
||||
GenerationEndpoint::GenAi | GenerationEndpoint::GenAiTokenCount => {
|
||||
super::genai::decode(
|
||||
&self.model,
|
||||
|
||||
@@ -19,6 +19,7 @@ use crate::data_plane::{
|
||||
};
|
||||
|
||||
pub(super) enum GenerationEncoder {
|
||||
Chat(crate::data_plane::chat_completions::delivery::ChatEncoder),
|
||||
Responses(OpenAiResponsesEncoder),
|
||||
GenAi {
|
||||
failed: bool,
|
||||
@@ -33,6 +34,7 @@ pub(super) enum GenerationEncoder {
|
||||
impl GenerationEncoder {
|
||||
pub(super) fn new(protocol: GenerationEndpoint) -> Self {
|
||||
match protocol {
|
||||
GenerationEndpoint::Chat => Self::Chat(Default::default()),
|
||||
GenerationEndpoint::Responses => Self::Responses(OpenAiResponsesEncoder::new()),
|
||||
GenerationEndpoint::GenAi | GenerationEndpoint::GenAiTokenCount => {
|
||||
Self::GenAi { failed: false }
|
||||
@@ -49,6 +51,7 @@ impl GenerationEncoder {
|
||||
|
||||
pub(super) fn push_sse(&mut self, event: &ProviderEvent) -> Vec<Bytes> {
|
||||
match self {
|
||||
Self::Chat(encoder) => encoder.push(event),
|
||||
Self::Responses(encoder) => encoder.push_sse(event),
|
||||
Self::GenAi { failed } => {
|
||||
let Some(wire) = event
|
||||
@@ -142,6 +145,7 @@ impl GenerationEncoder {
|
||||
match self {
|
||||
Self::Responses(encoder) => encoder.is_completed(),
|
||||
// 原生 GenAI 以 EOF 结束,finishReason 后仍可收到独立用量帧
|
||||
Self::Chat(encoder) => encoder.completed,
|
||||
Self::GenAi { .. } => false,
|
||||
Self::Messages { completed, .. } => *completed,
|
||||
}
|
||||
@@ -150,6 +154,7 @@ impl GenerationEncoder {
|
||||
pub(super) fn has_wire_failure(&self) -> bool {
|
||||
match self {
|
||||
Self::Responses(encoder) => encoder.has_wire_failure(),
|
||||
Self::Chat(encoder) => encoder.failed,
|
||||
Self::Messages { failed, .. } | Self::GenAi { failed } => *failed,
|
||||
}
|
||||
}
|
||||
@@ -157,6 +162,13 @@ impl GenerationEncoder {
|
||||
pub(super) fn error_frame(&self, error: &GatewayError) -> Bytes {
|
||||
let (status, error_type, code) = gateway_error_contract(error.kind());
|
||||
match self {
|
||||
Self::Chat(_) => {
|
||||
crate::data_plane::chat_completions::chat_error_frame(&json!({"error": {
|
||||
"type": error.client_error_type().unwrap_or(error_type),
|
||||
"code": error.client_error_code().unwrap_or(code),
|
||||
"message": error.client_message(),
|
||||
}}))
|
||||
}
|
||||
Self::Responses(encoder) => Bytes::from(response_failed_sse_event_with_id(
|
||||
encoder.response_id(),
|
||||
error.client_error_type().unwrap_or(error_type),
|
||||
@@ -180,6 +192,7 @@ impl GenerationEncoder {
|
||||
impl GenerationEndpoint {
|
||||
pub(super) const fn stream_error_encoder(self) -> Option<fn(&Value) -> Bytes> {
|
||||
match self {
|
||||
Self::Chat => Some(crate::data_plane::chat_completions::chat_error_frame),
|
||||
Self::Responses => None,
|
||||
Self::GenAi | Self::GenAiTokenCount => Some(crate::data_plane::genai::stream_error),
|
||||
Self::Messages | Self::MessageTokenCount => Some(messages::stream_error),
|
||||
@@ -191,7 +204,7 @@ impl GenerationEndpoint {
|
||||
response: axum::response::Response,
|
||||
) -> axum::response::Response {
|
||||
match self {
|
||||
Self::Responses => response,
|
||||
Self::Chat | Self::Responses => response,
|
||||
Self::GenAi | Self::GenAiTokenCount => {
|
||||
crate::data_plane::genai::project_error_response(response).await
|
||||
}
|
||||
@@ -203,7 +216,7 @@ impl GenerationEndpoint {
|
||||
|
||||
pub(super) fn terminal_bytes(self) -> Bytes {
|
||||
match self {
|
||||
Self::Responses => Bytes::from_static(DONE_SSE_FRAME.as_bytes()),
|
||||
Self::Chat | Self::Responses => Bytes::from_static(DONE_SSE_FRAME.as_bytes()),
|
||||
// Messages 的 message_stop 已在 wire 中交付,空帧只确认宿主交付终结
|
||||
Self::Messages | Self::MessageTokenCount | Self::GenAi | Self::GenAiTokenCount => {
|
||||
Bytes::new()
|
||||
@@ -212,6 +225,39 @@ impl GenerationEndpoint {
|
||||
}
|
||||
|
||||
pub(super) fn collect(self, events: &[ProviderEvent]) -> Result<Vec<u8>, ResponseEncodeError> {
|
||||
if self == Self::Chat {
|
||||
let mut accumulator = gateway_protocol::chat_completions::ChatAccumulator::default();
|
||||
let mut json_body = None;
|
||||
let mut chunks = false;
|
||||
for wire in events
|
||||
.iter()
|
||||
.filter_map(ProviderEvent::wire_event)
|
||||
.filter(|wire| wire.protocol() == self.wire())
|
||||
{
|
||||
if let Some(raw) = wire.raw_json_body() {
|
||||
if chunks || json_body.replace(raw).is_some() {
|
||||
return Err(ResponseEncodeError::InvalidOutputItems);
|
||||
}
|
||||
} else {
|
||||
if json_body.is_some() {
|
||||
return Err(ResponseEncodeError::InvalidOutputItems);
|
||||
}
|
||||
chunks = true;
|
||||
accumulator
|
||||
.push(wire.data())
|
||||
.map_err(|_| ResponseEncodeError::InvalidOutputItems)?;
|
||||
}
|
||||
}
|
||||
if let Some(raw) = json_body {
|
||||
return Ok(raw.to_vec());
|
||||
}
|
||||
return serde_json::to_vec(
|
||||
&accumulator
|
||||
.finish()
|
||||
.map_err(|_| ResponseEncodeError::MissingWireTerminal)?,
|
||||
)
|
||||
.map_err(|_| ResponseEncodeError::Serialization);
|
||||
}
|
||||
if self == Self::Responses {
|
||||
return serde_json::to_vec(&crate::data_plane::responses::response::collect_response(
|
||||
events,
|
||||
|
||||
@@ -14,6 +14,7 @@ use crate::data_plane::responses::validation::{
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) enum GenerationValidationFacts {
|
||||
Chat(Arc<Mutex<Option<String>>>),
|
||||
Responses(ResponseValidationFacts),
|
||||
Messages(Arc<Mutex<Option<String>>>),
|
||||
Count(&'static str),
|
||||
@@ -23,6 +24,7 @@ pub(super) enum GenerationValidationFacts {
|
||||
impl GenerationValidationFacts {
|
||||
pub(super) fn new(protocol: GenerationEndpoint) -> Self {
|
||||
match protocol {
|
||||
GenerationEndpoint::Chat => Self::Chat(Arc::default()),
|
||||
GenerationEndpoint::Responses => Self::Responses(ResponseValidationFacts::default()),
|
||||
GenerationEndpoint::Messages => Self::Messages(Arc::default()),
|
||||
GenerationEndpoint::MessageTokenCount => Self::Count("input_tokens"),
|
||||
@@ -33,6 +35,25 @@ impl GenerationValidationFacts {
|
||||
|
||||
pub(super) fn observe_event(&self, event: &ProviderEvent) {
|
||||
match self {
|
||||
Self::Chat(id) => {
|
||||
if let Some(wire) = event.wire_event().filter(|wire| {
|
||||
wire.protocol() == gateway_protocol::chat_completions::CHAT_PROTOCOL
|
||||
}) {
|
||||
let parsed = wire
|
||||
.raw_json_body()
|
||||
.and_then(|bytes| serde_json::from_slice::<Value>(bytes).ok());
|
||||
if let Some(value) = parsed
|
||||
.as_ref()
|
||||
.unwrap_or_else(|| wire.data())
|
||||
.get("id")
|
||||
.and_then(Value::as_str)
|
||||
{
|
||||
id.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.get_or_insert_with(|| value.to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
Self::Responses(facts) => facts.observe_event(event),
|
||||
Self::Messages(id) => {
|
||||
if let Some(value) = event
|
||||
@@ -73,12 +94,29 @@ impl GenerationValidationFacts {
|
||||
match self {
|
||||
Self::Responses(facts) => facts.response_id(),
|
||||
Self::Messages(id) => id.lock().ok().and_then(|id| id.clone()),
|
||||
Self::Chat(id) => id
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.clone(),
|
||||
Self::Count(_) | Self::GenAi => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn validate_buffered(&self, bytes: &[u8]) -> Result<(), ()> {
|
||||
match self {
|
||||
Self::Chat(id) => {
|
||||
crate::data_plane::chat_completions::delivery::validate_response(bytes)?;
|
||||
let value: Value = serde_json::from_slice(bytes).map_err(|_| ())?;
|
||||
if id
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.as_deref()
|
||||
.is_some_and(|id| value.get("id").and_then(Value::as_str) != Some(id))
|
||||
{
|
||||
return Err(());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Self::Responses(facts) => validate_buffered_response(facts, bytes).map_err(|_| ()),
|
||||
Self::Messages(_) => {
|
||||
let value: Value = serde_json::from_slice(bytes).map_err(|_| ())?;
|
||||
@@ -113,6 +151,7 @@ impl GenerationValidationFacts {
|
||||
}
|
||||
|
||||
pub(super) enum GenerationDeliveryValidator {
|
||||
Chat(crate::data_plane::chat_completions::delivery::ChatDeliveryValidator),
|
||||
Responses(ResponsesDeliveryValidator),
|
||||
Messages {
|
||||
id: Option<String>,
|
||||
@@ -127,6 +166,7 @@ pub(super) enum GenerationDeliveryValidator {
|
||||
impl GenerationDeliveryValidator {
|
||||
pub(super) fn new(protocol: GenerationEndpoint) -> Self {
|
||||
match protocol {
|
||||
GenerationEndpoint::Chat => Self::Chat(Default::default()),
|
||||
GenerationEndpoint::Responses => Self::Responses(ResponsesDeliveryValidator::default()),
|
||||
GenerationEndpoint::GenAi => Self::GenAi {
|
||||
observation: GenerateContentObservation::default(),
|
||||
@@ -141,6 +181,7 @@ impl GenerationDeliveryValidator {
|
||||
|
||||
pub(super) fn response_id(&self) -> Option<&str> {
|
||||
match self {
|
||||
Self::Chat(validator) => validator.response_id(),
|
||||
Self::Responses(validator) => validator.response_id(),
|
||||
Self::Messages { id, .. } => id.as_deref(),
|
||||
Self::GenAi { .. } => None,
|
||||
@@ -154,6 +195,18 @@ impl GenerationDeliveryValidator {
|
||||
facts: &GenerationValidationFacts,
|
||||
) -> Result<(), ()> {
|
||||
match (self, facts) {
|
||||
(Self::Chat(validator), GenerationValidationFacts::Chat(id)) => {
|
||||
validator.validate_frame(bytes)?;
|
||||
if validator.response_id().is_some_and(|actual| {
|
||||
id.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.as_deref()
|
||||
.is_some_and(|expected| expected != actual)
|
||||
}) {
|
||||
return Err(());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
(Self::Responses(validator), GenerationValidationFacts::Responses(facts)) => validator
|
||||
.validate_frame(bytes, transformed, facts)
|
||||
.map_err(|_| ()),
|
||||
@@ -234,6 +287,7 @@ impl GenerationDeliveryValidator {
|
||||
|
||||
pub(super) fn finish_delivery(&self) -> Result<(), ()> {
|
||||
match self {
|
||||
Self::Chat(validator) => validator.finish_delivery(),
|
||||
Self::Responses(validator) => validator.finish_delivery().map_err(|_| ()),
|
||||
Self::Messages { finished: true, .. } => Ok(()),
|
||||
Self::GenAi {
|
||||
|
||||
@@ -108,7 +108,6 @@ async fn execute(
|
||||
middleware_body: body,
|
||||
},
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -134,7 +133,7 @@ pub(super) fn decode_request(
|
||||
};
|
||||
validation.map_err(|error| {
|
||||
invalid(match error {
|
||||
anthropic::TranslationError::InvalidRequest(message) => message,
|
||||
anthropic::MessageError::InvalidRequest(message) => message,
|
||||
_ => "Messages request is invalid.",
|
||||
})
|
||||
})?;
|
||||
|
||||
@@ -57,7 +57,6 @@ pub(crate) async fn responses(
|
||||
middleware_body,
|
||||
},
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
//! Chat 字节交付只消费 Chat wire,并核对终态、身份与截断
|
||||
|
||||
use super::{
|
||||
chat_request, chunk, completed, created,
|
||||
http::{Fixture, json_body},
|
||||
};
|
||||
use crate::support::generation::Session;
|
||||
use axum::{body::to_bytes, http::StatusCode, response::Response};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub(super) async fn sse_body(response: Response) -> (String, Vec<Value>) {
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(response.headers()["content-type"], "text/event-stream");
|
||||
let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||
let text = String::from_utf8(bytes.to_vec()).unwrap();
|
||||
assert_eq!(text.matches("data: [DONE]").count(), 1, "{text}");
|
||||
assert!(text.ends_with("data: [DONE]\n\n"), "{text}");
|
||||
let chunks = text
|
||||
.lines()
|
||||
.filter_map(|line| line.strip_prefix("data: "))
|
||||
.filter(|data| *data != "[DONE]")
|
||||
.map(|data| serde_json::from_str(data).unwrap())
|
||||
.collect();
|
||||
(text, chunks)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn returns_chat_json_from_chat_chunks_without_responses_projection() {
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
created(),
|
||||
chunk(json!({"content":"你好 "}), Value::Null),
|
||||
completed("🌍"),
|
||||
]))
|
||||
.await;
|
||||
let response = fixture.post(chat_request(false)).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let body = json_body(response).await;
|
||||
assert_eq!(body["object"], "chat.completion");
|
||||
assert_eq!(body["choices"][0]["message"]["content"], "你好 🌍");
|
||||
assert_eq!(body["choices"][0]["finish_reason"], "stop");
|
||||
assert_eq!(fixture.captured().protocol, "chat_completions");
|
||||
assert!(fixture.captured().body.get("input").is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn returns_chat_sse_with_one_terminal_and_one_done() {
|
||||
let fixture = Fixture::new(Session::new(vec![created(), completed("answer")])).await;
|
||||
let (text, chunks) = sse_body(fixture.post(chat_request(true)).await).await;
|
||||
assert!(!text.contains("response.completed"));
|
||||
assert_eq!(
|
||||
chunks
|
||||
.iter()
|
||||
.filter(|value| value["choices"][0]["finish_reason"].is_string())
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
assert!(chunks.iter().all(|value| value["id"] == "chatcmpl_fixture"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn truncation_produces_error_without_success_finish() {
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
created(),
|
||||
chunk(json!({"content":"partial"}), Value::Null),
|
||||
]))
|
||||
.await;
|
||||
let (_, chunks) = sse_body(fixture.post(chat_request(true)).await).await;
|
||||
assert!(chunks.iter().any(|value| value.get("error").is_some()));
|
||||
assert!(
|
||||
!chunks
|
||||
.iter()
|
||||
.any(|value| value["choices"][0]["finish_reason"].is_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_invalid_chat_input_before_starting_execution() {
|
||||
for (field, value) in [
|
||||
("n", json!(2)),
|
||||
("store", json!(true)),
|
||||
("previous_response_id", json!("opaque")),
|
||||
] {
|
||||
let fixture = Fixture::new(Session::new(Vec::new())).await;
|
||||
let mut body = chat_request(false);
|
||||
body[field] = value;
|
||||
let response = fixture.post(body).await;
|
||||
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
||||
assert_eq!(json_body(response).await["error"]["param"], field);
|
||||
assert!(fixture.execution.captured.lock().unwrap().is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn buffered_chat_rejects_multiple_json_or_mixed_representations() {
|
||||
for events in [
|
||||
vec![super::json_completed(), super::json_completed()],
|
||||
vec![created(), super::json_completed()],
|
||||
vec![super::json_completed(), created()],
|
||||
] {
|
||||
let fixture = Fixture::new(Session::new(vec![]).with_batch(events)).await;
|
||||
let response = fixture.post(chat_request(false)).await;
|
||||
assert!(response.status().is_server_error());
|
||||
assert!(json_body(response).await.get("choices").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn final_usage_follows_the_finish_chunk_and_precedes_done() {
|
||||
use gateway_core::event::{GatewayEvent, ProtocolWireEvent, ProviderEvent, ResponseMeta};
|
||||
let usage = ProviderEvent::wire(ProtocolWireEvent::json("chat_completions", None, json!({
|
||||
"id":"chatcmpl_fixture","object":"chat.completion.chunk","created":100,"model":"model-a",
|
||||
"choices":[],"usage":{"prompt_tokens":3,"completion_tokens":2,"total_tokens":5}
|
||||
})).unwrap()).with_fact(GatewayEvent::Completed(ResponseMeta::new("upstream", "model-a")));
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
created(),
|
||||
chunk(json!({"content":"answer"}), Value::Null),
|
||||
chunk(json!({}), json!("stop")),
|
||||
usage,
|
||||
]))
|
||||
.await;
|
||||
let (_, chunks) = sse_body(fixture.post(chat_request(true)).await).await;
|
||||
assert_eq!(
|
||||
chunks[chunks.len() - 2]["choices"][0]["finish_reason"],
|
||||
"stop"
|
||||
);
|
||||
assert_eq!(chunks.last().unwrap()["usage"]["total_tokens"], 5);
|
||||
assert!(chunks.iter().all(|value| value.get("error").is_none()));
|
||||
}
|
||||
@@ -36,7 +36,7 @@ use gateway_core::{
|
||||
use serde_json::{Value, json};
|
||||
use tower::ServiceExt as _;
|
||||
|
||||
use super::{chat_request, completed, created, message};
|
||||
use super::{chat_request, completed, created};
|
||||
use crate::data_plane::{
|
||||
api_router, authenticated_client, authenticated_client_for_provider_with_limit,
|
||||
middleware::{RequestMiddleware, ResponseFrameAction},
|
||||
@@ -50,6 +50,7 @@ use crate::support::generation::{Finish, Session};
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct Captured {
|
||||
pub body: Value,
|
||||
pub protocol: String,
|
||||
pub context: Value,
|
||||
pub endpoint: String,
|
||||
}
|
||||
@@ -99,6 +100,7 @@ impl ExecutionService for Execution {
|
||||
};
|
||||
*self.captured.lock().unwrap() = Some(Captured {
|
||||
body: Value::Object(generation.protocol_payload().body().clone()),
|
||||
protocol: generation.protocol_payload().protocol().to_owned(),
|
||||
context: Value::Object(generation.protocol_payload().context().clone()),
|
||||
endpoint: request.metadata.endpoint,
|
||||
});
|
||||
@@ -209,7 +211,7 @@ impl MiddlewarePlan for InspectMiddleware {
|
||||
let headers = request.headers().to_vec();
|
||||
request = request
|
||||
.replace_parts(
|
||||
"openai".to_owned(),
|
||||
"chat_completions".to_owned(),
|
||||
headers,
|
||||
Bytes::from(body.to_string()),
|
||||
None,
|
||||
@@ -240,18 +242,18 @@ async fn rejects_missing_authentication_before_decoding_or_execution() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn request_middleware_sees_responses_and_preserves_the_chat_endpoint() {
|
||||
async fn request_middleware_sees_original_chat_and_preserves_the_endpoint() {
|
||||
let middleware = Arc::new(InspectMiddleware {
|
||||
inner: RequestMiddleware {
|
||||
expected_operation: Some(gateway_core::operation::OperationKind::Generate),
|
||||
..RequestMiddleware::default()
|
||||
},
|
||||
update: Some(|body| {
|
||||
body["input"] = json!("rewritten by request middleware");
|
||||
body["messages"][0]["content"] = json!("rewritten by request middleware");
|
||||
}),
|
||||
..InspectMiddleware::default()
|
||||
});
|
||||
let mut execution = Execution::new(Session::new(vec![completed(json!([message("ok")]))]));
|
||||
let mut execution = Execution::new(Session::new(vec![created(), completed("ok")]));
|
||||
execution.middleware = Some(middleware.frozen());
|
||||
let fixture = Fixture::with_execution(execution).await;
|
||||
let response = fixture.post(chat_request(false)).await;
|
||||
@@ -259,15 +261,19 @@ async fn request_middleware_sees_responses_and_preserves_the_chat_endpoint() {
|
||||
let downstream = json_body(response).await;
|
||||
assert_eq!(downstream["object"], "chat.completion");
|
||||
let observed = middleware.requests.lock().unwrap();
|
||||
assert!(observed[0].get("messages").is_none());
|
||||
assert_eq!(observed[0]["input"][0]["role"], "user");
|
||||
assert!(observed[0].get("input").is_none());
|
||||
assert_eq!(observed[0]["messages"][0]["role"], "user");
|
||||
assert_eq!(
|
||||
middleware.inner.endpoints.lock().unwrap().as_slice(),
|
||||
[PATH]
|
||||
);
|
||||
let captured = fixture.captured();
|
||||
assert_eq!(captured.endpoint, PATH);
|
||||
assert_eq!(captured.body["input"], "rewritten by request middleware");
|
||||
assert_eq!(captured.protocol, "chat_completions");
|
||||
assert_eq!(
|
||||
captured.body["messages"][0]["content"],
|
||||
"rewritten by request middleware"
|
||||
);
|
||||
assert_eq!(fixture.trace.commits.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
@@ -288,7 +294,7 @@ async fn dropping_chat_body_cancels_and_finalizes_the_original_execution() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn gzip_and_headers_reuse_the_responses_ingress_contract() {
|
||||
let mut session = Session::new(vec![completed(json!([message("ok")]))]);
|
||||
let mut session = Session::new(vec![created(), completed("ok")]);
|
||||
session.response_headers = vec![
|
||||
ProviderResponseHeader::new("x-future-multi", Bytes::from_static(b"first")),
|
||||
ProviderResponseHeader::new("x-future-multi", Bytes::from_static(b"second")),
|
||||
@@ -368,10 +374,13 @@ async fn corrupt_or_oversized_compressed_chat_never_starts_execution() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn response_middleware_is_validated_as_responses_before_chat_projection() {
|
||||
for matching_identity in [true, false] {
|
||||
let replacement = json!({"id":if matching_identity {"resp_chat_test"} else {"resp_other"},
|
||||
"status":"completed","output":[message("plugin text")]});
|
||||
async fn response_middleware_must_preserve_chat_shape_and_identity() {
|
||||
for (matching_identity, raw_json) in
|
||||
[(true, false), (false, false), (true, true), (false, true)]
|
||||
{
|
||||
let replacement = json!({"id":if matching_identity {"chatcmpl_fixture"} else {"chatcmpl_other"},
|
||||
"object":"chat.completion","created":100,"model":"model-a",
|
||||
"choices":[{"index":0,"message":{"role":"assistant","content":"plugin text"},"finish_reason":"stop"}]});
|
||||
let middleware = Arc::new(
|
||||
RequestMiddleware {
|
||||
expected_operation: Some(gateway_core::operation::OperationKind::Generate),
|
||||
@@ -381,8 +390,11 @@ async fn response_middleware_is_validated_as_responses_before_chat_projection()
|
||||
replacement.to_string(),
|
||||
))]),
|
||||
);
|
||||
let mut execution =
|
||||
Execution::new(Session::new(vec![completed(json!([message("original")]))]));
|
||||
let mut execution = Execution::new(Session::new(if raw_json {
|
||||
vec![super::json_completed()]
|
||||
} else {
|
||||
vec![created(), completed("original")]
|
||||
}));
|
||||
execution.middleware = Some(middleware.frozen());
|
||||
let fixture = Fixture::with_execution(execution).await;
|
||||
let response = fixture.post(chat_request(false)).await;
|
||||
@@ -406,7 +418,7 @@ async fn response_middleware_is_validated_as_responses_before_chat_projection()
|
||||
#[tokio::test]
|
||||
async fn commit_failure_does_not_deliver_buffered_or_first_terminal_chat_success() {
|
||||
for streaming in [false, true] {
|
||||
let mut session = Session::new(vec![completed(json!([message("not delivered")]))]);
|
||||
let mut session = Session::new(vec![created(), completed("not delivered")]);
|
||||
session.fail_commit = true;
|
||||
let fixture = Fixture::new(session).await;
|
||||
let response = fixture.post(chat_request(streaming)).await;
|
||||
@@ -421,11 +433,18 @@ async fn commit_failure_does_not_deliver_buffered_or_first_terminal_chat_success
|
||||
#[tokio::test]
|
||||
async fn the_same_execution_fixture_finishes_native_responses_with_one_commit() {
|
||||
for already_started in [false, true] {
|
||||
let native = |kind: &str, status: &str| {
|
||||
gateway_core::event::ProviderEvent::wire(
|
||||
gateway_core::event::ProtocolWireEvent::json("openai", Some(kind.to_owned()), json!({
|
||||
"type":kind,"response":{"id":"resp_native","object":"response","model":"model-a","status":status,
|
||||
"output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"native baseline"}]}]}
|
||||
})).unwrap())
|
||||
};
|
||||
let mut events = Vec::new();
|
||||
if already_started {
|
||||
events.push(created());
|
||||
events.push(native("response.created", "in_progress"));
|
||||
}
|
||||
events.push(completed(json!([message("native baseline")])));
|
||||
events.push(native("response.completed", "completed"));
|
||||
let fixture = Fixture::new(Session::new(events)).await;
|
||||
let mut request = request(json!({"model":"model-a","input":"hello","stream":true}));
|
||||
*request.uri_mut() = "/v1/responses".parse().unwrap();
|
||||
@@ -447,12 +466,11 @@ async fn the_same_execution_fixture_finishes_native_responses_with_one_commit()
|
||||
#[tokio::test]
|
||||
async fn finalization_failure_never_leaks_success_finish_or_usage() {
|
||||
for already_started in [false, true] {
|
||||
let mut events = Vec::new();
|
||||
if already_started {
|
||||
events.push(created());
|
||||
}
|
||||
events.push(completed(json!([])));
|
||||
let mut session = Session::new(events);
|
||||
let mut session = if already_started {
|
||||
Session::new(vec![created(), completed("")])
|
||||
} else {
|
||||
Session::new(Vec::new()).with_batch(vec![created(), completed("")])
|
||||
};
|
||||
session.finish = Finish::Error;
|
||||
let fixture = Fixture::new(session).await;
|
||||
let mut body = chat_request(true);
|
||||
@@ -460,7 +478,7 @@ async fn finalization_failure_never_leaks_success_finish_or_usage() {
|
||||
let response = fixture.post(body).await;
|
||||
// 原会话已经接受 200 提交,后续终结错误只能作为流内错误交付
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let (_, chunks) = super::response::sse_body(response).await;
|
||||
let (_, chunks) = super::delivery::sse_body(response).await;
|
||||
assert!(chunks.iter().any(|chunk| chunk.get("error").is_some()));
|
||||
assert!(
|
||||
!chunks
|
||||
@@ -481,7 +499,7 @@ async fn error_after_admission_keepalive_uses_chat_error_encoding() {
|
||||
session.finish = Finish::Error;
|
||||
let fixture = Fixture::new(session).await;
|
||||
let response = fixture.post(chat_request(true)).await;
|
||||
let (body, chunks) = super::response::sse_body(response).await;
|
||||
let (body, chunks) = super::delivery::sse_body(response).await;
|
||||
assert!(body.starts_with(": keep-alive\n\n"));
|
||||
assert!(chunks.iter().any(|chunk| chunk.get("error").is_some()));
|
||||
assert!(!body.contains("response.failed"));
|
||||
@@ -498,7 +516,7 @@ async fn early_middleware_failure_is_recorded_at_ingress_without_a_reserved_mode
|
||||
}
|
||||
.with_json_short_circuit(Bytes::from_static(b"{}")),
|
||||
);
|
||||
let mut execution = Execution::new(Session::new(vec![completed(json!([message("OK")]))]));
|
||||
let mut execution = Execution::new(Session::new(vec![created(), completed("OK")]));
|
||||
execution.middleware = Some(middleware.frozen());
|
||||
let execution = Arc::new(execution);
|
||||
let diagnostics = Arc::new(crate::support::RecordingDiagnostics::default());
|
||||
|
||||
@@ -1,45 +1,42 @@
|
||||
//! Chat Completions 的请求转换、输出投影与 HTTP 生命周期测试
|
||||
//! Chat 原始入口与交付生命周期测试,纯转换测试归 gateway-protocol
|
||||
|
||||
mod delivery;
|
||||
mod http;
|
||||
mod request;
|
||||
mod response;
|
||||
|
||||
use gateway_core::event::{ProtocolWireEvent, ProviderEvent};
|
||||
use gateway_core::event::{GatewayEvent, ProtocolWireEvent, ProviderEvent, ResponseMeta};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn chat_request(stream: bool) -> Value {
|
||||
json!({"model":"model-a","messages":[{"role":"user","content":"hello"}],"stream":stream})
|
||||
}
|
||||
|
||||
fn wire(kind: &str, mut value: Value) -> ProviderEvent {
|
||||
value["type"] = json!(kind);
|
||||
ProviderEvent::wire(ProtocolWireEvent::json("openai", Some(kind.to_owned()), value).unwrap())
|
||||
}
|
||||
|
||||
fn completed(output: Value) -> ProviderEvent {
|
||||
wire(
|
||||
"response.completed",
|
||||
json!({"response":{
|
||||
"id":"resp_chat_test","object":"response","model":"upstream-model",
|
||||
"status":"completed","output":output,
|
||||
"usage":{"input_tokens":11,"output_tokens":7,"total_tokens":18,
|
||||
"input_tokens_details":{"cached_tokens":3},
|
||||
"output_tokens_details":{"reasoning_tokens":2}}
|
||||
}}),
|
||||
fn chunk(delta: Value, finish: Value) -> ProviderEvent {
|
||||
ProviderEvent::wire(
|
||||
ProtocolWireEvent::json(
|
||||
"chat_completions",
|
||||
None,
|
||||
json!({
|
||||
"id":"chatcmpl_fixture", "object":"chat.completion.chunk", "created":100,
|
||||
"model":"model-a", "choices":[{"index":0,"delta":delta,"finish_reason":finish}]
|
||||
}),
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
fn message(text: &str) -> Value {
|
||||
json!({"id":"msg_chat_test","type":"message","role":"assistant","status":"completed",
|
||||
"content":[{"type":"output_text","text":text,"annotations":[]}]})
|
||||
fn completed(text: &str) -> ProviderEvent {
|
||||
chunk(json!({"content":text}), json!("stop")).with_fact(GatewayEvent::Completed(
|
||||
ResponseMeta::new("upstream_response", "model-a"),
|
||||
))
|
||||
}
|
||||
|
||||
fn created() -> ProviderEvent {
|
||||
wire(
|
||||
"response.created",
|
||||
json!({"response":{
|
||||
"id":"resp_chat_test","object":"response","model":"upstream-model",
|
||||
"status":"in_progress","output":[]
|
||||
}}),
|
||||
)
|
||||
chunk(json!({"role":"assistant"}), Value::Null)
|
||||
}
|
||||
|
||||
fn json_completed() -> ProviderEvent {
|
||||
ProviderEvent::wire(ProtocolWireEvent::raw_json("chat_completions", bytes::Bytes::from(json!({
|
||||
"id":"chatcmpl_fixture", "object":"chat.completion", "created":100,
|
||||
"model":"model-a", "choices":[{"index":0,"message":{"role":"assistant","content":"answer"},"finish_reason":"stop"}]
|
||||
}).to_string())).unwrap()).with_fact(GatewayEvent::Completed(ResponseMeta::new("upstream_response", "model-a")))
|
||||
}
|
||||
|
||||
@@ -424,6 +424,7 @@ pub struct GenerateRequest {
|
||||
|
||||
#[derive(Clone, PartialEq)]
|
||||
struct GeneratePayload {
|
||||
source_protocol: Option<String>,
|
||||
requires_native_protocol: bool,
|
||||
source_image_generation: bool,
|
||||
wire_facts: RequestFacts,
|
||||
@@ -461,6 +462,15 @@ impl ClientTurn {
|
||||
}
|
||||
|
||||
impl GenerateRequest {
|
||||
/// 返回可信入口协议,直接转换只能更新当前 wire,不能改写请求来源
|
||||
#[must_use]
|
||||
pub fn source_protocol(&self) -> &str {
|
||||
self.payload
|
||||
.source_protocol
|
||||
.as_deref()
|
||||
.unwrap_or_else(|| self.payload.protocol_payload.protocol())
|
||||
}
|
||||
|
||||
/// 创建携带协议不透明正文的生成请求
|
||||
///
|
||||
/// 完整请求以原始 wire object 保存,协议层提取路由与权限所需的纯事实
|
||||
@@ -469,6 +479,7 @@ impl GenerateRequest {
|
||||
pub fn from_protocol_payload(protocol_payload: ProtocolPayload) -> Self {
|
||||
Self {
|
||||
payload: Arc::new(GeneratePayload {
|
||||
source_protocol: None,
|
||||
requires_native_protocol: false,
|
||||
source_image_generation: false,
|
||||
wire_facts: request_facts(protocol_payload.protocol(), protocol_payload.body()),
|
||||
@@ -917,8 +928,11 @@ impl Operation {
|
||||
pub fn requires_web_search(&self) -> bool {
|
||||
matches!(self, Self::Generate(request) if {
|
||||
let payload = request.protocol_payload();
|
||||
payload.protocol() == gateway_protocol::openai::OPENAI_PROTOCOL &&
|
||||
gateway_protocol::openai::web_search::is_required(payload.body())
|
||||
match payload.protocol() {
|
||||
gateway_protocol::openai::OPENAI_PROTOCOL => gateway_protocol::openai::web_search::is_required(payload.body()),
|
||||
gateway_protocol::chat_completions::CHAT_PROTOCOL => payload.body().get("web_search_options").is_some_and(serde_json::Value::is_object),
|
||||
_ => false,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1091,6 +1105,7 @@ impl Operation {
|
||||
}
|
||||
})?;
|
||||
if let Some(protocol) = target_protocol {
|
||||
payload.source_protocol = Some(payload.protocol_payload.protocol.clone());
|
||||
payload.protocol_payload.protocol = protocol;
|
||||
}
|
||||
payload.wire_facts =
|
||||
|
||||
@@ -157,7 +157,7 @@ pub struct ModelCapabilities {
|
||||
features: BTreeMap<Feature, SupportLevel>,
|
||||
max_output_tokens: Option<u64>,
|
||||
upstream_validates_features: bool,
|
||||
generation_protocol: Option<&'static str>,
|
||||
native_generation_protocols: BTreeSet<&'static str>,
|
||||
translated_generation_protocols: BTreeSet<&'static str>,
|
||||
reasoning_variants: BTreeMap<String, ReasoningModelVariant>,
|
||||
account_metadata: BTreeMap<crate::account::ProviderAccountId, AccountModelMetadata>,
|
||||
@@ -434,7 +434,7 @@ impl ModelCapabilities {
|
||||
features: BTreeMap::new(),
|
||||
max_output_tokens,
|
||||
upstream_validates_features: false,
|
||||
generation_protocol: None,
|
||||
native_generation_protocols: BTreeSet::new(),
|
||||
translated_generation_protocols: BTreeSet::new(),
|
||||
reasoning_variants: BTreeMap::new(),
|
||||
account_metadata: BTreeMap::new(),
|
||||
@@ -491,8 +491,18 @@ impl ModelCapabilities {
|
||||
|
||||
/// 声明原生生成协议;额外转换入口须显式登记,其他操作沿用各自的能力约束
|
||||
#[must_use]
|
||||
pub const fn with_generation_protocol(mut self, protocol: &'static str) -> Self {
|
||||
self.generation_protocol = Some(protocol);
|
||||
pub fn with_generation_protocol(mut self, protocol: &'static str) -> Self {
|
||||
self.native_generation_protocols = BTreeSet::from([protocol]);
|
||||
self
|
||||
}
|
||||
|
||||
/// 同一 Provider 可包含不同协议的账号,最终资格仍由账号选择器核对
|
||||
#[must_use]
|
||||
pub fn with_native_generation_protocols(
|
||||
mut self,
|
||||
protocols: impl IntoIterator<Item = &'static str>,
|
||||
) -> Self {
|
||||
self.native_generation_protocols = protocols.into_iter().collect();
|
||||
self
|
||||
}
|
||||
|
||||
@@ -512,17 +522,29 @@ impl ModelCapabilities {
|
||||
requirements: &CapabilityRequirements,
|
||||
) -> Option<BTreeSet<Feature>> {
|
||||
if operation.requires_native_protocol()
|
||||
&& self.generation_protocol != Some(operation.protocol())
|
||||
&& !self
|
||||
.native_generation_protocols
|
||||
.contains(operation.protocol())
|
||||
{
|
||||
return None;
|
||||
}
|
||||
if matches!(operation, crate::operation::Operation::Generate(_))
|
||||
&& self.generation_protocol.is_some_and(|protocol| {
|
||||
protocol != operation.protocol()
|
||||
&& !self
|
||||
.translated_generation_protocols
|
||||
.contains(operation.protocol())
|
||||
})
|
||||
&& !self.native_generation_protocols.is_empty()
|
||||
&& !self
|
||||
.native_generation_protocols
|
||||
.contains(operation.protocol())
|
||||
&& !self
|
||||
.translated_generation_protocols
|
||||
.contains(operation.protocol())
|
||||
{
|
||||
return None;
|
||||
}
|
||||
if matches!(operation, crate::operation::Operation::CountTokens(_))
|
||||
&& operation.protocol() != "token-count"
|
||||
&& !self.native_generation_protocols.is_empty()
|
||||
&& !self
|
||||
.native_generation_protocols
|
||||
.contains(operation.protocol())
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -1668,8 +1668,11 @@ impl RuntimeSnapshot {
|
||||
.and_then(|models| models.get(upstream_model));
|
||||
// 原生入口不能借同名模型、发现型目录的匿名透传或插件声明跨协议分派
|
||||
if operation.requires_native_protocol()
|
||||
&& capabilities.and_then(|model| model.generation_protocol)
|
||||
!= Some(operation.protocol())
|
||||
&& !capabilities.is_some_and(|model| {
|
||||
model
|
||||
.native_generation_protocols
|
||||
.contains(operation.protocol())
|
||||
})
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -399,3 +399,41 @@ fn image_request_should_preserve_generation_and_edit_payloads_opaque() {
|
||||
);
|
||||
assert!(!format!("{edit:?}").contains("data:image/png"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chat_source_survives_the_one_authorized_wire_translation() {
|
||||
let original = serde_json::json!({"model":"shared", "messages":[{"role":"user","content":"hello"}], "max_completion_tokens":1024});
|
||||
let operation = Operation::Generate(GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object(
|
||||
gateway_protocol::chat_completions::CHAT_PROTOCOL,
|
||||
original.as_object().unwrap().clone(),
|
||||
)
|
||||
.unwrap(),
|
||||
));
|
||||
let requirements = operation.capability_requirements();
|
||||
let translated = operation.translate_protocol_wire("anthropic", Bytes::from_static(br#"{"model":"shared","messages":[{"role":"user","content":"hello"}],"max_tokens":1024}"#)).unwrap();
|
||||
let Operation::Generate(generate) = &translated else {
|
||||
unreachable!()
|
||||
};
|
||||
assert_eq!(
|
||||
generate.source_protocol(),
|
||||
gateway_protocol::chat_completions::CHAT_PROTOCOL
|
||||
);
|
||||
assert_eq!(generate.protocol_payload().protocol(), "anthropic");
|
||||
assert_eq!(translated.capability_requirements(), requirements);
|
||||
let replaced = translated
|
||||
.replace_protocol_wire(None, serde_json::Map::new())
|
||||
.unwrap();
|
||||
let Operation::Generate(generate) = &replaced else {
|
||||
unreachable!()
|
||||
};
|
||||
assert_eq!(
|
||||
generate.source_protocol(),
|
||||
gateway_protocol::chat_completions::CHAT_PROTOCOL
|
||||
);
|
||||
assert!(
|
||||
replaced
|
||||
.translate_protocol_wire("genai", Bytes::from_static(b"{}"))
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1039,3 +1039,57 @@ fn native_count_catalog_and_execution_do_not_fall_back_to_another_protocol() {
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_model_native_protocols_do_not_borrow_chat_conversion_capabilities() {
|
||||
let native = capabilities()
|
||||
.with_native_generation_protocols(["openai", "anthropic"])
|
||||
.with_translated_generation_protocols([gateway_protocol::chat_completions::CHAT_PROTOCOL]);
|
||||
let genai = capabilities()
|
||||
.with_generation_protocol("genai")
|
||||
.with_translated_generation_protocols([gateway_protocol::chat_completions::CHAT_PROTOCOL]);
|
||||
let snapshot = RuntimeSnapshot::new(
|
||||
ConfigRevision::new(1).unwrap(),
|
||||
settings(),
|
||||
vec![
|
||||
ProviderKind::new("openai").unwrap(),
|
||||
ProviderKind::new("xai").unwrap(),
|
||||
],
|
||||
vec![
|
||||
model("openai", "shared", native),
|
||||
model("xai", "shared", genai),
|
||||
],
|
||||
vec![],
|
||||
)
|
||||
.unwrap()
|
||||
.with_account_directory(account_directory());
|
||||
for (protocol, expected) in [
|
||||
("openai", vec!["openai"]),
|
||||
("anthropic", vec!["openai"]),
|
||||
("genai", vec!["xai"]),
|
||||
(
|
||||
gateway_protocol::chat_completions::CHAT_PROTOCOL,
|
||||
vec!["openai", "xai"],
|
||||
),
|
||||
] {
|
||||
let operation = Operation::Generate(GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object(protocol, Default::default()).unwrap(),
|
||||
));
|
||||
let plan = snapshot
|
||||
.plan(
|
||||
&PublicModelId::new("shared").unwrap(),
|
||||
&operation,
|
||||
account_scope(),
|
||||
&RoutingContext::default(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
plan.candidates()
|
||||
.iter()
|
||||
.map(|candidate| candidate.provider().as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
expected,
|
||||
"{protocol}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -508,15 +508,14 @@ Responses 终端重新解码插件正文时读取改写后的正文上限;atte
|
||||
更早的改写使用上述 HTTP 请求的 `settings`。`request.head.settings_sources` 使用相同的来源结构,`execution.input` 表示进入当前 Key 作用域时的有效值。
|
||||
原生 Responses WebSocket 每轮请求读取当前宿主快照,重新认证并解析 Key 策略,同时保留握手阶段的显式改写;已开始的执行保持自己的冻结值
|
||||
|
||||
Chat Completions 在 request 与 attempt 挂载中使用规范化的 Responses 请求和响应正文,
|
||||
`request.head.endpoint` 仍为 `/v1/chat/completions`,`protocol` 仍为 `openai`。
|
||||
request 改写按 Responses 合同重新解码,响应先经过该合同的复核,再由 API 投影成 Chat 交给外层 HTTP 挂载。
|
||||
Chat 的下游流模式及 `include_usage` 由 API 持有,request 阶段不能切换已确定的下游流模式。
|
||||
同一边界的原样保留不要求 Chat 与 Responses 字节相同;需要读写 `messages` 或 `choices` 的插件应使用 HTTP 挂载,
|
||||
字段范围见 [Chat 合同](../../../../../docs/api.md#chat-completions-请求)
|
||||
Chat Completions 在 request 与 attempt 挂载中保留 Chat 正文,`request.head.endpoint` 为 `/v1/chat/completions`,
|
||||
`protocol` 为 `chat_completions`。request 改写按 Chat 合同重新解码,`messages` 不会在进入选路前变成 Responses `input`。
|
||||
Provider 选定账号后直接转换到实际目标,`outbound` 看到目标协议请求;回程直接产生 Chat JSON 或 chunks,再经过对应响应挂载与 API 交付校验。
|
||||
下游流模式由 API 入口固定,request 阶段不能切换已经确定的 HTTP 响应模式。
|
||||
同一挂载边界仍遵守原始字节保留规则;字段范围见 [Chat 合同](../../../../../docs/api.md#chat-completions-请求)
|
||||
|
||||
Messages 入站的 `protocol` 为 `anthropic`,端点为 `/v1/messages`;计数使用 `/v1/messages/count_tokens` 与 `count_tokens` 操作
|
||||
同协议请求保留原生正文,Responses 与 Messages 之间的转换发生在所选上游的执行边界
|
||||
Messages 入站的 `protocol` 为 `anthropic`,端点为 `/v1/messages`;计数使用 `/v1/messages/count_tokens` 与 `count_tokens` 操作。
|
||||
原生请求只选择同协议账号,不调用内置 Chat 转换。插件自行承担转换与回译;宿主不保留旧 Chat 视图,不修复插件输出或补偿插件状态
|
||||
|
||||
中间件可读取和改写完整请求、响应 headers、正文与响应帧,也不按字段名称过滤认证、Cookie、会话或连接头。
|
||||
该能力遵循[完整信任](manifest.md#完整信任)边界;类型、HTTP 格式、大小及资源生命周期仍需符合合同
|
||||
|
||||
@@ -12,6 +12,8 @@ name = "main"
|
||||
path = "tests/main.rs"
|
||||
|
||||
[dependencies]
|
||||
sha2 = "0.11.0"
|
||||
url = "2.5.8"
|
||||
http = "1.5.0"
|
||||
httpdate = "1.0.3"
|
||||
memchr = "2.8.3"
|
||||
|
||||
@@ -1,175 +0,0 @@
|
||||
//! 文本、多模态内容和不透明回传载荷的协议表示
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const ANTHROPIC_CARRIER: &str = "cpr:anthropic:v1:";
|
||||
const OPENAI_CARRIER: &str = "cpr:openai:v1:";
|
||||
pub(crate) const GENAI_CARRIER: &str = "cpr:genai:v1:";
|
||||
const REDACTED_CARRIER: &str = "claude-redacted-thinking:";
|
||||
|
||||
pub(super) fn text(value: &Value) -> String {
|
||||
match value {
|
||||
Value::String(value) => value.clone(),
|
||||
Value::Array(parts) => parts
|
||||
.iter()
|
||||
.filter_map(|part| {
|
||||
part.get("text")
|
||||
.or_else(|| part.get("thinking"))
|
||||
.and_then(Value::as_str)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n"),
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn blocks(value: Option<&Value>) -> Vec<Value> {
|
||||
match value {
|
||||
Some(Value::String(text)) => vec![json!({"type":"text","text":text})],
|
||||
Some(Value::Array(parts)) => parts.clone(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn to_responses_content(block: &Value, assistant: bool) -> Option<Value> {
|
||||
match block.get("type").and_then(Value::as_str)? {
|
||||
"text" => Some(
|
||||
json!({"type": if assistant {"output_text"} else {"input_text"}, "text":block.get("text").and_then(Value::as_str).unwrap_or_default()}),
|
||||
),
|
||||
"image" => {
|
||||
let source = block.get("source")?;
|
||||
let url = source_url(source)?;
|
||||
Some(json!({"type":"input_image","image_url":url}))
|
||||
}
|
||||
"document" => {
|
||||
let source = block.get("source")?;
|
||||
match source.get("type").and_then(Value::as_str)? {
|
||||
"text" => Some(
|
||||
json!({"type":"input_text","text":source.get("data").and_then(Value::as_str).unwrap_or_default()}),
|
||||
),
|
||||
"file" => Some(json!({"type":"input_file","file_id":source.get("file_id")?})),
|
||||
"url" => Some(json!({"type":"input_file","file_url":source.get("url")?})),
|
||||
"base64" => Some(
|
||||
json!({"type":"input_file","filename":block.get("title").and_then(Value::as_str).unwrap_or("document.pdf"),"file_data":source_url(source)?}),
|
||||
),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
"search_result" => Some(
|
||||
json!({"type":"input_text","text":text(block.get("content").unwrap_or(&Value::Null))}),
|
||||
),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn to_messages_content(part: &Value) -> Option<Value> {
|
||||
match part.get("type").and_then(Value::as_str)? {
|
||||
"input_text" | "output_text" | "text" => Some(
|
||||
json!({"type":"text","text":part.get("text").and_then(Value::as_str).unwrap_or_default()}),
|
||||
),
|
||||
"refusal" => Some(
|
||||
json!({"type":"text","text":part.get("refusal").and_then(Value::as_str).unwrap_or_default()}),
|
||||
),
|
||||
"input_image" => {
|
||||
let url = part
|
||||
.get("image_url")
|
||||
.and_then(|v| v.as_str().or_else(|| v.get("url").and_then(Value::as_str)))?;
|
||||
Some(json!({"type":"image","source":url_source(url)}))
|
||||
}
|
||||
"input_file" => {
|
||||
let source = if let Some(data) = part.get("file_data").and_then(Value::as_str) {
|
||||
url_source(data)
|
||||
} else if let Some(url) = part.get("file_url").and_then(Value::as_str) {
|
||||
json!({"type":"url","url":url})
|
||||
} else {
|
||||
json!({"type":"file","file_id":part.get("file_id")?})
|
||||
};
|
||||
Some(json!({"type":"document","source":source}))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn source_url(source: &Value) -> Option<String> {
|
||||
match source.get("type").and_then(Value::as_str)? {
|
||||
"url" => source.get("url").and_then(Value::as_str).map(str::to_owned),
|
||||
"base64" => Some(format!(
|
||||
"data:{};base64,{}",
|
||||
source.get("media_type").and_then(Value::as_str)?,
|
||||
source.get("data").and_then(Value::as_str)?
|
||||
)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn split_data_url(url: &str) -> Option<(&str, &str)> {
|
||||
url.strip_prefix("data:")?.split_once(";base64,")
|
||||
}
|
||||
|
||||
fn url_source(url: &str) -> Value {
|
||||
if let Some((media_type, data)) = split_data_url(url) {
|
||||
return json!({"type":"base64","media_type":media_type,"data":data});
|
||||
}
|
||||
json!({"type":"url","url":url})
|
||||
}
|
||||
|
||||
pub(super) fn reasoning_text(item: &Value) -> String {
|
||||
let summary = text(item.get("summary").unwrap_or(&Value::Null));
|
||||
if summary.is_empty() {
|
||||
text(item.get("content").unwrap_or(&Value::Null))
|
||||
} else {
|
||||
summary
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn anthropic_carrier(block: &Value) -> String {
|
||||
format!("{ANTHROPIC_CARRIER}{block}")
|
||||
}
|
||||
|
||||
pub(super) fn openai_carrier(item: &Value) -> String {
|
||||
format!("{OPENAI_CARRIER}{item}")
|
||||
}
|
||||
|
||||
pub(super) fn is_openai_carrier(block: &Value) -> bool {
|
||||
block.get("type").and_then(Value::as_str) == Some("thinking")
|
||||
&& block
|
||||
.get("signature")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|signature| signature.starts_with(OPENAI_CARRIER))
|
||||
}
|
||||
|
||||
pub(super) fn is_anthropic_carrier(item: &Value) -> bool {
|
||||
item.get("type").and_then(Value::as_str) == Some("reasoning")
|
||||
&& item
|
||||
.get("encrypted_content")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|carrier| carrier.starts_with(ANTHROPIC_CARRIER))
|
||||
}
|
||||
|
||||
pub(crate) fn restore_anthropic(item: &Value) -> Option<Value> {
|
||||
let carrier = item.get("encrypted_content")?.as_str()?;
|
||||
if let Some(raw) = carrier.strip_prefix(ANTHROPIC_CARRIER) {
|
||||
return serde_json::from_str(raw).ok();
|
||||
}
|
||||
if let Some(data) = carrier.strip_prefix(REDACTED_CARRIER) {
|
||||
return Some(json!({"type":"redacted_thinking","data":data}));
|
||||
}
|
||||
// CPA 识别来源后回放签名,CPR 自己发出的载荷携带完整块以保留精确回传内容
|
||||
if carrier.starts_with("claude#") || carrier.starts_with("anthropic#") {
|
||||
return Some(
|
||||
json!({"type":"thinking","thinking":reasoning_text(item),"signature":carrier.split_once('#')?.1}),
|
||||
);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub(super) fn restore_openai(block: &Value) -> Option<Value> {
|
||||
let signature = block.get("signature")?.as_str()?;
|
||||
if let Some(raw) = signature.strip_prefix(OPENAI_CARRIER) {
|
||||
return serde_json::from_str(raw).ok();
|
||||
}
|
||||
if signature.starts_with("gAAAA") {
|
||||
return Some(json!({"type":"reasoning","summary":[],"encrypted_content":signature}));
|
||||
}
|
||||
None
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
//! 协议转换的结构错误
|
||||
//! Messages 原生解析的结构错误
|
||||
|
||||
use thiserror::Error;
|
||||
|
||||
/// 可安全传递给协议边界的转换错误
|
||||
/// 可安全传递给 Messages 协议边界的解析错误
|
||||
#[derive(Debug, Error, Clone, PartialEq, Eq)]
|
||||
pub enum TranslationError {
|
||||
pub enum MessageError {
|
||||
/// 请求结构无法解析
|
||||
#[error("{0}")]
|
||||
InvalidRequest(&'static str),
|
||||
|
||||
@@ -1,34 +1,18 @@
|
||||
//! Messages 编解码、用量事实和 Responses 双向转换
|
||||
//! Messages 原生解析、用量事实和流聚合
|
||||
|
||||
mod capabilities;
|
||||
mod content;
|
||||
mod error;
|
||||
mod request;
|
||||
mod response;
|
||||
mod session;
|
||||
mod stream;
|
||||
mod thinking;
|
||||
mod tools;
|
||||
mod usage;
|
||||
|
||||
pub(crate) use content::{GENAI_CARRIER, restore_anthropic, split_data_url};
|
||||
pub(crate) use tools::{ToolSet, allowed_tools};
|
||||
|
||||
pub use capabilities::MessagesModelCapabilities;
|
||||
pub use error::TranslationError;
|
||||
pub use request::{
|
||||
messages_to_responses_count_request, messages_to_responses_request,
|
||||
responses_to_messages_request, strip_foreign_reasoning_for_responses,
|
||||
strip_foreign_thinking_for_messages, validate_count_request, validate_request,
|
||||
};
|
||||
pub use response::{
|
||||
messages_to_responses_event, messages_to_responses_response, responses_to_messages_response,
|
||||
};
|
||||
pub use error::MessageError;
|
||||
pub use request::{validate_count_request, validate_request};
|
||||
pub use session::claude_session_id;
|
||||
pub use stream::{
|
||||
MessagesAccumulator, MessagesToResponsesStream, ResponsesToMessagesStream,
|
||||
message_to_stream_events,
|
||||
};
|
||||
pub use stream::{MessagesAccumulator, message_to_stream_events};
|
||||
pub use thinking::messages_request_effort;
|
||||
pub use usage::MessageUsage;
|
||||
|
||||
|
||||
@@ -1,50 +1,13 @@
|
||||
//! Messages 与 Responses 请求的无状态转换
|
||||
//! 校验原生 Messages 请求与计数合同
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use super::{
|
||||
MessagesModelCapabilities, TranslationError, content, thinking,
|
||||
tools::{ToolSet, messages_tools},
|
||||
};
|
||||
|
||||
/// 原生 Messages 上游不能消费本网关封装的外来源思考,仅删除已知载荷
|
||||
pub fn strip_foreign_thinking_for_messages(request: &mut Map<String, Value>) {
|
||||
let Some(messages) = request.get_mut("messages").and_then(Value::as_array_mut) else {
|
||||
return;
|
||||
};
|
||||
messages.retain_mut(|message| {
|
||||
let Some(blocks) = message.get_mut("content").and_then(Value::as_array_mut) else {
|
||||
return true;
|
||||
};
|
||||
let previous_len = blocks.len();
|
||||
blocks.retain(|block| {
|
||||
!content::is_openai_carrier(block)
|
||||
&& !(block["type"] == "thinking"
|
||||
&& block
|
||||
.get("signature")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|signature| {
|
||||
signature.starts_with(super::content::GENAI_CARRIER)
|
||||
}))
|
||||
});
|
||||
blocks.len() == previous_len || !blocks.is_empty()
|
||||
});
|
||||
}
|
||||
|
||||
/// 原生 Responses 上游不能消费本网关封装的 Anthropic 思考
|
||||
pub fn strip_foreign_reasoning_for_responses(request: &mut Map<String, Value>) {
|
||||
if let Some(input) = request.get_mut("input").and_then(Value::as_array_mut) {
|
||||
input.retain(|item| !content::is_anthropic_carrier(item));
|
||||
}
|
||||
}
|
||||
use super::MessageError;
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
/// 校验 Messages 生成请求的必需字段
|
||||
pub fn validate_request(request: &Map<String, Value>) -> Result<(), TranslationError> {
|
||||
pub fn validate_request(request: &Map<String, Value>) -> Result<(), MessageError> {
|
||||
validate_count_request(request)?;
|
||||
if request.get("max_tokens").and_then(Value::as_u64).is_none() {
|
||||
return Err(TranslationError::InvalidRequest(
|
||||
return Err(MessageError::InvalidRequest(
|
||||
"The max_tokens field must be a non-negative integer.",
|
||||
));
|
||||
}
|
||||
@@ -52,21 +15,25 @@ pub fn validate_request(request: &Map<String, Value>) -> Result<(), TranslationE
|
||||
}
|
||||
|
||||
/// 计数请求没有生成预算要求
|
||||
pub fn validate_count_request(request: &Map<String, Value>) -> Result<(), TranslationError> {
|
||||
pub fn validate_count_request(request: &Map<String, Value>) -> Result<(), MessageError> {
|
||||
if !request
|
||||
.get("model")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|v| !v.trim().is_empty())
|
||||
{
|
||||
return Err(TranslationError::InvalidRequest(
|
||||
return Err(MessageError::InvalidRequest(
|
||||
"The model field must be a non-empty string.",
|
||||
));
|
||||
}
|
||||
let messages = request.get("messages").and_then(Value::as_array).ok_or(
|
||||
TranslationError::InvalidRequest("The messages field must be an array."),
|
||||
)?;
|
||||
let messages =
|
||||
request
|
||||
.get("messages")
|
||||
.and_then(Value::as_array)
|
||||
.ok_or(MessageError::InvalidRequest(
|
||||
"The messages field must be an array.",
|
||||
))?;
|
||||
if messages.is_empty() {
|
||||
return Err(TranslationError::InvalidRequest(
|
||||
return Err(MessageError::InvalidRequest(
|
||||
"The messages field must not be empty.",
|
||||
));
|
||||
}
|
||||
@@ -76,7 +43,7 @@ pub fn validate_count_request(request: &Map<String, Value>) -> Result<(), Transl
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|v| matches!(v, "user" | "assistant" | "system"))
|
||||
{
|
||||
return Err(TranslationError::InvalidRequest(
|
||||
return Err(MessageError::InvalidRequest(
|
||||
"Each message role must be user, assistant, or system.",
|
||||
));
|
||||
}
|
||||
@@ -89,7 +56,7 @@ pub fn validate_count_request(request: &Map<String, Value>) -> Result<(), Transl
|
||||
.any(|block| block.get("type").and_then(Value::as_str).is_none())
|
||||
})
|
||||
{
|
||||
return Err(TranslationError::InvalidRequest(
|
||||
return Err(MessageError::InvalidRequest(
|
||||
"Each content block must contain a type string.",
|
||||
));
|
||||
}
|
||||
@@ -97,480 +64,20 @@ pub fn validate_count_request(request: &Map<String, Value>) -> Result<(), Transl
|
||||
.get("content")
|
||||
.is_some_and(|v| v.is_string() || v.is_array())
|
||||
{
|
||||
return Err(TranslationError::InvalidRequest(
|
||||
return Err(MessageError::InvalidRequest(
|
||||
"Each message content must be a string or an array.",
|
||||
));
|
||||
}
|
||||
}
|
||||
if request.get("stream").is_some_and(|v| !v.is_boolean()) {
|
||||
return Err(TranslationError::InvalidRequest(
|
||||
return Err(MessageError::InvalidRequest(
|
||||
"The stream field must be a boolean.",
|
||||
));
|
||||
}
|
||||
if request.get("tools").is_some_and(|v| !v.is_array()) {
|
||||
return Err(TranslationError::InvalidRequest(
|
||||
return Err(MessageError::InvalidRequest(
|
||||
"The tools field must be an array.",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Messages 请求转换为 Responses,外来 thinking 仅通过明确来源载荷恢复
|
||||
pub fn messages_to_responses_request(
|
||||
request: &Map<String, Value>,
|
||||
) -> Result<Map<String, Value>, TranslationError> {
|
||||
validate_request(request)?;
|
||||
if request
|
||||
.get("tools")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|tools| {
|
||||
tools.iter().any(|tool| {
|
||||
tool["type"]
|
||||
.as_str()
|
||||
.is_some_and(|kind| kind.starts_with("web_search_"))
|
||||
&& !tool["max_uses"].is_null()
|
||||
})
|
||||
})
|
||||
{
|
||||
return Err(TranslationError::InvalidRequest(
|
||||
"The Responses upstream cannot enforce the web search usage limit.",
|
||||
));
|
||||
}
|
||||
messages_to_responses_body(request)
|
||||
}
|
||||
|
||||
/// 计数请求复用内容转换,不引入生成预算
|
||||
pub fn messages_to_responses_count_request(
|
||||
request: &Map<String, Value>,
|
||||
) -> Result<Map<String, Value>, TranslationError> {
|
||||
validate_count_request(request)?;
|
||||
messages_to_responses_body(request)
|
||||
}
|
||||
|
||||
fn messages_to_responses_body(
|
||||
request: &Map<String, Value>,
|
||||
) -> Result<Map<String, Value>, TranslationError> {
|
||||
let mut result = Map::new();
|
||||
copy_fields(
|
||||
request,
|
||||
&mut result,
|
||||
&["model", "stream", "temperature", "top_p"],
|
||||
);
|
||||
// speed 与服务档位不是同一概念,按 CPA 映射显式 fast,其余使用目标协议的档位
|
||||
if request.get("speed").and_then(Value::as_str) == Some("fast") {
|
||||
result.insert("service_tier".into(), json!("priority"));
|
||||
} else if let Some(tier) = request.get("service_tier").and_then(Value::as_str) {
|
||||
match tier {
|
||||
"auto" => {
|
||||
result.insert("service_tier".into(), json!("auto"));
|
||||
}
|
||||
"standard_only" => {
|
||||
result.insert("service_tier".into(), json!("default"));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let Some(max_tokens) = request.get("max_tokens") {
|
||||
result.insert("max_output_tokens".into(), max_tokens.clone());
|
||||
}
|
||||
let mut input = Vec::new();
|
||||
let system = content::blocks(request.get("system"))
|
||||
.iter()
|
||||
.filter_map(|block| content::to_responses_content(block, false))
|
||||
.collect::<Vec<_>>();
|
||||
if !system.is_empty() {
|
||||
input.push(json!({"type":"message","role":"developer","content":system}));
|
||||
}
|
||||
for message in request
|
||||
.get("messages")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
let role = message
|
||||
.get("role")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("user");
|
||||
let mut parts = Vec::new();
|
||||
for block in content::blocks(message.get("content")) {
|
||||
match block
|
||||
.get("type")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default()
|
||||
{
|
||||
"tool_use" => {
|
||||
flush_responses(&mut input, role, &mut parts);
|
||||
input.push(json!({"type":"function_call","call_id":block.get("id"),"name":block.get("name"),"arguments":block.get("input").cloned().unwrap_or_else(||json!({})).to_string()}));
|
||||
}
|
||||
"tool_result" => {
|
||||
flush_responses(&mut input, role, &mut parts);
|
||||
let output = tool_output_to_responses(block.get("content"));
|
||||
input.push(json!({"type":"function_call_output","call_id":block.get("tool_use_id"),"output":output}));
|
||||
}
|
||||
"thinking" | "redacted_thinking" => {
|
||||
flush_responses(&mut input, role, &mut parts);
|
||||
if let Some(item) = content::restore_openai(&block) {
|
||||
input.push(item);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if let Some(part) = content::to_responses_content(&block, role == "assistant") {
|
||||
parts.push(part);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
flush_responses(&mut input, role, &mut parts);
|
||||
}
|
||||
result.insert("input".into(), Value::Array(input));
|
||||
if let Some(tools) = request.get("tools").and_then(Value::as_array) {
|
||||
result.insert("tools".into(), Value::Array(messages_tools(tools)));
|
||||
}
|
||||
if let Some(choice) = request.get("tool_choice") {
|
||||
let choice = match choice.get("type").and_then(Value::as_str).unwrap_or("auto") {
|
||||
"any" => json!("required"),
|
||||
"none" => json!("none"),
|
||||
"tool" => json!({"type":"function","name":choice.get("name")}),
|
||||
_ => json!("auto"),
|
||||
};
|
||||
result.insert("tool_choice".into(), choice);
|
||||
}
|
||||
if let Some(disabled) = request
|
||||
.get("tool_choice")
|
||||
.and_then(|v| v.get("disable_parallel_tool_use"))
|
||||
.and_then(Value::as_bool)
|
||||
{
|
||||
result.insert("parallel_tool_calls".into(), json!(!disabled));
|
||||
}
|
||||
result.insert("reasoning".into(), thinking::to_responses(request));
|
||||
result.insert("include".into(), json!(["reasoning.encrypted_content"]));
|
||||
if let Some(format) = request.get("output_config").and_then(|v| v.get("format")) {
|
||||
let mut format = format.clone();
|
||||
if format.get("type").and_then(Value::as_str) == Some("json_schema") {
|
||||
format["name"] = json!("response");
|
||||
}
|
||||
result.insert("text".into(), json!({"format":format}));
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Responses 请求转换为 Messages,工具结果采用 CPA 的配对与孤立结果降级规则
|
||||
pub fn responses_to_messages_request(
|
||||
request: &Map<String, Value>,
|
||||
capabilities: &MessagesModelCapabilities,
|
||||
) -> Result<Map<String, Value>, TranslationError> {
|
||||
let mut result = Map::new();
|
||||
copy_fields(
|
||||
request,
|
||||
&mut result,
|
||||
&["model", "stream", "temperature", "top_p"],
|
||||
);
|
||||
let requested_maximum =
|
||||
match request.get("max_output_tokens") {
|
||||
None | Some(Value::Null) => 32000,
|
||||
Some(value) => value.as_u64().filter(|value| *value > 0).ok_or(
|
||||
TranslationError::InvalidRequest(
|
||||
"The max_output_tokens field must be a positive integer.",
|
||||
),
|
||||
)?,
|
||||
};
|
||||
let maximum = capabilities
|
||||
.max_tokens
|
||||
.map_or(requested_maximum, |limit| requested_maximum.min(limit));
|
||||
result.insert("max_tokens".into(), json!(maximum));
|
||||
match request.get("service_tier").and_then(Value::as_str) {
|
||||
Some("priority") => {
|
||||
result.insert("speed".into(), json!("fast"));
|
||||
}
|
||||
Some("default") => {
|
||||
result.insert("service_tier".into(), json!("standard_only"));
|
||||
}
|
||||
Some("auto") => {
|
||||
result.insert("service_tier".into(), json!("auto"));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
result.extend(responses_to_messages_content(
|
||||
request,
|
||||
capabilities.hosted_web_search != Some(false),
|
||||
)?);
|
||||
thinking::apply_to_messages(request, &mut result, capabilities, maximum);
|
||||
if request
|
||||
.get("tool_choice")
|
||||
.is_some_and(|c| c["type"] == "allowed_tools" && c["mode"] == "required")
|
||||
&& result["tool_choice"]["type"] != "any"
|
||||
{
|
||||
return Err(TranslationError::InvalidRequest(
|
||||
"The Messages upstream cannot require an allowed tool with this thinking mode.",
|
||||
));
|
||||
}
|
||||
if matches!(
|
||||
result
|
||||
.get("thinking")
|
||||
.and_then(|value| value.get("type"))
|
||||
.and_then(Value::as_str),
|
||||
Some("enabled" | "adaptive")
|
||||
) {
|
||||
// CPA 在生成推理配置后移除不相容的采样参数;原生 Messages 不经过此转换
|
||||
result.shift_remove("temperature");
|
||||
result.shift_remove("top_p");
|
||||
}
|
||||
if let Some(format) = request.get("text").and_then(|v| v.get("format"))
|
||||
&& format.get("type").and_then(Value::as_str) == Some("json_schema")
|
||||
{
|
||||
let config = result.entry("output_config").or_insert_with(|| json!({}));
|
||||
config["format"] = json!({"type":"json_schema","schema":format.get("schema").cloned().unwrap_or_else(||json!({}))});
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn responses_to_messages_content(
|
||||
request: &Map<String, Value>,
|
||||
hosted_search: bool,
|
||||
) -> Result<Map<String, Value>, TranslationError> {
|
||||
let tools = ToolSet::from_responses(request);
|
||||
let mut result = Map::new();
|
||||
let mut system = Vec::new();
|
||||
if let Some(instructions) = request.get("instructions").and_then(Value::as_str)
|
||||
&& !instructions.is_empty()
|
||||
{
|
||||
system.push(json!({"type":"text","text":instructions}));
|
||||
}
|
||||
let mut messages = Vec::new();
|
||||
let inputs = match request.get("input") {
|
||||
Some(Value::String(input)) => {
|
||||
append_message(
|
||||
&mut messages,
|
||||
"user",
|
||||
vec![json!({"type":"text","text":input})],
|
||||
);
|
||||
&[][..]
|
||||
}
|
||||
Some(Value::Array(input)) => input.as_slice(),
|
||||
Some(Value::Null) | None => &[],
|
||||
_ => {
|
||||
return Err(TranslationError::InvalidRequest(
|
||||
"The input field must be a string or an array.",
|
||||
));
|
||||
}
|
||||
};
|
||||
for (position, item) in inputs.iter().enumerate() {
|
||||
match item
|
||||
.get("type")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("message")
|
||||
{
|
||||
"function_call" | "custom_tool_call" => {
|
||||
let custom = item.get("type").and_then(Value::as_str) == Some("custom_tool_call");
|
||||
let input = if custom {
|
||||
json!({"input":item.get("input").and_then(Value::as_str).unwrap_or_default()})
|
||||
} else {
|
||||
item.get("arguments")
|
||||
.and_then(Value::as_str)
|
||||
.and_then(|v| serde_json::from_str::<Value>(v).ok())
|
||||
.filter(Value::is_object)
|
||||
.unwrap_or_else(|| json!({}))
|
||||
};
|
||||
let name = item.get("name").and_then(Value::as_str).unwrap_or_default();
|
||||
let wire_name =
|
||||
tools.wire_name(name, item.get("namespace").and_then(Value::as_str));
|
||||
append_message(
|
||||
&mut messages,
|
||||
"assistant",
|
||||
vec![
|
||||
json!({"type":"tool_use","id":item.get("call_id").cloned().unwrap_or_else(||json!(format!("call_{position}"))),"name":wire_name,"input":input}),
|
||||
],
|
||||
);
|
||||
}
|
||||
"function_call_output" | "custom_tool_call_output" => {
|
||||
let call_id = item
|
||||
.get("call_id")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default();
|
||||
let output = item.get("output").unwrap_or(&Value::Null);
|
||||
let mut block = json!({"type":"tool_result","tool_use_id":call_id,"content":tool_output_to_messages(output)});
|
||||
if item.get("status").and_then(Value::as_str) == Some("incomplete") {
|
||||
block["is_error"] = json!(true);
|
||||
}
|
||||
append_message(&mut messages, "user", vec![block]);
|
||||
}
|
||||
"reasoning" => {
|
||||
if let Some(block) = content::restore_anthropic(item) {
|
||||
append_message(&mut messages, "assistant", vec![block]);
|
||||
}
|
||||
}
|
||||
"message" => {
|
||||
let role = item.get("role").and_then(Value::as_str).unwrap_or("user");
|
||||
let parts = match item.get("content") {
|
||||
Some(Value::String(text)) => vec![json!({"type":"text","text":text})],
|
||||
Some(Value::Array(parts)) => parts
|
||||
.iter()
|
||||
.filter_map(content::to_messages_content)
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
if matches!(role, "system" | "developer") {
|
||||
system.extend(parts);
|
||||
} else {
|
||||
append_message(&mut messages, role, parts);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if !system.is_empty() {
|
||||
result.insert("system".into(), Value::Array(system));
|
||||
}
|
||||
result.insert(
|
||||
"messages".into(),
|
||||
Value::Array(normalize_tool_pairing(messages)),
|
||||
);
|
||||
tools.write_messages_tools(request, &mut result, hosted_search)?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn copy_fields(source: &Map<String, Value>, target: &mut Map<String, Value>, fields: &[&str]) {
|
||||
for field in fields {
|
||||
if let Some(value) = source.get(*field) {
|
||||
target.insert((*field).into(), value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn flush_responses(input: &mut Vec<Value>, role: &str, parts: &mut Vec<Value>) {
|
||||
if !parts.is_empty() {
|
||||
input.push(json!({"type":"message","role":role,"content":std::mem::take(parts)}));
|
||||
}
|
||||
}
|
||||
|
||||
fn append_message(messages: &mut Vec<Value>, role: &str, parts: Vec<Value>) {
|
||||
if parts.is_empty() {
|
||||
return;
|
||||
}
|
||||
if let Some(last) = messages.last_mut()
|
||||
&& last.get("role").and_then(Value::as_str) == Some(role)
|
||||
&& let Some(content) = last.get_mut("content").and_then(Value::as_array_mut)
|
||||
{
|
||||
content.extend(parts);
|
||||
return;
|
||||
}
|
||||
messages.push(json!({"role":role,"content":parts}));
|
||||
}
|
||||
|
||||
fn tool_output_to_responses(value: Option<&Value>) -> Value {
|
||||
match value {
|
||||
Some(Value::String(text)) => json!(text),
|
||||
Some(Value::Array(blocks)) => Value::Array(
|
||||
blocks
|
||||
.iter()
|
||||
.filter_map(|block| content::to_responses_content(block, false))
|
||||
.collect(),
|
||||
),
|
||||
Some(value) => json!(value.to_string()),
|
||||
None => json!(""),
|
||||
}
|
||||
}
|
||||
|
||||
fn tool_output_to_messages(value: &Value) -> Value {
|
||||
match value {
|
||||
Value::String(text) => json!(text),
|
||||
Value::Array(parts) => Value::Array(
|
||||
parts
|
||||
.iter()
|
||||
.filter_map(content::to_messages_content)
|
||||
.collect(),
|
||||
),
|
||||
_ => json!(value.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
// Messages 要求每次工具调用在紧邻用户轮次闭合,不能用历史中的任意同 ID 调用配对
|
||||
fn normalize_tool_pairing(messages: Vec<Value>) -> Vec<Value> {
|
||||
let mut normalized = Vec::with_capacity(messages.len());
|
||||
let mut pending = Vec::<String>::new();
|
||||
for mut message in messages {
|
||||
if message["role"] == "user" {
|
||||
if let Some(blocks) = message.get_mut("content").and_then(Value::as_array_mut) {
|
||||
normalize_tool_results(blocks, &pending);
|
||||
}
|
||||
pending.clear();
|
||||
} else {
|
||||
if !pending.is_empty() {
|
||||
normalized.push(interrupted_tools_message(&pending));
|
||||
}
|
||||
pending = message
|
||||
.get("content")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|block| message["role"] == "assistant" && block["type"] == "tool_use")
|
||||
.filter_map(|block| block.get("id").and_then(Value::as_str))
|
||||
.filter(|id| !id.is_empty())
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
}
|
||||
normalized.push(message);
|
||||
}
|
||||
if !pending.is_empty() {
|
||||
normalized.push(interrupted_tools_message(&pending));
|
||||
}
|
||||
normalized
|
||||
}
|
||||
|
||||
fn normalize_tool_results(blocks: &mut Vec<Value>, pending: &[String]) {
|
||||
// 只在本轮保留同 ID 的最后一个结果;延迟结果不能抹掉更早轮次已经闭合的调用
|
||||
let mut seen = BTreeSet::new();
|
||||
blocks.reverse();
|
||||
blocks.retain(|block| tool_result_id(block).is_none_or(|id| seen.insert(id.to_owned())));
|
||||
blocks.reverse();
|
||||
|
||||
let mut unanswered = pending.iter().map(String::as_str).collect::<BTreeSet<_>>();
|
||||
let mut results = Vec::new();
|
||||
let mut ordinary = Vec::new();
|
||||
for mut block in std::mem::take(blocks) {
|
||||
match tool_result_id(&block) {
|
||||
Some(id) if unanswered.remove(id) => results.push(block),
|
||||
Some(_) => {
|
||||
let content = block.get_mut("content").map(Value::take);
|
||||
let parts = content::blocks(content.as_ref())
|
||||
.into_iter()
|
||||
.filter(|part| {
|
||||
part["type"] != "text"
|
||||
|| part
|
||||
.get("text")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|text| !text.trim().is_empty())
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if parts.is_empty() {
|
||||
ordinary.push(json!({"type":"text","text":"Tool result was empty."}));
|
||||
} else {
|
||||
ordinary.extend(parts);
|
||||
}
|
||||
}
|
||||
None => ordinary.push(block),
|
||||
}
|
||||
}
|
||||
blocks.extend(
|
||||
pending
|
||||
.iter()
|
||||
.filter(|id| unanswered.contains(id.as_str()))
|
||||
.map(|id| interrupted_tool_result(id)),
|
||||
);
|
||||
blocks.extend(results);
|
||||
blocks.extend(ordinary);
|
||||
}
|
||||
|
||||
fn tool_result_id(block: &Value) -> Option<&str> {
|
||||
(block["type"] == "tool_result")
|
||||
.then(|| block.get("tool_use_id").and_then(Value::as_str))
|
||||
.flatten()
|
||||
}
|
||||
|
||||
fn interrupted_tool_result(id: &str) -> Value {
|
||||
json!({"type":"tool_result","tool_use_id":id,"is_error":true,"content":"Tool call was interrupted before any output was recorded."})
|
||||
}
|
||||
|
||||
fn interrupted_tools_message(pending: &[String]) -> Value {
|
||||
json!({"role":"user","content":pending.iter().map(|id| interrupted_tool_result(id)).collect::<Vec<_>>()})
|
||||
}
|
||||
|
||||
@@ -1,228 +0,0 @@
|
||||
//! Messages 与 Responses 完整响应的映射
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use super::{MessageUsage, TranslationError, content, tools::ToolSet, usage};
|
||||
|
||||
/// 将完整 Messages JSON 转换为单个 Responses 终态事件
|
||||
pub fn messages_to_responses_event(
|
||||
message: &Value,
|
||||
original_request: &Map<String, Value>,
|
||||
) -> Result<Value, TranslationError> {
|
||||
messages_to_responses_response(message, original_request).map(terminal_response_event)
|
||||
}
|
||||
|
||||
pub(super) fn terminal_response_event(response: Value) -> Value {
|
||||
let event_type = match response.get("status").and_then(Value::as_str) {
|
||||
Some("incomplete") => "response.incomplete",
|
||||
Some("failed") => "response.failed",
|
||||
_ => "response.completed",
|
||||
};
|
||||
json!({"type":event_type,"response":response})
|
||||
}
|
||||
|
||||
/// Messages 完整响应转为 Responses,原始请求用于 custom 工具与模型身份恢复
|
||||
pub fn messages_to_responses_response(
|
||||
message: &Value,
|
||||
original_request: &Map<String, Value>,
|
||||
) -> Result<Value, TranslationError> {
|
||||
complete_response(
|
||||
message,
|
||||
original_request.get("model"),
|
||||
&ToolSet::identities(original_request),
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn complete_response(
|
||||
message: &Value,
|
||||
model: Option<&Value>,
|
||||
tools: &ToolSet,
|
||||
) -> Result<Value, TranslationError> {
|
||||
if message.get("type").and_then(Value::as_str) == Some("error") {
|
||||
return Ok(response_from_message(message, model, Vec::new()));
|
||||
}
|
||||
let blocks =
|
||||
message
|
||||
.get("content")
|
||||
.and_then(Value::as_array)
|
||||
.ok_or(TranslationError::InvalidEvent(
|
||||
"The Messages response content must be an array.",
|
||||
))?;
|
||||
let id = message
|
||||
.get("id")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("resp_messages");
|
||||
let output = blocks
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, block)| {
|
||||
messages_block_to_response(block, tools, &format!("{id}_{index}"))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
Ok(response_from_message(message, model, output))
|
||||
}
|
||||
|
||||
pub(super) fn response_from_message(
|
||||
message: &Value,
|
||||
model: Option<&Value>,
|
||||
output: Vec<Value>,
|
||||
) -> Value {
|
||||
if message.get("type").and_then(Value::as_str) == Some("error") {
|
||||
return json!({"object":"response","status":"failed","error":messages_error_to_responses(message.get("error").unwrap_or(&Value::Null)),"output":[]});
|
||||
}
|
||||
let id = message
|
||||
.get("id")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("resp_messages");
|
||||
let reason = message
|
||||
.get("stop_reason")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default();
|
||||
let incomplete = match reason {
|
||||
"max_tokens" | "model_context_window_exceeded" => Some("max_output_tokens"),
|
||||
"refusal" => Some("content_filter"),
|
||||
_ => None,
|
||||
};
|
||||
let mut response = json!({"id":id,"object":"response","created_at":0,"status":if incomplete.is_some(){"incomplete"}else{"completed"},"model":model.or_else(||message.get("model")),"output":output,"error":null,"incomplete_details":incomplete.map(|reason|json!({"reason":reason})),"usage":MessageUsage::from_value(message.get("usage").unwrap_or(&Value::Null)).responses()});
|
||||
if reason == "pause_turn" {
|
||||
response["end_turn"] = json!(false);
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
pub(super) fn messages_block_to_response(
|
||||
block: &Value,
|
||||
tools: &ToolSet,
|
||||
id: &str,
|
||||
) -> Option<Value> {
|
||||
match block.get("type").and_then(Value::as_str)? {
|
||||
"text" => Some(
|
||||
json!({"id":id,"type":"message","role":"assistant","status":"completed","content":[{"type":"output_text","text":block.get("text").and_then(Value::as_str).unwrap_or_default(),"annotations":block.get("citations").cloned().unwrap_or_else(||json!([]))}]}),
|
||||
),
|
||||
"tool_use" => Some(tools.call(block, id)),
|
||||
"thinking" | "redacted_thinking" => Some(
|
||||
json!({"id":id,"type":"reasoning","summary":if block.get("type").and_then(Value::as_str)==Some("thinking") {vec![json!({"type":"summary_text","text":block.get("thinking").and_then(Value::as_str).unwrap_or_default()})]}else{vec![]},"encrypted_content":content::anthropic_carrier(block)}),
|
||||
),
|
||||
// 服务端工具块作为有来源的不透明项保留,可随续接请求恢复
|
||||
"server_tool_use"
|
||||
| "web_search_tool_result"
|
||||
| "web_fetch_tool_result"
|
||||
| "code_execution_tool_result"
|
||||
| "bash_code_execution_tool_result"
|
||||
| "text_editor_code_execution_tool_result"
|
||||
| "tool_search_tool_result" => Some(
|
||||
json!({"id":id,"type":"reasoning","summary":[],"encrypted_content":content::anthropic_carrier(block)}),
|
||||
),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Responses 完整响应转为 Messages,推理载荷保留其来源供后续轮次回传
|
||||
pub fn responses_to_messages_response(
|
||||
response: &Value,
|
||||
original_request: &Map<String, Value>,
|
||||
) -> Result<Value, TranslationError> {
|
||||
complete_message(response, original_request.get("model"))
|
||||
}
|
||||
|
||||
pub(super) fn complete_message(
|
||||
response: &Value,
|
||||
model: Option<&Value>,
|
||||
) -> Result<Value, TranslationError> {
|
||||
if response.get("error").is_some_and(|v| !v.is_null())
|
||||
|| response.get("status").and_then(Value::as_str) == Some("failed")
|
||||
{
|
||||
return Ok(
|
||||
json!({"type":"error","error":responses_error_to_messages(response.get("error").unwrap_or(&Value::Null))}),
|
||||
);
|
||||
}
|
||||
let output =
|
||||
response
|
||||
.get("output")
|
||||
.and_then(Value::as_array)
|
||||
.ok_or(TranslationError::InvalidEvent(
|
||||
"The Responses output must be an array.",
|
||||
))?;
|
||||
let content = output
|
||||
.iter()
|
||||
.flat_map(responses_item_to_messages)
|
||||
.collect::<Vec<_>>();
|
||||
let has_tool = content
|
||||
.iter()
|
||||
.any(|block| block.get("type").and_then(Value::as_str) == Some("tool_use"));
|
||||
let stop = responses_stop_reason(response, has_tool);
|
||||
Ok(
|
||||
json!({"id":response.get("id").and_then(Value::as_str).unwrap_or("msg_responses"),"type":"message","role":"assistant","model":model.or_else(||response.get("model")),"content":content,"stop_reason":stop,"stop_sequence":null,"usage":usage::responses_usage(response.get("usage").unwrap_or(&Value::Null))}),
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn responses_stop_reason(response: &Value, has_tool: bool) -> &'static str {
|
||||
if response.get("status").and_then(Value::as_str) == Some("incomplete") {
|
||||
match response
|
||||
.pointer("/incomplete_details/reason")
|
||||
.and_then(Value::as_str)
|
||||
{
|
||||
Some("content_filter") => "refusal",
|
||||
_ => "max_tokens",
|
||||
}
|
||||
} else if response.get("end_turn").and_then(Value::as_bool) == Some(false) {
|
||||
"pause_turn"
|
||||
} else if has_tool {
|
||||
"tool_use"
|
||||
} else {
|
||||
"end_turn"
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn responses_error_to_messages(error: &Value) -> Value {
|
||||
let source = error
|
||||
.get("type")
|
||||
.or_else(|| error.get("code"))
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default();
|
||||
let kind = match source {
|
||||
"invalid_request_error" | "invalid_prompt" => "invalid_request_error",
|
||||
"authentication_error" => "authentication_error",
|
||||
"permission_error" => "permission_error",
|
||||
"not_found_error" => "not_found_error",
|
||||
"rate_limit_error" | "rate_limit_exceeded" => "rate_limit_error",
|
||||
"overloaded_error" => "overloaded_error",
|
||||
_ => "api_error",
|
||||
};
|
||||
json!({"type":kind,"message":error.get("message").and_then(Value::as_str).unwrap_or("The upstream response failed.")})
|
||||
}
|
||||
|
||||
fn messages_error_to_responses(error: &Value) -> Value {
|
||||
let code = match error
|
||||
.get("type")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default()
|
||||
{
|
||||
"rate_limit_error" => "rate_limit_exceeded",
|
||||
"invalid_request_error" => "invalid_prompt",
|
||||
_ => "server_error",
|
||||
};
|
||||
json!({"code":code,"message":error.get("message").and_then(Value::as_str).unwrap_or("The upstream response failed.")})
|
||||
}
|
||||
|
||||
pub(super) fn responses_item_to_messages(item: &Value) -> Vec<Value> {
|
||||
match item.get("type").and_then(Value::as_str).unwrap_or_default() {
|
||||
"message" => item
|
||||
.get("content")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(content::to_messages_content)
|
||||
.collect(),
|
||||
"function_call" => vec![
|
||||
json!({"type":"tool_use","id":item.get("call_id").or_else(||item.get("id")),"name":item.get("name"),"input":item.get("arguments").and_then(Value::as_str).and_then(|v|serde_json::from_str::<Value>(v).ok()).filter(Value::is_object).unwrap_or_else(||json!({}))}),
|
||||
],
|
||||
"custom_tool_call" => vec![
|
||||
json!({"type":"tool_use","id":item.get("call_id").or_else(||item.get("id")),"name":item.get("name"),"input":{"input":item.get("input").and_then(Value::as_str).unwrap_or_default()}}),
|
||||
],
|
||||
"reasoning" => vec![
|
||||
json!({"type":"thinking","thinking":content::reasoning_text(item),"signature":content::openai_carrier(item)}),
|
||||
],
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,10 @@ use std::collections::BTreeMap;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::super::TranslationError;
|
||||
use super::super::MessageError;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct Block {
|
||||
struct Block {
|
||||
pub value: Value,
|
||||
pub input_json: String,
|
||||
pub invalid_input: bool,
|
||||
@@ -15,15 +15,15 @@ pub(super) struct Block {
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct MessageSnapshot {
|
||||
struct MessageSnapshot {
|
||||
pub message: Value,
|
||||
pub blocks: BTreeMap<u64, Block>,
|
||||
}
|
||||
|
||||
impl MessageSnapshot {
|
||||
fn into_json(mut self) -> Result<Value, TranslationError> {
|
||||
fn into_json(mut self) -> Result<Value, MessageError> {
|
||||
if self.blocks.values().any(|block| block.invalid_input) {
|
||||
return Err(TranslationError::InvalidEvent(
|
||||
return Err(MessageError::InvalidEvent(
|
||||
"The Messages tool input is not valid JSON.",
|
||||
));
|
||||
}
|
||||
@@ -45,26 +45,22 @@ pub struct MessagesAccumulator {
|
||||
|
||||
impl MessagesAccumulator {
|
||||
/// message_stop 返回完整响应,error 返回原生错误终态,未知事件不改变状态
|
||||
pub fn push(&mut self, event: &Value) -> Result<Option<Value>, TranslationError> {
|
||||
pub fn push(&mut self, event: &Value) -> Result<Option<Value>, MessageError> {
|
||||
self.accumulate(event)?
|
||||
.map(MessageSnapshot::into_json)
|
||||
.transpose()
|
||||
}
|
||||
|
||||
// 原生 JSON 要求工具输入可解析,跨协议转换还需要保留合法截断的原始参数
|
||||
pub(super) fn accumulate(
|
||||
&mut self,
|
||||
event: &Value,
|
||||
) -> Result<Option<MessageSnapshot>, TranslationError> {
|
||||
let kind =
|
||||
event
|
||||
.get("type")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or(TranslationError::InvalidEvent(
|
||||
"The Messages event type is missing.",
|
||||
))?;
|
||||
// 原生 JSON 仅在完整工具输入可解析时交付
|
||||
fn accumulate(&mut self, event: &Value) -> Result<Option<MessageSnapshot>, MessageError> {
|
||||
let kind = event
|
||||
.get("type")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or(MessageError::InvalidEvent(
|
||||
"The Messages event type is missing.",
|
||||
))?;
|
||||
if self.terminal {
|
||||
return Err(TranslationError::InvalidEvent(
|
||||
return Err(MessageError::InvalidEvent(
|
||||
"The Messages stream contains events after its terminal event.",
|
||||
));
|
||||
}
|
||||
@@ -78,12 +74,12 @@ impl MessagesAccumulator {
|
||||
}
|
||||
"message_start" => {
|
||||
if self.message.is_some() {
|
||||
return Err(TranslationError::InvalidEvent(
|
||||
return Err(MessageError::InvalidEvent(
|
||||
"The Messages stream contains duplicate message_start events.",
|
||||
));
|
||||
}
|
||||
let message = event.get("message").filter(|v| v.is_object()).ok_or(
|
||||
TranslationError::InvalidEvent(
|
||||
MessageError::InvalidEvent(
|
||||
"The message_start event must contain a message object.",
|
||||
),
|
||||
)?;
|
||||
@@ -93,14 +89,14 @@ impl MessagesAccumulator {
|
||||
self.require_message()?;
|
||||
let index = index(event)?;
|
||||
if self.blocks.contains_key(&index) {
|
||||
return Err(TranslationError::InvalidEvent(
|
||||
return Err(MessageError::InvalidEvent(
|
||||
"The Messages content block index is duplicated.",
|
||||
));
|
||||
}
|
||||
let value = event
|
||||
.get("content_block")
|
||||
.filter(|v| v.is_object())
|
||||
.ok_or(TranslationError::InvalidEvent(
|
||||
.ok_or(MessageError::InvalidEvent(
|
||||
"The content_block_start event must contain a content block.",
|
||||
))?
|
||||
.clone();
|
||||
@@ -116,7 +112,7 @@ impl MessagesAccumulator {
|
||||
}
|
||||
"content_block_delta" => {
|
||||
let block = self.active_block(event)?;
|
||||
let delta = event.get("delta").ok_or(TranslationError::InvalidEvent(
|
||||
let delta = event.get("delta").ok_or(MessageError::InvalidEvent(
|
||||
"The content block delta is missing.",
|
||||
))?;
|
||||
match delta
|
||||
@@ -162,7 +158,7 @@ impl MessagesAccumulator {
|
||||
block.stopped = true;
|
||||
}
|
||||
"message_delta" => {
|
||||
let message = self.message.as_mut().ok_or(TranslationError::InvalidEvent(
|
||||
let message = self.message.as_mut().ok_or(MessageError::InvalidEvent(
|
||||
"The Messages delta arrived before message_start.",
|
||||
))?;
|
||||
if let Some(delta) = event.get("delta").and_then(Value::as_object) {
|
||||
@@ -182,14 +178,11 @@ impl MessagesAccumulator {
|
||||
"message_stop" => {
|
||||
self.require_message()?;
|
||||
if self.blocks.values().any(|block| !block.stopped) {
|
||||
return Err(TranslationError::InvalidEvent(
|
||||
return Err(MessageError::InvalidEvent(
|
||||
"The Messages stream ended with an open content block.",
|
||||
));
|
||||
}
|
||||
let message = self
|
||||
.message
|
||||
.take()
|
||||
.ok_or(TranslationError::IncompleteStream)?;
|
||||
let message = self.message.take().ok_or(MessageError::IncompleteStream)?;
|
||||
self.terminal = true;
|
||||
return Ok(Some(MessageSnapshot {
|
||||
message,
|
||||
@@ -202,43 +195,39 @@ impl MessagesAccumulator {
|
||||
}
|
||||
|
||||
/// 必须消费成功或失败终态,连接结束不能被当作成功
|
||||
pub fn finish(&self) -> Result<(), TranslationError> {
|
||||
pub fn finish(&self) -> Result<(), MessageError> {
|
||||
if self.terminal {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(TranslationError::IncompleteStream)
|
||||
Err(MessageError::IncompleteStream)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn block(&self, index: u64) -> Option<&Block> {
|
||||
self.blocks.get(&index)
|
||||
}
|
||||
|
||||
fn require_message(&self) -> Result<(), TranslationError> {
|
||||
fn require_message(&self) -> Result<(), MessageError> {
|
||||
if self.message.is_some() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(TranslationError::InvalidEvent(
|
||||
Err(MessageError::InvalidEvent(
|
||||
"The Messages content arrived before message_start.",
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn active_block(&mut self, event: &Value) -> Result<&mut Block, TranslationError> {
|
||||
fn active_block(&mut self, event: &Value) -> Result<&mut Block, MessageError> {
|
||||
self.blocks
|
||||
.get_mut(&index(event)?)
|
||||
.filter(|block| !block.stopped)
|
||||
.ok_or(TranslationError::InvalidEvent(
|
||||
.ok_or(MessageError::InvalidEvent(
|
||||
"The Messages delta references a content block that is not open.",
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn index(event: &Value) -> Result<u64, TranslationError> {
|
||||
fn index(event: &Value) -> Result<u64, MessageError> {
|
||||
event
|
||||
.get("index")
|
||||
.and_then(Value::as_u64)
|
||||
.ok_or(TranslationError::InvalidEvent(
|
||||
.ok_or(MessageError::InvalidEvent(
|
||||
"The content block index is missing.",
|
||||
))
|
||||
}
|
||||
|
||||
@@ -1,14 +1,10 @@
|
||||
//! 每次执行独立持有的 SSE 聚合与转换状态
|
||||
//! Messages 原生 SSE 聚合与完整消息编码
|
||||
|
||||
mod accumulator;
|
||||
mod to_messages;
|
||||
mod to_responses;
|
||||
|
||||
pub use accumulator::MessagesAccumulator;
|
||||
pub use to_messages::ResponsesToMessagesStream;
|
||||
pub use to_responses::MessagesToResponsesStream;
|
||||
|
||||
use super::TranslationError;
|
||||
use super::MessageError;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// 将已收到的完整原生消息交付给请求 SSE 的客户端,保留内容块与扩展字段
|
||||
@@ -16,9 +12,9 @@ use serde_json::{Value, json};
|
||||
/// # Errors
|
||||
///
|
||||
/// 对象不是完整 Messages 响应或缺少内容数组时返回错误
|
||||
pub fn message_to_stream_events(mut message: Value) -> Result<Vec<Value>, TranslationError> {
|
||||
pub fn message_to_stream_events(mut message: Value) -> Result<Vec<Value>, MessageError> {
|
||||
if message.get("type").and_then(Value::as_str) != Some("message") {
|
||||
return Err(TranslationError::InvalidEvent(
|
||||
return Err(MessageError::InvalidEvent(
|
||||
"The upstream response is not a message.",
|
||||
));
|
||||
}
|
||||
@@ -26,7 +22,7 @@ pub fn message_to_stream_events(mut message: Value) -> Result<Vec<Value>, Transl
|
||||
.get_mut("content")
|
||||
.and_then(Value::as_array_mut)
|
||||
.map(std::mem::take)
|
||||
.ok_or(TranslationError::InvalidEvent(
|
||||
.ok_or(MessageError::InvalidEvent(
|
||||
"The upstream message content is missing.",
|
||||
))?;
|
||||
let stop_reason = message["stop_reason"].take();
|
||||
|
||||
@@ -1,368 +0,0 @@
|
||||
//! Responses SSE 到 Messages SSE 的增量转换与签名终态回传
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use super::super::{
|
||||
TranslationError, content,
|
||||
response::{responses_error_to_messages, responses_item_to_messages, responses_stop_reason},
|
||||
usage,
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Block {
|
||||
index: usize,
|
||||
kind: String,
|
||||
emitted: String,
|
||||
signature_sent: bool,
|
||||
stopped: bool,
|
||||
last_summary_index: Option<u64>,
|
||||
}
|
||||
|
||||
/// 每次 Responses 执行独立持有输出块与结束状态
|
||||
#[derive(Debug)]
|
||||
pub struct ResponsesToMessagesStream {
|
||||
model: Option<Value>,
|
||||
blocks: BTreeMap<(u64, usize), Block>,
|
||||
started: bool,
|
||||
terminal: bool,
|
||||
}
|
||||
|
||||
impl ResponsesToMessagesStream {
|
||||
/// 原始 Messages 请求用于保留客户端模型身份
|
||||
#[must_use]
|
||||
pub fn new(original_request: &Map<String, Value>) -> Self {
|
||||
Self {
|
||||
model: original_request.get("model").cloned(),
|
||||
blocks: BTreeMap::new(),
|
||||
started: false,
|
||||
terminal: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// 完整 JSON 响应只需要客户端模型名
|
||||
pub fn complete_json(&self, response: &Value) -> Result<Value, TranslationError> {
|
||||
super::super::response::complete_message(response, self.model.as_ref())
|
||||
}
|
||||
|
||||
/// 输入已解码 Responses 事件,返回 Messages 事件
|
||||
pub fn push(&mut self, event: &Value) -> Result<Vec<Value>, TranslationError> {
|
||||
if self.terminal {
|
||||
return Err(TranslationError::InvalidEvent(
|
||||
"The Responses stream contains events after its terminal event.",
|
||||
));
|
||||
}
|
||||
let kind =
|
||||
event
|
||||
.get("type")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or(TranslationError::InvalidEvent(
|
||||
"The Responses event type is missing.",
|
||||
))?;
|
||||
let mut events = Vec::new();
|
||||
if matches!(kind, "error" | "response.failed") {
|
||||
let error = event.get("error").or_else(||event.pointer("/response/error")).cloned().unwrap_or_else(||json!({"type":"api_error","message":event.get("message").and_then(Value::as_str).unwrap_or("The upstream response failed.")}));
|
||||
self.terminal = true;
|
||||
return Ok(vec![
|
||||
json!({"type":"error","error":responses_error_to_messages(&error)}),
|
||||
]);
|
||||
}
|
||||
if kind.starts_with("response.") {
|
||||
self.start(event.get("response"), &mut events);
|
||||
}
|
||||
let output_index = event
|
||||
.get("output_index")
|
||||
.and_then(Value::as_u64)
|
||||
.unwrap_or_default();
|
||||
let content_index = event
|
||||
.get("content_index")
|
||||
.and_then(Value::as_u64)
|
||||
.unwrap_or_default() as usize;
|
||||
match kind {
|
||||
"response.output_item.added" => {
|
||||
let item = event.get("item").filter(|v| v.is_object()).ok_or(
|
||||
TranslationError::InvalidEvent("The output item event must contain an item."),
|
||||
)?;
|
||||
match item.get("type").and_then(Value::as_str).unwrap_or_default() {
|
||||
"function_call" | "custom_tool_call" | "reasoning" => {
|
||||
if let Some(block) = responses_item_to_messages(item).first() {
|
||||
self.ensure_block((output_index, 0), block, &mut events);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
"response.content_part.added" => {
|
||||
if let Some(part) = event.get("part").and_then(content::to_messages_content) {
|
||||
self.ensure_block((output_index, content_index), &part, &mut events);
|
||||
}
|
||||
}
|
||||
"response.output_text.delta" | "response.refusal.delta" => {
|
||||
let key = (output_index, content_index);
|
||||
self.ensure_block(key, &json!({"type":"text","text":""}), &mut events);
|
||||
self.emit_delta(
|
||||
key,
|
||||
"text_delta",
|
||||
"text",
|
||||
event
|
||||
.get("delta")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default(),
|
||||
&mut events,
|
||||
)?;
|
||||
}
|
||||
"response.reasoning_summary_text.delta" | "response.reasoning_text.delta" => {
|
||||
let key = (output_index, 0);
|
||||
self.ensure_block(key, &json!({"type":"thinking","thinking":""}), &mut events);
|
||||
let part_index = event
|
||||
.get("summary_index")
|
||||
.or_else(|| event.get("content_index"))
|
||||
.and_then(Value::as_u64)
|
||||
.unwrap_or_default();
|
||||
let separator = self.blocks.get(&key).is_some_and(|block| {
|
||||
!block.emitted.is_empty()
|
||||
&& block
|
||||
.last_summary_index
|
||||
.is_some_and(|previous| previous != part_index)
|
||||
});
|
||||
if separator {
|
||||
self.emit_delta(key, "thinking_delta", "thinking", "\n", &mut events)?;
|
||||
}
|
||||
if let Some(block) = self.blocks.get_mut(&key) {
|
||||
block.last_summary_index = Some(part_index);
|
||||
}
|
||||
self.emit_delta(
|
||||
key,
|
||||
"thinking_delta",
|
||||
"thinking",
|
||||
event
|
||||
.get("delta")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default(),
|
||||
&mut events,
|
||||
)?;
|
||||
}
|
||||
"response.function_call_arguments.delta" => {
|
||||
let key = (output_index, 0);
|
||||
if !self.blocks.contains_key(&key) {
|
||||
return Err(TranslationError::InvalidEvent(
|
||||
"The tool arguments arrived before the output item.",
|
||||
));
|
||||
}
|
||||
self.emit_delta(
|
||||
key,
|
||||
"input_json_delta",
|
||||
"partial_json",
|
||||
event
|
||||
.get("delta")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default(),
|
||||
&mut events,
|
||||
)?;
|
||||
}
|
||||
// custom 输入在完整 item 中一次包装为 JSON,不能逐片转义成独立参数
|
||||
"response.custom_tool_call_input.delta" => {
|
||||
if !self.blocks.contains_key(&(output_index, 0)) {
|
||||
return Err(TranslationError::InvalidEvent(
|
||||
"The custom tool input arrived before the output item.",
|
||||
));
|
||||
}
|
||||
}
|
||||
"response.output_item.done" => {
|
||||
let item = event.get("item").filter(|v| v.is_object()).ok_or(
|
||||
TranslationError::InvalidEvent("The output item event must contain an item."),
|
||||
)?;
|
||||
self.complete_item(output_index, item, false, &mut events)?;
|
||||
}
|
||||
"response.completed" | "response.incomplete" => {
|
||||
let response = event
|
||||
.get("response")
|
||||
.filter(|response| response.is_object())
|
||||
.ok_or(TranslationError::InvalidEvent(
|
||||
"The terminal Responses event must contain a response.",
|
||||
))?;
|
||||
if let Some(output) = response.get("output") {
|
||||
let output = output.as_array().ok_or(TranslationError::InvalidEvent(
|
||||
"The Responses output must be an array.",
|
||||
))?;
|
||||
for (index, item) in output.iter().enumerate() {
|
||||
self.complete_item(index as u64, item, true, &mut events)?;
|
||||
}
|
||||
}
|
||||
let open = self.blocks.values_mut().filter(|block| !block.stopped);
|
||||
for block in open {
|
||||
block.stopped = true;
|
||||
events.push(json!({"type":"content_block_stop","index":block.index}));
|
||||
}
|
||||
if !response["error"].is_null() || response["status"] == "failed" {
|
||||
events.push(json!({"type":"error","error":responses_error_to_messages(&response["error"])}));
|
||||
} else {
|
||||
// 终态可以省略已经交付的 output,停止原因由客户端实际收到的块决定
|
||||
let has_tool = self.blocks.values().any(|block| block.kind == "tool_use");
|
||||
events.push(json!({"type":"message_delta","delta":{"stop_reason":responses_stop_reason(response,has_tool),"stop_sequence":null},"usage":usage::responses_usage(&response["usage"])}));
|
||||
events.push(json!({"type":"message_stop"}));
|
||||
}
|
||||
self.terminal = true;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(events)
|
||||
}
|
||||
|
||||
/// 连接关闭仅在已消费终态时成功
|
||||
pub fn finish(&self) -> Result<(), TranslationError> {
|
||||
if self.terminal {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(TranslationError::IncompleteStream)
|
||||
}
|
||||
}
|
||||
|
||||
fn start(&mut self, response: Option<&Value>, events: &mut Vec<Value>) {
|
||||
if self.started {
|
||||
return;
|
||||
}
|
||||
let response = response.unwrap_or(&Value::Null);
|
||||
events.push(json!({"type":"message_start","message":{"id":response.get("id").and_then(Value::as_str).unwrap_or("msg_responses"),"type":"message","role":"assistant","model":self.model.as_ref().or_else(||response.get("model")),"content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}}}));
|
||||
self.started = true;
|
||||
}
|
||||
|
||||
fn ensure_block(&mut self, key: (u64, usize), block: &Value, events: &mut Vec<Value>) {
|
||||
if self.blocks.contains_key(&key) {
|
||||
return;
|
||||
}
|
||||
let kind = block.get("type").and_then(Value::as_str).unwrap_or("text");
|
||||
let mut start = block.clone();
|
||||
match kind {
|
||||
"text" => start["text"] = json!(""),
|
||||
"thinking" => {
|
||||
start["thinking"] = json!("");
|
||||
if let Some(object) = start.as_object_mut() {
|
||||
object.remove("signature");
|
||||
}
|
||||
}
|
||||
"tool_use" => start["input"] = json!({}),
|
||||
_ => {}
|
||||
}
|
||||
let index = self.blocks.len();
|
||||
self.blocks.insert(
|
||||
key,
|
||||
Block {
|
||||
index,
|
||||
kind: kind.to_owned(),
|
||||
emitted: String::new(),
|
||||
signature_sent: false,
|
||||
stopped: false,
|
||||
last_summary_index: None,
|
||||
},
|
||||
);
|
||||
events.push(json!({"type":"content_block_start","index":index,"content_block":start}));
|
||||
}
|
||||
|
||||
fn emit_delta(
|
||||
&mut self,
|
||||
key: (u64, usize),
|
||||
kind: &str,
|
||||
field: &str,
|
||||
fragment: &str,
|
||||
events: &mut Vec<Value>,
|
||||
) -> Result<(), TranslationError> {
|
||||
let block = self
|
||||
.blocks
|
||||
.get_mut(&key)
|
||||
.filter(|block| !block.stopped)
|
||||
.ok_or(TranslationError::InvalidEvent(
|
||||
"The Responses delta references a closed content block.",
|
||||
))?;
|
||||
block.emitted.push_str(fragment);
|
||||
if !fragment.is_empty() {
|
||||
events.push(json!({"type":"content_block_delta","index":block.index,"delta":{"type":kind,field:fragment}}));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn complete_item(
|
||||
&mut self,
|
||||
output_index: u64,
|
||||
item: &Value,
|
||||
terminal: bool,
|
||||
events: &mut Vec<Value>,
|
||||
) -> Result<(), TranslationError> {
|
||||
let contents = if item.get("type").and_then(Value::as_str) == Some("message") {
|
||||
item.get("content")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.enumerate()
|
||||
.filter_map(|(index, part)| {
|
||||
content::to_messages_content(part).map(|content| (index, content))
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
} else {
|
||||
responses_item_to_messages(item)
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.collect()
|
||||
};
|
||||
for (content_index, content) in &contents {
|
||||
let key = (output_index, *content_index);
|
||||
self.ensure_block(key, content, events);
|
||||
let Some(block) = self.blocks.get(&key) else {
|
||||
continue;
|
||||
};
|
||||
if block.stopped {
|
||||
continue;
|
||||
}
|
||||
let full = match block.kind.as_str() {
|
||||
"text" => content
|
||||
.get("text")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default()
|
||||
.to_owned(),
|
||||
"thinking" => content
|
||||
.get("thinking")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default()
|
||||
.to_owned(),
|
||||
"tool_use" => content
|
||||
.get("input")
|
||||
.cloned()
|
||||
.unwrap_or_else(|| json!({}))
|
||||
.to_string(),
|
||||
_ => String::new(),
|
||||
};
|
||||
let delta = full
|
||||
.strip_prefix(&block.emitted)
|
||||
.unwrap_or_default()
|
||||
.to_owned();
|
||||
let (kind, field) = match block.kind.as_str() {
|
||||
"text" => ("text_delta", "text"),
|
||||
"thinking" => ("thinking_delta", "thinking"),
|
||||
_ => ("input_json_delta", "partial_json"),
|
||||
};
|
||||
if !delta.is_empty() {
|
||||
self.emit_delta(key, kind, field, &delta, events)?;
|
||||
}
|
||||
let Some(block) = self.blocks.get_mut(&key) else {
|
||||
continue;
|
||||
};
|
||||
if block.kind == "thinking" && !block.signature_sent {
|
||||
if item
|
||||
.get("encrypted_content")
|
||||
.and_then(Value::as_str)
|
||||
.is_some()
|
||||
|| terminal
|
||||
{
|
||||
events.push(json!({"type":"content_block_delta","index":block.index,"delta":{"type":"signature_delta","signature":content::openai_carrier(item)}}));
|
||||
block.signature_sent = true;
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
block.stopped = true;
|
||||
events.push(json!({"type":"content_block_stop","index":block.index}));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,329 +0,0 @@
|
||||
//! Messages SSE 到 Responses SSE 的逐块转换
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use super::super::{
|
||||
TranslationError,
|
||||
response::{
|
||||
complete_response, messages_block_to_response, response_from_message,
|
||||
terminal_response_event,
|
||||
},
|
||||
tools::ToolSet,
|
||||
};
|
||||
use super::{
|
||||
MessagesAccumulator,
|
||||
accumulator::{Block, index},
|
||||
};
|
||||
|
||||
/// 单次 Messages 上游执行对应的 Responses 转换状态
|
||||
#[derive(Debug)]
|
||||
pub struct MessagesToResponsesStream {
|
||||
model: Option<Value>,
|
||||
tools: ToolSet,
|
||||
accumulator: MessagesAccumulator,
|
||||
response_id: String,
|
||||
output_indices: BTreeMap<u64, usize>,
|
||||
sequence: u64,
|
||||
}
|
||||
|
||||
impl MessagesToResponsesStream {
|
||||
/// 原始 Responses 请求用于工具身份与模型恢复
|
||||
#[must_use]
|
||||
pub fn new(original_request: &Map<String, Value>) -> Self {
|
||||
Self {
|
||||
model: original_request.get("model").cloned(),
|
||||
tools: ToolSet::identities(original_request),
|
||||
accumulator: MessagesAccumulator::default(),
|
||||
response_id: String::new(),
|
||||
output_indices: BTreeMap::new(),
|
||||
sequence: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// JSON 和事件流共用同一份模型及工具身份,不持有客户端历史
|
||||
pub fn complete_json_event(&self, message: &Value) -> Result<Value, TranslationError> {
|
||||
complete_response(message, self.model.as_ref(), &self.tools).map(terminal_response_event)
|
||||
}
|
||||
|
||||
/// 输入已解码事件,返回携带 type 的 Responses 事件
|
||||
pub fn push(&mut self, event: &Value) -> Result<Vec<Value>, TranslationError> {
|
||||
let terminal = self.accumulator.accumulate(event)?;
|
||||
let kind = event
|
||||
.get("type")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default();
|
||||
let mut events = Vec::new();
|
||||
match kind {
|
||||
"message_start" => {
|
||||
let message = event.get("message").ok_or(TranslationError::InvalidEvent(
|
||||
"The message_start event must contain a message.",
|
||||
))?;
|
||||
self.response_id = message
|
||||
.get("id")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("resp_messages")
|
||||
.to_owned();
|
||||
let mut response = complete_response(message, self.model.as_ref(), &self.tools)?;
|
||||
response["status"] = json!("in_progress");
|
||||
response["output"] = json!([]);
|
||||
response["usage"] = Value::Null;
|
||||
events.push(json!({"type":"response.created","response":response}));
|
||||
events.push(json!({"type":"response.in_progress","response":response}));
|
||||
}
|
||||
"content_block_start" => {
|
||||
let index = index(event)?;
|
||||
if let Some(block) = self.accumulator.block(index)
|
||||
&& let Some(mut item) = self.block_item(index, block)
|
||||
{
|
||||
let block = &block.value;
|
||||
let output_index = self.output_indices.len();
|
||||
self.output_indices.insert(index, output_index);
|
||||
let item_type = item
|
||||
.get("type")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default()
|
||||
.to_owned();
|
||||
item["status"] = json!("in_progress");
|
||||
match item_type.as_str() {
|
||||
"message" => item["content"] = json!([]),
|
||||
"function_call" => item["arguments"] = json!(""),
|
||||
"custom_tool_call" => item["input"] = json!(""),
|
||||
"reasoning" => {
|
||||
item["summary"] = json!([]);
|
||||
if let Some(object) = item.as_object_mut() {
|
||||
object.remove("encrypted_content");
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
events.push(json!({"type":"response.output_item.added","output_index":output_index,"item":item}));
|
||||
if item_type == "message" {
|
||||
events.push(json!({"type":"response.content_part.added","output_index":output_index,"item_id":self.item_id(index),"content_index":0,"part":{"type":"output_text","text":"","annotations":[]}}));
|
||||
if let Some(text) = block
|
||||
.get("text")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|v| !v.is_empty())
|
||||
{
|
||||
events.push(self.delta(
|
||||
index,
|
||||
output_index,
|
||||
"response.output_text.delta",
|
||||
"delta",
|
||||
text,
|
||||
));
|
||||
}
|
||||
} else if block.get("type").and_then(Value::as_str) == Some("thinking") {
|
||||
events.push(json!({"type":"response.reasoning_summary_part.added","output_index":output_index,"item_id":self.item_id(index),"summary_index":0,"part":{"type":"summary_text","text":""}}));
|
||||
if let Some(text) = block
|
||||
.get("thinking")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|v| !v.is_empty())
|
||||
{
|
||||
events.push(self.delta(
|
||||
index,
|
||||
output_index,
|
||||
"response.reasoning_summary_text.delta",
|
||||
"delta",
|
||||
text,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"content_block_delta" => {
|
||||
let index = index(event)?;
|
||||
if let Some(output_index) = self.output_indices.get(&index).copied() {
|
||||
let delta = event.get("delta").unwrap_or(&Value::Null);
|
||||
let (kind, key) = match delta
|
||||
.get("type")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default()
|
||||
{
|
||||
"text_delta" => ("response.output_text.delta", "text"),
|
||||
"thinking_delta" => ("response.reasoning_summary_text.delta", "thinking"),
|
||||
"input_json_delta" => {
|
||||
("response.function_call_arguments.delta", "partial_json")
|
||||
}
|
||||
_ => ("", ""),
|
||||
};
|
||||
let custom = self
|
||||
.accumulator
|
||||
.block(index)
|
||||
.and_then(|block| block.value.get("name"))
|
||||
.and_then(Value::as_str)
|
||||
.and_then(|name| self.tools.tools.get(name))
|
||||
.is_some_and(|tool| tool.custom);
|
||||
if !kind.is_empty() && !(custom && key == "partial_json") {
|
||||
events.push(self.delta(
|
||||
index,
|
||||
output_index,
|
||||
kind,
|
||||
"delta",
|
||||
delta.get(key).and_then(Value::as_str).unwrap_or_default(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
"content_block_stop" => {
|
||||
let index = index(event)?;
|
||||
if let Some(output_index) = self.output_indices.get(&index).copied()
|
||||
&& let Some(block) = self.accumulator.block(index)
|
||||
&& !block.invalid_input
|
||||
&& let Some(item) = self.block_item(index, block)
|
||||
{
|
||||
match item.get("type").and_then(Value::as_str).unwrap_or_default() {
|
||||
"message" => {
|
||||
let part = &item["content"][0];
|
||||
events.push(self.delta(
|
||||
index,
|
||||
output_index,
|
||||
"response.output_text.done",
|
||||
"text",
|
||||
part.get("text").and_then(Value::as_str).unwrap_or_default(),
|
||||
));
|
||||
events.push(json!({"type":"response.content_part.done","output_index":output_index,"item_id":self.item_id(index),"content_index":0,"part":part}));
|
||||
}
|
||||
"function_call" => events.push(
|
||||
self.delta(
|
||||
index,
|
||||
output_index,
|
||||
"response.function_call_arguments.done",
|
||||
"arguments",
|
||||
item.get("arguments")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default(),
|
||||
),
|
||||
),
|
||||
"custom_tool_call" => {
|
||||
let input = item
|
||||
.get("input")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default();
|
||||
events.push(self.delta(
|
||||
index,
|
||||
output_index,
|
||||
"response.custom_tool_call_input.delta",
|
||||
"delta",
|
||||
input,
|
||||
));
|
||||
events.push(self.delta(
|
||||
index,
|
||||
output_index,
|
||||
"response.custom_tool_call_input.done",
|
||||
"input",
|
||||
input,
|
||||
));
|
||||
}
|
||||
"reasoning" => {
|
||||
if let Some(part) = item
|
||||
.get("summary")
|
||||
.and_then(Value::as_array)
|
||||
.and_then(|parts| parts.first())
|
||||
{
|
||||
events.push(self.delta(
|
||||
index,
|
||||
output_index,
|
||||
"response.reasoning_summary_text.done",
|
||||
"text",
|
||||
part.get("text").and_then(Value::as_str).unwrap_or_default(),
|
||||
));
|
||||
events.push(json!({"type":"response.reasoning_summary_part.done","output_index":output_index,"item_id":self.item_id(index),"summary_index":0,"part":part}));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
events.push(json!({"type":"response.output_item.done","output_index":output_index,"item":item}));
|
||||
}
|
||||
}
|
||||
"message_stop" | "error" => {
|
||||
if let Some(snapshot) = terminal {
|
||||
let mut response =
|
||||
response_from_message(&snapshot.message, self.model.as_ref(), Vec::new());
|
||||
let mut output = Vec::new();
|
||||
for (index, block) in &snapshot.blocks {
|
||||
if block.invalid_input && block.value["type"] != "tool_use" {
|
||||
return Err(TranslationError::InvalidEvent(
|
||||
"The Messages tool input is not valid JSON.",
|
||||
));
|
||||
}
|
||||
if let Some(mut item) = self.block_item(*index, block) {
|
||||
if block.invalid_input {
|
||||
item["status"] = response["status"].clone();
|
||||
let output_index = self.output_indices.get(index).copied().ok_or(
|
||||
TranslationError::InvalidEvent(
|
||||
"The tool output item is missing.",
|
||||
),
|
||||
)?;
|
||||
let (event_type, field) = if item["type"] == "custom_tool_call" {
|
||||
events.push(self.delta(
|
||||
*index,
|
||||
output_index,
|
||||
"response.custom_tool_call_input.delta",
|
||||
"delta",
|
||||
item["input"].as_str().unwrap_or_default(),
|
||||
));
|
||||
("response.custom_tool_call_input.done", "input")
|
||||
} else {
|
||||
("response.function_call_arguments.done", "arguments")
|
||||
};
|
||||
events.push(self.delta(
|
||||
*index,
|
||||
output_index,
|
||||
event_type,
|
||||
field,
|
||||
item[field].as_str().unwrap_or_default(),
|
||||
));
|
||||
events.push(json!({"type":"response.output_item.done","output_index":output_index,"item":item}));
|
||||
}
|
||||
output.push(item);
|
||||
}
|
||||
}
|
||||
response["output"] = json!(output);
|
||||
if kind == "error" {
|
||||
response["id"] = json!(self.response_id);
|
||||
}
|
||||
events.push(terminal_response_event(response));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
for event in &mut events {
|
||||
event["sequence_number"] = json!(self.sequence);
|
||||
self.sequence += 1;
|
||||
}
|
||||
Ok(events)
|
||||
}
|
||||
|
||||
/// 验证流收到了原生终态
|
||||
pub fn finish(&self) -> Result<(), TranslationError> {
|
||||
self.accumulator.finish()
|
||||
}
|
||||
|
||||
fn item_id(&self, index: u64) -> String {
|
||||
format!("{}_{index}", self.response_id)
|
||||
}
|
||||
|
||||
fn block_item(&self, index: u64, block: &Block) -> Option<Value> {
|
||||
let mut item = messages_block_to_response(&block.value, &self.tools, &self.item_id(index))?;
|
||||
if item["type"] == "function_call" && !block.input_json.is_empty() {
|
||||
item["arguments"] = json!(block.input_json);
|
||||
}
|
||||
if block.invalid_input && item["type"] == "custom_tool_call" {
|
||||
item["input"] = json!(super::super::tools::partial_custom_input(&block.input_json));
|
||||
}
|
||||
Some(item)
|
||||
}
|
||||
|
||||
fn delta(&self, index: u64, output_index: usize, kind: &str, key: &str, text: &str) -> Value {
|
||||
let mut event =
|
||||
json!({"type":kind,"item_id":self.item_id(index),"output_index":output_index,key:text});
|
||||
if kind.contains("reasoning_summary") {
|
||||
event["summary_index"] = json!(0);
|
||||
} else if kind.contains("output_text") {
|
||||
event["content_index"] = json!(0);
|
||||
}
|
||||
event
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,6 @@
|
||||
//! 提取 Messages 显式 effort,并按目标模型能力映射推理等级与预算
|
||||
//! 提取 Messages 客户端显式设置的推理等级
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use super::MessagesModelCapabilities;
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
/// 返回客户端显式设置的 effort,预算与默认档位由转换器单独处理
|
||||
#[must_use]
|
||||
@@ -14,156 +12,3 @@ pub fn messages_request_effort(request: &Map<String, Value>) -> Option<&str> {
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
}
|
||||
|
||||
pub(super) fn to_responses(request: &Map<String, Value>) -> Value {
|
||||
let configured = messages_request_effort(request).map(str::to_ascii_lowercase);
|
||||
let thinking = request.get("thinking");
|
||||
let effort = match thinking
|
||||
.and_then(|value| value.get("type"))
|
||||
.and_then(Value::as_str)
|
||||
{
|
||||
Some("disabled") => "none".to_owned(),
|
||||
Some("enabled") => {
|
||||
let budget = thinking
|
||||
.and_then(|value| value.get("budget_tokens"))
|
||||
.and_then(Value::as_i64);
|
||||
match budget {
|
||||
Some(-1) => "auto",
|
||||
Some(0) => "none",
|
||||
Some(1..=512) => "minimal",
|
||||
Some(513..=1024) => "low",
|
||||
Some(1025..=8192) => "medium",
|
||||
Some(8193..=24576) => "high",
|
||||
Some(24577..) => "xhigh",
|
||||
_ => "medium",
|
||||
}
|
||||
.to_owned()
|
||||
}
|
||||
Some("adaptive" | "auto") => configured.unwrap_or_else(|| "xhigh".to_owned()),
|
||||
_ => configured.unwrap_or_else(|| "medium".to_owned()),
|
||||
};
|
||||
json!({"effort":effort})
|
||||
}
|
||||
|
||||
pub(super) fn apply_to_messages(
|
||||
request: &Map<String, Value>,
|
||||
target: &mut Map<String, Value>,
|
||||
capabilities: &MessagesModelCapabilities,
|
||||
maximum: u64,
|
||||
) {
|
||||
let effort = request
|
||||
.get("reasoning")
|
||||
.and_then(|v| v.get("effort"))
|
||||
.and_then(Value::as_str)
|
||||
.map(|v| v.trim().to_ascii_lowercase());
|
||||
let forced = matches!(
|
||||
target
|
||||
.get("tool_choice")
|
||||
.and_then(|v| v.get("type"))
|
||||
.and_then(Value::as_str),
|
||||
Some("any" | "tool")
|
||||
);
|
||||
let adaptive = capabilities.adaptive_thinking == Some(true);
|
||||
if forced && adaptive {
|
||||
// 新版 adaptive 模型可能不支持强制工具;沿 CPA 降级为 auto,保留并行限制与推理
|
||||
if let Some(choice) = target.get_mut("tool_choice").and_then(Value::as_object_mut) {
|
||||
choice.insert("type".into(), json!("auto"));
|
||||
choice.shift_remove("name");
|
||||
}
|
||||
} else if forced || (effort.is_none() && continues_without_thinking(target)) {
|
||||
// 默认开启推理的上游要求工具结果回传思考块;无思考的工具轮次保持关闭,直到用户开始新轮次
|
||||
if capabilities.thinking != Some(false) && capabilities.disabled_thinking != Some(false) {
|
||||
target.insert("thinking".into(), json!({"type":"disabled"}));
|
||||
}
|
||||
return;
|
||||
}
|
||||
let Some(effort) = effort else {
|
||||
return;
|
||||
};
|
||||
if capabilities.thinking == Some(false) {
|
||||
return;
|
||||
}
|
||||
if effort == "none" && capabilities.disabled_thinking != Some(false) {
|
||||
target.insert("thinking".into(), json!({"type":"disabled"}));
|
||||
return;
|
||||
}
|
||||
if adaptive {
|
||||
target.insert("thinking".into(), json!({"type":"adaptive"}));
|
||||
if let Some(effort) = adaptive_effort(&effort, capabilities.efforts.as_deref()) {
|
||||
target.entry("output_config").or_insert_with(|| json!({}))["effort"] = json!(effort);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if capabilities.manual_thinking == Some(false) {
|
||||
return;
|
||||
}
|
||||
let requested: u64 = match effort.as_str() {
|
||||
"minimal" => 512,
|
||||
"low" => 1024,
|
||||
"medium" => 8192,
|
||||
"high" => 24576,
|
||||
"xhigh" => 32768,
|
||||
"max" => 128000,
|
||||
"auto" => 8192,
|
||||
_ => return,
|
||||
};
|
||||
// 手动预算至少 1024 且小于输出上限,adaptive 不受此预算下限约束
|
||||
let budget = requested.max(1024).min(maximum.saturating_sub(1));
|
||||
if budget >= 1024 {
|
||||
target.insert(
|
||||
"thinking".into(),
|
||||
json!({"type":"enabled","budget_tokens":budget}),
|
||||
);
|
||||
} else if capabilities.disabled_thinking != Some(false) {
|
||||
target.insert("thinking".into(), json!({"type":"disabled"}));
|
||||
}
|
||||
}
|
||||
|
||||
fn continues_without_thinking(target: &Map<String, Value>) -> bool {
|
||||
let Some([.., assistant, user]) = target
|
||||
.get("messages")
|
||||
.and_then(Value::as_array)
|
||||
.map(Vec::as_slice)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
target.contains_key("tools")
|
||||
&& user["role"] == "user"
|
||||
&& user["content"].as_array().is_some_and(|blocks| {
|
||||
!blocks.is_empty() && blocks.iter().all(|block| block["type"] == "tool_result")
|
||||
})
|
||||
&& assistant["role"] == "assistant"
|
||||
&& assistant["content"].as_array().is_some_and(|blocks| {
|
||||
blocks.iter().any(|block| block["type"] == "tool_use")
|
||||
&& !blocks.iter().any(|block| {
|
||||
matches!(
|
||||
block["type"].as_str(),
|
||||
Some("thinking" | "redacted_thinking")
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn adaptive_effort<'a>(requested: &str, supported: Option<&'a [String]>) -> Option<&'a str> {
|
||||
const LEVELS: [&str; 5] = ["low", "medium", "high", "xhigh", "max"];
|
||||
let requested = match requested {
|
||||
"none" | "minimal" => "low",
|
||||
"auto" => return None,
|
||||
other => other,
|
||||
};
|
||||
let rank = LEVELS.iter().position(|level| *level == requested)?;
|
||||
let Some(supported) = supported else {
|
||||
return Some(LEVELS[rank]);
|
||||
};
|
||||
// 目录明确列出的等级优先,超出范围收敛到最近的较低档,全部更高时取最低可用档
|
||||
LEVELS[..=rank]
|
||||
.iter()
|
||||
.rev()
|
||||
.chain(LEVELS[rank + 1..].iter())
|
||||
.find_map(|level| {
|
||||
supported
|
||||
.iter()
|
||||
.find(|value| value.as_str() == *level)
|
||||
.map(String::as_str)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,315 +0,0 @@
|
||||
//! 工具名称、custom 参数和原生工具声明的双向映射
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use super::TranslationError;
|
||||
use crate::openai::web_search;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct Tool<D> {
|
||||
pub name: String,
|
||||
pub namespace: Option<String>,
|
||||
pub custom: bool,
|
||||
pub definition: D,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub(crate) struct ToolSet<D = ()> {
|
||||
pub tools: BTreeMap<String, Tool<D>>,
|
||||
}
|
||||
|
||||
impl<D> ToolSet<D> {
|
||||
fn collect<'a>(request: &'a Map<String, Value>, definition: impl Fn(&'a Value) -> D) -> Self {
|
||||
let mut result = Self {
|
||||
tools: BTreeMap::new(),
|
||||
};
|
||||
for tool in request
|
||||
.get("tools")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
if tool.get("type").and_then(Value::as_str) == Some("namespace") {
|
||||
let namespace = tool.get("name").and_then(Value::as_str).unwrap_or_default();
|
||||
for child in tool
|
||||
.get("tools")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
result.insert(child, Some(namespace), definition(child));
|
||||
}
|
||||
} else if !web_search::is_search(tool) {
|
||||
result.insert(tool, None, definition(tool));
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn insert(&mut self, definition: &Value, namespace: Option<&str>, retained: D) {
|
||||
let custom = definition.get("type").and_then(Value::as_str) == Some("custom");
|
||||
let Some(name) = definition.get("name").and_then(Value::as_str) else {
|
||||
return;
|
||||
};
|
||||
let qualified = namespace.map_or_else(|| name.to_owned(), |ns| format!("{ns}__{name}"));
|
||||
let mut wire_name = qualified;
|
||||
if wire_name.len() > 64
|
||||
|| !wire_name
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
|
||||
{
|
||||
wire_name = format!("tool_{}", self.tools.len());
|
||||
}
|
||||
let mut alias_index = self.tools.len();
|
||||
while self.tools.contains_key(&wire_name) {
|
||||
wire_name = format!("tool_{alias_index}");
|
||||
alias_index += 1;
|
||||
}
|
||||
self.tools.insert(
|
||||
wire_name,
|
||||
Tool {
|
||||
name: name.to_owned(),
|
||||
namespace: namespace.map(str::to_owned),
|
||||
custom,
|
||||
definition: retained,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
pub fn wire_name<'a>(&'a self, name: &'a str, namespace: Option<&str>) -> &'a str {
|
||||
self.tools
|
||||
.iter()
|
||||
.find_map(|(wire, tool)| {
|
||||
(tool.name == name && tool.namespace.as_deref() == namespace)
|
||||
.then_some(wire.as_str())
|
||||
})
|
||||
.unwrap_or(name)
|
||||
}
|
||||
|
||||
pub fn call(&self, block: &Value, item_id: &str) -> Value {
|
||||
let wire_name = block
|
||||
.get("name")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default();
|
||||
let tool = self.tools.get(wire_name);
|
||||
let name = tool.map_or(wire_name, |tool| tool.name.as_str());
|
||||
let call_id = block.get("id").and_then(Value::as_str).unwrap_or_default();
|
||||
let input = block.get("input").cloned().unwrap_or_else(|| json!({}));
|
||||
let mut item = if tool.is_some_and(|tool| tool.custom) {
|
||||
json!({"type":"custom_tool_call","id":item_id,"call_id":call_id,"name":name,"input":input.get("input").and_then(Value::as_str).unwrap_or_default(),"status":"completed"})
|
||||
} else {
|
||||
json!({"type":"function_call","id":item_id,"call_id":call_id,"name":name,"arguments":input.to_string(),"status":"completed"})
|
||||
};
|
||||
if let Some(namespace) = tool.and_then(|tool| tool.namespace.as_deref()) {
|
||||
item["namespace"] = json!(namespace);
|
||||
}
|
||||
item
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolSet {
|
||||
pub fn identities(request: &Map<String, Value>) -> Self {
|
||||
Self::collect(request, |_| ())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn allowed_tools(choice: &Value) -> Result<Option<&[Value]>, TranslationError> {
|
||||
if choice["type"] != "allowed_tools" {
|
||||
return Ok(None);
|
||||
}
|
||||
choice["tools"]
|
||||
.as_array()
|
||||
.filter(|tools| !tools.is_empty())
|
||||
.map(|tools| Some(tools.as_slice()))
|
||||
.ok_or(TranslationError::InvalidRequest(
|
||||
"Allowed tools must contain at least one tool.",
|
||||
))
|
||||
}
|
||||
|
||||
impl Tool<&Value> {
|
||||
pub(crate) fn schema(&self) -> Value {
|
||||
if self.custom {
|
||||
json!({"type":"object","properties":{"input":{"type":"string"}},"required":["input"]})
|
||||
} else {
|
||||
self.definition
|
||||
.get("parameters")
|
||||
.cloned()
|
||||
.unwrap_or_else(|| json!({"type":"object","properties":{}}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> ToolSet<&'a Value> {
|
||||
pub fn from_responses(request: &'a Map<String, Value>) -> Self {
|
||||
Self::collect(request, |tool| tool)
|
||||
}
|
||||
|
||||
pub(crate) fn declarations<'b>(
|
||||
&'b self,
|
||||
allowed: Option<&'b [Value]>,
|
||||
) -> impl Iterator<Item = (&'b str, &'b Tool<&'a Value>)> {
|
||||
self.tools
|
||||
.iter()
|
||||
.filter(move |(_, tool)| {
|
||||
allowed.is_none_or(|choices| {
|
||||
choices.iter().any(|choice| {
|
||||
matches!(choice["type"].as_str(), Some("function" | "custom"))
|
||||
&& choice["type"] == tool.definition["type"]
|
||||
&& choice.get("name").and_then(Value::as_str)
|
||||
== Some(tool.name.as_str())
|
||||
&& choice.get("namespace").and_then(Value::as_str)
|
||||
== tool.namespace.as_deref()
|
||||
})
|
||||
})
|
||||
})
|
||||
.map(|(name, tool)| (name.as_str(), tool))
|
||||
}
|
||||
|
||||
fn definitions(&self, allowed: Option<&[Value]>) -> Vec<Value> {
|
||||
self.declarations(allowed)
|
||||
.map(|(name, tool)| {
|
||||
let schema = tool.schema();
|
||||
let mut definition = json!({"name":name,"input_schema":schema});
|
||||
for field in ["description", "strict", "cache_control", "defer_loading"] {
|
||||
if let Some(value) = tool.definition.get(field) {
|
||||
definition[field] = value.clone();
|
||||
}
|
||||
}
|
||||
definition
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn write_messages_tools(
|
||||
&self,
|
||||
request: &Map<String, Value>,
|
||||
target: &mut Map<String, Value>,
|
||||
hosted_search: bool,
|
||||
) -> Result<(), TranslationError> {
|
||||
let choice = request.get("tool_choice").unwrap_or(&Value::Null);
|
||||
let allowed = allowed_tools(choice)?;
|
||||
let restricted = allowed.is_some();
|
||||
let mut definitions = self.definitions(allowed);
|
||||
for tool in web_search::allowed_declarations(request)
|
||||
.filter(|tool| hosted_search && web_search::allows_live_access(tool))
|
||||
{
|
||||
let mut search = json!({"type":"web_search_20250305","name":"web_search"});
|
||||
if let Some(filters) = tool.get("filters").filter(|v| !v.is_null()) {
|
||||
let filters = filters.as_object().ok_or(TranslationError::InvalidRequest(
|
||||
"Web search filters must be an object.",
|
||||
))?;
|
||||
for field in ["allowed_domains", "blocked_domains"] {
|
||||
if let Some(value) = filters.get(field) {
|
||||
search[field] = value.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
for field in ["max_uses", "user_location"] {
|
||||
if let Some(value) = tool.get(field) {
|
||||
search[field] = value.clone();
|
||||
}
|
||||
}
|
||||
definitions.push(search);
|
||||
}
|
||||
if definitions.is_empty() {
|
||||
// 转往仅支持函数的上游时,可选托管搜索可以省略,强制工具仍须可执行
|
||||
let optional_search = !hosted_search
|
||||
&& choice["mode"] == "auto"
|
||||
&& allowed.is_some_and(|tools| tools.iter().all(web_search::is_search));
|
||||
if !hosted_search
|
||||
&& (choice == "required"
|
||||
|| matches!(choice["type"].as_str(), Some("function" | "custom")))
|
||||
{
|
||||
return Err(TranslationError::InvalidRequest(
|
||||
"No declared function can satisfy the required tool choice.",
|
||||
));
|
||||
}
|
||||
if restricted && !optional_search {
|
||||
return Err(TranslationError::InvalidRequest(
|
||||
"No allowed tool can be used with the Messages upstream.",
|
||||
));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
target.insert("tools".into(), Value::Array(definitions));
|
||||
let serial = request.get("parallel_tool_calls").and_then(Value::as_bool) == Some(false);
|
||||
if choice.is_null() && !serial {
|
||||
return Ok(());
|
||||
}
|
||||
let kind = if restricted {
|
||||
match choice["mode"].as_str() {
|
||||
Some(mode @ ("auto" | "required")) => mode,
|
||||
_ => {
|
||||
return Err(TranslationError::InvalidRequest(
|
||||
"Allowed tools mode must be auto or required.",
|
||||
));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
choice
|
||||
.as_str()
|
||||
.or_else(|| choice.get("type").and_then(Value::as_str))
|
||||
.unwrap_or("auto")
|
||||
};
|
||||
let mut mapped = match kind {
|
||||
"required" => json!({"type":"any"}),
|
||||
"none" => json!({"type":"none"}),
|
||||
"function" | "custom" => {
|
||||
json!({"type":"tool","name":self.wire_name(choice["name"].as_str().unwrap_or_default(),choice["namespace"].as_str())})
|
||||
}
|
||||
_ => json!({"type":"auto"}),
|
||||
};
|
||||
if serial && kind != "none" {
|
||||
mapped["disable_parallel_tool_use"] = json!(true);
|
||||
}
|
||||
target.insert("tool_choice".into(), mapped);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn messages_tools(tools: &[Value]) -> Vec<Value> {
|
||||
tools.iter().map(|tool| {
|
||||
let kind = tool.get("type").and_then(Value::as_str).unwrap_or_default();
|
||||
if kind.starts_with("web_search_") {
|
||||
let mut search = json!({"type":"web_search"});
|
||||
for field in ["allowed_domains", "blocked_domains"] {
|
||||
if let Some(v) = tool.get(field) { search["filters"][field] = v.clone(); }
|
||||
}
|
||||
if let Some(v) = tool.get("user_location") { search["user_location"] = v.clone(); }
|
||||
return search;
|
||||
}
|
||||
let mut result = json!({"type":"function","name":tool.get("name").and_then(Value::as_str).unwrap_or_default(),"parameters":tool.get("input_schema").cloned().unwrap_or_else(||json!({"type":"object","properties":{}}))});
|
||||
for field in ["description", "strict"] {
|
||||
if let Some(value) = tool.get(field) { result[field] = value.clone(); }
|
||||
}
|
||||
result
|
||||
}).collect()
|
||||
}
|
||||
|
||||
// 截断的 custom 包装仍可携带已生成的字符串,未完成的转义按原片段保留
|
||||
pub(super) fn partial_custom_input(arguments: &str) -> String {
|
||||
let Some((_, rest)) = arguments.split_once("\"input\"") else {
|
||||
return arguments.to_owned();
|
||||
};
|
||||
let Some(value) = rest.trim_start().strip_prefix(':').map(str::trim_start) else {
|
||||
return arguments.to_owned();
|
||||
};
|
||||
if let Some(Ok(input)) = serde_json::Deserializer::from_str(value)
|
||||
.into_iter::<String>()
|
||||
.next()
|
||||
{
|
||||
return input;
|
||||
}
|
||||
// 一个未完成的 UTF-16 代理对最多占 12 字节,只尝试修复字符串尾部
|
||||
for end in std::iter::once(value.len())
|
||||
.chain(value.char_indices().rev().take(12).map(|(index, _)| index))
|
||||
{
|
||||
if let Ok(mut input) = serde_json::from_str::<String>(&format!("{}\"", &value[..end])) {
|
||||
input.push_str(&value[end..]);
|
||||
return input;
|
||||
}
|
||||
}
|
||||
arguments.to_owned()
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Messages 累计用量的字段合并与 Responses 投影
|
||||
//! Messages 累计用量的字段合并与缓存事实
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use serde_json::Value;
|
||||
|
||||
/// 原生 Messages 用量,缺失字段保留未知状态
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -51,27 +51,4 @@ impl MessageUsage {
|
||||
.saturating_add(self.cache_creation_input_tokens.unwrap_or_default())
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn responses(self) -> Value {
|
||||
let input = self.total_input_tokens().unwrap_or_default();
|
||||
let output = self.output_tokens.unwrap_or_default();
|
||||
// Messages 没有独立的推理 token 计数,省略详情,避免空对象违反 Responses 客户端合同
|
||||
json!({"input_tokens": input, "output_tokens": output, "total_tokens": input.saturating_add(output), "input_tokens_details": {"cached_tokens": self.cache_read_input_tokens.unwrap_or_default(), "cache_write_tokens": self.cache_creation_input_tokens.unwrap_or_default()}})
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn responses_usage(value: &Value) -> Value {
|
||||
let input = value
|
||||
.get("input_tokens")
|
||||
.and_then(Value::as_u64)
|
||||
.unwrap_or_default();
|
||||
let cached = value
|
||||
.pointer("/input_tokens_details/cached_tokens")
|
||||
.and_then(Value::as_u64)
|
||||
.unwrap_or_default();
|
||||
let written = value
|
||||
.pointer("/input_tokens_details/cache_write_tokens")
|
||||
.and_then(Value::as_u64)
|
||||
.unwrap_or_default();
|
||||
json!({"input_tokens": input.saturating_sub(cached).saturating_sub(written), "output_tokens": value.get("output_tokens").and_then(Value::as_u64).unwrap_or_default(), "cache_read_input_tokens": cached, "cache_creation_input_tokens": written})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
//! Chat 解析与直接转换的安全错误事实
|
||||
|
||||
use thiserror::Error;
|
||||
|
||||
/// 协议层错误不持有请求内容或上游凭据
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Error)]
|
||||
pub enum ChatError {
|
||||
#[error("Request body must be valid JSON.")]
|
||||
MalformedJson,
|
||||
#[error("Request body must be a JSON object.")]
|
||||
ExpectedObject,
|
||||
#[error("Required parameter `{field}` is missing.")]
|
||||
MissingField { field: String },
|
||||
#[error("Parameter `{field}` must be {expected}.")]
|
||||
InvalidType {
|
||||
field: String,
|
||||
expected: &'static str,
|
||||
},
|
||||
#[error("Parameter `{field}` must not be empty.")]
|
||||
EmptyField { field: String },
|
||||
#[error("Parameter `{field}` has an invalid value.")]
|
||||
InvalidValue { field: String },
|
||||
#[error("Unknown parameter `{field}`.")]
|
||||
UnknownField { field: String },
|
||||
#[error("Parameter `{field}` is not supported by this upstream.")]
|
||||
UnsupportedField { field: String },
|
||||
#[error("The requested `{field}` is not supported with `{other}`.")]
|
||||
UnsupportedCombination {
|
||||
field: &'static str,
|
||||
other: &'static str,
|
||||
},
|
||||
#[error("The upstream response cannot be represented as a Chat completion.")]
|
||||
InvalidResponse,
|
||||
#[error("The upstream stream ended before its terminal event.")]
|
||||
IncompleteStream,
|
||||
}
|
||||
|
||||
impl ChatError {
|
||||
/// 供 API 出口构造稳定的机器码
|
||||
pub const fn code(&self) -> &'static str {
|
||||
match self {
|
||||
Self::MalformedJson => "invalid_json",
|
||||
Self::ExpectedObject => "invalid_request_body",
|
||||
Self::MissingField { .. } => "missing_required_parameter",
|
||||
Self::InvalidType { .. } => "invalid_type",
|
||||
Self::EmptyField { .. } | Self::InvalidValue { .. } => "invalid_value",
|
||||
Self::UnknownField { .. } => "unknown_parameter",
|
||||
Self::UnsupportedField { .. } | Self::UnsupportedCombination { .. } => {
|
||||
"unsupported_parameter"
|
||||
}
|
||||
Self::InvalidResponse => "invalid_upstream_response",
|
||||
Self::IncompleteStream => "incomplete_upstream_response",
|
||||
}
|
||||
}
|
||||
|
||||
/// 字段路径仅包含协议结构,不包含用户值
|
||||
pub fn parameter(&self) -> Option<&str> {
|
||||
match self {
|
||||
Self::MissingField { field }
|
||||
| Self::InvalidType { field, .. }
|
||||
| Self::EmptyField { field }
|
||||
| Self::InvalidValue { field }
|
||||
| Self::UnknownField { field }
|
||||
| Self::UnsupportedField { field } => Some(field),
|
||||
Self::UnsupportedCombination { field, .. } => Some(field),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn invalid(field: &str) -> ChatError {
|
||||
ChatError::InvalidValue {
|
||||
field: field.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn unsupported(field: &str) -> ChatError {
|
||||
ChatError::UnsupportedField {
|
||||
field: field.to_owned(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
//! Chat 与 GenAI 的直接请求和响应映射
|
||||
|
||||
mod request;
|
||||
mod response;
|
||||
mod stream;
|
||||
|
||||
pub use request::convert_request;
|
||||
pub use response::{project_response, project_response_with_request};
|
||||
pub use stream::ChatStreamEncoder;
|
||||
@@ -0,0 +1,413 @@
|
||||
//! Chat 内容、工具与生成设置直接构造 GenAI 正文
|
||||
|
||||
use crate::chat_completions::{
|
||||
ChatError,
|
||||
error::{invalid, unsupported},
|
||||
request::string,
|
||||
validate_request,
|
||||
};
|
||||
use serde_json::{Map, Value, json};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>, ChatError> {
|
||||
validate_request(chat)?;
|
||||
let mut system = Vec::new();
|
||||
if let Some(instructions) = chat.get("instructions").filter(|v| !v.is_null()) {
|
||||
system.extend(parts(instructions, "instructions", true)?);
|
||||
}
|
||||
let mut contents = Vec::new();
|
||||
let mut calls = BTreeMap::new();
|
||||
let mut used = BTreeSet::new();
|
||||
for (index, message) in chat["messages"]
|
||||
.as_array()
|
||||
.ok_or_else(|| invalid("messages"))?
|
||||
.iter()
|
||||
.enumerate()
|
||||
{
|
||||
let path = format!("messages[{index}]");
|
||||
let role = message["role"].as_str().ok_or_else(|| invalid(&path))?;
|
||||
if matches!(role, "system" | "developer") {
|
||||
system.extend(parts(
|
||||
&message["content"],
|
||||
&format!("{path}.content"),
|
||||
true,
|
||||
)?);
|
||||
continue;
|
||||
}
|
||||
let content = if role == "tool" {
|
||||
let id = string(
|
||||
message.get("tool_call_id"),
|
||||
&format!("{path}.tool_call_id"),
|
||||
false,
|
||||
)?;
|
||||
let name = calls
|
||||
.get(id)
|
||||
.ok_or_else(|| invalid(&format!("{path}.tool_call_id")))?;
|
||||
if !used.insert(id.to_owned()) {
|
||||
return Err(invalid(&format!("{path}.tool_call_id")));
|
||||
}
|
||||
let mut text = Vec::new();
|
||||
let mut media = Vec::new();
|
||||
for part in parts(&message["content"], &format!("{path}.content"), false)? {
|
||||
if let Some(value) = part.get("text").and_then(Value::as_str) {
|
||||
text.push(value.to_owned());
|
||||
} else {
|
||||
media.push(part);
|
||||
}
|
||||
}
|
||||
let mut response = json!({"functionResponse":{"id":id,"name":name,"response":{"output":text.join("\n")}}});
|
||||
if !media.is_empty() {
|
||||
response["functionResponse"]["parts"] = media.into();
|
||||
}
|
||||
vec![response]
|
||||
} else {
|
||||
let mut content = if message["content"].is_null() {
|
||||
Vec::new()
|
||||
} else {
|
||||
parts(&message["content"], &format!("{path}.content"), false)?
|
||||
};
|
||||
if let Some(refusal) = message.get("refusal").and_then(Value::as_str) {
|
||||
content.push(json!({"text":refusal}));
|
||||
}
|
||||
for (call_index, call) in message
|
||||
.get("tool_calls")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.enumerate()
|
||||
{
|
||||
let path = format!("{path}.tool_calls[{call_index}]");
|
||||
let id = string(call.get("id"), &format!("{path}.id"), false)?;
|
||||
let kind = call["type"].as_str().ok_or_else(|| invalid(&path))?;
|
||||
let name = string(
|
||||
call[kind].get("name"),
|
||||
&format!("{path}.{kind}.name"),
|
||||
false,
|
||||
)?;
|
||||
if calls.insert(id.to_owned(), name.to_owned()).is_some() {
|
||||
return Err(invalid(&format!("{path}.id")));
|
||||
}
|
||||
let arguments = if kind == "custom" {
|
||||
json!({"input":call[kind]["input"]})
|
||||
} else {
|
||||
serde_json::from_str::<Value>(string(
|
||||
call[kind].get("arguments"),
|
||||
&format!("{path}.function.arguments"),
|
||||
true,
|
||||
)?)
|
||||
.map_err(|_| invalid(&format!("{path}.function.arguments")))?
|
||||
};
|
||||
if !arguments.is_object() {
|
||||
return Err(invalid(&format!("{path}.function.arguments")));
|
||||
}
|
||||
// Chat 历史没有 Google 签名,采用官方允许的外部工具历史标记
|
||||
content.push(json!({"functionCall":{"id":id,"name":name,"args":arguments},"thoughtSignature":"skip_thought_signature_validator"}));
|
||||
}
|
||||
content
|
||||
};
|
||||
append(
|
||||
&mut contents,
|
||||
if role == "assistant" { "model" } else { "user" },
|
||||
content,
|
||||
);
|
||||
}
|
||||
if contents.is_empty() {
|
||||
return Err(invalid("messages"));
|
||||
}
|
||||
let mut result = Map::from_iter([("contents".into(), contents.into())]);
|
||||
if !system.is_empty() {
|
||||
result.insert("systemInstruction".into(), json!({"parts":system}));
|
||||
}
|
||||
let mut generation = Map::new();
|
||||
if let Some(value) = ["max_completion_tokens", "max_tokens", "max_output_tokens"]
|
||||
.into_iter()
|
||||
.find_map(|key| chat.get(key).filter(|v| !v.is_null()))
|
||||
{
|
||||
let max = value
|
||||
.as_u64()
|
||||
.filter(|v| *v > 0)
|
||||
.ok_or_else(|| invalid("max_completion_tokens"))?;
|
||||
generation.insert("maxOutputTokens".into(), json!(max));
|
||||
}
|
||||
for (from, to) in [("temperature", "temperature"), ("top_p", "topP")] {
|
||||
if let Some(value) = chat.get(from).filter(|v| !v.is_null()) {
|
||||
generation.insert(to.into(), value.clone());
|
||||
}
|
||||
}
|
||||
if let Some(effort) = chat
|
||||
.get("reasoning_effort")
|
||||
.or_else(|| chat.get("reasoning").and_then(|v| v.get("effort")))
|
||||
.filter(|v| !v.is_null())
|
||||
{
|
||||
let budget: i64 = match effort.as_str() {
|
||||
Some("none") => 0,
|
||||
Some("minimal" | "low") => 1024,
|
||||
Some("medium") => 8192,
|
||||
Some("high") => 24576,
|
||||
Some("xhigh") => 32768,
|
||||
Some("max") => 128000,
|
||||
Some("auto") => -1,
|
||||
_ => return Err(invalid("reasoning_effort")),
|
||||
};
|
||||
generation.insert(
|
||||
"thinkingConfig".into(),
|
||||
if budget == 0 {
|
||||
json!({"thinkingBudget":0})
|
||||
} else {
|
||||
json!({"thinkingBudget":budget,"includeThoughts":true})
|
||||
},
|
||||
);
|
||||
}
|
||||
if let Some(format) = chat
|
||||
.get("response_format")
|
||||
.or_else(|| chat.get("text").and_then(|v| v.get("format")))
|
||||
.filter(|v| !v.is_null())
|
||||
{
|
||||
match format["type"].as_str() {
|
||||
Some("json_schema") => {
|
||||
generation.insert("responseMimeType".into(), json!("application/json"));
|
||||
let schema = format
|
||||
.get("json_schema")
|
||||
.unwrap_or(format)
|
||||
.get("schema")
|
||||
.filter(|v| v.is_object())
|
||||
.ok_or_else(|| invalid("response_format.json_schema.schema"))?;
|
||||
generation.insert("responseJsonSchema".into(), schema.clone());
|
||||
}
|
||||
Some("json_object") => {
|
||||
generation.insert("responseMimeType".into(), json!("application/json"));
|
||||
}
|
||||
Some("text") => {}
|
||||
_ => return Err(unsupported("response_format.type")),
|
||||
}
|
||||
}
|
||||
if chat.get("logprobs") == Some(&Value::Bool(true)) {
|
||||
generation.insert("responseLogprobs".into(), json!(true));
|
||||
if let Some(value) = chat.get("top_logprobs") {
|
||||
generation.insert("logprobs".into(), value.clone());
|
||||
}
|
||||
}
|
||||
tools(chat, &mut result)?;
|
||||
if !generation.is_empty() {
|
||||
result.insert("generationConfig".into(), generation.into());
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn append(contents: &mut Vec<Value>, role: &str, parts: Vec<Value>) {
|
||||
if let Some(last) = contents.last_mut().filter(|v| v["role"] == role) {
|
||||
last["parts"]
|
||||
.as_array_mut()
|
||||
.expect("已构造的内容为数组")
|
||||
.extend(parts);
|
||||
} else {
|
||||
contents.push(json!({"role":role,"parts":parts}));
|
||||
}
|
||||
}
|
||||
|
||||
fn parts(value: &Value, path: &str, system: bool) -> Result<Vec<Value>, ChatError> {
|
||||
if let Some(text) = value.as_str() {
|
||||
return Ok(vec![json!({"text":text})]);
|
||||
}
|
||||
value
|
||||
.as_array()
|
||||
.ok_or_else(|| invalid(path))?
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, part)| {
|
||||
let path = format!("{path}[{index}]");
|
||||
let kind = string(part.get("type"), &format!("{path}.type"), false)?;
|
||||
match kind {
|
||||
"text" | "input_text" | "output_text" => {
|
||||
Ok(json!({"text":string(part.get("text"), &format!("{path}.text"), true)?}))
|
||||
}
|
||||
"refusal" if !system => Ok(
|
||||
json!({"text":string(part.get("refusal"), &format!("{path}.refusal"), true)?}),
|
||||
),
|
||||
"image_url" | "input_image" if !system => {
|
||||
let url = part
|
||||
.get("image_url")
|
||||
.and_then(|v| v.as_str().or_else(|| v.get("url").and_then(Value::as_str)))
|
||||
.ok_or_else(|| invalid(&format!("{path}.image_url")))?;
|
||||
media(url, part.get("mime_type").and_then(Value::as_str), &path)
|
||||
}
|
||||
"file" | "input_file" if !system => {
|
||||
let file = if kind == "file" { &part["file"] } else { part };
|
||||
let url = file
|
||||
.get("file_data")
|
||||
.or_else(|| file.get("file_url"))
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| unsupported(&format!("{path}.file_id")))?;
|
||||
let mime = file.get("mime_type").and_then(Value::as_str).or_else(|| {
|
||||
file.get("filename")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|v| v.ends_with(".pdf"))
|
||||
.map(|_| "application/pdf")
|
||||
});
|
||||
media(url, mime, &path)
|
||||
}
|
||||
"input_audio" if !system => {
|
||||
let audio = &part["input_audio"];
|
||||
let data = string(
|
||||
audio.get("data"),
|
||||
&format!("{path}.input_audio.data"),
|
||||
false,
|
||||
)?;
|
||||
let format = string(
|
||||
audio.get("format"),
|
||||
&format!("{path}.input_audio.format"),
|
||||
false,
|
||||
)?;
|
||||
let mime = match format {
|
||||
"wav" => "audio/wav",
|
||||
"mp3" => "audio/mpeg",
|
||||
_ => return Err(unsupported(&format!("{path}.input_audio.format"))),
|
||||
};
|
||||
Ok(json!({"inlineData":{"mimeType":mime,"data":data}}))
|
||||
}
|
||||
_ => Err(unsupported(&format!("{path}.type"))),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn media(data: &str, mime: Option<&str>, path: &str) -> Result<Value, ChatError> {
|
||||
if let Some(data) = data.strip_prefix("data:") {
|
||||
let (mime, data) = data
|
||||
.split_once(";base64,")
|
||||
.filter(|(mime, data)| !mime.is_empty() && !data.is_empty())
|
||||
.ok_or_else(|| invalid(path))?;
|
||||
return Ok(json!({"inlineData":{"mimeType":mime,"data":data}}));
|
||||
}
|
||||
let mime = mime.ok_or_else(|| unsupported(&format!("{path}.mime_type")))?;
|
||||
if let Ok(url) = url::Url::parse(data)
|
||||
&& matches!(url.scheme(), "https" | "http" | "gs")
|
||||
{
|
||||
return Ok(json!({"fileData":{"mimeType":mime,"fileUri":data}}));
|
||||
}
|
||||
if !data.is_empty() {
|
||||
return Ok(json!({"inlineData":{"mimeType":mime,"data":data}}));
|
||||
}
|
||||
Err(invalid(path))
|
||||
}
|
||||
|
||||
fn tools(chat: &Map<String, Value>, result: &mut Map<String, Value>) -> Result<(), ChatError> {
|
||||
let mut declarations = Vec::new();
|
||||
if let Some(tools) = chat.get("tools").filter(|v| !v.is_null()) {
|
||||
for (index, tool) in tools
|
||||
.as_array()
|
||||
.ok_or_else(|| invalid("tools"))?
|
||||
.iter()
|
||||
.enumerate()
|
||||
{
|
||||
let path = format!("tools[{index}]");
|
||||
let kind = string(tool.get("type"), &format!("{path}.type"), false)?;
|
||||
if !matches!(kind, "function" | "custom") {
|
||||
return Err(unsupported(&format!("{path}.type")));
|
||||
}
|
||||
let definition = &tool[kind];
|
||||
let name = string(
|
||||
definition.get("name"),
|
||||
&format!("{path}.{kind}.name"),
|
||||
false,
|
||||
)?;
|
||||
let parameters = if kind == "custom" {
|
||||
json!({"type":"object","properties":{"input":{"type":"string"}},"required":["input"]})
|
||||
} else {
|
||||
definition
|
||||
.get("parameters")
|
||||
.cloned()
|
||||
.unwrap_or_else(|| json!({"type":"object","properties":{}}))
|
||||
};
|
||||
if !parameters.is_object() {
|
||||
return Err(invalid(&format!("{path}.function.parameters")));
|
||||
}
|
||||
let mut declaration = json!({"name":name,"parametersJsonSchema":parameters});
|
||||
if let Some(value) = definition.get("description") {
|
||||
declaration["description"] = value.clone();
|
||||
}
|
||||
declarations.push(declaration);
|
||||
}
|
||||
}
|
||||
let mut choice = chat.get("tool_choice").cloned().unwrap_or(Value::Null);
|
||||
if let Some(options) = chat.get("web_search_options").filter(|v| !v.is_null()) {
|
||||
if !options.is_object()
|
||||
|| !declarations.is_empty()
|
||||
|| (!choice.is_null() && choice != "auto")
|
||||
{
|
||||
return Err(invalid("web_search_options"));
|
||||
}
|
||||
for field in ["user_location", "search_context_size"] {
|
||||
if options.get(field).is_some_and(|v| !v.is_null()) {
|
||||
return Err(unsupported(&format!("web_search_options.{field}")));
|
||||
}
|
||||
}
|
||||
result.insert("tools".into(), json!([{"googleSearch":{}}]));
|
||||
return Ok(());
|
||||
}
|
||||
if choice["type"] == "allowed_tools" {
|
||||
let allowed = choice.get("allowed_tools").unwrap_or(&choice);
|
||||
let permitted = allowed["tools"]
|
||||
.as_array()
|
||||
.filter(|v| !v.is_empty())
|
||||
.ok_or_else(|| invalid("tool_choice.allowed_tools.tools"))?;
|
||||
declarations.retain(|tool| {
|
||||
permitted.iter().any(|v| {
|
||||
v.get(v["type"].as_str().unwrap_or("function"))
|
||||
.and_then(|v| v.get("name"))
|
||||
.or_else(|| v.get("name"))
|
||||
== tool.get("name")
|
||||
})
|
||||
});
|
||||
choice = allowed
|
||||
.get("mode")
|
||||
.cloned()
|
||||
.ok_or_else(|| invalid("tool_choice.allowed_tools.mode"))?;
|
||||
}
|
||||
if declarations.is_empty() {
|
||||
if !choice.is_null() && choice != "auto" && choice != "none" {
|
||||
return Err(invalid("tool_choice"));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let kind = choice
|
||||
.as_str()
|
||||
.or_else(|| choice.get("type").and_then(Value::as_str))
|
||||
.unwrap_or("auto");
|
||||
let mut config = match kind {
|
||||
"auto" => json!({"mode":"AUTO"}),
|
||||
"none" => json!({"mode":"NONE"}),
|
||||
"required" => json!({"mode":"ANY"}),
|
||||
"function" | "custom" => {
|
||||
let name = string(
|
||||
choice.get(kind).and_then(|v| v.get("name")),
|
||||
"tool_choice.name",
|
||||
false,
|
||||
)?;
|
||||
if !declarations.iter().any(|v| v["name"] == name) {
|
||||
return Err(invalid("tool_choice"));
|
||||
}
|
||||
json!({"mode":"ANY","allowedFunctionNames":[name]})
|
||||
}
|
||||
_ => return Err(unsupported("tool_choice")),
|
||||
};
|
||||
// Google 的函数调用配置没有禁止并行的同义字段,不伪造未受支持的约束
|
||||
if chat.get("parallel_tool_calls") == Some(&Value::Bool(false)) {
|
||||
return Err(unsupported("parallel_tool_calls"));
|
||||
}
|
||||
if config["mode"] == "ANY" && config.get("allowedFunctionNames").is_none() {
|
||||
config["allowedFunctionNames"] = declarations
|
||||
.iter()
|
||||
.map(|v| v["name"].clone())
|
||||
.collect::<Vec<_>>()
|
||||
.into();
|
||||
}
|
||||
result.insert(
|
||||
"tools".into(),
|
||||
json!([{"functionDeclarations":declarations}]),
|
||||
);
|
||||
if !choice.is_null() {
|
||||
result.insert("toolConfig".into(), json!({"functionCallingConfig":config}));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
//! GenAI 完整响应、用量和来源直接投影为 Chat
|
||||
|
||||
use super::stream::ChatStreamEncoder;
|
||||
use crate::chat_completions::{ChatAccumulator, ChatError, ChatIdentity};
|
||||
use crate::genai::UsageMetadata;
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
pub fn project_response(response: &Value, identity: &ChatIdentity) -> Result<Value, ChatError> {
|
||||
project(response, ChatStreamEncoder::new(identity.clone(), true))
|
||||
}
|
||||
|
||||
pub fn project_response_with_request(
|
||||
response: &Value,
|
||||
identity: &ChatIdentity,
|
||||
request: &Map<String, Value>,
|
||||
) -> Result<Value, ChatError> {
|
||||
project(
|
||||
response,
|
||||
ChatStreamEncoder::with_request(identity.clone(), true, request),
|
||||
)
|
||||
}
|
||||
|
||||
fn project(response: &Value, mut encoder: ChatStreamEncoder) -> Result<Value, ChatError> {
|
||||
let mut accumulator = ChatAccumulator::default();
|
||||
for chunk in encoder.push_event(None, response)? {
|
||||
accumulator.push(&chunk)?;
|
||||
}
|
||||
for chunk in encoder.finish()? {
|
||||
accumulator.push(&chunk)?;
|
||||
}
|
||||
accumulator.finish()
|
||||
}
|
||||
|
||||
pub(super) fn usage(usage: &UsageMetadata) -> Option<Value> {
|
||||
let input = usage.input_tokens()?;
|
||||
let output = usage.output_tokens()?;
|
||||
let mut result = json!({"prompt_tokens":input,"completion_tokens":output,"total_tokens":usage.total.unwrap_or_else(||input.saturating_add(output))});
|
||||
if let Some(cached) = usage.cached {
|
||||
result["prompt_tokens_details"]["cached_tokens"] = json!(cached);
|
||||
}
|
||||
if let Some(image) = usage.image_input_tokens() {
|
||||
result["prompt_tokens_details"]["image_tokens"] = json!(image);
|
||||
}
|
||||
if let Some(reasoning) = usage.thoughts {
|
||||
result["completion_tokens_details"]["reasoning_tokens"] = json!(reasoning);
|
||||
}
|
||||
if let Some(image) = usage.candidate_image {
|
||||
result["completion_tokens_details"]["image_tokens"] = json!(image);
|
||||
}
|
||||
Some(result)
|
||||
}
|
||||
|
||||
pub(super) fn annotations(candidate: &Value, full_text: &str, text_start: usize) -> Vec<Value> {
|
||||
let mut positions = Vec::new();
|
||||
let mut char_offset = text_start;
|
||||
for part in candidate
|
||||
.pointer("/content/parts")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
let text = part
|
||||
.get("text")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|_| part["thought"] != true);
|
||||
positions.push(text.map(|text| {
|
||||
let offset = char_offset;
|
||||
char_offset += text.chars().count();
|
||||
(offset, text)
|
||||
}));
|
||||
}
|
||||
if positions.is_empty() {
|
||||
positions.push(Some((0, full_text)));
|
||||
}
|
||||
let metadata = &candidate["groundingMetadata"];
|
||||
let Some(chunks) = metadata["groundingChunks"].as_array() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut output = Vec::new();
|
||||
for support in metadata["groundingSupports"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
let segment = &support["segment"];
|
||||
let index = segment
|
||||
.get("partIndex")
|
||||
.and_then(Value::as_u64)
|
||||
.unwrap_or_default() as usize;
|
||||
let Some(Some((offset, text))) = positions.get(index) else {
|
||||
continue;
|
||||
};
|
||||
let start = segment
|
||||
.get("startIndex")
|
||||
.and_then(Value::as_u64)
|
||||
.unwrap_or_default() as usize;
|
||||
let Some(end) = segment
|
||||
.get("endIndex")
|
||||
.and_then(Value::as_u64)
|
||||
.and_then(|v| usize::try_from(v).ok())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if start > end || !text.is_char_boundary(start) || !text.is_char_boundary(end) {
|
||||
continue;
|
||||
}
|
||||
if let Some(expected) = segment.get("text").and_then(Value::as_str)
|
||||
&& text.get(start..end) != Some(expected)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let start = offset + text[..start].chars().count();
|
||||
let end = offset + text[..end].chars().count();
|
||||
for index in support["groundingChunkIndices"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(Value::as_u64)
|
||||
{
|
||||
let Some(source) = chunks.get(index as usize).and_then(|v| v.get("web")) else {
|
||||
continue;
|
||||
};
|
||||
let Some(url) = source.get("uri").and_then(Value::as_str) else {
|
||||
continue;
|
||||
};
|
||||
if !url::Url::parse(url)
|
||||
.is_ok_and(|v| matches!(v.scheme(), "http" | "https") && v.host_str().is_some())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let annotation = json!({"type":"url_citation","url_citation":{"url":url,"title":source.get("title").and_then(Value::as_str).unwrap_or(url),"start_index":start,"end_index":end}});
|
||||
if !output.contains(&annotation) {
|
||||
output.push(annotation);
|
||||
}
|
||||
}
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
pub(super) fn logprobs(candidate: &Value) -> Result<Option<Value>, ChatError> {
|
||||
let Some(result) = candidate.get("logprobsResult").filter(|v| !v.is_null()) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let chosen = result
|
||||
.get("chosenCandidates")
|
||||
.and_then(Value::as_array)
|
||||
.ok_or(ChatError::InvalidResponse)?;
|
||||
let top = result.get("topCandidates").and_then(Value::as_array);
|
||||
let tokens = chosen
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, chosen)| {
|
||||
let mut token = logprob(chosen)?;
|
||||
let top = top
|
||||
.and_then(|v| v.get(index))
|
||||
.and_then(|v| v.get("candidates"))
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(logprob)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
token["top_logprobs"] = top.into();
|
||||
Ok(token)
|
||||
})
|
||||
.collect::<Result<Vec<_>, ChatError>>()?;
|
||||
Ok(Some(json!({"content":tokens,"refusal":null})))
|
||||
}
|
||||
|
||||
fn logprob(value: &Value) -> Result<Value, ChatError> {
|
||||
let token = value
|
||||
.get("token")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or(ChatError::InvalidResponse)?;
|
||||
let probability = value
|
||||
.get("logProbability")
|
||||
.filter(|v| v.is_number())
|
||||
.ok_or(ChatError::InvalidResponse)?;
|
||||
Ok(json!({"token":token,"logprob":probability,"bytes":token.as_bytes()}))
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
//! GenAI 原生候选增量直接产生 Chat chunk,EOF 校验生成终态
|
||||
|
||||
use super::response::{annotations, logprobs, usage};
|
||||
use crate::chat_completions::{
|
||||
ChatError, ChatIdentity,
|
||||
response::{chunk, custom_tools, tool_call, usage_chunk},
|
||||
};
|
||||
use crate::genai::{GenerateContentObservation, GenerationFinish};
|
||||
use serde_json::{Map, Value, json};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
pub struct ChatStreamEncoder {
|
||||
identity: ChatIdentity,
|
||||
include_usage: bool,
|
||||
custom: BTreeSet<String>,
|
||||
observation: GenerateContentObservation,
|
||||
usage: Option<Value>,
|
||||
started: bool,
|
||||
completed: bool,
|
||||
failed: bool,
|
||||
candidate_finished: bool,
|
||||
calls: BTreeSet<String>,
|
||||
text: String,
|
||||
annotations: Vec<Value>,
|
||||
required_search: bool,
|
||||
grounded: bool,
|
||||
}
|
||||
|
||||
impl ChatStreamEncoder {
|
||||
pub fn new(identity: ChatIdentity, include_usage: bool) -> Self {
|
||||
Self {
|
||||
identity,
|
||||
include_usage,
|
||||
custom: BTreeSet::new(),
|
||||
observation: GenerateContentObservation::default(),
|
||||
usage: None,
|
||||
started: false,
|
||||
completed: false,
|
||||
failed: false,
|
||||
candidate_finished: false,
|
||||
calls: BTreeSet::new(),
|
||||
text: String::new(),
|
||||
annotations: Vec::new(),
|
||||
required_search: false,
|
||||
grounded: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_request(
|
||||
identity: ChatIdentity,
|
||||
include_usage: bool,
|
||||
request: &Map<String, Value>,
|
||||
) -> Self {
|
||||
Self {
|
||||
custom: custom_tools(request),
|
||||
required_search: request
|
||||
.get("web_search_options")
|
||||
.is_some_and(|v| !v.is_null()),
|
||||
..Self::new(identity, include_usage)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_completed(&self) -> bool {
|
||||
self.completed
|
||||
}
|
||||
pub fn has_wire_failure(&self) -> bool {
|
||||
self.failed
|
||||
}
|
||||
|
||||
pub fn push_event(
|
||||
&mut self,
|
||||
_event: Option<&str>,
|
||||
value: &Value,
|
||||
) -> Result<Vec<Value>, ChatError> {
|
||||
if self.failed {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
if self.completed || !value.is_object() {
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
if let Some(error) = value.get("error") {
|
||||
if !error.is_object() {
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
self.failed = true;
|
||||
return Ok(vec![json!({"error":error})]);
|
||||
}
|
||||
if let Some(usage) = self.observation.observe(value).and_then(usage) {
|
||||
self.usage = Some(usage);
|
||||
}
|
||||
let mut frames = Vec::new();
|
||||
if !self.started {
|
||||
self.started = true;
|
||||
frames.push(chunk(
|
||||
&self.identity,
|
||||
json!({"role":"assistant","content":"","refusal":null}),
|
||||
None,
|
||||
self.include_usage,
|
||||
));
|
||||
}
|
||||
let candidates = match value.get("candidates") {
|
||||
None | Some(Value::Null) => &[][..],
|
||||
Some(value) => value
|
||||
.as_array()
|
||||
.map(Vec::as_slice)
|
||||
.ok_or(ChatError::InvalidResponse)?,
|
||||
};
|
||||
if candidates.len() > 1 {
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
for candidate in candidates {
|
||||
if candidate
|
||||
.get("index")
|
||||
.and_then(Value::as_u64)
|
||||
.unwrap_or_default()
|
||||
!= 0
|
||||
{
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
let parts = match candidate.pointer("/content/parts") {
|
||||
None | Some(Value::Null) => &[][..],
|
||||
Some(value) => value
|
||||
.as_array()
|
||||
.map(Vec::as_slice)
|
||||
.ok_or(ChatError::InvalidResponse)?,
|
||||
};
|
||||
if self.candidate_finished && !parts.is_empty() {
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
let start = self.text.chars().count();
|
||||
for part in parts {
|
||||
let delta = if let Some(text) = part.get("text") {
|
||||
let text = text.as_str().ok_or(ChatError::InvalidResponse)?;
|
||||
if part["thought"] == true {
|
||||
json!({"reasoning_content":text})
|
||||
} else {
|
||||
self.text.push_str(text);
|
||||
json!({"content":text})
|
||||
}
|
||||
} else if let Some(call) = part.get("functionCall") {
|
||||
let name = call
|
||||
.get("name")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|v| !v.is_empty())
|
||||
.ok_or(ChatError::InvalidResponse)?;
|
||||
let id = call
|
||||
.get("id")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|v| !v.is_empty())
|
||||
.map(str::to_owned)
|
||||
.unwrap_or_else(|| format!("call_{}", uuid::Uuid::new_v4().simple()));
|
||||
let index = self.calls.len();
|
||||
if !self.calls.insert(id.clone()) {
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
let input = call.get("args").cloned().unwrap_or_else(|| json!({}));
|
||||
let mut call = tool_call(&id, name, &input, &self.custom)?;
|
||||
call["index"] = json!(index);
|
||||
json!({"tool_calls":[call]})
|
||||
} else if let Some(data) = part.get("inlineData") {
|
||||
let mime = data
|
||||
.get("mimeType")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|v| v.starts_with("image/"))
|
||||
.ok_or(ChatError::InvalidResponse)?;
|
||||
let data = data
|
||||
.get("data")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|v| !v.is_empty())
|
||||
.ok_or(ChatError::InvalidResponse)?;
|
||||
json!({"images":[{"type":"image_url","image_url":{"url":format!("data:{mime};base64,{data}")}}]})
|
||||
} else if part.get("thoughtSignature").is_some() {
|
||||
continue;
|
||||
} else {
|
||||
return Err(ChatError::InvalidResponse);
|
||||
};
|
||||
frames.push(chunk(&self.identity, delta, None, self.include_usage));
|
||||
}
|
||||
let metadata = &candidate["groundingMetadata"];
|
||||
self.grounded |= metadata["webSearchQueries"]
|
||||
.as_array()
|
||||
.is_some_and(|v| !v.is_empty())
|
||||
|| metadata["groundingChunks"]
|
||||
.as_array()
|
||||
.is_some_and(|v| v.iter().any(|v| v["web"]["uri"].is_string()));
|
||||
let new_annotations = annotations(candidate, &self.text, start)
|
||||
.into_iter()
|
||||
.filter(|v| !self.annotations.contains(v))
|
||||
.collect::<Vec<_>>();
|
||||
if !new_annotations.is_empty() {
|
||||
self.annotations.extend(new_annotations.iter().cloned());
|
||||
frames.push(chunk(
|
||||
&self.identity,
|
||||
json!({"annotations":new_annotations}),
|
||||
None,
|
||||
self.include_usage,
|
||||
));
|
||||
}
|
||||
if let Some(logprobs) = logprobs(candidate)? {
|
||||
let mut frame = chunk(&self.identity, json!({}), None, self.include_usage);
|
||||
frame["choices"][0]["logprobs"] = logprobs;
|
||||
frames.push(frame);
|
||||
}
|
||||
if let Some(reason) = candidate
|
||||
.get("finishReason")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|v| !matches!(*v, "" | "FINISH_REASON_UNSPECIFIED"))
|
||||
{
|
||||
if self.candidate_finished {
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
if !matches!(
|
||||
reason,
|
||||
"STOP"
|
||||
| "MAX_TOKENS"
|
||||
| "SAFETY"
|
||||
| "RECITATION"
|
||||
| "BLOCKLIST"
|
||||
| "PROHIBITED_CONTENT"
|
||||
| "SPII"
|
||||
| "IMAGE_SAFETY"
|
||||
| "MALFORMED_FUNCTION_CALL"
|
||||
| "UNEXPECTED_TOOL_CALL"
|
||||
| "OTHER"
|
||||
| "LANGUAGE"
|
||||
| "NO_IMAGE"
|
||||
| "IMAGE_OTHER"
|
||||
| "IMAGE_RECITATION"
|
||||
) {
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
self.candidate_finished = true;
|
||||
}
|
||||
}
|
||||
Ok(frames)
|
||||
}
|
||||
|
||||
pub fn finish(&mut self) -> Result<Vec<Value>, ChatError> {
|
||||
if self.completed || self.failed {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let reason = match self
|
||||
.observation
|
||||
.finish()
|
||||
.ok_or(ChatError::IncompleteStream)?
|
||||
{
|
||||
GenerationFinish::Blocked => "content_filter",
|
||||
GenerationFinish::Candidate {
|
||||
reason: "STOP",
|
||||
tool_call,
|
||||
} => {
|
||||
if self.required_search && !self.grounded {
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
if tool_call { "tool_calls" } else { "stop" }
|
||||
}
|
||||
GenerationFinish::Candidate {
|
||||
reason: "MAX_TOKENS",
|
||||
..
|
||||
} => "length",
|
||||
GenerationFinish::Candidate {
|
||||
reason:
|
||||
"SAFETY" | "RECITATION" | "BLOCKLIST" | "PROHIBITED_CONTENT" | "SPII"
|
||||
| "IMAGE_SAFETY",
|
||||
..
|
||||
} => "content_filter",
|
||||
GenerationFinish::Candidate { .. } => return Err(ChatError::InvalidResponse),
|
||||
};
|
||||
self.completed = true;
|
||||
let mut frames = vec![chunk(
|
||||
&self.identity,
|
||||
json!({}),
|
||||
Some(reason),
|
||||
self.include_usage,
|
||||
)];
|
||||
if self.include_usage
|
||||
&& let Some(usage) = self.usage.take()
|
||||
{
|
||||
frames.push(usage_chunk(&self.identity, usage));
|
||||
}
|
||||
Ok(frames)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
//! Chat 与 Messages 的直接请求和响应映射
|
||||
|
||||
mod request;
|
||||
mod response;
|
||||
mod stream;
|
||||
|
||||
pub use request::convert_request;
|
||||
pub use response::{project_response, project_response_with_request};
|
||||
pub use stream::ChatStreamEncoder;
|
||||
@@ -0,0 +1,470 @@
|
||||
//! Chat 字段、内容和工具历史直接构造 Messages 正文
|
||||
|
||||
use crate::anthropic::MessagesModelCapabilities;
|
||||
use crate::chat_completions::{
|
||||
ChatError,
|
||||
error::{invalid, unsupported},
|
||||
request::string,
|
||||
validate_request,
|
||||
};
|
||||
use serde_json::{Map, Value, json};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
/// 模型能力来自 Provider 已选模型,不按名称猜测
|
||||
pub fn convert_request(
|
||||
chat: &Map<String, Value>,
|
||||
capabilities: &MessagesModelCapabilities,
|
||||
) -> Result<Map<String, Value>, ChatError> {
|
||||
validate_request(chat)?;
|
||||
let max_tokens = ["max_completion_tokens", "max_tokens", "max_output_tokens"]
|
||||
.into_iter()
|
||||
.find_map(|key| chat.get(key).filter(|v| !v.is_null()))
|
||||
.map(|value| {
|
||||
value
|
||||
.as_u64()
|
||||
.filter(|v| *v > 0)
|
||||
.ok_or_else(|| invalid("max_completion_tokens"))
|
||||
})
|
||||
.transpose()?
|
||||
.unwrap_or(32_000)
|
||||
.min(capabilities.max_tokens.unwrap_or(u64::MAX));
|
||||
let mut result = Map::from_iter([
|
||||
("model".into(), chat["model"].clone()),
|
||||
("max_tokens".into(), json!(max_tokens)),
|
||||
]);
|
||||
for field in ["stream", "temperature", "top_p"] {
|
||||
if let Some(value) = chat.get(field).filter(|v| !v.is_null()) {
|
||||
result.insert(field.into(), value.clone());
|
||||
}
|
||||
}
|
||||
if let Some(tier) = chat.get("service_tier").and_then(Value::as_str) {
|
||||
match tier {
|
||||
"priority" => {
|
||||
result.insert("speed".into(), json!("fast"));
|
||||
}
|
||||
"default" => {
|
||||
result.insert("service_tier".into(), json!("standard_only"));
|
||||
}
|
||||
"auto" => {
|
||||
result.insert("service_tier".into(), json!("auto"));
|
||||
}
|
||||
_ => return Err(unsupported("service_tier")),
|
||||
}
|
||||
}
|
||||
let mut system = Vec::new();
|
||||
if let Some(instructions) = chat.get("instructions").filter(|v| !v.is_null()) {
|
||||
system.extend(content(instructions, "instructions", true)?);
|
||||
}
|
||||
let mut messages = Vec::new();
|
||||
let mut calls = BTreeMap::new();
|
||||
let mut used = BTreeSet::new();
|
||||
for (index, message) in chat["messages"]
|
||||
.as_array()
|
||||
.ok_or_else(|| invalid("messages"))?
|
||||
.iter()
|
||||
.enumerate()
|
||||
{
|
||||
let path = format!("messages[{index}]");
|
||||
let role = message["role"].as_str().ok_or_else(|| invalid(&path))?;
|
||||
if matches!(role, "system" | "developer") {
|
||||
system.extend(content(
|
||||
&message["content"],
|
||||
&format!("{path}.content"),
|
||||
true,
|
||||
)?);
|
||||
continue;
|
||||
}
|
||||
let blocks = if role == "tool" {
|
||||
let id = string(
|
||||
message.get("tool_call_id"),
|
||||
&format!("{path}.tool_call_id"),
|
||||
false,
|
||||
)?;
|
||||
if !calls.contains_key(id) || !used.insert(id.to_owned()) {
|
||||
return Err(invalid(&format!("{path}.tool_call_id")));
|
||||
}
|
||||
vec![
|
||||
json!({"type":"tool_result","tool_use_id":id,"content":content(&message["content"], &format!("{path}.content"), false)?}),
|
||||
]
|
||||
} else {
|
||||
let mut blocks = if message["content"].is_null() {
|
||||
Vec::new()
|
||||
} else {
|
||||
content(&message["content"], &format!("{path}.content"), false)?
|
||||
};
|
||||
if let Some(refusal) = message.get("refusal").and_then(Value::as_str) {
|
||||
blocks.push(json!({"type":"text","text":refusal}));
|
||||
}
|
||||
for (call_index, call) in message
|
||||
.get("tool_calls")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.enumerate()
|
||||
{
|
||||
let call_path = format!("{path}.tool_calls[{call_index}]");
|
||||
let id = string(call.get("id"), &format!("{call_path}.id"), false)?;
|
||||
let kind = call["type"].as_str().ok_or_else(|| invalid(&call_path))?;
|
||||
let name = string(
|
||||
call[kind].get("name"),
|
||||
&format!("{call_path}.{kind}.name"),
|
||||
false,
|
||||
)?;
|
||||
if calls.insert(id.to_owned(), name.to_owned()).is_some() {
|
||||
return Err(invalid(&format!("{call_path}.id")));
|
||||
}
|
||||
let input = if kind == "custom" {
|
||||
json!({"input":call[kind]["input"]})
|
||||
} else {
|
||||
serde_json::from_str::<Value>(string(
|
||||
call[kind].get("arguments"),
|
||||
&format!("{call_path}.function.arguments"),
|
||||
true,
|
||||
)?)
|
||||
.map_err(|_| invalid(&format!("{call_path}.function.arguments")))?
|
||||
};
|
||||
if !input.is_object() {
|
||||
return Err(invalid(&format!("{call_path}.function.arguments")));
|
||||
}
|
||||
blocks.push(json!({"type":"tool_use","id":id,"name":name,"input":input}));
|
||||
}
|
||||
blocks
|
||||
};
|
||||
append_message(
|
||||
&mut messages,
|
||||
if role == "assistant" {
|
||||
"assistant"
|
||||
} else {
|
||||
"user"
|
||||
},
|
||||
blocks,
|
||||
);
|
||||
}
|
||||
if messages.is_empty() {
|
||||
return Err(invalid("messages"));
|
||||
}
|
||||
if !system.is_empty() {
|
||||
result.insert("system".into(), system.into());
|
||||
}
|
||||
result.insert("messages".into(), messages.into());
|
||||
tools(chat, &mut result, capabilities)?;
|
||||
let format = chat
|
||||
.get("response_format")
|
||||
.or_else(|| chat.get("text").and_then(|v| v.get("format")));
|
||||
if let Some(format) = format.filter(|v| !v.is_null()) {
|
||||
match format["type"].as_str() {
|
||||
Some("json_schema") => {
|
||||
let schema = format
|
||||
.get("json_schema")
|
||||
.unwrap_or(format)
|
||||
.get("schema")
|
||||
.filter(|v| v.is_object())
|
||||
.ok_or_else(|| invalid("response_format.json_schema.schema"))?;
|
||||
result.insert(
|
||||
"output_config".into(),
|
||||
json!({"format":{"type":"json_schema","schema":schema}}),
|
||||
);
|
||||
}
|
||||
Some("json_object") => {
|
||||
result.insert(
|
||||
"output_config".into(),
|
||||
json!({"format":{"type":"json_schema","schema":{"type":"object"}}}),
|
||||
);
|
||||
}
|
||||
Some("text") => {}
|
||||
_ => return Err(unsupported("response_format.type")),
|
||||
}
|
||||
}
|
||||
reasoning(chat, &mut result, capabilities, max_tokens)?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn append_message(messages: &mut Vec<Value>, role: &str, blocks: Vec<Value>) {
|
||||
if let Some(last) = messages.last_mut().filter(|v| v["role"] == role) {
|
||||
last["content"]
|
||||
.as_array_mut()
|
||||
.expect("已构造的消息内容为数组")
|
||||
.extend(blocks);
|
||||
} else {
|
||||
messages.push(json!({"role":role,"content":blocks}));
|
||||
}
|
||||
}
|
||||
|
||||
fn content(value: &Value, path: &str, system: bool) -> Result<Vec<Value>, ChatError> {
|
||||
if let Some(text) = value.as_str() {
|
||||
return Ok(vec![json!({"type":"text","text":text})]);
|
||||
}
|
||||
let mut output: Vec<Value> = Vec::new();
|
||||
for (index, part) in value
|
||||
.as_array()
|
||||
.ok_or_else(|| invalid(path))?
|
||||
.iter()
|
||||
.enumerate()
|
||||
{
|
||||
let path = format!("{path}[{index}]");
|
||||
let kind = string(part.get("type"), &format!("{path}.type"), false)?;
|
||||
let block = match kind {
|
||||
"text" | "input_text" | "output_text" => {
|
||||
json!({"type":"text","text":string(part.get("text"), &format!("{path}.text"), true)?})
|
||||
}
|
||||
"refusal" if !system => {
|
||||
json!({"type":"text","text":string(part.get("refusal"), &format!("{path}.refusal"), true)?})
|
||||
}
|
||||
"image_url" | "input_image" if !system => {
|
||||
let url = part
|
||||
.get("image_url")
|
||||
.and_then(|v| v.as_str().or_else(|| v.get("url").and_then(Value::as_str)))
|
||||
.ok_or_else(|| invalid(&format!("{path}.image_url")))?;
|
||||
json!({"type":"image","source":source(url, None, &path)?})
|
||||
}
|
||||
"file" | "input_file" if !system => {
|
||||
let file = if kind == "file" { &part["file"] } else { part };
|
||||
let source = if let Some(id) = file.get("file_id").and_then(Value::as_str) {
|
||||
json!({"type":"file","file_id":id})
|
||||
} else if let Some(data) = file
|
||||
.get("file_data")
|
||||
.or_else(|| file.get("file_url"))
|
||||
.and_then(Value::as_str)
|
||||
{
|
||||
source(data, Some("application/pdf"), &path)?
|
||||
} else {
|
||||
return Err(invalid(&path));
|
||||
};
|
||||
let mut block = json!({"type":"document","source":source});
|
||||
if let Some(name) = file.get("filename") {
|
||||
block["title"] = name.clone();
|
||||
}
|
||||
block
|
||||
}
|
||||
"prompt_cache_breakpoint" => {
|
||||
let last = output.last_mut().ok_or_else(|| invalid(&path))?;
|
||||
last["cache_control"] = part
|
||||
.get("cache_control")
|
||||
.cloned()
|
||||
.unwrap_or_else(|| json!({"type":"ephemeral"}));
|
||||
continue;
|
||||
}
|
||||
_ => return Err(unsupported(&format!("{path}.type"))),
|
||||
};
|
||||
output.push(block);
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
fn source(url: &str, mime: Option<&str>, path: &str) -> Result<Value, ChatError> {
|
||||
if let Some(data) = url.strip_prefix("data:") {
|
||||
let (media_type, data) = data
|
||||
.split_once(";base64,")
|
||||
.filter(|(_, data)| !data.is_empty())
|
||||
.ok_or_else(|| invalid(path))?;
|
||||
if mime.is_none() && !media_type.starts_with("image/") {
|
||||
return Err(invalid(path));
|
||||
}
|
||||
return Ok(json!({"type":"base64","media_type":media_type,"data":data}));
|
||||
}
|
||||
if let Ok(url) = url::Url::parse(url)
|
||||
&& matches!(url.scheme(), "http" | "https")
|
||||
&& url.host_str().is_some()
|
||||
{
|
||||
return Ok(json!({"type":"url","url":url.as_str()}));
|
||||
}
|
||||
if let Some(mime) = mime
|
||||
&& !url.is_empty()
|
||||
{
|
||||
return Ok(json!({"type":"base64","media_type":mime,"data":url}));
|
||||
}
|
||||
Err(invalid(path))
|
||||
}
|
||||
|
||||
fn tools(
|
||||
chat: &Map<String, Value>,
|
||||
result: &mut Map<String, Value>,
|
||||
capabilities: &MessagesModelCapabilities,
|
||||
) -> Result<(), ChatError> {
|
||||
let mut tools = Vec::new();
|
||||
if let Some(definitions) = chat.get("tools").filter(|v| !v.is_null()) {
|
||||
for (index, tool) in definitions
|
||||
.as_array()
|
||||
.ok_or_else(|| invalid("tools"))?
|
||||
.iter()
|
||||
.enumerate()
|
||||
{
|
||||
let path = format!("tools[{index}]");
|
||||
let kind = string(tool.get("type"), &format!("{path}.type"), false)?;
|
||||
if !matches!(kind, "function" | "custom") {
|
||||
return Err(unsupported(&format!("{path}.type")));
|
||||
}
|
||||
let declaration = &tool[kind];
|
||||
let name = string(
|
||||
declaration.get("name"),
|
||||
&format!("{path}.{kind}.name"),
|
||||
false,
|
||||
)?;
|
||||
let schema = if kind == "custom" {
|
||||
json!({"type":"object","properties":{"input":{"type":"string"}},"required":["input"]})
|
||||
} else {
|
||||
declaration
|
||||
.get("parameters")
|
||||
.cloned()
|
||||
.unwrap_or_else(|| json!({"type":"object","properties":{}}))
|
||||
};
|
||||
if !schema.is_object() {
|
||||
return Err(invalid(&format!("{path}.function.parameters")));
|
||||
}
|
||||
let mut target = json!({"name":name,"input_schema":schema});
|
||||
for field in ["description", "strict", "cache_control"] {
|
||||
if let Some(value) = declaration.get(field) {
|
||||
target[field] = value.clone();
|
||||
}
|
||||
}
|
||||
tools.push(target);
|
||||
}
|
||||
}
|
||||
let mut choice = chat.get("tool_choice").cloned().unwrap_or(Value::Null);
|
||||
if let Some(options) = chat.get("web_search_options").filter(|v| !v.is_null()) {
|
||||
if !options.is_object() || !tools.is_empty() || (!choice.is_null() && choice != "auto") {
|
||||
return Err(invalid("web_search_options"));
|
||||
}
|
||||
if capabilities.hosted_web_search != Some(true) {
|
||||
return Err(unsupported("web_search_options"));
|
||||
}
|
||||
let mut tool = json!({"type":"web_search_20250305","name":"web_search"});
|
||||
if let Some(location) = options.get("user_location") {
|
||||
if location["type"] != "approximate" || !location["approximate"].is_object() {
|
||||
return Err(invalid("web_search_options.user_location"));
|
||||
}
|
||||
tool["user_location"] = location["approximate"].clone();
|
||||
tool["user_location"]["type"] = json!("approximate");
|
||||
}
|
||||
tools.push(tool);
|
||||
choice = json!({"type":"function","function":{"name":"web_search"}});
|
||||
}
|
||||
if choice["type"] == "allowed_tools" {
|
||||
let allowed = choice.get("allowed_tools").unwrap_or(&choice);
|
||||
let permitted = allowed["tools"]
|
||||
.as_array()
|
||||
.filter(|v| !v.is_empty())
|
||||
.ok_or_else(|| invalid("tool_choice.allowed_tools.tools"))?;
|
||||
tools.retain(|tool| {
|
||||
permitted.iter().any(|v| {
|
||||
v.get(v["type"].as_str().unwrap_or("function"))
|
||||
.and_then(|v| v.get("name"))
|
||||
.or_else(|| v.get("name"))
|
||||
== tool.get("name")
|
||||
})
|
||||
});
|
||||
choice = allowed
|
||||
.get("mode")
|
||||
.cloned()
|
||||
.ok_or_else(|| invalid("tool_choice.allowed_tools.mode"))?;
|
||||
}
|
||||
if tools.is_empty() {
|
||||
if !choice.is_null() && choice != "auto" && choice != "none" {
|
||||
return Err(invalid("tool_choice"));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let serial = chat.get("parallel_tool_calls") == Some(&Value::Bool(false));
|
||||
let kind = choice
|
||||
.as_str()
|
||||
.or_else(|| choice.get("type").and_then(Value::as_str))
|
||||
.unwrap_or("auto");
|
||||
let mut mapped = match kind {
|
||||
"auto" | "none" => json!({"type":kind}),
|
||||
"required" => json!({"type":"any"}),
|
||||
"function" | "custom" => {
|
||||
let name = string(
|
||||
choice.get(kind).and_then(|v| v.get("name")),
|
||||
"tool_choice.name",
|
||||
false,
|
||||
)?;
|
||||
if !tools.iter().any(|v| v["name"] == name) {
|
||||
return Err(invalid("tool_choice"));
|
||||
}
|
||||
json!({"type":"tool","name":name})
|
||||
}
|
||||
_ => return Err(unsupported("tool_choice")),
|
||||
};
|
||||
if serial && kind != "none" {
|
||||
mapped["disable_parallel_tool_use"] = json!(true);
|
||||
}
|
||||
if !choice.is_null() || serial {
|
||||
result.insert("tool_choice".into(), mapped);
|
||||
}
|
||||
result.insert("tools".into(), tools.into());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn reasoning(
|
||||
chat: &Map<String, Value>,
|
||||
result: &mut Map<String, Value>,
|
||||
capabilities: &MessagesModelCapabilities,
|
||||
max_tokens: u64,
|
||||
) -> Result<(), ChatError> {
|
||||
let Some(effort) = chat
|
||||
.get("reasoning_effort")
|
||||
.or_else(|| chat.get("reasoning").and_then(|v| v.get("effort")))
|
||||
.filter(|v| !v.is_null())
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let effort = effort.as_str().ok_or_else(|| invalid("reasoning_effort"))?;
|
||||
if effort == "none" {
|
||||
if capabilities.disabled_thinking == Some(false) {
|
||||
return Err(unsupported("reasoning_effort"));
|
||||
}
|
||||
result.insert("thinking".into(), json!({"type":"disabled"}));
|
||||
return Ok(());
|
||||
}
|
||||
let budget = match effort {
|
||||
"minimal" | "low" => 1024,
|
||||
"medium" | "auto" => 8192,
|
||||
"high" => 24576,
|
||||
"xhigh" => 32768,
|
||||
"max" => 128000,
|
||||
_ => return Err(invalid("reasoning_effort")),
|
||||
};
|
||||
if capabilities.thinking == Some(false) {
|
||||
return Err(unsupported("reasoning_effort"));
|
||||
}
|
||||
if result
|
||||
.get("tool_choice")
|
||||
.and_then(|v| v.get("type"))
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|v| matches!(v, "any" | "tool"))
|
||||
{
|
||||
return Err(ChatError::UnsupportedCombination {
|
||||
field: "reasoning_effort",
|
||||
other: "tool_choice",
|
||||
});
|
||||
}
|
||||
if capabilities.adaptive_thinking == Some(true) {
|
||||
result.insert("thinking".into(), json!({"type":"adaptive"}));
|
||||
let effort = if effort == "minimal" {
|
||||
"low"
|
||||
} else if effort == "auto" {
|
||||
"high"
|
||||
} else {
|
||||
effort
|
||||
};
|
||||
if capabilities
|
||||
.efforts
|
||||
.as_ref()
|
||||
.is_some_and(|supported| !supported.iter().any(|v| v == effort))
|
||||
{
|
||||
return Err(unsupported("reasoning_effort"));
|
||||
}
|
||||
result.entry("output_config").or_insert_with(|| json!({}))["effort"] = json!(effort);
|
||||
} else {
|
||||
if capabilities.manual_thinking == Some(false) || max_tokens <= 1024 {
|
||||
return Err(unsupported("reasoning_effort"));
|
||||
}
|
||||
result.insert(
|
||||
"thinking".into(),
|
||||
json!({"type":"enabled","budget_tokens":budget.min(max_tokens-1)}),
|
||||
);
|
||||
}
|
||||
result.remove("temperature");
|
||||
result.remove("top_p");
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
//! Messages 完整响应直接投影为 Chat 响应
|
||||
|
||||
use crate::anthropic::MessageUsage;
|
||||
use crate::chat_completions::{
|
||||
ChatError, ChatIdentity,
|
||||
response::{completion, custom_tools, tool_call},
|
||||
};
|
||||
use serde_json::{Map, Value, json};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
/// 无 custom 工具上下文时的完整响应投影
|
||||
pub fn project_response(message: &Value, identity: &ChatIdentity) -> Result<Value, ChatError> {
|
||||
project(message, identity, &BTreeSet::new())
|
||||
}
|
||||
|
||||
/// 恢复 Chat 请求声明的 custom 工具语义
|
||||
pub fn project_response_with_request(
|
||||
message: &Value,
|
||||
identity: &ChatIdentity,
|
||||
request: &Map<String, Value>,
|
||||
) -> Result<Value, ChatError> {
|
||||
project(message, identity, &custom_tools(request))
|
||||
}
|
||||
|
||||
fn project(
|
||||
message: &Value,
|
||||
identity: &ChatIdentity,
|
||||
custom: &BTreeSet<String>,
|
||||
) -> Result<Value, ChatError> {
|
||||
if let Some(error) = message.get("error") {
|
||||
return Ok(json!({"error":error}));
|
||||
}
|
||||
if message["type"] != "message" || message["role"] != "assistant" {
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
let reason = finish_reason(
|
||||
message
|
||||
.get("stop_reason")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or(ChatError::InvalidResponse)?,
|
||||
)?;
|
||||
let mut text = String::new();
|
||||
let mut reasoning = String::new();
|
||||
let mut calls = Vec::new();
|
||||
let mut annotations = Vec::new();
|
||||
let mut ids = BTreeSet::new();
|
||||
for block in message
|
||||
.get("content")
|
||||
.and_then(Value::as_array)
|
||||
.ok_or(ChatError::InvalidResponse)?
|
||||
{
|
||||
match block
|
||||
.get("type")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or(ChatError::InvalidResponse)?
|
||||
{
|
||||
"text" => {
|
||||
let fragment = block
|
||||
.get("text")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or(ChatError::InvalidResponse)?;
|
||||
let start = text.chars().count();
|
||||
text.push_str(fragment);
|
||||
for citation in block
|
||||
.get("citations")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
if let Some(citation) = annotation(citation, start, text.chars().count()) {
|
||||
annotations.push(citation);
|
||||
}
|
||||
}
|
||||
}
|
||||
"thinking" => reasoning.push_str(
|
||||
block
|
||||
.get("thinking")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or(ChatError::InvalidResponse)?,
|
||||
),
|
||||
"tool_use" => {
|
||||
let id = block
|
||||
.get("id")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|v| !v.is_empty())
|
||||
.ok_or(ChatError::InvalidResponse)?;
|
||||
if !ids.insert(id) {
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
calls.push(tool_call(
|
||||
id,
|
||||
block
|
||||
.get("name")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|v| !v.is_empty())
|
||||
.ok_or(ChatError::InvalidResponse)?,
|
||||
&block["input"],
|
||||
custom,
|
||||
)?);
|
||||
}
|
||||
"redacted_thinking" | "server_tool_use" | "web_search_tool_result" => {}
|
||||
_ => return Err(ChatError::InvalidResponse),
|
||||
}
|
||||
}
|
||||
let mut output = json!({"role":"assistant","content":if text.is_empty(){Value::Null}else{json!(text)},"refusal":null});
|
||||
if !reasoning.is_empty() {
|
||||
output["reasoning_content"] = json!(reasoning);
|
||||
}
|
||||
if !calls.is_empty() {
|
||||
output["tool_calls"] = calls.into();
|
||||
}
|
||||
if !annotations.is_empty() {
|
||||
output["annotations"] = annotations.into();
|
||||
}
|
||||
Ok(completion(
|
||||
identity,
|
||||
output,
|
||||
reason,
|
||||
usage(MessageUsage::from_value(&message["usage"])),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) fn annotation(citation: &Value, start: usize, end: usize) -> Option<Value> {
|
||||
let url = citation.get("url")?.as_str()?;
|
||||
Some(
|
||||
json!({"type":"url_citation","url_citation":{"url":url,"title":citation.get("title").and_then(Value::as_str).unwrap_or_default(),"start_index":start,"end_index":end}}),
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn finish_reason(reason: &str) -> Result<&'static str, ChatError> {
|
||||
match reason {
|
||||
"end_turn" | "stop_sequence" | "pause_turn" => Ok("stop"),
|
||||
"tool_use" => Ok("tool_calls"),
|
||||
"max_tokens" | "model_context_window_exceeded" => Ok("length"),
|
||||
"refusal" => Ok("content_filter"),
|
||||
_ => Err(ChatError::InvalidResponse),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn usage(usage: MessageUsage) -> Option<Value> {
|
||||
let input = usage.total_input_tokens()?;
|
||||
let output = usage.output_tokens?;
|
||||
let mut value = json!({"prompt_tokens":input,"completion_tokens":output,"total_tokens":input.saturating_add(output)});
|
||||
if let Some(cached) = usage.cache_read_input_tokens {
|
||||
value["prompt_tokens_details"]["cached_tokens"] = json!(cached);
|
||||
}
|
||||
if let Some(written) = usage.cache_creation_input_tokens {
|
||||
value["prompt_tokens_details"]["cache_write_tokens"] = json!(written);
|
||||
}
|
||||
Some(value)
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
//! Messages 事件直接产生 Chat chunk,独立维护原生块终态
|
||||
|
||||
use super::response::{annotation, finish_reason, usage};
|
||||
use crate::anthropic::MessageUsage;
|
||||
use crate::chat_completions::{
|
||||
ChatError, ChatIdentity,
|
||||
response::{chunk, custom_tools, usage_chunk},
|
||||
};
|
||||
use serde_json::{Map, Value, json};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
struct Block {
|
||||
kind: String,
|
||||
stopped: bool,
|
||||
tool_index: Option<usize>,
|
||||
custom: bool,
|
||||
arguments: String,
|
||||
initial_input: Value,
|
||||
text_start: usize,
|
||||
}
|
||||
|
||||
/// 仅持有本次 Messages 流的内容块与累计用量状态
|
||||
pub struct ChatStreamEncoder {
|
||||
identity: ChatIdentity,
|
||||
include_usage: bool,
|
||||
custom: BTreeSet<String>,
|
||||
blocks: BTreeMap<u64, Block>,
|
||||
calls: BTreeSet<String>,
|
||||
started: bool,
|
||||
completed: bool,
|
||||
failed: bool,
|
||||
reason: Option<&'static str>,
|
||||
usage: MessageUsage,
|
||||
text_len: usize,
|
||||
}
|
||||
|
||||
impl ChatStreamEncoder {
|
||||
pub fn new(identity: ChatIdentity, include_usage: bool) -> Self {
|
||||
Self {
|
||||
identity,
|
||||
include_usage,
|
||||
custom: BTreeSet::new(),
|
||||
blocks: BTreeMap::new(),
|
||||
calls: BTreeSet::new(),
|
||||
started: false,
|
||||
completed: false,
|
||||
failed: false,
|
||||
reason: None,
|
||||
usage: MessageUsage::default(),
|
||||
text_len: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_request(
|
||||
identity: ChatIdentity,
|
||||
include_usage: bool,
|
||||
request: &Map<String, Value>,
|
||||
) -> Self {
|
||||
Self {
|
||||
custom: custom_tools(request),
|
||||
..Self::new(identity, include_usage)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_completed(&self) -> bool {
|
||||
self.completed
|
||||
}
|
||||
pub fn has_wire_failure(&self) -> bool {
|
||||
self.failed
|
||||
}
|
||||
|
||||
pub fn push_event(
|
||||
&mut self,
|
||||
event: Option<&str>,
|
||||
value: &Value,
|
||||
) -> Result<Vec<Value>, ChatError> {
|
||||
if self.failed {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
if self.completed {
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
let kind = event
|
||||
.or_else(|| value.get("type").and_then(Value::as_str))
|
||||
.ok_or(ChatError::InvalidResponse)?;
|
||||
if let Some(data_kind) = value.get("type").and_then(Value::as_str)
|
||||
&& data_kind != kind
|
||||
{
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
if kind == "error" {
|
||||
let error = value
|
||||
.get("error")
|
||||
.filter(|v| v.is_object())
|
||||
.ok_or(ChatError::InvalidResponse)?;
|
||||
self.failed = true;
|
||||
return Ok(vec![json!({"error":error})]);
|
||||
}
|
||||
if kind == "ping" {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
if kind == "message_start" {
|
||||
if self.started {
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
let message = &value["message"];
|
||||
if message["type"] != "message"
|
||||
|| message["role"] != "assistant"
|
||||
|| !message["content"].as_array().is_some_and(Vec::is_empty)
|
||||
{
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
self.started = true;
|
||||
self.usage.merge(&message["usage"]);
|
||||
return Ok(vec![chunk(
|
||||
&self.identity,
|
||||
json!({"role":"assistant","content":"","refusal":null}),
|
||||
None,
|
||||
self.include_usage,
|
||||
)]);
|
||||
}
|
||||
if !self.started {
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
let mut deltas = Vec::new();
|
||||
match kind {
|
||||
"content_block_start" => {
|
||||
if self.reason.is_some() {
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
let index = value
|
||||
.get("index")
|
||||
.and_then(Value::as_u64)
|
||||
.ok_or(ChatError::InvalidResponse)?;
|
||||
if self.blocks.contains_key(&index) {
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
let block = &value["content_block"];
|
||||
let kind = block
|
||||
.get("type")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or(ChatError::InvalidResponse)?;
|
||||
let mut state = Block {
|
||||
kind: kind.into(),
|
||||
stopped: false,
|
||||
tool_index: None,
|
||||
custom: false,
|
||||
arguments: String::new(),
|
||||
initial_input: Value::Null,
|
||||
text_start: self.text_len,
|
||||
};
|
||||
match kind {
|
||||
"text" => {
|
||||
let text = block
|
||||
.get("text")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or(ChatError::InvalidResponse)?;
|
||||
self.text_len += text.chars().count();
|
||||
if !text.is_empty() {
|
||||
deltas.push(json!({"content":text}));
|
||||
}
|
||||
for citation in block
|
||||
.get("citations")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
if let Some(citation) =
|
||||
annotation(citation, state.text_start, self.text_len)
|
||||
{
|
||||
deltas.push(json!({"annotations":[citation]}));
|
||||
}
|
||||
}
|
||||
}
|
||||
"thinking" => {
|
||||
let text = block
|
||||
.get("thinking")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or(ChatError::InvalidResponse)?;
|
||||
if !text.is_empty() {
|
||||
deltas.push(json!({"reasoning_content":text}));
|
||||
}
|
||||
}
|
||||
"tool_use" => {
|
||||
let id = block
|
||||
.get("id")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|v| !v.is_empty())
|
||||
.ok_or(ChatError::InvalidResponse)?;
|
||||
let name = block
|
||||
.get("name")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|v| !v.is_empty())
|
||||
.ok_or(ChatError::InvalidResponse)?;
|
||||
let tool_index = self.calls.len();
|
||||
if !self.calls.insert(id.into()) || !block["input"].is_object() {
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
state.tool_index = Some(tool_index);
|
||||
state.custom = self.custom.contains(name);
|
||||
state.initial_input = block["input"].clone();
|
||||
let call = if state.custom {
|
||||
json!({"index":tool_index,"id":id,"type":"custom","custom":{"name":name,"input":""}})
|
||||
} else {
|
||||
json!({"index":tool_index,"id":id,"type":"function","function":{"name":name,"arguments":""}})
|
||||
};
|
||||
deltas.push(json!({"tool_calls":[call]}));
|
||||
}
|
||||
"redacted_thinking" | "server_tool_use" | "web_search_tool_result" => {}
|
||||
_ => return Err(ChatError::InvalidResponse),
|
||||
}
|
||||
self.blocks.insert(index, state);
|
||||
}
|
||||
"content_block_delta" => {
|
||||
let index = value
|
||||
.get("index")
|
||||
.and_then(Value::as_u64)
|
||||
.ok_or(ChatError::InvalidResponse)?;
|
||||
let block = self
|
||||
.blocks
|
||||
.get_mut(&index)
|
||||
.filter(|v| !v.stopped)
|
||||
.ok_or(ChatError::InvalidResponse)?;
|
||||
let delta = &value["delta"];
|
||||
match delta.get("type").and_then(Value::as_str).ok_or(ChatError::InvalidResponse)? {
|
||||
"text_delta" if block.kind == "text" => { let text = delta.get("text").and_then(Value::as_str).ok_or(ChatError::InvalidResponse)?; self.text_len += text.chars().count(); deltas.push(json!({"content":text})); }
|
||||
"thinking_delta" if block.kind == "thinking" => deltas.push(json!({"reasoning_content":delta.get("thinking").and_then(Value::as_str).ok_or(ChatError::InvalidResponse)?})),
|
||||
"signature_delta" if block.kind == "thinking" => {},
|
||||
"input_json_delta" if matches!(block.kind.as_str(), "tool_use" | "server_tool_use") => {
|
||||
let arguments = delta.get("partial_json").and_then(Value::as_str).ok_or(ChatError::InvalidResponse)?;
|
||||
block.arguments.push_str(arguments);
|
||||
if !block.custom && let Some(index) = block.tool_index { deltas.push(json!({"tool_calls":[{"index":index,"function":{"arguments":arguments}}]})); }
|
||||
}
|
||||
"citations_delta" if block.kind == "text" => { if let Some(citation) = annotation(&delta["citation"], block.text_start, self.text_len) { deltas.push(json!({"annotations":[citation]})); } }
|
||||
_ => return Err(ChatError::InvalidResponse),
|
||||
}
|
||||
}
|
||||
"content_block_stop" => {
|
||||
let index = value
|
||||
.get("index")
|
||||
.and_then(Value::as_u64)
|
||||
.ok_or(ChatError::InvalidResponse)?;
|
||||
let block = self
|
||||
.blocks
|
||||
.get_mut(&index)
|
||||
.filter(|v| !v.stopped)
|
||||
.ok_or(ChatError::InvalidResponse)?;
|
||||
if let Some(index) = block.tool_index {
|
||||
let input = if block.arguments.is_empty() {
|
||||
block.initial_input.clone()
|
||||
} else {
|
||||
serde_json::from_str::<Value>(&block.arguments)
|
||||
.map_err(|_| ChatError::InvalidResponse)?
|
||||
};
|
||||
if !input.is_object() {
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
if block.custom {
|
||||
deltas.push(json!({"tool_calls":[{"index":index,"custom":{"input":input.get("input").and_then(Value::as_str).ok_or(ChatError::InvalidResponse)?}}]}));
|
||||
} else if block.arguments.is_empty() {
|
||||
deltas.push(json!({"tool_calls":[{"index":index,"function":{"arguments":input.to_string()}}]}));
|
||||
}
|
||||
}
|
||||
block.stopped = true;
|
||||
}
|
||||
"message_delta" => {
|
||||
if self.blocks.values().any(|v| !v.stopped) {
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
if let Some(reason) = value.pointer("/delta/stop_reason").filter(|v| !v.is_null()) {
|
||||
if self.reason.is_some() {
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
self.reason = Some(finish_reason(
|
||||
reason.as_str().ok_or(ChatError::InvalidResponse)?,
|
||||
)?);
|
||||
}
|
||||
self.usage.merge(&value["usage"]);
|
||||
}
|
||||
"message_stop" => {
|
||||
if self.blocks.values().any(|v| !v.stopped) {
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
let reason = self.reason.ok_or(ChatError::InvalidResponse)?;
|
||||
self.completed = true;
|
||||
let mut frames = vec![chunk(
|
||||
&self.identity,
|
||||
json!({}),
|
||||
Some(reason),
|
||||
self.include_usage,
|
||||
)];
|
||||
if self.include_usage
|
||||
&& let Some(usage) = usage(self.usage)
|
||||
{
|
||||
frames.push(usage_chunk(&self.identity, usage));
|
||||
}
|
||||
return Ok(frames);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(deltas
|
||||
.into_iter()
|
||||
.map(|delta| chunk(&self.identity, delta, None, self.include_usage))
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn finish(&mut self) -> Result<Vec<Value>, ChatError> {
|
||||
if self.completed || self.failed {
|
||||
Ok(Vec::new())
|
||||
} else {
|
||||
Err(ChatError::IncompleteStream)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
//! Chat 原生请求事实及按目标协议隔离的直接转换
|
||||
|
||||
mod error;
|
||||
mod request;
|
||||
mod response;
|
||||
|
||||
pub mod genai;
|
||||
pub mod messages;
|
||||
pub mod responses;
|
||||
|
||||
pub use error::ChatError;
|
||||
pub use request::{ChatRequest, parse_request, validate_request};
|
||||
pub(crate) use request::{request_effort, request_facts};
|
||||
pub use response::{ChatAccumulator, ChatIdentity, completion_chunks};
|
||||
|
||||
/// Chat Completions 线协议标识
|
||||
pub const CHAT_PROTOCOL: &str = "chat_completions";
|
||||
@@ -0,0 +1,252 @@
|
||||
//! Chat 入站解析和能力提取,选路前保持 Chat 正文
|
||||
|
||||
use super::{
|
||||
ChatError,
|
||||
error::{invalid, unsupported},
|
||||
};
|
||||
use crate::capabilities::RequestFacts;
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
/// 已解码的 Chat 正文与交付选项
|
||||
pub struct ChatRequest {
|
||||
pub body: Map<String, Value>,
|
||||
pub include_usage: bool,
|
||||
}
|
||||
|
||||
/// 仅解析当前协议,不构造目标平台报文
|
||||
pub fn parse_request(bytes: &[u8]) -> Result<ChatRequest, ChatError> {
|
||||
let value: Value = serde_json::from_slice(bytes).map_err(|_| ChatError::MalformedJson)?;
|
||||
let Value::Object(body) = value else {
|
||||
return Err(ChatError::ExpectedObject);
|
||||
};
|
||||
validate_request(&body)?;
|
||||
let include_usage = body
|
||||
.get("stream_options")
|
||||
.and_then(|v| v.get("include_usage"))
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false);
|
||||
Ok(ChatRequest {
|
||||
body,
|
||||
include_usage,
|
||||
})
|
||||
}
|
||||
|
||||
/// 校验各目标共同遵守的 Chat 请求合同
|
||||
pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
|
||||
string(body.get("model"), "model", false)?;
|
||||
let messages = body
|
||||
.get("messages")
|
||||
.ok_or_else(|| ChatError::MissingField {
|
||||
field: "messages".into(),
|
||||
})?
|
||||
.as_array()
|
||||
.ok_or_else(|| ChatError::InvalidType {
|
||||
field: "messages".into(),
|
||||
expected: "an array",
|
||||
})?;
|
||||
if messages.is_empty() {
|
||||
return Err(ChatError::EmptyField {
|
||||
field: "messages".into(),
|
||||
});
|
||||
}
|
||||
for (index, message) in messages.iter().enumerate() {
|
||||
let path = format!("messages[{index}]");
|
||||
let message = message.as_object().ok_or_else(|| invalid(&path))?;
|
||||
let role = string(message.get("role"), &format!("{path}.role"), false)?;
|
||||
if !matches!(role, "system" | "developer" | "user" | "assistant" | "tool") {
|
||||
return Err(unsupported(&format!("{path}.role")));
|
||||
}
|
||||
for (field, allowed) in [
|
||||
("tool_calls", "assistant"),
|
||||
("refusal", "assistant"),
|
||||
("tool_call_id", "tool"),
|
||||
] {
|
||||
if role != allowed && message.get(field).is_some_and(|v| !v.is_null()) {
|
||||
return Err(invalid(&format!("{path}.{field}")));
|
||||
}
|
||||
}
|
||||
for field in ["function_call", "audio"] {
|
||||
if message.get(field).is_some_and(|v| !v.is_null()) {
|
||||
return Err(unsupported(&format!("{path}.{field}")));
|
||||
}
|
||||
}
|
||||
if role == "tool" {
|
||||
string(
|
||||
message.get("tool_call_id"),
|
||||
&format!("{path}.tool_call_id"),
|
||||
false,
|
||||
)?;
|
||||
}
|
||||
if let Some(content) = message.get("content").filter(|v| !v.is_null()) {
|
||||
if !content.is_string() && !content.is_array() {
|
||||
return Err(invalid(&format!("{path}.content")));
|
||||
}
|
||||
if let Some(parts) = content.as_array() {
|
||||
for (part_index, part) in parts.iter().enumerate() {
|
||||
let part_path = format!("{path}.content[{part_index}]");
|
||||
let kind = string(part.get("type"), &format!("{part_path}.type"), false)?;
|
||||
match kind {
|
||||
"text" | "input_text" | "output_text" => {
|
||||
string(part.get("text"), &format!("{part_path}.text"), true)?;
|
||||
}
|
||||
"image_url" | "file" | "input_audio" | "input_image" | "input_file"
|
||||
if matches!(role, "user" | "tool") => {}
|
||||
"refusal" if role == "assistant" => {
|
||||
string(part.get("refusal"), &format!("{part_path}.refusal"), true)?;
|
||||
}
|
||||
_ => return Err(unsupported(&format!("{part_path}.type"))),
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if role != "assistant"
|
||||
|| (!message
|
||||
.get("tool_calls")
|
||||
.is_some_and(|v| v.as_array().is_some_and(|v| !v.is_empty()))
|
||||
&& !message.get("refusal").is_some_and(Value::is_string))
|
||||
{
|
||||
return Err(invalid(&format!("{path}.content")));
|
||||
}
|
||||
if let Some(calls) = message.get("tool_calls").filter(|v| !v.is_null()) {
|
||||
for (call_index, call) in calls
|
||||
.as_array()
|
||||
.ok_or_else(|| invalid(&format!("{path}.tool_calls")))?
|
||||
.iter()
|
||||
.enumerate()
|
||||
{
|
||||
let call_path = format!("{path}.tool_calls[{call_index}]");
|
||||
string(call.get("id"), &format!("{call_path}.id"), false)?;
|
||||
let kind = string(call.get("type"), &format!("{call_path}.type"), false)?;
|
||||
if !matches!(kind, "function" | "custom") {
|
||||
return Err(unsupported(&format!("{call_path}.type")));
|
||||
}
|
||||
string(
|
||||
call.get(kind).and_then(|v| v.get("name")),
|
||||
&format!("{call_path}.{kind}.name"),
|
||||
false,
|
||||
)?;
|
||||
string(
|
||||
call.get(kind).and_then(|v| {
|
||||
v.get(if kind == "function" {
|
||||
"arguments"
|
||||
} else {
|
||||
"input"
|
||||
})
|
||||
}),
|
||||
&format!("{call_path}.{kind}"),
|
||||
true,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (field, value) in body.iter().filter(|(_, v)| !v.is_null()) {
|
||||
let valid = match field.as_str() {
|
||||
"n" => value.as_u64() == Some(1),
|
||||
"store" | "background" => value == false,
|
||||
"functions" => value.as_array().is_some_and(Vec::is_empty),
|
||||
"modalities" => value == &json!(["text"]),
|
||||
"audio" | "function_call" | "input" | "previous_response_id" | "conversation" => false,
|
||||
_ => true,
|
||||
};
|
||||
if !valid {
|
||||
return Err(unsupported(field));
|
||||
}
|
||||
}
|
||||
for field in ["stream", "parallel_tool_calls", "logprobs"] {
|
||||
if body
|
||||
.get(field)
|
||||
.is_some_and(|v| !v.is_null() && !v.is_boolean())
|
||||
{
|
||||
return Err(invalid(field));
|
||||
}
|
||||
}
|
||||
if let Some(options) = body.get("stream_options").filter(|v| !v.is_null()) {
|
||||
if body.get("stream") != Some(&Value::Bool(true)) || !options.is_object() {
|
||||
return Err(invalid("stream_options"));
|
||||
}
|
||||
for field in ["include_usage", "include_obfuscation"] {
|
||||
if options
|
||||
.get(field)
|
||||
.is_some_and(|v| !v.is_null() && !v.is_boolean())
|
||||
{
|
||||
return Err(invalid(&format!("stream_options.{field}")));
|
||||
}
|
||||
}
|
||||
if options.get("include_obfuscation") == Some(&Value::Bool(true)) {
|
||||
return Err(unsupported("stream_options.include_obfuscation"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn string<'a>(
|
||||
value: Option<&'a Value>,
|
||||
path: &str,
|
||||
empty: bool,
|
||||
) -> Result<&'a str, ChatError> {
|
||||
let value = value
|
||||
.filter(|v| !v.is_null())
|
||||
.ok_or_else(|| ChatError::MissingField {
|
||||
field: path.to_owned(),
|
||||
})?;
|
||||
let value = value.as_str().ok_or_else(|| ChatError::InvalidType {
|
||||
field: path.to_owned(),
|
||||
expected: "a string",
|
||||
})?;
|
||||
if !empty && value.trim().is_empty() {
|
||||
return Err(ChatError::EmptyField {
|
||||
field: path.to_owned(),
|
||||
});
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
pub(crate) fn request_facts(body: &Map<String, Value>) -> RequestFacts {
|
||||
RequestFacts {
|
||||
max_output_tokens: ["max_completion_tokens", "max_tokens", "max_output_tokens"]
|
||||
.into_iter()
|
||||
.find_map(|key| body.get(key).and_then(Value::as_u64)),
|
||||
tools: body
|
||||
.get("tools")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|v| !v.is_empty())
|
||||
|| body.contains_key("web_search_options"),
|
||||
vision: has_type(body.get("messages"), &["image_url", "input_image"]),
|
||||
image_generation: has_type(body.get("tools"), &["image_generation"]),
|
||||
reasoning: body.get("reasoning_effort").is_some_and(|v| !v.is_null())
|
||||
|| body.get("reasoning").is_some_and(Value::is_object),
|
||||
json_schema: body
|
||||
.get("response_format")
|
||||
.and_then(|v| v.get("type"))
|
||||
.and_then(Value::as_str)
|
||||
== Some("json_schema")
|
||||
|| body
|
||||
.get("text")
|
||||
.and_then(|v| v.pointer("/format/type"))
|
||||
.and_then(Value::as_str)
|
||||
== Some("json_schema"),
|
||||
..RequestFacts::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn request_effort(body: &Map<String, Value>) -> Option<&str> {
|
||||
body.get("reasoning_effort")
|
||||
.and_then(Value::as_str)
|
||||
.or_else(|| {
|
||||
body.get("reasoning")
|
||||
.and_then(|value| value.get("effort"))
|
||||
.and_then(Value::as_str)
|
||||
})
|
||||
}
|
||||
|
||||
fn has_type(value: Option<&Value>, kinds: &[&str]) -> bool {
|
||||
match value {
|
||||
Some(Value::Object(v)) => {
|
||||
v.get("type")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|v| kinds.contains(&v))
|
||||
|| v.values().any(|v| has_type(Some(v), kinds))
|
||||
}
|
||||
Some(Value::Array(v)) => v.iter().any(|v| has_type(Some(v), kinds)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,408 @@
|
||||
//! Chat 响应封套及直接 Chat 流的完整结果聚合
|
||||
|
||||
use super::ChatError;
|
||||
use serde::Serialize;
|
||||
use serde_json::{Map, Value, json};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
/// 响应身份由请求执行边界提供,转换器不创建执行状态
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct ChatIdentity {
|
||||
pub id: String,
|
||||
pub created: u64,
|
||||
pub model: String,
|
||||
}
|
||||
|
||||
pub(super) fn completion(
|
||||
identity: &ChatIdentity,
|
||||
message: Value,
|
||||
reason: &str,
|
||||
usage: Option<Value>,
|
||||
) -> Value {
|
||||
let mut result = json!({"id":identity.id,"object":"chat.completion","created":identity.created,"model":identity.model,"choices":[{"index":0,"message":message,"finish_reason":reason,"logprobs":null}]});
|
||||
if let Some(usage) = usage {
|
||||
result["usage"] = usage;
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub(super) fn chunk(
|
||||
identity: &ChatIdentity,
|
||||
delta: Value,
|
||||
reason: Option<&str>,
|
||||
include_usage: bool,
|
||||
) -> Value {
|
||||
let mut result = json!({"id":identity.id,"object":"chat.completion.chunk","created":identity.created,"model":identity.model,"choices":[{"index":0,"delta":delta,"finish_reason":reason,"logprobs":null}]});
|
||||
if include_usage {
|
||||
result["usage"] = Value::Null;
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub(super) fn usage_chunk(identity: &ChatIdentity, usage: Value) -> Value {
|
||||
json!({"id":identity.id,"object":"chat.completion.chunk","created":identity.created,"model":identity.model,"choices":[],"usage":usage})
|
||||
}
|
||||
|
||||
/// 完整 Chat 结果直接交付为 Chat chunk,不借用其他协议的事件生命周期
|
||||
pub fn completion_chunks(completion: &Value, include_usage: bool) -> Result<Vec<Value>, ChatError> {
|
||||
let mut envelope = completion
|
||||
.as_object()
|
||||
.cloned()
|
||||
.ok_or(ChatError::InvalidResponse)?;
|
||||
if envelope.get("object").and_then(Value::as_str) != Some("chat.completion")
|
||||
|| !envelope.get("id").is_some_and(Value::is_string)
|
||||
|| !envelope.get("model").is_some_and(Value::is_string)
|
||||
|| !envelope.get("created").is_some_and(Value::is_u64)
|
||||
{
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
let choices = envelope
|
||||
.remove("choices")
|
||||
.ok_or(ChatError::InvalidResponse)?;
|
||||
let choices = choices
|
||||
.as_array()
|
||||
.filter(|choices| !choices.is_empty())
|
||||
.ok_or(ChatError::InvalidResponse)?;
|
||||
let usage = envelope.remove("usage").filter(|value| !value.is_null());
|
||||
envelope.insert("object".into(), json!("chat.completion.chunk"));
|
||||
if include_usage {
|
||||
envelope.insert("usage".into(), Value::Null);
|
||||
}
|
||||
let mut roles = Vec::with_capacity(choices.len());
|
||||
let mut contents = Vec::with_capacity(choices.len());
|
||||
let mut terminals = Vec::with_capacity(choices.len());
|
||||
let mut indices = BTreeSet::new();
|
||||
for choice in choices {
|
||||
let index = choice
|
||||
.get("index")
|
||||
.and_then(Value::as_u64)
|
||||
.ok_or(ChatError::InvalidResponse)?;
|
||||
if !indices.insert(index) {
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
let mut message = choice
|
||||
.get("message")
|
||||
.and_then(Value::as_object)
|
||||
.cloned()
|
||||
.ok_or(ChatError::InvalidResponse)?;
|
||||
let role = message
|
||||
.remove("role")
|
||||
.filter(|role| role == "assistant")
|
||||
.ok_or(ChatError::InvalidResponse)?;
|
||||
let reason = choice
|
||||
.get("finish_reason")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or(ChatError::InvalidResponse)?;
|
||||
if let Some(calls) = message
|
||||
.get_mut("tool_calls")
|
||||
.filter(|value| !value.is_null())
|
||||
{
|
||||
for (index, call) in calls
|
||||
.as_array_mut()
|
||||
.ok_or(ChatError::InvalidResponse)?
|
||||
.iter_mut()
|
||||
.enumerate()
|
||||
{
|
||||
call.as_object_mut()
|
||||
.ok_or(ChatError::InvalidResponse)?
|
||||
.insert("index".into(), json!(index));
|
||||
}
|
||||
}
|
||||
roles.push(
|
||||
json!({"index":index,"delta":{"role":role},"finish_reason":null,"logprobs":null}),
|
||||
);
|
||||
contents.push(json!({"index":index,"delta":message,"finish_reason":null,"logprobs":choice.get("logprobs")}));
|
||||
terminals.push(json!({"index":index,"delta":{},"finish_reason":reason,"logprobs":null}));
|
||||
}
|
||||
let mut chunks = Vec::with_capacity(4);
|
||||
for choices in [roles, contents, terminals] {
|
||||
let mut chunk = envelope.clone();
|
||||
chunk.insert("choices".into(), choices.into());
|
||||
chunks.push(Value::Object(chunk));
|
||||
}
|
||||
if include_usage && let Some(usage) = usage {
|
||||
envelope.insert("choices".into(), json!([]));
|
||||
envelope.insert("usage".into(), usage);
|
||||
chunks.push(Value::Object(envelope));
|
||||
}
|
||||
Ok(chunks)
|
||||
}
|
||||
|
||||
/// 仅在非流式交付时聚合 Chat chunk,不消费其他平台协议
|
||||
#[derive(Default)]
|
||||
pub struct ChatAccumulator {
|
||||
envelope: Option<Map<String, Value>>,
|
||||
message: Map<String, Value>,
|
||||
tools: BTreeMap<u64, Value>,
|
||||
finish_reason: Option<String>,
|
||||
logprobs: Map<String, Value>,
|
||||
error: Option<Value>,
|
||||
}
|
||||
|
||||
impl ChatAccumulator {
|
||||
/// 聚合一个 Chat JSON chunk;结束原因后允许独立用量帧
|
||||
pub fn push(&mut self, chunk: &Value) -> Result<(), ChatError> {
|
||||
if let Some(error) = chunk.get("error") {
|
||||
if self.error.is_some() || self.finish_reason.is_some() {
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
self.error = Some(json!({"error":error}));
|
||||
return Ok(());
|
||||
}
|
||||
if self.error.is_some() {
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
let body = chunk.as_object().ok_or(ChatError::InvalidResponse)?;
|
||||
if self.envelope.is_none() {
|
||||
for field in ["id", "model"] {
|
||||
if !body.get(field).is_some_and(Value::is_string) {
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
}
|
||||
if !body.get("created").is_some_and(Value::is_u64) {
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
self.envelope = Some(Map::from_iter([
|
||||
("id".into(), body["id"].clone()),
|
||||
("model".into(), body["model"].clone()),
|
||||
("created".into(), body["created"].clone()),
|
||||
("object".into(), json!("chat.completion")),
|
||||
]));
|
||||
self.message.insert("role".into(), json!("assistant"));
|
||||
self.message.insert("content".into(), Value::Null);
|
||||
self.message.insert("refusal".into(), Value::Null);
|
||||
}
|
||||
let envelope = self.envelope.as_mut().ok_or(ChatError::InvalidResponse)?;
|
||||
for field in ["id", "model", "created"] {
|
||||
if body.get(field) != envelope.get(field) {
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
}
|
||||
for field in [
|
||||
"usage",
|
||||
"metadata",
|
||||
"service_tier",
|
||||
"moderation",
|
||||
"system_fingerprint",
|
||||
] {
|
||||
if let Some(value) = body.get(field).filter(|v| !v.is_null()) {
|
||||
envelope.insert(field.into(), value.clone());
|
||||
}
|
||||
}
|
||||
for choice in body
|
||||
.get("choices")
|
||||
.and_then(Value::as_array)
|
||||
.ok_or(ChatError::InvalidResponse)?
|
||||
{
|
||||
if choice.get("index").and_then(Value::as_u64) != Some(0)
|
||||
|| self.finish_reason.is_some()
|
||||
{
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
let delta = choice
|
||||
.get("delta")
|
||||
.and_then(Value::as_object)
|
||||
.ok_or(ChatError::InvalidResponse)?;
|
||||
for (field, value) in delta {
|
||||
if value.is_null() {
|
||||
continue;
|
||||
}
|
||||
match field.as_str() {
|
||||
"role" if value == "assistant" => {}
|
||||
"content" | "refusal" | "reasoning_content" => {
|
||||
append_string(&mut self.message, field, value)?
|
||||
}
|
||||
"tool_calls" => {
|
||||
for call in value.as_array().ok_or(ChatError::InvalidResponse)? {
|
||||
let index = call
|
||||
.get("index")
|
||||
.and_then(Value::as_u64)
|
||||
.ok_or(ChatError::InvalidResponse)?;
|
||||
let target = self.tools.entry(index).or_insert_with(|| json!({}));
|
||||
for field in ["id", "type"] {
|
||||
if let Some(value) = call.get(field) {
|
||||
if target.get(field).is_some_and(|v| v != value) {
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
target[field] = value.clone();
|
||||
}
|
||||
}
|
||||
for kind in ["function", "custom"] {
|
||||
if let Some(function) = call.get(kind).and_then(Value::as_object) {
|
||||
if target.get(kind).is_none() {
|
||||
target[kind] = json!({});
|
||||
}
|
||||
let function_target = target[kind]
|
||||
.as_object_mut()
|
||||
.ok_or(ChatError::InvalidResponse)?;
|
||||
for (key, value) in function {
|
||||
append_string(function_target, key, value)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"annotations" => append_array(&mut self.message, field, value)?,
|
||||
"images" => merge_images(&mut self.message, value)?,
|
||||
_ => {
|
||||
self.message.insert(field.clone(), value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(logprobs) = choice.get("logprobs").and_then(Value::as_object) {
|
||||
for (field, value) in logprobs {
|
||||
if !value.is_null() {
|
||||
append_array(&mut self.logprobs, field, value)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(reason) = choice.get("finish_reason").filter(|v| !v.is_null()) {
|
||||
self.finish_reason = Some(
|
||||
reason
|
||||
.as_str()
|
||||
.ok_or(ChatError::InvalidResponse)?
|
||||
.to_owned(),
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 生成完整 Chat 响应;EOF 本身不能补造成功终态
|
||||
pub fn finish(mut self) -> Result<Value, ChatError> {
|
||||
if let Some(error) = self.error {
|
||||
return Ok(error);
|
||||
}
|
||||
let reason = self.finish_reason.ok_or(ChatError::IncompleteStream)?;
|
||||
let mut result = self.envelope.take().ok_or(ChatError::IncompleteStream)?;
|
||||
if !self.tools.is_empty() {
|
||||
for call in self.tools.values() {
|
||||
let kind = call
|
||||
.get("type")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or(ChatError::InvalidResponse)?;
|
||||
if !matches!(kind, "function" | "custom")
|
||||
|| !call.get("id").is_some_and(Value::is_string)
|
||||
|| !call
|
||||
.get(kind)
|
||||
.and_then(|v| v.get("name"))
|
||||
.is_some_and(Value::is_string)
|
||||
{
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
}
|
||||
self.message.insert(
|
||||
"tool_calls".into(),
|
||||
self.tools.into_values().collect::<Vec<_>>().into(),
|
||||
);
|
||||
}
|
||||
if let Some(images) = self.message.get_mut("images").and_then(Value::as_array_mut) {
|
||||
for image in images {
|
||||
if let Some(image) = image.as_object_mut() {
|
||||
image.remove("index");
|
||||
}
|
||||
}
|
||||
}
|
||||
for field in ["content", "refusal"] {
|
||||
if self.message.get(field).and_then(Value::as_str) == Some("") {
|
||||
self.message.insert(field.into(), Value::Null);
|
||||
}
|
||||
}
|
||||
result.insert("choices".into(), json!([{"index":0,"message":self.message,"finish_reason":reason,"logprobs":if self.logprobs.is_empty(){Value::Null}else{Value::Object(self.logprobs)}}]));
|
||||
Ok(result.into())
|
||||
}
|
||||
}
|
||||
|
||||
// 同一图片的预览和最终图共享 index,完整JSON只保留最后一次快照
|
||||
fn merge_images(target: &mut Map<String, Value>, value: &Value) -> Result<(), ChatError> {
|
||||
let images = value.as_array().ok_or(ChatError::InvalidResponse)?;
|
||||
let target = target
|
||||
.entry("images")
|
||||
.or_insert_with(|| json!([]))
|
||||
.as_array_mut()
|
||||
.ok_or(ChatError::InvalidResponse)?;
|
||||
for image in images {
|
||||
if !image.is_object() {
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
let index = image.get("index").and_then(Value::as_u64);
|
||||
if let Some(previous) = index.and_then(|index| {
|
||||
target
|
||||
.iter_mut()
|
||||
.find(|entry| entry.get("index").and_then(Value::as_u64) == Some(index))
|
||||
}) {
|
||||
*previous = image.clone();
|
||||
} else {
|
||||
target.push(image.clone());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn append_string(
|
||||
target: &mut Map<String, Value>,
|
||||
field: &str,
|
||||
value: &Value,
|
||||
) -> Result<(), ChatError> {
|
||||
let fragment = value.as_str().ok_or(ChatError::InvalidResponse)?;
|
||||
match target.get_mut(field) {
|
||||
Some(Value::String(text)) => text.push_str(fragment),
|
||||
None | Some(Value::Null) => {
|
||||
target.insert(field.into(), json!(fragment));
|
||||
}
|
||||
_ => return Err(ChatError::InvalidResponse),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn append_array(
|
||||
target: &mut Map<String, Value>,
|
||||
field: &str,
|
||||
value: &Value,
|
||||
) -> Result<(), ChatError> {
|
||||
let values = value.as_array().ok_or(ChatError::InvalidResponse)?;
|
||||
let target = target
|
||||
.entry(field)
|
||||
.or_insert_with(|| json!([]))
|
||||
.as_array_mut()
|
||||
.ok_or(ChatError::InvalidResponse)?;
|
||||
target.extend(values.iter().cloned());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn custom_tools(request: &Map<String, Value>) -> BTreeSet<String> {
|
||||
request
|
||||
.get("tools")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|v| v["type"] == "custom")
|
||||
.filter_map(|v| {
|
||||
v.pointer("/custom/name")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_owned)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn tool_call(
|
||||
id: &str,
|
||||
name: &str,
|
||||
input: &Value,
|
||||
custom: &BTreeSet<String>,
|
||||
) -> Result<Value, ChatError> {
|
||||
if !input.is_object() {
|
||||
return Err(ChatError::InvalidResponse);
|
||||
}
|
||||
if custom.contains(name) {
|
||||
let input = input
|
||||
.get("input")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or(ChatError::InvalidResponse)?;
|
||||
Ok(json!({"id":id,"type":"custom","custom":{"name":name,"input":input}}))
|
||||
} else {
|
||||
Ok(
|
||||
json!({"id":id,"type":"function","function":{"name":name,"arguments":input.to_string()}}),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
//! Chat 与 Responses 的直接请求和响应映射
|
||||
|
||||
mod request;
|
||||
mod response;
|
||||
|
||||
pub use request::convert_request;
|
||||
pub use response::{ChatStreamEncoder, project_response};
|
||||
+9
-42
@@ -1,27 +1,20 @@
|
||||
//! 将 Chat 请求转换为 Responses 正文,协议选项留在 API,业务 JSON 与上游兼容规则保持原有归属
|
||||
//! Chat 请求到 Responses 的直接字段与内容映射
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::data_plane::body::RequestDecodeError;
|
||||
use crate::chat_completions::ChatError as RequestDecodeError;
|
||||
|
||||
pub(in crate::data_plane) struct ConvertedChatRequest {
|
||||
pub(in crate::data_plane) body: Map<String, Value>,
|
||||
pub(in crate::data_plane) include_usage: bool,
|
||||
}
|
||||
|
||||
pub(in crate::data_plane) fn convert_request(
|
||||
body: &[u8],
|
||||
) -> Result<ConvertedChatRequest, RequestDecodeError> {
|
||||
let value = serde_json::from_slice(body).map_err(|_| RequestDecodeError::MalformedJson)?;
|
||||
let Value::Object(mut chat) = value else {
|
||||
return Err(RequestDecodeError::ExpectedObject);
|
||||
};
|
||||
/// 将已验证的 Chat 正文直接转换为 Responses 请求
|
||||
pub fn convert_request(
|
||||
request: &Map<String, Value>,
|
||||
) -> Result<Map<String, Value>, RequestDecodeError> {
|
||||
let mut chat = request.clone();
|
||||
validate_options(&chat)?;
|
||||
let model = required_string(&mut chat, "model", "model", false)?;
|
||||
let stream = optional_bool(&mut chat, "stream", "stream")?.unwrap_or(false);
|
||||
let include_usage = stream_options(optional(&mut chat, "stream_options"), stream)?;
|
||||
stream_options(optional(&mut chat, "stream_options"), stream)?;
|
||||
let input = messages(required(&mut chat, "messages", "messages")?)?;
|
||||
let mut body = Map::from_iter([
|
||||
("model".into(), model.into()),
|
||||
@@ -131,33 +124,7 @@ pub(in crate::data_plane) fn convert_request(
|
||||
body.insert("top_logprobs".into(), value);
|
||||
}
|
||||
}
|
||||
let ignored = [
|
||||
"stop",
|
||||
"seed",
|
||||
"frequency_penalty",
|
||||
"presence_penalty",
|
||||
"logit_bias",
|
||||
"prediction",
|
||||
]
|
||||
.into_iter()
|
||||
.filter(|field| {
|
||||
chat.get(*field).is_some_and(|value| {
|
||||
!value.is_null()
|
||||
&& value.as_f64() != Some(0.0)
|
||||
&& !value.as_array().is_some_and(Vec::is_empty)
|
||||
&& !value.as_object().is_some_and(Map::is_empty)
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if !ignored.is_empty() {
|
||||
tracing::info!(target: "request_trace", stage="chat.compatibility", ignored_options=?ignored,
|
||||
"Chat-only optional controls omitted from Responses request");
|
||||
}
|
||||
// 未识别的客户端顶层扩展不等于 Responses 参数,不进入上游正文
|
||||
Ok(ConvertedChatRequest {
|
||||
body,
|
||||
include_usage,
|
||||
})
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
fn validate_options(chat: &Map<String, Value>) -> Result<(), RequestDecodeError> {
|
||||
+29
-40
@@ -2,21 +2,12 @@
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use bytes::Bytes;
|
||||
use gateway_protocol::openai::events::{billable_usage_is_complete, extract_usage};
|
||||
use gateway_protocol::openai::sse::encode_sse_event;
|
||||
use crate::openai::events::{billable_usage_is_complete, extract_usage};
|
||||
use serde::Serialize;
|
||||
use serde_json::{Value, json};
|
||||
use sha2::{Digest as _, Sha256};
|
||||
|
||||
use crate::client_error::{ProtocolError, ProtocolErrorBody};
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub(in crate::data_plane) struct ChatIdentity {
|
||||
pub id: String,
|
||||
pub created: u64,
|
||||
pub model: String,
|
||||
}
|
||||
use crate::chat_completions::{ChatError as ProtocolErrorBody, ChatIdentity};
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Envelope<'a> {
|
||||
@@ -35,7 +26,7 @@ struct Envelope<'a> {
|
||||
}
|
||||
|
||||
/// 输入已由现有 Responses collector 聚合,投影不再恢复或重建缺失的 output
|
||||
pub(in crate::data_plane) fn project_response(
|
||||
pub fn project_response(
|
||||
response: &Value,
|
||||
identity: &ChatIdentity,
|
||||
) -> Result<Value, ProtocolErrorBody> {
|
||||
@@ -211,7 +202,7 @@ enum Terminal {
|
||||
}
|
||||
|
||||
/// 只保存身份关联与快照去重所需内容;终态帧由外层受管 body 决定何时交付
|
||||
pub(in crate::data_plane) struct ChatStreamEncoder {
|
||||
pub struct ChatStreamEncoder {
|
||||
identity: ChatIdentity,
|
||||
include_usage: bool,
|
||||
role_sent: bool,
|
||||
@@ -221,7 +212,7 @@ pub(in crate::data_plane) struct ChatStreamEncoder {
|
||||
}
|
||||
|
||||
impl ChatStreamEncoder {
|
||||
pub(in crate::data_plane) fn new(identity: ChatIdentity, include_usage: bool) -> Self {
|
||||
pub fn new(identity: ChatIdentity, include_usage: bool) -> Self {
|
||||
Self {
|
||||
identity,
|
||||
include_usage,
|
||||
@@ -232,19 +223,19 @@ impl ChatStreamEncoder {
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::data_plane) fn is_completed(&self) -> bool {
|
||||
pub fn is_completed(&self) -> bool {
|
||||
self.terminal == Some(Terminal::Completed)
|
||||
}
|
||||
|
||||
pub(in crate::data_plane) fn has_wire_failure(&self) -> bool {
|
||||
pub fn has_wire_failure(&self) -> bool {
|
||||
self.terminal == Some(Terminal::Failed)
|
||||
}
|
||||
|
||||
pub(in crate::data_plane) fn push_event(
|
||||
pub fn push_event(
|
||||
&mut self,
|
||||
event_type: Option<&str>,
|
||||
data: &Value,
|
||||
) -> Result<Vec<Bytes>, ProtocolErrorBody> {
|
||||
) -> Result<Vec<Value>, ProtocolErrorBody> {
|
||||
let event_type = event_type.or_else(|| data.get("type").and_then(Value::as_str));
|
||||
if self.has_wire_failure() {
|
||||
return Ok(Vec::new());
|
||||
@@ -427,7 +418,7 @@ impl ChatStreamEncoder {
|
||||
{
|
||||
error["type"] = json!("server_error");
|
||||
}
|
||||
frames.push(sse_frame(&json!({"error": error})));
|
||||
frames.push(json!({"error": error}));
|
||||
self.terminal = Some(Terminal::Failed);
|
||||
}
|
||||
// 辅助事件可随上游演进;实际 output item 和 content part 仍逐项检查可表达性
|
||||
@@ -441,6 +432,15 @@ impl ChatStreamEncoder {
|
||||
Ok(frames)
|
||||
}
|
||||
|
||||
/// 只有已经消费成功或错误终态的流才允许结束
|
||||
pub fn finish(&mut self) -> Result<Vec<Value>, ProtocolErrorBody> {
|
||||
if self.terminal.is_some() {
|
||||
Ok(Vec::new())
|
||||
} else {
|
||||
Err(ProtocolErrorBody::IncompleteStream)
|
||||
}
|
||||
}
|
||||
|
||||
fn text_event(
|
||||
&mut self,
|
||||
data: &Value,
|
||||
@@ -448,7 +448,7 @@ impl ChatStreamEncoder {
|
||||
text: &str,
|
||||
snapshot: bool,
|
||||
metadata: &Value,
|
||||
frames: &mut Vec<Bytes>,
|
||||
frames: &mut Vec<Value>,
|
||||
) -> Result<(), ProtocolErrorBody> {
|
||||
let mut content_chars = self.content_chars;
|
||||
let part = self.event_part(data, kind)?;
|
||||
@@ -508,7 +508,7 @@ impl ChatStreamEncoder {
|
||||
part: (bool, u64),
|
||||
text: &str,
|
||||
snapshot: bool,
|
||||
frames: &mut Vec<Bytes>,
|
||||
frames: &mut Vec<Value>,
|
||||
) -> Result<(), ProtocolErrorBody> {
|
||||
let has_text = self.output.values().any(|item| {
|
||||
matches!(&item.output,
|
||||
@@ -573,7 +573,7 @@ impl ChatStreamEncoder {
|
||||
index: u64,
|
||||
snapshot: &Value,
|
||||
terminal: bool,
|
||||
frames: &mut Vec<Bytes>,
|
||||
frames: &mut Vec<Value>,
|
||||
) -> Result<(), ProtocolErrorBody> {
|
||||
let id = optional_id(snapshot, "id")?;
|
||||
let kind = required_str(snapshot, "type")?;
|
||||
@@ -706,7 +706,7 @@ impl ChatStreamEncoder {
|
||||
Ok(found)
|
||||
}
|
||||
|
||||
fn delta(&self, delta: Value) -> Result<Bytes, ProtocolErrorBody> {
|
||||
fn delta(&self, delta: Value) -> Result<Value, ProtocolErrorBody> {
|
||||
delta_frame(&self.identity, self.include_usage, delta)
|
||||
}
|
||||
|
||||
@@ -715,7 +715,7 @@ impl ChatStreamEncoder {
|
||||
choices: Value,
|
||||
usage: Option<Value>,
|
||||
response: Option<&Value>,
|
||||
) -> Result<Bytes, ProtocolErrorBody> {
|
||||
) -> Result<Value, ProtocolErrorBody> {
|
||||
chunk_frame(&self.identity, choices, usage, response)
|
||||
}
|
||||
}
|
||||
@@ -964,7 +964,7 @@ fn logprobs_frame(
|
||||
include_usage: bool,
|
||||
kind: PartKind,
|
||||
values: Vec<Value>,
|
||||
) -> Result<Bytes, ProtocolErrorBody> {
|
||||
) -> Result<Value, ProtocolErrorBody> {
|
||||
chunk_frame(
|
||||
identity,
|
||||
json!([{"index":0, "delta":{}, "finish_reason":null,
|
||||
@@ -1087,7 +1087,7 @@ fn delta_frame(
|
||||
identity: &ChatIdentity,
|
||||
include_usage: bool,
|
||||
delta: Value,
|
||||
) -> Result<Bytes, ProtocolErrorBody> {
|
||||
) -> Result<Value, ProtocolErrorBody> {
|
||||
chunk_frame(
|
||||
identity,
|
||||
json!([{"index": 0, "delta": delta, "finish_reason": null, "logprobs": null}]),
|
||||
@@ -1101,7 +1101,7 @@ fn chunk_frame(
|
||||
choices: Value,
|
||||
usage: Option<Value>,
|
||||
response: Option<&Value>,
|
||||
) -> Result<Bytes, ProtocolErrorBody> {
|
||||
) -> Result<Value, ProtocolErrorBody> {
|
||||
let value = serde_json::to_value(Envelope {
|
||||
identity,
|
||||
object: "chat.completion.chunk",
|
||||
@@ -1112,11 +1112,7 @@ fn chunk_frame(
|
||||
moderation: response.map(project_moderation).transpose()?.flatten(),
|
||||
})
|
||||
.map_err(|_| invalid_response())?;
|
||||
Ok(sse_frame(&value))
|
||||
}
|
||||
|
||||
fn sse_frame(value: &Value) -> Bytes {
|
||||
Bytes::from(encode_sse_event("", &value.to_string()))
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn required_str<'a>(value: &'a Value, field: &str) -> Result<&'a str, ProtocolErrorBody> {
|
||||
@@ -1149,12 +1145,5 @@ fn required_index(value: &Value, field: &str) -> Result<u64, ProtocolErrorBody>
|
||||
}
|
||||
|
||||
fn invalid_response() -> ProtocolErrorBody {
|
||||
ProtocolErrorBody {
|
||||
error: ProtocolError {
|
||||
kind: "server_error",
|
||||
code: "invalid_upstream_response",
|
||||
message: "The upstream response cannot be represented as a Chat completion.".to_owned(),
|
||||
param: None,
|
||||
},
|
||||
}
|
||||
ProtocolErrorBody::InvalidResponse
|
||||
}
|
||||
@@ -1,193 +0,0 @@
|
||||
//! 将一次完整搜索的 Google 来源与正文区间投影到同一套 Responses 事件
|
||||
|
||||
use crate::anthropic::TranslationError;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub fn grounded_search_events(
|
||||
native: &Value,
|
||||
mut events: Vec<Value>,
|
||||
include_sources: bool,
|
||||
event_budget: usize,
|
||||
) -> Result<Vec<Value>, TranslationError> {
|
||||
let candidate = &native["candidates"][0];
|
||||
let metadata = &candidate["groundingMetadata"];
|
||||
let queries: Vec<_> = array(&metadata["webSearchQueries"])
|
||||
.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.collect();
|
||||
let chunks = array(&metadata["groundingChunks"]);
|
||||
if queries.is_empty() && !chunks.iter().any(|c| web_source(c).is_some()) {
|
||||
if candidate["finishReason"] == "STOP" {
|
||||
return Err(TranslationError::InvalidEvent(
|
||||
"Required web search returned no grounding evidence.",
|
||||
));
|
||||
}
|
||||
return Ok(events);
|
||||
}
|
||||
let Some(response) = events.last_mut().and_then(|e| e.get_mut("response")) else {
|
||||
return Err(TranslationError::InvalidEvent(
|
||||
"Web search translation is missing its terminal response.",
|
||||
));
|
||||
};
|
||||
let id = format!("ws_{}", response["id"].as_str().unwrap_or_default());
|
||||
let mut action = json!({"type":"search","queries":queries});
|
||||
if let Some(query) = queries.first() {
|
||||
action["query"] = json!(query)
|
||||
}
|
||||
if include_sources {
|
||||
action["sources"] = Value::Array(
|
||||
chunks
|
||||
.iter()
|
||||
.filter_map(web_source)
|
||||
.map(|(url, _)| json!({"type":"url","url":url}))
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
let call = json!({"type":"web_search_call","id":id,"status":"completed","action":action});
|
||||
let Some(output) = response["output"].as_array_mut() else {
|
||||
return Err(TranslationError::InvalidEvent(
|
||||
"Web search translation is missing its terminal response.",
|
||||
));
|
||||
};
|
||||
let citations = annotations(candidate, output);
|
||||
for (item, annotations) in output.iter_mut().zip(&citations) {
|
||||
if !annotations.is_empty() {
|
||||
item["content"][0]["annotations"] = json!(annotations)
|
||||
}
|
||||
}
|
||||
output.insert(0, call.clone());
|
||||
// 单次搜索已经拿到完整正文,来源很多时仍通过 content_part.done 和终态交付全部引用
|
||||
let incremental_annotations =
|
||||
events.len() + 5 + citations.iter().map(Vec::len).sum::<usize>() <= event_budget;
|
||||
let mut result = Vec::with_capacity(events.len() + 5);
|
||||
for mut event in events {
|
||||
let kind = event["type"].as_str().unwrap_or_default();
|
||||
if kind == "response.in_progress" {
|
||||
result.push(event);
|
||||
let pending = json!({"type":"web_search_call","id":id,"status":"in_progress"});
|
||||
result
|
||||
.push(json!({"type":"response.output_item.added","output_index":0,"item":pending}));
|
||||
for stage in ["in_progress", "searching", "completed"] {
|
||||
result.push(json!({"type":format!("response.web_search_call.{stage}"),"output_index":0,"item_id":id}));
|
||||
}
|
||||
result.push(json!({"type":"response.output_item.done","output_index":0,"item":call}));
|
||||
continue;
|
||||
}
|
||||
if let Some(index) = index(&event["output_index"]) {
|
||||
if let Some(annotations) = citations.get(index).filter(|v| !v.is_empty()) {
|
||||
match kind {
|
||||
"response.output_text.done" if incremental_annotations => {
|
||||
for (i, annotation) in annotations.iter().enumerate() {
|
||||
result.push(json!({"type":"response.output_text.annotation.added","item_id":event["item_id"],"output_index":index+1,"content_index":0,"annotation_index":i,"annotation":annotation}));
|
||||
}
|
||||
}
|
||||
"response.content_part.done" => {
|
||||
event["part"]["annotations"] = json!(annotations)
|
||||
}
|
||||
"response.output_item.done" => {
|
||||
event["item"]["content"][0]["annotations"] = json!(annotations)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
event["output_index"] = json!(index + 1);
|
||||
}
|
||||
result.push(event);
|
||||
}
|
||||
for (i, event) in result.iter_mut().enumerate() {
|
||||
event["sequence_number"] = json!(i);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn array(value: &Value) -> &[Value] {
|
||||
value.as_array().map_or(&[], Vec::as_slice)
|
||||
}
|
||||
|
||||
fn index(value: &Value) -> Option<usize> {
|
||||
usize::try_from(value.as_u64()?).ok()
|
||||
}
|
||||
|
||||
fn web_source(chunk: &Value) -> Option<(&str, &str)> {
|
||||
let web = &chunk["web"];
|
||||
let url = web["uri"].as_str()?;
|
||||
let uri = url.parse::<http::Uri>().ok()?;
|
||||
if !matches!(uri.scheme_str(), Some("http" | "https")) || uri.host().is_none_or(str::is_empty) {
|
||||
return None;
|
||||
}
|
||||
Some((url, web["title"].as_str().unwrap_or(url)))
|
||||
}
|
||||
|
||||
fn annotations(candidate: &Value, output: &[Value]) -> Vec<Vec<Value>> {
|
||||
let mut found = vec![Vec::new(); output.len()];
|
||||
let mut native_text = String::new();
|
||||
let mut parts = Vec::new();
|
||||
for part in array(&candidate["content"]["parts"]) {
|
||||
parts.push(
|
||||
part["text"]
|
||||
.as_str()
|
||||
.filter(|_| part["thought"] != true)
|
||||
.map(|text| {
|
||||
let start = native_text.len();
|
||||
native_text.push_str(text);
|
||||
(start, text)
|
||||
}),
|
||||
);
|
||||
}
|
||||
// Google 的 offset 是单个 Part 的 UTF-8 字节;Responses 需要每个 output_text 内的字符索引
|
||||
let mut ranges = Vec::new();
|
||||
let mut end = 0;
|
||||
for (i, item) in output.iter().enumerate() {
|
||||
if let Some(text) = item.pointer("/content/0/text").and_then(Value::as_str) {
|
||||
if !native_text[end..].starts_with(text) {
|
||||
return found;
|
||||
}
|
||||
ranges.push((end, end + text.len(), i));
|
||||
end += text.len();
|
||||
}
|
||||
}
|
||||
if end != native_text.len() {
|
||||
return found;
|
||||
}
|
||||
let metadata = &candidate["groundingMetadata"];
|
||||
for support in array(&metadata["groundingSupports"]) {
|
||||
let segment = &support["segment"];
|
||||
let proto_index = |field| segment.get(field).map_or(Some(0), index);
|
||||
let Some(part) = proto_index("partIndex") else {
|
||||
continue;
|
||||
};
|
||||
let Some(&(offset, text)) = parts.get(part).and_then(Option::as_ref) else {
|
||||
continue;
|
||||
};
|
||||
let Some(start) = proto_index("startIndex") else {
|
||||
continue;
|
||||
};
|
||||
let Some(end) = index(&segment["endIndex"]) else {
|
||||
continue;
|
||||
};
|
||||
let Some(span) = text.get(start..end).filter(|s| !s.is_empty()) else {
|
||||
continue;
|
||||
};
|
||||
if segment["text"].as_str().is_some_and(|s| s != span) {
|
||||
continue;
|
||||
}
|
||||
let Some(&(begin, _, item)) = ranges
|
||||
.iter()
|
||||
.find(|(begin, limit, _)| offset + start >= *begin && offset + end <= *limit)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let first = native_text[begin..offset + start].chars().count();
|
||||
let last = first + span.chars().count();
|
||||
for source in array(&support["groundingChunkIndices"]) {
|
||||
let Some((url, title)) = index(source)
|
||||
.and_then(|i| array(&metadata["groundingChunks"]).get(i))
|
||||
.and_then(web_source)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
found[item].push(json!({"type":"url_citation","url":url,"title":title,"start_index":first,"end_index":last}));
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
@@ -1,199 +0,0 @@
|
||||
//! Messages 内容到 GenAI 的纯协议映射,签名载荷只按明确来源恢复
|
||||
|
||||
use super::parts::{TurnParts, content, function_response, invalid};
|
||||
use crate::anthropic::TranslationError;
|
||||
use serde_json::{Map, Value, json};
|
||||
use std::{borrow::Cow, collections::BTreeMap};
|
||||
|
||||
/// 转换 Messages 请求;不支持的内容返回错误,避免静默丢失客户端输入
|
||||
pub fn messages_to_genai_request(
|
||||
request: &Map<String, Value>,
|
||||
) -> Result<Map<String, Value>, TranslationError> {
|
||||
let mut result = content_to_genai(request)?;
|
||||
let mut generation = Map::new();
|
||||
for (from, to) in [
|
||||
("max_tokens", "maxOutputTokens"),
|
||||
("temperature", "temperature"),
|
||||
("top_p", "topP"),
|
||||
("top_k", "topK"),
|
||||
("stop_sequences", "stopSequences"),
|
||||
] {
|
||||
if let Some(value) = request.get(from) {
|
||||
generation.insert(to.into(), value.clone());
|
||||
}
|
||||
}
|
||||
if let Some(thinking) = request.get("thinking") {
|
||||
match thinking["type"].as_str() {
|
||||
Some("disabled") => {
|
||||
generation.insert("thinkingConfig".into(), json!({"thinkingBudget":0}));
|
||||
}
|
||||
Some("enabled") => {
|
||||
generation.insert(
|
||||
"thinkingConfig".into(),
|
||||
json!({"thinkingBudget":thinking["budget_tokens"],"includeThoughts":true}),
|
||||
);
|
||||
}
|
||||
Some("adaptive" | "auto") => {
|
||||
generation.insert(
|
||||
"thinkingConfig".into(),
|
||||
json!({"thinkingBudget":-1,"includeThoughts":true}),
|
||||
);
|
||||
}
|
||||
_ => return Err(invalid()),
|
||||
}
|
||||
}
|
||||
if let Some(format) = request.get("output_config").and_then(|c| c.get("format")) {
|
||||
if format["type"] != "json_schema" {
|
||||
return Err(invalid());
|
||||
}
|
||||
generation.insert("responseMimeType".into(), json!("application/json"));
|
||||
generation.insert("responseSchema".into(), format["schema"].clone());
|
||||
}
|
||||
result.insert("generationConfig".into(), Value::Object(generation));
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn content_to_genai(request: &Map<String, Value>) -> Result<Map<String, Value>, TranslationError> {
|
||||
let mut result = Map::new();
|
||||
if let Some(system) = request.get("system") {
|
||||
result.insert(
|
||||
"systemInstruction".into(),
|
||||
json!({"parts":plain_parts(system)?}),
|
||||
);
|
||||
}
|
||||
let mut calls = BTreeMap::new();
|
||||
let mut contents = Vec::new();
|
||||
for message in request
|
||||
.get("messages")
|
||||
.and_then(Value::as_array)
|
||||
.ok_or_else(invalid)?
|
||||
{
|
||||
let blocks = match &message["content"] {
|
||||
Value::String(text) => Cow::Owned(vec![json!({"type":"text","text":text})]),
|
||||
Value::Array(blocks) => Cow::Borrowed(blocks.as_slice()),
|
||||
_ => return Err(invalid()),
|
||||
};
|
||||
// 空内容消息不承载对话;客户端的空占位不应进入上游历史
|
||||
if blocks.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let role = match message["role"].as_str() {
|
||||
Some("assistant") => "model",
|
||||
Some("user") => "user",
|
||||
_ => return Err(invalid()),
|
||||
};
|
||||
let mut parts = TurnParts::default();
|
||||
for block in blocks.iter() {
|
||||
let part = match block["type"].as_str() {
|
||||
Some("text") => json!({"text":block["text"]}),
|
||||
Some("image" | "document") => media(&block["source"])?,
|
||||
Some("thinking") => {
|
||||
parts.thinking(block)?;
|
||||
continue;
|
||||
}
|
||||
Some("redacted_thinking") => continue,
|
||||
Some("tool_use") => {
|
||||
let id = block["id"].as_str().ok_or_else(invalid)?;
|
||||
let name = block["name"].as_str().ok_or_else(invalid)?;
|
||||
calls.insert(id.to_owned(), name.to_owned());
|
||||
if !block["input"].is_object() {
|
||||
return Err(invalid());
|
||||
}
|
||||
json!({"functionCall":{"id":id,"name":name,"args":block["input"]}})
|
||||
}
|
||||
Some("tool_result") => {
|
||||
let id = block["tool_use_id"].as_str().ok_or_else(invalid)?;
|
||||
let name = calls.get(id).ok_or_else(invalid)?;
|
||||
function_response(
|
||||
id,
|
||||
name,
|
||||
block["is_error"] == true,
|
||||
&block["content"],
|
||||
|block| match block["type"].as_str() {
|
||||
Some("text") => Ok(json!({"text":block["text"]})),
|
||||
Some("image" | "document") => media(&block["source"]),
|
||||
_ => Err(invalid()),
|
||||
},
|
||||
)?
|
||||
}
|
||||
_ => return Err(invalid()),
|
||||
};
|
||||
parts.push(part);
|
||||
}
|
||||
let parts = parts.finish()?;
|
||||
if !parts.is_empty() {
|
||||
contents.push(content(role, parts));
|
||||
}
|
||||
}
|
||||
result.insert("contents".into(), Value::Array(contents));
|
||||
if let Some(tools) = request.get("tools").and_then(Value::as_array) {
|
||||
let declarations = tools
|
||||
.iter()
|
||||
.map(|tool| {
|
||||
if tool
|
||||
.get("type")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|t| t != "custom")
|
||||
|| !tool["input_schema"].is_object()
|
||||
{
|
||||
return Err(invalid());
|
||||
}
|
||||
let mut declaration =
|
||||
json!({"name":tool["name"],"parametersJsonSchema":tool["input_schema"]});
|
||||
if let Some(description) = tool.get("description") {
|
||||
declaration["description"] = description.clone();
|
||||
}
|
||||
Ok(declaration)
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
result.insert(
|
||||
"tools".into(),
|
||||
json!([{"functionDeclarations":declarations}]),
|
||||
);
|
||||
}
|
||||
if let Some(choice) = request.get("tool_choice") {
|
||||
let mode = match choice["type"].as_str() {
|
||||
Some("auto") => "AUTO",
|
||||
Some("any" | "tool") => "ANY",
|
||||
Some("none") => "NONE",
|
||||
_ => return Err(invalid()),
|
||||
};
|
||||
let mut config = json!({"mode":mode});
|
||||
if choice["type"] == "tool" {
|
||||
config["allowedFunctionNames"] = json!([choice["name"]]);
|
||||
}
|
||||
result.insert("toolConfig".into(), json!({"functionCallingConfig":config}));
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn plain_parts(value: &Value) -> Result<Vec<Value>, TranslationError> {
|
||||
if let Some(text) = value.as_str() {
|
||||
return Ok(vec![json!({"text":text})]);
|
||||
}
|
||||
value
|
||||
.as_array()
|
||||
.ok_or_else(invalid)?
|
||||
.iter()
|
||||
.map(|block| {
|
||||
if block["type"] != "text" {
|
||||
return Err(invalid());
|
||||
}
|
||||
Ok(json!({"text":block["text"]}))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn media(source: &Value) -> Result<Value, TranslationError> {
|
||||
match source["type"].as_str() {
|
||||
Some("base64") => {
|
||||
Ok(json!({"inlineData":{"mimeType":source["media_type"],"data":source["data"]}}))
|
||||
}
|
||||
Some("text") => Ok(json!({"text":source["data"]})),
|
||||
// URL 文件需有明确 MIME 类型;不替客户端下载未知资源
|
||||
Some("url") if source["media_type"].is_string() => {
|
||||
Ok(json!({"fileData":{"mimeType":source["media_type"],"fileUri":source["url"]}}))
|
||||
}
|
||||
_ => Err(invalid()),
|
||||
}
|
||||
}
|
||||
@@ -12,14 +12,5 @@ pub use response::{
|
||||
/// Google 原生请求与响应使用同一 wire 标识
|
||||
pub const GENAI_PROTOCOL: &str = "genai";
|
||||
|
||||
mod messages;
|
||||
mod parts;
|
||||
mod responses;
|
||||
mod stream;
|
||||
mod tokens;
|
||||
pub use messages::messages_to_genai_request;
|
||||
pub use responses::responses_to_genai_request;
|
||||
pub use stream::GenAiToMessagesStream;
|
||||
pub use tokens::{count_tokens_request, count_tokens_to_messages};
|
||||
mod grounding;
|
||||
pub use grounding::grounded_search_events;
|
||||
pub use tokens::{CountTokensError, count_tokens_request};
|
||||
|
||||
@@ -1,101 +0,0 @@
|
||||
//! GenAI 轮次中的签名和多模态函数返回
|
||||
use crate::anthropic::{GENAI_CARRIER as SIGNATURE_PREFIX, TranslationError};
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
pub(super) fn invalid() -> TranslationError {
|
||||
TranslationError::InvalidRequest(
|
||||
"The request contains content unsupported by the GenAI adapter.",
|
||||
)
|
||||
}
|
||||
|
||||
// 工具截图可能很大,组装轮次时直接移入已编码的媒体数据
|
||||
pub(super) fn content(role: &str, parts: Vec<Value>) -> Value {
|
||||
Value::Object(Map::from_iter([
|
||||
("role".into(), json!(role)),
|
||||
("parts".into(), Value::Array(parts)),
|
||||
]))
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct TurnParts {
|
||||
parts: Vec<Value>,
|
||||
pending_signature: Option<Value>,
|
||||
}
|
||||
|
||||
impl TurnParts {
|
||||
pub(super) fn thinking(&mut self, block: &Value) -> Result<(), TranslationError> {
|
||||
let Some(raw) = block["signature"]
|
||||
.as_str()
|
||||
.and_then(|s| s.strip_prefix(SIGNATURE_PREFIX))
|
||||
else {
|
||||
// 只回放由本协议返回的思考签名
|
||||
return Ok(());
|
||||
};
|
||||
let carrier: Value = serde_json::from_str(raw).map_err(|_| invalid())?;
|
||||
let signature = carrier["signature"].as_str().ok_or_else(invalid)?;
|
||||
match carrier["target"].as_str() {
|
||||
Some("previous") => {
|
||||
self.parts.last_mut().ok_or_else(invalid)?["thoughtSignature"] = json!(signature)
|
||||
}
|
||||
Some("next") => self.pending_signature = Some(json!(signature)),
|
||||
Some("thinking") => self.push(
|
||||
json!({"text":block["thinking"],"thought":true,"thoughtSignature":signature}),
|
||||
),
|
||||
_ => return Err(invalid()),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(super) fn push(&mut self, mut part: Value) {
|
||||
if let Some(signature) = self.pending_signature.take() {
|
||||
part["thoughtSignature"] = signature;
|
||||
}
|
||||
// Google 为外部历史提供的兜底值;真实签名优先,Chat 等无签名合同无需服务端缓存
|
||||
// https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/thinking/thought-signatures
|
||||
if part.get("functionCall").is_some() && part.get("thoughtSignature").is_none() {
|
||||
part["thoughtSignature"] = json!("skip_thought_signature_validator");
|
||||
}
|
||||
self.parts.push(part);
|
||||
}
|
||||
pub(super) fn finish(mut self) -> Result<Vec<Value>, TranslationError> {
|
||||
if self.pending_signature.is_some() {
|
||||
return Err(invalid());
|
||||
}
|
||||
self.parts
|
||||
.retain(|part| part["text"] != "" || part.get("thoughtSignature").is_some());
|
||||
Ok(self.parts)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn function_response(
|
||||
id: &str,
|
||||
name: &str,
|
||||
error: bool,
|
||||
output: &Value,
|
||||
parse_part: impl Fn(&Value) -> Result<Value, TranslationError>,
|
||||
) -> Result<Value, TranslationError> {
|
||||
let mut result = json!({"id":id,"name":name});
|
||||
let key = if error { "error" } else { "output" };
|
||||
let value = if let Some(blocks) = output.as_array() {
|
||||
let mut texts = Vec::new();
|
||||
let mut media = Vec::new();
|
||||
for block in blocks {
|
||||
let part = parse_part(block)?;
|
||||
if let Some(text) = part.get("text").and_then(Value::as_str) {
|
||||
texts.push(text.to_owned());
|
||||
} else {
|
||||
media.push(part);
|
||||
}
|
||||
}
|
||||
if !media.is_empty() {
|
||||
result["parts"] = Value::Array(media);
|
||||
}
|
||||
Value::String(texts.join("\n"))
|
||||
} else {
|
||||
output.clone()
|
||||
};
|
||||
result["response"] = json!({(key):value});
|
||||
Ok(Value::Object(Map::from_iter([(
|
||||
"functionResponse".into(),
|
||||
result,
|
||||
)])))
|
||||
}
|
||||
@@ -1,381 +0,0 @@
|
||||
//! Responses 输入、函数声明与生成参数直接映射到 GenAI
|
||||
|
||||
use super::parts::{TurnParts, content, function_response, invalid};
|
||||
use crate::anthropic::{
|
||||
ToolSet, TranslationError, allowed_tools, restore_anthropic, split_data_url,
|
||||
};
|
||||
use crate::openai::web_search;
|
||||
use serde_json::{Map, Value, json};
|
||||
use std::{borrow::Cow, collections::BTreeMap};
|
||||
|
||||
/// 普通生成只映射函数工具,独立搜索由 Provider 按账号能力编排
|
||||
pub fn responses_to_genai_request(
|
||||
request: &Map<String, Value>,
|
||||
) -> Result<Map<String, Value>, TranslationError> {
|
||||
let mut generation = Map::new();
|
||||
if let Some(value) = request
|
||||
.get("max_output_tokens")
|
||||
.filter(|value| !value.is_null())
|
||||
{
|
||||
let maximum =
|
||||
value
|
||||
.as_u64()
|
||||
.filter(|value| *value > 0)
|
||||
.ok_or(TranslationError::InvalidRequest(
|
||||
"The max_output_tokens field must be a positive integer.",
|
||||
))?;
|
||||
generation.insert("maxOutputTokens".into(), json!(maximum));
|
||||
}
|
||||
for (from, to) in [("temperature", "temperature"), ("top_p", "topP")] {
|
||||
if let Some(value) = request.get(from) {
|
||||
generation.insert(to.into(), value.clone());
|
||||
}
|
||||
}
|
||||
if let Some(thinking) = request
|
||||
.get("reasoning")
|
||||
.and_then(|value| value.get("effort"))
|
||||
.and_then(Value::as_str)
|
||||
.and_then(thinking_config)
|
||||
{
|
||||
generation.insert("thinkingConfig".into(), thinking);
|
||||
}
|
||||
if let Some(format) = request.get("text").and_then(|value| value.get("format"))
|
||||
&& format["type"] == "json_schema"
|
||||
{
|
||||
generation.insert("responseMimeType".into(), json!("application/json"));
|
||||
generation.insert(
|
||||
"responseSchema".into(),
|
||||
format.get("schema").cloned().unwrap_or_else(|| json!({})),
|
||||
);
|
||||
}
|
||||
let tools = ToolSet::from_responses(request);
|
||||
let mut result = conversation(request, &tools)?;
|
||||
write_tools(request, &tools, &mut result)?;
|
||||
result.insert("generationConfig".into(), Value::Object(generation));
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn thinking_config(effort: &str) -> Option<Value> {
|
||||
// 档位预算不受 Messages 的必填输出上限、强制工具或无思考续轮规则影响
|
||||
let budget = match effort.trim().to_ascii_lowercase().as_str() {
|
||||
"none" => return Some(json!({"thinkingBudget":0})),
|
||||
"minimal" | "low" => 1024,
|
||||
"medium" => 8192,
|
||||
"high" => 24576,
|
||||
"xhigh" => 32768,
|
||||
"max" => 128000,
|
||||
"auto" => -1,
|
||||
_ => return None,
|
||||
};
|
||||
Some(json!({"thinkingBudget":budget,"includeThoughts":true}))
|
||||
}
|
||||
|
||||
fn content_part(part: &Value) -> Result<Value, TranslationError> {
|
||||
let data = match part["type"].as_str() {
|
||||
Some("text" | "input_text" | "output_text") => {
|
||||
return Ok(json!({"text":part["text"].as_str().ok_or_else(invalid)?}));
|
||||
}
|
||||
Some("refusal") => {
|
||||
return Ok(json!({"text":part["refusal"].as_str().ok_or_else(invalid)?}));
|
||||
}
|
||||
Some("input_image") => part["image_url"]
|
||||
.as_str()
|
||||
.or_else(|| part["image_url"]["url"].as_str()),
|
||||
Some("input_file") => part["file_data"]
|
||||
.as_str()
|
||||
.or_else(|| part["file_url"].as_str()),
|
||||
_ => return Err(invalid()),
|
||||
}
|
||||
.ok_or_else(invalid)?;
|
||||
if let Some((mime, bytes)) = split_data_url(data) {
|
||||
return Ok(json!({"inlineData":{"mimeType":mime,"data":bytes}}));
|
||||
}
|
||||
if let Some(mime) = part["mime_type"].as_str() {
|
||||
return Ok(json!({"fileData":{"mimeType":mime,"fileUri":data}}));
|
||||
}
|
||||
Err(invalid())
|
||||
}
|
||||
|
||||
fn content_parts(content: &Value) -> Result<Vec<Value>, TranslationError> {
|
||||
match content {
|
||||
Value::String(text) => Ok(vec![json!({"text":text})]),
|
||||
Value::Array(parts) => parts.iter().map(content_part).collect(),
|
||||
_ => Err(invalid()),
|
||||
}
|
||||
}
|
||||
|
||||
fn conversation(
|
||||
request: &Map<String, Value>,
|
||||
tools: &ToolSet<&Value>,
|
||||
) -> Result<Map<String, Value>, TranslationError> {
|
||||
let mut result = Map::new();
|
||||
let mut system = Vec::new();
|
||||
if let Some(text) = request
|
||||
.get("instructions")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|s| !s.is_empty())
|
||||
{
|
||||
system.push(json!({"text":text}));
|
||||
}
|
||||
let mut contents = Vec::new();
|
||||
let mut history = Vec::new();
|
||||
let input = match request.get("input") {
|
||||
None | Some(Value::Null) => &[][..],
|
||||
Some(Value::String(text)) => {
|
||||
if !text.is_empty() {
|
||||
contents.push(json!({"role":"user","parts":[{"text":text}]}));
|
||||
}
|
||||
&[]
|
||||
}
|
||||
Some(Value::Array(items)) => items.as_slice(),
|
||||
_ => {
|
||||
return Err(TranslationError::InvalidRequest(
|
||||
"The input field must be a string or an array.",
|
||||
));
|
||||
}
|
||||
};
|
||||
for (pos, item) in input.iter().enumerate() {
|
||||
let kind = item["type"].as_str().unwrap_or("message");
|
||||
let role = match kind {
|
||||
"message" => match item["role"].as_str().unwrap_or("user") {
|
||||
"system" | "developer" => {
|
||||
let parts = content_parts(&item["content"])?;
|
||||
if parts.iter().any(|part| !part["text"].is_string()) {
|
||||
return Err(invalid());
|
||||
}
|
||||
system.extend(parts);
|
||||
continue;
|
||||
}
|
||||
"assistant" => "model",
|
||||
"user" => "user",
|
||||
_ => return Err(invalid()),
|
||||
},
|
||||
"reasoning" => {
|
||||
// CPR 的历史签名载荷包含完整思考块,其他来源的推理不应打断相邻轮次
|
||||
if let Some(block) = restore_anthropic(item)
|
||||
&& block["type"] == "thinking"
|
||||
&& block["signature"]
|
||||
.as_str()
|
||||
.is_some_and(|v| v.starts_with(crate::anthropic::GENAI_CARRIER))
|
||||
{
|
||||
history.push(InputItem {
|
||||
role: "model",
|
||||
position: pos,
|
||||
body: Cow::Owned(block),
|
||||
});
|
||||
}
|
||||
continue;
|
||||
}
|
||||
"function_call" | "custom_tool_call" => "model",
|
||||
"function_call_output" | "custom_tool_call_output" => "user",
|
||||
// 托管工具的历史事件不包含可回放的模型内容
|
||||
"web_search_call" => continue,
|
||||
_ => return Err(invalid()),
|
||||
};
|
||||
history.push(InputItem {
|
||||
role,
|
||||
position: pos,
|
||||
body: Cow::Borrowed(item),
|
||||
});
|
||||
}
|
||||
let mut calls = Vec::new();
|
||||
for turn in history.chunk_by(|a, b| a.role == b.role) {
|
||||
let role = turn[0].role;
|
||||
let parts = if role == "model" {
|
||||
model_turn(turn, tools, &mut calls)?
|
||||
} else {
|
||||
user_turn(turn, &mut calls)?
|
||||
};
|
||||
if !parts.is_empty() {
|
||||
contents.push(content(role, parts));
|
||||
}
|
||||
}
|
||||
if !calls.is_empty() {
|
||||
contents.push(content("user", user_turn(&[], &mut calls)?));
|
||||
}
|
||||
result.insert("contents".into(), Value::Array(contents));
|
||||
if !system.is_empty() {
|
||||
result.insert("systemInstruction".into(), json!({"parts":system}));
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
struct InputItem<'a> {
|
||||
role: &'static str,
|
||||
position: usize,
|
||||
body: Cow<'a, Value>,
|
||||
}
|
||||
|
||||
fn model_turn(
|
||||
turn: &[InputItem<'_>],
|
||||
tools: &ToolSet<&Value>,
|
||||
calls: &mut Vec<(String, String)>,
|
||||
) -> Result<Vec<Value>, TranslationError> {
|
||||
let mut parts = TurnParts::default();
|
||||
for entry in turn {
|
||||
let item = entry.body.as_ref();
|
||||
match item["type"].as_str().unwrap_or("message") {
|
||||
"thinking" => parts.thinking(item)?,
|
||||
"message" => {
|
||||
for part in content_parts(&item["content"])? {
|
||||
parts.push(part);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let name = tools.wire_name(
|
||||
item["name"].as_str().ok_or_else(invalid)?,
|
||||
item["namespace"].as_str(),
|
||||
);
|
||||
let id = item["call_id"]
|
||||
.as_str()
|
||||
.map(str::to_owned)
|
||||
.unwrap_or_else(|| format!("call_{}", entry.position));
|
||||
let args = if item["type"] == "custom_tool_call" {
|
||||
json!({"input":item["input"].as_str().ok_or_else(invalid)?})
|
||||
} else {
|
||||
serde_json::from_str::<Value>(item["arguments"].as_str().unwrap_or("{}"))
|
||||
.map_err(|_| invalid())?
|
||||
};
|
||||
if !args.is_object() {
|
||||
return Err(invalid());
|
||||
}
|
||||
parts.push(json!({"functionCall":{"id":id,"name":name,"args":args}}));
|
||||
calls.push((id, name.to_owned()));
|
||||
}
|
||||
}
|
||||
}
|
||||
parts.finish()
|
||||
}
|
||||
|
||||
fn user_turn(
|
||||
turn: &[InputItem<'_>],
|
||||
calls: &mut Vec<(String, String)>,
|
||||
) -> Result<Vec<Value>, TranslationError> {
|
||||
let mut outputs = BTreeMap::new();
|
||||
for entry in turn {
|
||||
let item = entry.body.as_ref();
|
||||
if matches!(
|
||||
item["type"].as_str(),
|
||||
Some("function_call_output" | "custom_tool_call_output")
|
||||
) {
|
||||
outputs.insert(
|
||||
item["call_id"].as_str().unwrap_or_default(),
|
||||
(entry.position, item),
|
||||
);
|
||||
}
|
||||
}
|
||||
// 同轮按调用顺序闭合,重复返回只取最后一项,迟到的结果保留为普通用户内容
|
||||
let mut parts = Vec::new();
|
||||
for (id, name) in calls.drain(..) {
|
||||
let response = if let Some((_, item)) = outputs.remove(id.as_str()) {
|
||||
function_response(
|
||||
&id,
|
||||
&name,
|
||||
item["status"] == "incomplete",
|
||||
&item["output"],
|
||||
content_part,
|
||||
)?
|
||||
} else {
|
||||
function_response(
|
||||
&id,
|
||||
&name,
|
||||
true,
|
||||
&json!("Tool call was interrupted before any output was recorded."),
|
||||
content_part,
|
||||
)?
|
||||
};
|
||||
parts.push(response);
|
||||
}
|
||||
for entry in turn {
|
||||
let item = entry.body.as_ref();
|
||||
if item["type"].as_str().unwrap_or("message") == "message" {
|
||||
parts.extend(
|
||||
content_parts(&item["content"])?
|
||||
.into_iter()
|
||||
.filter(|part| part["text"] != ""),
|
||||
);
|
||||
} else if outputs
|
||||
.get(item["call_id"].as_str().unwrap_or_default())
|
||||
.is_some_and(|(last, _)| *last == entry.position)
|
||||
{
|
||||
let output = &item["output"];
|
||||
let blocks = if output.is_array() || output.is_string() {
|
||||
content_parts(output)?
|
||||
} else {
|
||||
vec![json!({"text":output.to_string()})]
|
||||
};
|
||||
let before = parts.len();
|
||||
parts.extend(
|
||||
blocks
|
||||
.into_iter()
|
||||
.filter(|p| p["text"].as_str().is_none_or(|s| !s.trim().is_empty())),
|
||||
);
|
||||
if parts.len() == before {
|
||||
parts.push(json!({"text":"Tool result was empty."}));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(parts)
|
||||
}
|
||||
|
||||
fn write_tools(
|
||||
request: &Map<String, Value>,
|
||||
tools: &ToolSet<&Value>,
|
||||
result: &mut Map<String, Value>,
|
||||
) -> Result<(), TranslationError> {
|
||||
let choice = request.get("tool_choice").unwrap_or(&Value::Null);
|
||||
let allowed = allowed_tools(choice)?;
|
||||
let mut declarations = Vec::new();
|
||||
for (name, tool) in tools.declarations(allowed) {
|
||||
let schema = tool.schema();
|
||||
if !schema.is_object() {
|
||||
return Err(invalid());
|
||||
}
|
||||
let mut declaration = json!({"name":name,"parametersJsonSchema":schema});
|
||||
if let Some(description) = tool.definition.get("description") {
|
||||
declaration["description"] = description.clone();
|
||||
}
|
||||
declarations.push(declaration);
|
||||
}
|
||||
let kind = if allowed.is_some() {
|
||||
match choice["mode"].as_str() {
|
||||
Some(mode @ ("required" | "auto")) => Some(mode),
|
||||
_ => return Err(invalid()),
|
||||
}
|
||||
} else {
|
||||
choice.as_str().or_else(|| choice["type"].as_str())
|
||||
};
|
||||
if declarations.is_empty() {
|
||||
if matches!(kind, Some("required" | "function" | "custom"))
|
||||
|| allowed.is_some_and(|a| !a.iter().all(web_search::is_search))
|
||||
{
|
||||
return Err(TranslationError::InvalidRequest(
|
||||
"No declared function can satisfy the tool choice.",
|
||||
));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let config = match kind {
|
||||
Some("function" | "custom") => {
|
||||
let (name, _) = tools
|
||||
.declarations(Some(std::slice::from_ref(choice)))
|
||||
.next()
|
||||
.ok_or(TranslationError::InvalidRequest(
|
||||
"The selected function must be declared.",
|
||||
))?;
|
||||
Some(json!({"mode":"ANY","allowedFunctionNames":[name]}))
|
||||
}
|
||||
Some("required") => Some(json!({"mode":"ANY"})),
|
||||
Some("none") => Some(json!({"mode":"NONE"})),
|
||||
Some("auto") => Some(json!({"mode":"AUTO"})),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(config) = config {
|
||||
result.insert("toolConfig".into(), json!({"functionCallingConfig":config}));
|
||||
}
|
||||
result.insert(
|
||||
"tools".into(),
|
||||
json!([{"functionDeclarations":declarations}]),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,203 +0,0 @@
|
||||
//! GenAI 增量帧转为 Messages 事件,终态在上游 EOF 后输出
|
||||
|
||||
use super::{GenerateContentObservation, GenerationFinish};
|
||||
use crate::anthropic::GENAI_CARRIER as SIGNATURE_PREFIX;
|
||||
use crate::anthropic::TranslationError;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// 每条上游流独占转换状态;同一文本块跨帧延续,签名和尾部用量不会提前丢弃
|
||||
#[derive(Default)]
|
||||
pub struct GenAiToMessagesStream {
|
||||
observation: GenerateContentObservation,
|
||||
model: String,
|
||||
started: bool,
|
||||
finished: bool,
|
||||
index: usize,
|
||||
usage: Value,
|
||||
active_thinking: Option<bool>,
|
||||
pending_empty: Option<bool>,
|
||||
}
|
||||
|
||||
impl GenAiToMessagesStream {
|
||||
/// 上游首帧未附模型版本时使用请求模型,避免交付 null 模型字段
|
||||
pub fn new(model: impl Into<String>) -> Self {
|
||||
Self {
|
||||
model: model.into(),
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// 消费已解开 Cloud Code 外层的原生响应
|
||||
pub fn push(&mut self, value: &Value) -> Result<Vec<Value>, TranslationError> {
|
||||
if self.finished {
|
||||
return Err(TranslationError::InvalidEvent(
|
||||
"The GenAI stream has already ended.",
|
||||
));
|
||||
}
|
||||
let mut events = Vec::new();
|
||||
if !self.started {
|
||||
self.started = true;
|
||||
let id = value["responseId"]
|
||||
.as_str()
|
||||
.map(str::to_owned)
|
||||
.unwrap_or_else(|| format!("msg_{}", uuid::Uuid::new_v4()));
|
||||
events.push(json!({"type":"message_start","message":{"id":id,"type":"message","role":"assistant","model":value["modelVersion"].as_str().unwrap_or(&self.model),"content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}}}));
|
||||
}
|
||||
if let Some(usage) = self.observation.observe(value) {
|
||||
self.usage = json!({"input_tokens":usage.input_tokens().unwrap_or_default().saturating_sub(usage.cached.unwrap_or_default()),"cache_read_input_tokens":usage.cached.unwrap_or_default(),"output_tokens":usage.output_tokens().unwrap_or_default()});
|
||||
}
|
||||
for candidate in value["candidates"].as_array().into_iter().flatten() {
|
||||
if candidate["index"].as_u64().unwrap_or_default() != 0 {
|
||||
return Err(TranslationError::InvalidEvent(
|
||||
"Multiple GenAI candidates cannot be translated to a single message.",
|
||||
));
|
||||
}
|
||||
for part in candidate["content"]["parts"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
self.part(part, &mut events)?;
|
||||
}
|
||||
}
|
||||
Ok(events)
|
||||
}
|
||||
|
||||
fn part(&mut self, part: &Value, events: &mut Vec<Value>) -> Result<(), TranslationError> {
|
||||
let signature = part.get("thoughtSignature");
|
||||
if let Some(call) = part.get("functionCall") {
|
||||
self.pending_empty = None;
|
||||
self.close(None, events);
|
||||
if let Some(signature) = signature {
|
||||
self.carrier(signature, "next", events);
|
||||
}
|
||||
let id = call["id"]
|
||||
.as_str()
|
||||
.map(str::to_owned)
|
||||
.unwrap_or_else(|| format!("call_{}", uuid::Uuid::new_v4()));
|
||||
let index = self.index;
|
||||
self.index += 1;
|
||||
events.push(json!({"type":"content_block_start","index":index,"content_block":{"type":"tool_use","id":id,"name":call["name"],"input":{}}}));
|
||||
events.push(json!({"type":"content_block_delta","index":index,"delta":{"type":"input_json_delta","partial_json":call.get("args").unwrap_or(&json!({})).to_string()}}));
|
||||
events.push(json!({"type":"content_block_stop","index":index}));
|
||||
} else if let Some(text) = part.get("text").and_then(Value::as_str) {
|
||||
let thinking = part["thought"] == true;
|
||||
if text.is_empty() && signature.is_none() {
|
||||
// 空占位仅在后续携带签名时保留,避免 Claude 历史回放被空 text 拒绝
|
||||
if self.active_thinking.is_none() {
|
||||
self.pending_empty = Some(thinking);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
self.pending_empty = None;
|
||||
self.text(thinking, text, events);
|
||||
if let Some(signature) = signature {
|
||||
self.signature(signature, events);
|
||||
}
|
||||
} else if let Some(signature) = signature {
|
||||
if self.active_thinking.is_none()
|
||||
&& let Some(thinking) = self.pending_empty.take()
|
||||
{
|
||||
self.text(thinking, "", events);
|
||||
}
|
||||
self.signature(signature, events);
|
||||
} else {
|
||||
return Err(TranslationError::InvalidEvent(
|
||||
"The GenAI response contains unsupported content.",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn text(&mut self, thinking: bool, text: &str, events: &mut Vec<Value>) {
|
||||
if self
|
||||
.active_thinking
|
||||
.is_some_and(|active| active != thinking)
|
||||
{
|
||||
self.close(None, events);
|
||||
}
|
||||
if self.active_thinking.is_none() {
|
||||
let block = if thinking {
|
||||
json!({"type":"thinking","thinking":"","signature":""})
|
||||
} else {
|
||||
json!({"type":"text","text":""})
|
||||
};
|
||||
events.push(
|
||||
json!({"type":"content_block_start","index":self.index,"content_block":block}),
|
||||
);
|
||||
self.index += 1;
|
||||
self.active_thinking = Some(thinking);
|
||||
}
|
||||
if !text.is_empty() {
|
||||
let mut delta = json!({"type":if thinking {"thinking_delta"} else {"text_delta"}});
|
||||
delta[if thinking { "thinking" } else { "text" }] = json!(text);
|
||||
events.push(json!({"type":"content_block_delta","index":self.index-1,"delta":delta}));
|
||||
}
|
||||
}
|
||||
|
||||
fn signature(&mut self, signature: &Value, events: &mut Vec<Value>) {
|
||||
match self.active_thinking {
|
||||
Some(true) => self.close(Some(signature), events),
|
||||
// 普通文本签名不强制回传;追加空思考载体或拆分正文会使 Claude Code
|
||||
// 的最终 result 为空或只有末段;保持正文连续,原生入口仍完整透传签名
|
||||
Some(false) => {}
|
||||
None => self.carrier(signature, "previous", events),
|
||||
}
|
||||
}
|
||||
|
||||
fn close(&mut self, signature: Option<&Value>, events: &mut Vec<Value>) {
|
||||
let Some(thinking) = self.active_thinking.take() else {
|
||||
return;
|
||||
};
|
||||
let index = self.index - 1;
|
||||
if thinking {
|
||||
events.push(json!({"type":"content_block_delta","index":index,"delta":{"type":"signature_delta","signature":carrier(signature.unwrap_or(&Value::Null),"thinking")}}));
|
||||
}
|
||||
events.push(json!({"type":"content_block_stop","index":index}));
|
||||
}
|
||||
|
||||
/// 只有上游正常 EOF 且存在完成信号时才发出完成事件
|
||||
pub fn finish(&mut self) -> Result<Vec<Value>, TranslationError> {
|
||||
if self.finished {
|
||||
return Err(TranslationError::IncompleteStream);
|
||||
}
|
||||
let reason = match self
|
||||
.observation
|
||||
.finish()
|
||||
.ok_or(TranslationError::IncompleteStream)?
|
||||
{
|
||||
GenerationFinish::Blocked => "refusal",
|
||||
GenerationFinish::Candidate {
|
||||
reason: "MAX_TOKENS",
|
||||
..
|
||||
} => "max_tokens",
|
||||
GenerationFinish::Candidate {
|
||||
reason: "STOP" | "OTHER",
|
||||
tool_call: true,
|
||||
} => "tool_use",
|
||||
GenerationFinish::Candidate { reason: "STOP", .. } => "end_turn",
|
||||
GenerationFinish::Candidate { .. } => "refusal",
|
||||
};
|
||||
self.finished = true;
|
||||
let mut events = Vec::new();
|
||||
self.close(None, &mut events);
|
||||
events.push(json!({"type":"message_delta","delta":{"stop_reason":reason,"stop_sequence":null},"usage":self.usage}));
|
||||
events.push(json!({"type":"message_stop"}));
|
||||
Ok(events)
|
||||
}
|
||||
|
||||
fn carrier(&mut self, signature: &Value, target: &str, events: &mut Vec<Value>) {
|
||||
let index = self.index;
|
||||
self.index += 1;
|
||||
events.push(json!({"type":"content_block_start","index":index,"content_block":{"type":"thinking","thinking":"","signature":""}}));
|
||||
events.push(json!({"type":"content_block_delta","index":index,"delta":{"type":"signature_delta","signature":carrier(signature,target)}}));
|
||||
events.push(json!({"type":"content_block_stop","index":index}));
|
||||
}
|
||||
}
|
||||
|
||||
fn carrier(signature: &Value, target: &str) -> String {
|
||||
format!(
|
||||
"{SIGNATURE_PREFIX}{}",
|
||||
json!({"signature":signature,"target":target})
|
||||
)
|
||||
}
|
||||
@@ -1,27 +1,22 @@
|
||||
//! GenAI 输入计数的请求封装和跨协议结果投影
|
||||
//! GenAI 输入计数的原生请求封装
|
||||
|
||||
use crate::anthropic::TranslationError;
|
||||
use serde_json::{Map, Value, json};
|
||||
use serde_json::{Map, Value};
|
||||
use thiserror::Error;
|
||||
|
||||
/// 原生计数封套的解析错误
|
||||
#[derive(Debug, Error, Clone, PartialEq, Eq)]
|
||||
#[error("generateContentRequest must be a JSON object.")]
|
||||
pub struct CountTokensError;
|
||||
|
||||
/// 完整生成请求存在时,以它作为计数输入,外层 contents 不参与计数
|
||||
pub fn count_tokens_request(
|
||||
request: &Map<String, Value>,
|
||||
) -> Result<&Map<String, Value>, TranslationError> {
|
||||
) -> Result<&Map<String, Value>, CountTokensError> {
|
||||
match request
|
||||
.get("generateContentRequest")
|
||||
.or_else(|| request.get("generate_content_request"))
|
||||
{
|
||||
Some(value) => value.as_object().ok_or(TranslationError::InvalidRequest(
|
||||
"generateContentRequest must be a JSON object.",
|
||||
)),
|
||||
Some(value) => value.as_object().ok_or(CountTokensError),
|
||||
None => Ok(request),
|
||||
}
|
||||
}
|
||||
|
||||
/// 只投影上游明确给出的计数,不把缺失或无效结果当作零
|
||||
pub fn count_tokens_to_messages(response: &Value) -> Result<Value, TranslationError> {
|
||||
let tokens = response.get("totalTokens").and_then(Value::as_u64).ok_or(
|
||||
TranslationError::InvalidEvent("The upstream token count is invalid."),
|
||||
)?;
|
||||
Ok(json!({"input_tokens":tokens}))
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ pub mod openai;
|
||||
/// Google GenAI 原生生成协议
|
||||
pub mod genai;
|
||||
|
||||
/// Anthropic Messages 与 Responses 的线协议转换
|
||||
/// Anthropic Messages 原生解析、计量与流聚合
|
||||
pub mod anthropic;
|
||||
|
||||
/// 协议请求中的共享能力事实
|
||||
@@ -18,3 +18,6 @@ pub mod request;
|
||||
|
||||
/// CPR 互联只读观测协议
|
||||
pub mod peer;
|
||||
|
||||
/// Chat Completions 直接转换
|
||||
pub mod chat_completions;
|
||||
|
||||
@@ -5,6 +5,7 @@ use serde_json::{Map, Value};
|
||||
pub use crate::capabilities::RequestFacts;
|
||||
|
||||
use crate::anthropic::{ANTHROPIC_PROTOCOL, messages_request_effort};
|
||||
use crate::chat_completions::{self, CHAT_PROTOCOL};
|
||||
use crate::genai::{self, GENAI_PROTOCOL};
|
||||
use crate::openai::{OPENAI_PROTOCOL, codex_responses_request_semantics_with_turn_metadata};
|
||||
|
||||
@@ -63,6 +64,10 @@ pub fn request_observation(
|
||||
compact: semantics.compact,
|
||||
}
|
||||
}
|
||||
CHAT_PROTOCOL => RequestObservation {
|
||||
reasoning_effort: chat_completions::request_effort(body).map(str::to_owned),
|
||||
..RequestObservation::default()
|
||||
},
|
||||
ANTHROPIC_PROTOCOL => RequestObservation {
|
||||
reasoning_effort: messages_request_effort(body).map(str::to_owned),
|
||||
..RequestObservation::default()
|
||||
@@ -121,6 +126,7 @@ pub fn request_facts(protocol: &str, body: &Map<String, Value>) -> RequestFacts
|
||||
== Some("json_schema");
|
||||
}
|
||||
GENAI_PROTOCOL => genai::request_facts(body, &mut facts),
|
||||
CHAT_PROTOCOL => facts = chat_completions::request_facts(body),
|
||||
_ => {}
|
||||
}
|
||||
facts
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
mod capabilities;
|
||||
mod request;
|
||||
mod response;
|
||||
mod session;
|
||||
mod stream;
|
||||
mod usage;
|
||||
|
||||
@@ -1,624 +1,17 @@
|
||||
//! 验证请求内容、工具配对和签名来源
|
||||
//! 原生 Messages 生成与计数合同
|
||||
|
||||
use gateway_protocol::anthropic::{
|
||||
messages_to_responses_count_request, messages_to_responses_request,
|
||||
messages_to_responses_response, responses_to_messages_request, responses_to_messages_response,
|
||||
validate_count_request, validate_request,
|
||||
};
|
||||
use serde_json::{Map, Value, json};
|
||||
use gateway_protocol::anthropic::{validate_count_request, validate_request};
|
||||
use serde_json::json;
|
||||
|
||||
use gateway_protocol::anthropic::{
|
||||
strip_foreign_reasoning_for_responses, strip_foreign_thinking_for_messages,
|
||||
};
|
||||
|
||||
fn object(value: Value) -> Map<String, Value> {
|
||||
value.as_object().expect("测试正文必须是对象").clone()
|
||||
#[test]
|
||||
fn counting_does_not_require_generation_budget() {
|
||||
let request = json!({"model":"model","messages":[{"role":"user","content":"hello"}]});
|
||||
assert!(validate_count_request(request.as_object().unwrap()).is_ok());
|
||||
assert!(validate_request(request.as_object().unwrap()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mid_conversation_system_messages_keep_their_role_and_position() {
|
||||
let request = object(json!({
|
||||
"model":"claude", "max_tokens":128,
|
||||
"messages":[
|
||||
{"role":"user", "content":"hello"},
|
||||
{"role":"system", "content":"Be brief."},
|
||||
{"role":"system", "content":[], "output_config":{"effort":"medium"}}
|
||||
]
|
||||
}));
|
||||
assert!(validate_request(&request).is_ok());
|
||||
let converted = messages_to_responses_request(&request).expect("转换会话中的 system 消息");
|
||||
assert_eq!(converted["input"].as_array().unwrap().len(), 2);
|
||||
assert_eq!(converted["input"][0]["role"], "user");
|
||||
assert_eq!(converted["input"][1]["role"], "system");
|
||||
assert_eq!(converted["input"][1]["content"][0]["text"], "Be brief.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn counting_does_not_require_or_invent_generation_budget() {
|
||||
let request = object(json!({"model":"model","messages":[{"role":"user","content":"hello"}]}));
|
||||
assert!(validate_count_request(&request).is_ok());
|
||||
assert!(validate_request(&request).is_err());
|
||||
let converted = messages_to_responses_count_request(&request).expect("计数转换");
|
||||
assert!(!converted.contains_key("max_output_tokens"));
|
||||
assert_eq!(converted["input"][0]["content"][0]["text"], "hello");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn system_images_tools_and_structured_output_map_without_losing_order() {
|
||||
let request = object(
|
||||
json!({"model":"claude","max_tokens":4096,"system":"brief","messages":[{"role":"user","content":[{"type":"text","text":"look"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"AA=="}}]},{"role":"assistant","content":[{"type":"text","text":"calling"},{"type":"tool_use","id":"call_1","name":"lookup","input":{"q":"x"}}]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"call_1","content":"found"}]}],"tools":[{"name":"lookup","input_schema":{"type":"object"}}],"tool_choice":{"type":"tool","name":"lookup","disable_parallel_tool_use":true},"output_config":{"format":{"type":"json_schema","schema":{"type":"object"}}}}),
|
||||
);
|
||||
let converted = messages_to_responses_request(&request).expect("转换");
|
||||
assert_eq!(converted["input"][0]["role"], "developer");
|
||||
assert_eq!(
|
||||
converted["input"][1]["content"][1]["image_url"],
|
||||
"data:image/png;base64,AA=="
|
||||
);
|
||||
assert_eq!(converted["input"][3]["type"], "function_call");
|
||||
assert_eq!(converted["input"][4]["output"], "found");
|
||||
assert_eq!(converted["parallel_tool_calls"], false);
|
||||
assert_eq!(converted["text"]["format"]["name"], "response");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_tools_round_trip_and_orphan_outputs_follow_cpa_fallback() {
|
||||
let request = object(
|
||||
json!({"model":"model","tools":[{"type":"custom","name":"shell","description":"run a command"}],"input":[{"type":"custom_tool_call","call_id":"call_1","name":"shell","input":"echo ok"},{"type":"custom_tool_call_output","call_id":"call_1","output":"old"},{"type":"custom_tool_call_output","call_id":"call_1","output":"new"},{"type":"function_call_output","call_id":"missing","output":"orphan"}]}),
|
||||
);
|
||||
let converted = responses_to_messages_request(&request, &Default::default()).expect("转换");
|
||||
assert_eq!(
|
||||
converted["messages"][0]["content"][0]["input"]["input"],
|
||||
"echo ok"
|
||||
);
|
||||
assert_eq!(converted["messages"][1]["content"][0]["content"], "new");
|
||||
assert_eq!(converted["messages"][1]["content"][1]["text"], "orphan");
|
||||
let native = json!({"id":"m1","content":[{"type":"tool_use","id":"call_2","name":"shell","input":{"input":"pwd"}}],"stop_reason":"tool_use","usage":{}});
|
||||
let response = messages_to_responses_response(&native, &request).expect("返回转换");
|
||||
assert_eq!(response["output"][0]["type"], "custom_tool_call");
|
||||
assert_eq!(response["output"][0]["input"], "pwd");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parallel_tool_results_precede_text_and_keep_custom_input_and_errors() {
|
||||
let request = object(json!({
|
||||
"model":"model",
|
||||
"tools":[
|
||||
{"type":"function","name":"read","parameters":{"type":"object"}},
|
||||
{"type":"custom","name":"patch"}
|
||||
],
|
||||
"input":[
|
||||
{"type":"function_call","call_id":"read_1","name":"read","arguments":"{}"},
|
||||
{"type":"custom_tool_call","call_id":"patch_1","name":"patch","input":"patch text"},
|
||||
{"role":"user","content":"before"},
|
||||
{"type":"custom_tool_call_output","call_id":"patch_1","output":"patch failed","status":"incomplete"},
|
||||
{"role":"user","content":"between"},
|
||||
{"type":"function_call_output","call_id":"read_1","output":"read result"}
|
||||
]
|
||||
}));
|
||||
let converted = responses_to_messages_request(&request, &Default::default()).unwrap();
|
||||
assert_eq!(
|
||||
converted["messages"][0]["content"][1]["input"],
|
||||
json!({"input":"patch text"})
|
||||
);
|
||||
assert_eq!(
|
||||
converted["messages"][1]["content"],
|
||||
json!([
|
||||
{"type":"tool_result","tool_use_id":"patch_1","content":"patch failed","is_error":true},
|
||||
{"type":"tool_result","tool_use_id":"read_1","content":"read result"},
|
||||
{"type":"text","text":"before"},
|
||||
{"type":"text","text":"between"}
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interrupted_parallel_calls_close_before_the_conversation_continues() {
|
||||
let request = object(json!({"model":"model","input":[
|
||||
{"type":"function_call","call_id":"first","name":"read","arguments":"{}"},
|
||||
{"type":"function_call","call_id":"second","name":"read","arguments":"{}"},
|
||||
{"type":"function_call_output","call_id":"first","output":"available"},
|
||||
{"role":"user","content":"continue without waiting"},
|
||||
{"role":"assistant","content":"continuing"},
|
||||
{"type":"function_call_output","call_id":"second","output":"late result"}
|
||||
]}));
|
||||
let converted = responses_to_messages_request(&request, &Default::default()).unwrap();
|
||||
assert_eq!(
|
||||
converted["messages"][1]["content"],
|
||||
json!([
|
||||
{"type":"tool_result","tool_use_id":"second","is_error":true,"content":"Tool call was interrupted before any output was recorded."},
|
||||
{"type":"tool_result","tool_use_id":"first","content":"available"},
|
||||
{"type":"text","text":"continue without waiting"}
|
||||
])
|
||||
);
|
||||
assert_eq!(converted["messages"][2]["content"][0]["text"], "continuing");
|
||||
assert_eq!(
|
||||
converted["messages"][3]["content"],
|
||||
json!([
|
||||
{"type":"text","text":"late result"}
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trailing_tool_calls_get_explicit_interrupted_results() {
|
||||
let request = object(json!({"model":"model","input":[
|
||||
{"role":"user","content":"read files"},
|
||||
{"type":"function_call","call_id":"second","name":"read","arguments":"{}"},
|
||||
{"type":"function_call","call_id":"first","name":"read","arguments":"{}"}
|
||||
]}));
|
||||
let converted = responses_to_messages_request(&request, &Default::default()).unwrap();
|
||||
assert_eq!(converted["messages"][2]["role"], "user");
|
||||
let results = converted["messages"][2]["content"].as_array().unwrap();
|
||||
assert_eq!(results.len(), 2);
|
||||
assert_eq!(results[0]["tool_use_id"], "second");
|
||||
assert_eq!(results[1]["tool_use_id"], "first");
|
||||
assert!(results.iter().all(|result| result["is_error"] == true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_results_do_not_break_an_earlier_completed_round() {
|
||||
let request = object(json!({"model":"model","input":[
|
||||
{"type":"function_call","call_id":"call","name":"read","arguments":"{}"},
|
||||
{"type":"function_call_output","call_id":"call","output":"old"},
|
||||
{"type":"function_call_output","call_id":"call","output":"new"},
|
||||
{"role":"assistant","content":"completed"},
|
||||
{"type":"function_call_output","call_id":"call","output":"late duplicate"}
|
||||
]}));
|
||||
let converted = responses_to_messages_request(&request, &Default::default()).unwrap();
|
||||
assert_eq!(
|
||||
converted["messages"][1]["content"],
|
||||
json!([
|
||||
{"type":"tool_result","tool_use_id":"call","content":"new"}
|
||||
])
|
||||
);
|
||||
assert_eq!(
|
||||
converted["messages"][3]["content"],
|
||||
json!([
|
||||
{"type":"text","text":"late duplicate"}
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn orphan_results_reuse_multimodal_content_and_empty_results_keep_a_marker() {
|
||||
let request = object(json!({"model":"model","input":[
|
||||
{"type":"function_call_output","call_id":"missing","output":[
|
||||
{"type":"input_text","text":" "},
|
||||
{"type":"input_image","image_url":"data:image/png;base64,AA=="},
|
||||
{"type":"input_file","file_url":"https://example.com/file.pdf"},
|
||||
{"type":"input_text","text":"caption"}
|
||||
]},
|
||||
{"type":"function_call_output","call_id":"empty","output":""}
|
||||
]}));
|
||||
let converted = responses_to_messages_request(&request, &Default::default()).unwrap();
|
||||
assert_eq!(
|
||||
converted["messages"][0]["content"],
|
||||
json!([
|
||||
{"type":"image","source":{"type":"base64","media_type":"image/png","data":"AA=="}},
|
||||
{"type":"document","source":{"type":"url","url":"https://example.com/file.pdf"}},
|
||||
{"type":"text","text":"caption"},
|
||||
{"type":"text","text":"Tool result was empty."}
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closed_tool_history_is_unchanged_after_another_round_trip() {
|
||||
let request = object(json!({"model":"model","input":[
|
||||
{"role":"user","content":"read"},
|
||||
{"type":"function_call","call_id":"call","name":"read","arguments":"{\"path\":\"file\"}"},
|
||||
{"type":"function_call_output","call_id":"call","output":"result"},
|
||||
{"role":"user","content":"summarize"},
|
||||
{"role":"assistant","content":"summary"}
|
||||
]}));
|
||||
let converted = responses_to_messages_request(&request, &Default::default()).unwrap();
|
||||
let replay = messages_to_responses_request(&converted).unwrap();
|
||||
let restored = responses_to_messages_request(&replay, &Default::default()).unwrap();
|
||||
assert_eq!(restored["messages"], converted["messages"]);
|
||||
assert_eq!(
|
||||
converted["messages"][2]["content"],
|
||||
json!([
|
||||
{"type":"tool_result","tool_use_id":"call","content":"result"},
|
||||
{"type":"text","text":"summarize"}
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn anthropic_thinking_and_redacted_blocks_return_to_their_origin() {
|
||||
let request = object(json!({"model":"model","input":"hi"}));
|
||||
let blocks = json!([{"type":"thinking","thinking":"private","signature":"signed-native"},{"type":"redacted_thinking","data":"opaque"}]);
|
||||
let response = messages_to_responses_response(
|
||||
&json!({"id":"m1","content":blocks,"stop_reason":"end_turn","usage":{}}),
|
||||
&request,
|
||||
)
|
||||
.expect("响应转换");
|
||||
let mut followup = request;
|
||||
followup.insert("input".into(), response["output"].clone());
|
||||
let restored = responses_to_messages_request(&followup, &Default::default()).expect("回传转换");
|
||||
assert_eq!(restored["messages"][0]["content"], blocks);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openai_reasoning_returns_to_its_origin_and_foreign_signatures_are_dropped() {
|
||||
let request = object(
|
||||
json!({"model":"model","max_tokens":100,"messages":[{"role":"user","content":"hi"}]}),
|
||||
);
|
||||
let item = json!({"type":"reasoning","id":"r1","summary":[{"type":"summary_text","text":"reason"}],"encrypted_content":"gAAAAopaque"});
|
||||
let response = responses_to_messages_response(
|
||||
&json!({"id":"r0","status":"completed","output":[item],"usage":{}}),
|
||||
&request,
|
||||
)
|
||||
.expect("响应转换");
|
||||
let mut followup = request;
|
||||
followup.insert(
|
||||
"messages".into(),
|
||||
json!([{"role":"assistant","content":response["content"]}]),
|
||||
);
|
||||
let restored = messages_to_responses_request(&followup).expect("回传转换");
|
||||
assert_eq!(restored["input"][0], item);
|
||||
followup.insert("messages".into(),json!([{"role":"assistant","content":[{"type":"thinking","thinking":"thought","signature":"foreign-anthropic"},{"type":"text","text":"answer"}]}]));
|
||||
let foreign = messages_to_responses_request(&followup).expect("外来源降级");
|
||||
assert_eq!(foreign["input"].as_array().expect("数组").len(), 1);
|
||||
assert_eq!(foreign["input"][0]["type"], "message");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reasoning_budget_stays_inside_explicit_output_limit() {
|
||||
let request = object(
|
||||
json!({"model":"model","input":"hi","max_output_tokens":2048,"reasoning":{"effort":"high"}}),
|
||||
);
|
||||
let converted = responses_to_messages_request(&request, &Default::default()).expect("预算转换");
|
||||
assert_eq!(
|
||||
converted["thinking"],
|
||||
json!({"type":"enabled","budget_tokens":2047})
|
||||
);
|
||||
assert_eq!(converted["max_tokens"], 2048);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn switching_to_native_messages_only_removes_our_openai_carrier() {
|
||||
let source = object(
|
||||
json!({"model":"model","max_tokens":100,"messages":[{"role":"user","content":"hi"}]}),
|
||||
);
|
||||
let response=responses_to_messages_response(&json!({"id":"r1","status":"completed","output":[{"type":"reasoning","id":"reason1","summary":[{"type":"summary_text","text":"thinking"}],"encrypted_content":"gAAAAopaque"},{"type":"message","role":"assistant","content":[{"type":"output_text","text":"answer"}]}],"usage":{}}),&source).expect("第一次走Responses上游");
|
||||
let mut next = source;
|
||||
let native = json!({"type":"thinking","thinking":"native","signature":"unknown-native-signature","future_field":9});
|
||||
next.insert("messages".into(),json!([{"role":"assistant","content":response["content"]},{"role":"assistant","content":[native]},{"role":"user","content":"continue"}]));
|
||||
strip_foreign_thinking_for_messages(&mut next);
|
||||
assert_eq!(
|
||||
next["messages"][0]["content"],
|
||||
json!([{"type":"text","text":"answer"}])
|
||||
);
|
||||
assert_eq!(next["messages"][1]["content"][0], native);
|
||||
assert_eq!(next["messages"][2]["content"], "continue");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn switching_to_native_responses_only_removes_our_anthropic_carrier() {
|
||||
let source = object(json!({"model":"model","input":"hi"}));
|
||||
let response=messages_to_responses_response(&json!({"id":"m1","content":[{"type":"thinking","thinking":"thought","signature":"native"},{"type":"text","text":"answer"}],"stop_reason":"end_turn","usage":{}}),&source).expect("第一次走Messages上游");
|
||||
let mut next = source;
|
||||
let native = json!({"type":"reasoning","encrypted_content":"unknown-native","future_field":7});
|
||||
let mut input = response["output"].as_array().expect("输出数组").clone();
|
||||
input.push(native.clone());
|
||||
next.insert("input".into(), json!(input));
|
||||
strip_foreign_reasoning_for_responses(&mut next);
|
||||
assert_eq!(next["input"].as_array().expect("输入数组").len(), 2);
|
||||
assert_eq!(next["input"][0]["type"], "message");
|
||||
assert_eq!(next["input"][1], native);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aliased_tool_names_never_overwrite_an_existing_declaration() {
|
||||
let source = object(
|
||||
json!({"model":"model","input":"hi","tools":[{"type":"function","name":"invalid.name","parameters":{}},{"type":"function","name":"tool_0","parameters":{}}]}),
|
||||
);
|
||||
let converted = responses_to_messages_request(&source, &Default::default()).expect("工具别名");
|
||||
assert_eq!(converted["tools"].as_array().expect("工具数组").len(), 2);
|
||||
let wire = converted["tools"][1]["name"].as_str().expect("工具名称");
|
||||
let response = messages_to_responses_response(
|
||||
&json!({"content":[{"type":"tool_use","id":"c1","name":wire,"input":{}}],"usage":{}}),
|
||||
&source,
|
||||
)
|
||||
.expect("反向工具别名");
|
||||
assert_eq!(response["output"][0]["name"], "tool_0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_thinking_switches_and_cpa_budget_levels_survive_conversion() {
|
||||
for (effort, budget) in [
|
||||
("minimal", 1024),
|
||||
("low", 1024),
|
||||
("medium", 8192),
|
||||
("high", 24576),
|
||||
("xhigh", 32768),
|
||||
("max", 128000),
|
||||
] {
|
||||
let request = object(
|
||||
json!({"model":"model","input":"hi","max_output_tokens":200000,"reasoning":{"effort":effort}}),
|
||||
);
|
||||
let converted = responses_to_messages_request(&request, &Default::default()).unwrap();
|
||||
assert_eq!(
|
||||
converted["thinking"],
|
||||
json!({"type":"enabled","budget_tokens":budget})
|
||||
);
|
||||
}
|
||||
let disabled = object(json!({"model":"model","input":"hi","reasoning":{"effort":"none"}}));
|
||||
assert_eq!(
|
||||
responses_to_messages_request(&disabled, &Default::default()).unwrap()["thinking"],
|
||||
json!({"type":"disabled"})
|
||||
);
|
||||
let no_budget = object(
|
||||
json!({"model":"model","input":"hi","max_output_tokens":1024,"reasoning":{"effort":"high"}}),
|
||||
);
|
||||
assert_eq!(
|
||||
responses_to_messages_request(&no_budget, &Default::default()).unwrap()["thinking"],
|
||||
json!({"type":"disabled"})
|
||||
);
|
||||
for (thinking, effort) in [
|
||||
(json!({"type":"disabled"}), "none"),
|
||||
(json!({"type":"enabled","budget_tokens":1024}), "low"),
|
||||
(json!({"type":"enabled","budget_tokens":8192}), "medium"),
|
||||
(json!({"type":"enabled","budget_tokens":24576}), "high"),
|
||||
(json!({"type":"enabled","budget_tokens":32768}), "xhigh"),
|
||||
] {
|
||||
let request = object(
|
||||
json!({"model":"model","messages":[{"role":"user","content":"hi"}],"max_tokens":200000,"thinking":thinking}),
|
||||
);
|
||||
assert_eq!(
|
||||
messages_to_responses_request(&request).unwrap()["reasoning"]["effort"],
|
||||
effort
|
||||
);
|
||||
}
|
||||
for thinking in [None, Some(json!({"type":"adaptive"}))] {
|
||||
let mut request = object(
|
||||
json!({"model":"model","messages":[{"role":"user","content":"hi"}],"max_tokens":1024,"output_config":{"effort":"low"}}),
|
||||
);
|
||||
if let Some(thinking) = thinking {
|
||||
request.insert("thinking".into(), thinking);
|
||||
}
|
||||
assert_eq!(
|
||||
messages_to_responses_request(&request).unwrap()["reasoning"]["effort"],
|
||||
"low"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adaptive_capabilities_drive_thinking_effort_and_output_limit_without_model_guessing() {
|
||||
let capabilities = gateway_protocol::anthropic::MessagesModelCapabilities::from_model(&json!({
|
||||
"max_tokens":512,
|
||||
"capabilities":{"thinking":{"supported":true,"types":{"adaptive":{"supported":true},"enabled":{"supported":false},"disabled":{"supported":false}}},"effort":{"low":{"supported":true},"high":{"supported":true}}}
|
||||
}));
|
||||
for (effort, expected) in [
|
||||
("none", Some("low")),
|
||||
("minimal", Some("low")),
|
||||
("medium", Some("low")),
|
||||
("high", Some("high")),
|
||||
("max", Some("high")),
|
||||
("auto", None),
|
||||
] {
|
||||
let source = object(
|
||||
json!({"model":"arbitrary-alias","input":"hello","max_output_tokens":1000,"temperature":0.3,"top_p":0.9,"reasoning":{"effort":effort},"text":{"format":{"type":"json_schema","schema":{"type":"object"}}}}),
|
||||
);
|
||||
let converted = responses_to_messages_request(&source, &capabilities).unwrap();
|
||||
assert_eq!(converted["thinking"], json!({"type":"adaptive"}));
|
||||
assert_eq!(converted["max_tokens"], 512);
|
||||
assert!(!converted.contains_key("temperature"));
|
||||
assert!(!converted.contains_key("top_p"));
|
||||
assert_eq!(
|
||||
converted["output_config"]
|
||||
.get("effort")
|
||||
.and_then(Value::as_str),
|
||||
expected
|
||||
);
|
||||
assert_eq!(
|
||||
converted["output_config"]["format"]["schema"]["type"],
|
||||
"object"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forced_tools_respect_manual_and_adaptive_thinking_modes() {
|
||||
let source = object(
|
||||
json!({"model":"alias","input":"hello","tools":[{"type":"function","name":"echo","parameters":{"type":"object"}}],"reasoning":{"effort":"high"},"tool_choice":{"type":"function","name":"echo"},"parallel_tool_calls":false}),
|
||||
);
|
||||
let converted = responses_to_messages_request(&source, &Default::default()).unwrap();
|
||||
assert_eq!(
|
||||
converted["tool_choice"],
|
||||
json!({"type":"tool","name":"echo","disable_parallel_tool_use":true})
|
||||
);
|
||||
assert_eq!(converted["thinking"], json!({"type":"disabled"}));
|
||||
let adaptive = gateway_protocol::anthropic::MessagesModelCapabilities {
|
||||
adaptive_thinking: Some(true),
|
||||
disabled_thinking: Some(false),
|
||||
..Default::default()
|
||||
};
|
||||
let converted = responses_to_messages_request(&source, &adaptive).unwrap();
|
||||
assert_eq!(
|
||||
converted["tool_choice"],
|
||||
json!({"type":"auto","disable_parallel_tool_use":true})
|
||||
);
|
||||
assert_eq!(converted["thinking"], json!({"type":"adaptive"}));
|
||||
assert_eq!(converted["output_config"]["effort"], "high");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serial_tools_get_default_choice_but_none_has_no_parallel_option() {
|
||||
for (choice, expected) in [
|
||||
(
|
||||
None,
|
||||
json!({"type":"auto","disable_parallel_tool_use":true}),
|
||||
),
|
||||
(Some(json!("none")), json!({"type":"none"})),
|
||||
(
|
||||
Some(json!("required")),
|
||||
json!({"type":"any","disable_parallel_tool_use":true}),
|
||||
),
|
||||
] {
|
||||
let mut source = object(
|
||||
json!({"input":"hello","tools":[{"type":"function","name":"echo"}],"parallel_tool_calls":false}),
|
||||
);
|
||||
if let Some(choice) = choice {
|
||||
source.insert("tool_choice".into(), choice);
|
||||
}
|
||||
assert_eq!(
|
||||
responses_to_messages_request(&source, &Default::default()).unwrap()["tool_choice"],
|
||||
expected
|
||||
);
|
||||
source.remove("tools");
|
||||
assert!(
|
||||
!responses_to_messages_request(&source, &Default::default())
|
||||
.unwrap()
|
||||
.contains_key("tool_choice")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn service_tier_and_speed_map_by_protocol_meaning() {
|
||||
for (tier, speed, target_tier) in [
|
||||
("priority", Some("fast"), None),
|
||||
("default", None, Some("standard_only")),
|
||||
("auto", None, Some("auto")),
|
||||
("flex", None, None),
|
||||
] {
|
||||
let converted = responses_to_messages_request(
|
||||
&object(json!({"input":"hello","service_tier":tier})),
|
||||
&Default::default(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(converted.get("speed").and_then(Value::as_str), speed);
|
||||
assert_eq!(
|
||||
converted.get("service_tier").and_then(Value::as_str),
|
||||
target_tier
|
||||
);
|
||||
}
|
||||
for (tier, speed, expected) in [
|
||||
("auto", None, "auto"),
|
||||
("standard_only", None, "default"),
|
||||
("standard_only", Some("fast"), "priority"),
|
||||
] {
|
||||
let mut source = object(
|
||||
json!({"model":"alias","max_tokens":1000,"messages":[{"role":"user","content":"hello"}],"service_tier":tier}),
|
||||
);
|
||||
if let Some(speed) = speed {
|
||||
source.insert("speed".into(), json!(speed));
|
||||
}
|
||||
assert_eq!(
|
||||
messages_to_responses_request(&source).unwrap()["service_tier"],
|
||||
expected
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hosted_search_never_widens_network_access() {
|
||||
for access in [json!(false), json!("cached"), json!("indexed")] {
|
||||
let req = object(
|
||||
json!({"tools":[{"type":"web_search","name":"web_search","external_web_access":access}]}),
|
||||
);
|
||||
assert!(
|
||||
!responses_to_messages_request(&req, &Default::default())
|
||||
.unwrap()
|
||||
.contains_key("tools")
|
||||
);
|
||||
}
|
||||
let limited = object(
|
||||
json!({"model":"m","max_tokens":12,"messages":[{"role":"user","content":"hi"}],"tools":[{"type":"web_search_20250305","name":"web_search","max_uses":1}]}),
|
||||
);
|
||||
assert!(messages_to_responses_request(&limited).is_err());
|
||||
assert!(messages_to_responses_count_request(&limited).is_ok());
|
||||
for field in ["allowed_domains", "blocked_domains"] {
|
||||
let req = object(
|
||||
json!({"model":"m","max_tokens":12,"messages":[{"role":"user","content":"hi"}],"tools":[{"type":"web_search_20250305","name":"web_search",field:["docs.example"]}]}),
|
||||
);
|
||||
let converted = messages_to_responses_request(&req).unwrap();
|
||||
assert_eq!(
|
||||
converted["tools"][0]["filters"][field],
|
||||
json!(["docs.example"])
|
||||
);
|
||||
let back = responses_to_messages_request(&converted, &Default::default()).unwrap();
|
||||
assert_eq!(back["tools"], req["tools"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn allowed_tools_limit_current_turn_without_renaming_history() {
|
||||
let mut req = object(
|
||||
json!({"tools":[{"type":"function","name":"delete"},{"type":"namespace","name":"fs","tools":[{"type":"function","name":"read"}]},{"type":"custom","name":"read"},{"type":"web_search"}],"tool_choice":{"type":"allowed_tools","mode":"required","tools":[{"type":"function","name":"read","namespace":"fs"}]},"parallel_tool_calls":false,"input":[{"type":"function_call","call_id":"c","name":"delete","arguments":"{}"},{"type":"function_call_output","call_id":"c","output":"done"}]}),
|
||||
);
|
||||
let converted = responses_to_messages_request(&req, &Default::default()).unwrap();
|
||||
assert_eq!(converted["tools"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(converted["tools"][0]["name"], "fs__read");
|
||||
assert_eq!(
|
||||
converted["tool_choice"],
|
||||
json!({"type":"any","disable_parallel_tool_use":true})
|
||||
);
|
||||
assert_eq!(converted["messages"][0]["content"][0]["name"], "delete");
|
||||
req["tool_choice"]["tools"] = json!([{"type":"web_search"}]);
|
||||
req["tool_choice"]["mode"] = json!("auto");
|
||||
let converted = responses_to_messages_request(&req, &Default::default()).unwrap();
|
||||
assert_eq!(
|
||||
converted["tools"],
|
||||
json!([{"type":"web_search_20250305","name":"web_search"}])
|
||||
);
|
||||
req["tool_choice"]["tools"] = json!([{"type":"function","name":"missing"}]);
|
||||
assert!(responses_to_messages_request(&req, &Default::default()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_result_continuation_without_thinking_keeps_the_current_mode() {
|
||||
let mut req = object(json!({
|
||||
"tools":[{"type":"function","name":"read"}],
|
||||
"input":[{"type":"function_call","call_id":"c","name":"read","arguments":"{}"},
|
||||
{"type":"function_call_output","call_id":"c","output":"ok"}]
|
||||
}));
|
||||
let convert =
|
||||
|req: &Map<String, Value>| responses_to_messages_request(req, &Default::default()).unwrap();
|
||||
assert_eq!(convert(&req)["thinking"], json!({"type":"disabled"}));
|
||||
req.insert("reasoning".into(), json!({"effort":"high"}));
|
||||
assert_eq!(convert(&req)["thinking"]["type"], "enabled");
|
||||
req.remove("reasoning");
|
||||
req["input"]
|
||||
.as_array_mut()
|
||||
.unwrap()
|
||||
.push(json!({"role":"user","content":"new question"}));
|
||||
assert!(!convert(&req).contains_key("thinking"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn function_only_target_preserves_tool_choice_when_search_is_optional() {
|
||||
use gateway_protocol::anthropic::{MessagesModelCapabilities, responses_to_messages_request};
|
||||
let caps = MessagesModelCapabilities {
|
||||
hosted_web_search: Some(false),
|
||||
..Default::default()
|
||||
};
|
||||
let search = serde_json::json!({"type":"web_search","external_web_access":true});
|
||||
let function = serde_json::json!({"type":"function","name":"pwd"});
|
||||
for (choice, mode) in [
|
||||
(serde_json::json!("auto"), "auto"),
|
||||
(serde_json::json!("required"), "any"),
|
||||
(function.clone(), "tool"),
|
||||
(
|
||||
serde_json::json!({"type":"allowed_tools","mode":"required","tools":[function,search]}),
|
||||
"any",
|
||||
),
|
||||
] {
|
||||
let original =
|
||||
serde_json::json!({"input":"hello","tools":[search,function],"tool_choice":choice});
|
||||
let mapped = responses_to_messages_request(original.as_object().unwrap(), &caps).unwrap();
|
||||
assert_eq!(mapped["tools"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(mapped["tools"][0]["name"], "pwd");
|
||||
assert_eq!(mapped["tool_choice"]["type"], mode);
|
||||
if mode == "tool" {
|
||||
assert_eq!(mapped["tool_choice"]["name"], "pwd")
|
||||
}
|
||||
}
|
||||
let original = serde_json::json!({"input":"hello","tools":[{"type":"web_search","external_web_access":false},function],"tool_choice":{"type":"allowed_tools","mode":"auto","tools":[{"type":"web_search"}]}});
|
||||
let mapped = responses_to_messages_request(original.as_object().unwrap(), &caps).unwrap();
|
||||
assert!(!mapped.contains_key("tools"));
|
||||
assert!(!mapped.contains_key("tool_choice"));
|
||||
fn native_validation_retains_roles_and_extensions() {
|
||||
let request = json!({"model":"model","max_tokens":1024,"messages":[{"role":"user","content":"hello"},{"role":"system","content":[],"output_config":{"effort":"medium"}}]});
|
||||
assert!(validate_request(request.as_object().unwrap()).is_ok());
|
||||
}
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
//! 验证完整响应的停止语义与错误终态
|
||||
|
||||
use gateway_protocol::anthropic::{messages_to_responses_response, responses_to_messages_response};
|
||||
use serde_json::{Map, json};
|
||||
|
||||
#[test]
|
||||
fn stop_reasons_distinguish_incomplete_refusal_pause_and_tools() {
|
||||
for (reason, status, incomplete) in [
|
||||
("max_tokens", "incomplete", Some("max_output_tokens")),
|
||||
(
|
||||
"model_context_window_exceeded",
|
||||
"incomplete",
|
||||
Some("max_output_tokens"),
|
||||
),
|
||||
("refusal", "incomplete", Some("content_filter")),
|
||||
("pause_turn", "completed", None),
|
||||
("tool_use", "completed", None),
|
||||
("end_turn", "completed", None),
|
||||
] {
|
||||
let converted = messages_to_responses_response(
|
||||
&json!({"id":"m1","content":[],"stop_reason":reason,"usage":{}}),
|
||||
&Map::new(),
|
||||
)
|
||||
.expect("停止转换");
|
||||
assert_eq!(converted["status"], status);
|
||||
assert_eq!(
|
||||
converted
|
||||
.pointer("/incomplete_details/reason")
|
||||
.and_then(|v| v.as_str()),
|
||||
incomplete
|
||||
);
|
||||
assert_eq!(
|
||||
converted.get("end_turn").and_then(|v| v.as_bool()),
|
||||
(reason == "pause_turn").then_some(false)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upstream_errors_remain_errors_in_both_directions() {
|
||||
let response = messages_to_responses_response(
|
||||
&json!({"type":"error","error":{"type":"overloaded_error","message":"Busy."}}),
|
||||
&Map::new(),
|
||||
)
|
||||
.expect("错误转换");
|
||||
assert_eq!(response["status"], "failed");
|
||||
let message = responses_to_messages_response(&response, &Map::new()).expect("错误回转");
|
||||
assert_eq!(message["type"], "error");
|
||||
assert_eq!(message["error"]["message"], "Busy.");
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
//! SSE 增量转换和聚合的测试入口
|
||||
|
||||
mod accumulator;
|
||||
mod translation;
|
||||
|
||||
@@ -1,292 +0,0 @@
|
||||
//! 验证双向增量输出与完整 JSON 语义一致
|
||||
|
||||
use gateway_protocol::anthropic::{
|
||||
MessagesAccumulator, MessagesToResponsesStream, ResponsesToMessagesStream,
|
||||
messages_to_responses_response, responses_to_messages_response,
|
||||
};
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
#[test]
|
||||
fn messages_stream_emits_live_text_and_final_cache_usage() {
|
||||
let request = Map::from_iter([("model".into(), json!("alias"))]);
|
||||
let mut stream = MessagesToResponsesStream::new(&request);
|
||||
let mut events = Vec::new();
|
||||
for event in [
|
||||
json!({"type":"message_start","message":{"id":"m1","model":"upstream","content":[],"usage":{"input_tokens":4,"output_tokens":0,"cache_read_input_tokens":8}}}),
|
||||
json!({"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}),
|
||||
json!({"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hello"}}),
|
||||
json!({"type":"content_block_stop","index":0}),
|
||||
json!({"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":3}}),
|
||||
json!({"type":"message_stop"}),
|
||||
] {
|
||||
events.extend(stream.push(&event).expect("转换事件"));
|
||||
}
|
||||
stream.finish().expect("终态完整");
|
||||
assert!(events.iter().any(|event|event["type"]=="response.output_text.delta" && event["delta"]=="hello"));
|
||||
for (index, event) in events.iter().enumerate() {
|
||||
assert_eq!(event["sequence_number"], index);
|
||||
}
|
||||
let final_response = &events.last().expect("结束事件")["response"];
|
||||
let expected=messages_to_responses_response(&json!({"id":"m1","content":[{"type":"text","text":"hello"}],"stop_reason":"end_turn","usage":{"input_tokens":4,"output_tokens":3,"cache_read_input_tokens":8}}),&request).expect("JSON响应");
|
||||
assert_eq!(final_response, &expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_tools_use_custom_events_and_restore_string_input() {
|
||||
let request = json!({"model":"alias","tools":[{"type":"custom","name":"shell"}]})
|
||||
.as_object()
|
||||
.expect("请求对象")
|
||||
.clone();
|
||||
let mut stream = MessagesToResponsesStream::new(&request);
|
||||
let mut events = Vec::new();
|
||||
for event in [
|
||||
json!({"type":"message_start","message":{"id":"m1","content":[],"usage":{}}}),
|
||||
json!({"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"c1","name":"shell","input":{}}}),
|
||||
json!({"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\"input\":\"pwd\"}"}}),
|
||||
json!({"type":"content_block_stop","index":0}),
|
||||
json!({"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{}}),
|
||||
json!({"type":"message_stop"}),
|
||||
] {
|
||||
events.extend(stream.push(&event).expect("工具转换"));
|
||||
}
|
||||
assert!(events.iter().any(
|
||||
|event| event["type"] == "response.custom_tool_call_input.delta" && event["delta"] == "pwd"
|
||||
));
|
||||
assert!(
|
||||
!events
|
||||
.iter()
|
||||
.any(|event| event["type"] == "response.function_call_arguments.delta")
|
||||
);
|
||||
assert_eq!(
|
||||
events.last().expect("结束事件")["response"]["output"][0]["input"],
|
||||
"pwd"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn responses_thinking_uses_final_signature_without_replaying_text() {
|
||||
let request = Map::from_iter([("model".into(), json!("alias"))]);
|
||||
let item = json!({"type":"reasoning","id":"reason1","summary":[{"type":"summary_text","text":"thought"}],"encrypted_content":"gAAAAsigned"});
|
||||
let response = json!({"id":"r1","model":"upstream","status":"completed","output":[item],"usage":{"input_tokens":12,"output_tokens":4,"input_tokens_details":{"cached_tokens":2}}});
|
||||
let mut stream = ResponsesToMessagesStream::new(&request);
|
||||
let mut events = Vec::new();
|
||||
for event in [
|
||||
json!({"type":"response.created","response":{"id":"r1"}}),
|
||||
json!({"type":"response.output_item.added","output_index":0,"item":{"type":"reasoning","id":"reason1","summary":[]}}),
|
||||
json!({"type":"response.reasoning_summary_text.delta","output_index":0,"summary_index":0,"delta":"thought"}),
|
||||
json!({"type":"response.output_item.done","output_index":0,"item":item}),
|
||||
json!({"type":"response.completed","response":response}),
|
||||
] {
|
||||
events.extend(stream.push(&event).expect("思考转换"));
|
||||
}
|
||||
stream.finish().expect("终态完整");
|
||||
assert_eq!(
|
||||
events
|
||||
.iter()
|
||||
.filter(|event| event.pointer("/delta/type") == Some(&json!("thinking_delta")))
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
events
|
||||
.iter()
|
||||
.filter(|event| event.pointer("/delta/type") == Some(&json!("signature_delta")))
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
let mut accumulator = MessagesAccumulator::default();
|
||||
let mut final_message = None;
|
||||
for event in events {
|
||||
if let Some(message) = accumulator.push(&event).expect("聚合转换流") {
|
||||
final_message = Some(message);
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
final_message.expect("终态消息"),
|
||||
responses_to_messages_response(&response, &request).expect("完整响应转换")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn responses_json_only_terminal_synthesizes_content_and_stops() {
|
||||
let request = Map::from_iter([("model".into(), json!("alias"))]);
|
||||
let response = json!({"id":"r1","status":"incomplete","incomplete_details":{"reason":"max_output_tokens"},"output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"partial"}]}],"usage":{"input_tokens":2,"output_tokens":1}});
|
||||
let mut stream = ResponsesToMessagesStream::new(&request);
|
||||
let events = stream
|
||||
.push(&json!({"type":"response.incomplete","response":response}))
|
||||
.expect("完整终态");
|
||||
let mut accumulator = MessagesAccumulator::default();
|
||||
let mut final_message = Value::Null;
|
||||
for event in events {
|
||||
if let Some(message) = accumulator.push(&event).expect("聚合消息") {
|
||||
final_message = message;
|
||||
}
|
||||
}
|
||||
assert_eq!(final_message["content"][0]["text"], "partial");
|
||||
assert_eq!(final_message["stop_reason"], "max_tokens");
|
||||
stream.finish().expect("不完整生成也是完整协议终态");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_errors_and_truncated_streams_are_distinct() {
|
||||
let mut to_messages = ResponsesToMessagesStream::new(&Map::new());
|
||||
assert!(to_messages.finish().is_err());
|
||||
let events=to_messages.push(&json!({"type":"response.failed","response":{"error":{"type":"server_error","message":"Failed."}}})).expect("错误转换");
|
||||
assert_eq!(events[0]["type"], "error");
|
||||
assert!(to_messages.finish().is_ok());
|
||||
let mut to_responses = MessagesToResponsesStream::new(&Map::new());
|
||||
assert!(to_responses.finish().is_err());
|
||||
let events = to_responses
|
||||
.push(&json!({"type":"error","error":{"type":"overloaded_error","message":"Busy."}}))
|
||||
.expect("错误转换");
|
||||
assert_eq!(events[0]["type"], "response.failed");
|
||||
assert!(to_responses.finish().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interrupted_function_arguments_wait_for_stop_reason_and_keep_raw_input() {
|
||||
for reason in ["max_tokens", "model_context_window_exceeded", "tool_use"] {
|
||||
let mut stream = MessagesToResponsesStream::new(&Map::new());
|
||||
let mut events = Vec::new();
|
||||
let arguments = "{\n \"value\": \"未完成";
|
||||
for event in [
|
||||
json!({"type":"message_start","message":{"id":"m1","content":[],"usage":{"input_tokens":7}}}),
|
||||
json!({"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"c1","name":"lookup","input":{}}}),
|
||||
json!({"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":arguments}}),
|
||||
json!({"type":"content_block_stop","index":0}),
|
||||
json!({"type":"content_block_start","index":1,"content_block":{"type":"text","text":"partial answer"}}),
|
||||
json!({"type":"content_block_stop","index":1}),
|
||||
json!({"type":"message_delta","delta":{"stop_reason":reason},"usage":{"output_tokens":5}}),
|
||||
] {
|
||||
events.extend(stream.push(&event).expect("等待消息终态"));
|
||||
}
|
||||
assert!(stream.finish().is_err());
|
||||
assert!(
|
||||
!events
|
||||
.iter()
|
||||
.any(|event| event["type"] == "response.function_call_arguments.done")
|
||||
);
|
||||
events.extend(
|
||||
stream
|
||||
.push(&json!({"type":"message_stop"}))
|
||||
.expect("保留上游终态"),
|
||||
);
|
||||
stream.finish().expect("工具输入不影响协议终态");
|
||||
let final_event = events.last().unwrap();
|
||||
let expected_status = if reason == "tool_use" {
|
||||
"completed"
|
||||
} else {
|
||||
"incomplete"
|
||||
};
|
||||
assert_eq!(final_event["type"], format!("response.{expected_status}"));
|
||||
if reason != "tool_use" {
|
||||
assert_eq!(
|
||||
final_event["response"]["incomplete_details"]["reason"],
|
||||
"max_output_tokens"
|
||||
);
|
||||
}
|
||||
assert_eq!(final_event["response"]["output"][0]["arguments"], arguments);
|
||||
assert_eq!(
|
||||
final_event["response"]["output"][0]["status"],
|
||||
expected_status
|
||||
);
|
||||
assert_eq!(
|
||||
final_event["response"]["output"][1]["content"][0]["text"],
|
||||
"partial answer"
|
||||
);
|
||||
assert_eq!(final_event["response"]["usage"]["output_tokens"], 5);
|
||||
assert!(events.iter().any(|event| event["type"]
|
||||
== "response.function_call_arguments.done"
|
||||
&& event["arguments"] == arguments));
|
||||
for (index, event) in events.iter().enumerate() {
|
||||
assert_eq!(event["sequence_number"], index);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incomplete_custom_input_preserves_decoded_prefix_and_unfinished_escapes() {
|
||||
let request = json!({"tools":[{"type":"custom","name":"shell"}]})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone();
|
||||
for (arguments, expected) in [
|
||||
(
|
||||
r#"{"input":"printf\n值\uD83D\uDE00tail\"#,
|
||||
"printf\n值😀tail\\",
|
||||
),
|
||||
(r#"{"input":"x\uD83D\u"#, r"x\uD83D\u"),
|
||||
(r#"{"input":"finished""#, "finished"),
|
||||
("{", "{"),
|
||||
] {
|
||||
let mut stream = MessagesToResponsesStream::new(&request);
|
||||
let mut events = Vec::new();
|
||||
for event in [
|
||||
json!({"type":"message_start","message":{"id":"m1","content":[],"usage":{}}}),
|
||||
json!({"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"c1","name":"shell","input":{}}}),
|
||||
json!({"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":arguments}}),
|
||||
json!({"type":"content_block_stop","index":0}),
|
||||
json!({"type":"message_delta","delta":{"stop_reason":"max_tokens"},"usage":{}}),
|
||||
json!({"type":"message_stop"}),
|
||||
] {
|
||||
events.extend(stream.push(&event).expect("截断 custom 工具"));
|
||||
}
|
||||
let item = &events.last().unwrap()["response"]["output"][0];
|
||||
assert_eq!(item["type"], "custom_tool_call");
|
||||
assert_eq!(item["status"], "incomplete");
|
||||
assert_eq!(item["input"], expected);
|
||||
assert!(events.iter().any(|event| event["type"]
|
||||
== "response.custom_tool_call_input.delta"
|
||||
&& event["delta"] == expected));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn complete_function_arguments_keep_the_original_serialization() {
|
||||
let arguments = "{ \"number\": 1.00, \"text\": \"\\u0061\" }";
|
||||
let mut stream = MessagesToResponsesStream::new(&Map::new());
|
||||
let mut events = Vec::new();
|
||||
for event in [
|
||||
json!({"type":"message_start","message":{"id":"m1","content":[],"usage":{}}}),
|
||||
json!({"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"c1","name":"lookup","input":{}}}),
|
||||
json!({"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":arguments}}),
|
||||
json!({"type":"content_block_stop","index":0}),
|
||||
json!({"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{}}),
|
||||
json!({"type":"message_stop"}),
|
||||
] {
|
||||
events.extend(stream.push(&event).unwrap());
|
||||
}
|
||||
assert!(events.iter().any(
|
||||
|event| event["type"] == "response.function_call_arguments.done"
|
||||
&& event["arguments"] == arguments
|
||||
));
|
||||
assert_eq!(
|
||||
events.last().unwrap()["response"]["output"][0]["arguments"],
|
||||
arguments
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminal_uses_delivered_tool_when_output_is_not_repeated() {
|
||||
for (terminal, expected) in [
|
||||
(json!({"id":"r","status":"completed"}), "tool_use"),
|
||||
(
|
||||
json!({"id":"r","status":"completed","output":[]}),
|
||||
"tool_use",
|
||||
),
|
||||
(
|
||||
json!({"id":"r","status":"incomplete","incomplete_details":{"reason":"max_output_tokens"}}),
|
||||
"max_tokens",
|
||||
),
|
||||
] {
|
||||
let mut stream = ResponsesToMessagesStream::new(&Map::new());
|
||||
let done=stream.push(&json!({"type":"response.output_item.done","output_index":0,"item":{"type":"function_call","call_id":"c","name":"read","arguments":"{}"}})).unwrap();
|
||||
assert!(
|
||||
done.iter()
|
||||
.any(|e| e.pointer("/content_block/type") == Some(&json!("tool_use")))
|
||||
);
|
||||
let events=stream.push(&json!({"type":format!("response.{}",terminal["status"].as_str().unwrap()),"response":terminal})).unwrap();
|
||||
assert_eq!(events[0]["delta"]["stop_reason"], expected);
|
||||
assert_eq!(events[1]["type"], "message_stop");
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,7 @@
|
||||
//! 验证 Messages 缓存用量合并与统一输入量
|
||||
|
||||
use gateway_protocol::anthropic::{MessageUsage, messages_to_responses_response};
|
||||
use gateway_protocol::openai::events::{billable_usage_is_complete, extract_usage};
|
||||
use serde_json::{Map, json};
|
||||
use gateway_protocol::anthropic::MessageUsage;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn usage_deltas_replace_counters_and_keep_cache_facts() {
|
||||
@@ -13,15 +12,3 @@ fn usage_deltas_replace_counters_and_keep_cache_facts() {
|
||||
assert_eq!(usage.total_input_tokens(), Some(34));
|
||||
assert_eq!(usage.output_tokens, Some(9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converted_usage_matches_canonical_cache_write_accounting() {
|
||||
let converted=messages_to_responses_response(&json!({"id":"m1","content":[],"stop_reason":"end_turn","usage":{"input_tokens":4,"output_tokens":9,"cache_read_input_tokens":20,"cache_creation_input_tokens":10}}),&Map::new()).expect("用量转换");
|
||||
assert!(converted["usage"].get("output_tokens_details").is_none());
|
||||
let usage = extract_usage(&converted).expect("提取统一用量");
|
||||
assert_eq!(usage.input_tokens, 34);
|
||||
assert_eq!(usage.cache_write_input_tokens, 10);
|
||||
assert_eq!(usage.cached_input_tokens, 20);
|
||||
assert_eq!(usage.total_tokens, 43);
|
||||
assert!(billable_usage_is_complete(&converted, usage));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
//! genai 直接映射合同
|
||||
|
||||
mod request;
|
||||
mod response;
|
||||
mod stream;
|
||||
@@ -0,0 +1,102 @@
|
||||
//! Chat 到 GenAI 直接请求支持多模态和工具轮次
|
||||
|
||||
use gateway_protocol::chat_completions::genai::convert_request;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn maps_system_media_and_tools_without_an_intermediate_platform() {
|
||||
let chat = json!({"model":"gemini","messages":[{"role":"developer","content":"brief"},{"role":"user","content":[{"type":"text","text":"look"},{"type":"image_url","image_url":{"url":"data:image/png;base64,AA=="}},{"type":"input_audio","input_audio":{"data":"QQ==","format":"mp3"}},{"type":"file","file":{"filename":"a.pdf","file_data":"data:application/pdf;base64,QQ=="}}]},{"role":"assistant","content":null,"tool_calls":[{"id":"a","type":"custom","custom":{"name":"shell","input":"pwd"}}]},{"role":"tool","tool_call_id":"a","content":"directory"}],"tools":[{"type":"custom","custom":{"name":"shell"}}],"tool_choice":"required","max_completion_tokens":256,"reasoning_effort":"low"});
|
||||
let result = convert_request(chat.as_object().unwrap()).unwrap();
|
||||
assert_eq!(result["systemInstruction"]["parts"][0]["text"], "brief");
|
||||
assert_eq!(
|
||||
result["contents"][0]["parts"][1]["inlineData"]["mimeType"],
|
||||
"image/png"
|
||||
);
|
||||
assert_eq!(
|
||||
result["contents"][0]["parts"][2]["inlineData"]["mimeType"],
|
||||
"audio/mpeg"
|
||||
);
|
||||
assert_eq!(
|
||||
result["contents"][0]["parts"][3]["inlineData"]["mimeType"],
|
||||
"application/pdf"
|
||||
);
|
||||
assert_eq!(
|
||||
result["contents"][1]["parts"][0]["functionCall"]["args"],
|
||||
json!({"input":"pwd"})
|
||||
);
|
||||
assert_eq!(
|
||||
result["contents"][1]["parts"][0]["thoughtSignature"],
|
||||
"skip_thought_signature_validator"
|
||||
);
|
||||
assert_eq!(
|
||||
result["contents"][2]["parts"][0]["functionResponse"]["name"],
|
||||
"shell"
|
||||
);
|
||||
assert_eq!(result["generationConfig"]["maxOutputTokens"], 256);
|
||||
assert_eq!(
|
||||
result["generationConfig"]["thinkingConfig"]["thinkingBudget"],
|
||||
1024
|
||||
);
|
||||
assert_eq!(
|
||||
result["toolConfig"]["functionCallingConfig"],
|
||||
json!({"mode":"ANY","allowedFunctionNames":["shell"]})
|
||||
);
|
||||
for field in ["messages", "input", "max_tokens"] {
|
||||
assert!(!result.contains_key(field));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn structured_output_preserves_json_schema_and_explicit_logprobs() {
|
||||
let mut request = super::super::request();
|
||||
request.insert("response_format".into(),json!({"type":"json_schema","json_schema":{"name":"result","schema":{"type":"object","additionalProperties":false,"properties":{"kind":{"const":"x"}}}}}));
|
||||
request.insert("logprobs".into(), json!(true));
|
||||
request.insert("top_logprobs".into(), json!(2));
|
||||
let result = convert_request(&request).unwrap();
|
||||
assert_eq!(
|
||||
result["generationConfig"]["responseJsonSchema"],
|
||||
request["response_format"]["json_schema"]["schema"]
|
||||
);
|
||||
assert_eq!(result["generationConfig"]["responseLogprobs"], true);
|
||||
assert_eq!(result["generationConfig"]["logprobs"], 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hosted_search_is_generated_directly_and_constraints_are_not_silently_dropped() {
|
||||
let mut request = super::super::request();
|
||||
request.insert("web_search_options".into(), json!({}));
|
||||
assert_eq!(
|
||||
convert_request(&request).unwrap()["tools"],
|
||||
json!([{"googleSearch":{}}])
|
||||
);
|
||||
request["web_search_options"]["user_location"] =
|
||||
json!({"type":"approximate","approximate":{"city":"Paris"}});
|
||||
assert!(convert_request(&request).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn orphan_tool_results_and_untyped_remote_media_are_rejected() {
|
||||
for messages in [
|
||||
json!([{"role":"tool","tool_call_id":"orphan","content":"result"}]),
|
||||
json!([{"role":"user","content":[{"type":"image_url","image_url":{"url":"https://example.com/image"}}]}]),
|
||||
] {
|
||||
let mut request = super::super::request();
|
||||
request.insert("messages".into(), messages);
|
||||
assert!(convert_request(&request).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_context_without_a_genai_equivalent_is_not_silently_ignored() {
|
||||
for size in ["low", "medium", "high"] {
|
||||
let mut request = super::super::request();
|
||||
request.insert(
|
||||
"web_search_options".into(),
|
||||
json!({"search_context_size":size}),
|
||||
);
|
||||
assert_eq!(
|
||||
convert_request(&request).unwrap_err().parameter(),
|
||||
Some("web_search_options.search_context_size")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
//! GenAI 结果的工具、用量、Unicode 引用和安全终态
|
||||
|
||||
use gateway_protocol::chat_completions::genai::{project_response, project_response_with_request};
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn projects_custom_calls_reasoning_and_native_usage_directly() {
|
||||
let mut request = super::super::request();
|
||||
request.insert(
|
||||
"tools".into(),
|
||||
json!([{"type":"custom","custom":{"name":"shell"}}]),
|
||||
);
|
||||
let native = json!({"candidates":[{"content":{"parts":[{"thought":true,"text":"reason","thoughtSignature":"private"},{"text":"answer"},{"functionCall":{"id":"a","name":"shell","args":{"input":"pwd"}}}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":3,"toolUsePromptTokenCount":2,"candidatesTokenCount":5,"thoughtsTokenCount":7,"cachedContentTokenCount":1,"totalTokenCount":17}});
|
||||
let result =
|
||||
project_response_with_request(&native, &super::super::identity(), &request).unwrap();
|
||||
assert_eq!(result["choices"][0]["finish_reason"], "tool_calls");
|
||||
assert_eq!(
|
||||
result["choices"][0]["message"]["tool_calls"][0],
|
||||
json!({"id":"a","type":"custom","custom":{"name":"shell","input":"pwd"}})
|
||||
);
|
||||
assert_eq!(
|
||||
result["choices"][0]["message"]["reasoning_content"],
|
||||
"reason"
|
||||
);
|
||||
assert_eq!(result["usage"]["prompt_tokens"], 5);
|
||||
assert_eq!(result["usage"]["completion_tokens"], 12);
|
||||
assert_eq!(
|
||||
result["usage"]["completion_tokens_details"]["reasoning_tokens"],
|
||||
7
|
||||
);
|
||||
assert!(!result.to_string().contains("private"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grounding_converts_byte_offsets_to_chat_character_offsets() {
|
||||
let native = json!({"candidates":[{"content":{"parts":[{"text":"你好🌍"}]},"finishReason":"STOP","groundingMetadata":{"groundingChunks":[{"web":{"uri":"https://example.com","title":"source"}}],"groundingSupports":[{"segment":{"startIndex":3,"endIndex":10,"text":"好🌍"},"groundingChunkIndices":[0]}]}}]});
|
||||
let result = project_response(&native, &super::super::identity()).unwrap();
|
||||
assert_eq!(
|
||||
result["choices"][0]["message"]["annotations"][0]["url_citation"],
|
||||
json!({"url":"https://example.com","title":"source","start_index":1,"end_index":3})
|
||||
);
|
||||
assert!(result.get("usage").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocked_prompts_and_errors_are_not_normal_successes() {
|
||||
let result = project_response(
|
||||
&json!({"promptFeedback":{"blockReason":"SAFETY"}}),
|
||||
&super::super::identity(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(result["choices"][0]["finish_reason"], "content_filter");
|
||||
let error = json!({"error":{"code":429,"status":"RESOURCE_EXHAUSTED","message":"busy"}});
|
||||
assert_eq!(
|
||||
project_response(&error, &super::super::identity()).unwrap(),
|
||||
error
|
||||
);
|
||||
assert!(
|
||||
project_response(
|
||||
&json!({"candidates":[{"content":{"parts":[{"text":"partial"}]}}]}),
|
||||
&super::super::identity()
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
//! GenAI 流只在终态候选后的 EOF 交付结束和累计用量
|
||||
|
||||
use gateway_protocol::chat_completions::{ChatAccumulator, ChatError, genai::ChatStreamEncoder};
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn usage_after_finish_reason_is_included_once_at_eof() {
|
||||
let mut encoder = ChatStreamEncoder::new(super::super::identity(), true);
|
||||
let mut accumulator = ChatAccumulator::default();
|
||||
for event in [
|
||||
json!({"candidates":[{"content":{"parts":[{"text":"hello "}]}}]}),
|
||||
json!({"candidates":[{"content":{"parts":[{"text":"world"}]},"finishReason":"STOP"}]}),
|
||||
json!({"usageMetadata":{"promptTokenCount":3,"candidatesTokenCount":5,"totalTokenCount":8}}),
|
||||
] {
|
||||
let chunks = encoder.push_event(None, &event).unwrap();
|
||||
assert!(
|
||||
chunks
|
||||
.iter()
|
||||
.all(|v| v["choices"][0]["finish_reason"].is_null())
|
||||
);
|
||||
for chunk in chunks {
|
||||
accumulator.push(&chunk).unwrap();
|
||||
}
|
||||
}
|
||||
assert!(!encoder.is_completed());
|
||||
for chunk in encoder.finish().unwrap() {
|
||||
accumulator.push(&chunk).unwrap();
|
||||
}
|
||||
assert!(encoder.is_completed());
|
||||
assert!(encoder.finish().unwrap().is_empty());
|
||||
let result = accumulator.finish().unwrap();
|
||||
assert_eq!(result["choices"][0]["message"]["content"], "hello world");
|
||||
assert_eq!(result["usage"]["total_tokens"], 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_candidates_and_content_after_finished_are_rejected() {
|
||||
let mut encoder = ChatStreamEncoder::new(super::super::identity(), false);
|
||||
assert_eq!(encoder.finish().unwrap_err(), ChatError::IncompleteStream);
|
||||
assert!(
|
||||
encoder
|
||||
.push_event(
|
||||
None,
|
||||
&json!({"candidates":[{"index":1,"finishReason":"STOP"}]})
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
let mut encoder = ChatStreamEncoder::new(super::super::identity(), false);
|
||||
encoder
|
||||
.push_event(None, &json!({"candidates":[{"finishReason":"STOP"}]}))
|
||||
.unwrap();
|
||||
assert!(
|
||||
encoder
|
||||
.push_event(
|
||||
None,
|
||||
&json!({"candidates":[{"content":{"parts":[{"text":"late"}]}}]})
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn required_search_needs_upstream_grounding_evidence() {
|
||||
let mut request = super::super::request();
|
||||
request.insert("web_search_options".into(), json!({}));
|
||||
let mut encoder = ChatStreamEncoder::with_request(super::super::identity(), false, &request);
|
||||
encoder.push_event(None,&json!({"candidates":[{"content":{"parts":[{"text":"answer"}]},"finishReason":"STOP"}]})).unwrap();
|
||||
assert_eq!(encoder.finish().unwrap_err(), ChatError::InvalidResponse);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
//! messages 直接映射合同
|
||||
|
||||
mod request;
|
||||
mod response;
|
||||
mod stream;
|
||||
@@ -0,0 +1,110 @@
|
||||
//! Chat 到 Messages 的工具、媒体、能力和生成设置合同
|
||||
|
||||
use gateway_protocol::{
|
||||
anthropic::MessagesModelCapabilities, chat_completions::messages::convert_request,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn maps_multimodal_conversation_and_tool_results_directly() {
|
||||
let request = json!({"model":"claude","messages":[{"role":"system","content":"brief"},{"role":"user","content":[{"type":"image_url","image_url":{"url":"data:image/png;base64,AA=="}},{"type":"file","file":{"filename":"a.pdf","file_data":"data:application/pdf;base64,QQ=="}}]},{"role":"assistant","content":null,"tool_calls":[{"id":"a","type":"function","function":{"name":"lookup","arguments":"{\"q\":1}"}},{"id":"b","type":"custom","custom":{"name":"shell","input":"pwd"}}]},{"role":"tool","tool_call_id":"a","content":"result"},{"role":"tool","tool_call_id":"b","content":"directory"}],"tools":[{"type":"function","function":{"name":"lookup","parameters":{"type":"object"}}},{"type":"custom","custom":{"name":"shell"}}],"parallel_tool_calls":false});
|
||||
let result = convert_request(
|
||||
request.as_object().unwrap(),
|
||||
&MessagesModelCapabilities::default(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(result["system"][0]["text"], "brief");
|
||||
assert_eq!(
|
||||
result["messages"][0]["content"][0]["source"]["media_type"],
|
||||
"image/png"
|
||||
);
|
||||
assert_eq!(result["messages"][0]["content"][1]["type"], "document");
|
||||
assert_eq!(
|
||||
result["messages"][1]["content"][1]["input"],
|
||||
json!({"input":"pwd"})
|
||||
);
|
||||
assert_eq!(
|
||||
result["messages"][2]["content"].as_array().unwrap().len(),
|
||||
2
|
||||
);
|
||||
assert_eq!(result["messages"][2]["content"][0]["tool_use_id"], "a");
|
||||
assert_eq!(
|
||||
result["tool_choice"],
|
||||
json!({"type":"auto","disable_parallel_tool_use":true})
|
||||
);
|
||||
assert!(result.get("input").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_capabilities_drive_budget_and_adaptive_reasoning() {
|
||||
let mut request = super::super::request();
|
||||
request.insert("reasoning_effort".into(), json!("high"));
|
||||
request.insert("max_completion_tokens".into(), json!(5000));
|
||||
request.insert(
|
||||
"response_format".into(),
|
||||
json!({"type":"json_schema","json_schema":{"name":"answer","schema":{"type":"object"}}}),
|
||||
);
|
||||
request.insert("temperature".into(), json!(0.8));
|
||||
let capabilities = MessagesModelCapabilities {
|
||||
adaptive_thinking: Some(true),
|
||||
max_tokens: Some(4000),
|
||||
efforts: Some(vec!["high".into()]),
|
||||
..Default::default()
|
||||
};
|
||||
let result = convert_request(&request, &capabilities).unwrap();
|
||||
assert_eq!(result["max_tokens"], 4000);
|
||||
assert_eq!(result["thinking"], json!({"type":"adaptive"}));
|
||||
assert_eq!(
|
||||
result["output_config"],
|
||||
json!({"effort":"high","format":{"type":"json_schema","schema":{"type":"object"}}})
|
||||
);
|
||||
assert!(!result.contains_key("temperature"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forced_tool_and_reasoning_cannot_silently_change_user_policy() {
|
||||
let mut request = super::super::request();
|
||||
request.insert("reasoning_effort".into(), json!("high"));
|
||||
request.insert(
|
||||
"tools".into(),
|
||||
json!([{"type":"function","function":{"name":"f"}}]),
|
||||
);
|
||||
request.insert("tool_choice".into(), json!("required"));
|
||||
let error = convert_request(&request, &MessagesModelCapabilities::default()).unwrap_err();
|
||||
assert_eq!(error.parameter(), Some("reasoning_effort"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hosted_search_is_only_enabled_by_selected_model_capability() {
|
||||
let mut request = super::super::request();
|
||||
request.insert(
|
||||
"web_search_options".into(),
|
||||
json!({"user_location":{"type":"approximate","approximate":{"city":"Paris"}}}),
|
||||
);
|
||||
assert!(convert_request(&request, &MessagesModelCapabilities::default()).is_err());
|
||||
let capabilities = MessagesModelCapabilities {
|
||||
hosted_web_search: Some(true),
|
||||
..Default::default()
|
||||
};
|
||||
let result = convert_request(&request, &capabilities).unwrap();
|
||||
assert_eq!(
|
||||
result["tools"][0]["user_location"],
|
||||
json!({"type":"approximate","city":"Paris"})
|
||||
);
|
||||
assert_eq!(
|
||||
result["tool_choice"],
|
||||
json!({"type":"tool","name":"web_search"})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn orphan_results_and_unrepresentable_audio_are_rejected() {
|
||||
for messages in [
|
||||
json!([{"role":"tool","tool_call_id":"orphan","content":"result"}]),
|
||||
json!([{"role":"user","content":[{"type":"input_audio","input_audio":{"data":"AA==","format":"wav"}}]}]),
|
||||
] {
|
||||
let mut request = super::super::request();
|
||||
request.insert("messages".into(), messages);
|
||||
assert!(convert_request(&request, &MessagesModelCapabilities::default()).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
//! Messages JSON 的 Chat 投影保留工具身份和原生用量
|
||||
|
||||
use gateway_protocol::chat_completions::messages::{
|
||||
project_response, project_response_with_request,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn projects_text_reasoning_custom_tools_citations_and_cache_usage() {
|
||||
let mut request = super::super::request();
|
||||
request.insert(
|
||||
"tools".into(),
|
||||
json!([{"type":"custom","custom":{"name":"shell"}}]),
|
||||
);
|
||||
let native = json!({"type":"message","role":"assistant","content":[{"type":"thinking","thinking":"reason","signature":"private"},{"type":"text","text":"answer","citations":[{"type":"web_search_result_location","url":"https://example.com","title":"example"}]},{"type":"tool_use","id":"a","name":"shell","input":{"input":"pwd"}}],"stop_reason":"tool_use","usage":{"input_tokens":3,"cache_read_input_tokens":5,"cache_creation_input_tokens":7,"output_tokens":11}});
|
||||
let result =
|
||||
project_response_with_request(&native, &super::super::identity(), &request).unwrap();
|
||||
let message = &result["choices"][0]["message"];
|
||||
assert_eq!(message["content"], "answer");
|
||||
assert_eq!(message["reasoning_content"], "reason");
|
||||
assert_eq!(
|
||||
message["tool_calls"][0],
|
||||
json!({"id":"a","type":"custom","custom":{"name":"shell","input":"pwd"}})
|
||||
);
|
||||
assert_eq!(message["annotations"][0]["url_citation"]["end_index"], 6);
|
||||
assert_eq!(result["usage"]["prompt_tokens"], 15);
|
||||
assert_eq!(result["usage"]["total_tokens"], 26);
|
||||
assert_eq!(
|
||||
result["usage"]["prompt_tokens_details"]["cache_write_tokens"],
|
||||
7
|
||||
);
|
||||
assert!(!result.to_string().contains("private"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_usage_is_unknown_and_stop_reasons_are_explicit() {
|
||||
for (native, chat) in [
|
||||
("end_turn", "stop"),
|
||||
("tool_use", "tool_calls"),
|
||||
("max_tokens", "length"),
|
||||
("refusal", "content_filter"),
|
||||
] {
|
||||
let result = project_response(
|
||||
&json!({"type":"message","role":"assistant","content":[],"stop_reason":native}),
|
||||
&super::super::identity(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(result["choices"][0]["finish_reason"], chat);
|
||||
assert!(result.get("usage").is_none());
|
||||
}
|
||||
assert!(
|
||||
project_response(
|
||||
&json!({"type":"message","role":"assistant","content":[]}),
|
||||
&super::super::identity()
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
//! Messages SSE 的块顺序、终态、工具与累计用量合同
|
||||
|
||||
use gateway_protocol::anthropic::message_to_stream_events;
|
||||
use gateway_protocol::chat_completions::{
|
||||
ChatAccumulator, ChatError,
|
||||
messages::{ChatStreamEncoder, project_response_with_request},
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
#[test]
|
||||
fn native_json_and_stream_produce_the_same_chat_result() {
|
||||
let mut request = super::super::request();
|
||||
request.insert(
|
||||
"tools".into(),
|
||||
json!([{"type":"custom","custom":{"name":"shell"}}]),
|
||||
);
|
||||
let native = json!({"id":"native","type":"message","role":"assistant","content":[{"type":"text","text":"answer"},{"type":"thinking","thinking":"reason","signature":"private"},{"type":"tool_use","id":"a","name":"shell","input":{"input":"pwd"}}],"stop_reason":"tool_use","usage":{"input_tokens":3,"output_tokens":7}});
|
||||
let identity = super::super::identity();
|
||||
let expected = project_response_with_request(&native, &identity, &request).unwrap();
|
||||
let mut encoder = ChatStreamEncoder::with_request(identity, true, &request);
|
||||
let mut accumulator = ChatAccumulator::default();
|
||||
for event in message_to_stream_events(native).unwrap() {
|
||||
for chunk in encoder.push_event(None, &event).unwrap() {
|
||||
accumulator.push(&chunk).unwrap();
|
||||
}
|
||||
}
|
||||
assert!(encoder.is_completed());
|
||||
assert!(encoder.finish().unwrap().is_empty());
|
||||
assert_eq!(accumulator.finish().unwrap(), expected);
|
||||
}
|
||||
|
||||
fn start() -> Value {
|
||||
json!({"type":"message_start","message":{"type":"message","role":"assistant","content":[],"usage":{"input_tokens":3,"output_tokens":0}}})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streams_function_arguments_and_defers_custom_json_unwrapping_until_block_stop() {
|
||||
let mut request = super::super::request();
|
||||
request.insert(
|
||||
"tools".into(),
|
||||
json!([{"type":"custom","custom":{"name":"shell"}}]),
|
||||
);
|
||||
let mut encoder = ChatStreamEncoder::with_request(super::super::identity(), true, &request);
|
||||
let mut accumulator = ChatAccumulator::default();
|
||||
for event in [
|
||||
start(),
|
||||
json!({"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"a","name":"shell","input":{}}}),
|
||||
json!({"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\"input\":\"echo \\"}}),
|
||||
json!({"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"\"ok\\\"\"}"}}),
|
||||
json!({"type":"content_block_stop","index":0}),
|
||||
json!({"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":9}}),
|
||||
json!({"type":"message_stop"}),
|
||||
] {
|
||||
for chunk in encoder.push_event(None, &event).unwrap() {
|
||||
accumulator.push(&chunk).unwrap();
|
||||
}
|
||||
}
|
||||
let result = accumulator.finish().unwrap();
|
||||
assert_eq!(
|
||||
result["choices"][0]["message"]["tool_calls"][0]["custom"]["input"],
|
||||
"echo \"ok\""
|
||||
);
|
||||
assert_eq!(result["usage"]["completion_tokens"], 9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncation_duplicate_blocks_and_early_stop_do_not_become_success() {
|
||||
let mut encoder = ChatStreamEncoder::new(super::super::identity(), false);
|
||||
encoder.push_event(None, &start()).unwrap();
|
||||
assert_eq!(encoder.finish().unwrap_err(), ChatError::IncompleteStream);
|
||||
let block =
|
||||
json!({"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}});
|
||||
encoder.push_event(None, &block).unwrap();
|
||||
assert_eq!(
|
||||
encoder.push_event(None, &block).unwrap_err(),
|
||||
ChatError::InvalidResponse
|
||||
);
|
||||
assert_eq!(
|
||||
encoder
|
||||
.push_event(None, &json!({"type":"message_stop"}))
|
||||
.unwrap_err(),
|
||||
ChatError::InvalidResponse
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upstream_error_preserves_error_type_without_finish_chunk() {
|
||||
let mut encoder = ChatStreamEncoder::new(super::super::identity(), true);
|
||||
let error = json!({"type":"error","error":{"type":"overloaded_error","message":"busy"}});
|
||||
assert_eq!(
|
||||
encoder.push_event(None, &error).unwrap(),
|
||||
vec![json!({"error":error["error"]})]
|
||||
);
|
||||
assert!(encoder.has_wire_failure());
|
||||
assert!(!encoder.is_completed());
|
||||
assert!(encoder.finish().unwrap().is_empty());
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
//! Chat 请求解析、聚合与直接转换合同
|
||||
|
||||
mod genai;
|
||||
mod messages;
|
||||
mod request;
|
||||
mod response;
|
||||
mod responses;
|
||||
|
||||
use gateway_protocol::chat_completions::ChatIdentity;
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
fn identity() -> ChatIdentity {
|
||||
ChatIdentity {
|
||||
id: "chatcmpl-test".into(),
|
||||
created: 10,
|
||||
model: "public-model".into(),
|
||||
}
|
||||
}
|
||||
fn request() -> Map<String, Value> {
|
||||
json!({"model":"public-model","messages":[{"role":"user","content":"hello"}]})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone()
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
//! Chat 原文解析与选路事实不依赖任何目标转换
|
||||
|
||||
use gateway_protocol::{
|
||||
chat_completions::{CHAT_PROTOCOL, ChatError, parse_request},
|
||||
request::{request_facts, request_observation},
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn parsing_retains_original_protocol_and_usage_preference() {
|
||||
let value = json!({"model":"m","messages":[{"role":"user","content":"hello"}],"stream":true,"stream_options":{"include_usage":true},"future":{"store":true}});
|
||||
let parsed = parse_request(&serde_json::to_vec(&value).unwrap()).unwrap();
|
||||
assert_eq!(parsed.body, value.as_object().unwrap().clone());
|
||||
assert!(parsed.include_usage);
|
||||
assert!(!parsed.body.contains_key("input"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn facts_are_extracted_from_chat_fields_directly() {
|
||||
let value = json!({"model":"m","max_tokens":12,"max_completion_tokens":34,"messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"data:image/png;base64,AA=="}}]}],"tools":[{"type":"function","function":{"name":"f"}}],"reasoning_effort":"high","response_format":{"type":"json_schema"}});
|
||||
let facts = request_facts(CHAT_PROTOCOL, value.as_object().unwrap());
|
||||
assert_eq!(facts.max_output_tokens, Some(34));
|
||||
assert!(facts.vision && facts.tools && facts.reasoning && facts.json_schema);
|
||||
assert!(!facts.native_continuation);
|
||||
assert_eq!(
|
||||
request_observation(
|
||||
CHAT_PROTOCOL,
|
||||
value.as_object().unwrap(),
|
||||
&Default::default(),
|
||||
None
|
||||
)
|
||||
.reasoning_effort
|
||||
.as_deref(),
|
||||
Some("high")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_envelopes_and_stream_options_keep_safe_field_errors() {
|
||||
assert_eq!(parse_request(b"[").err(), Some(ChatError::MalformedJson));
|
||||
assert_eq!(parse_request(b"[]").err(), Some(ChatError::ExpectedObject));
|
||||
for (field, value) in [
|
||||
("n", json!(2)),
|
||||
("stream_options", json!({"include_usage":true})),
|
||||
] {
|
||||
let mut request = super::request();
|
||||
request.insert(field.into(), value);
|
||||
let error = parse_request(&serde_json::to_vec(&request).unwrap())
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.parameter(), Some(field));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_tool_history_reports_source_path() {
|
||||
let request = json!({"model":"m","messages":[{"role":"tool","content":"ok"}]});
|
||||
assert_eq!(
|
||||
parse_request(&serde_json::to_vec(&request).unwrap())
|
||||
.err()
|
||||
.unwrap()
|
||||
.parameter(),
|
||||
Some("messages[0].tool_call_id")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_content_is_rejected_before_any_target_is_selected() {
|
||||
for (role, part) in [
|
||||
("user", json!({"type":"SENSITIVE_CONTENT"})),
|
||||
(
|
||||
"assistant",
|
||||
json!({"type":"image_url","image_url":{"url":"https://example.invalid/private"}}),
|
||||
),
|
||||
] {
|
||||
let request = json!({"model":"m","messages":[{"role":role,"content":[part]}]});
|
||||
let error = parse_request(&serde_json::to_vec(&request).unwrap())
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.parameter(), Some("messages[0].content[0].type"));
|
||||
assert!(!error.to_string().contains("SENSITIVE_CONTENT"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
//! Chat 聚合器只聚合当前协议且要求显式终态
|
||||
|
||||
use gateway_protocol::chat_completions::{ChatAccumulator, ChatError};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn frame(delta: Value, reason: Value) -> Value {
|
||||
json!({"id":"c","model":"m","created":1,"object":"chat.completion.chunk","choices":[{"index":0,"delta":delta,"finish_reason":reason}]})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn assembles_interleaved_tools_and_late_usage_without_changing_identity() {
|
||||
let mut accumulator = ChatAccumulator::default();
|
||||
for value in [
|
||||
frame(
|
||||
json!({"role":"assistant","content":"hello ","tool_calls":[{"index":0,"id":"a","type":"function","function":{"name":"read","arguments":"{\"q\":"}},{"index":1,"id":"b","type":"custom","custom":{"name":"shell","input":"echo"}}]}),
|
||||
Value::Null,
|
||||
),
|
||||
frame(
|
||||
json!({"content":"world","reasoning_content":"thought","tool_calls":[{"index":1,"custom":{"input":" ok"}},{"index":0,"function":{"arguments":"1}"}}]}),
|
||||
Value::Null,
|
||||
),
|
||||
frame(json!({}), json!("tool_calls")),
|
||||
json!({"id":"c","model":"m","created":1,"choices":[],"usage":{"prompt_tokens":4,"completion_tokens":5,"total_tokens":9}}),
|
||||
] {
|
||||
accumulator.push(&value).unwrap();
|
||||
}
|
||||
let result = accumulator.finish().unwrap();
|
||||
assert_eq!(result["object"], "chat.completion");
|
||||
assert_eq!(result["choices"][0]["message"]["content"], "hello world");
|
||||
assert_eq!(
|
||||
result["choices"][0]["message"]["tool_calls"][0]["function"]["arguments"],
|
||||
"{\"q\":1}"
|
||||
);
|
||||
assert_eq!(
|
||||
result["choices"][0]["message"]["tool_calls"][1]["custom"]["input"],
|
||||
"echo ok"
|
||||
);
|
||||
assert_eq!(result["usage"]["total_tokens"], 9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncation_and_post_terminal_content_are_rejected() {
|
||||
let mut accumulator = ChatAccumulator::default();
|
||||
accumulator
|
||||
.push(&frame(json!({"content":"partial"}), Value::Null))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
accumulator.finish().unwrap_err(),
|
||||
ChatError::IncompleteStream
|
||||
);
|
||||
let mut accumulator = ChatAccumulator::default();
|
||||
accumulator.push(&frame(json!({}), json!("stop"))).unwrap();
|
||||
assert_eq!(
|
||||
accumulator
|
||||
.push(&frame(json!({"content":"extra"}), Value::Null))
|
||||
.unwrap_err(),
|
||||
ChatError::InvalidResponse
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_envelope_retains_recovery_fields_without_success() {
|
||||
let error = json!({"error":{"type":"overloaded_error","message":"busy","retry_after":3}});
|
||||
let mut accumulator = ChatAccumulator::default();
|
||||
accumulator.push(&error).unwrap();
|
||||
assert_eq!(accumulator.finish().unwrap(), error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_only_completions_keep_null_assistant_content() {
|
||||
let mut accumulator = ChatAccumulator::default();
|
||||
accumulator
|
||||
.push(&frame(
|
||||
json!({"role":"assistant","content":""}),
|
||||
Value::Null,
|
||||
))
|
||||
.unwrap();
|
||||
accumulator.push(&frame(json!({"tool_calls":[{"index":0,"id":"a","type":"function","function":{"name":"read","arguments":"{}"}}]}),json!("tool_calls"))).unwrap();
|
||||
assert!(accumulator.finish().unwrap()["choices"][0]["message"]["content"].is_null());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn complete_json_becomes_ordered_chunks_without_losing_tools_logprobs_or_usage() {
|
||||
let completion = json!({"id":"c","model":"m","created":1,"object":"chat.completion","service_tier":"priority","choices":[{"index":0,"message":{"role":"assistant","content":"answer","refusal":null,"reasoning_content":"thought","annotations":[{"type":"url_citation","url_citation":{"url":"https://example.org","start_index":0,"end_index":6}}],"tool_calls":[{"id":"call","type":"function","function":{"name":"read","arguments":"{}"}},{"id":"custom","type":"custom","custom":{"name":"shell","input":"echo ok"}}]},"finish_reason":"tool_calls","logprobs":{"content":[{"token":"answer","logprob":-0.1}]}}],"usage":{"prompt_tokens":5,"completion_tokens":3,"total_tokens":8}});
|
||||
for include_usage in [false, true] {
|
||||
let chunks =
|
||||
gateway_protocol::chat_completions::completion_chunks(&completion, include_usage)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
chunks[0]["choices"][0]["delta"],
|
||||
json!({"role":"assistant"})
|
||||
);
|
||||
assert_eq!(
|
||||
chunks[1]["choices"][0]["delta"]["tool_calls"][1]["index"],
|
||||
1
|
||||
);
|
||||
assert_eq!(chunks[2]["choices"][0]["finish_reason"], "tool_calls");
|
||||
assert_eq!(chunks.len(), if include_usage { 4 } else { 3 });
|
||||
if !include_usage {
|
||||
assert!(chunks.iter().all(|chunk| chunk.get("usage").is_none()));
|
||||
}
|
||||
let mut accumulator = ChatAccumulator::default();
|
||||
for chunk in &chunks {
|
||||
accumulator.push(chunk).unwrap();
|
||||
}
|
||||
let reconstructed = accumulator.finish().unwrap();
|
||||
assert_eq!(reconstructed["choices"], completion["choices"]);
|
||||
assert_eq!(reconstructed["service_tier"], "priority");
|
||||
if include_usage {
|
||||
assert_eq!(reconstructed["usage"], completion["usage"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn complete_json_requires_a_complete_chat_identity_and_terminal() {
|
||||
for completion in [
|
||||
json!({"object":"response"}),
|
||||
json!({"id":"c","model":"m","created":1,"object":"chat.completion","choices":[{"index":0,"message":{"role":"assistant","content":"partial"},"finish_reason":null}]}),
|
||||
] {
|
||||
assert_eq!(
|
||||
gateway_protocol::chat_completions::completion_chunks(&completion, true).unwrap_err(),
|
||||
ChatError::InvalidResponse
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn buffered_images_replace_previews_without_losing_other_images() {
|
||||
let mut accumulator = ChatAccumulator::default();
|
||||
for (index, url) in [
|
||||
(0, "preview-a"),
|
||||
(1, "preview-b"),
|
||||
(0, "final-a"),
|
||||
(1, "final-b"),
|
||||
] {
|
||||
accumulator
|
||||
.push(&frame(
|
||||
json!({"images":[{"index":index,"type":"image_url","image_url":{"url":url}}]}),
|
||||
Value::Null,
|
||||
))
|
||||
.unwrap();
|
||||
}
|
||||
accumulator.push(&frame(json!({}), json!("stop"))).unwrap();
|
||||
let result = accumulator.finish().unwrap();
|
||||
let images = result["choices"][0]["message"]["images"]
|
||||
.as_array()
|
||||
.unwrap();
|
||||
assert_eq!(images.len(), 2);
|
||||
assert_eq!(images[0]["image_url"]["url"], "final-a");
|
||||
assert_eq!(images[1]["image_url"]["url"], "final-b");
|
||||
assert!(images.iter().all(|image| image.get("index").is_none()));
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
//! responses 直接映射合同
|
||||
|
||||
mod request;
|
||||
mod response;
|
||||
+47
-138
@@ -1,25 +1,20 @@
|
||||
//! Chat 请求映射保留消息、工具和不透明业务数据的语义
|
||||
//! Chat 到 Responses 的字段、媒体和工具映射回归
|
||||
|
||||
use axum::http::StatusCode;
|
||||
use gateway_protocol::chat_completions::responses::convert_request;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{
|
||||
chat_request, completed,
|
||||
http::{Fixture, json_body},
|
||||
message,
|
||||
};
|
||||
|
||||
async fn convert(body: Value) -> Value {
|
||||
let fixture = Fixture::new(Session::new(vec![completed(json!([message("ok")]))])).await;
|
||||
let response = fixture.post(body).await;
|
||||
let status = response.status();
|
||||
let result = json_body(response).await;
|
||||
assert_eq!(status, StatusCode::OK, "{result}");
|
||||
fixture.captured().body
|
||||
fn chat_request(stream: bool) -> Value {
|
||||
json!({"model":"model-a","messages":[{"role":"user","content":"hello"}],"stream":stream})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn preserves_ordered_roles_images_and_modern_tool_round_trip() {
|
||||
fn convert(body: Value) -> Value {
|
||||
convert_request(body.as_object().unwrap())
|
||||
.expect("请求映射")
|
||||
.into()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_ordered_roles_images_and_modern_tool_round_trip() {
|
||||
let arguments = "{ \"city\" : \"北京\", \"store\":true }";
|
||||
let converted = convert(json!({"model":"model-a","messages":[
|
||||
{"role":"system","content":"system text"},
|
||||
@@ -30,7 +25,7 @@ async fn preserves_ordered_roles_images_and_modern_tool_round_trip() {
|
||||
{"id":"call-weather","type":"function","function":{"name":"weather","arguments":arguments}}]},
|
||||
{"role":"tool","tool_call_id":"call-weather","name":"weather","content":"{\"temperature\":25}"},
|
||||
{"role":"user","content":"continue"}
|
||||
]})).await;
|
||||
]}));
|
||||
let input = converted["input"].as_array().unwrap();
|
||||
assert_eq!(
|
||||
input
|
||||
@@ -58,8 +53,8 @@ async fn preserves_ordered_roles_images_and_modern_tool_round_trip() {
|
||||
assert!(converted.get("previous_response_id").is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn web_search_options_require_a_hosted_search_and_flatten_location() {
|
||||
#[test]
|
||||
fn web_search_options_require_a_hosted_search_and_flatten_location() {
|
||||
for (options, expected) in [
|
||||
(json!({}), json!({"type":"web_search"})),
|
||||
(
|
||||
@@ -71,53 +66,19 @@ async fn web_search_options_require_a_hosted_search_and_flatten_location() {
|
||||
] {
|
||||
let mut request = chat_request(false);
|
||||
request["web_search_options"] = options;
|
||||
let body = convert(request).await;
|
||||
let body = convert(request);
|
||||
assert_eq!(body["tools"], json!([expected]));
|
||||
assert_eq!(body["tool_choice"], json!({"type":"web_search"}));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_search_options_and_conflicting_tool_policies_report_the_field() {
|
||||
for (fields, param) in [
|
||||
(
|
||||
json!({"web_search_options":{"search_context_size":7}}),
|
||||
"web_search_options.search_context_size",
|
||||
),
|
||||
(
|
||||
json!({"web_search_options":{"user_location":{"type":"approximate"}}}),
|
||||
"web_search_options.user_location.approximate",
|
||||
),
|
||||
(
|
||||
json!({"web_search_options":{}, "tool_choice":"none"}),
|
||||
"tool_choice",
|
||||
),
|
||||
(
|
||||
json!({"web_search_options":{},"tools":[{"type":"function","function":{"name":"lookup"}}]}),
|
||||
"tools",
|
||||
),
|
||||
] {
|
||||
let mut request = chat_request(false);
|
||||
request
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.extend(fields.as_object().unwrap().clone());
|
||||
let fixture = Fixture::new(Session::new(Vec::new())).await;
|
||||
let response = fixture.post(request).await;
|
||||
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
||||
assert_eq!(json_body(response).await["error"]["param"], param);
|
||||
assert!(fixture.execution.captured.lock().unwrap().is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn maps_inline_user_pdf_without_reencoding_its_data() {
|
||||
#[test]
|
||||
fn maps_inline_user_pdf_without_reencoding_its_data() {
|
||||
let data = "data:application/pdf;base64,JVBERi0xLjQ=";
|
||||
let converted = convert(json!({"model":"model-a","messages":[
|
||||
{"role":"user","content":[{"type":"text","text":"Read the attachment"},
|
||||
{"type":"file","file":{"filename":"document.pdf","file_data":data}}]}
|
||||
]}))
|
||||
.await;
|
||||
]}));
|
||||
assert_eq!(
|
||||
converted["input"][0]["content"],
|
||||
json!([{"type":"input_text","text":"Read the attachment"},
|
||||
@@ -125,8 +86,8 @@ async fn maps_inline_user_pdf_without_reencoding_its_data() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn assistant_history_uses_output_content_for_text_and_refusals() {
|
||||
#[test]
|
||||
fn assistant_history_uses_output_content_for_text_and_refusals() {
|
||||
for content in [
|
||||
json!("previous answer"),
|
||||
json!([{"type":"text","text":"previous answer"}]),
|
||||
@@ -136,8 +97,7 @@ async fn assistant_history_uses_output_content_for_text_and_refusals() {
|
||||
{"role":"user","content":"first turn"},
|
||||
{"role":"assistant","content":content},
|
||||
{"role":"user","content":"continue from the previous answer"}
|
||||
]}))
|
||||
.await;
|
||||
]}));
|
||||
let history = &converted["input"][1];
|
||||
assert_eq!(history["role"], "assistant");
|
||||
assert_eq!(history["status"], "completed");
|
||||
@@ -156,8 +116,8 @@ async fn assistant_history_uses_output_content_for_text_and_refusals() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn preserves_nested_schema_metadata_and_future_opaque_values() {
|
||||
#[test]
|
||||
fn preserves_nested_schema_metadata_and_future_opaque_values() {
|
||||
let schema = json!({"type":"object","properties":{
|
||||
"messages":{"type":"string"},"store":{"type":"boolean"},
|
||||
"function_call":{"type":"string"},"future":{"x-extension":[1,2]}},
|
||||
@@ -173,7 +133,7 @@ async fn preserves_nested_schema_metadata_and_future_opaque_values() {
|
||||
body["verbosity"] = json!("future-verbosity");
|
||||
body["service_tier"] = json!("future-tier");
|
||||
body["future_client_extension"] = json!({"opaque":true});
|
||||
let converted = convert(body).await;
|
||||
let converted = convert(body);
|
||||
assert_eq!(converted["model"], "future-model-opaque:β");
|
||||
assert_eq!(converted["tools"][0]["parameters"], schema);
|
||||
assert_eq!(converted["tools"][0]["strict"], false);
|
||||
@@ -193,8 +153,8 @@ async fn preserves_nested_schema_metadata_and_future_opaque_values() {
|
||||
assert!(converted.get("future_client_extension").is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn normalizes_neutral_defaults_without_dropping_shared_provider_parameters() {
|
||||
#[test]
|
||||
fn normalizes_neutral_defaults_without_dropping_shared_provider_parameters() {
|
||||
let mut body = chat_request(false);
|
||||
for name in [
|
||||
"stream",
|
||||
@@ -215,7 +175,7 @@ async fn normalizes_neutral_defaults_without_dropping_shared_provider_parameters
|
||||
body["temperature"] = json!(0.2);
|
||||
body["top_p"] = json!(0.9);
|
||||
body["prompt_cache_retention"] = json!("24h");
|
||||
let converted = convert(body).await;
|
||||
let converted = convert(body);
|
||||
assert_eq!(converted["stream"], false);
|
||||
assert_eq!(converted["store"], false);
|
||||
assert_eq!(converted["max_output_tokens"], 24);
|
||||
@@ -224,57 +184,8 @@ async fn normalizes_neutral_defaults_without_dropping_shared_provider_parameters
|
||||
assert_eq!(converted["prompt_cache_retention"], "24h");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refuses_known_unrepresentable_features_before_starting_execution() {
|
||||
for (name, value) in [
|
||||
("n", json!(2)),
|
||||
("store", json!(true)),
|
||||
("functions", json!([{"name":"old"}])),
|
||||
("function_call", json!("auto")),
|
||||
("input", json!("not chat")),
|
||||
("previous_response_id", json!("resp_previous")),
|
||||
("audio", json!({"voice":"alloy","format":"wav"})),
|
||||
] {
|
||||
let fixture = Fixture::new(Session::new(Vec::new())).await;
|
||||
let mut body = chat_request(false);
|
||||
body[name] = value;
|
||||
let response = fixture.post(body).await;
|
||||
assert_eq!(response.status(), StatusCode::BAD_REQUEST, "{name}");
|
||||
let body = json_body(response).await;
|
||||
assert_eq!(body["error"]["param"], name, "{body}");
|
||||
assert!(
|
||||
fixture.execution.captured.lock().unwrap().is_none(),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_unmapped_message_content_and_identity_fields() {
|
||||
for message in [
|
||||
json!({"role":"tool","tool_call_id":"call-lookup","name":42,"content":"result"}),
|
||||
json!({"role":"assistant","content":[{"type":"file","file":{"filename":"a.pdf","file_data":"data:application/pdf;base64,JVBERg=="}}]}),
|
||||
json!({"role":"assistant","content":[{"type":"text","text":"history","prompt_cache_breakpoint":{"type":"default"}}]}),
|
||||
json!({"role":"tool","content":"unassociated output"}),
|
||||
] {
|
||||
let fixture = Fixture::new(Session::new(Vec::new())).await;
|
||||
let response = fixture
|
||||
.post(json!({"model":"model-a","messages":[message]}))
|
||||
.await;
|
||||
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
||||
let body = json_body(response).await;
|
||||
assert!(
|
||||
body["error"]["param"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.starts_with("messages")
|
||||
);
|
||||
assert!(fixture.execution.captured.lock().unwrap().is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn assistant_tool_history_keeps_arguments_opaque_and_cache_annotations_structural() {
|
||||
#[test]
|
||||
fn assistant_tool_history_keeps_arguments_opaque_and_cache_annotations_structural() {
|
||||
let cache = json!({"type":"default","future_setting":{"keep":true}});
|
||||
let arguments = "not valid JSON {\n \"raw\" : 🦀";
|
||||
let converted = convert(json!({"model":"model-a","messages":[
|
||||
@@ -282,8 +193,7 @@ async fn assistant_tool_history_keeps_arguments_opaque_and_cache_annotations_str
|
||||
{"role":"assistant","content":null,"tool_calls":[{"id":"call-raw","type":"function",
|
||||
"function":{"name":"raw","arguments":arguments}}]},
|
||||
{"role":"tool","tool_call_id":"call-raw","content":[{"type":"text","text":"result"}]}
|
||||
],"prompt_cache_options":{"future":{"keep":true}},"moderation":{"future":{"keep":true}}}))
|
||||
.await;
|
||||
],"prompt_cache_options":{"future":{"keep":true}},"moderation":{"future":{"keep":true}}}));
|
||||
assert_eq!(
|
||||
converted["input"][0]["content"][0]["prompt_cache_breakpoint"],
|
||||
cache
|
||||
@@ -300,15 +210,14 @@ async fn assistant_tool_history_keeps_arguments_opaque_and_cache_annotations_str
|
||||
assert_eq!(converted["moderation"], json!({"future":{"keep":true}}));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn optional_chat_controls_degrade_without_blocking_upstream_execution() {
|
||||
#[test]
|
||||
fn optional_chat_controls_degrade_without_blocking_upstream_execution() {
|
||||
for stop in [json!("end"), json!(["end", "stop"]), json!([])] {
|
||||
let converted = convert(json!({"model":"model-a", "messages":[
|
||||
{"role":"user", "name":"speaker", "content":"hello"},
|
||||
{"role":"assistant", "reasoning_content":"display-only", "content":"previous"}
|
||||
], "stop":stop, "seed":7, "frequency_penalty":0.3, "presence_penalty":0.5,
|
||||
"logit_bias":{"10":-10}, "prediction":{"type":"content", "content":"hint"}}))
|
||||
.await;
|
||||
"logit_bias":{"10":-10}, "prediction":{"type":"content", "content":"hint"}}));
|
||||
assert_eq!(converted["input"][0]["content"][0]["text"], "hello");
|
||||
assert_eq!(converted["input"][1]["content"][0]["text"], "previous");
|
||||
for field in [
|
||||
@@ -324,8 +233,8 @@ async fn optional_chat_controls_degrade_without_blocking_upstream_execution() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shared_options_and_native_extensions_reach_upstream_without_model_prejudgment() {
|
||||
#[test]
|
||||
fn shared_options_and_native_extensions_reach_upstream_without_model_prejudgment() {
|
||||
let mut request = chat_request(false);
|
||||
request.as_object_mut().unwrap().extend(json!({
|
||||
"max_output_tokens":10, "temperature":3.0, "top_p":1.5,
|
||||
@@ -336,7 +245,7 @@ async fn shared_options_and_native_extensions_reach_upstream_without_model_preju
|
||||
"tool_choice":"future_choice", "logprobs":true, "top_logprobs":3,
|
||||
"include":["reasoning.encrypted_content"], "truncation":"auto", "max_tool_calls":5
|
||||
}).as_object().unwrap().clone());
|
||||
let converted = convert(request).await;
|
||||
let converted = convert(request);
|
||||
assert_eq!(converted["max_output_tokens"], 10);
|
||||
assert_eq!(converted["temperature"], 3.0);
|
||||
assert_eq!(converted["top_p"], 1.5);
|
||||
@@ -363,8 +272,8 @@ async fn shared_options_and_native_extensions_reach_upstream_without_model_preju
|
||||
assert_eq!(converted["top_logprobs"], 3);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn custom_tools_keep_native_input_and_mixed_call_families_through_history() {
|
||||
#[test]
|
||||
fn custom_tools_keep_native_input_and_mixed_call_families_through_history() {
|
||||
let schema = json!({"type":"grammar", "grammar":{"syntax":"lark", "definition":"start: /.+/"}});
|
||||
let converted = convert(json!({"model":"model-a", "tools":[
|
||||
{"type":"custom", "custom":{"name":"patch", "format":schema}},
|
||||
@@ -380,7 +289,7 @@ async fn custom_tools_keep_native_input_and_mixed_call_families_through_history(
|
||||
{"role":"tool", "tool_call_id":"call_lookup", "content":[{"type":"image_url", "image_url":{"url":"https://example.com/result.png"}}]},
|
||||
{"role":"assistant", "tool_calls":[{"id":"call_patch", "type":"function", "function":{"name":"lookup", "arguments":"{}"}}]},
|
||||
{"role":"tool", "tool_call_id":"call_patch", "content":"reused id"}
|
||||
]})).await;
|
||||
]}));
|
||||
assert_eq!(
|
||||
converted["tools"][0],
|
||||
json!({"type":"custom", "name":"patch", "format":schema})
|
||||
@@ -398,16 +307,18 @@ async fn custom_tools_keep_native_input_and_mixed_call_families_through_history(
|
||||
assert_eq!(converted["input"][5]["type"], "function_call_output");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn files_and_audio_are_preserved_as_inputs_instead_of_losing_the_user_turn() {
|
||||
#[test]
|
||||
fn files_and_audio_are_preserved_as_inputs_instead_of_losing_the_user_turn() {
|
||||
for file in [
|
||||
json!({"file_id":"file_test"}),
|
||||
json!({"file_url":"https://example.com/report.txt"}),
|
||||
json!({"file_data":"data:text/plain;base64,aGk=", "filename":"report.txt", "detail":"high"}),
|
||||
] {
|
||||
let converted = convert(json!({"model":"model-a", "messages":[{"role":"user", "content":[
|
||||
{"type":"file", "file":file}, {"type":"input_audio", "input_audio":{"data":"aGk=", "format":"mp3"}}
|
||||
]}]})).await;
|
||||
let converted = convert(
|
||||
json!({"model":"model-a", "messages":[{"role":"user", "content":[
|
||||
{"type":"file", "file":file}, {"type":"input_audio", "input_audio":{"data":"aGk=", "format":"mp3"}}
|
||||
]}]}),
|
||||
);
|
||||
let mut expected = file;
|
||||
expected["type"] = json!("input_file");
|
||||
assert_eq!(converted["input"][0]["content"][0], expected);
|
||||
@@ -417,5 +328,3 @@ async fn files_and_audio_are_preserved_as_inputs_instead_of_losing_the_user_turn
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
use crate::support::generation::Session;
|
||||
+381
-254
@@ -1,32 +1,124 @@
|
||||
//! Chat JSON 与 SSE 的真实 wire 投影、去重和协议扩展边界
|
||||
//! Responses 到 Chat 的完整响应、SSE增量及历史字段回归
|
||||
|
||||
use axum::{body::to_bytes, http::StatusCode, response::Response};
|
||||
use gateway_protocol::chat_completions::{
|
||||
ChatAccumulator, ChatError, ChatIdentity,
|
||||
responses::{ChatStreamEncoder, project_response},
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use super::{
|
||||
chat_request, completed, created,
|
||||
http::{Fixture, json_body},
|
||||
message, wire,
|
||||
};
|
||||
|
||||
pub(super) async fn sse_body(response: Response) -> (String, Vec<Value>) {
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(response.headers()["content-type"], "text/event-stream");
|
||||
let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||
let text = String::from_utf8(bytes.to_vec()).unwrap();
|
||||
assert_eq!(text.matches("data: [DONE]").count(), 1, "{text}");
|
||||
assert!(text.ends_with("data: [DONE]\n\n"), "{text}");
|
||||
assert!(!text.contains("event: response."), "{text}");
|
||||
let chunks = text
|
||||
.lines()
|
||||
.filter_map(|line| line.strip_prefix("data: "))
|
||||
.filter(|data| *data != "[DONE]")
|
||||
.map(|data| serde_json::from_str(data).unwrap())
|
||||
.collect();
|
||||
(text, chunks)
|
||||
struct Session(Vec<Value>);
|
||||
impl Session {
|
||||
fn new(events: Vec<Value>) -> Self {
|
||||
Self(events)
|
||||
}
|
||||
fn with_batch(mut self, events: Vec<Value>) -> Self {
|
||||
self.0.extend(events);
|
||||
self
|
||||
}
|
||||
}
|
||||
struct Fixture(Session);
|
||||
struct Projection {
|
||||
json: Option<Value>,
|
||||
chunks: Vec<Value>,
|
||||
error: Option<ChatError>,
|
||||
}
|
||||
impl Fixture {
|
||||
fn new(events: Session) -> Self {
|
||||
Self(events)
|
||||
}
|
||||
fn post(&self, request: Value) -> Projection {
|
||||
let identity = ChatIdentity {
|
||||
id: "chatcmpl-test".to_owned(),
|
||||
created: 100,
|
||||
model: "model-a".to_owned(),
|
||||
};
|
||||
let mut result = Projection {
|
||||
json: None,
|
||||
chunks: Vec::new(),
|
||||
error: None,
|
||||
};
|
||||
if request["stream"] == true {
|
||||
let mut encoder = ChatStreamEncoder::new(
|
||||
identity,
|
||||
request["stream_options"]["include_usage"] == true,
|
||||
);
|
||||
for event in &self.0.0 {
|
||||
match encoder.push_event(event["type"].as_str(), event) {
|
||||
Ok(chunks) => result.chunks.extend(chunks),
|
||||
Err(error) => {
|
||||
result.error = Some(error);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
match encoder.finish() {
|
||||
Ok(chunks) => result.chunks.extend(chunks),
|
||||
Err(error) => result.error = Some(error),
|
||||
}
|
||||
} else {
|
||||
let projected = if self.0.0.len() == 1 {
|
||||
self.0.0[0]
|
||||
.get("response")
|
||||
.ok_or(ChatError::IncompleteStream)
|
||||
.and_then(|value| project_response(value, &identity))
|
||||
} else {
|
||||
let mut encoder = ChatStreamEncoder::new(identity, true);
|
||||
let mut accumulator = ChatAccumulator::default();
|
||||
let mut collect = || {
|
||||
for event in &self.0.0 {
|
||||
for chunk in encoder.push_event(event["type"].as_str(), event)? {
|
||||
accumulator.push(&chunk)?;
|
||||
}
|
||||
}
|
||||
for chunk in encoder.finish()? {
|
||||
accumulator.push(&chunk)?;
|
||||
}
|
||||
Ok::<_, ChatError>(())
|
||||
};
|
||||
collect().and_then(|()| accumulator.finish())
|
||||
};
|
||||
match projected {
|
||||
Ok(value) => result.json = Some(value),
|
||||
Err(error) => result.error = Some(error),
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
fn json_body(response: Projection) -> Value {
|
||||
assert!(response.error.is_none(), "{:?}", response.error);
|
||||
response.json.unwrap()
|
||||
}
|
||||
fn sse_body(response: Projection) -> (String, Vec<Value>) {
|
||||
assert!(response.error.is_none(), "{:?}", response.error);
|
||||
(
|
||||
serde_json::to_string(&response.chunks).unwrap(),
|
||||
response.chunks,
|
||||
)
|
||||
}
|
||||
fn chat_request(stream: bool) -> Value {
|
||||
json!({"model":"model-a","messages":[{"role":"user","content":"hello"}],"stream":stream})
|
||||
}
|
||||
fn wire(kind: &str, mut value: Value) -> Value {
|
||||
value["type"] = json!(kind);
|
||||
value
|
||||
}
|
||||
fn completed(output: Value) -> Value {
|
||||
wire(
|
||||
"response.completed",
|
||||
json!({"response":{"id":"resp_chat_test","object":"response","model":"upstream-model","status":"completed","output":output,"usage":{"input_tokens":11,"output_tokens":7,"total_tokens":18,"input_tokens_details":{"cached_tokens":3},"output_tokens_details":{"reasoning_tokens":2}}}}),
|
||||
)
|
||||
}
|
||||
fn message(text: &str) -> Value {
|
||||
json!({"id":"msg_chat_test","type":"message","role":"assistant","status":"completed","content":[{"type":"output_text","text":text,"annotations":[]}]})
|
||||
}
|
||||
fn created() -> Value {
|
||||
wire(
|
||||
"response.created",
|
||||
json!({"response":{"id":"resp_chat_test","object":"response","model":"upstream-model","status":"in_progress","output":[]}}),
|
||||
)
|
||||
}
|
||||
|
||||
fn combined(chunks: &[Value], name: &str) -> String {
|
||||
chunks
|
||||
.iter()
|
||||
@@ -38,16 +130,12 @@ fn tool(id: &str, call_id: &str, name: &str, arguments: &str) -> Value {
|
||||
json!({"type":"function_call","id":id,"call_id":call_id,"name":name,"arguments":arguments,"status":"completed"})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn json_projects_public_identity_text_and_actual_usage() {
|
||||
let fixture = Fixture::new(Session::new(vec![completed(json!([message("你好 🌍")]))])).await;
|
||||
let response = fixture.post(chat_request(false)).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(
|
||||
response.headers()["x-gateway-request-id"],
|
||||
"req_chat_fixture"
|
||||
);
|
||||
let body = json_body(response).await;
|
||||
#[test]
|
||||
fn json_projects_public_identity_text_and_actual_usage() {
|
||||
let fixture = Fixture::new(Session::new(vec![completed(json!([message("你好 🌍")]))]));
|
||||
let response = fixture.post(chat_request(false));
|
||||
assert!(response.error.is_none(), "{:?}", response.error);
|
||||
let body = json_body(response);
|
||||
assert_eq!(body["object"], "chat.completion");
|
||||
assert!(body["id"].as_str().unwrap().starts_with("chatcmpl-"));
|
||||
assert!(body["created"].as_u64().is_some());
|
||||
@@ -61,8 +149,8 @@ async fn json_projects_public_identity_text_and_actual_usage() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn web_search_projects_citations_in_json_and_streams_the_original_links() {
|
||||
#[test]
|
||||
fn web_search_projects_citations_in_json_and_streams_the_original_links() {
|
||||
let linked = "[IANA](https://www.iana.org/)";
|
||||
let text = format!("见 {linked}");
|
||||
let citation = json!({"type":"url_citation","url":"https://www.iana.org/","title":"IANA",
|
||||
@@ -99,22 +187,21 @@ async fn web_search_projects_citations_in_json_and_streams_the_original_links()
|
||||
json!({"output_index":2,"item":answer}),
|
||||
),
|
||||
completed(json!([])),
|
||||
]))
|
||||
.await;
|
||||
]));
|
||||
let mut request = chat_request(stream);
|
||||
request["web_search_options"] = json!({});
|
||||
let response = fixture.post(request).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let response = fixture.post(request);
|
||||
assert!(response.error.is_none(), "{:?}", response.error);
|
||||
let expected = format!("🌍 {text}");
|
||||
if stream {
|
||||
let (_, chunks) = sse_body(response).await;
|
||||
let (_, chunks) = sse_body(response);
|
||||
assert_eq!(combined(&chunks, "content"), expected);
|
||||
assert_eq!(
|
||||
chunks.last().unwrap()["choices"][0]["finish_reason"],
|
||||
"stop"
|
||||
);
|
||||
} else {
|
||||
let body = json_body(response).await;
|
||||
let body = json_body(response);
|
||||
let choice = &body["choices"][0];
|
||||
assert_eq!(choice["finish_reason"], "stop");
|
||||
assert_eq!(choice["message"]["content"], expected);
|
||||
@@ -127,18 +214,18 @@ async fn web_search_projects_citations_in_json_and_streams_the_original_links()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn json_tool_arguments_and_refusal_do_not_become_assistant_text() {
|
||||
#[test]
|
||||
fn json_tool_arguments_and_refusal_do_not_become_assistant_text() {
|
||||
for output in [
|
||||
json!([tool("fc1", "call1", "weather", "{ \"city\" : \"北京\" }")]),
|
||||
json!([{"type":"reasoning","id":"rs1","summary":[{"type":"summary_text","text":"public summary"}]},
|
||||
{"type":"message","id":"refusal1","role":"assistant","status":"completed",
|
||||
"content":[{"type":"refusal","refusal":"cannot help"}]}]),
|
||||
] {
|
||||
let fixture = Fixture::new(Session::new(vec![completed(output.clone())])).await;
|
||||
let response = fixture.post(chat_request(false)).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let body = json_body(response).await;
|
||||
let fixture = Fixture::new(Session::new(vec![completed(output.clone())]));
|
||||
let response = fixture.post(chat_request(false));
|
||||
assert!(response.error.is_none(), "{:?}", response.error);
|
||||
let body = json_body(response);
|
||||
let choice = &body["choices"][0];
|
||||
assert_eq!(choice["message"]["content"], Value::Null);
|
||||
if output[0]["type"] == "reasoning" {
|
||||
@@ -157,18 +244,32 @@ async fn json_tool_arguments_and_refusal_do_not_become_assistant_text() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sse_deduplicates_text_snapshots_and_emits_usage_only_when_requested() {
|
||||
#[test]
|
||||
fn sse_deduplicates_text_snapshots_and_emits_usage_only_when_requested() {
|
||||
for include_usage in [false, true] {
|
||||
let fixture = Fixture::new(Session::new(vec![created(),
|
||||
wire("response.output_text.delta",json!({"item_id":"msg_chat_test","output_index":0,"content_index":0,"delta":"你好 "})),
|
||||
wire("response.output_text.done",json!({"item_id":"msg_chat_test","output_index":0,"content_index":0,"text":"你好 🌍"})),
|
||||
wire("response.content_part.done",json!({"item_id":"msg_chat_test","output_index":0,"content_index":0,"part":{"type":"output_text","text":"你好 🌍"}})),
|
||||
wire("response.output_item.done",json!({"output_index":0,"item":message("你好 🌍")})),
|
||||
completed(json!([message("你好 🌍")]))])).await;
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
created(),
|
||||
wire(
|
||||
"response.output_text.delta",
|
||||
json!({"item_id":"msg_chat_test","output_index":0,"content_index":0,"delta":"你好 "}),
|
||||
),
|
||||
wire(
|
||||
"response.output_text.done",
|
||||
json!({"item_id":"msg_chat_test","output_index":0,"content_index":0,"text":"你好 🌍"}),
|
||||
),
|
||||
wire(
|
||||
"response.content_part.done",
|
||||
json!({"item_id":"msg_chat_test","output_index":0,"content_index":0,"part":{"type":"output_text","text":"你好 🌍"}}),
|
||||
),
|
||||
wire(
|
||||
"response.output_item.done",
|
||||
json!({"output_index":0,"item":message("你好 🌍")}),
|
||||
),
|
||||
completed(json!([message("你好 🌍")])),
|
||||
]));
|
||||
let mut body = chat_request(true);
|
||||
body["stream_options"] = json!({"include_usage":include_usage});
|
||||
let (_, chunks) = sse_body(fixture.post(body).await).await;
|
||||
let (_, chunks) = sse_body(fixture.post(body));
|
||||
assert_eq!(combined(&chunks, "content"), "你好 🌍");
|
||||
assert_eq!(
|
||||
chunks
|
||||
@@ -198,13 +299,11 @@ async fn sse_deduplicates_text_snapshots_and_emits_usage_only_when_requested() {
|
||||
if include_usage {
|
||||
assert_eq!(usage[0]["usage"]["total_tokens"], 18);
|
||||
}
|
||||
let captured = fixture.captured();
|
||||
assert!(captured.body.get("stream_options").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sse_preserves_interleaved_tools_and_reordered_terminal_snapshots() {
|
||||
#[test]
|
||||
fn sse_preserves_interleaved_tools_and_reordered_terminal_snapshots() {
|
||||
let first = tool(
|
||||
"fc_first",
|
||||
"call_first",
|
||||
@@ -243,9 +342,8 @@ async fn sse_preserves_interleaved_tools_and_reordered_terminal_snapshots() {
|
||||
json!({"output_index":2,"item":first}),
|
||||
),
|
||||
completed(json!([second, first])),
|
||||
]))
|
||||
.await;
|
||||
let (_, chunks) = sse_body(fixture.post(chat_request(true)).await).await;
|
||||
]));
|
||||
let (_, chunks) = sse_body(fixture.post(chat_request(true)));
|
||||
let mut tools = BTreeMap::<u64, (String, String, String)>::new();
|
||||
for chunk in &chunks {
|
||||
if let Some(calls) = chunk["choices"][0]["delta"]["tool_calls"].as_array() {
|
||||
@@ -290,8 +388,8 @@ async fn sse_preserves_interleaved_tools_and_reordered_terminal_snapshots() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn extra_attributes_and_auxiliary_events_preserve_existing_chat_results() {
|
||||
#[test]
|
||||
fn extra_attributes_and_auxiliary_events_preserve_existing_chat_results() {
|
||||
let mut text = message("preserved");
|
||||
text["future_optional"] = json!({"opaque":true});
|
||||
text["content"][0]["future_attribute"] = json!([1, 2, 3]);
|
||||
@@ -303,26 +401,18 @@ async fn extra_attributes_and_auxiliary_events_preserve_existing_chat_results()
|
||||
),
|
||||
created(),
|
||||
completed(json!([text])),
|
||||
]))
|
||||
.await;
|
||||
let (_, chunks) = sse_body(fixture.post(chat_request(true)).await).await;
|
||||
]));
|
||||
let (_, chunks) = sse_body(fixture.post(chat_request(true)));
|
||||
assert_eq!(combined(&chunks, "content"), "preserved");
|
||||
assert!(
|
||||
!chunks
|
||||
.iter()
|
||||
.any(|chunk| chunk.to_string().contains("private"))
|
||||
);
|
||||
assert_eq!(
|
||||
fixture
|
||||
.trace
|
||||
.discarded
|
||||
.load(std::sync::atomic::Ordering::SeqCst),
|
||||
2
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn compaction_state_preserves_chat_answer_without_exposing_ciphertext() {
|
||||
#[test]
|
||||
fn compaction_state_preserves_chat_answer_without_exposing_ciphertext() {
|
||||
for kind in ["compaction", "compaction_summary", "context_compaction"] {
|
||||
for streaming in [false, true] {
|
||||
let state =
|
||||
@@ -338,11 +428,10 @@ async fn compaction_state_preserves_chat_answer_without_exposing_ciphertext() {
|
||||
json!({"output_index":0,"item":state}),
|
||||
),
|
||||
completed(json!([state, message("preserved")])),
|
||||
]))
|
||||
.await;
|
||||
let response = fixture.post(chat_request(streaming)).await;
|
||||
]));
|
||||
let response = fixture.post(chat_request(streaming));
|
||||
if streaming {
|
||||
let (text, chunks) = sse_body(response).await;
|
||||
let (text, chunks) = sse_body(response);
|
||||
assert_eq!(combined(&chunks, "content"), "preserved");
|
||||
assert!(!text.contains("opaque-private-state"));
|
||||
assert_eq!(
|
||||
@@ -350,8 +439,8 @@ async fn compaction_state_preserves_chat_answer_without_exposing_ciphertext() {
|
||||
"stop"
|
||||
);
|
||||
} else {
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let body = json_body(response).await;
|
||||
assert!(response.error.is_none(), "{:?}", response.error);
|
||||
let body = json_body(response);
|
||||
assert_eq!(body["choices"][0]["message"]["content"], "preserved");
|
||||
assert_eq!(body["choices"][0]["finish_reason"], "stop");
|
||||
assert!(!body.to_string().contains("opaque-private-state"));
|
||||
@@ -360,8 +449,8 @@ async fn compaction_state_preserves_chat_answer_without_exposing_ciphertext() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn incomplete_projects_only_supported_finish_reasons() {
|
||||
#[test]
|
||||
fn incomplete_projects_only_supported_finish_reasons() {
|
||||
for (reason, expected) in [
|
||||
("max_output_tokens", "length"),
|
||||
("content_filter", "content_filter"),
|
||||
@@ -373,27 +462,24 @@ async fn incomplete_projects_only_supported_finish_reasons() {
|
||||
"id":"resp_chat_test","status":"incomplete","output":[message("partial")],
|
||||
"incomplete_details":{"reason":reason}}}),
|
||||
);
|
||||
let fixture = Fixture::new(Session::new(vec![created(), event])).await;
|
||||
let response = fixture.post(chat_request(streaming)).await;
|
||||
let fixture = Fixture::new(Session::new(vec![created(), event]));
|
||||
let response = fixture.post(chat_request(streaming));
|
||||
if streaming {
|
||||
let (_, chunks) = sse_body(response).await;
|
||||
let (_, chunks) = sse_body(response);
|
||||
assert_eq!(
|
||||
chunks.last().unwrap()["choices"][0]["finish_reason"],
|
||||
expected
|
||||
);
|
||||
} else {
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(
|
||||
json_body(response).await["choices"][0]["finish_reason"],
|
||||
expected
|
||||
);
|
||||
assert!(response.error.is_none(), "{:?}", response.error);
|
||||
assert_eq!(json_body(response)["choices"][0]["finish_reason"], expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn encrypted_reasoning_stays_private_while_public_text_and_usage_are_projected() {
|
||||
#[test]
|
||||
fn encrypted_reasoning_stays_private_while_public_text_and_usage_are_projected() {
|
||||
let reasoning = json!({
|
||||
"id":"rs_private","type":"reasoning",
|
||||
"summary":[{"type":"summary_text","text":"PUBLIC_SUMMARY_MARKER"}],
|
||||
@@ -418,22 +504,24 @@ async fn encrypted_reasoning_stays_private_while_public_text_and_usage_are_proje
|
||||
"response.output_item.done",
|
||||
json!({"output_index":1,"item":message("public answer")}),
|
||||
),
|
||||
wire("response.completed", json!({"response":{
|
||||
"id":"resp_chat_test","object":"response","model":"upstream-model","status":"completed",
|
||||
"output":[reasoning,message("public answer")],
|
||||
"usage":{"input_tokens":11,"output_tokens":7,"total_tokens":18,
|
||||
"input_tokens_details":{"cached_tokens":3,"cache_write_tokens":4},
|
||||
"output_tokens_details":{"reasoning_tokens":2,"accepted_prediction_tokens":1}}
|
||||
}})),
|
||||
]))
|
||||
.await;
|
||||
wire(
|
||||
"response.completed",
|
||||
json!({"response":{
|
||||
"id":"resp_chat_test","object":"response","model":"upstream-model","status":"completed",
|
||||
"output":[reasoning,message("public answer")],
|
||||
"usage":{"input_tokens":11,"output_tokens":7,"total_tokens":18,
|
||||
"input_tokens_details":{"cached_tokens":3,"cache_write_tokens":4},
|
||||
"output_tokens_details":{"reasoning_tokens":2,"accepted_prediction_tokens":1}}
|
||||
}}),
|
||||
),
|
||||
]));
|
||||
let mut request = chat_request(streaming);
|
||||
if streaming {
|
||||
request["stream_options"] = json!({"include_usage":true});
|
||||
}
|
||||
let response = fixture.post(request).await;
|
||||
let response = fixture.post(request);
|
||||
let (body, content, usage) = if streaming {
|
||||
let (body, chunks) = sse_body(response).await;
|
||||
let (body, chunks) = sse_body(response);
|
||||
let usage = chunks
|
||||
.iter()
|
||||
.find(|chunk| chunk["choices"] == json!([]))
|
||||
@@ -441,8 +529,8 @@ async fn encrypted_reasoning_stays_private_while_public_text_and_usage_are_proje
|
||||
.clone();
|
||||
(body, combined(&chunks, "content"), usage)
|
||||
} else {
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let body = json_body(response).await;
|
||||
assert!(response.error.is_none(), "{:?}", response.error);
|
||||
let body = json_body(response);
|
||||
(
|
||||
body.to_string(),
|
||||
body["choices"][0]["message"]["content"]
|
||||
@@ -467,75 +555,69 @@ async fn encrypted_reasoning_stays_private_while_public_text_and_usage_are_proje
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unrepresentable_business_output_fails_without_successful_chat_completion() {
|
||||
#[test]
|
||||
fn unrepresentable_business_output_fails_without_successful_chat_completion() {
|
||||
for output in [
|
||||
json!({"id":"future_output","type":"future_business_output","payload":"unrepresentable"}),
|
||||
json!({"id":"action_native","type":"computer_call","status":"completed","call_id":"call_action","action":{"type":"click","x":1,"y":2}}),
|
||||
] {
|
||||
for streaming in [false, true] {
|
||||
let fixture =
|
||||
Fixture::new(Session::new(vec![created(), completed(json!([output]))])).await;
|
||||
let fixture = Fixture::new(Session::new(vec![created(), completed(json!([output]))]));
|
||||
let mut request = chat_request(streaming);
|
||||
if streaming {
|
||||
request["stream_options"] = json!({"include_usage":true});
|
||||
}
|
||||
let response = fixture.post(request).await;
|
||||
if streaming {
|
||||
let (body, chunks) = sse_body(response).await;
|
||||
assert!(chunks.iter().any(|chunk| chunk.get("error").is_some()));
|
||||
assert!(
|
||||
!chunks
|
||||
.iter()
|
||||
.any(|chunk| chunk["choices"][0]["finish_reason"].is_string())
|
||||
);
|
||||
assert!(!chunks.iter().any(|chunk| chunk["choices"] == json!([])));
|
||||
assert!(!body.contains("OPAQUE_IMAGE_MARKER"));
|
||||
} else {
|
||||
assert!(response.status().is_server_error());
|
||||
let body = json_body(response).await;
|
||||
assert!(body.get("error").is_some());
|
||||
assert!(body.get("choices").is_none());
|
||||
assert!(!body.to_string().contains("OPAQUE_IMAGE_MARKER"));
|
||||
}
|
||||
let response = fixture.post(request);
|
||||
assert_eq!(response.error, Some(ChatError::InvalidResponse));
|
||||
assert!(
|
||||
!response
|
||||
.chunks
|
||||
.iter()
|
||||
.any(|chunk| chunk["choices"][0]["finish_reason"].is_string())
|
||||
);
|
||||
assert!(response.json.is_none());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stream_without_terminal_does_not_emit_a_successful_finish_or_usage() {
|
||||
#[test]
|
||||
fn stream_without_terminal_does_not_emit_a_successful_finish_or_usage() {
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
created(),
|
||||
wire(
|
||||
"response.output_text.delta",
|
||||
json!({"item_id":"msg_chat_test","output_index":0,"content_index":0,"delta":"partial"}),
|
||||
),
|
||||
]))
|
||||
.await;
|
||||
]));
|
||||
let mut body = chat_request(true);
|
||||
body["stream_options"] = json!({"include_usage":true});
|
||||
let (_, chunks) = sse_body(fixture.post(body).await).await;
|
||||
assert!(chunks.iter().any(|chunk| chunk.get("error").is_some()));
|
||||
let response = fixture.post(body);
|
||||
assert_eq!(response.error, Some(ChatError::IncompleteStream));
|
||||
assert!(
|
||||
!chunks
|
||||
!response
|
||||
.chunks
|
||||
.iter()
|
||||
.any(|chunk| chunk["choices"][0]["finish_reason"].is_string())
|
||||
);
|
||||
assert!(!chunks.iter().any(|chunk| chunk["choices"] == json!([])));
|
||||
assert!(
|
||||
!response
|
||||
.chunks
|
||||
.iter()
|
||||
.any(|chunk| chunk["choices"] == json!([]))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn first_batch_terminal_can_finish_without_creating_usage_facts() {
|
||||
#[test]
|
||||
fn first_batch_terminal_can_finish_without_creating_usage_facts() {
|
||||
let fixture = Fixture::new(Session::new(vec![wire(
|
||||
"response.completed",
|
||||
json!({"response":{
|
||||
"id":"resp_chat_test","status":"completed","output":[message("done only")]
|
||||
}}),
|
||||
)]))
|
||||
.await;
|
||||
)]));
|
||||
let mut body = chat_request(true);
|
||||
body["stream_options"] = json!({"include_usage":true});
|
||||
let (_, chunks) = sse_body(fixture.post(body).await).await;
|
||||
let (_, chunks) = sse_body(fixture.post(body));
|
||||
assert_eq!(combined(&chunks, "content"), "done only");
|
||||
assert_eq!(
|
||||
chunks
|
||||
@@ -545,54 +627,25 @@ async fn first_batch_terminal_can_finish_without_creating_usage_facts() {
|
||||
1
|
||||
);
|
||||
assert!(!chunks.iter().any(|chunk| chunk["usage"].is_object()));
|
||||
assert!(
|
||||
fixture
|
||||
.trace
|
||||
.finalized
|
||||
.load(std::sync::atomic::Ordering::SeqCst)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn native_sse_byte_fragments_and_multiple_events_preserve_unicode() {
|
||||
let first = gateway_protocol::openai::sse::encode_sse_event("response.output_text.delta",&json!({
|
||||
"type":"response.output_text.delta","item_id":"msg_chat_test","output_index":0,"content_index":0,"delta":"你"
|
||||
}).to_string());
|
||||
let second = gateway_protocol::openai::sse::encode_sse_event("response.output_text.delta",&json!({
|
||||
"type":"response.output_text.delta","item_id":"msg_chat_test","output_index":0,"content_index":0,"delta":"好"
|
||||
}).to_string());
|
||||
let split = first.find('你').unwrap() + 1;
|
||||
let mut remainder = first.as_bytes()[split..].to_vec();
|
||||
remainder.extend_from_slice(second.as_bytes());
|
||||
let raw = |bytes| {
|
||||
gateway_core::event::ProviderEvent::wire(
|
||||
gateway_core::event::ProtocolWireEvent::raw_sse("openai", bytes).unwrap(),
|
||||
)
|
||||
};
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
created(),
|
||||
raw(bytes::Bytes::copy_from_slice(&first.as_bytes()[..split])),
|
||||
raw(bytes::Bytes::from(remainder)),
|
||||
completed(json!([message("你好")])),
|
||||
]))
|
||||
.await;
|
||||
let (_, chunks) = sse_body(fixture.post(chat_request(true)).await).await;
|
||||
assert_eq!(combined(&chunks, "content"), "你好");
|
||||
assert_eq!(
|
||||
chunks.last().unwrap()["choices"][0]["finish_reason"],
|
||||
"stop"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refusal_deltas_and_done_snapshots_produce_only_standard_refusal() {
|
||||
#[test]
|
||||
fn refusal_deltas_and_done_snapshots_produce_only_standard_refusal() {
|
||||
let output = json!({"id":"msg_refusal","type":"message","role":"assistant","status":"completed",
|
||||
"content":[{"type":"refusal","refusal":"cannot help"}]});
|
||||
let fixture = Fixture::new(Session::new(vec![created(),
|
||||
wire("response.refusal.delta",json!({"item_id":"msg_refusal","output_index":0,"content_index":0,"delta":"cannot "})),
|
||||
wire("response.refusal.done",json!({"item_id":"msg_refusal","output_index":0,"content_index":0,"refusal":"cannot help"})),
|
||||
completed(json!([output]))])).await;
|
||||
let (_, chunks) = sse_body(fixture.post(chat_request(true)).await).await;
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
created(),
|
||||
wire(
|
||||
"response.refusal.delta",
|
||||
json!({"item_id":"msg_refusal","output_index":0,"content_index":0,"delta":"cannot "}),
|
||||
),
|
||||
wire(
|
||||
"response.refusal.done",
|
||||
json!({"item_id":"msg_refusal","output_index":0,"content_index":0,"refusal":"cannot help"}),
|
||||
),
|
||||
completed(json!([output])),
|
||||
]));
|
||||
let (_, chunks) = sse_body(fixture.post(chat_request(true)));
|
||||
assert_eq!(combined(&chunks, "refusal"), "cannot help");
|
||||
assert_eq!(combined(&chunks, "content"), "");
|
||||
assert_eq!(
|
||||
@@ -601,8 +654,8 @@ async fn refusal_deltas_and_done_snapshots_produce_only_standard_refusal() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn auxiliary_events_after_completed_preserve_exactly_one_finish_and_usage() {
|
||||
#[test]
|
||||
fn auxiliary_events_after_completed_preserve_exactly_one_finish_and_usage() {
|
||||
for with_created in [false, true] {
|
||||
// 终态与辅助事件同属一批 Core 交付 不构造已终结会话继续产出事件的另一种异常
|
||||
let session = Session::new(if with_created {
|
||||
@@ -617,10 +670,10 @@ async fn auxiliary_events_after_completed_preserve_exactly_one_finish_and_usage(
|
||||
json!({"response_id":"resp_chat_test","future":{"kept":true}}),
|
||||
),
|
||||
]);
|
||||
let fixture = Fixture::new(session).await;
|
||||
let fixture = Fixture::new(session);
|
||||
let mut body = chat_request(true);
|
||||
body["stream_options"] = json!({"include_usage":true});
|
||||
let (_, chunks) = sse_body(fixture.post(body).await).await;
|
||||
let (_, chunks) = sse_body(fixture.post(body));
|
||||
assert_eq!(combined(&chunks, "content"), "completed text");
|
||||
assert_eq!(
|
||||
chunks
|
||||
@@ -636,18 +689,11 @@ async fn auxiliary_events_after_completed_preserve_exactly_one_finish_and_usage(
|
||||
assert_eq!(usage.len(), 1);
|
||||
assert_eq!(usage[0]["usage"]["total_tokens"], 18);
|
||||
assert!(!chunks.iter().any(|chunk| chunk.get("error").is_some()));
|
||||
assert_eq!(
|
||||
fixture
|
||||
.trace
|
||||
.commits
|
||||
.load(std::sync::atomic::Ordering::SeqCst),
|
||||
1
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn wire_failures_preserve_existing_recovery_fields_without_success_chunks() {
|
||||
#[test]
|
||||
fn wire_failures_preserve_existing_recovery_fields_without_success_chunks() {
|
||||
for shape in ["response.failed", "error", "bare_error"] {
|
||||
let mut expected = json!({
|
||||
"type":"rate_limit_error","code":"rate_limit_exceeded","param":null,
|
||||
@@ -671,10 +717,10 @@ async fn wire_failures_preserve_existing_recovery_fields_without_success_chunks(
|
||||
failure
|
||||
}
|
||||
};
|
||||
let fixture = Fixture::new(Session::new(vec![created(), failure])).await;
|
||||
let fixture = Fixture::new(Session::new(vec![created(), failure]));
|
||||
let mut body = chat_request(true);
|
||||
body["stream_options"] = json!({"include_usage":true});
|
||||
let (_, chunks) = sse_body(fixture.post(body).await).await;
|
||||
let (_, chunks) = sse_body(fixture.post(body));
|
||||
let errors = chunks
|
||||
.iter()
|
||||
.filter_map(|chunk| chunk.get("error"))
|
||||
@@ -688,33 +734,32 @@ async fn wire_failures_preserve_existing_recovery_fields_without_success_chunks(
|
||||
);
|
||||
assert!(!chunks.iter().any(|chunk| chunk["choices"] == json!([])));
|
||||
assert!(!chunks.iter().any(|chunk| chunk["usage"].is_object()));
|
||||
assert_eq!(
|
||||
fixture
|
||||
.trace
|
||||
.commits
|
||||
.load(std::sync::atomic::Ordering::SeqCst),
|
||||
1
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn conflicting_text_snapshot_fails_instead_of_appending_replacement_content() {
|
||||
let fixture = Fixture::new(Session::new(vec![created(),
|
||||
wire("response.output_text.delta",json!({"item_id":"msg_chat_test","output_index":0,"content_index":0,"delta":"already sent"})),
|
||||
completed(json!([message("different result")]))])).await;
|
||||
let (_, chunks) = sse_body(fixture.post(chat_request(true)).await).await;
|
||||
assert_eq!(combined(&chunks, "content"), "already sent");
|
||||
assert!(chunks.iter().any(|chunk| chunk.get("error").is_some()));
|
||||
#[test]
|
||||
fn conflicting_text_snapshot_fails_instead_of_appending_replacement_content() {
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
created(),
|
||||
wire(
|
||||
"response.output_text.delta",
|
||||
json!({"item_id":"msg_chat_test","output_index":0,"content_index":0,"delta":"already sent"}),
|
||||
),
|
||||
completed(json!([message("different result")])),
|
||||
]));
|
||||
let response = fixture.post(chat_request(true));
|
||||
assert_eq!(response.error, Some(ChatError::InvalidResponse));
|
||||
assert_eq!(combined(&response.chunks, "content"), "already sent");
|
||||
assert!(
|
||||
!chunks
|
||||
!response
|
||||
.chunks
|
||||
.iter()
|
||||
.any(|chunk| chunk["choices"][0]["finish_reason"].is_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn custom_and_function_calls_keep_distinct_shapes_in_json_and_interleaved_streams() {
|
||||
#[test]
|
||||
fn custom_and_function_calls_keep_distinct_shapes_in_json_and_interleaved_streams() {
|
||||
let custom = json!({"id":"ct_1","type":"custom_tool_call","call_id":"call_custom","name":"patch","input":"first\nsecond"});
|
||||
let function = json!({"id":"fc_1","type":"function_call","call_id":"call_function","name":"lookup","arguments":"{}"});
|
||||
for streaming in [false, true] {
|
||||
@@ -745,12 +790,11 @@ async fn custom_and_function_calls_keep_distinct_shapes_in_json_and_interleaved_
|
||||
json!({"output_index":0,"item_id":"ct_1","input":"first\nsecond"}),
|
||||
),
|
||||
completed(json!([custom, function])),
|
||||
]))
|
||||
.await;
|
||||
let response = fixture.post(chat_request(streaming)).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
]));
|
||||
let response = fixture.post(chat_request(streaming));
|
||||
assert!(response.error.is_none(), "{:?}", response.error);
|
||||
if streaming {
|
||||
let (_, chunks) = sse_body(response).await;
|
||||
let (_, chunks) = sse_body(response);
|
||||
let calls = chunks
|
||||
.iter()
|
||||
.filter_map(|chunk| chunk["choices"][0]["delta"]["tool_calls"].as_array())
|
||||
@@ -786,7 +830,7 @@ async fn custom_and_function_calls_keep_distinct_shapes_in_json_and_interleaved_
|
||||
"tool_calls"
|
||||
);
|
||||
} else {
|
||||
let body = json_body(response).await;
|
||||
let body = json_body(response);
|
||||
assert_eq!(
|
||||
body["choices"][0]["message"]["tool_calls"],
|
||||
json!([
|
||||
@@ -798,20 +842,26 @@ async fn custom_and_function_calls_keep_distinct_shapes_in_json_and_interleaved_
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn image_previews_and_final_images_are_projected_once_per_distinct_snapshot() {
|
||||
#[test]
|
||||
fn image_previews_and_final_images_are_projected_once_per_distinct_snapshot() {
|
||||
let image = json!({"id":"ig_one","type":"image_generation_call","status":"completed","result":"ZmluYWw=","output_format":"webp"});
|
||||
for streaming in [false, true] {
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
created(),
|
||||
wire("response.image_generation_call.partial_image", json!({"output_index":0,"item_id":"ig_one","partial_image_b64":"cHJldmlldw==","output_format":"webp"})),
|
||||
wire("response.output_item.done", json!({"output_index":0,"item":image})),
|
||||
wire(
|
||||
"response.image_generation_call.partial_image",
|
||||
json!({"output_index":0,"item_id":"ig_one","partial_image_b64":"cHJldmlldw==","output_format":"webp"}),
|
||||
),
|
||||
wire(
|
||||
"response.output_item.done",
|
||||
json!({"output_index":0,"item":image}),
|
||||
),
|
||||
completed(json!([image, message("created")])),
|
||||
])).await;
|
||||
let response = fixture.post(chat_request(streaming)).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
]));
|
||||
let response = fixture.post(chat_request(streaming));
|
||||
assert!(response.error.is_none(), "{:?}", response.error);
|
||||
if streaming {
|
||||
let (_, chunks) = sse_body(response).await;
|
||||
let (_, chunks) = sse_body(response);
|
||||
let images = chunks
|
||||
.iter()
|
||||
.filter_map(|chunk| chunk["choices"][0]["delta"]["images"].as_array())
|
||||
@@ -824,7 +874,7 @@ async fn image_previews_and_final_images_are_projected_once_per_distinct_snapsho
|
||||
"data:image/webp;base64,ZmluYWw="
|
||||
);
|
||||
} else {
|
||||
let body = json_body(response).await;
|
||||
let body = json_body(response);
|
||||
assert_eq!(
|
||||
body["choices"][0]["message"]["images"][0]["image_url"]["url"],
|
||||
"data:image/webp;base64,ZmluYWw="
|
||||
@@ -833,8 +883,8 @@ async fn image_previews_and_final_images_are_projected_once_per_distinct_snapsho
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn output_logprobs_survive_json_projection_and_stream_snapshot_deduplication() {
|
||||
#[test]
|
||||
fn output_logprobs_survive_json_projection_and_stream_snapshot_deduplication() {
|
||||
let probabilities =
|
||||
json!([{"token":"hello","logprob":-0.1,"bytes":[104,101,108,108,111],"top_logprobs":[]}]);
|
||||
let mut output = message("hello");
|
||||
@@ -842,14 +892,20 @@ async fn output_logprobs_survive_json_projection_and_stream_snapshot_deduplicati
|
||||
for streaming in [false, true] {
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
created(),
|
||||
wire("response.output_text.delta", json!({"output_index":0,"content_index":0,"item_id":"msg_chat_test","delta":"hello","logprobs":probabilities})),
|
||||
wire("response.output_text.done", json!({"output_index":0,"content_index":0,"item_id":"msg_chat_test","text":"hello","logprobs":probabilities})),
|
||||
wire(
|
||||
"response.output_text.delta",
|
||||
json!({"output_index":0,"content_index":0,"item_id":"msg_chat_test","delta":"hello","logprobs":probabilities}),
|
||||
),
|
||||
wire(
|
||||
"response.output_text.done",
|
||||
json!({"output_index":0,"content_index":0,"item_id":"msg_chat_test","text":"hello","logprobs":probabilities}),
|
||||
),
|
||||
completed(json!([output])),
|
||||
])).await;
|
||||
let response = fixture.post(chat_request(streaming)).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
]));
|
||||
let response = fixture.post(chat_request(streaming));
|
||||
assert!(response.error.is_none(), "{:?}", response.error);
|
||||
if streaming {
|
||||
let (_, chunks) = sse_body(response).await;
|
||||
let (_, chunks) = sse_body(response);
|
||||
let values = chunks
|
||||
.iter()
|
||||
.filter_map(|chunk| chunk["choices"][0]["logprobs"]["content"].as_array())
|
||||
@@ -859,15 +915,15 @@ async fn output_logprobs_survive_json_projection_and_stream_snapshot_deduplicati
|
||||
assert_eq!(json!(values), probabilities);
|
||||
} else {
|
||||
assert_eq!(
|
||||
json_body(response).await["choices"][0]["logprobs"]["content"],
|
||||
json_body(response)["choices"][0]["logprobs"]["content"],
|
||||
probabilities
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn streaming_citation_offsets_follow_delivered_text_when_messages_interleave() {
|
||||
#[test]
|
||||
fn streaming_citation_offsets_follow_delivered_text_when_messages_interleave() {
|
||||
let citation = json!({"type":"url_citation","start_index":2,"end_index":4,"url":"https://example.com","title":"source"});
|
||||
let mut first = message("abcd");
|
||||
first["content"][0]["annotations"] = json!([citation]);
|
||||
@@ -875,13 +931,25 @@ async fn streaming_citation_offsets_follow_delivered_text_when_messages_interlea
|
||||
second["id"] = json!("msg_second");
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
created(),
|
||||
wire("response.output_text.delta", json!({"output_index":0,"content_index":0,"item_id":"msg_chat_test","delta":"ab"})),
|
||||
wire("response.output_text.delta", json!({"output_index":1,"content_index":0,"item_id":"msg_second","delta":"xy"})),
|
||||
wire("response.output_text.delta", json!({"output_index":0,"content_index":0,"item_id":"msg_chat_test","delta":"cd"})),
|
||||
wire("response.output_text.annotation.added", json!({"output_index":0,"content_index":0,"item_id":"msg_chat_test","annotation_index":0,"annotation":citation})),
|
||||
wire(
|
||||
"response.output_text.delta",
|
||||
json!({"output_index":0,"content_index":0,"item_id":"msg_chat_test","delta":"ab"}),
|
||||
),
|
||||
wire(
|
||||
"response.output_text.delta",
|
||||
json!({"output_index":1,"content_index":0,"item_id":"msg_second","delta":"xy"}),
|
||||
),
|
||||
wire(
|
||||
"response.output_text.delta",
|
||||
json!({"output_index":0,"content_index":0,"item_id":"msg_chat_test","delta":"cd"}),
|
||||
),
|
||||
wire(
|
||||
"response.output_text.annotation.added",
|
||||
json!({"output_index":0,"content_index":0,"item_id":"msg_chat_test","annotation_index":0,"annotation":citation}),
|
||||
),
|
||||
completed(json!([first, second])),
|
||||
])).await;
|
||||
let (_, chunks) = sse_body(fixture.post(chat_request(true)).await).await;
|
||||
]));
|
||||
let (_, chunks) = sse_body(fixture.post(chat_request(true)));
|
||||
assert_eq!(combined(&chunks, "content"), "abxycd");
|
||||
let annotations = chunks
|
||||
.iter()
|
||||
@@ -893,4 +961,63 @@ async fn streaming_citation_offsets_follow_delivered_text_when_messages_interlea
|
||||
assert_eq!(annotations[0]["url_citation"]["end_index"], 6);
|
||||
}
|
||||
|
||||
use crate::support::generation::Session;
|
||||
fn codec_message(text: &str) -> Value {
|
||||
json!({"type":"message","id":"msg","role":"assistant","status":"completed","content":[{"type":"output_text","text":text,"annotations":[]}]})
|
||||
}
|
||||
fn codec_completed(output: Value) -> Value {
|
||||
json!({"type":"response.completed","response":{"id":"native","status":"completed","output":output,"usage":{"input_tokens":3,"output_tokens":5,"total_tokens":8}}})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deduplicates_snapshots_and_preserves_usage_and_identity() {
|
||||
let mut encoder = ChatStreamEncoder::new(super::super::identity(), true);
|
||||
let mut accumulator = ChatAccumulator::default();
|
||||
let terminal = codec_completed(json!([codec_message("你好 🌍")]));
|
||||
for event in [
|
||||
json!({"type":"response.created","response":{"id":"native"}}),
|
||||
json!({"type":"response.output_text.delta","output_index":0,"content_index":0,"item_id":"msg","delta":"你好 "}),
|
||||
json!({"type":"response.output_text.done","output_index":0,"content_index":0,"item_id":"msg","text":"你好 🌍"}),
|
||||
terminal.clone(),
|
||||
] {
|
||||
for chunk in encoder.push_event(None, &event).unwrap() {
|
||||
accumulator.push(&chunk).unwrap();
|
||||
}
|
||||
}
|
||||
assert!(encoder.is_completed());
|
||||
assert!(encoder.finish().unwrap().is_empty());
|
||||
let result = accumulator.finish().unwrap();
|
||||
assert_eq!(result["choices"][0]["message"]["content"], "你好 🌍");
|
||||
assert_eq!(result["usage"]["total_tokens"], 8);
|
||||
assert_eq!(result["id"], "chatcmpl-test");
|
||||
assert_eq!(
|
||||
result,
|
||||
project_response(&terminal["response"], &super::super::identity()).unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_function_reasoning_and_refusal_keep_separate_shapes() {
|
||||
let response = codec_completed(
|
||||
json!([{"type":"custom_tool_call","id":"custom","call_id":"a","name":"shell","input":"pwd","status":"completed"},{"type":"function_call","id":"function","call_id":"b","name":"read","arguments":"{}","status":"completed"},{"type":"reasoning","id":"reason","summary":[{"type":"summary_text","text":"thought"}],"encrypted_content":"secret"},{"type":"message","id":"refusal","role":"assistant","status":"completed","content":[{"type":"refusal","refusal":"no"}]}]),
|
||||
);
|
||||
let result = project_response(&response["response"], &super::super::identity()).unwrap();
|
||||
let message = &result["choices"][0]["message"];
|
||||
assert_eq!(message["refusal"], "no");
|
||||
assert_eq!(message["reasoning_content"], "thought");
|
||||
assert_eq!(message["tool_calls"][0]["custom"]["input"], "pwd");
|
||||
assert_eq!(message["tool_calls"][1]["function"]["arguments"], "{}");
|
||||
assert!(!result.to_string().contains("secret"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conflicting_snapshots_and_eof_fail_without_synthesizing_success() {
|
||||
let mut encoder = ChatStreamEncoder::new(super::super::identity(), false);
|
||||
encoder.push_event(None,&json!({"type":"response.output_text.delta","output_index":0,"content_index":0,"item_id":"msg","delta":"sent"})).unwrap();
|
||||
assert_eq!(encoder.finish().unwrap_err(), ChatError::IncompleteStream);
|
||||
assert_eq!(
|
||||
encoder
|
||||
.push_event(None, &codec_completed(json!([codec_message("different")])))
|
||||
.unwrap_err(),
|
||||
ChatError::InvalidResponse
|
||||
);
|
||||
}
|
||||
@@ -1,249 +0,0 @@
|
||||
//! 验证转换路径的工具往返、多模态输入和签名来源
|
||||
|
||||
use gateway_protocol::{
|
||||
anthropic::{MessagesAccumulator, MessagesToResponsesStream},
|
||||
genai::{GenAiToMessagesStream, messages_to_genai_request, responses_to_genai_request},
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
#[test]
|
||||
fn signed_tool_roundtrip_preserves_custom_identity_and_final_usage() {
|
||||
let original =
|
||||
json!({"model":"fixture","input":"Use patch","tools":[{"type":"custom","name":"patch"}]});
|
||||
let mut native = GenAiToMessagesStream::default();
|
||||
let mut responses = MessagesToResponsesStream::new(original.as_object().unwrap());
|
||||
let first = json!({"responseId":"r","candidates":[{"content":{"parts":[{"functionCall":{"name":"patch","args":{"input":"abc"}},"thoughtSignature":"opaque-signature"}]},"finishReason":"STOP"}]});
|
||||
let mut emitted = Vec::new();
|
||||
for event in native.push(&first).unwrap() {
|
||||
emitted.extend(responses.push(&event).unwrap());
|
||||
}
|
||||
assert!(!emitted.iter().any(|e| e["type"] == "response.completed"));
|
||||
for event in native.push(&json!({"usageMetadata":{"promptTokenCount":10,"cachedContentTokenCount":4,"candidatesTokenCount":3,"thoughtsTokenCount":2}})).unwrap().into_iter().chain(native.finish().unwrap()) {
|
||||
emitted.extend(responses.push(&event).unwrap());
|
||||
}
|
||||
let response = &emitted.last().unwrap()["response"];
|
||||
assert_eq!(response["usage"]["input_tokens"], 10);
|
||||
assert_eq!(response["usage"]["output_tokens"], 5);
|
||||
let mut input = response["output"].as_array().unwrap().clone();
|
||||
let call = input
|
||||
.iter()
|
||||
.find(|e| e["type"] == "custom_tool_call")
|
||||
.unwrap();
|
||||
assert_eq!(call["input"], "abc");
|
||||
let call_id = call["call_id"].clone();
|
||||
input.push(json!({"type":"custom_tool_call_output","call_id":call_id,"output":"done"}));
|
||||
let next = json!({"model":"fixture","input":input,"tools":original["tools"]});
|
||||
let request = responses_to_genai_request(next.as_object().unwrap()).unwrap();
|
||||
let call = &request["contents"][0]["parts"][0];
|
||||
assert_eq!(call["thoughtSignature"], "opaque-signature");
|
||||
assert_eq!(call["functionCall"]["name"], "patch");
|
||||
assert_eq!(
|
||||
request["contents"][1]["parts"][0]["functionResponse"]["name"],
|
||||
"patch"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn messages_replay_keeps_late_signatures_and_rejects_incomplete_stream() {
|
||||
let mut native = GenAiToMessagesStream::default();
|
||||
let mut messages = MessagesAccumulator::default();
|
||||
for frame in [
|
||||
json!({"candidates":[{"content":{"parts":[{"text":"reason","thought":true}]}}]}),
|
||||
json!({"candidates":[{"content":{"parts":[{"thoughtSignature":"late"},{"text":"answer"}]},"finishReason":"STOP"}]}),
|
||||
] {
|
||||
for event in native.push(&frame).unwrap() {
|
||||
messages.push(&event).unwrap();
|
||||
}
|
||||
}
|
||||
let mut complete = None;
|
||||
for event in native.finish().unwrap() {
|
||||
complete = messages.push(&event).unwrap().or(complete);
|
||||
}
|
||||
let complete = complete.unwrap();
|
||||
let request = json!({"messages":[{"role":"assistant","content":complete["content"]}]});
|
||||
let body = messages_to_genai_request(request.as_object().unwrap()).unwrap();
|
||||
assert_eq!(body["contents"][0]["parts"][0]["thoughtSignature"], "late");
|
||||
assert_eq!(body["contents"][0]["parts"][0]["text"], "reason");
|
||||
let mut incomplete = GenAiToMessagesStream::default();
|
||||
incomplete
|
||||
.push(&json!({"candidates":[{"content":{"parts":[{"text":"partial"}]}}]}))
|
||||
.unwrap();
|
||||
assert!(incomplete.finish().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_system_images_schema_and_forced_tools_without_dropping_unknown_content() {
|
||||
let request = json!({"system":"system","messages":[{"role":"user","content":[{"type":"image","source":{"type":"base64","media_type":"image/png","data":"image"}}]}],"tools":[{"name":"lookup","input_schema":{"type":"object"}}],"tool_choice":{"type":"tool","name":"lookup"},"output_config":{"format":{"type":"json_schema","schema":{"type":"object"}}}});
|
||||
let body = messages_to_genai_request(request.as_object().unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
body["contents"][0]["parts"][0]["inlineData"]["mimeType"],
|
||||
"image/png"
|
||||
);
|
||||
assert_eq!(
|
||||
body["toolConfig"]["functionCallingConfig"]["allowedFunctionNames"],
|
||||
json!(["lookup"])
|
||||
);
|
||||
assert_eq!(
|
||||
body["generationConfig"]["responseMimeType"],
|
||||
"application/json"
|
||||
);
|
||||
assert_eq!(
|
||||
body["generationConfig"]["responseSchema"],
|
||||
json!({"type":"object"})
|
||||
);
|
||||
let invalid = json!({"messages":[{"role":"user","content":[{"type":"unknown"}]}]});
|
||||
assert!(messages_to_genai_request(invalid.as_object().unwrap()).is_err());
|
||||
let _: Value = request;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merges_text_frames_and_omits_unsigned_empty_tool_placeholders() {
|
||||
let mut stream = GenAiToMessagesStream::default();
|
||||
let mut messages = MessagesAccumulator::default();
|
||||
for frame in [
|
||||
json!({"candidates":[{"content":{"parts":[{"text":"first "}]}}]}),
|
||||
json!({"candidates":[{"content":{"parts":[{"text":"second"},{"thoughtSignature":"text-signature"},{"text":""}]}}]}),
|
||||
json!({"candidates":[{"content":{"parts":[{"functionCall":{"id":"call","name":"lookup","args":{}}},{"text":""}]},"finishReason":"OTHER"}]}),
|
||||
] {
|
||||
for event in stream.push(&frame).unwrap() {
|
||||
messages.push(&event).unwrap();
|
||||
}
|
||||
}
|
||||
let mut complete = None;
|
||||
for event in stream.finish().unwrap() {
|
||||
complete = messages.push(&event).unwrap().or(complete);
|
||||
}
|
||||
let complete = complete.unwrap();
|
||||
assert_eq!(complete["stop_reason"], "tool_use");
|
||||
assert_eq!(complete["content"][0]["text"], "first second");
|
||||
let request = json!({"messages":[{"role":"assistant","content":complete["content"]}]});
|
||||
let native = messages_to_genai_request(request.as_object().unwrap()).unwrap();
|
||||
let parts = native["contents"][0]["parts"].as_array().unwrap();
|
||||
assert_eq!(parts.len(), 2);
|
||||
assert!(parts[0].get("thoughtSignature").is_none());
|
||||
assert_eq!(parts[1]["functionCall"]["name"], "lookup");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visible_text_streams_as_one_block_without_a_trailing_signature_carrier() {
|
||||
for late in [false, true] {
|
||||
let mut stream = GenAiToMessagesStream::default();
|
||||
let mut accumulator = MessagesAccumulator::default();
|
||||
let mut events = stream
|
||||
.push(&json!({"candidates":[{"content":{"parts":[{"text":"first "}]}}]}))
|
||||
.unwrap();
|
||||
assert!(
|
||||
events
|
||||
.iter()
|
||||
.any(|event| event["delta"]["text"] == "first ")
|
||||
);
|
||||
let mut part = json!({"text":"answer"});
|
||||
if !late {
|
||||
part["thoughtSignature"] = json!("opaque");
|
||||
}
|
||||
events.extend(
|
||||
stream
|
||||
.push(&json!({"candidates":[{"content":{"parts":[part]}}]}))
|
||||
.unwrap(),
|
||||
);
|
||||
if late {
|
||||
events.extend(stream.push(&json!({"candidates":[{"content":{"parts":[{"thoughtSignature":"opaque"}]}}]})).unwrap());
|
||||
}
|
||||
events.extend(
|
||||
stream
|
||||
.push(&json!({"candidates":[{"finishReason":"STOP"}]}))
|
||||
.unwrap(),
|
||||
);
|
||||
events.extend(stream.finish().unwrap());
|
||||
let mut complete = None;
|
||||
for event in events {
|
||||
complete = accumulator.push(&event).unwrap().or(complete);
|
||||
}
|
||||
let complete = complete.unwrap();
|
||||
assert_eq!(
|
||||
complete["content"],
|
||||
json!([{"type":"text","text":"first answer"}])
|
||||
);
|
||||
let request = json!({"messages":[{"role":"assistant","content":complete["content"]}]});
|
||||
let native = messages_to_genai_request(request.as_object().unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
native["contents"][0]["parts"],
|
||||
json!([{"text":"first answer"}])
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_signature_carriers_do_not_reach_anthropic_upstreams() {
|
||||
let mut request = json!({"messages":[{"role":"assistant","content":[
|
||||
{"type":"thinking","thinking":"private","signature":"cpr:genai:v1:{}"},
|
||||
{"type":"thinking","thinking":"native","signature":"anthropic-signature"},
|
||||
{"type":"text","text":"visible"}
|
||||
]}]})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone();
|
||||
gateway_protocol::anthropic::strip_foreign_thinking_for_messages(&mut request);
|
||||
assert_eq!(
|
||||
request["messages"][0]["content"].as_array().unwrap().len(),
|
||||
2
|
||||
);
|
||||
assert_eq!(
|
||||
request["messages"][0]["content"][0]["signature"],
|
||||
"anthropic-signature"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsigned_tool_history_uses_documented_fallback_without_a_signature_cache() {
|
||||
let request = json!({"messages":[
|
||||
{"role":"assistant","content":[{"type":"text","text":""},{"type":"tool_use","id":"call","name":"lookup","input":{}}]},
|
||||
{"role":"user","content":[{"type":"tool_result","tool_use_id":"call","content":"value"}]}
|
||||
]});
|
||||
let native = messages_to_genai_request(request.as_object().unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
native["contents"][0]["parts"][0]["thoughtSignature"],
|
||||
"skip_thought_signature_validator"
|
||||
);
|
||||
assert_eq!(
|
||||
native["contents"][1]["parts"][0]["functionResponse"]["id"],
|
||||
"call"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_client_placeholders_do_not_change_message_roles_or_system_content() {
|
||||
let request = json!({"system":"instructions","messages":[
|
||||
{"role":"user","content":"hello"},{"role":"system","content":[]}
|
||||
]});
|
||||
let native = messages_to_genai_request(request.as_object().unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
native["contents"],
|
||||
json!([{"role":"user","parts":[{"text":"hello"}]}])
|
||||
);
|
||||
assert_eq!(
|
||||
native["systemInstruction"]["parts"][0]["text"],
|
||||
"instructions"
|
||||
);
|
||||
let invalid = json!({"messages":[{"role":"system","content":"instructions"}]});
|
||||
assert!(messages_to_genai_request(invalid.as_object().unwrap()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn messages_tool_result_documents_use_native_response_parts() {
|
||||
let request = json!({"messages":[
|
||||
{"role":"assistant","content":[{"type":"tool_use","name":"read","id":"c","input":{}}]},
|
||||
{"role":"user","content":[{"type":"tool_result","tool_use_id":"c","content":[
|
||||
{"type":"document","source":{"type":"text","data":"caption"}},
|
||||
{"type":"image","source":{"type":"base64","media_type":"image/png","data":"AA=="}}
|
||||
]}]}
|
||||
]});
|
||||
let body = messages_to_genai_request(request.as_object().unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
body["contents"][1]["parts"][0],
|
||||
json!({"functionResponse":{
|
||||
"name":"read","id":"c","response":{"output":"caption"},
|
||||
"parts":[{"inlineData":{"mimeType":"image/png","data":"AA=="}}]
|
||||
}})
|
||||
);
|
||||
}
|
||||
@@ -2,6 +2,3 @@
|
||||
|
||||
mod response;
|
||||
mod tokens;
|
||||
|
||||
mod messages;
|
||||
mod responses;
|
||||
|
||||
@@ -1,173 +0,0 @@
|
||||
//! Responses 生成参数不继承 Messages 的默认值、推理约束和采样裁剪
|
||||
|
||||
use gateway_protocol::genai::responses_to_genai_request;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
#[test]
|
||||
fn unspecified_generation_settings_remain_unspecified_on_tool_continuations() {
|
||||
let function = json!({"type":"function","name":"lookup","parameters":{"type":"object"}});
|
||||
for choice in [json!("auto"), json!("required"), function.clone()] {
|
||||
let mut request = json!({"tools":[function],"tool_choice":choice,"input":[
|
||||
{"type":"function_call","call_id":"c","name":"lookup","arguments":"{}"},
|
||||
{"type":"function_call_output","call_id":"c","output":"value"}
|
||||
]});
|
||||
for maximum in [None, Some(Value::Null)] {
|
||||
if let Some(maximum) = maximum {
|
||||
request["max_output_tokens"] = maximum;
|
||||
}
|
||||
let body = responses_to_genai_request(request.as_object().unwrap()).unwrap();
|
||||
assert_eq!(body["generationConfig"], json!({}));
|
||||
assert_eq!(
|
||||
body["contents"][1]["parts"][0]["functionResponse"]["name"],
|
||||
"lookup"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_reasoning_and_sampling_survive_required_tools_and_small_output_limits() {
|
||||
let function = json!({"type":"function","name":"lookup","parameters":{"type":"object"}});
|
||||
for choice in [
|
||||
json!("required"),
|
||||
function.clone(),
|
||||
json!({"type":"allowed_tools","mode":"required","tools":[{"type":"function","name":"lookup"}]}),
|
||||
] {
|
||||
let request = json!({"input":"hello","tools":[function],"tool_choice":choice,
|
||||
"max_output_tokens":128,"reasoning":{"effort":"high"},"temperature":0.3,"top_p":0.8});
|
||||
let body = responses_to_genai_request(request.as_object().unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
body["generationConfig"],
|
||||
json!({"maxOutputTokens":128,"thinkingConfig":{"thinkingBudget":24576,"includeThoughts":true},"temperature":0.3,"topP":0.8})
|
||||
);
|
||||
assert_eq!(body["toolConfig"]["functionCallingConfig"]["mode"], "ANY");
|
||||
if choice["type"] == "function" {
|
||||
assert_eq!(
|
||||
body["toolConfig"]["functionCallingConfig"]["allowedFunctionNames"],
|
||||
json!(["lookup"])
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reasoning_budgets_do_not_inherit_messages_limits() {
|
||||
for (effort, budget) in [
|
||||
("none", 0),
|
||||
("minimal", 1024),
|
||||
("low", 1024),
|
||||
("medium", 8192),
|
||||
("high", 24576),
|
||||
("xhigh", 32768),
|
||||
("max", 128000),
|
||||
("auto", -1),
|
||||
] {
|
||||
let request = json!({"input":"hello","reasoning":{"effort":effort}});
|
||||
let body = responses_to_genai_request(request.as_object().unwrap()).unwrap();
|
||||
let thinking = &body["generationConfig"]["thinkingConfig"];
|
||||
assert_eq!(thinking["thinkingBudget"], budget, "{effort}");
|
||||
assert_eq!(
|
||||
thinking.get("includeThoughts"),
|
||||
(budget != 0).then_some(&json!(true))
|
||||
);
|
||||
assert!(body["generationConfig"].get("maxOutputTokens").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_output_limits_must_be_positive_integers() {
|
||||
for maximum in [json!(0), json!(-1), json!(1.5), json!("128"), json!(true)] {
|
||||
let request = json!({"input":"hello","max_output_tokens":maximum});
|
||||
assert!(
|
||||
responses_to_genai_request(request.as_object().unwrap()).is_err(),
|
||||
"{maximum}"
|
||||
);
|
||||
}
|
||||
for maximum in [1, 128, 100000] {
|
||||
let request = json!({"input":"hello","max_output_tokens":maximum});
|
||||
let body = responses_to_genai_request(request.as_object().unwrap()).unwrap();
|
||||
assert_eq!(body["generationConfig"]["maxOutputTokens"], maximum);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_and_json_schema_preserve_their_target_representation() {
|
||||
let request = json!({"instructions":"system","input":[{"role":"user","content":[
|
||||
{"type":"input_text","text":"hello"},
|
||||
{"type":"input_image","image_url":"data:image/png;base64,AA=="}
|
||||
]}],"text":{"format":{"type":"json_schema","name":"answer","schema":{"type":"object","properties":{"answer":{"type":"string"}}}}}});
|
||||
let body = responses_to_genai_request(request.as_object().unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
body["systemInstruction"]["parts"],
|
||||
json!([{"text":"system"}])
|
||||
);
|
||||
assert_eq!(
|
||||
body["contents"][0]["parts"],
|
||||
json!([{"text":"hello"},{"inlineData":{"mimeType":"image/png","data":"AA=="}}])
|
||||
);
|
||||
assert_eq!(
|
||||
body["generationConfig"],
|
||||
json!({"responseMimeType":"application/json","responseSchema":request["text"]["format"]["schema"]})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parallel_tool_results_keep_call_order_and_native_media() {
|
||||
let request = json!({"input":[
|
||||
{"type":"custom_tool_call","call_id":"a","name":"display","namespace":"screen","input":"shot"},
|
||||
{"type":"function_call","call_id":"b","name":"lookup","arguments":"{}"},
|
||||
{"type":"function_call_output","call_id":"b","output":{"value":2}},
|
||||
{"type":"custom_tool_call_output","call_id":"a","output":"stale"},
|
||||
{"type":"custom_tool_call_output","call_id":"a","status":"incomplete","output":[
|
||||
{"type":"input_text","text":"captured"},
|
||||
{"type":"input_image","image_url":"data:image/png;base64,AA=="},
|
||||
{"type":"input_file","file_data":"data:application/pdf;base64,AQ=="}
|
||||
]}
|
||||
], "tools":[{"type":"namespace","name":"screen","tools":[{"type":"custom","name":"display"}]}],
|
||||
"tool_choice":{"type":"custom","name":"display","namespace":"screen"}});
|
||||
let body = responses_to_genai_request(request.as_object().unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
body["toolConfig"]["functionCallingConfig"]["allowedFunctionNames"],
|
||||
json!(["screen__display"])
|
||||
);
|
||||
assert_eq!(
|
||||
body["contents"][1]["parts"],
|
||||
json!([
|
||||
{"functionResponse":{"id":"a","name":"screen__display","response":{"error":"captured"},"parts":[
|
||||
{"inlineData":{"mimeType":"image/png","data":"AA=="}},{"inlineData":{"mimeType":"application/pdf","data":"AQ=="}}
|
||||
]}},
|
||||
{"functionResponse":{"id":"b","name":"lookup","response":{"output":{"value":2}}}}
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn late_tool_results_remain_in_user_order_and_do_not_close_earlier_turns() {
|
||||
let request = json!({"input":[
|
||||
{"type":"function_call","name":"tool","call_id":"a","arguments":"{}"},
|
||||
{"role":"user","content":"continue"},
|
||||
{"role":"assistant","content":"ok"},
|
||||
{"role":"user","content":"before"},
|
||||
{"type":"reasoning","summary":[],"encrypted_content":"opaque-other-model"},
|
||||
{"type":"function_call_output","call_id":"a","output":[{"type":"input_text","text":"late"}]},
|
||||
{"role":"user","content":"after"}
|
||||
]});
|
||||
let body = responses_to_genai_request(request.as_object().unwrap()).unwrap();
|
||||
assert!(body["contents"][1]["parts"][0]["functionResponse"]["response"]["error"].is_string());
|
||||
assert_eq!(
|
||||
body["contents"][3]["parts"],
|
||||
json!([{"text":"before"},{"text":"late"},{"text":"after"}])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_tool_selection_requires_the_declared_type_and_namespace() {
|
||||
let function = json!({"type":"function","name":"read"});
|
||||
for choice in [
|
||||
json!({"type":"function","name":"read","namespace":"missing"}),
|
||||
json!({"type":"custom","name":"read"}),
|
||||
] {
|
||||
let request = json!({"input":"read","tools":[function],"tool_choice":choice});
|
||||
assert!(responses_to_genai_request(request.as_object().unwrap()).is_err());
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//! 原生完整请求优先级和 Messages 计数投影合同
|
||||
|
||||
use gateway_protocol::genai::{count_tokens_request, count_tokens_to_messages};
|
||||
use gateway_protocol::genai::count_tokens_request;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
@@ -17,22 +17,3 @@ fn full_request_wins_over_outer_contents_and_keeps_tools() {
|
||||
count_tokens_request(json!({"generateContentRequest":null}).as_object().unwrap()).is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn messages_count_never_estimates_or_invents_zero() {
|
||||
assert_eq!(
|
||||
count_tokens_to_messages(&json!({"totalTokens":0})).unwrap(),
|
||||
json!({"input_tokens":0})
|
||||
);
|
||||
assert_eq!(
|
||||
count_tokens_to_messages(&json!({"totalTokens":77,"future":true})).unwrap(),
|
||||
json!({"input_tokens":77})
|
||||
);
|
||||
for invalid in [
|
||||
json!({}),
|
||||
json!({"totalTokens":-1}),
|
||||
json!({"totalTokens":"77"}),
|
||||
] {
|
||||
assert!(count_tokens_to_messages(&invalid).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,3 +4,5 @@ mod anthropic;
|
||||
mod genai;
|
||||
mod openai;
|
||||
mod request;
|
||||
|
||||
mod chat_completions;
|
||||
|
||||
@@ -205,10 +205,7 @@ impl CatalogService {
|
||||
)
|
||||
.with_dedicated_web_search(search_models)
|
||||
.with_generation_protocol(gateway_protocol::genai::GENAI_PROTOCOL)
|
||||
.with_translated_generation_protocols([
|
||||
gateway_protocol::openai::OPENAI_PROTOCOL,
|
||||
gateway_protocol::anthropic::ANTHROPIC_PROTOCOL,
|
||||
])
|
||||
.with_translated_generation_protocols([gateway_protocol::chat_completions::CHAT_PROTOCOL])
|
||||
.with_upstream_feature_validation();
|
||||
let mut models = BTreeMap::new();
|
||||
for (id, metadata) in members {
|
||||
|
||||
@@ -5,7 +5,7 @@ use gateway_core::{
|
||||
operation::Operation, policy::ClientApiKeyId, provider_ports::ProviderSessionAffinityKey,
|
||||
routing::UpstreamModelId,
|
||||
};
|
||||
use gateway_protocol::{anthropic, genai, openai};
|
||||
use gateway_protocol::{chat_completions::CHAT_PROTOCOL, genai};
|
||||
use serde_json::{Map, Value};
|
||||
use sha2::{Digest as _, Sha256};
|
||||
|
||||
@@ -19,13 +19,8 @@ pub(super) fn session_key(
|
||||
};
|
||||
let payload = generate.protocol_payload();
|
||||
let session = match payload.protocol() {
|
||||
openai::OPENAI_PROTOCOL => {
|
||||
openai::codex_account_session_id(payload.body(), payload.context())
|
||||
}
|
||||
anthropic::ANTHROPIC_PROTOCOL => anthropic::claude_session_id(
|
||||
payload.body(),
|
||||
header(payload.context(), "x-claude-code-session-id").as_deref(),
|
||||
),
|
||||
CHAT_PROTOCOL => header(payload.context(), "x-http-session-id")
|
||||
.or_else(|| header(payload.context(), "x-session-id")),
|
||||
genai::GENAI_PROTOCOL => header(payload.context(), "x-http-session-id")
|
||||
.or_else(|| header(payload.context(), "x-session-id"))
|
||||
.or_else(|| {
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
//! Chat 直接装配 GenAI,请求转换和响应状态不接触账号租约
|
||||
|
||||
use crate::transport::{sent, unsent};
|
||||
use gateway_core::{
|
||||
engine::{AttemptContext, provider::NativeResponseTranslator},
|
||||
error::{ProviderError, ProviderErrorKind},
|
||||
event::ProtocolWireEvent,
|
||||
operation::Operation,
|
||||
provider_ports::ProviderSessionAffinityKey,
|
||||
};
|
||||
use gateway_protocol::{
|
||||
chat_completions::{CHAT_PROTOCOL, ChatIdentity, genai},
|
||||
genai::GENAI_PROTOCOL,
|
||||
};
|
||||
use serde_json::{Map, Value};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
pub(super) fn prepare(
|
||||
operation: Operation,
|
||||
context: &AttemptContext,
|
||||
affinity: Option<&ProviderSessionAffinityKey>,
|
||||
) -> Result<(Operation, Option<Translator>), ProviderError> {
|
||||
let Operation::Generate(generate) = &operation else {
|
||||
return Err(unsent(ProviderErrorKind::Unsupported));
|
||||
};
|
||||
let payload = generate.protocol_payload();
|
||||
if payload.protocol() == GENAI_PROTOCOL {
|
||||
return Ok((operation, None));
|
||||
}
|
||||
if payload.protocol() != CHAT_PROTOCOL || generate.source_protocol() != CHAT_PROTOCOL {
|
||||
return Err(unsent(ProviderErrorKind::Unsupported));
|
||||
}
|
||||
let original = payload.body();
|
||||
let streaming = original
|
||||
.get("stream")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false);
|
||||
let include_usage = !streaming
|
||||
|| original
|
||||
.get("stream_options")
|
||||
.and_then(|options| options.get("include_usage"))
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false);
|
||||
let identity = ChatIdentity {
|
||||
id: format!("chatcmpl-{}", context.request_id().as_str()),
|
||||
created: SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs(),
|
||||
model: original
|
||||
.get("model")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default()
|
||||
.to_owned(),
|
||||
};
|
||||
let mut body = genai::convert_request(original)
|
||||
.map_err(|error| unsent(ProviderErrorKind::InvalidRequest).with_source(error))?;
|
||||
if let Some(session) = affinity {
|
||||
body.insert(
|
||||
"sessionId".to_owned(),
|
||||
Value::String(super::affinity::upstream_session_id(session)),
|
||||
);
|
||||
}
|
||||
let translator = Translator {
|
||||
encoder: genai::ChatStreamEncoder::with_request(identity.clone(), include_usage, original),
|
||||
identity,
|
||||
// 完整 JSON 的投影只需工具声明,不重复保存对话正文
|
||||
original: original
|
||||
.get("tools")
|
||||
.map(|tools| Map::from_iter([("tools".into(), tools.clone())]))
|
||||
.unwrap_or_default(),
|
||||
streaming,
|
||||
include_usage,
|
||||
complete_json: false,
|
||||
};
|
||||
let mut wire_context = payload.context().clone();
|
||||
// 托管搜索的 Cloud Code 端点只返回 JSON,响应仍直接投影到所需的 Chat 交付形式
|
||||
wire_context.insert(
|
||||
"stream".to_owned(),
|
||||
Value::Bool(streaming && !operation.requires_web_search()),
|
||||
);
|
||||
let body = serde_json::to_vec(&body).map_err(|_| unsent(ProviderErrorKind::InvalidRequest))?;
|
||||
let operation = operation
|
||||
.replace_protocol_wire(None, wire_context)
|
||||
.and_then(|operation| operation.translate_protocol_wire(GENAI_PROTOCOL, body.into()))
|
||||
.map_err(|_| unsent(ProviderErrorKind::InvalidRequest))?;
|
||||
Ok((operation, Some(translator)))
|
||||
}
|
||||
|
||||
pub(super) struct Translator {
|
||||
identity: ChatIdentity,
|
||||
original: Map<String, Value>,
|
||||
encoder: genai::ChatStreamEncoder,
|
||||
streaming: bool,
|
||||
include_usage: bool,
|
||||
complete_json: bool,
|
||||
}
|
||||
|
||||
impl NativeResponseTranslator for Translator {
|
||||
fn source_protocol(&self) -> &str {
|
||||
GENAI_PROTOCOL
|
||||
}
|
||||
fn target_protocol(&self) -> &str {
|
||||
CHAT_PROTOCOL
|
||||
}
|
||||
|
||||
fn translate(
|
||||
&mut self,
|
||||
event: &ProtocolWireEvent,
|
||||
) -> Result<Vec<ProtocolWireEvent>, ProviderError> {
|
||||
if self.complete_json {
|
||||
return Err(sent(ProviderErrorKind::Protocol));
|
||||
}
|
||||
if let Some(raw) = event.raw_json_body() {
|
||||
let body =
|
||||
serde_json::from_slice(raw).map_err(|_| sent(ProviderErrorKind::Protocol))?;
|
||||
let value = genai::project_response_with_request(&body, &self.identity, &self.original)
|
||||
.map_err(|error| sent(ProviderErrorKind::Protocol).with_source(error))?;
|
||||
self.complete_json = true;
|
||||
if self.streaming {
|
||||
return wire_events(
|
||||
gateway_protocol::chat_completions::completion_chunks(
|
||||
&value,
|
||||
self.include_usage,
|
||||
)
|
||||
.map_err(|error| sent(ProviderErrorKind::Protocol).with_source(error))?,
|
||||
);
|
||||
}
|
||||
return ProtocolWireEvent::raw_json(
|
||||
CHAT_PROTOCOL,
|
||||
serde_json::to_vec(&value)
|
||||
.map_err(|_| sent(ProviderErrorKind::Protocol))?
|
||||
.into(),
|
||||
)
|
||||
.map(|wire| vec![wire])
|
||||
.map_err(|_| sent(ProviderErrorKind::Protocol));
|
||||
}
|
||||
if !event.has_json_data() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let chunks = self
|
||||
.encoder
|
||||
.push_event(event.event_type(), event.data())
|
||||
.map_err(|error| sent(ProviderErrorKind::Protocol).with_source(error))?;
|
||||
wire_events(chunks)
|
||||
}
|
||||
|
||||
fn finish(&mut self) -> Result<Vec<ProtocolWireEvent>, ProviderError> {
|
||||
if self.complete_json {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
wire_events(
|
||||
self.encoder
|
||||
.finish()
|
||||
.map_err(|error| sent(ProviderErrorKind::Protocol).with_source(error))?,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn wire_events(chunks: Vec<Value>) -> Result<Vec<ProtocolWireEvent>, ProviderError> {
|
||||
chunks
|
||||
.into_iter()
|
||||
.map(|chunk| {
|
||||
ProtocolWireEvent::json(CHAT_PROTOCOL, None, chunk)
|
||||
.map_err(|_| sent(ProviderErrorKind::Protocol))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
//! GenAI 原生计数与 Provider 计数端点的正文解包
|
||||
|
||||
use crate::transport::{sent, unsent};
|
||||
use gateway_core::{
|
||||
engine::provider::NativeResponseTranslator,
|
||||
error::{ProviderError, ProviderErrorKind},
|
||||
event::ProtocolWireEvent,
|
||||
operation::Operation,
|
||||
};
|
||||
use gateway_protocol::genai::{GENAI_PROTOCOL, count_tokens_request};
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
pub(super) fn prepare(
|
||||
operation: Operation,
|
||||
) -> Result<(Operation, Option<Translator>), ProviderError> {
|
||||
let Operation::CountTokens(request) = &operation else {
|
||||
return Err(unsent(ProviderErrorKind::Unsupported));
|
||||
};
|
||||
let source = request.payload().protocol();
|
||||
if !matches!(source, GENAI_PROTOCOL | "token-count") {
|
||||
return Err(unsent(ProviderErrorKind::Unsupported));
|
||||
}
|
||||
let body: Map<String, Value> = serde_json::from_slice(request.payload().body())
|
||||
.map_err(|error| unsent(ProviderErrorKind::InvalidRequest).with_source(error))?;
|
||||
let body = count_tokens_request(&body)
|
||||
.map_err(|error| unsent(ProviderErrorKind::InvalidRequest).with_source(error))?;
|
||||
let bytes = serde_json::to_vec(body).map_err(|_| unsent(ProviderErrorKind::InvalidRequest))?;
|
||||
let translated = source == "token-count";
|
||||
let operation = if translated {
|
||||
operation.translate_protocol_wire(GENAI_PROTOCOL, bytes.into())
|
||||
} else {
|
||||
let context = request.payload().context().clone();
|
||||
operation.replace_protocol_wire(Some(bytes.into()), context)
|
||||
}
|
||||
.map_err(|_| unsent(ProviderErrorKind::InvalidRequest))?;
|
||||
Ok((operation, translated.then_some(Translator)))
|
||||
}
|
||||
|
||||
pub(super) struct Translator;
|
||||
|
||||
impl NativeResponseTranslator for Translator {
|
||||
fn source_protocol(&self) -> &str {
|
||||
GENAI_PROTOCOL
|
||||
}
|
||||
fn target_protocol(&self) -> &str {
|
||||
"token-count"
|
||||
}
|
||||
fn translate(
|
||||
&mut self,
|
||||
event: &ProtocolWireEvent,
|
||||
) -> Result<Vec<ProtocolWireEvent>, ProviderError> {
|
||||
let wire = match event.raw_json_body() {
|
||||
Some(raw) => ProtocolWireEvent::raw_json("token-count", raw.clone()),
|
||||
None => ProtocolWireEvent::json("token-count", None, event.data().clone()),
|
||||
};
|
||||
wire.map(|wire| vec![wire])
|
||||
.map_err(|_| sent(ProviderErrorKind::Protocol))
|
||||
}
|
||||
}
|
||||
@@ -7,13 +7,11 @@ use gateway_core::{
|
||||
account::AccountHistorySnapshot,
|
||||
engine::{
|
||||
AttemptContext,
|
||||
execution::ClientTransport,
|
||||
provider::{
|
||||
ProviderCallMetadata, ProviderRequest, ProviderSelectionObservation, ProviderStream,
|
||||
},
|
||||
},
|
||||
error::{ProviderError, ProviderErrorKind as Kind},
|
||||
event::GatewayEvent,
|
||||
operation::Operation,
|
||||
upstream::{UpstreamSendState, UpstreamTransport},
|
||||
};
|
||||
@@ -26,17 +24,16 @@ impl AntigravityProvider {
|
||||
request: ProviderRequest,
|
||||
ctx: AttemptContext,
|
||||
) -> Result<ProviderStream, ProviderError> {
|
||||
if !matches!(
|
||||
request.operation().protocol(),
|
||||
GENAI_PROTOCOL
|
||||
| "token-count"
|
||||
| gateway_protocol::openai::OPENAI_PROTOCOL
|
||||
| gateway_protocol::anthropic::ANTHROPIC_PROTOCOL
|
||||
) {
|
||||
return Err(unsent(Kind::Unsupported));
|
||||
match request.operation() {
|
||||
Operation::Generate(_)
|
||||
if matches!(
|
||||
request.operation().protocol(),
|
||||
GENAI_PROTOCOL | gateway_protocol::chat_completions::CHAT_PROTOCOL
|
||||
) => {}
|
||||
Operation::CountTokens(count)
|
||||
if matches!(count.payload().protocol(), GENAI_PROTOCOL | "token-count") => {}
|
||||
_ => return Err(unsent(Kind::Unsupported)),
|
||||
}
|
||||
// 在选号和中间件改写前保留客户端的非生成与续接语义
|
||||
super::translation::validate_request_mode(request.operation())?;
|
||||
let model = request
|
||||
.candidate()
|
||||
.upstream_model()
|
||||
@@ -88,10 +85,7 @@ impl AntigravityProvider {
|
||||
.get(self.kind.as_str())
|
||||
.and_then(|models| models.get(model.as_str())),
|
||||
);
|
||||
// AGY 没有可跨轮引用的响应,Responses WS 客户端可在新连接上直接发送完整输入
|
||||
let transport = ctx.client_transport();
|
||||
let reconnect_websocket = transport == ClientTransport::WebSocket
|
||||
&& request.operation().protocol() == gateway_protocol::openai::OPENAI_PROTOCOL;
|
||||
let terminal_context = ctx.clone();
|
||||
ctx.execute_middleware(
|
||||
request.operation().clone(),
|
||||
self.kind.clone(),
|
||||
@@ -101,7 +95,13 @@ impl AntigravityProvider {
|
||||
if operation.requires_web_search() != search {
|
||||
return Err(ProviderError::invalid_request("Middleware changed the required web search after model selection."));
|
||||
}
|
||||
let (operation, translator) = super::translation::prepare(operation, transport, affinity.as_ref())?;
|
||||
let (operation, translator, count_translator) = if matches!(operation, Operation::CountTokens(_)) {
|
||||
let (operation, translator) = super::count::prepare(operation)?;
|
||||
(operation, None, translator)
|
||||
} else {
|
||||
let (operation, translator) = super::chat::prepare(operation, &terminal_context, affinity.as_ref())?;
|
||||
(operation, translator, None)
|
||||
};
|
||||
let headers = crate::transport::request_headers(&operation, headers, selected.account_switch);
|
||||
if operation.protocol() != GENAI_PROTOCOL {
|
||||
return Err(unsent(Kind::Unsupported));
|
||||
@@ -158,15 +158,10 @@ impl AntigravityProvider {
|
||||
Box::pin(crate::transport::events(response, context))
|
||||
};
|
||||
while let Some(event) = events.next().await {
|
||||
let mut event = match event {
|
||||
let event = match event {
|
||||
Ok(event) => event,
|
||||
Err(error) => Err(record_failure(error).await)?,
|
||||
};
|
||||
if reconnect_websocket && event.canonical_facts().iter()
|
||||
.any(|fact| matches!(fact, GatewayEvent::Completed(_)))
|
||||
{
|
||||
event.request_websocket_reconnect();
|
||||
}
|
||||
yield event;
|
||||
}
|
||||
};
|
||||
@@ -175,6 +170,10 @@ impl AntigravityProvider {
|
||||
Some(translator) => stream.with_native_response_translator(translator),
|
||||
None => stream,
|
||||
};
|
||||
let stream = match count_translator {
|
||||
Some(translator) => stream.with_native_response_translator(translator),
|
||||
None => stream,
|
||||
};
|
||||
Ok(match stats {
|
||||
Some(stats) => stream.with_account_feedback(stats),
|
||||
None => stream,
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
|
||||
mod affinity;
|
||||
mod candidates;
|
||||
mod chat;
|
||||
mod count;
|
||||
mod execution;
|
||||
mod feedback;
|
||||
mod selection;
|
||||
mod translation;
|
||||
pub(crate) mod workers;
|
||||
|
||||
use crate::{
|
||||
@@ -17,8 +18,8 @@ use gateway_core::{
|
||||
account::{AccountFeedbackStats, ProviderAccountId, ProviderAccountStore},
|
||||
concurrency::ConcurrencyWaitQueue,
|
||||
engine::{
|
||||
AttemptContext, ModelRequestId,
|
||||
provider::{LocalWebSocketPrewarm, Provider, ProviderRequest, ProviderStream},
|
||||
AttemptContext,
|
||||
provider::{Provider, ProviderRequest, ProviderStream},
|
||||
},
|
||||
error::{ErrorSource, ProviderError, ProviderErrorKind},
|
||||
provider_ports::{
|
||||
@@ -74,14 +75,6 @@ impl AntigravityProvider {
|
||||
|
||||
#[async_trait]
|
||||
impl Provider for AntigravityProvider {
|
||||
fn local_websocket_prewarm(
|
||||
&self,
|
||||
operation: &gateway_core::operation::Operation,
|
||||
request_id: &ModelRequestId,
|
||||
) -> Option<LocalWebSocketPrewarm> {
|
||||
translation::websocket_prewarm(operation, request_id)
|
||||
}
|
||||
|
||||
fn is_direct_account(&self, authentication_kind: &str) -> bool {
|
||||
authentication_kind == "oauth"
|
||||
}
|
||||
@@ -136,5 +129,3 @@ fn unavailable(error: impl Into<ErrorSource>) -> ProviderError {
|
||||
crate::transport::unsent(ProviderErrorKind::ProviderInfrastructureUnavailable)
|
||||
.with_source(error)
|
||||
}
|
||||
|
||||
mod web_search;
|
||||
|
||||
@@ -1,316 +0,0 @@
|
||||
//! 跨协议请求使用共享转换器,原生响应转换在 Core 中间件阶段之间执行
|
||||
|
||||
use crate::transport::{sent, unsent};
|
||||
use gateway_core::{
|
||||
engine::{
|
||||
ModelRequestId,
|
||||
execution::ClientTransport,
|
||||
provider::{LocalWebSocketPrewarm, NativeResponseTranslator},
|
||||
},
|
||||
error::{ClientVisibleUpstreamError, ProviderError, ProviderErrorKind},
|
||||
event::ProtocolWireEvent,
|
||||
operation::{Operation, ProtocolPayload},
|
||||
provider_ports::ProviderSessionAffinityKey,
|
||||
upstream::UpstreamSendState,
|
||||
};
|
||||
use gateway_protocol::{
|
||||
anthropic::{ANTHROPIC_PROTOCOL, MessagesToResponsesStream},
|
||||
genai::{
|
||||
GENAI_PROTOCOL, GenAiToMessagesStream, messages_to_genai_request,
|
||||
responses_to_genai_request,
|
||||
},
|
||||
openai::{OPENAI_PROTOCOL, web_search},
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use std::borrow::Cow;
|
||||
|
||||
fn is_root_prewarm(payload: &ProtocolPayload) -> bool {
|
||||
let body = payload.body();
|
||||
payload.protocol() == OPENAI_PROTOCOL
|
||||
&& body.get("generate").and_then(Value::as_bool) == Some(false)
|
||||
&& body.get("previous_response_id").is_none_or(Value::is_null)
|
||||
}
|
||||
|
||||
pub(super) fn websocket_prewarm(
|
||||
operation: &Operation,
|
||||
request_id: &ModelRequestId,
|
||||
) -> Option<LocalWebSocketPrewarm> {
|
||||
let Operation::Generate(generate) = operation else {
|
||||
return None;
|
||||
};
|
||||
let payload = generate.protocol_payload();
|
||||
if !is_root_prewarm(payload) {
|
||||
return None;
|
||||
}
|
||||
let model = payload.body().get("model")?.as_str()?;
|
||||
let response_id = format!("resp_prewarm_{}", request_id.as_str());
|
||||
let timestamp = chrono::Utc::now().timestamp();
|
||||
let frame = |kind: &str, sequence: u8, status: &str, usage: Value| {
|
||||
let data = json!({
|
||||
"type": kind,
|
||||
"sequence_number": sequence,
|
||||
"response": {
|
||||
"id": response_id, "object": "response", "created_at": timestamp, "model": model,
|
||||
"status": status, "error": null, "output": [], "usage": usage
|
||||
}
|
||||
});
|
||||
ProtocolWireEvent::json(OPENAI_PROTOCOL, Some(kind.to_owned()), data).ok()
|
||||
};
|
||||
let created = frame("response.created", 0, "in_progress", Value::Null)?;
|
||||
let usage = json!({"input_tokens": 0, "output_tokens": 0, "total_tokens": 0});
|
||||
let completed = frame("response.completed", 1, "completed", usage)?;
|
||||
Some(LocalWebSocketPrewarm {
|
||||
response_id,
|
||||
created,
|
||||
completed,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn validate_request_mode(operation: &Operation) -> Result<(), ProviderError> {
|
||||
let Operation::Generate(generate) = operation else {
|
||||
return Ok(());
|
||||
};
|
||||
let payload = generate.protocol_payload();
|
||||
if !matches!(payload.protocol(), OPENAI_PROTOCOL | ANTHROPIC_PROTOCOL) {
|
||||
return Ok(());
|
||||
}
|
||||
// 带父响应的预热也需要重放;其余未在 WS 入口完成的预热不能触发推理
|
||||
if is_root_prewarm(payload) {
|
||||
return Err(
|
||||
unsent(ProviderErrorKind::InvalidRequest).with_client_visible_upstream_error(
|
||||
ClientVisibleUpstreamError::new(
|
||||
"Antigravity supports prewarm only on a new Responses WebSocket chain.",
|
||||
Some("unsupported_prewarm".to_owned()),
|
||||
Some("invalid_request_error".to_owned()),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
match payload.body().get("previous_response_id") {
|
||||
None | Some(Value::Null) => Ok(()),
|
||||
Some(Value::String(id))
|
||||
if payload.protocol() == OPENAI_PROTOCOL && !id.trim().is_empty() =>
|
||||
{
|
||||
Err(ProviderError::responses_replay_required(
|
||||
"scope_unavailable",
|
||||
UpstreamSendState::NotSent,
|
||||
))
|
||||
}
|
||||
_ => Err(unsent(ProviderErrorKind::InvalidRequest)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn prepare(
|
||||
operation: Operation,
|
||||
transport: ClientTransport,
|
||||
affinity: Option<&ProviderSessionAffinityKey>,
|
||||
) -> Result<(Operation, Option<Translator>), ProviderError> {
|
||||
if matches!(operation, Operation::CountTokens(_)) {
|
||||
return prepare_count(operation);
|
||||
}
|
||||
let Operation::Generate(generate) = &operation else {
|
||||
return Err(unsent(ProviderErrorKind::Unsupported));
|
||||
};
|
||||
let payload = generate.protocol_payload();
|
||||
let source = payload.protocol();
|
||||
if source == GENAI_PROTOCOL {
|
||||
return Ok((operation, None));
|
||||
}
|
||||
if !matches!(source, OPENAI_PROTOCOL | ANTHROPIC_PROTOCOL) {
|
||||
return Err(unsent(ProviderErrorKind::Unsupported));
|
||||
}
|
||||
let original = payload.body();
|
||||
// attempt 中间件可能改变预热或续接字段
|
||||
validate_request_mode(&operation)?;
|
||||
let search = if source == OPENAI_PROTOCOL {
|
||||
web_search::required_tool(original)
|
||||
.map_err(|error| ProviderError::invalid_request(error.message()).with_source(error))?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut body = if let Some(tool) = search {
|
||||
super::web_search::request(original, tool)?
|
||||
} else {
|
||||
if source == OPENAI_PROTOCOL {
|
||||
responses_to_genai_request(original)
|
||||
} else {
|
||||
messages_to_genai_request(original)
|
||||
}
|
||||
.map_err(|e| unsent(ProviderErrorKind::InvalidRequest).with_source(e))?
|
||||
};
|
||||
if let Some(session) = affinity {
|
||||
body.insert(
|
||||
"sessionId".into(),
|
||||
json!(super::affinity::upstream_session_id(session)),
|
||||
);
|
||||
}
|
||||
let model = original
|
||||
.get("model")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default()
|
||||
.to_owned();
|
||||
let translator = if search.is_some() {
|
||||
Translator::Search(Box::new(super::web_search::SearchResponse::new(original)))
|
||||
} else {
|
||||
Translator::Generate(Box::new(GenerationTranslator {
|
||||
genai: GenAiToMessagesStream::new(model),
|
||||
responses: (source == OPENAI_PROTOCOL)
|
||||
.then(|| MessagesToResponsesStream::new(original)),
|
||||
}))
|
||||
};
|
||||
let mut context = payload.context().clone();
|
||||
// HTTP 和 WS 的交付模式在入口已确定,内部探测默认保留首输出观测
|
||||
let stream = match transport {
|
||||
ClientTransport::HttpJson => false,
|
||||
ClientTransport::HttpSse | ClientTransport::WebSocket => true,
|
||||
ClientTransport::InternalProbe | ClientTransport::InternalPlugin => original
|
||||
.get("stream")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(true),
|
||||
};
|
||||
context.insert("stream".into(), json!(search.is_none() && stream));
|
||||
let bytes = serde_json::to_vec(&body).map_err(|_| unsent(ProviderErrorKind::InvalidRequest))?;
|
||||
let operation = operation
|
||||
.replace_protocol_wire(None, context)
|
||||
.and_then(|operation| operation.translate_protocol_wire(GENAI_PROTOCOL, bytes.into()))
|
||||
.map_err(|_| unsent(ProviderErrorKind::InvalidRequest))?;
|
||||
Ok((operation, Some(translator)))
|
||||
}
|
||||
|
||||
pub(super) enum Translator {
|
||||
Generate(Box<GenerationTranslator>),
|
||||
Search(Box<super::web_search::SearchResponse>),
|
||||
Count(&'static str),
|
||||
}
|
||||
|
||||
pub(super) struct GenerationTranslator {
|
||||
genai: GenAiToMessagesStream,
|
||||
responses: Option<MessagesToResponsesStream>,
|
||||
}
|
||||
|
||||
impl GenerationTranslator {
|
||||
fn target_protocol(&self) -> &'static str {
|
||||
if self.responses.is_some() {
|
||||
OPENAI_PROTOCOL
|
||||
} else {
|
||||
ANTHROPIC_PROTOCOL
|
||||
}
|
||||
}
|
||||
|
||||
fn events(&mut self, events: Vec<Value>) -> Result<Vec<ProtocolWireEvent>, ProviderError> {
|
||||
let mut wire = Vec::new();
|
||||
for event in events {
|
||||
let events = if let Some(responses) = &mut self.responses {
|
||||
responses
|
||||
.push(&event)
|
||||
.map_err(|e| sent(ProviderErrorKind::Protocol).with_source(e))?
|
||||
} else {
|
||||
vec![event]
|
||||
};
|
||||
for event in events {
|
||||
wire.push(
|
||||
ProtocolWireEvent::json(
|
||||
self.target_protocol(),
|
||||
event["type"].as_str().map(str::to_owned),
|
||||
event,
|
||||
)
|
||||
.map_err(|_| sent(ProviderErrorKind::Protocol))?,
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(wire)
|
||||
}
|
||||
}
|
||||
|
||||
impl NativeResponseTranslator for Translator {
|
||||
fn source_protocol(&self) -> &str {
|
||||
GENAI_PROTOCOL
|
||||
}
|
||||
fn target_protocol(&self) -> &str {
|
||||
match self {
|
||||
Self::Generate(translator) => translator.target_protocol(),
|
||||
Self::Search(_) => OPENAI_PROTOCOL,
|
||||
Self::Count(protocol) => protocol,
|
||||
}
|
||||
}
|
||||
fn translate(
|
||||
&mut self,
|
||||
event: &ProtocolWireEvent,
|
||||
) -> Result<Vec<ProtocolWireEvent>, ProviderError> {
|
||||
if let Self::Search(search) = self {
|
||||
return search.translate(event);
|
||||
}
|
||||
let value = match event.raw_json_body() {
|
||||
Some(raw) => Cow::Owned(
|
||||
serde_json::from_slice(raw).map_err(|_| sent(ProviderErrorKind::Protocol))?,
|
||||
),
|
||||
None => Cow::Borrowed(event.data()),
|
||||
};
|
||||
let Self::Generate(translator) = self else {
|
||||
let body = if self.target_protocol() == ANTHROPIC_PROTOCOL {
|
||||
gateway_protocol::genai::count_tokens_to_messages(&value)
|
||||
.map_err(|e| sent(ProviderErrorKind::Protocol).with_source(e))?
|
||||
} else {
|
||||
value.into_owned()
|
||||
};
|
||||
return Ok(vec![
|
||||
ProtocolWireEvent::json(self.target_protocol(), None, body)
|
||||
.map_err(|_| sent(ProviderErrorKind::Protocol))?,
|
||||
]);
|
||||
};
|
||||
let events = translator
|
||||
.genai
|
||||
.push(&value)
|
||||
.map_err(|e| sent(ProviderErrorKind::Protocol).with_source(e))?;
|
||||
translator.events(events)
|
||||
}
|
||||
fn finish(&mut self) -> Result<Vec<ProtocolWireEvent>, ProviderError> {
|
||||
if let Self::Search(search) = self {
|
||||
return search.finish();
|
||||
}
|
||||
let Self::Generate(translator) = self else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
|
||||
let events = translator
|
||||
.genai
|
||||
.finish()
|
||||
.map_err(|e| sent(ProviderErrorKind::Protocol).with_source(e))?;
|
||||
translator.events(events)
|
||||
}
|
||||
}
|
||||
|
||||
fn prepare_count(operation: Operation) -> Result<(Operation, Option<Translator>), ProviderError> {
|
||||
let Operation::CountTokens(request) = &operation else {
|
||||
return Err(unsent(ProviderErrorKind::Unsupported));
|
||||
};
|
||||
let source = request.payload().protocol();
|
||||
let body: serde_json::Map<String, Value> = serde_json::from_slice(request.payload().body())
|
||||
.map_err(|e| unsent(ProviderErrorKind::InvalidRequest).with_source(e))?;
|
||||
let body = match source {
|
||||
ANTHROPIC_PROTOCOL => {
|
||||
gateway_protocol::anthropic::validate_count_request(&body)
|
||||
.map_err(|e| unsent(ProviderErrorKind::InvalidRequest).with_source(e))?;
|
||||
messages_to_genai_request(&body).map(Cow::Owned)
|
||||
}
|
||||
GENAI_PROTOCOL | "token-count" => {
|
||||
gateway_protocol::genai::count_tokens_request(&body).map(Cow::Borrowed)
|
||||
}
|
||||
_ => return Err(unsent(ProviderErrorKind::Unsupported)),
|
||||
}
|
||||
.map_err(|e| unsent(ProviderErrorKind::InvalidRequest).with_source(e))?;
|
||||
let translator = match source {
|
||||
ANTHROPIC_PROTOCOL => Some(Translator::Count(ANTHROPIC_PROTOCOL)),
|
||||
"token-count" => Some(Translator::Count("token-count")),
|
||||
_ => None,
|
||||
};
|
||||
let bytes = serde_json::to_vec(&body).map_err(|_| unsent(ProviderErrorKind::InvalidRequest))?;
|
||||
let operation = if source == GENAI_PROTOCOL {
|
||||
let context = request.payload().context().clone();
|
||||
operation.replace_protocol_wire(Some(bytes.into()), context)
|
||||
} else {
|
||||
operation.translate_protocol_wire(GENAI_PROTOCOL, bytes.into())
|
||||
}
|
||||
.map_err(|_| unsent(ProviderErrorKind::InvalidRequest))?;
|
||||
Ok((operation, translator))
|
||||
}
|
||||
@@ -1,183 +0,0 @@
|
||||
//! AGY 编码请求保留函数工具;只有强制搜索才构造独立的原生请求
|
||||
|
||||
use crate::transport::sent;
|
||||
use gateway_core::{
|
||||
engine::provider::MAX_NATIVE_RESPONSE_EVENTS_PER_INPUT,
|
||||
error::{ProviderError, ProviderErrorKind},
|
||||
event::ProtocolWireEvent,
|
||||
};
|
||||
use gateway_protocol::{
|
||||
anthropic::MessagesToResponsesStream,
|
||||
genai::{GenAiToMessagesStream, grounded_search_events},
|
||||
openai::{OPENAI_PROTOCOL, web_search},
|
||||
};
|
||||
use serde_json::{Map, Value, json};
|
||||
use std::borrow::Cow;
|
||||
|
||||
pub(super) fn request(
|
||||
original: &Map<String, Value>,
|
||||
tool: &Value,
|
||||
) -> Result<Map<String, Value>, ProviderError> {
|
||||
if !web_search::allows_live_access(tool) {
|
||||
return Err(ProviderError::invalid_request(
|
||||
"Antigravity web search requires live external web access.",
|
||||
));
|
||||
}
|
||||
let options = google_search_options(tool)?;
|
||||
if original
|
||||
.get("text")
|
||||
.and_then(|v| v.pointer("/format/type"))
|
||||
.is_some_and(|v| v != "text")
|
||||
{
|
||||
return Err(ProviderError::invalid_request(
|
||||
"Antigravity web search supports text output only.",
|
||||
));
|
||||
}
|
||||
// Desktop 的独立搜索只提交当前用户查询,编码历史和函数返回不进入搜索供应方
|
||||
let input = original.get("input").unwrap_or(&Value::Null);
|
||||
let query = if let Some(items) = input.as_array() {
|
||||
let item = items
|
||||
.last()
|
||||
.filter(|i| i["role"] == "user")
|
||||
.ok_or_else(invalid_query)?;
|
||||
let content = &item["content"];
|
||||
if let Some(parts) = content.as_array() {
|
||||
parts
|
||||
.iter()
|
||||
.map(|p| {
|
||||
(p["type"] == "input_text")
|
||||
.then(|| p["text"].as_str())
|
||||
.flatten()
|
||||
.ok_or_else(invalid_query)
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?
|
||||
.join("\n")
|
||||
} else {
|
||||
content.as_str().ok_or_else(invalid_query)?.to_owned()
|
||||
}
|
||||
} else {
|
||||
input.as_str().ok_or_else(invalid_query)?.to_owned()
|
||||
};
|
||||
if query.trim().is_empty() {
|
||||
return Err(invalid_query());
|
||||
}
|
||||
let mut body = Map::from_iter([
|
||||
(
|
||||
"contents".into(),
|
||||
json!([{"role":"user","parts":[{"text":query}]}]),
|
||||
),
|
||||
("tools".into(), json!([{"googleSearch":options}])),
|
||||
]);
|
||||
if let Some(limit) = original.get("max_output_tokens").filter(|v| !v.is_null()) {
|
||||
let limit = limit.as_u64().filter(|n| *n > 0).ok_or_else(|| {
|
||||
ProviderError::invalid_request("max_output_tokens must be a positive integer.")
|
||||
})?;
|
||||
body.insert("generationConfig".into(), json!({"maxOutputTokens":limit}));
|
||||
}
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
fn google_search_options(tool: &Value) -> Result<Map<String, Value>, ProviderError> {
|
||||
let unsupported = || {
|
||||
ProviderError::invalid_request("Antigravity cannot honor the specified web search options.")
|
||||
};
|
||||
let tool = tool.as_object().ok_or_else(unsupported)?;
|
||||
if tool.iter().any(|(k, v)| {
|
||||
!v.is_null() && !matches!(k.as_str(), "type" | "external_web_access" | "filters")
|
||||
}) {
|
||||
return Err(unsupported());
|
||||
}
|
||||
let mut options = Map::new();
|
||||
if let Some(filters) = tool.get("filters").filter(|v| !v.is_null()) {
|
||||
for (field, domains) in filters.as_object().ok_or_else(unsupported)? {
|
||||
let field = match field.as_str() {
|
||||
"allowed_domains" => "includedDomains",
|
||||
"blocked_domains" => "excludeDomains",
|
||||
_ => return Err(unsupported()),
|
||||
};
|
||||
let domains = domains
|
||||
.as_array()
|
||||
.filter(|values| {
|
||||
!values.is_empty()
|
||||
&& values
|
||||
.iter()
|
||||
.all(|v| v.as_str().is_some_and(|s| !s.trim().is_empty()))
|
||||
})
|
||||
.ok_or_else(unsupported)?;
|
||||
options.insert(field.into(), json!(domains));
|
||||
}
|
||||
}
|
||||
Ok(options)
|
||||
}
|
||||
|
||||
fn invalid_query() -> ProviderError {
|
||||
ProviderError::invalid_request(
|
||||
"Antigravity web search requires a text query in the last user message.",
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) struct SearchResponse {
|
||||
responses: MessagesToResponsesStream,
|
||||
include_sources: bool,
|
||||
terminal: Option<ProtocolWireEvent>,
|
||||
}
|
||||
|
||||
impl SearchResponse {
|
||||
pub(super) fn new(original: &Map<String, Value>) -> Self {
|
||||
Self {
|
||||
responses: MessagesToResponsesStream::new(original),
|
||||
include_sources: original
|
||||
.get("include")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|v| v.iter().any(|v| v == "web_search_call.action.sources")),
|
||||
terminal: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn translate(
|
||||
&mut self,
|
||||
event: &ProtocolWireEvent,
|
||||
) -> Result<Vec<ProtocolWireEvent>, ProviderError> {
|
||||
let value = match event.raw_json_body() {
|
||||
Some(raw) => Cow::Owned(
|
||||
serde_json::from_slice(raw).map_err(|_| sent(ProviderErrorKind::Protocol))?,
|
||||
),
|
||||
None => Cow::Borrowed(event.data()),
|
||||
};
|
||||
let error = |e| sent(ProviderErrorKind::Protocol).with_source(e);
|
||||
let mut genai = GenAiToMessagesStream::new(String::new());
|
||||
let mut messages = genai.push(&value).map_err(error)?;
|
||||
messages.extend(genai.finish().map_err(error)?);
|
||||
let mut responses = Vec::new();
|
||||
for message in messages {
|
||||
responses.extend(self.responses.push(&message).map_err(error)?);
|
||||
}
|
||||
let mut wire: Vec<_> = grounded_search_events(
|
||||
&value,
|
||||
responses,
|
||||
self.include_sources,
|
||||
MAX_NATIVE_RESPONSE_EVENTS_PER_INPUT + 1,
|
||||
)
|
||||
.map_err(error)?
|
||||
.into_iter()
|
||||
.map(|event| {
|
||||
ProtocolWireEvent::json(
|
||||
OPENAI_PROTOCOL,
|
||||
event["type"].as_str().map(str::to_owned),
|
||||
event,
|
||||
)
|
||||
.map_err(|_| sent(ProviderErrorKind::Protocol))
|
||||
})
|
||||
.collect::<Result<_, _>>()?;
|
||||
// 单次 JSON 先交付内容;协议终态必须随 Core 的 Completed 事实交付
|
||||
self.terminal = wire.pop();
|
||||
Ok(wire)
|
||||
}
|
||||
|
||||
pub(super) fn finish(&mut self) -> Result<Vec<ProtocolWireEvent>, ProviderError> {
|
||||
self.terminal
|
||||
.take()
|
||||
.map(|v| vec![v])
|
||||
.ok_or_else(|| sent(ProviderErrorKind::Protocol))
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
//! 验证三种入站协议的会话绑定、租户隔离与发送前原子认领
|
||||
//! 验证原生 GenAI 与 Chat 的会话绑定、租户隔离与发送前原子认领
|
||||
|
||||
use crate::support::{Fixture, context_with_policy, context_with_scope, request};
|
||||
use futures::TryStreamExt;
|
||||
@@ -64,14 +64,9 @@ async fn each_inbound_protocol_reuses_its_explicit_session_and_renews_ttl() {
|
||||
json!({"headers":{"x-http-session-id":"session-a"}}),
|
||||
),
|
||||
(
|
||||
gateway_protocol::openai::OPENAI_PROTOCOL,
|
||||
json!({"input":[], "client_metadata":{"session_id":"session-a"}}),
|
||||
json!({}),
|
||||
),
|
||||
(
|
||||
gateway_protocol::anthropic::ANTHROPIC_PROTOCOL,
|
||||
json!({"messages":[]}),
|
||||
json!({"opaque_request_headers":[["x-claude-code-session-id","c2Vzc2lvbi1h"]]}),
|
||||
gateway_protocol::chat_completions::CHAT_PROTOCOL,
|
||||
json!({"model":"fixture-model","messages":[{"role":"user","content":"hello"}]}),
|
||||
json!({"headers":{"x-http-session-id":"session-a"}}),
|
||||
),
|
||||
] {
|
||||
for ttl in [7200, 3600] {
|
||||
@@ -94,7 +89,7 @@ async fn each_inbound_protocol_reuses_its_explicit_session_and_renews_ttl() {
|
||||
let bindings = fixture.store.bindings.lock().unwrap();
|
||||
assert_eq!(
|
||||
bindings.len(),
|
||||
3,
|
||||
2,
|
||||
"each protocol has an independent identity namespace"
|
||||
);
|
||||
assert!(
|
||||
|
||||
@@ -196,7 +196,7 @@ async fn mock_project(upstream: &MockServer) {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn model_group_menu_routes_responses_and_native_generation_to_declared_members() {
|
||||
async fn model_group_menu_routes_chat_and_native_generation_to_declared_members() {
|
||||
use gateway_core::{
|
||||
engine::provider::ProviderRequest,
|
||||
operation::{GenerateRequest, Operation, ProtocolPayload},
|
||||
@@ -334,13 +334,14 @@ async fn model_group_menu_routes_responses_and_native_generation_to_declared_mem
|
||||
"data: {\"response\":{\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"OK\"}]},\"finishReason\":\"STOP\"}]}}\n\n",
|
||||
"text/event-stream",
|
||||
)).expect(1).mount(&upstream).await;
|
||||
let body = json!({"model":group.upstream_model().as_str(),"input":[
|
||||
{"role":"user","content":[{"type":"input_image","image_url":"data:image/png;base64,AA=="}]},
|
||||
{"type":"function_call","name":"capture","call_id":"c","arguments":"{}"},
|
||||
{"type":"function_call_output","call_id":"c","output":[{"type":"input_text","text":"ok"},{"type":"input_image","image_url":"data:image/png;base64,AQ=="}]}
|
||||
],"reasoning":{"effort":"high"}});
|
||||
let body = json!({"model":group.upstream_model().as_str(),"stream":true,"messages":[
|
||||
{"role":"user","content":[{"type":"image_url","image_url":{"url":"data:image/png;base64,AA=="}}]},
|
||||
{"role":"assistant","tool_calls":[{"id":"c","type":"function","function":{"name":"capture","arguments":"{}"}}]},
|
||||
{"role":"tool","tool_call_id":"c","content":[{"type":"text","text":"ok"},{"type":"image_url","image_url":{"url":"data:image/png;base64,AQ=="}}]}
|
||||
],"reasoning_effort":"high"});
|
||||
let operation = Operation::Generate(GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object("openai", body.as_object().unwrap().clone()).unwrap(),
|
||||
ProtocolPayload::json_object("chat_completions", body.as_object().unwrap().clone())
|
||||
.unwrap(),
|
||||
));
|
||||
let plan = snapshot
|
||||
.plan(
|
||||
@@ -609,127 +610,53 @@ async fn rate_limit_feedback_uses_model_scope_and_the_full_upstream_retry_delay(
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn responses_continuation_requests_full_replay_and_preserves_the_conversation() {
|
||||
async fn other_native_harnesses_are_rejected_without_synthetic_prewarm_or_account_selection() {
|
||||
use gateway_core::{
|
||||
engine::provider::ProviderRequest,
|
||||
error::{ContinuationRecoveryDisposition, GatewayError},
|
||||
operation::{GenerateRequest, Operation, ProtocolPayload},
|
||||
};
|
||||
let upstream = MockServer::start().await;
|
||||
let fixture = Fixture::new(&upstream.uri());
|
||||
let provider_request = |body: serde_json::Value| {
|
||||
let payload =
|
||||
ProtocolPayload::json_object("openai", body.as_object().unwrap().clone()).unwrap();
|
||||
ProviderRequest::new(
|
||||
Operation::Generate(GenerateRequest::from_protocol_payload(payload)),
|
||||
request(false).candidate().clone(),
|
||||
)
|
||||
};
|
||||
let execute = |body| {
|
||||
fixture.provider.clone().execute(
|
||||
provider_request(body),
|
||||
context(frozen_profile(), CancellationToken::new()),
|
||||
)
|
||||
};
|
||||
let history = json!([
|
||||
{"role":"user","content":"look up the color"},
|
||||
{"type":"function_call","call_id":"c","name":"lookup","arguments":"{}"},
|
||||
{"type":"function_call_output","call_id":"c","output":"amber"}
|
||||
]);
|
||||
let id = ModelRequestId::new("req_warm").unwrap();
|
||||
for input in [json!([]), history.clone()] {
|
||||
let body = json!({"generate":false,"model":"fixture-model","input":input,"tools":[{"type":"function","name":"lookup"}]});
|
||||
let warm = fixture
|
||||
.provider
|
||||
.local_websocket_prewarm(provider_request(body).operation(), &id)
|
||||
.unwrap();
|
||||
assert_eq!(warm.created.data()["type"], "response.created");
|
||||
assert_eq!(warm.created.data()["response"]["status"], "in_progress");
|
||||
assert_eq!(warm.completed.data()["type"], "response.completed");
|
||||
assert_eq!(warm.completed.data()["response"]["status"], "completed");
|
||||
assert_eq!(warm.created.data()["response"]["id"], warm.response_id);
|
||||
assert_eq!(warm.completed.data()["response"]["id"], warm.response_id);
|
||||
assert_eq!(warm.completed.data()["response"]["output"], json!([]));
|
||||
assert_eq!(
|
||||
warm.completed.data()["response"]["usage"]["total_tokens"],
|
||||
0
|
||||
);
|
||||
}
|
||||
for (mut body, code, recovery) in [
|
||||
(
|
||||
json!({"generate":false,"input":[]}),
|
||||
Some("unsupported_prewarm"),
|
||||
None,
|
||||
),
|
||||
(
|
||||
json!({"generate":false,"input":history}),
|
||||
Some("unsupported_prewarm"),
|
||||
None,
|
||||
),
|
||||
(
|
||||
json!({"previous_response_id":"resp_first","input":[history[2]]}),
|
||||
Some("previous_response_not_found"),
|
||||
Some(ContinuationRecoveryDisposition::ClientReplayRequired),
|
||||
),
|
||||
(
|
||||
json!({"generate":false,"previous_response_id":"resp_prewarm_req_warm","input":[history[2]]}),
|
||||
Some("previous_response_not_found"),
|
||||
Some(ContinuationRecoveryDisposition::ClientReplayRequired),
|
||||
),
|
||||
(
|
||||
json!({"previous_response_id":42,"input":[history[2]]}),
|
||||
None,
|
||||
None,
|
||||
),
|
||||
] {
|
||||
body["model"] = json!("fixture-model");
|
||||
if body.get("previous_response_id").is_some() {
|
||||
for protocol in ["openai", "anthropic"] {
|
||||
for body in [
|
||||
json!({"model":"fixture-model","generate":false,"input":[]}),
|
||||
json!({"model":"fixture-model","previous_response_id":"foreign","input":[]}),
|
||||
json!({"model":"fixture-model","messages":[{"role":"user","content":"hello"}]}),
|
||||
] {
|
||||
let operation = Operation::Generate(GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object(protocol, body.as_object().unwrap().clone()).unwrap(),
|
||||
));
|
||||
assert!(
|
||||
fixture
|
||||
.provider
|
||||
.local_websocket_prewarm(provider_request(body.clone()).operation(), &id)
|
||||
.local_websocket_prewarm(
|
||||
&operation,
|
||||
&ModelRequestId::new("req_foreign").unwrap()
|
||||
)
|
||||
.is_none()
|
||||
);
|
||||
let error = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
ProviderRequest::new(operation, request(false).candidate().clone()),
|
||||
context(frozen_profile(), CancellationToken::new()),
|
||||
)
|
||||
.await
|
||||
.err()
|
||||
.expect("foreign native harness cannot be translated");
|
||||
assert_eq!(error.kind(), ProviderErrorKind::Unsupported);
|
||||
assert_eq!(error.send_state(), UpstreamSendState::NotSent);
|
||||
assert!(error.continuation_recovery_disposition().is_none());
|
||||
}
|
||||
let error = execute(body)
|
||||
.await
|
||||
.err()
|
||||
.expect("only full generation requests reach GenAI");
|
||||
assert_eq!(error.send_state(), UpstreamSendState::NotSent);
|
||||
assert_eq!(
|
||||
GatewayError::from_provider(&error).client_error_code(),
|
||||
code
|
||||
);
|
||||
assert_eq!(error.continuation_recovery_disposition(), recovery);
|
||||
}
|
||||
assert!(upstream.received_requests().await.unwrap().is_empty());
|
||||
assert_eq!(fixture.store.scheduling_reads.load(Ordering::SeqCst), 0);
|
||||
Mock::given(path("/v1internal:streamGenerateContent"))
|
||||
.and(body_partial_json(json!({"request":{"contents":[
|
||||
{"role":"user","parts":[{"text":"look up the color"}]},
|
||||
{"role":"model","parts":[{"functionCall":{"id":"c","name":"lookup","args":{}}}]},
|
||||
{"role":"user","parts":[{"functionResponse":{"id":"c","name":"lookup","response":{"output":"amber"}}}]}
|
||||
]}})))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_raw(
|
||||
"data: {\"response\":{\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"amber\"}]},\"finishReason\":\"STOP\"}]}}\n\n", "text/event-stream",
|
||||
))
|
||||
.expect(1).mount(&upstream).await;
|
||||
let stream = execute(json!({"model":"fixture-model","generate":true,"input":history}))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
stream
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|event| event.has_client_event())
|
||||
);
|
||||
released(&fixture).await;
|
||||
assert_eq!(fixture.store.active_leases(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn translated_generation_delivers_terminal_wire_after_tail_usage() {
|
||||
async fn chat_direct_genai_keeps_json_sse_usage_and_releases_the_native_lease() {
|
||||
use gateway_core::{
|
||||
engine::{execution::ClientTransport, provider::ProviderRequest},
|
||||
event::GatewayEvent,
|
||||
@@ -737,150 +664,118 @@ async fn translated_generation_delivers_terminal_wire_after_tail_usage() {
|
||||
};
|
||||
let upstream = MockServer::start().await;
|
||||
Mock::given(method("POST")).and(path("/v1internal:streamGenerateContent"))
|
||||
.and(header("user-agent", "antigravity/cli/1.5.14 (aidev_client; os_type=linux; arch=amd64; auth_method=consumer)"))
|
||||
.and(body_partial_json(json!({"request":{"contents":[{"role":"user","parts":[{"text":"hello"}]}]}})))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_raw(concat!(
|
||||
"data: {\"response\":{\"responseId\":\"r\",\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"ok\"}]},\"finishReason\":\"STOP\"}]}}\n\n",
|
||||
"data: {\"response\":{\"usageMetadata\":{\"promptTokenCount\":7,\"candidatesTokenCount\":2}}}\n\n"
|
||||
),"text/event-stream")).expect(3).mount(&upstream).await;
|
||||
),"text/event-stream")).expect(1).mount(&upstream).await;
|
||||
Mock::given(method("POST")).and(path("/v1internal:generateContent"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"response":{
|
||||
"responseId":"r", "candidates":[{"content":{"parts":[{"text":"ok"}]},"finishReason":"STOP"}],
|
||||
"usageMetadata":{"promptTokenCount":7,"candidatesTokenCount":2}
|
||||
}}))).expect(2).mount(&upstream).await;
|
||||
let responses = json!({"model":"fixture-model","client_metadata":{"session_id":"same-conversation"},"input":"hello","max_output_tokens":100,"reasoning":{"effort":"high"},"temperature":0.3,"top_p":0.8,"tools":[{"type":"function","name":"pwd","parameters":{"type":"object"}}],"tool_choice":"required","text":{"format":{"type":"json_schema","schema":{"type":"object"}}}});
|
||||
for (protocol, transport, body) in [
|
||||
("openai", ClientTransport::WebSocket, responses.clone()),
|
||||
("openai", ClientTransport::HttpJson, responses.clone()),
|
||||
("openai", ClientTransport::HttpSse, responses),
|
||||
(
|
||||
"anthropic",
|
||||
ClientTransport::HttpJson,
|
||||
json!({"model":"fixture-model","messages":[{"role":"user","content":"hello"}],"max_tokens":100}),
|
||||
),
|
||||
(
|
||||
"anthropic",
|
||||
ClientTransport::HttpSse,
|
||||
json!({"model":"fixture-model","messages":[{"role":"user","content":"hello"}],"max_tokens":100}),
|
||||
),
|
||||
] {
|
||||
"responseId":"r","candidates":[{"content":{"parts":[{"text":"ok"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":7,"candidatesTokenCount":2}
|
||||
}}))).expect(1).mount(&upstream).await;
|
||||
for streaming in [false, true] {
|
||||
let fixture = Fixture::new(&upstream.uri());
|
||||
let mut body = json!({"model":"fixture-model","stream":streaming,"messages":[{"role":"user","content":"hello"}],"max_completion_tokens":100,"reasoning_effort":"high","temperature":0.3,"top_p":0.8,"tools":[{"type":"function","function":{"name":"pwd","parameters":{"type":"object"}}}],"tool_choice":"required","response_format":{"type":"json_schema","json_schema":{"name":"result","schema":{"type":"object"}}}});
|
||||
if streaming {
|
||||
body["stream_options"] = json!({"include_usage":true});
|
||||
}
|
||||
let operation = Operation::Generate(GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object(protocol, body.as_object().unwrap().clone()).unwrap(),
|
||||
ProtocolPayload::json_object("chat_completions", body.as_object().unwrap().clone())
|
||||
.unwrap(),
|
||||
));
|
||||
let request = ProviderRequest::new(operation, request(false).candidate().clone());
|
||||
let mut profile = crate::profile::ClientProfile::from_frozen(&frozen_profile()).unwrap();
|
||||
profile.system_prompt = "Frozen AGY prompt".into();
|
||||
let request_context = RequestAttemptContext::new(
|
||||
ModelRequestId::new("req_translation").unwrap(),
|
||||
ModelRequestId::new("req_chat").unwrap(),
|
||||
ClientApiKeyId::new("key_fixture").unwrap(),
|
||||
)
|
||||
.with_request_profile(Some(profile.frozen()))
|
||||
.with_middleware(None, Default::default(), protocol.to_owned(), transport);
|
||||
.with_middleware(
|
||||
None,
|
||||
Default::default(),
|
||||
"chat_completions".to_owned(),
|
||||
if streaming {
|
||||
ClientTransport::HttpSse
|
||||
} else {
|
||||
ClientTransport::HttpJson
|
||||
},
|
||||
);
|
||||
let mut stream = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
request,
|
||||
ProviderRequest::new(operation, request(false).candidate().clone()),
|
||||
crate::support::context_with_request(request_context, CancellationToken::new()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut output = Vec::new();
|
||||
let mut accumulator = gateway_protocol::chat_completions::ChatAccumulator::default();
|
||||
let mut result = None;
|
||||
let mut terminal_count = 0;
|
||||
while let Some(event) = stream.next().await {
|
||||
let event = event.unwrap();
|
||||
let terminal = event
|
||||
.canonical_facts()
|
||||
.iter()
|
||||
.any(|f| matches!(f, GatewayEvent::Completed(_)));
|
||||
output.extend(stream.translate_native_response(event, terminal).unwrap());
|
||||
.any(|fact| matches!(fact, GatewayEvent::Completed(_)));
|
||||
for event in stream.translate_native_response(event, terminal).unwrap() {
|
||||
assert!(!event.prefers_websocket_reconnect());
|
||||
assert!(event.session_update().is_none());
|
||||
terminal_count += usize::from(
|
||||
event
|
||||
.canonical_facts()
|
||||
.iter()
|
||||
.any(|fact| matches!(fact, GatewayEvent::Completed(_))),
|
||||
);
|
||||
if let Some(wire) = event.wire_event() {
|
||||
assert_eq!(wire.protocol(), "chat_completions");
|
||||
if streaming {
|
||||
accumulator.push(wire.data()).unwrap();
|
||||
} else {
|
||||
result = Some(
|
||||
serde_json::from_slice::<serde_json::Value>(
|
||||
wire.raw_json_body().unwrap(),
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let last = output.last().unwrap();
|
||||
assert_eq!(
|
||||
last.prefers_websocket_reconnect(),
|
||||
transport == ClientTransport::WebSocket
|
||||
);
|
||||
assert!(
|
||||
output[..output.len() - 1]
|
||||
.iter()
|
||||
.all(|event| !event.prefers_websocket_reconnect())
|
||||
);
|
||||
assert!(output.iter().all(|event| event.session_update().is_none()));
|
||||
assert!(
|
||||
last.canonical_facts()
|
||||
.iter()
|
||||
.any(|f| matches!(f, GatewayEvent::Completed(_)))
|
||||
);
|
||||
assert_eq!(terminal_count, 1);
|
||||
let result = result.unwrap_or_else(|| accumulator.finish().unwrap());
|
||||
assert_eq!(result["choices"][0]["message"]["content"], "ok");
|
||||
assert_eq!(result["choices"][0]["finish_reason"], "stop");
|
||||
assert_eq!(result["usage"]["prompt_tokens"], 7);
|
||||
assert_eq!(result["usage"]["completion_tokens"], 2);
|
||||
let sent = upstream.received_requests().await.unwrap();
|
||||
let body: serde_json::Value = serde_json::from_slice(&sent.last().unwrap().body).unwrap();
|
||||
let http_json = transport == ClientTransport::HttpJson;
|
||||
assert_eq!(
|
||||
sent.last().unwrap().url.path(),
|
||||
if http_json {
|
||||
"/v1internal:generateContent"
|
||||
} else {
|
||||
"/v1internal:streamGenerateContent"
|
||||
}
|
||||
);
|
||||
if protocol == "openai" {
|
||||
assert_eq!(body["request"]["sessionId"], "-6977519665959570574");
|
||||
} else {
|
||||
assert!(body["request"].get("sessionId").is_none());
|
||||
}
|
||||
assert!(body.get("enabledCreditTypes").is_none());
|
||||
assert_eq!(body["request"]["generationConfig"]["maxOutputTokens"], 100);
|
||||
assert!(body["request"].get("input").is_none());
|
||||
assert_eq!(
|
||||
body["request"]["systemInstruction"]["parts"][0]["text"],
|
||||
"Frozen AGY prompt"
|
||||
);
|
||||
assert!(
|
||||
output
|
||||
.iter()
|
||||
.filter_map(|event| event.response_observation())
|
||||
.any(|observation| observation.timings().first_token_ms.is_some())
|
||||
assert_eq!(body["request"]["generationConfig"]["maxOutputTokens"], 100);
|
||||
assert_eq!(
|
||||
body["request"]["generationConfig"]["thinkingConfig"]["thinkingBudget"],
|
||||
24576
|
||||
);
|
||||
assert_eq!(
|
||||
body["request"]["toolConfig"]["functionCallingConfig"]["mode"],
|
||||
"ANY"
|
||||
);
|
||||
assert_eq!(
|
||||
body["request"]["generationConfig"]["responseJsonSchema"],
|
||||
json!({"type":"object"})
|
||||
);
|
||||
if protocol == "openai" {
|
||||
assert_eq!(
|
||||
body["request"]["generationConfig"]["thinkingConfig"]["thinkingBudget"],
|
||||
24576
|
||||
);
|
||||
assert_eq!(body["request"]["generationConfig"]["temperature"], 0.3);
|
||||
assert_eq!(body["request"]["generationConfig"]["topP"], 0.8);
|
||||
assert_eq!(
|
||||
body["request"]["toolConfig"]["functionCallingConfig"]["mode"],
|
||||
"ANY"
|
||||
);
|
||||
assert_eq!(
|
||||
body["request"]["generationConfig"]["responseSchema"],
|
||||
json!({"type":"object"})
|
||||
);
|
||||
} else {
|
||||
assert_eq!(
|
||||
output[0].wire_event().unwrap().data()["message"]["model"],
|
||||
"fixture-model"
|
||||
);
|
||||
}
|
||||
let wire = last.wire_event().unwrap();
|
||||
assert_eq!(wire.protocol(), protocol);
|
||||
if protocol == "openai" {
|
||||
assert_eq!(wire.data()["type"], "response.completed");
|
||||
assert_eq!(wire.data()["response"]["usage"]["input_tokens"], 7);
|
||||
} else {
|
||||
assert_eq!(wire.data()["type"], "message_stop");
|
||||
assert!(
|
||||
output
|
||||
.iter()
|
||||
.filter_map(|e| e.wire_event())
|
||||
.any(|w| w.data()["usage"]["input_tokens"] == 7)
|
||||
);
|
||||
}
|
||||
drop(stream);
|
||||
released(&fixture).await;
|
||||
}
|
||||
upstream.verify().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn optional_search_preserves_functions_and_unspecified_output_limit() {
|
||||
async fn chat_function_choice_preserves_functions_and_unspecified_output_limit() {
|
||||
use gateway_core::{
|
||||
engine::provider::ProviderRequest,
|
||||
operation::{GenerateRequest, Operation, ProtocolPayload},
|
||||
@@ -893,21 +788,22 @@ async fn optional_search_preserves_functions_and_unspecified_output_limit() {
|
||||
"text/event-stream",
|
||||
))
|
||||
.expect(4).mount(&upstream).await;
|
||||
let search = json!({"type":"web_search"});
|
||||
let function = json!({"type":"function","name":"pwd","parameters":{"type":"object"}});
|
||||
let function =
|
||||
json!({"type":"function","function":{"name":"pwd","parameters":{"type":"object"}}});
|
||||
for choice in [
|
||||
json!(null),
|
||||
json!("auto"),
|
||||
json!("required"),
|
||||
json!({"type":"allowed_tools","mode":"required","tools":[search,function]}),
|
||||
json!({"type":"allowed_tools","allowed_tools":{"mode":"required","tools":[function]}}),
|
||||
] {
|
||||
let fixture = Fixture::new(&upstream.uri());
|
||||
let mut body = json!({"model":"fixture-model","input":"hello","tools":[search,function],"tool_choice":choice});
|
||||
let mut body = json!({"model":"fixture-model","stream":true,"messages":[{"role":"user","content":"hello"}],"tools":[function],"tool_choice":choice});
|
||||
if choice == "required" {
|
||||
body["max_output_tokens"] = json!(null);
|
||||
body["max_completion_tokens"] = json!(null);
|
||||
}
|
||||
let operation = Operation::Generate(GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object("openai", body.as_object().unwrap().clone()).unwrap(),
|
||||
ProtocolPayload::json_object("chat_completions", body.as_object().unwrap().clone())
|
||||
.unwrap(),
|
||||
));
|
||||
let stream = fixture
|
||||
.provider
|
||||
@@ -937,7 +833,7 @@ async fn optional_search_preserves_functions_and_unspecified_output_limit() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_required_search_is_rejected_before_sending_and_releases_lease() {
|
||||
async fn unsupported_chat_search_options_fail_before_sending_and_release_the_lease() {
|
||||
use gateway_core::{
|
||||
engine::provider::ProviderRequest,
|
||||
operation::{GenerateRequest, Operation, ProtocolPayload},
|
||||
@@ -951,30 +847,14 @@ async fn invalid_required_search_is_rejected_before_sending_and_releases_lease()
|
||||
value["webSearchModelIds"] = json!(["fixture-model"]);
|
||||
*bytes = value.to_string().into();
|
||||
}
|
||||
let search = json!({"type":"web_search"});
|
||||
for (tools, message) in [
|
||||
(json!([]), "The selected web search tool must be declared."),
|
||||
(
|
||||
json!([search, search]),
|
||||
"Select one web search declaration.",
|
||||
),
|
||||
(
|
||||
json!([{"type":"web_search","external_web_access":false}]),
|
||||
"Antigravity web search requires live external web access.",
|
||||
),
|
||||
(
|
||||
json!([{"type":"web_search","external_web_access":"cached"}]),
|
||||
"Antigravity web search requires live external web access.",
|
||||
),
|
||||
(
|
||||
json!([{"type":"web_search","user_location":{"type":"approximate","country":"US"}}]),
|
||||
"Antigravity cannot honor the specified web search options.",
|
||||
),
|
||||
for options in [
|
||||
json!({"user_location":{"type":"approximate","approximate":{"country":"US"}}}),
|
||||
json!({"search_context_size":"high"}),
|
||||
] {
|
||||
let body =
|
||||
json!({"model":"fixture-model","input":"hello","tools":tools,"tool_choice":search});
|
||||
let body = json!({"model":"fixture-model","messages":[{"role":"user","content":"hello"}],"web_search_options":options});
|
||||
let operation = Operation::Generate(GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object("openai", body.as_object().unwrap().clone()).unwrap(),
|
||||
ProtocolPayload::json_object("chat_completions", body.as_object().unwrap().clone())
|
||||
.unwrap(),
|
||||
));
|
||||
let error = fixture
|
||||
.provider
|
||||
@@ -985,20 +865,17 @@ async fn invalid_required_search_is_rejected_before_sending_and_releases_lease()
|
||||
)
|
||||
.await
|
||||
.err()
|
||||
.expect("invalid search request");
|
||||
.expect("unsupported search options cannot silently disappear");
|
||||
assert_eq!(error.kind(), ProviderErrorKind::InvalidRequest);
|
||||
assert_eq!(error.send_state(), UpstreamSendState::NotSent);
|
||||
assert_eq!(
|
||||
gateway_core::error::GatewayError::from_provider(&error).client_message(),
|
||||
message
|
||||
);
|
||||
assert!(error.error_details().is_some());
|
||||
released(&fixture).await;
|
||||
}
|
||||
assert!(upstream.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn required_search_uses_catalog_target_and_delivers_grounded_terminal() {
|
||||
async fn chat_search_uses_catalog_target_and_delivers_grounded_terminal() {
|
||||
use gateway_core::{
|
||||
engine::provider::ProviderRequest,
|
||||
event::GatewayEvent,
|
||||
@@ -1039,11 +916,10 @@ async fn required_search_uses_catalog_target_and_delivers_grounded_terminal() {
|
||||
vec![],
|
||||
)
|
||||
.unwrap();
|
||||
let search = json!({"type":"web_search","filters":{"allowed_domains":["example.org"]}});
|
||||
let choice = json!({"type":"allowed_tools","mode":"required","tools":[{"type":"web_search"}]});
|
||||
let body = json!({"model":"fixture-model","input":"你好","tool_choice":choice,"tools":[search,{"type":"function","name":"pwd"}],"include":["web_search_call.action.sources"]});
|
||||
let body = json!({"model":"fixture-model","stream":true,"stream_options":{"include_usage":true},"messages":[{"role":"user","content":"你好"}],"web_search_options":{}});
|
||||
let op = Operation::Generate(GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object("openai", body.as_object().unwrap().clone()).unwrap(),
|
||||
ProtocolPayload::json_object("chat_completions", body.as_object().unwrap().clone())
|
||||
.unwrap(),
|
||||
));
|
||||
let plan = snapshot
|
||||
.plan(
|
||||
@@ -1056,7 +932,7 @@ async fn required_search_uses_catalog_target_and_delivers_grounded_terminal() {
|
||||
let candidate = &plan.candidates()[0];
|
||||
assert_eq!(candidate.upstream_model().unwrap().as_str(), "search-only");
|
||||
Mock::given(path("/v1internal:generateContent")).and(body_partial_json(json!({
|
||||
"model":"search-only","requestType":"web_search","request":{"tools":[{"googleSearch":{"includedDomains":["example.org"]}}],"contents":[{"role":"user","parts":[{"text":"你好"}]}]}
|
||||
"model":"search-only","requestType":"web_search","request":{"tools":[{"googleSearch":{}}],"contents":[{"role":"user","parts":[{"text":"你好"}]}]}
|
||||
}))).respond_with(ResponseTemplate::new(200).set_body_json(json!({"response":{
|
||||
"responseId":"r","candidates":[{"content":{"parts":[{"text":"前 "},{"text":"答案"}]},"finishReason":"STOP",
|
||||
"groundingMetadata":{"webSearchQueries":["你好"],"groundingChunks":[{"web":{"uri":"https://example.org","title":"来源"}}],
|
||||
@@ -1079,29 +955,23 @@ async fn required_search_uses_catalog_target_and_delivers_grounded_terminal() {
|
||||
.any(|f| matches!(f, GatewayEvent::Completed(_)));
|
||||
for translated in stream.translate_native_response(event, terminal).unwrap() {
|
||||
if let Some(frame) = translated.wire_event() {
|
||||
assert_eq!(frame.data()["type"] == "response.completed", terminal);
|
||||
assert_eq!(frame.protocol(), "chat_completions");
|
||||
wire.push(frame.data().clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
for (i, event) in wire.iter().enumerate() {
|
||||
assert_eq!(event["sequence_number"], i)
|
||||
let mut accumulator = gateway_protocol::chat_completions::ChatAccumulator::default();
|
||||
for chunk in &wire {
|
||||
accumulator.push(chunk).unwrap();
|
||||
}
|
||||
let response = &wire.last().unwrap()["response"];
|
||||
let response = accumulator.finish().unwrap();
|
||||
assert_eq!(response["model"], "fixture-model");
|
||||
assert_eq!(response["usage"]["total_tokens"], 7);
|
||||
let output = &response["output"];
|
||||
assert_eq!(
|
||||
output[0]["action"]["sources"][0]["url"],
|
||||
"https://example.org"
|
||||
);
|
||||
let citation = &output[1]["content"][0]["annotations"][0];
|
||||
let citation = &response["choices"][0]["message"]["annotations"][0]["url_citation"];
|
||||
assert_eq!(citation["start_index"], 2);
|
||||
assert_eq!(citation["end_index"], 4);
|
||||
assert_eq!(citation["url"], "https://example.org");
|
||||
assert!(
|
||||
wire.iter()
|
||||
.any(|v| v["type"] == "response.output_text.annotation.added"
|
||||
&& &v["annotation"] == citation)
|
||||
);
|
||||
server.verify().await;
|
||||
drop(stream);
|
||||
released(&fixture).await;
|
||||
}
|
||||
|
||||
@@ -74,12 +74,8 @@ async fn native_and_translated_requests_forward_business_headers_with_account_id
|
||||
json!({"contents":[]}),
|
||||
),
|
||||
(
|
||||
gateway_protocol::openai::OPENAI_PROTOCOL,
|
||||
json!({"input":[]}),
|
||||
),
|
||||
(
|
||||
gateway_protocol::anthropic::ANTHROPIC_PROTOCOL,
|
||||
json!({"messages":[]}),
|
||||
gateway_protocol::chat_completions::CHAT_PROTOCOL,
|
||||
json!({"model":"fixture-model","messages":[{"role":"user","content":"hello"}]}),
|
||||
),
|
||||
] {
|
||||
let input = super::affinity::session_request(protocol, body, metadata.clone());
|
||||
@@ -114,7 +110,7 @@ async fn native_and_translated_requests_forward_business_headers_with_account_id
|
||||
.await
|
||||
.unwrap();
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
assert_eq!(requests.len(), 4);
|
||||
assert_eq!(requests.len(), 3);
|
||||
for request in requests {
|
||||
let values: Vec<_> = request
|
||||
.headers
|
||||
|
||||
@@ -133,3 +133,146 @@ async fn middleware_business_headers_survive_without_overriding_frozen_authentic
|
||||
let events: Vec<_> = stream.try_collect().await.unwrap();
|
||||
assert!(events.iter().any(|event| event.has_client_event()));
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ProtocolRewrite {
|
||||
protocol: &'static str,
|
||||
body: Bytes,
|
||||
}
|
||||
|
||||
impl ExtensionSetLease for ProtocolRewrite {
|
||||
fn is_ready(&self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl MiddlewarePlan for ProtocolRewrite {
|
||||
fn handle(
|
||||
&self,
|
||||
_: MiddlewareContext,
|
||||
request: MiddlewareRequest,
|
||||
next: MiddlewareNext,
|
||||
) -> BoxFuture<'static, Result<MiddlewareResponse, MiddlewareError>> {
|
||||
let headers = request.headers().to_vec();
|
||||
next.run(
|
||||
request
|
||||
.replace_parts(self.protocol.to_owned(), headers, self.body.clone(), None)
|
||||
.unwrap(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn protocol_context(protocol: &'static str, body: Bytes) -> gateway_core::engine::AttemptContext {
|
||||
let middleware = Arc::new(ProtocolRewrite { protocol, body });
|
||||
let plan = FrozenMiddlewarePlan::new(
|
||||
middleware.clone(),
|
||||
ExtensionSetReference::new(
|
||||
ExtensionSetId::new("fixture_protocol".into()).unwrap(),
|
||||
middleware,
|
||||
),
|
||||
);
|
||||
context_with_request(
|
||||
RequestAttemptContext::new(
|
||||
ModelRequestId::new("req_plugin_protocol").unwrap(),
|
||||
ClientApiKeyId::new("key_fixture").unwrap(),
|
||||
)
|
||||
.with_middleware(
|
||||
Some(plan),
|
||||
Arc::from([]),
|
||||
"/v1/chat/completions".into(),
|
||||
ClientTransport::HttpJson,
|
||||
),
|
||||
CancellationToken::new(),
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn explicit_native_rewrites_run_without_borrowing_the_builtin_chat_converter() {
|
||||
use gateway_core::{
|
||||
engine::provider::ProviderRequest,
|
||||
operation::{GenerateRequest, Operation, ProtocolPayload},
|
||||
};
|
||||
let upstream = MockServer::start().await;
|
||||
let fixture = Fixture::new(&upstream.uri());
|
||||
Mock::given(path("/v1internal:generateContent"))
|
||||
.and(wiremock::matchers::body_partial_json(json!({"request":{"contents":[{"role":"user","parts":[{"text":"plugin converted"}]}]}})))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"ok"}]},"finishReason":"STOP"}]}}))).expect(2).mount(&upstream).await;
|
||||
for in_attempt in [false, true] {
|
||||
let source = Operation::Generate(GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object(
|
||||
"chat_completions",
|
||||
json!({"model":"fixture-model","messages":[{"role":"user","content":"hello"}]})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone(),
|
||||
)
|
||||
.unwrap(),
|
||||
));
|
||||
let native = Bytes::from_static(
|
||||
br#"{"contents":[{"role":"user","parts":[{"text":"plugin converted"}]}]}"#,
|
||||
);
|
||||
let operation = if in_attempt {
|
||||
source
|
||||
} else {
|
||||
source
|
||||
.replace_middleware_wire("genai", native.clone())
|
||||
.unwrap()
|
||||
};
|
||||
let mut stream = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
ProviderRequest::new(operation, request(false).candidate().clone()),
|
||||
protocol_context("genai", native),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(fixture.store.active_leases(), 1);
|
||||
let mut delivered = false;
|
||||
while let Some(event) = stream.next().await {
|
||||
let event = event.unwrap();
|
||||
let terminal = event
|
||||
.canonical_facts()
|
||||
.iter()
|
||||
.any(|fact| matches!(fact, gateway_core::event::GatewayEvent::Completed(_)));
|
||||
for event in stream.translate_native_response(event, terminal).unwrap() {
|
||||
if let Some(wire) = event.wire_event() {
|
||||
let body: serde_json::Value =
|
||||
serde_json::from_slice(wire.raw_json_body().unwrap()).unwrap();
|
||||
assert!(body.get("choices").is_none());
|
||||
assert_eq!(body["candidates"][0]["content"]["parts"][0]["text"], "ok");
|
||||
delivered = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(delivered);
|
||||
drop(stream);
|
||||
assert_eq!(fixture.store.active_leases(), 0);
|
||||
}
|
||||
upstream.verify().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn explicit_middleware_cannot_relabel_native_genai_as_an_authorized_chat_source() {
|
||||
let upstream = MockServer::start().await;
|
||||
let fixture = Fixture::new(&upstream.uri());
|
||||
let error = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
request(false),
|
||||
protocol_context(
|
||||
"chat_completions",
|
||||
Bytes::from_static(
|
||||
br#"{"model":"fixture-model","messages":[{"role":"user","content":"hello"}]}"#,
|
||||
),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.err()
|
||||
.expect("a native source cannot borrow the built-in Chat converter");
|
||||
assert_eq!(error.kind(), ProviderErrorKind::Unsupported);
|
||||
assert_eq!(error.send_state(), UpstreamSendState::NotSent);
|
||||
assert!(upstream.received_requests().await.unwrap().is_empty());
|
||||
assert_eq!(fixture.store.active_leases(), 0);
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ async fn released(fixture: &Fixture) {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn native_and_messages_count_share_identity_and_never_generate_usage() {
|
||||
async fn native_and_provider_count_share_identity_and_never_generate_usage() {
|
||||
for (protocol, body, expected) in [
|
||||
(
|
||||
"genai",
|
||||
@@ -52,9 +52,9 @@ async fn native_and_messages_count_share_identity_and_never_generate_usage() {
|
||||
json!({"totalTokens":42}),
|
||||
),
|
||||
(
|
||||
"anthropic",
|
||||
json!({"model":"fixture-model","messages":[{"role":"user","content":"hello"}],"system":"client identity","tools":[{"name":"read","input_schema":{"type":"object"}}]}),
|
||||
json!({"input_tokens":42}),
|
||||
"token-count",
|
||||
json!({"model":"fixture-model","contents":[{"role":"user","parts":[{"text":"hello"}]}],"systemInstruction":{"parts":[{"text":"client identity"}]},"tools":[{"functionDeclarations":[{"name":"read"}]}]}),
|
||||
json!({"totalTokens":42}),
|
||||
),
|
||||
] {
|
||||
let upstream = MockServer::start().await;
|
||||
@@ -208,3 +208,26 @@ async fn empty_protobuf_count_response_is_an_explicit_zero() {
|
||||
assert_eq!(value, json!({"totalTokens":0}));
|
||||
released(&fixture).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn messages_count_cannot_use_the_genai_native_counter() {
|
||||
let upstream = MockServer::start().await;
|
||||
let fixture = Fixture::new(&upstream.uri());
|
||||
let error = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
counted(
|
||||
"anthropic",
|
||||
json!({"messages":[{"role":"user","content":"hello"}]}),
|
||||
),
|
||||
context(profile(), CancellationToken::new()),
|
||||
)
|
||||
.await
|
||||
.err()
|
||||
.expect("native count protocols cannot be converted");
|
||||
assert_eq!(error.kind(), ProviderErrorKind::Unsupported);
|
||||
assert_eq!(error.send_state(), UpstreamSendState::NotSent);
|
||||
assert!(upstream.received_requests().await.unwrap().is_empty());
|
||||
released(&fixture).await;
|
||||
}
|
||||
|
||||
@@ -112,6 +112,7 @@ enum CookieRecovery {
|
||||
}
|
||||
|
||||
pub struct SelectCodexCredential<'a> {
|
||||
pub protocol: &'a str,
|
||||
pub upstream_model: &'a str,
|
||||
pub request_url: &'a Url,
|
||||
pub attempt: &'a AttemptContext,
|
||||
@@ -126,6 +127,7 @@ pub(crate) struct SelectCodexProviderEndpointCredential<'a> {
|
||||
}
|
||||
|
||||
struct CredentialSelectionInput<'a> {
|
||||
native_protocol: NativeProtocol,
|
||||
managed_upstream: bool,
|
||||
requires_websocket: bool,
|
||||
request_url: &'a Url,
|
||||
@@ -350,6 +352,7 @@ impl CodexCredentialSelector {
|
||||
) -> Result<CodexCredentialLease, CredentialSelectionError> {
|
||||
let input = CredentialSelectionInput {
|
||||
managed_upstream: false,
|
||||
native_protocol: NativeProtocol::for_source(request.protocol),
|
||||
requires_websocket: false,
|
||||
request_url: request.request_url,
|
||||
attempt: request.attempt,
|
||||
@@ -410,6 +413,7 @@ impl CodexCredentialSelector {
|
||||
) -> Result<CodexCredentialLease, CredentialSelectionError> {
|
||||
let input = CredentialSelectionInput {
|
||||
managed_upstream: true,
|
||||
native_protocol: NativeProtocol::for_source(request.protocol),
|
||||
requires_websocket,
|
||||
request_url: request.request_url,
|
||||
attempt: request.attempt,
|
||||
@@ -429,7 +433,7 @@ impl CodexCredentialSelector {
|
||||
///
|
||||
/// 此处只复用既有亲和与 cyber-policy 端口,不再次选号;冲突必须在发送前失败,
|
||||
/// 避免同一 attempt 持有旧租约时重入账号选择
|
||||
pub(crate) async fn validate_translated_selection(
|
||||
pub(crate) async fn validate_selected_affinity(
|
||||
&self,
|
||||
lease: &mut CodexCredentialLease,
|
||||
session_affinity: Option<&CodexSessionAffinity>,
|
||||
@@ -483,6 +487,7 @@ impl CodexCredentialSelector {
|
||||
request: &SelectCodexProviderEndpointCredential<'_>,
|
||||
) -> Result<CodexCredentialLease, CredentialSelectionError> {
|
||||
let input = CredentialSelectionInput {
|
||||
native_protocol: NativeProtocol::Fixed(ApiKeyProtocol::Responses),
|
||||
managed_upstream: false,
|
||||
requires_websocket: false,
|
||||
request_url: request.request_url,
|
||||
@@ -959,15 +964,29 @@ impl CodexCredentialSelector {
|
||||
}
|
||||
native_accounts.insert(account.id().clone());
|
||||
}
|
||||
let endpoint_requires_responses =
|
||||
!matches!(model, CodexSelectionModel::Requested(_))
|
||||
&& account.authentication_kind()
|
||||
== super::CODEX_AUTHENTICATION_KIND_API_KEY;
|
||||
if adapter.is_none()
|
||||
&& matches!(request.native_protocol, NativeProtocol::Unsupported)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let required_protocol = match request.native_protocol {
|
||||
NativeProtocol::Fixed(protocol) => Some(protocol),
|
||||
NativeProtocol::Chat | NativeProtocol::Unsupported => None,
|
||||
};
|
||||
// OAuth 的原生协议固定,只有 API Key 需要读取与 revision 绑定的协议配置
|
||||
if adapter.is_none()
|
||||
&& account.authentication_kind() == CODEX_AUTHENTICATION_KIND_OAUTH
|
||||
&& required_protocol == Some(ApiKeyProtocol::Messages)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let check_protocol = required_protocol.is_some()
|
||||
&& account.authentication_kind() == super::CODEX_AUTHENTICATION_KIND_API_KEY;
|
||||
let check_ws = request.requires_websocket
|
||||
&& pinned_account.as_ref().is_none_or(|id| id == account.id());
|
||||
if adapter.is_none() && (endpoint_requires_responses || check_ws) {
|
||||
if adapter.is_none() && (check_protocol || check_ws) {
|
||||
// 只复用同 revision 的协议类型;选中后仍以完整账号快照重读凭据
|
||||
if endpoint_requires_responses && !check_ws {
|
||||
if check_protocol && !check_ws {
|
||||
let cached = self
|
||||
.endpoint_protocols
|
||||
.lock()
|
||||
@@ -976,7 +995,7 @@ impl CodexCredentialSelector {
|
||||
.copied()
|
||||
.filter(|(rev, _)| *rev == account.revision());
|
||||
if let Some((_, protocol)) = cached {
|
||||
if protocol == ApiKeyProtocol::Responses {
|
||||
if Some(protocol) == required_protocol {
|
||||
eligible.push(account);
|
||||
}
|
||||
continue;
|
||||
@@ -1004,7 +1023,7 @@ impl CodexCredentialSelector {
|
||||
}
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
if endpoint_requires_responses {
|
||||
if check_protocol {
|
||||
self.endpoint_protocols
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
@@ -1015,9 +1034,9 @@ impl CodexCredentialSelector {
|
||||
}
|
||||
if (request.requires_websocket
|
||||
&& runtime.transport == super::ResponsesTransport::Http)
|
||||
|| (endpoint_requires_responses
|
||||
&& runtime.authentication.api_protocol()
|
||||
== super::ApiKeyProtocol::Messages)
|
||||
|| required_protocol.is_some_and(|protocol| {
|
||||
runtime.authentication.api_protocol() != protocol
|
||||
})
|
||||
{
|
||||
continue;
|
||||
}
|
||||
@@ -2484,3 +2503,24 @@ fn minimum_duration(current: Option<Duration>, candidate: Option<Duration>) -> O
|
||||
(None, candidate) => candidate,
|
||||
}
|
||||
}
|
||||
|
||||
// 原生资格在账号边界检查,显式插件适配拥有自己的输入协议
|
||||
#[derive(Clone, Copy)]
|
||||
enum NativeProtocol {
|
||||
Fixed(ApiKeyProtocol),
|
||||
Chat,
|
||||
Unsupported,
|
||||
}
|
||||
|
||||
impl NativeProtocol {
|
||||
fn for_source(protocol: &str) -> Self {
|
||||
match protocol {
|
||||
gateway_protocol::openai::OPENAI_PROTOCOL => Self::Fixed(ApiKeyProtocol::Responses),
|
||||
gateway_protocol::anthropic::ANTHROPIC_PROTOCOL | "token-count" => {
|
||||
Self::Fixed(ApiKeyProtocol::Messages)
|
||||
}
|
||||
gateway_protocol::chat_completions::CHAT_PROTOCOL => Self::Chat,
|
||||
_ => Self::Unsupported,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
//! Chat 到 Messages 的协议头隔离,不改变其他原生入口
|
||||
|
||||
use gateway_core::engine::middleware::MiddlewareHeader;
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
pub(super) fn retain_messages_headers(
|
||||
context: &mut Map<String, Value>,
|
||||
headers: &mut Vec<MiddlewareHeader>,
|
||||
) {
|
||||
let keep = |name: &str| {
|
||||
let name = name.to_ascii_lowercase();
|
||||
![
|
||||
"openai-",
|
||||
"x-openai-",
|
||||
"x-codex-",
|
||||
"x-oai-",
|
||||
"x-responsesapi-",
|
||||
"chatgpt-",
|
||||
]
|
||||
.iter()
|
||||
.any(|prefix| name.starts_with(prefix))
|
||||
&& !matches!(
|
||||
name.as_str(),
|
||||
"session-id" | "conversation-id" | "thread-id" | "turn-id" | "session_id"
|
||||
)
|
||||
};
|
||||
if let Some(entries) = context
|
||||
.get_mut(crate::transport::request::PASSTHROUGH_HEADERS_CONTEXT_KEY)
|
||||
.and_then(Value::as_array_mut)
|
||||
{
|
||||
entries.retain(|entry| {
|
||||
entry
|
||||
.as_array()
|
||||
.and_then(|entry| entry.first())
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(keep)
|
||||
});
|
||||
}
|
||||
headers.retain(|header| keep(header.name()));
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
//! 选定账号后装配 Chat 与实际上游协议的直接转换
|
||||
|
||||
mod headers;
|
||||
mod response;
|
||||
|
||||
use super::*;
|
||||
use crate::credential::{ApiKeyProtocol, CodexRuntimeAuthentication};
|
||||
use gateway_protocol::chat_completions::{ChatIdentity, messages, responses};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
impl CodexProvider {
|
||||
pub(super) async fn execute_selected_chat(
|
||||
self: Arc<Self>,
|
||||
operation: Operation,
|
||||
mut headers: Vec<MiddlewareHeader>,
|
||||
model: UpstreamModelId,
|
||||
context: AttemptContext,
|
||||
mut selected: SelectedGenerate,
|
||||
) -> Result<ProviderStream, ProviderError> {
|
||||
let Operation::Generate(generate) = &operation else {
|
||||
return Err(request_error());
|
||||
};
|
||||
if generate.source_protocol() != gateway_protocol::chat_completions::CHAT_PROTOCOL {
|
||||
return Err(request_error());
|
||||
}
|
||||
let original = generate.protocol_payload().body();
|
||||
let identity = ChatIdentity {
|
||||
id: format!("chatcmpl-{}", context.request_id().as_str()),
|
||||
created: SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs(),
|
||||
model: original
|
||||
.get("model")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or(model.as_str())
|
||||
.to_owned(),
|
||||
};
|
||||
let mut source_context = generate.protocol_payload().context().clone();
|
||||
let target = selected.lease.authentication().api_protocol();
|
||||
let translator = response::ChatResponseTranslator::new(target, identity, original);
|
||||
match target {
|
||||
ApiKeyProtocol::Messages => {
|
||||
let capabilities = self
|
||||
.catalog
|
||||
.messages_model_capabilities(selected.lease.account(), &model)
|
||||
.unwrap_or_default();
|
||||
let mut body = messages::convert_request(original, &capabilities)
|
||||
.map_err(|error| request_error().with_source(error))?;
|
||||
body.insert("model".to_owned(), Value::String(model.as_str().to_owned()));
|
||||
headers::retain_messages_headers(&mut source_context, &mut headers);
|
||||
if body.get("speed").and_then(Value::as_str) == Some("fast") {
|
||||
crate::compat::add_translated_fast_beta(
|
||||
&mut headers,
|
||||
&crate::transport::request::decode_passthrough_headers(&source_context),
|
||||
);
|
||||
}
|
||||
let stream = self
|
||||
.execute_selected_messages(
|
||||
body,
|
||||
source_context,
|
||||
headers,
|
||||
model,
|
||||
context,
|
||||
selected,
|
||||
)
|
||||
.await?;
|
||||
Ok(stream.with_native_response_translator(translator))
|
||||
}
|
||||
ApiKeyProtocol::Responses => {
|
||||
let mut body = responses::convert_request(original)
|
||||
.map_err(|error| request_error().with_source(error))?;
|
||||
if matches!(
|
||||
selected.lease.authentication(),
|
||||
CodexRuntimeAuthentication::OAuth(_)
|
||||
) {
|
||||
crate::compat::normalize_translated_codex_service_tier(&mut body);
|
||||
}
|
||||
let body = serde_json::to_vec(&body).map_err(|_| request_error())?;
|
||||
let operation = operation
|
||||
.translate_protocol_wire(OPENAI_PROTOCOL, body.into())
|
||||
.map_err(|_| request_error())?;
|
||||
if let Operation::Generate(generate) = &operation {
|
||||
selected.frozen_requirements = generate.wire_capability_requirements();
|
||||
}
|
||||
let stream = self
|
||||
.execute_selected_generate(operation, headers, model, context, selected)
|
||||
.await?;
|
||||
Ok(stream.with_native_response_translator(translator))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn request_error() -> ProviderError {
|
||||
provider_error(
|
||||
ProviderErrorKind::InvalidRequest,
|
||||
UpstreamSendState::NotSent,
|
||||
)
|
||||
}
|
||||
|
||||
fn response_error() -> ProviderError {
|
||||
provider_error(ProviderErrorKind::Protocol, UpstreamSendState::Sent)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user