use super::config::{
AnthropicGatewayConfig, KernelGatewayConfig, OpenAiChatGatewayConfig,
OpenAiResponsesGatewayConfig,
};
use super::stream::{establish_stream, model_stream};
use crate::gateway_transport::{GatewayCore, check_control, finish_response, send_with_control};
use crate::media::MediaResolver;
use async_trait::async_trait;
use causa_kernel::{
BlockContent, CallControl, ContentPart, MediaRef, ModelGateway, ModelInvokeError, ModelOutput,
ModelRequest,
};
use causa_protocol::translation::media::MediaSet;
use causa_protocol::translation::streaming::{
StreamDecoder, StreamLimits, configure_stream_request,
};
use reqwest::Client;
use std::sync::Arc;
use tracing::Instrument;
pub struct KernelHttpGateway<C: KernelGatewayConfig> {
core: GatewayCore,
api_key: String,
config: C,
media_resolver: Option<Arc<dyn MediaResolver>>,
max_inline_media_bytes: usize,
stream_limits: StreamLimits,
}
impl<C: KernelGatewayConfig> std::fmt::Debug for KernelHttpGateway<C> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("KernelHttpGateway")
.field("provider", &C::PROVIDER)
.field("path", &C::PATH)
.field("media_resolver", &self.media_resolver.is_some())
.field("max_inline_media_bytes", &self.max_inline_media_bytes)
.field("stream_limits", &self.stream_limits)
.finish_non_exhaustive()
}
}
impl<C: KernelGatewayConfig> Clone for KernelHttpGateway<C> {
fn clone(&self) -> Self {
Self {
core: self.core.clone(),
api_key: self.api_key.clone(),
config: self.config.clone(),
media_resolver: self.media_resolver.clone(),
max_inline_media_bytes: self.max_inline_media_bytes,
stream_limits: self.stream_limits,
}
}
}
impl<C: KernelGatewayConfig> KernelHttpGateway<C> {
pub fn new(api_key: impl Into<String>) -> Self {
Self {
core: GatewayCore::new(C::DEFAULT_ENDPOINT),
api_key: api_key.into(),
config: C::default(),
media_resolver: None,
max_inline_media_bytes: 5 * 1024 * 1024,
stream_limits: StreamLimits::default(),
}
}
pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
self.core = self.core.with_base_url(base_url, C::PATH);
self
}
pub fn with_endpoint(mut self, endpoint: impl Into<String>) -> Self {
self.core = self.core.with_endpoint(endpoint);
self
}
pub fn with_http_client(mut self, http: Client) -> Self {
self.core = self.core.with_http_client(http);
self
}
pub fn with_media_resolver(mut self, resolver: Arc<dyn MediaResolver>) -> Self {
self.media_resolver = Some(resolver);
self
}
pub fn with_max_inline_media_bytes(mut self, max_bytes: usize) -> Self {
self.max_inline_media_bytes = max_bytes;
self
}
pub fn with_stream_limits(mut self, limits: StreamLimits) -> Self {
self.stream_limits = limits;
self
}
fn render_request(
&self,
request: &ModelRequest,
) -> Result<serde_json::Value, ModelInvokeError> {
self.config.render(request, &self.resolve_media(request))
}
fn resolve_media(&self, request: &ModelRequest) -> MediaSet {
let mut set = MediaSet::new();
let Some(resolver) = &self.media_resolver else {
return set;
};
let mut refs: Vec<MediaRef> = Vec::new();
let mut seen = std::collections::HashSet::new();
for block in &request.frame.blocks {
let collect = |r: &MediaRef,
refs: &mut Vec<MediaRef>,
seen: &mut std::collections::HashSet<String>| {
if seen.insert(r.reference.clone()) {
refs.push(r.clone());
}
};
match block.content() {
BlockContent::Parts(parts) => {
for part in parts {
if let ContentPart::Media(r) = part {
collect(r, &mut refs, &mut seen);
}
}
}
BlockContent::ToolResult(result) => {
for r in &result.media {
collect(r, &mut refs, &mut seen);
}
}
BlockContent::ToolCall(_) => {}
}
}
for r in refs {
if let Some(payload) = resolver.resolve(&r)
&& payload.data_base64.len() * 3 / 4 <= self.max_inline_media_bytes
{
set.insert(r.reference, payload);
}
}
set
}
}
impl KernelHttpGateway<AnthropicGatewayConfig> {
pub fn with_anthropic_version(mut self, version: impl Into<String>) -> Self {
self.config.anthropic_version = version.into();
self
}
pub fn with_beta(mut self, value: impl Into<String>) -> Self {
self.config.beta.push(value.into());
self
}
}
impl KernelHttpGateway<OpenAiChatGatewayConfig> {
pub fn with_reasoning_content_replay(mut self, replay: bool) -> Self {
self.config.render_options.replay_reasoning_content = replay;
self
}
}
impl KernelHttpGateway<OpenAiResponsesGatewayConfig> {
pub fn with_encrypted_reasoning(mut self, include: bool) -> Self {
self.config.render_options.include_encrypted_reasoning = include;
self
}
pub fn with_store(mut self, store: Option<bool>) -> Self {
self.config.render_options.store = store;
self
}
}
#[async_trait]
impl<C: KernelGatewayConfig> ModelGateway for KernelHttpGateway<C> {
async fn stream(
&self,
request: &ModelRequest,
control: &CallControl,
) -> Result<causa_kernel::ModelStream, ModelInvokeError> {
let span = tracing::debug_span!("agent.http", provider = C::PROVIDER, path = C::PATH);
async {
check_control(control)?;
let decoder = StreamDecoder::new(C::PROTOCOL, self.stream_limits)?;
let mut body = self.render_request(request)?;
configure_stream_request(C::PROTOCOL, &mut body)?;
check_control(control)?;
let req = self
.config
.decorate_request(self.core.post(), &self.api_key)
.header(reqwest::header::ACCEPT, "text/event-stream")
.json(&body);
let response = establish_stream(req, control, C::PROVIDER).await?;
Ok(model_stream(response, decoder, control.clone()))
}
.instrument(span)
.await
}
async fn invoke(
&self,
request: &ModelRequest,
control: &CallControl,
) -> Result<ModelOutput, ModelInvokeError> {
let span = tracing::debug_span!("agent.http", provider = C::PROVIDER, path = C::PATH);
async {
check_control(control)?;
let body = self.render_request(request)?;
check_control(control)?;
let req = self
.config
.decorate_request(self.core.post(), &self.api_key)
.json(&body);
let response = send_with_control(req, control).await?;
finish_response(response, C::PROVIDER, |v| self.config.parse(v))
}
.instrument(span)
.await
}
}