use trusty_common::inference as tci;
use super::error::LlmError;
use super::message::ChatMessage;
use super::request::{
CacheControl, ChatRequest, FunctionCall, RequestUsageConfig, ToolCall, ToolDefinition,
};
use super::response::{AssistantMessage, ChatChoice, ChatResponse};
use super::usage::{PromptTokensDetails, UsageBlock};
pub fn to_shared_request(req: &ChatRequest, wire_model: String) -> tci::ChatRequest {
tci::ChatRequest {
model: wire_model,
messages: req.messages.iter().map(to_shared_message).collect(),
temperature: req.temperature,
max_tokens: req.max_tokens,
tools: req
.tools
.as_ref()
.map(|tools| tools.iter().map(to_shared_tool_def).collect()),
tool_choice: req.tool_choice.clone(),
stop: None,
usage: req.usage.as_ref().map(to_shared_usage_directive),
}
}
pub fn from_shared_response(resp: tci::ChatResponse) -> ChatResponse {
let u = &resp.usage;
let usage = UsageBlock {
prompt_tokens: u.prompt_tokens,
completion_tokens: u.completion_tokens,
total_tokens: u.total_tokens,
cache_read_input_tokens: u.cache_read_input_tokens,
cache_creation_input_tokens: u.cache_creation_input_tokens,
prompt_tokens_details: u
.prompt_tokens_details
.as_ref()
.map(|d| PromptTokensDetails {
cached_tokens: d.cached_tokens,
cache_write_tokens: d.cache_write_tokens,
}),
cost: u.cost,
};
ChatResponse {
id: resp.id,
model: resp.model,
choices: resp.choices.iter().map(from_shared_choice).collect(),
usage,
}
}
pub fn map_error(err: tci::InferenceError) -> LlmError {
match err {
tci::InferenceError::Api { status, body } => LlmError::ApiError { status, body },
tci::InferenceError::MissingCredential { provider } => LlmError::MissingConfig(format!(
"no API key resolved for provider '{provider}' (checked its env var, .env.local, \
and the secure credential store)"
)),
other => LlmError::Inference(other.to_string()),
}
}
fn to_shared_message(msg: &ChatMessage) -> tci::ChatMessage {
tci::ChatMessage {
role: msg.role.clone(),
content: msg.content.clone(),
tool_calls: msg
.tool_calls
.as_ref()
.map(|calls| calls.iter().map(to_shared_tool_call).collect()),
tool_call_id: msg.tool_call_id.clone(),
name: msg.name.clone(),
cache_control: msg.cache_control.as_ref().map(to_shared_cache_control),
}
}
fn to_shared_tool_call(call: &ToolCall) -> tci::ToolCall {
tci::ToolCall {
id: call.id.clone(),
kind: call.kind.clone(),
function: tci::FunctionCall {
name: call.function.name.clone(),
arguments: call.function.arguments.clone(),
},
}
}
fn to_shared_tool_def(def: &ToolDefinition) -> tci::ToolDefinition {
tci::ToolDefinition {
kind: def.kind.clone(),
function: tci::FunctionDefinition {
name: def.function.name.clone(),
description: def.function.description.clone(),
parameters: def.function.parameters.clone(),
cache_control: def
.function
.cache_control
.as_ref()
.map(to_shared_cache_control),
},
}
}
fn to_shared_cache_control(cc: &CacheControl) -> tci::CacheControl {
tci::CacheControl {
kind: cc.kind.clone(),
}
}
fn to_shared_usage_directive(cfg: &RequestUsageConfig) -> tci::RequestUsageConfig {
tci::RequestUsageConfig {
include: cfg.include,
}
}
fn from_shared_choice(choice: &tci::ChatChoice) -> ChatChoice {
ChatChoice {
message: AssistantMessage {
content: choice.message.content.clone(),
tool_calls: choice
.message
.tool_calls
.iter()
.map(from_shared_tool_call)
.collect(),
},
finish_reason: choice.finish_reason.clone(),
}
}
fn from_shared_tool_call(call: &tci::ToolCall) -> ToolCall {
ToolCall {
id: call.id.clone(),
kind: call.kind.clone(),
function: FunctionCall {
name: call.function.name.clone(),
arguments: call.function.arguments.clone(),
},
}
}
#[cfg(test)]
mod tests {
use super::super::request::FunctionDefinition;
use super::*;
#[test]
fn to_shared_request_maps_all_fields() {
let req = ChatRequest {
model: "fireworks/accounts/fireworks/models/llama".into(),
messages: vec![ChatMessage::system("sys"), ChatMessage::user("hi")],
temperature: Some(0.0),
max_tokens: Some(4096),
tools: Some(vec![ToolDefinition::function(FunctionDefinition {
name: "search".into(),
description: Some("d".into()),
parameters: Some(serde_json::json!({"type": "object"})),
cache_control: None,
})]),
tool_choice: Some(serde_json::json!("auto")),
usage: Some(RequestUsageConfig::detailed()),
};
let shared = to_shared_request(&req, "accounts/fireworks/models/llama".into());
assert_eq!(shared.model, "accounts/fireworks/models/llama");
assert_eq!(shared.messages.len(), 2);
assert_eq!(shared.messages[0].role, "system");
assert_eq!(shared.temperature, Some(0.0));
assert_eq!(shared.max_tokens, Some(4096));
assert_eq!(shared.tools.as_ref().unwrap().len(), 1);
assert_eq!(shared.tools.as_ref().unwrap()[0].function.name, "search");
assert_eq!(shared.tool_choice, Some(serde_json::json!("auto")));
assert!(shared.stop.is_none());
assert_eq!(
shared.usage,
Some(tci::RequestUsageConfig { include: true })
);
}
#[test]
fn cache_control_carries_through() {
let mut msg = ChatMessage::system("prefix");
msg.cache_control = Some(CacheControl::ephemeral());
let tool = ToolDefinition::function(FunctionDefinition {
name: "write_file".into(),
description: None,
parameters: None,
cache_control: Some(CacheControl::ephemeral()),
});
let req = ChatRequest {
model: "anthropic/claude-sonnet-4-5".into(),
messages: vec![msg],
temperature: None,
max_tokens: None,
tools: Some(vec![tool]),
tool_choice: None,
usage: None,
};
let shared = to_shared_request(&req, "anthropic/claude-sonnet-4-5".into());
assert!(shared.messages[0].cache_control.is_some());
assert!(
shared.tools.as_ref().unwrap()[0]
.function
.cache_control
.is_some()
);
let v = serde_json::to_value(&shared.messages[0]).expect("serialise");
assert_eq!(
v["content"],
serde_json::json!([{
"type": "text",
"text": "prefix",
"cache_control": {"type": "ephemeral"}
}])
);
}
#[test]
fn from_shared_response_maps_all_fields() {
let fixture = r#"{
"id": "gen-1",
"model": "openai/gpt-4o-mini",
"choices": [{"message": {"role": "assistant", "content": null,
"tool_calls": [{"id": "c1", "type": "function",
"function": {"name": "bash", "arguments": "{}"}}]},
"finish_reason": "tool_calls"}],
"usage": {"prompt_tokens": 12, "completion_tokens": 3, "total_tokens": 15,
"cache_read_input_tokens": 4, "cache_creation_input_tokens": 1}
}"#;
let shared: tci::ChatResponse = serde_json::from_str(fixture).expect("deserialise");
let resp = from_shared_response(shared);
assert_eq!(resp.id, "gen-1");
assert_eq!(resp.resolved_model("asked"), "openai/gpt-4o-mini");
assert!(resp.first_text().is_none());
assert_eq!(resp.first_tool_calls().len(), 1);
assert_eq!(resp.first_tool_calls()[0].function.name, "bash");
assert_eq!(resp.finish_reason(), Some("tool_calls"));
let usage = resp.token_usage();
assert_eq!(usage.prompt_tokens, 12);
assert_eq!(usage.cache_read_tokens, 4);
assert_eq!(usage.cache_creation_tokens, 1);
}
#[test]
fn usage_block_round_trips() {
let fixture = r#"{
"id": "z", "choices": [],
"usage": {"prompt_tokens": 1200, "completion_tokens": 80,
"prompt_tokens_details": {"cached_tokens": 900, "cache_write_tokens": 300},
"cost": 0.00123}
}"#;
let shared: tci::ChatResponse = serde_json::from_str(fixture).expect("deserialise");
let usage = from_shared_response(shared).token_usage();
assert_eq!(usage.cache_read_tokens, 900);
assert_eq!(usage.cache_creation_tokens, 300);
assert_eq!(usage.cost_usd, Some(0.00123));
}
#[test]
fn map_error_preserves_api_status() {
let err = map_error(tci::InferenceError::Api {
status: 429,
body: "slow down".into(),
});
match err {
LlmError::ApiError { status, body } => {
assert_eq!(status, 429);
assert_eq!(body, "slow down");
}
other => panic!("expected ApiError, got {other:?}"),
}
}
#[test]
fn map_error_maps_missing_credential() {
let err = map_error(tci::InferenceError::MissingCredential {
provider: tci::ProviderId::OpenRouter,
});
match err {
LlmError::MissingConfig(msg) => assert!(msg.contains("openrouter"), "{msg}"),
other => panic!("expected MissingConfig, got {other:?}"),
}
}
#[test]
fn map_error_wraps_other() {
let err = map_error(tci::InferenceError::Transport("connection refused".into()));
match err {
LlmError::Inference(msg) => assert!(msg.contains("connection refused"), "{msg}"),
other => panic!("expected Inference, got {other:?}"),
}
}
}