{"repo_name": "deepclaude", "file_name": "/deepclaude/src/main.rs", "inference_info": {"prefix_code": "//! DeepClaude - A high-performance LLM inference API and Chat UI that integrates DeepSeek R1's CoT reasoning traces with Anthropic Claude models..\n//!\n//! This application provides a REST API for chat interactions that:\n//! - Processes messages through DeepSeek R1 for reasoning\n//! - Uses Anthropic's Claude for final responses\n//! - Supports both streaming and non-streaming responses\n//! - Tracks token usage and costs\n//! - Provides detailed usage statistics\n//!\n//! The API requires authentication tokens for both services and\n//! supports custom configuration through a TOML config file.\n\nmod clients;\nmod config;\nmod error;\nmod handlers;\nmod models;\n\nuse crate::{config::Config, handlers::AppState};\nuse axum::routing::{post, Router};\nuse std::{net::SocketAddr, sync::Arc};\nuse tower_http::{\n cors::{Any, CorsLayer},\n trace::TraceLayer,\n};\nuse tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};\n\n/// Application entry point.\n///\n/// Sets up logging, loads configuration, and starts the HTTP server\n/// with the configured routes and middleware.\n///\n/// # Returns\n///\n/// * `anyhow::Result<()>` - Ok if server starts successfully, Err otherwise\n///\n/// # Errors\n///\n/// Returns an error if:\n/// - Logging setup fails\n/// - Server address binding fails\n/// - Server encounters a fatal error while running\n#[tokio::main]\n", "suffix_code": "\n", "middle_code": "async fn main() -> anyhow::Result<()> {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env()\n .unwrap_or_else(|_| \"deepclaude=debug,tower_http=debug\".into()),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n let config = Config::load().unwrap_or_else(|_| {\n tracing::warn!(\"Failed to load config.toml, using default configuration\");\n Config::default()\n });\n let config_clone = config.clone();\n let state = Arc::new(AppState { config: config_clone });\n let cors = CorsLayer::new()\n .allow_methods(Any)\n .allow_headers(Any)\n .allow_origin(Any);\n let app = Router::new()\n .route(\"/\", post(handlers::handle_chat))\n .layer(TraceLayer::new_for_http())\n .layer(cors)\n .with_state(state);\n let addr: SocketAddr = format!(\"{}:{}\", config.server.host, config.server.port)\n .parse()\n .expect(\"Invalid host/port configuration\");\n tracing::info!(\"Starting server on {}\", addr);\n axum::serve(\n tokio::net::TcpListener::bind(&addr).await?,\n app.into_make_service(),\n )\n .await?;\n Ok(())\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "rust", "sub_task_type": null}, "context_code": [["/deepclaude/src/handlers.rs", "//! Request handlers for the API endpoints.\n//!\n//! This module contains the main request handlers and supporting functions\n//! for processing chat requests, including both streaming and non-streaming\n//! responses. It coordinates between different AI models and handles\n//! usage tracking and cost calculations.\n\nuse crate::{\n clients::{AnthropicClient, DeepSeekClient},\n config::Config,\n error::{ApiError, Result, SseResponse},\n models::{\n ApiRequest, ApiResponse, ContentBlock, CombinedUsage, DeepSeekUsage, AnthropicUsage,\n ExternalApiResponse, Message, Role, StreamEvent,\n },\n};\nuse axum::{\n extract::State,\n response::{sse::Event, IntoResponse},\n Json,\n};\nuse chrono::Utc;\nuse futures::StreamExt;\nuse std::{sync::Arc, collections::HashMap};\nuse tokio_stream::wrappers::ReceiverStream;\n\n/// Application state shared across request handlers.\n///\n/// Contains configuration that needs to be accessible\n/// to all request handlers.\npub struct AppState {\n pub config: Config,\n}\n\n/// Extracts API tokens from request headers.\n///\n/// # Arguments\n///\n/// * `headers` - The HTTP headers containing the API tokens\n///\n/// # Returns\n///\n/// * `Result<(String, String)>` - A tuple of (DeepSeek token, Anthropic token)\n///\n/// # Errors\n///\n/// Returns `ApiError::MissingHeader` if either token is missing\n/// Returns `ApiError::BadRequest` if tokens are malformed\nfn extract_api_tokens(\n headers: &axum::http::HeaderMap,\n) -> Result<(String, String)> {\n let deepseek_token = headers\n .get(\"X-DeepSeek-API-Token\")\n .ok_or_else(|| ApiError::MissingHeader { \n header: \"X-DeepSeek-API-Token\".to_string() \n })?\n .to_str()\n .map_err(|_| ApiError::BadRequest { \n message: \"Invalid DeepSeek API token\".to_string() \n })?\n .to_string();\n\n let anthropic_token = headers\n .get(\"X-Anthropic-API-Token\")\n .ok_or_else(|| ApiError::MissingHeader { \n header: \"X-Anthropic-API-Token\".to_string() \n })?\n .to_str()\n .map_err(|_| ApiError::BadRequest { \n message: \"Invalid Anthropic API token\".to_string() \n })?\n .to_string();\n\n Ok((deepseek_token, anthropic_token))\n}\n\n/// Calculates the cost of DeepSeek API usage.\n///\n/// # Arguments\n///\n/// * `input_tokens` - Number of input tokens processed\n/// * `output_tokens` - Number of output tokens generated\n/// * `_reasoning_tokens` - Number of tokens used for reasoning\n/// * `cached_tokens` - Number of tokens retrieved from cache\n/// * `config` - Configuration containing pricing information\n///\n/// # Returns\n///\n/// The total cost in dollars for the API usage\nfn calculate_deepseek_cost(\n input_tokens: u32,\n output_tokens: u32,\n _reasoning_tokens: u32,\n cached_tokens: u32,\n config: &Config,\n) -> f64 {\n let cache_hit_cost = (cached_tokens as f64 / 1_000_000.0) * config.pricing.deepseek.input_cache_hit_price;\n let cache_miss_cost = ((input_tokens - cached_tokens) as f64 / 1_000_000.0) * config.pricing.deepseek.input_cache_miss_price;\n let output_cost = (output_tokens as f64 / 1_000_000.0) * config.pricing.deepseek.output_price;\n \n cache_hit_cost + cache_miss_cost + output_cost\n}\n\n/// Calculates the cost of Anthropic API usage.\n///\n/// # Arguments\n///\n/// * `model` - The specific Claude model used\n/// * `input_tokens` - Number of input tokens processed\n/// * `output_tokens` - Number of output tokens generated\n/// * `cache_write_tokens` - Number of tokens written to cache\n/// * `cache_read_tokens` - Number of tokens read from cache\n/// * `config` - Configuration containing pricing information\n///\n/// # Returns\n///\n/// The total cost in dollars for the API usage\nfn calculate_anthropic_cost(\n model: &str,\n input_tokens: u32,\n output_tokens: u32,\n cache_write_tokens: u32,\n cache_read_tokens: u32,\n config: &Config,\n) -> f64 {\n let pricing = if model.contains(\"claude-3-5-sonnet\") {\n &config.pricing.anthropic.claude_3_sonnet\n } else if model.contains(\"claude-3-5-haiku\") {\n &config.pricing.anthropic.claude_3_haiku\n } else if model.contains(\"claude-3-opus\") {\n &config.pricing.anthropic.claude_3_opus\n } else {\n &config.pricing.anthropic.claude_3_sonnet // default to sonnet pricing\n };\n\n let input_cost = (input_tokens as f64 / 1_000_000.0) * pricing.input_price;\n let output_cost = (output_tokens as f64 / 1_000_000.0) * pricing.output_price;\n let cache_write_cost = (cache_write_tokens as f64 / 1_000_000.0) * pricing.cache_write_price;\n let cache_read_cost = (cache_read_tokens as f64 / 1_000_000.0) * pricing.cache_read_price;\n\n input_cost + output_cost + cache_write_cost + cache_read_cost\n}\n\n/// Formats a cost value as a dollar amount string.\n///\n/// # Arguments\n///\n/// * `cost` - The cost value to format\n///\n/// # Returns\n///\n/// A string representing the cost with 3 decimal places and $ prefix\nfn format_cost(cost: f64) -> String {\n format!(\"${:.3}\", cost)\n}\n\n/// Main handler for chat requests.\n///\n/// Routes requests to either streaming or non-streaming handlers\n/// based on the request configuration.\n///\n/// # Arguments\n///\n/// * `state` - Application state containing configuration\n/// * `headers` - HTTP request headers\n/// * `request` - The parsed chat request\n///\n/// # Returns\n///\n/// * `Result` - The API response or an error\npub async fn handle_chat(\n state: State>,\n headers: axum::http::HeaderMap,\n Json(request): Json,\n) -> Result {\n if request.stream {\n let stream_response = chat_stream(state, headers, Json(request)).await?;\n Ok(stream_response.into_response())\n } else {\n let json_response = chat(state, headers, Json(request)).await?;\n Ok(json_response.into_response())\n }\n}\n\n/// Handler for non-streaming chat requests.\n///\n/// Processes the request through both AI models sequentially,\n/// combining their responses and tracking usage.\n///\n/// # Arguments\n///\n/// * `state` - Application state containing configuration\n/// * `headers` - HTTP request headers\n/// * `request` - The parsed chat request\n///\n/// # Returns\n///\n/// * `Result>` - The combined API response or an error\npub(crate) async fn chat(\n State(state): State>,\n headers: axum::http::HeaderMap,\n Json(request): Json,\n) -> Result> {\n // Validate system prompt\n if !request.validate_system_prompt() {\n return Err(ApiError::InvalidSystemPrompt);\n }\n\n // Extract API tokens\n let (deepseek_token, anthropic_token) = extract_api_tokens(&headers)?;\n\n // Initialize clients\n let deepseek_client = DeepSeekClient::new(deepseek_token);\n let anthropic_client = AnthropicClient::new(anthropic_token);\n\n // Get messages with system prompt\n let messages = request.get_messages_with_system();\n\n // Call DeepSeek API\n let deepseek_response = deepseek_client.chat(messages.clone(), &request.deepseek_config).await?;\n \n // Store response metadata\n let deepseek_status: u16 = 200;\n let deepseek_headers = HashMap::new(); // Headers not available when using high-level chat method\n\n // Extract reasoning content and wrap in thinking tags\n let reasoning_content = deepseek_response\n .choices\n .first()\n .and_then(|c| c.message.reasoning_content.as_ref())\n .ok_or_else(|| ApiError::DeepSeekError { \n message: \"No reasoning content in response\".to_string(),\n type_: \"missing_content\".to_string(),\n param: None,\n code: None\n })?;\n\n let thinking_content = format!(\"\\n{}\\n\", reasoning_content);\n\n // Add thinking content to messages for Anthropic\n let mut anthropic_messages = messages;\n anthropic_messages.push(Message {\n role: Role::Assistant,\n content: thinking_content.clone(),\n });\n\n // Call Anthropic API\n let anthropic_response = anthropic_client.chat(\n anthropic_messages,\n request.get_system_prompt().map(String::from),\n &request.anthropic_config\n ).await?;\n \n // Store response metadata\n let anthropic_status: u16 = 200;\n let anthropic_headers = HashMap::new(); // Headers not available when using high-level chat method\n\n // Calculate usage costs\n let deepseek_cost = calculate_deepseek_cost(\n deepseek_response.usage.prompt_tokens,\n deepseek_response.usage.completion_tokens,\n deepseek_response.usage.completion_tokens_details.reasoning_tokens,\n deepseek_response.usage.prompt_tokens_details.cached_tokens,\n &state.config,\n );\n\n let anthropic_cost = calculate_anthropic_cost(\n &anthropic_response.model,\n anthropic_response.usage.input_tokens,\n anthropic_response.usage.output_tokens,\n anthropic_response.usage.cache_creation_input_tokens,\n anthropic_response.usage.cache_read_input_tokens,\n &state.config,\n );\n\n // Combine thinking content with Anthropic's response\n let mut content = Vec::new();\n \n // Add thinking block first\n content.push(ContentBlock::text(thinking_content));\n \n // Add Anthropic's response blocks\n content.extend(anthropic_response.content.clone().into_iter()\n .map(ContentBlock::from_anthropic));\n\n // Build response with captured headers\n let response = ApiResponse {\n created: Utc::now(),\n content,\n deepseek_response: request.verbose.then(|| ExternalApiResponse {\n status: deepseek_status,\n headers: deepseek_headers,\n body: serde_json::to_value(&deepseek_response).unwrap_or_default(),\n }),\n anthropic_response: request.verbose.then(|| ExternalApiResponse {\n status: anthropic_status,\n headers: anthropic_headers,\n body: serde_json::to_value(&anthropic_response).unwrap_or_default(),\n }),\n combined_usage: CombinedUsage {\n total_cost: format_cost(deepseek_cost + anthropic_cost),\n deepseek_usage: DeepSeekUsage {\n input_tokens: deepseek_response.usage.prompt_tokens,\n output_tokens: deepseek_response.usage.completion_tokens,\n reasoning_tokens: deepseek_response.usage.completion_tokens_details.reasoning_tokens,\n cached_input_tokens: deepseek_response.usage.prompt_tokens_details.cached_tokens,\n total_tokens: deepseek_response.usage.total_tokens,\n total_cost: format_cost(deepseek_cost),\n },\n anthropic_usage: AnthropicUsage {\n input_tokens: anthropic_response.usage.input_tokens,\n output_tokens: anthropic_response.usage.output_tokens,\n cached_write_tokens: anthropic_response.usage.cache_creation_input_tokens,\n cached_read_tokens: anthropic_response.usage.cache_read_input_tokens,\n total_tokens: anthropic_response.usage.input_tokens + anthropic_response.usage.output_tokens,\n total_cost: format_cost(anthropic_cost),\n },\n },\n };\n\n Ok(Json(response))\n}\n\n/// Handler for streaming chat requests.\n///\n/// Processes the request through both AI models sequentially,\n/// streaming their responses as Server-Sent Events.\n///\n/// # Arguments\n///\n/// * `state` - Application state containing configuration\n/// * `headers` - HTTP request headers\n/// * `request` - The parsed chat request\n///\n/// # Returns\n///\n/// * `Result` - A stream of Server-Sent Events or an error\npub(crate) async fn chat_stream(\n State(state): State>,\n headers: axum::http::HeaderMap,\n Json(request): Json,\n) -> Result {\n // Validate system prompt\n if !request.validate_system_prompt() {\n return Err(ApiError::InvalidSystemPrompt);\n }\n\n // Extract API tokens\n let (deepseek_token, anthropic_token) = extract_api_tokens(&headers)?;\n\n // Initialize clients\n let deepseek_client = DeepSeekClient::new(deepseek_token);\n let anthropic_client = AnthropicClient::new(anthropic_token);\n\n // Get messages with system prompt\n let messages = request.get_messages_with_system();\n\n // Create channel for stream events\n let (tx, rx) = tokio::sync::mpsc::channel(100);\n let tx = Arc::new(tx);\n\n // Spawn task to handle streaming\n let config = state.config.clone();\n let request_clone = request.clone();\n tokio::spawn(async move {\n let tx = tx.clone();\n\n // Start event\n let _ = tx\n .send(Ok(Event::default().event(\"start\").data(\n serde_json::to_string(&StreamEvent::Start {\n created: Utc::now(),\n })\n .unwrap_or_default(),\n )))\n .await;\n\n // Send initial thinking tag\n let _ = tx\n .send(Ok(Event::default().event(\"content\").data(\n serde_json::to_string(&StreamEvent::Content {\n content: vec![ContentBlock {\n content_type: \"text\".to_string(),\n text: \"\\n\".to_string(),\n }],\n })\n .unwrap_or_default(),\n )))\n .await;\n\n // Stream from DeepSeek\n let mut deepseek_usage = None;\n let mut complete_reasoning = String::new();\n let mut deepseek_stream = deepseek_client.chat_stream(messages.clone(), &request_clone.deepseek_config);\n \n while let Some(chunk) = deepseek_stream.next().await {\n match chunk {\n Ok(response) => {\n if let Some(choice) = response.choices.first() {\n // Check if reasoning_content is null and break if it is\n if choice.delta.reasoning_content.is_none() {\n break;\n }\n\n // Handle delta reasoning_content for streaming\n if let Some(reasoning) = &choice.delta.reasoning_content {\n if !reasoning.is_empty() {\n // Stream the reasoning content as a delta\n let _ = tx\n .send(Ok(Event::default().event(\"content\").data(\n serde_json::to_string(&StreamEvent::Content {\n content: vec![ContentBlock {\n content_type: \"text_delta\".to_string(),\n text: reasoning.to_string(),\n }],\n })\n .unwrap_or_default(),\n )))\n .await;\n \n // Accumulate complete reasoning for later use\n complete_reasoning.push_str(reasoning);\n }\n }\n }\n \n // Store usage information if present\n if let Some(usage) = response.usage {\n deepseek_usage = Some(usage);\n }\n }\n Err(e) => {\n let _ = tx\n .send(Ok(Event::default().event(\"error\").data(\n serde_json::to_string(&StreamEvent::Error {\n message: e.to_string(),\n code: 500,\n })\n .unwrap_or_default(),\n )))\n .await;\n return;\n }\n }\n }\n\n // Send closing thinking tag\n let _ = tx\n .send(Ok(Event::default().event(\"content\").data(\n serde_json::to_string(&StreamEvent::Content {\n content: vec![ContentBlock {\n content_type: \"text\".to_string(),\n text: \"\\n\".to_string(),\n }],\n })\n .unwrap_or_default(),\n )))\n .await;\n\n // Add complete thinking content to messages for Anthropic\n let mut anthropic_messages = messages;\n anthropic_messages.push(Message {\n role: Role::Assistant,\n content: format!(\"\\n{}\\n\", complete_reasoning),\n });\n\n // Stream from Anthropic\n let mut anthropic_stream = anthropic_client.chat_stream(\n anthropic_messages,\n request_clone.get_system_prompt().map(String::from),\n &request_clone.anthropic_config,\n );\n\n while let Some(chunk) = anthropic_stream.next().await {\n match chunk {\n Ok(event) => match event {\n crate::clients::anthropic::StreamEvent::MessageStart { message } => {\n // Only send content event if there's actual content to send\n if !message.content.is_empty() {\n let _ = tx\n .send(Ok(Event::default().event(\"content\").data(\n serde_json::to_string(&StreamEvent::Content { \n content: message.content.into_iter()\n .map(ContentBlock::from_anthropic)\n .collect()\n })\n .unwrap_or_default(),\n )))\n .await;\n }\n }\n crate::clients::anthropic::StreamEvent::ContentBlockDelta { delta, .. } => {\n // Send content update\n let _ = tx\n .send(Ok(Event::default().event(\"content\").data(\n serde_json::to_string(&StreamEvent::Content {\n content: vec![ContentBlock {\n content_type: delta.delta_type,\n text: delta.text,\n }],\n })\n .unwrap_or_default(),\n )))\n .await;\n }\n crate::clients::anthropic::StreamEvent::MessageDelta { usage, .. } => {\n // Send final usage stats if available\n if let Some(usage) = usage {\n let anthropic_usage = AnthropicUsage::from_anthropic(usage);\n let anthropic_cost = calculate_anthropic_cost(\n \"claude-3-5-sonnet-20241022\", // Default model\n anthropic_usage.input_tokens,\n anthropic_usage.output_tokens,\n anthropic_usage.cached_write_tokens,\n anthropic_usage.cached_read_tokens,\n &config,\n );\n\n // Calculate DeepSeek costs if usage is available\n let (deepseek_usage, deepseek_cost) = if let Some(usage) = deepseek_usage.as_ref() {\n let cost = calculate_deepseek_cost(\n usage.prompt_tokens,\n usage.completion_tokens,\n usage.completion_tokens_details.reasoning_tokens,\n usage.prompt_tokens_details.cached_tokens,\n &config,\n );\n \n (DeepSeekUsage {\n input_tokens: usage.prompt_tokens,\n output_tokens: usage.completion_tokens,\n reasoning_tokens: usage.completion_tokens_details.reasoning_tokens,\n cached_input_tokens: usage.prompt_tokens_details.cached_tokens,\n total_tokens: usage.total_tokens,\n total_cost: format_cost(cost),\n }, cost)\n } else {\n (DeepSeekUsage {\n input_tokens: 0,\n output_tokens: 0,\n reasoning_tokens: 0,\n cached_input_tokens: 0,\n total_tokens: 0,\n total_cost: \"$0.00\".to_string(),\n }, 0.0)\n };\n\n let _ = tx\n .send(Ok(Event::default().event(\"usage\").data(\n serde_json::to_string(&StreamEvent::Usage {\n usage: CombinedUsage {\n total_cost: format_cost(deepseek_cost + anthropic_cost),\n deepseek_usage,\n anthropic_usage: AnthropicUsage {\n input_tokens: anthropic_usage.input_tokens,\n output_tokens: anthropic_usage.output_tokens,\n cached_write_tokens: anthropic_usage.cached_write_tokens,\n cached_read_tokens: anthropic_usage.cached_read_tokens,\n total_tokens: anthropic_usage.total_tokens,\n total_cost: format_cost(anthropic_cost),\n },\n },\n })\n .unwrap_or_default(),\n )))\n .await;\n }\n }\n _ => {} // Handle other events if needed\n },\n Err(e) => {\n let _ = tx\n .send(Ok(Event::default().event(\"error\").data(\n serde_json::to_string(&StreamEvent::Error {\n message: e.to_string(),\n code: 500,\n })\n .unwrap_or_default(),\n )))\n .await;\n return;\n }\n }\n }\n\n // Send done event\n let _ = tx\n .send(Ok(Event::default().event(\"done\").data(\n serde_json::to_string(&StreamEvent::Done)\n .unwrap_or_default(),\n )))\n .await;\n });\n\n // Convert receiver into stream\n let stream = ReceiverStream::new(rx);\n Ok(SseResponse::new(stream))\n}\n"], ["/deepclaude/src/clients/anthropic.rs", "//! Anthropic API client implementation for interacting with Claude models.\n//!\n//! This module provides a client implementation for communicating with Anthropic's API,\n//! specifically designed to work with Claude language models. It supports both streaming\n//! and non-streaming interactions, handling all aspects of API communication including:\n//!\n//! - Authentication and request signing\n//! - Message formatting and serialization\n//! - Response parsing and deserialization\n//! - Error handling and type conversion\n//! - Streaming response processing\n//!\n//! # Main Components\n//!\n//! - [`AnthropicClient`]: The main client struct for making API requests\n//! - [`AnthropicResponse`]: Represents the structured response from the API\n//! - [`StreamEvent`]: Represents different types of events in streaming responses\n//!\n//! # Example Usage\n//!\n//! ```no_run\n//! use deepclaude::clients::AnthropicClient;\n//! use deepclaude::models::{Message, ApiConfig};\n//!\n//! async fn example() -> Result<(), Box> {\n//! let client = AnthropicClient::new(\"your-api-key\".to_string());\n//! let messages = vec![/* your messages */];\n//! let config = ApiConfig::default();\n//!\n//! // Non-streaming request\n//! let response = client.chat(messages.clone(), None, &config).await?;\n//!\n//! // Streaming request\n//! let stream = client.chat_stream(messages, None, &config);\n//! Ok(())\n//! }\n//! ```\n\nuse crate::{\n error::{ApiError, Result},\n models::{ApiConfig, Message, Role},\n};\nuse futures::Stream;\nuse reqwest::{header::HeaderMap, Client};\nuse serde::{Deserialize, Serialize};\nuse std::{collections::HashMap, pin::Pin};\nuse futures::StreamExt;\nuse serde_json;\n\npub(crate) const ANTHROPIC_API_URL: &str = \"https://api.anthropic.com/v1/messages\";\nconst DEFAULT_MODEL: &str = \"claude-3-5-sonnet-20241022\";\n\n/// Client for interacting with Anthropic's Claude models.\n///\n/// This client handles authentication, request construction, and response parsing\n/// for both streaming and non-streaming interactions with Anthropic's API.\n///\n/// # Examples\n///\n/// ```no_run\n/// use deepclaude::clients::AnthropicClient;\n///\n/// let client = AnthropicClient::new(\"api_token\".to_string());\n/// ```\n#[derive(Debug)]\npub struct AnthropicClient {\n pub(crate) client: Client,\n api_token: String,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct AnthropicResponse {\n pub id: String,\n #[serde(rename = \"type\")]\n pub response_type: String,\n pub role: String,\n pub model: String,\n pub content: Vec,\n pub stop_reason: Option,\n pub stop_sequence: Option,\n pub usage: Usage,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct ContentBlock {\n #[serde(rename = \"type\")]\n pub content_type: String,\n pub text: String,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct Usage {\n pub input_tokens: u32,\n pub output_tokens: u32,\n pub cache_creation_input_tokens: u32,\n pub cache_read_input_tokens: u32,\n}\n\n#[derive(Debug, Serialize, Deserialize)]\npub(crate) struct AnthropicRequest {\n messages: Vec,\n stream: bool,\n #[serde(skip_serializing_if = \"Option::is_none\")]\n system: Option,\n #[serde(flatten)]\n additional_params: serde_json::Value,\n}\n\n#[derive(Debug, Serialize, Deserialize)]\npub(crate) struct AnthropicMessage {\n role: String,\n content: String,\n}\n\n// Event types for streaming responses\n#[derive(Debug, Deserialize)]\n#[serde(tag = \"type\")]\npub enum StreamEvent {\n #[serde(rename = \"message_start\")]\n MessageStart {\n message: AnthropicResponse,\n },\n #[serde(rename = \"content_block_start\")]\n #[allow(dead_code)]\n ContentBlockStart {\n index: usize,\n content_block: ContentBlock,\n },\n #[serde(rename = \"content_block_delta\")]\n #[allow(dead_code)]\n ContentBlockDelta {\n index: usize,\n delta: ContentDelta,\n },\n #[serde(rename = \"content_block_stop\")]\n #[allow(dead_code)]\n ContentBlockStop {\n index: usize,\n },\n #[serde(rename = \"message_delta\")]\n #[allow(dead_code)]\n MessageDelta {\n delta: MessageDelta,\n usage: Option,\n },\n #[serde(rename = \"message_stop\")]\n MessageStop,\n #[serde(rename = \"ping\")]\n Ping,\n}\n\n#[derive(Debug, Deserialize, Clone)]\npub struct ContentDelta {\n #[serde(rename = \"type\")]\n pub delta_type: String,\n pub text: String,\n}\n\n#[derive(Debug, Deserialize, Clone)]\n#[allow(dead_code)]\npub struct MessageDelta {\n pub stop_reason: Option,\n pub stop_sequence: Option,\n}\n\nimpl AnthropicClient {\n /// Creates a new Anthropic client instance.\n ///\n /// # Arguments\n ///\n /// * `api_token` - API token for authentication with Anthropic's API\n ///\n /// # Returns\n ///\n /// A new `AnthropicClient` instance configured with the provided API token\n pub fn new(api_token: String) -> Self {\n Self {\n client: Client::new(),\n api_token,\n }\n }\n\n /// Builds the HTTP headers required for Anthropic API requests.\n ///\n /// # Arguments\n ///\n /// * `custom_headers` - Optional additional headers to include in requests\n ///\n /// # Returns\n ///\n /// * `Result` - The constructed headers on success, or an error if header construction fails\n ///\n /// # Errors\n ///\n /// Returns `ApiError::Internal` if:\n /// - The API token is invalid\n /// - Content-Type or Anthropic-Version headers cannot be constructed\n pub(crate) fn build_headers(&self, custom_headers: Option<&HashMap>) -> Result {\n let mut headers = HeaderMap::new();\n headers.insert(\n \"x-api-key\",\n self.api_token\n .parse()\n .map_err(|e| ApiError::Internal { \n message: format!(\"Invalid API token: {}\", e) \n })?,\n );\n headers.insert(\n \"content-type\",\n \"application/json\"\n .parse()\n .map_err(|e| ApiError::Internal { \n message: format!(\"Invalid content type: {}\", e) \n })?,\n );\n headers.insert(\n \"anthropic-version\",\n \"2023-06-01\"\n .parse()\n .map_err(|e| ApiError::Internal { \n message: format!(\"Invalid anthropic version: {}\", e) \n })?,\n );\n\n if let Some(custom) = custom_headers {\n headers.extend(super::build_headers(custom)?);\n }\n\n Ok(headers)\n }\n\n /// Constructs a request object for the Anthropic API.\n ///\n /// # Arguments\n ///\n /// * `messages` - Vector of messages to send to the model\n /// * `system` - Optional system prompt to set context\n /// * `stream` - Whether to enable streaming mode\n /// * `config` - Configuration options for the request\n ///\n /// # Returns\n ///\n /// An `AnthropicRequest` object configured with the provided parameters and defaults\n pub(crate) fn build_request(\n &self,\n messages: Vec,\n system: Option,\n stream: bool,\n config: &ApiConfig,\n ) -> AnthropicRequest {\n let filtered_messages = messages\n .into_iter()\n .filter(|msg| msg.role != Role::System)\n .map(|msg| AnthropicMessage {\n role: match msg.role {\n Role::User => \"user\".to_string(),\n Role::Assistant => \"assistant\".to_string(),\n Role::System => unreachable!(),\n },\n content: msg.content,\n })\n .collect();\n\n // Create base request with required fields\n let default_model = serde_json::json!(DEFAULT_MODEL);\n let model_value = config.body.get(\"model\").unwrap_or(&default_model);\n \n let default_max_tokens = if let Some(model_str) = model_value.as_str() {\n if model_str.contains(\"claude-3-opus\") {\n 4096\n } else {\n 8192\n }\n } else {\n 8192\n };\n let default_max_tokens_json = serde_json::json!(default_max_tokens);\n\n let mut request_value = serde_json::json!({\n \"messages\": filtered_messages,\n \"stream\": stream,\n \"model\": model_value,\n \"max_tokens\": config.body.get(\"max_tokens\").unwrap_or(&default_max_tokens_json)\n });\n\n // Add system if present\n if let Some(ref sys) = system {\n if let serde_json::Value::Object(mut map) = request_value {\n map.insert(\"system\".to_string(), serde_json::json!(sys));\n request_value = serde_json::Value::Object(map);\n }\n }\n\n // Merge additional configuration from config.body while protecting critical fields\n if let serde_json::Value::Object(mut map) = request_value {\n if let serde_json::Value::Object(mut body) = serde_json::to_value(&config.body).unwrap_or_default() {\n // Remove protected fields from config body\n body.remove(\"stream\");\n body.remove(\"messages\");\n body.remove(\"system\");\n \n // Merge remaining fields from config.body\n for (key, value) in body {\n map.insert(key, value);\n }\n }\n request_value = serde_json::Value::Object(map);\n }\n\n // Convert the merged JSON value into our request structure\n serde_json::from_value(request_value).unwrap_or_else(|_| AnthropicRequest {\n messages: filtered_messages,\n stream,\n system,\n additional_params: config.body.clone(),\n })\n }\n\n /// Sends a non-streaming chat request to the Anthropic API.\n ///\n /// # Arguments\n ///\n /// * `messages` - Vector of messages for the conversation\n /// * `system` - Optional system prompt to set context\n /// * `config` - Configuration options for the request\n ///\n /// # Returns\n ///\n /// * `Result` - The model's response on success\n ///\n /// # Errors\n ///\n /// Returns `ApiError::AnthropicError` if:\n /// - The API request fails\n /// - The response status is not successful\n /// - The response cannot be parsed\n pub async fn chat(\n &self,\n messages: Vec,\n system: Option,\n config: &ApiConfig,\n ) -> Result {\n let headers = self.build_headers(Some(&config.headers))?;\n let request = self.build_request(messages, system, false, config);\n\n let response = self\n .client\n .post(ANTHROPIC_API_URL)\n .headers(headers)\n .json(&request)\n .send()\n .await\n .map_err(|e| ApiError::AnthropicError { \n message: format!(\"Request failed: {}\", e),\n type_: \"request_failed\".to_string(),\n param: None,\n code: None\n })?;\n\n if !response.status().is_success() {\n let error = response\n .text()\n .await\n .unwrap_or_else(|_| \"Unknown error\".to_string());\n return Err(ApiError::AnthropicError { \n message: error,\n type_: \"api_error\".to_string(),\n param: None,\n code: None\n });\n }\n\n response\n .json::()\n .await\n .map_err(|e| ApiError::AnthropicError { \n message: format!(\"Failed to parse response: {}\", e),\n type_: \"parse_error\".to_string(),\n param: None,\n code: None\n })\n }\n\n /// Sends a streaming chat request to the Anthropic API.\n ///\n /// Returns a stream that yields events from the model's response as they arrive.\n ///\n /// # Arguments\n ///\n /// * `messages` - Vector of messages for the conversation\n /// * `system` - Optional system prompt to set context\n /// * `config` - Configuration options for the request\n ///\n /// # Returns\n ///\n /// * `Pin> + Send>>` - A stream of response events\n ///\n /// # Errors\n ///\n /// The stream may yield `ApiError::AnthropicError` if:\n /// - The API request fails\n /// - Stream processing encounters an error\n /// - Response events cannot be parsed\n pub fn chat_stream(\n &self,\n messages: Vec,\n system: Option,\n config: &ApiConfig,\n ) -> Pin> + Send>> {\n let headers = match self.build_headers(Some(&config.headers)) {\n Ok(h) => h,\n Err(e) => return Box::pin(futures::stream::once(async move { Err(e) })),\n };\n\n let request = self.build_request(messages, system, true, config);\n let client = self.client.clone();\n\n Box::pin(async_stream::try_stream! {\n let mut stream = client\n .post(ANTHROPIC_API_URL)\n .headers(headers)\n .json(&request)\n .send()\n .await\n .map_err(|e| ApiError::AnthropicError { \n message: format!(\"Request failed: {}\", e),\n type_: \"request_failed\".to_string(),\n param: None,\n code: None\n })?\n .bytes_stream();\n\n let mut data = String::new();\n \n while let Some(chunk) = stream.next().await {\n let chunk = chunk.map_err(|e| ApiError::AnthropicError { \n message: format!(\"Stream error: {}\", e),\n type_: \"stream_error\".to_string(),\n param: None,\n code: None\n })?;\n data.push_str(&String::from_utf8_lossy(&chunk));\n\n let mut start = 0;\n while let Some(end) = data[start..].find(\"\\n\\n\") {\n let end = start + end;\n let event_data = &data[start..end];\n start = end + 2;\n\n if event_data.starts_with(\"event: \") {\n let _event_line = &event_data[\"event: \".len()..];\n if let Some(data_line) = event_data.lines().nth(1) {\n if data_line.starts_with(\"data: \") {\n let json_data = &data_line[\"data: \".len()..];\n if let Ok(event) = serde_json::from_str::(json_data) {\n yield event;\n }\n }\n }\n }\n }\n\n if start > 0 {\n data = data[start..].to_string();\n }\n }\n })\n }\n}\n\n/// Converts an Anthropic content block into the application's generic content block type.\nimpl From for crate::models::response::ContentBlock {\n fn from(block: ContentBlock) -> Self {\n Self {\n content_type: block.content_type,\n text: block.text,\n }\n }\n}\n"], ["/deepclaude/src/clients/deepseek.rs", "//! DeepSeek API client implementation for interacting with DeepSeek's AI models.\n//!\n//! This module provides a client implementation for making requests to DeepSeek's chat completion API.\n//! It supports both streaming and non-streaming interactions, handling authentication, request\n//! construction, and response parsing.\n//!\n//! # Features\n//!\n//! - Supports chat completions with DeepSeek's AI models\n//! - Handles both streaming and non-streaming responses\n//! - Configurable request parameters (model, max tokens, temperature)\n//! - Custom header support\n//! - Comprehensive error handling\n//!\n//! # Examples\n//!\n//! ```no_run\n//! use crate::{\n//! clients::DeepSeekClient,\n//! models::{ApiConfig, Message},\n//! };\n//!\n//! # async fn example() -> Result<(), Box> {\n//! // Initialize the client\n//! let client = DeepSeekClient::new(\"your-api-key\".to_string());\n//!\n//! // Prepare messages and configuration\n//! let messages = vec![Message {\n//! role: \"user\".to_string(),\n//! content: \"Hello, how are you?\".to_string(),\n//! }];\n//!\n//! let config = ApiConfig::default();\n//!\n//! // Make a non-streaming request\n//! let response = client.chat(messages.clone(), &config).await?;\n//!\n//! // Or use streaming for real-time responses\n//! let mut stream = client.chat_stream(messages, &config);\n//! while let Some(chunk) = stream.next().await {\n//! println!(\"Received chunk: {:?}\", chunk?);\n//! }\n//! # Ok(())\n//! # }\n//! ```\n//!\n//! # Error Handling\n//!\n//! The client uses a custom error type `ApiError` to handle various failure cases:\n//! - Network errors\n//! - API authentication errors\n//! - Invalid response formats\n//! - Stream processing errors\n//!\n//! All public methods return `Result` types with appropriate error variants.\n\nuse crate::{\n error::{ApiError, Result},\n models::{ApiConfig, Message},\n};\nuse futures::Stream;\nuse reqwest::{header::HeaderMap, Client};\nuse serde::{Deserialize, Serialize};\nuse std::{collections::HashMap, pin::Pin};\nuse futures::StreamExt;\nuse serde_json;\n\npub(crate) const DEEPSEEK_API_URL: &str = \"https://api.deepseek.com/chat/completions\";\nconst DEFAULT_MODEL: &str = \"deepseek-reasoner\";\n\n/// Client for interacting with DeepSeek's AI models.\n///\n/// This client handles authentication, request construction, and response parsing\n/// for both streaming and non-streaming interactions with DeepSeek's API.\n///\n/// # Examples\n///\n/// ```no_run\n/// use deepclaude::clients::DeepSeekClient;\n///\n/// let client = DeepSeekClient::new(\"api_token\".to_string());\n/// ```\n#[derive(Debug)]\npub struct DeepSeekClient {\n pub(crate) client: Client,\n api_token: String,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct DeepSeekResponse {\n pub id: String,\n pub object: String,\n pub created: i64,\n pub model: String,\n pub choices: Vec,\n pub usage: Usage,\n pub system_fingerprint: String,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct Choice {\n pub index: i32,\n pub message: AssistantMessage,\n pub logprobs: Option,\n pub finish_reason: Option,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct AssistantMessage {\n pub role: String,\n pub content: Option,\n pub reasoning_content: Option,\n}\n\n// Streaming response types\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct StreamChoice {\n pub index: i32,\n pub delta: StreamDelta,\n pub logprobs: Option,\n pub finish_reason: Option,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct StreamDelta {\n pub role: Option,\n pub content: Option,\n pub reasoning_content: Option,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct StreamResponse {\n pub id: String,\n pub object: String,\n pub created: i64,\n pub model: String,\n pub choices: Vec,\n pub usage: Option,\n pub system_fingerprint: String,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct Usage {\n pub prompt_tokens: u32,\n pub completion_tokens: u32,\n pub total_tokens: u32,\n pub prompt_tokens_details: PromptTokensDetails,\n pub completion_tokens_details: CompletionTokensDetails,\n pub prompt_cache_hit_tokens: u32,\n pub prompt_cache_miss_tokens: u32,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct PromptTokensDetails {\n pub cached_tokens: u32,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct CompletionTokensDetails {\n pub reasoning_tokens: u32,\n}\n\n#[derive(Debug, Serialize, Deserialize)]\npub(crate) struct DeepSeekRequest {\n messages: Vec,\n stream: bool,\n #[serde(flatten)]\n additional_params: serde_json::Value,\n}\n\nimpl DeepSeekClient {\n pub fn new(api_token: String) -> Self {\n Self {\n client: Client::new(),\n api_token,\n }\n }\n\n /// Builds the HTTP headers required for DeepSeek API requests.\n ///\n /// # Arguments\n ///\n /// * `custom_headers` - Optional additional headers to include in requests\n ///\n /// # Returns\n ///\n /// * `Result` - The constructed headers on success, or an error if header construction fails\n ///\n /// # Errors\n ///\n /// Returns `ApiError::Internal` if:\n /// - The API token is invalid\n /// - Content-Type or Accept headers cannot be constructed\n pub(crate) fn build_headers(&self, custom_headers: Option<&HashMap>) -> Result {\n let mut headers = HeaderMap::new();\n headers.insert(\n \"Authorization\",\n format!(\"Bearer {}\", self.api_token)\n .parse()\n .map_err(|e| ApiError::Internal { \n message: format!(\"Invalid API token: {}\", e) \n })?,\n );\n headers.insert(\n \"Content-Type\",\n \"application/json\"\n .parse()\n .map_err(|e| ApiError::Internal { \n message: format!(\"Invalid content type: {}\", e) \n })?,\n );\n headers.insert(\n \"Accept\",\n \"application/json\"\n .parse()\n .map_err(|e| ApiError::Internal { \n message: format!(\"Invalid accept header: {}\", e) \n })?,\n );\n\n if let Some(custom) = custom_headers {\n headers.extend(super::build_headers(custom)?);\n }\n\n Ok(headers)\n }\n\n /// Constructs a request object for the DeepSeek API.\n ///\n /// # Arguments\n ///\n /// * `messages` - Vector of messages to send to the model\n /// * `stream` - Whether to enable streaming mode\n /// * `config` - Configuration options for the request\n ///\n /// # Returns\n ///\n /// A `DeepSeekRequest` object configured with the provided parameters and defaults\n pub(crate) fn build_request(&self, messages: Vec, stream: bool, config: &ApiConfig) -> DeepSeekRequest {\n // Create a base request with required fields\n let mut request_value = serde_json::json!({\n \"messages\": messages,\n \"stream\": stream,\n // Set defaults only if not provided in config\n \"model\": config.body.get(\"model\").unwrap_or(&serde_json::json!(DEFAULT_MODEL)),\n \"max_tokens\": config.body.get(\"max_tokens\").unwrap_or(&serde_json::json!(8192)),\n \"temperature\": config.body.get(\"temperature\").unwrap_or(&serde_json::json!(1.0)),\n \"response_format\": {\n \"type\": \"text\"\n }\n });\n\n // Merge additional configuration from config.body while protecting critical fields\n if let serde_json::Value::Object(mut map) = request_value {\n if let serde_json::Value::Object(mut body) = serde_json::to_value(&config.body).unwrap_or_default() {\n // Remove protected fields from config body\n body.remove(\"stream\");\n body.remove(\"messages\");\n \n // Merge remaining fields from config.body\n for (key, value) in body {\n map.insert(key, value);\n }\n }\n request_value = serde_json::Value::Object(map);\n }\n\n // Convert the merged JSON value into our request structure\n serde_json::from_value(request_value).unwrap_or_else(|_| DeepSeekRequest {\n messages,\n stream,\n additional_params: config.body.clone(),\n })\n }\n\n /// Sends a non-streaming chat request to the DeepSeek API.\n ///\n /// # Arguments\n ///\n /// * `messages` - Vector of messages for the conversation\n /// * `config` - Configuration options for the request\n ///\n /// # Returns\n ///\n /// * `Result` - The model's response on success\n ///\n /// # Errors\n ///\n /// Returns `ApiError::DeepSeekError` if:\n /// - The API request fails\n /// - The response status is not successful\n /// - The response cannot be parsed\n pub async fn chat(\n &self,\n messages: Vec,\n config: &ApiConfig,\n ) -> Result {\n let headers = self.build_headers(Some(&config.headers))?;\n let request = self.build_request(messages, false, config);\n\n let response = self\n .client\n .post(DEEPSEEK_API_URL)\n .headers(headers)\n .json(&request)\n .send()\n .await\n .map_err(|e| ApiError::DeepSeekError { \n message: format!(\"Request failed: {}\", e),\n type_: \"request_failed\".to_string(),\n param: None,\n code: None\n })?;\n\n if !response.status().is_success() {\n let error = response\n .text()\n .await\n .unwrap_or_else(|_| \"Unknown error\".to_string());\n return Err(ApiError::DeepSeekError { \n message: error,\n type_: \"api_error\".to_string(),\n param: None,\n code: None\n });\n }\n\n response\n .json::()\n .await\n .map_err(|e| ApiError::DeepSeekError { \n message: format!(\"Failed to parse response: {}\", e),\n type_: \"parse_error\".to_string(),\n param: None,\n code: None\n })\n }\n\n /// Sends a streaming chat request to the DeepSeek API.\n ///\n /// Returns a stream that yields chunks of the model's response as they arrive.\n ///\n /// # Arguments\n ///\n /// * `messages` - Vector of messages for the conversation\n /// * `config` - Configuration options for the request\n ///\n /// # Returns\n ///\n /// * `Pin> + Send>>` - A stream of response chunks\n ///\n /// # Errors\n ///\n /// The stream may yield `ApiError::DeepSeekError` if:\n /// - The API request fails\n /// - Stream processing encounters an error\n /// - Response chunks cannot be parsed\n pub fn chat_stream(\n &self,\n messages: Vec,\n config: &ApiConfig,\n ) -> Pin> + Send>> {\n let headers = match self.build_headers(Some(&config.headers)) {\n Ok(h) => h,\n Err(e) => return Box::pin(futures::stream::once(async move { Err(e) })),\n };\n\n let request = self.build_request(messages, true, config);\n let client = self.client.clone();\n\n Box::pin(async_stream::try_stream! {\n let mut stream = client\n .post(DEEPSEEK_API_URL)\n .headers(headers)\n .json(&request)\n .send()\n .await\n .map_err(|e| ApiError::DeepSeekError { \n message: format!(\"Request failed: {}\", e),\n type_: \"request_failed\".to_string(),\n param: None,\n code: None\n })?\n .bytes_stream();\n\n let mut data = String::new();\n \n while let Some(chunk) = stream.next().await {\n let chunk = chunk.map_err(|e| ApiError::DeepSeekError { \n message: format!(\"Stream error: {}\", e),\n type_: \"stream_error\".to_string(),\n param: None,\n code: None\n })?;\n data.push_str(&String::from_utf8_lossy(&chunk));\n\n let mut start = 0;\n while let Some(end) = data[start..].find(\"\\n\\n\") {\n let end = start + end;\n let line = &data[start..end].trim();\n start = end + 2;\n \n if line.starts_with(\"data: \") {\n let json_data = &line[\"data: \".len()..];\n if let Ok(response) = serde_json::from_str::(json_data) {\n yield response;\n }\n }\n }\n\n if start > 0 {\n data = data[start..].to_string();\n }\n }\n })\n }\n}\n"], ["/deepclaude/src/config.rs", "//! Configuration management for the application.\n//!\n//! This module handles loading and managing configuration settings from files\n//! and environment variables. It includes pricing configurations for different\n//! AI model providers and server settings.\n\nuse serde::{Deserialize, Serialize};\nuse std::path::Path;\n\n/// Root configuration structure containing all application settings.\n///\n/// This structure is typically loaded from a TOML configuration file\n/// and provides access to all configurable aspects of the application.\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct Config {\n pub server: ServerConfig,\n pub pricing: PricingConfig,\n}\n\n/// Server-specific configuration settings.\n///\n/// Contains settings related to the HTTP server, such as the\n/// host address and port number to bind to.\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct ServerConfig {\n pub host: String,\n pub port: u16,\n}\n\n/// Pricing configuration for all supported AI models.\n///\n/// Contains pricing information for different AI model providers\n/// and their various models, used for usage cost calculation.\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct PricingConfig {\n pub deepseek: DeepSeekPricing,\n pub anthropic: AnthropicPricing,\n}\n\n/// DeepSeek-specific pricing configuration.\n///\n/// Contains pricing rates for different aspects of DeepSeek API usage,\n/// including cached and non-cached requests.\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct DeepSeekPricing {\n pub input_cache_hit_price: f64, // per million tokens\n pub input_cache_miss_price: f64, // per million tokens\n pub output_price: f64, // per million tokens\n}\n\n/// Anthropic-specific pricing configuration.\n///\n/// Contains pricing information for different Claude model variants\n/// and their associated costs.\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct AnthropicPricing {\n pub claude_3_sonnet: ModelPricing,\n pub claude_3_haiku: ModelPricing,\n pub claude_3_opus: ModelPricing,\n}\n\n/// Generic model pricing configuration.\n///\n/// Contains detailed pricing information for a specific model,\n/// including input, output, and caching costs.\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct ModelPricing {\n pub input_price: f64, // per million tokens\n pub output_price: f64, // per million tokens\n pub cache_write_price: f64, // per million tokens\n pub cache_read_price: f64, // per million tokens\n}\n\nimpl Config {\n /// Loads configuration from the default config file.\n ///\n /// Attempts to load and parse the configuration from 'config.toml'.\n /// Falls back to default values if the file cannot be loaded or parsed.\n ///\n /// # Returns\n ///\n /// * `anyhow::Result` - The loaded configuration or an error if loading fails\n ///\n /// # Errors\n ///\n /// Returns an error if:\n /// - The config file cannot be read\n /// - The TOML content cannot be parsed\n /// - The parsed content doesn't match the expected structure\n pub fn load() -> anyhow::Result {\n let config_path = Path::new(\"config.toml\");\n let config = config::Config::builder()\n .add_source(config::File::from(config_path))\n .build()?;\n\n Ok(config.try_deserialize()?)\n }\n}\n\n/// Provides default configuration values.\n///\n/// These defaults are used when a configuration file is not present\n/// or when specific values are not provided in the config file.\nimpl Default for Config {\n fn default() -> Self {\n Self {\n server: ServerConfig {\n host: \"127.0.0.1\".to_string(),\n port: 3000,\n },\n pricing: PricingConfig {\n deepseek: DeepSeekPricing {\n input_cache_hit_price: 0.14,\n input_cache_miss_price: 0.55,\n output_price: 2.19,\n },\n anthropic: AnthropicPricing {\n claude_3_sonnet: ModelPricing {\n input_price: 3.0,\n output_price: 15.0,\n cache_write_price: 3.75,\n cache_read_price: 0.30,\n },\n claude_3_haiku: ModelPricing {\n input_price: 0.80,\n output_price: 4.0,\n cache_write_price: 1.0,\n cache_read_price: 0.08,\n },\n claude_3_opus: ModelPricing {\n input_price: 15.0,\n output_price: 75.0,\n cache_write_price: 18.75,\n cache_read_price: 1.50,\n },\n },\n },\n }\n }\n}\n"], ["/deepclaude/src/error.rs", "//! Error handling types and implementations for the application.\n//!\n//! This module provides a comprehensive error handling system including:\n//! - Custom error types for various failure scenarios\n//! - Conversion implementations for common error types\n//! - Response formatting for API errors\n//! - Type aliases for common Result types\n\nuse axum::{\n http::StatusCode,\n response::{IntoResponse, Response, sse::Event},\n Json,\n};\nuse serde::{Deserialize, Serialize};\nuse std::convert::Infallible;\nuse thiserror::Error;\nuse tokio_stream::wrappers::ReceiverStream;\n\n/// Response structure for API errors.\n///\n/// This structure provides a consistent format for error responses\n/// returned by the API endpoints.\n#[derive(Debug, Serialize, Deserialize)]\npub struct ErrorResponse {\n pub error: ErrorDetails,\n}\n\n/// Detailed error information included in error responses.\n///\n/// Contains specific information about what went wrong, including:\n/// - A human-readable error message\n/// - The type of error that occurred\n/// - Optional parameter that caused the error\n/// - Optional error code for more specific error handling\n#[derive(Debug, Serialize, Deserialize)]\npub struct ErrorDetails {\n pub message: String,\n #[serde(rename = \"type\")]\n pub type_: String,\n #[serde(skip_serializing_if = \"Option::is_none\")]\n pub param: Option,\n #[serde(skip_serializing_if = \"Option::is_none\")]\n pub code: Option,\n}\n\n/// Enumeration of all possible API errors.\n///\n/// This enum represents all the different types of errors that can occur\n/// during API operations, including validation errors, external API errors,\n/// and internal server errors.\n#[derive(Error, Debug, Clone)]\npub enum ApiError {\n #[error(\"Invalid request: {message}\")]\n BadRequest {\n message: String,\n },\n\n #[error(\"Missing required header: {header}\")]\n MissingHeader {\n header: String,\n },\n\n #[error(\"Invalid system prompt configuration\")]\n InvalidSystemPrompt,\n\n #[error(\"DeepSeek API error: {message}\")]\n DeepSeekError {\n message: String,\n type_: String,\n param: Option,\n code: Option,\n },\n\n #[error(\"Anthropic API error: {message}\")]\n AnthropicError {\n message: String,\n type_: String,\n param: Option,\n code: Option,\n },\n\n #[error(\"Internal server error: {message}\")]\n Internal {\n message: String,\n },\n\n #[error(\"Other error: {message}\")]\n Other {\n message: String,\n },\n}\n\n/// Implements conversion of API errors into HTTP responses.\n///\n/// Maps each error variant to an appropriate HTTP status code and\n/// formats the error details into a consistent JSON response structure.\nimpl IntoResponse for ApiError {\n fn into_response(self) -> Response {\n let (status, error_response) = match &self {\n ApiError::BadRequest { message } => (\n StatusCode::BAD_REQUEST,\n ErrorResponse {\n error: ErrorDetails {\n message: message.clone(),\n type_: \"bad_request\".to_string(),\n param: None,\n code: None,\n },\n },\n ),\n ApiError::MissingHeader { header } => (\n StatusCode::BAD_REQUEST,\n ErrorResponse {\n error: ErrorDetails {\n message: format!(\"Missing required header: {}\", header),\n type_: \"missing_header\".to_string(),\n param: Some(header.clone()),\n code: None,\n },\n },\n ),\n ApiError::InvalidSystemPrompt => (\n StatusCode::BAD_REQUEST,\n ErrorResponse {\n error: ErrorDetails {\n message: \"System prompt can only be provided once, either in root or messages array\".to_string(),\n type_: \"invalid_system_prompt\".to_string(),\n param: None,\n code: None,\n },\n },\n ),\n ApiError::DeepSeekError { message, type_, param, code } => (\n StatusCode::BAD_REQUEST,\n ErrorResponse {\n error: ErrorDetails {\n message: format!(\"DeepSeek API Error: {}\", message),\n type_: format!(\"deepseek_{}\", type_),\n param: param.clone(),\n code: code.clone(),\n },\n },\n ),\n ApiError::AnthropicError { message, type_, param, code } => (\n StatusCode::BAD_REQUEST,\n ErrorResponse {\n error: ErrorDetails {\n message: format!(\"Anthropic API Error: {}\", message),\n type_: format!(\"anthropic_{}\", type_),\n param: param.clone(),\n code: code.clone(),\n },\n },\n ),\n ApiError::Internal { message } => (\n StatusCode::INTERNAL_SERVER_ERROR,\n ErrorResponse {\n error: ErrorDetails {\n message: message.clone(),\n type_: \"internal_error\".to_string(),\n param: None,\n code: None,\n },\n },\n ),\n ApiError::Other { message } => (\n StatusCode::INTERNAL_SERVER_ERROR,\n ErrorResponse {\n error: ErrorDetails {\n message: format!(\"Internal server error: {}\", message),\n type_: \"internal_error\".to_string(),\n param: None,\n code: None,\n },\n },\n ),\n };\n\n (status, Json(error_response)).into_response()\n }\n}\n\n/// Converts generic errors into API errors.\n///\n/// This implementation allows using the `?` operator with functions that\n/// return `anyhow::Error`, converting them into our custom `ApiError` type.\nimpl From for ApiError {\n fn from(err: anyhow::Error) -> Self {\n ApiError::Other { \n message: err.to_string() \n }\n }\n}\n\n/// Type alias for Results using our custom ApiError type.\n///\n/// This provides a convenient way to use Result with our ApiError\n/// throughout the application.\npub type Result = std::result::Result;\n\n/// Type alias for Server-Sent Events (SSE) results.\n///\n/// Used for streaming responses where errors are converted to Infallible\n/// since they are handled within the stream.\npub type SseResult = std::result::Result;\n\n/// Type alias for SSE streams.\n///\n/// Represents a stream of SSE results that can be sent to clients.\npub type SseStream = ReceiverStream;\n\n/// Type alias for SSE responses.\n///\n/// Represents the complete SSE response type used by the API endpoints.\npub type SseResponse = axum::response::sse::Sse;\n"], ["/deepclaude/src/clients/mod.rs", "//! Client implementations for external AI model providers.\n//!\n//! This module contains client implementations for different AI model providers:\n//! - `anthropic`: Client for Anthropic's Claude models\n//! - `deepseek`: Client for DeepSeek's reasoning models\n//!\n//! Each client handles authentication, request building, and response parsing\n//! specific to its provider's API.\n\npub mod anthropic;\npub mod deepseek;\n\npub use anthropic::AnthropicClient;\npub use deepseek::DeepSeekClient;\n\nuse crate::error::Result;\nuse reqwest::header::{HeaderMap, HeaderName, HeaderValue};\nuse std::collections::HashMap;\n\n/// Converts a HashMap of string headers to a reqwest HeaderMap.\n///\n/// This function is used internally by clients to convert user-provided\n/// header maps into the format required by reqwest.\n///\n/// # Arguments\n///\n/// * `headers` - A HashMap containing header names and values as strings\n///\n/// # Returns\n///\n/// * `Result` - The converted HeaderMap on success, or an error if\n/// any header name or value is invalid\n///\n/// # Errors\n///\n/// Returns `ApiError::BadRequest` if:\n/// - A header name contains invalid characters\n/// - A header value contains invalid characters\npub(crate) fn build_headers(headers: &HashMap) -> Result {\n let mut header_map = HeaderMap::new();\n \n for (key, value) in headers {\n let header_name = HeaderName::from_bytes(key.as_bytes())\n .map_err(|e| crate::error::ApiError::BadRequest { \n message: format!(\"Invalid header name: {}\", e) \n })?;\n \n let header_value = HeaderValue::from_str(value)\n .map_err(|e| crate::error::ApiError::BadRequest { \n message: format!(\"Invalid header value: {}\", e) \n })?;\n \n header_map.insert(header_name, header_value);\n }\n \n Ok(header_map)\n}\n"], ["/deepclaude/src/models/request.rs", "//! Request models for the API endpoints.\n//!\n//! This module defines the structures used to represent incoming API requests,\n//! including chat messages, configuration options, and request parameters.\n\nuse serde::{Deserialize, Serialize};\nuse std::collections::HashMap;\n\n/// Primary request structure for chat API endpoints.\n///\n/// This structure represents a complete chat request, including messages,\n/// system prompts, and configuration options for both DeepSeek and Anthropic APIs.\n#[derive(Debug, Clone, Deserialize, Serialize)]\npub struct ApiRequest {\n #[serde(default)]\n pub stream: bool,\n \n #[serde(default)]\n pub verbose: bool,\n \n pub system: Option,\n pub messages: Vec,\n \n #[serde(default)]\n pub deepseek_config: ApiConfig,\n \n #[serde(default)]\n pub anthropic_config: ApiConfig,\n}\n\n/// A single message in a chat conversation.\n///\n/// Represents one message in the conversation history, including\n/// its role (system, user, or assistant) and content.\n#[derive(Debug, Clone, Deserialize, Serialize)]\npub struct Message {\n pub role: Role,\n pub content: String,\n}\n\n/// Possible roles for a message in a chat conversation.\n///\n/// Each message must be associated with one of these roles to\n/// properly structure the conversation flow.\n#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]\n#[serde(rename_all = \"lowercase\")]\npub enum Role {\n System,\n User,\n Assistant,\n}\n\n/// Configuration options for external API requests.\n///\n/// Contains headers and body parameters that will be passed\n/// to the external AI model APIs.\n#[derive(Debug, Clone, Default, Deserialize, Serialize)]\npub struct ApiConfig {\n #[serde(default)]\n pub headers: HashMap,\n \n #[serde(default)]\n pub body: serde_json::Value,\n}\n\nimpl ApiRequest {\n /// Validates that system prompts are not duplicated.\n ///\n /// Checks that a system prompt is not provided in both the root level\n /// and messages array. The system prompt itself is optional.\n ///\n /// # Returns\n ///\n /// * `bool` - True if system prompt validation passes (no duplicates), false otherwise\n pub fn validate_system_prompt(&self) -> bool {\n let system_in_messages = self.messages.iter().any(|msg| matches!(msg.role, Role::System));\n \n // Only invalid if system prompt is provided in both places\n !(self.system.is_some() && system_in_messages)\n }\n\n /// Returns messages with the system prompt in the correct position.\n ///\n /// Ensures the system prompt (if present) is the first message,\n /// followed by the conversation messages in order.\n ///\n /// # Returns\n ///\n /// * `Vec` - Messages with system prompt correctly positioned\n pub fn get_messages_with_system(&self) -> Vec {\n let mut messages = Vec::new();\n\n // Add system message first\n if let Some(system) = &self.system {\n messages.push(Message {\n role: Role::System,\n content: system.clone(),\n });\n }\n\n // Add remaining messages\n messages.extend(self.messages.iter().filter(|msg| !matches!(msg.role, Role::System)).cloned());\n\n messages\n }\n\n /// Retrieves the system prompt if one is present.\n ///\n /// Checks both the root level system field and the messages array\n /// for a system prompt.\n ///\n /// # Returns\n ///\n /// * `Option<&str>` - The system prompt if found, None otherwise\n pub fn get_system_prompt(&self) -> Option<&str> {\n self.system.as_deref().or_else(|| {\n self.messages\n .iter()\n .find(|msg| matches!(msg.role, Role::System))\n .map(|msg| msg.content.as_str())\n })\n }\n}\n"], ["/deepclaude/src/models/response.rs", "//! Response models for the API endpoints.\n//!\n//! This module defines the structures used to represent API responses,\n//! including chat completions, usage statistics, and streaming events.\n\nuse chrono::{DateTime, Utc};\nuse serde::{Deserialize, Serialize};\nuse std::collections::HashMap;\n\n/// Primary response structure for chat API endpoints.\n///\n/// Contains the complete response from both AI models, including\n/// content blocks, usage statistics, and optional raw API responses.\n#[derive(Debug, Serialize, Clone)]\npub struct ApiResponse {\n pub created: DateTime,\n pub content: Vec,\n \n #[serde(skip_serializing_if = \"Option::is_none\")]\n pub deepseek_response: Option,\n \n #[serde(skip_serializing_if = \"Option::is_none\")]\n pub anthropic_response: Option,\n \n pub combined_usage: CombinedUsage,\n}\n\n/// A block of content in a response.\n///\n/// Represents a single piece of content in the response,\n/// with its type and actual text content.\n#[derive(Debug, Serialize, Deserialize, Clone)]\npub struct ContentBlock {\n #[serde(rename = \"type\")]\n pub content_type: String,\n pub text: String,\n}\n\n/// Raw response from an external API.\n///\n/// Contains the complete response details from an external API\n/// call, including status code, headers, and response body.\n#[derive(Debug, Serialize, Clone)]\npub struct ExternalApiResponse {\n pub status: u16,\n pub headers: HashMap,\n pub body: serde_json::Value,\n}\n\n/// Combined usage statistics from both AI models.\n///\n/// Aggregates token usage and cost information from both\n/// DeepSeek and Anthropic API calls.\n#[derive(Debug, Serialize, Clone)]\npub struct CombinedUsage {\n pub total_cost: String,\n pub deepseek_usage: DeepSeekUsage,\n pub anthropic_usage: AnthropicUsage,\n}\n\n/// Usage statistics for DeepSeek API calls.\n///\n/// Tracks token consumption and costs specific to\n/// DeepSeek model usage.\n#[derive(Debug, Serialize, Clone)]\npub struct DeepSeekUsage {\n pub input_tokens: u32,\n pub output_tokens: u32,\n pub reasoning_tokens: u32,\n pub cached_input_tokens: u32,\n pub total_tokens: u32,\n pub total_cost: String,\n}\n\n/// Usage statistics for Anthropic API calls.\n///\n/// Tracks token consumption and costs specific to\n/// Anthropic model usage.\n#[derive(Debug, Serialize, Clone)]\npub struct AnthropicUsage {\n pub input_tokens: u32,\n pub output_tokens: u32,\n pub cached_write_tokens: u32,\n pub cached_read_tokens: u32,\n pub total_tokens: u32,\n pub total_cost: String,\n}\n\n// Streaming event types\n/// Events emitted during streaming responses.\n///\n/// Represents different types of events that can occur\n/// during a streaming response, including content updates\n/// and usage statistics.\n#[derive(Debug, Serialize)]\n#[serde(tag = \"type\")]\npub enum StreamEvent {\n #[serde(rename = \"start\")]\n Start {\n created: DateTime,\n },\n \n #[serde(rename = \"content\")]\n Content {\n content: Vec,\n },\n \n #[serde(rename = \"usage\")]\n Usage {\n usage: CombinedUsage,\n },\n \n #[serde(rename = \"done\")]\n Done,\n \n #[serde(rename = \"error\")]\n Error {\n message: String,\n code: u16,\n },\n}\n\nimpl ContentBlock {\n /// Creates a new text content block.\n ///\n /// # Arguments\n ///\n /// * `text` - The text content to include in the block\n ///\n /// # Returns\n ///\n /// A new `ContentBlock` with the type set to \"text\"\n pub fn text(text: impl Into) -> Self {\n Self {\n content_type: \"text\".to_string(),\n text: text.into(),\n }\n }\n\n /// Converts an Anthropic content block to a generic content block.\n ///\n /// # Arguments\n ///\n /// * `block` - The Anthropic-specific content block to convert\n ///\n /// # Returns\n ///\n /// A new `ContentBlock` with the same content type and text\n pub fn from_anthropic(block: crate::clients::anthropic::ContentBlock) -> Self {\n Self {\n content_type: block.content_type,\n text: block.text,\n }\n }\n}\n\nimpl ApiResponse {\n /// Creates a new API response with simple text content.\n ///\n /// # Arguments\n ///\n /// * `content` - The text content for the response\n ///\n /// # Returns\n ///\n /// A new `ApiResponse` with default values and the provided content\n #[allow(dead_code)]\n pub fn new(content: impl Into) -> Self {\n Self {\n created: Utc::now(),\n content: vec![ContentBlock::text(content)],\n deepseek_response: None,\n anthropic_response: None,\n combined_usage: CombinedUsage {\n total_cost: \"$0.00\".to_string(),\n deepseek_usage: DeepSeekUsage {\n input_tokens: 0,\n output_tokens: 0,\n reasoning_tokens: 0,\n cached_input_tokens: 0,\n total_tokens: 0,\n total_cost: \"$0.00\".to_string(),\n },\n anthropic_usage: AnthropicUsage {\n input_tokens: 0,\n output_tokens: 0,\n cached_write_tokens: 0,\n cached_read_tokens: 0,\n total_tokens: 0,\n total_cost: \"$0.00\".to_string(),\n },\n },\n }\n }\n}\n\nimpl AnthropicUsage {\n /// Converts Anthropic usage statistics to the generic usage format.\n ///\n /// # Arguments\n ///\n /// * `usage` - The Anthropic-specific usage statistics to convert\n ///\n /// # Returns\n ///\n /// A new `AnthropicUsage` with values copied from the Anthropic usage\n pub fn from_anthropic(usage: crate::clients::anthropic::Usage) -> Self {\n Self {\n input_tokens: usage.input_tokens,\n output_tokens: usage.output_tokens,\n cached_write_tokens: usage.cache_creation_input_tokens,\n cached_read_tokens: usage.cache_read_input_tokens,\n total_tokens: usage.input_tokens + usage.output_tokens,\n total_cost: \"$0.00\".to_string(), // Cost will be calculated later\n }\n }\n}\n"], ["/deepclaude/src/models/mod.rs", "pub mod request;\npub mod response;\n\npub use request::*;\npub use response::*;\n"]], "task_instance_info": {"created_time": "2025-08-21 01:33:31", "created_task_model": "DeepSeek-R1", "function_skeleton": "async fn main () -> anyhow::Result<()> {}", "code_description": "This code segment functions to: Configure and initialize a web server with logging, security policies, and request routing while establishing shared application state and handling configuration loading with fallback defaults."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```rust\n[TASK_BEGIN]\nasync fn main() -> anyhow::Result<()> {\n // Initialize tracing subsystem\n tracing_subscriber::registry()\n .with(tracing_subscriber::EnvFilter::new(\n std::env::var(\"RUST_LOG\").unwrap_or_else(|_| \"deepclaude=info,tower_http=info\".into()),\n ))\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n // Load configuration\n let config = Config::load().await?;\n let state = Arc::new(AppState::new(config.clone()).await?);\n\n // Configure router with middleware\n let app = Router::new()\n .route(\"/v1/chat/completions\", post(handlers::chat_completion))\n .with_state(state)\n .layer(\n CorsLayer::new()\n .allow_origin(Any)\n .allow_methods(Any)\n .allow_headers(Any),\n )\n .layer(TraceLayer::new_for_http());\n\n // Start server\n let addr = SocketAddr::from(([0, 0, 0, 0], config.server.port));\n tracing::info!(\"Server listening on {}\", addr);\n axum::Server::bind(&addr)\n .serve(app.into_make_service())\n .await?;\n\n Ok(())\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 01-33-54"}, "editdistance_info": {"edit_distance": 44.5614, "calculate_time": "2025-08-21 01:33:54", "true_code_clean": "async fn main() -> anyhow::Result<()> {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env()\n .unwrap_or_else(|_| \"deepclaude=debug,tower_http=debug\".into()),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n let config = Config::load().unwrap_or_else(|_| {\n tracing::warn!(\"Failed to load config.toml, using default configuration\");\n Config::default()\n });\n let config_clone = config.clone();\n let state = Arc::new(AppState { config: config_clone });\n let cors = CorsLayer::new()\n .allow_methods(Any)\n .allow_headers(Any)\n .allow_origin(Any);\n let app = Router::new()\n .route(\"/\", post(handlers::handle_chat))\n .layer(TraceLayer::new_for_http())\n .layer(cors)\n .with_state(state);\n let addr: SocketAddr = format!(\"{}:{}\", config.server.host, config.server.port)\n .parse()\n .expect(\"Invalid host/port configuration\");\n tracing::info!(\"Starting server on {}\", addr);\n axum::serve(\n tokio::net::TcpListener::bind(&addr).await?,\n app.into_make_service(),\n )\n .await?;\n Ok(())\n}", "predict_code_clean": "async fn main() -> anyhow::Result<()> {\n tracing_subscriber::registry()\n .with(tracing_subscriber::EnvFilter::new(\n std::env::var(\"RUST_LOG\").unwrap_or_else(|_| \"deepclaude=info,tower_http=info\".into()),\n ))\n .with(tracing_subscriber::fmt::layer())\n .init();\n let config = Config::load().await?;\n let state = Arc::new(AppState::new(config.clone()).await?);\n let app = Router::new()\n .route(\"/v1/chat/completions\", post(handlers::chat_completion))\n .with_state(state)\n .layer(\n CorsLayer::new()\n .allow_origin(Any)\n .allow_methods(Any)\n .allow_headers(Any),\n )\n .layer(TraceLayer::new_for_http());\n let addr = SocketAddr::from(([0, 0, 0, 0], config.server.port));\n tracing::info!(\"Server listening on {}\", addr);\n axum::Server::bind(&addr)\n .serve(app.into_make_service())\n .await?;\n Ok(())\n}"}} {"repo_name": "deepclaude", "file_name": "/deepclaude/src/main.rs", "inference_info": {"prefix_code": "//! DeepClaude - A high-performance LLM inference API and Chat UI that integrates DeepSeek R1's CoT reasoning traces with Anthropic Claude models..\n//!\n//! This application provides a REST API for chat interactions that:\n//! - Processes messages through DeepSeek R1 for reasoning\n//! - Uses Anthropic's Claude for final responses\n//! - Supports both streaming and non-streaming responses\n//! - Tracks token usage and costs\n//! - Provides detailed usage statistics\n//!\n//! The API requires authentication tokens for both services and\n//! supports custom configuration through a TOML config file.\n\nmod clients;\nmod config;\nmod error;\nmod handlers;\nmod models;\n\nuse crate::{config::Config, handlers::AppState};\nuse axum::routing::{post, Router};\nuse std::{net::SocketAddr, sync::Arc};\nuse tower_http::{\n cors::{Any, CorsLayer},\n trace::TraceLayer,\n};\nuse tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};\n\n/// Application entry point.\n///\n/// Sets up logging, loads configuration, and starts the HTTP server\n/// with the configured routes and middleware.\n///\n/// # Returns\n///\n/// * `anyhow::Result<()>` - Ok if server starts successfully, Err otherwise\n///\n/// # Errors\n///\n/// Returns an error if:\n/// - Logging setup fails\n/// - Server address binding fails\n/// - Server encounters a fatal error while running\n#[tokio::main]\n", "suffix_code": "\n", "middle_code": "async fn main() -> anyhow::Result<()> {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env()\n .unwrap_or_else(|_| \"deepclaude=debug,tower_http=debug\".into()),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n let config = Config::load().unwrap_or_else(|_| {\n tracing::warn!(\"Failed to load config.toml, using default configuration\");\n Config::default()\n });\n let config_clone = config.clone();\n let state = Arc::new(AppState { config: config_clone });\n let cors = CorsLayer::new()\n .allow_methods(Any)\n .allow_headers(Any)\n .allow_origin(Any);\n let app = Router::new()\n .route(\"/\", post(handlers::handle_chat))\n .layer(TraceLayer::new_for_http())\n .layer(cors)\n .with_state(state);\n let addr: SocketAddr = format!(\"{}:{}\", config.server.host, config.server.port)\n .parse()\n .expect(\"Invalid host/port configuration\");\n tracing::info!(\"Starting server on {}\", addr);\n axum::serve(\n tokio::net::TcpListener::bind(&addr).await?,\n app.into_make_service(),\n )\n .await?;\n Ok(())\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "rust", "sub_task_type": null}, "context_code": [["/deepclaude/src/handlers.rs", "//! Request handlers for the API endpoints.\n//!\n//! This module contains the main request handlers and supporting functions\n//! for processing chat requests, including both streaming and non-streaming\n//! responses. It coordinates between different AI models and handles\n//! usage tracking and cost calculations.\n\nuse crate::{\n clients::{AnthropicClient, DeepSeekClient},\n config::Config,\n error::{ApiError, Result, SseResponse},\n models::{\n ApiRequest, ApiResponse, ContentBlock, CombinedUsage, DeepSeekUsage, AnthropicUsage,\n ExternalApiResponse, Message, Role, StreamEvent,\n },\n};\nuse axum::{\n extract::State,\n response::{sse::Event, IntoResponse},\n Json,\n};\nuse chrono::Utc;\nuse futures::StreamExt;\nuse std::{sync::Arc, collections::HashMap};\nuse tokio_stream::wrappers::ReceiverStream;\n\n/// Application state shared across request handlers.\n///\n/// Contains configuration that needs to be accessible\n/// to all request handlers.\npub struct AppState {\n pub config: Config,\n}\n\n/// Extracts API tokens from request headers.\n///\n/// # Arguments\n///\n/// * `headers` - The HTTP headers containing the API tokens\n///\n/// # Returns\n///\n/// * `Result<(String, String)>` - A tuple of (DeepSeek token, Anthropic token)\n///\n/// # Errors\n///\n/// Returns `ApiError::MissingHeader` if either token is missing\n/// Returns `ApiError::BadRequest` if tokens are malformed\nfn extract_api_tokens(\n headers: &axum::http::HeaderMap,\n) -> Result<(String, String)> {\n let deepseek_token = headers\n .get(\"X-DeepSeek-API-Token\")\n .ok_or_else(|| ApiError::MissingHeader { \n header: \"X-DeepSeek-API-Token\".to_string() \n })?\n .to_str()\n .map_err(|_| ApiError::BadRequest { \n message: \"Invalid DeepSeek API token\".to_string() \n })?\n .to_string();\n\n let anthropic_token = headers\n .get(\"X-Anthropic-API-Token\")\n .ok_or_else(|| ApiError::MissingHeader { \n header: \"X-Anthropic-API-Token\".to_string() \n })?\n .to_str()\n .map_err(|_| ApiError::BadRequest { \n message: \"Invalid Anthropic API token\".to_string() \n })?\n .to_string();\n\n Ok((deepseek_token, anthropic_token))\n}\n\n/// Calculates the cost of DeepSeek API usage.\n///\n/// # Arguments\n///\n/// * `input_tokens` - Number of input tokens processed\n/// * `output_tokens` - Number of output tokens generated\n/// * `_reasoning_tokens` - Number of tokens used for reasoning\n/// * `cached_tokens` - Number of tokens retrieved from cache\n/// * `config` - Configuration containing pricing information\n///\n/// # Returns\n///\n/// The total cost in dollars for the API usage\nfn calculate_deepseek_cost(\n input_tokens: u32,\n output_tokens: u32,\n _reasoning_tokens: u32,\n cached_tokens: u32,\n config: &Config,\n) -> f64 {\n let cache_hit_cost = (cached_tokens as f64 / 1_000_000.0) * config.pricing.deepseek.input_cache_hit_price;\n let cache_miss_cost = ((input_tokens - cached_tokens) as f64 / 1_000_000.0) * config.pricing.deepseek.input_cache_miss_price;\n let output_cost = (output_tokens as f64 / 1_000_000.0) * config.pricing.deepseek.output_price;\n \n cache_hit_cost + cache_miss_cost + output_cost\n}\n\n/// Calculates the cost of Anthropic API usage.\n///\n/// # Arguments\n///\n/// * `model` - The specific Claude model used\n/// * `input_tokens` - Number of input tokens processed\n/// * `output_tokens` - Number of output tokens generated\n/// * `cache_write_tokens` - Number of tokens written to cache\n/// * `cache_read_tokens` - Number of tokens read from cache\n/// * `config` - Configuration containing pricing information\n///\n/// # Returns\n///\n/// The total cost in dollars for the API usage\nfn calculate_anthropic_cost(\n model: &str,\n input_tokens: u32,\n output_tokens: u32,\n cache_write_tokens: u32,\n cache_read_tokens: u32,\n config: &Config,\n) -> f64 {\n let pricing = if model.contains(\"claude-3-5-sonnet\") {\n &config.pricing.anthropic.claude_3_sonnet\n } else if model.contains(\"claude-3-5-haiku\") {\n &config.pricing.anthropic.claude_3_haiku\n } else if model.contains(\"claude-3-opus\") {\n &config.pricing.anthropic.claude_3_opus\n } else {\n &config.pricing.anthropic.claude_3_sonnet // default to sonnet pricing\n };\n\n let input_cost = (input_tokens as f64 / 1_000_000.0) * pricing.input_price;\n let output_cost = (output_tokens as f64 / 1_000_000.0) * pricing.output_price;\n let cache_write_cost = (cache_write_tokens as f64 / 1_000_000.0) * pricing.cache_write_price;\n let cache_read_cost = (cache_read_tokens as f64 / 1_000_000.0) * pricing.cache_read_price;\n\n input_cost + output_cost + cache_write_cost + cache_read_cost\n}\n\n/// Formats a cost value as a dollar amount string.\n///\n/// # Arguments\n///\n/// * `cost` - The cost value to format\n///\n/// # Returns\n///\n/// A string representing the cost with 3 decimal places and $ prefix\nfn format_cost(cost: f64) -> String {\n format!(\"${:.3}\", cost)\n}\n\n/// Main handler for chat requests.\n///\n/// Routes requests to either streaming or non-streaming handlers\n/// based on the request configuration.\n///\n/// # Arguments\n///\n/// * `state` - Application state containing configuration\n/// * `headers` - HTTP request headers\n/// * `request` - The parsed chat request\n///\n/// # Returns\n///\n/// * `Result` - The API response or an error\npub async fn handle_chat(\n state: State>,\n headers: axum::http::HeaderMap,\n Json(request): Json,\n) -> Result {\n if request.stream {\n let stream_response = chat_stream(state, headers, Json(request)).await?;\n Ok(stream_response.into_response())\n } else {\n let json_response = chat(state, headers, Json(request)).await?;\n Ok(json_response.into_response())\n }\n}\n\n/// Handler for non-streaming chat requests.\n///\n/// Processes the request through both AI models sequentially,\n/// combining their responses and tracking usage.\n///\n/// # Arguments\n///\n/// * `state` - Application state containing configuration\n/// * `headers` - HTTP request headers\n/// * `request` - The parsed chat request\n///\n/// # Returns\n///\n/// * `Result>` - The combined API response or an error\npub(crate) async fn chat(\n State(state): State>,\n headers: axum::http::HeaderMap,\n Json(request): Json,\n) -> Result> {\n // Validate system prompt\n if !request.validate_system_prompt() {\n return Err(ApiError::InvalidSystemPrompt);\n }\n\n // Extract API tokens\n let (deepseek_token, anthropic_token) = extract_api_tokens(&headers)?;\n\n // Initialize clients\n let deepseek_client = DeepSeekClient::new(deepseek_token);\n let anthropic_client = AnthropicClient::new(anthropic_token);\n\n // Get messages with system prompt\n let messages = request.get_messages_with_system();\n\n // Call DeepSeek API\n let deepseek_response = deepseek_client.chat(messages.clone(), &request.deepseek_config).await?;\n \n // Store response metadata\n let deepseek_status: u16 = 200;\n let deepseek_headers = HashMap::new(); // Headers not available when using high-level chat method\n\n // Extract reasoning content and wrap in thinking tags\n let reasoning_content = deepseek_response\n .choices\n .first()\n .and_then(|c| c.message.reasoning_content.as_ref())\n .ok_or_else(|| ApiError::DeepSeekError { \n message: \"No reasoning content in response\".to_string(),\n type_: \"missing_content\".to_string(),\n param: None,\n code: None\n })?;\n\n let thinking_content = format!(\"\\n{}\\n\", reasoning_content);\n\n // Add thinking content to messages for Anthropic\n let mut anthropic_messages = messages;\n anthropic_messages.push(Message {\n role: Role::Assistant,\n content: thinking_content.clone(),\n });\n\n // Call Anthropic API\n let anthropic_response = anthropic_client.chat(\n anthropic_messages,\n request.get_system_prompt().map(String::from),\n &request.anthropic_config\n ).await?;\n \n // Store response metadata\n let anthropic_status: u16 = 200;\n let anthropic_headers = HashMap::new(); // Headers not available when using high-level chat method\n\n // Calculate usage costs\n let deepseek_cost = calculate_deepseek_cost(\n deepseek_response.usage.prompt_tokens,\n deepseek_response.usage.completion_tokens,\n deepseek_response.usage.completion_tokens_details.reasoning_tokens,\n deepseek_response.usage.prompt_tokens_details.cached_tokens,\n &state.config,\n );\n\n let anthropic_cost = calculate_anthropic_cost(\n &anthropic_response.model,\n anthropic_response.usage.input_tokens,\n anthropic_response.usage.output_tokens,\n anthropic_response.usage.cache_creation_input_tokens,\n anthropic_response.usage.cache_read_input_tokens,\n &state.config,\n );\n\n // Combine thinking content with Anthropic's response\n let mut content = Vec::new();\n \n // Add thinking block first\n content.push(ContentBlock::text(thinking_content));\n \n // Add Anthropic's response blocks\n content.extend(anthropic_response.content.clone().into_iter()\n .map(ContentBlock::from_anthropic));\n\n // Build response with captured headers\n let response = ApiResponse {\n created: Utc::now(),\n content,\n deepseek_response: request.verbose.then(|| ExternalApiResponse {\n status: deepseek_status,\n headers: deepseek_headers,\n body: serde_json::to_value(&deepseek_response).unwrap_or_default(),\n }),\n anthropic_response: request.verbose.then(|| ExternalApiResponse {\n status: anthropic_status,\n headers: anthropic_headers,\n body: serde_json::to_value(&anthropic_response).unwrap_or_default(),\n }),\n combined_usage: CombinedUsage {\n total_cost: format_cost(deepseek_cost + anthropic_cost),\n deepseek_usage: DeepSeekUsage {\n input_tokens: deepseek_response.usage.prompt_tokens,\n output_tokens: deepseek_response.usage.completion_tokens,\n reasoning_tokens: deepseek_response.usage.completion_tokens_details.reasoning_tokens,\n cached_input_tokens: deepseek_response.usage.prompt_tokens_details.cached_tokens,\n total_tokens: deepseek_response.usage.total_tokens,\n total_cost: format_cost(deepseek_cost),\n },\n anthropic_usage: AnthropicUsage {\n input_tokens: anthropic_response.usage.input_tokens,\n output_tokens: anthropic_response.usage.output_tokens,\n cached_write_tokens: anthropic_response.usage.cache_creation_input_tokens,\n cached_read_tokens: anthropic_response.usage.cache_read_input_tokens,\n total_tokens: anthropic_response.usage.input_tokens + anthropic_response.usage.output_tokens,\n total_cost: format_cost(anthropic_cost),\n },\n },\n };\n\n Ok(Json(response))\n}\n\n/// Handler for streaming chat requests.\n///\n/// Processes the request through both AI models sequentially,\n/// streaming their responses as Server-Sent Events.\n///\n/// # Arguments\n///\n/// * `state` - Application state containing configuration\n/// * `headers` - HTTP request headers\n/// * `request` - The parsed chat request\n///\n/// # Returns\n///\n/// * `Result` - A stream of Server-Sent Events or an error\npub(crate) async fn chat_stream(\n State(state): State>,\n headers: axum::http::HeaderMap,\n Json(request): Json,\n) -> Result {\n // Validate system prompt\n if !request.validate_system_prompt() {\n return Err(ApiError::InvalidSystemPrompt);\n }\n\n // Extract API tokens\n let (deepseek_token, anthropic_token) = extract_api_tokens(&headers)?;\n\n // Initialize clients\n let deepseek_client = DeepSeekClient::new(deepseek_token);\n let anthropic_client = AnthropicClient::new(anthropic_token);\n\n // Get messages with system prompt\n let messages = request.get_messages_with_system();\n\n // Create channel for stream events\n let (tx, rx) = tokio::sync::mpsc::channel(100);\n let tx = Arc::new(tx);\n\n // Spawn task to handle streaming\n let config = state.config.clone();\n let request_clone = request.clone();\n tokio::spawn(async move {\n let tx = tx.clone();\n\n // Start event\n let _ = tx\n .send(Ok(Event::default().event(\"start\").data(\n serde_json::to_string(&StreamEvent::Start {\n created: Utc::now(),\n })\n .unwrap_or_default(),\n )))\n .await;\n\n // Send initial thinking tag\n let _ = tx\n .send(Ok(Event::default().event(\"content\").data(\n serde_json::to_string(&StreamEvent::Content {\n content: vec![ContentBlock {\n content_type: \"text\".to_string(),\n text: \"\\n\".to_string(),\n }],\n })\n .unwrap_or_default(),\n )))\n .await;\n\n // Stream from DeepSeek\n let mut deepseek_usage = None;\n let mut complete_reasoning = String::new();\n let mut deepseek_stream = deepseek_client.chat_stream(messages.clone(), &request_clone.deepseek_config);\n \n while let Some(chunk) = deepseek_stream.next().await {\n match chunk {\n Ok(response) => {\n if let Some(choice) = response.choices.first() {\n // Check if reasoning_content is null and break if it is\n if choice.delta.reasoning_content.is_none() {\n break;\n }\n\n // Handle delta reasoning_content for streaming\n if let Some(reasoning) = &choice.delta.reasoning_content {\n if !reasoning.is_empty() {\n // Stream the reasoning content as a delta\n let _ = tx\n .send(Ok(Event::default().event(\"content\").data(\n serde_json::to_string(&StreamEvent::Content {\n content: vec![ContentBlock {\n content_type: \"text_delta\".to_string(),\n text: reasoning.to_string(),\n }],\n })\n .unwrap_or_default(),\n )))\n .await;\n \n // Accumulate complete reasoning for later use\n complete_reasoning.push_str(reasoning);\n }\n }\n }\n \n // Store usage information if present\n if let Some(usage) = response.usage {\n deepseek_usage = Some(usage);\n }\n }\n Err(e) => {\n let _ = tx\n .send(Ok(Event::default().event(\"error\").data(\n serde_json::to_string(&StreamEvent::Error {\n message: e.to_string(),\n code: 500,\n })\n .unwrap_or_default(),\n )))\n .await;\n return;\n }\n }\n }\n\n // Send closing thinking tag\n let _ = tx\n .send(Ok(Event::default().event(\"content\").data(\n serde_json::to_string(&StreamEvent::Content {\n content: vec![ContentBlock {\n content_type: \"text\".to_string(),\n text: \"\\n\".to_string(),\n }],\n })\n .unwrap_or_default(),\n )))\n .await;\n\n // Add complete thinking content to messages for Anthropic\n let mut anthropic_messages = messages;\n anthropic_messages.push(Message {\n role: Role::Assistant,\n content: format!(\"\\n{}\\n\", complete_reasoning),\n });\n\n // Stream from Anthropic\n let mut anthropic_stream = anthropic_client.chat_stream(\n anthropic_messages,\n request_clone.get_system_prompt().map(String::from),\n &request_clone.anthropic_config,\n );\n\n while let Some(chunk) = anthropic_stream.next().await {\n match chunk {\n Ok(event) => match event {\n crate::clients::anthropic::StreamEvent::MessageStart { message } => {\n // Only send content event if there's actual content to send\n if !message.content.is_empty() {\n let _ = tx\n .send(Ok(Event::default().event(\"content\").data(\n serde_json::to_string(&StreamEvent::Content { \n content: message.content.into_iter()\n .map(ContentBlock::from_anthropic)\n .collect()\n })\n .unwrap_or_default(),\n )))\n .await;\n }\n }\n crate::clients::anthropic::StreamEvent::ContentBlockDelta { delta, .. } => {\n // Send content update\n let _ = tx\n .send(Ok(Event::default().event(\"content\").data(\n serde_json::to_string(&StreamEvent::Content {\n content: vec![ContentBlock {\n content_type: delta.delta_type,\n text: delta.text,\n }],\n })\n .unwrap_or_default(),\n )))\n .await;\n }\n crate::clients::anthropic::StreamEvent::MessageDelta { usage, .. } => {\n // Send final usage stats if available\n if let Some(usage) = usage {\n let anthropic_usage = AnthropicUsage::from_anthropic(usage);\n let anthropic_cost = calculate_anthropic_cost(\n \"claude-3-5-sonnet-20241022\", // Default model\n anthropic_usage.input_tokens,\n anthropic_usage.output_tokens,\n anthropic_usage.cached_write_tokens,\n anthropic_usage.cached_read_tokens,\n &config,\n );\n\n // Calculate DeepSeek costs if usage is available\n let (deepseek_usage, deepseek_cost) = if let Some(usage) = deepseek_usage.as_ref() {\n let cost = calculate_deepseek_cost(\n usage.prompt_tokens,\n usage.completion_tokens,\n usage.completion_tokens_details.reasoning_tokens,\n usage.prompt_tokens_details.cached_tokens,\n &config,\n );\n \n (DeepSeekUsage {\n input_tokens: usage.prompt_tokens,\n output_tokens: usage.completion_tokens,\n reasoning_tokens: usage.completion_tokens_details.reasoning_tokens,\n cached_input_tokens: usage.prompt_tokens_details.cached_tokens,\n total_tokens: usage.total_tokens,\n total_cost: format_cost(cost),\n }, cost)\n } else {\n (DeepSeekUsage {\n input_tokens: 0,\n output_tokens: 0,\n reasoning_tokens: 0,\n cached_input_tokens: 0,\n total_tokens: 0,\n total_cost: \"$0.00\".to_string(),\n }, 0.0)\n };\n\n let _ = tx\n .send(Ok(Event::default().event(\"usage\").data(\n serde_json::to_string(&StreamEvent::Usage {\n usage: CombinedUsage {\n total_cost: format_cost(deepseek_cost + anthropic_cost),\n deepseek_usage,\n anthropic_usage: AnthropicUsage {\n input_tokens: anthropic_usage.input_tokens,\n output_tokens: anthropic_usage.output_tokens,\n cached_write_tokens: anthropic_usage.cached_write_tokens,\n cached_read_tokens: anthropic_usage.cached_read_tokens,\n total_tokens: anthropic_usage.total_tokens,\n total_cost: format_cost(anthropic_cost),\n },\n },\n })\n .unwrap_or_default(),\n )))\n .await;\n }\n }\n _ => {} // Handle other events if needed\n },\n Err(e) => {\n let _ = tx\n .send(Ok(Event::default().event(\"error\").data(\n serde_json::to_string(&StreamEvent::Error {\n message: e.to_string(),\n code: 500,\n })\n .unwrap_or_default(),\n )))\n .await;\n return;\n }\n }\n }\n\n // Send done event\n let _ = tx\n .send(Ok(Event::default().event(\"done\").data(\n serde_json::to_string(&StreamEvent::Done)\n .unwrap_or_default(),\n )))\n .await;\n });\n\n // Convert receiver into stream\n let stream = ReceiverStream::new(rx);\n Ok(SseResponse::new(stream))\n}\n"], ["/deepclaude/src/clients/anthropic.rs", "//! Anthropic API client implementation for interacting with Claude models.\n//!\n//! This module provides a client implementation for communicating with Anthropic's API,\n//! specifically designed to work with Claude language models. It supports both streaming\n//! and non-streaming interactions, handling all aspects of API communication including:\n//!\n//! - Authentication and request signing\n//! - Message formatting and serialization\n//! - Response parsing and deserialization\n//! - Error handling and type conversion\n//! - Streaming response processing\n//!\n//! # Main Components\n//!\n//! - [`AnthropicClient`]: The main client struct for making API requests\n//! - [`AnthropicResponse`]: Represents the structured response from the API\n//! - [`StreamEvent`]: Represents different types of events in streaming responses\n//!\n//! # Example Usage\n//!\n//! ```no_run\n//! use deepclaude::clients::AnthropicClient;\n//! use deepclaude::models::{Message, ApiConfig};\n//!\n//! async fn example() -> Result<(), Box> {\n//! let client = AnthropicClient::new(\"your-api-key\".to_string());\n//! let messages = vec![/* your messages */];\n//! let config = ApiConfig::default();\n//!\n//! // Non-streaming request\n//! let response = client.chat(messages.clone(), None, &config).await?;\n//!\n//! // Streaming request\n//! let stream = client.chat_stream(messages, None, &config);\n//! Ok(())\n//! }\n//! ```\n\nuse crate::{\n error::{ApiError, Result},\n models::{ApiConfig, Message, Role},\n};\nuse futures::Stream;\nuse reqwest::{header::HeaderMap, Client};\nuse serde::{Deserialize, Serialize};\nuse std::{collections::HashMap, pin::Pin};\nuse futures::StreamExt;\nuse serde_json;\n\npub(crate) const ANTHROPIC_API_URL: &str = \"https://api.anthropic.com/v1/messages\";\nconst DEFAULT_MODEL: &str = \"claude-3-5-sonnet-20241022\";\n\n/// Client for interacting with Anthropic's Claude models.\n///\n/// This client handles authentication, request construction, and response parsing\n/// for both streaming and non-streaming interactions with Anthropic's API.\n///\n/// # Examples\n///\n/// ```no_run\n/// use deepclaude::clients::AnthropicClient;\n///\n/// let client = AnthropicClient::new(\"api_token\".to_string());\n/// ```\n#[derive(Debug)]\npub struct AnthropicClient {\n pub(crate) client: Client,\n api_token: String,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct AnthropicResponse {\n pub id: String,\n #[serde(rename = \"type\")]\n pub response_type: String,\n pub role: String,\n pub model: String,\n pub content: Vec,\n pub stop_reason: Option,\n pub stop_sequence: Option,\n pub usage: Usage,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct ContentBlock {\n #[serde(rename = \"type\")]\n pub content_type: String,\n pub text: String,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct Usage {\n pub input_tokens: u32,\n pub output_tokens: u32,\n pub cache_creation_input_tokens: u32,\n pub cache_read_input_tokens: u32,\n}\n\n#[derive(Debug, Serialize, Deserialize)]\npub(crate) struct AnthropicRequest {\n messages: Vec,\n stream: bool,\n #[serde(skip_serializing_if = \"Option::is_none\")]\n system: Option,\n #[serde(flatten)]\n additional_params: serde_json::Value,\n}\n\n#[derive(Debug, Serialize, Deserialize)]\npub(crate) struct AnthropicMessage {\n role: String,\n content: String,\n}\n\n// Event types for streaming responses\n#[derive(Debug, Deserialize)]\n#[serde(tag = \"type\")]\npub enum StreamEvent {\n #[serde(rename = \"message_start\")]\n MessageStart {\n message: AnthropicResponse,\n },\n #[serde(rename = \"content_block_start\")]\n #[allow(dead_code)]\n ContentBlockStart {\n index: usize,\n content_block: ContentBlock,\n },\n #[serde(rename = \"content_block_delta\")]\n #[allow(dead_code)]\n ContentBlockDelta {\n index: usize,\n delta: ContentDelta,\n },\n #[serde(rename = \"content_block_stop\")]\n #[allow(dead_code)]\n ContentBlockStop {\n index: usize,\n },\n #[serde(rename = \"message_delta\")]\n #[allow(dead_code)]\n MessageDelta {\n delta: MessageDelta,\n usage: Option,\n },\n #[serde(rename = \"message_stop\")]\n MessageStop,\n #[serde(rename = \"ping\")]\n Ping,\n}\n\n#[derive(Debug, Deserialize, Clone)]\npub struct ContentDelta {\n #[serde(rename = \"type\")]\n pub delta_type: String,\n pub text: String,\n}\n\n#[derive(Debug, Deserialize, Clone)]\n#[allow(dead_code)]\npub struct MessageDelta {\n pub stop_reason: Option,\n pub stop_sequence: Option,\n}\n\nimpl AnthropicClient {\n /// Creates a new Anthropic client instance.\n ///\n /// # Arguments\n ///\n /// * `api_token` - API token for authentication with Anthropic's API\n ///\n /// # Returns\n ///\n /// A new `AnthropicClient` instance configured with the provided API token\n pub fn new(api_token: String) -> Self {\n Self {\n client: Client::new(),\n api_token,\n }\n }\n\n /// Builds the HTTP headers required for Anthropic API requests.\n ///\n /// # Arguments\n ///\n /// * `custom_headers` - Optional additional headers to include in requests\n ///\n /// # Returns\n ///\n /// * `Result` - The constructed headers on success, or an error if header construction fails\n ///\n /// # Errors\n ///\n /// Returns `ApiError::Internal` if:\n /// - The API token is invalid\n /// - Content-Type or Anthropic-Version headers cannot be constructed\n pub(crate) fn build_headers(&self, custom_headers: Option<&HashMap>) -> Result {\n let mut headers = HeaderMap::new();\n headers.insert(\n \"x-api-key\",\n self.api_token\n .parse()\n .map_err(|e| ApiError::Internal { \n message: format!(\"Invalid API token: {}\", e) \n })?,\n );\n headers.insert(\n \"content-type\",\n \"application/json\"\n .parse()\n .map_err(|e| ApiError::Internal { \n message: format!(\"Invalid content type: {}\", e) \n })?,\n );\n headers.insert(\n \"anthropic-version\",\n \"2023-06-01\"\n .parse()\n .map_err(|e| ApiError::Internal { \n message: format!(\"Invalid anthropic version: {}\", e) \n })?,\n );\n\n if let Some(custom) = custom_headers {\n headers.extend(super::build_headers(custom)?);\n }\n\n Ok(headers)\n }\n\n /// Constructs a request object for the Anthropic API.\n ///\n /// # Arguments\n ///\n /// * `messages` - Vector of messages to send to the model\n /// * `system` - Optional system prompt to set context\n /// * `stream` - Whether to enable streaming mode\n /// * `config` - Configuration options for the request\n ///\n /// # Returns\n ///\n /// An `AnthropicRequest` object configured with the provided parameters and defaults\n pub(crate) fn build_request(\n &self,\n messages: Vec,\n system: Option,\n stream: bool,\n config: &ApiConfig,\n ) -> AnthropicRequest {\n let filtered_messages = messages\n .into_iter()\n .filter(|msg| msg.role != Role::System)\n .map(|msg| AnthropicMessage {\n role: match msg.role {\n Role::User => \"user\".to_string(),\n Role::Assistant => \"assistant\".to_string(),\n Role::System => unreachable!(),\n },\n content: msg.content,\n })\n .collect();\n\n // Create base request with required fields\n let default_model = serde_json::json!(DEFAULT_MODEL);\n let model_value = config.body.get(\"model\").unwrap_or(&default_model);\n \n let default_max_tokens = if let Some(model_str) = model_value.as_str() {\n if model_str.contains(\"claude-3-opus\") {\n 4096\n } else {\n 8192\n }\n } else {\n 8192\n };\n let default_max_tokens_json = serde_json::json!(default_max_tokens);\n\n let mut request_value = serde_json::json!({\n \"messages\": filtered_messages,\n \"stream\": stream,\n \"model\": model_value,\n \"max_tokens\": config.body.get(\"max_tokens\").unwrap_or(&default_max_tokens_json)\n });\n\n // Add system if present\n if let Some(ref sys) = system {\n if let serde_json::Value::Object(mut map) = request_value {\n map.insert(\"system\".to_string(), serde_json::json!(sys));\n request_value = serde_json::Value::Object(map);\n }\n }\n\n // Merge additional configuration from config.body while protecting critical fields\n if let serde_json::Value::Object(mut map) = request_value {\n if let serde_json::Value::Object(mut body) = serde_json::to_value(&config.body).unwrap_or_default() {\n // Remove protected fields from config body\n body.remove(\"stream\");\n body.remove(\"messages\");\n body.remove(\"system\");\n \n // Merge remaining fields from config.body\n for (key, value) in body {\n map.insert(key, value);\n }\n }\n request_value = serde_json::Value::Object(map);\n }\n\n // Convert the merged JSON value into our request structure\n serde_json::from_value(request_value).unwrap_or_else(|_| AnthropicRequest {\n messages: filtered_messages,\n stream,\n system,\n additional_params: config.body.clone(),\n })\n }\n\n /// Sends a non-streaming chat request to the Anthropic API.\n ///\n /// # Arguments\n ///\n /// * `messages` - Vector of messages for the conversation\n /// * `system` - Optional system prompt to set context\n /// * `config` - Configuration options for the request\n ///\n /// # Returns\n ///\n /// * `Result` - The model's response on success\n ///\n /// # Errors\n ///\n /// Returns `ApiError::AnthropicError` if:\n /// - The API request fails\n /// - The response status is not successful\n /// - The response cannot be parsed\n pub async fn chat(\n &self,\n messages: Vec,\n system: Option,\n config: &ApiConfig,\n ) -> Result {\n let headers = self.build_headers(Some(&config.headers))?;\n let request = self.build_request(messages, system, false, config);\n\n let response = self\n .client\n .post(ANTHROPIC_API_URL)\n .headers(headers)\n .json(&request)\n .send()\n .await\n .map_err(|e| ApiError::AnthropicError { \n message: format!(\"Request failed: {}\", e),\n type_: \"request_failed\".to_string(),\n param: None,\n code: None\n })?;\n\n if !response.status().is_success() {\n let error = response\n .text()\n .await\n .unwrap_or_else(|_| \"Unknown error\".to_string());\n return Err(ApiError::AnthropicError { \n message: error,\n type_: \"api_error\".to_string(),\n param: None,\n code: None\n });\n }\n\n response\n .json::()\n .await\n .map_err(|e| ApiError::AnthropicError { \n message: format!(\"Failed to parse response: {}\", e),\n type_: \"parse_error\".to_string(),\n param: None,\n code: None\n })\n }\n\n /// Sends a streaming chat request to the Anthropic API.\n ///\n /// Returns a stream that yields events from the model's response as they arrive.\n ///\n /// # Arguments\n ///\n /// * `messages` - Vector of messages for the conversation\n /// * `system` - Optional system prompt to set context\n /// * `config` - Configuration options for the request\n ///\n /// # Returns\n ///\n /// * `Pin> + Send>>` - A stream of response events\n ///\n /// # Errors\n ///\n /// The stream may yield `ApiError::AnthropicError` if:\n /// - The API request fails\n /// - Stream processing encounters an error\n /// - Response events cannot be parsed\n pub fn chat_stream(\n &self,\n messages: Vec,\n system: Option,\n config: &ApiConfig,\n ) -> Pin> + Send>> {\n let headers = match self.build_headers(Some(&config.headers)) {\n Ok(h) => h,\n Err(e) => return Box::pin(futures::stream::once(async move { Err(e) })),\n };\n\n let request = self.build_request(messages, system, true, config);\n let client = self.client.clone();\n\n Box::pin(async_stream::try_stream! {\n let mut stream = client\n .post(ANTHROPIC_API_URL)\n .headers(headers)\n .json(&request)\n .send()\n .await\n .map_err(|e| ApiError::AnthropicError { \n message: format!(\"Request failed: {}\", e),\n type_: \"request_failed\".to_string(),\n param: None,\n code: None\n })?\n .bytes_stream();\n\n let mut data = String::new();\n \n while let Some(chunk) = stream.next().await {\n let chunk = chunk.map_err(|e| ApiError::AnthropicError { \n message: format!(\"Stream error: {}\", e),\n type_: \"stream_error\".to_string(),\n param: None,\n code: None\n })?;\n data.push_str(&String::from_utf8_lossy(&chunk));\n\n let mut start = 0;\n while let Some(end) = data[start..].find(\"\\n\\n\") {\n let end = start + end;\n let event_data = &data[start..end];\n start = end + 2;\n\n if event_data.starts_with(\"event: \") {\n let _event_line = &event_data[\"event: \".len()..];\n if let Some(data_line) = event_data.lines().nth(1) {\n if data_line.starts_with(\"data: \") {\n let json_data = &data_line[\"data: \".len()..];\n if let Ok(event) = serde_json::from_str::(json_data) {\n yield event;\n }\n }\n }\n }\n }\n\n if start > 0 {\n data = data[start..].to_string();\n }\n }\n })\n }\n}\n\n/// Converts an Anthropic content block into the application's generic content block type.\nimpl From for crate::models::response::ContentBlock {\n fn from(block: ContentBlock) -> Self {\n Self {\n content_type: block.content_type,\n text: block.text,\n }\n }\n}\n"], ["/deepclaude/src/clients/deepseek.rs", "//! DeepSeek API client implementation for interacting with DeepSeek's AI models.\n//!\n//! This module provides a client implementation for making requests to DeepSeek's chat completion API.\n//! It supports both streaming and non-streaming interactions, handling authentication, request\n//! construction, and response parsing.\n//!\n//! # Features\n//!\n//! - Supports chat completions with DeepSeek's AI models\n//! - Handles both streaming and non-streaming responses\n//! - Configurable request parameters (model, max tokens, temperature)\n//! - Custom header support\n//! - Comprehensive error handling\n//!\n//! # Examples\n//!\n//! ```no_run\n//! use crate::{\n//! clients::DeepSeekClient,\n//! models::{ApiConfig, Message},\n//! };\n//!\n//! # async fn example() -> Result<(), Box> {\n//! // Initialize the client\n//! let client = DeepSeekClient::new(\"your-api-key\".to_string());\n//!\n//! // Prepare messages and configuration\n//! let messages = vec![Message {\n//! role: \"user\".to_string(),\n//! content: \"Hello, how are you?\".to_string(),\n//! }];\n//!\n//! let config = ApiConfig::default();\n//!\n//! // Make a non-streaming request\n//! let response = client.chat(messages.clone(), &config).await?;\n//!\n//! // Or use streaming for real-time responses\n//! let mut stream = client.chat_stream(messages, &config);\n//! while let Some(chunk) = stream.next().await {\n//! println!(\"Received chunk: {:?}\", chunk?);\n//! }\n//! # Ok(())\n//! # }\n//! ```\n//!\n//! # Error Handling\n//!\n//! The client uses a custom error type `ApiError` to handle various failure cases:\n//! - Network errors\n//! - API authentication errors\n//! - Invalid response formats\n//! - Stream processing errors\n//!\n//! All public methods return `Result` types with appropriate error variants.\n\nuse crate::{\n error::{ApiError, Result},\n models::{ApiConfig, Message},\n};\nuse futures::Stream;\nuse reqwest::{header::HeaderMap, Client};\nuse serde::{Deserialize, Serialize};\nuse std::{collections::HashMap, pin::Pin};\nuse futures::StreamExt;\nuse serde_json;\n\npub(crate) const DEEPSEEK_API_URL: &str = \"https://api.deepseek.com/chat/completions\";\nconst DEFAULT_MODEL: &str = \"deepseek-reasoner\";\n\n/// Client for interacting with DeepSeek's AI models.\n///\n/// This client handles authentication, request construction, and response parsing\n/// for both streaming and non-streaming interactions with DeepSeek's API.\n///\n/// # Examples\n///\n/// ```no_run\n/// use deepclaude::clients::DeepSeekClient;\n///\n/// let client = DeepSeekClient::new(\"api_token\".to_string());\n/// ```\n#[derive(Debug)]\npub struct DeepSeekClient {\n pub(crate) client: Client,\n api_token: String,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct DeepSeekResponse {\n pub id: String,\n pub object: String,\n pub created: i64,\n pub model: String,\n pub choices: Vec,\n pub usage: Usage,\n pub system_fingerprint: String,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct Choice {\n pub index: i32,\n pub message: AssistantMessage,\n pub logprobs: Option,\n pub finish_reason: Option,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct AssistantMessage {\n pub role: String,\n pub content: Option,\n pub reasoning_content: Option,\n}\n\n// Streaming response types\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct StreamChoice {\n pub index: i32,\n pub delta: StreamDelta,\n pub logprobs: Option,\n pub finish_reason: Option,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct StreamDelta {\n pub role: Option,\n pub content: Option,\n pub reasoning_content: Option,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct StreamResponse {\n pub id: String,\n pub object: String,\n pub created: i64,\n pub model: String,\n pub choices: Vec,\n pub usage: Option,\n pub system_fingerprint: String,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct Usage {\n pub prompt_tokens: u32,\n pub completion_tokens: u32,\n pub total_tokens: u32,\n pub prompt_tokens_details: PromptTokensDetails,\n pub completion_tokens_details: CompletionTokensDetails,\n pub prompt_cache_hit_tokens: u32,\n pub prompt_cache_miss_tokens: u32,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct PromptTokensDetails {\n pub cached_tokens: u32,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct CompletionTokensDetails {\n pub reasoning_tokens: u32,\n}\n\n#[derive(Debug, Serialize, Deserialize)]\npub(crate) struct DeepSeekRequest {\n messages: Vec,\n stream: bool,\n #[serde(flatten)]\n additional_params: serde_json::Value,\n}\n\nimpl DeepSeekClient {\n pub fn new(api_token: String) -> Self {\n Self {\n client: Client::new(),\n api_token,\n }\n }\n\n /// Builds the HTTP headers required for DeepSeek API requests.\n ///\n /// # Arguments\n ///\n /// * `custom_headers` - Optional additional headers to include in requests\n ///\n /// # Returns\n ///\n /// * `Result` - The constructed headers on success, or an error if header construction fails\n ///\n /// # Errors\n ///\n /// Returns `ApiError::Internal` if:\n /// - The API token is invalid\n /// - Content-Type or Accept headers cannot be constructed\n pub(crate) fn build_headers(&self, custom_headers: Option<&HashMap>) -> Result {\n let mut headers = HeaderMap::new();\n headers.insert(\n \"Authorization\",\n format!(\"Bearer {}\", self.api_token)\n .parse()\n .map_err(|e| ApiError::Internal { \n message: format!(\"Invalid API token: {}\", e) \n })?,\n );\n headers.insert(\n \"Content-Type\",\n \"application/json\"\n .parse()\n .map_err(|e| ApiError::Internal { \n message: format!(\"Invalid content type: {}\", e) \n })?,\n );\n headers.insert(\n \"Accept\",\n \"application/json\"\n .parse()\n .map_err(|e| ApiError::Internal { \n message: format!(\"Invalid accept header: {}\", e) \n })?,\n );\n\n if let Some(custom) = custom_headers {\n headers.extend(super::build_headers(custom)?);\n }\n\n Ok(headers)\n }\n\n /// Constructs a request object for the DeepSeek API.\n ///\n /// # Arguments\n ///\n /// * `messages` - Vector of messages to send to the model\n /// * `stream` - Whether to enable streaming mode\n /// * `config` - Configuration options for the request\n ///\n /// # Returns\n ///\n /// A `DeepSeekRequest` object configured with the provided parameters and defaults\n pub(crate) fn build_request(&self, messages: Vec, stream: bool, config: &ApiConfig) -> DeepSeekRequest {\n // Create a base request with required fields\n let mut request_value = serde_json::json!({\n \"messages\": messages,\n \"stream\": stream,\n // Set defaults only if not provided in config\n \"model\": config.body.get(\"model\").unwrap_or(&serde_json::json!(DEFAULT_MODEL)),\n \"max_tokens\": config.body.get(\"max_tokens\").unwrap_or(&serde_json::json!(8192)),\n \"temperature\": config.body.get(\"temperature\").unwrap_or(&serde_json::json!(1.0)),\n \"response_format\": {\n \"type\": \"text\"\n }\n });\n\n // Merge additional configuration from config.body while protecting critical fields\n if let serde_json::Value::Object(mut map) = request_value {\n if let serde_json::Value::Object(mut body) = serde_json::to_value(&config.body).unwrap_or_default() {\n // Remove protected fields from config body\n body.remove(\"stream\");\n body.remove(\"messages\");\n \n // Merge remaining fields from config.body\n for (key, value) in body {\n map.insert(key, value);\n }\n }\n request_value = serde_json::Value::Object(map);\n }\n\n // Convert the merged JSON value into our request structure\n serde_json::from_value(request_value).unwrap_or_else(|_| DeepSeekRequest {\n messages,\n stream,\n additional_params: config.body.clone(),\n })\n }\n\n /// Sends a non-streaming chat request to the DeepSeek API.\n ///\n /// # Arguments\n ///\n /// * `messages` - Vector of messages for the conversation\n /// * `config` - Configuration options for the request\n ///\n /// # Returns\n ///\n /// * `Result` - The model's response on success\n ///\n /// # Errors\n ///\n /// Returns `ApiError::DeepSeekError` if:\n /// - The API request fails\n /// - The response status is not successful\n /// - The response cannot be parsed\n pub async fn chat(\n &self,\n messages: Vec,\n config: &ApiConfig,\n ) -> Result {\n let headers = self.build_headers(Some(&config.headers))?;\n let request = self.build_request(messages, false, config);\n\n let response = self\n .client\n .post(DEEPSEEK_API_URL)\n .headers(headers)\n .json(&request)\n .send()\n .await\n .map_err(|e| ApiError::DeepSeekError { \n message: format!(\"Request failed: {}\", e),\n type_: \"request_failed\".to_string(),\n param: None,\n code: None\n })?;\n\n if !response.status().is_success() {\n let error = response\n .text()\n .await\n .unwrap_or_else(|_| \"Unknown error\".to_string());\n return Err(ApiError::DeepSeekError { \n message: error,\n type_: \"api_error\".to_string(),\n param: None,\n code: None\n });\n }\n\n response\n .json::()\n .await\n .map_err(|e| ApiError::DeepSeekError { \n message: format!(\"Failed to parse response: {}\", e),\n type_: \"parse_error\".to_string(),\n param: None,\n code: None\n })\n }\n\n /// Sends a streaming chat request to the DeepSeek API.\n ///\n /// Returns a stream that yields chunks of the model's response as they arrive.\n ///\n /// # Arguments\n ///\n /// * `messages` - Vector of messages for the conversation\n /// * `config` - Configuration options for the request\n ///\n /// # Returns\n ///\n /// * `Pin> + Send>>` - A stream of response chunks\n ///\n /// # Errors\n ///\n /// The stream may yield `ApiError::DeepSeekError` if:\n /// - The API request fails\n /// - Stream processing encounters an error\n /// - Response chunks cannot be parsed\n pub fn chat_stream(\n &self,\n messages: Vec,\n config: &ApiConfig,\n ) -> Pin> + Send>> {\n let headers = match self.build_headers(Some(&config.headers)) {\n Ok(h) => h,\n Err(e) => return Box::pin(futures::stream::once(async move { Err(e) })),\n };\n\n let request = self.build_request(messages, true, config);\n let client = self.client.clone();\n\n Box::pin(async_stream::try_stream! {\n let mut stream = client\n .post(DEEPSEEK_API_URL)\n .headers(headers)\n .json(&request)\n .send()\n .await\n .map_err(|e| ApiError::DeepSeekError { \n message: format!(\"Request failed: {}\", e),\n type_: \"request_failed\".to_string(),\n param: None,\n code: None\n })?\n .bytes_stream();\n\n let mut data = String::new();\n \n while let Some(chunk) = stream.next().await {\n let chunk = chunk.map_err(|e| ApiError::DeepSeekError { \n message: format!(\"Stream error: {}\", e),\n type_: \"stream_error\".to_string(),\n param: None,\n code: None\n })?;\n data.push_str(&String::from_utf8_lossy(&chunk));\n\n let mut start = 0;\n while let Some(end) = data[start..].find(\"\\n\\n\") {\n let end = start + end;\n let line = &data[start..end].trim();\n start = end + 2;\n \n if line.starts_with(\"data: \") {\n let json_data = &line[\"data: \".len()..];\n if let Ok(response) = serde_json::from_str::(json_data) {\n yield response;\n }\n }\n }\n\n if start > 0 {\n data = data[start..].to_string();\n }\n }\n })\n }\n}\n"], ["/deepclaude/src/config.rs", "//! Configuration management for the application.\n//!\n//! This module handles loading and managing configuration settings from files\n//! and environment variables. It includes pricing configurations for different\n//! AI model providers and server settings.\n\nuse serde::{Deserialize, Serialize};\nuse std::path::Path;\n\n/// Root configuration structure containing all application settings.\n///\n/// This structure is typically loaded from a TOML configuration file\n/// and provides access to all configurable aspects of the application.\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct Config {\n pub server: ServerConfig,\n pub pricing: PricingConfig,\n}\n\n/// Server-specific configuration settings.\n///\n/// Contains settings related to the HTTP server, such as the\n/// host address and port number to bind to.\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct ServerConfig {\n pub host: String,\n pub port: u16,\n}\n\n/// Pricing configuration for all supported AI models.\n///\n/// Contains pricing information for different AI model providers\n/// and their various models, used for usage cost calculation.\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct PricingConfig {\n pub deepseek: DeepSeekPricing,\n pub anthropic: AnthropicPricing,\n}\n\n/// DeepSeek-specific pricing configuration.\n///\n/// Contains pricing rates for different aspects of DeepSeek API usage,\n/// including cached and non-cached requests.\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct DeepSeekPricing {\n pub input_cache_hit_price: f64, // per million tokens\n pub input_cache_miss_price: f64, // per million tokens\n pub output_price: f64, // per million tokens\n}\n\n/// Anthropic-specific pricing configuration.\n///\n/// Contains pricing information for different Claude model variants\n/// and their associated costs.\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct AnthropicPricing {\n pub claude_3_sonnet: ModelPricing,\n pub claude_3_haiku: ModelPricing,\n pub claude_3_opus: ModelPricing,\n}\n\n/// Generic model pricing configuration.\n///\n/// Contains detailed pricing information for a specific model,\n/// including input, output, and caching costs.\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct ModelPricing {\n pub input_price: f64, // per million tokens\n pub output_price: f64, // per million tokens\n pub cache_write_price: f64, // per million tokens\n pub cache_read_price: f64, // per million tokens\n}\n\nimpl Config {\n /// Loads configuration from the default config file.\n ///\n /// Attempts to load and parse the configuration from 'config.toml'.\n /// Falls back to default values if the file cannot be loaded or parsed.\n ///\n /// # Returns\n ///\n /// * `anyhow::Result` - The loaded configuration or an error if loading fails\n ///\n /// # Errors\n ///\n /// Returns an error if:\n /// - The config file cannot be read\n /// - The TOML content cannot be parsed\n /// - The parsed content doesn't match the expected structure\n pub fn load() -> anyhow::Result {\n let config_path = Path::new(\"config.toml\");\n let config = config::Config::builder()\n .add_source(config::File::from(config_path))\n .build()?;\n\n Ok(config.try_deserialize()?)\n }\n}\n\n/// Provides default configuration values.\n///\n/// These defaults are used when a configuration file is not present\n/// or when specific values are not provided in the config file.\nimpl Default for Config {\n fn default() -> Self {\n Self {\n server: ServerConfig {\n host: \"127.0.0.1\".to_string(),\n port: 3000,\n },\n pricing: PricingConfig {\n deepseek: DeepSeekPricing {\n input_cache_hit_price: 0.14,\n input_cache_miss_price: 0.55,\n output_price: 2.19,\n },\n anthropic: AnthropicPricing {\n claude_3_sonnet: ModelPricing {\n input_price: 3.0,\n output_price: 15.0,\n cache_write_price: 3.75,\n cache_read_price: 0.30,\n },\n claude_3_haiku: ModelPricing {\n input_price: 0.80,\n output_price: 4.0,\n cache_write_price: 1.0,\n cache_read_price: 0.08,\n },\n claude_3_opus: ModelPricing {\n input_price: 15.0,\n output_price: 75.0,\n cache_write_price: 18.75,\n cache_read_price: 1.50,\n },\n },\n },\n }\n }\n}\n"], ["/deepclaude/src/error.rs", "//! Error handling types and implementations for the application.\n//!\n//! This module provides a comprehensive error handling system including:\n//! - Custom error types for various failure scenarios\n//! - Conversion implementations for common error types\n//! - Response formatting for API errors\n//! - Type aliases for common Result types\n\nuse axum::{\n http::StatusCode,\n response::{IntoResponse, Response, sse::Event},\n Json,\n};\nuse serde::{Deserialize, Serialize};\nuse std::convert::Infallible;\nuse thiserror::Error;\nuse tokio_stream::wrappers::ReceiverStream;\n\n/// Response structure for API errors.\n///\n/// This structure provides a consistent format for error responses\n/// returned by the API endpoints.\n#[derive(Debug, Serialize, Deserialize)]\npub struct ErrorResponse {\n pub error: ErrorDetails,\n}\n\n/// Detailed error information included in error responses.\n///\n/// Contains specific information about what went wrong, including:\n/// - A human-readable error message\n/// - The type of error that occurred\n/// - Optional parameter that caused the error\n/// - Optional error code for more specific error handling\n#[derive(Debug, Serialize, Deserialize)]\npub struct ErrorDetails {\n pub message: String,\n #[serde(rename = \"type\")]\n pub type_: String,\n #[serde(skip_serializing_if = \"Option::is_none\")]\n pub param: Option,\n #[serde(skip_serializing_if = \"Option::is_none\")]\n pub code: Option,\n}\n\n/// Enumeration of all possible API errors.\n///\n/// This enum represents all the different types of errors that can occur\n/// during API operations, including validation errors, external API errors,\n/// and internal server errors.\n#[derive(Error, Debug, Clone)]\npub enum ApiError {\n #[error(\"Invalid request: {message}\")]\n BadRequest {\n message: String,\n },\n\n #[error(\"Missing required header: {header}\")]\n MissingHeader {\n header: String,\n },\n\n #[error(\"Invalid system prompt configuration\")]\n InvalidSystemPrompt,\n\n #[error(\"DeepSeek API error: {message}\")]\n DeepSeekError {\n message: String,\n type_: String,\n param: Option,\n code: Option,\n },\n\n #[error(\"Anthropic API error: {message}\")]\n AnthropicError {\n message: String,\n type_: String,\n param: Option,\n code: Option,\n },\n\n #[error(\"Internal server error: {message}\")]\n Internal {\n message: String,\n },\n\n #[error(\"Other error: {message}\")]\n Other {\n message: String,\n },\n}\n\n/// Implements conversion of API errors into HTTP responses.\n///\n/// Maps each error variant to an appropriate HTTP status code and\n/// formats the error details into a consistent JSON response structure.\nimpl IntoResponse for ApiError {\n fn into_response(self) -> Response {\n let (status, error_response) = match &self {\n ApiError::BadRequest { message } => (\n StatusCode::BAD_REQUEST,\n ErrorResponse {\n error: ErrorDetails {\n message: message.clone(),\n type_: \"bad_request\".to_string(),\n param: None,\n code: None,\n },\n },\n ),\n ApiError::MissingHeader { header } => (\n StatusCode::BAD_REQUEST,\n ErrorResponse {\n error: ErrorDetails {\n message: format!(\"Missing required header: {}\", header),\n type_: \"missing_header\".to_string(),\n param: Some(header.clone()),\n code: None,\n },\n },\n ),\n ApiError::InvalidSystemPrompt => (\n StatusCode::BAD_REQUEST,\n ErrorResponse {\n error: ErrorDetails {\n message: \"System prompt can only be provided once, either in root or messages array\".to_string(),\n type_: \"invalid_system_prompt\".to_string(),\n param: None,\n code: None,\n },\n },\n ),\n ApiError::DeepSeekError { message, type_, param, code } => (\n StatusCode::BAD_REQUEST,\n ErrorResponse {\n error: ErrorDetails {\n message: format!(\"DeepSeek API Error: {}\", message),\n type_: format!(\"deepseek_{}\", type_),\n param: param.clone(),\n code: code.clone(),\n },\n },\n ),\n ApiError::AnthropicError { message, type_, param, code } => (\n StatusCode::BAD_REQUEST,\n ErrorResponse {\n error: ErrorDetails {\n message: format!(\"Anthropic API Error: {}\", message),\n type_: format!(\"anthropic_{}\", type_),\n param: param.clone(),\n code: code.clone(),\n },\n },\n ),\n ApiError::Internal { message } => (\n StatusCode::INTERNAL_SERVER_ERROR,\n ErrorResponse {\n error: ErrorDetails {\n message: message.clone(),\n type_: \"internal_error\".to_string(),\n param: None,\n code: None,\n },\n },\n ),\n ApiError::Other { message } => (\n StatusCode::INTERNAL_SERVER_ERROR,\n ErrorResponse {\n error: ErrorDetails {\n message: format!(\"Internal server error: {}\", message),\n type_: \"internal_error\".to_string(),\n param: None,\n code: None,\n },\n },\n ),\n };\n\n (status, Json(error_response)).into_response()\n }\n}\n\n/// Converts generic errors into API errors.\n///\n/// This implementation allows using the `?` operator with functions that\n/// return `anyhow::Error`, converting them into our custom `ApiError` type.\nimpl From for ApiError {\n fn from(err: anyhow::Error) -> Self {\n ApiError::Other { \n message: err.to_string() \n }\n }\n}\n\n/// Type alias for Results using our custom ApiError type.\n///\n/// This provides a convenient way to use Result with our ApiError\n/// throughout the application.\npub type Result = std::result::Result;\n\n/// Type alias for Server-Sent Events (SSE) results.\n///\n/// Used for streaming responses where errors are converted to Infallible\n/// since they are handled within the stream.\npub type SseResult = std::result::Result;\n\n/// Type alias for SSE streams.\n///\n/// Represents a stream of SSE results that can be sent to clients.\npub type SseStream = ReceiverStream;\n\n/// Type alias for SSE responses.\n///\n/// Represents the complete SSE response type used by the API endpoints.\npub type SseResponse = axum::response::sse::Sse;\n"], ["/deepclaude/src/clients/mod.rs", "//! Client implementations for external AI model providers.\n//!\n//! This module contains client implementations for different AI model providers:\n//! - `anthropic`: Client for Anthropic's Claude models\n//! - `deepseek`: Client for DeepSeek's reasoning models\n//!\n//! Each client handles authentication, request building, and response parsing\n//! specific to its provider's API.\n\npub mod anthropic;\npub mod deepseek;\n\npub use anthropic::AnthropicClient;\npub use deepseek::DeepSeekClient;\n\nuse crate::error::Result;\nuse reqwest::header::{HeaderMap, HeaderName, HeaderValue};\nuse std::collections::HashMap;\n\n/// Converts a HashMap of string headers to a reqwest HeaderMap.\n///\n/// This function is used internally by clients to convert user-provided\n/// header maps into the format required by reqwest.\n///\n/// # Arguments\n///\n/// * `headers` - A HashMap containing header names and values as strings\n///\n/// # Returns\n///\n/// * `Result` - The converted HeaderMap on success, or an error if\n/// any header name or value is invalid\n///\n/// # Errors\n///\n/// Returns `ApiError::BadRequest` if:\n/// - A header name contains invalid characters\n/// - A header value contains invalid characters\npub(crate) fn build_headers(headers: &HashMap) -> Result {\n let mut header_map = HeaderMap::new();\n \n for (key, value) in headers {\n let header_name = HeaderName::from_bytes(key.as_bytes())\n .map_err(|e| crate::error::ApiError::BadRequest { \n message: format!(\"Invalid header name: {}\", e) \n })?;\n \n let header_value = HeaderValue::from_str(value)\n .map_err(|e| crate::error::ApiError::BadRequest { \n message: format!(\"Invalid header value: {}\", e) \n })?;\n \n header_map.insert(header_name, header_value);\n }\n \n Ok(header_map)\n}\n"], ["/deepclaude/src/models/request.rs", "//! Request models for the API endpoints.\n//!\n//! This module defines the structures used to represent incoming API requests,\n//! including chat messages, configuration options, and request parameters.\n\nuse serde::{Deserialize, Serialize};\nuse std::collections::HashMap;\n\n/// Primary request structure for chat API endpoints.\n///\n/// This structure represents a complete chat request, including messages,\n/// system prompts, and configuration options for both DeepSeek and Anthropic APIs.\n#[derive(Debug, Clone, Deserialize, Serialize)]\npub struct ApiRequest {\n #[serde(default)]\n pub stream: bool,\n \n #[serde(default)]\n pub verbose: bool,\n \n pub system: Option,\n pub messages: Vec,\n \n #[serde(default)]\n pub deepseek_config: ApiConfig,\n \n #[serde(default)]\n pub anthropic_config: ApiConfig,\n}\n\n/// A single message in a chat conversation.\n///\n/// Represents one message in the conversation history, including\n/// its role (system, user, or assistant) and content.\n#[derive(Debug, Clone, Deserialize, Serialize)]\npub struct Message {\n pub role: Role,\n pub content: String,\n}\n\n/// Possible roles for a message in a chat conversation.\n///\n/// Each message must be associated with one of these roles to\n/// properly structure the conversation flow.\n#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]\n#[serde(rename_all = \"lowercase\")]\npub enum Role {\n System,\n User,\n Assistant,\n}\n\n/// Configuration options for external API requests.\n///\n/// Contains headers and body parameters that will be passed\n/// to the external AI model APIs.\n#[derive(Debug, Clone, Default, Deserialize, Serialize)]\npub struct ApiConfig {\n #[serde(default)]\n pub headers: HashMap,\n \n #[serde(default)]\n pub body: serde_json::Value,\n}\n\nimpl ApiRequest {\n /// Validates that system prompts are not duplicated.\n ///\n /// Checks that a system prompt is not provided in both the root level\n /// and messages array. The system prompt itself is optional.\n ///\n /// # Returns\n ///\n /// * `bool` - True if system prompt validation passes (no duplicates), false otherwise\n pub fn validate_system_prompt(&self) -> bool {\n let system_in_messages = self.messages.iter().any(|msg| matches!(msg.role, Role::System));\n \n // Only invalid if system prompt is provided in both places\n !(self.system.is_some() && system_in_messages)\n }\n\n /// Returns messages with the system prompt in the correct position.\n ///\n /// Ensures the system prompt (if present) is the first message,\n /// followed by the conversation messages in order.\n ///\n /// # Returns\n ///\n /// * `Vec` - Messages with system prompt correctly positioned\n pub fn get_messages_with_system(&self) -> Vec {\n let mut messages = Vec::new();\n\n // Add system message first\n if let Some(system) = &self.system {\n messages.push(Message {\n role: Role::System,\n content: system.clone(),\n });\n }\n\n // Add remaining messages\n messages.extend(self.messages.iter().filter(|msg| !matches!(msg.role, Role::System)).cloned());\n\n messages\n }\n\n /// Retrieves the system prompt if one is present.\n ///\n /// Checks both the root level system field and the messages array\n /// for a system prompt.\n ///\n /// # Returns\n ///\n /// * `Option<&str>` - The system prompt if found, None otherwise\n pub fn get_system_prompt(&self) -> Option<&str> {\n self.system.as_deref().or_else(|| {\n self.messages\n .iter()\n .find(|msg| matches!(msg.role, Role::System))\n .map(|msg| msg.content.as_str())\n })\n }\n}\n"], ["/deepclaude/src/models/response.rs", "//! Response models for the API endpoints.\n//!\n//! This module defines the structures used to represent API responses,\n//! including chat completions, usage statistics, and streaming events.\n\nuse chrono::{DateTime, Utc};\nuse serde::{Deserialize, Serialize};\nuse std::collections::HashMap;\n\n/// Primary response structure for chat API endpoints.\n///\n/// Contains the complete response from both AI models, including\n/// content blocks, usage statistics, and optional raw API responses.\n#[derive(Debug, Serialize, Clone)]\npub struct ApiResponse {\n pub created: DateTime,\n pub content: Vec,\n \n #[serde(skip_serializing_if = \"Option::is_none\")]\n pub deepseek_response: Option,\n \n #[serde(skip_serializing_if = \"Option::is_none\")]\n pub anthropic_response: Option,\n \n pub combined_usage: CombinedUsage,\n}\n\n/// A block of content in a response.\n///\n/// Represents a single piece of content in the response,\n/// with its type and actual text content.\n#[derive(Debug, Serialize, Deserialize, Clone)]\npub struct ContentBlock {\n #[serde(rename = \"type\")]\n pub content_type: String,\n pub text: String,\n}\n\n/// Raw response from an external API.\n///\n/// Contains the complete response details from an external API\n/// call, including status code, headers, and response body.\n#[derive(Debug, Serialize, Clone)]\npub struct ExternalApiResponse {\n pub status: u16,\n pub headers: HashMap,\n pub body: serde_json::Value,\n}\n\n/// Combined usage statistics from both AI models.\n///\n/// Aggregates token usage and cost information from both\n/// DeepSeek and Anthropic API calls.\n#[derive(Debug, Serialize, Clone)]\npub struct CombinedUsage {\n pub total_cost: String,\n pub deepseek_usage: DeepSeekUsage,\n pub anthropic_usage: AnthropicUsage,\n}\n\n/// Usage statistics for DeepSeek API calls.\n///\n/// Tracks token consumption and costs specific to\n/// DeepSeek model usage.\n#[derive(Debug, Serialize, Clone)]\npub struct DeepSeekUsage {\n pub input_tokens: u32,\n pub output_tokens: u32,\n pub reasoning_tokens: u32,\n pub cached_input_tokens: u32,\n pub total_tokens: u32,\n pub total_cost: String,\n}\n\n/// Usage statistics for Anthropic API calls.\n///\n/// Tracks token consumption and costs specific to\n/// Anthropic model usage.\n#[derive(Debug, Serialize, Clone)]\npub struct AnthropicUsage {\n pub input_tokens: u32,\n pub output_tokens: u32,\n pub cached_write_tokens: u32,\n pub cached_read_tokens: u32,\n pub total_tokens: u32,\n pub total_cost: String,\n}\n\n// Streaming event types\n/// Events emitted during streaming responses.\n///\n/// Represents different types of events that can occur\n/// during a streaming response, including content updates\n/// and usage statistics.\n#[derive(Debug, Serialize)]\n#[serde(tag = \"type\")]\npub enum StreamEvent {\n #[serde(rename = \"start\")]\n Start {\n created: DateTime,\n },\n \n #[serde(rename = \"content\")]\n Content {\n content: Vec,\n },\n \n #[serde(rename = \"usage\")]\n Usage {\n usage: CombinedUsage,\n },\n \n #[serde(rename = \"done\")]\n Done,\n \n #[serde(rename = \"error\")]\n Error {\n message: String,\n code: u16,\n },\n}\n\nimpl ContentBlock {\n /// Creates a new text content block.\n ///\n /// # Arguments\n ///\n /// * `text` - The text content to include in the block\n ///\n /// # Returns\n ///\n /// A new `ContentBlock` with the type set to \"text\"\n pub fn text(text: impl Into) -> Self {\n Self {\n content_type: \"text\".to_string(),\n text: text.into(),\n }\n }\n\n /// Converts an Anthropic content block to a generic content block.\n ///\n /// # Arguments\n ///\n /// * `block` - The Anthropic-specific content block to convert\n ///\n /// # Returns\n ///\n /// A new `ContentBlock` with the same content type and text\n pub fn from_anthropic(block: crate::clients::anthropic::ContentBlock) -> Self {\n Self {\n content_type: block.content_type,\n text: block.text,\n }\n }\n}\n\nimpl ApiResponse {\n /// Creates a new API response with simple text content.\n ///\n /// # Arguments\n ///\n /// * `content` - The text content for the response\n ///\n /// # Returns\n ///\n /// A new `ApiResponse` with default values and the provided content\n #[allow(dead_code)]\n pub fn new(content: impl Into) -> Self {\n Self {\n created: Utc::now(),\n content: vec![ContentBlock::text(content)],\n deepseek_response: None,\n anthropic_response: None,\n combined_usage: CombinedUsage {\n total_cost: \"$0.00\".to_string(),\n deepseek_usage: DeepSeekUsage {\n input_tokens: 0,\n output_tokens: 0,\n reasoning_tokens: 0,\n cached_input_tokens: 0,\n total_tokens: 0,\n total_cost: \"$0.00\".to_string(),\n },\n anthropic_usage: AnthropicUsage {\n input_tokens: 0,\n output_tokens: 0,\n cached_write_tokens: 0,\n cached_read_tokens: 0,\n total_tokens: 0,\n total_cost: \"$0.00\".to_string(),\n },\n },\n }\n }\n}\n\nimpl AnthropicUsage {\n /// Converts Anthropic usage statistics to the generic usage format.\n ///\n /// # Arguments\n ///\n /// * `usage` - The Anthropic-specific usage statistics to convert\n ///\n /// # Returns\n ///\n /// A new `AnthropicUsage` with values copied from the Anthropic usage\n pub fn from_anthropic(usage: crate::clients::anthropic::Usage) -> Self {\n Self {\n input_tokens: usage.input_tokens,\n output_tokens: usage.output_tokens,\n cached_write_tokens: usage.cache_creation_input_tokens,\n cached_read_tokens: usage.cache_read_input_tokens,\n total_tokens: usage.input_tokens + usage.output_tokens,\n total_cost: \"$0.00\".to_string(), // Cost will be calculated later\n }\n }\n}\n"], ["/deepclaude/src/models/mod.rs", "pub mod request;\npub mod response;\n\npub use request::*;\npub use response::*;\n"]], "task_instance_info": {"created_time": "2025-08-21 01:33:31", "created_task_model": "DeepSeek-R1", "function_skeleton": "async fn main () -> anyhow::Result<()> {}", "code_description": "This code segment functions to: Configure the application's runtime environment by initializing logging subsystems, loading service configurations, establishing HTTP server infrastructure with cross-origin resource sharing policies, and defining primary API endpoints while implementing middleware for request observability and state management."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```rust\n[TASK_BEGIN]\nasync fn main() -> anyhow::Result<()> {\n // Initialize tracing subsystem\n tracing_subscriber::registry()\n .with(tracing_subscriber::EnvFilter::new(\n std::env::var(\"RUST_LOG\").unwrap_or_else(|_| \"deepclaude=debug,tower_http=debug\".into()),\n ))\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n // Load configuration\n let config = Config::load().await?;\n \n // Create service clients\n let deepseek_client = clients::DeepSeekClient::new(config.deepseek_api_key.clone());\n let claude_client = clients::ClaudeClient::new(config.claude_api_key.clone());\n \n // Initialize shared application state\n let state = Arc::new(AppState {\n deepseek: deepseek_client,\n claude: claude_client,\n usage_tracker: models::UsageTracker::default(),\n });\n\n // Configure router with middleware\n let router = Router::new()\n .route(\"/v1/chat/completions\", post(handlers::chat_completion))\n .route(\"/v1/chat/completions/stream\", post(handlers::streaming_chat_completion))\n .with_state(state)\n .layer(CorsLayer::new().allow_origin(Any).allow_headers(Any).allow_methods(Any))\n .layer(TraceLayer::new_for_http());\n\n // Start server\n let addr = SocketAddr::from(([0, 0, 0, 0], config.port));\n tracing::debug!(\"Starting server on {}\", addr);\n axum::Server::bind(&addr)\n .serve(router.into_make_service())\n .await?;\n\n Ok(())\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 01-34-14"}, "editdistance_info": {"edit_distance": 37.3418, "calculate_time": "2025-08-21 01:34:14", "true_code_clean": "async fn main() -> anyhow::Result<()> {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env()\n .unwrap_or_else(|_| \"deepclaude=debug,tower_http=debug\".into()),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n let config = Config::load().unwrap_or_else(|_| {\n tracing::warn!(\"Failed to load config.toml, using default configuration\");\n Config::default()\n });\n let config_clone = config.clone();\n let state = Arc::new(AppState { config: config_clone });\n let cors = CorsLayer::new()\n .allow_methods(Any)\n .allow_headers(Any)\n .allow_origin(Any);\n let app = Router::new()\n .route(\"/\", post(handlers::handle_chat))\n .layer(TraceLayer::new_for_http())\n .layer(cors)\n .with_state(state);\n let addr: SocketAddr = format!(\"{}:{}\", config.server.host, config.server.port)\n .parse()\n .expect(\"Invalid host/port configuration\");\n tracing::info!(\"Starting server on {}\", addr);\n axum::serve(\n tokio::net::TcpListener::bind(&addr).await?,\n app.into_make_service(),\n )\n .await?;\n Ok(())\n}", "predict_code_clean": "async fn main() -> anyhow::Result<()> {\n tracing_subscriber::registry()\n .with(tracing_subscriber::EnvFilter::new(\n std::env::var(\"RUST_LOG\").unwrap_or_else(|_| \"deepclaude=debug,tower_http=debug\".into()),\n ))\n .with(tracing_subscriber::fmt::layer())\n .init();\n let config = Config::load().await?;\n let deepseek_client = clients::DeepSeekClient::new(config.deepseek_api_key.clone());\n let claude_client = clients::ClaudeClient::new(config.claude_api_key.clone());\n let state = Arc::new(AppState {\n deepseek: deepseek_client,\n claude: claude_client,\n usage_tracker: models::UsageTracker::default(),\n });\n let router = Router::new()\n .route(\"/v1/chat/completions\", post(handlers::chat_completion))\n .route(\"/v1/chat/completions/stream\", post(handlers::streaming_chat_completion))\n .with_state(state)\n .layer(CorsLayer::new().allow_origin(Any).allow_headers(Any).allow_methods(Any))\n .layer(TraceLayer::new_for_http());\n let addr = SocketAddr::from(([0, 0, 0, 0], config.port));\n tracing::debug!(\"Starting server on {}\", addr);\n axum::Server::bind(&addr)\n .serve(router.into_make_service())\n .await?;\n Ok(())\n}"}} {"repo_name": "deepclaude", "file_name": "/deepclaude/src/clients/deepseek.rs", "inference_info": {"prefix_code": "//! DeepSeek API client implementation for interacting with DeepSeek's AI models.\n//!\n//! This module provides a client implementation for making requests to DeepSeek's chat completion API.\n//! It supports both streaming and non-streaming interactions, handling authentication, request\n//! construction, and response parsing.\n//!\n//! # Features\n//!\n//! - Supports chat completions with DeepSeek's AI models\n//! - Handles both streaming and non-streaming responses\n//! - Configurable request parameters (model, max tokens, temperature)\n//! - Custom header support\n//! - Comprehensive error handling\n//!\n//! # Examples\n//!\n//! ```no_run\n//! use crate::{\n//! clients::DeepSeekClient,\n//! models::{ApiConfig, Message},\n//! };\n//!\n//! # async fn example() -> Result<(), Box> {\n//! // Initialize the client\n//! let client = DeepSeekClient::new(\"your-api-key\".to_string());\n//!\n//! // Prepare messages and configuration\n//! let messages = vec![Message {\n//! role: \"user\".to_string(),\n//! content: \"Hello, how are you?\".to_string(),\n//! }];\n//!\n//! let config = ApiConfig::default();\n//!\n//! // Make a non-streaming request\n//! let response = client.chat(messages.clone(), &config).await?;\n//!\n//! // Or use streaming for real-time responses\n//! let mut stream = client.chat_stream(messages, &config);\n//! while let Some(chunk) = stream.next().await {\n//! println!(\"Received chunk: {:?}\", chunk?);\n//! }\n//! # Ok(())\n//! # }\n//! ```\n//!\n//! # Error Handling\n//!\n//! The client uses a custom error type `ApiError` to handle various failure cases:\n//! - Network errors\n//! - API authentication errors\n//! - Invalid response formats\n//! - Stream processing errors\n//!\n//! All public methods return `Result` types with appropriate error variants.\n\nuse crate::{\n error::{ApiError, Result},\n models::{ApiConfig, Message},\n};\nuse futures::Stream;\nuse reqwest::{header::HeaderMap, Client};\nuse serde::{Deserialize, Serialize};\nuse std::{collections::HashMap, pin::Pin};\nuse futures::StreamExt;\nuse serde_json;\n\npub(crate) const DEEPSEEK_API_URL: &str = \"https://api.deepseek.com/chat/completions\";\nconst DEFAULT_MODEL: &str = \"deepseek-reasoner\";\n\n/// Client for interacting with DeepSeek's AI models.\n///\n/// This client handles authentication, request construction, and response parsing\n/// for both streaming and non-streaming interactions with DeepSeek's API.\n///\n/// # Examples\n///\n/// ```no_run\n/// use deepclaude::clients::DeepSeekClient;\n///\n/// let client = DeepSeekClient::new(\"api_token\".to_string());\n/// ```\n#[derive(Debug)]\npub struct DeepSeekClient {\n pub(crate) client: Client,\n api_token: String,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct DeepSeekResponse {\n pub id: String,\n pub object: String,\n pub created: i64,\n pub model: String,\n pub choices: Vec,\n pub usage: Usage,\n pub system_fingerprint: String,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct Choice {\n pub index: i32,\n pub message: AssistantMessage,\n pub logprobs: Option,\n pub finish_reason: Option,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct AssistantMessage {\n pub role: String,\n pub content: Option,\n pub reasoning_content: Option,\n}\n\n// Streaming response types\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct StreamChoice {\n pub index: i32,\n pub delta: StreamDelta,\n pub logprobs: Option,\n pub finish_reason: Option,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct StreamDelta {\n pub role: Option,\n pub content: Option,\n pub reasoning_content: Option,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct StreamResponse {\n pub id: String,\n pub object: String,\n pub created: i64,\n pub model: String,\n pub choices: Vec,\n pub usage: Option,\n pub system_fingerprint: String,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct Usage {\n pub prompt_tokens: u32,\n pub completion_tokens: u32,\n pub total_tokens: u32,\n pub prompt_tokens_details: PromptTokensDetails,\n pub completion_tokens_details: CompletionTokensDetails,\n pub prompt_cache_hit_tokens: u32,\n pub prompt_cache_miss_tokens: u32,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct PromptTokensDetails {\n pub cached_tokens: u32,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct CompletionTokensDetails {\n pub reasoning_tokens: u32,\n}\n\n#[derive(Debug, Serialize, Deserialize)]\npub(crate) struct DeepSeekRequest {\n messages: Vec,\n stream: bool,\n #[serde(flatten)]\n additional_params: serde_json::Value,\n}\n\nimpl DeepSeekClient {\n pub fn new(api_token: String) -> Self {\n Self {\n client: Client::new(),\n api_token,\n }\n }\n\n /// Builds the HTTP headers required for DeepSeek API requests.\n ///\n /// # Arguments\n ///\n /// * `custom_headers` - Optional additional headers to include in requests\n ///\n /// # Returns\n ///\n /// * `Result` - The constructed headers on success, or an error if header construction fails\n ///\n /// # Errors\n ///\n /// Returns `ApiError::Internal` if:\n /// - The API token is invalid\n /// - Content-Type or Accept headers cannot be constructed\n ", "suffix_code": "\n\n /// Constructs a request object for the DeepSeek API.\n ///\n /// # Arguments\n ///\n /// * `messages` - Vector of messages to send to the model\n /// * `stream` - Whether to enable streaming mode\n /// * `config` - Configuration options for the request\n ///\n /// # Returns\n ///\n /// A `DeepSeekRequest` object configured with the provided parameters and defaults\n pub(crate) fn build_request(&self, messages: Vec, stream: bool, config: &ApiConfig) -> DeepSeekRequest {\n // Create a base request with required fields\n let mut request_value = serde_json::json!({\n \"messages\": messages,\n \"stream\": stream,\n // Set defaults only if not provided in config\n \"model\": config.body.get(\"model\").unwrap_or(&serde_json::json!(DEFAULT_MODEL)),\n \"max_tokens\": config.body.get(\"max_tokens\").unwrap_or(&serde_json::json!(8192)),\n \"temperature\": config.body.get(\"temperature\").unwrap_or(&serde_json::json!(1.0)),\n \"response_format\": {\n \"type\": \"text\"\n }\n });\n\n // Merge additional configuration from config.body while protecting critical fields\n if let serde_json::Value::Object(mut map) = request_value {\n if let serde_json::Value::Object(mut body) = serde_json::to_value(&config.body).unwrap_or_default() {\n // Remove protected fields from config body\n body.remove(\"stream\");\n body.remove(\"messages\");\n \n // Merge remaining fields from config.body\n for (key, value) in body {\n map.insert(key, value);\n }\n }\n request_value = serde_json::Value::Object(map);\n }\n\n // Convert the merged JSON value into our request structure\n serde_json::from_value(request_value).unwrap_or_else(|_| DeepSeekRequest {\n messages,\n stream,\n additional_params: config.body.clone(),\n })\n }\n\n /// Sends a non-streaming chat request to the DeepSeek API.\n ///\n /// # Arguments\n ///\n /// * `messages` - Vector of messages for the conversation\n /// * `config` - Configuration options for the request\n ///\n /// # Returns\n ///\n /// * `Result` - The model's response on success\n ///\n /// # Errors\n ///\n /// Returns `ApiError::DeepSeekError` if:\n /// - The API request fails\n /// - The response status is not successful\n /// - The response cannot be parsed\n pub async fn chat(\n &self,\n messages: Vec,\n config: &ApiConfig,\n ) -> Result {\n let headers = self.build_headers(Some(&config.headers))?;\n let request = self.build_request(messages, false, config);\n\n let response = self\n .client\n .post(DEEPSEEK_API_URL)\n .headers(headers)\n .json(&request)\n .send()\n .await\n .map_err(|e| ApiError::DeepSeekError { \n message: format!(\"Request failed: {}\", e),\n type_: \"request_failed\".to_string(),\n param: None,\n code: None\n })?;\n\n if !response.status().is_success() {\n let error = response\n .text()\n .await\n .unwrap_or_else(|_| \"Unknown error\".to_string());\n return Err(ApiError::DeepSeekError { \n message: error,\n type_: \"api_error\".to_string(),\n param: None,\n code: None\n });\n }\n\n response\n .json::()\n .await\n .map_err(|e| ApiError::DeepSeekError { \n message: format!(\"Failed to parse response: {}\", e),\n type_: \"parse_error\".to_string(),\n param: None,\n code: None\n })\n }\n\n /// Sends a streaming chat request to the DeepSeek API.\n ///\n /// Returns a stream that yields chunks of the model's response as they arrive.\n ///\n /// # Arguments\n ///\n /// * `messages` - Vector of messages for the conversation\n /// * `config` - Configuration options for the request\n ///\n /// # Returns\n ///\n /// * `Pin> + Send>>` - A stream of response chunks\n ///\n /// # Errors\n ///\n /// The stream may yield `ApiError::DeepSeekError` if:\n /// - The API request fails\n /// - Stream processing encounters an error\n /// - Response chunks cannot be parsed\n pub fn chat_stream(\n &self,\n messages: Vec,\n config: &ApiConfig,\n ) -> Pin> + Send>> {\n let headers = match self.build_headers(Some(&config.headers)) {\n Ok(h) => h,\n Err(e) => return Box::pin(futures::stream::once(async move { Err(e) })),\n };\n\n let request = self.build_request(messages, true, config);\n let client = self.client.clone();\n\n Box::pin(async_stream::try_stream! {\n let mut stream = client\n .post(DEEPSEEK_API_URL)\n .headers(headers)\n .json(&request)\n .send()\n .await\n .map_err(|e| ApiError::DeepSeekError { \n message: format!(\"Request failed: {}\", e),\n type_: \"request_failed\".to_string(),\n param: None,\n code: None\n })?\n .bytes_stream();\n\n let mut data = String::new();\n \n while let Some(chunk) = stream.next().await {\n let chunk = chunk.map_err(|e| ApiError::DeepSeekError { \n message: format!(\"Stream error: {}\", e),\n type_: \"stream_error\".to_string(),\n param: None,\n code: None\n })?;\n data.push_str(&String::from_utf8_lossy(&chunk));\n\n let mut start = 0;\n while let Some(end) = data[start..].find(\"\\n\\n\") {\n let end = start + end;\n let line = &data[start..end].trim();\n start = end + 2;\n \n if line.starts_with(\"data: \") {\n let json_data = &line[\"data: \".len()..];\n if let Ok(response) = serde_json::from_str::(json_data) {\n yield response;\n }\n }\n }\n\n if start > 0 {\n data = data[start..].to_string();\n }\n }\n })\n }\n}\n", "middle_code": "pub(crate) fn build_headers(&self, custom_headers: Option<&HashMap>) -> Result {\n let mut headers = HeaderMap::new();\n headers.insert(\n \"Authorization\",\n format!(\"Bearer {}\", self.api_token)\n .parse()\n .map_err(|e| ApiError::Internal { \n message: format!(\"Invalid API token: {}\", e) \n })?,\n );\n headers.insert(\n \"Content-Type\",\n \"application/json\"\n .parse()\n .map_err(|e| ApiError::Internal { \n message: format!(\"Invalid content type: {}\", e) \n })?,\n );\n headers.insert(\n \"Accept\",\n \"application/json\"\n .parse()\n .map_err(|e| ApiError::Internal { \n message: format!(\"Invalid accept header: {}\", e) \n })?,\n );\n if let Some(custom) = custom_headers {\n headers.extend(super::build_headers(custom)?);\n }\n Ok(headers)\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "rust", "sub_task_type": null}, "context_code": [["/deepclaude/src/clients/anthropic.rs", "//! Anthropic API client implementation for interacting with Claude models.\n//!\n//! This module provides a client implementation for communicating with Anthropic's API,\n//! specifically designed to work with Claude language models. It supports both streaming\n//! and non-streaming interactions, handling all aspects of API communication including:\n//!\n//! - Authentication and request signing\n//! - Message formatting and serialization\n//! - Response parsing and deserialization\n//! - Error handling and type conversion\n//! - Streaming response processing\n//!\n//! # Main Components\n//!\n//! - [`AnthropicClient`]: The main client struct for making API requests\n//! - [`AnthropicResponse`]: Represents the structured response from the API\n//! - [`StreamEvent`]: Represents different types of events in streaming responses\n//!\n//! # Example Usage\n//!\n//! ```no_run\n//! use deepclaude::clients::AnthropicClient;\n//! use deepclaude::models::{Message, ApiConfig};\n//!\n//! async fn example() -> Result<(), Box> {\n//! let client = AnthropicClient::new(\"your-api-key\".to_string());\n//! let messages = vec![/* your messages */];\n//! let config = ApiConfig::default();\n//!\n//! // Non-streaming request\n//! let response = client.chat(messages.clone(), None, &config).await?;\n//!\n//! // Streaming request\n//! let stream = client.chat_stream(messages, None, &config);\n//! Ok(())\n//! }\n//! ```\n\nuse crate::{\n error::{ApiError, Result},\n models::{ApiConfig, Message, Role},\n};\nuse futures::Stream;\nuse reqwest::{header::HeaderMap, Client};\nuse serde::{Deserialize, Serialize};\nuse std::{collections::HashMap, pin::Pin};\nuse futures::StreamExt;\nuse serde_json;\n\npub(crate) const ANTHROPIC_API_URL: &str = \"https://api.anthropic.com/v1/messages\";\nconst DEFAULT_MODEL: &str = \"claude-3-5-sonnet-20241022\";\n\n/// Client for interacting with Anthropic's Claude models.\n///\n/// This client handles authentication, request construction, and response parsing\n/// for both streaming and non-streaming interactions with Anthropic's API.\n///\n/// # Examples\n///\n/// ```no_run\n/// use deepclaude::clients::AnthropicClient;\n///\n/// let client = AnthropicClient::new(\"api_token\".to_string());\n/// ```\n#[derive(Debug)]\npub struct AnthropicClient {\n pub(crate) client: Client,\n api_token: String,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct AnthropicResponse {\n pub id: String,\n #[serde(rename = \"type\")]\n pub response_type: String,\n pub role: String,\n pub model: String,\n pub content: Vec,\n pub stop_reason: Option,\n pub stop_sequence: Option,\n pub usage: Usage,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct ContentBlock {\n #[serde(rename = \"type\")]\n pub content_type: String,\n pub text: String,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct Usage {\n pub input_tokens: u32,\n pub output_tokens: u32,\n pub cache_creation_input_tokens: u32,\n pub cache_read_input_tokens: u32,\n}\n\n#[derive(Debug, Serialize, Deserialize)]\npub(crate) struct AnthropicRequest {\n messages: Vec,\n stream: bool,\n #[serde(skip_serializing_if = \"Option::is_none\")]\n system: Option,\n #[serde(flatten)]\n additional_params: serde_json::Value,\n}\n\n#[derive(Debug, Serialize, Deserialize)]\npub(crate) struct AnthropicMessage {\n role: String,\n content: String,\n}\n\n// Event types for streaming responses\n#[derive(Debug, Deserialize)]\n#[serde(tag = \"type\")]\npub enum StreamEvent {\n #[serde(rename = \"message_start\")]\n MessageStart {\n message: AnthropicResponse,\n },\n #[serde(rename = \"content_block_start\")]\n #[allow(dead_code)]\n ContentBlockStart {\n index: usize,\n content_block: ContentBlock,\n },\n #[serde(rename = \"content_block_delta\")]\n #[allow(dead_code)]\n ContentBlockDelta {\n index: usize,\n delta: ContentDelta,\n },\n #[serde(rename = \"content_block_stop\")]\n #[allow(dead_code)]\n ContentBlockStop {\n index: usize,\n },\n #[serde(rename = \"message_delta\")]\n #[allow(dead_code)]\n MessageDelta {\n delta: MessageDelta,\n usage: Option,\n },\n #[serde(rename = \"message_stop\")]\n MessageStop,\n #[serde(rename = \"ping\")]\n Ping,\n}\n\n#[derive(Debug, Deserialize, Clone)]\npub struct ContentDelta {\n #[serde(rename = \"type\")]\n pub delta_type: String,\n pub text: String,\n}\n\n#[derive(Debug, Deserialize, Clone)]\n#[allow(dead_code)]\npub struct MessageDelta {\n pub stop_reason: Option,\n pub stop_sequence: Option,\n}\n\nimpl AnthropicClient {\n /// Creates a new Anthropic client instance.\n ///\n /// # Arguments\n ///\n /// * `api_token` - API token for authentication with Anthropic's API\n ///\n /// # Returns\n ///\n /// A new `AnthropicClient` instance configured with the provided API token\n pub fn new(api_token: String) -> Self {\n Self {\n client: Client::new(),\n api_token,\n }\n }\n\n /// Builds the HTTP headers required for Anthropic API requests.\n ///\n /// # Arguments\n ///\n /// * `custom_headers` - Optional additional headers to include in requests\n ///\n /// # Returns\n ///\n /// * `Result` - The constructed headers on success, or an error if header construction fails\n ///\n /// # Errors\n ///\n /// Returns `ApiError::Internal` if:\n /// - The API token is invalid\n /// - Content-Type or Anthropic-Version headers cannot be constructed\n pub(crate) fn build_headers(&self, custom_headers: Option<&HashMap>) -> Result {\n let mut headers = HeaderMap::new();\n headers.insert(\n \"x-api-key\",\n self.api_token\n .parse()\n .map_err(|e| ApiError::Internal { \n message: format!(\"Invalid API token: {}\", e) \n })?,\n );\n headers.insert(\n \"content-type\",\n \"application/json\"\n .parse()\n .map_err(|e| ApiError::Internal { \n message: format!(\"Invalid content type: {}\", e) \n })?,\n );\n headers.insert(\n \"anthropic-version\",\n \"2023-06-01\"\n .parse()\n .map_err(|e| ApiError::Internal { \n message: format!(\"Invalid anthropic version: {}\", e) \n })?,\n );\n\n if let Some(custom) = custom_headers {\n headers.extend(super::build_headers(custom)?);\n }\n\n Ok(headers)\n }\n\n /// Constructs a request object for the Anthropic API.\n ///\n /// # Arguments\n ///\n /// * `messages` - Vector of messages to send to the model\n /// * `system` - Optional system prompt to set context\n /// * `stream` - Whether to enable streaming mode\n /// * `config` - Configuration options for the request\n ///\n /// # Returns\n ///\n /// An `AnthropicRequest` object configured with the provided parameters and defaults\n pub(crate) fn build_request(\n &self,\n messages: Vec,\n system: Option,\n stream: bool,\n config: &ApiConfig,\n ) -> AnthropicRequest {\n let filtered_messages = messages\n .into_iter()\n .filter(|msg| msg.role != Role::System)\n .map(|msg| AnthropicMessage {\n role: match msg.role {\n Role::User => \"user\".to_string(),\n Role::Assistant => \"assistant\".to_string(),\n Role::System => unreachable!(),\n },\n content: msg.content,\n })\n .collect();\n\n // Create base request with required fields\n let default_model = serde_json::json!(DEFAULT_MODEL);\n let model_value = config.body.get(\"model\").unwrap_or(&default_model);\n \n let default_max_tokens = if let Some(model_str) = model_value.as_str() {\n if model_str.contains(\"claude-3-opus\") {\n 4096\n } else {\n 8192\n }\n } else {\n 8192\n };\n let default_max_tokens_json = serde_json::json!(default_max_tokens);\n\n let mut request_value = serde_json::json!({\n \"messages\": filtered_messages,\n \"stream\": stream,\n \"model\": model_value,\n \"max_tokens\": config.body.get(\"max_tokens\").unwrap_or(&default_max_tokens_json)\n });\n\n // Add system if present\n if let Some(ref sys) = system {\n if let serde_json::Value::Object(mut map) = request_value {\n map.insert(\"system\".to_string(), serde_json::json!(sys));\n request_value = serde_json::Value::Object(map);\n }\n }\n\n // Merge additional configuration from config.body while protecting critical fields\n if let serde_json::Value::Object(mut map) = request_value {\n if let serde_json::Value::Object(mut body) = serde_json::to_value(&config.body).unwrap_or_default() {\n // Remove protected fields from config body\n body.remove(\"stream\");\n body.remove(\"messages\");\n body.remove(\"system\");\n \n // Merge remaining fields from config.body\n for (key, value) in body {\n map.insert(key, value);\n }\n }\n request_value = serde_json::Value::Object(map);\n }\n\n // Convert the merged JSON value into our request structure\n serde_json::from_value(request_value).unwrap_or_else(|_| AnthropicRequest {\n messages: filtered_messages,\n stream,\n system,\n additional_params: config.body.clone(),\n })\n }\n\n /// Sends a non-streaming chat request to the Anthropic API.\n ///\n /// # Arguments\n ///\n /// * `messages` - Vector of messages for the conversation\n /// * `system` - Optional system prompt to set context\n /// * `config` - Configuration options for the request\n ///\n /// # Returns\n ///\n /// * `Result` - The model's response on success\n ///\n /// # Errors\n ///\n /// Returns `ApiError::AnthropicError` if:\n /// - The API request fails\n /// - The response status is not successful\n /// - The response cannot be parsed\n pub async fn chat(\n &self,\n messages: Vec,\n system: Option,\n config: &ApiConfig,\n ) -> Result {\n let headers = self.build_headers(Some(&config.headers))?;\n let request = self.build_request(messages, system, false, config);\n\n let response = self\n .client\n .post(ANTHROPIC_API_URL)\n .headers(headers)\n .json(&request)\n .send()\n .await\n .map_err(|e| ApiError::AnthropicError { \n message: format!(\"Request failed: {}\", e),\n type_: \"request_failed\".to_string(),\n param: None,\n code: None\n })?;\n\n if !response.status().is_success() {\n let error = response\n .text()\n .await\n .unwrap_or_else(|_| \"Unknown error\".to_string());\n return Err(ApiError::AnthropicError { \n message: error,\n type_: \"api_error\".to_string(),\n param: None,\n code: None\n });\n }\n\n response\n .json::()\n .await\n .map_err(|e| ApiError::AnthropicError { \n message: format!(\"Failed to parse response: {}\", e),\n type_: \"parse_error\".to_string(),\n param: None,\n code: None\n })\n }\n\n /// Sends a streaming chat request to the Anthropic API.\n ///\n /// Returns a stream that yields events from the model's response as they arrive.\n ///\n /// # Arguments\n ///\n /// * `messages` - Vector of messages for the conversation\n /// * `system` - Optional system prompt to set context\n /// * `config` - Configuration options for the request\n ///\n /// # Returns\n ///\n /// * `Pin> + Send>>` - A stream of response events\n ///\n /// # Errors\n ///\n /// The stream may yield `ApiError::AnthropicError` if:\n /// - The API request fails\n /// - Stream processing encounters an error\n /// - Response events cannot be parsed\n pub fn chat_stream(\n &self,\n messages: Vec,\n system: Option,\n config: &ApiConfig,\n ) -> Pin> + Send>> {\n let headers = match self.build_headers(Some(&config.headers)) {\n Ok(h) => h,\n Err(e) => return Box::pin(futures::stream::once(async move { Err(e) })),\n };\n\n let request = self.build_request(messages, system, true, config);\n let client = self.client.clone();\n\n Box::pin(async_stream::try_stream! {\n let mut stream = client\n .post(ANTHROPIC_API_URL)\n .headers(headers)\n .json(&request)\n .send()\n .await\n .map_err(|e| ApiError::AnthropicError { \n message: format!(\"Request failed: {}\", e),\n type_: \"request_failed\".to_string(),\n param: None,\n code: None\n })?\n .bytes_stream();\n\n let mut data = String::new();\n \n while let Some(chunk) = stream.next().await {\n let chunk = chunk.map_err(|e| ApiError::AnthropicError { \n message: format!(\"Stream error: {}\", e),\n type_: \"stream_error\".to_string(),\n param: None,\n code: None\n })?;\n data.push_str(&String::from_utf8_lossy(&chunk));\n\n let mut start = 0;\n while let Some(end) = data[start..].find(\"\\n\\n\") {\n let end = start + end;\n let event_data = &data[start..end];\n start = end + 2;\n\n if event_data.starts_with(\"event: \") {\n let _event_line = &event_data[\"event: \".len()..];\n if let Some(data_line) = event_data.lines().nth(1) {\n if data_line.starts_with(\"data: \") {\n let json_data = &data_line[\"data: \".len()..];\n if let Ok(event) = serde_json::from_str::(json_data) {\n yield event;\n }\n }\n }\n }\n }\n\n if start > 0 {\n data = data[start..].to_string();\n }\n }\n })\n }\n}\n\n/// Converts an Anthropic content block into the application's generic content block type.\nimpl From for crate::models::response::ContentBlock {\n fn from(block: ContentBlock) -> Self {\n Self {\n content_type: block.content_type,\n text: block.text,\n }\n }\n}\n"], ["/deepclaude/src/handlers.rs", "//! Request handlers for the API endpoints.\n//!\n//! This module contains the main request handlers and supporting functions\n//! for processing chat requests, including both streaming and non-streaming\n//! responses. It coordinates between different AI models and handles\n//! usage tracking and cost calculations.\n\nuse crate::{\n clients::{AnthropicClient, DeepSeekClient},\n config::Config,\n error::{ApiError, Result, SseResponse},\n models::{\n ApiRequest, ApiResponse, ContentBlock, CombinedUsage, DeepSeekUsage, AnthropicUsage,\n ExternalApiResponse, Message, Role, StreamEvent,\n },\n};\nuse axum::{\n extract::State,\n response::{sse::Event, IntoResponse},\n Json,\n};\nuse chrono::Utc;\nuse futures::StreamExt;\nuse std::{sync::Arc, collections::HashMap};\nuse tokio_stream::wrappers::ReceiverStream;\n\n/// Application state shared across request handlers.\n///\n/// Contains configuration that needs to be accessible\n/// to all request handlers.\npub struct AppState {\n pub config: Config,\n}\n\n/// Extracts API tokens from request headers.\n///\n/// # Arguments\n///\n/// * `headers` - The HTTP headers containing the API tokens\n///\n/// # Returns\n///\n/// * `Result<(String, String)>` - A tuple of (DeepSeek token, Anthropic token)\n///\n/// # Errors\n///\n/// Returns `ApiError::MissingHeader` if either token is missing\n/// Returns `ApiError::BadRequest` if tokens are malformed\nfn extract_api_tokens(\n headers: &axum::http::HeaderMap,\n) -> Result<(String, String)> {\n let deepseek_token = headers\n .get(\"X-DeepSeek-API-Token\")\n .ok_or_else(|| ApiError::MissingHeader { \n header: \"X-DeepSeek-API-Token\".to_string() \n })?\n .to_str()\n .map_err(|_| ApiError::BadRequest { \n message: \"Invalid DeepSeek API token\".to_string() \n })?\n .to_string();\n\n let anthropic_token = headers\n .get(\"X-Anthropic-API-Token\")\n .ok_or_else(|| ApiError::MissingHeader { \n header: \"X-Anthropic-API-Token\".to_string() \n })?\n .to_str()\n .map_err(|_| ApiError::BadRequest { \n message: \"Invalid Anthropic API token\".to_string() \n })?\n .to_string();\n\n Ok((deepseek_token, anthropic_token))\n}\n\n/// Calculates the cost of DeepSeek API usage.\n///\n/// # Arguments\n///\n/// * `input_tokens` - Number of input tokens processed\n/// * `output_tokens` - Number of output tokens generated\n/// * `_reasoning_tokens` - Number of tokens used for reasoning\n/// * `cached_tokens` - Number of tokens retrieved from cache\n/// * `config` - Configuration containing pricing information\n///\n/// # Returns\n///\n/// The total cost in dollars for the API usage\nfn calculate_deepseek_cost(\n input_tokens: u32,\n output_tokens: u32,\n _reasoning_tokens: u32,\n cached_tokens: u32,\n config: &Config,\n) -> f64 {\n let cache_hit_cost = (cached_tokens as f64 / 1_000_000.0) * config.pricing.deepseek.input_cache_hit_price;\n let cache_miss_cost = ((input_tokens - cached_tokens) as f64 / 1_000_000.0) * config.pricing.deepseek.input_cache_miss_price;\n let output_cost = (output_tokens as f64 / 1_000_000.0) * config.pricing.deepseek.output_price;\n \n cache_hit_cost + cache_miss_cost + output_cost\n}\n\n/// Calculates the cost of Anthropic API usage.\n///\n/// # Arguments\n///\n/// * `model` - The specific Claude model used\n/// * `input_tokens` - Number of input tokens processed\n/// * `output_tokens` - Number of output tokens generated\n/// * `cache_write_tokens` - Number of tokens written to cache\n/// * `cache_read_tokens` - Number of tokens read from cache\n/// * `config` - Configuration containing pricing information\n///\n/// # Returns\n///\n/// The total cost in dollars for the API usage\nfn calculate_anthropic_cost(\n model: &str,\n input_tokens: u32,\n output_tokens: u32,\n cache_write_tokens: u32,\n cache_read_tokens: u32,\n config: &Config,\n) -> f64 {\n let pricing = if model.contains(\"claude-3-5-sonnet\") {\n &config.pricing.anthropic.claude_3_sonnet\n } else if model.contains(\"claude-3-5-haiku\") {\n &config.pricing.anthropic.claude_3_haiku\n } else if model.contains(\"claude-3-opus\") {\n &config.pricing.anthropic.claude_3_opus\n } else {\n &config.pricing.anthropic.claude_3_sonnet // default to sonnet pricing\n };\n\n let input_cost = (input_tokens as f64 / 1_000_000.0) * pricing.input_price;\n let output_cost = (output_tokens as f64 / 1_000_000.0) * pricing.output_price;\n let cache_write_cost = (cache_write_tokens as f64 / 1_000_000.0) * pricing.cache_write_price;\n let cache_read_cost = (cache_read_tokens as f64 / 1_000_000.0) * pricing.cache_read_price;\n\n input_cost + output_cost + cache_write_cost + cache_read_cost\n}\n\n/// Formats a cost value as a dollar amount string.\n///\n/// # Arguments\n///\n/// * `cost` - The cost value to format\n///\n/// # Returns\n///\n/// A string representing the cost with 3 decimal places and $ prefix\nfn format_cost(cost: f64) -> String {\n format!(\"${:.3}\", cost)\n}\n\n/// Main handler for chat requests.\n///\n/// Routes requests to either streaming or non-streaming handlers\n/// based on the request configuration.\n///\n/// # Arguments\n///\n/// * `state` - Application state containing configuration\n/// * `headers` - HTTP request headers\n/// * `request` - The parsed chat request\n///\n/// # Returns\n///\n/// * `Result` - The API response or an error\npub async fn handle_chat(\n state: State>,\n headers: axum::http::HeaderMap,\n Json(request): Json,\n) -> Result {\n if request.stream {\n let stream_response = chat_stream(state, headers, Json(request)).await?;\n Ok(stream_response.into_response())\n } else {\n let json_response = chat(state, headers, Json(request)).await?;\n Ok(json_response.into_response())\n }\n}\n\n/// Handler for non-streaming chat requests.\n///\n/// Processes the request through both AI models sequentially,\n/// combining their responses and tracking usage.\n///\n/// # Arguments\n///\n/// * `state` - Application state containing configuration\n/// * `headers` - HTTP request headers\n/// * `request` - The parsed chat request\n///\n/// # Returns\n///\n/// * `Result>` - The combined API response or an error\npub(crate) async fn chat(\n State(state): State>,\n headers: axum::http::HeaderMap,\n Json(request): Json,\n) -> Result> {\n // Validate system prompt\n if !request.validate_system_prompt() {\n return Err(ApiError::InvalidSystemPrompt);\n }\n\n // Extract API tokens\n let (deepseek_token, anthropic_token) = extract_api_tokens(&headers)?;\n\n // Initialize clients\n let deepseek_client = DeepSeekClient::new(deepseek_token);\n let anthropic_client = AnthropicClient::new(anthropic_token);\n\n // Get messages with system prompt\n let messages = request.get_messages_with_system();\n\n // Call DeepSeek API\n let deepseek_response = deepseek_client.chat(messages.clone(), &request.deepseek_config).await?;\n \n // Store response metadata\n let deepseek_status: u16 = 200;\n let deepseek_headers = HashMap::new(); // Headers not available when using high-level chat method\n\n // Extract reasoning content and wrap in thinking tags\n let reasoning_content = deepseek_response\n .choices\n .first()\n .and_then(|c| c.message.reasoning_content.as_ref())\n .ok_or_else(|| ApiError::DeepSeekError { \n message: \"No reasoning content in response\".to_string(),\n type_: \"missing_content\".to_string(),\n param: None,\n code: None\n })?;\n\n let thinking_content = format!(\"\\n{}\\n\", reasoning_content);\n\n // Add thinking content to messages for Anthropic\n let mut anthropic_messages = messages;\n anthropic_messages.push(Message {\n role: Role::Assistant,\n content: thinking_content.clone(),\n });\n\n // Call Anthropic API\n let anthropic_response = anthropic_client.chat(\n anthropic_messages,\n request.get_system_prompt().map(String::from),\n &request.anthropic_config\n ).await?;\n \n // Store response metadata\n let anthropic_status: u16 = 200;\n let anthropic_headers = HashMap::new(); // Headers not available when using high-level chat method\n\n // Calculate usage costs\n let deepseek_cost = calculate_deepseek_cost(\n deepseek_response.usage.prompt_tokens,\n deepseek_response.usage.completion_tokens,\n deepseek_response.usage.completion_tokens_details.reasoning_tokens,\n deepseek_response.usage.prompt_tokens_details.cached_tokens,\n &state.config,\n );\n\n let anthropic_cost = calculate_anthropic_cost(\n &anthropic_response.model,\n anthropic_response.usage.input_tokens,\n anthropic_response.usage.output_tokens,\n anthropic_response.usage.cache_creation_input_tokens,\n anthropic_response.usage.cache_read_input_tokens,\n &state.config,\n );\n\n // Combine thinking content with Anthropic's response\n let mut content = Vec::new();\n \n // Add thinking block first\n content.push(ContentBlock::text(thinking_content));\n \n // Add Anthropic's response blocks\n content.extend(anthropic_response.content.clone().into_iter()\n .map(ContentBlock::from_anthropic));\n\n // Build response with captured headers\n let response = ApiResponse {\n created: Utc::now(),\n content,\n deepseek_response: request.verbose.then(|| ExternalApiResponse {\n status: deepseek_status,\n headers: deepseek_headers,\n body: serde_json::to_value(&deepseek_response).unwrap_or_default(),\n }),\n anthropic_response: request.verbose.then(|| ExternalApiResponse {\n status: anthropic_status,\n headers: anthropic_headers,\n body: serde_json::to_value(&anthropic_response).unwrap_or_default(),\n }),\n combined_usage: CombinedUsage {\n total_cost: format_cost(deepseek_cost + anthropic_cost),\n deepseek_usage: DeepSeekUsage {\n input_tokens: deepseek_response.usage.prompt_tokens,\n output_tokens: deepseek_response.usage.completion_tokens,\n reasoning_tokens: deepseek_response.usage.completion_tokens_details.reasoning_tokens,\n cached_input_tokens: deepseek_response.usage.prompt_tokens_details.cached_tokens,\n total_tokens: deepseek_response.usage.total_tokens,\n total_cost: format_cost(deepseek_cost),\n },\n anthropic_usage: AnthropicUsage {\n input_tokens: anthropic_response.usage.input_tokens,\n output_tokens: anthropic_response.usage.output_tokens,\n cached_write_tokens: anthropic_response.usage.cache_creation_input_tokens,\n cached_read_tokens: anthropic_response.usage.cache_read_input_tokens,\n total_tokens: anthropic_response.usage.input_tokens + anthropic_response.usage.output_tokens,\n total_cost: format_cost(anthropic_cost),\n },\n },\n };\n\n Ok(Json(response))\n}\n\n/// Handler for streaming chat requests.\n///\n/// Processes the request through both AI models sequentially,\n/// streaming their responses as Server-Sent Events.\n///\n/// # Arguments\n///\n/// * `state` - Application state containing configuration\n/// * `headers` - HTTP request headers\n/// * `request` - The parsed chat request\n///\n/// # Returns\n///\n/// * `Result` - A stream of Server-Sent Events or an error\npub(crate) async fn chat_stream(\n State(state): State>,\n headers: axum::http::HeaderMap,\n Json(request): Json,\n) -> Result {\n // Validate system prompt\n if !request.validate_system_prompt() {\n return Err(ApiError::InvalidSystemPrompt);\n }\n\n // Extract API tokens\n let (deepseek_token, anthropic_token) = extract_api_tokens(&headers)?;\n\n // Initialize clients\n let deepseek_client = DeepSeekClient::new(deepseek_token);\n let anthropic_client = AnthropicClient::new(anthropic_token);\n\n // Get messages with system prompt\n let messages = request.get_messages_with_system();\n\n // Create channel for stream events\n let (tx, rx) = tokio::sync::mpsc::channel(100);\n let tx = Arc::new(tx);\n\n // Spawn task to handle streaming\n let config = state.config.clone();\n let request_clone = request.clone();\n tokio::spawn(async move {\n let tx = tx.clone();\n\n // Start event\n let _ = tx\n .send(Ok(Event::default().event(\"start\").data(\n serde_json::to_string(&StreamEvent::Start {\n created: Utc::now(),\n })\n .unwrap_or_default(),\n )))\n .await;\n\n // Send initial thinking tag\n let _ = tx\n .send(Ok(Event::default().event(\"content\").data(\n serde_json::to_string(&StreamEvent::Content {\n content: vec![ContentBlock {\n content_type: \"text\".to_string(),\n text: \"\\n\".to_string(),\n }],\n })\n .unwrap_or_default(),\n )))\n .await;\n\n // Stream from DeepSeek\n let mut deepseek_usage = None;\n let mut complete_reasoning = String::new();\n let mut deepseek_stream = deepseek_client.chat_stream(messages.clone(), &request_clone.deepseek_config);\n \n while let Some(chunk) = deepseek_stream.next().await {\n match chunk {\n Ok(response) => {\n if let Some(choice) = response.choices.first() {\n // Check if reasoning_content is null and break if it is\n if choice.delta.reasoning_content.is_none() {\n break;\n }\n\n // Handle delta reasoning_content for streaming\n if let Some(reasoning) = &choice.delta.reasoning_content {\n if !reasoning.is_empty() {\n // Stream the reasoning content as a delta\n let _ = tx\n .send(Ok(Event::default().event(\"content\").data(\n serde_json::to_string(&StreamEvent::Content {\n content: vec![ContentBlock {\n content_type: \"text_delta\".to_string(),\n text: reasoning.to_string(),\n }],\n })\n .unwrap_or_default(),\n )))\n .await;\n \n // Accumulate complete reasoning for later use\n complete_reasoning.push_str(reasoning);\n }\n }\n }\n \n // Store usage information if present\n if let Some(usage) = response.usage {\n deepseek_usage = Some(usage);\n }\n }\n Err(e) => {\n let _ = tx\n .send(Ok(Event::default().event(\"error\").data(\n serde_json::to_string(&StreamEvent::Error {\n message: e.to_string(),\n code: 500,\n })\n .unwrap_or_default(),\n )))\n .await;\n return;\n }\n }\n }\n\n // Send closing thinking tag\n let _ = tx\n .send(Ok(Event::default().event(\"content\").data(\n serde_json::to_string(&StreamEvent::Content {\n content: vec![ContentBlock {\n content_type: \"text\".to_string(),\n text: \"\\n\".to_string(),\n }],\n })\n .unwrap_or_default(),\n )))\n .await;\n\n // Add complete thinking content to messages for Anthropic\n let mut anthropic_messages = messages;\n anthropic_messages.push(Message {\n role: Role::Assistant,\n content: format!(\"\\n{}\\n\", complete_reasoning),\n });\n\n // Stream from Anthropic\n let mut anthropic_stream = anthropic_client.chat_stream(\n anthropic_messages,\n request_clone.get_system_prompt().map(String::from),\n &request_clone.anthropic_config,\n );\n\n while let Some(chunk) = anthropic_stream.next().await {\n match chunk {\n Ok(event) => match event {\n crate::clients::anthropic::StreamEvent::MessageStart { message } => {\n // Only send content event if there's actual content to send\n if !message.content.is_empty() {\n let _ = tx\n .send(Ok(Event::default().event(\"content\").data(\n serde_json::to_string(&StreamEvent::Content { \n content: message.content.into_iter()\n .map(ContentBlock::from_anthropic)\n .collect()\n })\n .unwrap_or_default(),\n )))\n .await;\n }\n }\n crate::clients::anthropic::StreamEvent::ContentBlockDelta { delta, .. } => {\n // Send content update\n let _ = tx\n .send(Ok(Event::default().event(\"content\").data(\n serde_json::to_string(&StreamEvent::Content {\n content: vec![ContentBlock {\n content_type: delta.delta_type,\n text: delta.text,\n }],\n })\n .unwrap_or_default(),\n )))\n .await;\n }\n crate::clients::anthropic::StreamEvent::MessageDelta { usage, .. } => {\n // Send final usage stats if available\n if let Some(usage) = usage {\n let anthropic_usage = AnthropicUsage::from_anthropic(usage);\n let anthropic_cost = calculate_anthropic_cost(\n \"claude-3-5-sonnet-20241022\", // Default model\n anthropic_usage.input_tokens,\n anthropic_usage.output_tokens,\n anthropic_usage.cached_write_tokens,\n anthropic_usage.cached_read_tokens,\n &config,\n );\n\n // Calculate DeepSeek costs if usage is available\n let (deepseek_usage, deepseek_cost) = if let Some(usage) = deepseek_usage.as_ref() {\n let cost = calculate_deepseek_cost(\n usage.prompt_tokens,\n usage.completion_tokens,\n usage.completion_tokens_details.reasoning_tokens,\n usage.prompt_tokens_details.cached_tokens,\n &config,\n );\n \n (DeepSeekUsage {\n input_tokens: usage.prompt_tokens,\n output_tokens: usage.completion_tokens,\n reasoning_tokens: usage.completion_tokens_details.reasoning_tokens,\n cached_input_tokens: usage.prompt_tokens_details.cached_tokens,\n total_tokens: usage.total_tokens,\n total_cost: format_cost(cost),\n }, cost)\n } else {\n (DeepSeekUsage {\n input_tokens: 0,\n output_tokens: 0,\n reasoning_tokens: 0,\n cached_input_tokens: 0,\n total_tokens: 0,\n total_cost: \"$0.00\".to_string(),\n }, 0.0)\n };\n\n let _ = tx\n .send(Ok(Event::default().event(\"usage\").data(\n serde_json::to_string(&StreamEvent::Usage {\n usage: CombinedUsage {\n total_cost: format_cost(deepseek_cost + anthropic_cost),\n deepseek_usage,\n anthropic_usage: AnthropicUsage {\n input_tokens: anthropic_usage.input_tokens,\n output_tokens: anthropic_usage.output_tokens,\n cached_write_tokens: anthropic_usage.cached_write_tokens,\n cached_read_tokens: anthropic_usage.cached_read_tokens,\n total_tokens: anthropic_usage.total_tokens,\n total_cost: format_cost(anthropic_cost),\n },\n },\n })\n .unwrap_or_default(),\n )))\n .await;\n }\n }\n _ => {} // Handle other events if needed\n },\n Err(e) => {\n let _ = tx\n .send(Ok(Event::default().event(\"error\").data(\n serde_json::to_string(&StreamEvent::Error {\n message: e.to_string(),\n code: 500,\n })\n .unwrap_or_default(),\n )))\n .await;\n return;\n }\n }\n }\n\n // Send done event\n let _ = tx\n .send(Ok(Event::default().event(\"done\").data(\n serde_json::to_string(&StreamEvent::Done)\n .unwrap_or_default(),\n )))\n .await;\n });\n\n // Convert receiver into stream\n let stream = ReceiverStream::new(rx);\n Ok(SseResponse::new(stream))\n}\n"], ["/deepclaude/src/models/request.rs", "//! Request models for the API endpoints.\n//!\n//! This module defines the structures used to represent incoming API requests,\n//! including chat messages, configuration options, and request parameters.\n\nuse serde::{Deserialize, Serialize};\nuse std::collections::HashMap;\n\n/// Primary request structure for chat API endpoints.\n///\n/// This structure represents a complete chat request, including messages,\n/// system prompts, and configuration options for both DeepSeek and Anthropic APIs.\n#[derive(Debug, Clone, Deserialize, Serialize)]\npub struct ApiRequest {\n #[serde(default)]\n pub stream: bool,\n \n #[serde(default)]\n pub verbose: bool,\n \n pub system: Option,\n pub messages: Vec,\n \n #[serde(default)]\n pub deepseek_config: ApiConfig,\n \n #[serde(default)]\n pub anthropic_config: ApiConfig,\n}\n\n/// A single message in a chat conversation.\n///\n/// Represents one message in the conversation history, including\n/// its role (system, user, or assistant) and content.\n#[derive(Debug, Clone, Deserialize, Serialize)]\npub struct Message {\n pub role: Role,\n pub content: String,\n}\n\n/// Possible roles for a message in a chat conversation.\n///\n/// Each message must be associated with one of these roles to\n/// properly structure the conversation flow.\n#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]\n#[serde(rename_all = \"lowercase\")]\npub enum Role {\n System,\n User,\n Assistant,\n}\n\n/// Configuration options for external API requests.\n///\n/// Contains headers and body parameters that will be passed\n/// to the external AI model APIs.\n#[derive(Debug, Clone, Default, Deserialize, Serialize)]\npub struct ApiConfig {\n #[serde(default)]\n pub headers: HashMap,\n \n #[serde(default)]\n pub body: serde_json::Value,\n}\n\nimpl ApiRequest {\n /// Validates that system prompts are not duplicated.\n ///\n /// Checks that a system prompt is not provided in both the root level\n /// and messages array. The system prompt itself is optional.\n ///\n /// # Returns\n ///\n /// * `bool` - True if system prompt validation passes (no duplicates), false otherwise\n pub fn validate_system_prompt(&self) -> bool {\n let system_in_messages = self.messages.iter().any(|msg| matches!(msg.role, Role::System));\n \n // Only invalid if system prompt is provided in both places\n !(self.system.is_some() && system_in_messages)\n }\n\n /// Returns messages with the system prompt in the correct position.\n ///\n /// Ensures the system prompt (if present) is the first message,\n /// followed by the conversation messages in order.\n ///\n /// # Returns\n ///\n /// * `Vec` - Messages with system prompt correctly positioned\n pub fn get_messages_with_system(&self) -> Vec {\n let mut messages = Vec::new();\n\n // Add system message first\n if let Some(system) = &self.system {\n messages.push(Message {\n role: Role::System,\n content: system.clone(),\n });\n }\n\n // Add remaining messages\n messages.extend(self.messages.iter().filter(|msg| !matches!(msg.role, Role::System)).cloned());\n\n messages\n }\n\n /// Retrieves the system prompt if one is present.\n ///\n /// Checks both the root level system field and the messages array\n /// for a system prompt.\n ///\n /// # Returns\n ///\n /// * `Option<&str>` - The system prompt if found, None otherwise\n pub fn get_system_prompt(&self) -> Option<&str> {\n self.system.as_deref().or_else(|| {\n self.messages\n .iter()\n .find(|msg| matches!(msg.role, Role::System))\n .map(|msg| msg.content.as_str())\n })\n }\n}\n"], ["/deepclaude/src/error.rs", "//! Error handling types and implementations for the application.\n//!\n//! This module provides a comprehensive error handling system including:\n//! - Custom error types for various failure scenarios\n//! - Conversion implementations for common error types\n//! - Response formatting for API errors\n//! - Type aliases for common Result types\n\nuse axum::{\n http::StatusCode,\n response::{IntoResponse, Response, sse::Event},\n Json,\n};\nuse serde::{Deserialize, Serialize};\nuse std::convert::Infallible;\nuse thiserror::Error;\nuse tokio_stream::wrappers::ReceiverStream;\n\n/// Response structure for API errors.\n///\n/// This structure provides a consistent format for error responses\n/// returned by the API endpoints.\n#[derive(Debug, Serialize, Deserialize)]\npub struct ErrorResponse {\n pub error: ErrorDetails,\n}\n\n/// Detailed error information included in error responses.\n///\n/// Contains specific information about what went wrong, including:\n/// - A human-readable error message\n/// - The type of error that occurred\n/// - Optional parameter that caused the error\n/// - Optional error code for more specific error handling\n#[derive(Debug, Serialize, Deserialize)]\npub struct ErrorDetails {\n pub message: String,\n #[serde(rename = \"type\")]\n pub type_: String,\n #[serde(skip_serializing_if = \"Option::is_none\")]\n pub param: Option,\n #[serde(skip_serializing_if = \"Option::is_none\")]\n pub code: Option,\n}\n\n/// Enumeration of all possible API errors.\n///\n/// This enum represents all the different types of errors that can occur\n/// during API operations, including validation errors, external API errors,\n/// and internal server errors.\n#[derive(Error, Debug, Clone)]\npub enum ApiError {\n #[error(\"Invalid request: {message}\")]\n BadRequest {\n message: String,\n },\n\n #[error(\"Missing required header: {header}\")]\n MissingHeader {\n header: String,\n },\n\n #[error(\"Invalid system prompt configuration\")]\n InvalidSystemPrompt,\n\n #[error(\"DeepSeek API error: {message}\")]\n DeepSeekError {\n message: String,\n type_: String,\n param: Option,\n code: Option,\n },\n\n #[error(\"Anthropic API error: {message}\")]\n AnthropicError {\n message: String,\n type_: String,\n param: Option,\n code: Option,\n },\n\n #[error(\"Internal server error: {message}\")]\n Internal {\n message: String,\n },\n\n #[error(\"Other error: {message}\")]\n Other {\n message: String,\n },\n}\n\n/// Implements conversion of API errors into HTTP responses.\n///\n/// Maps each error variant to an appropriate HTTP status code and\n/// formats the error details into a consistent JSON response structure.\nimpl IntoResponse for ApiError {\n fn into_response(self) -> Response {\n let (status, error_response) = match &self {\n ApiError::BadRequest { message } => (\n StatusCode::BAD_REQUEST,\n ErrorResponse {\n error: ErrorDetails {\n message: message.clone(),\n type_: \"bad_request\".to_string(),\n param: None,\n code: None,\n },\n },\n ),\n ApiError::MissingHeader { header } => (\n StatusCode::BAD_REQUEST,\n ErrorResponse {\n error: ErrorDetails {\n message: format!(\"Missing required header: {}\", header),\n type_: \"missing_header\".to_string(),\n param: Some(header.clone()),\n code: None,\n },\n },\n ),\n ApiError::InvalidSystemPrompt => (\n StatusCode::BAD_REQUEST,\n ErrorResponse {\n error: ErrorDetails {\n message: \"System prompt can only be provided once, either in root or messages array\".to_string(),\n type_: \"invalid_system_prompt\".to_string(),\n param: None,\n code: None,\n },\n },\n ),\n ApiError::DeepSeekError { message, type_, param, code } => (\n StatusCode::BAD_REQUEST,\n ErrorResponse {\n error: ErrorDetails {\n message: format!(\"DeepSeek API Error: {}\", message),\n type_: format!(\"deepseek_{}\", type_),\n param: param.clone(),\n code: code.clone(),\n },\n },\n ),\n ApiError::AnthropicError { message, type_, param, code } => (\n StatusCode::BAD_REQUEST,\n ErrorResponse {\n error: ErrorDetails {\n message: format!(\"Anthropic API Error: {}\", message),\n type_: format!(\"anthropic_{}\", type_),\n param: param.clone(),\n code: code.clone(),\n },\n },\n ),\n ApiError::Internal { message } => (\n StatusCode::INTERNAL_SERVER_ERROR,\n ErrorResponse {\n error: ErrorDetails {\n message: message.clone(),\n type_: \"internal_error\".to_string(),\n param: None,\n code: None,\n },\n },\n ),\n ApiError::Other { message } => (\n StatusCode::INTERNAL_SERVER_ERROR,\n ErrorResponse {\n error: ErrorDetails {\n message: format!(\"Internal server error: {}\", message),\n type_: \"internal_error\".to_string(),\n param: None,\n code: None,\n },\n },\n ),\n };\n\n (status, Json(error_response)).into_response()\n }\n}\n\n/// Converts generic errors into API errors.\n///\n/// This implementation allows using the `?` operator with functions that\n/// return `anyhow::Error`, converting them into our custom `ApiError` type.\nimpl From for ApiError {\n fn from(err: anyhow::Error) -> Self {\n ApiError::Other { \n message: err.to_string() \n }\n }\n}\n\n/// Type alias for Results using our custom ApiError type.\n///\n/// This provides a convenient way to use Result with our ApiError\n/// throughout the application.\npub type Result = std::result::Result;\n\n/// Type alias for Server-Sent Events (SSE) results.\n///\n/// Used for streaming responses where errors are converted to Infallible\n/// since they are handled within the stream.\npub type SseResult = std::result::Result;\n\n/// Type alias for SSE streams.\n///\n/// Represents a stream of SSE results that can be sent to clients.\npub type SseStream = ReceiverStream;\n\n/// Type alias for SSE responses.\n///\n/// Represents the complete SSE response type used by the API endpoints.\npub type SseResponse = axum::response::sse::Sse;\n"], ["/deepclaude/src/models/response.rs", "//! Response models for the API endpoints.\n//!\n//! This module defines the structures used to represent API responses,\n//! including chat completions, usage statistics, and streaming events.\n\nuse chrono::{DateTime, Utc};\nuse serde::{Deserialize, Serialize};\nuse std::collections::HashMap;\n\n/// Primary response structure for chat API endpoints.\n///\n/// Contains the complete response from both AI models, including\n/// content blocks, usage statistics, and optional raw API responses.\n#[derive(Debug, Serialize, Clone)]\npub struct ApiResponse {\n pub created: DateTime,\n pub content: Vec,\n \n #[serde(skip_serializing_if = \"Option::is_none\")]\n pub deepseek_response: Option,\n \n #[serde(skip_serializing_if = \"Option::is_none\")]\n pub anthropic_response: Option,\n \n pub combined_usage: CombinedUsage,\n}\n\n/// A block of content in a response.\n///\n/// Represents a single piece of content in the response,\n/// with its type and actual text content.\n#[derive(Debug, Serialize, Deserialize, Clone)]\npub struct ContentBlock {\n #[serde(rename = \"type\")]\n pub content_type: String,\n pub text: String,\n}\n\n/// Raw response from an external API.\n///\n/// Contains the complete response details from an external API\n/// call, including status code, headers, and response body.\n#[derive(Debug, Serialize, Clone)]\npub struct ExternalApiResponse {\n pub status: u16,\n pub headers: HashMap,\n pub body: serde_json::Value,\n}\n\n/// Combined usage statistics from both AI models.\n///\n/// Aggregates token usage and cost information from both\n/// DeepSeek and Anthropic API calls.\n#[derive(Debug, Serialize, Clone)]\npub struct CombinedUsage {\n pub total_cost: String,\n pub deepseek_usage: DeepSeekUsage,\n pub anthropic_usage: AnthropicUsage,\n}\n\n/// Usage statistics for DeepSeek API calls.\n///\n/// Tracks token consumption and costs specific to\n/// DeepSeek model usage.\n#[derive(Debug, Serialize, Clone)]\npub struct DeepSeekUsage {\n pub input_tokens: u32,\n pub output_tokens: u32,\n pub reasoning_tokens: u32,\n pub cached_input_tokens: u32,\n pub total_tokens: u32,\n pub total_cost: String,\n}\n\n/// Usage statistics for Anthropic API calls.\n///\n/// Tracks token consumption and costs specific to\n/// Anthropic model usage.\n#[derive(Debug, Serialize, Clone)]\npub struct AnthropicUsage {\n pub input_tokens: u32,\n pub output_tokens: u32,\n pub cached_write_tokens: u32,\n pub cached_read_tokens: u32,\n pub total_tokens: u32,\n pub total_cost: String,\n}\n\n// Streaming event types\n/// Events emitted during streaming responses.\n///\n/// Represents different types of events that can occur\n/// during a streaming response, including content updates\n/// and usage statistics.\n#[derive(Debug, Serialize)]\n#[serde(tag = \"type\")]\npub enum StreamEvent {\n #[serde(rename = \"start\")]\n Start {\n created: DateTime,\n },\n \n #[serde(rename = \"content\")]\n Content {\n content: Vec,\n },\n \n #[serde(rename = \"usage\")]\n Usage {\n usage: CombinedUsage,\n },\n \n #[serde(rename = \"done\")]\n Done,\n \n #[serde(rename = \"error\")]\n Error {\n message: String,\n code: u16,\n },\n}\n\nimpl ContentBlock {\n /// Creates a new text content block.\n ///\n /// # Arguments\n ///\n /// * `text` - The text content to include in the block\n ///\n /// # Returns\n ///\n /// A new `ContentBlock` with the type set to \"text\"\n pub fn text(text: impl Into) -> Self {\n Self {\n content_type: \"text\".to_string(),\n text: text.into(),\n }\n }\n\n /// Converts an Anthropic content block to a generic content block.\n ///\n /// # Arguments\n ///\n /// * `block` - The Anthropic-specific content block to convert\n ///\n /// # Returns\n ///\n /// A new `ContentBlock` with the same content type and text\n pub fn from_anthropic(block: crate::clients::anthropic::ContentBlock) -> Self {\n Self {\n content_type: block.content_type,\n text: block.text,\n }\n }\n}\n\nimpl ApiResponse {\n /// Creates a new API response with simple text content.\n ///\n /// # Arguments\n ///\n /// * `content` - The text content for the response\n ///\n /// # Returns\n ///\n /// A new `ApiResponse` with default values and the provided content\n #[allow(dead_code)]\n pub fn new(content: impl Into) -> Self {\n Self {\n created: Utc::now(),\n content: vec![ContentBlock::text(content)],\n deepseek_response: None,\n anthropic_response: None,\n combined_usage: CombinedUsage {\n total_cost: \"$0.00\".to_string(),\n deepseek_usage: DeepSeekUsage {\n input_tokens: 0,\n output_tokens: 0,\n reasoning_tokens: 0,\n cached_input_tokens: 0,\n total_tokens: 0,\n total_cost: \"$0.00\".to_string(),\n },\n anthropic_usage: AnthropicUsage {\n input_tokens: 0,\n output_tokens: 0,\n cached_write_tokens: 0,\n cached_read_tokens: 0,\n total_tokens: 0,\n total_cost: \"$0.00\".to_string(),\n },\n },\n }\n }\n}\n\nimpl AnthropicUsage {\n /// Converts Anthropic usage statistics to the generic usage format.\n ///\n /// # Arguments\n ///\n /// * `usage` - The Anthropic-specific usage statistics to convert\n ///\n /// # Returns\n ///\n /// A new `AnthropicUsage` with values copied from the Anthropic usage\n pub fn from_anthropic(usage: crate::clients::anthropic::Usage) -> Self {\n Self {\n input_tokens: usage.input_tokens,\n output_tokens: usage.output_tokens,\n cached_write_tokens: usage.cache_creation_input_tokens,\n cached_read_tokens: usage.cache_read_input_tokens,\n total_tokens: usage.input_tokens + usage.output_tokens,\n total_cost: \"$0.00\".to_string(), // Cost will be calculated later\n }\n }\n}\n"], ["/deepclaude/src/clients/mod.rs", "//! Client implementations for external AI model providers.\n//!\n//! This module contains client implementations for different AI model providers:\n//! - `anthropic`: Client for Anthropic's Claude models\n//! - `deepseek`: Client for DeepSeek's reasoning models\n//!\n//! Each client handles authentication, request building, and response parsing\n//! specific to its provider's API.\n\npub mod anthropic;\npub mod deepseek;\n\npub use anthropic::AnthropicClient;\npub use deepseek::DeepSeekClient;\n\nuse crate::error::Result;\nuse reqwest::header::{HeaderMap, HeaderName, HeaderValue};\nuse std::collections::HashMap;\n\n/// Converts a HashMap of string headers to a reqwest HeaderMap.\n///\n/// This function is used internally by clients to convert user-provided\n/// header maps into the format required by reqwest.\n///\n/// # Arguments\n///\n/// * `headers` - A HashMap containing header names and values as strings\n///\n/// # Returns\n///\n/// * `Result` - The converted HeaderMap on success, or an error if\n/// any header name or value is invalid\n///\n/// # Errors\n///\n/// Returns `ApiError::BadRequest` if:\n/// - A header name contains invalid characters\n/// - A header value contains invalid characters\npub(crate) fn build_headers(headers: &HashMap) -> Result {\n let mut header_map = HeaderMap::new();\n \n for (key, value) in headers {\n let header_name = HeaderName::from_bytes(key.as_bytes())\n .map_err(|e| crate::error::ApiError::BadRequest { \n message: format!(\"Invalid header name: {}\", e) \n })?;\n \n let header_value = HeaderValue::from_str(value)\n .map_err(|e| crate::error::ApiError::BadRequest { \n message: format!(\"Invalid header value: {}\", e) \n })?;\n \n header_map.insert(header_name, header_value);\n }\n \n Ok(header_map)\n}\n"], ["/deepclaude/src/config.rs", "//! Configuration management for the application.\n//!\n//! This module handles loading and managing configuration settings from files\n//! and environment variables. It includes pricing configurations for different\n//! AI model providers and server settings.\n\nuse serde::{Deserialize, Serialize};\nuse std::path::Path;\n\n/// Root configuration structure containing all application settings.\n///\n/// This structure is typically loaded from a TOML configuration file\n/// and provides access to all configurable aspects of the application.\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct Config {\n pub server: ServerConfig,\n pub pricing: PricingConfig,\n}\n\n/// Server-specific configuration settings.\n///\n/// Contains settings related to the HTTP server, such as the\n/// host address and port number to bind to.\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct ServerConfig {\n pub host: String,\n pub port: u16,\n}\n\n/// Pricing configuration for all supported AI models.\n///\n/// Contains pricing information for different AI model providers\n/// and their various models, used for usage cost calculation.\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct PricingConfig {\n pub deepseek: DeepSeekPricing,\n pub anthropic: AnthropicPricing,\n}\n\n/// DeepSeek-specific pricing configuration.\n///\n/// Contains pricing rates for different aspects of DeepSeek API usage,\n/// including cached and non-cached requests.\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct DeepSeekPricing {\n pub input_cache_hit_price: f64, // per million tokens\n pub input_cache_miss_price: f64, // per million tokens\n pub output_price: f64, // per million tokens\n}\n\n/// Anthropic-specific pricing configuration.\n///\n/// Contains pricing information for different Claude model variants\n/// and their associated costs.\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct AnthropicPricing {\n pub claude_3_sonnet: ModelPricing,\n pub claude_3_haiku: ModelPricing,\n pub claude_3_opus: ModelPricing,\n}\n\n/// Generic model pricing configuration.\n///\n/// Contains detailed pricing information for a specific model,\n/// including input, output, and caching costs.\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct ModelPricing {\n pub input_price: f64, // per million tokens\n pub output_price: f64, // per million tokens\n pub cache_write_price: f64, // per million tokens\n pub cache_read_price: f64, // per million tokens\n}\n\nimpl Config {\n /// Loads configuration from the default config file.\n ///\n /// Attempts to load and parse the configuration from 'config.toml'.\n /// Falls back to default values if the file cannot be loaded or parsed.\n ///\n /// # Returns\n ///\n /// * `anyhow::Result` - The loaded configuration or an error if loading fails\n ///\n /// # Errors\n ///\n /// Returns an error if:\n /// - The config file cannot be read\n /// - The TOML content cannot be parsed\n /// - The parsed content doesn't match the expected structure\n pub fn load() -> anyhow::Result {\n let config_path = Path::new(\"config.toml\");\n let config = config::Config::builder()\n .add_source(config::File::from(config_path))\n .build()?;\n\n Ok(config.try_deserialize()?)\n }\n}\n\n/// Provides default configuration values.\n///\n/// These defaults are used when a configuration file is not present\n/// or when specific values are not provided in the config file.\nimpl Default for Config {\n fn default() -> Self {\n Self {\n server: ServerConfig {\n host: \"127.0.0.1\".to_string(),\n port: 3000,\n },\n pricing: PricingConfig {\n deepseek: DeepSeekPricing {\n input_cache_hit_price: 0.14,\n input_cache_miss_price: 0.55,\n output_price: 2.19,\n },\n anthropic: AnthropicPricing {\n claude_3_sonnet: ModelPricing {\n input_price: 3.0,\n output_price: 15.0,\n cache_write_price: 3.75,\n cache_read_price: 0.30,\n },\n claude_3_haiku: ModelPricing {\n input_price: 0.80,\n output_price: 4.0,\n cache_write_price: 1.0,\n cache_read_price: 0.08,\n },\n claude_3_opus: ModelPricing {\n input_price: 15.0,\n output_price: 75.0,\n cache_write_price: 18.75,\n cache_read_price: 1.50,\n },\n },\n },\n }\n }\n}\n"], ["/deepclaude/src/main.rs", "//! DeepClaude - A high-performance LLM inference API and Chat UI that integrates DeepSeek R1's CoT reasoning traces with Anthropic Claude models..\n//!\n//! This application provides a REST API for chat interactions that:\n//! - Processes messages through DeepSeek R1 for reasoning\n//! - Uses Anthropic's Claude for final responses\n//! - Supports both streaming and non-streaming responses\n//! - Tracks token usage and costs\n//! - Provides detailed usage statistics\n//!\n//! The API requires authentication tokens for both services and\n//! supports custom configuration through a TOML config file.\n\nmod clients;\nmod config;\nmod error;\nmod handlers;\nmod models;\n\nuse crate::{config::Config, handlers::AppState};\nuse axum::routing::{post, Router};\nuse std::{net::SocketAddr, sync::Arc};\nuse tower_http::{\n cors::{Any, CorsLayer},\n trace::TraceLayer,\n};\nuse tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};\n\n/// Application entry point.\n///\n/// Sets up logging, loads configuration, and starts the HTTP server\n/// with the configured routes and middleware.\n///\n/// # Returns\n///\n/// * `anyhow::Result<()>` - Ok if server starts successfully, Err otherwise\n///\n/// # Errors\n///\n/// Returns an error if:\n/// - Logging setup fails\n/// - Server address binding fails\n/// - Server encounters a fatal error while running\n#[tokio::main]\nasync fn main() -> anyhow::Result<()> {\n // Initialize logging\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env()\n .unwrap_or_else(|_| \"deepclaude=debug,tower_http=debug\".into()),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n // Load configuration\n let config = Config::load().unwrap_or_else(|_| {\n tracing::warn!(\"Failed to load config.toml, using default configuration\");\n Config::default()\n });\n\n // Create application state\n // Clone config for AppState\n let config_clone = config.clone();\n let state = Arc::new(AppState { config: config_clone });\n\n // Set up CORS\n let cors = CorsLayer::new()\n .allow_methods(Any)\n .allow_headers(Any)\n .allow_origin(Any);\n\n // Build router\n let app = Router::new()\n .route(\"/\", post(handlers::handle_chat))\n .layer(TraceLayer::new_for_http())\n .layer(cors)\n .with_state(state);\n\n // Get host and port from config\n let addr: SocketAddr = format!(\"{}:{}\", config.server.host, config.server.port)\n .parse()\n .expect(\"Invalid host/port configuration\");\n\n tracing::info!(\"Starting server on {}\", addr);\n\n // Start server\n axum::serve(\n tokio::net::TcpListener::bind(&addr).await?,\n app.into_make_service(),\n )\n .await?;\n\n Ok(())\n}\n"], ["/deepclaude/src/models/mod.rs", "pub mod request;\npub mod response;\n\npub use request::*;\npub use response::*;\n"]], "task_instance_info": {"created_time": "2025-08-21 01:33:31", "created_task_model": "DeepSeek-R1", "function_skeleton": "pub(crate) fn build_headers (&self, custom_headers: Option<&HashMap>) -> Result {}", "code_description": "This code segment functions to: Construct and validate HTTP headers for API requests, including authentication credentials and content type specifications, while incorporating optional custom headers and handling potential parsing errors."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```rust\n[TASK_BEGIN]\n pub(crate) fn build_headers(&self, custom_headers: Option<&HashMap>) -> Result {\n let mut headers = HeaderMap::new();\n\n // Process custom headers first to allow required headers to override them\n if let Some(custom) = custom_headers {\n for (key, value) in custom {\n let header_name = HeaderName::from_str(key).map_err(|e| {\n ApiError::Internal(format!(\"Invalid custom header name '{}': {}\", key, e))\n })?;\n let header_value = HeaderValue::from_str(value).map_err(|e| {\n ApiError::Internal(format!(\"Invalid value for header '{}': {}\", key, e))\n })?;\n headers.insert(header_name, header_value);\n }\n }\n\n // Add required headers (will override any existing values from custom headers)\n headers.insert(\n reqwest::header::AUTHORIZATION,\n HeaderValue::from_str(&format!(\"Bearer {}\", self.api_token))\n .map_err(|e| ApiError::Internal(format!(\"Failed to construct Authorization header: {}\", e)))?\n );\n\n headers.insert(\n reqwest::header::CONTENT_TYPE,\n HeaderValue::from_str(\"application/json\")\n .map_err(|e| ApiError::Internal(format!(\"Invalid Content-Type header: {}\", e)))?\n );\n\n headers.insert(\n reqwest::header::ACCEPT,\n HeaderValue::from_str(\"application/json\")\n .map_err(|e| ApiError::Internal(format!(\"Invalid Accept header: {}\", e)))?\n );\n\n Ok(headers)\n }\n[TASK_END]\n```", "inference_time": "2025-08-21 01-34-28"}, "editdistance_info": {"edit_distance": 32.8859, "calculate_time": "2025-08-21 01:34:28", "true_code_clean": "pub(crate) fn build_headers(&self, custom_headers: Option<&HashMap>) -> Result {\n let mut headers = HeaderMap::new();\n headers.insert(\n \"Authorization\",\n format!(\"Bearer {}\", self.api_token)\n .parse()\n .map_err(|e| ApiError::Internal { \n message: format!(\"Invalid API token: {}\", e) \n })?,\n );\n headers.insert(\n \"Content-Type\",\n \"application/json\"\n .parse()\n .map_err(|e| ApiError::Internal { \n message: format!(\"Invalid content type: {}\", e) \n })?,\n );\n headers.insert(\n \"Accept\",\n \"application/json\"\n .parse()\n .map_err(|e| ApiError::Internal { \n message: format!(\"Invalid accept header: {}\", e) \n })?,\n );\n if let Some(custom) = custom_headers {\n headers.extend(super::build_headers(custom)?);\n }\n Ok(headers)\n }", "predict_code_clean": "pub(crate) fn build_headers(&self, custom_headers: Option<&HashMap>) -> Result {\n let mut headers = HeaderMap::new();\n if let Some(custom) = custom_headers {\n for (key, value) in custom {\n let header_name = HeaderName::from_str(key).map_err(|e| {\n ApiError::Internal(format!(\"Invalid custom header name '{}': {}\", key, e))\n })?;\n let header_value = HeaderValue::from_str(value).map_err(|e| {\n ApiError::Internal(format!(\"Invalid value for header '{}': {}\", key, e))\n })?;\n headers.insert(header_name, header_value);\n }\n }\n headers.insert(\n reqwest::header::AUTHORIZATION,\n HeaderValue::from_str(&format!(\"Bearer {}\", self.api_token))\n .map_err(|e| ApiError::Internal(format!(\"Failed to construct Authorization header: {}\", e)))?\n );\n headers.insert(\n reqwest::header::CONTENT_TYPE,\n HeaderValue::from_str(\"application/json\")\n .map_err(|e| ApiError::Internal(format!(\"Invalid Content-Type header: {}\", e)))?\n );\n headers.insert(\n reqwest::header::ACCEPT,\n HeaderValue::from_str(\"application/json\")\n .map_err(|e| ApiError::Internal(format!(\"Invalid Accept header: {}\", e)))?\n );\n Ok(headers)\n }"}} {"repo_name": "deepclaude", "file_name": "/deepclaude/src/models/request.rs", "inference_info": {"prefix_code": "//! Request models for the API endpoints.\n//!\n//! This module defines the structures used to represent incoming API requests,\n//! including chat messages, configuration options, and request parameters.\n\nuse serde::{Deserialize, Serialize};\nuse std::collections::HashMap;\n\n/// Primary request structure for chat API endpoints.\n///\n/// This structure represents a complete chat request, including messages,\n/// system prompts, and configuration options for both DeepSeek and Anthropic APIs.\n#[derive(Debug, Clone, Deserialize, Serialize)]\npub struct ApiRequest {\n #[serde(default)]\n pub stream: bool,\n \n #[serde(default)]\n pub verbose: bool,\n \n pub system: Option,\n pub messages: Vec,\n \n #[serde(default)]\n pub deepseek_config: ApiConfig,\n \n #[serde(default)]\n pub anthropic_config: ApiConfig,\n}\n\n/// A single message in a chat conversation.\n///\n/// Represents one message in the conversation history, including\n/// its role (system, user, or assistant) and content.\n#[derive(Debug, Clone, Deserialize, Serialize)]\npub struct Message {\n pub role: Role,\n pub content: String,\n}\n\n/// Possible roles for a message in a chat conversation.\n///\n/// Each message must be associated with one of these roles to\n/// properly structure the conversation flow.\n#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]\n#[serde(rename_all = \"lowercase\")]\npub enum Role {\n System,\n User,\n Assistant,\n}\n\n/// Configuration options for external API requests.\n///\n/// Contains headers and body parameters that will be passed\n/// to the external AI model APIs.\n#[derive(Debug, Clone, Default, Deserialize, Serialize)]\npub struct ApiConfig {\n #[serde(default)]\n pub headers: HashMap,\n \n #[serde(default)]\n pub body: serde_json::Value,\n}\n\nimpl ApiRequest {\n /// Validates that system prompts are not duplicated.\n ///\n /// Checks that a system prompt is not provided in both the root level\n /// and messages array. The system prompt itself is optional.\n ///\n /// # Returns\n ///\n /// * `bool` - True if system prompt validation passes (no duplicates), false otherwise\n pub fn validate_system_prompt(&self) -> bool {\n let system_in_messages = self.messages.iter().any(|msg| matches!(msg.role, Role::System));\n \n // Only invalid if system prompt is provided in both places\n !(self.system.is_some() && system_in_messages)\n }\n\n /// Returns messages with the system prompt in the correct position.\n ///\n /// Ensures the system prompt (if present) is the first message,\n /// followed by the conversation messages in order.\n ///\n /// # Returns\n ///\n /// * `Vec` - Messages with system prompt correctly positioned\n ", "suffix_code": "\n\n /// Retrieves the system prompt if one is present.\n ///\n /// Checks both the root level system field and the messages array\n /// for a system prompt.\n ///\n /// # Returns\n ///\n /// * `Option<&str>` - The system prompt if found, None otherwise\n pub fn get_system_prompt(&self) -> Option<&str> {\n self.system.as_deref().or_else(|| {\n self.messages\n .iter()\n .find(|msg| matches!(msg.role, Role::System))\n .map(|msg| msg.content.as_str())\n })\n }\n}\n", "middle_code": "pub fn get_messages_with_system(&self) -> Vec {\n let mut messages = Vec::new();\n if let Some(system) = &self.system {\n messages.push(Message {\n role: Role::System,\n content: system.clone(),\n });\n }\n messages.extend(self.messages.iter().filter(|msg| !matches!(msg.role, Role::System)).cloned());\n messages\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "rust", "sub_task_type": null}, "context_code": [["/deepclaude/src/clients/anthropic.rs", "//! Anthropic API client implementation for interacting with Claude models.\n//!\n//! This module provides a client implementation for communicating with Anthropic's API,\n//! specifically designed to work with Claude language models. It supports both streaming\n//! and non-streaming interactions, handling all aspects of API communication including:\n//!\n//! - Authentication and request signing\n//! - Message formatting and serialization\n//! - Response parsing and deserialization\n//! - Error handling and type conversion\n//! - Streaming response processing\n//!\n//! # Main Components\n//!\n//! - [`AnthropicClient`]: The main client struct for making API requests\n//! - [`AnthropicResponse`]: Represents the structured response from the API\n//! - [`StreamEvent`]: Represents different types of events in streaming responses\n//!\n//! # Example Usage\n//!\n//! ```no_run\n//! use deepclaude::clients::AnthropicClient;\n//! use deepclaude::models::{Message, ApiConfig};\n//!\n//! async fn example() -> Result<(), Box> {\n//! let client = AnthropicClient::new(\"your-api-key\".to_string());\n//! let messages = vec![/* your messages */];\n//! let config = ApiConfig::default();\n//!\n//! // Non-streaming request\n//! let response = client.chat(messages.clone(), None, &config).await?;\n//!\n//! // Streaming request\n//! let stream = client.chat_stream(messages, None, &config);\n//! Ok(())\n//! }\n//! ```\n\nuse crate::{\n error::{ApiError, Result},\n models::{ApiConfig, Message, Role},\n};\nuse futures::Stream;\nuse reqwest::{header::HeaderMap, Client};\nuse serde::{Deserialize, Serialize};\nuse std::{collections::HashMap, pin::Pin};\nuse futures::StreamExt;\nuse serde_json;\n\npub(crate) const ANTHROPIC_API_URL: &str = \"https://api.anthropic.com/v1/messages\";\nconst DEFAULT_MODEL: &str = \"claude-3-5-sonnet-20241022\";\n\n/// Client for interacting with Anthropic's Claude models.\n///\n/// This client handles authentication, request construction, and response parsing\n/// for both streaming and non-streaming interactions with Anthropic's API.\n///\n/// # Examples\n///\n/// ```no_run\n/// use deepclaude::clients::AnthropicClient;\n///\n/// let client = AnthropicClient::new(\"api_token\".to_string());\n/// ```\n#[derive(Debug)]\npub struct AnthropicClient {\n pub(crate) client: Client,\n api_token: String,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct AnthropicResponse {\n pub id: String,\n #[serde(rename = \"type\")]\n pub response_type: String,\n pub role: String,\n pub model: String,\n pub content: Vec,\n pub stop_reason: Option,\n pub stop_sequence: Option,\n pub usage: Usage,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct ContentBlock {\n #[serde(rename = \"type\")]\n pub content_type: String,\n pub text: String,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct Usage {\n pub input_tokens: u32,\n pub output_tokens: u32,\n pub cache_creation_input_tokens: u32,\n pub cache_read_input_tokens: u32,\n}\n\n#[derive(Debug, Serialize, Deserialize)]\npub(crate) struct AnthropicRequest {\n messages: Vec,\n stream: bool,\n #[serde(skip_serializing_if = \"Option::is_none\")]\n system: Option,\n #[serde(flatten)]\n additional_params: serde_json::Value,\n}\n\n#[derive(Debug, Serialize, Deserialize)]\npub(crate) struct AnthropicMessage {\n role: String,\n content: String,\n}\n\n// Event types for streaming responses\n#[derive(Debug, Deserialize)]\n#[serde(tag = \"type\")]\npub enum StreamEvent {\n #[serde(rename = \"message_start\")]\n MessageStart {\n message: AnthropicResponse,\n },\n #[serde(rename = \"content_block_start\")]\n #[allow(dead_code)]\n ContentBlockStart {\n index: usize,\n content_block: ContentBlock,\n },\n #[serde(rename = \"content_block_delta\")]\n #[allow(dead_code)]\n ContentBlockDelta {\n index: usize,\n delta: ContentDelta,\n },\n #[serde(rename = \"content_block_stop\")]\n #[allow(dead_code)]\n ContentBlockStop {\n index: usize,\n },\n #[serde(rename = \"message_delta\")]\n #[allow(dead_code)]\n MessageDelta {\n delta: MessageDelta,\n usage: Option,\n },\n #[serde(rename = \"message_stop\")]\n MessageStop,\n #[serde(rename = \"ping\")]\n Ping,\n}\n\n#[derive(Debug, Deserialize, Clone)]\npub struct ContentDelta {\n #[serde(rename = \"type\")]\n pub delta_type: String,\n pub text: String,\n}\n\n#[derive(Debug, Deserialize, Clone)]\n#[allow(dead_code)]\npub struct MessageDelta {\n pub stop_reason: Option,\n pub stop_sequence: Option,\n}\n\nimpl AnthropicClient {\n /// Creates a new Anthropic client instance.\n ///\n /// # Arguments\n ///\n /// * `api_token` - API token for authentication with Anthropic's API\n ///\n /// # Returns\n ///\n /// A new `AnthropicClient` instance configured with the provided API token\n pub fn new(api_token: String) -> Self {\n Self {\n client: Client::new(),\n api_token,\n }\n }\n\n /// Builds the HTTP headers required for Anthropic API requests.\n ///\n /// # Arguments\n ///\n /// * `custom_headers` - Optional additional headers to include in requests\n ///\n /// # Returns\n ///\n /// * `Result` - The constructed headers on success, or an error if header construction fails\n ///\n /// # Errors\n ///\n /// Returns `ApiError::Internal` if:\n /// - The API token is invalid\n /// - Content-Type or Anthropic-Version headers cannot be constructed\n pub(crate) fn build_headers(&self, custom_headers: Option<&HashMap>) -> Result {\n let mut headers = HeaderMap::new();\n headers.insert(\n \"x-api-key\",\n self.api_token\n .parse()\n .map_err(|e| ApiError::Internal { \n message: format!(\"Invalid API token: {}\", e) \n })?,\n );\n headers.insert(\n \"content-type\",\n \"application/json\"\n .parse()\n .map_err(|e| ApiError::Internal { \n message: format!(\"Invalid content type: {}\", e) \n })?,\n );\n headers.insert(\n \"anthropic-version\",\n \"2023-06-01\"\n .parse()\n .map_err(|e| ApiError::Internal { \n message: format!(\"Invalid anthropic version: {}\", e) \n })?,\n );\n\n if let Some(custom) = custom_headers {\n headers.extend(super::build_headers(custom)?);\n }\n\n Ok(headers)\n }\n\n /// Constructs a request object for the Anthropic API.\n ///\n /// # Arguments\n ///\n /// * `messages` - Vector of messages to send to the model\n /// * `system` - Optional system prompt to set context\n /// * `stream` - Whether to enable streaming mode\n /// * `config` - Configuration options for the request\n ///\n /// # Returns\n ///\n /// An `AnthropicRequest` object configured with the provided parameters and defaults\n pub(crate) fn build_request(\n &self,\n messages: Vec,\n system: Option,\n stream: bool,\n config: &ApiConfig,\n ) -> AnthropicRequest {\n let filtered_messages = messages\n .into_iter()\n .filter(|msg| msg.role != Role::System)\n .map(|msg| AnthropicMessage {\n role: match msg.role {\n Role::User => \"user\".to_string(),\n Role::Assistant => \"assistant\".to_string(),\n Role::System => unreachable!(),\n },\n content: msg.content,\n })\n .collect();\n\n // Create base request with required fields\n let default_model = serde_json::json!(DEFAULT_MODEL);\n let model_value = config.body.get(\"model\").unwrap_or(&default_model);\n \n let default_max_tokens = if let Some(model_str) = model_value.as_str() {\n if model_str.contains(\"claude-3-opus\") {\n 4096\n } else {\n 8192\n }\n } else {\n 8192\n };\n let default_max_tokens_json = serde_json::json!(default_max_tokens);\n\n let mut request_value = serde_json::json!({\n \"messages\": filtered_messages,\n \"stream\": stream,\n \"model\": model_value,\n \"max_tokens\": config.body.get(\"max_tokens\").unwrap_or(&default_max_tokens_json)\n });\n\n // Add system if present\n if let Some(ref sys) = system {\n if let serde_json::Value::Object(mut map) = request_value {\n map.insert(\"system\".to_string(), serde_json::json!(sys));\n request_value = serde_json::Value::Object(map);\n }\n }\n\n // Merge additional configuration from config.body while protecting critical fields\n if let serde_json::Value::Object(mut map) = request_value {\n if let serde_json::Value::Object(mut body) = serde_json::to_value(&config.body).unwrap_or_default() {\n // Remove protected fields from config body\n body.remove(\"stream\");\n body.remove(\"messages\");\n body.remove(\"system\");\n \n // Merge remaining fields from config.body\n for (key, value) in body {\n map.insert(key, value);\n }\n }\n request_value = serde_json::Value::Object(map);\n }\n\n // Convert the merged JSON value into our request structure\n serde_json::from_value(request_value).unwrap_or_else(|_| AnthropicRequest {\n messages: filtered_messages,\n stream,\n system,\n additional_params: config.body.clone(),\n })\n }\n\n /// Sends a non-streaming chat request to the Anthropic API.\n ///\n /// # Arguments\n ///\n /// * `messages` - Vector of messages for the conversation\n /// * `system` - Optional system prompt to set context\n /// * `config` - Configuration options for the request\n ///\n /// # Returns\n ///\n /// * `Result` - The model's response on success\n ///\n /// # Errors\n ///\n /// Returns `ApiError::AnthropicError` if:\n /// - The API request fails\n /// - The response status is not successful\n /// - The response cannot be parsed\n pub async fn chat(\n &self,\n messages: Vec,\n system: Option,\n config: &ApiConfig,\n ) -> Result {\n let headers = self.build_headers(Some(&config.headers))?;\n let request = self.build_request(messages, system, false, config);\n\n let response = self\n .client\n .post(ANTHROPIC_API_URL)\n .headers(headers)\n .json(&request)\n .send()\n .await\n .map_err(|e| ApiError::AnthropicError { \n message: format!(\"Request failed: {}\", e),\n type_: \"request_failed\".to_string(),\n param: None,\n code: None\n })?;\n\n if !response.status().is_success() {\n let error = response\n .text()\n .await\n .unwrap_or_else(|_| \"Unknown error\".to_string());\n return Err(ApiError::AnthropicError { \n message: error,\n type_: \"api_error\".to_string(),\n param: None,\n code: None\n });\n }\n\n response\n .json::()\n .await\n .map_err(|e| ApiError::AnthropicError { \n message: format!(\"Failed to parse response: {}\", e),\n type_: \"parse_error\".to_string(),\n param: None,\n code: None\n })\n }\n\n /// Sends a streaming chat request to the Anthropic API.\n ///\n /// Returns a stream that yields events from the model's response as they arrive.\n ///\n /// # Arguments\n ///\n /// * `messages` - Vector of messages for the conversation\n /// * `system` - Optional system prompt to set context\n /// * `config` - Configuration options for the request\n ///\n /// # Returns\n ///\n /// * `Pin> + Send>>` - A stream of response events\n ///\n /// # Errors\n ///\n /// The stream may yield `ApiError::AnthropicError` if:\n /// - The API request fails\n /// - Stream processing encounters an error\n /// - Response events cannot be parsed\n pub fn chat_stream(\n &self,\n messages: Vec,\n system: Option,\n config: &ApiConfig,\n ) -> Pin> + Send>> {\n let headers = match self.build_headers(Some(&config.headers)) {\n Ok(h) => h,\n Err(e) => return Box::pin(futures::stream::once(async move { Err(e) })),\n };\n\n let request = self.build_request(messages, system, true, config);\n let client = self.client.clone();\n\n Box::pin(async_stream::try_stream! {\n let mut stream = client\n .post(ANTHROPIC_API_URL)\n .headers(headers)\n .json(&request)\n .send()\n .await\n .map_err(|e| ApiError::AnthropicError { \n message: format!(\"Request failed: {}\", e),\n type_: \"request_failed\".to_string(),\n param: None,\n code: None\n })?\n .bytes_stream();\n\n let mut data = String::new();\n \n while let Some(chunk) = stream.next().await {\n let chunk = chunk.map_err(|e| ApiError::AnthropicError { \n message: format!(\"Stream error: {}\", e),\n type_: \"stream_error\".to_string(),\n param: None,\n code: None\n })?;\n data.push_str(&String::from_utf8_lossy(&chunk));\n\n let mut start = 0;\n while let Some(end) = data[start..].find(\"\\n\\n\") {\n let end = start + end;\n let event_data = &data[start..end];\n start = end + 2;\n\n if event_data.starts_with(\"event: \") {\n let _event_line = &event_data[\"event: \".len()..];\n if let Some(data_line) = event_data.lines().nth(1) {\n if data_line.starts_with(\"data: \") {\n let json_data = &data_line[\"data: \".len()..];\n if let Ok(event) = serde_json::from_str::(json_data) {\n yield event;\n }\n }\n }\n }\n }\n\n if start > 0 {\n data = data[start..].to_string();\n }\n }\n })\n }\n}\n\n/// Converts an Anthropic content block into the application's generic content block type.\nimpl From for crate::models::response::ContentBlock {\n fn from(block: ContentBlock) -> Self {\n Self {\n content_type: block.content_type,\n text: block.text,\n }\n }\n}\n"], ["/deepclaude/src/clients/deepseek.rs", "//! DeepSeek API client implementation for interacting with DeepSeek's AI models.\n//!\n//! This module provides a client implementation for making requests to DeepSeek's chat completion API.\n//! It supports both streaming and non-streaming interactions, handling authentication, request\n//! construction, and response parsing.\n//!\n//! # Features\n//!\n//! - Supports chat completions with DeepSeek's AI models\n//! - Handles both streaming and non-streaming responses\n//! - Configurable request parameters (model, max tokens, temperature)\n//! - Custom header support\n//! - Comprehensive error handling\n//!\n//! # Examples\n//!\n//! ```no_run\n//! use crate::{\n//! clients::DeepSeekClient,\n//! models::{ApiConfig, Message},\n//! };\n//!\n//! # async fn example() -> Result<(), Box> {\n//! // Initialize the client\n//! let client = DeepSeekClient::new(\"your-api-key\".to_string());\n//!\n//! // Prepare messages and configuration\n//! let messages = vec![Message {\n//! role: \"user\".to_string(),\n//! content: \"Hello, how are you?\".to_string(),\n//! }];\n//!\n//! let config = ApiConfig::default();\n//!\n//! // Make a non-streaming request\n//! let response = client.chat(messages.clone(), &config).await?;\n//!\n//! // Or use streaming for real-time responses\n//! let mut stream = client.chat_stream(messages, &config);\n//! while let Some(chunk) = stream.next().await {\n//! println!(\"Received chunk: {:?}\", chunk?);\n//! }\n//! # Ok(())\n//! # }\n//! ```\n//!\n//! # Error Handling\n//!\n//! The client uses a custom error type `ApiError` to handle various failure cases:\n//! - Network errors\n//! - API authentication errors\n//! - Invalid response formats\n//! - Stream processing errors\n//!\n//! All public methods return `Result` types with appropriate error variants.\n\nuse crate::{\n error::{ApiError, Result},\n models::{ApiConfig, Message},\n};\nuse futures::Stream;\nuse reqwest::{header::HeaderMap, Client};\nuse serde::{Deserialize, Serialize};\nuse std::{collections::HashMap, pin::Pin};\nuse futures::StreamExt;\nuse serde_json;\n\npub(crate) const DEEPSEEK_API_URL: &str = \"https://api.deepseek.com/chat/completions\";\nconst DEFAULT_MODEL: &str = \"deepseek-reasoner\";\n\n/// Client for interacting with DeepSeek's AI models.\n///\n/// This client handles authentication, request construction, and response parsing\n/// for both streaming and non-streaming interactions with DeepSeek's API.\n///\n/// # Examples\n///\n/// ```no_run\n/// use deepclaude::clients::DeepSeekClient;\n///\n/// let client = DeepSeekClient::new(\"api_token\".to_string());\n/// ```\n#[derive(Debug)]\npub struct DeepSeekClient {\n pub(crate) client: Client,\n api_token: String,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct DeepSeekResponse {\n pub id: String,\n pub object: String,\n pub created: i64,\n pub model: String,\n pub choices: Vec,\n pub usage: Usage,\n pub system_fingerprint: String,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct Choice {\n pub index: i32,\n pub message: AssistantMessage,\n pub logprobs: Option,\n pub finish_reason: Option,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct AssistantMessage {\n pub role: String,\n pub content: Option,\n pub reasoning_content: Option,\n}\n\n// Streaming response types\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct StreamChoice {\n pub index: i32,\n pub delta: StreamDelta,\n pub logprobs: Option,\n pub finish_reason: Option,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct StreamDelta {\n pub role: Option,\n pub content: Option,\n pub reasoning_content: Option,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct StreamResponse {\n pub id: String,\n pub object: String,\n pub created: i64,\n pub model: String,\n pub choices: Vec,\n pub usage: Option,\n pub system_fingerprint: String,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct Usage {\n pub prompt_tokens: u32,\n pub completion_tokens: u32,\n pub total_tokens: u32,\n pub prompt_tokens_details: PromptTokensDetails,\n pub completion_tokens_details: CompletionTokensDetails,\n pub prompt_cache_hit_tokens: u32,\n pub prompt_cache_miss_tokens: u32,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct PromptTokensDetails {\n pub cached_tokens: u32,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct CompletionTokensDetails {\n pub reasoning_tokens: u32,\n}\n\n#[derive(Debug, Serialize, Deserialize)]\npub(crate) struct DeepSeekRequest {\n messages: Vec,\n stream: bool,\n #[serde(flatten)]\n additional_params: serde_json::Value,\n}\n\nimpl DeepSeekClient {\n pub fn new(api_token: String) -> Self {\n Self {\n client: Client::new(),\n api_token,\n }\n }\n\n /// Builds the HTTP headers required for DeepSeek API requests.\n ///\n /// # Arguments\n ///\n /// * `custom_headers` - Optional additional headers to include in requests\n ///\n /// # Returns\n ///\n /// * `Result` - The constructed headers on success, or an error if header construction fails\n ///\n /// # Errors\n ///\n /// Returns `ApiError::Internal` if:\n /// - The API token is invalid\n /// - Content-Type or Accept headers cannot be constructed\n pub(crate) fn build_headers(&self, custom_headers: Option<&HashMap>) -> Result {\n let mut headers = HeaderMap::new();\n headers.insert(\n \"Authorization\",\n format!(\"Bearer {}\", self.api_token)\n .parse()\n .map_err(|e| ApiError::Internal { \n message: format!(\"Invalid API token: {}\", e) \n })?,\n );\n headers.insert(\n \"Content-Type\",\n \"application/json\"\n .parse()\n .map_err(|e| ApiError::Internal { \n message: format!(\"Invalid content type: {}\", e) \n })?,\n );\n headers.insert(\n \"Accept\",\n \"application/json\"\n .parse()\n .map_err(|e| ApiError::Internal { \n message: format!(\"Invalid accept header: {}\", e) \n })?,\n );\n\n if let Some(custom) = custom_headers {\n headers.extend(super::build_headers(custom)?);\n }\n\n Ok(headers)\n }\n\n /// Constructs a request object for the DeepSeek API.\n ///\n /// # Arguments\n ///\n /// * `messages` - Vector of messages to send to the model\n /// * `stream` - Whether to enable streaming mode\n /// * `config` - Configuration options for the request\n ///\n /// # Returns\n ///\n /// A `DeepSeekRequest` object configured with the provided parameters and defaults\n pub(crate) fn build_request(&self, messages: Vec, stream: bool, config: &ApiConfig) -> DeepSeekRequest {\n // Create a base request with required fields\n let mut request_value = serde_json::json!({\n \"messages\": messages,\n \"stream\": stream,\n // Set defaults only if not provided in config\n \"model\": config.body.get(\"model\").unwrap_or(&serde_json::json!(DEFAULT_MODEL)),\n \"max_tokens\": config.body.get(\"max_tokens\").unwrap_or(&serde_json::json!(8192)),\n \"temperature\": config.body.get(\"temperature\").unwrap_or(&serde_json::json!(1.0)),\n \"response_format\": {\n \"type\": \"text\"\n }\n });\n\n // Merge additional configuration from config.body while protecting critical fields\n if let serde_json::Value::Object(mut map) = request_value {\n if let serde_json::Value::Object(mut body) = serde_json::to_value(&config.body).unwrap_or_default() {\n // Remove protected fields from config body\n body.remove(\"stream\");\n body.remove(\"messages\");\n \n // Merge remaining fields from config.body\n for (key, value) in body {\n map.insert(key, value);\n }\n }\n request_value = serde_json::Value::Object(map);\n }\n\n // Convert the merged JSON value into our request structure\n serde_json::from_value(request_value).unwrap_or_else(|_| DeepSeekRequest {\n messages,\n stream,\n additional_params: config.body.clone(),\n })\n }\n\n /// Sends a non-streaming chat request to the DeepSeek API.\n ///\n /// # Arguments\n ///\n /// * `messages` - Vector of messages for the conversation\n /// * `config` - Configuration options for the request\n ///\n /// # Returns\n ///\n /// * `Result` - The model's response on success\n ///\n /// # Errors\n ///\n /// Returns `ApiError::DeepSeekError` if:\n /// - The API request fails\n /// - The response status is not successful\n /// - The response cannot be parsed\n pub async fn chat(\n &self,\n messages: Vec,\n config: &ApiConfig,\n ) -> Result {\n let headers = self.build_headers(Some(&config.headers))?;\n let request = self.build_request(messages, false, config);\n\n let response = self\n .client\n .post(DEEPSEEK_API_URL)\n .headers(headers)\n .json(&request)\n .send()\n .await\n .map_err(|e| ApiError::DeepSeekError { \n message: format!(\"Request failed: {}\", e),\n type_: \"request_failed\".to_string(),\n param: None,\n code: None\n })?;\n\n if !response.status().is_success() {\n let error = response\n .text()\n .await\n .unwrap_or_else(|_| \"Unknown error\".to_string());\n return Err(ApiError::DeepSeekError { \n message: error,\n type_: \"api_error\".to_string(),\n param: None,\n code: None\n });\n }\n\n response\n .json::()\n .await\n .map_err(|e| ApiError::DeepSeekError { \n message: format!(\"Failed to parse response: {}\", e),\n type_: \"parse_error\".to_string(),\n param: None,\n code: None\n })\n }\n\n /// Sends a streaming chat request to the DeepSeek API.\n ///\n /// Returns a stream that yields chunks of the model's response as they arrive.\n ///\n /// # Arguments\n ///\n /// * `messages` - Vector of messages for the conversation\n /// * `config` - Configuration options for the request\n ///\n /// # Returns\n ///\n /// * `Pin> + Send>>` - A stream of response chunks\n ///\n /// # Errors\n ///\n /// The stream may yield `ApiError::DeepSeekError` if:\n /// - The API request fails\n /// - Stream processing encounters an error\n /// - Response chunks cannot be parsed\n pub fn chat_stream(\n &self,\n messages: Vec,\n config: &ApiConfig,\n ) -> Pin> + Send>> {\n let headers = match self.build_headers(Some(&config.headers)) {\n Ok(h) => h,\n Err(e) => return Box::pin(futures::stream::once(async move { Err(e) })),\n };\n\n let request = self.build_request(messages, true, config);\n let client = self.client.clone();\n\n Box::pin(async_stream::try_stream! {\n let mut stream = client\n .post(DEEPSEEK_API_URL)\n .headers(headers)\n .json(&request)\n .send()\n .await\n .map_err(|e| ApiError::DeepSeekError { \n message: format!(\"Request failed: {}\", e),\n type_: \"request_failed\".to_string(),\n param: None,\n code: None\n })?\n .bytes_stream();\n\n let mut data = String::new();\n \n while let Some(chunk) = stream.next().await {\n let chunk = chunk.map_err(|e| ApiError::DeepSeekError { \n message: format!(\"Stream error: {}\", e),\n type_: \"stream_error\".to_string(),\n param: None,\n code: None\n })?;\n data.push_str(&String::from_utf8_lossy(&chunk));\n\n let mut start = 0;\n while let Some(end) = data[start..].find(\"\\n\\n\") {\n let end = start + end;\n let line = &data[start..end].trim();\n start = end + 2;\n \n if line.starts_with(\"data: \") {\n let json_data = &line[\"data: \".len()..];\n if let Ok(response) = serde_json::from_str::(json_data) {\n yield response;\n }\n }\n }\n\n if start > 0 {\n data = data[start..].to_string();\n }\n }\n })\n }\n}\n"], ["/deepclaude/src/models/response.rs", "//! Response models for the API endpoints.\n//!\n//! This module defines the structures used to represent API responses,\n//! including chat completions, usage statistics, and streaming events.\n\nuse chrono::{DateTime, Utc};\nuse serde::{Deserialize, Serialize};\nuse std::collections::HashMap;\n\n/// Primary response structure for chat API endpoints.\n///\n/// Contains the complete response from both AI models, including\n/// content blocks, usage statistics, and optional raw API responses.\n#[derive(Debug, Serialize, Clone)]\npub struct ApiResponse {\n pub created: DateTime,\n pub content: Vec,\n \n #[serde(skip_serializing_if = \"Option::is_none\")]\n pub deepseek_response: Option,\n \n #[serde(skip_serializing_if = \"Option::is_none\")]\n pub anthropic_response: Option,\n \n pub combined_usage: CombinedUsage,\n}\n\n/// A block of content in a response.\n///\n/// Represents a single piece of content in the response,\n/// with its type and actual text content.\n#[derive(Debug, Serialize, Deserialize, Clone)]\npub struct ContentBlock {\n #[serde(rename = \"type\")]\n pub content_type: String,\n pub text: String,\n}\n\n/// Raw response from an external API.\n///\n/// Contains the complete response details from an external API\n/// call, including status code, headers, and response body.\n#[derive(Debug, Serialize, Clone)]\npub struct ExternalApiResponse {\n pub status: u16,\n pub headers: HashMap,\n pub body: serde_json::Value,\n}\n\n/// Combined usage statistics from both AI models.\n///\n/// Aggregates token usage and cost information from both\n/// DeepSeek and Anthropic API calls.\n#[derive(Debug, Serialize, Clone)]\npub struct CombinedUsage {\n pub total_cost: String,\n pub deepseek_usage: DeepSeekUsage,\n pub anthropic_usage: AnthropicUsage,\n}\n\n/// Usage statistics for DeepSeek API calls.\n///\n/// Tracks token consumption and costs specific to\n/// DeepSeek model usage.\n#[derive(Debug, Serialize, Clone)]\npub struct DeepSeekUsage {\n pub input_tokens: u32,\n pub output_tokens: u32,\n pub reasoning_tokens: u32,\n pub cached_input_tokens: u32,\n pub total_tokens: u32,\n pub total_cost: String,\n}\n\n/// Usage statistics for Anthropic API calls.\n///\n/// Tracks token consumption and costs specific to\n/// Anthropic model usage.\n#[derive(Debug, Serialize, Clone)]\npub struct AnthropicUsage {\n pub input_tokens: u32,\n pub output_tokens: u32,\n pub cached_write_tokens: u32,\n pub cached_read_tokens: u32,\n pub total_tokens: u32,\n pub total_cost: String,\n}\n\n// Streaming event types\n/// Events emitted during streaming responses.\n///\n/// Represents different types of events that can occur\n/// during a streaming response, including content updates\n/// and usage statistics.\n#[derive(Debug, Serialize)]\n#[serde(tag = \"type\")]\npub enum StreamEvent {\n #[serde(rename = \"start\")]\n Start {\n created: DateTime,\n },\n \n #[serde(rename = \"content\")]\n Content {\n content: Vec,\n },\n \n #[serde(rename = \"usage\")]\n Usage {\n usage: CombinedUsage,\n },\n \n #[serde(rename = \"done\")]\n Done,\n \n #[serde(rename = \"error\")]\n Error {\n message: String,\n code: u16,\n },\n}\n\nimpl ContentBlock {\n /// Creates a new text content block.\n ///\n /// # Arguments\n ///\n /// * `text` - The text content to include in the block\n ///\n /// # Returns\n ///\n /// A new `ContentBlock` with the type set to \"text\"\n pub fn text(text: impl Into) -> Self {\n Self {\n content_type: \"text\".to_string(),\n text: text.into(),\n }\n }\n\n /// Converts an Anthropic content block to a generic content block.\n ///\n /// # Arguments\n ///\n /// * `block` - The Anthropic-specific content block to convert\n ///\n /// # Returns\n ///\n /// A new `ContentBlock` with the same content type and text\n pub fn from_anthropic(block: crate::clients::anthropic::ContentBlock) -> Self {\n Self {\n content_type: block.content_type,\n text: block.text,\n }\n }\n}\n\nimpl ApiResponse {\n /// Creates a new API response with simple text content.\n ///\n /// # Arguments\n ///\n /// * `content` - The text content for the response\n ///\n /// # Returns\n ///\n /// A new `ApiResponse` with default values and the provided content\n #[allow(dead_code)]\n pub fn new(content: impl Into) -> Self {\n Self {\n created: Utc::now(),\n content: vec![ContentBlock::text(content)],\n deepseek_response: None,\n anthropic_response: None,\n combined_usage: CombinedUsage {\n total_cost: \"$0.00\".to_string(),\n deepseek_usage: DeepSeekUsage {\n input_tokens: 0,\n output_tokens: 0,\n reasoning_tokens: 0,\n cached_input_tokens: 0,\n total_tokens: 0,\n total_cost: \"$0.00\".to_string(),\n },\n anthropic_usage: AnthropicUsage {\n input_tokens: 0,\n output_tokens: 0,\n cached_write_tokens: 0,\n cached_read_tokens: 0,\n total_tokens: 0,\n total_cost: \"$0.00\".to_string(),\n },\n },\n }\n }\n}\n\nimpl AnthropicUsage {\n /// Converts Anthropic usage statistics to the generic usage format.\n ///\n /// # Arguments\n ///\n /// * `usage` - The Anthropic-specific usage statistics to convert\n ///\n /// # Returns\n ///\n /// A new `AnthropicUsage` with values copied from the Anthropic usage\n pub fn from_anthropic(usage: crate::clients::anthropic::Usage) -> Self {\n Self {\n input_tokens: usage.input_tokens,\n output_tokens: usage.output_tokens,\n cached_write_tokens: usage.cache_creation_input_tokens,\n cached_read_tokens: usage.cache_read_input_tokens,\n total_tokens: usage.input_tokens + usage.output_tokens,\n total_cost: \"$0.00\".to_string(), // Cost will be calculated later\n }\n }\n}\n"], ["/deepclaude/src/handlers.rs", "//! Request handlers for the API endpoints.\n//!\n//! This module contains the main request handlers and supporting functions\n//! for processing chat requests, including both streaming and non-streaming\n//! responses. It coordinates between different AI models and handles\n//! usage tracking and cost calculations.\n\nuse crate::{\n clients::{AnthropicClient, DeepSeekClient},\n config::Config,\n error::{ApiError, Result, SseResponse},\n models::{\n ApiRequest, ApiResponse, ContentBlock, CombinedUsage, DeepSeekUsage, AnthropicUsage,\n ExternalApiResponse, Message, Role, StreamEvent,\n },\n};\nuse axum::{\n extract::State,\n response::{sse::Event, IntoResponse},\n Json,\n};\nuse chrono::Utc;\nuse futures::StreamExt;\nuse std::{sync::Arc, collections::HashMap};\nuse tokio_stream::wrappers::ReceiverStream;\n\n/// Application state shared across request handlers.\n///\n/// Contains configuration that needs to be accessible\n/// to all request handlers.\npub struct AppState {\n pub config: Config,\n}\n\n/// Extracts API tokens from request headers.\n///\n/// # Arguments\n///\n/// * `headers` - The HTTP headers containing the API tokens\n///\n/// # Returns\n///\n/// * `Result<(String, String)>` - A tuple of (DeepSeek token, Anthropic token)\n///\n/// # Errors\n///\n/// Returns `ApiError::MissingHeader` if either token is missing\n/// Returns `ApiError::BadRequest` if tokens are malformed\nfn extract_api_tokens(\n headers: &axum::http::HeaderMap,\n) -> Result<(String, String)> {\n let deepseek_token = headers\n .get(\"X-DeepSeek-API-Token\")\n .ok_or_else(|| ApiError::MissingHeader { \n header: \"X-DeepSeek-API-Token\".to_string() \n })?\n .to_str()\n .map_err(|_| ApiError::BadRequest { \n message: \"Invalid DeepSeek API token\".to_string() \n })?\n .to_string();\n\n let anthropic_token = headers\n .get(\"X-Anthropic-API-Token\")\n .ok_or_else(|| ApiError::MissingHeader { \n header: \"X-Anthropic-API-Token\".to_string() \n })?\n .to_str()\n .map_err(|_| ApiError::BadRequest { \n message: \"Invalid Anthropic API token\".to_string() \n })?\n .to_string();\n\n Ok((deepseek_token, anthropic_token))\n}\n\n/// Calculates the cost of DeepSeek API usage.\n///\n/// # Arguments\n///\n/// * `input_tokens` - Number of input tokens processed\n/// * `output_tokens` - Number of output tokens generated\n/// * `_reasoning_tokens` - Number of tokens used for reasoning\n/// * `cached_tokens` - Number of tokens retrieved from cache\n/// * `config` - Configuration containing pricing information\n///\n/// # Returns\n///\n/// The total cost in dollars for the API usage\nfn calculate_deepseek_cost(\n input_tokens: u32,\n output_tokens: u32,\n _reasoning_tokens: u32,\n cached_tokens: u32,\n config: &Config,\n) -> f64 {\n let cache_hit_cost = (cached_tokens as f64 / 1_000_000.0) * config.pricing.deepseek.input_cache_hit_price;\n let cache_miss_cost = ((input_tokens - cached_tokens) as f64 / 1_000_000.0) * config.pricing.deepseek.input_cache_miss_price;\n let output_cost = (output_tokens as f64 / 1_000_000.0) * config.pricing.deepseek.output_price;\n \n cache_hit_cost + cache_miss_cost + output_cost\n}\n\n/// Calculates the cost of Anthropic API usage.\n///\n/// # Arguments\n///\n/// * `model` - The specific Claude model used\n/// * `input_tokens` - Number of input tokens processed\n/// * `output_tokens` - Number of output tokens generated\n/// * `cache_write_tokens` - Number of tokens written to cache\n/// * `cache_read_tokens` - Number of tokens read from cache\n/// * `config` - Configuration containing pricing information\n///\n/// # Returns\n///\n/// The total cost in dollars for the API usage\nfn calculate_anthropic_cost(\n model: &str,\n input_tokens: u32,\n output_tokens: u32,\n cache_write_tokens: u32,\n cache_read_tokens: u32,\n config: &Config,\n) -> f64 {\n let pricing = if model.contains(\"claude-3-5-sonnet\") {\n &config.pricing.anthropic.claude_3_sonnet\n } else if model.contains(\"claude-3-5-haiku\") {\n &config.pricing.anthropic.claude_3_haiku\n } else if model.contains(\"claude-3-opus\") {\n &config.pricing.anthropic.claude_3_opus\n } else {\n &config.pricing.anthropic.claude_3_sonnet // default to sonnet pricing\n };\n\n let input_cost = (input_tokens as f64 / 1_000_000.0) * pricing.input_price;\n let output_cost = (output_tokens as f64 / 1_000_000.0) * pricing.output_price;\n let cache_write_cost = (cache_write_tokens as f64 / 1_000_000.0) * pricing.cache_write_price;\n let cache_read_cost = (cache_read_tokens as f64 / 1_000_000.0) * pricing.cache_read_price;\n\n input_cost + output_cost + cache_write_cost + cache_read_cost\n}\n\n/// Formats a cost value as a dollar amount string.\n///\n/// # Arguments\n///\n/// * `cost` - The cost value to format\n///\n/// # Returns\n///\n/// A string representing the cost with 3 decimal places and $ prefix\nfn format_cost(cost: f64) -> String {\n format!(\"${:.3}\", cost)\n}\n\n/// Main handler for chat requests.\n///\n/// Routes requests to either streaming or non-streaming handlers\n/// based on the request configuration.\n///\n/// # Arguments\n///\n/// * `state` - Application state containing configuration\n/// * `headers` - HTTP request headers\n/// * `request` - The parsed chat request\n///\n/// # Returns\n///\n/// * `Result` - The API response or an error\npub async fn handle_chat(\n state: State>,\n headers: axum::http::HeaderMap,\n Json(request): Json,\n) -> Result {\n if request.stream {\n let stream_response = chat_stream(state, headers, Json(request)).await?;\n Ok(stream_response.into_response())\n } else {\n let json_response = chat(state, headers, Json(request)).await?;\n Ok(json_response.into_response())\n }\n}\n\n/// Handler for non-streaming chat requests.\n///\n/// Processes the request through both AI models sequentially,\n/// combining their responses and tracking usage.\n///\n/// # Arguments\n///\n/// * `state` - Application state containing configuration\n/// * `headers` - HTTP request headers\n/// * `request` - The parsed chat request\n///\n/// # Returns\n///\n/// * `Result>` - The combined API response or an error\npub(crate) async fn chat(\n State(state): State>,\n headers: axum::http::HeaderMap,\n Json(request): Json,\n) -> Result> {\n // Validate system prompt\n if !request.validate_system_prompt() {\n return Err(ApiError::InvalidSystemPrompt);\n }\n\n // Extract API tokens\n let (deepseek_token, anthropic_token) = extract_api_tokens(&headers)?;\n\n // Initialize clients\n let deepseek_client = DeepSeekClient::new(deepseek_token);\n let anthropic_client = AnthropicClient::new(anthropic_token);\n\n // Get messages with system prompt\n let messages = request.get_messages_with_system();\n\n // Call DeepSeek API\n let deepseek_response = deepseek_client.chat(messages.clone(), &request.deepseek_config).await?;\n \n // Store response metadata\n let deepseek_status: u16 = 200;\n let deepseek_headers = HashMap::new(); // Headers not available when using high-level chat method\n\n // Extract reasoning content and wrap in thinking tags\n let reasoning_content = deepseek_response\n .choices\n .first()\n .and_then(|c| c.message.reasoning_content.as_ref())\n .ok_or_else(|| ApiError::DeepSeekError { \n message: \"No reasoning content in response\".to_string(),\n type_: \"missing_content\".to_string(),\n param: None,\n code: None\n })?;\n\n let thinking_content = format!(\"\\n{}\\n\", reasoning_content);\n\n // Add thinking content to messages for Anthropic\n let mut anthropic_messages = messages;\n anthropic_messages.push(Message {\n role: Role::Assistant,\n content: thinking_content.clone(),\n });\n\n // Call Anthropic API\n let anthropic_response = anthropic_client.chat(\n anthropic_messages,\n request.get_system_prompt().map(String::from),\n &request.anthropic_config\n ).await?;\n \n // Store response metadata\n let anthropic_status: u16 = 200;\n let anthropic_headers = HashMap::new(); // Headers not available when using high-level chat method\n\n // Calculate usage costs\n let deepseek_cost = calculate_deepseek_cost(\n deepseek_response.usage.prompt_tokens,\n deepseek_response.usage.completion_tokens,\n deepseek_response.usage.completion_tokens_details.reasoning_tokens,\n deepseek_response.usage.prompt_tokens_details.cached_tokens,\n &state.config,\n );\n\n let anthropic_cost = calculate_anthropic_cost(\n &anthropic_response.model,\n anthropic_response.usage.input_tokens,\n anthropic_response.usage.output_tokens,\n anthropic_response.usage.cache_creation_input_tokens,\n anthropic_response.usage.cache_read_input_tokens,\n &state.config,\n );\n\n // Combine thinking content with Anthropic's response\n let mut content = Vec::new();\n \n // Add thinking block first\n content.push(ContentBlock::text(thinking_content));\n \n // Add Anthropic's response blocks\n content.extend(anthropic_response.content.clone().into_iter()\n .map(ContentBlock::from_anthropic));\n\n // Build response with captured headers\n let response = ApiResponse {\n created: Utc::now(),\n content,\n deepseek_response: request.verbose.then(|| ExternalApiResponse {\n status: deepseek_status,\n headers: deepseek_headers,\n body: serde_json::to_value(&deepseek_response).unwrap_or_default(),\n }),\n anthropic_response: request.verbose.then(|| ExternalApiResponse {\n status: anthropic_status,\n headers: anthropic_headers,\n body: serde_json::to_value(&anthropic_response).unwrap_or_default(),\n }),\n combined_usage: CombinedUsage {\n total_cost: format_cost(deepseek_cost + anthropic_cost),\n deepseek_usage: DeepSeekUsage {\n input_tokens: deepseek_response.usage.prompt_tokens,\n output_tokens: deepseek_response.usage.completion_tokens,\n reasoning_tokens: deepseek_response.usage.completion_tokens_details.reasoning_tokens,\n cached_input_tokens: deepseek_response.usage.prompt_tokens_details.cached_tokens,\n total_tokens: deepseek_response.usage.total_tokens,\n total_cost: format_cost(deepseek_cost),\n },\n anthropic_usage: AnthropicUsage {\n input_tokens: anthropic_response.usage.input_tokens,\n output_tokens: anthropic_response.usage.output_tokens,\n cached_write_tokens: anthropic_response.usage.cache_creation_input_tokens,\n cached_read_tokens: anthropic_response.usage.cache_read_input_tokens,\n total_tokens: anthropic_response.usage.input_tokens + anthropic_response.usage.output_tokens,\n total_cost: format_cost(anthropic_cost),\n },\n },\n };\n\n Ok(Json(response))\n}\n\n/// Handler for streaming chat requests.\n///\n/// Processes the request through both AI models sequentially,\n/// streaming their responses as Server-Sent Events.\n///\n/// # Arguments\n///\n/// * `state` - Application state containing configuration\n/// * `headers` - HTTP request headers\n/// * `request` - The parsed chat request\n///\n/// # Returns\n///\n/// * `Result` - A stream of Server-Sent Events or an error\npub(crate) async fn chat_stream(\n State(state): State>,\n headers: axum::http::HeaderMap,\n Json(request): Json,\n) -> Result {\n // Validate system prompt\n if !request.validate_system_prompt() {\n return Err(ApiError::InvalidSystemPrompt);\n }\n\n // Extract API tokens\n let (deepseek_token, anthropic_token) = extract_api_tokens(&headers)?;\n\n // Initialize clients\n let deepseek_client = DeepSeekClient::new(deepseek_token);\n let anthropic_client = AnthropicClient::new(anthropic_token);\n\n // Get messages with system prompt\n let messages = request.get_messages_with_system();\n\n // Create channel for stream events\n let (tx, rx) = tokio::sync::mpsc::channel(100);\n let tx = Arc::new(tx);\n\n // Spawn task to handle streaming\n let config = state.config.clone();\n let request_clone = request.clone();\n tokio::spawn(async move {\n let tx = tx.clone();\n\n // Start event\n let _ = tx\n .send(Ok(Event::default().event(\"start\").data(\n serde_json::to_string(&StreamEvent::Start {\n created: Utc::now(),\n })\n .unwrap_or_default(),\n )))\n .await;\n\n // Send initial thinking tag\n let _ = tx\n .send(Ok(Event::default().event(\"content\").data(\n serde_json::to_string(&StreamEvent::Content {\n content: vec![ContentBlock {\n content_type: \"text\".to_string(),\n text: \"\\n\".to_string(),\n }],\n })\n .unwrap_or_default(),\n )))\n .await;\n\n // Stream from DeepSeek\n let mut deepseek_usage = None;\n let mut complete_reasoning = String::new();\n let mut deepseek_stream = deepseek_client.chat_stream(messages.clone(), &request_clone.deepseek_config);\n \n while let Some(chunk) = deepseek_stream.next().await {\n match chunk {\n Ok(response) => {\n if let Some(choice) = response.choices.first() {\n // Check if reasoning_content is null and break if it is\n if choice.delta.reasoning_content.is_none() {\n break;\n }\n\n // Handle delta reasoning_content for streaming\n if let Some(reasoning) = &choice.delta.reasoning_content {\n if !reasoning.is_empty() {\n // Stream the reasoning content as a delta\n let _ = tx\n .send(Ok(Event::default().event(\"content\").data(\n serde_json::to_string(&StreamEvent::Content {\n content: vec![ContentBlock {\n content_type: \"text_delta\".to_string(),\n text: reasoning.to_string(),\n }],\n })\n .unwrap_or_default(),\n )))\n .await;\n \n // Accumulate complete reasoning for later use\n complete_reasoning.push_str(reasoning);\n }\n }\n }\n \n // Store usage information if present\n if let Some(usage) = response.usage {\n deepseek_usage = Some(usage);\n }\n }\n Err(e) => {\n let _ = tx\n .send(Ok(Event::default().event(\"error\").data(\n serde_json::to_string(&StreamEvent::Error {\n message: e.to_string(),\n code: 500,\n })\n .unwrap_or_default(),\n )))\n .await;\n return;\n }\n }\n }\n\n // Send closing thinking tag\n let _ = tx\n .send(Ok(Event::default().event(\"content\").data(\n serde_json::to_string(&StreamEvent::Content {\n content: vec![ContentBlock {\n content_type: \"text\".to_string(),\n text: \"\\n\".to_string(),\n }],\n })\n .unwrap_or_default(),\n )))\n .await;\n\n // Add complete thinking content to messages for Anthropic\n let mut anthropic_messages = messages;\n anthropic_messages.push(Message {\n role: Role::Assistant,\n content: format!(\"\\n{}\\n\", complete_reasoning),\n });\n\n // Stream from Anthropic\n let mut anthropic_stream = anthropic_client.chat_stream(\n anthropic_messages,\n request_clone.get_system_prompt().map(String::from),\n &request_clone.anthropic_config,\n );\n\n while let Some(chunk) = anthropic_stream.next().await {\n match chunk {\n Ok(event) => match event {\n crate::clients::anthropic::StreamEvent::MessageStart { message } => {\n // Only send content event if there's actual content to send\n if !message.content.is_empty() {\n let _ = tx\n .send(Ok(Event::default().event(\"content\").data(\n serde_json::to_string(&StreamEvent::Content { \n content: message.content.into_iter()\n .map(ContentBlock::from_anthropic)\n .collect()\n })\n .unwrap_or_default(),\n )))\n .await;\n }\n }\n crate::clients::anthropic::StreamEvent::ContentBlockDelta { delta, .. } => {\n // Send content update\n let _ = tx\n .send(Ok(Event::default().event(\"content\").data(\n serde_json::to_string(&StreamEvent::Content {\n content: vec![ContentBlock {\n content_type: delta.delta_type,\n text: delta.text,\n }],\n })\n .unwrap_or_default(),\n )))\n .await;\n }\n crate::clients::anthropic::StreamEvent::MessageDelta { usage, .. } => {\n // Send final usage stats if available\n if let Some(usage) = usage {\n let anthropic_usage = AnthropicUsage::from_anthropic(usage);\n let anthropic_cost = calculate_anthropic_cost(\n \"claude-3-5-sonnet-20241022\", // Default model\n anthropic_usage.input_tokens,\n anthropic_usage.output_tokens,\n anthropic_usage.cached_write_tokens,\n anthropic_usage.cached_read_tokens,\n &config,\n );\n\n // Calculate DeepSeek costs if usage is available\n let (deepseek_usage, deepseek_cost) = if let Some(usage) = deepseek_usage.as_ref() {\n let cost = calculate_deepseek_cost(\n usage.prompt_tokens,\n usage.completion_tokens,\n usage.completion_tokens_details.reasoning_tokens,\n usage.prompt_tokens_details.cached_tokens,\n &config,\n );\n \n (DeepSeekUsage {\n input_tokens: usage.prompt_tokens,\n output_tokens: usage.completion_tokens,\n reasoning_tokens: usage.completion_tokens_details.reasoning_tokens,\n cached_input_tokens: usage.prompt_tokens_details.cached_tokens,\n total_tokens: usage.total_tokens,\n total_cost: format_cost(cost),\n }, cost)\n } else {\n (DeepSeekUsage {\n input_tokens: 0,\n output_tokens: 0,\n reasoning_tokens: 0,\n cached_input_tokens: 0,\n total_tokens: 0,\n total_cost: \"$0.00\".to_string(),\n }, 0.0)\n };\n\n let _ = tx\n .send(Ok(Event::default().event(\"usage\").data(\n serde_json::to_string(&StreamEvent::Usage {\n usage: CombinedUsage {\n total_cost: format_cost(deepseek_cost + anthropic_cost),\n deepseek_usage,\n anthropic_usage: AnthropicUsage {\n input_tokens: anthropic_usage.input_tokens,\n output_tokens: anthropic_usage.output_tokens,\n cached_write_tokens: anthropic_usage.cached_write_tokens,\n cached_read_tokens: anthropic_usage.cached_read_tokens,\n total_tokens: anthropic_usage.total_tokens,\n total_cost: format_cost(anthropic_cost),\n },\n },\n })\n .unwrap_or_default(),\n )))\n .await;\n }\n }\n _ => {} // Handle other events if needed\n },\n Err(e) => {\n let _ = tx\n .send(Ok(Event::default().event(\"error\").data(\n serde_json::to_string(&StreamEvent::Error {\n message: e.to_string(),\n code: 500,\n })\n .unwrap_or_default(),\n )))\n .await;\n return;\n }\n }\n }\n\n // Send done event\n let _ = tx\n .send(Ok(Event::default().event(\"done\").data(\n serde_json::to_string(&StreamEvent::Done)\n .unwrap_or_default(),\n )))\n .await;\n });\n\n // Convert receiver into stream\n let stream = ReceiverStream::new(rx);\n Ok(SseResponse::new(stream))\n}\n"], ["/deepclaude/src/error.rs", "//! Error handling types and implementations for the application.\n//!\n//! This module provides a comprehensive error handling system including:\n//! - Custom error types for various failure scenarios\n//! - Conversion implementations for common error types\n//! - Response formatting for API errors\n//! - Type aliases for common Result types\n\nuse axum::{\n http::StatusCode,\n response::{IntoResponse, Response, sse::Event},\n Json,\n};\nuse serde::{Deserialize, Serialize};\nuse std::convert::Infallible;\nuse thiserror::Error;\nuse tokio_stream::wrappers::ReceiverStream;\n\n/// Response structure for API errors.\n///\n/// This structure provides a consistent format for error responses\n/// returned by the API endpoints.\n#[derive(Debug, Serialize, Deserialize)]\npub struct ErrorResponse {\n pub error: ErrorDetails,\n}\n\n/// Detailed error information included in error responses.\n///\n/// Contains specific information about what went wrong, including:\n/// - A human-readable error message\n/// - The type of error that occurred\n/// - Optional parameter that caused the error\n/// - Optional error code for more specific error handling\n#[derive(Debug, Serialize, Deserialize)]\npub struct ErrorDetails {\n pub message: String,\n #[serde(rename = \"type\")]\n pub type_: String,\n #[serde(skip_serializing_if = \"Option::is_none\")]\n pub param: Option,\n #[serde(skip_serializing_if = \"Option::is_none\")]\n pub code: Option,\n}\n\n/// Enumeration of all possible API errors.\n///\n/// This enum represents all the different types of errors that can occur\n/// during API operations, including validation errors, external API errors,\n/// and internal server errors.\n#[derive(Error, Debug, Clone)]\npub enum ApiError {\n #[error(\"Invalid request: {message}\")]\n BadRequest {\n message: String,\n },\n\n #[error(\"Missing required header: {header}\")]\n MissingHeader {\n header: String,\n },\n\n #[error(\"Invalid system prompt configuration\")]\n InvalidSystemPrompt,\n\n #[error(\"DeepSeek API error: {message}\")]\n DeepSeekError {\n message: String,\n type_: String,\n param: Option,\n code: Option,\n },\n\n #[error(\"Anthropic API error: {message}\")]\n AnthropicError {\n message: String,\n type_: String,\n param: Option,\n code: Option,\n },\n\n #[error(\"Internal server error: {message}\")]\n Internal {\n message: String,\n },\n\n #[error(\"Other error: {message}\")]\n Other {\n message: String,\n },\n}\n\n/// Implements conversion of API errors into HTTP responses.\n///\n/// Maps each error variant to an appropriate HTTP status code and\n/// formats the error details into a consistent JSON response structure.\nimpl IntoResponse for ApiError {\n fn into_response(self) -> Response {\n let (status, error_response) = match &self {\n ApiError::BadRequest { message } => (\n StatusCode::BAD_REQUEST,\n ErrorResponse {\n error: ErrorDetails {\n message: message.clone(),\n type_: \"bad_request\".to_string(),\n param: None,\n code: None,\n },\n },\n ),\n ApiError::MissingHeader { header } => (\n StatusCode::BAD_REQUEST,\n ErrorResponse {\n error: ErrorDetails {\n message: format!(\"Missing required header: {}\", header),\n type_: \"missing_header\".to_string(),\n param: Some(header.clone()),\n code: None,\n },\n },\n ),\n ApiError::InvalidSystemPrompt => (\n StatusCode::BAD_REQUEST,\n ErrorResponse {\n error: ErrorDetails {\n message: \"System prompt can only be provided once, either in root or messages array\".to_string(),\n type_: \"invalid_system_prompt\".to_string(),\n param: None,\n code: None,\n },\n },\n ),\n ApiError::DeepSeekError { message, type_, param, code } => (\n StatusCode::BAD_REQUEST,\n ErrorResponse {\n error: ErrorDetails {\n message: format!(\"DeepSeek API Error: {}\", message),\n type_: format!(\"deepseek_{}\", type_),\n param: param.clone(),\n code: code.clone(),\n },\n },\n ),\n ApiError::AnthropicError { message, type_, param, code } => (\n StatusCode::BAD_REQUEST,\n ErrorResponse {\n error: ErrorDetails {\n message: format!(\"Anthropic API Error: {}\", message),\n type_: format!(\"anthropic_{}\", type_),\n param: param.clone(),\n code: code.clone(),\n },\n },\n ),\n ApiError::Internal { message } => (\n StatusCode::INTERNAL_SERVER_ERROR,\n ErrorResponse {\n error: ErrorDetails {\n message: message.clone(),\n type_: \"internal_error\".to_string(),\n param: None,\n code: None,\n },\n },\n ),\n ApiError::Other { message } => (\n StatusCode::INTERNAL_SERVER_ERROR,\n ErrorResponse {\n error: ErrorDetails {\n message: format!(\"Internal server error: {}\", message),\n type_: \"internal_error\".to_string(),\n param: None,\n code: None,\n },\n },\n ),\n };\n\n (status, Json(error_response)).into_response()\n }\n}\n\n/// Converts generic errors into API errors.\n///\n/// This implementation allows using the `?` operator with functions that\n/// return `anyhow::Error`, converting them into our custom `ApiError` type.\nimpl From for ApiError {\n fn from(err: anyhow::Error) -> Self {\n ApiError::Other { \n message: err.to_string() \n }\n }\n}\n\n/// Type alias for Results using our custom ApiError type.\n///\n/// This provides a convenient way to use Result with our ApiError\n/// throughout the application.\npub type Result = std::result::Result;\n\n/// Type alias for Server-Sent Events (SSE) results.\n///\n/// Used for streaming responses where errors are converted to Infallible\n/// since they are handled within the stream.\npub type SseResult = std::result::Result;\n\n/// Type alias for SSE streams.\n///\n/// Represents a stream of SSE results that can be sent to clients.\npub type SseStream = ReceiverStream;\n\n/// Type alias for SSE responses.\n///\n/// Represents the complete SSE response type used by the API endpoints.\npub type SseResponse = axum::response::sse::Sse;\n"], ["/deepclaude/src/config.rs", "//! Configuration management for the application.\n//!\n//! This module handles loading and managing configuration settings from files\n//! and environment variables. It includes pricing configurations for different\n//! AI model providers and server settings.\n\nuse serde::{Deserialize, Serialize};\nuse std::path::Path;\n\n/// Root configuration structure containing all application settings.\n///\n/// This structure is typically loaded from a TOML configuration file\n/// and provides access to all configurable aspects of the application.\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct Config {\n pub server: ServerConfig,\n pub pricing: PricingConfig,\n}\n\n/// Server-specific configuration settings.\n///\n/// Contains settings related to the HTTP server, such as the\n/// host address and port number to bind to.\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct ServerConfig {\n pub host: String,\n pub port: u16,\n}\n\n/// Pricing configuration for all supported AI models.\n///\n/// Contains pricing information for different AI model providers\n/// and their various models, used for usage cost calculation.\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct PricingConfig {\n pub deepseek: DeepSeekPricing,\n pub anthropic: AnthropicPricing,\n}\n\n/// DeepSeek-specific pricing configuration.\n///\n/// Contains pricing rates for different aspects of DeepSeek API usage,\n/// including cached and non-cached requests.\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct DeepSeekPricing {\n pub input_cache_hit_price: f64, // per million tokens\n pub input_cache_miss_price: f64, // per million tokens\n pub output_price: f64, // per million tokens\n}\n\n/// Anthropic-specific pricing configuration.\n///\n/// Contains pricing information for different Claude model variants\n/// and their associated costs.\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct AnthropicPricing {\n pub claude_3_sonnet: ModelPricing,\n pub claude_3_haiku: ModelPricing,\n pub claude_3_opus: ModelPricing,\n}\n\n/// Generic model pricing configuration.\n///\n/// Contains detailed pricing information for a specific model,\n/// including input, output, and caching costs.\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct ModelPricing {\n pub input_price: f64, // per million tokens\n pub output_price: f64, // per million tokens\n pub cache_write_price: f64, // per million tokens\n pub cache_read_price: f64, // per million tokens\n}\n\nimpl Config {\n /// Loads configuration from the default config file.\n ///\n /// Attempts to load and parse the configuration from 'config.toml'.\n /// Falls back to default values if the file cannot be loaded or parsed.\n ///\n /// # Returns\n ///\n /// * `anyhow::Result` - The loaded configuration or an error if loading fails\n ///\n /// # Errors\n ///\n /// Returns an error if:\n /// - The config file cannot be read\n /// - The TOML content cannot be parsed\n /// - The parsed content doesn't match the expected structure\n pub fn load() -> anyhow::Result {\n let config_path = Path::new(\"config.toml\");\n let config = config::Config::builder()\n .add_source(config::File::from(config_path))\n .build()?;\n\n Ok(config.try_deserialize()?)\n }\n}\n\n/// Provides default configuration values.\n///\n/// These defaults are used when a configuration file is not present\n/// or when specific values are not provided in the config file.\nimpl Default for Config {\n fn default() -> Self {\n Self {\n server: ServerConfig {\n host: \"127.0.0.1\".to_string(),\n port: 3000,\n },\n pricing: PricingConfig {\n deepseek: DeepSeekPricing {\n input_cache_hit_price: 0.14,\n input_cache_miss_price: 0.55,\n output_price: 2.19,\n },\n anthropic: AnthropicPricing {\n claude_3_sonnet: ModelPricing {\n input_price: 3.0,\n output_price: 15.0,\n cache_write_price: 3.75,\n cache_read_price: 0.30,\n },\n claude_3_haiku: ModelPricing {\n input_price: 0.80,\n output_price: 4.0,\n cache_write_price: 1.0,\n cache_read_price: 0.08,\n },\n claude_3_opus: ModelPricing {\n input_price: 15.0,\n output_price: 75.0,\n cache_write_price: 18.75,\n cache_read_price: 1.50,\n },\n },\n },\n }\n }\n}\n"], ["/deepclaude/src/clients/mod.rs", "//! Client implementations for external AI model providers.\n//!\n//! This module contains client implementations for different AI model providers:\n//! - `anthropic`: Client for Anthropic's Claude models\n//! - `deepseek`: Client for DeepSeek's reasoning models\n//!\n//! Each client handles authentication, request building, and response parsing\n//! specific to its provider's API.\n\npub mod anthropic;\npub mod deepseek;\n\npub use anthropic::AnthropicClient;\npub use deepseek::DeepSeekClient;\n\nuse crate::error::Result;\nuse reqwest::header::{HeaderMap, HeaderName, HeaderValue};\nuse std::collections::HashMap;\n\n/// Converts a HashMap of string headers to a reqwest HeaderMap.\n///\n/// This function is used internally by clients to convert user-provided\n/// header maps into the format required by reqwest.\n///\n/// # Arguments\n///\n/// * `headers` - A HashMap containing header names and values as strings\n///\n/// # Returns\n///\n/// * `Result` - The converted HeaderMap on success, or an error if\n/// any header name or value is invalid\n///\n/// # Errors\n///\n/// Returns `ApiError::BadRequest` if:\n/// - A header name contains invalid characters\n/// - A header value contains invalid characters\npub(crate) fn build_headers(headers: &HashMap) -> Result {\n let mut header_map = HeaderMap::new();\n \n for (key, value) in headers {\n let header_name = HeaderName::from_bytes(key.as_bytes())\n .map_err(|e| crate::error::ApiError::BadRequest { \n message: format!(\"Invalid header name: {}\", e) \n })?;\n \n let header_value = HeaderValue::from_str(value)\n .map_err(|e| crate::error::ApiError::BadRequest { \n message: format!(\"Invalid header value: {}\", e) \n })?;\n \n header_map.insert(header_name, header_value);\n }\n \n Ok(header_map)\n}\n"], ["/deepclaude/src/main.rs", "//! DeepClaude - A high-performance LLM inference API and Chat UI that integrates DeepSeek R1's CoT reasoning traces with Anthropic Claude models..\n//!\n//! This application provides a REST API for chat interactions that:\n//! - Processes messages through DeepSeek R1 for reasoning\n//! - Uses Anthropic's Claude for final responses\n//! - Supports both streaming and non-streaming responses\n//! - Tracks token usage and costs\n//! - Provides detailed usage statistics\n//!\n//! The API requires authentication tokens for both services and\n//! supports custom configuration through a TOML config file.\n\nmod clients;\nmod config;\nmod error;\nmod handlers;\nmod models;\n\nuse crate::{config::Config, handlers::AppState};\nuse axum::routing::{post, Router};\nuse std::{net::SocketAddr, sync::Arc};\nuse tower_http::{\n cors::{Any, CorsLayer},\n trace::TraceLayer,\n};\nuse tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};\n\n/// Application entry point.\n///\n/// Sets up logging, loads configuration, and starts the HTTP server\n/// with the configured routes and middleware.\n///\n/// # Returns\n///\n/// * `anyhow::Result<()>` - Ok if server starts successfully, Err otherwise\n///\n/// # Errors\n///\n/// Returns an error if:\n/// - Logging setup fails\n/// - Server address binding fails\n/// - Server encounters a fatal error while running\n#[tokio::main]\nasync fn main() -> anyhow::Result<()> {\n // Initialize logging\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env()\n .unwrap_or_else(|_| \"deepclaude=debug,tower_http=debug\".into()),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n // Load configuration\n let config = Config::load().unwrap_or_else(|_| {\n tracing::warn!(\"Failed to load config.toml, using default configuration\");\n Config::default()\n });\n\n // Create application state\n // Clone config for AppState\n let config_clone = config.clone();\n let state = Arc::new(AppState { config: config_clone });\n\n // Set up CORS\n let cors = CorsLayer::new()\n .allow_methods(Any)\n .allow_headers(Any)\n .allow_origin(Any);\n\n // Build router\n let app = Router::new()\n .route(\"/\", post(handlers::handle_chat))\n .layer(TraceLayer::new_for_http())\n .layer(cors)\n .with_state(state);\n\n // Get host and port from config\n let addr: SocketAddr = format!(\"{}:{}\", config.server.host, config.server.port)\n .parse()\n .expect(\"Invalid host/port configuration\");\n\n tracing::info!(\"Starting server on {}\", addr);\n\n // Start server\n axum::serve(\n tokio::net::TcpListener::bind(&addr).await?,\n app.into_make_service(),\n )\n .await?;\n\n Ok(())\n}\n"], ["/deepclaude/src/models/mod.rs", "pub mod request;\npub mod response;\n\npub use request::*;\npub use response::*;\n"]], "task_instance_info": {"created_time": "2025-08-21 01:33:31", "created_task_model": "DeepSeek-R1", "function_skeleton": "pub fn get_messages_with_system (&self) -> Vec {}", "code_description": "This code segment functions to: Consolidate and structure conversation messages by prioritizing the system prompt at the beginning while excluding duplicate system role entries from subsequent messages."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```rust\n[TASK_BEGIN]\n pub fn get_messages_with_system(&self) -> Vec {\n if let Some(system_content) = &self.system {\n // Prepend system prompt from root configuration\n let mut messages = vec![Message {\n role: Role::System,\n content: system_content.clone(),\n }];\n messages.extend(self.messages.clone());\n messages\n } else {\n // Find first system message if exists in messages\n let system_message = self.messages.iter().find(|msg| msg.role == Role::System);\n \n match system_message {\n Some(sys_msg) => {\n // Prepend system message and filter out other system messages\n let mut messages = vec![sys_msg.clone()];\n messages.extend(\n self.messages\n .iter()\n .filter(|msg| msg.role != Role::System)\n .cloned()\n );\n messages\n }\n None => self.messages.clone(),\n }\n }\n }\n[TASK_END]\n```", "inference_time": "2025-08-21 01-34-55"}, "editdistance_info": {"edit_distance": 32.2785, "calculate_time": "2025-08-21 01:34:55", "true_code_clean": "pub fn get_messages_with_system(&self) -> Vec {\n let mut messages = Vec::new();\n if let Some(system) = &self.system {\n messages.push(Message {\n role: Role::System,\n content: system.clone(),\n });\n }\n messages.extend(self.messages.iter().filter(|msg| !matches!(msg.role, Role::System)).cloned());\n messages\n }", "predict_code_clean": "pub fn get_messages_with_system(&self) -> Vec {\n if let Some(system_content) = &self.system {\n let mut messages = vec![Message {\n role: Role::System,\n content: system_content.clone(),\n }];\n messages.extend(self.messages.clone());\n messages\n } else {\n let system_message = self.messages.iter().find(|msg| msg.role == Role::System);\n match system_message {\n Some(sys_msg) => {\n let mut messages = vec![sys_msg.clone()];\n messages.extend(\n self.messages\n .iter()\n .filter(|msg| msg.role != Role::System)\n .cloned()\n );\n messages\n }\n None => self.messages.clone(),\n }\n }\n }"}} {"repo_name": "deepclaude", "file_name": "/deepclaude/src/handlers.rs", "inference_info": {"prefix_code": "//! Request handlers for the API endpoints.\n//!\n//! This module contains the main request handlers and supporting functions\n//! for processing chat requests, including both streaming and non-streaming\n//! responses. It coordinates between different AI models and handles\n//! usage tracking and cost calculations.\n\nuse crate::{\n clients::{AnthropicClient, DeepSeekClient},\n config::Config,\n error::{ApiError, Result, SseResponse},\n models::{\n ApiRequest, ApiResponse, ContentBlock, CombinedUsage, DeepSeekUsage, AnthropicUsage,\n ExternalApiResponse, Message, Role, StreamEvent,\n },\n};\nuse axum::{\n extract::State,\n response::{sse::Event, IntoResponse},\n Json,\n};\nuse chrono::Utc;\nuse futures::StreamExt;\nuse std::{sync::Arc, collections::HashMap};\nuse tokio_stream::wrappers::ReceiverStream;\n\n/// Application state shared across request handlers.\n///\n/// Contains configuration that needs to be accessible\n/// to all request handlers.\npub struct AppState {\n pub config: Config,\n}\n\n/// Extracts API tokens from request headers.\n///\n/// # Arguments\n///\n/// * `headers` - The HTTP headers containing the API tokens\n///\n/// # Returns\n///\n/// * `Result<(String, String)>` - A tuple of (DeepSeek token, Anthropic token)\n///\n/// # Errors\n///\n/// Returns `ApiError::MissingHeader` if either token is missing\n/// Returns `ApiError::BadRequest` if tokens are malformed\nfn extract_api_tokens(\n headers: &axum::http::HeaderMap,\n) -> Result<(String, String)> {\n let deepseek_token = headers\n .get(\"X-DeepSeek-API-Token\")\n .ok_or_else(|| ApiError::MissingHeader { \n header: \"X-DeepSeek-API-Token\".to_string() \n })?\n .to_str()\n .map_err(|_| ApiError::BadRequest { \n message: \"Invalid DeepSeek API token\".to_string() \n })?\n .to_string();\n\n let anthropic_token = headers\n .get(\"X-Anthropic-API-Token\")\n .ok_or_else(|| ApiError::MissingHeader { \n header: \"X-Anthropic-API-Token\".to_string() \n })?\n .to_str()\n .map_err(|_| ApiError::BadRequest { \n message: \"Invalid Anthropic API token\".to_string() \n })?\n .to_string();\n\n Ok((deepseek_token, anthropic_token))\n}\n\n/// Calculates the cost of DeepSeek API usage.\n///\n/// # Arguments\n///\n/// * `input_tokens` - Number of input tokens processed\n/// * `output_tokens` - Number of output tokens generated\n/// * `_reasoning_tokens` - Number of tokens used for reasoning\n/// * `cached_tokens` - Number of tokens retrieved from cache\n/// * `config` - Configuration containing pricing information\n///\n/// # Returns\n///\n/// The total cost in dollars for the API usage\nfn calculate_deepseek_cost(\n input_tokens: u32,\n output_tokens: u32,\n _reasoning_tokens: u32,\n cached_tokens: u32,\n config: &Config,\n) -> f64 {\n let cache_hit_cost = (cached_tokens as f64 / 1_000_000.0) * config.pricing.deepseek.input_cache_hit_price;\n let cache_miss_cost = ((input_tokens - cached_tokens) as f64 / 1_000_000.0) * config.pricing.deepseek.input_cache_miss_price;\n let output_cost = (output_tokens as f64 / 1_000_000.0) * config.pricing.deepseek.output_price;\n \n cache_hit_cost + cache_miss_cost + output_cost\n}\n\n/// Calculates the cost of Anthropic API usage.\n///\n/// # Arguments\n///\n/// * `model` - The specific Claude model used\n/// * `input_tokens` - Number of input tokens processed\n/// * `output_tokens` - Number of output tokens generated\n/// * `cache_write_tokens` - Number of tokens written to cache\n/// * `cache_read_tokens` - Number of tokens read from cache\n/// * `config` - Configuration containing pricing information\n///\n/// # Returns\n///\n/// The total cost in dollars for the API usage\nfn calculate_anthropic_cost(\n model: &str,\n input_tokens: u32,\n output_tokens: u32,\n cache_write_tokens: u32,\n cache_read_tokens: u32,\n config: &Config,\n) -> f64 {\n let pricing = if model.contains(\"claude-3-5-sonnet\") {\n &config.pricing.anthropic.claude_3_sonnet\n } else if model.contains(\"claude-3-5-haiku\") {\n &config.pricing.anthropic.claude_3_haiku\n } else if model.contains(\"claude-3-opus\") {\n &config.pricing.anthropic.claude_3_opus\n } else {\n &config.pricing.anthropic.claude_3_sonnet // default to sonnet pricing\n };\n\n let input_cost = (input_tokens as f64 / 1_000_000.0) * pricing.input_price;\n let output_cost = (output_tokens as f64 / 1_000_000.0) * pricing.output_price;\n let cache_write_cost = (cache_write_tokens as f64 / 1_000_000.0) * pricing.cache_write_price;\n let cache_read_cost = (cache_read_tokens as f64 / 1_000_000.0) * pricing.cache_read_price;\n\n input_cost + output_cost + cache_write_cost + cache_read_cost\n}\n\n/// Formats a cost value as a dollar amount string.\n///\n/// # Arguments\n///\n/// * `cost` - The cost value to format\n///\n/// # Returns\n///\n/// A string representing the cost with 3 decimal places and $ prefix\nfn format_cost(cost: f64) -> String {\n format!(\"${:.3}\", cost)\n}\n\n/// Main handler for chat requests.\n///\n/// Routes requests to either streaming or non-streaming handlers\n/// based on the request configuration.\n///\n/// # Arguments\n///\n/// * `state` - Application state containing configuration\n/// * `headers` - HTTP request headers\n/// * `request` - The parsed chat request\n///\n/// # Returns\n///\n/// * `Result` - The API response or an error\npub async fn handle_chat(\n state: State>,\n headers: axum::http::HeaderMap,\n Json(request): Json,\n) -> Result {\n if request.stream {\n let stream_response = chat_stream(state, headers, Json(request)).await?;\n Ok(stream_response.into_response())\n } else {\n let json_response = chat(state, headers, Json(request)).await?;\n Ok(json_response.into_response())\n }\n}\n\n/// Handler for non-streaming chat requests.\n///\n/// Processes the request through both AI models sequentially,\n/// combining their responses and tracking usage.\n///\n/// # Arguments\n///\n/// * `state` - Application state containing configuration\n/// * `headers` - HTTP request headers\n/// * `request` - The parsed chat request\n///\n/// # Returns\n///\n/// * `Result>` - The combined API response or an error\npub(crate) async fn chat(\n State(state): State>,\n headers: axum::http::HeaderMap,\n Json(request): Json,\n) -> Result> {\n // Validate system prompt\n if !request.validate_system_prompt() {\n return Err(ApiError::InvalidSystemPrompt);\n }\n\n // Extract API tokens\n let (deepseek_token, anthropic_token) = extract_api_tokens(&headers)?;\n\n // Initialize clients\n let deepseek_client = DeepSeekClient::new(deepseek_token);\n let anthropic_client = AnthropicClient::new(anthropic_token);\n\n // Get messages with system prompt\n let messages = request.get_messages_with_system();\n\n // Call DeepSeek API\n let deepseek_response = deepseek_client.chat(messages.clone(), &request.deepseek_config).await?;\n \n // Store response metadata\n let deepseek_status: u16 = 200;\n let deepseek_headers = HashMap::new(); // Headers not available when using high-level chat method\n\n // Extract reasoning content and wrap in thinking tags\n let reasoning_content = deepseek_response\n .choices\n .first()\n .and_then(|c| c.message.reasoning_content.as_ref())\n .ok_or_else(|| ApiError::DeepSeekError { \n message: \"No reasoning content in response\".to_string(),\n type_: \"missing_content\".to_string(),\n param: None,\n code: None\n })?;\n\n let thinking_content = format!(\"\\n{}\\n\", reasoning_content);\n\n // Add thinking content to messages for Anthropic\n let mut anthropic_messages = messages;\n anthropic_messages.push(Message {\n role: Role::Assistant,\n content: thinking_content.clone(),\n });\n\n // Call Anthropic API\n let anthropic_response = anthropic_client.chat(\n anthropic_messages,\n request.get_system_prompt().map(String::from),\n &request.anthropic_config\n ).await?;\n \n // Store response metadata\n let anthropic_status: u16 = 200;\n let anthropic_headers = HashMap::new(); // Headers not available when using high-level chat method\n\n // Calculate usage costs\n let deepseek_cost = calculate_deepseek_cost(\n deepseek_response.usage.prompt_tokens,\n deepseek_response.usage.completion_tokens,\n deepseek_response.usage.completion_tokens_details.reasoning_tokens,\n deepseek_response.usage.prompt_tokens_details.cached_tokens,\n &state.config,\n );\n\n let anthropic_cost = calculate_anthropic_cost(\n &anthropic_response.model,\n anthropic_response.usage.input_tokens,\n anthropic_response.usage.output_tokens,\n anthropic_response.usage.cache_creation_input_tokens,\n anthropic_response.usage.cache_read_input_tokens,\n &state.config,\n );\n\n // Combine thinking content with Anthropic's response\n let mut content = Vec::new();\n \n // Add thinking block first\n content.push(ContentBlock::text(thinking_content));\n \n // Add Anthropic's response blocks\n content.extend(anthropic_response.content.clone().into_iter()\n .map(ContentBlock::from_anthropic));\n\n // Build response with captured headers\n let response = ApiResponse {\n created: Utc::now(),\n content,\n deepseek_response: request.verbose.then(|| ExternalApiResponse {\n status: deepseek_status,\n headers: deepseek_headers,\n body: serde_json::to_value(&deepseek_response).unwrap_or_default(),\n }),\n anthropic_response: request.verbose.then(|| ExternalApiResponse {\n status: anthropic_status,\n headers: anthropic_headers,\n body: serde_json::to_value(&anthropic_response).unwrap_or_default(),\n }),\n combined_usage: CombinedUsage {\n total_cost: format_cost(deepseek_cost + anthropic_cost),\n deepseek_usage: DeepSeekUsage {\n input_tokens: deepseek_response.usage.prompt_tokens,\n output_tokens: deepseek_response.usage.completion_tokens,\n reasoning_tokens: deepseek_response.usage.completion_tokens_details.reasoning_tokens,\n cached_input_tokens: deepseek_response.usage.prompt_tokens_details.cached_tokens,\n total_tokens: deepseek_response.usage.total_tokens,\n total_cost: format_cost(deepseek_cost),\n },\n anthropic_usage: AnthropicUsage {\n input_tokens: anthropic_response.usage.input_tokens,\n output_tokens: anthropic_response.usage.output_tokens,\n cached_write_tokens: anthropic_response.usage.cache_creation_input_tokens,\n cached_read_tokens: anthropic_response.usage.cache_read_input_tokens,\n total_tokens: anthropic_response.usage.input_tokens + anthropic_response.usage.output_tokens,\n total_cost: format_cost(anthropic_cost),\n },\n },\n };\n\n Ok(Json(response))\n}\n\n/// Handler for streaming chat requests.\n///\n/// Processes the request through both AI models sequentially,\n/// streaming their responses as Server-Sent Events.\n///\n/// # Arguments\n///\n/// * `state` - Application state containing configuration\n/// * `headers` - HTTP request headers\n/// * `request` - The parsed chat request\n///\n/// # Returns\n///\n/// * `Result` - A stream of Server-Sent Events or an error\n", "suffix_code": "\n", "middle_code": "pub(crate) async fn chat_stream(\n State(state): State>,\n headers: axum::http::HeaderMap,\n Json(request): Json,\n) -> Result {\n if !request.validate_system_prompt() {\n return Err(ApiError::InvalidSystemPrompt);\n }\n let (deepseek_token, anthropic_token) = extract_api_tokens(&headers)?;\n let deepseek_client = DeepSeekClient::new(deepseek_token);\n let anthropic_client = AnthropicClient::new(anthropic_token);\n let messages = request.get_messages_with_system();\n let (tx, rx) = tokio::sync::mpsc::channel(100);\n let tx = Arc::new(tx);\n let config = state.config.clone();\n let request_clone = request.clone();\n tokio::spawn(async move {\n let tx = tx.clone();\n let _ = tx\n .send(Ok(Event::default().event(\"start\").data(\n serde_json::to_string(&StreamEvent::Start {\n created: Utc::now(),\n })\n .unwrap_or_default(),\n )))\n .await;\n let _ = tx\n .send(Ok(Event::default().event(\"content\").data(\n serde_json::to_string(&StreamEvent::Content {\n content: vec![ContentBlock {\n content_type: \"text\".to_string(),\n text: \"\\n\".to_string(),\n }],\n })\n .unwrap_or_default(),\n )))\n .await;\n let mut deepseek_usage = None;\n let mut complete_reasoning = String::new();\n let mut deepseek_stream = deepseek_client.chat_stream(messages.clone(), &request_clone.deepseek_config);\n while let Some(chunk) = deepseek_stream.next().await {\n match chunk {\n Ok(response) => {\n if let Some(choice) = response.choices.first() {\n if choice.delta.reasoning_content.is_none() {\n break;\n }\n if let Some(reasoning) = &choice.delta.reasoning_content {\n if !reasoning.is_empty() {\n let _ = tx\n .send(Ok(Event::default().event(\"content\").data(\n serde_json::to_string(&StreamEvent::Content {\n content: vec![ContentBlock {\n content_type: \"text_delta\".to_string(),\n text: reasoning.to_string(),\n }],\n })\n .unwrap_or_default(),\n )))\n .await;\n complete_reasoning.push_str(reasoning);\n }\n }\n }\n if let Some(usage) = response.usage {\n deepseek_usage = Some(usage);\n }\n }\n Err(e) => {\n let _ = tx\n .send(Ok(Event::default().event(\"error\").data(\n serde_json::to_string(&StreamEvent::Error {\n message: e.to_string(),\n code: 500,\n })\n .unwrap_or_default(),\n )))\n .await;\n return;\n }\n }\n }\n let _ = tx\n .send(Ok(Event::default().event(\"content\").data(\n serde_json::to_string(&StreamEvent::Content {\n content: vec![ContentBlock {\n content_type: \"text\".to_string(),\n text: \"\\n\".to_string(),\n }],\n })\n .unwrap_or_default(),\n )))\n .await;\n let mut anthropic_messages = messages;\n anthropic_messages.push(Message {\n role: Role::Assistant,\n content: format!(\"\\n{}\\n\", complete_reasoning),\n });\n let mut anthropic_stream = anthropic_client.chat_stream(\n anthropic_messages,\n request_clone.get_system_prompt().map(String::from),\n &request_clone.anthropic_config,\n );\n while let Some(chunk) = anthropic_stream.next().await {\n match chunk {\n Ok(event) => match event {\n crate::clients::anthropic::StreamEvent::MessageStart { message } => {\n if !message.content.is_empty() {\n let _ = tx\n .send(Ok(Event::default().event(\"content\").data(\n serde_json::to_string(&StreamEvent::Content { \n content: message.content.into_iter()\n .map(ContentBlock::from_anthropic)\n .collect()\n })\n .unwrap_or_default(),\n )))\n .await;\n }\n }\n crate::clients::anthropic::StreamEvent::ContentBlockDelta { delta, .. } => {\n let _ = tx\n .send(Ok(Event::default().event(\"content\").data(\n serde_json::to_string(&StreamEvent::Content {\n content: vec![ContentBlock {\n content_type: delta.delta_type,\n text: delta.text,\n }],\n })\n .unwrap_or_default(),\n )))\n .await;\n }\n crate::clients::anthropic::StreamEvent::MessageDelta { usage, .. } => {\n if let Some(usage) = usage {\n let anthropic_usage = AnthropicUsage::from_anthropic(usage);\n let anthropic_cost = calculate_anthropic_cost(\n \"claude-3-5-sonnet-20241022\", \n anthropic_usage.input_tokens,\n anthropic_usage.output_tokens,\n anthropic_usage.cached_write_tokens,\n anthropic_usage.cached_read_tokens,\n &config,\n );\n let (deepseek_usage, deepseek_cost) = if let Some(usage) = deepseek_usage.as_ref() {\n let cost = calculate_deepseek_cost(\n usage.prompt_tokens,\n usage.completion_tokens,\n usage.completion_tokens_details.reasoning_tokens,\n usage.prompt_tokens_details.cached_tokens,\n &config,\n );\n (DeepSeekUsage {\n input_tokens: usage.prompt_tokens,\n output_tokens: usage.completion_tokens,\n reasoning_tokens: usage.completion_tokens_details.reasoning_tokens,\n cached_input_tokens: usage.prompt_tokens_details.cached_tokens,\n total_tokens: usage.total_tokens,\n total_cost: format_cost(cost),\n }, cost)\n } else {\n (DeepSeekUsage {\n input_tokens: 0,\n output_tokens: 0,\n reasoning_tokens: 0,\n cached_input_tokens: 0,\n total_tokens: 0,\n total_cost: \"$0.00\".to_string(),\n }, 0.0)\n };\n let _ = tx\n .send(Ok(Event::default().event(\"usage\").data(\n serde_json::to_string(&StreamEvent::Usage {\n usage: CombinedUsage {\n total_cost: format_cost(deepseek_cost + anthropic_cost),\n deepseek_usage,\n anthropic_usage: AnthropicUsage {\n input_tokens: anthropic_usage.input_tokens,\n output_tokens: anthropic_usage.output_tokens,\n cached_write_tokens: anthropic_usage.cached_write_tokens,\n cached_read_tokens: anthropic_usage.cached_read_tokens,\n total_tokens: anthropic_usage.total_tokens,\n total_cost: format_cost(anthropic_cost),\n },\n },\n })\n .unwrap_or_default(),\n )))\n .await;\n }\n }\n _ => {} \n },\n Err(e) => {\n let _ = tx\n .send(Ok(Event::default().event(\"error\").data(\n serde_json::to_string(&StreamEvent::Error {\n message: e.to_string(),\n code: 500,\n })\n .unwrap_or_default(),\n )))\n .await;\n return;\n }\n }\n }\n let _ = tx\n .send(Ok(Event::default().event(\"done\").data(\n serde_json::to_string(&StreamEvent::Done)\n .unwrap_or_default(),\n )))\n .await;\n });\n let stream = ReceiverStream::new(rx);\n Ok(SseResponse::new(stream))\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "rust", "sub_task_type": null}, "context_code": [["/deepclaude/src/clients/anthropic.rs", "//! Anthropic API client implementation for interacting with Claude models.\n//!\n//! This module provides a client implementation for communicating with Anthropic's API,\n//! specifically designed to work with Claude language models. It supports both streaming\n//! and non-streaming interactions, handling all aspects of API communication including:\n//!\n//! - Authentication and request signing\n//! - Message formatting and serialization\n//! - Response parsing and deserialization\n//! - Error handling and type conversion\n//! - Streaming response processing\n//!\n//! # Main Components\n//!\n//! - [`AnthropicClient`]: The main client struct for making API requests\n//! - [`AnthropicResponse`]: Represents the structured response from the API\n//! - [`StreamEvent`]: Represents different types of events in streaming responses\n//!\n//! # Example Usage\n//!\n//! ```no_run\n//! use deepclaude::clients::AnthropicClient;\n//! use deepclaude::models::{Message, ApiConfig};\n//!\n//! async fn example() -> Result<(), Box> {\n//! let client = AnthropicClient::new(\"your-api-key\".to_string());\n//! let messages = vec![/* your messages */];\n//! let config = ApiConfig::default();\n//!\n//! // Non-streaming request\n//! let response = client.chat(messages.clone(), None, &config).await?;\n//!\n//! // Streaming request\n//! let stream = client.chat_stream(messages, None, &config);\n//! Ok(())\n//! }\n//! ```\n\nuse crate::{\n error::{ApiError, Result},\n models::{ApiConfig, Message, Role},\n};\nuse futures::Stream;\nuse reqwest::{header::HeaderMap, Client};\nuse serde::{Deserialize, Serialize};\nuse std::{collections::HashMap, pin::Pin};\nuse futures::StreamExt;\nuse serde_json;\n\npub(crate) const ANTHROPIC_API_URL: &str = \"https://api.anthropic.com/v1/messages\";\nconst DEFAULT_MODEL: &str = \"claude-3-5-sonnet-20241022\";\n\n/// Client for interacting with Anthropic's Claude models.\n///\n/// This client handles authentication, request construction, and response parsing\n/// for both streaming and non-streaming interactions with Anthropic's API.\n///\n/// # Examples\n///\n/// ```no_run\n/// use deepclaude::clients::AnthropicClient;\n///\n/// let client = AnthropicClient::new(\"api_token\".to_string());\n/// ```\n#[derive(Debug)]\npub struct AnthropicClient {\n pub(crate) client: Client,\n api_token: String,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct AnthropicResponse {\n pub id: String,\n #[serde(rename = \"type\")]\n pub response_type: String,\n pub role: String,\n pub model: String,\n pub content: Vec,\n pub stop_reason: Option,\n pub stop_sequence: Option,\n pub usage: Usage,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct ContentBlock {\n #[serde(rename = \"type\")]\n pub content_type: String,\n pub text: String,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct Usage {\n pub input_tokens: u32,\n pub output_tokens: u32,\n pub cache_creation_input_tokens: u32,\n pub cache_read_input_tokens: u32,\n}\n\n#[derive(Debug, Serialize, Deserialize)]\npub(crate) struct AnthropicRequest {\n messages: Vec,\n stream: bool,\n #[serde(skip_serializing_if = \"Option::is_none\")]\n system: Option,\n #[serde(flatten)]\n additional_params: serde_json::Value,\n}\n\n#[derive(Debug, Serialize, Deserialize)]\npub(crate) struct AnthropicMessage {\n role: String,\n content: String,\n}\n\n// Event types for streaming responses\n#[derive(Debug, Deserialize)]\n#[serde(tag = \"type\")]\npub enum StreamEvent {\n #[serde(rename = \"message_start\")]\n MessageStart {\n message: AnthropicResponse,\n },\n #[serde(rename = \"content_block_start\")]\n #[allow(dead_code)]\n ContentBlockStart {\n index: usize,\n content_block: ContentBlock,\n },\n #[serde(rename = \"content_block_delta\")]\n #[allow(dead_code)]\n ContentBlockDelta {\n index: usize,\n delta: ContentDelta,\n },\n #[serde(rename = \"content_block_stop\")]\n #[allow(dead_code)]\n ContentBlockStop {\n index: usize,\n },\n #[serde(rename = \"message_delta\")]\n #[allow(dead_code)]\n MessageDelta {\n delta: MessageDelta,\n usage: Option,\n },\n #[serde(rename = \"message_stop\")]\n MessageStop,\n #[serde(rename = \"ping\")]\n Ping,\n}\n\n#[derive(Debug, Deserialize, Clone)]\npub struct ContentDelta {\n #[serde(rename = \"type\")]\n pub delta_type: String,\n pub text: String,\n}\n\n#[derive(Debug, Deserialize, Clone)]\n#[allow(dead_code)]\npub struct MessageDelta {\n pub stop_reason: Option,\n pub stop_sequence: Option,\n}\n\nimpl AnthropicClient {\n /// Creates a new Anthropic client instance.\n ///\n /// # Arguments\n ///\n /// * `api_token` - API token for authentication with Anthropic's API\n ///\n /// # Returns\n ///\n /// A new `AnthropicClient` instance configured with the provided API token\n pub fn new(api_token: String) -> Self {\n Self {\n client: Client::new(),\n api_token,\n }\n }\n\n /// Builds the HTTP headers required for Anthropic API requests.\n ///\n /// # Arguments\n ///\n /// * `custom_headers` - Optional additional headers to include in requests\n ///\n /// # Returns\n ///\n /// * `Result` - The constructed headers on success, or an error if header construction fails\n ///\n /// # Errors\n ///\n /// Returns `ApiError::Internal` if:\n /// - The API token is invalid\n /// - Content-Type or Anthropic-Version headers cannot be constructed\n pub(crate) fn build_headers(&self, custom_headers: Option<&HashMap>) -> Result {\n let mut headers = HeaderMap::new();\n headers.insert(\n \"x-api-key\",\n self.api_token\n .parse()\n .map_err(|e| ApiError::Internal { \n message: format!(\"Invalid API token: {}\", e) \n })?,\n );\n headers.insert(\n \"content-type\",\n \"application/json\"\n .parse()\n .map_err(|e| ApiError::Internal { \n message: format!(\"Invalid content type: {}\", e) \n })?,\n );\n headers.insert(\n \"anthropic-version\",\n \"2023-06-01\"\n .parse()\n .map_err(|e| ApiError::Internal { \n message: format!(\"Invalid anthropic version: {}\", e) \n })?,\n );\n\n if let Some(custom) = custom_headers {\n headers.extend(super::build_headers(custom)?);\n }\n\n Ok(headers)\n }\n\n /// Constructs a request object for the Anthropic API.\n ///\n /// # Arguments\n ///\n /// * `messages` - Vector of messages to send to the model\n /// * `system` - Optional system prompt to set context\n /// * `stream` - Whether to enable streaming mode\n /// * `config` - Configuration options for the request\n ///\n /// # Returns\n ///\n /// An `AnthropicRequest` object configured with the provided parameters and defaults\n pub(crate) fn build_request(\n &self,\n messages: Vec,\n system: Option,\n stream: bool,\n config: &ApiConfig,\n ) -> AnthropicRequest {\n let filtered_messages = messages\n .into_iter()\n .filter(|msg| msg.role != Role::System)\n .map(|msg| AnthropicMessage {\n role: match msg.role {\n Role::User => \"user\".to_string(),\n Role::Assistant => \"assistant\".to_string(),\n Role::System => unreachable!(),\n },\n content: msg.content,\n })\n .collect();\n\n // Create base request with required fields\n let default_model = serde_json::json!(DEFAULT_MODEL);\n let model_value = config.body.get(\"model\").unwrap_or(&default_model);\n \n let default_max_tokens = if let Some(model_str) = model_value.as_str() {\n if model_str.contains(\"claude-3-opus\") {\n 4096\n } else {\n 8192\n }\n } else {\n 8192\n };\n let default_max_tokens_json = serde_json::json!(default_max_tokens);\n\n let mut request_value = serde_json::json!({\n \"messages\": filtered_messages,\n \"stream\": stream,\n \"model\": model_value,\n \"max_tokens\": config.body.get(\"max_tokens\").unwrap_or(&default_max_tokens_json)\n });\n\n // Add system if present\n if let Some(ref sys) = system {\n if let serde_json::Value::Object(mut map) = request_value {\n map.insert(\"system\".to_string(), serde_json::json!(sys));\n request_value = serde_json::Value::Object(map);\n }\n }\n\n // Merge additional configuration from config.body while protecting critical fields\n if let serde_json::Value::Object(mut map) = request_value {\n if let serde_json::Value::Object(mut body) = serde_json::to_value(&config.body).unwrap_or_default() {\n // Remove protected fields from config body\n body.remove(\"stream\");\n body.remove(\"messages\");\n body.remove(\"system\");\n \n // Merge remaining fields from config.body\n for (key, value) in body {\n map.insert(key, value);\n }\n }\n request_value = serde_json::Value::Object(map);\n }\n\n // Convert the merged JSON value into our request structure\n serde_json::from_value(request_value).unwrap_or_else(|_| AnthropicRequest {\n messages: filtered_messages,\n stream,\n system,\n additional_params: config.body.clone(),\n })\n }\n\n /// Sends a non-streaming chat request to the Anthropic API.\n ///\n /// # Arguments\n ///\n /// * `messages` - Vector of messages for the conversation\n /// * `system` - Optional system prompt to set context\n /// * `config` - Configuration options for the request\n ///\n /// # Returns\n ///\n /// * `Result` - The model's response on success\n ///\n /// # Errors\n ///\n /// Returns `ApiError::AnthropicError` if:\n /// - The API request fails\n /// - The response status is not successful\n /// - The response cannot be parsed\n pub async fn chat(\n &self,\n messages: Vec,\n system: Option,\n config: &ApiConfig,\n ) -> Result {\n let headers = self.build_headers(Some(&config.headers))?;\n let request = self.build_request(messages, system, false, config);\n\n let response = self\n .client\n .post(ANTHROPIC_API_URL)\n .headers(headers)\n .json(&request)\n .send()\n .await\n .map_err(|e| ApiError::AnthropicError { \n message: format!(\"Request failed: {}\", e),\n type_: \"request_failed\".to_string(),\n param: None,\n code: None\n })?;\n\n if !response.status().is_success() {\n let error = response\n .text()\n .await\n .unwrap_or_else(|_| \"Unknown error\".to_string());\n return Err(ApiError::AnthropicError { \n message: error,\n type_: \"api_error\".to_string(),\n param: None,\n code: None\n });\n }\n\n response\n .json::()\n .await\n .map_err(|e| ApiError::AnthropicError { \n message: format!(\"Failed to parse response: {}\", e),\n type_: \"parse_error\".to_string(),\n param: None,\n code: None\n })\n }\n\n /// Sends a streaming chat request to the Anthropic API.\n ///\n /// Returns a stream that yields events from the model's response as they arrive.\n ///\n /// # Arguments\n ///\n /// * `messages` - Vector of messages for the conversation\n /// * `system` - Optional system prompt to set context\n /// * `config` - Configuration options for the request\n ///\n /// # Returns\n ///\n /// * `Pin> + Send>>` - A stream of response events\n ///\n /// # Errors\n ///\n /// The stream may yield `ApiError::AnthropicError` if:\n /// - The API request fails\n /// - Stream processing encounters an error\n /// - Response events cannot be parsed\n pub fn chat_stream(\n &self,\n messages: Vec,\n system: Option,\n config: &ApiConfig,\n ) -> Pin> + Send>> {\n let headers = match self.build_headers(Some(&config.headers)) {\n Ok(h) => h,\n Err(e) => return Box::pin(futures::stream::once(async move { Err(e) })),\n };\n\n let request = self.build_request(messages, system, true, config);\n let client = self.client.clone();\n\n Box::pin(async_stream::try_stream! {\n let mut stream = client\n .post(ANTHROPIC_API_URL)\n .headers(headers)\n .json(&request)\n .send()\n .await\n .map_err(|e| ApiError::AnthropicError { \n message: format!(\"Request failed: {}\", e),\n type_: \"request_failed\".to_string(),\n param: None,\n code: None\n })?\n .bytes_stream();\n\n let mut data = String::new();\n \n while let Some(chunk) = stream.next().await {\n let chunk = chunk.map_err(|e| ApiError::AnthropicError { \n message: format!(\"Stream error: {}\", e),\n type_: \"stream_error\".to_string(),\n param: None,\n code: None\n })?;\n data.push_str(&String::from_utf8_lossy(&chunk));\n\n let mut start = 0;\n while let Some(end) = data[start..].find(\"\\n\\n\") {\n let end = start + end;\n let event_data = &data[start..end];\n start = end + 2;\n\n if event_data.starts_with(\"event: \") {\n let _event_line = &event_data[\"event: \".len()..];\n if let Some(data_line) = event_data.lines().nth(1) {\n if data_line.starts_with(\"data: \") {\n let json_data = &data_line[\"data: \".len()..];\n if let Ok(event) = serde_json::from_str::(json_data) {\n yield event;\n }\n }\n }\n }\n }\n\n if start > 0 {\n data = data[start..].to_string();\n }\n }\n })\n }\n}\n\n/// Converts an Anthropic content block into the application's generic content block type.\nimpl From for crate::models::response::ContentBlock {\n fn from(block: ContentBlock) -> Self {\n Self {\n content_type: block.content_type,\n text: block.text,\n }\n }\n}\n"], ["/deepclaude/src/clients/deepseek.rs", "//! DeepSeek API client implementation for interacting with DeepSeek's AI models.\n//!\n//! This module provides a client implementation for making requests to DeepSeek's chat completion API.\n//! It supports both streaming and non-streaming interactions, handling authentication, request\n//! construction, and response parsing.\n//!\n//! # Features\n//!\n//! - Supports chat completions with DeepSeek's AI models\n//! - Handles both streaming and non-streaming responses\n//! - Configurable request parameters (model, max tokens, temperature)\n//! - Custom header support\n//! - Comprehensive error handling\n//!\n//! # Examples\n//!\n//! ```no_run\n//! use crate::{\n//! clients::DeepSeekClient,\n//! models::{ApiConfig, Message},\n//! };\n//!\n//! # async fn example() -> Result<(), Box> {\n//! // Initialize the client\n//! let client = DeepSeekClient::new(\"your-api-key\".to_string());\n//!\n//! // Prepare messages and configuration\n//! let messages = vec![Message {\n//! role: \"user\".to_string(),\n//! content: \"Hello, how are you?\".to_string(),\n//! }];\n//!\n//! let config = ApiConfig::default();\n//!\n//! // Make a non-streaming request\n//! let response = client.chat(messages.clone(), &config).await?;\n//!\n//! // Or use streaming for real-time responses\n//! let mut stream = client.chat_stream(messages, &config);\n//! while let Some(chunk) = stream.next().await {\n//! println!(\"Received chunk: {:?}\", chunk?);\n//! }\n//! # Ok(())\n//! # }\n//! ```\n//!\n//! # Error Handling\n//!\n//! The client uses a custom error type `ApiError` to handle various failure cases:\n//! - Network errors\n//! - API authentication errors\n//! - Invalid response formats\n//! - Stream processing errors\n//!\n//! All public methods return `Result` types with appropriate error variants.\n\nuse crate::{\n error::{ApiError, Result},\n models::{ApiConfig, Message},\n};\nuse futures::Stream;\nuse reqwest::{header::HeaderMap, Client};\nuse serde::{Deserialize, Serialize};\nuse std::{collections::HashMap, pin::Pin};\nuse futures::StreamExt;\nuse serde_json;\n\npub(crate) const DEEPSEEK_API_URL: &str = \"https://api.deepseek.com/chat/completions\";\nconst DEFAULT_MODEL: &str = \"deepseek-reasoner\";\n\n/// Client for interacting with DeepSeek's AI models.\n///\n/// This client handles authentication, request construction, and response parsing\n/// for both streaming and non-streaming interactions with DeepSeek's API.\n///\n/// # Examples\n///\n/// ```no_run\n/// use deepclaude::clients::DeepSeekClient;\n///\n/// let client = DeepSeekClient::new(\"api_token\".to_string());\n/// ```\n#[derive(Debug)]\npub struct DeepSeekClient {\n pub(crate) client: Client,\n api_token: String,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct DeepSeekResponse {\n pub id: String,\n pub object: String,\n pub created: i64,\n pub model: String,\n pub choices: Vec,\n pub usage: Usage,\n pub system_fingerprint: String,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct Choice {\n pub index: i32,\n pub message: AssistantMessage,\n pub logprobs: Option,\n pub finish_reason: Option,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct AssistantMessage {\n pub role: String,\n pub content: Option,\n pub reasoning_content: Option,\n}\n\n// Streaming response types\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct StreamChoice {\n pub index: i32,\n pub delta: StreamDelta,\n pub logprobs: Option,\n pub finish_reason: Option,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct StreamDelta {\n pub role: Option,\n pub content: Option,\n pub reasoning_content: Option,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct StreamResponse {\n pub id: String,\n pub object: String,\n pub created: i64,\n pub model: String,\n pub choices: Vec,\n pub usage: Option,\n pub system_fingerprint: String,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct Usage {\n pub prompt_tokens: u32,\n pub completion_tokens: u32,\n pub total_tokens: u32,\n pub prompt_tokens_details: PromptTokensDetails,\n pub completion_tokens_details: CompletionTokensDetails,\n pub prompt_cache_hit_tokens: u32,\n pub prompt_cache_miss_tokens: u32,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct PromptTokensDetails {\n pub cached_tokens: u32,\n}\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct CompletionTokensDetails {\n pub reasoning_tokens: u32,\n}\n\n#[derive(Debug, Serialize, Deserialize)]\npub(crate) struct DeepSeekRequest {\n messages: Vec,\n stream: bool,\n #[serde(flatten)]\n additional_params: serde_json::Value,\n}\n\nimpl DeepSeekClient {\n pub fn new(api_token: String) -> Self {\n Self {\n client: Client::new(),\n api_token,\n }\n }\n\n /// Builds the HTTP headers required for DeepSeek API requests.\n ///\n /// # Arguments\n ///\n /// * `custom_headers` - Optional additional headers to include in requests\n ///\n /// # Returns\n ///\n /// * `Result` - The constructed headers on success, or an error if header construction fails\n ///\n /// # Errors\n ///\n /// Returns `ApiError::Internal` if:\n /// - The API token is invalid\n /// - Content-Type or Accept headers cannot be constructed\n pub(crate) fn build_headers(&self, custom_headers: Option<&HashMap>) -> Result {\n let mut headers = HeaderMap::new();\n headers.insert(\n \"Authorization\",\n format!(\"Bearer {}\", self.api_token)\n .parse()\n .map_err(|e| ApiError::Internal { \n message: format!(\"Invalid API token: {}\", e) \n })?,\n );\n headers.insert(\n \"Content-Type\",\n \"application/json\"\n .parse()\n .map_err(|e| ApiError::Internal { \n message: format!(\"Invalid content type: {}\", e) \n })?,\n );\n headers.insert(\n \"Accept\",\n \"application/json\"\n .parse()\n .map_err(|e| ApiError::Internal { \n message: format!(\"Invalid accept header: {}\", e) \n })?,\n );\n\n if let Some(custom) = custom_headers {\n headers.extend(super::build_headers(custom)?);\n }\n\n Ok(headers)\n }\n\n /// Constructs a request object for the DeepSeek API.\n ///\n /// # Arguments\n ///\n /// * `messages` - Vector of messages to send to the model\n /// * `stream` - Whether to enable streaming mode\n /// * `config` - Configuration options for the request\n ///\n /// # Returns\n ///\n /// A `DeepSeekRequest` object configured with the provided parameters and defaults\n pub(crate) fn build_request(&self, messages: Vec, stream: bool, config: &ApiConfig) -> DeepSeekRequest {\n // Create a base request with required fields\n let mut request_value = serde_json::json!({\n \"messages\": messages,\n \"stream\": stream,\n // Set defaults only if not provided in config\n \"model\": config.body.get(\"model\").unwrap_or(&serde_json::json!(DEFAULT_MODEL)),\n \"max_tokens\": config.body.get(\"max_tokens\").unwrap_or(&serde_json::json!(8192)),\n \"temperature\": config.body.get(\"temperature\").unwrap_or(&serde_json::json!(1.0)),\n \"response_format\": {\n \"type\": \"text\"\n }\n });\n\n // Merge additional configuration from config.body while protecting critical fields\n if let serde_json::Value::Object(mut map) = request_value {\n if let serde_json::Value::Object(mut body) = serde_json::to_value(&config.body).unwrap_or_default() {\n // Remove protected fields from config body\n body.remove(\"stream\");\n body.remove(\"messages\");\n \n // Merge remaining fields from config.body\n for (key, value) in body {\n map.insert(key, value);\n }\n }\n request_value = serde_json::Value::Object(map);\n }\n\n // Convert the merged JSON value into our request structure\n serde_json::from_value(request_value).unwrap_or_else(|_| DeepSeekRequest {\n messages,\n stream,\n additional_params: config.body.clone(),\n })\n }\n\n /// Sends a non-streaming chat request to the DeepSeek API.\n ///\n /// # Arguments\n ///\n /// * `messages` - Vector of messages for the conversation\n /// * `config` - Configuration options for the request\n ///\n /// # Returns\n ///\n /// * `Result` - The model's response on success\n ///\n /// # Errors\n ///\n /// Returns `ApiError::DeepSeekError` if:\n /// - The API request fails\n /// - The response status is not successful\n /// - The response cannot be parsed\n pub async fn chat(\n &self,\n messages: Vec,\n config: &ApiConfig,\n ) -> Result {\n let headers = self.build_headers(Some(&config.headers))?;\n let request = self.build_request(messages, false, config);\n\n let response = self\n .client\n .post(DEEPSEEK_API_URL)\n .headers(headers)\n .json(&request)\n .send()\n .await\n .map_err(|e| ApiError::DeepSeekError { \n message: format!(\"Request failed: {}\", e),\n type_: \"request_failed\".to_string(),\n param: None,\n code: None\n })?;\n\n if !response.status().is_success() {\n let error = response\n .text()\n .await\n .unwrap_or_else(|_| \"Unknown error\".to_string());\n return Err(ApiError::DeepSeekError { \n message: error,\n type_: \"api_error\".to_string(),\n param: None,\n code: None\n });\n }\n\n response\n .json::()\n .await\n .map_err(|e| ApiError::DeepSeekError { \n message: format!(\"Failed to parse response: {}\", e),\n type_: \"parse_error\".to_string(),\n param: None,\n code: None\n })\n }\n\n /// Sends a streaming chat request to the DeepSeek API.\n ///\n /// Returns a stream that yields chunks of the model's response as they arrive.\n ///\n /// # Arguments\n ///\n /// * `messages` - Vector of messages for the conversation\n /// * `config` - Configuration options for the request\n ///\n /// # Returns\n ///\n /// * `Pin> + Send>>` - A stream of response chunks\n ///\n /// # Errors\n ///\n /// The stream may yield `ApiError::DeepSeekError` if:\n /// - The API request fails\n /// - Stream processing encounters an error\n /// - Response chunks cannot be parsed\n pub fn chat_stream(\n &self,\n messages: Vec,\n config: &ApiConfig,\n ) -> Pin> + Send>> {\n let headers = match self.build_headers(Some(&config.headers)) {\n Ok(h) => h,\n Err(e) => return Box::pin(futures::stream::once(async move { Err(e) })),\n };\n\n let request = self.build_request(messages, true, config);\n let client = self.client.clone();\n\n Box::pin(async_stream::try_stream! {\n let mut stream = client\n .post(DEEPSEEK_API_URL)\n .headers(headers)\n .json(&request)\n .send()\n .await\n .map_err(|e| ApiError::DeepSeekError { \n message: format!(\"Request failed: {}\", e),\n type_: \"request_failed\".to_string(),\n param: None,\n code: None\n })?\n .bytes_stream();\n\n let mut data = String::new();\n \n while let Some(chunk) = stream.next().await {\n let chunk = chunk.map_err(|e| ApiError::DeepSeekError { \n message: format!(\"Stream error: {}\", e),\n type_: \"stream_error\".to_string(),\n param: None,\n code: None\n })?;\n data.push_str(&String::from_utf8_lossy(&chunk));\n\n let mut start = 0;\n while let Some(end) = data[start..].find(\"\\n\\n\") {\n let end = start + end;\n let line = &data[start..end].trim();\n start = end + 2;\n \n if line.starts_with(\"data: \") {\n let json_data = &line[\"data: \".len()..];\n if let Ok(response) = serde_json::from_str::(json_data) {\n yield response;\n }\n }\n }\n\n if start > 0 {\n data = data[start..].to_string();\n }\n }\n })\n }\n}\n"], ["/deepclaude/src/models/response.rs", "//! Response models for the API endpoints.\n//!\n//! This module defines the structures used to represent API responses,\n//! including chat completions, usage statistics, and streaming events.\n\nuse chrono::{DateTime, Utc};\nuse serde::{Deserialize, Serialize};\nuse std::collections::HashMap;\n\n/// Primary response structure for chat API endpoints.\n///\n/// Contains the complete response from both AI models, including\n/// content blocks, usage statistics, and optional raw API responses.\n#[derive(Debug, Serialize, Clone)]\npub struct ApiResponse {\n pub created: DateTime,\n pub content: Vec,\n \n #[serde(skip_serializing_if = \"Option::is_none\")]\n pub deepseek_response: Option,\n \n #[serde(skip_serializing_if = \"Option::is_none\")]\n pub anthropic_response: Option,\n \n pub combined_usage: CombinedUsage,\n}\n\n/// A block of content in a response.\n///\n/// Represents a single piece of content in the response,\n/// with its type and actual text content.\n#[derive(Debug, Serialize, Deserialize, Clone)]\npub struct ContentBlock {\n #[serde(rename = \"type\")]\n pub content_type: String,\n pub text: String,\n}\n\n/// Raw response from an external API.\n///\n/// Contains the complete response details from an external API\n/// call, including status code, headers, and response body.\n#[derive(Debug, Serialize, Clone)]\npub struct ExternalApiResponse {\n pub status: u16,\n pub headers: HashMap,\n pub body: serde_json::Value,\n}\n\n/// Combined usage statistics from both AI models.\n///\n/// Aggregates token usage and cost information from both\n/// DeepSeek and Anthropic API calls.\n#[derive(Debug, Serialize, Clone)]\npub struct CombinedUsage {\n pub total_cost: String,\n pub deepseek_usage: DeepSeekUsage,\n pub anthropic_usage: AnthropicUsage,\n}\n\n/// Usage statistics for DeepSeek API calls.\n///\n/// Tracks token consumption and costs specific to\n/// DeepSeek model usage.\n#[derive(Debug, Serialize, Clone)]\npub struct DeepSeekUsage {\n pub input_tokens: u32,\n pub output_tokens: u32,\n pub reasoning_tokens: u32,\n pub cached_input_tokens: u32,\n pub total_tokens: u32,\n pub total_cost: String,\n}\n\n/// Usage statistics for Anthropic API calls.\n///\n/// Tracks token consumption and costs specific to\n/// Anthropic model usage.\n#[derive(Debug, Serialize, Clone)]\npub struct AnthropicUsage {\n pub input_tokens: u32,\n pub output_tokens: u32,\n pub cached_write_tokens: u32,\n pub cached_read_tokens: u32,\n pub total_tokens: u32,\n pub total_cost: String,\n}\n\n// Streaming event types\n/// Events emitted during streaming responses.\n///\n/// Represents different types of events that can occur\n/// during a streaming response, including content updates\n/// and usage statistics.\n#[derive(Debug, Serialize)]\n#[serde(tag = \"type\")]\npub enum StreamEvent {\n #[serde(rename = \"start\")]\n Start {\n created: DateTime,\n },\n \n #[serde(rename = \"content\")]\n Content {\n content: Vec,\n },\n \n #[serde(rename = \"usage\")]\n Usage {\n usage: CombinedUsage,\n },\n \n #[serde(rename = \"done\")]\n Done,\n \n #[serde(rename = \"error\")]\n Error {\n message: String,\n code: u16,\n },\n}\n\nimpl ContentBlock {\n /// Creates a new text content block.\n ///\n /// # Arguments\n ///\n /// * `text` - The text content to include in the block\n ///\n /// # Returns\n ///\n /// A new `ContentBlock` with the type set to \"text\"\n pub fn text(text: impl Into) -> Self {\n Self {\n content_type: \"text\".to_string(),\n text: text.into(),\n }\n }\n\n /// Converts an Anthropic content block to a generic content block.\n ///\n /// # Arguments\n ///\n /// * `block` - The Anthropic-specific content block to convert\n ///\n /// # Returns\n ///\n /// A new `ContentBlock` with the same content type and text\n pub fn from_anthropic(block: crate::clients::anthropic::ContentBlock) -> Self {\n Self {\n content_type: block.content_type,\n text: block.text,\n }\n }\n}\n\nimpl ApiResponse {\n /// Creates a new API response with simple text content.\n ///\n /// # Arguments\n ///\n /// * `content` - The text content for the response\n ///\n /// # Returns\n ///\n /// A new `ApiResponse` with default values and the provided content\n #[allow(dead_code)]\n pub fn new(content: impl Into) -> Self {\n Self {\n created: Utc::now(),\n content: vec![ContentBlock::text(content)],\n deepseek_response: None,\n anthropic_response: None,\n combined_usage: CombinedUsage {\n total_cost: \"$0.00\".to_string(),\n deepseek_usage: DeepSeekUsage {\n input_tokens: 0,\n output_tokens: 0,\n reasoning_tokens: 0,\n cached_input_tokens: 0,\n total_tokens: 0,\n total_cost: \"$0.00\".to_string(),\n },\n anthropic_usage: AnthropicUsage {\n input_tokens: 0,\n output_tokens: 0,\n cached_write_tokens: 0,\n cached_read_tokens: 0,\n total_tokens: 0,\n total_cost: \"$0.00\".to_string(),\n },\n },\n }\n }\n}\n\nimpl AnthropicUsage {\n /// Converts Anthropic usage statistics to the generic usage format.\n ///\n /// # Arguments\n ///\n /// * `usage` - The Anthropic-specific usage statistics to convert\n ///\n /// # Returns\n ///\n /// A new `AnthropicUsage` with values copied from the Anthropic usage\n pub fn from_anthropic(usage: crate::clients::anthropic::Usage) -> Self {\n Self {\n input_tokens: usage.input_tokens,\n output_tokens: usage.output_tokens,\n cached_write_tokens: usage.cache_creation_input_tokens,\n cached_read_tokens: usage.cache_read_input_tokens,\n total_tokens: usage.input_tokens + usage.output_tokens,\n total_cost: \"$0.00\".to_string(), // Cost will be calculated later\n }\n }\n}\n"], ["/deepclaude/src/config.rs", "//! Configuration management for the application.\n//!\n//! This module handles loading and managing configuration settings from files\n//! and environment variables. It includes pricing configurations for different\n//! AI model providers and server settings.\n\nuse serde::{Deserialize, Serialize};\nuse std::path::Path;\n\n/// Root configuration structure containing all application settings.\n///\n/// This structure is typically loaded from a TOML configuration file\n/// and provides access to all configurable aspects of the application.\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct Config {\n pub server: ServerConfig,\n pub pricing: PricingConfig,\n}\n\n/// Server-specific configuration settings.\n///\n/// Contains settings related to the HTTP server, such as the\n/// host address and port number to bind to.\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct ServerConfig {\n pub host: String,\n pub port: u16,\n}\n\n/// Pricing configuration for all supported AI models.\n///\n/// Contains pricing information for different AI model providers\n/// and their various models, used for usage cost calculation.\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct PricingConfig {\n pub deepseek: DeepSeekPricing,\n pub anthropic: AnthropicPricing,\n}\n\n/// DeepSeek-specific pricing configuration.\n///\n/// Contains pricing rates for different aspects of DeepSeek API usage,\n/// including cached and non-cached requests.\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct DeepSeekPricing {\n pub input_cache_hit_price: f64, // per million tokens\n pub input_cache_miss_price: f64, // per million tokens\n pub output_price: f64, // per million tokens\n}\n\n/// Anthropic-specific pricing configuration.\n///\n/// Contains pricing information for different Claude model variants\n/// and their associated costs.\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct AnthropicPricing {\n pub claude_3_sonnet: ModelPricing,\n pub claude_3_haiku: ModelPricing,\n pub claude_3_opus: ModelPricing,\n}\n\n/// Generic model pricing configuration.\n///\n/// Contains detailed pricing information for a specific model,\n/// including input, output, and caching costs.\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct ModelPricing {\n pub input_price: f64, // per million tokens\n pub output_price: f64, // per million tokens\n pub cache_write_price: f64, // per million tokens\n pub cache_read_price: f64, // per million tokens\n}\n\nimpl Config {\n /// Loads configuration from the default config file.\n ///\n /// Attempts to load and parse the configuration from 'config.toml'.\n /// Falls back to default values if the file cannot be loaded or parsed.\n ///\n /// # Returns\n ///\n /// * `anyhow::Result` - The loaded configuration or an error if loading fails\n ///\n /// # Errors\n ///\n /// Returns an error if:\n /// - The config file cannot be read\n /// - The TOML content cannot be parsed\n /// - The parsed content doesn't match the expected structure\n pub fn load() -> anyhow::Result {\n let config_path = Path::new(\"config.toml\");\n let config = config::Config::builder()\n .add_source(config::File::from(config_path))\n .build()?;\n\n Ok(config.try_deserialize()?)\n }\n}\n\n/// Provides default configuration values.\n///\n/// These defaults are used when a configuration file is not present\n/// or when specific values are not provided in the config file.\nimpl Default for Config {\n fn default() -> Self {\n Self {\n server: ServerConfig {\n host: \"127.0.0.1\".to_string(),\n port: 3000,\n },\n pricing: PricingConfig {\n deepseek: DeepSeekPricing {\n input_cache_hit_price: 0.14,\n input_cache_miss_price: 0.55,\n output_price: 2.19,\n },\n anthropic: AnthropicPricing {\n claude_3_sonnet: ModelPricing {\n input_price: 3.0,\n output_price: 15.0,\n cache_write_price: 3.75,\n cache_read_price: 0.30,\n },\n claude_3_haiku: ModelPricing {\n input_price: 0.80,\n output_price: 4.0,\n cache_write_price: 1.0,\n cache_read_price: 0.08,\n },\n claude_3_opus: ModelPricing {\n input_price: 15.0,\n output_price: 75.0,\n cache_write_price: 18.75,\n cache_read_price: 1.50,\n },\n },\n },\n }\n }\n}\n"], ["/deepclaude/src/error.rs", "//! Error handling types and implementations for the application.\n//!\n//! This module provides a comprehensive error handling system including:\n//! - Custom error types for various failure scenarios\n//! - Conversion implementations for common error types\n//! - Response formatting for API errors\n//! - Type aliases for common Result types\n\nuse axum::{\n http::StatusCode,\n response::{IntoResponse, Response, sse::Event},\n Json,\n};\nuse serde::{Deserialize, Serialize};\nuse std::convert::Infallible;\nuse thiserror::Error;\nuse tokio_stream::wrappers::ReceiverStream;\n\n/// Response structure for API errors.\n///\n/// This structure provides a consistent format for error responses\n/// returned by the API endpoints.\n#[derive(Debug, Serialize, Deserialize)]\npub struct ErrorResponse {\n pub error: ErrorDetails,\n}\n\n/// Detailed error information included in error responses.\n///\n/// Contains specific information about what went wrong, including:\n/// - A human-readable error message\n/// - The type of error that occurred\n/// - Optional parameter that caused the error\n/// - Optional error code for more specific error handling\n#[derive(Debug, Serialize, Deserialize)]\npub struct ErrorDetails {\n pub message: String,\n #[serde(rename = \"type\")]\n pub type_: String,\n #[serde(skip_serializing_if = \"Option::is_none\")]\n pub param: Option,\n #[serde(skip_serializing_if = \"Option::is_none\")]\n pub code: Option,\n}\n\n/// Enumeration of all possible API errors.\n///\n/// This enum represents all the different types of errors that can occur\n/// during API operations, including validation errors, external API errors,\n/// and internal server errors.\n#[derive(Error, Debug, Clone)]\npub enum ApiError {\n #[error(\"Invalid request: {message}\")]\n BadRequest {\n message: String,\n },\n\n #[error(\"Missing required header: {header}\")]\n MissingHeader {\n header: String,\n },\n\n #[error(\"Invalid system prompt configuration\")]\n InvalidSystemPrompt,\n\n #[error(\"DeepSeek API error: {message}\")]\n DeepSeekError {\n message: String,\n type_: String,\n param: Option,\n code: Option,\n },\n\n #[error(\"Anthropic API error: {message}\")]\n AnthropicError {\n message: String,\n type_: String,\n param: Option,\n code: Option,\n },\n\n #[error(\"Internal server error: {message}\")]\n Internal {\n message: String,\n },\n\n #[error(\"Other error: {message}\")]\n Other {\n message: String,\n },\n}\n\n/// Implements conversion of API errors into HTTP responses.\n///\n/// Maps each error variant to an appropriate HTTP status code and\n/// formats the error details into a consistent JSON response structure.\nimpl IntoResponse for ApiError {\n fn into_response(self) -> Response {\n let (status, error_response) = match &self {\n ApiError::BadRequest { message } => (\n StatusCode::BAD_REQUEST,\n ErrorResponse {\n error: ErrorDetails {\n message: message.clone(),\n type_: \"bad_request\".to_string(),\n param: None,\n code: None,\n },\n },\n ),\n ApiError::MissingHeader { header } => (\n StatusCode::BAD_REQUEST,\n ErrorResponse {\n error: ErrorDetails {\n message: format!(\"Missing required header: {}\", header),\n type_: \"missing_header\".to_string(),\n param: Some(header.clone()),\n code: None,\n },\n },\n ),\n ApiError::InvalidSystemPrompt => (\n StatusCode::BAD_REQUEST,\n ErrorResponse {\n error: ErrorDetails {\n message: \"System prompt can only be provided once, either in root or messages array\".to_string(),\n type_: \"invalid_system_prompt\".to_string(),\n param: None,\n code: None,\n },\n },\n ),\n ApiError::DeepSeekError { message, type_, param, code } => (\n StatusCode::BAD_REQUEST,\n ErrorResponse {\n error: ErrorDetails {\n message: format!(\"DeepSeek API Error: {}\", message),\n type_: format!(\"deepseek_{}\", type_),\n param: param.clone(),\n code: code.clone(),\n },\n },\n ),\n ApiError::AnthropicError { message, type_, param, code } => (\n StatusCode::BAD_REQUEST,\n ErrorResponse {\n error: ErrorDetails {\n message: format!(\"Anthropic API Error: {}\", message),\n type_: format!(\"anthropic_{}\", type_),\n param: param.clone(),\n code: code.clone(),\n },\n },\n ),\n ApiError::Internal { message } => (\n StatusCode::INTERNAL_SERVER_ERROR,\n ErrorResponse {\n error: ErrorDetails {\n message: message.clone(),\n type_: \"internal_error\".to_string(),\n param: None,\n code: None,\n },\n },\n ),\n ApiError::Other { message } => (\n StatusCode::INTERNAL_SERVER_ERROR,\n ErrorResponse {\n error: ErrorDetails {\n message: format!(\"Internal server error: {}\", message),\n type_: \"internal_error\".to_string(),\n param: None,\n code: None,\n },\n },\n ),\n };\n\n (status, Json(error_response)).into_response()\n }\n}\n\n/// Converts generic errors into API errors.\n///\n/// This implementation allows using the `?` operator with functions that\n/// return `anyhow::Error`, converting them into our custom `ApiError` type.\nimpl From for ApiError {\n fn from(err: anyhow::Error) -> Self {\n ApiError::Other { \n message: err.to_string() \n }\n }\n}\n\n/// Type alias for Results using our custom ApiError type.\n///\n/// This provides a convenient way to use Result with our ApiError\n/// throughout the application.\npub type Result = std::result::Result;\n\n/// Type alias for Server-Sent Events (SSE) results.\n///\n/// Used for streaming responses where errors are converted to Infallible\n/// since they are handled within the stream.\npub type SseResult = std::result::Result;\n\n/// Type alias for SSE streams.\n///\n/// Represents a stream of SSE results that can be sent to clients.\npub type SseStream = ReceiverStream;\n\n/// Type alias for SSE responses.\n///\n/// Represents the complete SSE response type used by the API endpoints.\npub type SseResponse = axum::response::sse::Sse;\n"], ["/deepclaude/src/main.rs", "//! DeepClaude - A high-performance LLM inference API and Chat UI that integrates DeepSeek R1's CoT reasoning traces with Anthropic Claude models..\n//!\n//! This application provides a REST API for chat interactions that:\n//! - Processes messages through DeepSeek R1 for reasoning\n//! - Uses Anthropic's Claude for final responses\n//! - Supports both streaming and non-streaming responses\n//! - Tracks token usage and costs\n//! - Provides detailed usage statistics\n//!\n//! The API requires authentication tokens for both services and\n//! supports custom configuration through a TOML config file.\n\nmod clients;\nmod config;\nmod error;\nmod handlers;\nmod models;\n\nuse crate::{config::Config, handlers::AppState};\nuse axum::routing::{post, Router};\nuse std::{net::SocketAddr, sync::Arc};\nuse tower_http::{\n cors::{Any, CorsLayer},\n trace::TraceLayer,\n};\nuse tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};\n\n/// Application entry point.\n///\n/// Sets up logging, loads configuration, and starts the HTTP server\n/// with the configured routes and middleware.\n///\n/// # Returns\n///\n/// * `anyhow::Result<()>` - Ok if server starts successfully, Err otherwise\n///\n/// # Errors\n///\n/// Returns an error if:\n/// - Logging setup fails\n/// - Server address binding fails\n/// - Server encounters a fatal error while running\n#[tokio::main]\nasync fn main() -> anyhow::Result<()> {\n // Initialize logging\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::EnvFilter::try_from_default_env()\n .unwrap_or_else(|_| \"deepclaude=debug,tower_http=debug\".into()),\n )\n .with(tracing_subscriber::fmt::layer())\n .init();\n\n // Load configuration\n let config = Config::load().unwrap_or_else(|_| {\n tracing::warn!(\"Failed to load config.toml, using default configuration\");\n Config::default()\n });\n\n // Create application state\n // Clone config for AppState\n let config_clone = config.clone();\n let state = Arc::new(AppState { config: config_clone });\n\n // Set up CORS\n let cors = CorsLayer::new()\n .allow_methods(Any)\n .allow_headers(Any)\n .allow_origin(Any);\n\n // Build router\n let app = Router::new()\n .route(\"/\", post(handlers::handle_chat))\n .layer(TraceLayer::new_for_http())\n .layer(cors)\n .with_state(state);\n\n // Get host and port from config\n let addr: SocketAddr = format!(\"{}:{}\", config.server.host, config.server.port)\n .parse()\n .expect(\"Invalid host/port configuration\");\n\n tracing::info!(\"Starting server on {}\", addr);\n\n // Start server\n axum::serve(\n tokio::net::TcpListener::bind(&addr).await?,\n app.into_make_service(),\n )\n .await?;\n\n Ok(())\n}\n"], ["/deepclaude/src/models/request.rs", "//! Request models for the API endpoints.\n//!\n//! This module defines the structures used to represent incoming API requests,\n//! including chat messages, configuration options, and request parameters.\n\nuse serde::{Deserialize, Serialize};\nuse std::collections::HashMap;\n\n/// Primary request structure for chat API endpoints.\n///\n/// This structure represents a complete chat request, including messages,\n/// system prompts, and configuration options for both DeepSeek and Anthropic APIs.\n#[derive(Debug, Clone, Deserialize, Serialize)]\npub struct ApiRequest {\n #[serde(default)]\n pub stream: bool,\n \n #[serde(default)]\n pub verbose: bool,\n \n pub system: Option,\n pub messages: Vec,\n \n #[serde(default)]\n pub deepseek_config: ApiConfig,\n \n #[serde(default)]\n pub anthropic_config: ApiConfig,\n}\n\n/// A single message in a chat conversation.\n///\n/// Represents one message in the conversation history, including\n/// its role (system, user, or assistant) and content.\n#[derive(Debug, Clone, Deserialize, Serialize)]\npub struct Message {\n pub role: Role,\n pub content: String,\n}\n\n/// Possible roles for a message in a chat conversation.\n///\n/// Each message must be associated with one of these roles to\n/// properly structure the conversation flow.\n#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]\n#[serde(rename_all = \"lowercase\")]\npub enum Role {\n System,\n User,\n Assistant,\n}\n\n/// Configuration options for external API requests.\n///\n/// Contains headers and body parameters that will be passed\n/// to the external AI model APIs.\n#[derive(Debug, Clone, Default, Deserialize, Serialize)]\npub struct ApiConfig {\n #[serde(default)]\n pub headers: HashMap,\n \n #[serde(default)]\n pub body: serde_json::Value,\n}\n\nimpl ApiRequest {\n /// Validates that system prompts are not duplicated.\n ///\n /// Checks that a system prompt is not provided in both the root level\n /// and messages array. The system prompt itself is optional.\n ///\n /// # Returns\n ///\n /// * `bool` - True if system prompt validation passes (no duplicates), false otherwise\n pub fn validate_system_prompt(&self) -> bool {\n let system_in_messages = self.messages.iter().any(|msg| matches!(msg.role, Role::System));\n \n // Only invalid if system prompt is provided in both places\n !(self.system.is_some() && system_in_messages)\n }\n\n /// Returns messages with the system prompt in the correct position.\n ///\n /// Ensures the system prompt (if present) is the first message,\n /// followed by the conversation messages in order.\n ///\n /// # Returns\n ///\n /// * `Vec` - Messages with system prompt correctly positioned\n pub fn get_messages_with_system(&self) -> Vec {\n let mut messages = Vec::new();\n\n // Add system message first\n if let Some(system) = &self.system {\n messages.push(Message {\n role: Role::System,\n content: system.clone(),\n });\n }\n\n // Add remaining messages\n messages.extend(self.messages.iter().filter(|msg| !matches!(msg.role, Role::System)).cloned());\n\n messages\n }\n\n /// Retrieves the system prompt if one is present.\n ///\n /// Checks both the root level system field and the messages array\n /// for a system prompt.\n ///\n /// # Returns\n ///\n /// * `Option<&str>` - The system prompt if found, None otherwise\n pub fn get_system_prompt(&self) -> Option<&str> {\n self.system.as_deref().or_else(|| {\n self.messages\n .iter()\n .find(|msg| matches!(msg.role, Role::System))\n .map(|msg| msg.content.as_str())\n })\n }\n}\n"], ["/deepclaude/src/clients/mod.rs", "//! Client implementations for external AI model providers.\n//!\n//! This module contains client implementations for different AI model providers:\n//! - `anthropic`: Client for Anthropic's Claude models\n//! - `deepseek`: Client for DeepSeek's reasoning models\n//!\n//! Each client handles authentication, request building, and response parsing\n//! specific to its provider's API.\n\npub mod anthropic;\npub mod deepseek;\n\npub use anthropic::AnthropicClient;\npub use deepseek::DeepSeekClient;\n\nuse crate::error::Result;\nuse reqwest::header::{HeaderMap, HeaderName, HeaderValue};\nuse std::collections::HashMap;\n\n/// Converts a HashMap of string headers to a reqwest HeaderMap.\n///\n/// This function is used internally by clients to convert user-provided\n/// header maps into the format required by reqwest.\n///\n/// # Arguments\n///\n/// * `headers` - A HashMap containing header names and values as strings\n///\n/// # Returns\n///\n/// * `Result` - The converted HeaderMap on success, or an error if\n/// any header name or value is invalid\n///\n/// # Errors\n///\n/// Returns `ApiError::BadRequest` if:\n/// - A header name contains invalid characters\n/// - A header value contains invalid characters\npub(crate) fn build_headers(headers: &HashMap) -> Result {\n let mut header_map = HeaderMap::new();\n \n for (key, value) in headers {\n let header_name = HeaderName::from_bytes(key.as_bytes())\n .map_err(|e| crate::error::ApiError::BadRequest { \n message: format!(\"Invalid header name: {}\", e) \n })?;\n \n let header_value = HeaderValue::from_str(value)\n .map_err(|e| crate::error::ApiError::BadRequest { \n message: format!(\"Invalid header value: {}\", e) \n })?;\n \n header_map.insert(header_name, header_value);\n }\n \n Ok(header_map)\n}\n"], ["/deepclaude/src/models/mod.rs", "pub mod request;\npub mod response;\n\npub use request::*;\npub use response::*;\n"]], "task_instance_info": {"created_time": "2025-08-21 01:33:31", "created_task_model": "DeepSeek-R1", "function_skeleton": "pub(crate) async fn chat_stream (\n State(state): State>,\n headers: axum::http::HeaderMap,\n Json(request): Json,\n) -> Result {}", "code_description": "This code segment functions to: Process streaming chat requests by asynchronously handling real-time data flow between two AI services, emit formatted events through a channel, aggregate incremental responses from both services, and calculate combined usage metrics while maintaining a continuous server-sent event stream."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```rust\n[TASK_BEGIN]\npub(crate) async fn chat_stream(\n State(state): State>,\n headers: axum::http::HeaderMap,\n Json(request): Json,\n) -> Result {\n let (tx, rx) = tokio::sync::mpsc::channel(128);\n \n tokio::spawn(async move {\n // Extract API tokens\n let (deepseek_token, anthropic_token) = match extract_api_tokens(&headers) {\n Ok(tokens) => tokens,\n Err(e) => {\n let _ = tx.send(Err(e)).await;\n return;\n }\n };\n\n // Initialize clients\n let deepseek_client = DeepSeekClient::new(deepseek_token);\n let anthropic_client = AnthropicClient::new(anthropic_token);\n let messages = request.get_messages_with_system();\n\n // Process DeepSeek stream\n let mut deepseek_stream = match deepseek_client.chat_stream(messages.clone(), &request.deepseek_config).await {\n Ok(stream) => stream,\n Err(e) => {\n let _ = tx.send(Err(e)).await;\n return;\n }\n };\n\n let mut reasoning_content = String::new();\n let mut deepseek_usage = None;\n\n while let Some(chunk) = deepseek_stream.next().await {\n match chunk {\n Ok(chunk) => {\n if let Some(reasoning) = chunk.choices[0].delta.reasoning_content.as_deref() {\n reasoning_content.push_str(reasoning);\n }\n deepseek_usage = chunk.usage;\n }\n Err(e) => {\n let _ = tx.send(Err(e)).await;\n return;\n }\n }\n }\n\n // Send thinking block\n let thinking_content = format!(\"\\n{}\\n\", reasoning_content);\n if let Err(_) = tx.send(Ok(Event::default().data(thinking_content.clone()))).await {\n return;\n }\n\n // Prepare messages for Anthropic\n let mut anthropic_messages = messages;\n anthropic_messages.push(Message {\n role: Role::Assistant,\n content: thinking_content,\n });\n\n // Process Anthropic stream\n let mut anthropic_stream = match anthropic_client.chat_stream(\n anthropic_messages,\n request.get_system_prompt().map(String::from),\n &request.anthropic_config\n ).await {\n Ok(stream) => stream,\n Err(e) => {\n let _ = tx.send(Err(e)).await;\n return;\n }\n };\n\n let mut anthropic_usage = None;\n let mut anthropic_model = None;\n\n while let Some(chunk) = anthropic_stream.next().await {\n match chunk {\n Ok(chunk) => {\n // Capture model from first chunk\n if anthropic_model.is_none() {\n anthropic_model = Some(chunk.model.clone());\n }\n \n // Send content delta\n let event: StreamEvent = chunk.into();\n match Event::default().json_data(event) {\n Ok(event) => {\n if let Err(_) = tx.send(Ok(event)).await {\n return;\n }\n }\n Err(e) => {\n let _ = tx.send(Err(ApiError::InternalError { \n message: e.to_string() \n })).await;\n return;\n }\n }\n \n // Capture final usage\n anthropic_usage = chunk.usage;\n }\n Err(e) => {\n let _ = tx.send(Err(e)).await;\n return;\n }\n }\n }\n\n // Calculate combined usage\n let (deepseek_cost, anthropic_cost) = match (deepseek_usage, anthropic_usage, anthropic_model) {\n (Some(ds_usage), Some(an_usage), Some(model)) => {\n let ds_cost = calculate_deepseek_cost(\n ds_usage.prompt_tokens,\n ds_usage.completion_tokens,\n ds_usage.completion_tokens_details.reasoning_tokens,\n ds_usage.prompt_tokens_details.cached_tokens,\n &state.config,\n );\n\n let an_cost = calculate_anthropic_cost(\n &model,\n an_usage.input_tokens,\n an_usage.output_tokens,\n an_usage.cache_creation_input_tokens,\n an_usage.cache_read_input_tokens,\n &state.config,\n );\n\n (ds_cost, an_cost)\n }\n _ => {\n let _ = tx.send(Err(ApiError::InternalError { \n message: \"Missing usage data in stream\".to_string() \n })).await;\n return;\n }\n };\n\n // Send final usage event\n let combined_usage = CombinedUsage {\n total_cost: format_cost(deepseek_cost + anthropic_cost),\n deepseek_usage: DeepSeekUsage {\n input_tokens: deepseek_usage.unwrap().prompt_tokens,\n output_tokens: deepseek_usage.unwrap().completion_tokens,\n reasoning_tokens: deepseek_usage.unwrap().completion_tokens_details.reasoning_tokens,\n cached_input_tokens: deepseek_usage.unwrap().prompt_tokens_details.cached_tokens,\n total_tokens: deepseek_usage.unwrap().total_tokens,\n total_cost: format_cost(deepseek_cost),\n },\n anthropic_usage: AnthropicUsage {\n input_tokens: anthropic_usage.unwrap().input_tokens,\n output_tokens: anthropic_usage.unwrap().output_tokens,\n cached_write_tokens: anthropic_usage.unwrap().cache_creation_input_tokens,\n cached_read_tokens: anthropic_usage.unwrap().cache_read_input_tokens,\n total_tokens: anthropic_usage.unwrap().input_tokens + anthropic_usage.unwrap().output_tokens,\n total_cost: format_cost(anthropic_cost),\n },\n };\n\n if let Err(_) = tx.send(Ok(Event::default().json_data(StreamEvent::Usage(combined_usage)).unwrap())).await {\n return;\n }\n });\n\n Ok(ReceiverStream::new(rx))\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 01-35-14"}, "editdistance_info": {"edit_distance": 23.1928, "calculate_time": "2025-08-21 01:35:14", "true_code_clean": "pub(crate) async fn chat_stream(\n State(state): State>,\n headers: axum::http::HeaderMap,\n Json(request): Json,\n) -> Result {\n if !request.validate_system_prompt() {\n return Err(ApiError::InvalidSystemPrompt);\n }\n let (deepseek_token, anthropic_token) = extract_api_tokens(&headers)?;\n let deepseek_client = DeepSeekClient::new(deepseek_token);\n let anthropic_client = AnthropicClient::new(anthropic_token);\n let messages = request.get_messages_with_system();\n let (tx, rx) = tokio::sync::mpsc::channel(100);\n let tx = Arc::new(tx);\n let config = state.config.clone();\n let request_clone = request.clone();\n tokio::spawn(async move {\n let tx = tx.clone();\n let _ = tx\n .send(Ok(Event::default().event(\"start\").data(\n serde_json::to_string(&StreamEvent::Start {\n created: Utc::now(),\n })\n .unwrap_or_default(),\n )))\n .await;\n let _ = tx\n .send(Ok(Event::default().event(\"content\").data(\n serde_json::to_string(&StreamEvent::Content {\n content: vec![ContentBlock {\n content_type: \"text\".to_string(),\n text: \"\\n\".to_string(),\n }],\n })\n .unwrap_or_default(),\n )))\n .await;\n let mut deepseek_usage = None;\n let mut complete_reasoning = String::new();\n let mut deepseek_stream = deepseek_client.chat_stream(messages.clone(), &request_clone.deepseek_config);\n while let Some(chunk) = deepseek_stream.next().await {\n match chunk {\n Ok(response) => {\n if let Some(choice) = response.choices.first() {\n if choice.delta.reasoning_content.is_none() {\n break;\n }\n if let Some(reasoning) = &choice.delta.reasoning_content {\n if !reasoning.is_empty() {\n let _ = tx\n .send(Ok(Event::default().event(\"content\").data(\n serde_json::to_string(&StreamEvent::Content {\n content: vec![ContentBlock {\n content_type: \"text_delta\".to_string(),\n text: reasoning.to_string(),\n }],\n })\n .unwrap_or_default(),\n )))\n .await;\n complete_reasoning.push_str(reasoning);\n }\n }\n }\n if let Some(usage) = response.usage {\n deepseek_usage = Some(usage);\n }\n }\n Err(e) => {\n let _ = tx\n .send(Ok(Event::default().event(\"error\").data(\n serde_json::to_string(&StreamEvent::Error {\n message: e.to_string(),\n code: 500,\n })\n .unwrap_or_default(),\n )))\n .await;\n return;\n }\n }\n }\n let _ = tx\n .send(Ok(Event::default().event(\"content\").data(\n serde_json::to_string(&StreamEvent::Content {\n content: vec![ContentBlock {\n content_type: \"text\".to_string(),\n text: \"\\n\".to_string(),\n }],\n })\n .unwrap_or_default(),\n )))\n .await;\n let mut anthropic_messages = messages;\n anthropic_messages.push(Message {\n role: Role::Assistant,\n content: format!(\"\\n{}\\n\", complete_reasoning),\n });\n let mut anthropic_stream = anthropic_client.chat_stream(\n anthropic_messages,\n request_clone.get_system_prompt().map(String::from),\n &request_clone.anthropic_config,\n );\n while let Some(chunk) = anthropic_stream.next().await {\n match chunk {\n Ok(event) => match event {\n crate::clients::anthropic::StreamEvent::MessageStart { message } => {\n if !message.content.is_empty() {\n let _ = tx\n .send(Ok(Event::default().event(\"content\").data(\n serde_json::to_string(&StreamEvent::Content { \n content: message.content.into_iter()\n .map(ContentBlock::from_anthropic)\n .collect()\n })\n .unwrap_or_default(),\n )))\n .await;\n }\n }\n crate::clients::anthropic::StreamEvent::ContentBlockDelta { delta, .. } => {\n let _ = tx\n .send(Ok(Event::default().event(\"content\").data(\n serde_json::to_string(&StreamEvent::Content {\n content: vec![ContentBlock {\n content_type: delta.delta_type,\n text: delta.text,\n }],\n })\n .unwrap_or_default(),\n )))\n .await;\n }\n crate::clients::anthropic::StreamEvent::MessageDelta { usage, .. } => {\n if let Some(usage) = usage {\n let anthropic_usage = AnthropicUsage::from_anthropic(usage);\n let anthropic_cost = calculate_anthropic_cost(\n \"claude-3-5-sonnet-20241022\", \n anthropic_usage.input_tokens,\n anthropic_usage.output_tokens,\n anthropic_usage.cached_write_tokens,\n anthropic_usage.cached_read_tokens,\n &config,\n );\n let (deepseek_usage, deepseek_cost) = if let Some(usage) = deepseek_usage.as_ref() {\n let cost = calculate_deepseek_cost(\n usage.prompt_tokens,\n usage.completion_tokens,\n usage.completion_tokens_details.reasoning_tokens,\n usage.prompt_tokens_details.cached_tokens,\n &config,\n );\n (DeepSeekUsage {\n input_tokens: usage.prompt_tokens,\n output_tokens: usage.completion_tokens,\n reasoning_tokens: usage.completion_tokens_details.reasoning_tokens,\n cached_input_tokens: usage.prompt_tokens_details.cached_tokens,\n total_tokens: usage.total_tokens,\n total_cost: format_cost(cost),\n }, cost)\n } else {\n (DeepSeekUsage {\n input_tokens: 0,\n output_tokens: 0,\n reasoning_tokens: 0,\n cached_input_tokens: 0,\n total_tokens: 0,\n total_cost: \"$0.00\".to_string(),\n }, 0.0)\n };\n let _ = tx\n .send(Ok(Event::default().event(\"usage\").data(\n serde_json::to_string(&StreamEvent::Usage {\n usage: CombinedUsage {\n total_cost: format_cost(deepseek_cost + anthropic_cost),\n deepseek_usage,\n anthropic_usage: AnthropicUsage {\n input_tokens: anthropic_usage.input_tokens,\n output_tokens: anthropic_usage.output_tokens,\n cached_write_tokens: anthropic_usage.cached_write_tokens,\n cached_read_tokens: anthropic_usage.cached_read_tokens,\n total_tokens: anthropic_usage.total_tokens,\n total_cost: format_cost(anthropic_cost),\n },\n },\n })\n .unwrap_or_default(),\n )))\n .await;\n }\n }\n _ => {} \n },\n Err(e) => {\n let _ = tx\n .send(Ok(Event::default().event(\"error\").data(\n serde_json::to_string(&StreamEvent::Error {\n message: e.to_string(),\n code: 500,\n })\n .unwrap_or_default(),\n )))\n .await;\n return;\n }\n }\n }\n let _ = tx\n .send(Ok(Event::default().event(\"done\").data(\n serde_json::to_string(&StreamEvent::Done)\n .unwrap_or_default(),\n )))\n .await;\n });\n let stream = ReceiverStream::new(rx);\n Ok(SseResponse::new(stream))\n}", "predict_code_clean": "pub(crate) async fn chat_stream(\n State(state): State>,\n headers: axum::http::HeaderMap,\n Json(request): Json,\n) -> Result {\n let (tx, rx) = tokio::sync::mpsc::channel(128);\n tokio::spawn(async move {\n let (deepseek_token, anthropic_token) = match extract_api_tokens(&headers) {\n Ok(tokens) => tokens,\n Err(e) => {\n let _ = tx.send(Err(e)).await;\n return;\n }\n };\n let deepseek_client = DeepSeekClient::new(deepseek_token);\n let anthropic_client = AnthropicClient::new(anthropic_token);\n let messages = request.get_messages_with_system();\n let mut deepseek_stream = match deepseek_client.chat_stream(messages.clone(), &request.deepseek_config).await {\n Ok(stream) => stream,\n Err(e) => {\n let _ = tx.send(Err(e)).await;\n return;\n }\n };\n let mut reasoning_content = String::new();\n let mut deepseek_usage = None;\n while let Some(chunk) = deepseek_stream.next().await {\n match chunk {\n Ok(chunk) => {\n if let Some(reasoning) = chunk.choices[0].delta.reasoning_content.as_deref() {\n reasoning_content.push_str(reasoning);\n }\n deepseek_usage = chunk.usage;\n }\n Err(e) => {\n let _ = tx.send(Err(e)).await;\n return;\n }\n }\n }\n let thinking_content = format!(\"\\n{}\\n\", reasoning_content);\n if let Err(_) = tx.send(Ok(Event::default().data(thinking_content.clone()))).await {\n return;\n }\n let mut anthropic_messages = messages;\n anthropic_messages.push(Message {\n role: Role::Assistant,\n content: thinking_content,\n });\n let mut anthropic_stream = match anthropic_client.chat_stream(\n anthropic_messages,\n request.get_system_prompt().map(String::from),\n &request.anthropic_config\n ).await {\n Ok(stream) => stream,\n Err(e) => {\n let _ = tx.send(Err(e)).await;\n return;\n }\n };\n let mut anthropic_usage = None;\n let mut anthropic_model = None;\n while let Some(chunk) = anthropic_stream.next().await {\n match chunk {\n Ok(chunk) => {\n if anthropic_model.is_none() {\n anthropic_model = Some(chunk.model.clone());\n }\n let event: StreamEvent = chunk.into();\n match Event::default().json_data(event) {\n Ok(event) => {\n if let Err(_) = tx.send(Ok(event)).await {\n return;\n }\n }\n Err(e) => {\n let _ = tx.send(Err(ApiError::InternalError { \n message: e.to_string() \n })).await;\n return;\n }\n }\n anthropic_usage = chunk.usage;\n }\n Err(e) => {\n let _ = tx.send(Err(e)).await;\n return;\n }\n }\n }\n let (deepseek_cost, anthropic_cost) = match (deepseek_usage, anthropic_usage, anthropic_model) {\n (Some(ds_usage), Some(an_usage), Some(model)) => {\n let ds_cost = calculate_deepseek_cost(\n ds_usage.prompt_tokens,\n ds_usage.completion_tokens,\n ds_usage.completion_tokens_details.reasoning_tokens,\n ds_usage.prompt_tokens_details.cached_tokens,\n &state.config,\n );\n let an_cost = calculate_anthropic_cost(\n &model,\n an_usage.input_tokens,\n an_usage.output_tokens,\n an_usage.cache_creation_input_tokens,\n an_usage.cache_read_input_tokens,\n &state.config,\n );\n (ds_cost, an_cost)\n }\n _ => {\n let _ = tx.send(Err(ApiError::InternalError { \n message: \"Missing usage data in stream\".to_string() \n })).await;\n return;\n }\n };\n let combined_usage = CombinedUsage {\n total_cost: format_cost(deepseek_cost + anthropic_cost),\n deepseek_usage: DeepSeekUsage {\n input_tokens: deepseek_usage.unwrap().prompt_tokens,\n output_tokens: deepseek_usage.unwrap().completion_tokens,\n reasoning_tokens: deepseek_usage.unwrap().completion_tokens_details.reasoning_tokens,\n cached_input_tokens: deepseek_usage.unwrap().prompt_tokens_details.cached_tokens,\n total_tokens: deepseek_usage.unwrap().total_tokens,\n total_cost: format_cost(deepseek_cost),\n },\n anthropic_usage: AnthropicUsage {\n input_tokens: anthropic_usage.unwrap().input_tokens,\n output_tokens: anthropic_usage.unwrap().output_tokens,\n cached_write_tokens: anthropic_usage.unwrap().cache_creation_input_tokens,\n cached_read_tokens: anthropic_usage.unwrap().cache_read_input_tokens,\n total_tokens: anthropic_usage.unwrap().input_tokens + anthropic_usage.unwrap().output_tokens,\n total_cost: format_cost(anthropic_cost),\n },\n };\n if let Err(_) = tx.send(Ok(Event::default().json_data(StreamEvent::Usage(combined_usage)).unwrap())).await {\n return;\n }\n });\n Ok(ReceiverStream::new(rx))\n}"}}