Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)
Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
227
akode-rs/akode-api/src/endpoint/memories.rs
Normal file
227
akode-rs/akode-api/src/endpoint/memories.rs
Normal file
@@ -0,0 +1,227 @@
|
||||
use crate::auth::SharedAuthProvider;
|
||||
use crate::common::MemorySummarizeInput;
|
||||
use crate::common::MemorySummarizeOutput;
|
||||
use crate::endpoint::session::EndpointSession;
|
||||
use crate::error::ApiError;
|
||||
use crate::provider::Provider;
|
||||
use akode_client::HttpTransport;
|
||||
use akode_client::RequestTelemetry;
|
||||
use http::HeaderMap;
|
||||
use http::Method;
|
||||
use serde::Deserialize;
|
||||
use serde_json::to_value;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub struct MemoriesClient<T: HttpTransport> {
|
||||
session: EndpointSession<T>,
|
||||
}
|
||||
|
||||
impl<T: HttpTransport> MemoriesClient<T> {
|
||||
pub fn new(transport: T, provider: Provider, auth: SharedAuthProvider) -> Self {
|
||||
Self {
|
||||
session: EndpointSession::new(transport, provider, auth),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_telemetry(self, request: Option<Arc<dyn RequestTelemetry>>) -> Self {
|
||||
Self {
|
||||
session: self.session.with_request_telemetry(request),
|
||||
}
|
||||
}
|
||||
|
||||
fn path() -> &'static str {
|
||||
"memories/trace_summarize"
|
||||
}
|
||||
|
||||
pub async fn summarize(
|
||||
&self,
|
||||
body: serde_json::Value,
|
||||
extra_headers: HeaderMap,
|
||||
) -> Result<Vec<MemorySummarizeOutput>, ApiError> {
|
||||
let resp = self
|
||||
.session
|
||||
.execute(Method::POST, Self::path(), extra_headers, Some(body))
|
||||
.await?;
|
||||
let parsed: SummarizeResponse =
|
||||
serde_json::from_slice(&resp.body).map_err(|e| ApiError::Stream(e.to_string()))?;
|
||||
Ok(parsed.output)
|
||||
}
|
||||
|
||||
pub async fn summarize_input(
|
||||
&self,
|
||||
input: &MemorySummarizeInput,
|
||||
extra_headers: HeaderMap,
|
||||
) -> Result<Vec<MemorySummarizeOutput>, ApiError> {
|
||||
let body = to_value(input).map_err(|e| {
|
||||
ApiError::Stream(format!("failed to encode memory summarize input: {e}"))
|
||||
})?;
|
||||
self.summarize(body, extra_headers).await
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SummarizeResponse {
|
||||
output: Vec<MemorySummarizeOutput>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::auth::AuthProvider;
|
||||
use crate::common::RawMemory;
|
||||
use crate::common::RawMemoryMetadata;
|
||||
use crate::provider::RetryConfig;
|
||||
use akode_client::Request;
|
||||
use akode_client::RequestBody;
|
||||
use akode_client::Response;
|
||||
use akode_client::StreamResponse;
|
||||
use akode_client::TransportError;
|
||||
use http::HeaderMap;
|
||||
use http::Method;
|
||||
use http::StatusCode;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct DummyTransport;
|
||||
|
||||
impl HttpTransport for DummyTransport {
|
||||
async fn execute(&self, _req: Request) -> Result<Response, TransportError> {
|
||||
Err(TransportError::Build("execute should not run".to_string()))
|
||||
}
|
||||
|
||||
async fn stream(&self, _req: Request) -> Result<StreamResponse, TransportError> {
|
||||
Err(TransportError::Build("stream should not run".to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct DummyAuth;
|
||||
|
||||
impl AuthProvider for DummyAuth {
|
||||
fn add_auth_headers(&self, _headers: &mut HeaderMap) -> Result<(), crate::AuthError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct CapturingTransport {
|
||||
last_request: Arc<Mutex<Option<Request>>>,
|
||||
response_body: Arc<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl CapturingTransport {
|
||||
fn new(response_body: Vec<u8>) -> Self {
|
||||
Self {
|
||||
last_request: Arc::new(Mutex::new(None)),
|
||||
response_body: Arc::new(response_body),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HttpTransport for CapturingTransport {
|
||||
async fn execute(&self, req: Request) -> Result<Response, TransportError> {
|
||||
*self.last_request.lock().expect("lock request store") = Some(req);
|
||||
Ok(Response {
|
||||
status: StatusCode::OK,
|
||||
headers: HeaderMap::new(),
|
||||
body: self.response_body.as_ref().clone().into(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn stream(&self, _req: Request) -> Result<StreamResponse, TransportError> {
|
||||
Err(TransportError::Build("stream should not run".to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
fn provider(base_url: &str) -> Provider {
|
||||
Provider {
|
||||
name: "test".to_string(),
|
||||
base_url: base_url.to_string(),
|
||||
query_params: None,
|
||||
headers: HeaderMap::new(),
|
||||
retry: RetryConfig {
|
||||
max_attempts: 1,
|
||||
base_delay: Duration::from_millis(1),
|
||||
retry_429: false,
|
||||
retry_5xx: true,
|
||||
retry_transport: true,
|
||||
},
|
||||
stream_idle_timeout: Duration::from_secs(1),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_is_memories_trace_summarize_for_wire_compatibility() {
|
||||
assert_eq!(
|
||||
MemoriesClient::<DummyTransport>::path(),
|
||||
"memories/trace_summarize"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn summarize_input_posts_expected_payload_and_parses_output() {
|
||||
let transport = CapturingTransport::new(
|
||||
serde_json::to_vec(&json!({
|
||||
"output": [
|
||||
{
|
||||
"trace_summary": "raw summary",
|
||||
"memory_summary": "memory summary"
|
||||
}
|
||||
]
|
||||
}))
|
||||
.expect("serialize response"),
|
||||
);
|
||||
let client = MemoriesClient::new(
|
||||
transport.clone(),
|
||||
provider("https://example.com/api/codex"),
|
||||
Arc::new(DummyAuth),
|
||||
);
|
||||
|
||||
let input = MemorySummarizeInput {
|
||||
model: "gpt-test".to_string(),
|
||||
raw_memories: vec![RawMemory {
|
||||
id: "trace-1".to_string(),
|
||||
metadata: RawMemoryMetadata {
|
||||
source_path: "/tmp/trace.json".to_string(),
|
||||
},
|
||||
items: vec![json!({"type": "message", "role": "user", "content": []})],
|
||||
}],
|
||||
reasoning: None,
|
||||
};
|
||||
|
||||
let output = client
|
||||
.summarize_input(&input, HeaderMap::new())
|
||||
.await
|
||||
.expect("summarize input request should succeed");
|
||||
assert_eq!(output.len(), 1);
|
||||
assert_eq!(output[0].raw_memory, "raw summary");
|
||||
assert_eq!(output[0].memory_summary, "memory summary");
|
||||
|
||||
let request = transport
|
||||
.last_request
|
||||
.lock()
|
||||
.expect("lock request store")
|
||||
.clone()
|
||||
.expect("request should be captured");
|
||||
assert_eq!(request.method, Method::POST);
|
||||
assert_eq!(
|
||||
request.url,
|
||||
"https://example.com/api/codex/memories/trace_summarize"
|
||||
);
|
||||
let body = request
|
||||
.body
|
||||
.as_ref()
|
||||
.and_then(RequestBody::json)
|
||||
.expect("request body should be JSON");
|
||||
assert_eq!(body["model"], "gpt-test");
|
||||
assert_eq!(body["traces"][0]["id"], "trace-1");
|
||||
assert_eq!(
|
||||
body["traces"][0]["metadata"]["source_path"],
|
||||
"/tmp/trace.json"
|
||||
);
|
||||
}
|
||||
}
|
||||
34
akode-rs/akode-api/src/endpoint/mod.rs
Normal file
34
akode-rs/akode-api/src/endpoint/mod.rs
Normal file
@@ -0,0 +1,34 @@
|
||||
pub(crate) mod memories;
|
||||
pub(crate) mod models;
|
||||
pub(crate) mod realtime_call;
|
||||
pub(crate) mod realtime_websocket;
|
||||
pub(crate) mod responses;
|
||||
pub(crate) mod responses_websocket;
|
||||
mod responses_websocket_probe;
|
||||
pub(crate) mod search;
|
||||
mod session;
|
||||
|
||||
pub use memories::MemoriesClient;
|
||||
pub use models::ModelsClient;
|
||||
pub use realtime_call::RealtimeCallClient;
|
||||
pub use realtime_call::RealtimeCallResponse;
|
||||
pub use realtime_websocket::RealtimeContextAppendChannel;
|
||||
pub use realtime_websocket::RealtimeEventParser;
|
||||
pub use realtime_websocket::RealtimeOutputModality;
|
||||
pub use realtime_websocket::RealtimeSessionConfig;
|
||||
pub use realtime_websocket::RealtimeSessionMode;
|
||||
pub use realtime_websocket::RealtimeTranscriptState;
|
||||
pub use realtime_websocket::RealtimeWebsocketClient;
|
||||
pub use realtime_websocket::RealtimeWebsocketConnection;
|
||||
pub use realtime_websocket::RealtimeWebsocketEvents;
|
||||
pub use realtime_websocket::RealtimeWebsocketWriter;
|
||||
pub use realtime_websocket::session_update_session_json;
|
||||
pub use responses::ResponsesClient;
|
||||
pub use responses::ResponsesOptions;
|
||||
pub use responses_websocket::ResponsesWebsocketClient;
|
||||
pub use responses_websocket::ResponsesWebsocketConnection;
|
||||
pub use responses_websocket_probe::ResponsesWebsocketClose;
|
||||
pub use responses_websocket_probe::ResponsesWebsocketProbe;
|
||||
pub use responses_websocket_probe::ResponsesWebsocketProbeError;
|
||||
pub use responses_websocket_probe::ResponsesWebsocketProbeFailureStage;
|
||||
pub use search::SearchClient;
|
||||
434
akode-rs/akode-api/src/endpoint/models.rs
Normal file
434
akode-rs/akode-api/src/endpoint/models.rs
Normal file
@@ -0,0 +1,434 @@
|
||||
use crate::auth::SharedAuthProvider;
|
||||
use crate::endpoint::session::EndpointSession;
|
||||
use crate::error::ApiError;
|
||||
use crate::provider::Provider;
|
||||
use bytes::Bytes;
|
||||
use akode_client::HttpTransport;
|
||||
use akode_client::RequestTelemetry;
|
||||
use akode_protocol::openai_models::ModelInfo;
|
||||
use akode_protocol::openai_models::ModelsResponse;
|
||||
use http::HeaderMap;
|
||||
use http::Method;
|
||||
use http::header::ETAG;
|
||||
use std::sync::Arc;
|
||||
use url::Url;
|
||||
|
||||
pub struct ModelsClient<T: HttpTransport> {
|
||||
session: EndpointSession<T>,
|
||||
}
|
||||
|
||||
impl<T: HttpTransport> ModelsClient<T> {
|
||||
pub fn new(transport: T, provider: Provider, auth: SharedAuthProvider) -> Self {
|
||||
Self {
|
||||
session: EndpointSession::new(transport, provider, auth),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_telemetry(self, request: Option<Arc<dyn RequestTelemetry>>) -> Self {
|
||||
Self {
|
||||
session: self.session.with_request_telemetry(request),
|
||||
}
|
||||
}
|
||||
|
||||
fn path() -> &'static str {
|
||||
"models"
|
||||
}
|
||||
|
||||
fn append_client_version_query(req: &mut akode_client::Request, client_version: &str) {
|
||||
let separator = if req.url.contains('?') { '&' } else { '?' };
|
||||
req.url = format!("{}{}client_version={client_version}", req.url, separator);
|
||||
}
|
||||
|
||||
pub fn request_url(provider: &Provider, client_version: &str) -> String {
|
||||
let mut request = provider.build_request(Method::GET, Self::path());
|
||||
Self::append_client_version_query(&mut request, client_version);
|
||||
request.url
|
||||
}
|
||||
|
||||
/// Builds a full catalog URL, preserving provider routing parameters and client version.
|
||||
pub fn catalog_request_url(
|
||||
provider: &Provider,
|
||||
catalog_url: &str,
|
||||
client_version: &str,
|
||||
) -> Result<String, ApiError> {
|
||||
let invalid = |message: &str| ApiError::InvalidRequest {
|
||||
message: message.to_string(),
|
||||
};
|
||||
let mut url = Url::parse(catalog_url)
|
||||
.map_err(|_| invalid("model_catalog_url must be an absolute URL"))?;
|
||||
{
|
||||
let mut query = url.query_pairs_mut();
|
||||
if let Some(params) = &provider.query_params {
|
||||
query.extend_pairs(params);
|
||||
}
|
||||
query.append_pair("client_version", client_version);
|
||||
}
|
||||
Ok(url.into())
|
||||
}
|
||||
|
||||
/// Fetches and decodes a catalog, optionally bounding response bytes before decoding.
|
||||
pub async fn list_models(
|
||||
&self,
|
||||
request_url: String,
|
||||
extra_headers: HeaderMap,
|
||||
response_body_limit_bytes: Option<usize>,
|
||||
) -> Result<(Vec<ModelInfo>, Option<String>), ApiError> {
|
||||
let (body, header_etag) = self
|
||||
.list_models_raw(request_url, extra_headers, response_body_limit_bytes)
|
||||
.await?;
|
||||
let ModelsResponse { models } =
|
||||
serde_json::from_slice::<ModelsResponse>(&body).map_err(|e| {
|
||||
ApiError::Stream(format!(
|
||||
"failed to decode models response: {:?} at line {} column {} (body: {} bytes)",
|
||||
e.classify(),
|
||||
e.line(),
|
||||
e.column(),
|
||||
body.len()
|
||||
))
|
||||
})?;
|
||||
|
||||
Ok((models, header_etag))
|
||||
}
|
||||
|
||||
/// Fetches a catalog using the provider's auth and retry policy without decoding it.
|
||||
///
|
||||
/// Callers accepting provider-controlled catalogs must validate the native response
|
||||
/// without including raw values in diagnostics.
|
||||
pub async fn list_models_raw(
|
||||
&self,
|
||||
request_url: String,
|
||||
extra_headers: HeaderMap,
|
||||
response_body_limit_bytes: Option<usize>,
|
||||
) -> Result<(Bytes, Option<String>), ApiError> {
|
||||
let resp = self
|
||||
.session
|
||||
.execute_with(
|
||||
Method::GET,
|
||||
Self::path(),
|
||||
extra_headers,
|
||||
/*body*/ None,
|
||||
move |req| {
|
||||
req.url.clone_from(&request_url);
|
||||
req.response_body_limit_bytes = response_body_limit_bytes;
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
let header_etag = resp
|
||||
.headers
|
||||
.get(ETAG)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.map(ToString::to_string);
|
||||
|
||||
Ok((resp.body, header_etag))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::auth::AuthError;
|
||||
use crate::auth::AuthProvider;
|
||||
use crate::auth::AuthProviderFuture;
|
||||
use crate::provider::RetryConfig;
|
||||
use akode_client::Request;
|
||||
use akode_client::Response;
|
||||
use akode_client::StreamResponse;
|
||||
use akode_client::TransportError;
|
||||
use http::HeaderMap;
|
||||
use http::StatusCode;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct CapturingTransport {
|
||||
last_request: Arc<Mutex<Option<Request>>>,
|
||||
body: Arc<ModelsResponse>,
|
||||
etag: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for CapturingTransport {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
last_request: Arc::new(Mutex::new(None)),
|
||||
body: Arc::new(ModelsResponse { models: Vec::new() }),
|
||||
etag: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HttpTransport for CapturingTransport {
|
||||
async fn execute(&self, req: Request) -> Result<Response, TransportError> {
|
||||
*self.last_request.lock().unwrap() = Some(req);
|
||||
let body = serde_json::to_vec(&*self.body).unwrap();
|
||||
let mut headers = HeaderMap::new();
|
||||
if let Some(etag) = &self.etag {
|
||||
headers.insert(ETAG, etag.parse().unwrap());
|
||||
}
|
||||
Ok(Response {
|
||||
status: StatusCode::OK,
|
||||
headers,
|
||||
body: body.into(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn stream(&self, _req: Request) -> Result<StreamResponse, TransportError> {
|
||||
Err(TransportError::Build("stream should not run".to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct DummyAuth;
|
||||
|
||||
impl AuthProvider for DummyAuth {
|
||||
fn add_auth_headers(&self, _headers: &mut HeaderMap) -> Result<(), crate::AuthError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct RetryAuth {
|
||||
request_limits: Mutex<Vec<Option<usize>>>,
|
||||
}
|
||||
|
||||
impl AuthProvider for RetryAuth {
|
||||
fn add_auth_headers(&self, headers: &mut HeaderMap) -> Result<(), AuthError> {
|
||||
headers.insert(http::header::AUTHORIZATION, "Bearer test".parse().unwrap());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn apply_auth(&self, mut request: Request) -> AuthProviderFuture<'_> {
|
||||
Box::pin(async move {
|
||||
let mut limits = self.request_limits.lock().unwrap();
|
||||
limits.push(request.response_body_limit_bytes);
|
||||
if limits.len() == 1 {
|
||||
return Err(AuthError::Transient("retry authentication".to_string()));
|
||||
}
|
||||
self.add_auth_headers(&mut request.headers)?;
|
||||
Ok(request)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn provider(base_url: &str) -> Provider {
|
||||
Provider {
|
||||
name: "test".to_string(),
|
||||
base_url: base_url.to_string(),
|
||||
query_params: None,
|
||||
headers: HeaderMap::new(),
|
||||
retry: RetryConfig {
|
||||
max_attempts: 1,
|
||||
base_delay: Duration::from_millis(1),
|
||||
retry_429: false,
|
||||
retry_5xx: true,
|
||||
retry_transport: true,
|
||||
},
|
||||
stream_idle_timeout: Duration::from_secs(1),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_request_url_preserves_routing_and_encodes_queries() {
|
||||
let mut provider = provider("https://gateway.example/v1");
|
||||
provider.query_params = Some(std::collections::HashMap::from([(
|
||||
"api-version".to_string(),
|
||||
"2026 09".to_string(),
|
||||
)]));
|
||||
let url = ModelsClient::<CapturingTransport>::catalog_request_url(
|
||||
&provider,
|
||||
"https://catalog.example/codex/models?deployment=one",
|
||||
"1.2.3",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
url,
|
||||
"https://catalog.example/codex/models?deployment=one&api-version=2026+09&client_version=1.2.3"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_request_url_rejects_relative_urls() {
|
||||
let provider = provider("https://gateway.example/v1");
|
||||
for catalog_url in ["/codex/models", "codex/models"] {
|
||||
let error = ModelsClient::<CapturingTransport>::catalog_request_url(
|
||||
&provider,
|
||||
catalog_url,
|
||||
"1.2.3",
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(matches!(error, ApiError::InvalidRequest { .. }));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn response_body_limit_survives_auth_retry_without_limiting_other_models_requests() {
|
||||
let transport = CapturingTransport::default();
|
||||
let auth = Arc::new(RetryAuth::default());
|
||||
let mut provider = provider("https://example.com/api/codex");
|
||||
provider.retry.max_attempts = 2;
|
||||
let request_url = ModelsClient::<CapturingTransport>::request_url(&provider, "0.99.0");
|
||||
let client = ModelsClient::new(transport.clone(), provider, auth.clone());
|
||||
|
||||
client
|
||||
.list_models(
|
||||
request_url.clone(),
|
||||
HeaderMap::new(),
|
||||
/*response_body_limit_bytes*/ Some(64),
|
||||
)
|
||||
.await
|
||||
.expect("limited request should succeed after auth retry");
|
||||
{
|
||||
let request = transport.last_request.lock().unwrap();
|
||||
let request = request.as_ref().unwrap();
|
||||
assert_eq!(request.response_body_limit_bytes, Some(64));
|
||||
assert_eq!(request.url, request_url);
|
||||
assert_eq!(request.headers[http::header::AUTHORIZATION], "Bearer test");
|
||||
}
|
||||
|
||||
let (models, _) = client
|
||||
.list_models(
|
||||
request_url,
|
||||
HeaderMap::new(),
|
||||
/*response_body_limit_bytes*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("ordinary request on the same client should remain unbounded");
|
||||
assert!(models.is_empty());
|
||||
assert_eq!(
|
||||
transport
|
||||
.last_request
|
||||
.lock()
|
||||
.unwrap()
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.response_body_limit_bytes,
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
*auth.request_limits.lock().unwrap(),
|
||||
vec![Some(64), Some(64), None]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn appends_client_version_query() {
|
||||
let response = ModelsResponse { models: Vec::new() };
|
||||
|
||||
let transport = CapturingTransport {
|
||||
last_request: Arc::new(Mutex::new(None)),
|
||||
body: Arc::new(response),
|
||||
etag: None,
|
||||
};
|
||||
|
||||
let provider = provider("https://example.com/api/codex");
|
||||
let request_url = ModelsClient::<CapturingTransport>::request_url(&provider, "0.99.0");
|
||||
let client = ModelsClient::new(transport.clone(), provider, Arc::new(DummyAuth));
|
||||
|
||||
let (models, _) = client
|
||||
.list_models(
|
||||
request_url,
|
||||
HeaderMap::new(),
|
||||
/*response_body_limit_bytes*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("request should succeed");
|
||||
|
||||
assert_eq!(models.len(), 0);
|
||||
|
||||
let url = transport
|
||||
.last_request
|
||||
.lock()
|
||||
.unwrap()
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.url
|
||||
.clone();
|
||||
assert_eq!(
|
||||
url,
|
||||
"https://example.com/api/codex/models?client_version=0.99.0"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn parses_models_response() {
|
||||
let response = ModelsResponse {
|
||||
models: vec![
|
||||
serde_json::from_value(json!({
|
||||
"slug": "gpt-test",
|
||||
"display_name": "gpt-test",
|
||||
"description": "desc",
|
||||
"default_reasoning_level": "medium",
|
||||
"supported_reasoning_levels": [{"effort": "low", "description": "low"}, {"effort": "medium", "description": "medium"}, {"effort": "high", "description": "high"}],
|
||||
"shell_type": "shell_command",
|
||||
"visibility": "list",
|
||||
"minimal_client_version": [0, 99, 0],
|
||||
"supported_in_api": true,
|
||||
"priority": 1,
|
||||
"upgrade": null,
|
||||
"support_verbosity": false,
|
||||
"default_verbosity": null,
|
||||
"apply_patch_tool_type": null,
|
||||
"truncation_policy": {"mode": "bytes", "limit": 10_000},
|
||||
"supports_image_detail_original": false,
|
||||
"context_window": 272_000,
|
||||
"experimental_supported_tools": [],
|
||||
}))
|
||||
.unwrap(),
|
||||
],
|
||||
};
|
||||
|
||||
let transport = CapturingTransport {
|
||||
last_request: Arc::new(Mutex::new(None)),
|
||||
body: Arc::new(response),
|
||||
etag: None,
|
||||
};
|
||||
|
||||
let provider = provider("https://example.com/api/codex");
|
||||
let request_url = ModelsClient::<CapturingTransport>::request_url(&provider, "0.99.0");
|
||||
let client = ModelsClient::new(transport, provider, Arc::new(DummyAuth));
|
||||
|
||||
let (models, _) = client
|
||||
.list_models(
|
||||
request_url,
|
||||
HeaderMap::new(),
|
||||
/*response_body_limit_bytes*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("request should succeed");
|
||||
|
||||
assert_eq!(models.len(), 1);
|
||||
assert_eq!(models[0].slug, "gpt-test");
|
||||
assert_eq!(models[0].supported_in_api, true);
|
||||
assert_eq!(models[0].priority, 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_models_includes_etag() {
|
||||
let response = ModelsResponse { models: Vec::new() };
|
||||
|
||||
let transport = CapturingTransport {
|
||||
last_request: Arc::new(Mutex::new(None)),
|
||||
body: Arc::new(response),
|
||||
etag: Some("\"abc\"".to_string()),
|
||||
};
|
||||
|
||||
let provider = provider("https://example.com/api/codex");
|
||||
let request_url = ModelsClient::<CapturingTransport>::request_url(&provider, "0.1.0");
|
||||
let client = ModelsClient::new(transport, provider, Arc::new(DummyAuth));
|
||||
|
||||
let (models, etag) = client
|
||||
.list_models(
|
||||
request_url,
|
||||
HeaderMap::new(),
|
||||
/*response_body_limit_bytes*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("request should succeed");
|
||||
|
||||
assert_eq!(models.len(), 0);
|
||||
assert_eq!(etag, Some("\"abc\"".to_string()));
|
||||
}
|
||||
}
|
||||
644
akode-rs/akode-api/src/endpoint/realtime_call.rs
Normal file
644
akode-rs/akode-api/src/endpoint/realtime_call.rs
Normal file
@@ -0,0 +1,644 @@
|
||||
use crate::auth::SharedAuthProvider;
|
||||
use crate::endpoint::realtime_websocket::RealtimeEventParser;
|
||||
use crate::endpoint::realtime_websocket::RealtimeSessionConfig;
|
||||
use crate::endpoint::realtime_websocket::session_update_session_json;
|
||||
use crate::endpoint::session::EndpointSession;
|
||||
use crate::error::ApiError;
|
||||
use crate::provider::Provider;
|
||||
use bytes::Bytes;
|
||||
use akode_client::HttpTransport;
|
||||
use akode_client::Request;
|
||||
use akode_client::RequestBody;
|
||||
use akode_client::RequestTelemetry;
|
||||
use http::HeaderMap;
|
||||
use http::HeaderValue;
|
||||
use http::Method;
|
||||
use http::header::CONTENT_TYPE;
|
||||
use http::header::LOCATION;
|
||||
use serde_json::Value;
|
||||
use serde_json::to_string;
|
||||
use std::sync::Arc;
|
||||
use tracing::instrument;
|
||||
use tracing::trace;
|
||||
|
||||
const MULTIPART_BOUNDARY: &str = "codex-realtime-call-boundary";
|
||||
const MULTIPART_CONTENT_TYPE: &str = "multipart/form-data; boundary=codex-realtime-call-boundary";
|
||||
|
||||
pub struct RealtimeCallClient<T: HttpTransport> {
|
||||
session: EndpointSession<T>,
|
||||
}
|
||||
|
||||
/// Answer from creating a WebRTC Realtime call.
|
||||
///
|
||||
/// `sdp` configures the peer connection. `call_id` is parsed from the response `Location` header
|
||||
/// and is later used by the server-side sideband WebSocket to join this exact call.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RealtimeCallResponse {
|
||||
pub sdp: String,
|
||||
pub call_id: String,
|
||||
}
|
||||
|
||||
impl<T: HttpTransport> RealtimeCallClient<T> {
|
||||
pub fn new(transport: T, provider: Provider, auth: SharedAuthProvider) -> Self {
|
||||
Self {
|
||||
session: EndpointSession::new(transport, provider, auth),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_telemetry(self, request: Option<Arc<dyn RequestTelemetry>>) -> Self {
|
||||
Self {
|
||||
session: self.session.with_request_telemetry(request),
|
||||
}
|
||||
}
|
||||
|
||||
fn path() -> &'static str {
|
||||
"realtime/calls"
|
||||
}
|
||||
|
||||
fn path_for_session(&self, event_parser: RealtimeEventParser) -> &'static str {
|
||||
match event_parser {
|
||||
RealtimeEventParser::FramelessBidi => "live",
|
||||
RealtimeEventParser::V1 | RealtimeEventParser::RealtimeV2 => Self::path(),
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument(
|
||||
name = "realtime_call.create",
|
||||
level = "info",
|
||||
skip_all,
|
||||
fields(
|
||||
http.method = "POST",
|
||||
api.path = "realtime/calls"
|
||||
)
|
||||
)]
|
||||
pub async fn create(&self, sdp: String) -> Result<RealtimeCallResponse, ApiError> {
|
||||
self.create_with_headers(sdp, HeaderMap::new()).await
|
||||
}
|
||||
|
||||
pub async fn create_with_session(
|
||||
&self,
|
||||
sdp: String,
|
||||
session_config: RealtimeSessionConfig,
|
||||
) -> Result<RealtimeCallResponse, ApiError> {
|
||||
self.create_with_session_and_headers(sdp, session_config, HeaderMap::new())
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn create_with_headers(
|
||||
&self,
|
||||
sdp: String,
|
||||
extra_headers: HeaderMap,
|
||||
) -> Result<RealtimeCallResponse, ApiError> {
|
||||
let resp = self
|
||||
.session
|
||||
.execute_with(
|
||||
Method::POST,
|
||||
Self::path(),
|
||||
extra_headers,
|
||||
/*body*/ None,
|
||||
|req| {
|
||||
req.headers
|
||||
.insert(CONTENT_TYPE, HeaderValue::from_static("application/sdp"));
|
||||
req.body = Some(RequestBody::Raw(Bytes::from(sdp.clone())));
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
let sdp = decode_sdp_response(resp.body.as_ref())?;
|
||||
let call_id = decode_call_id_from_location(&resp.headers)?;
|
||||
|
||||
Ok(RealtimeCallResponse { sdp, call_id })
|
||||
}
|
||||
|
||||
pub async fn create_with_session_and_headers(
|
||||
&self,
|
||||
sdp: String,
|
||||
session_config: RealtimeSessionConfig,
|
||||
extra_headers: HeaderMap,
|
||||
) -> Result<RealtimeCallResponse, ApiError> {
|
||||
trace!(target: "akode_api::realtime_websocket::wire", "realtime call request SDP: {sdp}");
|
||||
// WebRTC can begin inference as soon as the peer connection comes up, so the initial
|
||||
// session payload is sent with call creation. Legacy sidebands still send session.update
|
||||
// after joining; Frameless sidebands attach to the session that is already running.
|
||||
validate_avas_session_config(&session_config)?;
|
||||
let event_parser = session_config.event_parser;
|
||||
let path = self.path_for_session(event_parser);
|
||||
let mut session = realtime_session_json(session_config)?;
|
||||
if let Some(session) = session.as_object_mut() {
|
||||
session.remove("id");
|
||||
}
|
||||
let session = to_string(&session).map_err(|err| ApiError::InvalidRequest {
|
||||
message: err.to_string(),
|
||||
})?;
|
||||
let mut body = Vec::new();
|
||||
body.extend_from_slice(format!("--{MULTIPART_BOUNDARY}\r\n").as_bytes());
|
||||
body.extend_from_slice(b"Content-Disposition: form-data; name=\"sdp\"\r\n");
|
||||
body.extend_from_slice(b"Content-Type: application/sdp\r\n\r\n");
|
||||
body.extend_from_slice(sdp.as_bytes());
|
||||
body.extend_from_slice(b"\r\n");
|
||||
body.extend_from_slice(format!("--{MULTIPART_BOUNDARY}\r\n").as_bytes());
|
||||
body.extend_from_slice(b"Content-Disposition: form-data; name=\"session\"\r\n");
|
||||
body.extend_from_slice(b"Content-Type: application/json\r\n\r\n");
|
||||
body.extend_from_slice(session.as_bytes());
|
||||
body.extend_from_slice(b"\r\n");
|
||||
body.extend_from_slice(format!("--{MULTIPART_BOUNDARY}--\r\n").as_bytes());
|
||||
|
||||
let resp = self
|
||||
.session
|
||||
.execute_with(
|
||||
Method::POST,
|
||||
path,
|
||||
extra_headers,
|
||||
/*body*/ None,
|
||||
|req| {
|
||||
configure_realtime_call_request(req, event_parser);
|
||||
req.headers.insert(
|
||||
CONTENT_TYPE,
|
||||
HeaderValue::from_static(MULTIPART_CONTENT_TYPE),
|
||||
);
|
||||
req.body = Some(RequestBody::Raw(Bytes::from(body.clone())));
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
let sdp = decode_sdp_response(resp.body.as_ref())?;
|
||||
let call_id = decode_call_id_from_location(&resp.headers)?;
|
||||
|
||||
Ok(RealtimeCallResponse { sdp, call_id })
|
||||
}
|
||||
}
|
||||
|
||||
fn configure_realtime_call_request(request: &mut Request, event_parser: RealtimeEventParser) {
|
||||
if event_parser == RealtimeEventParser::V1 {
|
||||
append_query_pair(&mut request.url, "intent", "quicksilver");
|
||||
append_query_pair(&mut request.url, "architecture", "avas");
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_avas_session_config(session_config: &RealtimeSessionConfig) -> Result<(), ApiError> {
|
||||
if session_config.event_parser == RealtimeEventParser::RealtimeV2 {
|
||||
return Err(ApiError::InvalidRequest {
|
||||
message: "AVAS realtime calls require realtime v1 or v3".to_string(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn append_query_pair(url: &mut String, key: &str, value: &str) {
|
||||
if url.contains('?') {
|
||||
url.push('&');
|
||||
} else {
|
||||
url.push('?');
|
||||
}
|
||||
url.push_str(key);
|
||||
url.push('=');
|
||||
url.push_str(value);
|
||||
}
|
||||
|
||||
fn realtime_session_json(session_config: RealtimeSessionConfig) -> Result<Value, ApiError> {
|
||||
session_update_session_json(session_config)
|
||||
.map_err(|err| ApiError::Stream(format!("failed to encode realtime call session: {err}")))
|
||||
}
|
||||
|
||||
fn decode_sdp_response(body: &[u8]) -> Result<String, ApiError> {
|
||||
String::from_utf8(body.to_vec()).map_err(|err| {
|
||||
ApiError::Stream(format!(
|
||||
"failed to decode realtime call SDP response: {err}"
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
fn decode_call_id_from_location(headers: &HeaderMap) -> Result<String, ApiError> {
|
||||
let location = headers
|
||||
.get(LOCATION)
|
||||
.ok_or_else(|| ApiError::Stream("realtime call response missing Location".to_string()))?
|
||||
.to_str()
|
||||
.map_err(|err| ApiError::Stream(format!("invalid realtime call Location: {err}")))?;
|
||||
trace!("realtime call Location: {location}");
|
||||
|
||||
location
|
||||
.split('?')
|
||||
.next()
|
||||
.unwrap_or(location)
|
||||
.rsplit('/')
|
||||
.find(|segment| is_realtime_call_id_segment(segment))
|
||||
.map(str::to_string)
|
||||
.ok_or_else(|| {
|
||||
ApiError::Stream(format!(
|
||||
"realtime call Location does not contain a call id: {location}"
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
fn is_realtime_call_id_segment(segment: &str) -> bool {
|
||||
if segment.starts_with("rtc_") && segment.len() > "rtc_".len() {
|
||||
return true;
|
||||
}
|
||||
|
||||
if segment.len() != 36 {
|
||||
return false;
|
||||
}
|
||||
|
||||
segment.char_indices().all(|(index, ch)| match index {
|
||||
8 | 13 | 18 | 23 => ch == '-',
|
||||
_ => ch.is_ascii_hexdigit(),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::auth::AuthProvider;
|
||||
use crate::endpoint::realtime_websocket::RealtimeEventParser;
|
||||
use crate::endpoint::realtime_websocket::RealtimeOutputModality;
|
||||
use crate::endpoint::realtime_websocket::RealtimeSessionMode;
|
||||
use crate::provider::RetryConfig;
|
||||
use akode_client::Request;
|
||||
use akode_client::Response;
|
||||
use akode_client::StreamResponse;
|
||||
use akode_client::TransportError;
|
||||
use akode_protocol::protocol::RealtimeVoice;
|
||||
use http::StatusCode;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct CapturingTransport {
|
||||
last_request: Arc<Mutex<Option<Request>>>,
|
||||
response_headers: HeaderMap,
|
||||
}
|
||||
|
||||
impl CapturingTransport {
|
||||
fn new() -> Self {
|
||||
Self::with_location("/v1/realtime/calls/rtc_test")
|
||||
}
|
||||
|
||||
fn with_location(location: &str) -> Self {
|
||||
let mut response_headers = HeaderMap::new();
|
||||
response_headers.insert(LOCATION, HeaderValue::from_str(location).unwrap());
|
||||
Self {
|
||||
last_request: Arc::new(Mutex::new(None)),
|
||||
response_headers,
|
||||
}
|
||||
}
|
||||
|
||||
fn without_location() -> Self {
|
||||
Self {
|
||||
last_request: Arc::new(Mutex::new(None)),
|
||||
response_headers: HeaderMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HttpTransport for CapturingTransport {
|
||||
async fn execute(&self, req: Request) -> Result<Response, TransportError> {
|
||||
*self.last_request.lock().unwrap() = Some(req);
|
||||
Ok(Response {
|
||||
status: StatusCode::OK,
|
||||
headers: self.response_headers.clone(),
|
||||
body: Bytes::from_static(b"v=0\r\n"),
|
||||
})
|
||||
}
|
||||
|
||||
async fn stream(&self, _req: Request) -> Result<StreamResponse, TransportError> {
|
||||
Err(TransportError::Build("stream should not run".to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct DummyAuth;
|
||||
|
||||
impl AuthProvider for DummyAuth {
|
||||
fn add_auth_headers(&self, headers: &mut HeaderMap) -> Result<(), crate::AuthError> {
|
||||
headers.insert(
|
||||
http::header::AUTHORIZATION,
|
||||
HeaderValue::from_static("Bearer test-token"),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn provider(base_url: &str) -> Provider {
|
||||
Provider {
|
||||
name: "test".to_string(),
|
||||
base_url: base_url.to_string(),
|
||||
query_params: None,
|
||||
headers: HeaderMap::new(),
|
||||
retry: RetryConfig {
|
||||
max_attempts: 1,
|
||||
base_delay: Duration::from_millis(1),
|
||||
retry_429: false,
|
||||
retry_5xx: true,
|
||||
retry_transport: true,
|
||||
},
|
||||
stream_idle_timeout: Duration::from_secs(1),
|
||||
}
|
||||
}
|
||||
|
||||
fn realtime_session_config(session_id: &str) -> RealtimeSessionConfig {
|
||||
RealtimeSessionConfig {
|
||||
instructions: "hi".to_string(),
|
||||
initial_items: Vec::new(),
|
||||
delegation_ack_filler: None,
|
||||
model: Some("gpt-realtime".to_string()),
|
||||
session_id: Some(session_id.to_string()),
|
||||
event_parser: RealtimeEventParser::V1,
|
||||
session_mode: RealtimeSessionMode::Conversational,
|
||||
output_modality: RealtimeOutputModality::Audio,
|
||||
voice: RealtimeVoice::Cove,
|
||||
}
|
||||
}
|
||||
|
||||
fn realtime_v2_session_config(session_id: &str) -> RealtimeSessionConfig {
|
||||
RealtimeSessionConfig {
|
||||
event_parser: RealtimeEventParser::RealtimeV2,
|
||||
voice: RealtimeVoice::Marin,
|
||||
..realtime_session_config(session_id)
|
||||
}
|
||||
}
|
||||
|
||||
fn frameless_bidi_session_config(session_id: &str) -> RealtimeSessionConfig {
|
||||
RealtimeSessionConfig {
|
||||
event_parser: RealtimeEventParser::FramelessBidi,
|
||||
..realtime_session_config(session_id)
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sends_sdp_offer_as_raw_body() {
|
||||
let transport = CapturingTransport::new();
|
||||
let client = RealtimeCallClient::new(
|
||||
transport.clone(),
|
||||
provider("https://api.openai.com/v1"),
|
||||
Arc::new(DummyAuth),
|
||||
);
|
||||
|
||||
let response = client
|
||||
.create("v=offer\r\n".to_string())
|
||||
.await
|
||||
.expect("request should succeed");
|
||||
|
||||
assert_eq!(
|
||||
response,
|
||||
RealtimeCallResponse {
|
||||
sdp: "v=0\r\n".to_string(),
|
||||
call_id: "rtc_test".to_string(),
|
||||
}
|
||||
);
|
||||
|
||||
let request = transport.last_request.lock().unwrap().clone().unwrap();
|
||||
assert_eq!(request.method, Method::POST);
|
||||
assert_eq!(request.url, "https://api.openai.com/v1/realtime/calls");
|
||||
assert_eq!(
|
||||
request.headers.get(CONTENT_TYPE).unwrap(),
|
||||
HeaderValue::from_static("application/sdp")
|
||||
);
|
||||
assert_eq!(
|
||||
request
|
||||
.headers
|
||||
.get(http::header::AUTHORIZATION)
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some("Bearer test-token")
|
||||
);
|
||||
assert_eq!(
|
||||
request.body,
|
||||
Some(RequestBody::Raw(Bytes::from_static(b"v=offer\r\n")))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn extracts_call_id_from_forwarded_gateway_location() {
|
||||
let transport =
|
||||
CapturingTransport::with_location("/v1/realtime/calls/calls/rtc_backend_test");
|
||||
let client = RealtimeCallClient::new(
|
||||
transport.clone(),
|
||||
provider("https://gateway.example/backend/v1"),
|
||||
Arc::new(DummyAuth),
|
||||
);
|
||||
|
||||
let response = client
|
||||
.create("v=offer\r\n".to_string())
|
||||
.await
|
||||
.expect("request should succeed");
|
||||
|
||||
assert_eq!(
|
||||
response,
|
||||
RealtimeCallResponse {
|
||||
sdp: "v=0\r\n".to_string(),
|
||||
call_id: "rtc_backend_test".to_string(),
|
||||
}
|
||||
);
|
||||
|
||||
let request = transport.last_request.lock().unwrap().clone().unwrap();
|
||||
assert_eq!(request.method, Method::POST);
|
||||
assert_eq!(
|
||||
request.url,
|
||||
"https://gateway.example/backend/v1/realtime/calls"
|
||||
);
|
||||
assert_eq!(
|
||||
request.body,
|
||||
Some(RequestBody::Raw(Bytes::from_static(b"v=offer\r\n")))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sends_api_session_call_as_multipart_body() {
|
||||
let transport = CapturingTransport::new();
|
||||
let client = RealtimeCallClient::new(
|
||||
transport.clone(),
|
||||
provider("https://api.openai.com/v1"),
|
||||
Arc::new(DummyAuth),
|
||||
);
|
||||
|
||||
let response = client
|
||||
.create_with_session(
|
||||
"v=offer\r\n".to_string(),
|
||||
realtime_session_config("sess-api"),
|
||||
)
|
||||
.await
|
||||
.expect("request should succeed");
|
||||
|
||||
assert_eq!(
|
||||
response,
|
||||
RealtimeCallResponse {
|
||||
sdp: "v=0\r\n".to_string(),
|
||||
call_id: "rtc_test".to_string(),
|
||||
}
|
||||
);
|
||||
|
||||
let request = transport.last_request.lock().unwrap().clone().unwrap();
|
||||
assert_eq!(request.method, Method::POST);
|
||||
assert_eq!(
|
||||
request.url,
|
||||
"https://api.openai.com/v1/realtime/calls?intent=quicksilver&architecture=avas"
|
||||
);
|
||||
assert_eq!(
|
||||
request.headers.get(CONTENT_TYPE).unwrap(),
|
||||
HeaderValue::from_static(MULTIPART_CONTENT_TYPE)
|
||||
);
|
||||
let Some(RequestBody::Raw(body)) = request.body else {
|
||||
panic!("multipart body should be raw");
|
||||
};
|
||||
let body = std::str::from_utf8(&body).expect("multipart body should be utf-8");
|
||||
let mut session = realtime_session_json(realtime_session_config("sess-api"))
|
||||
.expect("session should encode");
|
||||
session
|
||||
.as_object_mut()
|
||||
.expect("session should be an object")
|
||||
.remove("id");
|
||||
let session = to_string(&session).expect("session should serialize");
|
||||
assert_eq!(
|
||||
body,
|
||||
format!(
|
||||
"--codex-realtime-call-boundary\r\n\
|
||||
Content-Disposition: form-data; name=\"sdp\"\r\n\
|
||||
Content-Type: application/sdp\r\n\
|
||||
\r\n\
|
||||
v=offer\r\n\
|
||||
\r\n\
|
||||
--codex-realtime-call-boundary\r\n\
|
||||
Content-Disposition: form-data; name=\"session\"\r\n\
|
||||
Content-Type: application/json\r\n\
|
||||
\r\n\
|
||||
{session}\r\n\
|
||||
--codex-realtime-call-boundary--\r\n"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sends_frameless_session_call_to_live_without_legacy_query_params() {
|
||||
let transport = CapturingTransport::with_location("/v1/live/rtc_frameless");
|
||||
let client = RealtimeCallClient::new(
|
||||
transport.clone(),
|
||||
provider("https://api.openai.com/v1"),
|
||||
Arc::new(DummyAuth),
|
||||
);
|
||||
|
||||
let response = client
|
||||
.create_with_session(
|
||||
"v=offer\r\n".to_string(),
|
||||
frameless_bidi_session_config("sess-api"),
|
||||
)
|
||||
.await
|
||||
.expect("request should succeed");
|
||||
|
||||
assert_eq!(response.call_id, "rtc_frameless");
|
||||
let request = transport.last_request.lock().unwrap().clone().unwrap();
|
||||
assert_eq!(request.method, Method::POST);
|
||||
assert_eq!(request.url, "https://api.openai.com/v1/live");
|
||||
let Some(RequestBody::Raw(body)) = request.body else {
|
||||
panic!("multipart body should be raw");
|
||||
};
|
||||
let body = std::str::from_utf8(&body).expect("multipart body should be utf-8");
|
||||
assert!(body.contains("\"model\":\"gpt-realtime\""));
|
||||
assert!(body.contains("\"delegation\":{\"type\":\"client\"}"));
|
||||
assert!(!body.contains("\"id\":\"sess-api\""));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sends_session_call_with_avas_query_params() {
|
||||
let transport = CapturingTransport::new();
|
||||
let client = RealtimeCallClient::new(
|
||||
transport.clone(),
|
||||
provider("https://api.openai.com/v1"),
|
||||
Arc::new(DummyAuth),
|
||||
);
|
||||
|
||||
let response = client
|
||||
.create_with_session_and_headers(
|
||||
"v=offer\r\n".to_string(),
|
||||
realtime_session_config("sess-api"),
|
||||
HeaderMap::new(),
|
||||
)
|
||||
.await
|
||||
.expect("request should succeed");
|
||||
|
||||
assert_eq!(
|
||||
response,
|
||||
RealtimeCallResponse {
|
||||
sdp: "v=0\r\n".to_string(),
|
||||
call_id: "rtc_test".to_string(),
|
||||
}
|
||||
);
|
||||
|
||||
let request = transport.last_request.lock().unwrap().clone().unwrap();
|
||||
assert_eq!(request.method, Method::POST);
|
||||
assert_eq!(
|
||||
request.url,
|
||||
"https://api.openai.com/v1/realtime/calls?intent=quicksilver&architecture=avas"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_v2_session_call_before_sending_request() {
|
||||
let transport = CapturingTransport::new();
|
||||
let client = RealtimeCallClient::new(
|
||||
transport.clone(),
|
||||
provider("https://api.openai.com/v1"),
|
||||
Arc::new(DummyAuth),
|
||||
);
|
||||
|
||||
let err = client
|
||||
.create_with_session(
|
||||
"v=offer\r\n".to_string(),
|
||||
realtime_v2_session_config("sess-api"),
|
||||
)
|
||||
.await
|
||||
.expect_err("v2 session config should be rejected");
|
||||
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"invalid request: AVAS realtime calls require realtime v1 or v3"
|
||||
);
|
||||
assert!(transport.last_request.lock().unwrap().is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn errors_when_location_is_missing() {
|
||||
let transport = CapturingTransport::without_location();
|
||||
let client = RealtimeCallClient::new(
|
||||
transport,
|
||||
provider("https://api.openai.com/v1"),
|
||||
Arc::new(DummyAuth),
|
||||
);
|
||||
|
||||
let err = client
|
||||
.create("v=offer\r\n".to_string())
|
||||
.await
|
||||
.expect_err("request should require Location");
|
||||
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"stream error: realtime call response missing Location"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_location_without_call_id() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(LOCATION, HeaderValue::from_static("/v1/realtime/calls"));
|
||||
|
||||
let err = decode_call_id_from_location(&headers)
|
||||
.expect_err("Location without rtc_ segment should fail");
|
||||
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"stream error: realtime call Location does not contain a call id: /v1/realtime/calls"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_uuid_call_id_from_location() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
LOCATION,
|
||||
HeaderValue::from_static("/v1/realtime/calls/019eb97d-8e9a-7ff3-94b0-ea019babd5d7"),
|
||||
);
|
||||
|
||||
let call_id = decode_call_id_from_location(&headers).expect("UUID call id should parse");
|
||||
|
||||
assert_eq!(call_id, "019eb97d-8e9a-7ff3-94b0-ea019babd5d7");
|
||||
}
|
||||
}
|
||||
3288
akode-rs/akode-api/src/endpoint/realtime_websocket/methods.rs
Normal file
3288
akode-rs/akode-api/src/endpoint/realtime_websocket/methods.rs
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,158 @@
|
||||
//! Adapts caller-owned, bounded JSON channels to the existing realtime parser and writer.
|
||||
//!
|
||||
//! ```text
|
||||
//! Caller -- incoming JSON --> read loop -- Message::Text --> Core event parser
|
||||
//! Caller <-- outgoing JSON -- write loop <-- WsCommand ----- Core writer
|
||||
//! ```
|
||||
//!
|
||||
//! Each channel item carries one JSON message of up to 1 MiB. The loops run
|
||||
//! independently so Core can still receive events while a command waits for
|
||||
//! space in the caller's queue. Shutdown seals incoming messages and drains accepted
|
||||
//! input before closing both directions, including a frame awaiting parser capacity.
|
||||
|
||||
use super::*;
|
||||
use akode_protocol::protocol::RealtimeSidebandTransport;
|
||||
|
||||
const MAX_MESSAGE_BYTES: usize = 1024 * 1024;
|
||||
|
||||
impl RealtimeWebsocketConnection {
|
||||
/// Uses an already authenticated, caller-owned stream without opening or reconnecting a socket.
|
||||
pub fn from_sideband(
|
||||
transport: RealtimeSidebandTransport,
|
||||
event_parser: RealtimeEventParser,
|
||||
) -> Self {
|
||||
let RealtimeSidebandTransport {
|
||||
mut incoming,
|
||||
outgoing,
|
||||
} = transport;
|
||||
|
||||
let (tx_command, mut rx_command) = mpsc::channel::<WsCommand>(32);
|
||||
let (tx_message, rx_message) = async_channel::bounded(32);
|
||||
let (_, terminal_policy_error) = tokio::sync::watch::channel(None);
|
||||
|
||||
let (input_stop, mut input_stopped) = tokio::sync::watch::channel(false);
|
||||
let transport_input_stop = input_stop.clone();
|
||||
let transport_task = tokio::spawn(async move {
|
||||
let read = async {
|
||||
let mut is_draining = false;
|
||||
loop {
|
||||
let text = if is_draining {
|
||||
// A reserved but unsent permit must not hold shutdown open.
|
||||
// try_recv() will drain messages already queued and exit when emptied.
|
||||
incoming.try_recv().ok()
|
||||
} else {
|
||||
tokio::select! {
|
||||
biased;
|
||||
// Core requested shutdown, or the transport's write loop ended.
|
||||
_ = input_stopped.changed() => {
|
||||
incoming.close();
|
||||
is_draining = true;
|
||||
continue;
|
||||
}
|
||||
// The caller dropped its receiver for Core commands.
|
||||
// Detect this even when the writer is idle, then drain accepted input.
|
||||
_ = outgoing.closed() => {
|
||||
incoming.close();
|
||||
is_draining = true;
|
||||
continue;
|
||||
}
|
||||
text = incoming.recv() => text,
|
||||
}
|
||||
};
|
||||
let Some(text) = text else {
|
||||
break;
|
||||
};
|
||||
if text.len() > MAX_MESSAGE_BYTES {
|
||||
break;
|
||||
}
|
||||
if tx_message
|
||||
.send(Ok(Message::Text(text.into())))
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let write = async {
|
||||
while let Some(command) = rx_command.recv().await {
|
||||
// These commands are still called WsCommand for legacy reasons.
|
||||
match command {
|
||||
WsCommand::Send {
|
||||
message: Message::Text(text),
|
||||
tx_result,
|
||||
} => {
|
||||
let result = if text.len() > MAX_MESSAGE_BYTES {
|
||||
Err(WsError::Io(std::io::Error::other(
|
||||
"sideband message too large",
|
||||
)))
|
||||
} else {
|
||||
outgoing
|
||||
.send(text.to_string())
|
||||
.await
|
||||
.map_err(|_| WsError::ConnectionClosed)
|
||||
};
|
||||
let failed = result.is_err();
|
||||
// Tell Core's writer whether the caller's channel accepted the command.
|
||||
let _ = tx_result.send(result);
|
||||
if failed {
|
||||
break;
|
||||
}
|
||||
}
|
||||
WsCommand::Close {
|
||||
frame: _,
|
||||
tx_result,
|
||||
} => {
|
||||
let _ = tx_result.send(Ok(()));
|
||||
break;
|
||||
}
|
||||
WsCommand::Send { tx_result, .. } => {
|
||||
let _ = tx_result.send(Err(WsError::Io(std::io::Error::other(
|
||||
"sideband requires JSON text",
|
||||
))));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
tokio::pin!(read);
|
||||
tokio::select! {
|
||||
_ = &mut read => {},
|
||||
_ = write => {
|
||||
transport_input_stop.send_replace(true);
|
||||
// Preserve the read future: it may already own a frame that
|
||||
// has not yet fit into the parser queue.
|
||||
read.await;
|
||||
},
|
||||
}
|
||||
});
|
||||
|
||||
Self::new(
|
||||
WsStream {
|
||||
tx_command,
|
||||
transport_task,
|
||||
sideband_input_stop: Some(input_stop),
|
||||
terminal_policy_error,
|
||||
},
|
||||
rx_message,
|
||||
event_parser,
|
||||
RealtimeTranscriptState::default(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl RealtimeWebsocketWriter {
|
||||
/// Seal caller-owned input so its accepted events can drain without waiting for producers.
|
||||
/// Socket-backed connections are unaffected.
|
||||
pub fn close_sideband_input(&self) {
|
||||
if let Some(input_stop) = &self.stream.sideband_input_stop {
|
||||
input_stop.send_replace(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "sideband_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,210 @@
|
||||
#![cfg(test)]
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::time::Duration;
|
||||
use tokio::time::timeout;
|
||||
|
||||
fn connection() -> (
|
||||
RealtimeWebsocketConnection,
|
||||
mpsc::Sender<String>,
|
||||
mpsc::Receiver<String>,
|
||||
) {
|
||||
let (events, incoming) = mpsc::channel(1);
|
||||
let (outgoing, commands) = mpsc::channel(1);
|
||||
(
|
||||
RealtimeWebsocketConnection::from_sideband(
|
||||
RealtimeSidebandTransport { incoming, outgoing },
|
||||
RealtimeEventParser::FramelessBidi,
|
||||
),
|
||||
events,
|
||||
commands,
|
||||
)
|
||||
}
|
||||
|
||||
/// A blocked command receiver must not prevent receiving a realtime event on the other half.
|
||||
#[tokio::test]
|
||||
async fn stalled_output_does_not_block_input() {
|
||||
let (connection, events, commands) = connection();
|
||||
let writer = connection.writer();
|
||||
writer.send_payload("first".into()).await.unwrap();
|
||||
let blocked = tokio::spawn(async move { writer.send_payload("second".into()).await });
|
||||
events
|
||||
.send(r#"{"type":"session.started","session":{"id":"call"}}"#.into())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
timeout(Duration::from_secs(1), connection.next_event())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.is_some()
|
||||
);
|
||||
assert!(!blocked.is_finished());
|
||||
drop(commands);
|
||||
assert!(
|
||||
timeout(Duration::from_secs(1), blocked)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
timeout(Duration::from_secs(1), connection.next_event())
|
||||
.await
|
||||
.unwrap()
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
/// Ending the input stream closes the output too and never attempts reconnection.
|
||||
#[tokio::test]
|
||||
async fn input_half_close_ends_attachment() {
|
||||
let (connection, events, mut commands) = connection();
|
||||
drop(events);
|
||||
assert!(
|
||||
timeout(Duration::from_secs(1), connection.next_event())
|
||||
.await
|
||||
.unwrap()
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(
|
||||
timeout(Duration::from_secs(1), commands.recv())
|
||||
.await
|
||||
.unwrap(),
|
||||
None
|
||||
);
|
||||
assert!(
|
||||
connection
|
||||
.writer()
|
||||
.send_payload("late".into())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
/// A caller dropping its response half releases an idle transport without waiting for another command.
|
||||
#[tokio::test]
|
||||
async fn response_half_close_ends_idle_attachment() {
|
||||
let (_connection, events, commands) = connection();
|
||||
drop(commands);
|
||||
timeout(Duration::from_secs(1), events.closed())
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Oversized payloads fail the transport before entering the parser or caller's outgoing queue.
|
||||
#[tokio::test]
|
||||
async fn oversized_payloads_close_both_directions() {
|
||||
let (input_connection, events, mut commands) = connection();
|
||||
events
|
||||
.send("x".repeat(MAX_MESSAGE_BYTES + 1))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
timeout(Duration::from_secs(1), input_connection.next_event())
|
||||
.await
|
||||
.unwrap()
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(
|
||||
timeout(Duration::from_secs(1), commands.recv())
|
||||
.await
|
||||
.unwrap(),
|
||||
None
|
||||
);
|
||||
let (output_connection, _events, mut commands) = connection();
|
||||
assert!(
|
||||
output_connection
|
||||
.writer()
|
||||
.send_payload("x".repeat(MAX_MESSAGE_BYTES + 1))
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(
|
||||
timeout(Duration::from_secs(1), commands.recv())
|
||||
.await
|
||||
.unwrap(),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
/// A final transcript accepted before peer hangup must reach both the parser and transcript tail.
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn queued_transcript_survives_peer_hangup() {
|
||||
for _ in 0..64 {
|
||||
let (connection, events, commands) = connection();
|
||||
events
|
||||
.try_send(r#"{"type":"input_transcript.added","item":{"text":"last words"}}"#.into())
|
||||
.unwrap();
|
||||
drop(events);
|
||||
drop(commands);
|
||||
assert_eq!(
|
||||
timeout(Duration::from_secs(1), connection.next_event())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap(),
|
||||
Some(
|
||||
akode_protocol::protocol::RealtimeEvent::InputTranscriptDelta(
|
||||
akode_protocol::protocol::RealtimeTranscriptDelta {
|
||||
delta: "last words".into()
|
||||
}
|
||||
)
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
connection.events().take_transcript_tail().await,
|
||||
vec![akode_protocol::protocol::RealtimeTranscriptEntry {
|
||||
role: "user".into(),
|
||||
text: "last words".into()
|
||||
}]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Explicit shutdown preserves a frame blocked on parser capacity and does not wait for an unsent permit.
|
||||
#[tokio::test]
|
||||
async fn input_stop_drains_backpressure_without_waiting_for_reserved_permit() {
|
||||
let (events, incoming) = mpsc::channel(64);
|
||||
let (outgoing, _commands) = mpsc::channel(1);
|
||||
let connection = RealtimeWebsocketConnection::from_sideband(
|
||||
RealtimeSidebandTransport { incoming, outgoing },
|
||||
RealtimeEventParser::FramelessBidi,
|
||||
);
|
||||
let _permit = events.reserve().await.unwrap();
|
||||
for _ in 0..63 {
|
||||
events
|
||||
.try_send(r#"{"type":"input_transcript.added","item":{"text":"tail"}}"#.into())
|
||||
.unwrap();
|
||||
}
|
||||
timeout(Duration::from_secs(1), async {
|
||||
while events.capacity() < 33 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
connection.writer().close_sideband_input();
|
||||
for _ in 0..63 {
|
||||
assert_eq!(
|
||||
timeout(Duration::from_secs(1), connection.next_event())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap(),
|
||||
Some(
|
||||
akode_protocol::protocol::RealtimeEvent::InputTranscriptDelta(
|
||||
akode_protocol::protocol::RealtimeTranscriptDelta {
|
||||
delta: "tail".into()
|
||||
}
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
timeout(Duration::from_secs(1), connection.next_event())
|
||||
.await
|
||||
.unwrap()
|
||||
.is_err()
|
||||
);
|
||||
assert!(events.is_closed());
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
//! Verifies fresh handshake credentials and rejection after the selected credentials change.
|
||||
|
||||
use super::*;
|
||||
use crate::AuthError;
|
||||
use crate::AuthHeadersFuture;
|
||||
use crate::AuthProvider;
|
||||
use crate::provider::RetryConfig;
|
||||
use http::HeaderName;
|
||||
use http::header::AUTHORIZATION;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::time::Duration;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio_tungstenite::accept_hdr_async;
|
||||
use tokio_tungstenite::tungstenite::handshake::server::Request;
|
||||
use tokio_tungstenite::tungstenite::handshake::server::Response;
|
||||
|
||||
struct HandshakeAuth(AtomicUsize);
|
||||
|
||||
impl AuthProvider for HandshakeAuth {
|
||||
fn add_auth_headers(&self, _headers: &mut HeaderMap) -> Result<(), AuthError> {
|
||||
Err(AuthError::Build(
|
||||
"authentication requires async header resolution".to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
fn apply_auth_headers(&self, mut headers: HeaderMap) -> AuthHeadersFuture<'_> {
|
||||
Box::pin(async move {
|
||||
let attempt = self.0.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
headers.remove("x-openai-agent-assertion");
|
||||
headers.insert(
|
||||
AUTHORIZATION,
|
||||
format!("AgentAssertion proof-{attempt}").parse().unwrap(),
|
||||
);
|
||||
Ok(headers)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn client(base_url: String) -> RealtimeWebsocketClient {
|
||||
RealtimeWebsocketClient::new(
|
||||
Provider {
|
||||
name: "test".to_string(),
|
||||
base_url: base_url.clone(),
|
||||
query_params: None,
|
||||
headers: HeaderMap::new(),
|
||||
retry: RetryConfig {
|
||||
max_attempts: 1,
|
||||
base_delay: Duration::from_millis(1),
|
||||
retry_429: false,
|
||||
retry_5xx: true,
|
||||
retry_transport: true,
|
||||
},
|
||||
stream_idle_timeout: Duration::from_secs(5),
|
||||
},
|
||||
akode_http_client::HttpClientFactory::new(
|
||||
akode_http_client::OutboundProxyPolicy::ReqwestDefault,
|
||||
),
|
||||
)
|
||||
.with_webrtc_sideband_base_url(base_url)
|
||||
}
|
||||
|
||||
fn session() -> RealtimeSessionConfig {
|
||||
RealtimeSessionConfig {
|
||||
instructions: String::new(),
|
||||
initial_items: Vec::new(),
|
||||
delegation_ack_filler: None,
|
||||
model: None,
|
||||
session_id: None,
|
||||
event_parser: RealtimeEventParser::V1,
|
||||
session_mode: RealtimeSessionMode::Conversational,
|
||||
output_modality: RealtimeOutputModality::Audio,
|
||||
voice: RealtimeVoice::Cedar,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sideband_retry_and_reconnect_replace_cached_auth_headers() -> anyhow::Result<()> {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let base_url = format!("http://{}/v1", listener.local_addr()?);
|
||||
let server = tokio::spawn(async move {
|
||||
let mut requests = Vec::new();
|
||||
for attempt in 0..3 {
|
||||
let (stream, _) = listener.accept().await.unwrap();
|
||||
let result = accept_hdr_async(stream, |request: &Request, response: Response| {
|
||||
requests.push(request.headers().clone());
|
||||
if attempt == 0 {
|
||||
Err(http::Response::builder().status(503).body(None).unwrap())
|
||||
} else {
|
||||
Ok(response)
|
||||
}
|
||||
})
|
||||
.await;
|
||||
if attempt == 0 {
|
||||
assert!(result.is_err());
|
||||
} else {
|
||||
let mut stream = result.unwrap();
|
||||
assert!(matches!(stream.next().await, Some(Ok(Message::Close(_)))));
|
||||
}
|
||||
}
|
||||
requests
|
||||
});
|
||||
let client = client(base_url).with_auth(Arc::new(HandshakeAuth(AtomicUsize::new(0))));
|
||||
let headers = HeaderMap::from_iter([
|
||||
(
|
||||
AUTHORIZATION,
|
||||
HeaderValue::from_static("Bearer stale-credential"),
|
||||
),
|
||||
(
|
||||
HeaderName::from_static("x-openai-agent-assertion"),
|
||||
HeaderValue::from_static("stale-proof"),
|
||||
),
|
||||
(
|
||||
HeaderName::from_static("x-request-context"),
|
||||
HeaderValue::from_static("keep"),
|
||||
),
|
||||
]);
|
||||
for _ in 0..2 {
|
||||
let connection = tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
client.connect_existing_call_sideband(
|
||||
session(),
|
||||
"rtc_test",
|
||||
headers.clone(),
|
||||
HeaderMap::new(),
|
||||
RealtimeTranscriptState::default(),
|
||||
),
|
||||
)
|
||||
.await??;
|
||||
connection.close().await?;
|
||||
}
|
||||
let requests = tokio::time::timeout(Duration::from_secs(5), server).await??;
|
||||
assert_eq!(requests.len(), 3);
|
||||
for (index, headers) in requests.iter().enumerate() {
|
||||
assert_eq!(
|
||||
headers[AUTHORIZATION],
|
||||
format!("AgentAssertion proof-{}", index + 1)
|
||||
);
|
||||
assert!(!headers.contains_key("x-openai-agent-assertion"));
|
||||
assert_eq!(headers["x-request-context"], "keep");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct RejectedAuth;
|
||||
|
||||
impl AuthProvider for RejectedAuth {
|
||||
fn add_auth_headers(&self, _headers: &mut HeaderMap) -> Result<(), AuthError> {
|
||||
Err(AuthError::Build(
|
||||
"authentication requires async header resolution".to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
fn apply_auth_headers(&self, _headers: http::HeaderMap) -> AuthHeadersFuture<'_> {
|
||||
Box::pin(async { Err(AuthError::Build("runtime revoked".to_string())) })
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejected_auth_prevents_the_websocket_request() -> anyhow::Result<()> {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let client =
|
||||
client(format!("http://{}/v1", listener.local_addr()?)).with_auth(Arc::new(RejectedAuth));
|
||||
let result = client
|
||||
.connect(session(), HeaderMap::new(), HeaderMap::new())
|
||||
.await;
|
||||
assert!(result.is_err());
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(50), listener.accept())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
use crate::endpoint::realtime_websocket::methods_frameless_bidi::delegation_context_append_message as frameless_delegation_context_append_message;
|
||||
use crate::endpoint::realtime_websocket::methods_frameless_bidi::session_context_append_message as frameless_session_context_append_message;
|
||||
use crate::endpoint::realtime_websocket::methods_frameless_bidi::session_json as frameless_session_json;
|
||||
use crate::endpoint::realtime_websocket::methods_frameless_bidi::session_update_message as frameless_session_update_message;
|
||||
use crate::endpoint::realtime_websocket::methods_v1::conversation_handoff_append_message as v1_conversation_handoff_append_message;
|
||||
use crate::endpoint::realtime_websocket::methods_v1::conversation_item_create_message as v1_conversation_item_create_message;
|
||||
use crate::endpoint::realtime_websocket::methods_v1::session_update_session as v1_session_update_session;
|
||||
use crate::endpoint::realtime_websocket::methods_v1::websocket_intent as v1_websocket_intent;
|
||||
use crate::endpoint::realtime_websocket::methods_v2::conversation_function_call_output_message as v2_conversation_function_call_output_message;
|
||||
use crate::endpoint::realtime_websocket::methods_v2::conversation_item_create_message as v2_conversation_item_create_message;
|
||||
use crate::endpoint::realtime_websocket::methods_v2::session_update_session as v2_session_update_session;
|
||||
use crate::endpoint::realtime_websocket::methods_v2::websocket_intent as v2_websocket_intent;
|
||||
use crate::endpoint::realtime_websocket::protocol::RealtimeContextAppendChannel;
|
||||
use crate::endpoint::realtime_websocket::protocol::RealtimeOutboundMessage;
|
||||
use crate::endpoint::realtime_websocket::protocol::RealtimeOutputModality;
|
||||
use crate::endpoint::realtime_websocket::protocol::RealtimeSessionConfig;
|
||||
use crate::endpoint::realtime_websocket::protocol::RealtimeSessionMode;
|
||||
use crate::endpoint::realtime_websocket::protocol::RealtimeVoice;
|
||||
use crate::endpoint::realtime_websocket::protocol::RealtimeWireAdapter;
|
||||
use akode_protocol::protocol::ConversationTextParams;
|
||||
use akode_protocol::protocol::ConversationTextRole;
|
||||
use serde_json::Result as JsonResult;
|
||||
use serde_json::Value;
|
||||
use serde_json::to_value;
|
||||
|
||||
pub(super) const REALTIME_AUDIO_SAMPLE_RATE: u32 = 24_000;
|
||||
const AGENT_FINAL_MESSAGE_PREFIX: &str = "\"Agent Final Message\":\n\n";
|
||||
|
||||
pub(super) fn normalized_session_mode(
|
||||
wire_adapter: RealtimeWireAdapter,
|
||||
session_mode: RealtimeSessionMode,
|
||||
) -> RealtimeSessionMode {
|
||||
match wire_adapter {
|
||||
RealtimeWireAdapter::V1 | RealtimeWireAdapter::FramelessBidi => {
|
||||
RealtimeSessionMode::Conversational
|
||||
}
|
||||
RealtimeWireAdapter::RealtimeV2 => session_mode,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn conversation_item_create_message(
|
||||
wire_adapter: RealtimeWireAdapter,
|
||||
text: String,
|
||||
role: ConversationTextRole,
|
||||
context_append_channel: Option<RealtimeContextAppendChannel>,
|
||||
) -> RealtimeOutboundMessage {
|
||||
match wire_adapter {
|
||||
RealtimeWireAdapter::V1 => v1_conversation_item_create_message(text, role),
|
||||
RealtimeWireAdapter::FramelessBidi => {
|
||||
frameless_session_context_append_message(text, context_append_channel)
|
||||
}
|
||||
RealtimeWireAdapter::RealtimeV2 => v2_conversation_item_create_message(text, role),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn conversation_handoff_append_message(
|
||||
wire_adapter: RealtimeWireAdapter,
|
||||
handoff_id: String,
|
||||
output_text: String,
|
||||
context_append_channel: Option<RealtimeContextAppendChannel>,
|
||||
) -> RealtimeOutboundMessage {
|
||||
match wire_adapter {
|
||||
RealtimeWireAdapter::V1 => v1_conversation_handoff_append_message(handoff_id, output_text),
|
||||
RealtimeWireAdapter::FramelessBidi => frameless_delegation_context_append_message(
|
||||
handoff_id,
|
||||
output_text,
|
||||
context_append_channel,
|
||||
),
|
||||
RealtimeWireAdapter::RealtimeV2 => {
|
||||
unreachable!("realtime v2 does not send conversation handoff output")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn standalone_handoff_message(
|
||||
wire_adapter: RealtimeWireAdapter,
|
||||
handoff_id: String,
|
||||
output_text: String,
|
||||
context_append_channel: Option<RealtimeContextAppendChannel>,
|
||||
) -> RealtimeOutboundMessage {
|
||||
match wire_adapter {
|
||||
RealtimeWireAdapter::V1 => v1_conversation_handoff_append_message(handoff_id, output_text),
|
||||
RealtimeWireAdapter::FramelessBidi => {
|
||||
frameless_session_context_append_message(output_text, context_append_channel)
|
||||
}
|
||||
RealtimeWireAdapter::RealtimeV2 => {
|
||||
unreachable!("realtime v2 does not send standalone handoff output")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn conversation_function_call_output_message(
|
||||
wire_adapter: RealtimeWireAdapter,
|
||||
call_id: String,
|
||||
output_text: String,
|
||||
context_append_channel: Option<RealtimeContextAppendChannel>,
|
||||
) -> RealtimeOutboundMessage {
|
||||
match wire_adapter {
|
||||
RealtimeWireAdapter::V1 => v1_conversation_handoff_append_message(
|
||||
call_id,
|
||||
format!("{AGENT_FINAL_MESSAGE_PREFIX}{output_text}"),
|
||||
),
|
||||
RealtimeWireAdapter::FramelessBidi => frameless_delegation_context_append_message(
|
||||
call_id,
|
||||
output_text,
|
||||
context_append_channel,
|
||||
),
|
||||
RealtimeWireAdapter::RealtimeV2 => {
|
||||
v2_conversation_function_call_output_message(call_id, output_text)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn session_update_message(
|
||||
wire_adapter: RealtimeWireAdapter,
|
||||
instructions: String,
|
||||
initial_items: Vec<ConversationTextParams>,
|
||||
session_mode: RealtimeSessionMode,
|
||||
output_modality: RealtimeOutputModality,
|
||||
voice: RealtimeVoice,
|
||||
delegation_ack_filler: Option<bool>,
|
||||
) -> RealtimeOutboundMessage {
|
||||
let session_mode = normalized_session_mode(wire_adapter, session_mode);
|
||||
match wire_adapter {
|
||||
RealtimeWireAdapter::V1 => RealtimeOutboundMessage::SessionUpdate {
|
||||
session: v1_session_update_session(instructions, voice),
|
||||
},
|
||||
RealtimeWireAdapter::FramelessBidi => frameless_session_update_message(
|
||||
instructions,
|
||||
initial_items,
|
||||
voice,
|
||||
delegation_ack_filler,
|
||||
),
|
||||
RealtimeWireAdapter::RealtimeV2 => RealtimeOutboundMessage::SessionUpdate {
|
||||
session: v2_session_update_session(instructions, session_mode, output_modality, voice),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn session_update_session_json(config: RealtimeSessionConfig) -> JsonResult<Value> {
|
||||
match config.event_parser {
|
||||
RealtimeWireAdapter::V1 | RealtimeWireAdapter::RealtimeV2 => {
|
||||
let mut session = match config.event_parser {
|
||||
RealtimeWireAdapter::V1 => {
|
||||
v1_session_update_session(config.instructions, config.voice)
|
||||
}
|
||||
RealtimeWireAdapter::RealtimeV2 => v2_session_update_session(
|
||||
config.instructions,
|
||||
config.session_mode,
|
||||
config.output_modality,
|
||||
config.voice,
|
||||
),
|
||||
RealtimeWireAdapter::FramelessBidi => unreachable!(),
|
||||
};
|
||||
session.id = config.session_id;
|
||||
session.model = config.model;
|
||||
to_value(session)
|
||||
}
|
||||
RealtimeWireAdapter::FramelessBidi => Ok(frameless_session_json(
|
||||
config.model,
|
||||
config.instructions,
|
||||
config.initial_items,
|
||||
config.voice,
|
||||
config.delegation_ack_filler,
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn websocket_intent(wire_adapter: RealtimeWireAdapter) -> Option<&'static str> {
|
||||
match wire_adapter {
|
||||
RealtimeWireAdapter::V1 => v1_websocket_intent(),
|
||||
RealtimeWireAdapter::FramelessBidi => None,
|
||||
RealtimeWireAdapter::RealtimeV2 => v2_websocket_intent(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "methods_common_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,150 @@
|
||||
use super::conversation_function_call_output_message;
|
||||
use super::conversation_handoff_append_message;
|
||||
use super::session_update_message;
|
||||
use super::standalone_handoff_message;
|
||||
use crate::endpoint::realtime_websocket::protocol::RealtimeContextAppendChannel;
|
||||
use crate::endpoint::realtime_websocket::protocol::RealtimeOutputModality;
|
||||
use crate::endpoint::realtime_websocket::protocol::RealtimeSessionMode;
|
||||
use crate::endpoint::realtime_websocket::protocol::RealtimeVoice;
|
||||
use crate::endpoint::realtime_websocket::protocol::RealtimeWireAdapter;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use serde_json::to_value;
|
||||
|
||||
#[test]
|
||||
fn frameless_session_update_encodes_explicit_delegation_ack_filler() {
|
||||
for delegation_ack_filler in [false, true] {
|
||||
let message = session_update_message(
|
||||
RealtimeWireAdapter::FramelessBidi,
|
||||
"instructions".to_string(),
|
||||
Vec::new(),
|
||||
RealtimeSessionMode::Conversational,
|
||||
RealtimeOutputModality::Audio,
|
||||
RealtimeVoice::Marin,
|
||||
Some(delegation_ack_filler),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
to_value(message).expect("frameless session update should serialize"),
|
||||
json!({
|
||||
"type": "session.update",
|
||||
"session": {
|
||||
"instructions": "instructions",
|
||||
"audio": {
|
||||
"output": {
|
||||
"voice": "marin",
|
||||
},
|
||||
},
|
||||
"delegation": {
|
||||
"type": "client",
|
||||
"ack_filler": delegation_ack_filler,
|
||||
},
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_append_channel_only_encodes_for_frameless_handoff_output() {
|
||||
let legacy = conversation_handoff_append_message(
|
||||
RealtimeWireAdapter::V1,
|
||||
"handoff-123".to_string(),
|
||||
"The result".to_string(),
|
||||
Some(RealtimeContextAppendChannel::Commentary),
|
||||
);
|
||||
let frameless = conversation_handoff_append_message(
|
||||
RealtimeWireAdapter::FramelessBidi,
|
||||
"handoff-123".to_string(),
|
||||
"The result".to_string(),
|
||||
Some(RealtimeContextAppendChannel::Commentary),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
to_value(legacy).expect("legacy handoff should serialize"),
|
||||
json!({
|
||||
"type": "conversation.handoff.append",
|
||||
"handoff_id": "handoff-123",
|
||||
"output_text": "The result",
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
to_value(frameless).expect("frameless handoff should serialize"),
|
||||
json!({
|
||||
"type": "delegation.context.append",
|
||||
"delegation_item_id": "handoff-123",
|
||||
"channel": "commentary",
|
||||
"content": [{"type": "input_text", "text": "The result"}],
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn standalone_handoff_uses_session_context_for_frameless() {
|
||||
let legacy = standalone_handoff_message(
|
||||
RealtimeWireAdapter::V1,
|
||||
"codex".to_string(),
|
||||
"Speak this".to_string(),
|
||||
Some(RealtimeContextAppendChannel::Speakable),
|
||||
);
|
||||
let frameless = standalone_handoff_message(
|
||||
RealtimeWireAdapter::FramelessBidi,
|
||||
"codex".to_string(),
|
||||
"Speak this".to_string(),
|
||||
Some(RealtimeContextAppendChannel::Speakable),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
to_value(legacy).expect("legacy standalone handoff should serialize"),
|
||||
json!({
|
||||
"type": "conversation.handoff.append",
|
||||
"handoff_id": "codex",
|
||||
"output_text": "Speak this",
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
to_value(frameless).expect("frameless standalone handoff should serialize"),
|
||||
json!({
|
||||
"type": "session.context.append",
|
||||
"channel": "speakable",
|
||||
"content": [{"type": "input_text", "text": "Speak this"}],
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completed_handoff_only_prefixes_v1_payload_text() {
|
||||
for wire_adapter in [RealtimeWireAdapter::V1, RealtimeWireAdapter::FramelessBidi] {
|
||||
let encoded = to_value(conversation_function_call_output_message(
|
||||
wire_adapter,
|
||||
"handoff-123".to_string(),
|
||||
"Done".to_string(),
|
||||
Some(RealtimeContextAppendChannel::Speakable),
|
||||
))
|
||||
.expect("handoff output should serialize");
|
||||
let text = match wire_adapter {
|
||||
RealtimeWireAdapter::V1 => &encoded["output_text"],
|
||||
RealtimeWireAdapter::FramelessBidi => &encoded["content"][0]["text"],
|
||||
RealtimeWireAdapter::RealtimeV2 => unreachable!(),
|
||||
};
|
||||
assert_eq!(
|
||||
text,
|
||||
&Value::String(match wire_adapter {
|
||||
RealtimeWireAdapter::V1 => "\"Agent Final Message\":\n\nDone".to_string(),
|
||||
RealtimeWireAdapter::FramelessBidi => "Done".to_string(),
|
||||
RealtimeWireAdapter::RealtimeV2 => unreachable!(),
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
encoded.get("channel").cloned(),
|
||||
match wire_adapter {
|
||||
RealtimeWireAdapter::V1 => None,
|
||||
RealtimeWireAdapter::FramelessBidi => {
|
||||
Some(Value::String("speakable".to_string()))
|
||||
}
|
||||
RealtimeWireAdapter::RealtimeV2 => unreachable!(),
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
use crate::endpoint::realtime_websocket::protocol::FramelessContentType;
|
||||
use crate::endpoint::realtime_websocket::protocol::FramelessInputTextContent;
|
||||
use crate::endpoint::realtime_websocket::protocol::RealtimeContextAppendChannel;
|
||||
use crate::endpoint::realtime_websocket::protocol::RealtimeOutboundMessage;
|
||||
use crate::endpoint::realtime_websocket::protocol::RealtimeVoice;
|
||||
use akode_protocol::protocol::ConversationTextParams;
|
||||
use akode_protocol::protocol::ConversationTextRole;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
|
||||
const CONTEXT_APPEND_MAX_BYTES: usize = 500;
|
||||
|
||||
pub(super) fn delegation_context_append_message(
|
||||
delegation_item_id: String,
|
||||
text: String,
|
||||
channel: Option<RealtimeContextAppendChannel>,
|
||||
) -> RealtimeOutboundMessage {
|
||||
RealtimeOutboundMessage::DelegationContextAppend {
|
||||
delegation_item_id,
|
||||
channel,
|
||||
content: input_text_content(text),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn session_context_append_message(
|
||||
text: String,
|
||||
channel: Option<RealtimeContextAppendChannel>,
|
||||
) -> RealtimeOutboundMessage {
|
||||
RealtimeOutboundMessage::SessionContextAppend {
|
||||
channel,
|
||||
content: input_text_content(text),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn session_update_message(
|
||||
instructions: String,
|
||||
initial_items: Vec<ConversationTextParams>,
|
||||
voice: RealtimeVoice,
|
||||
delegation_ack_filler: Option<bool>,
|
||||
) -> RealtimeOutboundMessage {
|
||||
RealtimeOutboundMessage::FramelessSessionUpdate {
|
||||
session: session_json(
|
||||
/*model*/ None,
|
||||
instructions,
|
||||
initial_items,
|
||||
voice,
|
||||
delegation_ack_filler,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn session_json(
|
||||
model: Option<String>,
|
||||
instructions: String,
|
||||
initial_items: Vec<ConversationTextParams>,
|
||||
voice: RealtimeVoice,
|
||||
delegation_ack_filler: Option<bool>,
|
||||
) -> Value {
|
||||
let mut session = json!({
|
||||
"instructions": instructions,
|
||||
"audio": {
|
||||
"output": {
|
||||
"voice": voice,
|
||||
},
|
||||
},
|
||||
"delegation": {
|
||||
"type": "client",
|
||||
},
|
||||
});
|
||||
if let Some(model) = model {
|
||||
session["model"] = Value::String(model);
|
||||
}
|
||||
if let Some(delegation_ack_filler) = delegation_ack_filler {
|
||||
session["delegation"]["ack_filler"] = Value::Bool(delegation_ack_filler);
|
||||
}
|
||||
if !initial_items.is_empty() {
|
||||
session["initial_items"] = Value::Array(
|
||||
initial_items
|
||||
.into_iter()
|
||||
.map(|item| {
|
||||
let content_type = match item.role {
|
||||
ConversationTextRole::User | ConversationTextRole::Developer => {
|
||||
"input_text"
|
||||
}
|
||||
ConversationTextRole::Assistant => "output_text",
|
||||
};
|
||||
json!({
|
||||
"type": "message",
|
||||
"role": item.role,
|
||||
"content": [{
|
||||
"type": content_type,
|
||||
"text": item.text,
|
||||
}],
|
||||
})
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
session
|
||||
}
|
||||
|
||||
fn input_text_content(text: String) -> Vec<FramelessInputTextContent> {
|
||||
vec![FramelessInputTextContent {
|
||||
r#type: FramelessContentType::InputText,
|
||||
text,
|
||||
}]
|
||||
}
|
||||
|
||||
pub(super) fn context_append_chunks(text: &str) -> Vec<String> {
|
||||
if text.len() <= CONTEXT_APPEND_MAX_BYTES {
|
||||
return vec![text.to_string()];
|
||||
}
|
||||
|
||||
let mut chunks = Vec::new();
|
||||
let mut start = 0;
|
||||
while start < text.len() {
|
||||
let mut end = (start + CONTEXT_APPEND_MAX_BYTES).min(text.len());
|
||||
while end > start && !text.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
chunks.push(text[start..end].to_string());
|
||||
start = end;
|
||||
}
|
||||
chunks
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "methods_frameless_bidi_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,102 @@
|
||||
use super::CONTEXT_APPEND_MAX_BYTES;
|
||||
use super::context_append_chunks;
|
||||
use super::session_json;
|
||||
use crate::endpoint::realtime_websocket::protocol::RealtimeVoice;
|
||||
use akode_protocol::protocol::ConversationTextParams;
|
||||
use akode_protocol::protocol::ConversationTextRole;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn context_append_chunks_preserve_text_within_wire_limit() {
|
||||
for text in ["a".repeat(1_201), "🙂".repeat(200)] {
|
||||
let chunks = context_append_chunks(&text);
|
||||
assert_eq!(chunks.concat(), text);
|
||||
assert!(
|
||||
chunks
|
||||
.iter()
|
||||
.all(|chunk| chunk.len() <= CONTEXT_APPEND_MAX_BYTES)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_json_omits_initial_items_when_empty() {
|
||||
let session = session_json(
|
||||
Some("gpt-live".to_string()),
|
||||
"instructions".to_string(),
|
||||
Vec::new(),
|
||||
RealtimeVoice::Marin,
|
||||
/*delegation_ack_filler*/ None,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
session,
|
||||
json!({
|
||||
"model": "gpt-live",
|
||||
"instructions": "instructions",
|
||||
"audio": {
|
||||
"output": {
|
||||
"voice": "marin",
|
||||
},
|
||||
},
|
||||
"delegation": {
|
||||
"type": "client",
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_json_encodes_role_bearing_initial_items() {
|
||||
let session = session_json(
|
||||
Some("gpt-live".to_string()),
|
||||
"instructions".to_string(),
|
||||
vec![
|
||||
ConversationTextParams {
|
||||
text: "Remember this.".to_string(),
|
||||
role: ConversationTextRole::Developer,
|
||||
},
|
||||
ConversationTextParams {
|
||||
text: "What do you remember?".to_string(),
|
||||
role: ConversationTextRole::User,
|
||||
},
|
||||
ConversationTextParams {
|
||||
text: "I remember.".to_string(),
|
||||
role: ConversationTextRole::Assistant,
|
||||
},
|
||||
],
|
||||
RealtimeVoice::Marin,
|
||||
/*delegation_ack_filler*/ None,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
session["initial_items"],
|
||||
json!([
|
||||
{
|
||||
"type": "message",
|
||||
"role": "developer",
|
||||
"content": [{
|
||||
"type": "input_text",
|
||||
"text": "Remember this.",
|
||||
}],
|
||||
},
|
||||
{
|
||||
"type": "message",
|
||||
"role": "user",
|
||||
"content": [{
|
||||
"type": "input_text",
|
||||
"text": "What do you remember?",
|
||||
}],
|
||||
},
|
||||
{
|
||||
"type": "message",
|
||||
"role": "assistant",
|
||||
"content": [{
|
||||
"type": "output_text",
|
||||
"text": "I remember.",
|
||||
}],
|
||||
},
|
||||
])
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
use crate::endpoint::realtime_websocket::methods_common::REALTIME_AUDIO_SAMPLE_RATE;
|
||||
use crate::endpoint::realtime_websocket::protocol::AudioFormatType;
|
||||
use crate::endpoint::realtime_websocket::protocol::ConversationContentType;
|
||||
use crate::endpoint::realtime_websocket::protocol::ConversationItemContent;
|
||||
use crate::endpoint::realtime_websocket::protocol::ConversationItemPayload;
|
||||
use crate::endpoint::realtime_websocket::protocol::ConversationItemType;
|
||||
use crate::endpoint::realtime_websocket::protocol::ConversationMessageItem;
|
||||
use crate::endpoint::realtime_websocket::protocol::RealtimeOutboundMessage;
|
||||
use crate::endpoint::realtime_websocket::protocol::RealtimeVoice;
|
||||
use crate::endpoint::realtime_websocket::protocol::SessionAudio;
|
||||
use crate::endpoint::realtime_websocket::protocol::SessionAudioFormat;
|
||||
use crate::endpoint::realtime_websocket::protocol::SessionAudioInput;
|
||||
use crate::endpoint::realtime_websocket::protocol::SessionAudioOutput;
|
||||
use crate::endpoint::realtime_websocket::protocol::SessionType;
|
||||
use crate::endpoint::realtime_websocket::protocol::SessionUpdateSession;
|
||||
use akode_protocol::protocol::ConversationTextRole;
|
||||
|
||||
pub(super) fn conversation_item_create_message(
|
||||
text: String,
|
||||
role: ConversationTextRole,
|
||||
) -> RealtimeOutboundMessage {
|
||||
let content_type = match role {
|
||||
ConversationTextRole::Assistant => ConversationContentType::OutputText,
|
||||
ConversationTextRole::User | ConversationTextRole::Developer => {
|
||||
ConversationContentType::InputText
|
||||
}
|
||||
};
|
||||
|
||||
RealtimeOutboundMessage::ConversationItemCreate {
|
||||
item: ConversationItemPayload::Message(ConversationMessageItem {
|
||||
r#type: ConversationItemType::Message,
|
||||
role,
|
||||
content: vec![ConversationItemContent {
|
||||
r#type: content_type,
|
||||
text,
|
||||
}],
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn conversation_handoff_append_message(
|
||||
handoff_id: String,
|
||||
output_text: String,
|
||||
) -> RealtimeOutboundMessage {
|
||||
RealtimeOutboundMessage::ConversationHandoffAppend {
|
||||
handoff_id,
|
||||
output_text,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn session_update_session(
|
||||
instructions: String,
|
||||
voice: RealtimeVoice,
|
||||
) -> SessionUpdateSession {
|
||||
SessionUpdateSession {
|
||||
id: None,
|
||||
r#type: SessionType::Quicksilver,
|
||||
model: None,
|
||||
instructions: Some(instructions),
|
||||
output_modalities: None,
|
||||
audio: SessionAudio {
|
||||
input: SessionAudioInput {
|
||||
format: SessionAudioFormat {
|
||||
r#type: AudioFormatType::AudioPcm,
|
||||
rate: REALTIME_AUDIO_SAMPLE_RATE,
|
||||
},
|
||||
noise_reduction: None,
|
||||
transcription: None,
|
||||
turn_detection: None,
|
||||
},
|
||||
output: Some(SessionAudioOutput {
|
||||
format: None,
|
||||
voice,
|
||||
}),
|
||||
},
|
||||
tools: None,
|
||||
tool_choice: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn websocket_intent() -> Option<&'static str> {
|
||||
Some("quicksilver")
|
||||
}
|
||||
180
akode-rs/akode-api/src/endpoint/realtime_websocket/methods_v2.rs
Normal file
180
akode-rs/akode-api/src/endpoint/realtime_websocket/methods_v2.rs
Normal file
@@ -0,0 +1,180 @@
|
||||
use crate::endpoint::realtime_websocket::methods_common::REALTIME_AUDIO_SAMPLE_RATE;
|
||||
use crate::endpoint::realtime_websocket::protocol::AudioFormatType;
|
||||
use crate::endpoint::realtime_websocket::protocol::ConversationContentType;
|
||||
use crate::endpoint::realtime_websocket::protocol::ConversationFunctionCallOutputItem;
|
||||
use crate::endpoint::realtime_websocket::protocol::ConversationItemContent;
|
||||
use crate::endpoint::realtime_websocket::protocol::ConversationItemPayload;
|
||||
use crate::endpoint::realtime_websocket::protocol::ConversationItemType;
|
||||
use crate::endpoint::realtime_websocket::protocol::ConversationMessageItem;
|
||||
use crate::endpoint::realtime_websocket::protocol::NoiseReductionType;
|
||||
use crate::endpoint::realtime_websocket::protocol::RealtimeOutboundMessage;
|
||||
use crate::endpoint::realtime_websocket::protocol::RealtimeOutputModality;
|
||||
use crate::endpoint::realtime_websocket::protocol::RealtimeSessionMode;
|
||||
use crate::endpoint::realtime_websocket::protocol::RealtimeVoice;
|
||||
use crate::endpoint::realtime_websocket::protocol::SessionAudio;
|
||||
use crate::endpoint::realtime_websocket::protocol::SessionAudioFormat;
|
||||
use crate::endpoint::realtime_websocket::protocol::SessionAudioInput;
|
||||
use crate::endpoint::realtime_websocket::protocol::SessionAudioOutput;
|
||||
use crate::endpoint::realtime_websocket::protocol::SessionAudioOutputFormat;
|
||||
use crate::endpoint::realtime_websocket::protocol::SessionFunctionTool;
|
||||
use crate::endpoint::realtime_websocket::protocol::SessionInputAudioTranscription;
|
||||
use crate::endpoint::realtime_websocket::protocol::SessionNoiseReduction;
|
||||
use crate::endpoint::realtime_websocket::protocol::SessionToolType;
|
||||
use crate::endpoint::realtime_websocket::protocol::SessionTurnDetection;
|
||||
use crate::endpoint::realtime_websocket::protocol::SessionType;
|
||||
use crate::endpoint::realtime_websocket::protocol::SessionUpdateSession;
|
||||
use crate::endpoint::realtime_websocket::protocol::TurnDetectionType;
|
||||
use akode_protocol::protocol::ConversationTextRole;
|
||||
use serde_json::json;
|
||||
|
||||
const REALTIME_V2_OUTPUT_MODALITY_AUDIO: &str = "audio";
|
||||
const REALTIME_V2_OUTPUT_MODALITY_TEXT: &str = "text";
|
||||
const REALTIME_V2_TOOL_CHOICE: &str = "auto";
|
||||
const REALTIME_V2_BACKGROUND_AGENT_TOOL_NAME: &str = "background_agent";
|
||||
const REALTIME_V2_BACKGROUND_AGENT_TOOL_DESCRIPTION: &str = "Send a user request to the background agent. Use this as the default action. Do not rephrase the user's ask or rewrite it in your own words; pass along the user's own words. If the background agent is idle, this starts a new task and returns the final result to the user. If the background agent is already working on a task, this sends the request as guidance to steer that previous task. If the user asks to do something next, later, after this, or once current work finishes, call this tool so the work is actually queued instead of merely promising to do it later.";
|
||||
const REALTIME_V2_SILENCE_TOOL_NAME: &str = "remain_silent";
|
||||
const REALTIME_V2_SILENCE_TOOL_DESCRIPTION: &str = "Call this when the best response is to say nothing. Use it instead of speaking after hidden system/control messages, after background agent updates in silent modes, or whenever acknowledging aloud would be distracting. This tool has no user-visible effect.";
|
||||
const REALTIME_V2_INPUT_TRANSCRIPTION_MODEL: &str = "gpt-4o-mini-transcribe";
|
||||
|
||||
pub(super) fn conversation_item_create_message(
|
||||
text: String,
|
||||
role: ConversationTextRole,
|
||||
) -> RealtimeOutboundMessage {
|
||||
let content_type = match role {
|
||||
ConversationTextRole::Assistant => ConversationContentType::OutputText,
|
||||
ConversationTextRole::User | ConversationTextRole::Developer => {
|
||||
ConversationContentType::InputText
|
||||
}
|
||||
};
|
||||
|
||||
RealtimeOutboundMessage::ConversationItemCreate {
|
||||
item: ConversationItemPayload::Message(ConversationMessageItem {
|
||||
r#type: ConversationItemType::Message,
|
||||
role,
|
||||
content: vec![ConversationItemContent {
|
||||
r#type: content_type,
|
||||
text,
|
||||
}],
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn conversation_function_call_output_message(
|
||||
call_id: String,
|
||||
output_text: String,
|
||||
) -> RealtimeOutboundMessage {
|
||||
RealtimeOutboundMessage::ConversationItemCreate {
|
||||
item: ConversationItemPayload::FunctionCallOutput(ConversationFunctionCallOutputItem {
|
||||
r#type: ConversationItemType::FunctionCallOutput,
|
||||
call_id,
|
||||
output: output_text,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn session_update_session(
|
||||
instructions: String,
|
||||
session_mode: RealtimeSessionMode,
|
||||
output_modality: RealtimeOutputModality,
|
||||
voice: RealtimeVoice,
|
||||
) -> SessionUpdateSession {
|
||||
match session_mode {
|
||||
RealtimeSessionMode::Conversational => SessionUpdateSession {
|
||||
id: None,
|
||||
r#type: SessionType::Realtime,
|
||||
model: None,
|
||||
instructions: Some(instructions),
|
||||
output_modalities: Some(vec![output_modality_value(output_modality).to_string()]),
|
||||
audio: SessionAudio {
|
||||
input: SessionAudioInput {
|
||||
format: SessionAudioFormat {
|
||||
r#type: AudioFormatType::AudioPcm,
|
||||
rate: REALTIME_AUDIO_SAMPLE_RATE,
|
||||
},
|
||||
noise_reduction: Some(SessionNoiseReduction {
|
||||
r#type: NoiseReductionType::NearField,
|
||||
}),
|
||||
transcription: Some(SessionInputAudioTranscription {
|
||||
model: REALTIME_V2_INPUT_TRANSCRIPTION_MODEL.to_string(),
|
||||
}),
|
||||
turn_detection: Some(SessionTurnDetection {
|
||||
r#type: TurnDetectionType::ServerVad,
|
||||
interrupt_response: true,
|
||||
create_response: true,
|
||||
silence_duration_ms: 500,
|
||||
}),
|
||||
},
|
||||
output: Some(SessionAudioOutput {
|
||||
format: Some(SessionAudioOutputFormat {
|
||||
r#type: AudioFormatType::AudioPcm,
|
||||
rate: REALTIME_AUDIO_SAMPLE_RATE,
|
||||
}),
|
||||
voice,
|
||||
}),
|
||||
},
|
||||
tools: Some(vec![
|
||||
SessionFunctionTool {
|
||||
r#type: SessionToolType::Function,
|
||||
name: REALTIME_V2_BACKGROUND_AGENT_TOOL_NAME.to_string(),
|
||||
description: REALTIME_V2_BACKGROUND_AGENT_TOOL_DESCRIPTION.to_string(),
|
||||
parameters: json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"prompt": {
|
||||
"type": "string",
|
||||
"description": "The user request to delegate to the background agent."
|
||||
}
|
||||
},
|
||||
"required": ["prompt"],
|
||||
"additionalProperties": false
|
||||
}),
|
||||
},
|
||||
SessionFunctionTool {
|
||||
r#type: SessionToolType::Function,
|
||||
name: REALTIME_V2_SILENCE_TOOL_NAME.to_string(),
|
||||
description: REALTIME_V2_SILENCE_TOOL_DESCRIPTION.to_string(),
|
||||
parameters: json!({
|
||||
"type": "object",
|
||||
"properties": {},
|
||||
"additionalProperties": false
|
||||
}),
|
||||
},
|
||||
]),
|
||||
tool_choice: Some(REALTIME_V2_TOOL_CHOICE.to_string()),
|
||||
},
|
||||
RealtimeSessionMode::Transcription => SessionUpdateSession {
|
||||
id: None,
|
||||
r#type: SessionType::Transcription,
|
||||
model: None,
|
||||
instructions: None,
|
||||
output_modalities: None,
|
||||
audio: SessionAudio {
|
||||
input: SessionAudioInput {
|
||||
format: SessionAudioFormat {
|
||||
r#type: AudioFormatType::AudioPcm,
|
||||
rate: REALTIME_AUDIO_SAMPLE_RATE,
|
||||
},
|
||||
noise_reduction: None,
|
||||
transcription: Some(SessionInputAudioTranscription {
|
||||
model: REALTIME_V2_INPUT_TRANSCRIPTION_MODEL.to_string(),
|
||||
}),
|
||||
turn_detection: None,
|
||||
},
|
||||
output: None,
|
||||
},
|
||||
tools: None,
|
||||
tool_choice: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn output_modality_value(output_modality: RealtimeOutputModality) -> &'static str {
|
||||
match output_modality {
|
||||
RealtimeOutputModality::Text => REALTIME_V2_OUTPUT_MODALITY_TEXT,
|
||||
RealtimeOutputModality::Audio => REALTIME_V2_OUTPUT_MODALITY_AUDIO,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn websocket_intent() -> Option<&'static str> {
|
||||
None
|
||||
}
|
||||
22
akode-rs/akode-api/src/endpoint/realtime_websocket/mod.rs
Normal file
22
akode-rs/akode-api/src/endpoint/realtime_websocket/mod.rs
Normal file
@@ -0,0 +1,22 @@
|
||||
pub(crate) mod methods;
|
||||
mod methods_common;
|
||||
mod methods_frameless_bidi;
|
||||
mod methods_v1;
|
||||
mod methods_v2;
|
||||
pub(crate) mod protocol;
|
||||
mod protocol_common;
|
||||
mod protocol_frameless_bidi;
|
||||
mod protocol_v1;
|
||||
mod protocol_v2;
|
||||
|
||||
pub use methods::RealtimeTranscriptState;
|
||||
pub use methods::RealtimeWebsocketClient;
|
||||
pub use methods::RealtimeWebsocketConnection;
|
||||
pub use methods::RealtimeWebsocketEvents;
|
||||
pub use methods::RealtimeWebsocketWriter;
|
||||
pub use methods_common::session_update_session_json;
|
||||
pub use protocol::RealtimeContextAppendChannel;
|
||||
pub use protocol::RealtimeEventParser;
|
||||
pub use protocol::RealtimeOutputModality;
|
||||
pub use protocol::RealtimeSessionConfig;
|
||||
pub use protocol::RealtimeSessionMode;
|
||||
272
akode-rs/akode-api/src/endpoint/realtime_websocket/protocol.rs
Normal file
272
akode-rs/akode-api/src/endpoint/realtime_websocket/protocol.rs
Normal file
@@ -0,0 +1,272 @@
|
||||
use crate::endpoint::realtime_websocket::protocol_frameless_bidi::parse_frameless_bidi_event;
|
||||
use crate::endpoint::realtime_websocket::protocol_v1::parse_realtime_event_v1;
|
||||
use crate::endpoint::realtime_websocket::protocol_v2::parse_realtime_event_v2;
|
||||
use akode_protocol::protocol::ConversationTextParams;
|
||||
use akode_protocol::protocol::ConversationTextRole;
|
||||
pub use akode_protocol::protocol::RealtimeAudioFrame;
|
||||
pub use akode_protocol::protocol::RealtimeEvent;
|
||||
pub use akode_protocol::protocol::RealtimeOutputModality;
|
||||
pub use akode_protocol::protocol::RealtimeTranscriptEntry;
|
||||
pub use akode_protocol::protocol::RealtimeVoice;
|
||||
use serde::Serialize;
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RealtimeEventParser {
|
||||
V1,
|
||||
FramelessBidi,
|
||||
RealtimeV2,
|
||||
}
|
||||
|
||||
pub type RealtimeWireAdapter = RealtimeEventParser;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RealtimeSessionMode {
|
||||
Conversational,
|
||||
Transcription,
|
||||
}
|
||||
|
||||
/// Selects the semantic stream used for Frameless Bidi context appends.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum RealtimeContextAppendChannel {
|
||||
Speakable,
|
||||
Commentary,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RealtimeSessionConfig {
|
||||
pub instructions: String,
|
||||
pub initial_items: Vec<ConversationTextParams>,
|
||||
pub delegation_ack_filler: Option<bool>,
|
||||
pub model: Option<String>,
|
||||
pub session_id: Option<String>,
|
||||
pub event_parser: RealtimeEventParser,
|
||||
pub session_mode: RealtimeSessionMode,
|
||||
pub output_modality: RealtimeOutputModality,
|
||||
pub voice: RealtimeVoice,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(tag = "type")]
|
||||
pub(super) enum RealtimeOutboundMessage {
|
||||
#[serde(rename = "input_audio_buffer.append")]
|
||||
InputAudioBufferAppend { audio: String },
|
||||
#[serde(rename = "conversation.handoff.append")]
|
||||
ConversationHandoffAppend {
|
||||
handoff_id: String,
|
||||
output_text: String,
|
||||
},
|
||||
#[serde(rename = "input_audio.append")]
|
||||
InputAudioAppend { audio: String },
|
||||
#[serde(rename = "delegation.context.append")]
|
||||
DelegationContextAppend {
|
||||
delegation_item_id: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
channel: Option<RealtimeContextAppendChannel>,
|
||||
content: Vec<FramelessInputTextContent>,
|
||||
},
|
||||
#[serde(rename = "session.context.append")]
|
||||
SessionContextAppend {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
channel: Option<RealtimeContextAppendChannel>,
|
||||
content: Vec<FramelessInputTextContent>,
|
||||
},
|
||||
#[serde(rename = "session.close")]
|
||||
SessionClose,
|
||||
#[serde(rename = "response.create")]
|
||||
ResponseCreate,
|
||||
#[serde(rename = "session.update")]
|
||||
SessionUpdate { session: SessionUpdateSession },
|
||||
#[serde(rename = "session.update")]
|
||||
FramelessSessionUpdate { session: Value },
|
||||
#[serde(rename = "conversation.item.create")]
|
||||
ConversationItemCreate { item: ConversationItemPayload },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub(super) struct FramelessInputTextContent {
|
||||
#[serde(rename = "type")]
|
||||
pub(super) r#type: FramelessContentType,
|
||||
pub(super) text: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub(super) enum FramelessContentType {
|
||||
InputText,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub(super) struct SessionUpdateSession {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub(super) id: Option<String>,
|
||||
#[serde(rename = "type")]
|
||||
pub(super) r#type: SessionType,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub(super) model: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub(super) instructions: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub(super) output_modalities: Option<Vec<String>>,
|
||||
pub(super) audio: SessionAudio,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub(super) tools: Option<Vec<SessionFunctionTool>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub(super) tool_choice: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub(super) enum SessionType {
|
||||
Quicksilver,
|
||||
Realtime,
|
||||
Transcription,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub(super) struct SessionAudio {
|
||||
pub(super) input: SessionAudioInput,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub(super) output: Option<SessionAudioOutput>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub(super) struct SessionAudioInput {
|
||||
pub(super) format: SessionAudioFormat,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub(super) noise_reduction: Option<SessionNoiseReduction>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub(super) transcription: Option<SessionInputAudioTranscription>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub(super) turn_detection: Option<SessionTurnDetection>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub(super) struct SessionInputAudioTranscription {
|
||||
pub(super) model: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub(super) struct SessionAudioFormat {
|
||||
#[serde(rename = "type")]
|
||||
pub(super) r#type: AudioFormatType,
|
||||
pub(super) rate: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize)]
|
||||
pub(super) enum AudioFormatType {
|
||||
#[serde(rename = "audio/pcm")]
|
||||
AudioPcm,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub(super) struct SessionAudioOutput {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub(super) format: Option<SessionAudioOutputFormat>,
|
||||
pub(super) voice: RealtimeVoice,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub(super) struct SessionNoiseReduction {
|
||||
#[serde(rename = "type")]
|
||||
pub(super) r#type: NoiseReductionType,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub(super) enum NoiseReductionType {
|
||||
NearField,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub(super) struct SessionTurnDetection {
|
||||
#[serde(rename = "type")]
|
||||
pub(super) r#type: TurnDetectionType,
|
||||
pub(super) interrupt_response: bool,
|
||||
pub(super) create_response: bool,
|
||||
pub(super) silence_duration_ms: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub(super) enum TurnDetectionType {
|
||||
ServerVad,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub(super) struct SessionAudioOutputFormat {
|
||||
#[serde(rename = "type")]
|
||||
pub(super) r#type: AudioFormatType,
|
||||
pub(super) rate: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub(super) struct ConversationMessageItem {
|
||||
#[serde(rename = "type")]
|
||||
pub(super) r#type: ConversationItemType,
|
||||
pub(super) role: ConversationTextRole,
|
||||
pub(super) content: Vec<ConversationItemContent>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub(super) enum ConversationItemType {
|
||||
Message,
|
||||
FunctionCallOutput,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(untagged)]
|
||||
pub(super) enum ConversationItemPayload {
|
||||
Message(ConversationMessageItem),
|
||||
FunctionCallOutput(ConversationFunctionCallOutputItem),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub(super) struct ConversationFunctionCallOutputItem {
|
||||
#[serde(rename = "type")]
|
||||
pub(super) r#type: ConversationItemType,
|
||||
pub(super) call_id: String,
|
||||
pub(super) output: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub(super) struct ConversationItemContent {
|
||||
#[serde(rename = "type")]
|
||||
pub(super) r#type: ConversationContentType,
|
||||
pub(super) text: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub(super) enum ConversationContentType {
|
||||
InputText,
|
||||
OutputText,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub(super) struct SessionFunctionTool {
|
||||
#[serde(rename = "type")]
|
||||
pub(super) r#type: SessionToolType,
|
||||
pub(super) name: String,
|
||||
pub(super) description: String,
|
||||
pub(super) parameters: Value,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub(super) enum SessionToolType {
|
||||
Function,
|
||||
}
|
||||
|
||||
pub(super) fn parse_realtime_event(
|
||||
payload: &str,
|
||||
event_parser: RealtimeEventParser,
|
||||
) -> Option<RealtimeEvent> {
|
||||
match event_parser {
|
||||
RealtimeEventParser::V1 => parse_realtime_event_v1(payload),
|
||||
RealtimeEventParser::FramelessBidi => parse_frameless_bidi_event(payload),
|
||||
RealtimeEventParser::RealtimeV2 => parse_realtime_event_v2(payload),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
use akode_protocol::protocol::RealtimeEvent;
|
||||
use akode_protocol::protocol::RealtimeTranscriptDelta;
|
||||
use akode_protocol::protocol::RealtimeTranscriptDone;
|
||||
use serde_json::Value;
|
||||
use tracing::debug;
|
||||
|
||||
pub(super) fn parse_realtime_payload(payload: &str, parser_name: &str) -> Option<(Value, String)> {
|
||||
let parsed: Value = match serde_json::from_str(payload) {
|
||||
Ok(message) => message,
|
||||
Err(err) => {
|
||||
debug!("failed to parse {parser_name} event: {err}, data: {payload}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
let message_type = match parsed.get("type").and_then(Value::as_str) {
|
||||
Some(message_type) => message_type.to_string(),
|
||||
None => {
|
||||
debug!("received {parser_name} event without type field: {payload}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
Some((parsed, message_type))
|
||||
}
|
||||
|
||||
pub(super) fn parse_session_updated_event(parsed: &Value) -> Option<RealtimeEvent> {
|
||||
let session_id = parsed
|
||||
.get("session")
|
||||
.and_then(Value::as_object)
|
||||
.and_then(|session| session.get("id"))
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string)?;
|
||||
let instructions = parsed
|
||||
.get("session")
|
||||
.and_then(Value::as_object)
|
||||
.and_then(|session| session.get("instructions"))
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string);
|
||||
Some(RealtimeEvent::SessionUpdated {
|
||||
realtime_session_id: session_id,
|
||||
instructions,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn parse_transcript_delta_event(
|
||||
parsed: &Value,
|
||||
field: &str,
|
||||
) -> Option<RealtimeTranscriptDelta> {
|
||||
parsed
|
||||
.get(field)
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string)
|
||||
.map(|delta| RealtimeTranscriptDelta { delta })
|
||||
}
|
||||
|
||||
pub(super) fn parse_transcript_done_event(
|
||||
parsed: &Value,
|
||||
field: &str,
|
||||
) -> Option<RealtimeTranscriptDone> {
|
||||
parsed
|
||||
.get(field)
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string)
|
||||
.map(|text| RealtimeTranscriptDone { text })
|
||||
}
|
||||
|
||||
pub(super) fn parse_error_event(parsed: &Value) -> Option<RealtimeEvent> {
|
||||
parsed
|
||||
.get("message")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string)
|
||||
.or_else(|| {
|
||||
parsed
|
||||
.get("error")
|
||||
.and_then(Value::as_object)
|
||||
.and_then(|error| error.get("message"))
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string)
|
||||
})
|
||||
.or_else(|| parsed.get("error").map(ToString::to_string))
|
||||
.map(RealtimeEvent::Error)
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
use crate::endpoint::realtime_websocket::protocol_common::parse_error_event;
|
||||
use crate::endpoint::realtime_websocket::protocol_common::parse_realtime_payload;
|
||||
use crate::endpoint::realtime_websocket::protocol_common::parse_session_updated_event;
|
||||
use akode_protocol::protocol::RealtimeAudioFrame;
|
||||
use akode_protocol::protocol::RealtimeEvent;
|
||||
use akode_protocol::protocol::RealtimeHandoffRequested;
|
||||
use akode_protocol::protocol::RealtimeTranscriptDelta;
|
||||
use akode_protocol::protocol::RealtimeTranscriptDone;
|
||||
use serde_json::Value;
|
||||
use tracing::debug;
|
||||
|
||||
const DEFAULT_AUDIO_SAMPLE_RATE: u32 = 24_000;
|
||||
const DEFAULT_AUDIO_CHANNELS: u16 = 1;
|
||||
|
||||
pub(super) fn parse_frameless_bidi_event(payload: &str) -> Option<RealtimeEvent> {
|
||||
let (parsed, message_type) = parse_realtime_payload(payload, "frameless bidi")?;
|
||||
match message_type.as_str() {
|
||||
"session.started" | "session.updated" => parse_session_updated_event(&parsed),
|
||||
"output_audio.delta" => parse_output_audio_delta(&parsed),
|
||||
"input_transcript.added" => {
|
||||
parse_transcript_item(&parsed).map(RealtimeEvent::InputTranscriptDelta)
|
||||
}
|
||||
"output_transcript.added" => {
|
||||
parse_transcript_item(&parsed).map(RealtimeEvent::OutputTranscriptDelta)
|
||||
}
|
||||
"turn.done" => parse_turn_done(&parsed),
|
||||
"delegation.created" => parse_delegation_created(&parsed),
|
||||
"error" => parse_error_event(&parsed),
|
||||
_ => {
|
||||
debug!(
|
||||
"received unsupported frameless bidi event type: {message_type}, data: {payload}"
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_output_audio_delta(parsed: &Value) -> Option<RealtimeEvent> {
|
||||
Some(RealtimeEvent::AudioOut(RealtimeAudioFrame {
|
||||
data: parsed.get("audio").and_then(Value::as_str)?.to_string(),
|
||||
sample_rate: DEFAULT_AUDIO_SAMPLE_RATE,
|
||||
num_channels: DEFAULT_AUDIO_CHANNELS,
|
||||
samples_per_channel: None,
|
||||
item_id: None,
|
||||
}))
|
||||
}
|
||||
|
||||
fn parse_transcript_item(parsed: &Value) -> Option<RealtimeTranscriptDelta> {
|
||||
parsed
|
||||
.get("item")
|
||||
.and_then(Value::as_object)
|
||||
.and_then(|item| item.get("text"))
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string)
|
||||
.map(|delta| RealtimeTranscriptDelta { delta })
|
||||
}
|
||||
|
||||
fn parse_turn_done(parsed: &Value) -> Option<RealtimeEvent> {
|
||||
let turn = parsed.get("turn")?.as_object()?;
|
||||
let role = turn.get("role").and_then(Value::as_str)?;
|
||||
let text = turn
|
||||
.get("transcript")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string)?;
|
||||
let done = RealtimeTranscriptDone { text };
|
||||
match role {
|
||||
"user" => Some(RealtimeEvent::InputTranscriptDone(done)),
|
||||
"assistant" => Some(RealtimeEvent::OutputTranscriptDone(done)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_delegation_created(parsed: &Value) -> Option<RealtimeEvent> {
|
||||
let item = parsed.get("item")?.as_object()?;
|
||||
if item.get("type").and_then(Value::as_str) != Some("delegation")
|
||||
|| item.get("target").and_then(Value::as_str) != Some("client")
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let item_id = item.get("id").and_then(Value::as_str)?.to_string();
|
||||
let input_transcript = item
|
||||
.get("content")
|
||||
.and_then(Value::as_array)?
|
||||
.iter()
|
||||
.filter(|content| content.get("type").and_then(Value::as_str) == Some("input_text"))
|
||||
.filter_map(|content| content.get("text").and_then(Value::as_str))
|
||||
.collect::<String>();
|
||||
|
||||
Some(RealtimeEvent::HandoffRequested(RealtimeHandoffRequested {
|
||||
handoff_id: item_id.clone(),
|
||||
item_id,
|
||||
input_transcript,
|
||||
active_transcript: Vec::new(),
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "protocol_frameless_bidi_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,64 @@
|
||||
use super::parse_frameless_bidi_event;
|
||||
use crate::endpoint::realtime_websocket::protocol_v1::parse_realtime_event_v1;
|
||||
use akode_protocol::protocol::RealtimeEvent;
|
||||
use akode_protocol::protocol::RealtimeHandoffRequested;
|
||||
|
||||
#[test]
|
||||
fn legacy_and_frameless_delegations_decode_to_the_same_handoff() {
|
||||
let expected = Some(RealtimeEvent::HandoffRequested(RealtimeHandoffRequested {
|
||||
handoff_id: "handoff-123".to_string(),
|
||||
item_id: "handoff-123".to_string(),
|
||||
input_transcript: "check the weather".to_string(),
|
||||
active_transcript: Vec::new(),
|
||||
}));
|
||||
let legacy = r#"{
|
||||
"type": "conversation.handoff.requested",
|
||||
"handoff_id": "handoff-123",
|
||||
"item_id": "handoff-123",
|
||||
"input_transcript": "check the weather"
|
||||
}"#;
|
||||
let frameless = r#"{
|
||||
"type": "delegation.created",
|
||||
"offset_ms": 1000,
|
||||
"item": {
|
||||
"id": "handoff-123",
|
||||
"type": "delegation",
|
||||
"target": "client",
|
||||
"content": [{"type": "input_text", "text": "check the weather"}]
|
||||
}
|
||||
}"#;
|
||||
|
||||
assert_eq!(parse_realtime_event_v1(legacy), expected);
|
||||
assert_eq!(parse_frameless_bidi_event(frameless), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frameless_transcript_and_audio_events_reuse_existing_internal_events() {
|
||||
let input = r#"{
|
||||
"type": "input_transcript.added",
|
||||
"item": {"id": "input-1", "type": "input_transcript", "text": "hello"}
|
||||
}"#;
|
||||
let done = r#"{
|
||||
"type": "turn.done",
|
||||
"turn": {"id": "turn-1", "role": "user", "transcript": "hello"}
|
||||
}"#;
|
||||
let audio = r#"{
|
||||
"type": "output_audio.delta",
|
||||
"audio": "AAE=",
|
||||
"start_ms": 0,
|
||||
"end_ms": 100
|
||||
}"#;
|
||||
|
||||
assert!(matches!(
|
||||
parse_frameless_bidi_event(input),
|
||||
Some(RealtimeEvent::InputTranscriptDelta(_))
|
||||
));
|
||||
assert!(matches!(
|
||||
parse_frameless_bidi_event(done),
|
||||
Some(RealtimeEvent::InputTranscriptDone(_))
|
||||
));
|
||||
assert!(matches!(
|
||||
parse_frameless_bidi_event(audio),
|
||||
Some(RealtimeEvent::AudioOut(_))
|
||||
));
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
use crate::endpoint::realtime_websocket::protocol_common::parse_error_event;
|
||||
use crate::endpoint::realtime_websocket::protocol_common::parse_realtime_payload;
|
||||
use crate::endpoint::realtime_websocket::protocol_common::parse_session_updated_event;
|
||||
use crate::endpoint::realtime_websocket::protocol_common::parse_transcript_delta_event;
|
||||
use crate::endpoint::realtime_websocket::protocol_common::parse_transcript_done_event;
|
||||
use akode_protocol::protocol::RealtimeAudioFrame;
|
||||
use akode_protocol::protocol::RealtimeEvent;
|
||||
use akode_protocol::protocol::RealtimeHandoffRequested;
|
||||
use serde_json::Value;
|
||||
use tracing::debug;
|
||||
|
||||
pub(super) fn parse_realtime_event_v1(payload: &str) -> Option<RealtimeEvent> {
|
||||
let (parsed, message_type) = parse_realtime_payload(payload, "realtime v1")?;
|
||||
match message_type.as_str() {
|
||||
"session.updated" => parse_session_updated_event(&parsed),
|
||||
"conversation.output_audio.delta" => {
|
||||
let data = parsed
|
||||
.get("delta")
|
||||
.and_then(Value::as_str)
|
||||
.or_else(|| parsed.get("data").and_then(Value::as_str))
|
||||
.map(str::to_string)?;
|
||||
let sample_rate = parsed
|
||||
.get("sample_rate")
|
||||
.and_then(Value::as_u64)
|
||||
.and_then(|value| u32::try_from(value).ok())?;
|
||||
let num_channels = parsed
|
||||
.get("channels")
|
||||
.or_else(|| parsed.get("num_channels"))
|
||||
.and_then(Value::as_u64)
|
||||
.and_then(|value| u16::try_from(value).ok())?;
|
||||
Some(RealtimeEvent::AudioOut(RealtimeAudioFrame {
|
||||
data,
|
||||
sample_rate,
|
||||
num_channels,
|
||||
samples_per_channel: parsed
|
||||
.get("samples_per_channel")
|
||||
.and_then(Value::as_u64)
|
||||
.and_then(|value| u32::try_from(value).ok()),
|
||||
item_id: None,
|
||||
}))
|
||||
}
|
||||
"conversation.input_transcript.delta"
|
||||
| "conversation.item.input_audio_transcription.delta" => {
|
||||
parse_transcript_delta_event(&parsed, "delta").map(RealtimeEvent::InputTranscriptDelta)
|
||||
}
|
||||
"conversation.input_transcript.turn_marked"
|
||||
| "conversation.item.input_audio_transcription.completed" => {
|
||||
parse_transcript_done_event(&parsed, "transcript")
|
||||
.map(RealtimeEvent::InputTranscriptDone)
|
||||
}
|
||||
"conversation.output_transcript.delta"
|
||||
| "response.output_text.delta"
|
||||
| "response.output_audio_transcript.delta" => {
|
||||
parse_transcript_delta_event(&parsed, "delta").map(RealtimeEvent::OutputTranscriptDelta)
|
||||
}
|
||||
"response.output_audio_transcript.done" => {
|
||||
parse_transcript_done_event(&parsed, "transcript")
|
||||
.map(RealtimeEvent::OutputTranscriptDone)
|
||||
}
|
||||
"conversation.item.added" => parsed
|
||||
.get("item")
|
||||
.cloned()
|
||||
.map(RealtimeEvent::ConversationItemAdded),
|
||||
"conversation.item.done" => parse_conversation_item_done_event(&parsed),
|
||||
"conversation.handoff.requested" => {
|
||||
let handoff_id = parsed
|
||||
.get("handoff_id")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string)?;
|
||||
let item_id = parsed
|
||||
.get("item_id")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string)?;
|
||||
let input_transcript = parsed
|
||||
.get("input_transcript")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string)?;
|
||||
Some(RealtimeEvent::HandoffRequested(RealtimeHandoffRequested {
|
||||
handoff_id,
|
||||
item_id,
|
||||
input_transcript,
|
||||
active_transcript: Vec::new(),
|
||||
}))
|
||||
}
|
||||
"error" => parse_error_event(&parsed),
|
||||
_ => {
|
||||
debug!("received unsupported realtime v1 event type: {message_type}, data: {payload}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_conversation_item_done_event(parsed: &Value) -> Option<RealtimeEvent> {
|
||||
let item = parsed.get("item")?.as_object()?;
|
||||
item.get("id")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string)
|
||||
.map(|item_id| RealtimeEvent::ConversationItemDone { item_id })
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
use crate::endpoint::realtime_websocket::protocol_common::parse_error_event;
|
||||
use crate::endpoint::realtime_websocket::protocol_common::parse_realtime_payload;
|
||||
use crate::endpoint::realtime_websocket::protocol_common::parse_session_updated_event;
|
||||
use crate::endpoint::realtime_websocket::protocol_common::parse_transcript_delta_event;
|
||||
use crate::endpoint::realtime_websocket::protocol_common::parse_transcript_done_event;
|
||||
use akode_protocol::protocol::RealtimeAudioFrame;
|
||||
use akode_protocol::protocol::RealtimeEvent;
|
||||
use akode_protocol::protocol::RealtimeHandoffRequested;
|
||||
use akode_protocol::protocol::RealtimeInputAudioSpeechStarted;
|
||||
use akode_protocol::protocol::RealtimeNoopRequested;
|
||||
use akode_protocol::protocol::RealtimeResponseCancelled;
|
||||
use akode_protocol::protocol::RealtimeResponseCreated;
|
||||
use akode_protocol::protocol::RealtimeResponseDone;
|
||||
use serde_json::Map as JsonMap;
|
||||
use serde_json::Value;
|
||||
use tracing::debug;
|
||||
|
||||
const BACKGROUND_AGENT_TOOL_NAME: &str = "background_agent";
|
||||
const SILENCE_TOOL_NAME: &str = "remain_silent";
|
||||
const DEFAULT_AUDIO_SAMPLE_RATE: u32 = 24_000;
|
||||
const DEFAULT_AUDIO_CHANNELS: u16 = 1;
|
||||
const TOOL_ARGUMENT_KEYS: [&str; 5] = ["input_transcript", "input", "text", "prompt", "query"];
|
||||
|
||||
pub(super) fn parse_realtime_event_v2(payload: &str) -> Option<RealtimeEvent> {
|
||||
let (parsed, message_type) = parse_realtime_payload(payload, "realtime v2")?;
|
||||
|
||||
match message_type.as_str() {
|
||||
"session.updated" => parse_session_updated_event(&parsed),
|
||||
"response.output_audio.delta" | "response.audio.delta" => {
|
||||
parse_output_audio_delta_event(&parsed)
|
||||
}
|
||||
"conversation.item.input_audio_transcription.delta" => {
|
||||
parse_transcript_delta_event(&parsed, "delta").map(RealtimeEvent::InputTranscriptDelta)
|
||||
}
|
||||
"conversation.item.input_audio_transcription.completed" => {
|
||||
parse_transcript_done_event(&parsed, "transcript")
|
||||
.map(RealtimeEvent::InputTranscriptDone)
|
||||
}
|
||||
"response.output_text.delta" | "response.output_audio_transcript.delta" => {
|
||||
parse_transcript_delta_event(&parsed, "delta").map(RealtimeEvent::OutputTranscriptDelta)
|
||||
}
|
||||
"response.output_text.done" => {
|
||||
parse_transcript_done_event(&parsed, "text").map(RealtimeEvent::OutputTranscriptDone)
|
||||
}
|
||||
"response.output_audio_transcript.done" => {
|
||||
parse_transcript_done_event(&parsed, "transcript")
|
||||
.map(RealtimeEvent::OutputTranscriptDone)
|
||||
}
|
||||
"input_audio_buffer.speech_started" => Some(RealtimeEvent::InputAudioSpeechStarted(
|
||||
RealtimeInputAudioSpeechStarted {
|
||||
item_id: parsed
|
||||
.get("item_id")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string),
|
||||
},
|
||||
)),
|
||||
"conversation.item.added" | "conversation.item.created" => parsed
|
||||
.get("item")
|
||||
.cloned()
|
||||
.map(RealtimeEvent::ConversationItemAdded),
|
||||
"conversation.item.done" => parse_conversation_item_done_event(&parsed),
|
||||
"response.created" => Some(RealtimeEvent::ResponseCreated(RealtimeResponseCreated {
|
||||
response_id: parse_response_event_response_id(&parsed),
|
||||
})),
|
||||
"response.cancelled" => Some(RealtimeEvent::ResponseCancelled(
|
||||
RealtimeResponseCancelled {
|
||||
response_id: parse_response_event_response_id(&parsed),
|
||||
},
|
||||
)),
|
||||
"response.done" => Some(RealtimeEvent::ResponseDone(RealtimeResponseDone {
|
||||
response_id: parse_response_event_response_id(&parsed),
|
||||
})),
|
||||
"error" => parse_error_event(&parsed),
|
||||
_ => {
|
||||
debug!("received unsupported realtime v2 event type: {message_type}, data: {payload}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_response_event_response_id(parsed: &Value) -> Option<String> {
|
||||
parsed
|
||||
.get("response")
|
||||
.and_then(Value::as_object)
|
||||
.and_then(|response| response.get("id"))
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string)
|
||||
.or_else(|| {
|
||||
parsed
|
||||
.get("response_id")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string)
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_output_audio_delta_event(parsed: &Value) -> Option<RealtimeEvent> {
|
||||
let data = parsed
|
||||
.get("delta")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string)?;
|
||||
let sample_rate = parsed
|
||||
.get("sample_rate")
|
||||
.and_then(Value::as_u64)
|
||||
.and_then(|value| u32::try_from(value).ok())
|
||||
.unwrap_or(DEFAULT_AUDIO_SAMPLE_RATE);
|
||||
let num_channels = parsed
|
||||
.get("channels")
|
||||
.or_else(|| parsed.get("num_channels"))
|
||||
.and_then(Value::as_u64)
|
||||
.and_then(|value| u16::try_from(value).ok())
|
||||
.unwrap_or(DEFAULT_AUDIO_CHANNELS);
|
||||
Some(RealtimeEvent::AudioOut(RealtimeAudioFrame {
|
||||
data,
|
||||
sample_rate,
|
||||
num_channels,
|
||||
samples_per_channel: parsed
|
||||
.get("samples_per_channel")
|
||||
.and_then(Value::as_u64)
|
||||
.and_then(|value| u32::try_from(value).ok()),
|
||||
item_id: parsed
|
||||
.get("item_id")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string),
|
||||
}))
|
||||
}
|
||||
|
||||
fn parse_conversation_item_done_event(parsed: &Value) -> Option<RealtimeEvent> {
|
||||
let item = parsed.get("item")?.as_object()?;
|
||||
if let Some(handoff) = parse_handoff_requested_event(item) {
|
||||
return Some(handoff);
|
||||
}
|
||||
if let Some(noop) = parse_noop_requested_event(item) {
|
||||
return Some(noop);
|
||||
}
|
||||
|
||||
item.get("id")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string)
|
||||
.map(|item_id| RealtimeEvent::ConversationItemDone { item_id })
|
||||
}
|
||||
|
||||
fn parse_handoff_requested_event(item: &JsonMap<String, Value>) -> Option<RealtimeEvent> {
|
||||
let item_type = item.get("type").and_then(Value::as_str);
|
||||
let item_name = item.get("name").and_then(Value::as_str);
|
||||
if item_type != Some("function_call") || item_name != Some(BACKGROUND_AGENT_TOOL_NAME) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let call_id = item
|
||||
.get("call_id")
|
||||
.and_then(Value::as_str)
|
||||
.or_else(|| item.get("id").and_then(Value::as_str))?;
|
||||
let item_id = item
|
||||
.get("id")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or(call_id)
|
||||
.to_string();
|
||||
let arguments = item.get("arguments").and_then(Value::as_str).unwrap_or("");
|
||||
|
||||
Some(RealtimeEvent::HandoffRequested(RealtimeHandoffRequested {
|
||||
handoff_id: call_id.to_string(),
|
||||
item_id,
|
||||
input_transcript: extract_input_transcript(arguments),
|
||||
active_transcript: Vec::new(),
|
||||
}))
|
||||
}
|
||||
|
||||
fn parse_noop_requested_event(item: &JsonMap<String, Value>) -> Option<RealtimeEvent> {
|
||||
let item_type = item.get("type").and_then(Value::as_str);
|
||||
let item_name = item.get("name").and_then(Value::as_str);
|
||||
if item_type != Some("function_call") || item_name != Some(SILENCE_TOOL_NAME) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let call_id = item
|
||||
.get("call_id")
|
||||
.and_then(Value::as_str)
|
||||
.or_else(|| item.get("id").and_then(Value::as_str))?;
|
||||
let item_id = item
|
||||
.get("id")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or(call_id)
|
||||
.to_string();
|
||||
|
||||
Some(RealtimeEvent::NoopRequested(RealtimeNoopRequested {
|
||||
call_id: call_id.to_string(),
|
||||
item_id,
|
||||
}))
|
||||
}
|
||||
|
||||
fn extract_input_transcript(arguments: &str) -> String {
|
||||
if arguments.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
|
||||
if let Ok(arguments_json) = serde_json::from_str::<Value>(arguments)
|
||||
&& let Some(arguments_object) = arguments_json.as_object()
|
||||
{
|
||||
for key in TOOL_ARGUMENT_KEYS {
|
||||
if let Some(value) = arguments_object.get(key).and_then(Value::as_str) {
|
||||
let trimmed = value.trim();
|
||||
if !trimmed.is_empty() {
|
||||
return trimmed.to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
arguments.to_string()
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
//! V3 transcript reconciliation across interleaved speakers, reconnects, and turn boundaries.
|
||||
|
||||
use super::*;
|
||||
use akode_protocol::protocol::RealtimeTranscriptDone;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn events(transcript_state: RealtimeTranscriptState) -> RealtimeWebsocketEvents {
|
||||
let (_, rx_message) = async_channel::unbounded();
|
||||
RealtimeWebsocketEvents {
|
||||
rx_message,
|
||||
pending_events: Arc::new(Mutex::new(VecDeque::new())),
|
||||
transcript_state,
|
||||
event_parser: RealtimeEventParser::FramelessBidi,
|
||||
is_closed: Arc::new(AtomicBool::new(false)),
|
||||
}
|
||||
}
|
||||
|
||||
fn entry(role: &str, text: &str) -> RealtimeTranscriptEntry {
|
||||
RealtimeTranscriptEntry {
|
||||
role: role.to_string(),
|
||||
text: text.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn observe(events: &RealtimeWebsocketEvents, mut event: RealtimeEvent) {
|
||||
let original = event.clone();
|
||||
events.update_active_transcript(&mut event).await;
|
||||
assert_eq!(
|
||||
event, original,
|
||||
"live transcript events must pass through unchanged"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn interleaved_transcripts_reconcile_across_reconnect_in_either_completion_order() {
|
||||
for assistant_finishes_first in [false, true] {
|
||||
let state = RealtimeTranscriptState::default();
|
||||
let first = events(state.clone());
|
||||
for event in [
|
||||
RealtimeEvent::InputTranscriptDelta(RealtimeTranscriptDelta {
|
||||
delta: "What can ".into(),
|
||||
}),
|
||||
RealtimeEvent::OutputTranscriptDelta(RealtimeTranscriptDelta {
|
||||
delta: "A bunch ".into(),
|
||||
}),
|
||||
RealtimeEvent::InputTranscriptDelta(RealtimeTranscriptDelta {
|
||||
delta: "you do?".into(),
|
||||
}),
|
||||
RealtimeEvent::OutputTranscriptDelta(RealtimeTranscriptDelta {
|
||||
delta: "of stuff".into(),
|
||||
}),
|
||||
] {
|
||||
observe(&first, event).await;
|
||||
}
|
||||
let reconnected = events(state);
|
||||
let user = RealtimeEvent::InputTranscriptDone(RealtimeTranscriptDone {
|
||||
text: "What can you do?".into(),
|
||||
});
|
||||
let assistant = RealtimeEvent::OutputTranscriptDone(RealtimeTranscriptDone {
|
||||
text: "A bunch of stuff, including coding.".into(),
|
||||
});
|
||||
let finals = if assistant_finishes_first {
|
||||
[assistant, user]
|
||||
} else {
|
||||
[user, assistant]
|
||||
};
|
||||
for event in finals {
|
||||
observe(&reconnected, event).await;
|
||||
}
|
||||
assert_eq!(
|
||||
reconnected.take_transcript_tail().await,
|
||||
vec![
|
||||
entry("user", "What can you do?"),
|
||||
entry("assistant", "A bunch of stuff, including coding."),
|
||||
]
|
||||
);
|
||||
assert_eq!(reconnected.take_transcript_tail().await, vec![]);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn completed_utterances_keep_repeated_speech_and_final_only_turns_distinct() {
|
||||
let events = events(RealtimeTranscriptState::default());
|
||||
for role in ["user", "assistant"] {
|
||||
for with_delta in [true, true, false] {
|
||||
if with_delta {
|
||||
let delta = RealtimeTranscriptDelta {
|
||||
delta: "Again".into(),
|
||||
};
|
||||
observe(
|
||||
&events,
|
||||
if role == "user" {
|
||||
RealtimeEvent::InputTranscriptDelta(delta)
|
||||
} else {
|
||||
RealtimeEvent::OutputTranscriptDelta(delta)
|
||||
},
|
||||
)
|
||||
.await;
|
||||
}
|
||||
let done = RealtimeTranscriptDone {
|
||||
text: "Again.".into(),
|
||||
};
|
||||
observe(
|
||||
&events,
|
||||
if role == "user" {
|
||||
RealtimeEvent::InputTranscriptDone(done)
|
||||
} else {
|
||||
RealtimeEvent::OutputTranscriptDone(done)
|
||||
},
|
||||
)
|
||||
.await;
|
||||
// An empty delta must not reopen the utterance we just completed.
|
||||
let empty = RealtimeTranscriptDelta {
|
||||
delta: String::new(),
|
||||
};
|
||||
observe(
|
||||
&events,
|
||||
if role == "user" {
|
||||
RealtimeEvent::InputTranscriptDelta(empty)
|
||||
} else {
|
||||
RealtimeEvent::OutputTranscriptDelta(empty)
|
||||
},
|
||||
)
|
||||
.await;
|
||||
}
|
||||
assert_eq!(
|
||||
events.take_transcript_tail().await,
|
||||
vec![entry(role, "Again."); 3]
|
||||
);
|
||||
}
|
||||
}
|
||||
159
akode-rs/akode-api/src/endpoint/responses.rs
Normal file
159
akode-rs/akode-api/src/endpoint/responses.rs
Normal file
@@ -0,0 +1,159 @@
|
||||
use crate::auth::SharedAuthProvider;
|
||||
use crate::common::ResponseStream;
|
||||
use crate::common::ResponsesApiRequest;
|
||||
use crate::endpoint::session::EndpointSession;
|
||||
use crate::error::ApiError;
|
||||
use crate::provider::Provider;
|
||||
use crate::requests::Compression;
|
||||
use crate::requests::headers::build_session_headers;
|
||||
use crate::requests::headers::insert_header;
|
||||
use crate::requests::headers::subagent_header;
|
||||
use crate::sse::spawn_response_stream;
|
||||
use crate::telemetry::SseTelemetry;
|
||||
use akode_client::EncodedJsonBody;
|
||||
use akode_client::HttpTransport;
|
||||
use akode_client::RequestCompression;
|
||||
use akode_client::RequestTelemetry;
|
||||
use akode_protocol::protocol::SessionSource;
|
||||
use http::HeaderMap;
|
||||
use http::HeaderValue;
|
||||
use http::Method;
|
||||
use serde_json::Value;
|
||||
use std::sync::Arc;
|
||||
use std::sync::OnceLock;
|
||||
use tracing::instrument;
|
||||
|
||||
pub struct ResponsesClient<T: HttpTransport> {
|
||||
session: EndpointSession<T>,
|
||||
sse_telemetry: Option<Arc<dyn SseTelemetry>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct ResponsesOptions {
|
||||
pub session_id: Option<String>,
|
||||
pub thread_id: Option<String>,
|
||||
pub session_source: Option<SessionSource>,
|
||||
pub extra_headers: HeaderMap,
|
||||
pub compression: Compression,
|
||||
pub turn_state: Option<Arc<OnceLock<String>>>,
|
||||
}
|
||||
|
||||
impl<T: HttpTransport> ResponsesClient<T> {
|
||||
pub fn new(transport: T, provider: Provider, auth: SharedAuthProvider) -> Self {
|
||||
Self {
|
||||
session: EndpointSession::new(transport, provider, auth),
|
||||
sse_telemetry: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_telemetry(
|
||||
self,
|
||||
request: Option<Arc<dyn RequestTelemetry>>,
|
||||
sse: Option<Arc<dyn SseTelemetry>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
session: self.session.with_request_telemetry(request),
|
||||
sse_telemetry: sse,
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument(
|
||||
name = "responses.stream_request",
|
||||
level = "info",
|
||||
skip_all,
|
||||
fields(
|
||||
transport = "responses_http",
|
||||
http.method = "POST",
|
||||
api.path = "/responses"
|
||||
)
|
||||
)]
|
||||
pub async fn stream_request(
|
||||
&self,
|
||||
request: ResponsesApiRequest,
|
||||
options: ResponsesOptions,
|
||||
) -> Result<ResponseStream, ApiError> {
|
||||
let ResponsesOptions {
|
||||
session_id,
|
||||
thread_id,
|
||||
session_source,
|
||||
extra_headers,
|
||||
compression,
|
||||
turn_state,
|
||||
} = options;
|
||||
let body = EncodedJsonBody::encode(&request)
|
||||
.map_err(|e| ApiError::Stream(format!("failed to encode responses request: {e}")))?;
|
||||
|
||||
let mut headers = extra_headers;
|
||||
if let Some(ref thread_id) = thread_id {
|
||||
insert_header(&mut headers, "x-client-request-id", thread_id);
|
||||
}
|
||||
headers.extend(build_session_headers(session_id, thread_id));
|
||||
if let Some(subagent) = subagent_header(&session_source) {
|
||||
insert_header(&mut headers, "x-openai-subagent", &subagent);
|
||||
}
|
||||
|
||||
self.stream_encoded(body, headers, compression, turn_state)
|
||||
.await
|
||||
}
|
||||
|
||||
#[instrument(
|
||||
name = "responses.stream",
|
||||
level = "info",
|
||||
skip_all,
|
||||
fields(
|
||||
transport = "responses_http",
|
||||
http.method = "POST",
|
||||
api.path = "/responses",
|
||||
turn.has_state = turn_state.is_some()
|
||||
)
|
||||
)]
|
||||
pub async fn stream(
|
||||
&self,
|
||||
body: Value,
|
||||
extra_headers: HeaderMap,
|
||||
compression: Compression,
|
||||
turn_state: Option<Arc<OnceLock<String>>>,
|
||||
) -> Result<ResponseStream, ApiError> {
|
||||
let body = EncodedJsonBody::encode(&body)
|
||||
.map_err(|e| ApiError::Stream(format!("failed to encode responses request: {e}")))?;
|
||||
self.stream_encoded(body, extra_headers, compression, turn_state)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn stream_encoded(
|
||||
&self,
|
||||
body: EncodedJsonBody,
|
||||
extra_headers: HeaderMap,
|
||||
compression: Compression,
|
||||
turn_state: Option<Arc<OnceLock<String>>>,
|
||||
) -> Result<ResponseStream, ApiError> {
|
||||
let request_compression = match compression {
|
||||
Compression::None => RequestCompression::None,
|
||||
Compression::Zstd => RequestCompression::Zstd,
|
||||
};
|
||||
|
||||
let stream_response = self
|
||||
.session
|
||||
.stream_encoded_json_with(
|
||||
Method::POST,
|
||||
"/responses",
|
||||
extra_headers,
|
||||
Some(body),
|
||||
|req| {
|
||||
req.headers.insert(
|
||||
http::header::ACCEPT,
|
||||
HeaderValue::from_static("text/event-stream"),
|
||||
);
|
||||
req.compression = request_compression;
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(spawn_response_stream(
|
||||
stream_response,
|
||||
self.session.provider().stream_idle_timeout,
|
||||
self.sse_telemetry.clone(),
|
||||
turn_state,
|
||||
))
|
||||
}
|
||||
}
|
||||
1471
akode-rs/akode-api/src/endpoint/responses_websocket.rs
Normal file
1471
akode-rs/akode-api/src/endpoint/responses_websocket.rs
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,51 @@
|
||||
//! Establishes Responses sockets with caller-owned TLS and proxy configuration.
|
||||
//! Connector reuse never caches authentication or bypasses per-connection destination policy.
|
||||
|
||||
use super::ResponsesWebsocketClient;
|
||||
use super::ResponsesWebsocketConnection;
|
||||
use super::connect_websocket;
|
||||
use super::merge_request_headers;
|
||||
use crate::ApiError;
|
||||
use crate::RESPONSES_PATH;
|
||||
use crate::WebsocketTelemetry;
|
||||
use akode_websocket_client::WebSocketConnector;
|
||||
use http::HeaderMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
impl ResponsesWebsocketClient {
|
||||
/// Opens a socket using the caller's reusable connector and this client's current auth.
|
||||
/// The caller owns the lifetime of the connector's TLS configuration snapshot.
|
||||
#[tracing::instrument(
|
||||
name = "responses_websocket.connect",
|
||||
level = "info",
|
||||
skip_all,
|
||||
fields(transport = "responses_websocket", api.path = "/responses")
|
||||
)]
|
||||
pub async fn connect_with_connector(
|
||||
&self,
|
||||
connector: &WebSocketConnector,
|
||||
extra_headers: HeaderMap,
|
||||
default_headers: HeaderMap,
|
||||
turn_state: Option<Arc<OnceLock<String>>>,
|
||||
telemetry: Option<Arc<dyn WebsocketTelemetry>>,
|
||||
) -> Result<ResponsesWebsocketConnection, ApiError> {
|
||||
let ws_url = self
|
||||
.provider
|
||||
.websocket_url_for_path(RESPONSES_PATH)
|
||||
.map_err(|err| ApiError::Stream(format!("failed to build websocket URL: {err}")))?;
|
||||
let headers = merge_request_headers(&self.provider.headers, extra_headers, default_headers);
|
||||
let headers = self.auth.apply_auth_headers(headers).await?;
|
||||
let (stream, _response, server_reasoning_included, server_model) =
|
||||
connect_websocket(ws_url, headers, connector, turn_state)
|
||||
.await
|
||||
.map_err(|failure| *failure.error)?;
|
||||
Ok(ResponsesWebsocketConnection::new(
|
||||
stream,
|
||||
self.provider.stream_idle_timeout,
|
||||
server_reasoning_included,
|
||||
server_model,
|
||||
telemetry,
|
||||
))
|
||||
}
|
||||
}
|
||||
101
akode-rs/akode-api/src/endpoint/responses_websocket_probe.rs
Normal file
101
akode-rs/akode-api/src/endpoint/responses_websocket_probe.rs
Normal file
@@ -0,0 +1,101 @@
|
||||
//! Handshake probe evidence. Failure stages require typed evidence, and Debug output hides wire
|
||||
//! values that may contain credentials; diagnostic callers must redact displayed values themselves.
|
||||
|
||||
use crate::error::ApiError;
|
||||
use http::HeaderMap;
|
||||
use http::StatusCode;
|
||||
|
||||
/// Close frame information captured by a handshake probe.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct ResponsesWebsocketClose {
|
||||
/// WebSocket close code returned by the server.
|
||||
pub code: String,
|
||||
/// Human-readable close reason returned by the server.
|
||||
pub reason: String,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ResponsesWebsocketClose {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("ResponsesWebsocketClose")
|
||||
.field("code", &self.code)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// Result of a handshake-only Responses WebSocket probe.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct ResponsesWebsocketProbe {
|
||||
/// Redacted by callers before displaying or serializing support reports.
|
||||
pub url: String,
|
||||
/// HTTP status returned by the successful WebSocket upgrade.
|
||||
pub status: StatusCode,
|
||||
/// Allowlisted tracking headers from the successful upgrade.
|
||||
pub headers: HeaderMap,
|
||||
/// Whether the server reported reasoning support in the upgrade response.
|
||||
pub reasoning_included: bool,
|
||||
/// Whether the server returned a server-selected model in the upgrade response.
|
||||
pub server_model_present: bool,
|
||||
/// Close frame received immediately after upgrade, when one arrives quickly.
|
||||
pub immediate_close: Option<ResponsesWebsocketClose>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ResponsesWebsocketProbe {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("ResponsesWebsocketProbe")
|
||||
.field("status", &self.status)
|
||||
.field("reasoning_included", &self.reasoning_included)
|
||||
.field("server_model_present", &self.server_model_present)
|
||||
.field("immediate_close", &self.immediate_close)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// A failure stage established by typed evidence at the handshake boundary.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ResponsesWebsocketProbeFailureStage {
|
||||
/// TLS configuration or a typed TLS handshake failure.
|
||||
Tls,
|
||||
/// The transport did not expose enough evidence to identify a failure stage.
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// Probe failure with any HTTP upgrade evidence received before the failure.
|
||||
///
|
||||
/// Rejected upgrades retain status and headers in the original [`ApiError`]. An error after a
|
||||
/// successful upgrade also retains that upgrade's status and allowlisted tracking headers here.
|
||||
#[derive(thiserror::Error)]
|
||||
#[error("Responses WebSocket probe failed")]
|
||||
pub struct ResponsesWebsocketProbeError {
|
||||
/// Original API error, preserving the production connection's error behavior.
|
||||
#[source]
|
||||
pub error: Box<ApiError>,
|
||||
/// Failure stage, when typed evidence establishes one.
|
||||
pub stage: ResponsesWebsocketProbeFailureStage,
|
||||
/// Status received before a subsequent read failure.
|
||||
pub status: Option<StatusCode>,
|
||||
/// Allowlisted tracking headers received before a subsequent read failure.
|
||||
pub headers: Option<HeaderMap>,
|
||||
}
|
||||
|
||||
impl ResponsesWebsocketProbeError {
|
||||
pub(crate) fn before_upgrade(
|
||||
error: ApiError,
|
||||
stage: ResponsesWebsocketProbeFailureStage,
|
||||
) -> Self {
|
||||
Self {
|
||||
error: Box::new(error),
|
||||
stage,
|
||||
status: None,
|
||||
headers: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ResponsesWebsocketProbeError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("ResponsesWebsocketProbeError")
|
||||
.field("stage", &self.stage)
|
||||
.field("status", &self.status)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
324
akode-rs/akode-api/src/endpoint/search.rs
Normal file
324
akode-rs/akode-api/src/endpoint/search.rs
Normal file
@@ -0,0 +1,324 @@
|
||||
use crate::auth::SharedAuthProvider;
|
||||
use crate::endpoint::session::EndpointSession;
|
||||
use crate::error::ApiError;
|
||||
use crate::provider::Provider;
|
||||
use crate::search::SearchRequest;
|
||||
use crate::search::SearchResponse;
|
||||
use akode_client::HttpTransport;
|
||||
use akode_client::RequestTelemetry;
|
||||
use http::HeaderMap;
|
||||
use http::Method;
|
||||
use serde_json::to_value;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The provider-relative endpoint for standalone web search.
|
||||
const SEARCH_ENDPOINT: &str = "alpha/search";
|
||||
|
||||
pub struct SearchClient<T: HttpTransport> {
|
||||
session: EndpointSession<T>,
|
||||
}
|
||||
|
||||
impl<T: HttpTransport> SearchClient<T> {
|
||||
pub fn new(transport: T, provider: Provider, auth: SharedAuthProvider) -> Self {
|
||||
Self {
|
||||
session: EndpointSession::new(transport, provider, auth),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_telemetry(self, request: Option<Arc<dyn RequestTelemetry>>) -> Self {
|
||||
Self {
|
||||
session: self.session.with_request_telemetry(request),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn search(
|
||||
&self,
|
||||
request: &SearchRequest,
|
||||
extra_headers: HeaderMap,
|
||||
) -> Result<SearchResponse, ApiError> {
|
||||
let body = to_value(request)
|
||||
.map_err(|e| ApiError::Stream(format!("failed to encode search request: {e}")))?;
|
||||
let resp = self
|
||||
.session
|
||||
.execute(Method::POST, SEARCH_ENDPOINT, extra_headers, Some(body))
|
||||
.await?;
|
||||
serde_json::from_slice(&resp.body)
|
||||
.map_err(|e| ApiError::Stream(format!("failed to decode search response: {e}")))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::auth::AuthProvider;
|
||||
use crate::provider::RetryConfig;
|
||||
use crate::search::AllowedCaller;
|
||||
use crate::search::ApproximateLocation;
|
||||
use crate::search::ExternalWebAccess;
|
||||
use crate::search::LocationType;
|
||||
use crate::search::OpenOperation;
|
||||
use crate::search::SearchCommands;
|
||||
use crate::search::SearchContextSize;
|
||||
use crate::search::SearchFilters;
|
||||
use crate::search::SearchImageSettings;
|
||||
use crate::search::SearchInput;
|
||||
use crate::search::SearchQuery;
|
||||
use crate::search::SearchSettings;
|
||||
use akode_client::Request;
|
||||
use akode_client::RequestBody;
|
||||
use akode_client::Response;
|
||||
use akode_client::StreamResponse;
|
||||
use akode_client::TransportError;
|
||||
use akode_protocol::ResponseItemId;
|
||||
use akode_protocol::models::ContentItem;
|
||||
use akode_protocol::models::ImageReference;
|
||||
use akode_protocol::models::ResponseItem;
|
||||
use http::StatusCode;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct DummyAuth;
|
||||
|
||||
impl AuthProvider for DummyAuth {
|
||||
fn add_auth_headers(&self, _headers: &mut HeaderMap) -> Result<(), crate::AuthError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct CapturingTransport {
|
||||
last_request: Arc<Mutex<Option<Request>>>,
|
||||
response_body: Arc<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl CapturingTransport {
|
||||
fn new(response_body: Vec<u8>) -> Self {
|
||||
Self {
|
||||
last_request: Arc::new(Mutex::new(None)),
|
||||
response_body: Arc::new(response_body),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HttpTransport for CapturingTransport {
|
||||
async fn execute(&self, req: Request) -> Result<Response, TransportError> {
|
||||
*self.last_request.lock().expect("lock request store") = Some(req);
|
||||
Ok(Response {
|
||||
status: StatusCode::OK,
|
||||
headers: HeaderMap::new(),
|
||||
body: self.response_body.as_ref().clone().into(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn stream(&self, _req: Request) -> Result<StreamResponse, TransportError> {
|
||||
Err(TransportError::Build("stream should not run".to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
fn provider() -> Provider {
|
||||
Provider {
|
||||
name: "test".to_string(),
|
||||
base_url: "https://example.com/v1".to_string(),
|
||||
query_params: None,
|
||||
headers: HeaderMap::new(),
|
||||
retry: RetryConfig {
|
||||
max_attempts: 1,
|
||||
base_delay: Duration::from_millis(1),
|
||||
retry_429: false,
|
||||
retry_5xx: true,
|
||||
retry_transport: true,
|
||||
},
|
||||
stream_idle_timeout: Duration::from_secs(1),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn search_posts_typed_request_and_parses_output() {
|
||||
let transport = CapturingTransport::new(
|
||||
serde_json::to_vec(&json!({
|
||||
"encrypted_output": "ciphertext",
|
||||
"output": "search result",
|
||||
"results": [{
|
||||
"type": "text_result",
|
||||
"ref_id": "turn0search0",
|
||||
"url": "https://example.com/result",
|
||||
"future_field": {"preserved": true},
|
||||
}],
|
||||
}))
|
||||
.expect("serialize response"),
|
||||
);
|
||||
let client = SearchClient::new(transport.clone(), provider(), Arc::new(DummyAuth));
|
||||
|
||||
let response = client
|
||||
.search(
|
||||
&SearchRequest {
|
||||
id: "search-session".to_string(),
|
||||
model: "gpt-test".to_string(),
|
||||
reasoning: None,
|
||||
input: Some(SearchInput::Items(vec![ResponseItem::Message {
|
||||
status: None,
|
||||
encrypted_content: None,
|
||||
id: Some(ResponseItemId::with_suffix("msg", "search")),
|
||||
role: "user".to_string(),
|
||||
content: vec![
|
||||
ContentItem::InputText {
|
||||
text: "find this".to_string(),
|
||||
},
|
||||
ContentItem::InputImage {
|
||||
image: ImageReference::Inline {
|
||||
image_url: "https://example.com/image.png".to_string(),
|
||||
},
|
||||
detail: None,
|
||||
},
|
||||
],
|
||||
phase: None,
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
}])),
|
||||
commands: Some(SearchCommands {
|
||||
search_query: Some(vec![SearchQuery {
|
||||
q: "OpenAI news".to_string(),
|
||||
recency: Some(7),
|
||||
domains: Some(vec!["openai.com".to_string()]),
|
||||
}]),
|
||||
open: Some(vec![OpenOperation {
|
||||
ref_id: "https://openai.com".to_string(),
|
||||
lineno: Some(12),
|
||||
}]),
|
||||
..Default::default()
|
||||
}),
|
||||
settings: Some(SearchSettings {
|
||||
user_location: Some(ApproximateLocation {
|
||||
r#type: LocationType::Approximate,
|
||||
country: Some("US".to_string()),
|
||||
region: None,
|
||||
city: Some("San Francisco".to_string()),
|
||||
timezone: None,
|
||||
}),
|
||||
search_context_size: Some(SearchContextSize::Low),
|
||||
filters: Some(SearchFilters {
|
||||
allowed_domains: Some(vec!["openai.com".to_string()]),
|
||||
blocked_domains: Some(vec!["example.com".to_string()]),
|
||||
}),
|
||||
image_settings: Some(SearchImageSettings {
|
||||
max_results: Some(4),
|
||||
caption: Some(true),
|
||||
}),
|
||||
allowed_callers: Some(vec![AllowedCaller::Direct]),
|
||||
external_web_access: Some(ExternalWebAccess::Boolean(true)),
|
||||
}),
|
||||
max_output_tokens: Some(2500),
|
||||
},
|
||||
HeaderMap::new(),
|
||||
)
|
||||
.await
|
||||
.expect("search request should succeed");
|
||||
|
||||
assert_eq!(
|
||||
response,
|
||||
SearchResponse {
|
||||
encrypted_output: Some("ciphertext".to_string()),
|
||||
output: "search result".to_string(),
|
||||
results: Some(vec![json!({
|
||||
"type": "text_result",
|
||||
"ref_id": "turn0search0",
|
||||
"url": "https://example.com/result",
|
||||
"future_field": {"preserved": true},
|
||||
})]),
|
||||
}
|
||||
);
|
||||
|
||||
let request = transport
|
||||
.last_request
|
||||
.lock()
|
||||
.expect("lock request store")
|
||||
.clone()
|
||||
.expect("request should be captured");
|
||||
let body = request
|
||||
.body
|
||||
.as_ref()
|
||||
.and_then(RequestBody::json)
|
||||
.expect("request body should be JSON");
|
||||
assert_eq!(
|
||||
body,
|
||||
&json!({
|
||||
"id": "search-session",
|
||||
"model": "gpt-test",
|
||||
"input": [{
|
||||
"type": "message",
|
||||
"id": "msg_search",
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "input_text", "text": "find this"},
|
||||
{
|
||||
"type": "input_image",
|
||||
"image_url": "https://example.com/image.png"
|
||||
}
|
||||
]
|
||||
}],
|
||||
"commands": {
|
||||
"search_query": [{
|
||||
"q": "OpenAI news",
|
||||
"recency": 7,
|
||||
"domains": ["openai.com"]
|
||||
}],
|
||||
"open": [{"ref_id": "https://openai.com", "lineno": 12}]
|
||||
},
|
||||
"settings": {
|
||||
"user_location": {
|
||||
"type": "approximate",
|
||||
"country": "US",
|
||||
"city": "San Francisco"
|
||||
},
|
||||
"search_context_size": "low",
|
||||
"filters": {
|
||||
"allowed_domains": ["openai.com"],
|
||||
"blocked_domains": ["example.com"]
|
||||
},
|
||||
"image_settings": {"max_results": 4, "caption": true},
|
||||
"allowed_callers": ["direct"],
|
||||
"external_web_access": true
|
||||
},
|
||||
"max_output_tokens": 2500
|
||||
})
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn search_response_defaults_missing_results_for_older_endpoints() {
|
||||
let response: SearchResponse = serde_json::from_value(json!({
|
||||
"encrypted_output": null,
|
||||
"output": "search result",
|
||||
}))
|
||||
.expect("response without results should deserialize");
|
||||
|
||||
assert_eq!(
|
||||
response,
|
||||
SearchResponse {
|
||||
encrypted_output: None,
|
||||
output: "search result".to_string(),
|
||||
results: None,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_response_preserves_supported_empty_results() {
|
||||
let response: SearchResponse = serde_json::from_value(json!({
|
||||
"encrypted_output": null,
|
||||
"output": "search result",
|
||||
"results": [],
|
||||
}))
|
||||
.expect("response with empty results should deserialize");
|
||||
|
||||
assert_eq!(
|
||||
response,
|
||||
SearchResponse {
|
||||
encrypted_output: None,
|
||||
output: "search result".to_string(),
|
||||
results: Some(Vec::new()),
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
156
akode-rs/akode-api/src/endpoint/session.rs
Normal file
156
akode-rs/akode-api/src/endpoint/session.rs
Normal file
@@ -0,0 +1,156 @@
|
||||
use crate::auth::SharedAuthProvider;
|
||||
use crate::error::ApiError;
|
||||
use crate::provider::Provider;
|
||||
use crate::telemetry::run_with_request_telemetry;
|
||||
use akode_client::EncodedJsonBody;
|
||||
use akode_client::HttpTransport;
|
||||
use akode_client::Request;
|
||||
use akode_client::RequestBody;
|
||||
use akode_client::RequestTelemetry;
|
||||
use akode_client::Response;
|
||||
use akode_client::StreamResponse;
|
||||
use akode_client::TransportError;
|
||||
use http::HeaderMap;
|
||||
use http::Method;
|
||||
use serde_json::Value;
|
||||
use std::sync::Arc;
|
||||
use tracing::instrument;
|
||||
|
||||
pub(crate) struct EndpointSession<T: HttpTransport> {
|
||||
transport: T,
|
||||
provider: Provider,
|
||||
auth: SharedAuthProvider,
|
||||
request_telemetry: Option<Arc<dyn RequestTelemetry>>,
|
||||
}
|
||||
|
||||
impl<T: HttpTransport> EndpointSession<T> {
|
||||
pub(crate) fn new(transport: T, provider: Provider, auth: SharedAuthProvider) -> Self {
|
||||
Self {
|
||||
transport,
|
||||
provider,
|
||||
auth,
|
||||
request_telemetry: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn with_request_telemetry(
|
||||
mut self,
|
||||
request: Option<Arc<dyn RequestTelemetry>>,
|
||||
) -> Self {
|
||||
self.request_telemetry = request;
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn provider(&self) -> &Provider {
|
||||
&self.provider
|
||||
}
|
||||
|
||||
fn make_request(
|
||||
&self,
|
||||
method: &Method,
|
||||
path: &str,
|
||||
extra_headers: &HeaderMap,
|
||||
body: Option<&RequestBody>,
|
||||
) -> Request {
|
||||
let mut req = self.provider.build_request(method.clone(), path);
|
||||
req.headers.extend(extra_headers.clone());
|
||||
if let Some(body) = body {
|
||||
req.body = Some(body.clone());
|
||||
}
|
||||
req
|
||||
}
|
||||
|
||||
pub(crate) async fn execute(
|
||||
&self,
|
||||
method: Method,
|
||||
path: &str,
|
||||
extra_headers: HeaderMap,
|
||||
body: Option<Value>,
|
||||
) -> Result<Response, ApiError> {
|
||||
self.execute_with(method, path, extra_headers, body, |_| {})
|
||||
.await
|
||||
}
|
||||
|
||||
#[instrument(
|
||||
name = "endpoint_session.execute_with",
|
||||
level = "info",
|
||||
skip_all,
|
||||
fields(http.method = %method, api.path = path)
|
||||
)]
|
||||
pub(crate) async fn execute_with<C>(
|
||||
&self,
|
||||
method: Method,
|
||||
path: &str,
|
||||
extra_headers: HeaderMap,
|
||||
body: Option<Value>,
|
||||
configure: C,
|
||||
) -> Result<Response, ApiError>
|
||||
where
|
||||
C: Fn(&mut Request),
|
||||
{
|
||||
let body = body.map(RequestBody::Json);
|
||||
let make_request = || {
|
||||
let mut req = self.make_request(&method, path, &extra_headers, body.as_ref());
|
||||
configure(&mut req);
|
||||
req
|
||||
};
|
||||
|
||||
let response = run_with_request_telemetry(
|
||||
self.provider.retry.to_policy(),
|
||||
self.request_telemetry.clone(),
|
||||
make_request,
|
||||
|req| {
|
||||
let auth = self.auth.clone();
|
||||
let transport = &self.transport;
|
||||
async move {
|
||||
let req = auth.apply_auth(req).await.map_err(TransportError::from)?;
|
||||
transport.execute(req).await
|
||||
}
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
#[instrument(
|
||||
name = "endpoint_session.stream_encoded_json_with",
|
||||
level = "info",
|
||||
skip_all,
|
||||
fields(http.method = %method, api.path = path)
|
||||
)]
|
||||
pub(crate) async fn stream_encoded_json_with<C>(
|
||||
&self,
|
||||
method: Method,
|
||||
path: &str,
|
||||
extra_headers: HeaderMap,
|
||||
body: Option<EncodedJsonBody>,
|
||||
configure: C,
|
||||
) -> Result<StreamResponse, ApiError>
|
||||
where
|
||||
C: Fn(&mut Request),
|
||||
{
|
||||
let body = body.map(RequestBody::EncodedJson);
|
||||
let mut request = self.make_request(&method, path, &extra_headers, body.as_ref());
|
||||
configure(&mut request);
|
||||
let request = request.into_prepared().map_err(TransportError::Build)?;
|
||||
let make_request = || request.clone();
|
||||
|
||||
let stream = run_with_request_telemetry(
|
||||
self.provider.retry.to_policy(),
|
||||
self.request_telemetry.clone(),
|
||||
make_request,
|
||||
|req| {
|
||||
let auth = self.auth.clone();
|
||||
let transport = &self.transport;
|
||||
async move {
|
||||
let req = auth.apply_auth(req).await.map_err(TransportError::from)?;
|
||||
transport.stream(req).await
|
||||
}
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(stream)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user