use super::*;
impl StepFunProvider {
pub(super) fn build_payload(&self, request: &LLMRequest, stream: bool) -> Result<Value, LLMError> {
let mut instructions_segments: Vec<String> = Vec::new();
if let Some(system_prompt) = &request.system_prompt {
let trimmed = system_prompt.trim();
if !trimmed.is_empty() {
instructions_segments.push(trimmed.to_owned());
}
}
let mut input: Vec<Value> = Vec::new();
let mut active_tool_calls: HashSet<String> = HashSet::new();
let mut deferred_tool_outputs: HashMap<String, String> = HashMap::new();
for (index, message) in request.messages.iter().enumerate() {
match message.role {
MessageRole::System => {
let text = message.content.as_text();
let trimmed = text.trim();
if !trimmed.is_empty() {
instructions_segments.push(trimmed.to_owned());
}
}
MessageRole::User => {
let parts = user_content_parts(&message.content);
if !parts.is_empty() {
input.push(json!({"role": "user", "content": parts}));
}
}
MessageRole::Assistant => {
let text = message.content.as_text();
if !text.trim().is_empty() {
input.push(json!({"role": "assistant", "content": text.to_string()}));
}
if let Some(tool_calls) = &message.tool_calls {
for (call_index, call) in tool_calls.iter().enumerate() {
let Some(function) = &call.function else {
continue;
};
input.push(json!({
"type": "function_call",
"id": format!("fc_{index}_{call_index}"),
"call_id": call.id,
"name": function.name,
"arguments": function.arguments,
}));
active_tool_calls.insert(call.id.clone());
if let Some(output) = deferred_tool_outputs.remove(&call.id) {
active_tool_calls.remove(&call.id);
input.push(json!({
"type": "function_call_output",
"call_id": call.id,
"output": output,
}));
}
}
}
}
MessageRole::Tool => {
let Some(call_id) = message.tool_call_id.as_ref() else {
return Err(LLMError::InvalidRequest {
message: error_display::format_llm_error(
PROVIDER_NAME,
"Tool messages must include tool_call_id for the Responses API",
),
metadata: None,
});
};
let output = function_output_string(function_output_value_from_message_content(&message.content));
if active_tool_calls.remove(call_id) {
input.push(json!({
"type": "function_call_output",
"call_id": call_id,
"output": output,
}));
} else {
deferred_tool_outputs.insert(call_id.clone(), output);
}
}
}
}
for call_id in active_tool_calls {
input.push(json!({
"type": "function_call_output",
"call_id": call_id,
"output": "aborted",
}));
}
let mut payload = json!({
"model": request.model,
"input": input,
"stream": stream,
});
if !instructions_segments.is_empty() {
payload["instructions"] = json!(instructions_segments.join("\n\n"));
}
let reasoning_active = request
.reasoning_effort
.is_some_and(|effort| effort != ReasoningEffortLevel::None);
if !reasoning_active {
if let Some(temperature) = request.temperature {
payload["temperature"] = json!(sampling_param_f64(temperature));
}
if let Some(top_p) = request.top_p {
payload["top_p"] = json!(sampling_param_f64(top_p));
}
}
if let Some(max_tokens) = request.max_tokens {
payload["max_output_tokens"] = json!(max_tokens);
}
if let Some(effort) = request.reasoning_effort.and_then(reasoning_effort_value) {
payload["reasoning"] = json!({"effort": effort});
}
if !matches!(request.tool_choice, Some(ToolChoice::None))
&& let Some(tools) = &request.tools
{
let serialized = serialize_tools(tools);
if !serialized.is_empty() {
payload["tools"] = Value::Array(serialized);
payload["tool_choice"] = json!("auto");
}
}
if let Some(output_format) = &request.output_format {
payload["text"] = json!({"format": text_format_from_output_format(output_format)});
}
Ok(payload)
}
pub(super) fn parse_response(response_json: Value, model: String) -> Result<LLMResponse, LLMError> {
let output = response_json
.get("output")
.and_then(Value::as_array)
.ok_or_else(|| LLMError::Provider {
message: error_display::format_llm_error(PROVIDER_NAME, "Invalid response: missing output array"),
metadata: None,
})?;
let status = response_json.get("status").and_then(Value::as_str).unwrap_or("completed");
if status == "failed" {
let message = response_json
.get("error")
.and_then(|error| error.get("message"))
.and_then(Value::as_str)
.unwrap_or("Response generation failed");
return Err(LLMError::Provider {
message: error_display::format_llm_error(PROVIDER_NAME, message),
metadata: None,
});
}
let mut content = String::new();
let mut reasoning = String::new();
let mut tool_calls = Vec::new();
let mut tool_references = Vec::new();
for item in output {
let item_type = item.get("type").and_then(Value::as_str).unwrap_or("");
match item_type {
"message" => {
if let Some(content_parts) = item.get("content").and_then(Value::as_array) {
for part in content_parts {
if let Some(text) = part.get("text").and_then(Value::as_str) {
content.push_str(text);
}
}
}
}
"function_call" => {
let call_id = item
.get("call_id")
.and_then(Value::as_str)
.or_else(|| item.get("id").and_then(Value::as_str))
.unwrap_or("")
.to_string();
let name = item.get("name").and_then(Value::as_str).unwrap_or("").to_string();
let arguments = item
.get("arguments")
.map(|value| {
if value.is_string() {
value.as_str().unwrap_or("{}").to_string()
} else {
value.to_string()
}
})
.unwrap_or_else(|| "{}".to_string());
tool_calls.push(crate::provider::ToolCall::function(call_id, name, arguments));
}
"reasoning" => {
if let Some(text) = item.get("content").and_then(Value::as_str) {
content_reasoning_append(&mut reasoning, text);
}
if let Some(summary) = item.get("summary").and_then(Value::as_array) {
for part in summary {
if let Some(text) = part.get("text").and_then(Value::as_str) {
content_reasoning_append(&mut reasoning, text);
}
}
}
}
"tool_search_output" => {
crate::providers::shared::collect_tool_references_from_tool_search_output(
item,
&mut tool_references,
);
}
_ => {}
}
}
let finish_reason = if !tool_calls.is_empty() {
FinishReason::ToolCalls
} else {
match status {
"incomplete" => FinishReason::Length,
_ => FinishReason::Stop,
}
};
let usage = response_json.get("usage").map(|usage_value| Usage {
prompt_tokens: usage_value
.get("input_tokens")
.or_else(|| usage_value.get("prompt_tokens"))
.and_then(Value::as_u64)
.and_then(|value| u32::try_from(value).ok())
.unwrap_or(0),
completion_tokens: usage_value
.get("output_tokens")
.or_else(|| usage_value.get("completion_tokens"))
.and_then(Value::as_u64)
.and_then(|value| u32::try_from(value).ok())
.unwrap_or(0),
total_tokens: usage_value
.get("total_tokens")
.and_then(Value::as_u64)
.and_then(|value| u32::try_from(value).ok())
.unwrap_or(0),
cached_prompt_tokens: None,
cache_creation_tokens: None,
cache_read_tokens: None,
iterations: None,
});
Ok(LLMResponse {
content: (!content.is_empty()).then_some(content),
tool_calls: (!tool_calls.is_empty()).then_some(tool_calls),
model,
usage,
finish_reason,
reasoning: (!reasoning.is_empty()).then_some(reasoning),
reasoning_details: None,
tool_references,
request_id: response_json.get("id").and_then(Value::as_str).map(ToOwned::to_owned),
organization_id: None,
compaction: None,
})
}
}