Skip to main content

vtcode_llm/providers/stepfun/
mod.rs

1//! StepFun provider backed by the native Responses API
2//! (`POST {base}/responses`).
3//!
4//! StepFun's `/responses` surface is wire-compatible with the OpenAI Responses
5//! API: history is replayed as `input` items (`message`, `function_call`,
6//! `function_call_output`), the system prompt travels as top-level
7//! `instructions`, reasoning effort is encoded as `reasoning.effort`, and the
8//! output-token budget uses `max_output_tokens`.
9//!
10//! This replaces the previous chat-completions implementation. The provider
11//! keeps the registration contract expected by `impl_standard_provider_constructor!`
12//! (type name + 7-argument `from_config`) and reuses the shared Responses
13//! streaming adapter so normalized stream events stay consistent with the native
14//! OpenAI provider.
15
16use crate::error_display;
17use crate::provider::{
18    FinishReason, LLMError, LLMNormalizedStream, LLMProvider, LLMRequest, LLMResponse, LLMStream, LLMStreamEvent,
19    MessageContent, MessageRole, ToolChoice, ToolDefinition, Usage,
20};
21use crate::providers::common::{
22    ensure_model, impl_llm_client, override_base_url, parse_json_response, read_provider_error_body, resolve_model,
23    sampling_param_f64, validate_supported_models,
24};
25use crate::providers::error_handling::{format_network_error, format_parse_error};
26use crate::providers::openai::tool_serialization::sanitize_openai_function_parameters;
27use crate::providers::shared::{
28    ResponsesNormalizedStreamOptions, StreamAggregator, Utf8StreamDecoder, create_responses_normalized_stream,
29    drain_and_bound_sse_tail, extract_data_payload, find_sse_boundary_bytes,
30    function_output_value_from_message_content,
31};
32use async_stream::try_stream;
33use async_trait::async_trait;
34use futures::StreamExt;
35use reqwest::Client as HttpClient;
36use serde_json::{Value, json};
37use std::collections::{HashMap, HashSet};
38use vtcode_config::TimeoutsConfig;
39use vtcode_config::constants::{env_vars, models, urls};
40use vtcode_config::core::{AnthropicConfig, ModelConfig, PromptCachingConfig};
41use vtcode_config::types::ReasoningEffortLevel;
42
43const PROVIDER_NAME: &str = "StepFun";
44const PROVIDER_KEY: &str = "stepfun";
45const LEGACY_API_KEY_ENV: &str = "STEP_API_KEY";
46
47/// Maps VT Code's effort ladder onto StepFun's `reasoning.effort` vocabulary.
48fn reasoning_effort_value(effort: ReasoningEffortLevel) -> Option<&'static str> {
49    match effort {
50        ReasoningEffortLevel::None | ReasoningEffortLevel::Unknown => None,
51        ReasoningEffortLevel::Minimal | ReasoningEffortLevel::Low => Some("low"),
52        ReasoningEffortLevel::Medium => Some("medium"),
53        ReasoningEffortLevel::High | ReasoningEffortLevel::XHigh | ReasoningEffortLevel::Max => Some("high"),
54    }
55}
56
57/// Render one user/assistant content block list for the `input` array.
58fn user_content_parts(content: &MessageContent) -> Vec<Value> {
59    use crate::provider::ContentPart;
60
61    let mut parts = Vec::new();
62    match content {
63        MessageContent::Text(text) => {
64            if !text.trim().is_empty() {
65                parts.push(json!({"type": "input_text", "text": text}));
66            }
67        }
68        MessageContent::Parts(content_parts) => {
69            for part in content_parts {
70                match part {
71                    ContentPart::Text { text } => {
72                        if !text.trim().is_empty() {
73                            parts.push(json!({"type": "input_text", "text": text}));
74                        }
75                    }
76                    ContentPart::Image { data, mime_type, image_url, detail, .. } => {
77                        let image_url = match image_url {
78                            Some(url) => url.clone(),
79                            None => format!("data:{mime_type};base64,{data}"),
80                        };
81                        let mut image_part = json!({"type": "input_image", "image_url": image_url});
82                        if let Some(detail) = detail {
83                            image_part["detail"] = json!(detail.as_str());
84                        }
85                        parts.push(image_part);
86                    }
87                    ContentPart::File { filename, file_id, file_url, .. } => {
88                        // StepFun documents no file input block for the Responses
89                        // API; degrade to a text note rather than sending an
90                        // unsupported payload the server would reject.
91                        let fallback = filename
92                            .clone()
93                            .or_else(|| file_id.clone())
94                            .or_else(|| file_url.clone())
95                            .unwrap_or_else(|| "attached file".to_string());
96                        parts.push(json!({
97                            "type": "input_text",
98                            "text": format!("[File input not directly supported: {fallback}]")
99                        }));
100                    }
101                }
102            }
103        }
104    }
105    parts
106}
107
108/// `function_call_output.output` must be a string on the StepFun wire.
109fn function_output_string(value: Value) -> String {
110    match value {
111        Value::String(text) => text,
112        other => other.to_string(),
113    }
114}
115
116/// Flatten VT Code tool definitions into StepFun's `function` tool shape.
117fn serialize_tools(tools: &[ToolDefinition]) -> Vec<Value> {
118    tools
119        .iter()
120        .filter_map(|tool| {
121            let function = tool.function.as_ref()?;
122            let mut serialized = json!({
123                "type": "function",
124                "name": function.name,
125                "description": function.description,
126                "parameters": sanitize_openai_function_parameters(function.parameters.clone(), true),
127            });
128            if tool.strict == Some(true) {
129                serialized["strict"] = json!(true);
130            }
131            Some(serialized)
132        })
133        .collect()
134}
135
136/// Map VT Code's provider-agnostic `output_format` onto StepFun's
137/// `text.format` descriptor.
138fn text_format_from_output_format(output_format: &Value) -> Value {
139    if let Some(json_schema) = output_format.get("json_schema") {
140        let name = json_schema.get("name").and_then(Value::as_str).unwrap_or("response");
141        let schema = json_schema.get("schema").cloned().unwrap_or_else(|| json!({"type": "object"}));
142        return json!({"type": "json_schema", "name": name, "schema": schema});
143    }
144
145    if let Some(format_type) = output_format.get("type").and_then(Value::as_str) {
146        if format_type == "json_schema"
147            && let Some(schema) = output_format.get("schema")
148        {
149            let name = output_format.get("name").and_then(Value::as_str).unwrap_or("response");
150            return json!({"type": "json_schema", "name": name, "schema": schema});
151        }
152        if format_type == "json_object" {
153            return json!({"type": "json_object"});
154        }
155    }
156
157    json!({"type": "json_object"})
158}
159
160pub struct StepFunProvider {
161    http_client: HttpClient,
162    base_url: String,
163    model: String,
164    api_key: String,
165    model_behavior: Option<ModelConfig>,
166}
167
168impl StepFunProvider {
169    pub fn new(api_key: String) -> Self {
170        Self::with_model(api_key, models::stepfun::DEFAULT_MODEL.to_string())
171    }
172
173    pub fn with_model(api_key: String, model: String) -> Self {
174        Self::with_model_internal(api_key, model, None, TimeoutsConfig::default(), None)
175    }
176
177    pub fn new_with_client(
178        api_key: String,
179        model: String,
180        http_client: HttpClient,
181        base_url: String,
182        _timeouts: TimeoutsConfig,
183    ) -> Self {
184        Self {
185            http_client,
186            base_url,
187            model,
188            api_key,
189            model_behavior: None,
190        }
191    }
192
193    pub fn from_config(
194        api_key: Option<String>,
195        model: Option<String>,
196        base_url: Option<String>,
197        _prompt_cache: Option<PromptCachingConfig>,
198        timeouts: Option<TimeoutsConfig>,
199        _anthropic: Option<AnthropicConfig>,
200        model_behavior: Option<ModelConfig>,
201    ) -> Self {
202        let api_key = resolve_api_key(api_key);
203        let resolved_model = resolve_model(model, models::stepfun::DEFAULT_MODEL);
204        Self::with_model_internal(api_key, resolved_model, base_url, timeouts.unwrap_or_default(), model_behavior)
205    }
206
207    fn with_model_internal(
208        api_key: String,
209        model: String,
210        base_url: Option<String>,
211        timeouts: TimeoutsConfig,
212        model_behavior: Option<ModelConfig>,
213    ) -> Self {
214        use crate::http_client::HttpClientFactory;
215
216        Self {
217            http_client: HttpClientFactory::for_llm(&timeouts),
218            base_url: override_base_url(urls::STEPFUN_API_BASE, base_url, Some(env_vars::STEPFUN_BASE_URL)),
219            model,
220            api_key,
221            model_behavior,
222        }
223    }
224
225    fn responses_url(&self) -> String {
226        format!("{}/responses", self.base_url.trim_end_matches('/'))
227    }
228
229    fn reasoning_enabled(model: &str) -> bool {
230        models::stepfun::REASONING_MODELS.contains(&model)
231    }
232
233    fn model_behavior_flag(
234        model_behavior: Option<&ModelConfig>,
235        select: impl Fn(&ModelConfig) -> Option<bool>,
236    ) -> bool {
237        model_behavior.and_then(select).unwrap_or(false)
238    }
239
240    /// Builds the `/responses` request payload.
241    fn build_payload(&self, request: &LLMRequest, stream: bool) -> Result<Value, LLMError> {
242        let mut instructions_segments: Vec<String> = Vec::new();
243        if let Some(system_prompt) = &request.system_prompt {
244            let trimmed = system_prompt.trim();
245            if !trimmed.is_empty() {
246                instructions_segments.push(trimmed.to_owned());
247            }
248        }
249
250        let mut input: Vec<Value> = Vec::new();
251        let mut active_tool_calls: HashSet<String> = HashSet::new();
252        let mut deferred_tool_outputs: HashMap<String, String> = HashMap::new();
253
254        for (index, message) in request.messages.iter().enumerate() {
255            match message.role {
256                MessageRole::System => {
257                    let text = message.content.as_text();
258                    let trimmed = text.trim();
259                    if !trimmed.is_empty() {
260                        instructions_segments.push(trimmed.to_owned());
261                    }
262                }
263                MessageRole::User => {
264                    let parts = user_content_parts(&message.content);
265                    if !parts.is_empty() {
266                        input.push(json!({"role": "user", "content": parts}));
267                    }
268                }
269                MessageRole::Assistant => {
270                    let text = message.content.as_text();
271                    if !text.trim().is_empty() {
272                        input.push(json!({"role": "assistant", "content": text.to_string()}));
273                    }
274
275                    if let Some(tool_calls) = &message.tool_calls {
276                        for (call_index, call) in tool_calls.iter().enumerate() {
277                            let Some(function) = &call.function else {
278                                continue;
279                            };
280
281                            input.push(json!({
282                                "type": "function_call",
283                                "id": format!("fc_{index}_{call_index}"),
284                                "call_id": call.id,
285                                "name": function.name,
286                                "arguments": function.arguments,
287                            }));
288                            active_tool_calls.insert(call.id.clone());
289
290                            if let Some(output) = deferred_tool_outputs.remove(&call.id) {
291                                active_tool_calls.remove(&call.id);
292                                input.push(json!({
293                                    "type": "function_call_output",
294                                    "call_id": call.id,
295                                    "output": output,
296                                }));
297                            }
298                        }
299                    }
300                }
301                MessageRole::Tool => {
302                    let Some(call_id) = message.tool_call_id.as_ref() else {
303                        return Err(LLMError::InvalidRequest {
304                            message: error_display::format_llm_error(
305                                PROVIDER_NAME,
306                                "Tool messages must include tool_call_id for the Responses API",
307                            ),
308                            metadata: None,
309                        });
310                    };
311                    let output = function_output_string(function_output_value_from_message_content(&message.content));
312
313                    if active_tool_calls.remove(call_id) {
314                        input.push(json!({
315                            "type": "function_call_output",
316                            "call_id": call_id,
317                            "output": output,
318                        }));
319                    } else {
320                        deferred_tool_outputs.insert(call_id.clone(), output);
321                    }
322                }
323            }
324        }
325
326        // Every replayed `function_call` needs a paired output; synthesize one
327        // so a partially paired history cannot fail replay.
328        for call_id in active_tool_calls {
329            input.push(json!({
330                "type": "function_call_output",
331                "call_id": call_id,
332                "output": "aborted",
333            }));
334        }
335
336        let mut payload = json!({
337            "model": request.model,
338            "input": input,
339            "stream": stream,
340        });
341
342        if !instructions_segments.is_empty() {
343            payload["instructions"] = json!(instructions_segments.join("\n\n"));
344        }
345
346        let reasoning_active = request
347            .reasoning_effort
348            .is_some_and(|effort| effort != ReasoningEffortLevel::None);
349        if !reasoning_active {
350            if let Some(temperature) = request.temperature {
351                payload["temperature"] = json!(sampling_param_f64(temperature));
352            }
353            if let Some(top_p) = request.top_p {
354                payload["top_p"] = json!(sampling_param_f64(top_p));
355            }
356        }
357
358        if let Some(max_tokens) = request.max_tokens {
359            payload["max_output_tokens"] = json!(max_tokens);
360        }
361
362        if let Some(effort) = request.reasoning_effort.and_then(reasoning_effort_value) {
363            payload["reasoning"] = json!({"effort": effort});
364        }
365
366        // StepFun accepts only tool_choice=auto. Omit callable definitions
367        // for tool-free synthesis instead of silently enabling tool use.
368        if !matches!(request.tool_choice, Some(ToolChoice::None))
369            && let Some(tools) = &request.tools
370        {
371            let serialized = serialize_tools(tools);
372            if !serialized.is_empty() {
373                payload["tools"] = Value::Array(serialized);
374                payload["tool_choice"] = json!("auto");
375            }
376        }
377
378        if let Some(output_format) = &request.output_format {
379            payload["text"] = json!({"format": text_format_from_output_format(output_format)});
380        }
381
382        Ok(payload)
383    }
384
385    /// Parses a non-streaming `/responses` body (also used as the final-event
386    /// parser for normalized streaming).
387    fn parse_response(response_json: Value, model: String) -> Result<LLMResponse, LLMError> {
388        let output = response_json
389            .get("output")
390            .and_then(Value::as_array)
391            .ok_or_else(|| LLMError::Provider {
392                message: error_display::format_llm_error(PROVIDER_NAME, "Invalid response: missing output array"),
393                metadata: None,
394            })?;
395
396        let status = response_json.get("status").and_then(Value::as_str).unwrap_or("completed");
397        if status == "failed" {
398            let message = response_json
399                .get("error")
400                .and_then(|error| error.get("message"))
401                .and_then(Value::as_str)
402                .unwrap_or("Response generation failed");
403            return Err(LLMError::Provider {
404                message: error_display::format_llm_error(PROVIDER_NAME, message),
405                metadata: None,
406            });
407        }
408
409        let mut content = String::new();
410        let mut reasoning = String::new();
411        let mut tool_calls = Vec::new();
412        let mut tool_references = Vec::new();
413
414        for item in output {
415            let item_type = item.get("type").and_then(Value::as_str).unwrap_or("");
416            match item_type {
417                "message" => {
418                    if let Some(content_parts) = item.get("content").and_then(Value::as_array) {
419                        for part in content_parts {
420                            if let Some(text) = part.get("text").and_then(Value::as_str) {
421                                content.push_str(text);
422                            }
423                        }
424                    }
425                }
426                "function_call" => {
427                    let call_id = item
428                        .get("call_id")
429                        .and_then(Value::as_str)
430                        .or_else(|| item.get("id").and_then(Value::as_str))
431                        .unwrap_or("")
432                        .to_string();
433                    let name = item.get("name").and_then(Value::as_str).unwrap_or("").to_string();
434                    let arguments = item
435                        .get("arguments")
436                        .map(|value| {
437                            if value.is_string() {
438                                value.as_str().unwrap_or("{}").to_string()
439                            } else {
440                                value.to_string()
441                            }
442                        })
443                        .unwrap_or_else(|| "{}".to_string());
444                    tool_calls.push(crate::provider::ToolCall::function(call_id, name, arguments));
445                }
446                "reasoning" => {
447                    if let Some(text) = item.get("content").and_then(Value::as_str) {
448                        content_reasoning_append(&mut reasoning, text);
449                    }
450                    if let Some(summary) = item.get("summary").and_then(Value::as_array) {
451                        for part in summary {
452                            if let Some(text) = part.get("text").and_then(Value::as_str) {
453                                content_reasoning_append(&mut reasoning, text);
454                            }
455                        }
456                    }
457                }
458                "tool_search_output" => {
459                    crate::providers::shared::collect_tool_references_from_tool_search_output(
460                        item,
461                        &mut tool_references,
462                    );
463                }
464                _ => {}
465            }
466        }
467
468        let finish_reason = if !tool_calls.is_empty() {
469            FinishReason::ToolCalls
470        } else {
471            match status {
472                "incomplete" => FinishReason::Length,
473                _ => FinishReason::Stop,
474            }
475        };
476
477        let usage = response_json.get("usage").map(|usage_value| Usage {
478            prompt_tokens: usage_value
479                .get("input_tokens")
480                .or_else(|| usage_value.get("prompt_tokens"))
481                .and_then(Value::as_u64)
482                .and_then(|value| u32::try_from(value).ok())
483                .unwrap_or(0),
484            completion_tokens: usage_value
485                .get("output_tokens")
486                .or_else(|| usage_value.get("completion_tokens"))
487                .and_then(Value::as_u64)
488                .and_then(|value| u32::try_from(value).ok())
489                .unwrap_or(0),
490            total_tokens: usage_value
491                .get("total_tokens")
492                .and_then(Value::as_u64)
493                .and_then(|value| u32::try_from(value).ok())
494                .unwrap_or(0),
495            // StepFun advertises no prompt-cache metrics; do not surface them.
496            cached_prompt_tokens: None,
497            cache_creation_tokens: None,
498            cache_read_tokens: None,
499            iterations: None,
500        });
501
502        Ok(LLMResponse {
503            content: (!content.is_empty()).then_some(content),
504            tool_calls: (!tool_calls.is_empty()).then_some(tool_calls),
505            model,
506            usage,
507            finish_reason,
508            reasoning: (!reasoning.is_empty()).then_some(reasoning),
509            reasoning_details: None,
510            tool_references,
511            request_id: response_json.get("id").and_then(Value::as_str).map(ToOwned::to_owned),
512            organization_id: None,
513            compaction: None,
514        })
515    }
516
517    async fn generate_request(&self, request: &LLMRequest) -> Result<LLMResponse, LLMError> {
518        let model = request.model.clone();
519        let payload = self.build_payload(request, false)?;
520
521        let response = self
522            .http_client
523            .post(self.responses_url())
524            .bearer_auth(&self.api_key)
525            .json(&payload)
526            .send()
527            .await
528            .map_err(|error| format_network_error(PROVIDER_NAME, &error))?;
529
530        if !response.status().is_success() {
531            let status = response.status();
532            let body = read_provider_error_body(response).await;
533            let formatted_error = error_display::format_llm_error(PROVIDER_NAME, &format!("HTTP {status}: {body}"));
534            return Err(LLMError::Provider { message: formatted_error, metadata: None });
535        }
536
537        let json = parse_json_response(response, PROVIDER_NAME).await?;
538        Self::parse_response(json, model)
539    }
540
541    /// Legacy `LLMStream` path over the StepFun Responses SSE wire.
542    async fn stream_request(&self, request: &LLMRequest) -> Result<LLMStream, LLMError> {
543        let model = request.model.clone();
544        let payload = self.build_payload(request, true)?;
545
546        let response = self
547            .http_client
548            .post(self.responses_url())
549            .bearer_auth(&self.api_key)
550            .json(&payload)
551            .send()
552            .await
553            .map_err(|error| format_network_error(PROVIDER_NAME, &error))?;
554
555        if !response.status().is_success() {
556            let status = response.status();
557            let body = read_provider_error_body(response).await;
558            let formatted_error = error_display::format_llm_error(PROVIDER_NAME, &format!("HTTP {status}: {body}"));
559            return Err(LLMError::Provider { message: formatted_error, metadata: None });
560        }
561
562        let stream = try_stream! {
563            let mut body_stream = response.bytes_stream();
564            let mut buffer: Vec<u8> = Vec::new();
565            let mut offset = 0usize;
566            let mut decoder = Utf8StreamDecoder::new();
567            let mut aggregator = StreamAggregator::new(model.clone());
568
569            while let Some(chunk_result) = body_stream.next().await {
570                let chunk = chunk_result.map_err(|error| format_network_error(PROVIDER_NAME, &error))?;
571                decoder.push_bytes(&chunk, &mut buffer);
572
573                while let Some((split_idx, delimiter_len)) = find_sse_boundary_bytes(&buffer, offset) {
574                    let event = std::str::from_utf8(&buffer[offset..split_idx]).expect("valid utf-8 stream data");
575                    offset = split_idx + delimiter_len;
576
577                    let Some(data_payload) = extract_data_payload(event) else {
578                        continue;
579                    };
580                    let trimmed = data_payload.trim();
581                    if trimmed.is_empty() || trimmed == "[DONE]" {
582                        continue;
583                    }
584
585                    let Ok(event) = serde_json::from_str::<Value>(trimmed) else {
586                        continue;
587                    };
588                    let event_type = event.get("type").and_then(Value::as_str).unwrap_or("");
589
590                    match event_type {
591                        "response.output_text.delta" => {
592                            if let Some(delta) = event.get("delta").and_then(Value::as_str) {
593                                for stream_event in aggregator.handle_content(delta) {
594                                    yield stream_event;
595                                }
596                            }
597                        }
598                        "response.reasoning.delta"
599                        | "response.reasoning_content.delta"
600                        | "response.reasoning_text.delta" => {
601                            if let Some(delta) = event.get("delta").and_then(Value::as_str)
602                                && let Some(delta) = aggregator.handle_reasoning(delta)
603                            {
604                                yield LLMStreamEvent::Reasoning { delta };
605                            }
606                        }
607                        "response.reasoning_text.done" => {
608                            let text = event
609                                .get("text")
610                                .and_then(Value::as_str)
611                                .or_else(|| event.get("delta").and_then(Value::as_str));
612                            if let Some(text) = text
613                                && let Some(delta) = aggregator.handle_reasoning(text)
614                            {
615                                yield LLMStreamEvent::Reasoning { delta };
616                            }
617                        }
618                        "response.function_call_arguments.delta" => {
619                            if let Some(delta) = event.get("delta").and_then(Value::as_str) {
620                                let call_id = event
621                                    .get("item_id")
622                                    .or_else(|| event.get("call_id"))
623                                    .and_then(Value::as_str)
624                                    .unwrap_or("");
625                                aggregator.handle_tool_calls(&[json!({
626                                    "index": event.get("output_index").and_then(Value::as_u64).unwrap_or(0),
627                                    "id": call_id,
628                                    "function": {"arguments": delta},
629                                })]);
630                            }
631                        }
632                        "response.output_item.done" => {
633                            if let Some(item) = event.get("item")
634                                && item.get("type").and_then(Value::as_str) == Some("compaction")
635                            {
636                                aggregator.append_reasoning_detail(item);
637                            }
638                        }
639                        "response.completed" => {
640                            let streamed = aggregator.finalize();
641                            let response = match event.get("response") {
642                                Some(response_value) => Self::parse_response(response_value.clone(), model.clone())
643                                    .unwrap_or(streamed),
644                                None => streamed,
645                            };
646                            yield LLMStreamEvent::Completed { response: Box::new(response) };
647                            return;
648                        }
649                        "response.incomplete" | "response.failed" => {
650                            let message = event
651                                .get("response")
652                                .and_then(|response| response.get("error"))
653                                .and_then(|error| error.get("message"))
654                                .and_then(Value::as_str)
655                                .unwrap_or("Response generation failed");
656                            Err(LLMError::Provider {
657                                message: error_display::format_llm_error(PROVIDER_NAME, message),
658                                metadata: None,
659                            })?;
660                        }
661                        "error" => {
662                            let message = event
663                                .get("error")
664                                .and_then(|error| error.get("message"))
665                                .and_then(Value::as_str)
666                                .unwrap_or("Unknown error from StepFun Responses API");
667                            Err(LLMError::Provider {
668                                message: error_display::format_llm_error(PROVIDER_NAME, message),
669                                metadata: None,
670                            })?;
671                        }
672                        _ => {}
673                    }
674                }
675
676                // Drain the consumed prefix and fail closed when the retained
677                // tail tops the shared SSE bound, so a peer that never emits
678                // an event boundary cannot grow memory for the stream lifetime.
679                drain_and_bound_sse_tail(&mut buffer, &mut offset).map_err(|overflow| LLMError::Provider {
680                    message: error_display::format_llm_error(PROVIDER_NAME, &overflow.to_string()),
681                    metadata: None,
682                })?;
683            }
684
685            yield LLMStreamEvent::Completed { response: Box::new(aggregator.finalize()) };
686        };
687
688        Ok(Box::pin(stream))
689    }
690}
691
692/// Appends a reasoning fragment, separating fragments with a blank line.
693fn content_reasoning_append(reasoning: &mut String, text: &str) {
694    if text.trim().is_empty() {
695        return;
696    }
697    if !reasoning.is_empty() {
698        reasoning.push_str("\n\n");
699    }
700    reasoning.push_str(text);
701}
702
703fn resolve_api_key(api_key: Option<String>) -> String {
704    api_key
705        .or_else(|| std::env::var("STEPFUN_API_KEY").ok().filter(|key| !key.trim().is_empty()))
706        .or_else(|| std::env::var(LEGACY_API_KEY_ENV).ok().filter(|key| !key.trim().is_empty()))
707        .unwrap_or_default()
708}
709
710#[async_trait]
711impl LLMProvider for StepFunProvider {
712    fn name(&self) -> &str {
713        PROVIDER_KEY
714    }
715
716    fn supports_streaming(&self) -> bool {
717        true
718    }
719
720    fn supports_non_streaming(&self, _model: &str) -> bool {
721        // `/responses` services `stream: false`; pinned so the runloop's
722        // stream-timeout fallback to non-streaming cannot silently regress.
723        true
724    }
725
726    fn supports_reasoning(&self, model: &str) -> bool {
727        let requested = if model.trim().is_empty() { &self.model } else { model };
728        Self::model_behavior_flag(self.model_behavior.as_ref(), |behavior| behavior.model_supports_reasoning)
729            || Self::reasoning_enabled(requested)
730    }
731
732    fn supports_reasoning_effort(&self, model: &str) -> bool {
733        let requested = if model.trim().is_empty() { &self.model } else { model };
734        Self::model_behavior_flag(self.model_behavior.as_ref(), |behavior| behavior.model_supports_reasoning_effort)
735            || Self::reasoning_enabled(requested)
736    }
737
738    fn supports_structured_output(&self, _model: &str) -> bool {
739        true
740    }
741
742    fn supports_vision(&self, _model: &str) -> bool {
743        true
744    }
745
746    fn effective_context_size(&self, model: &str) -> usize {
747        crate::provider::catalog_context_window(PROVIDER_KEY, model, 262_144)
748    }
749
750    fn supported_models(&self) -> Vec<String> {
751        models::stepfun::SUPPORTED_MODELS
752            .iter()
753            .map(|model| (*model).to_string())
754            .collect()
755    }
756
757    fn validate_request(&self, request: &LLMRequest) -> Result<(), LLMError> {
758        validate_supported_models(request, PROVIDER_NAME, PROVIDER_KEY, models::stepfun::SUPPORTED_MODELS)
759    }
760
761    async fn generate(&self, mut request: LLMRequest) -> Result<LLMResponse, LLMError> {
762        ensure_model(&mut request, &self.model);
763        self.validate_request(&request)?;
764        self.generate_request(&request).await
765    }
766
767    async fn stream(&self, mut request: LLMRequest) -> Result<LLMStream, LLMError> {
768        ensure_model(&mut request, &self.model);
769        self.validate_request(&request)?;
770        request.stream = true;
771        self.stream_request(&request).await
772    }
773
774    async fn stream_normalized(&self, mut request: LLMRequest) -> Result<LLMNormalizedStream, LLMError> {
775        ensure_model(&mut request, &self.model);
776        self.validate_request(&request)?;
777        request.stream = true;
778        let model = request.model.clone();
779        let payload = self.build_payload(&request, true)?;
780
781        let response = self
782            .http_client
783            .post(self.responses_url())
784            .bearer_auth(&self.api_key)
785            .json(&payload)
786            .send()
787            .await
788            .map_err(|error| format_network_error(PROVIDER_NAME, &error))?;
789
790        if !response.status().is_success() {
791            let status = response.status();
792            let body = read_provider_error_body(response).await;
793            let formatted_error = error_display::format_llm_error(PROVIDER_NAME, &format!("HTTP {status}: {body}"));
794            return Err(LLMError::Provider { message: formatted_error, metadata: None });
795        }
796
797        let emit_reasoning = self.supports_reasoning(&model);
798        Ok(create_responses_normalized_stream(
799            response,
800            ResponsesNormalizedStreamOptions {
801                provider_name: PROVIDER_NAME,
802                model: model.clone(),
803                emit_reasoning,
804                include_cached_prompt_metrics: false,
805                require_completion_event: false,
806                prefer_completed_text: false,
807            },
808            move |value| Self::parse_response(value, model.clone()),
809        ))
810    }
811}
812
813impl_llm_client!(StepFunProvider);
814
815#[cfg(test)]
816mod tests;